From 713c31a21ef1820446edb7456a682f268fbead4e Mon Sep 17 00:00:00 2001 From: seb Date: Mon, 12 Oct 2026 18:01:21 +0200 Subject: [PATCH] u --- docs/api/routes-all.md | 78 ++-- docs/api/routes/modelconversation.get.md | 4 +- docs/api/routes/modelconversation.post.md | 4 +- docs/api/routes/modelconversation/_id.get.md | 4 +- src/api/openapi.js | 6 + src/api/routes/modelconversation.js | 28 +- src/services/conversationManager.js | 8 + src/tools/prompts.js | 12 + src/tools/subagent.js | 411 +++++++++++++++++++ 9 files changed, 511 insertions(+), 44 deletions(-) create mode 100644 src/tools/subagent.js diff --git a/docs/api/routes-all.md b/docs/api/routes-all.md index 2a188d2..b829af6 100644 --- a/docs/api/routes-all.md +++ b/docs/api/routes-all.md @@ -10,35 +10,35 @@ Params: path values first, then `query:` and `body:` (`body?` = optional body). ### Reusable types - `T1` = `{ article: T2 }` -- `T2` = `{ id: int, sku: str, name: str, slug: str, desc: str|null, seo: str|null, track_stock: bool, unitamount: num|null, weight: num|null, unit: T32, brand: T29|null, categoryIds: int[], photos: T27[], eans: str[], prices: T40[], suppliers: T13[] }` +- `T2` = `{ id: int, sku: str, name: str, slug: str, desc: str|null, seo: str|null, track_stock: bool, unitamount: num|null, weight: num|null, unit: T32, brand: T30|null, categoryIds: int[], photos: T28[], eans: str[], prices: T40[], suppliers: T13[] }` - `T3` = `{ order: T4 }` -- `T4` = `{ id: int, number: str, type: str, entityId: int|null, date: str, lines: T22[], createdAt?: str, shipping?: T39|null, shippings?: T39[], payment?: T35|null, payments?: T35[], paid?: bool, delivered?: bool }` +- `T4` = `{ id: int, number: str, type: str, entityId: int|null, date: str, lines: T23[], createdAt?: str, shipping?: T39|null, shippings?: T39[], payment?: T35|null, payments?: T35[], paid?: bool, delivered?: bool }` - `T5` = `{ delivery: T6 }` -- `T6` = `{ id: int, number: str, type: str, supplierId: int|null, date: str, lines: T22[], files: T10[], externalNumber?: str|null, createdAt?: str, ledger?: T44 }` +- `T6` = `{ id: int, number: str, type: str, supplierId: int|null, date: str, lines: T23[], files: T10[], externalNumber?: str|null, createdAt?: str, ledger?: T44 }` - `T7` = `{ labeltemplate: T8 }` -- `T8` = `{ id: int, name: str, width: num, height: num, dpi: int, type: str, content: T18, thumb?: str|null }` +- `T8` = `{ id: int, name: str, width: num, height: num, dpi: int, type: str, content: T19, thumb?: str|null }` - `T9` = `{ quote: T12 }` - `T10` = `{ id: int, manifestId: int, fileId: int, sort: int, hash: str, mimetype: str, name: str, size: int, created?: str, modified?: str, thumbavif?: str|null, thumbx?: int|null, thumby?: int|null, meta?: { [k]: str }|null }` - `T11` = `{ id: int, name: str, pairingpin?: str|null, token?: str|null, pairedAt?: str|null, clientserial?: str|null, rootCategoryId?: int|null, syncRootArticles?: bool, lastseenAt?: str|null, updatedAt?: str|null, categoryIds?: int[] }` -- `T12` = `{ id: int, number: str, type: str, entityId: int|null, date: str, lines: T22[], createdAt?: str }` +- `T12` = `{ id: int, number: str, type: str, entityId: int|null, date: str, lines: T23[], createdAt?: str }` - `T13` = `{ id: int, articleId: int, entityId: int, pu: num, sort: int, supplierName?: str|null, sku?: str|null, stock?: num|null, priceId?: int|null, price?: T46|null }` - `T14` = `{ id: int, entityId: int, addressType: str, firstName?: str|null, name?: str|null, street?: str|null, streetNumber?: str|null, zip?: str|null, city?: str|null, county?: str|null }` - `T15` = `{ ledger: T16[] }` - `T16` = `{ id: int, manifestarticle_id: int, transaction_type: str, amount: num, transaction_text: str, hash_version: int, prev_hash?: str, sku?: str|null, created_at?: str }` - `T17` = `{ id: int, name: str, sort: int, exclusive: bool, values: T33[], articleCount?: int }` -- `T18` = `{ objects: T23[] }` +- `T18` = `{ id: int, companyuser_id: int, provider: str, model: str, created_at: str, updated_at: str, state: str, started_by?: integer,null, first_message?: string,null }` - `T19` = `{ objects: T24[] }` -- `T20` = `{ printer: T25 }` -- `T21` = `{ entity: T28 }` -- `T22` = `{ id: int, sku: str|null, name: str|null, pu: num, amount: num, net: num, rebate: num, taxrate: num, comment: str|null }` -- `T23` = `{ id: str, type: str, x: num, y: num, w?: num, h?: num, text?: str, font?: str, fontSize?: num, barcodeFormat?: str }` +- `T20` = `{ objects: T25[] }` +- `T21` = `{ printer: T26 }` +- `T22` = `{ entity: T29 }` +- `T23` = `{ id: int, sku: str|null, name: str|null, pu: num, amount: num, net: num, rebate: num, taxrate: num, comment: str|null }` - `T24` = `{ id: str, type: str, x: num, y: num, w?: num, h?: num, text?: str, font?: str, fontSize?: num, barcodeFormat?: str }` -- `T25` = `{ id: int, company_id: int, address: str, type: str, sort: int, model?: str|null, serial?: str|null, desc?: str|null }` -- `T26` = `{ amount: num, net: num, taxrate: num, sku?: str|null, name?: str|null, pu?: num, rebate?: num, comment?: str|null }` -- `T27` = `{ sort: int, fullHash: str, fullW: int, fullH: int, fullSize: int, thumbW: int, thumbH: int, thumbHash: str }` -- `T28` = `{ id: int, customergroupId: int, firstName: str|null, name: str, number: str|null, createdAt: str, updatedAt: str }` -- `T29` = `{ name: str, id?: int|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }` -- `T30` = `{ id: int, companyuser_id: int, provider: str, model: str, created_at: str, updated_at: str, state: str }` +- `T25` = `{ id: str, type: str, x: num, y: num, w?: num, h?: num, text?: str, font?: str, fontSize?: num, barcodeFormat?: str }` +- `T26` = `{ id: int, company_id: int, address: str, type: str, sort: int, model?: str|null, serial?: str|null, desc?: str|null }` +- `T27` = `{ amount: num, net: num, taxrate: num, sku?: str|null, name?: str|null, pu?: num, rebate?: num, comment?: str|null }` +- `T28` = `{ sort: int, fullHash: str, fullW: int, fullH: int, fullSize: int, thumbW: int, thumbH: int, thumbHash: str }` +- `T29` = `{ id: int, customergroupId: int, firstName: str|null, name: str, number: str|null, createdAt: str, updatedAt: str }` +- `T30` = `{ name: str, id?: int|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }` - `T31` = `{ article: T37 }` - `T32` = `{ si: str, basesi: str, basesifactor: num, symbol?: str|null, name?: str|null }` - `T33` = `{ id: int, attributeId: int, value: str, sort: int, articleCount?: int }` @@ -272,7 +272,7 @@ _none_ - Returns: `200 { categoryIds: int[] }` #### Category tree — `GET /category/tree` _none_ -- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T29|null }[] }` +- Returns: `200 { languageId: int, tree: { id: int, sort: int, posterminalIds: int[], parentId?: int|null, name?: str|null, slug?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null }[], articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T30|null }[] }` #### Delete category — `DELETE /category/{id}` - Params: `id: int, query: recursive?: bool` - Returns: `204 void` @@ -281,7 +281,7 @@ _none_ - Returns: `200 { category: { id: int, name: str, slug: str, parentId: int, sort: int } }` #### Articles in category — `GET /category/{id}/articles` - Params: `id: int` -- Returns: `200 { articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T29|null }[] }` +- Returns: `200 { articles: { id: int, sku: str, name: str, slug: str, track_stock: bool, optionsCount: int, articleListCount: int, childCount: int, net?: num|null, taxRate?: num|null, parentArticleId?: int|null, parentSku?: str|null, fullHash?: str|null, thumbW?: int|null, thumbH?: int|null, thumbHash?: str|null, brand?: T30|null }[] }` #### List category attribute values — `GET /category/{id}/attributevalue` - Params: `id: int` - Returns: `200 { attributevalues: { id: int, attributeId: int, attributeName: str, attributeValueId: int, value: str, sort: int, categoryId?: int, exclusive?: bool }[] }` @@ -361,7 +361,7 @@ _none_ _none_ - Returns: `200 { deliveries: { id: int, number: str, type: str, supplierId: int|null, date: str, externalNumber?: str|null, createdAt?: str, ledger?: T44 }[] }` #### Create delivery — `POST /delivery` -- Params: `body: { externalNumber: str, date: str, lines: T26[], supplierId?: int|null, files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` +- Params: `body: { externalNumber: str, date: str, lines: T27[], supplierId?: int|null, files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` - Returns: `201 T5` #### Parse document (SSE) — `POST /delivery/parse` - Params: `form: { file: str }` @@ -382,7 +382,7 @@ _none_ - Params: `id: int` - Returns: `200 T5` #### Update delivery — `PATCH /delivery/{id}` -- Params: `id: int, body: { externalNumber?: str|null, date?: str, supplierId?: int|null, lines?: T26[], files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` +- Params: `id: int, body: { externalNumber?: str|null, date?: str, supplierId?: int|null, lines?: T27[], files?: { mimetype: str, name: str, content: str, sort?: int, size?: int, hash?: str, created?: str, modified?: str, meta?: { [k]: str } }[] }` - Returns: `200 T5` #### Get delivery attachment file content — `GET /delivery/{id}/file/{fileId}` - Params: `id: int, fileId: int, query: download?: bool` @@ -392,10 +392,10 @@ _none_ #### List entities — `GET /entity` - Params: `query: customergroupId?: int, role?: str` -- Returns: `200 { entities: T28[] }` +- Returns: `200 { entities: T29[] }` #### Create entity — `POST /entity` - Params: `body: { customergroupId: int, name: str, firstName?: str|null, number?: str }` -- Returns: `201 T21` +- Returns: `201 T22` #### Peek next customer number — `GET /entity/next-number` _none_ - Returns: `200 { number: str }` @@ -428,10 +428,10 @@ _none_ - Returns: `204 void` #### Get entity — `GET /entity/{id}` - Params: `id: int` -- Returns: `200 T21` +- Returns: `200 T22` #### Update entity — `PATCH /entity/{id}` - Params: `id: int, body: { name?: str, firstName?: str|null, number?: str|null }` -- Returns: `200 T21` +- Returns: `200 T22` ### Section: /events @@ -473,7 +473,7 @@ _none_ _none_ - Returns: `200 { labeltemplates: { id: int, name: str, width: num, height: num, dpi: int, type: str, thumb?: str|null }[] }` #### Create label template — `POST /labeltemplate` -- Params: `body: { name: str, width: num, height: num, dpi: int, type: str, content: T19 }` +- Params: `body: { name: str, width: num, height: num, dpi: int, type: str, content: T20 }` - Returns: `201 T7` #### Delete label template — `DELETE /labeltemplate/{id}` - Params: `id: int` @@ -482,10 +482,10 @@ _none_ - Params: `id: int` - Returns: `200 T7` #### Update label template (partial) — `PATCH /labeltemplate/{id}` -- Params: `id: int, body: { name?: str, width?: num, height?: num, dpi?: int, type?: str, content?: T19 }` +- Params: `id: int, body: { name?: str, width?: num, height?: num, dpi?: int, type?: str, content?: T20 }` - Returns: `200 T7` #### Update label template — `PUT /labeltemplate/{id}` -- Params: `id: int, body: { name?: str, width?: num, height?: num, dpi?: int, type?: str, content?: T19 }` +- Params: `id: int, body: { name?: str, width?: num, height?: num, dpi?: int, type?: str, content?: T20 }` - Returns: `200 T7` ### Section: /ledger @@ -507,16 +507,16 @@ _none_ #### List conversations — `GET /modelconversation` _none_ -- Returns: `200 { conversations: T30[] }` +- Returns: `200 { conversations: T18[] }` #### Create conversation — `POST /modelconversation` - Params: `body: { provider: str, model: str }` -- Returns: `201 { conversation: T30 }` +- Returns: `201 { conversation: T18 }` #### Delete conversation — `DELETE /modelconversation/{id}` - Params: `id: int` - Returns: `204 void` #### Get conversation — `GET /modelconversation/{id}` - Params: `id: int` -- Returns: `200 { conversation: T30 }` +- Returns: `200 { conversation: T18 }` #### List conversation messages — `GET /modelconversation/{id}/message` - Params: `id: int` - Returns: `200 { messages: { id: int, conversation_id: int, created_at: str, role: str, message: str }[] }` @@ -542,7 +542,7 @@ _none_ - Params: `query: offset?: int, limit?: int` - Returns: `200 { orders: T4[], total: int, offset: int, limit: int }` #### Create order — `POST /order` -- Params: `body: { number: str, date: str, lines: T26[], entityId?: int|null }` +- Params: `body: { number: str, date: str, lines: T27[], entityId?: int|null }` - Returns: `201 T3` #### Delete order — `DELETE /order/{id}` - Params: `id: int` @@ -551,7 +551,7 @@ _none_ - Params: `id: int` - Returns: `200 T3` #### Update order — `PATCH /order/{id}` -- Params: `id: int, body: { number?: str, date?: str, entityId?: int|null, lines?: T26[] }` +- Params: `id: int, body: { number?: str, date?: str, entityId?: int|null, lines?: T27[] }` - Returns: `200 T3` #### List payments of an order — `GET /order/{id}/payment` - Params: `id: int` @@ -609,10 +609,10 @@ _none_ #### List printers — `GET /printer` _none_ -- Returns: `200 { printers: T25[] }` +- Returns: `200 { printers: T26[] }` #### Create printer — `POST /printer` - Params: `body: { address: str, type: str, model?: str|null, serial?: str|null, sort?: int, desc?: str|null }` -- Returns: `201 T20` +- Returns: `201 T21` #### Reorder printers — `PUT /printer/order` - Params: `body: { printerIds: int[] }` - Returns: `200 { printerIds: int[] }` @@ -621,13 +621,13 @@ _none_ - Returns: `204 void` #### Get printer by ID — `GET /printer/{id}` - Params: `id: int` -- Returns: `200 T20` +- Returns: `200 T21` #### Update printer (partial) — `PATCH /printer/{id}` - Params: `id: int, body: { address?: str, type?: str, model?: str|null, serial?: str|null, sort?: int, desc?: str|null }` -- Returns: `200 T20` +- Returns: `200 T21` #### Update printer — `PUT /printer/{id}` - Params: `id: int, body: { address?: str, type?: str, model?: str|null, serial?: str|null, sort?: int, desc?: str|null }` -- Returns: `200 T20` +- Returns: `200 T21` ### Section: /propertyname @@ -668,7 +668,7 @@ _none_ _none_ - Returns: `200 { quotes: { id: int, number: str, type: str, entityId: int|null, date: str, createdAt?: str }[] }` #### Create quote — `POST /quote` -- Params: `body: { number: str, date: str, lines: T26[], entityId?: int|null }` +- Params: `body: { number: str, date: str, lines: T27[], entityId?: int|null }` - Returns: `201 T9` #### Delete quote — `DELETE /quote/{id}` - Params: `id: int` @@ -677,7 +677,7 @@ _none_ - Params: `id: int` - Returns: `200 T9` #### Update quote — `PATCH /quote/{id}` -- Params: `id: int, body: { number?: str, date?: str, entityId?: int|null, lines?: T26[] }` +- Params: `id: int, body: { number?: str, date?: str, entityId?: int|null, lines?: T27[] }` - Returns: `200 T9` ### Section: /serper diff --git a/docs/api/routes/modelconversation.get.md b/docs/api/routes/modelconversation.get.md index 0017921..06266ad 100644 --- a/docs/api/routes/modelconversation.get.md +++ b/docs/api/routes/modelconversation.get.md @@ -20,7 +20,9 @@ List of conversations "model": "…", "created_at": "…", "updated_at": "…", - "state": "idle" + "state": "idle", + "started_by": "…", + "first_message": "…" } ] } diff --git a/docs/api/routes/modelconversation.post.md b/docs/api/routes/modelconversation.post.md index d75d180..9ab38eb 100644 --- a/docs/api/routes/modelconversation.post.md +++ b/docs/api/routes/modelconversation.post.md @@ -37,7 +37,9 @@ Created conversation "model": "…", "created_at": "…", "updated_at": "…", - "state": "idle" + "state": "idle", + "started_by": "…", + "first_message": "…" } } ``` diff --git a/docs/api/routes/modelconversation/_id.get.md b/docs/api/routes/modelconversation/_id.get.md index 88200fd..2869d42 100644 --- a/docs/api/routes/modelconversation/_id.get.md +++ b/docs/api/routes/modelconversation/_id.get.md @@ -25,7 +25,9 @@ Conversation details "model": "…", "created_at": "…", "updated_at": "…", - "state": "idle" + "state": "idle", + "started_by": "…", + "first_message": "…" } } ``` diff --git a/src/api/openapi.js b/src/api/openapi.js index 6cea055..e113bd0 100644 --- a/src/api/openapi.js +++ b/src/api/openapi.js @@ -1114,6 +1114,12 @@ * type: string * enum: [idle, busy] * description: Messages can only be posted while `idle` + * started_by: + * type: [integer, 'null'] + * description: Id of the conversation that started this one as a subagent, or null for a top-level conversation. Deleting a conversation also deletes every conversation below it in this chain. + * first_message: + * type: [string, 'null'] + * description: Only returned by the list endpoint. Plain text of the conversation's first user message (max 200 chars, ellipsis if cut), or null if there is none yet. * ModelConversationCreateInput: * type: object * required: [provider, model] diff --git a/src/api/routes/modelconversation.js b/src/api/routes/modelconversation.js index 489a337..21eac7c 100644 --- a/src/api/routes/modelconversation.js +++ b/src/api/routes/modelconversation.js @@ -2,7 +2,9 @@ import * as db from '../../db/modelconversation.js'; import env from '../../config/env.js'; import { RETIRED_MODELS, resolveDefaultModel } from '../../tools/llm-key.js'; import { emit } from '../sse.js'; -import { getOrCreateManager, removeManager } from '../../services/conversationManager.js'; +import { getOrCreateManager, removeManager, cleanUserMessageContent } from '../../services/conversationManager.js'; + +const FIRST_MESSAGE_MAX_CHARS = 200; // #region Helpers @@ -22,6 +24,24 @@ function parsePositiveInt(value, field) { return { id }; } +/** + * Turns the stored first user message payload (`{"content": ...}`) into short plain text + * for conversation lists. + * @param {string|null} storedMessage + * @returns {string|null} + */ +function buildFirstMessagePreview(storedMessage) { + if (!storedMessage) return null; + let rawContent; + try { + rawContent = JSON.parse(storedMessage).content; + } catch { + rawContent = storedMessage; + } + const text = cleanUserMessageContent(rawContent).trim(); + return text.length > FIRST_MESSAGE_MAX_CHARS ? `${text.slice(0, FIRST_MESSAGE_MAX_CHARS)}…` : text; +} + function modelConversationErrorStatus(error) { if (error.message === 'No company selected') return 400; if (error.message === 'Not authorized') return 403; @@ -92,7 +112,11 @@ export function register(app, basePath = '') { } try { - const conversations = await db.list(req.user.id); + const rows = await db.list(req.user.id); + const conversations = rows.map(({ first_user_message: storedFirstMessage, ...conversation }) => ({ + ...conversation, + first_message: buildFirstMessagePreview(storedFirstMessage), + })); res.status(200).json({ conversations }); } catch (error) { const status = modelConversationErrorStatus(error); diff --git a/src/services/conversationManager.js b/src/services/conversationManager.js index a552844..51f287a 100644 --- a/src/services/conversationManager.js +++ b/src/services/conversationManager.js @@ -28,6 +28,7 @@ import { createSearchArticlesTool } from '../tools/search-articles.js'; import { createEanChecksumTool } from '../tools/ean-checksum.js'; import { createNetGrossCalcTool } from '../tools/net-gross-calc.js'; import { createSetUserRouteTool } from '../tools/set-user-route.js'; +import { createSubagentTool } from '../tools/subagent.js'; import { resolveOpenRouterKey, resolveDefaultModel, resolveModelReasoning, RETIRED_MODELS, hasConfiguredOpenRouterKey } from '../tools/llm-key.js'; // #region Constants @@ -757,6 +758,13 @@ export class ConversationManager { this.broadcast('route', { route }); }, }), + createSubagentTool({ + googleAuthId, + companyId: this.companyId, + conversationId: this.conversationId, + parentModel: model, + depth: 0, + }), ], }); diff --git a/src/tools/prompts.js b/src/tools/prompts.js index 8a6f2f1..1caab61 100644 --- a/src/tools/prompts.js +++ b/src/tools/prompts.js @@ -98,6 +98,10 @@ export const TOOL_DESCRIPTIONS = { set_user_route: 'Navigate user to a frontend route when asked to view/open an entity or page (see ROUTE MATRIX in prompt).', + + subagent: + 'Delegate a task to an isolated subagent. Pre-loads requested SKILL files into its ' + + 'system prompt and returns a compact summary of tool executions alongside the final output.', }; // #endregion @@ -243,6 +247,14 @@ export const TOOL_PARAMETER_DESCRIPTIONS = { set_user_route: { route: 'Frontend route from Route Matrix (e.g. "/artikel/ART-10042", "/auftrag/1001").', }, + + subagent: { + note: NOTE_DESC, + task: 'Specific instructions and goal for the subagent.', + skills: 'Array of SKILL names or slugs to inject directly into the subagent system prompt (e.g. ["api-article", "label"]).', + conversation_id: 'Existing subagent conversation ID to follow up on, or null to create a new one.', + max_iterations: 'Safety bound on tool loops (default 15, max 30).', + }, }; export const PATCH_PARAMETER_DESCRIPTIONS = TOOL_PARAMETER_DESCRIPTIONS.patch; diff --git a/src/tools/subagent.js b/src/tools/subagent.js new file mode 100644 index 0000000..5bd526f --- /dev/null +++ b/src/tools/subagent.js @@ -0,0 +1,411 @@ +import fs from 'fs'; +import path from 'path'; +import { LLMOrbiter, OpenRouterProvider, defineTool, ToolError } from 'libllmorbiter'; +import env from '../config/env.js'; +import * as db from '../db/modelconversation.js'; +import { emit as emitCompanyEvent } from '../api/sse.js'; +import { buildSystemPrompt } from '../services/prompts.js'; +import { historyToLlmMessages } from '../services/conversationManager.js'; +import { resolveOpenRouterKey, resolveModelReasoning } from './llm-key.js'; +import { TOOL_DESCRIPTIONS, TOOL_PARAMETER_DESCRIPTIONS } from './prompts.js'; +import { SKILL_EXT, isSkillName, parseSkill } from './skill.js'; +import { getApiRouteSkill } from './routes-skills.js'; +import { prepareVfs } from './vfs.js'; +import { createDashbackRequestTool } from './dashback-request.js'; +import { createJavascriptExecuteTool } from './javascript.js'; +import { createFindFilesTool } from './find-files.js'; +import { createReadFileTool } from './read-file.js'; +import { createPatchTool } from './patch.js'; +import { createRmTool } from './rm.js'; +import { createSearchImagesTool } from './search-images.js'; +import { createAnalyzeImageTool } from './analyze-image.js'; +import { createEditImageTool } from './edit-image.js'; +import { createWebSearchTool } from './web-search.js'; +import { createUrlGetTool } from './url-get.js'; +import { createPdfReadTool } from './pdf-read.js'; +import { createResetVfsTool } from './reset-vfs.js'; +import { createApiSuggestionsOrIssuesTool } from './apisuggestionsorissues.js'; +import { createSearchArticlesTool } from './search-articles.js'; +import { createEanChecksumTool } from './ean-checksum.js'; +import { createNetGrossCalcTool } from './net-gross-calc.js'; + +/** + * subagent — delegates a self-contained task to an isolated LLMOrbiter run that lives in + * its own persisted conversation (`modelconversation` / `modelmessage`). + * + * The subagent gets the parent's toolbelt minus `ask_user`, `subagent` and `set_user_route` + * (it cannot talk to the user, spawn further subagents or drive the UI). The parent only + * receives the final output plus a byte-level audit of the tool calls; the full transcript + * stays in the subagent's conversation. + */ + +// #region Constants + +const DEFAULT_MAX_ITERATIONS = 15; +const MAX_ITERATIONS_LIMIT = 30; +/** Subagents never spawn subagents: the parent runs at depth 0, its child at depth 1. */ +const MAX_SUBAGENT_DEPTH = 1; +const SUBAGENT_PROVIDER = 'openrouter'; + +const SUBAGENT_PROMPT_NOTICE = [ + 'SUBAGENT MODE:', + '- You are a subagent working for a primary agent, not talking to the end user. You cannot ask the user questions.', + '- Complete the task with your tools, then finish with a concise, self-contained final answer: what was done, key findings, and any file paths or IDs the primary agent needs.', + '- Do not ask for confirmation; if the task is ambiguous, state your assumption and proceed.', +].join('\n'); + +// #endregion + +// #region Skill Injection + +/** + * Turns a skill name or slug into its flat SKILL file name: `api-article` → `api-article.SKILL`. + * @param {string} nameOrSlug + * @returns {string} + */ +function toSkillFileName(nameOrSlug) { + const trimmed = String(nameOrSlug ?? '').trim(); + return trimmed.toLowerCase().endsWith(SKILL_EXT.toLowerCase()) ? trimmed : `${trimmed}${SKILL_EXT}`; +} + +/** + * Finds a SKILL file by name: the company's VFS root first, then the virtual + * `api-
.SKILL` files generated from docs/api/routes.md. + * @param {string} vfsRoot + * @param {string} fileName + * @returns {string|null} raw SKILL content, or null when no such skill exists + */ +function readSkillContent(vfsRoot, fileName) { + const diskPath = path.join(vfsRoot, fileName); + if (fs.existsSync(diskPath) && fs.statSync(diskPath).isFile()) { + return fs.readFileSync(diskPath, 'utf8'); + } + return getApiRouteSkill(fileName)?.content ?? null; +} + +/** + * Resolves the requested skills and renders them as an `# INJECTED SKILLS` prompt block. + * Unknown skills are rejected as a whole so the primary agent can correct the call + * instead of delegating to a subagent that silently lacks its guidelines. + * + * @param {string} vfsRoot + * @param {string[]|null|undefined} skillNames + * @returns {string} empty string when no skills were requested + * @throws {ToolError} on malformed or unknown skill names + */ +function buildInjectedSkillsBlock(vfsRoot, skillNames) { + if (skillNames == null) return ''; + if (!Array.isArray(skillNames)) throw new ToolError('"skills" must be an array of skill names or null.'); + + const fileNames = [...new Set(skillNames.map(toSkillFileName))]; + const invalid = fileNames.filter((fileName) => !isSkillName(fileName)); + if (invalid.length > 0) { + throw new ToolError(`Invalid skill name(s): ${invalid.join(', ')}. Skills are flat names like "api-article".`); + } + + const sections = []; + const missing = []; + for (const fileName of fileNames) { + const content = readSkillContent(vfsRoot, fileName); + if (content == null) { + missing.push(fileName); + continue; + } + const { title, markdown } = parseSkill(content); + sections.push(`## ${title} (${fileName})\n\n${markdown}`); + } + if (missing.length > 0) { + throw new ToolError( + `Unknown skill(s): ${missing.join(', ')}. Call find_files({ skills: true }) to list available skills.` + ); + } + return sections.length > 0 ? `# INJECTED SKILLS\n\n${sections.join('\n\n')}` : ''; +} + +// #endregion + +// #region Conversation Guards + +/** + * Rejects a follow-up when the target thread is not in a state where appending a user + * message is a legal turn: it must be idle, and its last conversational message must + * not already be a `user` message awaiting a response. + * + * @param {object} conversation + * @param {Array<{ role: string }>} history + * @throws {ToolError} + */ +function assertConversationAcceptsTask(conversation, history) { + if (conversation.state !== 'idle') { + throw new ToolError(`Subagent conversation ${conversation.id} is busy; wait for it to finish.`); + } + // `usage` and `reasoning` rows are bookkeeping, not conversational turns. + const lastTurn = [...history].reverse().find((m) => m.role !== 'usage' && m.role !== 'reasoning'); + if (lastTurn?.role === 'user') { + throw new ToolError( + `Subagent conversation ${conversation.id} is already awaiting a response (last message is a user message).` + ); + } +} + +// #endregion + +// #region Helpers + +function stringifyToolOutput(result) { + return typeof result === 'string' ? result : JSON.stringify(result ?? ''); +} + +/** + * Builds the subagent toolbelt: the parent's tools without `ask_user`, `subagent` and + * `set_user_route`. + */ +function createSubagentTools({ googleAuthId, companyId, model }) { + return [ + createDashbackRequestTool({ googleAuthId }), + createJavascriptExecuteTool({ googleAuthId }), + createFindFilesTool({ googleAuthId }), + createReadFileTool({ googleAuthId }), + createPatchTool({ googleAuthId }), + createRmTool({ googleAuthId }), + createSearchImagesTool({ googleAuthId }), + createAnalyzeImageTool({ googleAuthId, model }), + createEditImageTool({ googleAuthId, model }), + createWebSearchTool({ googleAuthId }), + createUrlGetTool({ googleAuthId }), + createPdfReadTool({ googleAuthId }), + createResetVfsTool({ googleAuthId }), + createApiSuggestionsOrIssuesTool({ googleAuthId, companyId }), + createSearchArticlesTool({ googleAuthId, companyId }), + createEanChecksumTool(), + createNetGrossCalcTool(), + ]; +} + +// #endregion + +// #region Factory + +/** + * Creates the `subagent` tool. + * + * @param {{ + * googleAuthId: number, + * companyId: number, + * conversationId: number, + * parentModel: string, + * depth?: number, + * }} ctx `conversationId` is the active parent conversation (target of the self-talk guard); + * `parentModel` is the parent's resolved model, inherited by the subagent. + */ +// MARK: createSubagentTool — guarded subagent execution loop +export function createSubagentTool({ googleAuthId, companyId, conversationId: parentConversationId, parentModel, depth = 0 }) { + return defineTool({ + name: 'subagent', + description: TOOL_DESCRIPTIONS.subagent, + strict: false, + parameters: { + type: 'object', + additionalProperties: false, + required: ['task'], + properties: { + task: { type: 'string', description: TOOL_PARAMETER_DESCRIPTIONS.subagent.task }, + skills: { + type: ['array', 'null'], + items: { type: 'string' }, + description: TOOL_PARAMETER_DESCRIPTIONS.subagent.skills, + }, + conversation_id: { + type: ['integer', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.subagent.conversation_id, + }, + max_iterations: { + type: ['integer', 'null'], + description: TOOL_PARAMETER_DESCRIPTIONS.subagent.max_iterations, + }, + note: { type: ['string', 'null'], description: TOOL_PARAMETER_DESCRIPTIONS.subagent.note }, + }, + }, + invoke: async ({ task, skills = null, conversation_id: targetConversationId = null, max_iterations: maxIterations = null } = {}, { signal } = {}) => { + // MARK: validate input and guards before touching the database + if (depth >= MAX_SUBAGENT_DEPTH) { + throw new ToolError('Subagents cannot spawn further subagents.'); + } + if (typeof task !== 'string' || !task.trim()) { + throw new ToolError('"task" must be a non-empty string.'); + } + if (targetConversationId != null && targetConversationId === parentConversationId) { + throw new ToolError('Cannot target active parent conversation'); + } + const iterationLimit = maxIterations != null ? Number(maxIterations) : DEFAULT_MAX_ITERATIONS; + if (!Number.isInteger(iterationLimit) || iterationLimit < 1) { + throw new ToolError(`"max_iterations" must be a positive integer (received ${maxIterations}).`); + } + const boundedIterations = Math.min(iterationLimit, MAX_ITERATIONS_LIMIT); + + const vfsRoot = await prepareVfs({ googleAuthId }); + const injectedSkills = buildInjectedSkillsBlock(vfsRoot, skills); + + // MARK: create or resume the subagent conversation + let conversation; + let history = []; + if (targetConversationId != null) { + conversation = await db.get(googleAuthId, targetConversationId); + history = await db.listMessages(googleAuthId, targetConversationId); + if (conversation.started_by !== parentConversationId) { + throw new ToolError(`Conversation ${targetConversationId} is not a subagent conversation started by this conversation.`); + } + assertConversationAcceptsTask(conversation, history); + } else { + conversation = await db.create(googleAuthId, { provider: SUBAGENT_PROVIDER, model: parentModel, started_by: parentConversationId }); + emitCompanyEvent('modelconversation', { companyId }); + } + const subagentConversationId = conversation.id; + + // Persist the task as a user turn (DB refuses unless idle), then mark busy. + await db.addMessage(googleAuthId, subagentConversationId, { + role: 'user', + message: JSON.stringify({ content: task.trim() }), + }); + await db.setState(googleAuthId, subagentConversationId, 'busy'); + emitCompanyEvent('modelconversation', { companyId }); + + const toolCalls = []; + const toolCallsById = new Map(); + let streamedText = ''; + let streamedReasoning = ''; + + const saveMessage = async (role, payload, label) => { + try { + await db.addMessage(googleAuthId, subagentConversationId, { role, message: JSON.stringify(payload) }); + emitCompanyEvent('modelconversation', { companyId }); + } catch (err) { + console.error(`[subagent ${subagentConversationId}] failed to save ${label}:`, err); + } + }; + + try { + const apiKey = await resolveOpenRouterKey(googleAuthId); + const reasoningEffort = await resolveModelReasoning(googleAuthId); + const fullHistory = await db.listMessages(googleAuthId, subagentConversationId); + const systemPrompt = [ + await buildSystemPrompt(vfsRoot, googleAuthId), + SUBAGENT_PROMPT_NOTICE, + injectedSkills, + ].filter(Boolean).join('\n\n'); + + const orbiter = new LLMOrbiter(new OpenRouterProvider({ apiKey, apiUrl: env.openrouterApiUrl }), { + onReasoning: (reasoning) => { + streamedReasoning = reasoning; + }, + onContent: (chunk) => { + streamedText += chunk; + }, + onAssistantMessage: async ({ content, tool_calls, reasoning_details, reasoning }) => { + const plain = (reasoning || streamedReasoning.trim() || reasoning_details?.find((d) => d?.type === 'reasoning.summary')?.summary || '').trim(); + const encrypted = reasoning_details?.find((d) => d?.type === 'reasoning.encrypted')?.data || ''; + streamedReasoning = ''; + if (plain || encrypted) { + await saveMessage('reasoning', { plain, encrypted }, 'reasoning message'); + } + + const trimmedContent = (content || streamedText).trim(); + const hasToolCalls = Array.isArray(tool_calls) && tool_calls.length > 0; + if (trimmedContent || hasToolCalls) { + await saveMessage('assistant', { + content: trimmedContent, + ...(hasToolCalls ? { tool_calls } : {}), + }, 'assistant message'); + streamedText = ''; + } + }, + onToolCall: async ({ name, args, id, callItem }) => { + const rawArgs = callItem?.function?.arguments || (typeof args === 'string' ? args : JSON.stringify(args || {})); + const entry = { name, input_bytes: Buffer.byteLength(rawArgs), output_bytes: 0 }; + toolCalls.push(entry); + toolCallsById.set(id || callItem?.id || `${name}#${toolCalls.length}`, entry); + console.log(`[subagent ${subagentConversationId}] tool call: ${name} args=${rawArgs}`); + }, + onToolResult: async ({ name, result, id, callItem }) => { + const rawArgs = callItem?.function?.arguments || ''; + const output = stringifyToolOutput(result); + const entry = toolCallsById.get(id || callItem?.id); + if (entry) entry.output_bytes = Buffer.byteLength(output); + await saveMessage('tool', { + name, + parameters: rawArgs, + content: output, + tool_call_id: id || callItem?.id || '', + }, 'tool result message'); + }, + onToolError: async ({ name, error, id, callItem }) => { + const rawArgs = callItem?.function?.arguments || ''; + const output = `Tool error [${name}]: ${error}`; + const entry = toolCallsById.get(id || callItem?.id); + if (entry) entry.output_bytes = Buffer.byteLength(output); + await saveMessage('tool', { + name, + parameters: rawArgs, + content: output, + tool_call_id: id || callItem?.id || '', + }, 'tool error message'); + }, + onUsage: async (u) => { + if (!u) return; + await saveMessage('usage', { + input: u.input ?? 0, + cached: u.cached ?? 0, + output: u.output ?? 0, + ...(u.cost != null ? { cost: u.cost } : {}), + }, 'usage message'); + }, + onLLMCall: (call) => { + console.log( + `[subagent ${subagentConversationId}] LLM call #${call.iteration}: ` + + `model=${call.model}, messages=${call.messageCount}, promptChars=${call.promptSize}` + ); + }, + }); + + const result = await orbiter.run({ + messages: [ + { role: 'system', content: systemPrompt }, + ...historyToLlmMessages(fullHistory), + ], + model: parentModel, + maxIterations: boundedIterations, + extraBody: reasoningEffort ? { reasoning: { effort: reasoningEffort } } : {}, + tools: createSubagentTools({ googleAuthId, companyId, model: parentModel }), + signal, + }); + + const output = (result.content ?? '').trim(); + return { + conversation_id: subagentConversationId, + status: output ? 'completed' : 'empty', + output, + tool_calls: toolCalls, + iterations: result.iterations, + usage: { + input: result.usage?.input ?? 0, + output: result.usage?.output ?? 0, + cached: result.usage?.cached ?? 0, + }, + }; + } catch (err) { + if (err instanceof ToolError) throw err; + console.error(`[subagent ${subagentConversationId}] run failed:`, err); + throw new ToolError(`Subagent conversation ${subagentConversationId} failed: ${err.message}`); + } finally { + try { + await db.setState(googleAuthId, subagentConversationId, 'idle'); + } catch (err) { + console.error(`[subagent ${subagentConversationId}] failed to reset state:`, err); + } + emitCompanyEvent('modelconversation', { companyId }); + } + }, + }); +} + +// #endregion