@illuma-ai/agents 1.4.0-alpha.2 → 1.4.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cjs/main.cjs +37 -27
  2. package/dist/cjs/main.cjs.map +1 -1
  3. package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs +4 -0
  4. package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs.map +1 -1
  5. package/dist/cjs/providers/types.cjs.map +1 -1
  6. package/dist/cjs/tools/artifacts/schema.cjs +86 -0
  7. package/dist/cjs/tools/artifacts/schema.cjs.map +1 -0
  8. package/dist/cjs/tools/artifacts/tool.cjs +219 -0
  9. package/dist/cjs/tools/artifacts/tool.cjs.map +1 -0
  10. package/dist/cjs/tools/fileSearch/formatter.cjs +2 -4
  11. package/dist/cjs/tools/fileSearch/formatter.cjs.map +1 -1
  12. package/dist/cjs/tools/fileSearch/ragClient.cjs +4 -6
  13. package/dist/cjs/tools/fileSearch/ragClient.cjs.map +1 -1
  14. package/dist/cjs/tools/fileSearch/schema.cjs.map +1 -1
  15. package/dist/cjs/tools/fileSearch/tool.cjs.map +1 -1
  16. package/dist/esm/main.mjs +2 -0
  17. package/dist/esm/main.mjs.map +1 -1
  18. package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs +4 -0
  19. package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs.map +1 -1
  20. package/dist/esm/providers/types.mjs.map +1 -1
  21. package/dist/esm/tools/artifacts/schema.mjs +79 -0
  22. package/dist/esm/tools/artifacts/schema.mjs.map +1 -0
  23. package/dist/esm/tools/artifacts/tool.mjs +213 -0
  24. package/dist/esm/tools/artifacts/tool.mjs.map +1 -0
  25. package/dist/esm/tools/fileSearch/formatter.mjs +2 -4
  26. package/dist/esm/tools/fileSearch/formatter.mjs.map +1 -1
  27. package/dist/esm/tools/fileSearch/ragClient.mjs +4 -6
  28. package/dist/esm/tools/fileSearch/ragClient.mjs.map +1 -1
  29. package/dist/esm/tools/fileSearch/schema.mjs.map +1 -1
  30. package/dist/esm/tools/fileSearch/tool.mjs.map +1 -1
  31. package/dist/types/index.d.ts +1 -0
  32. package/dist/types/providers/types.d.ts +14 -0
  33. package/dist/types/tools/artifacts/index.d.ts +3 -0
  34. package/dist/types/tools/artifacts/schema.d.ts +63 -0
  35. package/dist/types/tools/artifacts/tool.d.ts +16 -0
  36. package/dist/types/tools/artifacts/types.d.ts +127 -0
  37. package/package.json +1 -1
  38. package/src/index.ts +1 -0
  39. package/src/providers/tools-server/ToolsServerCapabilityProvider.ts +8 -0
  40. package/src/providers/types.ts +17 -0
  41. package/src/tools/artifacts/__tests__/tool.test.ts +259 -0
  42. package/src/tools/artifacts/index.ts +33 -0
  43. package/src/tools/artifacts/schema.ts +99 -0
  44. package/src/tools/artifacts/tool.ts +289 -0
  45. package/src/tools/artifacts/types.ts +162 -0
  46. package/src/tools/fileSearch/__tests__/tool.test.ts +20 -10
  47. package/src/tools/fileSearch/formatter.ts +5 -7
  48. package/src/tools/fileSearch/ragClient.ts +6 -10
  49. package/src/tools/fileSearch/schema.ts +2 -2
  50. package/src/tools/fileSearch/tool.ts +6 -6
  51. package/src/tools/fileSearch/types.ts +4 -2
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.cjs","sources":["../../../../src/tools/fileSearch/formatter.ts"],"sourcesContent":["/**\n * Default result formatters.\n *\n * - `plainTextFormatter`: CLI / A2A / generic output. No citation anchors.\n * - `citationAnchorFormatter`: ranger-style `\\ue202turn0fileN` anchors with\n * a monotonic `sourceOffset` so multi-call turns stay globally unique.\n *\n * Runtimes can supply their own `FileSearchResultFormatter` to override.\n */\n\nimport type {\n FileSearchResultFormatter,\n FileSearchFile,\n RagChunk,\n} from './types';\n\ntype AnnotatedChunk = RagChunk & {\n filename: string;\n isCurrentMessage: boolean;\n};\n\nexport const plainTextFormatter: FileSearchResultFormatter = {\n format(chunks, { files: _files }) {\n if (chunks.length === 0) {\n return { message: 'No relevant results found in the available files.' };\n }\n const body = chunks\n .map((c) => {\n const page = getPage(c);\n const rel = (1 - c.distance).toFixed(4);\n return (\n `File: ${c.filename}` +\n (page != null ? `\\nPage: ${page}` : '') +\n `\\nRelevance: ${rel}\\nContent: ${c.page_content}\\n`\n );\n })\n .join('\\n---\\n');\n\n const sources = chunks.map((c) => ({\n type: 'file' as const,\n fileId: c.file_id,\n content: c.page_content,\n fileName: c.filename,\n relevance: 1 - c.distance,\n pages: getPage(c) != null ? [getPage(c) as number] : [],\n }));\n\n return { message: body, artifact: { file_search: { sources } } };\n },\n};\n\nexport interface CitationAnchorFormatterOptions {\n /** Tool name used in the `file_search` artifact wrapper. Defaults to `'file_search'`. */\n toolName?: string;\n /**\n * Monotonic counter for source indices within a turn. Pass the SAME\n * function to the formatter across multiple calls in the same turn so\n * anchors stay globally unique.\n */\n getSourceOffset?: () => number;\n /** Called after formatting to advance the offset. */\n advanceSourceOffset?: (by: number) => void;\n}\n\nexport function createCitationAnchorFormatter(\n opts: CitationAnchorFormatterOptions = {},\n): FileSearchResultFormatter {\n const toolName = opts.toolName ?? 'file_search';\n const getOffset = opts.getSourceOffset ?? (() => 0);\n const advance = opts.advanceSourceOffset ?? (() => {});\n\n return {\n format(chunks) {\n if (chunks.length === 0) {\n return {\n message:\n 'No results found or errors occurred while searching the files.',\n };\n }\n const base = getOffset();\n const body = chunks\n .map((c, i) => {\n const globalIndex = base + i;\n const page = getPage(c);\n const rel = (1 - c.distance).toFixed(4);\n return (\n `[Source ${globalIndex}] File: ${c.filename} | Anchor: \\\\ue202turn0file${globalIndex}` +\n (page != null ? ` | Page: ${page}` : '') +\n ` | Relevance: ${rel}\\nContent: ${c.page_content}\\n` +\n `↑ Cite this source using: \\\\ue202turn0file${globalIndex}`\n );\n })\n .join('\\n---\\n');\n\n const sources = chunks.map((c) => ({\n type: 'file' as const,\n fileId: c.file_id,\n content: c.page_content,\n fileName: c.filename,\n relevance: 1 - c.distance,\n pages: getPage(c) != null ? [getPage(c) as number] : [],\n pageRelevance:\n getPage(c) != null\n ? { [getPage(c) as number]: 1 - c.distance }\n : {},\n }));\n\n advance(chunks.length);\n return {\n message: body,\n artifact: { [toolName]: { sources, fileCitations: true } },\n };\n },\n };\n}\n\n/** Extract a 1-indexed page number from the chunk metadata, or null. */\nfunction getPage(chunk: AnnotatedChunk | RagChunk): number | null {\n const raw =\n (chunk.metadata?.page as unknown) ??\n (chunk.metadata?.page_number as unknown) ??\n null;\n if (raw == null) return null;\n const parsed = typeof raw === 'number' ? raw : parseInt(String(raw), 10);\n if (Number.isNaN(parsed) || parsed < 0) return null;\n // rag_api stores 0-indexed; display is 1-indexed\n return parsed + 1;\n}\n\n// Re-export so consumers only import from the formatter module.\nexport type { FileSearchResultFormatter, FileSearchFile, RagChunk };\n"],"names":[],"mappings":";;AAAA;;;;;;;;AAQG;AAaI,MAAM,kBAAkB,GAA8B;AAC3D,IAAA,MAAM,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,EAAA;AAC9B,QAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,YAAA,OAAO,EAAE,OAAO,EAAE,mDAAmD,EAAE;QACzE;QACA,MAAM,IAAI,GAAG;AACV,aAAA,GAAG,CAAC,CAAC,CAAC,KAAI;AACT,YAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC;AACvB,YAAA,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AACvC,YAAA,QACE,CAAA,MAAA,EAAS,CAAC,CAAC,QAAQ,CAAA,CAAE;AACrB,iBAAC,IAAI,IAAI,IAAI,GAAG,CAAA,QAAA,EAAW,IAAI,CAAA,CAAE,GAAG,EAAE,CAAC;AACvC,gBAAA,CAAA,aAAA,EAAgB,GAAG,CAAA,WAAA,EAAc,CAAC,CAAC,YAAY,CAAA,EAAA,CAAI;A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D;QACH,CAAC;KACF;AACH;AAEA;AACA,SAAS,OAAO,CAAC,KAAgC,EAAA;AAC/C,IAAA,MAAM,GAAG,GACN,KAAK,CAAC,QAAQ,EAAE,IAAgB;QAChC,KAAK,CAAC,QAAQ,EAAE,WAAuB;AACxC,QAAA,IAAI;IACN,IAAI,GAAG,IAAI,IAAI;AAAE,QAAA,OAAO,IAAI;IAC5B,MAAM,MAAM,GAAG,OAAO,GAAG,KAAK,QAAQ,GAAG,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;IACxE,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;AAAE,QAAA,OAAO,IAAI;;IAEnD,OAAO,MAAM,GAAG,CAAC;AACnB;;;;;"}
1
+ {"version":3,"file":"formatter.cjs","sources":["../../../../src/tools/fileSearch/formatter.ts"],"sourcesContent":["/**\n * Default result formatters.\n *\n * - `plainTextFormatter`: CLI / A2A / generic output. No citation anchors.\n * - `citationAnchorFormatter`: ranger-style `\\ue202turn0fileN` anchors with\n * a monotonic `sourceOffset` so multi-call turns stay globally unique.\n *\n * Runtimes can supply their own `FileSearchResultFormatter` to override.\n */\n\nimport type {\n FileSearchResultFormatter,\n FileSearchFile,\n RagChunk,\n} from './types';\n\ntype AnnotatedChunk = RagChunk & {\n filename: string;\n isCurrentMessage: boolean;\n};\n\nexport const plainTextFormatter: FileSearchResultFormatter = {\n format(chunks, { files: _files }) {\n if (chunks.length === 0) {\n return { message: 'No relevant results found in the available files.' };\n }\n const body = chunks\n .map((c) => {\n const page = getPage(c);\n const rel = (1 - c.distance).toFixed(4);\n return (\n `File: ${c.filename}` +\n (page != null ? `\\nPage: ${page}` : '') +\n `\\nRelevance: ${rel}\\nContent: ${c.page_content}\\n`\n );\n })\n .join('\\n---\\n');\n\n const sources = chunks.map((c) => ({\n type: 'file' as const,\n fileId: c.file_id,\n content: c.page_content,\n fileName: c.filename,\n relevance: 1 - c.distance,\n pages: getPage(c) != null ? [getPage(c) as number] : [],\n }));\n\n return { message: body, artifact: { file_search: { sources } } };\n },\n};\n\nexport interface CitationAnchorFormatterOptions {\n /** Tool name used in the `file_search` artifact wrapper. Defaults to `'file_search'`. */\n toolName?: string;\n /**\n * Monotonic counter for source indices within a turn. Pass the SAME\n * function to the formatter across multiple calls in the same turn so\n * anchors stay globally unique.\n */\n getSourceOffset?: () => number;\n /** Called after formatting to advance the offset. */\n advanceSourceOffset?: (by: number) => void;\n}\n\nexport function createCitationAnchorFormatter(\n opts: CitationAnchorFormatterOptions = {}\n): FileSearchResultFormatter {\n const toolName = opts.toolName ?? 'file_search';\n const getOffset = opts.getSourceOffset ?? ((): number => 0);\n const advance = opts.advanceSourceOffset ?? ((_by: number): void => {});\n\n return {\n format(chunks): { message: string; artifact?: unknown } {\n if (chunks.length === 0) {\n return {\n message:\n 'No results found or errors occurred while searching the files.',\n };\n }\n const base = getOffset();\n const body = chunks\n .map((c, i) => {\n const globalIndex = base + i;\n const page = getPage(c);\n const rel = (1 - c.distance).toFixed(4);\n return (\n `[Source ${globalIndex}] File: ${c.filename} | Anchor: \\\\ue202turn0file${globalIndex}` +\n (page != null ? ` | Page: ${page}` : '') +\n ` | Relevance: ${rel}\\nContent: ${c.page_content}\\n` +\n `↑ Cite this source using: \\\\ue202turn0file${globalIndex}`\n );\n })\n .join('\\n---\\n');\n\n const sources = chunks.map((c) => ({\n type: 'file' as const,\n fileId: c.file_id,\n content: c.page_content,\n fileName: c.filename,\n relevance: 1 - c.distance,\n pages: getPage(c) != null ? [getPage(c) as number] : [],\n pageRelevance:\n getPage(c) != null ? { [getPage(c) as number]: 1 - c.distance } : {},\n }));\n\n advance(chunks.length);\n return {\n message: body,\n artifact: { [toolName]: { sources, fileCitations: true } },\n };\n },\n };\n}\n\n/** Extract a 1-indexed page number from the chunk metadata, or null. */\nfunction getPage(chunk: AnnotatedChunk | RagChunk): number | null {\n const raw =\n (chunk.metadata?.page as unknown) ??\n (chunk.metadata?.page_number as unknown) ??\n null;\n if (raw == null) return null;\n const parsed = typeof raw === 'number' ? raw : parseInt(String(raw), 10);\n if (Number.isNaN(parsed) || parsed < 0) return null;\n // rag_api stores 0-indexed; display is 1-indexed\n return parsed + 1;\n}\n\n// Re-export so consumers only import from the formatter module.\nexport type { FileSearchResultFormatter, FileSearchFile, RagChunk };\n"],"names":[],"mappings":";;AAAA;;;;;;;;AAQG;AAaI,MAAM,kBAAkB,GAA8B;AAC3D,IAAA,MAAM,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,EAAA;AAC9B,QAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,YAAA,OAAO,EAAE,OAAO,EAAE,mDAAmD,EAAE;QACzE;QACA,MAAM,IAAI,GAAG;AACV,aAAA,GAAG,CAAC,CAAC,CAAC,KAAI;AACT,YAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC;AACvB,YAAA,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AACvC,YAAA,QACE,CAAA,MAAA,EAAS,CAAC,CAAC,QAAQ,CAAA,CAAE;AACrB,iBAAC,IAAI,IAAI,IAAI,GAAG,CAAA,QAAA,EAAW,IAAI,CAAA,CAAE,GAAG,EAAE,CAAC;AACvC,gBAAA,CAAA,aAAA,EAAgB,GAAG,CAAA,WAAA,EAAc,CAAC,CAAC,YAAY,CAAA,EAAA,CAAI;AAEvD,QAAA,CAAC;aACA,IAAI,CAAC,SAAS,CAAC;QAElB,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM;AACjC,YAAA,IAAI,EAAE,MAAe;YACrB,MAAM,EAAE,CAAC,CAAC,OAAO;YACjB,OAAO,EAAE,CAAC,CAAC,YAAY;YACvB,QAAQ,EAAE,CAAC,CAAC,QAAQ;AACpB,YAAA,SAAS,EAAE,CAAC,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,QAAQ,GAAG,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;IACxE,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;AAAE,QAAA,OAAO,IAAI;;IAEnD,OAAO,MAAM,GAAG,CAAC;AACnB;;;;;"}
@@ -15,9 +15,7 @@ var env = require('@langchain/core/utils/env');
15
15
  const RAG_API_URL_ENV = 'RAG_API_URL';
16
16
  /** Resolve base URL at call time so env-var changes propagate. */
17
17
  function getRagBaseUrl(override) {
18
- const url = override ??
19
- env.getEnvironmentVariable(RAG_API_URL_ENV) ??
20
- '';
18
+ const url = override ?? env.getEnvironmentVariable(RAG_API_URL_ENV) ?? '';
21
19
  if (!url) {
22
20
  throw new Error(`file_search: ${RAG_API_URL_ENV} is not configured. ` +
23
21
  `Set the env var or pass baseUrl to HttpRagClient.`);
@@ -90,10 +88,10 @@ class HttpRagClient {
90
88
  return resp
91
89
  .filter((row) => Array.isArray(row) && row.length === 2)
92
90
  .map(([doc, distance]) => ({
93
- file_id: doc?.metadata?.file_id ?? file_id,
94
- page_content: doc?.page_content ?? '',
91
+ file_id: doc.metadata?.file_id ?? file_id,
92
+ page_content: doc.page_content ?? '',
95
93
  distance: typeof distance === 'number' ? distance : 1,
96
- metadata: doc?.metadata,
94
+ metadata: doc.metadata,
97
95
  }));
98
96
  }
99
97
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ragClient.cjs","sources":["../../../../src/tools/fileSearch/ragClient.ts"],"sourcesContent":["/**\n * Default HTTP RAG client. Posts to `${baseUrl}/query` with the shape\n * rag_api expects (`{ file_id, query, k, entity_id? }`). Runtimes that\n * use a different vector backend implement their own `RagClient`.\n *\n * Auth is runtime-provided per call (via `authHeaders` on the params) so\n * short-lived tokens can be minted per request without the client\n * caching stale credentials.\n */\n\nimport fetch from 'node-fetch';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type {\n RagClient,\n RagQueryParams,\n RagChunk,\n FileSearchToolLogger,\n} from './types';\n\nexport const RAG_API_URL_ENV = 'RAG_API_URL';\n\n/** Resolve base URL at call time so env-var changes propagate. */\nexport function getRagBaseUrl(override?: string): string {\n const url =\n override ??\n getEnvironmentVariable(RAG_API_URL_ENV) ??\n '';\n if (!url) {\n throw new Error(\n `file_search: ${RAG_API_URL_ENV} is not configured. ` +\n `Set the env var or pass baseUrl to HttpRagClient.`,\n );\n }\n return url.replace(/\\/$/, '');\n}\n\nexport interface HttpRagClientOptions {\n /** Base URL of the RAG service (no trailing slash). Falls back to env. */\n baseUrl?: string;\n /** Default headers sent on every request (e.g., a static API key). */\n defaultHeaders?: Record<string, string>;\n /** Default timeout if params don't override. Default 15_000. */\n defaultTimeoutMs?: number;\n logger?: FileSearchToolLogger;\n}\n\n/**\n * Expected rag_api response shape: `[[{ page_content, metadata }, distance], ...]`\n * — an array of [doc, score] tuples. Normalized here into `RagChunk[]`.\n */\ntype RagApiResponse = Array<\n [\n {\n page_content: string;\n metadata?: Record<string, unknown>;\n },\n number,\n ]\n>;\n\nexport class HttpRagClient implements RagClient {\n private readonly baseUrlOverride?: string;\n private readonly defaultHeaders: Record<string, string>;\n private readonly defaultTimeoutMs: number;\n private readonly logger?: FileSearchToolLogger;\n\n constructor(opts: HttpRagClientOptions = {}) {\n this.baseUrlOverride = opts.baseUrl;\n this.defaultHeaders = opts.defaultHeaders ?? {};\n this.defaultTimeoutMs = opts.defaultTimeoutMs ?? 15_000;\n this.logger = opts.logger;\n }\n\n async query(params: RagQueryParams): Promise<RagChunk[]> {\n const baseUrl = getRagBaseUrl(this.baseUrlOverride);\n const url = `${baseUrl}/query`;\n\n const body: Record<string, unknown> = {\n file_id: params.file_id,\n query: params.query,\n k: params.k ?? 10,\n };\n if (params.entity_id) body.entity_id = params.entity_id;\n if (params.scope) body.scope = params.scope;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.defaultHeaders,\n ...(params.authHeaders ?? {}),\n };\n\n const timeoutMs = params.timeoutMs ?? this.defaultTimeoutMs;\n const controller =\n typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timer = controller\n ? setTimeout(() => controller.abort(), timeoutMs)\n : null;\n\n this.logger?.debug('[file_search] RAG query', {\n url,\n file_id: params.file_id,\n k: body.k,\n });\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: controller?.signal as unknown as undefined,\n });\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(\n `RAG query failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`,\n );\n }\n const json = (await res.json()) as RagApiResponse;\n return this.normalize(params.file_id, json);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n /** Convert rag_api's tuple format into the library's normalized shape. */\n private normalize(file_id: string, resp: RagApiResponse): RagChunk[] {\n if (!Array.isArray(resp)) {\n this.logger?.warn('[file_search] RAG response not an array', { resp });\n return [];\n }\n return resp\n .filter((row) => Array.isArray(row) && row.length === 2)\n .map(([doc, distance]) => ({\n file_id:\n (doc?.metadata?.file_id as string | undefined) ?? file_id,\n page_content: doc?.page_content ?? '',\n distance: typeof distance === 'number' ? distance : 1,\n metadata: doc?.metadata,\n }));\n }\n}\n"],"names":["getEnvironmentVariable"],"mappings":";;;;;AAAA;;;;;;;;AAQG;AAWI,MAAM,eAAe,GAAG;AAE/B;AACM,SAAU,aAAa,CAAC,QAAiB,EAAA;IAC7C,MAAM,GAAG,GACP,QAAQ;QACRA,0BAAsB,CAAC,eAAe,CAAC;AACvC,QAAA,EAAE;IACJ,IAAI,CAAC,GAAG,EAAE;AACR,QAAA,MAAM,IAAI,KAAK,CACb,CAAA,aAAA,EAAgB,eAAe,CAAA,oBAAA,CAAsB;AACnD,YAAA,CAAA,iDAAA,CAAmD,CACtD;IACH;IACA,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;AAC/B;MA0Ba,aAAa,CAAA;AACP,IAAA,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KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;aACtD,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM;AACzB,YAAA,OAAO,EACJ,GAAG,EAAE,QAAQ,EAAE,OAA8B,IAAI,OAAO;AAC3D,YAAA,YAAY,EAAE,GAAG,EAAE,YAAY,IAAI,EAAE;AACrC,YAAA,QAAQ,EAAE,OAAO,QAAQ,KAAK,QAAQ,GAAG,QAAQ,GAAG,CAAC;YACrD,QAAQ,EAAE,GAAG,EAAE,QAAQ;AACxB,SAAA,CAAC,CAAC;IACP;AACD;;;;;;"}
1
+ {"version":3,"file":"ragClient.cjs","sources":["../../../../src/tools/fileSearch/ragClient.ts"],"sourcesContent":["/**\n * Default HTTP RAG client. Posts to `${baseUrl}/query` with the shape\n * rag_api expects (`{ file_id, query, k, entity_id? }`). Runtimes that\n * use a different vector backend implement their own `RagClient`.\n *\n * Auth is runtime-provided per call (via `authHeaders` on the params) so\n * short-lived tokens can be minted per request without the client\n * caching stale credentials.\n */\n\nimport fetch from 'node-fetch';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type {\n RagClient,\n RagQueryParams,\n RagChunk,\n FileSearchToolLogger,\n} from './types';\n\nexport const RAG_API_URL_ENV = 'RAG_API_URL';\n\n/** Resolve base URL at call time so env-var changes propagate. */\nexport function getRagBaseUrl(override?: string): string {\n const url = override ?? getEnvironmentVariable(RAG_API_URL_ENV) ?? '';\n if (!url) {\n throw new Error(\n `file_search: ${RAG_API_URL_ENV} is not configured. ` +\n `Set the env var or pass baseUrl to HttpRagClient.`\n );\n }\n return url.replace(/\\/$/, '');\n}\n\nexport interface HttpRagClientOptions {\n /** Base URL of the RAG service (no trailing slash). Falls back to env. */\n baseUrl?: string;\n /** Default headers sent on every request (e.g., a static API key). */\n defaultHeaders?: Record<string, string>;\n /** Default timeout if params don't override. Default 15_000. */\n defaultTimeoutMs?: number;\n logger?: FileSearchToolLogger;\n}\n\n/**\n * Expected rag_api response shape: `[[{ page_content, metadata }, distance], ...]`\n * — an array of [doc, score] tuples. Normalized here into `RagChunk[]`.\n */\ntype RagApiResponse = Array<\n [\n {\n page_content: string;\n metadata?: Record<string, unknown>;\n },\n number,\n ]\n>;\n\nexport class HttpRagClient implements RagClient {\n private readonly baseUrlOverride?: string;\n private readonly defaultHeaders: Record<string, string>;\n private readonly defaultTimeoutMs: number;\n private readonly logger?: FileSearchToolLogger;\n\n constructor(opts: HttpRagClientOptions = {}) {\n this.baseUrlOverride = opts.baseUrl;\n this.defaultHeaders = opts.defaultHeaders ?? {};\n this.defaultTimeoutMs = opts.defaultTimeoutMs ?? 15_000;\n this.logger = opts.logger;\n }\n\n async query(params: RagQueryParams): Promise<RagChunk[]> {\n const baseUrl = getRagBaseUrl(this.baseUrlOverride);\n const url = `${baseUrl}/query`;\n\n const body: Record<string, unknown> = {\n file_id: params.file_id,\n query: params.query,\n k: params.k ?? 10,\n };\n if (params.entity_id) body.entity_id = params.entity_id;\n if (params.scope) body.scope = params.scope;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.defaultHeaders,\n ...(params.authHeaders ?? {}),\n };\n\n const timeoutMs = params.timeoutMs ?? this.defaultTimeoutMs;\n const controller =\n typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timer = controller\n ? setTimeout(() => controller.abort(), timeoutMs)\n : null;\n\n this.logger?.debug('[file_search] RAG query', {\n url,\n file_id: params.file_id,\n k: body.k,\n });\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: controller?.signal as unknown as undefined,\n });\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(\n `RAG query failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`\n );\n }\n const json = (await res.json()) as RagApiResponse;\n return this.normalize(params.file_id, json);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n /** Convert rag_api's tuple format into the library's normalized shape. */\n private normalize(file_id: string, resp: RagApiResponse): RagChunk[] {\n if (!Array.isArray(resp)) {\n this.logger?.warn('[file_search] RAG response not an array', { resp });\n return [];\n }\n return resp\n .filter((row) => Array.isArray(row) && row.length === 2)\n .map(([doc, distance]) => ({\n file_id: (doc.metadata?.file_id as string | undefined) ?? file_id,\n page_content: doc.page_content ?? '',\n distance: typeof distance === 'number' ? distance : 1,\n metadata: doc.metadata,\n }));\n }\n}\n"],"names":["getEnvironmentVariable"],"mappings":";;;;;AAAA;;;;;;;;AAQG;AAWI,MAAM,eAAe,GAAG;AAE/B;AACM,SAAU,aAAa,CAAC,QAAiB,EAAA;IAC7C,MAAM,GAAG,GAAG,QAAQ,IAAIA,0BAAsB,CAAC,eAAe,CAAC,IAAI,EAAE;IACrE,IAAI,CAAC,GAAG,EAAE;AACR,QAAA,MAAM,IAAI,KAAK,CACb,CAAA,aAAA,EAAgB,eAAe,CAAA,oBAAA,CAAsB;AACnD,YAAA,CAAA,iDAAA,CAAmD,CACtD;IACH;IACA,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;AAC/B;MA0Ba,aAAa,CAAA;AACP,IAAA,eAAe;AACf,IAAA,cAAc;AACd,IAAA,gBAAgB;AAChB,IAAA,MAAM;AAEvB,IAAA,WAAA,CAAY,OAA6B,EAAE,EAAA;AACzC,QAAA,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,OAAO;QACnC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,IAAI,EAAE;QAC/C,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,gBAAgB,IAAI,MAAM;AACvD,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM;IAC3B;IAEA,MAAM,KAAK,CAAC,MAAsB,EAAA;QAChC,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC;AACnD,QAAA,MAAM,GAAG,GAAG,CAAA,EAAG,OAAO,QAAQ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z } from 'zod';\n\nexport const fileSearchInputSchema = z.object({\n query: z\n .string()\n .describe(\n \"A natural language query to search for relevant information in the files. Be SPECIFIC and TARGETED — use keywords for the specific section or topic you need. For comprehensive tasks (summaries, overviews), call this tool multiple times with different targeted queries (e.g., 'introduction', 'methodology', 'results', 'conclusions') rather than one broad query.\",\n ),\n target_files: z\n .array(z.string())\n .optional()\n .describe(\n 'Optional list of filenames (or partial names) to limit the search to. When provided, only files whose name contains one of these strings will be searched. Use this to avoid searching irrelevant files. Omit to search all available files.',\n ),\n});\n\nexport type FileSearchInput = z.infer<typeof fileSearchInputSchema>;\n\nexport const FileSearchToolName = 'file_search';\n"],"names":["z"],"mappings":";;;;AAEO,MAAM,qBAAqB,GAAGA,KAAC,CAAC,MAAM,CAAC;AAC5C,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;SACN,QAAQ,CACP,0WAA0W,CAC3W;AACH,IAAA,YAAY,EAAEA;AACX,SAAA,KAAK,CAACA,KAAC,CAAC,MAAM,EAAE;AAChB,SAAA,QAAQ;SACR,QAAQ,CACP,8OAA8O,CAC/O;AACJ,CAAA;AAIM,MAAM,kBAAkB,GAAG;;;;;"}
1
+ {"version":3,"file":"schema.cjs","sources":["../../../../src/tools/fileSearch/schema.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const fileSearchInputSchema = z.object({\n query: z\n .string()\n .describe(\n \"A natural language query to search for relevant information in the files. Be SPECIFIC and TARGETED — use keywords for the specific section or topic you need. For comprehensive tasks (summaries, overviews), call this tool multiple times with different targeted queries (e.g., 'introduction', 'methodology', 'results', 'conclusions') rather than one broad query.\"\n ),\n target_files: z\n .array(z.string())\n .optional()\n .describe(\n 'Optional list of filenames (or partial names) to limit the search to. When provided, only files whose name contains one of these strings will be searched. Use this to avoid searching irrelevant files. Omit to search all available files.'\n ),\n});\n\nexport type FileSearchInput = z.infer<typeof fileSearchInputSchema>;\n\nexport const FileSearchToolName = 'file_search';\n"],"names":["z"],"mappings":";;;;AAEO,MAAM,qBAAqB,GAAGA,KAAC,CAAC,MAAM,CAAC;AAC5C,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;SACN,QAAQ,CACP,0WAA0W,CAC3W;AACH,IAAA,YAAY,EAAEA;AACX,SAAA,KAAK,CAACA,KAAC,CAAC,MAAM,EAAE;AAChB,SAAA,QAAQ;SACR,QAAQ,CACP,8OAA8O,CAC/O;AACJ,CAAA;AAIM,MAAM,kBAAkB,GAAG;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.cjs","sources":["../../../../src/tools/fileSearch/tool.ts"],"sourcesContent":["/**\n * file_search tool factory — library-native equivalent of the CodeExecutor\n * pattern. Runtimes supply a `RagClient`, the file list for this turn, and\n * an optional formatter (ranger uses citation anchors; CLI/A2A use plain\n * text).\n *\n * The tool itself:\n * 1. Accepts `{ query, target_files? }` from the LLM.\n * 2. Filters files by `target_files` substring match when provided.\n * 3. Queries each file in bounded concurrent batches.\n * 4. Enforces per-file timeouts (failures isolated per file).\n * 5. Flattens chunks, deprioritizes stale-turn files, caps results.\n * 6. Hands formatted output to the runtime's formatter for final shape.\n */\n\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport {\n fileSearchInputSchema,\n type FileSearchInput,\n FileSearchToolName,\n} from './schema';\nimport type {\n FileSearchToolConfig,\n FileSearchFile,\n RagChunk,\n RagQueryParams,\n} from './types';\nimport { plainTextFormatter } from './formatter';\n\nconst DEFAULT_QUERY_TIMEOUT_MS = 15_000;\nconst DEFAULT_CONCURRENCY = 10;\nconst DEFAULT_TOP_K = 10;\n\n/**\n * Build the tool description. Runtimes that use citation anchors supply\n * `fileCitations: true` (via the formatter); the description includes the\n * citation ruleset only when that's on.\n */\nfunction buildDescription(opts: { fileCitations: boolean }): string {\n const core = `Performs semantic search across the attached \"${FileSearchToolName}\" documents using natural language queries. Analyzes the content of loaded files to find relevant information, quotes, and passages matching the query.\n\n**Use target_files to narrow the search:**\nWhen you know which file(s) contain the relevant information, ALWAYS pass target_files. This is faster and returns more focused results. Pass partial filenames — they match via substring.\n\n**Multiple searches for thorough analysis:**\nFor summaries/overviews, call this tool MULTIPLE times with DIFFERENT queries targeting different aspects (intro, methodology, results, conclusions). A single search only returns chunks from one part of the document.`;\n\n if (!opts.fileCitations) return core;\n\n return `${core}\n\n**CITING FILE SEARCH RESULTS — MANDATORY:**\nCite EVERY statement derived from file content. Place the citation anchor IMMEDIATELY after each paragraph using that source. Each search result has a unique source index — use DIFFERENT indices for different claims; do not reuse the same anchor for all paragraphs. Format: \\`\\\\ue202turn0fileN\\`. With a page: include \\`(p. N)\\` inline. Multiple sources: \\`\\\\ue200\\\\ue202turn0file0\\\\ue202turn0file1\\\\ue201\\`. NEVER substitute with footnotes, brackets, or symbols.`;\n}\n\nexport function createFileSearchTool(\n config: FileSearchToolConfig,\n): DynamicStructuredTool {\n const {\n ragClient,\n files,\n entity_id,\n scope,\n getAuthHeaders,\n formatter = plainTextFormatter,\n queryTimeoutMs = DEFAULT_QUERY_TIMEOUT_MS,\n concurrencyLimit = DEFAULT_CONCURRENCY,\n topK = DEFAULT_TOP_K,\n resultCap,\n callbacks,\n logger,\n } = config;\n\n // Monotonic call counter used by citation-style formatters to keep source\n // indices unique across multiple invocations within a single turn.\n let callIndex = 0;\n\n // Infer whether the formatter wants citations from the artifact it emits\n // on an empty-chunk format. This keeps the description/behavior aligned\n // without forcing the host to declare `fileCitations` twice.\n const fileCitations = formatter !== plainTextFormatter;\n\n return tool(\n async (rawInput: FileSearchInput) => {\n const { query, target_files } = rawInput;\n\n if (files.length === 0) {\n return [\n 'No files to search. Instruct the user to add files for the search.',\n undefined,\n ];\n }\n\n // target_files: case-insensitive substring match, fallback to all\n // files with a warning if the filter excludes everything.\n let filesToQuery: FileSearchFile[] = files;\n if (target_files && target_files.length > 0) {\n const lowerTargets = target_files.map((t) => t.toLowerCase());\n const matched = files.filter((f) =>\n lowerTargets.some((t) => f.filename.toLowerCase().includes(t)),\n );\n if (matched.length === 0) {\n logger?.warn(\n `[file_search] No files matched target_files ${target_files.join(', ')}; falling back to all files`,\n );\n filesToQuery = files;\n } else {\n logger?.info(\n `[file_search] Filtered to ${matched.length}/${files.length} via target_files`,\n );\n filesToQuery = matched;\n }\n }\n\n const authHeaders = getAuthHeaders ? await getAuthHeaders() : undefined;\n\n const queryOne = async (file: FileSearchFile): Promise<RagChunk[]> => {\n const params: RagQueryParams = {\n file_id: file.file_id,\n query,\n k: topK,\n entity_id,\n scope,\n authHeaders,\n timeoutMs: queryTimeoutMs,\n };\n try {\n const chunks = await ragClient.query(params);\n callbacks?.onFileQueried?.(file, chunks.length);\n return chunks;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n logger?.error(\n `[file_search] Query failed for ${file.filename}: ${e.message}`,\n );\n callbacks?.onFileError?.(file, e);\n return [];\n }\n };\n\n // Bounded-concurrency batching. Server-side rerankers handle their\n // own concurrency; this protects the HTTP connection pool when the\n // agent has many files.\n const allChunks: RagChunk[] = [];\n for (let i = 0; i < filesToQuery.length; i += concurrencyLimit) {\n const batch = filesToQuery.slice(i, i + concurrencyLimit);\n const batchResults = await Promise.all(batch.map(queryOne));\n for (const chunks of batchResults) allChunks.push(...chunks);\n }\n\n if (allChunks.length === 0) {\n return [\n 'No content found in the files. The files may not have been processed correctly or the query may need refinement.',\n undefined,\n ];\n }\n\n // Build annotated results: attach filename + isCurrentMessage via\n // a file-id lookup (metadata wins, factory list is fallback).\n const fileById = new Map(files.map((f) => [f.file_id, f]));\n const annotated = allChunks.map((c) => {\n const matched = fileById.get(c.file_id);\n const filename =\n (c.metadata?.source\n ? String(c.metadata.source).split(/[/\\\\]/).pop()\n : undefined) ??\n matched?.filename ??\n 'Unknown';\n return {\n ...c,\n filename,\n isCurrentMessage: matched?.isCurrentMessage === true,\n };\n });\n\n // Sort: current-turn files first, then by relevance (lower distance).\n annotated.sort((a, b) => {\n if (a.isCurrentMessage !== b.isCurrentMessage)\n return a.isCurrentMessage ? -1 : 1;\n return a.distance - b.distance;\n });\n\n const cap = resultCap ?? Math.max(10, filesToQuery.length * 3);\n const limited = annotated.slice(0, cap);\n\n const { message, artifact } = formatter.format(limited, {\n callIndex,\n files,\n });\n callIndex += 1;\n\n // Suppress unused-variable warning for fileCitations (currently only\n // used to gate description; kept in case formatters need it).\n void fileCitations;\n\n return [message, artifact];\n },\n {\n name: FileSearchToolName,\n responseFormat: 'content_and_artifact',\n description: buildDescription({ fileCitations }),\n schema: fileSearchInputSchema,\n },\n );\n}\n\nexport { FileSearchToolName } from './schema';\n"],"names":["FileSearchToolName","formatter","plainTextFormatter","tool","fileSearchInputSchema"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;AAaG;AAgBH,MAAM,wBAAwB,GAAG,MAAM;AACvC,MAAM,mBAAmB,GAAG,EAAE;AAC9B,MAAM,aAAa,GAAG,EAAE;AAExB;;;;AAIG;AACH,SAAS,gBAAgB,CAAC,IAAgC,EAAA;IACxD,MAAM,IAAI,GAAG,CAAA,8CAAA,EAAiDA,yBAAkB,CAAA;;;;;;yNAMuI;IAEvN,IAAI,CAAC,IAAI,CAAC,aAAa;AAAE,QAAA,OAAO,IAAI;AAEpC,IAAA,OAAO,GAAG,IAAI;;;gdAGgc;AAChd;AAEM,SAAU,oBAAoB,CAClC,MAA4B,EAAA;AAE5B,IAAA,MAAM,EACJ,SAAS,EACT,KAAK,EACL,SAAS,EACT,KAAK,EACL,cAAc,aACdC,WAAS,GAAGC,4BAAkB,EAC9B,cAAc,GAAG,wBAAwB,EACzC,gBAAgB,GAAG,mBAAmB,EACtC,IAAI,GAAG,aAAa,EACpB,SAAS,EACT,SAAS,EACT,MAAM,GACP,GAAG,MAAM;;;IAIV,IAAI,SAAS,GAAG,CAAC;;;;AAKjB,IAAA,MAAM,aAAa,GAAGD,WAAS,KAAKC,4BAAkB;AAEtD,IAAA,OAAOC,UAAI,CACT,OAAO,QAAyB,KAAI;AAClC,QAAA,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,QAAQ;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C,QAAA,WAAW,EAAE,gBAAgB,CAAC,EAAE,aAAa,EAAE,CAAC;AAChD,QAAA,MAAM,EAAEI,4BAAqB;AAC9B,KAAA,CACF;AACH;;;;;"}
1
+ {"version":3,"file":"tool.cjs","sources":["../../../../src/tools/fileSearch/tool.ts"],"sourcesContent":["/**\n * file_search tool factory — library-native equivalent of the CodeExecutor\n * pattern. Runtimes supply a `RagClient`, the file list for this turn, and\n * an optional formatter (ranger uses citation anchors; CLI/A2A use plain\n * text).\n *\n * The tool itself:\n * 1. Accepts `{ query, target_files? }` from the LLM.\n * 2. Filters files by `target_files` substring match when provided.\n * 3. Queries each file in bounded concurrent batches.\n * 4. Enforces per-file timeouts (failures isolated per file).\n * 5. Flattens chunks, deprioritizes stale-turn files, caps results.\n * 6. Hands formatted output to the runtime's formatter for final shape.\n */\n\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport {\n fileSearchInputSchema,\n type FileSearchInput,\n FileSearchToolName,\n} from './schema';\nimport type {\n FileSearchToolConfig,\n FileSearchFile,\n RagChunk,\n RagQueryParams,\n} from './types';\nimport { plainTextFormatter } from './formatter';\n\nconst DEFAULT_QUERY_TIMEOUT_MS = 15_000;\nconst DEFAULT_CONCURRENCY = 10;\nconst DEFAULT_TOP_K = 10;\n\n/**\n * Build the tool description. Runtimes that use citation anchors supply\n * `fileCitations: true` (via the formatter); the description includes the\n * citation ruleset only when that's on.\n */\nfunction buildDescription(opts: { fileCitations: boolean }): string {\n const core = `Performs semantic search across the attached \"${FileSearchToolName}\" documents using natural language queries. Analyzes the content of loaded files to find relevant information, quotes, and passages matching the query.\n\n**Use target_files to narrow the search:**\nWhen you know which file(s) contain the relevant information, ALWAYS pass target_files. This is faster and returns more focused results. Pass partial filenames — they match via substring.\n\n**Multiple searches for thorough analysis:**\nFor summaries/overviews, call this tool MULTIPLE times with DIFFERENT queries targeting different aspects (intro, methodology, results, conclusions). A single search only returns chunks from one part of the document.`;\n\n if (!opts.fileCitations) return core;\n\n return `${core}\n\n**CITING FILE SEARCH RESULTS — MANDATORY:**\nCite EVERY statement derived from file content. Place the citation anchor IMMEDIATELY after each paragraph using that source. Each search result has a unique source index — use DIFFERENT indices for different claims; do not reuse the same anchor for all paragraphs. Format: \\`\\\\ue202turn0fileN\\`. With a page: include \\`(p. N)\\` inline. Multiple sources: \\`\\\\ue200\\\\ue202turn0file0\\\\ue202turn0file1\\\\ue201\\`. NEVER substitute with footnotes, brackets, or symbols.`;\n}\n\nexport function createFileSearchTool(\n config: FileSearchToolConfig\n): DynamicStructuredTool {\n const {\n ragClient,\n files,\n entity_id,\n scope,\n getAuthHeaders,\n formatter = plainTextFormatter,\n queryTimeoutMs = DEFAULT_QUERY_TIMEOUT_MS,\n concurrencyLimit = DEFAULT_CONCURRENCY,\n topK = DEFAULT_TOP_K,\n resultCap,\n callbacks,\n logger,\n } = config;\n\n // Monotonic call counter used by citation-style formatters to keep source\n // indices unique across multiple invocations within a single turn.\n let callIndex = 0;\n\n // Infer whether the formatter wants citations from the artifact it emits\n // on an empty-chunk format. This keeps the description/behavior aligned\n // without forcing the host to declare `fileCitations` twice.\n const fileCitations = formatter !== plainTextFormatter;\n\n return tool(\n async (rawInput: FileSearchInput) => {\n const { query, target_files } = rawInput;\n\n if (files.length === 0) {\n return [\n 'No files to search. Instruct the user to add files for the search.',\n undefined,\n ];\n }\n\n // target_files: case-insensitive substring match, fallback to all\n // files with a warning if the filter excludes everything.\n let filesToQuery: FileSearchFile[] = files;\n if (target_files && target_files.length > 0) {\n const lowerTargets = target_files.map((t) => t.toLowerCase());\n const matched = files.filter((f) =>\n lowerTargets.some((t) => f.filename.toLowerCase().includes(t))\n );\n if (matched.length === 0) {\n logger?.warn(\n `[file_search] No files matched target_files ${target_files.join(', ')}; falling back to all files`\n );\n filesToQuery = files;\n } else {\n logger?.info(\n `[file_search] Filtered to ${matched.length}/${files.length} via target_files`\n );\n filesToQuery = matched;\n }\n }\n\n const authHeaders = getAuthHeaders ? await getAuthHeaders() : undefined;\n\n const queryOne = async (file: FileSearchFile): Promise<RagChunk[]> => {\n const params: RagQueryParams = {\n file_id: file.file_id,\n query,\n k: topK,\n entity_id,\n scope,\n authHeaders,\n timeoutMs: queryTimeoutMs,\n };\n try {\n const chunks = await ragClient.query(params);\n callbacks?.onFileQueried?.(file, chunks.length);\n return chunks;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n logger?.error(\n `[file_search] Query failed for ${file.filename}: ${e.message}`\n );\n callbacks?.onFileError?.(file, e);\n return [];\n }\n };\n\n // Bounded-concurrency batching. Server-side rerankers handle their\n // own concurrency; this protects the HTTP connection pool when the\n // agent has many files.\n const allChunks: RagChunk[] = [];\n for (let i = 0; i < filesToQuery.length; i += concurrencyLimit) {\n const batch = filesToQuery.slice(i, i + concurrencyLimit);\n const batchResults = await Promise.all(batch.map(queryOne));\n for (const chunks of batchResults) allChunks.push(...chunks);\n }\n\n if (allChunks.length === 0) {\n return [\n 'No content found in the files. The files may not have been processed correctly or the query may need refinement.',\n undefined,\n ];\n }\n\n // Build annotated results: attach filename + isCurrentMessage via\n // a file-id lookup (metadata wins, factory list is fallback).\n const fileById = new Map(files.map((f) => [f.file_id, f]));\n const annotated = allChunks.map((c) => {\n const matched = fileById.get(c.file_id);\n const filename =\n (c.metadata?.source\n ? String(c.metadata.source).split(/[/\\\\]/).pop()\n : undefined) ??\n matched?.filename ??\n 'Unknown';\n return {\n ...c,\n filename,\n isCurrentMessage: matched?.isCurrentMessage === true,\n };\n });\n\n // Sort: current-turn files first, then by relevance (lower distance).\n annotated.sort((a, b) => {\n if (a.isCurrentMessage !== b.isCurrentMessage)\n return a.isCurrentMessage ? -1 : 1;\n return a.distance - b.distance;\n });\n\n const cap = resultCap ?? Math.max(10, filesToQuery.length * 3);\n const limited = annotated.slice(0, cap);\n\n const { message, artifact } = formatter.format(limited, {\n callIndex,\n files,\n });\n callIndex += 1;\n\n // Suppress unused-variable warning for fileCitations (currently only\n // used to gate description; kept in case formatters need it).\n void fileCitations;\n\n return [message, artifact];\n },\n {\n name: FileSearchToolName,\n responseFormat: 'content_and_artifact',\n description: buildDescription({ fileCitations }),\n schema: fileSearchInputSchema,\n }\n );\n}\n\nexport { FileSearchToolName } from './schema';\n"],"names":["FileSearchToolName","formatter","plainTextFormatter","tool","fileSearchInputSchema"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;AAaG;AAgBH,MAAM,wBAAwB,GAAG,MAAM;AACvC,MAAM,mBAAmB,GAAG,EAAE;AAC9B,MAAM,aAAa,GAAG,EAAE;AAExB;;;;AAIG;AACH,SAAS,gBAAgB,CAAC,IAAgC,EAAA;IACxD,MAAM,IAAI,GAAG,CAAA,8CAAA,EAAiDA,yBAAkB,CAAA;;;;;;yNAMuI;IAEvN,IAAI,CAAC,IAAI,CAAC,aAAa;AAAE,QAAA,OAAO,IAAI;AAEpC,IAAA,OAAO,GAAG,IAAI;;;gdAGgc;AAChd;AAEM,SAAU,oBAAoB,CAClC,MAA4B,EAAA;AAE5B,IAAA,MAAM,EACJ,SAAS,EACT,KAAK,EACL,SAAS,EACT,KAAK,EACL,cAAc,aACdC,WAAS,GAAGC,4BAAkB,EAC9B,cAAc,GAAG,wBAAwB,EACzC,gBAAgB,GAAG,mBAAmB,EACtC,IAAI,GAAG,aAAa,EACpB,SAAS,EACT,SAAS,EACT,MAAM,GACP,GAAG,MAAM;;;IAIV,IAAI,SAAS,GAAG,CAAC;;;;AAKjB,IAAA,MAAM,aAAa,GAAGD,WAAS,KAAKC,4BAAkB;AAEtD,IAAA,OAAOC,UAAI,CACT,OAAO,QAAyB,KAAI;AAClC,QAAA,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,QAAQ;AAExC,QAAA,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO;gBACL,oEAAoE;gBACpE,SAAS;aACV;QACH;;;QAIA,IAAI,YAAY,GAAqB,KAAK;QAC1C,IAAI,YAAY,IAAI,YAAY,CAAC,MAAM,GAAG,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ileSearch/tool.mjs';
30
30
  export { HttpRagClient, RAG_API_URL_ENV, getRagBaseUrl } from './tools/fileSearch/ragClient.mjs';
31
31
  export { createCitationAnchorFormatter, plainTextFormatter } from './tools/fileSearch/formatter.mjs';
32
32
  export { FileSearchToolName, fileSearchInputSchema } from './tools/fileSearch/schema.mjs';
33
+ export { createArtifactTool, createContentReaderTool } from './tools/artifacts/tool.mjs';
34
+ export { ARTIFACT_TOOL_NAME, ARTIFACT_WRITE_ACTIONS, CONTENT_READER_NAME, CONTENT_READ_ACTIONS, artifactToolSchema, contentReaderSchema } from './tools/artifacts/schema.mjs';
33
35
  export { buildProxyTool } from './tools/proxyTool.mjs';
34
36
  export { AuthSource, CapabilityKind } from './providers/types.mjs';
35
37
  export { CAPABILITY_NAME_SEPARATOR, formatCapabilityName, parseCapabilityName } from './providers/capabilityNaming.mjs';
@@ -1 +1 @@
1
- {"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -111,6 +111,10 @@ function normalizeEntry(entry) {
111
111
  icon: entry.icon,
112
112
  category: entry.category,
113
113
  tags: entry.tags,
114
+ // Governance — hosts use these to gate UI/role/environment.
115
+ hidden: entry.hidden,
116
+ admin: entry.admin,
117
+ env: entry.env,
114
118
  },
115
119
  };
116
120
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ToolsServerCapabilityProvider.mjs","sources":["../../../../src/providers/tools-server/ToolsServerCapabilityProvider.ts"],"sourcesContent":["/**\n * ToolsServerCapabilityProvider — capabilities sourced from a tools-server\n * HTTP endpoint.\n *\n * Fetches the manifest via GET /manifest, builds proxy StructuredTools via\n * POST /execute/:tool. Manifest is cached (TTL-configurable) so repeated\n * init cycles don't refetch.\n *\n * See docs/architecture-capability-layer.md for the design rationale.\n */\n\nimport type { AxiosInstance } from 'axios';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport {\n CapabilityKind,\n type Capability,\n type CapabilityFilter,\n type CapabilityProvider,\n type CredentialMap,\n} from '@/providers/types';\nimport {\n createHttpClient,\n type HttpClientConfig,\n assertOk,\n} from '@/utils/httpClient';\nimport {\n ManifestCache,\n filterToCacheKey,\n applyFilter,\n} from '@/utils/toolManifest';\nimport { buildProxyTool } from '@/tools/proxyTool';\n\n/** Configuration for ToolsServerCapabilityProvider. */\nexport interface ToolsServerConfig {\n /** Tools-server base URL (e.g., https://tools.illuma.ai or http://localhost:3500). */\n baseUrl: string;\n /** API key sent as x-api-key header on all requests. Required. */\n apiKey: string;\n /** Optional override for manifest path. Defaults to `/manifest`. */\n manifestPath?: string;\n /** Optional override for execute path template. Defaults to `/execute/:name`. */\n executePath?: string;\n /** Request timeout in ms. Defaults to 30_000. */\n timeoutMs?: number;\n /** Manifest cache TTL in ms. 0 disables. Defaults to 60_000 (1 min). */\n manifestTtlMs?: number;\n /** Optional pre-built axios instance (for testing). */\n client?: AxiosInstance;\n /** Optional proxy override (defaults to process.env.PROXY). */\n proxy?: string | null;\n}\n\n/**\n * Shape of a single entry from tools-server's /manifest response.\n *\n * Matches the tools-server ManifestToolEntry type. We define our own here\n * to avoid cross-package coupling — the shape is a stable HTTP contract.\n */\ninterface ToolsServerManifestEntry {\n pluginKey: string;\n name: string;\n description: string;\n icon?: string;\n authConfig?: Array<{\n authField: string;\n label?: string;\n description?: string;\n source?: string;\n required?: boolean;\n prod?: boolean;\n admin?: boolean;\n hide?: boolean;\n }>;\n /** Input schema as JSON Schema (tools-server emits `schema`). */\n schema?: unknown;\n /** Legacy alias accepted for backwards compatibility. */\n jsonSchema?: unknown;\n category?: string;\n tags?: string[];\n toolkit?: string;\n endpoint?: string;\n}\n\nexport class ToolsServerCapabilityProvider implements CapabilityProvider {\n readonly providerId: string;\n private readonly client: AxiosInstance;\n private readonly manifestPath: string;\n private readonly executePath: string;\n private readonly cache: ManifestCache;\n\n constructor(private readonly config: ToolsServerConfig) {\n const {\n baseUrl,\n apiKey,\n manifestPath = '/manifest',\n executePath = '/execute/:name',\n timeoutMs = 30_000,\n manifestTtlMs = 60_000,\n client,\n proxy,\n } = config;\n\n if (!baseUrl) {\n throw new Error('ToolsServerCapabilityProvider: baseUrl is required');\n }\n if (!apiKey) {\n throw new Error('ToolsServerCapabilityProvider: apiKey is required');\n }\n\n this.providerId = `tools-server:${baseUrl}`;\n this.manifestPath = manifestPath;\n this.executePath = executePath;\n this.cache = new ManifestCache({ ttlMs: manifestTtlMs });\n\n if (client) {\n this.client = client;\n } else {\n const httpConfig: HttpClientConfig = {\n baseURL: baseUrl,\n apiKey,\n timeoutMs,\n proxy,\n };\n this.client = createHttpClient(httpConfig);\n }\n }\n\n async fetchManifest(filter?: CapabilityFilter): Promise<Capability[]> {\n const cacheKey = filterToCacheKey(filter);\n const cached = this.cache.get(cacheKey);\n if (cached) {\n // DEBUG: cache hit (remove after stabilization)\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] manifest cache hit — ${cached.length} caps`\n );\n return cached;\n }\n\n // DEBUG\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] fetching manifest from ${this.manifestPath}`\n );\n\n const res = await this.client.get<ToolsServerManifestEntry[]>(\n this.manifestPath\n );\n assertOk(res.status, this.manifestPath, res.data);\n\n const entries = Array.isArray(res.data) ? res.data : [];\n const capabilities: Capability[] = entries.map((entry) =>\n normalizeEntry(entry)\n );\n\n // Apply filter before caching the full list separately so unfiltered\n // refetches don't re-hit the network.\n const fullCacheKey = filterToCacheKey();\n this.cache.set(fullCacheKey, capabilities);\n\n const filtered = applyFilter(capabilities, filter);\n if (cacheKey !== fullCacheKey) {\n this.cache.set(cacheKey, filtered);\n }\n\n // DEBUG\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] manifest loaded — ${capabilities.length} caps, ${filtered.length} after filter`\n );\n\n return filtered;\n }\n\n async createRunnables(\n capabilities: Capability[],\n credentials: CredentialMap\n ): Promise<StructuredToolInterface[]> {\n return capabilities.map((cap) =>\n buildProxyTool(cap, credentials, {\n client: this.client,\n executePath: this.executePath,\n })\n );\n }\n\n /** Force a manifest refresh on next fetchManifest call. */\n invalidateCache(): void {\n this.cache.clear();\n }\n}\n\n/**\n * Translate a raw tools-server manifest entry into a typed Capability.\n * Defensive — tools-server may add fields; we pull only what we need.\n */\nfunction normalizeEntry(entry: ToolsServerManifestEntry): Capability {\n return {\n kind: CapabilityKind.TOOL,\n name: entry.pluginKey,\n description: entry.description ?? '',\n schema: entry.schema ?? entry.jsonSchema,\n authConfig: (entry.authConfig ?? []).map((ac) => ({\n authField: ac.authField,\n label: ac.label,\n description: ac.description,\n required: ac.required,\n prod: ac.prod,\n admin: ac.admin,\n hide: ac.hide,\n // Source is a string in wire format; downstream consumers coerce to AuthSource.\n source: ac.source as Capability['authConfig'][number]['source'],\n })),\n metadata: {\n icon: entry.icon,\n category: entry.category,\n tags: entry.tags,\n },\n };\n}\n"],"names":[],"mappings":";;;;;AAAA;;;;;;;;;AASG;MA0EU,6BAA6B,CAAA;AAOX,IAAA,MAAA;AANpB,IAAA,UAAU;AACF,IAAA,MAAM;AACN,IAAA,YAAY;AACZ,IAAA,WAAW;AACX,IAAA,KAAK;AAEtB,IAAA,WAAA,CAA6B,MAAyB,EAAA;QAAzB,IAAA,CAAA,MAAM,GAAN,MAAM;QACjC,MAAM,EACJ,OAAO,EACP,MAAM,EACN,YAAY,GAAG,WAAW,EAC1B,WAAW,GAAG,gBAAgB,EAC9B,SAAS,GAAG,MAAM,EAClB,aAAa,GAAG,MAAM,EACtB,MAAM,EACN,KAAK,GACN,GAAG,MAAM;QAEV,IAAI,CAAC,OAAO,EAAE;AAC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IAAI,EAAE,KAAK,CAAC,SAAS;AACrB,QAAA,WAAW,EAAE,KAAK,CAAC,WAAW,IAAI,EAAE;AACpC,QAAA,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,UAAU;AACxC,QAAA,UAAU,EAAE,CAAC,KAAK,CAAC,UAAU,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC,EAAE,MAAM;YAChD,SAAS,EAAE,EAAE,CAAC,SAAS;YACvB,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,WAAW,EAAE,EAAE,CAAC,WAAW;YAC3B,QAAQ,EAAE,EAAE,CAAC,QAAQ;YACrB,IAAI,EAAE,EAAE,CAAC,IAAI;YACb,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,IAAI,EAAE,EAAE,CAAC,IAAI;;YAEb,MAAM,EAAE,EAAE,CAAC,MAAoD;AAChE,SAAA,CAAC,CAAC;AACH,QAAA,QAAQ,EAAE;YACR,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,IAAI,EAAE,KAAK,CAAC,IAAI;AACjB,SAAA;KACF;AACH;;;;"}
1
+ {"version":3,"file":"ToolsServerCapabilityProvider.mjs","sources":["../../../../src/providers/tools-server/ToolsServerCapabilityProvider.ts"],"sourcesContent":["/**\n * ToolsServerCapabilityProvider — capabilities sourced from a tools-server\n * HTTP endpoint.\n *\n * Fetches the manifest via GET /manifest, builds proxy StructuredTools via\n * POST /execute/:tool. Manifest is cached (TTL-configurable) so repeated\n * init cycles don't refetch.\n *\n * See docs/architecture-capability-layer.md for the design rationale.\n */\n\nimport type { AxiosInstance } from 'axios';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport {\n CapabilityKind,\n type Capability,\n type CapabilityFilter,\n type CapabilityProvider,\n type CredentialMap,\n} from '@/providers/types';\nimport {\n createHttpClient,\n type HttpClientConfig,\n assertOk,\n} from '@/utils/httpClient';\nimport {\n ManifestCache,\n filterToCacheKey,\n applyFilter,\n} from '@/utils/toolManifest';\nimport { buildProxyTool } from '@/tools/proxyTool';\n\n/** Configuration for ToolsServerCapabilityProvider. */\nexport interface ToolsServerConfig {\n /** Tools-server base URL (e.g., https://tools.illuma.ai or http://localhost:3500). */\n baseUrl: string;\n /** API key sent as x-api-key header on all requests. Required. */\n apiKey: string;\n /** Optional override for manifest path. Defaults to `/manifest`. */\n manifestPath?: string;\n /** Optional override for execute path template. Defaults to `/execute/:name`. */\n executePath?: string;\n /** Request timeout in ms. Defaults to 30_000. */\n timeoutMs?: number;\n /** Manifest cache TTL in ms. 0 disables. Defaults to 60_000 (1 min). */\n manifestTtlMs?: number;\n /** Optional pre-built axios instance (for testing). */\n client?: AxiosInstance;\n /** Optional proxy override (defaults to process.env.PROXY). */\n proxy?: string | null;\n}\n\n/**\n * Shape of a single entry from tools-server's /manifest response.\n *\n * Matches the tools-server ManifestToolEntry type. We define our own here\n * to avoid cross-package coupling — the shape is a stable HTTP contract.\n */\ninterface ToolsServerManifestEntry {\n pluginKey: string;\n name: string;\n description: string;\n icon?: string;\n authConfig?: Array<{\n authField: string;\n label?: string;\n description?: string;\n source?: string;\n required?: boolean;\n prod?: boolean;\n admin?: boolean;\n hide?: boolean;\n }>;\n /** Input schema as JSON Schema (tools-server emits `schema`). */\n schema?: unknown;\n /** Legacy alias accepted for backwards compatibility. */\n jsonSchema?: unknown;\n category?: string;\n tags?: string[];\n toolkit?: string;\n endpoint?: string;\n /** Governance flags forwarded by tools-server getManifest(). */\n hidden?: boolean;\n admin?: boolean;\n env?: Array<'development' | 'production' | 'test' | 'staging'>;\n}\n\nexport class ToolsServerCapabilityProvider implements CapabilityProvider {\n readonly providerId: string;\n private readonly client: AxiosInstance;\n private readonly manifestPath: string;\n private readonly executePath: string;\n private readonly cache: ManifestCache;\n\n constructor(private readonly config: ToolsServerConfig) {\n const {\n baseUrl,\n apiKey,\n manifestPath = '/manifest',\n executePath = '/execute/:name',\n timeoutMs = 30_000,\n manifestTtlMs = 60_000,\n client,\n proxy,\n } = config;\n\n if (!baseUrl) {\n throw new Error('ToolsServerCapabilityProvider: baseUrl is required');\n }\n if (!apiKey) {\n throw new Error('ToolsServerCapabilityProvider: apiKey is required');\n }\n\n this.providerId = `tools-server:${baseUrl}`;\n this.manifestPath = manifestPath;\n this.executePath = executePath;\n this.cache = new ManifestCache({ ttlMs: manifestTtlMs });\n\n if (client) {\n this.client = client;\n } else {\n const httpConfig: HttpClientConfig = {\n baseURL: baseUrl,\n apiKey,\n timeoutMs,\n proxy,\n };\n this.client = createHttpClient(httpConfig);\n }\n }\n\n async fetchManifest(filter?: CapabilityFilter): Promise<Capability[]> {\n const cacheKey = filterToCacheKey(filter);\n const cached = this.cache.get(cacheKey);\n if (cached) {\n // DEBUG: cache hit (remove after stabilization)\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] manifest cache hit — ${cached.length} caps`\n );\n return cached;\n }\n\n // DEBUG\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] fetching manifest from ${this.manifestPath}`\n );\n\n const res = await this.client.get<ToolsServerManifestEntry[]>(\n this.manifestPath\n );\n assertOk(res.status, this.manifestPath, res.data);\n\n const entries = Array.isArray(res.data) ? res.data : [];\n const capabilities: Capability[] = entries.map((entry) =>\n normalizeEntry(entry)\n );\n\n // Apply filter before caching the full list separately so unfiltered\n // refetches don't re-hit the network.\n const fullCacheKey = filterToCacheKey();\n this.cache.set(fullCacheKey, capabilities);\n\n const filtered = applyFilter(capabilities, filter);\n if (cacheKey !== fullCacheKey) {\n this.cache.set(cacheKey, filtered);\n }\n\n // DEBUG\n // eslint-disable-next-line no-console\n console.debug(\n `[${this.providerId}] manifest loaded — ${capabilities.length} caps, ${filtered.length} after filter`\n );\n\n return filtered;\n }\n\n async createRunnables(\n capabilities: Capability[],\n credentials: CredentialMap\n ): Promise<StructuredToolInterface[]> {\n return capabilities.map((cap) =>\n buildProxyTool(cap, credentials, {\n client: this.client,\n executePath: this.executePath,\n })\n );\n }\n\n /** Force a manifest refresh on next fetchManifest call. */\n invalidateCache(): void {\n this.cache.clear();\n }\n}\n\n/**\n * Translate a raw tools-server manifest entry into a typed Capability.\n * Defensive — tools-server may add fields; we pull only what we need.\n */\nfunction normalizeEntry(entry: ToolsServerManifestEntry): Capability {\n return {\n kind: CapabilityKind.TOOL,\n name: entry.pluginKey,\n description: entry.description ?? '',\n schema: entry.schema ?? entry.jsonSchema,\n authConfig: (entry.authConfig ?? []).map((ac) => ({\n authField: ac.authField,\n label: ac.label,\n description: ac.description,\n required: ac.required,\n prod: ac.prod,\n admin: ac.admin,\n hide: ac.hide,\n // Source is a string in wire format; downstream consumers coerce to AuthSource.\n source: ac.source as Capability['authConfig'][number]['source'],\n })),\n metadata: {\n icon: entry.icon,\n category: entry.category,\n tags: entry.tags,\n // Governance — hosts use these to gate UI/role/environment.\n hidden: entry.hidden,\n admin: entry.admin,\n env: entry.env,\n },\n };\n}\n"],"names":[],"mappings":";;;;;AAAA;;;;;;;;;AASG;MA8EU,6BAA6B,CAAA;AAOX,IAAA,MAAA;AANpB,IAAA,UAAU;AACF,IAAA,MAAM;AACN,IAAA,YAAY;AACZ,IAAA,WAAW;AACX,IAAA,KAAK;AAEtB,IAAA,WAAA,CAA6B,MAAyB,EAAA;QAAzB,IAAA,CAAA,MAAM,GAAN,MAAM;QACjC,MAAM,EACJ,OAAO,EACP,MAAM,EACN,YAAY,GAAG,WAAW,EAC1B,WAAW,GAAG,gBAAgB,EAC9B,SAAS,GAAG,MAAM,EAClB,aAAa,GAAG,MAAM,EACtB,MAAM,EACN,KAAK,GACN,GAAG,MAAM;QAEV,IAAI,CAAC,OAAO,EAAE;AACZ,YAAA,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC;QACvE;QACA,IAAI,CAAC,MAAM,EAAE;AACX,YAAA,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC;QACtE;AAEA,QAAA,IAAI,CAAC,UAAU,GAAG,CAAA,aAAA,EAAgB,OAA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,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC,EAAE,MAAM;YAChD,SAAS,EAAE,EAAE,CAAC,SAAS;YACvB,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,WAAW,EAAE,EAAE,CAAC,WAAW;YAC3B,QAAQ,EAAE,EAAE,CAAC,QAAQ;YACrB,IAAI,EAAE,EAAE,CAAC,IAAI;YACb,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,IAAI,EAAE,EAAE,CAAC,IAAI;;YAEb,MAAM,EAAE,EAAE,CAAC,MAAoD;AAChE,SAAA,CAAC,CAAC;AACH,QAAA,QAAQ,EAAE;YACR,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,IAAI,EAAE,KAAK,CAAC,IAAI;;YAEhB,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,GAAG,EAAE,KAAK,CAAC,GAAG;AACf,SAAA;KACF;AACH;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sources":["../../../src/providers/types.ts"],"sourcesContent":["/**\n * CapabilityProvider types — the abstraction that lets agents consume tools,\n * skills, and MCP-backed capabilities through a single interface regardless\n * of where they come from.\n *\n * Design principles:\n * 1. Source-agnostic — providers are distinguished by WHERE they come from\n * (tools-server, skill store, MCP server), not by the backend service\n * any individual tool calls.\n * 2. Credential-agnostic — providers receive a flat credentialMap from the\n * host; they don't know about user settings, databases, OAuth flows.\n * 3. Extension-ready — the shape reserves slots for upcoming patterns\n * (skills injectedMessages, ToolCall.auth/expires_at, skill sessions)\n * so when those land we don't refactor the core.\n */\n\nimport type { StructuredToolInterface } from '@langchain/core/tools';\n\n/**\n * Kind of capability. Today only TOOL is implemented; SKILL and MCP are\n * reserved — SkillCapabilityProvider + MCPCapabilityProvider will populate\n * them in later phases. Keeping the enum from day one prevents a breaking\n * change when those ship.\n */\nexport enum CapabilityKind {\n TOOL = 'tool',\n SKILL = 'skill',\n MCP = 'mcp',\n /**\n * Remote agent reachable over the A2A (Agent-to-Agent) protocol.\n * The library's `A2ACapabilityProvider` is a client for this kind —\n * invoking an A2A capability sends a JSON-RPC `tasks/send` to the\n * remote agent's endpoint.\n */\n A2A = 'a2a',\n}\n\n/**\n * Where an auth credential comes from. Used by hosts to decide whether to\n * forward the credential per-request or let the capability provider resolve\n * it from its own environment.\n */\nexport enum AuthSource {\n /** Resolved by the capability provider itself from its environment. Host never sends. */\n SERVER = 'server',\n /** User-configured value stored in the host's credential store. Host forwards per-request. */\n USER = 'user',\n /** Active OAuth/session token. Host forwards per-request from active session. */\n FORWARDED = 'forwarded',\n}\n\n/**\n * One entry in a capability's auth config. Describes a single credential\n * the capability needs. The `source` field tells the host how to resolve\n * the value; the `prod`/`admin`/`hide` flags control UI visibility.\n */\nexport interface AuthConfigEntry {\n /** Environment-variable-style name (e.g., \"OPENAI_API_KEY\"). Stable identifier. */\n authField: string;\n /** Human-readable label for UI. */\n label?: string;\n /** Optional description of how to obtain the credential. */\n description?: string;\n /** Where the value comes from. Defaults to USER if unspecified. */\n source?: AuthSource;\n /** True if the credential is required for the capability to function. */\n required?: boolean;\n /** Platform-managed in production — never prompt user. */\n prod?: boolean;\n /** Only admins can configure. */\n admin?: boolean;\n /** Never show in any UI (used when source === SERVER). */\n hide?: boolean;\n}\n\n/**\n * Arbitrary metadata attached to a capability. Extension point.\n *\n * Fields prefixed with \"Reserved for\" are not populated today but exist in\n * the type so upstream patterns (skills, auth expiration, sessions) can\n * drop in without a schema migration.\n */\nexport interface CapabilityMetadata {\n /** Icon URL or path relative to the provider's static asset root. */\n icon?: string;\n /** Category for UI grouping (e.g., \"search\", \"image\", \"finance\"). */\n category?: string;\n /** Free-form tags for filtering / search. */\n tags?: string[];\n\n // --- Reserved for upstream patterns (not populated today) ---\n\n /** Reserved for upstream `fix/auth-events` — auth mode declared by tool. */\n auth?: string;\n /** Reserved for upstream `fix/auth-events` — Unix timestamp for token expiration. */\n expires_at?: number;\n /** Reserved for upstream skills — capability returns injected messages on execute. */\n injectedMessages?: boolean;\n /** Reserved for upstream skills — capability consumes ToolSessionMap state. */\n sessionAware?: boolean;\n}\n\n/**\n * A single capability — a tool, skill, or MCP-backed operation that an agent\n * can invoke. The shape mirrors common plugin-manifest conventions so the\n * same entry can round-trip between an upstream catalog and a host registry.\n */\nexport interface Capability {\n /** What kind of capability this is. Controls how it's invoked downstream. */\n kind: CapabilityKind;\n /**\n * Stable unique identifier. For tools this is the pluginKey\n * (e.g., \"dalle\", \"wikipedia\"). For skills this is the skill's `name`.\n * Used everywhere the capability is referenced.\n */\n name: string;\n /** Human-readable description for the LLM and UI. */\n description: string;\n /**\n * Input schema as JSON Schema. For tools this comes from the Zod schema\n * passed through `zodToJsonSchema`. Optional for capabilities with no\n * input (e.g., parameter-less skills).\n */\n schema?: unknown;\n /** Credential requirements. */\n authConfig: AuthConfigEntry[];\n /** Extension metadata. See CapabilityMetadata. */\n metadata: CapabilityMetadata;\n}\n\n/** Filter for fetchManifest. All fields optional; missing = no filter. */\nexport interface CapabilityFilter {\n kind?: CapabilityKind;\n tags?: string[];\n /** Restrict to capabilities whose `name` is in this list. */\n names?: string[];\n}\n\n/**\n * A flat credential map: authField → value.\n *\n * The host is responsible for resolving values (from env vars, user\n * settings, OAuth sessions, etc.) before passing to the provider. The\n * provider does not inspect the origin — it just forwards to the tool.\n */\nexport type CredentialMap = Record<string, string>;\n\n/**\n * The core interface. All concrete providers implement this.\n *\n * Providers are identified by `providerId` for logging/debug. They fetch\n * their own manifest and build LangChain-compatible runnables from it.\n *\n * Lifetime: a provider may be instantiated once at startup (e.g., tools-\n * server pointing at a stable URL) or per-user (e.g., MCP with per-user\n * OAuth). The interface is agnostic.\n */\nexport interface CapabilityProvider {\n /** Stable identifier for this provider instance (e.g., \"tools-server:https://...\"). */\n readonly providerId: string;\n\n /**\n * Return the list of capabilities this provider exposes.\n *\n * Implementations may cache the manifest — the contract is that the\n * returned list reflects the provider's current view of available\n * capabilities.\n *\n * @param filter optional filter to scope the result\n */\n fetchManifest(filter?: CapabilityFilter): Promise<Capability[]>;\n\n /**\n * Build LangChain StructuredTools from a set of capabilities using the\n * caller-supplied credentials.\n *\n * Called at agent init. The returned tools are bound to the LLM and\n * invoked during the graph's tool-calling loop.\n *\n * @param capabilities the subset of capabilities the agent wants to use\n * @param credentials credential values keyed by authField\n */\n createRunnables(\n capabilities: Capability[],\n credentials: CredentialMap\n ): Promise<StructuredToolInterface[]>;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;AAcG;AAIH;;;;;AAKG;IACS;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,cAAA,CAAA,OAAA,CAAA,GAAA,OAAe;AACf,IAAA,cAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX;;;;;AAKG;AACH,IAAA,cAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACb,CAAC,EAXW,cAAc,KAAd,cAAc,GAAA,EAAA,CAAA,CAAA;AAa1B;;;;AAIG;IACS;AAAZ,CAAA,UAAY,UAAU,EAAA;;AAEpB,IAAA,UAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;;AAEjB,IAAA,UAAA,CAAA,MAAA,CAAA,GAAA,MAAa;;AAEb,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACzB,CAAC,EAPW,UAAU,KAAV,UAAU,GAAA,EAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"types.mjs","sources":["../../../src/providers/types.ts"],"sourcesContent":["/**\n * CapabilityProvider types — the abstraction that lets agents consume tools,\n * skills, and MCP-backed capabilities through a single interface regardless\n * of where they come from.\n *\n * Design principles:\n * 1. Source-agnostic — providers are distinguished by WHERE they come from\n * (tools-server, skill store, MCP server), not by the backend service\n * any individual tool calls.\n * 2. Credential-agnostic — providers receive a flat credentialMap from the\n * host; they don't know about user settings, databases, OAuth flows.\n * 3. Extension-ready — the shape reserves slots for upcoming patterns\n * (skills injectedMessages, ToolCall.auth/expires_at, skill sessions)\n * so when those land we don't refactor the core.\n */\n\nimport type { StructuredToolInterface } from '@langchain/core/tools';\n\n/**\n * Kind of capability. Today only TOOL is implemented; SKILL and MCP are\n * reserved — SkillCapabilityProvider + MCPCapabilityProvider will populate\n * them in later phases. Keeping the enum from day one prevents a breaking\n * change when those ship.\n */\nexport enum CapabilityKind {\n TOOL = 'tool',\n SKILL = 'skill',\n MCP = 'mcp',\n /**\n * Remote agent reachable over the A2A (Agent-to-Agent) protocol.\n * The library's `A2ACapabilityProvider` is a client for this kind —\n * invoking an A2A capability sends a JSON-RPC `tasks/send` to the\n * remote agent's endpoint.\n */\n A2A = 'a2a',\n}\n\n/**\n * Where an auth credential comes from. Used by hosts to decide whether to\n * forward the credential per-request or let the capability provider resolve\n * it from its own environment.\n */\nexport enum AuthSource {\n /** Resolved by the capability provider itself from its environment. Host never sends. */\n SERVER = 'server',\n /** User-configured value stored in the host's credential store. Host forwards per-request. */\n USER = 'user',\n /** Active OAuth/session token. Host forwards per-request from active session. */\n FORWARDED = 'forwarded',\n}\n\n/**\n * One entry in a capability's auth config. Describes a single credential\n * the capability needs. The `source` field tells the host how to resolve\n * the value; the `prod`/`admin`/`hide` flags control UI visibility.\n */\nexport interface AuthConfigEntry {\n /** Environment-variable-style name (e.g., \"OPENAI_API_KEY\"). Stable identifier. */\n authField: string;\n /** Human-readable label for UI. */\n label?: string;\n /** Optional description of how to obtain the credential. */\n description?: string;\n /** Where the value comes from. Defaults to USER if unspecified. */\n source?: AuthSource;\n /** True if the credential is required for the capability to function. */\n required?: boolean;\n /** Platform-managed in production — never prompt user. */\n prod?: boolean;\n /** Only admins can configure. */\n admin?: boolean;\n /** Never show in any UI (used when source === SERVER). */\n hide?: boolean;\n}\n\n/**\n * Arbitrary metadata attached to a capability. Extension point.\n *\n * Fields prefixed with \"Reserved for\" are not populated today but exist in\n * the type so upstream patterns (skills, auth expiration, sessions) can\n * drop in without a schema migration.\n */\nexport interface CapabilityMetadata {\n /** Icon URL or path relative to the provider's static asset root. */\n icon?: string;\n /** Category for UI grouping (e.g., \"search\", \"image\", \"finance\"). */\n category?: string;\n /** Free-form tags for filtering / search. */\n tags?: string[];\n\n // --- Governance flags ------------------------------------------------\n\n /**\n * When true, hosts omit this capability from user-facing pickers\n * (Agent Builder, tool dropdown). Still invokable when a saved agent\n * references it by name.\n */\n hidden?: boolean;\n /** When true, only admin-role users can enable or invoke this capability. */\n admin?: boolean;\n /**\n * Deployment-stage restriction. When set, hosts whose deployment stage\n * isn't in the array should hide the capability (e.g., a prod host\n * shouldn't surface a tool with `env: ['development']`).\n */\n env?: Array<'development' | 'production' | 'test' | 'staging'>;\n\n // --- Reserved for upstream patterns (not populated today) ---\n\n /** Reserved for upstream `fix/auth-events` — auth mode declared by tool. */\n auth?: string;\n /** Reserved for upstream `fix/auth-events` — Unix timestamp for token expiration. */\n expires_at?: number;\n /** Reserved for upstream skills — capability returns injected messages on execute. */\n injectedMessages?: boolean;\n /** Reserved for upstream skills — capability consumes ToolSessionMap state. */\n sessionAware?: boolean;\n}\n\n/**\n * A single capability — a tool, skill, or MCP-backed operation that an agent\n * can invoke. The shape mirrors common plugin-manifest conventions so the\n * same entry can round-trip between an upstream catalog and a host registry.\n */\nexport interface Capability {\n /** What kind of capability this is. Controls how it's invoked downstream. */\n kind: CapabilityKind;\n /**\n * Stable unique identifier. For tools this is the pluginKey\n * (e.g., \"dalle\", \"wikipedia\"). For skills this is the skill's `name`.\n * Used everywhere the capability is referenced.\n */\n name: string;\n /** Human-readable description for the LLM and UI. */\n description: string;\n /**\n * Input schema as JSON Schema. For tools this comes from the Zod schema\n * passed through `zodToJsonSchema`. Optional for capabilities with no\n * input (e.g., parameter-less skills).\n */\n schema?: unknown;\n /** Credential requirements. */\n authConfig: AuthConfigEntry[];\n /** Extension metadata. See CapabilityMetadata. */\n metadata: CapabilityMetadata;\n}\n\n/** Filter for fetchManifest. All fields optional; missing = no filter. */\nexport interface CapabilityFilter {\n kind?: CapabilityKind;\n tags?: string[];\n /** Restrict to capabilities whose `name` is in this list. */\n names?: string[];\n}\n\n/**\n * A flat credential map: authField → value.\n *\n * The host is responsible for resolving values (from env vars, user\n * settings, OAuth sessions, etc.) before passing to the provider. The\n * provider does not inspect the origin — it just forwards to the tool.\n */\nexport type CredentialMap = Record<string, string>;\n\n/**\n * The core interface. All concrete providers implement this.\n *\n * Providers are identified by `providerId` for logging/debug. They fetch\n * their own manifest and build LangChain-compatible runnables from it.\n *\n * Lifetime: a provider may be instantiated once at startup (e.g., tools-\n * server pointing at a stable URL) or per-user (e.g., MCP with per-user\n * OAuth). The interface is agnostic.\n */\nexport interface CapabilityProvider {\n /** Stable identifier for this provider instance (e.g., \"tools-server:https://...\"). */\n readonly providerId: string;\n\n /**\n * Return the list of capabilities this provider exposes.\n *\n * Implementations may cache the manifest — the contract is that the\n * returned list reflects the provider's current view of available\n * capabilities.\n *\n * @param filter optional filter to scope the result\n */\n fetchManifest(filter?: CapabilityFilter): Promise<Capability[]>;\n\n /**\n * Build LangChain StructuredTools from a set of capabilities using the\n * caller-supplied credentials.\n *\n * Called at agent init. The returned tools are bound to the LLM and\n * invoked during the graph's tool-calling loop.\n *\n * @param capabilities the subset of capabilities the agent wants to use\n * @param credentials credential values keyed by authField\n */\n createRunnables(\n capabilities: Capability[],\n credentials: CredentialMap\n ): Promise<StructuredToolInterface[]>;\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;AAcG;AAIH;;;;;AAKG;IACS;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,cAAA,CAAA,OAAA,CAAA,GAAA,OAAe;AACf,IAAA,cAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX;;;;;AAKG;AACH,IAAA,cAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACb,CAAC,EAXW,cAAc,KAAd,cAAc,GAAA,EAAA,CAAA,CAAA;AAa1B;;;;AAIG;IACS;AAAZ,CAAA,UAAY,UAAU,EAAA;;AAEpB,IAAA,UAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;;AAEjB,IAAA,UAAA,CAAA,MAAA,CAAA,GAAA,MAAa;;AAEb,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACzB,CAAC,EAPW,UAAU,KAAV,UAAU,GAAA,EAAA,CAAA,CAAA;;;;"}
@@ -0,0 +1,79 @@
1
+ import { z } from 'zod';
2
+
3
+ const ARTIFACT_WRITE_ACTIONS = [
4
+ 'write',
5
+ 'edit',
6
+ 'verify',
7
+ 'delete',
8
+ ];
9
+ const CONTENT_READ_ACTIONS = ['read', 'search', 'list', 'info'];
10
+ const artifactToolSchema = z.object({
11
+ action: z
12
+ .enum(ARTIFACT_WRITE_ACTIONS)
13
+ .describe('Authoring action: write (create/overwrite), edit (str_replace), verify (syntax check), delete (remove).'),
14
+ content_id: z
15
+ .string()
16
+ .optional()
17
+ .describe('ID of the artifact entry. Required for edit/verify/delete; optional for write (supply to overwrite an existing entry).'),
18
+ // write
19
+ content: z
20
+ .string()
21
+ .optional()
22
+ .describe('Full file content (required for write action).'),
23
+ name: z
24
+ .string()
25
+ .optional()
26
+ .describe('Filename for the new entry (required when creating). MUST include the correct file extension — the extension drives the preview template.'),
27
+ // edit (str_replace)
28
+ old_str: z
29
+ .string()
30
+ .optional()
31
+ .describe('Exact string to find and replace (required for edit).'),
32
+ new_str: z
33
+ .string()
34
+ .optional()
35
+ .describe('Replacement string (required for edit).'),
36
+ replace_all: z
37
+ .boolean()
38
+ .optional()
39
+ .describe('edit: when true, replaces every occurrence of old_str. When false (default) and old_str matches more than one location, the edit is refused.'),
40
+ });
41
+ const contentReaderSchema = z.object({
42
+ action: z
43
+ .enum(CONTENT_READ_ACTIONS)
44
+ .describe('Read-only action: read (lines), search (regex), list (all entries), info (metadata).'),
45
+ content_id: z
46
+ .string()
47
+ .optional()
48
+ .describe('ID of the content entry. Required for read/search/info. Omit for list.'),
49
+ // read pagination
50
+ start_line: z.number().optional().describe('1-based start line for reading.'),
51
+ end_line: z.number().optional().describe('1-based end line (inclusive).'),
52
+ // search
53
+ pattern: z
54
+ .string()
55
+ .optional()
56
+ .describe('Regex pattern (required for search).'),
57
+ flags: z
58
+ .string()
59
+ .optional()
60
+ .describe('Regex flags (e.g., "i" for case-insensitive).'),
61
+ context: z
62
+ .number()
63
+ .optional()
64
+ .describe('Lines of context around each match.'),
65
+ // shared pagination
66
+ offset: z
67
+ .number()
68
+ .optional()
69
+ .describe('Offset for read or search pagination.'),
70
+ limit: z
71
+ .number()
72
+ .optional()
73
+ .describe('Max lines (read) or matches (search).'),
74
+ });
75
+ const ARTIFACT_TOOL_NAME = 'artifact_tool';
76
+ const CONTENT_READER_NAME = 'content_reader';
77
+
78
+ export { ARTIFACT_TOOL_NAME, ARTIFACT_WRITE_ACTIONS, CONTENT_READER_NAME, CONTENT_READ_ACTIONS, artifactToolSchema, contentReaderSchema };
79
+ //# sourceMappingURL=schema.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.mjs","sources":["../../../../src/tools/artifacts/schema.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const ARTIFACT_WRITE_ACTIONS = [\n 'write',\n 'edit',\n 'verify',\n 'delete',\n] as const;\nexport const CONTENT_READ_ACTIONS = ['read', 'search', 'list', 'info'] as const;\n\nexport const artifactToolSchema = z.object({\n action: z\n .enum(ARTIFACT_WRITE_ACTIONS)\n .describe(\n 'Authoring action: write (create/overwrite), edit (str_replace), verify (syntax check), delete (remove).'\n ),\n content_id: z\n .string()\n .optional()\n .describe(\n 'ID of the artifact entry. Required for edit/verify/delete; optional for write (supply to overwrite an existing entry).'\n ),\n\n // write\n content: z\n .string()\n .optional()\n .describe('Full file content (required for write action).'),\n name: z\n .string()\n .optional()\n .describe(\n 'Filename for the new entry (required when creating). MUST include the correct file extension — the extension drives the preview template.'\n ),\n\n // edit (str_replace)\n old_str: z\n .string()\n .optional()\n .describe('Exact string to find and replace (required for edit).'),\n new_str: z\n .string()\n .optional()\n .describe('Replacement string (required for edit).'),\n replace_all: z\n .boolean()\n .optional()\n .describe(\n 'edit: when true, replaces every occurrence of old_str. When false (default) and old_str matches more than one location, the edit is refused.'\n ),\n});\n\nexport const contentReaderSchema = z.object({\n action: z\n .enum(CONTENT_READ_ACTIONS)\n .describe(\n 'Read-only action: read (lines), search (regex), list (all entries), info (metadata).'\n ),\n content_id: z\n .string()\n .optional()\n .describe(\n 'ID of the content entry. Required for read/search/info. Omit for list.'\n ),\n\n // read pagination\n start_line: z.number().optional().describe('1-based start line for reading.'),\n end_line: z.number().optional().describe('1-based end line (inclusive).'),\n\n // search\n pattern: z\n .string()\n .optional()\n .describe('Regex pattern (required for search).'),\n flags: z\n .string()\n .optional()\n .describe('Regex flags (e.g., \"i\" for case-insensitive).'),\n context: z\n .number()\n .optional()\n .describe('Lines of context around each match.'),\n\n // shared pagination\n offset: z\n .number()\n .optional()\n .describe('Offset for read or search pagination.'),\n limit: z\n .number()\n .optional()\n .describe('Max lines (read) or matches (search).'),\n});\n\nexport const ARTIFACT_TOOL_NAME = 'artifact_tool';\nexport const CONTENT_READER_NAME = 'content_reader';\n\nexport type ArtifactToolInput = z.infer<typeof artifactToolSchema>;\nexport type ContentReaderInput = z.infer<typeof contentReaderSchema>;\n"],"names":[],"mappings":";;AAEO,MAAM,sBAAsB,GAAG;IACpC,OAAO;IACP,MAAM;IACN,QAAQ;IACR,QAAQ;;AAEH,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM;AAE9D,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;AACzC,IAAA,MAAM,EAAE;SACL,IAAI,CAAC,sBAAsB;SAC3B,QAAQ,CACP,yGAAyG,CAC1G;AACH,IAAA,UAAU,EAAE;AACT,SAAA,MAAM;AACN,SAAA,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,MAAM,EAAE;AACL,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,uCAAuC,CAAC;AACpD,IAAA,KAAK,EAAE;AACJ,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,uCAAuC,CAAC;AACrD,CAAA;AAEM,MAAM,kBAAkB,GAAG;AAC3B,MAAM,mBAAmB,GAAG;;;;"}
@@ -0,0 +1,213 @@
1
+ import { tool } from '@langchain/core/tools';
2
+ import { artifactToolSchema, ARTIFACT_TOOL_NAME, contentReaderSchema, CONTENT_READER_NAME } from './schema.mjs';
3
+ export { ARTIFACT_WRITE_ACTIONS, CONTENT_READ_ACTIONS } from './schema.mjs';
4
+
5
+ /**
6
+ * artifact_tool + content_reader library factories.
7
+ *
8
+ * The library owns the LangChain wiring (schema, description, response
9
+ * shape) and the action dispatch; the runtime supplies a handler bundle
10
+ * matching the `ArtifactWriteHandlers` / `ContentReadHandlers` interface.
11
+ *
12
+ * This keeps 800+ LOC of host-specific handler logic (S3 adapters, file
13
+ * model CRUD, syntax checkers, line utils) out of the library while
14
+ * still centralizing the tool surface every runtime shares.
15
+ */
16
+ const DEFAULT_ARTIFACT_DESCRIPTION = `Author content artifacts that render live in the host's preview panel — this tool does NOT produce downloadable files (use execute_code for those).
17
+
18
+ Actions:
19
+ - write: Create a new artifact. Write a COMPLETE file in one call. The \`name\` field MUST include the file extension — it routes the preview (.tsx, .html, .mmd, .svg, .csv, .json, .dot, .md, .drawio).
20
+ - verify: Check an artifact for syntax errors. REQUIRED as the next step after every write/edit on code files — do not render until verify passes.
21
+ - edit: Surgical string replacement — provide old_str (exact match) and new_str. Works on all file types.
22
+ - delete: Remove an artifact and its backing file.
23
+
24
+ Artifacts are persisted by the host. No manual save needed.`;
25
+ const DEFAULT_CONTENT_READER_DESCRIPTION = `Read and navigate stored content — artifacts authored by artifact_tool, large tool results auto-cached by the host, uploaded file attachments, and code blocks.
26
+
27
+ Read-only surface. Use write/edit tools (artifact_tool, execute_code) to mutate.
28
+
29
+ Actions:
30
+ - read: Return line ranges from a specific content_id.
31
+ - search: Regex search across a specific content_id with paginated matches.
32
+ - list: Enumerate every content entry currently stored.
33
+ - info: Metadata (size, kind, creation time) for a specific content_id.`;
34
+ /**
35
+ * Optional content_id self-healing — if the runtime supplies a resolver,
36
+ * we pre-resolve the ID on every action that takes one so nicknames
37
+ * (e.g., "Dashboard") map to canonical IDs.
38
+ */
39
+ async function resolveContentIdIfPresent(resolver, id, scope, logger) {
40
+ if (!resolver || !id)
41
+ return id;
42
+ const out = await resolver.resolve(id, scope);
43
+ if (!out)
44
+ return id;
45
+ if (out.resolvedId !== id) {
46
+ logger?.debug(`[artifact] resolved "${id}" → "${out.resolvedId}"${out.resolvedName ? ` ("${out.resolvedName}")` : ''}`);
47
+ }
48
+ return out.resolvedId;
49
+ }
50
+ // ─── Writer tool (artifact_tool) ─────────────────────────────────────────
51
+ function createArtifactTool(config) {
52
+ const { handlers, getScope, resolver, logger, descriptionOverride } = config;
53
+ return tool(async (rawInput, runnableConfig) => {
54
+ const scope = getScope(runnableConfig);
55
+ if (!scope) {
56
+ logger?.warn('[artifact_tool] no scope resolved from runnableConfig');
57
+ return ['Error: No conversation context available', {}];
58
+ }
59
+ const input = rawInput;
60
+ const resolvedContentId = await resolveContentIdIfPresent(resolver, input.content_id, scope, logger);
61
+ const started = Date.now();
62
+ try {
63
+ switch (input.action) {
64
+ case 'write': {
65
+ const args = {
66
+ action: 'write',
67
+ content_id: resolvedContentId,
68
+ content: input.content ?? '',
69
+ name: input.name,
70
+ };
71
+ if (!args.content)
72
+ return ['Error: write requires content', {}];
73
+ return await handlers.write(args, scope);
74
+ }
75
+ case 'edit': {
76
+ if (!resolvedContentId)
77
+ return ['Error: edit requires content_id', {}];
78
+ const args = {
79
+ action: 'edit',
80
+ content_id: resolvedContentId,
81
+ old_str: input.old_str ?? '',
82
+ new_str: input.new_str ?? '',
83
+ replace_all: input.replace_all,
84
+ };
85
+ if (!args.old_str)
86
+ return ['Error: edit requires old_str', {}];
87
+ return await handlers.edit(args, scope);
88
+ }
89
+ case 'verify': {
90
+ if (!resolvedContentId)
91
+ return ['Error: verify requires content_id', {}];
92
+ const args = {
93
+ action: 'verify',
94
+ content_id: resolvedContentId,
95
+ };
96
+ return await handlers.verify(args, scope);
97
+ }
98
+ case 'delete': {
99
+ if (!resolvedContentId)
100
+ return ['Error: delete requires content_id', {}];
101
+ const args = {
102
+ action: 'delete',
103
+ content_id: resolvedContentId,
104
+ };
105
+ return await handlers.delete(args, scope);
106
+ }
107
+ default:
108
+ return [
109
+ `Unknown action: ${input.action}`,
110
+ {},
111
+ ];
112
+ }
113
+ }
114
+ catch (err) {
115
+ const e = err instanceof Error ? err : new Error(String(err));
116
+ logger?.error('[artifact_tool] handler threw', {
117
+ action: input.action,
118
+ contentId: resolvedContentId,
119
+ error: e.message,
120
+ elapsed: `${Date.now() - started}ms`,
121
+ });
122
+ return [`Error: ${e.message}`, {}];
123
+ }
124
+ }, {
125
+ name: ARTIFACT_TOOL_NAME,
126
+ responseFormat: 'content_and_artifact',
127
+ description: descriptionOverride ?? DEFAULT_ARTIFACT_DESCRIPTION,
128
+ schema: artifactToolSchema,
129
+ });
130
+ }
131
+ // ─── Reader tool (content_reader) ────────────────────────────────────────
132
+ function createContentReaderTool(config) {
133
+ const { handlers, getScope, resolver, logger, descriptionOverride } = config;
134
+ return tool(async (rawInput, runnableConfig) => {
135
+ const scope = getScope(runnableConfig);
136
+ if (!scope) {
137
+ logger?.warn('[content_reader] no scope resolved from runnableConfig');
138
+ return ['Error: No conversation context available', {}];
139
+ }
140
+ const input = rawInput;
141
+ const resolvedContentId = await resolveContentIdIfPresent(resolver, input.content_id, scope, logger);
142
+ const started = Date.now();
143
+ try {
144
+ switch (input.action) {
145
+ case 'read': {
146
+ if (!resolvedContentId)
147
+ return ['Error: read requires content_id', {}];
148
+ const args = {
149
+ action: 'read',
150
+ content_id: resolvedContentId,
151
+ start_line: input.start_line,
152
+ end_line: input.end_line,
153
+ offset: input.offset,
154
+ limit: input.limit,
155
+ };
156
+ return await handlers.read(args, scope);
157
+ }
158
+ case 'search': {
159
+ if (!resolvedContentId)
160
+ return ['Error: search requires content_id', {}];
161
+ if (!input.pattern)
162
+ return ['Error: search requires pattern', {}];
163
+ const args = {
164
+ action: 'search',
165
+ content_id: resolvedContentId,
166
+ pattern: input.pattern,
167
+ flags: input.flags,
168
+ context: input.context,
169
+ offset: input.offset,
170
+ limit: input.limit,
171
+ };
172
+ return await handlers.search(args, scope);
173
+ }
174
+ case 'list': {
175
+ const args = { action: 'list' };
176
+ return await handlers.list(args, scope);
177
+ }
178
+ case 'info': {
179
+ if (!resolvedContentId)
180
+ return ['Error: info requires content_id', {}];
181
+ const args = {
182
+ action: 'info',
183
+ content_id: resolvedContentId,
184
+ };
185
+ return await handlers.info(args, scope);
186
+ }
187
+ default:
188
+ return [
189
+ `Unknown action: ${input.action}`,
190
+ {},
191
+ ];
192
+ }
193
+ }
194
+ catch (err) {
195
+ const e = err instanceof Error ? err : new Error(String(err));
196
+ logger?.error('[content_reader] handler threw', {
197
+ action: input.action,
198
+ contentId: resolvedContentId,
199
+ error: e.message,
200
+ elapsed: `${Date.now() - started}ms`,
201
+ });
202
+ return [`Error: ${e.message}`, {}];
203
+ }
204
+ }, {
205
+ name: CONTENT_READER_NAME,
206
+ responseFormat: 'content_and_artifact',
207
+ description: descriptionOverride ?? DEFAULT_CONTENT_READER_DESCRIPTION,
208
+ schema: contentReaderSchema,
209
+ });
210
+ }
211
+
212
+ export { ARTIFACT_TOOL_NAME, CONTENT_READER_NAME, createArtifactTool, createContentReaderTool };
213
+ //# sourceMappingURL=tool.mjs.map