@contractspec/lib.ai-agent 1.62.0 → 2.0.0
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/agent/agent-factory.d.ts +0 -1
- package/dist/agent/agent-factory.js +41 -6
- package/dist/agent/agent.test.d.ts +0 -1
- package/dist/agent/contract-spec-agent.d.ts +0 -1
- package/dist/agent/contract-spec-agent.js +41 -6
- package/dist/agent/index.d.ts +0 -1
- package/dist/agent/index.js +43 -8
- package/dist/agent/json-runner.d.ts +0 -1
- package/dist/agent/json-runner.js +42 -7
- package/dist/agent/json-runner.test.d.ts +0 -1
- package/dist/agent/unified-agent.d.ts +0 -1
- package/dist/agent/unified-agent.js +42 -7
- package/dist/approval/index.d.ts +0 -1
- package/dist/approval/index.js +31 -5
- package/dist/approval/workflow.d.ts +7 -2
- package/dist/approval/workflow.js +31 -5
- package/dist/exporters/claude-agent-exporter.d.ts +0 -1
- package/dist/exporters/claude-agent-exporter.js +4 -4
- package/dist/exporters/index.d.ts +0 -1
- package/dist/exporters/index.js +4 -4
- package/dist/exporters/opencode-exporter.d.ts +0 -1
- package/dist/exporters/opencode-exporter.js +4 -4
- package/dist/exporters/types.d.ts +0 -1
- package/dist/i18n/catalogs/en.d.ts +1 -2
- package/dist/i18n/catalogs/en.js +1 -1
- package/dist/i18n/catalogs/es.d.ts +1 -2
- package/dist/i18n/catalogs/es.js +1 -1
- package/dist/i18n/catalogs/fr.d.ts +1 -2
- package/dist/i18n/catalogs/fr.js +1 -1
- package/dist/i18n/catalogs/index.d.ts +0 -1
- package/dist/i18n/catalogs/index.js +3 -3
- package/dist/i18n/i18n.test.d.ts +0 -1
- package/dist/i18n/index.d.ts +0 -1
- package/dist/i18n/index.js +4 -4
- package/dist/i18n/keys.d.ts +0 -1
- package/dist/i18n/locale.d.ts +0 -1
- package/dist/i18n/messages.d.ts +1 -2
- package/dist/i18n/messages.js +4 -4
- package/dist/index.d.ts +0 -14
- package/dist/index.js +6 -3523
- package/dist/interop/index.d.ts +0 -1
- package/dist/interop/index.js +4 -4
- package/dist/interop/spec-consumer.d.ts +0 -1
- package/dist/interop/spec-consumer.js +4 -4
- package/dist/interop/tool-consumer.d.ts +0 -1
- package/dist/interop/tool-consumer.js +4 -4
- package/dist/interop/types.d.ts +0 -1
- package/dist/knowledge/index.d.ts +0 -1
- package/dist/knowledge/index.js +4 -4
- package/dist/knowledge/injector.d.ts +0 -1
- package/dist/knowledge/injector.js +4 -4
- package/dist/memory/in-memory.d.ts +0 -1
- package/dist/memory/index.d.ts +0 -1
- package/dist/memory/manager.d.ts +0 -1
- package/dist/memory/memory.test.d.ts +0 -1
- package/dist/node/agent/agent-factory.js +41 -6
- package/dist/node/agent/contract-spec-agent.js +41 -6
- package/dist/node/agent/index.js +43 -8
- package/dist/node/agent/json-runner.js +42 -7
- package/dist/node/agent/unified-agent.js +42 -7
- package/dist/node/approval/index.js +31 -5
- package/dist/node/approval/workflow.js +31 -5
- package/dist/node/exporters/claude-agent-exporter.js +4 -4
- package/dist/node/exporters/index.js +4 -4
- package/dist/node/exporters/opencode-exporter.js +4 -4
- package/dist/node/i18n/catalogs/en.js +1 -1
- package/dist/node/i18n/catalogs/es.js +1 -1
- package/dist/node/i18n/catalogs/fr.js +1 -1
- package/dist/node/i18n/catalogs/index.js +3 -3
- package/dist/node/i18n/index.js +4 -4
- package/dist/node/i18n/messages.js +4 -4
- package/dist/node/index.js +6 -3523
- package/dist/node/interop/index.js +4 -4
- package/dist/node/interop/spec-consumer.js +4 -4
- package/dist/node/interop/tool-consumer.js +4 -4
- package/dist/node/knowledge/index.js +4 -4
- package/dist/node/knowledge/injector.js +4 -4
- package/dist/node/providers/claude-agent-sdk/adapter.js +4 -4
- package/dist/node/providers/claude-agent-sdk/index.js +4 -4
- package/dist/node/providers/claude-agent-sdk/tool-bridge.js +4 -4
- package/dist/node/providers/index.js +4 -4
- package/dist/node/providers/opencode-sdk/adapter.js +4 -4
- package/dist/node/providers/opencode-sdk/agent-bridge.js +4 -4
- package/dist/node/providers/opencode-sdk/index.js +4 -4
- package/dist/node/providers/opencode-sdk/tool-bridge.js +4 -4
- package/dist/node/providers/registry.js +4 -4
- package/dist/node/session/index.js +37 -2
- package/dist/node/session/store.js +37 -2
- package/dist/node/spec/index.js +5 -5
- package/dist/node/spec/registry.js +5 -5
- package/dist/node/spec/spec.js +4 -4
- package/dist/node/tools/index.js +4 -4
- package/dist/node/tools/knowledge-tool.js +4 -4
- package/dist/node/tools/mcp-server.js +4 -4
- package/dist/node/tools/tool-adapter.js +4 -4
- package/dist/providers/claude-agent-sdk/adapter.d.ts +0 -1
- package/dist/providers/claude-agent-sdk/adapter.js +4 -4
- package/dist/providers/claude-agent-sdk/index.d.ts +0 -1
- package/dist/providers/claude-agent-sdk/index.js +4 -4
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts +0 -1
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts +0 -1
- package/dist/providers/claude-agent-sdk/tool-bridge.js +4 -4
- package/dist/providers/index.d.ts +0 -1
- package/dist/providers/index.js +4 -4
- package/dist/providers/opencode-sdk/adapter.d.ts +0 -1
- package/dist/providers/opencode-sdk/adapter.js +4 -4
- package/dist/providers/opencode-sdk/agent-bridge.d.ts +0 -1
- package/dist/providers/opencode-sdk/agent-bridge.js +4 -4
- package/dist/providers/opencode-sdk/index.d.ts +0 -1
- package/dist/providers/opencode-sdk/index.js +4 -4
- package/dist/providers/opencode-sdk/tool-bridge.d.ts +0 -1
- package/dist/providers/opencode-sdk/tool-bridge.js +4 -4
- package/dist/providers/registry.d.ts +0 -1
- package/dist/providers/registry.js +4 -4
- package/dist/providers/types.d.ts +0 -1
- package/dist/schema/index.d.ts +0 -1
- package/dist/schema/json-schema-to-zod.d.ts +0 -1
- package/dist/schema/schema-output.d.ts +0 -1
- package/dist/session/index.d.ts +0 -1
- package/dist/session/index.js +37 -2
- package/dist/session/store.d.ts +12 -2
- package/dist/session/store.js +37 -2
- package/dist/spec/index.d.ts +0 -1
- package/dist/spec/index.js +5 -5
- package/dist/spec/registry.d.ts +1 -2
- package/dist/spec/registry.js +5 -5
- package/dist/spec/spec.d.ts +3 -4
- package/dist/spec/spec.js +4 -4
- package/dist/telemetry/adapter.d.ts +0 -1
- package/dist/telemetry/index.d.ts +0 -1
- package/dist/telemetry/posthog-types.d.ts +0 -1
- package/dist/telemetry/posthog.d.ts +0 -1
- package/dist/telemetry/posthog.test.d.ts +0 -1
- package/dist/tools/index.d.ts +0 -1
- package/dist/tools/index.js +4 -4
- package/dist/tools/knowledge-tool.d.ts +0 -1
- package/dist/tools/knowledge-tool.js +4 -4
- package/dist/tools/mcp-client.d.ts +0 -1
- package/dist/tools/mcp-server.d.ts +0 -1
- package/dist/tools/mcp-server.js +4 -4
- package/dist/tools/tool-adapter.d.ts +0 -1
- package/dist/tools/tool-adapter.js +4 -4
- package/dist/tools/tools.test.d.ts +0 -1
- package/dist/types.d.ts +0 -1
- package/package.json +12 -12
- package/dist/agent/agent-factory.d.ts.map +0 -1
- package/dist/agent/agent.test.d.ts.map +0 -1
- package/dist/agent/contract-spec-agent.d.ts.map +0 -1
- package/dist/agent/index.d.ts.map +0 -1
- package/dist/agent/json-runner.d.ts.map +0 -1
- package/dist/agent/json-runner.test.d.ts.map +0 -1
- package/dist/agent/unified-agent.d.ts.map +0 -1
- package/dist/approval/index.d.ts.map +0 -1
- package/dist/approval/workflow.d.ts.map +0 -1
- package/dist/exporters/claude-agent-exporter.d.ts.map +0 -1
- package/dist/exporters/index.d.ts.map +0 -1
- package/dist/exporters/opencode-exporter.d.ts.map +0 -1
- package/dist/exporters/types.d.ts.map +0 -1
- package/dist/i18n/catalogs/en.d.ts.map +0 -1
- package/dist/i18n/catalogs/es.d.ts.map +0 -1
- package/dist/i18n/catalogs/fr.d.ts.map +0 -1
- package/dist/i18n/catalogs/index.d.ts.map +0 -1
- package/dist/i18n/i18n.test.d.ts.map +0 -1
- package/dist/i18n/index.d.ts.map +0 -1
- package/dist/i18n/keys.d.ts.map +0 -1
- package/dist/i18n/locale.d.ts.map +0 -1
- package/dist/i18n/messages.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/interop/index.d.ts.map +0 -1
- package/dist/interop/spec-consumer.d.ts.map +0 -1
- package/dist/interop/tool-consumer.d.ts.map +0 -1
- package/dist/interop/types.d.ts.map +0 -1
- package/dist/knowledge/index.d.ts.map +0 -1
- package/dist/knowledge/injector.d.ts.map +0 -1
- package/dist/memory/in-memory.d.ts.map +0 -1
- package/dist/memory/index.d.ts.map +0 -1
- package/dist/memory/manager.d.ts.map +0 -1
- package/dist/memory/memory.test.d.ts.map +0 -1
- package/dist/providers/claude-agent-sdk/adapter.d.ts.map +0 -1
- package/dist/providers/claude-agent-sdk/index.d.ts.map +0 -1
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts.map +0 -1
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts.map +0 -1
- package/dist/providers/index.d.ts.map +0 -1
- package/dist/providers/opencode-sdk/adapter.d.ts.map +0 -1
- package/dist/providers/opencode-sdk/agent-bridge.d.ts.map +0 -1
- package/dist/providers/opencode-sdk/index.d.ts.map +0 -1
- package/dist/providers/opencode-sdk/tool-bridge.d.ts.map +0 -1
- package/dist/providers/registry.d.ts.map +0 -1
- package/dist/providers/types.d.ts.map +0 -1
- package/dist/schema/index.d.ts.map +0 -1
- package/dist/schema/json-schema-to-zod.d.ts.map +0 -1
- package/dist/schema/schema-output.d.ts.map +0 -1
- package/dist/session/index.d.ts.map +0 -1
- package/dist/session/store.d.ts.map +0 -1
- package/dist/spec/index.d.ts.map +0 -1
- package/dist/spec/registry.d.ts.map +0 -1
- package/dist/spec/spec.d.ts.map +0 -1
- package/dist/telemetry/adapter.d.ts.map +0 -1
- package/dist/telemetry/index.d.ts.map +0 -1
- package/dist/telemetry/posthog-types.d.ts.map +0 -1
- package/dist/telemetry/posthog.d.ts.map +0 -1
- package/dist/telemetry/posthog.test.d.ts.map +0 -1
- package/dist/tools/index.d.ts.map +0 -1
- package/dist/tools/knowledge-tool.d.ts.map +0 -1
- package/dist/tools/mcp-client.d.ts.map +0 -1
- package/dist/tools/mcp-server.d.ts.map +0 -1
- package/dist/tools/tool-adapter.d.ts.map +0 -1
- package/dist/tools/tools.test.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
package/dist/node/index.js
CHANGED
|
@@ -13,7 +13,7 @@ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
|
13
13
|
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
14
14
|
|
|
15
15
|
// src/i18n/catalogs/en.ts
|
|
16
|
-
import { defineTranslation } from "@contractspec/lib.contracts/translations";
|
|
16
|
+
import { defineTranslation } from "@contractspec/lib.contracts-spec/translations";
|
|
17
17
|
var enMessages;
|
|
18
18
|
var init_en = __esm(() => {
|
|
19
19
|
enMessages = defineTranslation({
|
|
@@ -609,7 +609,7 @@ var init_en = __esm(() => {
|
|
|
609
609
|
});
|
|
610
610
|
|
|
611
611
|
// src/i18n/catalogs/fr.ts
|
|
612
|
-
import { defineTranslation as defineTranslation2 } from "@contractspec/lib.contracts/translations";
|
|
612
|
+
import { defineTranslation as defineTranslation2 } from "@contractspec/lib.contracts-spec/translations";
|
|
613
613
|
var frMessages;
|
|
614
614
|
var init_fr = __esm(() => {
|
|
615
615
|
frMessages = defineTranslation2({
|
|
@@ -1220,7 +1220,7 @@ var init_fr = __esm(() => {
|
|
|
1220
1220
|
});
|
|
1221
1221
|
|
|
1222
1222
|
// src/i18n/catalogs/es.ts
|
|
1223
|
-
import { defineTranslation as defineTranslation3 } from "@contractspec/lib.contracts/translations";
|
|
1223
|
+
import { defineTranslation as defineTranslation3 } from "@contractspec/lib.contracts-spec/translations";
|
|
1224
1224
|
var esMessages;
|
|
1225
1225
|
var init_es = __esm(() => {
|
|
1226
1226
|
esMessages = defineTranslation3({
|
|
@@ -1885,7 +1885,7 @@ var init_locale = __esm(() => {
|
|
|
1885
1885
|
});
|
|
1886
1886
|
|
|
1887
1887
|
// src/i18n/messages.ts
|
|
1888
|
-
import { TranslationRegistry } from "@contractspec/lib.contracts/translations";
|
|
1888
|
+
import { TranslationRegistry } from "@contractspec/lib.contracts-spec/translations";
|
|
1889
1889
|
function getRegistry() {
|
|
1890
1890
|
if (!sharedRegistry) {
|
|
1891
1891
|
sharedRegistry = new TranslationRegistry([
|
|
@@ -2137,2786 +2137,10 @@ var init_spec = __esm(() => {
|
|
|
2137
2137
|
init_i18n();
|
|
2138
2138
|
});
|
|
2139
2139
|
|
|
2140
|
-
// src/schema/json-schema-to-zod.ts
|
|
2141
|
-
import { z } from "zod";
|
|
2142
|
-
function jsonSchemaToZod(schema) {
|
|
2143
|
-
const s = schema;
|
|
2144
|
-
const makeNullable = (zodSchema) => {
|
|
2145
|
-
return s.nullable ? z.union([zodSchema, z.null()]) : zodSchema;
|
|
2146
|
-
};
|
|
2147
|
-
if (s.const !== undefined) {
|
|
2148
|
-
return z.literal(s.const);
|
|
2149
|
-
}
|
|
2150
|
-
if (s.enum) {
|
|
2151
|
-
const values = s.enum;
|
|
2152
|
-
return makeNullable(z.enum(values.map(String)));
|
|
2153
|
-
}
|
|
2154
|
-
if (s.anyOf && s.anyOf.length > 0) {
|
|
2155
|
-
const schemas = s.anyOf.map((sub) => jsonSchemaToZod(sub));
|
|
2156
|
-
if (schemas.length === 1)
|
|
2157
|
-
return schemas[0] ?? z.unknown();
|
|
2158
|
-
return z.union([
|
|
2159
|
-
schemas[0] ?? z.unknown(),
|
|
2160
|
-
schemas[1] ?? z.unknown(),
|
|
2161
|
-
...schemas.slice(2)
|
|
2162
|
-
]);
|
|
2163
|
-
}
|
|
2164
|
-
if (s.oneOf && s.oneOf.length > 0) {
|
|
2165
|
-
const schemas = s.oneOf.map((sub) => jsonSchemaToZod(sub));
|
|
2166
|
-
if (schemas.length === 1)
|
|
2167
|
-
return schemas[0] ?? z.unknown();
|
|
2168
|
-
return z.union([
|
|
2169
|
-
schemas[0] ?? z.unknown(),
|
|
2170
|
-
schemas[1] ?? z.unknown(),
|
|
2171
|
-
...schemas.slice(2)
|
|
2172
|
-
]);
|
|
2173
|
-
}
|
|
2174
|
-
if (s.allOf && s.allOf.length > 0) {
|
|
2175
|
-
const schemas = s.allOf.map((sub) => jsonSchemaToZod(sub));
|
|
2176
|
-
return schemas.reduce((acc, curr) => z.intersection(acc, curr));
|
|
2177
|
-
}
|
|
2178
|
-
switch (s.type) {
|
|
2179
|
-
case "string":
|
|
2180
|
-
return makeNullable(buildStringSchema(s));
|
|
2181
|
-
case "number":
|
|
2182
|
-
case "integer":
|
|
2183
|
-
return makeNullable(buildNumberSchema(s));
|
|
2184
|
-
case "boolean":
|
|
2185
|
-
return makeNullable(z.boolean());
|
|
2186
|
-
case "null":
|
|
2187
|
-
return z.null();
|
|
2188
|
-
case "array":
|
|
2189
|
-
return makeNullable(buildArraySchema(s));
|
|
2190
|
-
case "object":
|
|
2191
|
-
return makeNullable(buildObjectSchema(s));
|
|
2192
|
-
default:
|
|
2193
|
-
return z.unknown();
|
|
2194
|
-
}
|
|
2195
|
-
}
|
|
2196
|
-
function buildStringSchema(schema) {
|
|
2197
|
-
let zodSchema = z.string();
|
|
2198
|
-
if (schema.description) {
|
|
2199
|
-
zodSchema = zodSchema.describe(schema.description);
|
|
2200
|
-
}
|
|
2201
|
-
switch (schema.format) {
|
|
2202
|
-
case "email":
|
|
2203
|
-
zodSchema = zodSchema.email();
|
|
2204
|
-
break;
|
|
2205
|
-
case "uri":
|
|
2206
|
-
case "url":
|
|
2207
|
-
zodSchema = zodSchema.url();
|
|
2208
|
-
break;
|
|
2209
|
-
case "uuid":
|
|
2210
|
-
zodSchema = zodSchema.uuid();
|
|
2211
|
-
break;
|
|
2212
|
-
case "date-time":
|
|
2213
|
-
zodSchema = zodSchema.datetime();
|
|
2214
|
-
break;
|
|
2215
|
-
case "date":
|
|
2216
|
-
zodSchema = zodSchema.date();
|
|
2217
|
-
break;
|
|
2218
|
-
}
|
|
2219
|
-
if (schema.minLength !== undefined) {
|
|
2220
|
-
zodSchema = zodSchema.min(schema.minLength);
|
|
2221
|
-
}
|
|
2222
|
-
if (schema.maxLength !== undefined) {
|
|
2223
|
-
zodSchema = zodSchema.max(schema.maxLength);
|
|
2224
|
-
}
|
|
2225
|
-
if (schema.pattern) {
|
|
2226
|
-
zodSchema = zodSchema.regex(new RegExp(schema.pattern));
|
|
2227
|
-
}
|
|
2228
|
-
return zodSchema;
|
|
2229
|
-
}
|
|
2230
|
-
function buildNumberSchema(schema) {
|
|
2231
|
-
let zodSchema = schema.type === "integer" ? z.number().int() : z.number();
|
|
2232
|
-
if (schema.description) {
|
|
2233
|
-
zodSchema = zodSchema.describe(schema.description);
|
|
2234
|
-
}
|
|
2235
|
-
if (schema.minimum !== undefined) {
|
|
2236
|
-
zodSchema = zodSchema.min(schema.minimum);
|
|
2237
|
-
}
|
|
2238
|
-
if (schema.maximum !== undefined) {
|
|
2239
|
-
zodSchema = zodSchema.max(schema.maximum);
|
|
2240
|
-
}
|
|
2241
|
-
return zodSchema;
|
|
2242
|
-
}
|
|
2243
|
-
function buildArraySchema(schema) {
|
|
2244
|
-
const itemsSchema = schema.items ? jsonSchemaToZod(schema.items) : z.unknown();
|
|
2245
|
-
let zodSchema = z.array(itemsSchema);
|
|
2246
|
-
if (schema.description) {
|
|
2247
|
-
zodSchema = zodSchema.describe(schema.description);
|
|
2248
|
-
}
|
|
2249
|
-
return zodSchema;
|
|
2250
|
-
}
|
|
2251
|
-
function buildObjectSchema(schema) {
|
|
2252
|
-
const properties = schema.properties ?? {};
|
|
2253
|
-
const required = new Set(schema.required ?? []);
|
|
2254
|
-
const shape = {};
|
|
2255
|
-
for (const [key, propSchema] of Object.entries(properties)) {
|
|
2256
|
-
const zodProp = jsonSchemaToZod(propSchema);
|
|
2257
|
-
shape[key] = required.has(key) ? zodProp : zodProp.optional();
|
|
2258
|
-
}
|
|
2259
|
-
let zodSchema = z.object(shape);
|
|
2260
|
-
if (schema.description) {
|
|
2261
|
-
zodSchema = zodSchema.describe(schema.description);
|
|
2262
|
-
}
|
|
2263
|
-
return zodSchema;
|
|
2264
|
-
}
|
|
2265
|
-
function jsonSchemaToZodSafe(schema) {
|
|
2266
|
-
if (!schema || Object.keys(schema).length === 0) {
|
|
2267
|
-
return z.object({});
|
|
2268
|
-
}
|
|
2269
|
-
return jsonSchemaToZod(schema);
|
|
2270
|
-
}
|
|
2271
|
-
var init_json_schema_to_zod = () => {};
|
|
2272
|
-
|
|
2273
|
-
// src/tools/tool-adapter.ts
|
|
2274
|
-
import { tool } from "ai";
|
|
2275
|
-
function specToolToAISDKTool(specTool, handler, context = {}) {
|
|
2276
|
-
return tool({
|
|
2277
|
-
description: specTool.description ?? specTool.name,
|
|
2278
|
-
inputSchema: jsonSchemaToZodSafe(specTool.schema),
|
|
2279
|
-
needsApproval: specTool.requiresApproval ?? !specTool.automationSafe,
|
|
2280
|
-
execute: async (input) => {
|
|
2281
|
-
const result = await handler(input, {
|
|
2282
|
-
agentId: context.agentId ?? "unknown",
|
|
2283
|
-
sessionId: context.sessionId ?? "unknown",
|
|
2284
|
-
tenantId: context.tenantId,
|
|
2285
|
-
actorId: context.actorId,
|
|
2286
|
-
metadata: context.metadata,
|
|
2287
|
-
signal: context.signal
|
|
2288
|
-
});
|
|
2289
|
-
return typeof result === "string" ? result : JSON.stringify(result);
|
|
2290
|
-
}
|
|
2291
|
-
});
|
|
2292
|
-
}
|
|
2293
|
-
function specToolsToAISDKTools(specTools, handlers, context = {}) {
|
|
2294
|
-
const tools = {};
|
|
2295
|
-
for (const specTool of specTools) {
|
|
2296
|
-
const handler = handlers.get(specTool.name);
|
|
2297
|
-
if (!handler) {
|
|
2298
|
-
throw new Error(getDefaultI18n().t("error.missingToolHandler", { name: specTool.name }));
|
|
2299
|
-
}
|
|
2300
|
-
tools[specTool.name] = specToolToAISDKTool(specTool, handler, context);
|
|
2301
|
-
}
|
|
2302
|
-
return tools;
|
|
2303
|
-
}
|
|
2304
|
-
function createToolHandler(handler) {
|
|
2305
|
-
return async (input, context) => {
|
|
2306
|
-
return handler(input, context);
|
|
2307
|
-
};
|
|
2308
|
-
}
|
|
2309
|
-
function buildToolHandlers(handlersObj) {
|
|
2310
|
-
return new Map(Object.entries(handlersObj));
|
|
2311
|
-
}
|
|
2312
|
-
var init_tool_adapter = __esm(() => {
|
|
2313
|
-
init_json_schema_to_zod();
|
|
2314
|
-
init_i18n();
|
|
2315
|
-
});
|
|
2316
|
-
|
|
2317
|
-
// src/tools/knowledge-tool.ts
|
|
2318
|
-
import { tool as tool2 } from "ai";
|
|
2319
|
-
import * as z2 from "zod";
|
|
2320
|
-
function createKnowledgeQueryTool(retriever, knowledgeRefs, locale) {
|
|
2321
|
-
const i18n = createAgentI18n(locale);
|
|
2322
|
-
const optionalSpaces = knowledgeRefs.filter((k) => !k.required).map((k) => k.key).filter((key) => retriever.supportsSpace(key));
|
|
2323
|
-
if (optionalSpaces.length === 0) {
|
|
2324
|
-
return null;
|
|
2325
|
-
}
|
|
2326
|
-
const spaceDescriptions = knowledgeRefs.filter((k) => !k.required && retriever.supportsSpace(k.key)).map((k) => `- ${k.key}: ${k.instructions ?? i18n.t("tool.knowledge.spaceDefault")}`).join(`
|
|
2327
|
-
`);
|
|
2328
|
-
return tool2({
|
|
2329
|
-
description: `${i18n.t("tool.knowledge.description")}
|
|
2330
|
-
|
|
2331
|
-
${i18n.t("tool.knowledge.availableSpaces")}
|
|
2332
|
-
${spaceDescriptions}`,
|
|
2333
|
-
inputSchema: z2.object({
|
|
2334
|
-
query: z2.string().describe(i18n.t("tool.knowledge.param.query")),
|
|
2335
|
-
spaceKey: z2.enum(optionalSpaces).optional().describe(i18n.t("tool.knowledge.param.spaceKey")),
|
|
2336
|
-
topK: z2.number().optional().default(5).describe(i18n.t("tool.knowledge.param.topK"))
|
|
2337
|
-
}),
|
|
2338
|
-
execute: async ({ query, spaceKey, topK }) => {
|
|
2339
|
-
const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;
|
|
2340
|
-
const allResults = [];
|
|
2341
|
-
for (const space of spacesToSearch) {
|
|
2342
|
-
try {
|
|
2343
|
-
const results = await retriever.retrieve(query, {
|
|
2344
|
-
spaceKey: space,
|
|
2345
|
-
topK: topK ?? 5
|
|
2346
|
-
});
|
|
2347
|
-
for (const result of results) {
|
|
2348
|
-
allResults.push({
|
|
2349
|
-
space,
|
|
2350
|
-
content: result.content,
|
|
2351
|
-
score: result.score
|
|
2352
|
-
});
|
|
2353
|
-
}
|
|
2354
|
-
} catch (error) {
|
|
2355
|
-
console.warn(i18n.t("log.knowledge.queryFailed", { space }), error);
|
|
2356
|
-
}
|
|
2357
|
-
}
|
|
2358
|
-
if (allResults.length === 0) {
|
|
2359
|
-
return i18n.t("tool.knowledge.noResults");
|
|
2360
|
-
}
|
|
2361
|
-
allResults.sort((a, b) => b.score - a.score);
|
|
2362
|
-
const topResults = allResults.slice(0, topK ?? 5);
|
|
2363
|
-
return topResults.map((r, i) => `${i18n.t("tool.knowledge.sourceLabel", { index: i + 1, space: r.space, score: (r.score * 100).toFixed(0) })}
|
|
2364
|
-
${r.content}`).join(`
|
|
2365
|
-
|
|
2366
|
-
---
|
|
2367
|
-
|
|
2368
|
-
`);
|
|
2369
|
-
}
|
|
2370
|
-
});
|
|
2371
|
-
}
|
|
2372
|
-
var init_knowledge_tool = __esm(() => {
|
|
2373
|
-
init_i18n();
|
|
2374
|
-
});
|
|
2375
|
-
|
|
2376
|
-
// src/knowledge/injector.ts
|
|
2377
|
-
async function injectStaticKnowledge(instructions, knowledgeRefs, retriever, locale) {
|
|
2378
|
-
if (!retriever)
|
|
2379
|
-
return instructions;
|
|
2380
|
-
const requiredRefs = knowledgeRefs.filter((ref) => ref.required);
|
|
2381
|
-
if (requiredRefs.length === 0)
|
|
2382
|
-
return instructions;
|
|
2383
|
-
const i18n = createAgentI18n(locale);
|
|
2384
|
-
const blocks = [];
|
|
2385
|
-
for (const ref of requiredRefs) {
|
|
2386
|
-
if (!retriever.supportsSpace(ref.key)) {
|
|
2387
|
-
console.warn(i18n.t("log.knowledge.spaceNotAvailable", { key: ref.key }));
|
|
2388
|
-
continue;
|
|
2389
|
-
}
|
|
2390
|
-
try {
|
|
2391
|
-
const content = await retriever.getStatic(ref.key);
|
|
2392
|
-
if (content) {
|
|
2393
|
-
const header = ref.instructions ? `## ${ref.key}
|
|
2394
|
-
${ref.instructions}` : `## ${ref.key}`;
|
|
2395
|
-
blocks.push(`${header}
|
|
2396
|
-
|
|
2397
|
-
${content}`);
|
|
2398
|
-
}
|
|
2399
|
-
} catch (error) {
|
|
2400
|
-
console.warn(i18n.t("log.knowledge.loadFailed", { key: ref.key }), error);
|
|
2401
|
-
}
|
|
2402
|
-
}
|
|
2403
|
-
if (blocks.length === 0)
|
|
2404
|
-
return instructions;
|
|
2405
|
-
return `${instructions}
|
|
2406
|
-
|
|
2407
|
-
---
|
|
2408
|
-
|
|
2409
|
-
# ${i18n.t("knowledge.header")}
|
|
2410
|
-
|
|
2411
|
-
${i18n.t("knowledge.description")}
|
|
2412
|
-
|
|
2413
|
-
${blocks.join(`
|
|
2414
|
-
|
|
2415
|
-
---
|
|
2416
|
-
|
|
2417
|
-
`)}`;
|
|
2418
|
-
}
|
|
2419
|
-
function createKnowledgeInjector(retriever, locale) {
|
|
2420
|
-
return {
|
|
2421
|
-
inject: (instructions, knowledgeRefs) => injectStaticKnowledge(instructions, knowledgeRefs, retriever, locale),
|
|
2422
|
-
hasSpace: (spaceKey) => retriever?.supportsSpace(spaceKey) ?? false,
|
|
2423
|
-
listSpaces: () => retriever?.listSpaces() ?? []
|
|
2424
|
-
};
|
|
2425
|
-
}
|
|
2426
|
-
var init_injector = __esm(() => {
|
|
2427
|
-
init_i18n();
|
|
2428
|
-
});
|
|
2429
|
-
|
|
2430
|
-
// src/session/store.ts
|
|
2431
|
-
class InMemorySessionStore {
|
|
2432
|
-
sessions = new Map;
|
|
2433
|
-
async get(sessionId) {
|
|
2434
|
-
return this.sessions.get(sessionId) ?? null;
|
|
2435
|
-
}
|
|
2436
|
-
async create(session) {
|
|
2437
|
-
const now = new Date;
|
|
2438
|
-
const fullSession = {
|
|
2439
|
-
...session,
|
|
2440
|
-
createdAt: now,
|
|
2441
|
-
updatedAt: now
|
|
2442
|
-
};
|
|
2443
|
-
this.sessions.set(session.sessionId, fullSession);
|
|
2444
|
-
return fullSession;
|
|
2445
|
-
}
|
|
2446
|
-
async appendStep(sessionId, step) {
|
|
2447
|
-
const session = this.sessions.get(sessionId);
|
|
2448
|
-
if (session) {
|
|
2449
|
-
session.steps.push(step);
|
|
2450
|
-
session.updatedAt = new Date;
|
|
2451
|
-
}
|
|
2452
|
-
}
|
|
2453
|
-
async appendMessage(sessionId, message) {
|
|
2454
|
-
const session = this.sessions.get(sessionId);
|
|
2455
|
-
if (session) {
|
|
2456
|
-
session.messages.push(message);
|
|
2457
|
-
session.updatedAt = new Date;
|
|
2458
|
-
}
|
|
2459
|
-
}
|
|
2460
|
-
async update(sessionId, updates) {
|
|
2461
|
-
const session = this.sessions.get(sessionId);
|
|
2462
|
-
if (session) {
|
|
2463
|
-
Object.assign(session, updates, { updatedAt: new Date });
|
|
2464
|
-
}
|
|
2465
|
-
}
|
|
2466
|
-
async delete(sessionId) {
|
|
2467
|
-
return this.sessions.delete(sessionId);
|
|
2468
|
-
}
|
|
2469
|
-
async listByAgent(agentId, limit = 100) {
|
|
2470
|
-
const results = [];
|
|
2471
|
-
for (const session of this.sessions.values()) {
|
|
2472
|
-
if (session.agentId === agentId) {
|
|
2473
|
-
results.push(session);
|
|
2474
|
-
if (results.length >= limit)
|
|
2475
|
-
break;
|
|
2476
|
-
}
|
|
2477
|
-
}
|
|
2478
|
-
return results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
2479
|
-
}
|
|
2480
|
-
async listByTenant(tenantId, limit = 100) {
|
|
2481
|
-
const results = [];
|
|
2482
|
-
for (const session of this.sessions.values()) {
|
|
2483
|
-
if (session.tenantId === tenantId) {
|
|
2484
|
-
results.push(session);
|
|
2485
|
-
if (results.length >= limit)
|
|
2486
|
-
break;
|
|
2487
|
-
}
|
|
2488
|
-
}
|
|
2489
|
-
return results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
2490
|
-
}
|
|
2491
|
-
clear() {
|
|
2492
|
-
this.sessions.clear();
|
|
2493
|
-
}
|
|
2494
|
-
}
|
|
2495
|
-
function createInMemorySessionStore() {
|
|
2496
|
-
return new InMemorySessionStore;
|
|
2497
|
-
}
|
|
2498
|
-
function generateSessionId() {
|
|
2499
|
-
return `sess_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
2500
|
-
}
|
|
2501
|
-
|
|
2502
|
-
// src/telemetry/adapter.ts
|
|
2503
|
-
function parseAgentId(agentId) {
|
|
2504
|
-
const match = agentId.match(/^(.+)\.v(\s+)$/);
|
|
2505
|
-
if (match) {
|
|
2506
|
-
return { name: match[1], version: match[2] };
|
|
2507
|
-
}
|
|
2508
|
-
return { name: agentId, version: "1.0.0" };
|
|
2509
|
-
}
|
|
2510
|
-
async function trackAgentStep(collector, agentId, step, durationMs) {
|
|
2511
|
-
const { name, version } = parseAgentId(agentId);
|
|
2512
|
-
for (const toolCall of step.toolCalls ?? []) {
|
|
2513
|
-
const toolSample = {
|
|
2514
|
-
operation: { name: `${name}.${toolCall.toolName}`, version },
|
|
2515
|
-
durationMs: durationMs ?? 0,
|
|
2516
|
-
success: step.toolResults?.some((r) => r.toolCallId === toolCall.toolCallId && r.output !== undefined) ?? false,
|
|
2517
|
-
timestamp: new Date,
|
|
2518
|
-
metadata: {
|
|
2519
|
-
agentId,
|
|
2520
|
-
toolName: toolCall.toolName,
|
|
2521
|
-
finishReason: step.finishReason
|
|
2522
|
-
}
|
|
2523
|
-
};
|
|
2524
|
-
await collector.collect(toolSample);
|
|
2525
|
-
}
|
|
2526
|
-
const stepSample = {
|
|
2527
|
-
operation: { name, version },
|
|
2528
|
-
durationMs: durationMs ?? 0,
|
|
2529
|
-
success: step.finishReason !== "error",
|
|
2530
|
-
timestamp: new Date,
|
|
2531
|
-
metadata: {
|
|
2532
|
-
agentId,
|
|
2533
|
-
finishReason: step.finishReason,
|
|
2534
|
-
tokenUsage: step.usage,
|
|
2535
|
-
toolCallCount: step.toolCalls?.length ?? 0
|
|
2536
|
-
}
|
|
2537
|
-
};
|
|
2538
|
-
await collector.collect(stepSample);
|
|
2539
|
-
}
|
|
2540
|
-
|
|
2541
|
-
class InMemoryTelemetryCollector {
|
|
2542
|
-
samples = [];
|
|
2543
|
-
async collect(sample) {
|
|
2544
|
-
this.samples.push(sample);
|
|
2545
|
-
}
|
|
2546
|
-
getSamples() {
|
|
2547
|
-
return [...this.samples];
|
|
2548
|
-
}
|
|
2549
|
-
getSamplesForOperation(operationName) {
|
|
2550
|
-
return this.samples.filter((s) => s.operation.name === operationName);
|
|
2551
|
-
}
|
|
2552
|
-
clear() {
|
|
2553
|
-
this.samples.length = 0;
|
|
2554
|
-
}
|
|
2555
|
-
}
|
|
2556
|
-
function createInMemoryTelemetryCollector() {
|
|
2557
|
-
return new InMemoryTelemetryCollector;
|
|
2558
|
-
}
|
|
2559
|
-
var noopTelemetryCollector;
|
|
2560
|
-
var init_adapter = __esm(() => {
|
|
2561
|
-
noopTelemetryCollector = {
|
|
2562
|
-
collect: async () => {}
|
|
2563
|
-
};
|
|
2564
|
-
});
|
|
2565
|
-
|
|
2566
|
-
// src/telemetry/posthog.ts
|
|
2567
|
-
var exports_posthog = {};
|
|
2568
|
-
__export(exports_posthog, {
|
|
2569
|
-
createPostHogTracedModel: () => createPostHogTracedModel,
|
|
2570
|
-
createPostHogTelemetryCollector: () => createPostHogTelemetryCollector,
|
|
2571
|
-
createCompositeTelemetryCollector: () => createCompositeTelemetryCollector,
|
|
2572
|
-
PostHogTelemetryCollector: () => PostHogTelemetryCollector,
|
|
2573
|
-
CompositeTelemetryCollector: () => CompositeTelemetryCollector
|
|
2574
|
-
});
|
|
2575
|
-
async function createPostHogTracedModel(model, config, overrides) {
|
|
2576
|
-
const { withTracing } = await importPostHogAI();
|
|
2577
|
-
const phClient = await resolvePostHogClient(config);
|
|
2578
|
-
const tracingOptions = {
|
|
2579
|
-
...config.defaults,
|
|
2580
|
-
...overrides
|
|
2581
|
-
};
|
|
2582
|
-
return withTracing(model, phClient, tracingOptions);
|
|
2583
|
-
}
|
|
2584
|
-
|
|
2585
|
-
class PostHogTelemetryCollector {
|
|
2586
|
-
phClient;
|
|
2587
|
-
config;
|
|
2588
|
-
initPromise;
|
|
2589
|
-
constructor(config) {
|
|
2590
|
-
this.config = config;
|
|
2591
|
-
this.phClient = config.client;
|
|
2592
|
-
}
|
|
2593
|
-
async collect(sample) {
|
|
2594
|
-
const client = await this.getClient();
|
|
2595
|
-
const distinctId = this.config.defaults?.posthogDistinctId ?? sample.metadata?.["actorId"] ?? "system";
|
|
2596
|
-
client.capture({
|
|
2597
|
-
distinctId,
|
|
2598
|
-
event: "$ai_generation",
|
|
2599
|
-
properties: {
|
|
2600
|
-
$ai_model: sample.operation.name,
|
|
2601
|
-
$ai_provider: "contractspec",
|
|
2602
|
-
$ai_latency: sample.durationMs / 1000,
|
|
2603
|
-
$ai_is_error: !sample.success,
|
|
2604
|
-
$ai_trace_id: this.config.defaults?.posthogTraceId,
|
|
2605
|
-
...sample.metadata?.["tokenUsage"] ? mapTokenUsage(sample.metadata["tokenUsage"]) : {},
|
|
2606
|
-
...this.config.defaults?.posthogProperties,
|
|
2607
|
-
contractspec_operation: sample.operation.name,
|
|
2608
|
-
contractspec_version: sample.operation.version,
|
|
2609
|
-
contractspec_agent_id: sample.metadata?.["agentId"],
|
|
2610
|
-
contractspec_finish_reason: sample.metadata?.["finishReason"],
|
|
2611
|
-
contractspec_tool_count: sample.metadata?.["toolCallCount"]
|
|
2612
|
-
},
|
|
2613
|
-
groups: this.config.defaults?.posthogGroups
|
|
2614
|
-
});
|
|
2615
|
-
}
|
|
2616
|
-
async shutdown() {
|
|
2617
|
-
if (this.phClient?.shutdown) {
|
|
2618
|
-
await this.phClient.shutdown();
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
async getClient() {
|
|
2622
|
-
if (this.phClient)
|
|
2623
|
-
return this.phClient;
|
|
2624
|
-
if (!this.initPromise) {
|
|
2625
|
-
this.initPromise = resolvePostHogClient(this.config).then((client) => {
|
|
2626
|
-
this.phClient = client;
|
|
2627
|
-
return client;
|
|
2628
|
-
});
|
|
2629
|
-
}
|
|
2630
|
-
return this.initPromise;
|
|
2631
|
-
}
|
|
2632
|
-
}
|
|
2633
|
-
function createPostHogTelemetryCollector(config) {
|
|
2634
|
-
return new PostHogTelemetryCollector(config);
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
class CompositeTelemetryCollector {
|
|
2638
|
-
collectors;
|
|
2639
|
-
constructor(collectors) {
|
|
2640
|
-
this.collectors = collectors;
|
|
2641
|
-
}
|
|
2642
|
-
async collect(sample) {
|
|
2643
|
-
await Promise.all(this.collectors.map((c) => c.collect(sample)));
|
|
2644
|
-
}
|
|
2645
|
-
}
|
|
2646
|
-
function createCompositeTelemetryCollector(collectors) {
|
|
2647
|
-
return new CompositeTelemetryCollector(collectors);
|
|
2648
|
-
}
|
|
2649
|
-
async function importPostHogAI() {
|
|
2650
|
-
try {
|
|
2651
|
-
return await import("@posthog/ai");
|
|
2652
|
-
} catch {
|
|
2653
|
-
throw new Error("PostHog LLM Analytics requires @posthog/ai to be installed. Run: npm install @posthog/ai posthog-node");
|
|
2654
|
-
}
|
|
2655
|
-
}
|
|
2656
|
-
async function resolvePostHogClient(config) {
|
|
2657
|
-
if (config.client)
|
|
2658
|
-
return config.client;
|
|
2659
|
-
if (!config.apiKey) {
|
|
2660
|
-
throw new Error("PostHog LLM Analytics requires either a client instance or an apiKey.");
|
|
2661
|
-
}
|
|
2662
|
-
try {
|
|
2663
|
-
const { PostHog } = await import("posthog-node");
|
|
2664
|
-
return new PostHog(config.apiKey, {
|
|
2665
|
-
host: config.host ?? "https://us.i.posthog.com"
|
|
2666
|
-
});
|
|
2667
|
-
} catch {
|
|
2668
|
-
throw new Error("PostHog LLM Analytics requires posthog-node to be installed. Run: npm install posthog-node");
|
|
2669
|
-
}
|
|
2670
|
-
}
|
|
2671
|
-
function mapTokenUsage(usage) {
|
|
2672
|
-
return {
|
|
2673
|
-
$ai_input_tokens: usage["promptTokens"],
|
|
2674
|
-
$ai_output_tokens: usage["completionTokens"]
|
|
2675
|
-
};
|
|
2676
|
-
}
|
|
2677
|
-
|
|
2678
|
-
// src/agent/contract-spec-agent.ts
|
|
2679
|
-
var exports_contract_spec_agent = {};
|
|
2680
|
-
__export(exports_contract_spec_agent, {
|
|
2681
|
-
ContractSpecAgent: () => ContractSpecAgent
|
|
2682
|
-
});
|
|
2683
|
-
import {
|
|
2684
|
-
Experimental_Agent as ToolLoopAgent,
|
|
2685
|
-
stepCountIs
|
|
2686
|
-
} from "ai";
|
|
2687
|
-
import * as z3 from "zod";
|
|
2688
|
-
|
|
2689
|
-
class ContractSpecAgent {
|
|
2690
|
-
version = "agent-v1";
|
|
2691
|
-
id;
|
|
2692
|
-
spec;
|
|
2693
|
-
tools;
|
|
2694
|
-
inner;
|
|
2695
|
-
config;
|
|
2696
|
-
instructions;
|
|
2697
|
-
constructor(config, instructions, tools) {
|
|
2698
|
-
this.config = config;
|
|
2699
|
-
this.spec = config.spec;
|
|
2700
|
-
this.id = agentKey(config.spec.meta);
|
|
2701
|
-
this.tools = tools;
|
|
2702
|
-
this.instructions = instructions;
|
|
2703
|
-
this.inner = new ToolLoopAgent({
|
|
2704
|
-
model: config.model,
|
|
2705
|
-
instructions,
|
|
2706
|
-
tools,
|
|
2707
|
-
stopWhen: stepCountIs(config.spec.maxSteps ?? 10),
|
|
2708
|
-
callOptionsSchema: ContractSpecCallOptionsSchema,
|
|
2709
|
-
onStepFinish: async (step) => {
|
|
2710
|
-
await this.handleStepFinish(step);
|
|
2711
|
-
}
|
|
2712
|
-
});
|
|
2713
|
-
}
|
|
2714
|
-
static async create(config) {
|
|
2715
|
-
let effectiveConfig = config;
|
|
2716
|
-
if (config.posthogConfig) {
|
|
2717
|
-
const { createPostHogTracedModel: createPostHogTracedModel2 } = await Promise.resolve().then(() => exports_posthog);
|
|
2718
|
-
const tracedModel = await createPostHogTracedModel2(config.model, config.posthogConfig, config.posthogConfig.tracingOptions);
|
|
2719
|
-
effectiveConfig = { ...config, model: tracedModel };
|
|
2720
|
-
}
|
|
2721
|
-
const instructions = await injectStaticKnowledge(effectiveConfig.spec.instructions, effectiveConfig.spec.knowledge ?? [], effectiveConfig.knowledgeRetriever);
|
|
2722
|
-
const specTools = specToolsToAISDKTools(effectiveConfig.spec.tools, effectiveConfig.toolHandlers, { agentId: agentKey(effectiveConfig.spec.meta) });
|
|
2723
|
-
const knowledgeTool = effectiveConfig.knowledgeRetriever ? createKnowledgeQueryTool(effectiveConfig.knowledgeRetriever, effectiveConfig.spec.knowledge ?? []) : null;
|
|
2724
|
-
const tools = {
|
|
2725
|
-
...specTools,
|
|
2726
|
-
...knowledgeTool ? { query_knowledge: knowledgeTool } : {},
|
|
2727
|
-
...effectiveConfig.additionalTools ?? {}
|
|
2728
|
-
};
|
|
2729
|
-
return new ContractSpecAgent(effectiveConfig, instructions, tools);
|
|
2730
|
-
}
|
|
2731
|
-
async generate(params) {
|
|
2732
|
-
const sessionId = params.options?.sessionId ?? generateSessionId();
|
|
2733
|
-
if (this.config.sessionStore) {
|
|
2734
|
-
const existing = await this.config.sessionStore.get(sessionId);
|
|
2735
|
-
if (!existing) {
|
|
2736
|
-
await this.config.sessionStore.create({
|
|
2737
|
-
sessionId,
|
|
2738
|
-
agentId: this.id,
|
|
2739
|
-
tenantId: params.options?.tenantId,
|
|
2740
|
-
actorId: params.options?.actorId,
|
|
2741
|
-
status: "running",
|
|
2742
|
-
messages: [],
|
|
2743
|
-
steps: [],
|
|
2744
|
-
metadata: params.options?.metadata
|
|
2745
|
-
});
|
|
2746
|
-
}
|
|
2747
|
-
}
|
|
2748
|
-
const prompt = params.systemOverride ? `${this.instructions}
|
|
2749
|
-
|
|
2750
|
-
${params.systemOverride}
|
|
2751
|
-
|
|
2752
|
-
${params.prompt}` : params.prompt;
|
|
2753
|
-
const result = await this.inner.generate({
|
|
2754
|
-
prompt,
|
|
2755
|
-
abortSignal: params.signal,
|
|
2756
|
-
options: {
|
|
2757
|
-
tenantId: params.options?.tenantId,
|
|
2758
|
-
actorId: params.options?.actorId,
|
|
2759
|
-
sessionId,
|
|
2760
|
-
metadata: params.options?.metadata
|
|
2761
|
-
}
|
|
2762
|
-
});
|
|
2763
|
-
if (this.config.sessionStore) {
|
|
2764
|
-
await this.config.sessionStore.update(sessionId, {
|
|
2765
|
-
status: "completed"
|
|
2766
|
-
});
|
|
2767
|
-
}
|
|
2768
|
-
return {
|
|
2769
|
-
text: result.text,
|
|
2770
|
-
steps: result.steps,
|
|
2771
|
-
toolCalls: result.toolCalls.map((tc) => ({
|
|
2772
|
-
type: "tool-call",
|
|
2773
|
-
toolCallId: tc.toolCallId,
|
|
2774
|
-
toolName: tc.toolName,
|
|
2775
|
-
args: "args" in tc ? tc.args : ("input" in tc) ? tc.input : undefined
|
|
2776
|
-
})),
|
|
2777
|
-
toolResults: result.toolResults.map((tr) => ({
|
|
2778
|
-
type: "tool-result",
|
|
2779
|
-
toolCallId: tr.toolCallId,
|
|
2780
|
-
toolName: tr.toolName,
|
|
2781
|
-
output: tr.output
|
|
2782
|
-
})),
|
|
2783
|
-
finishReason: result.finishReason,
|
|
2784
|
-
usage: result.usage
|
|
2785
|
-
};
|
|
2786
|
-
}
|
|
2787
|
-
async stream(params) {
|
|
2788
|
-
const sessionId = params.options?.sessionId ?? generateSessionId();
|
|
2789
|
-
const prompt = params.systemOverride ? `${this.instructions}
|
|
2790
|
-
|
|
2791
|
-
${params.systemOverride}
|
|
2792
|
-
|
|
2793
|
-
${params.prompt}` : params.prompt;
|
|
2794
|
-
return this.inner.stream({
|
|
2795
|
-
prompt,
|
|
2796
|
-
abortSignal: params.signal,
|
|
2797
|
-
options: {
|
|
2798
|
-
tenantId: params.options?.tenantId,
|
|
2799
|
-
actorId: params.options?.actorId,
|
|
2800
|
-
sessionId,
|
|
2801
|
-
metadata: params.options?.metadata
|
|
2802
|
-
}
|
|
2803
|
-
});
|
|
2804
|
-
}
|
|
2805
|
-
async handleStepFinish(step) {
|
|
2806
|
-
const sessionId = step.options?.sessionId;
|
|
2807
|
-
if (sessionId && this.config.sessionStore) {
|
|
2808
|
-
await this.config.sessionStore.appendStep(sessionId, step);
|
|
2809
|
-
}
|
|
2810
|
-
if (this.config.telemetryCollector) {
|
|
2811
|
-
await trackAgentStep(this.config.telemetryCollector, this.id, step);
|
|
2812
|
-
}
|
|
2813
|
-
}
|
|
2814
|
-
}
|
|
2815
|
-
var ContractSpecCallOptionsSchema;
|
|
2816
|
-
var init_contract_spec_agent = __esm(() => {
|
|
2817
|
-
init_spec();
|
|
2818
|
-
init_tool_adapter();
|
|
2819
|
-
init_knowledge_tool();
|
|
2820
|
-
init_injector();
|
|
2821
|
-
init_adapter();
|
|
2822
|
-
ContractSpecCallOptionsSchema = z3.object({
|
|
2823
|
-
tenantId: z3.string().optional(),
|
|
2824
|
-
actorId: z3.string().optional(),
|
|
2825
|
-
sessionId: z3.string().optional(),
|
|
2826
|
-
metadata: z3.record(z3.string(), z3.unknown()).optional()
|
|
2827
|
-
});
|
|
2828
|
-
});
|
|
2829
|
-
|
|
2830
|
-
// src/providers/types.ts
|
|
2831
|
-
var ExternalProviderError, ProviderNotAvailableError, ProviderExecutionError, ContextCreationError;
|
|
2832
|
-
var init_types = __esm(() => {
|
|
2833
|
-
ExternalProviderError = class ExternalProviderError extends Error {
|
|
2834
|
-
provider;
|
|
2835
|
-
code;
|
|
2836
|
-
cause;
|
|
2837
|
-
constructor(message, provider, code, cause) {
|
|
2838
|
-
super(message);
|
|
2839
|
-
this.provider = provider;
|
|
2840
|
-
this.code = code;
|
|
2841
|
-
this.cause = cause;
|
|
2842
|
-
this.name = "ExternalProviderError";
|
|
2843
|
-
}
|
|
2844
|
-
};
|
|
2845
|
-
ProviderNotAvailableError = class ProviderNotAvailableError extends ExternalProviderError {
|
|
2846
|
-
constructor(provider, reason) {
|
|
2847
|
-
super(`Provider '${provider}' is not available${reason ? `: ${reason}` : ""}`, provider, "PROVIDER_NOT_AVAILABLE");
|
|
2848
|
-
this.name = "ProviderNotAvailableError";
|
|
2849
|
-
}
|
|
2850
|
-
};
|
|
2851
|
-
ProviderExecutionError = class ProviderExecutionError extends ExternalProviderError {
|
|
2852
|
-
constructor(provider, message, cause) {
|
|
2853
|
-
super(message, provider, "EXECUTION_FAILED", cause);
|
|
2854
|
-
this.name = "ProviderExecutionError";
|
|
2855
|
-
}
|
|
2856
|
-
};
|
|
2857
|
-
ContextCreationError = class ContextCreationError extends ExternalProviderError {
|
|
2858
|
-
constructor(provider, message, cause) {
|
|
2859
|
-
super(message, provider, "CONTEXT_CREATION_FAILED", cause);
|
|
2860
|
-
this.name = "ContextCreationError";
|
|
2861
|
-
}
|
|
2862
|
-
};
|
|
2863
|
-
});
|
|
2864
|
-
|
|
2865
|
-
// src/providers/claude-agent-sdk/tool-bridge.ts
|
|
2866
|
-
function specToolToClaudeAgentTool(tool3, handler, context) {
|
|
2867
|
-
return {
|
|
2868
|
-
name: tool3.name,
|
|
2869
|
-
description: tool3.description ?? getDefaultI18n().t("tool.fallbackDescription", { name: tool3.name }),
|
|
2870
|
-
input_schema: normalizeSchema(tool3.schema),
|
|
2871
|
-
requires_confirmation: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
2872
|
-
execute: async (input) => {
|
|
2873
|
-
const fullContext = {
|
|
2874
|
-
agentId: context.agentId ?? "unknown",
|
|
2875
|
-
sessionId: context.sessionId ?? "unknown",
|
|
2876
|
-
tenantId: context.tenantId,
|
|
2877
|
-
actorId: context.actorId,
|
|
2878
|
-
metadata: context.metadata,
|
|
2879
|
-
signal: context.signal
|
|
2880
|
-
};
|
|
2881
|
-
return handler(input, fullContext);
|
|
2882
|
-
}
|
|
2883
|
-
};
|
|
2884
|
-
}
|
|
2885
|
-
function specToolsToClaudeAgentTools(tools, handlers, context) {
|
|
2886
|
-
return tools.filter((tool3) => handlers.has(tool3.name)).map((tool3) => {
|
|
2887
|
-
const handler = handlers.get(tool3.name);
|
|
2888
|
-
if (!handler) {
|
|
2889
|
-
throw new Error(getDefaultI18n().t("error.handlerNotFoundForTool", {
|
|
2890
|
-
name: tool3.name
|
|
2891
|
-
}));
|
|
2892
|
-
}
|
|
2893
|
-
return specToolToClaudeAgentTool(tool3, handler, context);
|
|
2894
|
-
});
|
|
2895
|
-
}
|
|
2896
|
-
function claudeAgentToolToSpecTool(claudeTool, execute) {
|
|
2897
|
-
const config = {
|
|
2898
|
-
name: claudeTool.name,
|
|
2899
|
-
description: claudeTool.description,
|
|
2900
|
-
schema: claudeTool.input_schema,
|
|
2901
|
-
requiresApproval: claudeTool.requires_confirmation,
|
|
2902
|
-
automationSafe: !claudeTool.requires_confirmation
|
|
2903
|
-
};
|
|
2904
|
-
const handler = execute ? async (input, _ctx) => String(await execute(input)) : undefined;
|
|
2905
|
-
return { config, handler };
|
|
2906
|
-
}
|
|
2907
|
-
function claudeAgentToolsToSpecTools(claudeTools) {
|
|
2908
|
-
const configs = [];
|
|
2909
|
-
const handlers = new Map;
|
|
2910
|
-
for (const claudeTool of claudeTools) {
|
|
2911
|
-
const { config, handler } = claudeAgentToolToSpecTool(claudeTool, claudeTool.execute);
|
|
2912
|
-
configs.push(config);
|
|
2913
|
-
if (handler) {
|
|
2914
|
-
handlers.set(config.name, handler);
|
|
2915
|
-
}
|
|
2916
|
-
}
|
|
2917
|
-
return { configs, handlers };
|
|
2918
|
-
}
|
|
2919
|
-
function specToolToExternalTool(tool3, handler, context) {
|
|
2920
|
-
return {
|
|
2921
|
-
name: tool3.name,
|
|
2922
|
-
description: tool3.description ?? getDefaultI18n().t("tool.fallbackDescription", { name: tool3.name }),
|
|
2923
|
-
inputSchema: tool3.schema ?? { type: "object" },
|
|
2924
|
-
requiresApproval: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
2925
|
-
execute: handler ? async (input) => {
|
|
2926
|
-
const fullContext = {
|
|
2927
|
-
agentId: context?.agentId ?? "unknown",
|
|
2928
|
-
sessionId: context?.sessionId ?? "unknown",
|
|
2929
|
-
tenantId: context?.tenantId,
|
|
2930
|
-
actorId: context?.actorId,
|
|
2931
|
-
metadata: context?.metadata,
|
|
2932
|
-
signal: context?.signal
|
|
2933
|
-
};
|
|
2934
|
-
return handler(input, fullContext);
|
|
2935
|
-
} : undefined
|
|
2936
|
-
};
|
|
2937
|
-
}
|
|
2938
|
-
function normalizeSchema(schema) {
|
|
2939
|
-
if (!schema) {
|
|
2940
|
-
return { type: "object" };
|
|
2941
|
-
}
|
|
2942
|
-
if (schema.type === "object") {
|
|
2943
|
-
return schema;
|
|
2944
|
-
}
|
|
2945
|
-
return {
|
|
2946
|
-
type: "object",
|
|
2947
|
-
properties: {
|
|
2948
|
-
value: schema
|
|
2949
|
-
},
|
|
2950
|
-
required: ["value"]
|
|
2951
|
-
};
|
|
2952
|
-
}
|
|
2953
|
-
function extractToolCalls(response) {
|
|
2954
|
-
if (!response.content) {
|
|
2955
|
-
return [];
|
|
2956
|
-
}
|
|
2957
|
-
return response.content.filter((block) => block.type === "tool_use").map((block) => ({
|
|
2958
|
-
toolCallId: block.id ?? "",
|
|
2959
|
-
toolName: block.name ?? "",
|
|
2960
|
-
args: block.input
|
|
2961
|
-
}));
|
|
2962
|
-
}
|
|
2963
|
-
var init_tool_bridge = __esm(() => {
|
|
2964
|
-
init_i18n();
|
|
2965
|
-
});
|
|
2966
|
-
|
|
2967
|
-
// src/providers/claude-agent-sdk/session-bridge.ts
|
|
2968
|
-
function toClaudeAgentSession(state) {
|
|
2969
|
-
const messages = [];
|
|
2970
|
-
for (const msg of state.messages) {
|
|
2971
|
-
if (msg.role === "user" || msg.role === "assistant") {
|
|
2972
|
-
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
|
|
2973
|
-
messages.push({
|
|
2974
|
-
role: msg.role,
|
|
2975
|
-
content
|
|
2976
|
-
});
|
|
2977
|
-
}
|
|
2978
|
-
}
|
|
2979
|
-
return {
|
|
2980
|
-
sessionId: state.sessionId,
|
|
2981
|
-
messages,
|
|
2982
|
-
metadata: {
|
|
2983
|
-
agentId: state.agentId,
|
|
2984
|
-
tenantId: state.tenantId,
|
|
2985
|
-
actorId: state.actorId
|
|
2986
|
-
}
|
|
2987
|
-
};
|
|
2988
|
-
}
|
|
2989
|
-
function createClaudeAgentSession(options) {
|
|
2990
|
-
return {
|
|
2991
|
-
sessionId: options?.sessionId,
|
|
2992
|
-
messages: [],
|
|
2993
|
-
metadata: {
|
|
2994
|
-
tenantId: options?.tenantId,
|
|
2995
|
-
actorId: options?.actorId,
|
|
2996
|
-
...options?.metadata
|
|
2997
|
-
}
|
|
2998
|
-
};
|
|
2999
|
-
}
|
|
3000
|
-
function createEmptyClaudeSession() {
|
|
3001
|
-
return createClaudeAgentSession();
|
|
3002
|
-
}
|
|
3003
|
-
function buildClaudeAgentContext(options) {
|
|
3004
|
-
return {
|
|
3005
|
-
tenantId: options?.tenantId,
|
|
3006
|
-
actorId: options?.actorId,
|
|
3007
|
-
sessionId: options?.sessionId,
|
|
3008
|
-
...options?.metadata
|
|
3009
|
-
};
|
|
3010
|
-
}
|
|
3011
|
-
function appendUserMessage(session, content) {
|
|
3012
|
-
return {
|
|
3013
|
-
...session,
|
|
3014
|
-
messages: [...session.messages, { role: "user", content }]
|
|
3015
|
-
};
|
|
3016
|
-
}
|
|
3017
|
-
function appendAssistantMessage(session, content) {
|
|
3018
|
-
return {
|
|
3019
|
-
...session,
|
|
3020
|
-
messages: [...session.messages, { role: "assistant", content }]
|
|
3021
|
-
};
|
|
3022
|
-
}
|
|
3023
|
-
function clearSession(session) {
|
|
3024
|
-
return {
|
|
3025
|
-
...session,
|
|
3026
|
-
messages: []
|
|
3027
|
-
};
|
|
3028
|
-
}
|
|
3029
|
-
function getRecentMessages(session, count) {
|
|
3030
|
-
return session.messages.slice(-count);
|
|
3031
|
-
}
|
|
3032
|
-
function extractToolUseBlocks(content) {
|
|
3033
|
-
if (typeof content === "string") {
|
|
3034
|
-
return [];
|
|
3035
|
-
}
|
|
3036
|
-
return content.filter((block) => block.type === "tool_use");
|
|
3037
|
-
}
|
|
3038
|
-
function createToolResultBlock(toolUseId, result, isError = false) {
|
|
3039
|
-
return {
|
|
3040
|
-
type: "tool_result",
|
|
3041
|
-
tool_use_id: toolUseId,
|
|
3042
|
-
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
3043
|
-
is_error: isError
|
|
3044
|
-
};
|
|
3045
|
-
}
|
|
3046
|
-
function updateSessionMetadata(session, metadata) {
|
|
3047
|
-
return {
|
|
3048
|
-
...session,
|
|
3049
|
-
metadata: {
|
|
3050
|
-
...session.metadata,
|
|
3051
|
-
...metadata
|
|
3052
|
-
}
|
|
3053
|
-
};
|
|
3054
|
-
}
|
|
3055
|
-
function getMessageCount(session) {
|
|
3056
|
-
return session.messages.length;
|
|
3057
|
-
}
|
|
3058
|
-
function estimateTokens(session) {
|
|
3059
|
-
let chars = 0;
|
|
3060
|
-
for (const msg of session.messages) {
|
|
3061
|
-
if (typeof msg.content === "string") {
|
|
3062
|
-
chars += msg.content.length;
|
|
3063
|
-
} else {
|
|
3064
|
-
chars += JSON.stringify(msg.content).length;
|
|
3065
|
-
}
|
|
3066
|
-
}
|
|
3067
|
-
return Math.ceil(chars / 4);
|
|
3068
|
-
}
|
|
3069
|
-
function summarizeSession(session) {
|
|
3070
|
-
let userMessages = 0;
|
|
3071
|
-
let assistantMessages = 0;
|
|
3072
|
-
for (const msg of session.messages) {
|
|
3073
|
-
if (msg.role === "user") {
|
|
3074
|
-
userMessages++;
|
|
3075
|
-
} else {
|
|
3076
|
-
assistantMessages++;
|
|
3077
|
-
}
|
|
3078
|
-
}
|
|
3079
|
-
return {
|
|
3080
|
-
messageCount: session.messages.length,
|
|
3081
|
-
userMessages,
|
|
3082
|
-
assistantMessages,
|
|
3083
|
-
estimatedTokens: estimateTokens(session)
|
|
3084
|
-
};
|
|
3085
|
-
}
|
|
3086
|
-
|
|
3087
|
-
// src/providers/claude-agent-sdk/adapter.ts
|
|
3088
|
-
class ClaudeAgentSDKProvider {
|
|
3089
|
-
name = "claude-agent-sdk";
|
|
3090
|
-
version = "1.0.0";
|
|
3091
|
-
config;
|
|
3092
|
-
sdkAvailable = null;
|
|
3093
|
-
constructor(config = {}) {
|
|
3094
|
-
this.config = {
|
|
3095
|
-
model: "claude-sonnet-4-20250514",
|
|
3096
|
-
extendedThinking: false,
|
|
3097
|
-
computerUse: false,
|
|
3098
|
-
maxTokens: 4096,
|
|
3099
|
-
temperature: 0.7,
|
|
3100
|
-
...config
|
|
3101
|
-
};
|
|
3102
|
-
}
|
|
3103
|
-
isAvailable() {
|
|
3104
|
-
if (this.sdkAvailable !== null) {
|
|
3105
|
-
return this.sdkAvailable;
|
|
3106
|
-
}
|
|
3107
|
-
try {
|
|
3108
|
-
__require.resolve("@anthropic-ai/claude-agent-sdk");
|
|
3109
|
-
const apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY;
|
|
3110
|
-
this.sdkAvailable = Boolean(apiKey);
|
|
3111
|
-
} catch {
|
|
3112
|
-
this.sdkAvailable = false;
|
|
3113
|
-
}
|
|
3114
|
-
return this.sdkAvailable;
|
|
3115
|
-
}
|
|
3116
|
-
async createContext(spec) {
|
|
3117
|
-
if (!this.isAvailable()) {
|
|
3118
|
-
throw new ProviderNotAvailableError(this.name, getDefaultI18n().t("error.provider.sdkNotConfigured"));
|
|
3119
|
-
}
|
|
3120
|
-
try {
|
|
3121
|
-
const toolSet = {};
|
|
3122
|
-
for (const tool3 of spec.tools) {
|
|
3123
|
-
toolSet[tool3.name] = specToolToExternalTool(tool3);
|
|
3124
|
-
}
|
|
3125
|
-
const instructions = await injectStaticKnowledge(spec.instructions, spec.knowledge ?? [], undefined);
|
|
3126
|
-
const contextId = `claude-${agentKey(spec.meta)}-${Date.now()}`;
|
|
3127
|
-
const metadata = {
|
|
3128
|
-
computerUseEnabled: this.config.computerUse ?? false,
|
|
3129
|
-
extendedThinkingEnabled: this.config.extendedThinking ?? false,
|
|
3130
|
-
mcpServerIds: this.config.mcpServers?.map((s) => s.name) ?? []
|
|
3131
|
-
};
|
|
3132
|
-
return {
|
|
3133
|
-
id: contextId,
|
|
3134
|
-
spec: {
|
|
3135
|
-
...spec,
|
|
3136
|
-
instructions
|
|
3137
|
-
},
|
|
3138
|
-
tools: toolSet,
|
|
3139
|
-
metadata,
|
|
3140
|
-
cleanup: async () => {}
|
|
3141
|
-
};
|
|
3142
|
-
} catch (error) {
|
|
3143
|
-
throw new ContextCreationError(this.name, getDefaultI18n().t("error.provider.contextCreation", {
|
|
3144
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3145
|
-
}), error instanceof Error ? error : undefined);
|
|
3146
|
-
}
|
|
3147
|
-
}
|
|
3148
|
-
async execute(context, params) {
|
|
3149
|
-
try {
|
|
3150
|
-
const sdk = await this.loadSDK();
|
|
3151
|
-
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
3152
|
-
|
|
3153
|
-
${params.systemOverride}` : context.spec.instructions;
|
|
3154
|
-
const claudeContext = buildClaudeAgentContext(params.options);
|
|
3155
|
-
let session = createEmptyClaudeSession();
|
|
3156
|
-
session = appendUserMessage(session, params.prompt);
|
|
3157
|
-
const claudeTools = this.prepareToolsForSDK(context, params);
|
|
3158
|
-
const rawResponse = await sdk.execute({
|
|
3159
|
-
model: this.config.model,
|
|
3160
|
-
system: systemPrompt,
|
|
3161
|
-
messages: session.messages,
|
|
3162
|
-
tools: claudeTools,
|
|
3163
|
-
max_tokens: this.config.maxTokens,
|
|
3164
|
-
temperature: this.config.temperature,
|
|
3165
|
-
metadata: claudeContext,
|
|
3166
|
-
extended_thinking: this.config.extendedThinking,
|
|
3167
|
-
computer_use: this.config.computerUse
|
|
3168
|
-
});
|
|
3169
|
-
const response = rawResponse;
|
|
3170
|
-
const toolCalls = extractToolCalls(response);
|
|
3171
|
-
const toolResults = await this.executeTools(toolCalls, context, params);
|
|
3172
|
-
if (response.content) {
|
|
3173
|
-
const content = response.content;
|
|
3174
|
-
session = appendAssistantMessage(session, content);
|
|
3175
|
-
}
|
|
3176
|
-
return {
|
|
3177
|
-
text: this.extractTextContent(response),
|
|
3178
|
-
toolCalls: toolCalls.map((tc) => ({
|
|
3179
|
-
type: "tool-call",
|
|
3180
|
-
toolCallId: tc.toolCallId,
|
|
3181
|
-
toolName: tc.toolName,
|
|
3182
|
-
args: tc.args
|
|
3183
|
-
})),
|
|
3184
|
-
toolResults: toolResults.map((tr) => ({
|
|
3185
|
-
type: "tool-result",
|
|
3186
|
-
toolCallId: tr.toolCallId,
|
|
3187
|
-
toolName: tr.toolName,
|
|
3188
|
-
output: tr.output
|
|
3189
|
-
})),
|
|
3190
|
-
usage: {
|
|
3191
|
-
inputTokens: response.usage?.input_tokens ?? 0,
|
|
3192
|
-
outputTokens: response.usage?.output_tokens ?? 0
|
|
3193
|
-
},
|
|
3194
|
-
finishReason: this.mapStopReason(response.stop_reason),
|
|
3195
|
-
metadata: {
|
|
3196
|
-
sessionId: context.metadata?.sessionId,
|
|
3197
|
-
model: response.model
|
|
3198
|
-
}
|
|
3199
|
-
};
|
|
3200
|
-
} catch (error) {
|
|
3201
|
-
throw new ProviderExecutionError(this.name, getDefaultI18n().t("error.provider.executionFailed", {
|
|
3202
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3203
|
-
}), error instanceof Error ? error : undefined);
|
|
3204
|
-
}
|
|
3205
|
-
}
|
|
3206
|
-
async* stream(context, params) {
|
|
3207
|
-
try {
|
|
3208
|
-
const sdk = await this.loadSDK();
|
|
3209
|
-
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
3210
|
-
|
|
3211
|
-
${params.systemOverride}` : context.spec.instructions;
|
|
3212
|
-
const claudeContext = buildClaudeAgentContext(params.options);
|
|
3213
|
-
const claudeTools = this.prepareToolsForSDK(context, params);
|
|
3214
|
-
const stream = await sdk.stream({
|
|
3215
|
-
model: this.config.model,
|
|
3216
|
-
system: systemPrompt,
|
|
3217
|
-
messages: [{ role: "user", content: params.prompt }],
|
|
3218
|
-
tools: claudeTools,
|
|
3219
|
-
max_tokens: this.config.maxTokens,
|
|
3220
|
-
temperature: this.config.temperature,
|
|
3221
|
-
metadata: claudeContext,
|
|
3222
|
-
extended_thinking: this.config.extendedThinking,
|
|
3223
|
-
computer_use: this.config.computerUse
|
|
3224
|
-
});
|
|
3225
|
-
let fullText = "";
|
|
3226
|
-
const allToolCalls = [];
|
|
3227
|
-
const allToolResults = [];
|
|
3228
|
-
let stepIndex = 0;
|
|
3229
|
-
for await (const event of stream) {
|
|
3230
|
-
if (event.type === "content_block_delta" && event.delta?.type === "text_delta") {
|
|
3231
|
-
const text = event.delta.text ?? "";
|
|
3232
|
-
fullText += text;
|
|
3233
|
-
yield { type: "text", text };
|
|
3234
|
-
}
|
|
3235
|
-
if (event.type === "content_block_start" && event.content_block?.type === "tool_use") {
|
|
3236
|
-
const toolCall = {
|
|
3237
|
-
toolCallId: event.content_block.id ?? "",
|
|
3238
|
-
toolName: event.content_block.name ?? "",
|
|
3239
|
-
args: event.content_block.input
|
|
3240
|
-
};
|
|
3241
|
-
allToolCalls.push(toolCall);
|
|
3242
|
-
yield {
|
|
3243
|
-
type: "tool-call",
|
|
3244
|
-
toolCall: {
|
|
3245
|
-
type: "tool-call",
|
|
3246
|
-
...toolCall
|
|
3247
|
-
}
|
|
3248
|
-
};
|
|
3249
|
-
}
|
|
3250
|
-
if (event.type === "message_stop") {
|
|
3251
|
-
stepIndex++;
|
|
3252
|
-
yield { type: "step-complete", stepIndex };
|
|
3253
|
-
}
|
|
3254
|
-
}
|
|
3255
|
-
for (const toolCall of allToolCalls) {
|
|
3256
|
-
const result = await this.executeTool(toolCall, context, params);
|
|
3257
|
-
allToolResults.push(result);
|
|
3258
|
-
yield {
|
|
3259
|
-
type: "tool-result",
|
|
3260
|
-
toolResult: {
|
|
3261
|
-
type: "tool-result",
|
|
3262
|
-
...result
|
|
3263
|
-
}
|
|
3264
|
-
};
|
|
3265
|
-
}
|
|
3266
|
-
yield {
|
|
3267
|
-
type: "done",
|
|
3268
|
-
result: {
|
|
3269
|
-
text: fullText,
|
|
3270
|
-
toolCalls: allToolCalls.map((tc) => ({
|
|
3271
|
-
type: "tool-call",
|
|
3272
|
-
...tc
|
|
3273
|
-
})),
|
|
3274
|
-
toolResults: allToolResults.map((tr) => ({
|
|
3275
|
-
type: "tool-result",
|
|
3276
|
-
...tr
|
|
3277
|
-
})),
|
|
3278
|
-
usage: { inputTokens: 0, outputTokens: 0 },
|
|
3279
|
-
finishReason: "stop"
|
|
3280
|
-
}
|
|
3281
|
-
};
|
|
3282
|
-
} catch (error) {
|
|
3283
|
-
throw new ProviderExecutionError(this.name, getDefaultI18n().t("error.provider.streamFailed", {
|
|
3284
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3285
|
-
}), error instanceof Error ? error : undefined);
|
|
3286
|
-
}
|
|
3287
|
-
}
|
|
3288
|
-
async loadSDK() {
|
|
3289
|
-
try {
|
|
3290
|
-
const module = __require("@anthropic-ai/claude-agent-sdk");
|
|
3291
|
-
return module.default ?? module;
|
|
3292
|
-
} catch {
|
|
3293
|
-
throw new ProviderNotAvailableError(this.name, getDefaultI18n().t("error.provider.claudeSdkMissing"));
|
|
3294
|
-
}
|
|
3295
|
-
}
|
|
3296
|
-
prepareToolsForSDK(context, params) {
|
|
3297
|
-
const handlers = new Map;
|
|
3298
|
-
for (const tool3 of context.spec.tools) {
|
|
3299
|
-
const externalTool = context.tools[tool3.name];
|
|
3300
|
-
if (externalTool?.execute) {
|
|
3301
|
-
handlers.set(tool3.name, async (input) => {
|
|
3302
|
-
if (!externalTool.execute) {
|
|
3303
|
-
throw new Error(getDefaultI18n().t("error.toolNoExecuteHandler", {
|
|
3304
|
-
name: tool3.name
|
|
3305
|
-
}));
|
|
3306
|
-
}
|
|
3307
|
-
const result = await externalTool.execute(input);
|
|
3308
|
-
return typeof result === "string" ? result : JSON.stringify(result);
|
|
3309
|
-
});
|
|
3310
|
-
}
|
|
3311
|
-
}
|
|
3312
|
-
return specToolsToClaudeAgentTools(context.spec.tools, handlers, {
|
|
3313
|
-
agentId: context.id,
|
|
3314
|
-
sessionId: params.options?.sessionId,
|
|
3315
|
-
tenantId: params.options?.tenantId,
|
|
3316
|
-
actorId: params.options?.actorId,
|
|
3317
|
-
metadata: params.options?.metadata,
|
|
3318
|
-
signal: params.signal
|
|
3319
|
-
});
|
|
3320
|
-
}
|
|
3321
|
-
async executeTool(toolCall, context, _params) {
|
|
3322
|
-
const tool3 = context.tools[toolCall.toolName];
|
|
3323
|
-
if (!tool3?.execute) {
|
|
3324
|
-
return {
|
|
3325
|
-
toolCallId: toolCall.toolCallId,
|
|
3326
|
-
toolName: toolCall.toolName,
|
|
3327
|
-
output: getDefaultI18n().t("error.toolNotFoundOrNoHandler", {
|
|
3328
|
-
name: toolCall.toolName
|
|
3329
|
-
})
|
|
3330
|
-
};
|
|
3331
|
-
}
|
|
3332
|
-
try {
|
|
3333
|
-
const output = await tool3.execute(toolCall.args);
|
|
3334
|
-
return {
|
|
3335
|
-
toolCallId: toolCall.toolCallId,
|
|
3336
|
-
toolName: toolCall.toolName,
|
|
3337
|
-
output
|
|
3338
|
-
};
|
|
3339
|
-
} catch (error) {
|
|
3340
|
-
return {
|
|
3341
|
-
toolCallId: toolCall.toolCallId,
|
|
3342
|
-
toolName: toolCall.toolName,
|
|
3343
|
-
output: `Error: ${error instanceof Error ? error.message : String(error)}`
|
|
3344
|
-
};
|
|
3345
|
-
}
|
|
3346
|
-
}
|
|
3347
|
-
async executeTools(toolCalls, context, params) {
|
|
3348
|
-
return Promise.all(toolCalls.map((tc) => this.executeTool(tc, context, params)));
|
|
3349
|
-
}
|
|
3350
|
-
extractTextContent(response) {
|
|
3351
|
-
if (!response.content) {
|
|
3352
|
-
return "";
|
|
3353
|
-
}
|
|
3354
|
-
return response.content.filter((block) => typeof block === "object" && block !== null && block.type === "text").map((block) => block.text).join("");
|
|
3355
|
-
}
|
|
3356
|
-
mapStopReason(stopReason) {
|
|
3357
|
-
switch (stopReason) {
|
|
3358
|
-
case "end_turn":
|
|
3359
|
-
case "stop_sequence":
|
|
3360
|
-
return "stop";
|
|
3361
|
-
case "tool_use":
|
|
3362
|
-
return "tool-calls";
|
|
3363
|
-
case "max_tokens":
|
|
3364
|
-
return "length";
|
|
3365
|
-
default:
|
|
3366
|
-
return "stop";
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
}
|
|
3370
|
-
var init_adapter2 = __esm(() => {
|
|
3371
|
-
init_spec();
|
|
3372
|
-
init_types();
|
|
3373
|
-
init_tool_bridge();
|
|
3374
|
-
init_injector();
|
|
3375
|
-
init_i18n();
|
|
3376
|
-
});
|
|
3377
|
-
|
|
3378
|
-
// src/providers/claude-agent-sdk/index.ts
|
|
3379
|
-
var exports_claude_agent_sdk = {};
|
|
3380
|
-
__export(exports_claude_agent_sdk, {
|
|
3381
|
-
updateSessionMetadata: () => updateSessionMetadata,
|
|
3382
|
-
toClaudeAgentSession: () => toClaudeAgentSession,
|
|
3383
|
-
summarizeSession: () => summarizeSession,
|
|
3384
|
-
specToolsToClaudeAgentTools: () => specToolsToClaudeAgentTools,
|
|
3385
|
-
specToolToExternalTool: () => specToolToExternalTool,
|
|
3386
|
-
specToolToClaudeAgentTool: () => specToolToClaudeAgentTool,
|
|
3387
|
-
getRecentMessages: () => getRecentMessages,
|
|
3388
|
-
getMessageCount: () => getMessageCount,
|
|
3389
|
-
extractToolUseBlocks: () => extractToolUseBlocks,
|
|
3390
|
-
extractToolCalls: () => extractToolCalls,
|
|
3391
|
-
estimateTokens: () => estimateTokens,
|
|
3392
|
-
createToolResultBlock: () => createToolResultBlock,
|
|
3393
|
-
createEmptyClaudeSession: () => createEmptyClaudeSession,
|
|
3394
|
-
createClaudeAgentSession: () => createClaudeAgentSession,
|
|
3395
|
-
clearSession: () => clearSession,
|
|
3396
|
-
claudeAgentToolsToSpecTools: () => claudeAgentToolsToSpecTools,
|
|
3397
|
-
claudeAgentToolToSpecTool: () => claudeAgentToolToSpecTool,
|
|
3398
|
-
buildClaudeAgentContext: () => buildClaudeAgentContext,
|
|
3399
|
-
appendUserMessage: () => appendUserMessage,
|
|
3400
|
-
appendAssistantMessage: () => appendAssistantMessage,
|
|
3401
|
-
ClaudeAgentSDKProvider: () => ClaudeAgentSDKProvider
|
|
3402
|
-
});
|
|
3403
|
-
var init_claude_agent_sdk = __esm(() => {
|
|
3404
|
-
init_adapter2();
|
|
3405
|
-
init_tool_bridge();
|
|
3406
|
-
});
|
|
3407
|
-
|
|
3408
|
-
// src/providers/opencode-sdk/tool-bridge.ts
|
|
3409
|
-
function specToolToOpenCodeTool(tool3) {
|
|
3410
|
-
return {
|
|
3411
|
-
name: tool3.name,
|
|
3412
|
-
description: tool3.description ?? getDefaultI18n().t("tool.fallbackDescription", { name: tool3.name }),
|
|
3413
|
-
parameters: normalizeToOpenCodeParameters(tool3.schema),
|
|
3414
|
-
permission: getPermissionLevel(tool3)
|
|
3415
|
-
};
|
|
3416
|
-
}
|
|
3417
|
-
function specToolsToOpenCodeTools(tools) {
|
|
3418
|
-
return tools.map(specToolToOpenCodeTool);
|
|
3419
|
-
}
|
|
3420
|
-
function getPermissionLevel(tool3) {
|
|
3421
|
-
if (tool3.requiresApproval) {
|
|
3422
|
-
return "ask";
|
|
3423
|
-
}
|
|
3424
|
-
if (tool3.automationSafe === false) {
|
|
3425
|
-
return "ask";
|
|
3426
|
-
}
|
|
3427
|
-
return "allow";
|
|
3428
|
-
}
|
|
3429
|
-
function openCodeToolToSpecTool(openCodeTool) {
|
|
3430
|
-
return {
|
|
3431
|
-
name: openCodeTool.name,
|
|
3432
|
-
description: openCodeTool.description,
|
|
3433
|
-
schema: openCodeTool.parameters,
|
|
3434
|
-
requiresApproval: openCodeTool.permission === "ask",
|
|
3435
|
-
automationSafe: openCodeTool.permission === "allow"
|
|
3436
|
-
};
|
|
3437
|
-
}
|
|
3438
|
-
function openCodeToolsToSpecTools(openCodeTools) {
|
|
3439
|
-
return openCodeTools.map(openCodeToolToSpecTool);
|
|
3440
|
-
}
|
|
3441
|
-
function specToolToExternalToolForOpenCode(tool3, handler, context) {
|
|
3442
|
-
return {
|
|
3443
|
-
name: tool3.name,
|
|
3444
|
-
description: tool3.description ?? getDefaultI18n().t("tool.fallbackDescription", { name: tool3.name }),
|
|
3445
|
-
inputSchema: tool3.schema ?? { type: "object" },
|
|
3446
|
-
requiresApproval: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
3447
|
-
execute: handler ? async (input) => {
|
|
3448
|
-
const fullContext = {
|
|
3449
|
-
agentId: context?.agentId ?? "unknown",
|
|
3450
|
-
sessionId: context?.sessionId ?? "unknown",
|
|
3451
|
-
tenantId: context?.tenantId,
|
|
3452
|
-
actorId: context?.actorId,
|
|
3453
|
-
metadata: context?.metadata,
|
|
3454
|
-
signal: context?.signal
|
|
3455
|
-
};
|
|
3456
|
-
return handler(input, fullContext);
|
|
3457
|
-
} : undefined
|
|
3458
|
-
};
|
|
3459
|
-
}
|
|
3460
|
-
function normalizeToOpenCodeParameters(schema) {
|
|
3461
|
-
if (!schema) {
|
|
3462
|
-
return { type: "object" };
|
|
3463
|
-
}
|
|
3464
|
-
if (schema.type === "object") {
|
|
3465
|
-
return {
|
|
3466
|
-
type: "object",
|
|
3467
|
-
properties: schema.properties,
|
|
3468
|
-
required: schema.required
|
|
3469
|
-
};
|
|
3470
|
-
}
|
|
3471
|
-
return {
|
|
3472
|
-
type: "object",
|
|
3473
|
-
properties: {
|
|
3474
|
-
value: convertToOpenCodeParameter(schema)
|
|
3475
|
-
},
|
|
3476
|
-
required: ["value"]
|
|
3477
|
-
};
|
|
3478
|
-
}
|
|
3479
|
-
function convertToOpenCodeParameter(schema) {
|
|
3480
|
-
const param = {
|
|
3481
|
-
type: schema.type ?? "string"
|
|
3482
|
-
};
|
|
3483
|
-
if (schema.description) {
|
|
3484
|
-
param.description = schema.description;
|
|
3485
|
-
}
|
|
3486
|
-
if (schema.enum) {
|
|
3487
|
-
param.enum = schema.enum;
|
|
3488
|
-
}
|
|
3489
|
-
if (schema.default !== undefined) {
|
|
3490
|
-
param.default = schema.default;
|
|
3491
|
-
}
|
|
3492
|
-
return param;
|
|
3493
|
-
}
|
|
3494
|
-
function createToolHandlerMap(tools) {
|
|
3495
|
-
const handlers = new Map;
|
|
3496
|
-
for (const [name, tool3] of Object.entries(tools)) {
|
|
3497
|
-
if (tool3.execute) {
|
|
3498
|
-
handlers.set(name, tool3.execute);
|
|
3499
|
-
}
|
|
3500
|
-
}
|
|
3501
|
-
return handlers;
|
|
3502
|
-
}
|
|
3503
|
-
async function executeToolCall(toolCall, handlers) {
|
|
3504
|
-
const handler = handlers.get(toolCall.name);
|
|
3505
|
-
if (!handler) {
|
|
3506
|
-
return {
|
|
3507
|
-
tool_call_id: toolCall.id,
|
|
3508
|
-
output: getDefaultI18n().t("error.toolNotFoundOrNoHandler", {
|
|
3509
|
-
name: toolCall.name
|
|
3510
|
-
}),
|
|
3511
|
-
is_error: true
|
|
3512
|
-
};
|
|
3513
|
-
}
|
|
3514
|
-
try {
|
|
3515
|
-
const result = await handler(toolCall.arguments);
|
|
3516
|
-
return {
|
|
3517
|
-
tool_call_id: toolCall.id,
|
|
3518
|
-
output: typeof result === "string" ? result : JSON.stringify(result)
|
|
3519
|
-
};
|
|
3520
|
-
} catch (error) {
|
|
3521
|
-
return {
|
|
3522
|
-
tool_call_id: toolCall.id,
|
|
3523
|
-
output: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
3524
|
-
is_error: true
|
|
3525
|
-
};
|
|
3526
|
-
}
|
|
3527
|
-
}
|
|
3528
|
-
var init_tool_bridge2 = __esm(() => {
|
|
3529
|
-
init_i18n();
|
|
3530
|
-
});
|
|
3531
|
-
|
|
3532
|
-
// src/providers/opencode-sdk/agent-bridge.ts
|
|
3533
|
-
function inferAgentType(spec) {
|
|
3534
|
-
const hasCodeTools = spec.tools.some((tool3) => [
|
|
3535
|
-
"write_file",
|
|
3536
|
-
"edit_file",
|
|
3537
|
-
"create_file",
|
|
3538
|
-
"delete_file",
|
|
3539
|
-
"bash",
|
|
3540
|
-
"execute",
|
|
3541
|
-
"run_command",
|
|
3542
|
-
"terminal"
|
|
3543
|
-
].includes(tool3.name.toLowerCase()));
|
|
3544
|
-
const instructionsLower = spec.instructions.toLowerCase();
|
|
3545
|
-
const hasPlanningKeywords = /\b(plan|design|architect|strategy|analyze|review|assess|evaluate)\b/.test(instructionsLower);
|
|
3546
|
-
const hasExplorationKeywords = /\b(search|find|explore|discover|locate|grep|pattern)\b/.test(instructionsLower);
|
|
3547
|
-
const hasResearchKeywords = /\b(research|investigate|understand|learn|gather|collect)\b/.test(instructionsLower);
|
|
3548
|
-
if (hasCodeTools) {
|
|
3549
|
-
return "build";
|
|
3550
|
-
}
|
|
3551
|
-
if (hasPlanningKeywords && !hasCodeTools) {
|
|
3552
|
-
return "plan";
|
|
3553
|
-
}
|
|
3554
|
-
if (hasExplorationKeywords && !hasResearchKeywords) {
|
|
3555
|
-
return "explore";
|
|
3556
|
-
}
|
|
3557
|
-
return "general";
|
|
3558
|
-
}
|
|
3559
|
-
function specToOpenCodeConfig(spec, options) {
|
|
3560
|
-
const agentType = options?.agentType ?? inferAgentType(spec);
|
|
3561
|
-
return {
|
|
3562
|
-
name: spec.meta.key,
|
|
3563
|
-
version: spec.meta.version,
|
|
3564
|
-
description: spec.description ?? spec.meta.description,
|
|
3565
|
-
instructions: spec.instructions,
|
|
3566
|
-
agent_type: agentType,
|
|
3567
|
-
tools: specToolsToOpenCodeTools(spec.tools),
|
|
3568
|
-
config: {
|
|
3569
|
-
max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
|
|
3570
|
-
temperature: options?.temperature ?? 0.7,
|
|
3571
|
-
model: options?.model,
|
|
3572
|
-
permissions: buildPermissions(spec)
|
|
3573
|
-
}
|
|
3574
|
-
};
|
|
3575
|
-
}
|
|
3576
|
-
function buildPermissions(spec) {
|
|
3577
|
-
const permissions = {};
|
|
3578
|
-
for (const tool3 of spec.tools) {
|
|
3579
|
-
if (tool3.requiresApproval) {
|
|
3580
|
-
permissions[tool3.name] = "ask";
|
|
3581
|
-
} else if (tool3.automationSafe === false) {
|
|
3582
|
-
permissions[tool3.name] = "ask";
|
|
3583
|
-
} else {
|
|
3584
|
-
permissions[tool3.name] = "allow";
|
|
3585
|
-
}
|
|
3586
|
-
}
|
|
3587
|
-
return permissions;
|
|
3588
|
-
}
|
|
3589
|
-
function specToOpenCodeMarkdown(spec, options) {
|
|
3590
|
-
const agentType = options?.agentType ?? inferAgentType(spec);
|
|
3591
|
-
return {
|
|
3592
|
-
frontmatter: {
|
|
3593
|
-
name: spec.meta.key,
|
|
3594
|
-
type: agentType,
|
|
3595
|
-
version: spec.meta.version,
|
|
3596
|
-
model: options?.model,
|
|
3597
|
-
temperature: options?.temperature ?? 0.7,
|
|
3598
|
-
max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
|
|
3599
|
-
tools: spec.tools.map((t) => t.name)
|
|
3600
|
-
},
|
|
3601
|
-
body: buildMarkdownBody(spec)
|
|
3602
|
-
};
|
|
3603
|
-
}
|
|
3604
|
-
function buildMarkdownBody(spec) {
|
|
3605
|
-
const i18n = getDefaultI18n();
|
|
3606
|
-
const lines = [];
|
|
3607
|
-
lines.push(`# ${spec.meta.key}`);
|
|
3608
|
-
lines.push("");
|
|
3609
|
-
if (spec.description ?? spec.meta.description) {
|
|
3610
|
-
lines.push(spec.description ?? spec.meta.description ?? "");
|
|
3611
|
-
lines.push("");
|
|
3612
|
-
}
|
|
3613
|
-
lines.push(i18n.t("export.instructions"));
|
|
3614
|
-
lines.push("");
|
|
3615
|
-
lines.push(spec.instructions);
|
|
3616
|
-
lines.push("");
|
|
3617
|
-
if (spec.tools.length > 0) {
|
|
3618
|
-
lines.push(i18n.t("export.tools"));
|
|
3619
|
-
lines.push("");
|
|
3620
|
-
for (const tool3 of spec.tools) {
|
|
3621
|
-
const permission = tool3.requiresApproval ? i18n.t("export.bridge.requiresApproval") : tool3.automationSafe === false ? i18n.t("export.bridge.askMode") : "";
|
|
3622
|
-
lines.push(`- **${tool3.name}**: ${tool3.description ?? i18n.t("export.noDescription")} ${permission}`.trim());
|
|
3623
|
-
}
|
|
3624
|
-
lines.push("");
|
|
3625
|
-
}
|
|
3626
|
-
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
3627
|
-
lines.push(i18n.t("export.knowledgeSources"));
|
|
3628
|
-
lines.push("");
|
|
3629
|
-
for (const k of spec.knowledge) {
|
|
3630
|
-
const required = k.required ? i18n.t("export.required") : i18n.t("export.optional");
|
|
3631
|
-
lines.push(`- ${k.key} ${required}`);
|
|
3632
|
-
}
|
|
3633
|
-
lines.push("");
|
|
3634
|
-
}
|
|
3635
|
-
return lines.join(`
|
|
3636
|
-
`);
|
|
3637
|
-
}
|
|
3638
|
-
function serializeOpenCodeMarkdown(markdown) {
|
|
3639
|
-
const lines = [];
|
|
3640
|
-
lines.push("---");
|
|
3641
|
-
lines.push(`name: ${markdown.frontmatter.name}`);
|
|
3642
|
-
lines.push(`type: ${markdown.frontmatter.type}`);
|
|
3643
|
-
if (markdown.frontmatter.version) {
|
|
3644
|
-
lines.push(`version: ${markdown.frontmatter.version}`);
|
|
3645
|
-
}
|
|
3646
|
-
if (markdown.frontmatter.model) {
|
|
3647
|
-
lines.push(`model: ${markdown.frontmatter.model}`);
|
|
3648
|
-
}
|
|
3649
|
-
if (markdown.frontmatter.temperature !== undefined) {
|
|
3650
|
-
lines.push(`temperature: ${markdown.frontmatter.temperature}`);
|
|
3651
|
-
}
|
|
3652
|
-
if (markdown.frontmatter.max_steps !== undefined) {
|
|
3653
|
-
lines.push(`max_steps: ${markdown.frontmatter.max_steps}`);
|
|
3654
|
-
}
|
|
3655
|
-
if (markdown.frontmatter.tools && markdown.frontmatter.tools.length > 0) {
|
|
3656
|
-
lines.push(`tools:`);
|
|
3657
|
-
for (const tool3 of markdown.frontmatter.tools) {
|
|
3658
|
-
lines.push(` - ${tool3}`);
|
|
3659
|
-
}
|
|
3660
|
-
}
|
|
3661
|
-
lines.push("---");
|
|
3662
|
-
lines.push("");
|
|
3663
|
-
lines.push(markdown.body);
|
|
3664
|
-
return lines.join(`
|
|
3665
|
-
`);
|
|
3666
|
-
}
|
|
3667
|
-
function openCodeConfigToSpec(config) {
|
|
3668
|
-
return {
|
|
3669
|
-
meta: {
|
|
3670
|
-
key: config.name,
|
|
3671
|
-
version: config.version ?? "1.0.0",
|
|
3672
|
-
description: config.description ?? "",
|
|
3673
|
-
stability: "experimental",
|
|
3674
|
-
owners: [],
|
|
3675
|
-
tags: []
|
|
3676
|
-
},
|
|
3677
|
-
description: config.description,
|
|
3678
|
-
instructions: config.instructions ?? "",
|
|
3679
|
-
tools: config.tools?.map((tool3) => ({
|
|
3680
|
-
name: tool3.name,
|
|
3681
|
-
description: tool3.description,
|
|
3682
|
-
schema: tool3.parameters,
|
|
3683
|
-
requiresApproval: tool3.permission === "ask",
|
|
3684
|
-
automationSafe: tool3.permission === "allow"
|
|
3685
|
-
})) ?? [],
|
|
3686
|
-
maxSteps: config.config?.max_steps ?? 10
|
|
3687
|
-
};
|
|
3688
|
-
}
|
|
3689
|
-
var init_agent_bridge = __esm(() => {
|
|
3690
|
-
init_tool_bridge2();
|
|
3691
|
-
init_i18n();
|
|
3692
|
-
});
|
|
3693
|
-
|
|
3694
|
-
// src/providers/opencode-sdk/adapter.ts
|
|
3695
|
-
class OpenCodeSDKProvider {
|
|
3696
|
-
name = "opencode-sdk";
|
|
3697
|
-
version = "1.0.0";
|
|
3698
|
-
config;
|
|
3699
|
-
sdkAvailable = null;
|
|
3700
|
-
constructor(config = {}) {
|
|
3701
|
-
this.config = {
|
|
3702
|
-
serverUrl: "http://127.0.0.1:4096",
|
|
3703
|
-
port: 4096,
|
|
3704
|
-
agentType: "general",
|
|
3705
|
-
temperature: 0.7,
|
|
3706
|
-
timeout: 30000,
|
|
3707
|
-
...config
|
|
3708
|
-
};
|
|
3709
|
-
if (!config.serverUrl && config.port) {
|
|
3710
|
-
this.config.serverUrl = `http://127.0.0.1:${config.port}`;
|
|
3711
|
-
}
|
|
3712
|
-
}
|
|
3713
|
-
isAvailable() {
|
|
3714
|
-
if (this.sdkAvailable !== null) {
|
|
3715
|
-
return this.sdkAvailable;
|
|
3716
|
-
}
|
|
3717
|
-
try {
|
|
3718
|
-
__require.resolve("@opencode-ai/sdk");
|
|
3719
|
-
this.sdkAvailable = true;
|
|
3720
|
-
} catch {
|
|
3721
|
-
this.sdkAvailable = false;
|
|
3722
|
-
}
|
|
3723
|
-
return this.sdkAvailable;
|
|
3724
|
-
}
|
|
3725
|
-
async createContext(spec) {
|
|
3726
|
-
if (!this.isAvailable()) {
|
|
3727
|
-
throw new ProviderNotAvailableError(this.name, getDefaultI18n().t("error.provider.sdkNotInstalled"));
|
|
3728
|
-
}
|
|
3729
|
-
try {
|
|
3730
|
-
const sdk = await this.loadSDK();
|
|
3731
|
-
const { client } = await sdk.createOpencode({
|
|
3732
|
-
hostname: this.getHostname(),
|
|
3733
|
-
port: this.config.port ?? 4096,
|
|
3734
|
-
timeout: this.config.timeout
|
|
3735
|
-
});
|
|
3736
|
-
const session = await client.session.create({
|
|
3737
|
-
agent: this.config.agentType ?? inferAgentType(spec),
|
|
3738
|
-
model: this.config.model
|
|
3739
|
-
});
|
|
3740
|
-
const toolSet = {};
|
|
3741
|
-
for (const tool3 of spec.tools) {
|
|
3742
|
-
toolSet[tool3.name] = specToolToExternalToolForOpenCode(tool3);
|
|
3743
|
-
}
|
|
3744
|
-
const instructions = await injectStaticKnowledge(spec.instructions, spec.knowledge ?? [], undefined);
|
|
3745
|
-
const contextId = `opencode-${agentKey(spec.meta)}-${Date.now()}`;
|
|
3746
|
-
const metadata = {
|
|
3747
|
-
sessionId: session.id,
|
|
3748
|
-
agentType: this.config.agentType ?? inferAgentType(spec),
|
|
3749
|
-
serverUrl: this.config.serverUrl ?? `http://127.0.0.1:${this.config.port ?? 4096}`
|
|
3750
|
-
};
|
|
3751
|
-
return {
|
|
3752
|
-
id: contextId,
|
|
3753
|
-
spec: {
|
|
3754
|
-
...spec,
|
|
3755
|
-
instructions
|
|
3756
|
-
},
|
|
3757
|
-
tools: toolSet,
|
|
3758
|
-
metadata,
|
|
3759
|
-
cleanup: async () => {
|
|
3760
|
-
try {
|
|
3761
|
-
await client.session.delete({ id: session.id });
|
|
3762
|
-
} catch {}
|
|
3763
|
-
}
|
|
3764
|
-
};
|
|
3765
|
-
} catch (error) {
|
|
3766
|
-
throw new ContextCreationError(this.name, getDefaultI18n().t("error.provider.contextCreation", {
|
|
3767
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3768
|
-
}), error instanceof Error ? error : undefined);
|
|
3769
|
-
}
|
|
3770
|
-
}
|
|
3771
|
-
async execute(context, params) {
|
|
3772
|
-
try {
|
|
3773
|
-
const sdk = await this.loadSDK();
|
|
3774
|
-
const metadata = context.metadata;
|
|
3775
|
-
const { client } = await sdk.createOpencodeClient({
|
|
3776
|
-
baseUrl: metadata.serverUrl
|
|
3777
|
-
});
|
|
3778
|
-
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
3779
|
-
|
|
3780
|
-
${params.systemOverride}` : context.spec.instructions;
|
|
3781
|
-
const response = await client.session.prompt({
|
|
3782
|
-
id: metadata.sessionId,
|
|
3783
|
-
body: {
|
|
3784
|
-
content: params.prompt,
|
|
3785
|
-
system: systemPrompt
|
|
3786
|
-
}
|
|
3787
|
-
});
|
|
3788
|
-
const toolCalls = this.extractToolCalls(response);
|
|
3789
|
-
const toolHandlers = createToolHandlerMap(context.tools);
|
|
3790
|
-
const toolResults = await Promise.all(toolCalls.map((tc) => executeToolCall(tc, toolHandlers)));
|
|
3791
|
-
return {
|
|
3792
|
-
text: this.extractTextContent(response),
|
|
3793
|
-
toolCalls: toolCalls.map((tc) => ({
|
|
3794
|
-
type: "tool-call",
|
|
3795
|
-
toolCallId: tc.id,
|
|
3796
|
-
toolName: tc.name,
|
|
3797
|
-
args: tc.arguments
|
|
3798
|
-
})),
|
|
3799
|
-
toolResults: toolResults.map((tr) => ({
|
|
3800
|
-
type: "tool-result",
|
|
3801
|
-
toolCallId: tr.tool_call_id,
|
|
3802
|
-
toolName: toolCalls.find((tc) => tc.id === tr.tool_call_id)?.name ?? "",
|
|
3803
|
-
output: tr.output
|
|
3804
|
-
})),
|
|
3805
|
-
usage: {
|
|
3806
|
-
inputTokens: response.usage?.input_tokens ?? 0,
|
|
3807
|
-
outputTokens: response.usage?.output_tokens ?? 0
|
|
3808
|
-
},
|
|
3809
|
-
finishReason: this.mapFinishReason(response.finish_reason),
|
|
3810
|
-
metadata: {
|
|
3811
|
-
sessionId: metadata.sessionId,
|
|
3812
|
-
agentType: metadata.agentType
|
|
3813
|
-
}
|
|
3814
|
-
};
|
|
3815
|
-
} catch (error) {
|
|
3816
|
-
throw new ProviderExecutionError(this.name, getDefaultI18n().t("error.provider.executionFailed", {
|
|
3817
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3818
|
-
}), error instanceof Error ? error : undefined);
|
|
3819
|
-
}
|
|
3820
|
-
}
|
|
3821
|
-
async* stream(context, params) {
|
|
3822
|
-
try {
|
|
3823
|
-
const sdk = await this.loadSDK();
|
|
3824
|
-
const metadata = context.metadata;
|
|
3825
|
-
const { client } = await sdk.createOpencodeClient({
|
|
3826
|
-
baseUrl: metadata.serverUrl
|
|
3827
|
-
});
|
|
3828
|
-
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
3829
|
-
|
|
3830
|
-
${params.systemOverride}` : context.spec.instructions;
|
|
3831
|
-
const events = client.session.subscribe({
|
|
3832
|
-
id: metadata.sessionId
|
|
3833
|
-
});
|
|
3834
|
-
await client.session.prompt({
|
|
3835
|
-
id: metadata.sessionId,
|
|
3836
|
-
body: {
|
|
3837
|
-
content: params.prompt,
|
|
3838
|
-
system: systemPrompt
|
|
3839
|
-
}
|
|
3840
|
-
});
|
|
3841
|
-
let fullText = "";
|
|
3842
|
-
const allToolCalls = [];
|
|
3843
|
-
const toolHandlers = createToolHandlerMap(context.tools);
|
|
3844
|
-
let stepIndex = 0;
|
|
3845
|
-
for await (const event of events) {
|
|
3846
|
-
if (event.type === "message.delta") {
|
|
3847
|
-
const text = event.delta?.content ?? "";
|
|
3848
|
-
fullText += text;
|
|
3849
|
-
yield { type: "text", text };
|
|
3850
|
-
}
|
|
3851
|
-
if (event.type === "tool.call") {
|
|
3852
|
-
const toolCall = {
|
|
3853
|
-
id: event.tool_call_id ?? `tc-${Date.now()}`,
|
|
3854
|
-
name: event.tool_name ?? "",
|
|
3855
|
-
arguments: event.arguments ?? {}
|
|
3856
|
-
};
|
|
3857
|
-
allToolCalls.push(toolCall);
|
|
3858
|
-
yield {
|
|
3859
|
-
type: "tool-call",
|
|
3860
|
-
toolCall: {
|
|
3861
|
-
type: "tool-call",
|
|
3862
|
-
toolCallId: toolCall.id,
|
|
3863
|
-
toolName: toolCall.name,
|
|
3864
|
-
args: toolCall.arguments
|
|
3865
|
-
}
|
|
3866
|
-
};
|
|
3867
|
-
}
|
|
3868
|
-
if (event.type === "step.complete") {
|
|
3869
|
-
stepIndex++;
|
|
3870
|
-
yield { type: "step-complete", stepIndex };
|
|
3871
|
-
}
|
|
3872
|
-
if (event.type === "message.complete") {
|
|
3873
|
-
break;
|
|
3874
|
-
}
|
|
3875
|
-
}
|
|
3876
|
-
for (const toolCall of allToolCalls) {
|
|
3877
|
-
const result = await executeToolCall(toolCall, toolHandlers);
|
|
3878
|
-
yield {
|
|
3879
|
-
type: "tool-result",
|
|
3880
|
-
toolResult: {
|
|
3881
|
-
type: "tool-result",
|
|
3882
|
-
toolCallId: result.tool_call_id,
|
|
3883
|
-
toolName: toolCall.name,
|
|
3884
|
-
output: result.output
|
|
3885
|
-
}
|
|
3886
|
-
};
|
|
3887
|
-
}
|
|
3888
|
-
yield {
|
|
3889
|
-
type: "done",
|
|
3890
|
-
result: {
|
|
3891
|
-
text: fullText,
|
|
3892
|
-
toolCalls: allToolCalls.map((tc) => ({
|
|
3893
|
-
type: "tool-call",
|
|
3894
|
-
toolCallId: tc.id,
|
|
3895
|
-
toolName: tc.name,
|
|
3896
|
-
args: tc.arguments
|
|
3897
|
-
})),
|
|
3898
|
-
toolResults: [],
|
|
3899
|
-
usage: { inputTokens: 0, outputTokens: 0 },
|
|
3900
|
-
finishReason: "stop"
|
|
3901
|
-
}
|
|
3902
|
-
};
|
|
3903
|
-
} catch (error) {
|
|
3904
|
-
throw new ProviderExecutionError(this.name, getDefaultI18n().t("error.provider.streamFailed", {
|
|
3905
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3906
|
-
}), error instanceof Error ? error : undefined);
|
|
3907
|
-
}
|
|
3908
|
-
}
|
|
3909
|
-
async loadSDK() {
|
|
3910
|
-
try {
|
|
3911
|
-
const module = __require("@opencode-ai/sdk");
|
|
3912
|
-
return module;
|
|
3913
|
-
} catch {
|
|
3914
|
-
throw new ProviderNotAvailableError(this.name, getDefaultI18n().t("error.provider.opencodeSdkMissing"));
|
|
3915
|
-
}
|
|
3916
|
-
}
|
|
3917
|
-
getHostname() {
|
|
3918
|
-
if (!this.config.serverUrl) {
|
|
3919
|
-
return "127.0.0.1";
|
|
3920
|
-
}
|
|
3921
|
-
try {
|
|
3922
|
-
const url = new URL(this.config.serverUrl);
|
|
3923
|
-
return url.hostname;
|
|
3924
|
-
} catch {
|
|
3925
|
-
return "127.0.0.1";
|
|
3926
|
-
}
|
|
3927
|
-
}
|
|
3928
|
-
extractToolCalls(response) {
|
|
3929
|
-
if (!response.tool_calls) {
|
|
3930
|
-
return [];
|
|
3931
|
-
}
|
|
3932
|
-
return response.tool_calls.map((tc) => ({
|
|
3933
|
-
id: tc.id,
|
|
3934
|
-
name: tc.name,
|
|
3935
|
-
arguments: tc.arguments ?? {}
|
|
3936
|
-
}));
|
|
3937
|
-
}
|
|
3938
|
-
extractTextContent(response) {
|
|
3939
|
-
return response.content ?? response.message?.content ?? "";
|
|
3940
|
-
}
|
|
3941
|
-
mapFinishReason(finishReason) {
|
|
3942
|
-
switch (finishReason) {
|
|
3943
|
-
case "stop":
|
|
3944
|
-
case "end":
|
|
3945
|
-
return "stop";
|
|
3946
|
-
case "tool_use":
|
|
3947
|
-
case "tool_calls":
|
|
3948
|
-
return "tool-calls";
|
|
3949
|
-
case "length":
|
|
3950
|
-
case "max_tokens":
|
|
3951
|
-
return "length";
|
|
3952
|
-
default:
|
|
3953
|
-
return "stop";
|
|
3954
|
-
}
|
|
3955
|
-
}
|
|
3956
|
-
}
|
|
3957
|
-
var init_adapter3 = __esm(() => {
|
|
3958
|
-
init_spec();
|
|
3959
|
-
init_types();
|
|
3960
|
-
init_tool_bridge2();
|
|
3961
|
-
init_agent_bridge();
|
|
3962
|
-
init_injector();
|
|
3963
|
-
init_i18n();
|
|
3964
|
-
});
|
|
3965
|
-
|
|
3966
|
-
// src/providers/opencode-sdk/index.ts
|
|
3967
|
-
var exports_opencode_sdk = {};
|
|
3968
|
-
__export(exports_opencode_sdk, {
|
|
3969
|
-
specToolsToOpenCodeTools: () => specToolsToOpenCodeTools,
|
|
3970
|
-
specToolToOpenCodeTool: () => specToolToOpenCodeTool,
|
|
3971
|
-
specToolToExternalToolForOpenCode: () => specToolToExternalToolForOpenCode,
|
|
3972
|
-
specToOpenCodeMarkdown: () => specToOpenCodeMarkdown,
|
|
3973
|
-
specToOpenCodeConfig: () => specToOpenCodeConfig,
|
|
3974
|
-
serializeOpenCodeMarkdown: () => serializeOpenCodeMarkdown,
|
|
3975
|
-
openCodeToolsToSpecTools: () => openCodeToolsToSpecTools,
|
|
3976
|
-
openCodeToolToSpecTool: () => openCodeToolToSpecTool,
|
|
3977
|
-
openCodeConfigToSpec: () => openCodeConfigToSpec,
|
|
3978
|
-
inferAgentType: () => inferAgentType,
|
|
3979
|
-
executeToolCall: () => executeToolCall,
|
|
3980
|
-
createToolHandlerMap: () => createToolHandlerMap,
|
|
3981
|
-
OpenCodeSDKProvider: () => OpenCodeSDKProvider
|
|
3982
|
-
});
|
|
3983
|
-
var init_opencode_sdk = __esm(() => {
|
|
3984
|
-
init_adapter3();
|
|
3985
|
-
init_tool_bridge2();
|
|
3986
|
-
init_agent_bridge();
|
|
3987
|
-
});
|
|
3988
|
-
|
|
3989
|
-
// src/agent/json-runner.ts
|
|
3990
|
-
init_i18n();
|
|
3991
|
-
init_contract_spec_agent();
|
|
3992
|
-
import { createProvider } from "@contractspec/lib.ai-providers/factory";
|
|
3993
|
-
import { StabilityEnum } from "@contractspec/lib.contracts/ownership";
|
|
3994
|
-
function getJsonOnlyRules(locale) {
|
|
3995
|
-
const i18n = createAgentI18n(locale);
|
|
3996
|
-
return [
|
|
3997
|
-
i18n.t("agent.json.rules.validJsonOnly"),
|
|
3998
|
-
i18n.t("agent.json.rules.noMarkdownFences"),
|
|
3999
|
-
i18n.t("agent.json.rules.noCommentary"),
|
|
4000
|
-
i18n.t("agent.json.rules.doubleQuotes"),
|
|
4001
|
-
i18n.t("agent.json.rules.noTrailingCommas")
|
|
4002
|
-
].join(`
|
|
4003
|
-
`);
|
|
4004
|
-
}
|
|
4005
|
-
function getDefaultSpec(locale) {
|
|
4006
|
-
const i18n = createAgentI18n(locale);
|
|
4007
|
-
return {
|
|
4008
|
-
meta: {
|
|
4009
|
-
key: "agent.json-runner",
|
|
4010
|
-
version: "1.0.0",
|
|
4011
|
-
description: i18n.t("agent.json.defaultDescription"),
|
|
4012
|
-
stability: StabilityEnum.Experimental,
|
|
4013
|
-
owners: ["platform.core"],
|
|
4014
|
-
tags: ["json", "agent"]
|
|
4015
|
-
},
|
|
4016
|
-
instructions: i18n.t("agent.json.systemPrompt"),
|
|
4017
|
-
tools: []
|
|
4018
|
-
};
|
|
4019
|
-
}
|
|
4020
|
-
function resolveModel(options) {
|
|
4021
|
-
if (options.model)
|
|
4022
|
-
return options.model;
|
|
4023
|
-
if (options.provider) {
|
|
4024
|
-
return createProvider(options.provider).getModel();
|
|
4025
|
-
}
|
|
4026
|
-
throw new Error(getDefaultI18n().t("error.jsonRunner.requiresModel"));
|
|
4027
|
-
}
|
|
4028
|
-
function applyModelSettings(model, settings) {
|
|
4029
|
-
const { temperature } = settings;
|
|
4030
|
-
if (temperature === undefined)
|
|
4031
|
-
return model;
|
|
4032
|
-
const withSettings = model;
|
|
4033
|
-
if (typeof withSettings.withSettings === "function") {
|
|
4034
|
-
return withSettings.withSettings({ temperature });
|
|
4035
|
-
}
|
|
4036
|
-
return model;
|
|
4037
|
-
}
|
|
4038
|
-
function buildInstructions(base, locale, system) {
|
|
4039
|
-
return [base, getJsonOnlyRules(locale), system].filter(Boolean).join(`
|
|
4040
|
-
|
|
4041
|
-
`);
|
|
4042
|
-
}
|
|
4043
|
-
function ensureToolHandlers(spec, handlers) {
|
|
4044
|
-
for (const tool3 of spec.tools) {
|
|
4045
|
-
if (!handlers.has(tool3.name)) {
|
|
4046
|
-
throw new Error(getDefaultI18n().t("error.missingToolHandler", { name: tool3.name }));
|
|
4047
|
-
}
|
|
4048
|
-
}
|
|
4049
|
-
}
|
|
4050
|
-
async function createAgentJsonRunner(options) {
|
|
4051
|
-
const model = applyModelSettings(resolveModel(options), {
|
|
4052
|
-
temperature: options.temperature ?? 0
|
|
4053
|
-
});
|
|
4054
|
-
const baseSpec = options.spec ?? getDefaultSpec(options.locale);
|
|
4055
|
-
const spec = {
|
|
4056
|
-
...baseSpec,
|
|
4057
|
-
locale: options.spec?.locale ?? options.locale,
|
|
4058
|
-
instructions: buildInstructions(baseSpec.instructions, options.locale, options.system),
|
|
4059
|
-
maxSteps: options.maxSteps ?? baseSpec.maxSteps
|
|
4060
|
-
};
|
|
4061
|
-
const toolHandlers = options.toolHandlers ?? new Map;
|
|
4062
|
-
ensureToolHandlers(spec, toolHandlers);
|
|
4063
|
-
const agent = await ContractSpecAgent.create({
|
|
4064
|
-
spec,
|
|
4065
|
-
model,
|
|
4066
|
-
toolHandlers
|
|
4067
|
-
});
|
|
4068
|
-
return {
|
|
4069
|
-
async generateJson(prompt) {
|
|
4070
|
-
const result = await agent.generate({ prompt });
|
|
4071
|
-
return result.text;
|
|
4072
|
-
}
|
|
4073
|
-
};
|
|
4074
|
-
}
|
|
4075
|
-
|
|
4076
|
-
// src/agent/unified-agent.ts
|
|
4077
|
-
init_i18n();
|
|
4078
|
-
import { createProvider as createProvider2 } from "@contractspec/lib.ai-providers/factory";
|
|
4079
|
-
|
|
4080
|
-
class UnifiedAgent {
|
|
4081
|
-
spec;
|
|
4082
|
-
config;
|
|
4083
|
-
tools;
|
|
4084
|
-
provider;
|
|
4085
|
-
context;
|
|
4086
|
-
state;
|
|
4087
|
-
constructor(spec, config) {
|
|
4088
|
-
this.spec = spec;
|
|
4089
|
-
this.config = config;
|
|
4090
|
-
this.tools = config.tools ?? new Map;
|
|
4091
|
-
this.state = {
|
|
4092
|
-
backend: config.backend,
|
|
4093
|
-
isReady: false,
|
|
4094
|
-
messageCount: 0
|
|
4095
|
-
};
|
|
4096
|
-
}
|
|
4097
|
-
async initialize() {
|
|
4098
|
-
const backend = this.config.backend;
|
|
4099
|
-
try {
|
|
4100
|
-
switch (backend) {
|
|
4101
|
-
case "ai-sdk":
|
|
4102
|
-
this.state.isReady = true;
|
|
4103
|
-
break;
|
|
4104
|
-
case "claude-agent-sdk":
|
|
4105
|
-
await this.initializeClaudeAgentSDK();
|
|
4106
|
-
break;
|
|
4107
|
-
case "opencode-sdk":
|
|
4108
|
-
await this.initializeOpenCodeSDK();
|
|
4109
|
-
break;
|
|
4110
|
-
default:
|
|
4111
|
-
throw new Error(getDefaultI18n().t("error.unknownBackend", {
|
|
4112
|
-
backend: String(backend)
|
|
4113
|
-
}));
|
|
4114
|
-
}
|
|
4115
|
-
} catch (error) {
|
|
4116
|
-
this.state.lastError = error instanceof Error ? error : new Error(String(error));
|
|
4117
|
-
if (this.config.fallbackBackend && this.config.fallbackBackend !== backend) {
|
|
4118
|
-
console.warn(getDefaultI18n().t("log.unifiedAgent.fallback", {
|
|
4119
|
-
backend: String(backend),
|
|
4120
|
-
fallback: String(this.config.fallbackBackend)
|
|
4121
|
-
}));
|
|
4122
|
-
this.state.backend = this.config.fallbackBackend;
|
|
4123
|
-
await this.initialize();
|
|
4124
|
-
} else {
|
|
4125
|
-
throw error;
|
|
4126
|
-
}
|
|
4127
|
-
}
|
|
4128
|
-
}
|
|
4129
|
-
async initializeClaudeAgentSDK() {
|
|
4130
|
-
try {
|
|
4131
|
-
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
4132
|
-
const config = this.config.config;
|
|
4133
|
-
this.provider = new ClaudeAgentSDKProvider2(config ?? {});
|
|
4134
|
-
if (!this.provider.isAvailable()) {
|
|
4135
|
-
throw new Error(getDefaultI18n().t("error.claudeSdk.notAvailable"));
|
|
4136
|
-
}
|
|
4137
|
-
this.context = await this.provider.createContext(this.spec);
|
|
4138
|
-
this.state.isReady = true;
|
|
4139
|
-
} catch (error) {
|
|
4140
|
-
if (error.code === "MODULE_NOT_FOUND") {
|
|
4141
|
-
throw new Error(getDefaultI18n().t("error.claudeSdk.notInstalled"));
|
|
4142
|
-
}
|
|
4143
|
-
throw error;
|
|
4144
|
-
}
|
|
4145
|
-
}
|
|
4146
|
-
async initializeOpenCodeSDK() {
|
|
4147
|
-
try {
|
|
4148
|
-
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
4149
|
-
const config = this.config.config;
|
|
4150
|
-
this.provider = new OpenCodeSDKProvider2(config ?? {});
|
|
4151
|
-
if (!this.provider.isAvailable()) {
|
|
4152
|
-
throw new Error(getDefaultI18n().t("error.opencodeSdk.notAvailable"));
|
|
4153
|
-
}
|
|
4154
|
-
this.context = await this.provider.createContext(this.spec);
|
|
4155
|
-
this.state.isReady = true;
|
|
4156
|
-
} catch (error) {
|
|
4157
|
-
if (error.code === "MODULE_NOT_FOUND") {
|
|
4158
|
-
throw new Error(getDefaultI18n().t("error.opencodeSdk.notInstalled"));
|
|
4159
|
-
}
|
|
4160
|
-
throw error;
|
|
4161
|
-
}
|
|
4162
|
-
}
|
|
4163
|
-
async run(message, options) {
|
|
4164
|
-
if (!this.state.isReady) {
|
|
4165
|
-
await this.initialize();
|
|
4166
|
-
}
|
|
4167
|
-
const backend = options?.backend ?? this.state.backend;
|
|
4168
|
-
this.state.messageCount++;
|
|
4169
|
-
try {
|
|
4170
|
-
switch (backend) {
|
|
4171
|
-
case "ai-sdk":
|
|
4172
|
-
return await this.runWithAISDK(message, options);
|
|
4173
|
-
case "claude-agent-sdk":
|
|
4174
|
-
case "opencode-sdk":
|
|
4175
|
-
return await this.runWithExternalProvider(message, options);
|
|
4176
|
-
default:
|
|
4177
|
-
throw new Error(getDefaultI18n().t("error.unknownBackend", {
|
|
4178
|
-
backend: String(backend)
|
|
4179
|
-
}));
|
|
4180
|
-
}
|
|
4181
|
-
} catch (error) {
|
|
4182
|
-
this.state.lastError = error instanceof Error ? error : new Error(String(error));
|
|
4183
|
-
throw error;
|
|
4184
|
-
}
|
|
4185
|
-
}
|
|
4186
|
-
async runWithAISDK(message, options) {
|
|
4187
|
-
const { ContractSpecAgent: ContractSpecAgent2 } = await Promise.resolve().then(() => (init_contract_spec_agent(), exports_contract_spec_agent));
|
|
4188
|
-
const model = await this.resolveAISDKModel();
|
|
4189
|
-
const agent = await ContractSpecAgent2.create({
|
|
4190
|
-
spec: this.spec,
|
|
4191
|
-
model,
|
|
4192
|
-
toolHandlers: this.tools
|
|
4193
|
-
});
|
|
4194
|
-
return await agent.generate({
|
|
4195
|
-
prompt: message,
|
|
4196
|
-
options
|
|
4197
|
-
});
|
|
4198
|
-
}
|
|
4199
|
-
async runWithExternalProvider(message, options) {
|
|
4200
|
-
if (!this.provider || !this.context) {
|
|
4201
|
-
throw new Error(getDefaultI18n().t("error.providerNotInitialized"));
|
|
4202
|
-
}
|
|
4203
|
-
const result = await this.provider.execute(this.context, {
|
|
4204
|
-
prompt: message,
|
|
4205
|
-
options
|
|
4206
|
-
});
|
|
4207
|
-
return this.convertExternalResult(result);
|
|
4208
|
-
}
|
|
4209
|
-
convertExternalResult(result) {
|
|
4210
|
-
return {
|
|
4211
|
-
text: result.text,
|
|
4212
|
-
steps: [],
|
|
4213
|
-
toolCalls: result.toolCalls.map((tc) => ({
|
|
4214
|
-
type: "tool-call",
|
|
4215
|
-
toolCallId: tc.toolCallId,
|
|
4216
|
-
toolName: tc.toolName,
|
|
4217
|
-
args: tc.args
|
|
4218
|
-
})),
|
|
4219
|
-
toolResults: result.toolResults.map((tr) => ({
|
|
4220
|
-
type: "tool-result",
|
|
4221
|
-
toolCallId: tr.toolCallId,
|
|
4222
|
-
toolName: tr.toolName,
|
|
4223
|
-
output: tr.output
|
|
4224
|
-
})),
|
|
4225
|
-
finishReason: result.finishReason,
|
|
4226
|
-
usage: result.usage ? {
|
|
4227
|
-
promptTokens: result.usage.inputTokens,
|
|
4228
|
-
completionTokens: result.usage.outputTokens,
|
|
4229
|
-
totalTokens: result.usage.totalTokens ?? result.usage.inputTokens + result.usage.outputTokens
|
|
4230
|
-
} : undefined
|
|
4231
|
-
};
|
|
4232
|
-
}
|
|
4233
|
-
getAISDKConfig() {
|
|
4234
|
-
if (this.config.backend !== "ai-sdk")
|
|
4235
|
-
return;
|
|
4236
|
-
return this.config.config;
|
|
4237
|
-
}
|
|
4238
|
-
async resolveAISDKModel() {
|
|
4239
|
-
const backendConfig = this.getAISDKConfig();
|
|
4240
|
-
let model;
|
|
4241
|
-
if (backendConfig?.modelInstance) {
|
|
4242
|
-
model = backendConfig.modelInstance;
|
|
4243
|
-
} else if (backendConfig?.provider) {
|
|
4244
|
-
model = createProvider2(backendConfig.provider).getModel();
|
|
4245
|
-
} else {
|
|
4246
|
-
const { anthropic } = await import("@ai-sdk/anthropic");
|
|
4247
|
-
model = anthropic(backendConfig?.model ?? "claude-3-5-sonnet-20240620");
|
|
4248
|
-
}
|
|
4249
|
-
return this.applyModelSettings(model, {
|
|
4250
|
-
temperature: backendConfig?.temperature,
|
|
4251
|
-
maxTokens: backendConfig?.maxTokens
|
|
4252
|
-
});
|
|
4253
|
-
}
|
|
4254
|
-
applyModelSettings(model, settings) {
|
|
4255
|
-
if (settings.temperature === undefined && settings.maxTokens === undefined) {
|
|
4256
|
-
return model;
|
|
4257
|
-
}
|
|
4258
|
-
const withSettings = model;
|
|
4259
|
-
if (typeof withSettings.withSettings === "function") {
|
|
4260
|
-
return withSettings.withSettings({
|
|
4261
|
-
temperature: settings.temperature,
|
|
4262
|
-
maxTokens: settings.maxTokens
|
|
4263
|
-
});
|
|
4264
|
-
}
|
|
4265
|
-
return model;
|
|
4266
|
-
}
|
|
4267
|
-
getState() {
|
|
4268
|
-
return { ...this.state };
|
|
4269
|
-
}
|
|
4270
|
-
getSpec() {
|
|
4271
|
-
return this.spec;
|
|
4272
|
-
}
|
|
4273
|
-
getBackend() {
|
|
4274
|
-
return this.state.backend;
|
|
4275
|
-
}
|
|
4276
|
-
async isBackendAvailable(backend) {
|
|
4277
|
-
switch (backend) {
|
|
4278
|
-
case "ai-sdk":
|
|
4279
|
-
return true;
|
|
4280
|
-
case "claude-agent-sdk":
|
|
4281
|
-
try {
|
|
4282
|
-
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
4283
|
-
const provider = new ClaudeAgentSDKProvider2({});
|
|
4284
|
-
return provider.isAvailable();
|
|
4285
|
-
} catch {
|
|
4286
|
-
return false;
|
|
4287
|
-
}
|
|
4288
|
-
case "opencode-sdk":
|
|
4289
|
-
try {
|
|
4290
|
-
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
4291
|
-
const provider = new OpenCodeSDKProvider2({});
|
|
4292
|
-
return provider.isAvailable();
|
|
4293
|
-
} catch {
|
|
4294
|
-
return false;
|
|
4295
|
-
}
|
|
4296
|
-
default:
|
|
4297
|
-
return false;
|
|
4298
|
-
}
|
|
4299
|
-
}
|
|
4300
|
-
async switchBackend(backend) {
|
|
4301
|
-
if (backend === this.state.backend) {
|
|
4302
|
-
return;
|
|
4303
|
-
}
|
|
4304
|
-
this.state.backend = backend;
|
|
4305
|
-
this.state.isReady = false;
|
|
4306
|
-
this.provider = undefined;
|
|
4307
|
-
this.context = undefined;
|
|
4308
|
-
await this.initialize();
|
|
4309
|
-
}
|
|
4310
|
-
reset() {
|
|
4311
|
-
this.state.messageCount = 0;
|
|
4312
|
-
this.state.sessionId = undefined;
|
|
4313
|
-
this.state.lastError = undefined;
|
|
4314
|
-
this.context = undefined;
|
|
4315
|
-
}
|
|
4316
|
-
addTool(name, handler) {
|
|
4317
|
-
this.tools.set(name, handler);
|
|
4318
|
-
}
|
|
4319
|
-
removeTool(name) {
|
|
4320
|
-
return this.tools.delete(name);
|
|
4321
|
-
}
|
|
4322
|
-
}
|
|
4323
|
-
function createUnifiedAgent(spec, config) {
|
|
4324
|
-
return new UnifiedAgent(spec, config);
|
|
4325
|
-
}
|
|
4326
|
-
function createAISDKAgent(spec, options) {
|
|
4327
|
-
return new UnifiedAgent(spec, {
|
|
4328
|
-
backend: "ai-sdk",
|
|
4329
|
-
tools: options?.tools,
|
|
4330
|
-
config: {
|
|
4331
|
-
model: options?.model,
|
|
4332
|
-
modelInstance: options?.modelInstance,
|
|
4333
|
-
provider: options?.provider,
|
|
4334
|
-
temperature: options?.temperature,
|
|
4335
|
-
maxTokens: options?.maxTokens
|
|
4336
|
-
}
|
|
4337
|
-
});
|
|
4338
|
-
}
|
|
4339
|
-
function createClaudeAgentSDKAgent(spec, config) {
|
|
4340
|
-
const { tools, ...sdkConfig } = config ?? {};
|
|
4341
|
-
return new UnifiedAgent(spec, {
|
|
4342
|
-
backend: "claude-agent-sdk",
|
|
4343
|
-
tools,
|
|
4344
|
-
config: sdkConfig
|
|
4345
|
-
});
|
|
4346
|
-
}
|
|
4347
|
-
function createOpenCodeSDKAgent(spec, config) {
|
|
4348
|
-
const { tools, ...sdkConfig } = config ?? {};
|
|
4349
|
-
return new UnifiedAgent(spec, {
|
|
4350
|
-
backend: "opencode-sdk",
|
|
4351
|
-
tools,
|
|
4352
|
-
config: sdkConfig
|
|
4353
|
-
});
|
|
4354
|
-
}
|
|
4355
|
-
async function getAvailableBackends() {
|
|
4356
|
-
const backends = ["ai-sdk"];
|
|
4357
|
-
try {
|
|
4358
|
-
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
4359
|
-
const provider = new ClaudeAgentSDKProvider2({});
|
|
4360
|
-
if (provider.isAvailable()) {
|
|
4361
|
-
backends.push("claude-agent-sdk");
|
|
4362
|
-
}
|
|
4363
|
-
} catch {}
|
|
4364
|
-
try {
|
|
4365
|
-
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
4366
|
-
const provider = new OpenCodeSDKProvider2({});
|
|
4367
|
-
if (provider.isAvailable()) {
|
|
4368
|
-
backends.push("opencode-sdk");
|
|
4369
|
-
}
|
|
4370
|
-
} catch {}
|
|
4371
|
-
return backends;
|
|
4372
|
-
}
|
|
4373
|
-
|
|
4374
|
-
// src/agent/index.ts
|
|
4375
|
-
init_contract_spec_agent();
|
|
4376
|
-
|
|
4377
|
-
// src/approval/workflow.ts
|
|
4378
|
-
init_i18n();
|
|
4379
|
-
import { randomUUID } from "node:crypto";
|
|
4380
|
-
|
|
4381
|
-
class InMemoryApprovalStore {
|
|
4382
|
-
items = new Map;
|
|
4383
|
-
async create(request) {
|
|
4384
|
-
this.items.set(request.id, request);
|
|
4385
|
-
}
|
|
4386
|
-
async get(id) {
|
|
4387
|
-
return this.items.get(id) ?? null;
|
|
4388
|
-
}
|
|
4389
|
-
async getByToolCallId(toolCallId) {
|
|
4390
|
-
for (const request of this.items.values()) {
|
|
4391
|
-
if (request.toolCallId === toolCallId) {
|
|
4392
|
-
return request;
|
|
4393
|
-
}
|
|
4394
|
-
}
|
|
4395
|
-
return null;
|
|
4396
|
-
}
|
|
4397
|
-
async update(id, updates) {
|
|
4398
|
-
const existing = this.items.get(id);
|
|
4399
|
-
if (existing) {
|
|
4400
|
-
this.items.set(id, { ...existing, ...updates });
|
|
4401
|
-
}
|
|
4402
|
-
}
|
|
4403
|
-
async list(options) {
|
|
4404
|
-
let results = [...this.items.values()];
|
|
4405
|
-
if (options?.status) {
|
|
4406
|
-
results = results.filter((r) => r.status === options.status);
|
|
4407
|
-
}
|
|
4408
|
-
if (options?.agentId) {
|
|
4409
|
-
results = results.filter((r) => r.agentId === options.agentId);
|
|
4410
|
-
}
|
|
4411
|
-
if (options?.tenantId) {
|
|
4412
|
-
results = results.filter((r) => r.tenantId === options.tenantId);
|
|
4413
|
-
}
|
|
4414
|
-
return results.sort((a, b) => b.requestedAt.getTime() - a.requestedAt.getTime());
|
|
4415
|
-
}
|
|
4416
|
-
clear() {
|
|
4417
|
-
this.items.clear();
|
|
4418
|
-
}
|
|
4419
|
-
}
|
|
4420
|
-
|
|
4421
|
-
class ApprovalWorkflow {
|
|
4422
|
-
store;
|
|
4423
|
-
constructor(store = new InMemoryApprovalStore) {
|
|
4424
|
-
this.store = store;
|
|
4425
|
-
}
|
|
4426
|
-
async requestApproval(params) {
|
|
4427
|
-
const request = {
|
|
4428
|
-
id: randomUUID(),
|
|
4429
|
-
sessionId: params.sessionId,
|
|
4430
|
-
agentId: params.agentId,
|
|
4431
|
-
tenantId: params.tenantId,
|
|
4432
|
-
toolName: params.toolName,
|
|
4433
|
-
toolCallId: params.toolCallId,
|
|
4434
|
-
toolArgs: params.toolArgs,
|
|
4435
|
-
reason: params.reason,
|
|
4436
|
-
requestedAt: new Date,
|
|
4437
|
-
status: "pending",
|
|
4438
|
-
payload: params.payload
|
|
4439
|
-
};
|
|
4440
|
-
await this.store.create(request);
|
|
4441
|
-
return request;
|
|
4442
|
-
}
|
|
4443
|
-
async requestApprovalFromToolCall(toolCall, context) {
|
|
4444
|
-
return this.requestApproval({
|
|
4445
|
-
sessionId: context.sessionId,
|
|
4446
|
-
agentId: context.agentId,
|
|
4447
|
-
tenantId: context.tenantId,
|
|
4448
|
-
toolName: toolCall.toolName,
|
|
4449
|
-
toolCallId: toolCall.toolCallId,
|
|
4450
|
-
toolArgs: toolCall.args,
|
|
4451
|
-
reason: context.reason ?? getDefaultI18n().t("approval.toolRequiresApproval", {
|
|
4452
|
-
name: toolCall.toolName
|
|
4453
|
-
})
|
|
4454
|
-
});
|
|
4455
|
-
}
|
|
4456
|
-
async approve(id, reviewer, notes) {
|
|
4457
|
-
await this.store.update(id, {
|
|
4458
|
-
status: "approved",
|
|
4459
|
-
reviewer,
|
|
4460
|
-
resolvedAt: new Date,
|
|
4461
|
-
notes
|
|
4462
|
-
});
|
|
4463
|
-
}
|
|
4464
|
-
async reject(id, reviewer, notes) {
|
|
4465
|
-
await this.store.update(id, {
|
|
4466
|
-
status: "rejected",
|
|
4467
|
-
reviewer,
|
|
4468
|
-
resolvedAt: new Date,
|
|
4469
|
-
notes
|
|
4470
|
-
});
|
|
4471
|
-
}
|
|
4472
|
-
async getStatus(toolCallId) {
|
|
4473
|
-
const request = await this.store.getByToolCallId(toolCallId);
|
|
4474
|
-
return request?.status ?? null;
|
|
4475
|
-
}
|
|
4476
|
-
async isApproved(toolCallId) {
|
|
4477
|
-
const status = await this.getStatus(toolCallId);
|
|
4478
|
-
return status === "approved";
|
|
4479
|
-
}
|
|
4480
|
-
async listPending(options) {
|
|
4481
|
-
return this.store.list({ ...options, status: "pending" });
|
|
4482
|
-
}
|
|
4483
|
-
async get(id) {
|
|
4484
|
-
return this.store.get(id);
|
|
4485
|
-
}
|
|
4486
|
-
}
|
|
4487
|
-
function createApprovalWorkflow(store) {
|
|
4488
|
-
return new ApprovalWorkflow(store);
|
|
4489
|
-
}
|
|
4490
|
-
// src/exporters/claude-agent-exporter.ts
|
|
4491
|
-
init_spec();
|
|
4492
|
-
init_i18n();
|
|
4493
|
-
|
|
4494
|
-
class ClaudeAgentExporter {
|
|
4495
|
-
format = "claude-agent";
|
|
4496
|
-
export(spec, options = {}) {
|
|
4497
|
-
const tools = this.exportTools(spec);
|
|
4498
|
-
const config = this.buildConfig(spec, tools, options);
|
|
4499
|
-
const claudeMd = options.generateClaudeMd ? this.generateClaudeMd(spec, options) : undefined;
|
|
4500
|
-
return {
|
|
4501
|
-
config,
|
|
4502
|
-
claudeMd,
|
|
4503
|
-
tools,
|
|
4504
|
-
exportedAt: new Date,
|
|
4505
|
-
sourceSpec: agentKey(spec.meta)
|
|
4506
|
-
};
|
|
4507
|
-
}
|
|
4508
|
-
exportMany(specs, options = {}) {
|
|
4509
|
-
return specs.map((spec) => this.export(spec, options));
|
|
4510
|
-
}
|
|
4511
|
-
validate(spec) {
|
|
4512
|
-
const i18n = getDefaultI18n();
|
|
4513
|
-
const errors = [];
|
|
4514
|
-
if (!spec.meta?.key) {
|
|
4515
|
-
errors.push(i18n.t("export.validation.requiresKey"));
|
|
4516
|
-
}
|
|
4517
|
-
if (!spec.instructions) {
|
|
4518
|
-
errors.push(i18n.t("export.validation.requiresInstructions"));
|
|
4519
|
-
}
|
|
4520
|
-
if (!spec.tools || spec.tools.length === 0) {
|
|
4521
|
-
errors.push(i18n.t("export.validation.requiresTool"));
|
|
4522
|
-
}
|
|
4523
|
-
for (const tool3 of spec.tools ?? []) {
|
|
4524
|
-
if (!tool3.name) {
|
|
4525
|
-
errors.push(i18n.t("export.validation.toolRequiresName"));
|
|
4526
|
-
}
|
|
4527
|
-
if (!tool3.description && !tool3.name) {
|
|
4528
|
-
errors.push(i18n.t("export.validation.toolRequiresDescOrName"));
|
|
4529
|
-
}
|
|
4530
|
-
}
|
|
4531
|
-
return { valid: errors.length === 0, errors };
|
|
4532
|
-
}
|
|
4533
|
-
buildConfig(spec, tools, options) {
|
|
4534
|
-
const config = {
|
|
4535
|
-
model: options.model ?? "claude-sonnet-4-20250514",
|
|
4536
|
-
system: this.buildSystemPrompt(spec, options),
|
|
4537
|
-
tools,
|
|
4538
|
-
max_turns: spec.maxSteps ?? 10
|
|
4539
|
-
};
|
|
4540
|
-
if (options.computerUse) {
|
|
4541
|
-
config.computer_use = true;
|
|
4542
|
-
}
|
|
4543
|
-
if (options.extendedThinking) {
|
|
4544
|
-
config.extended_thinking = true;
|
|
4545
|
-
}
|
|
4546
|
-
if (options.mcpServers && options.mcpServers.length > 0) {
|
|
4547
|
-
config.mcp_servers = options.mcpServers;
|
|
4548
|
-
}
|
|
4549
|
-
return config;
|
|
4550
|
-
}
|
|
4551
|
-
buildSystemPrompt(spec, options) {
|
|
4552
|
-
const i18n = getDefaultI18n();
|
|
4553
|
-
const parts = [];
|
|
4554
|
-
parts.push(spec.instructions);
|
|
4555
|
-
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
4556
|
-
parts.push("");
|
|
4557
|
-
parts.push(i18n.t("export.knowledgeSources"));
|
|
4558
|
-
for (const k of spec.knowledge) {
|
|
4559
|
-
if (k.instructions) {
|
|
4560
|
-
parts.push(`- ${k.key}: ${k.instructions}`);
|
|
4561
|
-
}
|
|
4562
|
-
}
|
|
4563
|
-
}
|
|
4564
|
-
if (spec.policy) {
|
|
4565
|
-
parts.push("");
|
|
4566
|
-
parts.push(i18n.t("export.policy"));
|
|
4567
|
-
if (spec.policy.confidence?.min) {
|
|
4568
|
-
parts.push(i18n.t("export.minConfidence", { min: spec.policy.confidence.min }));
|
|
4569
|
-
}
|
|
4570
|
-
if (spec.policy.escalation) {
|
|
4571
|
-
parts.push(i18n.t("export.escalationConfigured"));
|
|
4572
|
-
}
|
|
4573
|
-
}
|
|
4574
|
-
if (options.metadata) {
|
|
4575
|
-
parts.push("");
|
|
4576
|
-
parts.push(i18n.t("export.additionalContext"));
|
|
4577
|
-
for (const [key, value] of Object.entries(options.metadata)) {
|
|
4578
|
-
parts.push(`- ${key}: ${String(value)}`);
|
|
4579
|
-
}
|
|
4580
|
-
}
|
|
4581
|
-
return parts.join(`
|
|
4582
|
-
`);
|
|
4583
|
-
}
|
|
4584
|
-
exportTools(spec) {
|
|
4585
|
-
const i18n = getDefaultI18n();
|
|
4586
|
-
return spec.tools.map((tool3) => ({
|
|
4587
|
-
name: tool3.name,
|
|
4588
|
-
description: tool3.description ?? i18n.t("tool.fallbackDescription", { name: tool3.name }),
|
|
4589
|
-
input_schema: this.normalizeSchema(tool3.schema),
|
|
4590
|
-
requires_confirmation: tool3.requiresApproval ?? !tool3.automationSafe
|
|
4591
|
-
}));
|
|
4592
|
-
}
|
|
4593
|
-
normalizeSchema(schema) {
|
|
4594
|
-
if (!schema) {
|
|
4595
|
-
return { type: "object" };
|
|
4596
|
-
}
|
|
4597
|
-
if (schema.type === "object") {
|
|
4598
|
-
return {
|
|
4599
|
-
type: "object",
|
|
4600
|
-
properties: schema.properties,
|
|
4601
|
-
required: schema.required
|
|
4602
|
-
};
|
|
4603
|
-
}
|
|
4604
|
-
return {
|
|
4605
|
-
type: "object",
|
|
4606
|
-
properties: { value: schema },
|
|
4607
|
-
required: ["value"]
|
|
4608
|
-
};
|
|
4609
|
-
}
|
|
4610
|
-
generateClaudeMd(spec, options) {
|
|
4611
|
-
const i18n = getDefaultI18n();
|
|
4612
|
-
const lines = [];
|
|
4613
|
-
lines.push(i18n.t("export.agentConfiguration"));
|
|
4614
|
-
lines.push("");
|
|
4615
|
-
if (spec.description) {
|
|
4616
|
-
lines.push(`> ${spec.description}`);
|
|
4617
|
-
lines.push("");
|
|
4618
|
-
}
|
|
4619
|
-
lines.push(i18n.t("export.metadata"));
|
|
4620
|
-
lines.push("");
|
|
4621
|
-
lines.push(i18n.t("export.metaName", { name: spec.meta.key }));
|
|
4622
|
-
lines.push(i18n.t("export.metaVersion", { version: spec.meta.version }));
|
|
4623
|
-
if (spec.meta.owners && spec.meta.owners.length > 0) {
|
|
4624
|
-
lines.push(i18n.t("export.metaOwners", {
|
|
4625
|
-
owners: spec.meta.owners.join(", ")
|
|
4626
|
-
}));
|
|
4627
|
-
}
|
|
4628
|
-
if (options.model) {
|
|
4629
|
-
lines.push(i18n.t("export.metaModel", { model: options.model }));
|
|
4630
|
-
}
|
|
4631
|
-
lines.push("");
|
|
4632
|
-
lines.push(i18n.t("export.instructions"));
|
|
4633
|
-
lines.push("");
|
|
4634
|
-
lines.push(spec.instructions);
|
|
4635
|
-
lines.push("");
|
|
4636
|
-
if (spec.tools.length > 0) {
|
|
4637
|
-
lines.push(i18n.t("export.availableTools"));
|
|
4638
|
-
lines.push("");
|
|
4639
|
-
for (const tool3 of spec.tools) {
|
|
4640
|
-
const flags = [];
|
|
4641
|
-
if (tool3.requiresApproval) {
|
|
4642
|
-
flags.push(i18n.t("export.requiresApproval"));
|
|
4643
|
-
}
|
|
4644
|
-
if (tool3.automationSafe === false) {
|
|
4645
|
-
flags.push(i18n.t("export.notAutomationSafe"));
|
|
4646
|
-
}
|
|
4647
|
-
const flagStr = flags.length > 0 ? ` (${flags.join(", ")})` : "";
|
|
4648
|
-
lines.push(`### ${tool3.name}${flagStr}`);
|
|
4649
|
-
lines.push("");
|
|
4650
|
-
if (tool3.description) {
|
|
4651
|
-
lines.push(tool3.description);
|
|
4652
|
-
lines.push("");
|
|
4653
|
-
}
|
|
4654
|
-
if (tool3.schema) {
|
|
4655
|
-
lines.push(i18n.t("export.parameters"));
|
|
4656
|
-
lines.push("```json");
|
|
4657
|
-
lines.push(JSON.stringify(tool3.schema, null, 2));
|
|
4658
|
-
lines.push("```");
|
|
4659
|
-
lines.push("");
|
|
4660
|
-
}
|
|
4661
|
-
}
|
|
4662
|
-
}
|
|
4663
|
-
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
4664
|
-
lines.push(i18n.t("export.knowledgeSources"));
|
|
4665
|
-
lines.push("");
|
|
4666
|
-
for (const k of spec.knowledge) {
|
|
4667
|
-
const required = k.required ? i18n.t("export.required") : i18n.t("export.optional");
|
|
4668
|
-
lines.push(`- **${k.key}** ${required}`);
|
|
4669
|
-
if (k.instructions) {
|
|
4670
|
-
lines.push(` - ${k.instructions}`);
|
|
4671
|
-
}
|
|
4672
|
-
}
|
|
4673
|
-
lines.push("");
|
|
4674
|
-
}
|
|
4675
|
-
if (spec.policy) {
|
|
4676
|
-
lines.push(i18n.t("export.policy"));
|
|
4677
|
-
lines.push("");
|
|
4678
|
-
if (spec.policy.confidence?.min) {
|
|
4679
|
-
lines.push(i18n.t("export.minConfidence", { min: spec.policy.confidence.min }));
|
|
4680
|
-
}
|
|
4681
|
-
if (spec.policy.escalation) {
|
|
4682
|
-
lines.push(i18n.t("export.escalationPolicyConfigured"));
|
|
4683
|
-
}
|
|
4684
|
-
if (spec.policy.flags && spec.policy.flags.length > 0) {
|
|
4685
|
-
lines.push(i18n.t("export.featureFlags", {
|
|
4686
|
-
flags: spec.policy.flags.join(", ")
|
|
4687
|
-
}));
|
|
4688
|
-
}
|
|
4689
|
-
lines.push("");
|
|
4690
|
-
}
|
|
4691
|
-
if (options.mcpServers && options.mcpServers.length > 0) {
|
|
4692
|
-
lines.push(i18n.t("export.mcpServers"));
|
|
4693
|
-
lines.push("");
|
|
4694
|
-
for (const server of options.mcpServers) {
|
|
4695
|
-
lines.push(`- **${server.name}**: \`${server.command}${server.args ? " " + server.args.join(" ") : ""}\``);
|
|
4696
|
-
}
|
|
4697
|
-
lines.push("");
|
|
4698
|
-
}
|
|
4699
|
-
lines.push("---");
|
|
4700
|
-
lines.push("");
|
|
4701
|
-
lines.push(i18n.t("export.generatedFrom", { key: agentKey(spec.meta) }));
|
|
4702
|
-
return lines.join(`
|
|
4703
|
-
`);
|
|
4704
|
-
}
|
|
4705
|
-
}
|
|
4706
|
-
function exportToClaudeAgent(spec, options) {
|
|
4707
|
-
const exporter = new ClaudeAgentExporter;
|
|
4708
|
-
return exporter.export(spec, options);
|
|
4709
|
-
}
|
|
4710
|
-
function generateClaudeMd(spec, options) {
|
|
4711
|
-
const exporter = new ClaudeAgentExporter;
|
|
4712
|
-
const result = exporter.export(spec, { ...options, generateClaudeMd: true });
|
|
4713
|
-
return result.claudeMd ?? "";
|
|
4714
|
-
}
|
|
4715
|
-
function validateForClaudeAgent(spec) {
|
|
4716
|
-
const exporter = new ClaudeAgentExporter;
|
|
4717
|
-
return exporter.validate(spec);
|
|
4718
|
-
}
|
|
4719
|
-
// src/exporters/opencode-exporter.ts
|
|
4720
|
-
init_spec();
|
|
4721
|
-
init_agent_bridge();
|
|
4722
|
-
init_i18n();
|
|
4723
|
-
|
|
4724
|
-
class OpenCodeExporter {
|
|
4725
|
-
format = "opencode";
|
|
4726
|
-
export(spec, options = {}) {
|
|
4727
|
-
const jsonConfig = this.buildJsonConfig(spec, options);
|
|
4728
|
-
const markdownConfig = this.generateMarkdown(spec, jsonConfig, options);
|
|
4729
|
-
return {
|
|
4730
|
-
jsonConfig,
|
|
4731
|
-
markdownConfig,
|
|
4732
|
-
exportedAt: new Date,
|
|
4733
|
-
sourceSpec: agentKey(spec.meta)
|
|
4734
|
-
};
|
|
4735
|
-
}
|
|
4736
|
-
exportMany(specs, options = {}) {
|
|
4737
|
-
return specs.map((spec) => this.export(spec, options));
|
|
4738
|
-
}
|
|
4739
|
-
validate(spec) {
|
|
4740
|
-
const i18n = getDefaultI18n();
|
|
4741
|
-
const errors = [];
|
|
4742
|
-
if (!spec.meta?.key) {
|
|
4743
|
-
errors.push(i18n.t("export.validation.requiresKey"));
|
|
4744
|
-
}
|
|
4745
|
-
if (!spec.instructions) {
|
|
4746
|
-
errors.push(i18n.t("export.validation.requiresInstructions"));
|
|
4747
|
-
}
|
|
4748
|
-
for (const tool3 of spec.tools ?? []) {
|
|
4749
|
-
if (!tool3.name) {
|
|
4750
|
-
errors.push(i18n.t("export.validation.toolRequiresName"));
|
|
4751
|
-
}
|
|
4752
|
-
if (tool3.name && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tool3.name)) {
|
|
4753
|
-
errors.push(i18n.t("export.validation.toolInvalidName", { name: tool3.name }));
|
|
4754
|
-
}
|
|
4755
|
-
}
|
|
4756
|
-
return { valid: errors.length === 0, errors };
|
|
4757
|
-
}
|
|
4758
|
-
buildJsonConfig(spec, options) {
|
|
4759
|
-
const agentType = options.agentType ?? inferAgentType(spec);
|
|
4760
|
-
return {
|
|
4761
|
-
name: spec.meta.key,
|
|
4762
|
-
version: spec.meta.version,
|
|
4763
|
-
description: spec.description,
|
|
4764
|
-
type: agentType,
|
|
4765
|
-
instructions: spec.instructions,
|
|
4766
|
-
tools: this.exportTools(spec),
|
|
4767
|
-
config: {
|
|
4768
|
-
max_steps: options.maxSteps ?? spec.maxSteps ?? 10,
|
|
4769
|
-
temperature: options.temperature ?? 0.7,
|
|
4770
|
-
model: options.model
|
|
4771
|
-
}
|
|
4772
|
-
};
|
|
4773
|
-
}
|
|
4774
|
-
exportTools(spec) {
|
|
4775
|
-
const i18n = getDefaultI18n();
|
|
4776
|
-
return spec.tools.map((tool3) => ({
|
|
4777
|
-
name: tool3.name,
|
|
4778
|
-
description: tool3.description ?? i18n.t("tool.fallbackDescription", { name: tool3.name }),
|
|
4779
|
-
schema: tool3.schema ?? { type: "object" },
|
|
4780
|
-
requires_approval: tool3.requiresApproval ?? !tool3.automationSafe
|
|
4781
|
-
}));
|
|
4782
|
-
}
|
|
4783
|
-
generateMarkdown(spec, jsonConfig, options) {
|
|
4784
|
-
const i18n = getDefaultI18n();
|
|
4785
|
-
const lines = [];
|
|
4786
|
-
lines.push("---");
|
|
4787
|
-
lines.push(`name: ${jsonConfig.name}`);
|
|
4788
|
-
lines.push(`type: ${jsonConfig.type}`);
|
|
4789
|
-
if (jsonConfig.version) {
|
|
4790
|
-
lines.push(`version: ${jsonConfig.version}`);
|
|
4791
|
-
}
|
|
4792
|
-
if (jsonConfig.config.model) {
|
|
4793
|
-
lines.push(`model: ${jsonConfig.config.model}`);
|
|
4794
|
-
}
|
|
4795
|
-
if (jsonConfig.config.temperature !== undefined) {
|
|
4796
|
-
lines.push(`temperature: ${jsonConfig.config.temperature}`);
|
|
4797
|
-
}
|
|
4798
|
-
if (jsonConfig.config.max_steps !== undefined) {
|
|
4799
|
-
lines.push(`max_steps: ${jsonConfig.config.max_steps}`);
|
|
4800
|
-
}
|
|
4801
|
-
if (jsonConfig.tools.length > 0) {
|
|
4802
|
-
lines.push("tools:");
|
|
4803
|
-
for (const tool3 of jsonConfig.tools) {
|
|
4804
|
-
const permission = tool3.requires_approval ? ` # ${i18n.t("export.requiresApproval")}` : "";
|
|
4805
|
-
lines.push(` - ${tool3.name}${permission}`);
|
|
4806
|
-
}
|
|
4807
|
-
}
|
|
4808
|
-
lines.push("---");
|
|
4809
|
-
lines.push("");
|
|
4810
|
-
lines.push(`# ${spec.meta.key}`);
|
|
4811
|
-
lines.push("");
|
|
4812
|
-
if (spec.description) {
|
|
4813
|
-
lines.push(spec.description);
|
|
4814
|
-
lines.push("");
|
|
4815
|
-
}
|
|
4816
|
-
lines.push(i18n.t("export.agentType", { type: jsonConfig.type }));
|
|
4817
|
-
lines.push("");
|
|
4818
|
-
lines.push(this.getAgentTypeDescription(jsonConfig.type));
|
|
4819
|
-
lines.push("");
|
|
4820
|
-
lines.push(i18n.t("export.instructions"));
|
|
4821
|
-
lines.push("");
|
|
4822
|
-
lines.push(spec.instructions);
|
|
4823
|
-
lines.push("");
|
|
4824
|
-
if (spec.tools.length > 0) {
|
|
4825
|
-
lines.push(i18n.t("export.tools"));
|
|
4826
|
-
lines.push("");
|
|
4827
|
-
for (const tool3 of spec.tools) {
|
|
4828
|
-
const approval = tool3.requiresApproval ? ` ${i18n.t("export.requiresApprovalMd")}` : "";
|
|
4829
|
-
const safe = tool3.automationSafe === false ? ` ${i18n.t("export.notAutomationSafeMd")}` : "";
|
|
4830
|
-
lines.push(`### ${tool3.name}${approval}${safe}`);
|
|
4831
|
-
lines.push("");
|
|
4832
|
-
if (tool3.description) {
|
|
4833
|
-
lines.push(tool3.description);
|
|
4834
|
-
lines.push("");
|
|
4835
|
-
}
|
|
4836
|
-
if (tool3.schema && options.includeComments !== false) {
|
|
4837
|
-
lines.push(i18n.t("export.parameters"));
|
|
4838
|
-
lines.push("");
|
|
4839
|
-
lines.push("```json");
|
|
4840
|
-
lines.push(JSON.stringify(tool3.schema, null, options.prettyPrint !== false ? 2 : 0));
|
|
4841
|
-
lines.push("```");
|
|
4842
|
-
lines.push("");
|
|
4843
|
-
}
|
|
4844
|
-
}
|
|
4845
|
-
}
|
|
4846
|
-
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
4847
|
-
lines.push(i18n.t("export.knowledgeSources"));
|
|
4848
|
-
lines.push("");
|
|
4849
|
-
for (const k of spec.knowledge) {
|
|
4850
|
-
const required = k.required ? i18n.t("export.required") : i18n.t("export.optional");
|
|
4851
|
-
lines.push(`- **${k.key}** ${required}`);
|
|
4852
|
-
if (k.instructions) {
|
|
4853
|
-
lines.push(` - ${k.instructions}`);
|
|
4854
|
-
}
|
|
4855
|
-
}
|
|
4856
|
-
lines.push("");
|
|
4857
|
-
}
|
|
4858
|
-
if (spec.policy) {
|
|
4859
|
-
lines.push(i18n.t("export.policy"));
|
|
4860
|
-
lines.push("");
|
|
4861
|
-
if (spec.policy.confidence?.min) {
|
|
4862
|
-
lines.push(i18n.t("export.minConfidence", { min: spec.policy.confidence.min }));
|
|
4863
|
-
}
|
|
4864
|
-
if (spec.policy.escalation) {
|
|
4865
|
-
lines.push(i18n.t("export.escalationPolicyConfigured"));
|
|
4866
|
-
}
|
|
4867
|
-
lines.push("");
|
|
4868
|
-
}
|
|
4869
|
-
lines.push(i18n.t("export.configuration"));
|
|
4870
|
-
lines.push("");
|
|
4871
|
-
lines.push("```json");
|
|
4872
|
-
lines.push(JSON.stringify(jsonConfig.config, null, options.prettyPrint !== false ? 2 : 0));
|
|
4873
|
-
lines.push("```");
|
|
4874
|
-
lines.push("");
|
|
4875
|
-
lines.push("---");
|
|
4876
|
-
lines.push("");
|
|
4877
|
-
lines.push(i18n.t("export.generatedFrom", { key: agentKey(spec.meta) }));
|
|
4878
|
-
lines.push(i18n.t("export.exportedAt", { date: new Date().toISOString() }));
|
|
4879
|
-
return lines.join(`
|
|
4880
|
-
`);
|
|
4881
|
-
}
|
|
4882
|
-
getAgentTypeDescription(type) {
|
|
4883
|
-
const i18n = getDefaultI18n();
|
|
4884
|
-
switch (type) {
|
|
4885
|
-
case "build":
|
|
4886
|
-
return i18n.t("export.agentType.build");
|
|
4887
|
-
case "plan":
|
|
4888
|
-
return i18n.t("export.agentType.plan");
|
|
4889
|
-
case "general":
|
|
4890
|
-
return i18n.t("export.agentType.general");
|
|
4891
|
-
case "explore":
|
|
4892
|
-
return i18n.t("export.agentType.explore");
|
|
4893
|
-
default:
|
|
4894
|
-
return "";
|
|
4895
|
-
}
|
|
4896
|
-
}
|
|
4897
|
-
}
|
|
4898
|
-
function exportToOpenCode(spec, options) {
|
|
4899
|
-
const exporter = new OpenCodeExporter;
|
|
4900
|
-
return exporter.export(spec, options);
|
|
4901
|
-
}
|
|
4902
|
-
function generateOpenCodeMarkdown(spec, options) {
|
|
4903
|
-
const exporter = new OpenCodeExporter;
|
|
4904
|
-
const result = exporter.export(spec, options);
|
|
4905
|
-
return result.markdownConfig;
|
|
4906
|
-
}
|
|
4907
|
-
function generateOpenCodeJSON(spec, options) {
|
|
4908
|
-
const exporter = new OpenCodeExporter;
|
|
4909
|
-
const result = exporter.export(spec, options);
|
|
4910
|
-
return result.jsonConfig;
|
|
4911
|
-
}
|
|
4912
|
-
function validateForOpenCode(spec) {
|
|
4913
|
-
const exporter = new OpenCodeExporter;
|
|
4914
|
-
return exporter.validate(spec);
|
|
4915
|
-
}
|
|
4916
2140
|
// src/spec/registry.ts
|
|
4917
2141
|
init_i18n();
|
|
4918
2142
|
import { compareVersions } from "compare-versions";
|
|
4919
|
-
import { SpecContractRegistry } from "@contractspec/lib.contracts/registry";
|
|
2143
|
+
import { SpecContractRegistry } from "@contractspec/lib.contracts-spec/registry";
|
|
4920
2144
|
|
|
4921
2145
|
class AgentRegistry extends SpecContractRegistry {
|
|
4922
2146
|
constructor(items) {
|
|
@@ -4957,750 +2181,9 @@ function createAgentRegistry() {
|
|
|
4957
2181
|
|
|
4958
2182
|
// src/spec/index.ts
|
|
4959
2183
|
init_spec();
|
|
4960
|
-
// src/tools/mcp-client.ts
|
|
4961
|
-
import { experimental_createMCPClient } from "@ai-sdk/mcp";
|
|
4962
|
-
import { Experimental_StdioMCPTransport as StdioClientTransport } from "@ai-sdk/mcp/mcp-stdio";
|
|
4963
|
-
async function mcpServerToTools(config) {
|
|
4964
|
-
const transport = new StdioClientTransport({
|
|
4965
|
-
command: config.command,
|
|
4966
|
-
args: config.args,
|
|
4967
|
-
env: config.env
|
|
4968
|
-
});
|
|
4969
|
-
const client = await experimental_createMCPClient({ transport });
|
|
4970
|
-
const tools = await client.tools();
|
|
4971
|
-
return {
|
|
4972
|
-
tools,
|
|
4973
|
-
cleanup: () => client.close()
|
|
4974
|
-
};
|
|
4975
|
-
}
|
|
4976
|
-
async function createMcpToolsets(configs) {
|
|
4977
|
-
const results = await Promise.all(configs.map(mcpServerToTools));
|
|
4978
|
-
const combinedTools = {};
|
|
4979
|
-
for (const result of results) {
|
|
4980
|
-
Object.assign(combinedTools, result.tools);
|
|
4981
|
-
}
|
|
4982
|
-
return {
|
|
4983
|
-
tools: combinedTools,
|
|
4984
|
-
cleanup: async () => {
|
|
4985
|
-
await Promise.all(results.map((r) => r.cleanup()));
|
|
4986
|
-
}
|
|
4987
|
-
};
|
|
4988
|
-
}
|
|
4989
|
-
|
|
4990
|
-
// src/tools/mcp-server.ts
|
|
4991
|
-
init_json_schema_to_zod();
|
|
4992
|
-
init_i18n();
|
|
4993
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4994
|
-
import * as z4 from "zod";
|
|
4995
|
-
function agentToMcpServer(agent, spec2) {
|
|
4996
|
-
const i18n = createAgentI18n();
|
|
4997
|
-
const server = new McpServer({
|
|
4998
|
-
name: spec2.meta.key,
|
|
4999
|
-
version: `${spec2.meta.version}`
|
|
5000
|
-
});
|
|
5001
|
-
server.registerTool(spec2.meta.key, {
|
|
5002
|
-
description: spec2.description ?? i18n.t("tool.mcp.agentDescription", { key: spec2.meta.key }),
|
|
5003
|
-
inputSchema: z4.object({
|
|
5004
|
-
message: z4.string().describe(i18n.t("tool.mcp.param.message")),
|
|
5005
|
-
sessionId: z4.string().optional().describe(i18n.t("tool.mcp.param.sessionId"))
|
|
5006
|
-
})
|
|
5007
|
-
}, async (args) => {
|
|
5008
|
-
const { message, sessionId } = args;
|
|
5009
|
-
const result = await agent.generate({
|
|
5010
|
-
prompt: message,
|
|
5011
|
-
options: { sessionId }
|
|
5012
|
-
});
|
|
5013
|
-
return {
|
|
5014
|
-
content: [
|
|
5015
|
-
{
|
|
5016
|
-
type: "text",
|
|
5017
|
-
text: result.text
|
|
5018
|
-
}
|
|
5019
|
-
]
|
|
5020
|
-
};
|
|
5021
|
-
});
|
|
5022
|
-
for (const toolConfig of spec2.tools) {
|
|
5023
|
-
const inputSchema = toolConfig.schema ? jsonSchemaToZodSafe(toolConfig.schema) : z4.object({});
|
|
5024
|
-
server.registerTool(`${spec2.meta.key}.${toolConfig.name}`, {
|
|
5025
|
-
description: toolConfig.description ?? i18n.t("tool.mcp.toolDescription", { name: toolConfig.name }),
|
|
5026
|
-
inputSchema
|
|
5027
|
-
}, async (args) => {
|
|
5028
|
-
const result = await agent.generate({
|
|
5029
|
-
prompt: i18n.t("tool.mcp.executePrompt", {
|
|
5030
|
-
name: toolConfig.name,
|
|
5031
|
-
args: JSON.stringify(args)
|
|
5032
|
-
})
|
|
5033
|
-
});
|
|
5034
|
-
return {
|
|
5035
|
-
content: [
|
|
5036
|
-
{
|
|
5037
|
-
type: "text",
|
|
5038
|
-
text: result.text
|
|
5039
|
-
}
|
|
5040
|
-
]
|
|
5041
|
-
};
|
|
5042
|
-
});
|
|
5043
|
-
}
|
|
5044
|
-
return server;
|
|
5045
|
-
}
|
|
5046
|
-
function createAgentMcpServer(config) {
|
|
5047
|
-
return agentToMcpServer(config.agent, config.spec);
|
|
5048
|
-
}
|
|
5049
|
-
|
|
5050
|
-
// src/tools/index.ts
|
|
5051
|
-
init_tool_adapter();
|
|
5052
|
-
init_knowledge_tool();
|
|
5053
|
-
|
|
5054
|
-
// src/schema/schema-output.ts
|
|
5055
|
-
init_json_schema_to_zod();
|
|
5056
|
-
import { Output } from "ai";
|
|
5057
|
-
function jsonSchemaToOutput(schema) {
|
|
5058
|
-
const zodSchema = jsonSchemaToZod(schema);
|
|
5059
|
-
return Output.object({
|
|
5060
|
-
schema: zodSchema
|
|
5061
|
-
});
|
|
5062
|
-
}
|
|
5063
|
-
function jsonSchemaToArrayOutput(itemSchema) {
|
|
5064
|
-
const zodSchema = jsonSchemaToZod(itemSchema);
|
|
5065
|
-
return Output.array({
|
|
5066
|
-
element: zodSchema
|
|
5067
|
-
});
|
|
5068
|
-
}
|
|
5069
|
-
function enumToChoiceOutput(choices) {
|
|
5070
|
-
return Output.choice({
|
|
5071
|
-
options: choices
|
|
5072
|
-
});
|
|
5073
|
-
}
|
|
5074
|
-
function zodToOutput(schema) {
|
|
5075
|
-
return Output.object({
|
|
5076
|
-
schema
|
|
5077
|
-
});
|
|
5078
|
-
}
|
|
5079
|
-
function textOutput() {
|
|
5080
|
-
return Output.text();
|
|
5081
|
-
}
|
|
5082
|
-
var SchemaOutput = {
|
|
5083
|
-
fromJsonSchema: jsonSchemaToOutput,
|
|
5084
|
-
arrayFromJsonSchema: jsonSchemaToArrayOutput,
|
|
5085
|
-
fromEnum: enumToChoiceOutput,
|
|
5086
|
-
fromZod: zodToOutput,
|
|
5087
|
-
text: textOutput
|
|
5088
|
-
};
|
|
5089
|
-
|
|
5090
|
-
// src/schema/index.ts
|
|
5091
|
-
init_json_schema_to_zod();
|
|
5092
|
-
|
|
5093
|
-
// src/knowledge/index.ts
|
|
5094
|
-
init_injector();
|
|
5095
|
-
// src/telemetry/index.ts
|
|
5096
|
-
init_adapter();
|
|
5097
|
-
|
|
5098
|
-
// src/providers/registry.ts
|
|
5099
|
-
init_types();
|
|
5100
|
-
init_i18n();
|
|
5101
|
-
|
|
5102
|
-
class InMemoryProviderRegistry {
|
|
5103
|
-
providers = new Map;
|
|
5104
|
-
get(name) {
|
|
5105
|
-
return this.providers.get(name);
|
|
5106
|
-
}
|
|
5107
|
-
register(name, provider) {
|
|
5108
|
-
this.providers.set(name, provider);
|
|
5109
|
-
}
|
|
5110
|
-
list() {
|
|
5111
|
-
return Array.from(this.providers.keys());
|
|
5112
|
-
}
|
|
5113
|
-
isAvailable(name) {
|
|
5114
|
-
const provider = this.providers.get(name);
|
|
5115
|
-
return provider !== undefined && provider.isAvailable();
|
|
5116
|
-
}
|
|
5117
|
-
require(name) {
|
|
5118
|
-
const provider = this.providers.get(name);
|
|
5119
|
-
if (!provider) {
|
|
5120
|
-
throw new ProviderNotAvailableError(name, getDefaultI18n().t("error.provider.notRegistered"));
|
|
5121
|
-
}
|
|
5122
|
-
if (!provider.isAvailable()) {
|
|
5123
|
-
throw new ProviderNotAvailableError(name, getDefaultI18n().t("error.provider.depsNotInstalled"));
|
|
5124
|
-
}
|
|
5125
|
-
return provider;
|
|
5126
|
-
}
|
|
5127
|
-
clear() {
|
|
5128
|
-
this.providers.clear();
|
|
5129
|
-
}
|
|
5130
|
-
}
|
|
5131
|
-
function createProviderRegistry() {
|
|
5132
|
-
return new InMemoryProviderRegistry;
|
|
5133
|
-
}
|
|
5134
|
-
var defaultProviderRegistry = createProviderRegistry();
|
|
5135
|
-
|
|
5136
|
-
// src/providers/index.ts
|
|
5137
|
-
init_claude_agent_sdk();
|
|
5138
|
-
init_opencode_sdk();
|
|
5139
|
-
init_types();
|
|
5140
|
-
// src/interop/spec-consumer.ts
|
|
5141
|
-
init_spec();
|
|
5142
|
-
init_i18n();
|
|
5143
|
-
|
|
5144
|
-
class ContractSpecConsumer {
|
|
5145
|
-
specs;
|
|
5146
|
-
includeMetadata;
|
|
5147
|
-
baseUrl;
|
|
5148
|
-
constructor(config) {
|
|
5149
|
-
this.specs = new Map;
|
|
5150
|
-
this.includeMetadata = config.includeMetadata ?? true;
|
|
5151
|
-
this.baseUrl = config.baseUrl;
|
|
5152
|
-
for (const spec2 of config.specs) {
|
|
5153
|
-
const key = agentKey(spec2.meta);
|
|
5154
|
-
this.specs.set(key, spec2);
|
|
5155
|
-
}
|
|
5156
|
-
}
|
|
5157
|
-
getSpecMarkdown(specKey, options) {
|
|
5158
|
-
const spec2 = this.specs.get(specKey);
|
|
5159
|
-
if (!spec2) {
|
|
5160
|
-
throw new Error(getDefaultI18n().t("error.specNotFound", { specKey }));
|
|
5161
|
-
}
|
|
5162
|
-
const i18n = getDefaultI18n();
|
|
5163
|
-
const sections = [];
|
|
5164
|
-
const opts = {
|
|
5165
|
-
includeToc: options?.includeToc ?? true,
|
|
5166
|
-
includeTools: options?.includeTools ?? true,
|
|
5167
|
-
...options
|
|
5168
|
-
};
|
|
5169
|
-
if (opts.customHeader) {
|
|
5170
|
-
sections.push(opts.customHeader);
|
|
5171
|
-
sections.push("");
|
|
5172
|
-
}
|
|
5173
|
-
const specName = spec2.meta.key;
|
|
5174
|
-
sections.push(`# ${specName}`);
|
|
5175
|
-
sections.push("");
|
|
5176
|
-
if (spec2.description) {
|
|
5177
|
-
sections.push(spec2.description);
|
|
5178
|
-
sections.push("");
|
|
5179
|
-
}
|
|
5180
|
-
if (opts.includeToc) {
|
|
5181
|
-
sections.push(i18n.t("interop.md.toc"));
|
|
5182
|
-
sections.push("");
|
|
5183
|
-
sections.push("- [Overview](#overview)");
|
|
5184
|
-
sections.push("- [Instructions](#instructions)");
|
|
5185
|
-
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
5186
|
-
sections.push("- [Tools](#tools)");
|
|
5187
|
-
}
|
|
5188
|
-
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
5189
|
-
sections.push("- [Knowledge](#knowledge)");
|
|
5190
|
-
}
|
|
5191
|
-
sections.push("");
|
|
5192
|
-
}
|
|
5193
|
-
sections.push(i18n.t("interop.md.overview"));
|
|
5194
|
-
sections.push("");
|
|
5195
|
-
if (this.includeMetadata) {
|
|
5196
|
-
sections.push(i18n.t("interop.md.metaKey", { key: spec2.meta.key }));
|
|
5197
|
-
sections.push(i18n.t("interop.md.metaVersion", { version: spec2.meta.version }));
|
|
5198
|
-
if (spec2.meta.stability) {
|
|
5199
|
-
sections.push(i18n.t("interop.md.metaStability", {
|
|
5200
|
-
stability: spec2.meta.stability
|
|
5201
|
-
}));
|
|
5202
|
-
}
|
|
5203
|
-
if (spec2.meta.owners && spec2.meta.owners.length > 0) {
|
|
5204
|
-
sections.push(i18n.t("interop.md.metaOwners", {
|
|
5205
|
-
owners: spec2.meta.owners.join(", ")
|
|
5206
|
-
}));
|
|
5207
|
-
}
|
|
5208
|
-
if (spec2.tags && spec2.tags.length > 0) {
|
|
5209
|
-
sections.push(i18n.t("interop.md.metaTags", { tags: spec2.tags.join(", ") }));
|
|
5210
|
-
}
|
|
5211
|
-
}
|
|
5212
|
-
sections.push("");
|
|
5213
|
-
sections.push(i18n.t("interop.prompt.instructions"));
|
|
5214
|
-
sections.push("");
|
|
5215
|
-
sections.push(spec2.instructions);
|
|
5216
|
-
sections.push("");
|
|
5217
|
-
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
5218
|
-
sections.push(i18n.t("interop.md.tools"));
|
|
5219
|
-
sections.push("");
|
|
5220
|
-
for (const tool3 of spec2.tools) {
|
|
5221
|
-
sections.push(`### ${tool3.name}`);
|
|
5222
|
-
sections.push("");
|
|
5223
|
-
if (tool3.description) {
|
|
5224
|
-
sections.push(tool3.description);
|
|
5225
|
-
sections.push("");
|
|
5226
|
-
}
|
|
5227
|
-
if (tool3.schema) {
|
|
5228
|
-
sections.push(i18n.t("interop.md.schema"));
|
|
5229
|
-
sections.push("");
|
|
5230
|
-
sections.push("```json");
|
|
5231
|
-
sections.push(JSON.stringify(tool3.schema, null, 2));
|
|
5232
|
-
sections.push("```");
|
|
5233
|
-
sections.push("");
|
|
5234
|
-
}
|
|
5235
|
-
if (tool3.automationSafe !== undefined) {
|
|
5236
|
-
sections.push(i18n.t("interop.md.automationSafe", {
|
|
5237
|
-
value: tool3.automationSafe ? i18n.t("interop.md.yes") : i18n.t("interop.md.no")
|
|
5238
|
-
}));
|
|
5239
|
-
sections.push("");
|
|
5240
|
-
}
|
|
5241
|
-
}
|
|
5242
|
-
}
|
|
5243
|
-
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
5244
|
-
sections.push(i18n.t("interop.md.knowledge"));
|
|
5245
|
-
sections.push("");
|
|
5246
|
-
for (const k of spec2.knowledge) {
|
|
5247
|
-
const marker = k.required ? ` ${i18n.t("interop.md.required")}` : "";
|
|
5248
|
-
sections.push(`- **${k.key}**${marker}`);
|
|
5249
|
-
if (k.instructions) {
|
|
5250
|
-
sections.push(` - ${k.instructions}`);
|
|
5251
|
-
}
|
|
5252
|
-
}
|
|
5253
|
-
sections.push("");
|
|
5254
|
-
}
|
|
5255
|
-
if (spec2.policy) {
|
|
5256
|
-
sections.push(i18n.t("interop.md.policy"));
|
|
5257
|
-
sections.push("");
|
|
5258
|
-
if (spec2.policy.confidence) {
|
|
5259
|
-
sections.push(i18n.t("interop.md.minConfidence", {
|
|
5260
|
-
min: spec2.policy.confidence.min ?? 0.7
|
|
5261
|
-
}));
|
|
5262
|
-
}
|
|
5263
|
-
if (spec2.policy.escalation) {
|
|
5264
|
-
const esc = spec2.policy.escalation;
|
|
5265
|
-
if (esc.confidenceThreshold) {
|
|
5266
|
-
sections.push(i18n.t("interop.md.escalationThreshold", {
|
|
5267
|
-
threshold: esc.confidenceThreshold
|
|
5268
|
-
}));
|
|
5269
|
-
}
|
|
5270
|
-
if (esc.onToolFailure) {
|
|
5271
|
-
sections.push(i18n.t("interop.md.escalateToolFailure"));
|
|
5272
|
-
}
|
|
5273
|
-
if (esc.onTimeout) {
|
|
5274
|
-
sections.push(i18n.t("interop.md.escalateTimeout"));
|
|
5275
|
-
}
|
|
5276
|
-
}
|
|
5277
|
-
sections.push("");
|
|
5278
|
-
}
|
|
5279
|
-
return sections.join(`
|
|
5280
|
-
`);
|
|
5281
|
-
}
|
|
5282
|
-
getSpecPrompt(specKey, options) {
|
|
5283
|
-
const spec2 = this.specs.get(specKey);
|
|
5284
|
-
if (!spec2) {
|
|
5285
|
-
throw new Error(getDefaultI18n().t("error.specNotFound", { specKey }));
|
|
5286
|
-
}
|
|
5287
|
-
const i18n = getDefaultI18n();
|
|
5288
|
-
const sections = [];
|
|
5289
|
-
const opts = {
|
|
5290
|
-
includeTools: options?.includeTools ?? true,
|
|
5291
|
-
format: options?.format ?? "structured",
|
|
5292
|
-
...options
|
|
5293
|
-
};
|
|
5294
|
-
sections.push(i18n.t("interop.prompt.agentIdentity"));
|
|
5295
|
-
sections.push("");
|
|
5296
|
-
sections.push(i18n.t("interop.prompt.youAre", {
|
|
5297
|
-
key: spec2.meta.key,
|
|
5298
|
-
version: spec2.meta.version
|
|
5299
|
-
}));
|
|
5300
|
-
sections.push("");
|
|
5301
|
-
if (spec2.description) {
|
|
5302
|
-
sections.push(i18n.t("interop.prompt.description"));
|
|
5303
|
-
sections.push("");
|
|
5304
|
-
sections.push(spec2.description);
|
|
5305
|
-
sections.push("");
|
|
5306
|
-
}
|
|
5307
|
-
sections.push(i18n.t("interop.prompt.instructions"));
|
|
5308
|
-
sections.push("");
|
|
5309
|
-
sections.push(spec2.instructions);
|
|
5310
|
-
sections.push("");
|
|
5311
|
-
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
5312
|
-
sections.push(i18n.t("interop.prompt.availableTools"));
|
|
5313
|
-
sections.push("");
|
|
5314
|
-
sections.push(i18n.t("interop.prompt.toolsIntro"));
|
|
5315
|
-
sections.push("");
|
|
5316
|
-
for (const tool3 of spec2.tools) {
|
|
5317
|
-
sections.push(`### ${tool3.name}`);
|
|
5318
|
-
sections.push("");
|
|
5319
|
-
if (tool3.description) {
|
|
5320
|
-
sections.push(tool3.description);
|
|
5321
|
-
sections.push("");
|
|
5322
|
-
}
|
|
5323
|
-
if (tool3.schema && opts.format === "structured") {
|
|
5324
|
-
sections.push(i18n.t("interop.prompt.parameters"));
|
|
5325
|
-
sections.push("```json");
|
|
5326
|
-
sections.push(JSON.stringify(tool3.schema, null, 2));
|
|
5327
|
-
sections.push("```");
|
|
5328
|
-
sections.push("");
|
|
5329
|
-
}
|
|
5330
|
-
}
|
|
5331
|
-
}
|
|
5332
|
-
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
5333
|
-
const requiredKnowledge = spec2.knowledge.filter((k) => k.required);
|
|
5334
|
-
if (requiredKnowledge.length > 0) {
|
|
5335
|
-
sections.push(i18n.t("interop.prompt.knowledgeContext"));
|
|
5336
|
-
sections.push("");
|
|
5337
|
-
for (const k of requiredKnowledge) {
|
|
5338
|
-
if (k.instructions) {
|
|
5339
|
-
sections.push(k.instructions);
|
|
5340
|
-
sections.push("");
|
|
5341
|
-
}
|
|
5342
|
-
}
|
|
5343
|
-
}
|
|
5344
|
-
}
|
|
5345
|
-
if (options?.customContext) {
|
|
5346
|
-
sections.push(i18n.t("interop.prompt.additionalContext"));
|
|
5347
|
-
sections.push("");
|
|
5348
|
-
sections.push(options.customContext);
|
|
5349
|
-
sections.push("");
|
|
5350
|
-
}
|
|
5351
|
-
return sections.join(`
|
|
5352
|
-
`);
|
|
5353
|
-
}
|
|
5354
|
-
listSpecs(options) {
|
|
5355
|
-
const results = [];
|
|
5356
|
-
for (const [key, spec2] of this.specs) {
|
|
5357
|
-
if (options?.stability && spec2.meta.stability !== options.stability) {
|
|
5358
|
-
continue;
|
|
5359
|
-
}
|
|
5360
|
-
if (options?.tags && options.tags.length > 0) {
|
|
5361
|
-
const specTags = spec2.tags ?? [];
|
|
5362
|
-
const hasMatchingTag = options.tags.some((tag) => specTags.includes(tag));
|
|
5363
|
-
if (!hasMatchingTag) {
|
|
5364
|
-
continue;
|
|
5365
|
-
}
|
|
5366
|
-
}
|
|
5367
|
-
results.push({
|
|
5368
|
-
key,
|
|
5369
|
-
name: spec2.meta.key,
|
|
5370
|
-
version: spec2.meta.version,
|
|
5371
|
-
description: spec2.description,
|
|
5372
|
-
stability: spec2.meta.stability,
|
|
5373
|
-
tags: spec2.tags,
|
|
5374
|
-
toolCount: spec2.tools?.length ?? 0
|
|
5375
|
-
});
|
|
5376
|
-
}
|
|
5377
|
-
return results;
|
|
5378
|
-
}
|
|
5379
|
-
querySpec(specKey) {
|
|
5380
|
-
const spec2 = this.specs.get(specKey);
|
|
5381
|
-
if (!spec2) {
|
|
5382
|
-
return;
|
|
5383
|
-
}
|
|
5384
|
-
return {
|
|
5385
|
-
key: specKey,
|
|
5386
|
-
spec: spec2,
|
|
5387
|
-
markdown: this.getSpecMarkdown(specKey),
|
|
5388
|
-
prompt: this.getSpecPrompt(specKey)
|
|
5389
|
-
};
|
|
5390
|
-
}
|
|
5391
|
-
hasSpec(specKey) {
|
|
5392
|
-
return this.specs.has(specKey);
|
|
5393
|
-
}
|
|
5394
|
-
getSpec(specKey) {
|
|
5395
|
-
return this.specs.get(specKey);
|
|
5396
|
-
}
|
|
5397
|
-
getAllSpecs() {
|
|
5398
|
-
return Array.from(this.specs.values());
|
|
5399
|
-
}
|
|
5400
|
-
getSpecCount() {
|
|
5401
|
-
return this.specs.size;
|
|
5402
|
-
}
|
|
5403
|
-
addSpec(spec2) {
|
|
5404
|
-
const key = agentKey(spec2.meta);
|
|
5405
|
-
this.specs.set(key, spec2);
|
|
5406
|
-
}
|
|
5407
|
-
removeSpec(specKey) {
|
|
5408
|
-
return this.specs.delete(specKey);
|
|
5409
|
-
}
|
|
5410
|
-
}
|
|
5411
|
-
function createSpecConsumer(config) {
|
|
5412
|
-
return new ContractSpecConsumer(config);
|
|
5413
|
-
}
|
|
5414
|
-
function createSingleSpecConsumer(spec2, options) {
|
|
5415
|
-
return new ContractSpecConsumer({
|
|
5416
|
-
specs: [spec2],
|
|
5417
|
-
...options
|
|
5418
|
-
});
|
|
5419
|
-
}
|
|
5420
|
-
|
|
5421
|
-
// src/interop/tool-consumer.ts
|
|
5422
|
-
init_tool_bridge();
|
|
5423
|
-
init_tool_bridge2();
|
|
5424
|
-
init_i18n();
|
|
5425
|
-
|
|
5426
|
-
class MCPToolServer {
|
|
5427
|
-
tools;
|
|
5428
|
-
name;
|
|
5429
|
-
version;
|
|
5430
|
-
running = false;
|
|
5431
|
-
constructor(config) {
|
|
5432
|
-
this.tools = new Map;
|
|
5433
|
-
this.name = config.name ?? "contractspec-tools";
|
|
5434
|
-
this.version = config.version ?? "1.0.0";
|
|
5435
|
-
for (const tool3 of config.tools) {
|
|
5436
|
-
this.tools.set(tool3.config.name, tool3);
|
|
5437
|
-
}
|
|
5438
|
-
}
|
|
5439
|
-
async start() {
|
|
5440
|
-
if (this.running) {
|
|
5441
|
-
return;
|
|
5442
|
-
}
|
|
5443
|
-
this.running = true;
|
|
5444
|
-
console.log(getDefaultI18n().t("log.mcpServer.started", {
|
|
5445
|
-
name: this.name,
|
|
5446
|
-
version: this.version,
|
|
5447
|
-
count: this.tools.size
|
|
5448
|
-
}));
|
|
5449
|
-
}
|
|
5450
|
-
async stop() {
|
|
5451
|
-
if (!this.running) {
|
|
5452
|
-
return;
|
|
5453
|
-
}
|
|
5454
|
-
this.running = false;
|
|
5455
|
-
console.log(getDefaultI18n().t("log.mcpServer.stopped", { name: this.name }));
|
|
5456
|
-
}
|
|
5457
|
-
isRunning() {
|
|
5458
|
-
return this.running;
|
|
5459
|
-
}
|
|
5460
|
-
getTools() {
|
|
5461
|
-
return Array.from(this.tools.values()).map((t) => t.config);
|
|
5462
|
-
}
|
|
5463
|
-
async executeTool(toolName, args, context) {
|
|
5464
|
-
const tool3 = this.tools.get(toolName);
|
|
5465
|
-
if (!tool3) {
|
|
5466
|
-
throw new Error(getDefaultI18n().t("error.toolNotFound", { name: toolName }));
|
|
5467
|
-
}
|
|
5468
|
-
if (!tool3.handler) {
|
|
5469
|
-
throw new Error(getDefaultI18n().t("error.noHandlerForTool", { name: toolName }));
|
|
5470
|
-
}
|
|
5471
|
-
const fullContext = {
|
|
5472
|
-
agentId: context?.agentId ?? "mcp-server",
|
|
5473
|
-
sessionId: context?.sessionId ?? "mcp-session",
|
|
5474
|
-
tenantId: context?.tenantId,
|
|
5475
|
-
actorId: context?.actorId,
|
|
5476
|
-
metadata: context?.metadata,
|
|
5477
|
-
signal: context?.signal
|
|
5478
|
-
};
|
|
5479
|
-
return await tool3.handler(args, fullContext);
|
|
5480
|
-
}
|
|
5481
|
-
getMCPToolDefinitions() {
|
|
5482
|
-
const definitions = [];
|
|
5483
|
-
for (const [name, tool3] of this.tools) {
|
|
5484
|
-
definitions.push({
|
|
5485
|
-
name,
|
|
5486
|
-
description: tool3.config.description ?? "",
|
|
5487
|
-
inputSchema: tool3.config.schema ?? { type: "object", properties: {} }
|
|
5488
|
-
});
|
|
5489
|
-
}
|
|
5490
|
-
return definitions;
|
|
5491
|
-
}
|
|
5492
|
-
getServerInfo() {
|
|
5493
|
-
return {
|
|
5494
|
-
name: this.name,
|
|
5495
|
-
version: this.version,
|
|
5496
|
-
tools: this.tools.size,
|
|
5497
|
-
running: this.running
|
|
5498
|
-
};
|
|
5499
|
-
}
|
|
5500
|
-
}
|
|
5501
|
-
|
|
5502
|
-
class ContractSpecToolConsumer {
|
|
5503
|
-
tools;
|
|
5504
|
-
constructor(config) {
|
|
5505
|
-
this.tools = new Map;
|
|
5506
|
-
for (const tool3 of config.tools) {
|
|
5507
|
-
this.tools.set(tool3.config.name, tool3);
|
|
5508
|
-
}
|
|
5509
|
-
}
|
|
5510
|
-
createToolServer(config) {
|
|
5511
|
-
return new MCPToolServer({
|
|
5512
|
-
tools: Array.from(this.tools.values()),
|
|
5513
|
-
...config
|
|
5514
|
-
});
|
|
5515
|
-
}
|
|
5516
|
-
exportToolsForSDK(format) {
|
|
5517
|
-
const tools = Array.from(this.tools.values());
|
|
5518
|
-
const defaultContext = {
|
|
5519
|
-
agentId: "export",
|
|
5520
|
-
sessionId: "export"
|
|
5521
|
-
};
|
|
5522
|
-
switch (format) {
|
|
5523
|
-
case "claude-agent":
|
|
5524
|
-
return tools.filter((tool3) => !!tool3.handler).map((tool3) => specToolToClaudeAgentTool(tool3.config, tool3.handler, defaultContext));
|
|
5525
|
-
case "opencode":
|
|
5526
|
-
return tools.map((tool3) => specToolToOpenCodeTool(tool3.config));
|
|
5527
|
-
case "mcp":
|
|
5528
|
-
return tools.map((tool3) => ({
|
|
5529
|
-
name: tool3.config.name,
|
|
5530
|
-
description: tool3.config.description ?? "",
|
|
5531
|
-
inputSchema: tool3.config.schema ?? { type: "object", properties: {} }
|
|
5532
|
-
}));
|
|
5533
|
-
case "openai":
|
|
5534
|
-
return tools.map((tool3) => ({
|
|
5535
|
-
type: "function",
|
|
5536
|
-
function: {
|
|
5537
|
-
name: tool3.config.name,
|
|
5538
|
-
description: tool3.config.description ?? "",
|
|
5539
|
-
parameters: tool3.config.schema ?? {
|
|
5540
|
-
type: "object",
|
|
5541
|
-
properties: {}
|
|
5542
|
-
}
|
|
5543
|
-
}
|
|
5544
|
-
}));
|
|
5545
|
-
default:
|
|
5546
|
-
throw new Error(getDefaultI18n().t("error.unknownExportFormat", { format }));
|
|
5547
|
-
}
|
|
5548
|
-
}
|
|
5549
|
-
createBridgedHandler(toolName, _format) {
|
|
5550
|
-
const tool3 = this.tools.get(toolName);
|
|
5551
|
-
if (!tool3 || !tool3.handler) {
|
|
5552
|
-
return;
|
|
5553
|
-
}
|
|
5554
|
-
const handler = tool3.handler;
|
|
5555
|
-
return async (args) => {
|
|
5556
|
-
const context = {
|
|
5557
|
-
agentId: "bridge",
|
|
5558
|
-
sessionId: "bridge"
|
|
5559
|
-
};
|
|
5560
|
-
return handler(args, context);
|
|
5561
|
-
};
|
|
5562
|
-
}
|
|
5563
|
-
getTools() {
|
|
5564
|
-
return Array.from(this.tools.values()).map((t) => t.config);
|
|
5565
|
-
}
|
|
5566
|
-
getTool(name) {
|
|
5567
|
-
return this.tools.get(name)?.config;
|
|
5568
|
-
}
|
|
5569
|
-
hasTool(name) {
|
|
5570
|
-
return this.tools.has(name);
|
|
5571
|
-
}
|
|
5572
|
-
async executeTool(name, args, context) {
|
|
5573
|
-
const tool3 = this.tools.get(name);
|
|
5574
|
-
if (!tool3) {
|
|
5575
|
-
throw new Error(getDefaultI18n().t("error.toolNotFound", { name }));
|
|
5576
|
-
}
|
|
5577
|
-
if (!tool3.handler) {
|
|
5578
|
-
throw new Error(getDefaultI18n().t("error.noToolHandler", { name }));
|
|
5579
|
-
}
|
|
5580
|
-
const fullContext = {
|
|
5581
|
-
agentId: context?.agentId ?? "consumer",
|
|
5582
|
-
sessionId: context?.sessionId ?? "consumer-session",
|
|
5583
|
-
tenantId: context?.tenantId,
|
|
5584
|
-
actorId: context?.actorId,
|
|
5585
|
-
metadata: context?.metadata,
|
|
5586
|
-
signal: context?.signal
|
|
5587
|
-
};
|
|
5588
|
-
return await tool3.handler(args, fullContext);
|
|
5589
|
-
}
|
|
5590
|
-
addTool(config, handler) {
|
|
5591
|
-
this.tools.set(config.name, { config, handler });
|
|
5592
|
-
}
|
|
5593
|
-
removeTool(name) {
|
|
5594
|
-
return this.tools.delete(name);
|
|
5595
|
-
}
|
|
5596
|
-
getToolCount() {
|
|
5597
|
-
return this.tools.size;
|
|
5598
|
-
}
|
|
5599
|
-
}
|
|
5600
|
-
function createToolConsumer(config) {
|
|
5601
|
-
return new ContractSpecToolConsumer(config);
|
|
5602
|
-
}
|
|
5603
|
-
function createToolServer(config) {
|
|
5604
|
-
return new MCPToolServer(config);
|
|
5605
|
-
}
|
|
5606
|
-
function exportToolsForExternalSDK(tools, format) {
|
|
5607
|
-
const consumer = new ContractSpecToolConsumer({
|
|
5608
|
-
tools: tools.map((config) => ({ config }))
|
|
5609
|
-
});
|
|
5610
|
-
return consumer.exportToolsForSDK(format);
|
|
5611
|
-
}
|
|
5612
|
-
// src/index.ts
|
|
5613
|
-
init_i18n();
|
|
5614
|
-
import { Experimental_Agent } from "ai";
|
|
5615
2184
|
export {
|
|
5616
|
-
zodToOutput,
|
|
5617
|
-
validateForOpenCode,
|
|
5618
|
-
validateForClaudeAgent,
|
|
5619
|
-
trackAgentStep,
|
|
5620
|
-
textOutput,
|
|
5621
|
-
specToolsToAISDKTools,
|
|
5622
|
-
specToolToAISDKTool,
|
|
5623
|
-
resolveLocale,
|
|
5624
|
-
resetI18nRegistry,
|
|
5625
|
-
noopTelemetryCollector,
|
|
5626
|
-
mcpServerToTools,
|
|
5627
|
-
jsonSchemaToZodSafe,
|
|
5628
|
-
jsonSchemaToZod,
|
|
5629
|
-
jsonSchemaToOutput,
|
|
5630
|
-
jsonSchemaToArrayOutput,
|
|
5631
|
-
isSupportedLocale,
|
|
5632
|
-
injectStaticKnowledge,
|
|
5633
|
-
getDefaultI18n,
|
|
5634
|
-
getAvailableBackends,
|
|
5635
|
-
generateSessionId,
|
|
5636
|
-
generateOpenCodeMarkdown,
|
|
5637
|
-
generateOpenCodeJSON,
|
|
5638
|
-
generateClaudeMd,
|
|
5639
|
-
frMessages,
|
|
5640
|
-
exportToolsForExternalSDK,
|
|
5641
|
-
exportToOpenCode,
|
|
5642
|
-
exportToClaudeAgent,
|
|
5643
|
-
esMessages,
|
|
5644
|
-
enumToChoiceOutput,
|
|
5645
|
-
enMessages,
|
|
5646
2185
|
defineAgent,
|
|
5647
|
-
defaultProviderRegistry,
|
|
5648
|
-
createUnifiedAgent,
|
|
5649
|
-
createToolServer,
|
|
5650
|
-
createToolHandler,
|
|
5651
|
-
createToolConsumer,
|
|
5652
|
-
createSpecConsumer,
|
|
5653
|
-
createSingleSpecConsumer,
|
|
5654
|
-
createProviderRegistry,
|
|
5655
|
-
createPostHogTracedModel,
|
|
5656
|
-
createPostHogTelemetryCollector,
|
|
5657
|
-
createOpenCodeSDKAgent,
|
|
5658
|
-
createMcpToolsets,
|
|
5659
|
-
createKnowledgeQueryTool,
|
|
5660
|
-
createKnowledgeInjector,
|
|
5661
|
-
createInMemoryTelemetryCollector,
|
|
5662
|
-
createInMemorySessionStore,
|
|
5663
|
-
createCompositeTelemetryCollector,
|
|
5664
|
-
createClaudeAgentSDKAgent,
|
|
5665
|
-
createApprovalWorkflow,
|
|
5666
2186
|
createAgentRegistry,
|
|
5667
|
-
createAgentMcpServer,
|
|
5668
|
-
createAgentJsonRunner,
|
|
5669
|
-
createAgentI18n,
|
|
5670
|
-
createAISDKAgent,
|
|
5671
|
-
buildToolHandlers,
|
|
5672
|
-
agentToMcpServer,
|
|
5673
2187
|
agentKey,
|
|
5674
|
-
|
|
5675
|
-
Experimental_Agent as ToolLoopAgent,
|
|
5676
|
-
TOOL_KEYS,
|
|
5677
|
-
SchemaOutput,
|
|
5678
|
-
SUPPORTED_LOCALES,
|
|
5679
|
-
ProviderNotAvailableError,
|
|
5680
|
-
ProviderExecutionError,
|
|
5681
|
-
PostHogTelemetryCollector,
|
|
5682
|
-
OpenCodeSDKProvider,
|
|
5683
|
-
OpenCodeExporter,
|
|
5684
|
-
LOG_KEYS,
|
|
5685
|
-
KNOWLEDGE_KEYS,
|
|
5686
|
-
InMemoryTelemetryCollector,
|
|
5687
|
-
InMemorySessionStore,
|
|
5688
|
-
InMemoryApprovalStore,
|
|
5689
|
-
INTEROP_KEYS,
|
|
5690
|
-
I18N_KEYS,
|
|
5691
|
-
ExternalProviderError,
|
|
5692
|
-
EXPORT_KEYS,
|
|
5693
|
-
ERROR_KEYS,
|
|
5694
|
-
DEFAULT_LOCALE,
|
|
5695
|
-
ContractSpecToolConsumer,
|
|
5696
|
-
ContractSpecConsumer,
|
|
5697
|
-
ContractSpecAgent,
|
|
5698
|
-
ContextCreationError,
|
|
5699
|
-
CompositeTelemetryCollector,
|
|
5700
|
-
ClaudeAgentSDKProvider,
|
|
5701
|
-
ClaudeAgentExporter,
|
|
5702
|
-
ApprovalWorkflow,
|
|
5703
|
-
AgentRegistry,
|
|
5704
|
-
APPROVAL_KEYS,
|
|
5705
|
-
AGENT_KEYS
|
|
2188
|
+
AgentRegistry
|
|
5706
2189
|
};
|