@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.
- package/dist/cjs/main.cjs +37 -27
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs +4 -0
- package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs.map +1 -1
- package/dist/cjs/providers/types.cjs.map +1 -1
- package/dist/cjs/tools/artifacts/schema.cjs +86 -0
- package/dist/cjs/tools/artifacts/schema.cjs.map +1 -0
- package/dist/cjs/tools/artifacts/tool.cjs +219 -0
- package/dist/cjs/tools/artifacts/tool.cjs.map +1 -0
- package/dist/cjs/tools/fileSearch/formatter.cjs +2 -4
- package/dist/cjs/tools/fileSearch/formatter.cjs.map +1 -1
- package/dist/cjs/tools/fileSearch/ragClient.cjs +4 -6
- package/dist/cjs/tools/fileSearch/ragClient.cjs.map +1 -1
- package/dist/cjs/tools/fileSearch/schema.cjs.map +1 -1
- package/dist/cjs/tools/fileSearch/tool.cjs.map +1 -1
- package/dist/esm/main.mjs +2 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs +4 -0
- package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs.map +1 -1
- package/dist/esm/providers/types.mjs.map +1 -1
- package/dist/esm/tools/artifacts/schema.mjs +79 -0
- package/dist/esm/tools/artifacts/schema.mjs.map +1 -0
- package/dist/esm/tools/artifacts/tool.mjs +213 -0
- package/dist/esm/tools/artifacts/tool.mjs.map +1 -0
- package/dist/esm/tools/fileSearch/formatter.mjs +2 -4
- package/dist/esm/tools/fileSearch/formatter.mjs.map +1 -1
- package/dist/esm/tools/fileSearch/ragClient.mjs +4 -6
- package/dist/esm/tools/fileSearch/ragClient.mjs.map +1 -1
- package/dist/esm/tools/fileSearch/schema.mjs.map +1 -1
- package/dist/esm/tools/fileSearch/tool.mjs.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/providers/types.d.ts +14 -0
- package/dist/types/tools/artifacts/index.d.ts +3 -0
- package/dist/types/tools/artifacts/schema.d.ts +63 -0
- package/dist/types/tools/artifacts/tool.d.ts +16 -0
- package/dist/types/tools/artifacts/types.d.ts +127 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/providers/tools-server/ToolsServerCapabilityProvider.ts +8 -0
- package/src/providers/types.ts +17 -0
- package/src/tools/artifacts/__tests__/tool.test.ts +259 -0
- package/src/tools/artifacts/index.ts +33 -0
- package/src/tools/artifacts/schema.ts +99 -0
- package/src/tools/artifacts/tool.ts +289 -0
- package/src/tools/artifacts/types.ts +162 -0
- package/src/tools/fileSearch/__tests__/tool.test.ts +20 -10
- package/src/tools/fileSearch/formatter.ts +5 -7
- package/src/tools/fileSearch/ragClient.ts +6 -10
- package/src/tools/fileSearch/schema.ts +2 -2
- package/src/tools/fileSearch/tool.ts +6 -6
- package/src/tools/fileSearch/types.ts +4 -2
package/dist/cjs/main.cjs
CHANGED
|
@@ -23,15 +23,17 @@ var ProgrammaticToolCalling = require('./tools/ProgrammaticToolCalling.cjs');
|
|
|
23
23
|
var ToolSearch = require('./tools/ToolSearch.cjs');
|
|
24
24
|
var ToolNode = require('./tools/ToolNode.cjs');
|
|
25
25
|
var AskUser = require('./tools/AskUser.cjs');
|
|
26
|
-
var schema$
|
|
26
|
+
var schema$3 = require('./tools/schema.cjs');
|
|
27
27
|
var handlers$1 = require('./tools/handlers.cjs');
|
|
28
|
-
var tool$
|
|
29
|
-
var schema = require('./tools/search/schema.cjs');
|
|
28
|
+
var tool$2 = require('./tools/search/tool.cjs');
|
|
29
|
+
var schema$1 = require('./tools/search/schema.cjs');
|
|
30
30
|
var index$2 = require('./tools/memory/index.cjs');
|
|
31
|
-
var tool = require('./tools/fileSearch/tool.cjs');
|
|
31
|
+
var tool$1 = require('./tools/fileSearch/tool.cjs');
|
|
32
32
|
var ragClient = require('./tools/fileSearch/ragClient.cjs');
|
|
33
33
|
var formatter = require('./tools/fileSearch/formatter.cjs');
|
|
34
|
-
var schema$
|
|
34
|
+
var schema$2 = require('./tools/fileSearch/schema.cjs');
|
|
35
|
+
var tool = require('./tools/artifacts/tool.cjs');
|
|
36
|
+
var schema = require('./tools/artifacts/schema.cjs');
|
|
35
37
|
var proxyTool = require('./tools/proxyTool.cjs');
|
|
36
38
|
var types = require('./providers/types.cjs');
|
|
37
39
|
var capabilityNaming = require('./providers/capabilityNaming.cjs');
|
|
@@ -70,7 +72,7 @@ var run$1 = require('./utils/run.cjs');
|
|
|
70
72
|
var tokens = require('./utils/tokens.cjs');
|
|
71
73
|
var toonFormat = require('./utils/toonFormat.cjs');
|
|
72
74
|
var contextAnalytics = require('./utils/contextAnalytics.cjs');
|
|
73
|
-
var schema$
|
|
75
|
+
var schema$4 = require('./utils/schema.cjs');
|
|
74
76
|
var toolCallContinuation = require('./utils/toolCallContinuation.cjs');
|
|
75
77
|
var contextPressure = require('./utils/contextPressure.cjs');
|
|
76
78
|
var toolDiscoveryCache = require('./utils/toolDiscoveryCache.cjs');
|
|
@@ -199,38 +201,46 @@ exports.AskUserStepSchema = AskUser.AskUserStepSchema;
|
|
|
199
201
|
exports.AskUserToolName = AskUser.AskUserToolName;
|
|
200
202
|
exports.HITL_FIELDS = AskUser.HITL_FIELDS;
|
|
201
203
|
exports.createAskUserTool = AskUser.createAskUserTool;
|
|
202
|
-
exports.createSchemaOnlyTool = schema$
|
|
203
|
-
exports.createSchemaOnlyTools = schema$
|
|
204
|
+
exports.createSchemaOnlyTool = schema$3.createSchemaOnlyTool;
|
|
205
|
+
exports.createSchemaOnlyTools = schema$3.createSchemaOnlyTools;
|
|
204
206
|
exports.handleServerToolResult = handlers$1.handleServerToolResult;
|
|
205
207
|
exports.handleToolCallChunks = handlers$1.handleToolCallChunks;
|
|
206
208
|
exports.handleToolCalls = handlers$1.handleToolCalls;
|
|
207
209
|
exports.toolResultTypes = handlers$1.toolResultTypes;
|
|
208
|
-
exports.createSearchTool = tool$
|
|
210
|
+
exports.createSearchTool = tool$2.createSearchTool;
|
|
209
211
|
Object.defineProperty(exports, "DATE_RANGE", {
|
|
210
212
|
enumerable: true,
|
|
211
|
-
get: function () { return schema.DATE_RANGE; }
|
|
213
|
+
get: function () { return schema$1.DATE_RANGE; }
|
|
212
214
|
});
|
|
213
|
-
exports.DEFAULT_COUNTRY_DESCRIPTION = schema.DEFAULT_COUNTRY_DESCRIPTION;
|
|
214
|
-
exports.DEFAULT_QUERY_DESCRIPTION = schema.DEFAULT_QUERY_DESCRIPTION;
|
|
215
|
-
exports.WebSearchToolDefinition = schema.WebSearchToolDefinition;
|
|
216
|
-
exports.WebSearchToolDescription = schema.WebSearchToolDescription;
|
|
217
|
-
exports.WebSearchToolName = schema.WebSearchToolName;
|
|
218
|
-
exports.WebSearchToolSchema = schema.WebSearchToolSchema;
|
|
219
|
-
exports.countrySchema = schema.countrySchema;
|
|
220
|
-
exports.dateSchema = schema.dateSchema;
|
|
221
|
-
exports.imagesSchema = schema.imagesSchema;
|
|
222
|
-
exports.newsSchema = schema.newsSchema;
|
|
223
|
-
exports.querySchema = schema.querySchema;
|
|
224
|
-
exports.videosSchema = schema.videosSchema;
|
|
215
|
+
exports.DEFAULT_COUNTRY_DESCRIPTION = schema$1.DEFAULT_COUNTRY_DESCRIPTION;
|
|
216
|
+
exports.DEFAULT_QUERY_DESCRIPTION = schema$1.DEFAULT_QUERY_DESCRIPTION;
|
|
217
|
+
exports.WebSearchToolDefinition = schema$1.WebSearchToolDefinition;
|
|
218
|
+
exports.WebSearchToolDescription = schema$1.WebSearchToolDescription;
|
|
219
|
+
exports.WebSearchToolName = schema$1.WebSearchToolName;
|
|
220
|
+
exports.WebSearchToolSchema = schema$1.WebSearchToolSchema;
|
|
221
|
+
exports.countrySchema = schema$1.countrySchema;
|
|
222
|
+
exports.dateSchema = schema$1.dateSchema;
|
|
223
|
+
exports.imagesSchema = schema$1.imagesSchema;
|
|
224
|
+
exports.newsSchema = schema$1.newsSchema;
|
|
225
|
+
exports.querySchema = schema$1.querySchema;
|
|
226
|
+
exports.videosSchema = schema$1.videosSchema;
|
|
225
227
|
exports.buildMemoryTools = index$2.buildMemoryTools;
|
|
226
|
-
exports.createFileSearchTool = tool.createFileSearchTool;
|
|
228
|
+
exports.createFileSearchTool = tool$1.createFileSearchTool;
|
|
227
229
|
exports.HttpRagClient = ragClient.HttpRagClient;
|
|
228
230
|
exports.RAG_API_URL_ENV = ragClient.RAG_API_URL_ENV;
|
|
229
231
|
exports.getRagBaseUrl = ragClient.getRagBaseUrl;
|
|
230
232
|
exports.createCitationAnchorFormatter = formatter.createCitationAnchorFormatter;
|
|
231
233
|
exports.plainTextFormatter = formatter.plainTextFormatter;
|
|
232
|
-
exports.FileSearchToolName = schema$
|
|
233
|
-
exports.fileSearchInputSchema = schema$
|
|
234
|
+
exports.FileSearchToolName = schema$2.FileSearchToolName;
|
|
235
|
+
exports.fileSearchInputSchema = schema$2.fileSearchInputSchema;
|
|
236
|
+
exports.createArtifactTool = tool.createArtifactTool;
|
|
237
|
+
exports.createContentReaderTool = tool.createContentReaderTool;
|
|
238
|
+
exports.ARTIFACT_TOOL_NAME = schema.ARTIFACT_TOOL_NAME;
|
|
239
|
+
exports.ARTIFACT_WRITE_ACTIONS = schema.ARTIFACT_WRITE_ACTIONS;
|
|
240
|
+
exports.CONTENT_READER_NAME = schema.CONTENT_READER_NAME;
|
|
241
|
+
exports.CONTENT_READ_ACTIONS = schema.CONTENT_READ_ACTIONS;
|
|
242
|
+
exports.artifactToolSchema = schema.artifactToolSchema;
|
|
243
|
+
exports.contentReaderSchema = schema.contentReaderSchema;
|
|
234
244
|
exports.buildProxyTool = proxyTool.buildProxyTool;
|
|
235
245
|
Object.defineProperty(exports, "AuthSource", {
|
|
236
246
|
enumerable: true,
|
|
@@ -463,8 +473,8 @@ exports.isToonFormat = toonFormat.isToonFormat;
|
|
|
463
473
|
exports.jsonToToon = toonFormat.jsonToToon;
|
|
464
474
|
exports.processToolOutput = toonFormat.processToolOutput;
|
|
465
475
|
exports.buildContextAnalytics = contextAnalytics.buildContextAnalytics;
|
|
466
|
-
exports.isZodSchema = schema$
|
|
467
|
-
exports.toJsonSchema = schema$
|
|
476
|
+
exports.isZodSchema = schema$4.isZodSchema;
|
|
477
|
+
exports.toJsonSchema = schema$4.toJsonSchema;
|
|
468
478
|
exports.extractFinishReason = toolCallContinuation.extractFinishReason;
|
|
469
479
|
exports.isMaxTokensFinish = toolCallContinuation.isMaxTokensFinish;
|
|
470
480
|
exports.buildMultiDocHintContent = contextPressure.buildMultiDocHintContent;
|
package/dist/cjs/main.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -113,6 +113,10 @@ function normalizeEntry(entry) {
|
|
|
113
113
|
icon: entry.icon,
|
|
114
114
|
category: entry.category,
|
|
115
115
|
tags: entry.tags,
|
|
116
|
+
// Governance — hosts use these to gate UI/role/environment.
|
|
117
|
+
hidden: entry.hidden,
|
|
118
|
+
admin: entry.admin,
|
|
119
|
+
env: entry.env,
|
|
116
120
|
},
|
|
117
121
|
};
|
|
118
122
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolsServerCapabilityProvider.cjs","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":["Man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AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolsServerCapabilityProvider.cjs","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":["ManifestCache","createHttpClient","filterToCacheKey","assertOk","applyFilter","buildProxyTool","CapabilityKind"],"mappings":";;;;;;;AAAA;;;;;;;;;AASG;MA8EU,6BAA6B,CA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H;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","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":["CapabilityKind","AuthSource"],"mappings":";;AAAA;;;;;;;;;;;;;;AAcG;AAIH;;;;;AAKG;AACSA;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,EAXWA,sBAAc,KAAdA,sBAAc,GAAA,EAAA,CAAA,CAAA;AAa1B;;;;AAIG;AACSC;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,EAPWA,kBAAU,KAAVA,kBAAU,GAAA,EAAA,CAAA,CAAA;;"}
|
|
1
|
+
{"version":3,"file":"types.cjs","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":["CapabilityKind","AuthSource"],"mappings":";;AAAA;;;;;;;;;;;;;;AAcG;AAIH;;;;;AAKG;AACSA;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,EAXWA,sBAAc,KAAdA,sBAAc,GAAA,EAAA,CAAA,CAAA;AAa1B;;;;AAIG;AACSC;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,EAPWA,kBAAU,KAAVA,kBAAU,GAAA,EAAA,CAAA,CAAA;;"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
|
|
5
|
+
const ARTIFACT_WRITE_ACTIONS = [
|
|
6
|
+
'write',
|
|
7
|
+
'edit',
|
|
8
|
+
'verify',
|
|
9
|
+
'delete',
|
|
10
|
+
];
|
|
11
|
+
const CONTENT_READ_ACTIONS = ['read', 'search', 'list', 'info'];
|
|
12
|
+
const artifactToolSchema = zod.z.object({
|
|
13
|
+
action: zod.z
|
|
14
|
+
.enum(ARTIFACT_WRITE_ACTIONS)
|
|
15
|
+
.describe('Authoring action: write (create/overwrite), edit (str_replace), verify (syntax check), delete (remove).'),
|
|
16
|
+
content_id: zod.z
|
|
17
|
+
.string()
|
|
18
|
+
.optional()
|
|
19
|
+
.describe('ID of the artifact entry. Required for edit/verify/delete; optional for write (supply to overwrite an existing entry).'),
|
|
20
|
+
// write
|
|
21
|
+
content: zod.z
|
|
22
|
+
.string()
|
|
23
|
+
.optional()
|
|
24
|
+
.describe('Full file content (required for write action).'),
|
|
25
|
+
name: zod.z
|
|
26
|
+
.string()
|
|
27
|
+
.optional()
|
|
28
|
+
.describe('Filename for the new entry (required when creating). MUST include the correct file extension — the extension drives the preview template.'),
|
|
29
|
+
// edit (str_replace)
|
|
30
|
+
old_str: zod.z
|
|
31
|
+
.string()
|
|
32
|
+
.optional()
|
|
33
|
+
.describe('Exact string to find and replace (required for edit).'),
|
|
34
|
+
new_str: zod.z
|
|
35
|
+
.string()
|
|
36
|
+
.optional()
|
|
37
|
+
.describe('Replacement string (required for edit).'),
|
|
38
|
+
replace_all: zod.z
|
|
39
|
+
.boolean()
|
|
40
|
+
.optional()
|
|
41
|
+
.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.'),
|
|
42
|
+
});
|
|
43
|
+
const contentReaderSchema = zod.z.object({
|
|
44
|
+
action: zod.z
|
|
45
|
+
.enum(CONTENT_READ_ACTIONS)
|
|
46
|
+
.describe('Read-only action: read (lines), search (regex), list (all entries), info (metadata).'),
|
|
47
|
+
content_id: zod.z
|
|
48
|
+
.string()
|
|
49
|
+
.optional()
|
|
50
|
+
.describe('ID of the content entry. Required for read/search/info. Omit for list.'),
|
|
51
|
+
// read pagination
|
|
52
|
+
start_line: zod.z.number().optional().describe('1-based start line for reading.'),
|
|
53
|
+
end_line: zod.z.number().optional().describe('1-based end line (inclusive).'),
|
|
54
|
+
// search
|
|
55
|
+
pattern: zod.z
|
|
56
|
+
.string()
|
|
57
|
+
.optional()
|
|
58
|
+
.describe('Regex pattern (required for search).'),
|
|
59
|
+
flags: zod.z
|
|
60
|
+
.string()
|
|
61
|
+
.optional()
|
|
62
|
+
.describe('Regex flags (e.g., "i" for case-insensitive).'),
|
|
63
|
+
context: zod.z
|
|
64
|
+
.number()
|
|
65
|
+
.optional()
|
|
66
|
+
.describe('Lines of context around each match.'),
|
|
67
|
+
// shared pagination
|
|
68
|
+
offset: zod.z
|
|
69
|
+
.number()
|
|
70
|
+
.optional()
|
|
71
|
+
.describe('Offset for read or search pagination.'),
|
|
72
|
+
limit: zod.z
|
|
73
|
+
.number()
|
|
74
|
+
.optional()
|
|
75
|
+
.describe('Max lines (read) or matches (search).'),
|
|
76
|
+
});
|
|
77
|
+
const ARTIFACT_TOOL_NAME = 'artifact_tool';
|
|
78
|
+
const CONTENT_READER_NAME = 'content_reader';
|
|
79
|
+
|
|
80
|
+
exports.ARTIFACT_TOOL_NAME = ARTIFACT_TOOL_NAME;
|
|
81
|
+
exports.ARTIFACT_WRITE_ACTIONS = ARTIFACT_WRITE_ACTIONS;
|
|
82
|
+
exports.CONTENT_READER_NAME = CONTENT_READER_NAME;
|
|
83
|
+
exports.CONTENT_READ_ACTIONS = CONTENT_READ_ACTIONS;
|
|
84
|
+
exports.artifactToolSchema = artifactToolSchema;
|
|
85
|
+
exports.contentReaderSchema = contentReaderSchema;
|
|
86
|
+
//# sourceMappingURL=schema.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.cjs","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":["z"],"mappings":";;;;AAEO,MAAM,s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QAAQ,EAAE,CAAC,QAAQ,CAAC,+BAA+B,CAAC;;AAGzE,IAAA,OAAO,EAAEA;AACN,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,sCAAsC,CAAC;AACnD,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,+CAA+C,CAAC;AAC5D,IAAA,OAAO,EAAEA;AACN,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,qCAAqC,CAAC;;AAGlD,IAAA,MAAM,EAAEA;AACL,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,uCAAuC,CAAC;AACpD,IAAA,KAAK,EAAEA;AACJ,SAAA,MAAM;AACN,SAAA,QAAQ;SACR,QAAQ,CAAC,uCAAuC,CAAC;AACrD,CAAA;AAEM,MAAM,kBAAkB,GAAG;AAC3B,MAAM,mBAAmB,GAAG;;;;;;;;;"}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var tools = require('@langchain/core/tools');
|
|
4
|
+
var schema = require('./schema.cjs');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* artifact_tool + content_reader library factories.
|
|
8
|
+
*
|
|
9
|
+
* The library owns the LangChain wiring (schema, description, response
|
|
10
|
+
* shape) and the action dispatch; the runtime supplies a handler bundle
|
|
11
|
+
* matching the `ArtifactWriteHandlers` / `ContentReadHandlers` interface.
|
|
12
|
+
*
|
|
13
|
+
* This keeps 800+ LOC of host-specific handler logic (S3 adapters, file
|
|
14
|
+
* model CRUD, syntax checkers, line utils) out of the library while
|
|
15
|
+
* still centralizing the tool surface every runtime shares.
|
|
16
|
+
*/
|
|
17
|
+
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).
|
|
18
|
+
|
|
19
|
+
Actions:
|
|
20
|
+
- 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).
|
|
21
|
+
- 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.
|
|
22
|
+
- edit: Surgical string replacement — provide old_str (exact match) and new_str. Works on all file types.
|
|
23
|
+
- delete: Remove an artifact and its backing file.
|
|
24
|
+
|
|
25
|
+
Artifacts are persisted by the host. No manual save needed.`;
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
Read-only surface. Use write/edit tools (artifact_tool, execute_code) to mutate.
|
|
29
|
+
|
|
30
|
+
Actions:
|
|
31
|
+
- read: Return line ranges from a specific content_id.
|
|
32
|
+
- search: Regex search across a specific content_id with paginated matches.
|
|
33
|
+
- list: Enumerate every content entry currently stored.
|
|
34
|
+
- info: Metadata (size, kind, creation time) for a specific content_id.`;
|
|
35
|
+
/**
|
|
36
|
+
* Optional content_id self-healing — if the runtime supplies a resolver,
|
|
37
|
+
* we pre-resolve the ID on every action that takes one so nicknames
|
|
38
|
+
* (e.g., "Dashboard") map to canonical IDs.
|
|
39
|
+
*/
|
|
40
|
+
async function resolveContentIdIfPresent(resolver, id, scope, logger) {
|
|
41
|
+
if (!resolver || !id)
|
|
42
|
+
return id;
|
|
43
|
+
const out = await resolver.resolve(id, scope);
|
|
44
|
+
if (!out)
|
|
45
|
+
return id;
|
|
46
|
+
if (out.resolvedId !== id) {
|
|
47
|
+
logger?.debug(`[artifact] resolved "${id}" → "${out.resolvedId}"${out.resolvedName ? ` ("${out.resolvedName}")` : ''}`);
|
|
48
|
+
}
|
|
49
|
+
return out.resolvedId;
|
|
50
|
+
}
|
|
51
|
+
// ─── Writer tool (artifact_tool) ─────────────────────────────────────────
|
|
52
|
+
function createArtifactTool(config) {
|
|
53
|
+
const { handlers, getScope, resolver, logger, descriptionOverride } = config;
|
|
54
|
+
return tools.tool(async (rawInput, runnableConfig) => {
|
|
55
|
+
const scope = getScope(runnableConfig);
|
|
56
|
+
if (!scope) {
|
|
57
|
+
logger?.warn('[artifact_tool] no scope resolved from runnableConfig');
|
|
58
|
+
return ['Error: No conversation context available', {}];
|
|
59
|
+
}
|
|
60
|
+
const input = rawInput;
|
|
61
|
+
const resolvedContentId = await resolveContentIdIfPresent(resolver, input.content_id, scope, logger);
|
|
62
|
+
const started = Date.now();
|
|
63
|
+
try {
|
|
64
|
+
switch (input.action) {
|
|
65
|
+
case 'write': {
|
|
66
|
+
const args = {
|
|
67
|
+
action: 'write',
|
|
68
|
+
content_id: resolvedContentId,
|
|
69
|
+
content: input.content ?? '',
|
|
70
|
+
name: input.name,
|
|
71
|
+
};
|
|
72
|
+
if (!args.content)
|
|
73
|
+
return ['Error: write requires content', {}];
|
|
74
|
+
return await handlers.write(args, scope);
|
|
75
|
+
}
|
|
76
|
+
case 'edit': {
|
|
77
|
+
if (!resolvedContentId)
|
|
78
|
+
return ['Error: edit requires content_id', {}];
|
|
79
|
+
const args = {
|
|
80
|
+
action: 'edit',
|
|
81
|
+
content_id: resolvedContentId,
|
|
82
|
+
old_str: input.old_str ?? '',
|
|
83
|
+
new_str: input.new_str ?? '',
|
|
84
|
+
replace_all: input.replace_all,
|
|
85
|
+
};
|
|
86
|
+
if (!args.old_str)
|
|
87
|
+
return ['Error: edit requires old_str', {}];
|
|
88
|
+
return await handlers.edit(args, scope);
|
|
89
|
+
}
|
|
90
|
+
case 'verify': {
|
|
91
|
+
if (!resolvedContentId)
|
|
92
|
+
return ['Error: verify requires content_id', {}];
|
|
93
|
+
const args = {
|
|
94
|
+
action: 'verify',
|
|
95
|
+
content_id: resolvedContentId,
|
|
96
|
+
};
|
|
97
|
+
return await handlers.verify(args, scope);
|
|
98
|
+
}
|
|
99
|
+
case 'delete': {
|
|
100
|
+
if (!resolvedContentId)
|
|
101
|
+
return ['Error: delete requires content_id', {}];
|
|
102
|
+
const args = {
|
|
103
|
+
action: 'delete',
|
|
104
|
+
content_id: resolvedContentId,
|
|
105
|
+
};
|
|
106
|
+
return await handlers.delete(args, scope);
|
|
107
|
+
}
|
|
108
|
+
default:
|
|
109
|
+
return [
|
|
110
|
+
`Unknown action: ${input.action}`,
|
|
111
|
+
{},
|
|
112
|
+
];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
117
|
+
logger?.error('[artifact_tool] handler threw', {
|
|
118
|
+
action: input.action,
|
|
119
|
+
contentId: resolvedContentId,
|
|
120
|
+
error: e.message,
|
|
121
|
+
elapsed: `${Date.now() - started}ms`,
|
|
122
|
+
});
|
|
123
|
+
return [`Error: ${e.message}`, {}];
|
|
124
|
+
}
|
|
125
|
+
}, {
|
|
126
|
+
name: schema.ARTIFACT_TOOL_NAME,
|
|
127
|
+
responseFormat: 'content_and_artifact',
|
|
128
|
+
description: descriptionOverride ?? DEFAULT_ARTIFACT_DESCRIPTION,
|
|
129
|
+
schema: schema.artifactToolSchema,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
// ─── Reader tool (content_reader) ────────────────────────────────────────
|
|
133
|
+
function createContentReaderTool(config) {
|
|
134
|
+
const { handlers, getScope, resolver, logger, descriptionOverride } = config;
|
|
135
|
+
return tools.tool(async (rawInput, runnableConfig) => {
|
|
136
|
+
const scope = getScope(runnableConfig);
|
|
137
|
+
if (!scope) {
|
|
138
|
+
logger?.warn('[content_reader] no scope resolved from runnableConfig');
|
|
139
|
+
return ['Error: No conversation context available', {}];
|
|
140
|
+
}
|
|
141
|
+
const input = rawInput;
|
|
142
|
+
const resolvedContentId = await resolveContentIdIfPresent(resolver, input.content_id, scope, logger);
|
|
143
|
+
const started = Date.now();
|
|
144
|
+
try {
|
|
145
|
+
switch (input.action) {
|
|
146
|
+
case 'read': {
|
|
147
|
+
if (!resolvedContentId)
|
|
148
|
+
return ['Error: read requires content_id', {}];
|
|
149
|
+
const args = {
|
|
150
|
+
action: 'read',
|
|
151
|
+
content_id: resolvedContentId,
|
|
152
|
+
start_line: input.start_line,
|
|
153
|
+
end_line: input.end_line,
|
|
154
|
+
offset: input.offset,
|
|
155
|
+
limit: input.limit,
|
|
156
|
+
};
|
|
157
|
+
return await handlers.read(args, scope);
|
|
158
|
+
}
|
|
159
|
+
case 'search': {
|
|
160
|
+
if (!resolvedContentId)
|
|
161
|
+
return ['Error: search requires content_id', {}];
|
|
162
|
+
if (!input.pattern)
|
|
163
|
+
return ['Error: search requires pattern', {}];
|
|
164
|
+
const args = {
|
|
165
|
+
action: 'search',
|
|
166
|
+
content_id: resolvedContentId,
|
|
167
|
+
pattern: input.pattern,
|
|
168
|
+
flags: input.flags,
|
|
169
|
+
context: input.context,
|
|
170
|
+
offset: input.offset,
|
|
171
|
+
limit: input.limit,
|
|
172
|
+
};
|
|
173
|
+
return await handlers.search(args, scope);
|
|
174
|
+
}
|
|
175
|
+
case 'list': {
|
|
176
|
+
const args = { action: 'list' };
|
|
177
|
+
return await handlers.list(args, scope);
|
|
178
|
+
}
|
|
179
|
+
case 'info': {
|
|
180
|
+
if (!resolvedContentId)
|
|
181
|
+
return ['Error: info requires content_id', {}];
|
|
182
|
+
const args = {
|
|
183
|
+
action: 'info',
|
|
184
|
+
content_id: resolvedContentId,
|
|
185
|
+
};
|
|
186
|
+
return await handlers.info(args, scope);
|
|
187
|
+
}
|
|
188
|
+
default:
|
|
189
|
+
return [
|
|
190
|
+
`Unknown action: ${input.action}`,
|
|
191
|
+
{},
|
|
192
|
+
];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
197
|
+
logger?.error('[content_reader] handler threw', {
|
|
198
|
+
action: input.action,
|
|
199
|
+
contentId: resolvedContentId,
|
|
200
|
+
error: e.message,
|
|
201
|
+
elapsed: `${Date.now() - started}ms`,
|
|
202
|
+
});
|
|
203
|
+
return [`Error: ${e.message}`, {}];
|
|
204
|
+
}
|
|
205
|
+
}, {
|
|
206
|
+
name: schema.CONTENT_READER_NAME,
|
|
207
|
+
responseFormat: 'content_and_artifact',
|
|
208
|
+
description: descriptionOverride ?? DEFAULT_CONTENT_READER_DESCRIPTION,
|
|
209
|
+
schema: schema.contentReaderSchema,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
exports.ARTIFACT_TOOL_NAME = schema.ARTIFACT_TOOL_NAME;
|
|
214
|
+
exports.ARTIFACT_WRITE_ACTIONS = schema.ARTIFACT_WRITE_ACTIONS;
|
|
215
|
+
exports.CONTENT_READER_NAME = schema.CONTENT_READER_NAME;
|
|
216
|
+
exports.CONTENT_READ_ACTIONS = schema.CONTENT_READ_ACTIONS;
|
|
217
|
+
exports.createArtifactTool = createArtifactTool;
|
|
218
|
+
exports.createContentReaderTool = createContentReaderTool;
|
|
219
|
+
//# sourceMappingURL=tool.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.cjs","sources":["../../../../src/tools/artifacts/tool.ts"],"sourcesContent":["/**\n * artifact_tool + content_reader library factories.\n *\n * The library owns the LangChain wiring (schema, description, response\n * shape) and the action dispatch; the runtime supplies a handler bundle\n * matching the `ArtifactWriteHandlers` / `ContentReadHandlers` interface.\n *\n * This keeps 800+ LOC of host-specific handler logic (S3 adapters, file\n * model CRUD, syntax checkers, line utils) out of the library while\n * still centralizing the tool surface every runtime shares.\n */\n\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport {\n artifactToolSchema,\n contentReaderSchema,\n ARTIFACT_TOOL_NAME,\n CONTENT_READER_NAME,\n} from './schema';\nimport type {\n ArtifactToolConfig,\n ContentReaderToolConfig,\n ArtifactToolScope,\n ArtifactToolResult,\n WriteArgs,\n EditArgs,\n VerifyArgs,\n DeleteArgs,\n ReadArgs,\n SearchArgs,\n ListArgs,\n InfoArgs,\n ContentIdResolver,\n} from './types';\n\nconst 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).\n\nActions:\n- 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).\n- 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.\n- edit: Surgical string replacement — provide old_str (exact match) and new_str. Works on all file types.\n- delete: Remove an artifact and its backing file.\n\nArtifacts are persisted by the host. No manual save needed.`;\n\nconst 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.\n\nRead-only surface. Use write/edit tools (artifact_tool, execute_code) to mutate.\n\nActions:\n- read: Return line ranges from a specific content_id.\n- search: Regex search across a specific content_id with paginated matches.\n- list: Enumerate every content entry currently stored.\n- info: Metadata (size, kind, creation time) for a specific content_id.`;\n\n/**\n * Optional content_id self-healing — if the runtime supplies a resolver,\n * we pre-resolve the ID on every action that takes one so nicknames\n * (e.g., \"Dashboard\") map to canonical IDs.\n */\nasync function resolveContentIdIfPresent(\n resolver: ContentIdResolver | undefined,\n id: string | undefined,\n scope: ArtifactToolScope,\n logger?: { debug: (msg: string) => void }\n): Promise<string | undefined> {\n if (!resolver || !id) return id;\n const out = await resolver.resolve(id, scope);\n if (!out) return id;\n if (out.resolvedId !== id) {\n logger?.debug(\n `[artifact] resolved \"${id}\" → \"${out.resolvedId}\"${out.resolvedName ? ` (\"${out.resolvedName}\")` : ''}`\n );\n }\n return out.resolvedId;\n}\n\n// ─── Writer tool (artifact_tool) ─────────────────────────────────────────\n\nexport function createArtifactTool(\n config: ArtifactToolConfig\n): DynamicStructuredTool {\n const { handlers, getScope, resolver, logger, descriptionOverride } = config;\n\n return tool(\n async (rawInput, runnableConfig): Promise<ArtifactToolResult> => {\n const scope = getScope(runnableConfig);\n if (!scope) {\n logger?.warn('[artifact_tool] no scope resolved from runnableConfig');\n return ['Error: No conversation context available', {}];\n }\n\n const input = rawInput as {\n action: 'write' | 'edit' | 'verify' | 'delete';\n content_id?: string;\n content?: string;\n name?: string;\n old_str?: string;\n new_str?: string;\n replace_all?: boolean;\n };\n\n const resolvedContentId = await resolveContentIdIfPresent(\n resolver,\n input.content_id,\n scope,\n logger\n );\n\n const started = Date.now();\n try {\n switch (input.action) {\n case 'write': {\n const args: WriteArgs = {\n action: 'write',\n content_id: resolvedContentId,\n content: input.content ?? '',\n name: input.name,\n };\n if (!args.content) return ['Error: write requires content', {}];\n return await handlers.write(args, scope);\n }\n case 'edit': {\n if (!resolvedContentId)\n return ['Error: edit requires content_id', {}];\n const args: EditArgs = {\n action: 'edit',\n content_id: resolvedContentId,\n old_str: input.old_str ?? '',\n new_str: input.new_str ?? '',\n replace_all: input.replace_all,\n };\n if (!args.old_str) return ['Error: edit requires old_str', {}];\n return await handlers.edit(args, scope);\n }\n case 'verify': {\n if (!resolvedContentId)\n return ['Error: verify requires content_id', {}];\n const args: VerifyArgs = {\n action: 'verify',\n content_id: resolvedContentId,\n };\n return await handlers.verify(args, scope);\n }\n case 'delete': {\n if (!resolvedContentId)\n return ['Error: delete requires content_id', {}];\n const args: DeleteArgs = {\n action: 'delete',\n content_id: resolvedContentId,\n };\n return await handlers.delete(args, scope);\n }\n default:\n return [\n `Unknown action: ${(input as { action: string }).action}`,\n {},\n ];\n }\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n logger?.error('[artifact_tool] handler threw', {\n action: input.action,\n contentId: resolvedContentId,\n error: e.message,\n elapsed: `${Date.now() - started}ms`,\n });\n return [`Error: ${e.message}`, {}];\n }\n },\n {\n name: ARTIFACT_TOOL_NAME,\n responseFormat: 'content_and_artifact',\n description: descriptionOverride ?? DEFAULT_ARTIFACT_DESCRIPTION,\n schema: artifactToolSchema,\n }\n );\n}\n\n// ─── Reader tool (content_reader) ────────────────────────────────────────\n\nexport function createContentReaderTool(\n config: ContentReaderToolConfig\n): DynamicStructuredTool {\n const { handlers, getScope, resolver, logger, descriptionOverride } = config;\n\n return tool(\n async (rawInput, runnableConfig): Promise<ArtifactToolResult> => {\n const scope = getScope(runnableConfig);\n if (!scope) {\n logger?.warn('[content_reader] no scope resolved from runnableConfig');\n return ['Error: No conversation context available', {}];\n }\n\n const input = rawInput as {\n action: 'read' | 'search' | 'list' | 'info';\n content_id?: string;\n start_line?: number;\n end_line?: number;\n pattern?: string;\n flags?: string;\n context?: number;\n offset?: number;\n limit?: number;\n };\n\n const resolvedContentId = await resolveContentIdIfPresent(\n resolver,\n input.content_id,\n scope,\n logger\n );\n\n const started = Date.now();\n try {\n switch (input.action) {\n case 'read': {\n if (!resolvedContentId)\n return ['Error: read requires content_id', {}];\n const args: ReadArgs = {\n action: 'read',\n content_id: resolvedContentId,\n start_line: input.start_line,\n end_line: input.end_line,\n offset: input.offset,\n limit: input.limit,\n };\n return await handlers.read(args, scope);\n }\n case 'search': {\n if (!resolvedContentId)\n return ['Error: search requires content_id', {}];\n if (!input.pattern) return ['Error: search requires pattern', {}];\n const args: SearchArgs = {\n action: 'search',\n content_id: resolvedContentId,\n pattern: input.pattern,\n flags: input.flags,\n context: input.context,\n offset: input.offset,\n limit: input.limit,\n };\n return await handlers.search(args, scope);\n }\n case 'list': {\n const args: ListArgs = { action: 'list' };\n return await handlers.list(args, scope);\n }\n case 'info': {\n if (!resolvedContentId)\n return ['Error: info requires content_id', {}];\n const args: InfoArgs = {\n action: 'info',\n content_id: resolvedContentId,\n };\n return await handlers.info(args, scope);\n }\n default:\n return [\n `Unknown action: ${(input as { action: string }).action}`,\n {},\n ];\n }\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n logger?.error('[content_reader] handler threw', {\n action: input.action,\n contentId: resolvedContentId,\n error: e.message,\n elapsed: `${Date.now() - started}ms`,\n });\n return [`Error: ${e.message}`, {}];\n }\n },\n {\n name: CONTENT_READER_NAME,\n responseFormat: 'content_and_artifact',\n description: descriptionOverride ?? DEFAULT_CONTENT_READER_DESCRIPTION,\n schema: contentReaderSchema,\n }\n );\n}\n\nexport {\n ARTIFACT_TOOL_NAME,\n CONTENT_READER_NAME,\n ARTIFACT_WRITE_ACTIONS,\n CONTENT_READ_ACTIONS,\n} from './schema';\n"],"names":["tool","ARTIFACT_TOOL_NAME","artifactToolSchema","CONTENT_READER_NAME","contentReaderSchema"],"mappings":";;;;;AAAA;;;;;;;;;;AAUG;AAyBH,MAAM,4BAA4B,GAAG,CAAA;;;;;;;;4DAQuB;AAE5D,MAAM,kCAAkC,GAAG,CAAA;;;;;;;;wEAQ6B;AAExE;;;;AAIG;AACH,eAAe,yBAAyB,CACtC,QAAuC,EACvC,EAAsB,EACtB,KAAwB,EACxB,MAAyC,EAAA;AAEzC,IAAA,IAAI,CAAC,QAAQ,IAAI,CAAC,EAAE;AAAE,QAAA,OAAO,EAAE;IAC/B,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC;AAC7C,IAAA,IAAI,CAAC,GAAG;AAAE,QAAA,OAAO,EAAE;AACnB,IAAA,IAAI,GAAG,CAAC,UAAU,KAAK,EAAE,EAAE;QACzB,MAAM,EAAE,KAAK,CACX,CAAA,qBAAA,EAAwB,EAAE,CAAA,KAAA,EAAQ,GAAG,CAAC,UAAU,CAAA,CAAA,EAAI,GAAG,CAAC,YAAY,GAAG,CAAA,GAAA,EAAM,GAAG,CAAC,YAAY,CAAA,EAAA,CAAI,GAAG,EAAE,CAAA,CAAE,CACzG;IACH;IACA,OAAO,GAAG,CAAC,UAAU;AACvB;AAEA;AAEM,SAAU,kBAAkB,CAChC,MAA0B,EAAA;AAE1B,IAAA,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,MAAM;IAE5E,OAAOA,UAAI,CACT,OAAO,QA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QAEP;QAAE,OAAO,GAAG,EAAE;YACZ,MAAM,CAAC,GAAG,GAAG,YAAY,KAAK,GAAG,GAAG,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC7D,YAAA,MAAM,EAAE,KAAK,CAAC,gCAAgC,EAAE;gBAC9C,MAAM,EAAE,KAAK,CAAC,MAAM;AACpB,gBAAA,SAAS,EAAE,iBAAiB;gBAC5B,KAAK,EAAE,CAAC,CAAC,OAAO;gBAChB,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAA,EAAA,CAAI;AACrC,aAAA,CAAC;YACF,OAAO,CAAC,UAAU,CAAC,CAAC,OAAO,CAAA,CAAE,EAAE,EAAE,CAAC;QACpC;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAEG,0BAAmB;AACzB,QAAA,cAAc,EAAE,sBAAsB;QACtC,WAAW,EAAE,mBAAmB,IAAI,kCAAkC;AACtE,QAAA,MAAM,EAAEC,0BAAmB;AAC5B,KAAA,CACF;AACH;;;;;;;;;"}
|
|
@@ -37,7 +37,7 @@ const plainTextFormatter = {
|
|
|
37
37
|
function createCitationAnchorFormatter(opts = {}) {
|
|
38
38
|
const toolName = opts.toolName ?? 'file_search';
|
|
39
39
|
const getOffset = opts.getSourceOffset ?? (() => 0);
|
|
40
|
-
const advance = opts.advanceSourceOffset ?? (() => { });
|
|
40
|
+
const advance = opts.advanceSourceOffset ?? ((_by) => { });
|
|
41
41
|
return {
|
|
42
42
|
format(chunks) {
|
|
43
43
|
if (chunks.length === 0) {
|
|
@@ -64,9 +64,7 @@ function createCitationAnchorFormatter(opts = {}) {
|
|
|
64
64
|
fileName: c.filename,
|
|
65
65
|
relevance: 1 - c.distance,
|
|
66
66
|
pages: getPage(c) != null ? [getPage(c)] : [],
|
|
67
|
-
pageRelevance: getPage(c) != null
|
|
68
|
-
? { [getPage(c)]: 1 - c.distance }
|
|
69
|
-
: {},
|
|
67
|
+
pageRelevance: getPage(c) != null ? { [getPage(c)]: 1 - c.distance } : {},
|
|
70
68
|
}));
|
|
71
69
|
advance(chunks.length);
|
|
72
70
|
return {
|