@contractspec/lib.ai-agent 1.57.0 → 1.59.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 +67 -71
- package/dist/agent/agent-factory.d.ts.map +1 -1
- package/dist/agent/agent-factory.js +658 -100
- package/dist/agent/agent.test.d.ts +2 -0
- package/dist/agent/agent.test.d.ts.map +1 -0
- package/dist/agent/contract-spec-agent.d.ts +48 -52
- package/dist/agent/contract-spec-agent.d.ts.map +1 -1
- package/dist/agent/contract-spec-agent.js +605 -146
- package/dist/agent/index.d.ts +4 -4
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +2102 -4
- package/dist/agent/json-runner.d.ts +15 -19
- package/dist/agent/json-runner.d.ts.map +1 -1
- package/dist/agent/json-runner.js +672 -57
- package/dist/agent/json-runner.test.d.ts +2 -0
- package/dist/agent/json-runner.test.d.ts.map +1 -0
- package/dist/agent/unified-agent.d.ts +132 -109
- package/dist/agent/unified-agent.d.ts.map +1 -1
- package/dist/agent/unified-agent.js +2011 -293
- package/dist/approval/index.d.ts +3 -2
- package/dist/approval/index.d.ts.map +1 -0
- package/dist/approval/index.js +128 -2
- package/dist/approval/workflow.d.ts +106 -110
- package/dist/approval/workflow.d.ts.map +1 -1
- package/dist/approval/workflow.js +126 -157
- package/dist/exporters/claude-agent-exporter.d.ts +50 -48
- package/dist/exporters/claude-agent-exporter.d.ts.map +1 -1
- package/dist/exporters/claude-agent-exporter.js +258 -203
- package/dist/exporters/index.d.ts +28 -4
- package/dist/exporters/index.d.ts.map +1 -0
- package/dist/exporters/index.js +737 -3
- package/dist/exporters/opencode-exporter.d.ts +47 -45
- package/dist/exporters/opencode-exporter.d.ts.map +1 -1
- package/dist/exporters/opencode-exporter.js +507 -191
- package/dist/exporters/types.d.ts +171 -169
- package/dist/exporters/types.d.ts.map +1 -1
- package/dist/exporters/types.js +1 -0
- package/dist/index.d.ts +15 -39
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3337 -32
- package/dist/interop/index.d.ts +48 -4
- package/dist/interop/index.d.ts.map +1 -0
- package/dist/interop/index.js +709 -3
- package/dist/interop/spec-consumer.d.ts +57 -53
- package/dist/interop/spec-consumer.d.ts.map +1 -1
- package/dist/interop/spec-consumer.js +302 -282
- package/dist/interop/tool-consumer.d.ts +57 -53
- package/dist/interop/tool-consumer.d.ts.map +1 -1
- package/dist/interop/tool-consumer.js +412 -213
- package/dist/interop/types.d.ts +173 -171
- package/dist/interop/types.d.ts.map +1 -1
- package/dist/interop/types.js +1 -0
- package/dist/knowledge/index.d.ts +2 -2
- package/dist/knowledge/index.d.ts.map +1 -0
- package/dist/knowledge/index.js +66 -2
- package/dist/knowledge/injector.d.ts +16 -20
- package/dist/knowledge/injector.d.ts.map +1 -1
- package/dist/knowledge/injector.js +56 -47
- package/dist/memory/in-memory.d.ts +15 -19
- package/dist/memory/in-memory.d.ts.map +1 -1
- package/dist/memory/in-memory.js +152 -46
- package/dist/memory/index.d.ts +3 -3
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/index.js +155 -3
- package/dist/memory/manager.d.ts +32 -36
- package/dist/memory/manager.d.ts.map +1 -1
- package/dist/memory/manager.js +96 -70
- package/dist/memory/memory.test.d.ts +2 -0
- package/dist/memory/memory.test.d.ts.map +1 -0
- package/dist/node/agent/agent-factory.js +661 -0
- package/dist/node/agent/contract-spec-agent.js +607 -0
- package/dist/node/agent/index.js +2103 -0
- package/dist/node/agent/json-runner.js +684 -0
- package/dist/node/agent/unified-agent.js +2019 -0
- package/dist/node/approval/index.js +129 -0
- package/dist/node/approval/workflow.js +129 -0
- package/dist/node/exporters/claude-agent-exporter.js +265 -0
- package/dist/node/exporters/index.js +738 -0
- package/dist/node/exporters/opencode-exporter.js +516 -0
- package/dist/node/exporters/types.js +0 -0
- package/dist/node/index.js +3337 -0
- package/dist/node/interop/index.js +710 -0
- package/dist/node/interop/spec-consumer.js +307 -0
- package/dist/node/interop/tool-consumer.js +419 -0
- package/dist/node/interop/types.js +0 -0
- package/dist/node/knowledge/index.js +67 -0
- package/dist/node/knowledge/injector.js +67 -0
- package/dist/node/memory/in-memory.js +154 -0
- package/dist/node/memory/index.js +156 -0
- package/dist/node/memory/manager.js +105 -0
- package/dist/node/providers/claude-agent-sdk/adapter.js +624 -0
- package/dist/node/providers/claude-agent-sdk/index.js +673 -0
- package/dist/node/providers/claude-agent-sdk/session-bridge.js +149 -0
- package/dist/node/providers/claude-agent-sdk/tool-bridge.js +118 -0
- package/dist/node/providers/index.js +1261 -0
- package/dist/node/providers/opencode-sdk/adapter.js +669 -0
- package/dist/node/providers/opencode-sdk/agent-bridge.js +299 -0
- package/dist/node/providers/opencode-sdk/index.js +703 -0
- package/dist/node/providers/opencode-sdk/tool-bridge.js +141 -0
- package/dist/node/providers/registry.js +89 -0
- package/dist/node/providers/types.js +56 -0
- package/dist/node/schema/index.js +195 -0
- package/dist/node/schema/json-schema-to-zod.js +152 -0
- package/dist/node/schema/schema-output.js +190 -0
- package/dist/node/session/index.js +90 -0
- package/dist/node/session/store.js +90 -0
- package/dist/node/spec/index.js +85 -0
- package/dist/node/spec/registry.js +56 -0
- package/dist/node/spec/spec.js +44 -0
- package/dist/node/telemetry/adapter.js +85 -0
- package/dist/node/telemetry/index.js +86 -0
- package/dist/node/tools/index.js +345 -0
- package/dist/node/tools/knowledge-tool.js +74 -0
- package/dist/node/tools/mcp-client.js +47 -0
- package/dist/node/tools/mcp-server.js +205 -0
- package/dist/node/tools/tool-adapter.js +197 -0
- package/dist/node/types.js +0 -0
- package/dist/providers/claude-agent-sdk/adapter.d.ts +60 -52
- package/dist/providers/claude-agent-sdk/adapter.d.ts.map +1 -1
- package/dist/providers/claude-agent-sdk/adapter.js +622 -304
- package/dist/providers/claude-agent-sdk/index.d.ts +22 -4
- package/dist/providers/claude-agent-sdk/index.d.ts.map +1 -0
- package/dist/providers/claude-agent-sdk/index.js +672 -4
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts +43 -40
- package/dist/providers/claude-agent-sdk/session-bridge.d.ts.map +1 -1
- package/dist/providers/claude-agent-sdk/session-bridge.js +121 -130
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts +63 -60
- package/dist/providers/claude-agent-sdk/tool-bridge.d.ts.map +1 -1
- package/dist/providers/claude-agent-sdk/tool-bridge.js +104 -108
- package/dist/providers/index.d.ts +28 -7
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/index.js +1261 -8
- package/dist/providers/opencode-sdk/adapter.d.ts +56 -48
- package/dist/providers/opencode-sdk/adapter.d.ts.map +1 -1
- package/dist/providers/opencode-sdk/adapter.js +667 -274
- package/dist/providers/opencode-sdk/agent-bridge.d.ts +62 -57
- package/dist/providers/opencode-sdk/agent-bridge.d.ts.map +1 -1
- package/dist/providers/opencode-sdk/agent-bridge.js +289 -155
- package/dist/providers/opencode-sdk/index.d.ts +22 -4
- package/dist/providers/opencode-sdk/index.d.ts.map +1 -0
- package/dist/providers/opencode-sdk/index.js +702 -4
- package/dist/providers/opencode-sdk/tool-bridge.d.ts +41 -42
- package/dist/providers/opencode-sdk/tool-bridge.d.ts.map +1 -1
- package/dist/providers/opencode-sdk/tool-bridge.js +121 -107
- package/dist/providers/registry.d.ts +10 -11
- package/dist/providers/registry.d.ts.map +1 -1
- package/dist/providers/registry.js +86 -49
- package/dist/providers/types.d.ts +169 -166
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js +54 -42
- package/dist/schema/index.d.ts +3 -3
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +194 -3
- package/dist/schema/json-schema-to-zod.d.ts +23 -26
- package/dist/schema/json-schema-to-zod.d.ts.map +1 -1
- package/dist/schema/json-schema-to-zod.js +138 -110
- package/dist/schema/schema-output.d.ts +29 -32
- package/dist/schema/schema-output.d.ts.map +1 -1
- package/dist/schema/schema-output.js +178 -53
- package/dist/session/index.d.ts +2 -2
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/index.js +89 -2
- package/dist/session/store.d.ts +51 -55
- package/dist/session/store.d.ts.map +1 -1
- package/dist/session/store.js +85 -74
- package/dist/spec/index.d.ts +3 -3
- package/dist/spec/index.d.ts.map +1 -0
- package/dist/spec/index.js +84 -3
- package/dist/spec/registry.d.ts +32 -36
- package/dist/spec/registry.d.ts.map +1 -1
- package/dist/spec/registry.js +51 -60
- package/dist/spec/spec.d.ts +80 -84
- package/dist/spec/spec.d.ts.map +1 -1
- package/dist/spec/spec.js +40 -26
- package/dist/telemetry/adapter.d.ts +33 -37
- package/dist/telemetry/adapter.d.ts.map +1 -1
- package/dist/telemetry/adapter.js +78 -96
- package/dist/telemetry/index.d.ts +2 -2
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +85 -2
- package/dist/tools/index.d.ts +5 -5
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +344 -5
- package/dist/tools/knowledge-tool.d.ts +4 -8
- package/dist/tools/knowledge-tool.d.ts.map +1 -1
- package/dist/tools/knowledge-tool.js +68 -48
- package/dist/tools/mcp-client.d.ts +17 -21
- package/dist/tools/mcp-client.d.ts.map +1 -1
- package/dist/tools/mcp-client.js +42 -53
- package/dist/tools/mcp-server.d.ts +14 -18
- package/dist/tools/mcp-server.d.ts.map +1 -1
- package/dist/tools/mcp-server.js +200 -64
- package/dist/tools/tool-adapter.d.ts +7 -11
- package/dist/tools/tool-adapter.d.ts.map +1 -1
- package/dist/tools/tool-adapter.js +187 -70
- package/dist/tools/tools.test.d.ts +2 -0
- package/dist/tools/tools.test.d.ts.map +1 -0
- package/dist/types.d.ts +108 -111
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/package.json +448 -90
- package/dist/_virtual/_rolldown/runtime.js +0 -8
- package/dist/agent/agent-factory.js.map +0 -1
- package/dist/agent/contract-spec-agent.js.map +0 -1
- package/dist/agent/json-runner.js.map +0 -1
- package/dist/agent/unified-agent.js.map +0 -1
- package/dist/approval/workflow.js.map +0 -1
- package/dist/exporters/claude-agent-exporter.js.map +0 -1
- package/dist/exporters/opencode-exporter.js.map +0 -1
- package/dist/interop/spec-consumer.js.map +0 -1
- package/dist/interop/tool-consumer.js.map +0 -1
- package/dist/knowledge/injector.js.map +0 -1
- package/dist/memory/in-memory.js.map +0 -1
- package/dist/memory/manager.js.map +0 -1
- package/dist/providers/claude-agent-sdk/adapter.js.map +0 -1
- package/dist/providers/claude-agent-sdk/session-bridge.js.map +0 -1
- package/dist/providers/claude-agent-sdk/tool-bridge.js.map +0 -1
- package/dist/providers/opencode-sdk/adapter.js.map +0 -1
- package/dist/providers/opencode-sdk/agent-bridge.js.map +0 -1
- package/dist/providers/opencode-sdk/tool-bridge.js.map +0 -1
- package/dist/providers/registry.js.map +0 -1
- package/dist/providers/types.js.map +0 -1
- package/dist/schema/json-schema-to-zod.js.map +0 -1
- package/dist/schema/schema-output.js.map +0 -1
- package/dist/session/store.js.map +0 -1
- package/dist/spec/registry.js.map +0 -1
- package/dist/spec/spec.js.map +0 -1
- package/dist/telemetry/adapter.js.map +0 -1
- package/dist/tools/knowledge-tool.js.map +0 -1
- package/dist/tools/mcp-client.js.map +0 -1
- package/dist/tools/mcp-server.js.map +0 -1
- package/dist/tools/tool-adapter.js.map +0 -1
|
@@ -0,0 +1,3337 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __export = (target, all) => {
|
|
4
|
+
for (var name in all)
|
|
5
|
+
__defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true,
|
|
8
|
+
configurable: true,
|
|
9
|
+
set: (newValue) => all[name] = () => newValue
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
13
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
14
|
+
|
|
15
|
+
// src/spec/spec.ts
|
|
16
|
+
function defineAgent(spec) {
|
|
17
|
+
if (!spec.meta?.key) {
|
|
18
|
+
throw new Error("Agent key is required");
|
|
19
|
+
}
|
|
20
|
+
if (typeof spec.meta.version !== "string") {
|
|
21
|
+
throw new Error(`Agent ${spec.meta.key} is missing a string version`);
|
|
22
|
+
}
|
|
23
|
+
if (!spec.instructions?.trim()) {
|
|
24
|
+
throw new Error(`Agent ${spec.meta.key} requires instructions`);
|
|
25
|
+
}
|
|
26
|
+
if (!spec.tools?.length) {
|
|
27
|
+
throw new Error(`Agent ${spec.meta.key} must expose at least one tool`);
|
|
28
|
+
}
|
|
29
|
+
const toolNames = new Set;
|
|
30
|
+
for (const tool of spec.tools) {
|
|
31
|
+
if (toolNames.has(tool.name)) {
|
|
32
|
+
throw new Error(`Agent ${spec.meta.key} has duplicate tool name: ${tool.name}`);
|
|
33
|
+
}
|
|
34
|
+
toolNames.add(tool.name);
|
|
35
|
+
}
|
|
36
|
+
return Object.freeze(spec);
|
|
37
|
+
}
|
|
38
|
+
function agentKey(meta) {
|
|
39
|
+
return `${meta.key}.v${meta.version}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/schema/json-schema-to-zod.ts
|
|
43
|
+
import { z } from "zod";
|
|
44
|
+
function jsonSchemaToZod(schema) {
|
|
45
|
+
const s = schema;
|
|
46
|
+
const makeNullable = (zodSchema) => {
|
|
47
|
+
return s.nullable ? z.union([zodSchema, z.null()]) : zodSchema;
|
|
48
|
+
};
|
|
49
|
+
if (s.const !== undefined) {
|
|
50
|
+
return z.literal(s.const);
|
|
51
|
+
}
|
|
52
|
+
if (s.enum) {
|
|
53
|
+
const values = s.enum;
|
|
54
|
+
return makeNullable(z.enum(values.map(String)));
|
|
55
|
+
}
|
|
56
|
+
if (s.anyOf && s.anyOf.length > 0) {
|
|
57
|
+
const schemas = s.anyOf.map((sub) => jsonSchemaToZod(sub));
|
|
58
|
+
if (schemas.length === 1)
|
|
59
|
+
return schemas[0] ?? z.unknown();
|
|
60
|
+
return z.union([
|
|
61
|
+
schemas[0] ?? z.unknown(),
|
|
62
|
+
schemas[1] ?? z.unknown(),
|
|
63
|
+
...schemas.slice(2)
|
|
64
|
+
]);
|
|
65
|
+
}
|
|
66
|
+
if (s.oneOf && s.oneOf.length > 0) {
|
|
67
|
+
const schemas = s.oneOf.map((sub) => jsonSchemaToZod(sub));
|
|
68
|
+
if (schemas.length === 1)
|
|
69
|
+
return schemas[0] ?? z.unknown();
|
|
70
|
+
return z.union([
|
|
71
|
+
schemas[0] ?? z.unknown(),
|
|
72
|
+
schemas[1] ?? z.unknown(),
|
|
73
|
+
...schemas.slice(2)
|
|
74
|
+
]);
|
|
75
|
+
}
|
|
76
|
+
if (s.allOf && s.allOf.length > 0) {
|
|
77
|
+
const schemas = s.allOf.map((sub) => jsonSchemaToZod(sub));
|
|
78
|
+
return schemas.reduce((acc, curr) => z.intersection(acc, curr));
|
|
79
|
+
}
|
|
80
|
+
switch (s.type) {
|
|
81
|
+
case "string":
|
|
82
|
+
return makeNullable(buildStringSchema(s));
|
|
83
|
+
case "number":
|
|
84
|
+
case "integer":
|
|
85
|
+
return makeNullable(buildNumberSchema(s));
|
|
86
|
+
case "boolean":
|
|
87
|
+
return makeNullable(z.boolean());
|
|
88
|
+
case "null":
|
|
89
|
+
return z.null();
|
|
90
|
+
case "array":
|
|
91
|
+
return makeNullable(buildArraySchema(s));
|
|
92
|
+
case "object":
|
|
93
|
+
return makeNullable(buildObjectSchema(s));
|
|
94
|
+
default:
|
|
95
|
+
return z.unknown();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function buildStringSchema(schema) {
|
|
99
|
+
let zodSchema = z.string();
|
|
100
|
+
if (schema.description) {
|
|
101
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
102
|
+
}
|
|
103
|
+
switch (schema.format) {
|
|
104
|
+
case "email":
|
|
105
|
+
zodSchema = zodSchema.email();
|
|
106
|
+
break;
|
|
107
|
+
case "uri":
|
|
108
|
+
case "url":
|
|
109
|
+
zodSchema = zodSchema.url();
|
|
110
|
+
break;
|
|
111
|
+
case "uuid":
|
|
112
|
+
zodSchema = zodSchema.uuid();
|
|
113
|
+
break;
|
|
114
|
+
case "date-time":
|
|
115
|
+
zodSchema = zodSchema.datetime();
|
|
116
|
+
break;
|
|
117
|
+
case "date":
|
|
118
|
+
zodSchema = zodSchema.date();
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
if (schema.minLength !== undefined) {
|
|
122
|
+
zodSchema = zodSchema.min(schema.minLength);
|
|
123
|
+
}
|
|
124
|
+
if (schema.maxLength !== undefined) {
|
|
125
|
+
zodSchema = zodSchema.max(schema.maxLength);
|
|
126
|
+
}
|
|
127
|
+
if (schema.pattern) {
|
|
128
|
+
zodSchema = zodSchema.regex(new RegExp(schema.pattern));
|
|
129
|
+
}
|
|
130
|
+
return zodSchema;
|
|
131
|
+
}
|
|
132
|
+
function buildNumberSchema(schema) {
|
|
133
|
+
let zodSchema = schema.type === "integer" ? z.number().int() : z.number();
|
|
134
|
+
if (schema.description) {
|
|
135
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
136
|
+
}
|
|
137
|
+
if (schema.minimum !== undefined) {
|
|
138
|
+
zodSchema = zodSchema.min(schema.minimum);
|
|
139
|
+
}
|
|
140
|
+
if (schema.maximum !== undefined) {
|
|
141
|
+
zodSchema = zodSchema.max(schema.maximum);
|
|
142
|
+
}
|
|
143
|
+
return zodSchema;
|
|
144
|
+
}
|
|
145
|
+
function buildArraySchema(schema) {
|
|
146
|
+
const itemsSchema = schema.items ? jsonSchemaToZod(schema.items) : z.unknown();
|
|
147
|
+
let zodSchema = z.array(itemsSchema);
|
|
148
|
+
if (schema.description) {
|
|
149
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
150
|
+
}
|
|
151
|
+
return zodSchema;
|
|
152
|
+
}
|
|
153
|
+
function buildObjectSchema(schema) {
|
|
154
|
+
const properties = schema.properties ?? {};
|
|
155
|
+
const required = new Set(schema.required ?? []);
|
|
156
|
+
const shape = {};
|
|
157
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
158
|
+
const zodProp = jsonSchemaToZod(propSchema);
|
|
159
|
+
shape[key] = required.has(key) ? zodProp : zodProp.optional();
|
|
160
|
+
}
|
|
161
|
+
let zodSchema = z.object(shape);
|
|
162
|
+
if (schema.description) {
|
|
163
|
+
zodSchema = zodSchema.describe(schema.description);
|
|
164
|
+
}
|
|
165
|
+
return zodSchema;
|
|
166
|
+
}
|
|
167
|
+
function jsonSchemaToZodSafe(schema) {
|
|
168
|
+
if (!schema || Object.keys(schema).length === 0) {
|
|
169
|
+
return z.object({});
|
|
170
|
+
}
|
|
171
|
+
return jsonSchemaToZod(schema);
|
|
172
|
+
}
|
|
173
|
+
var init_json_schema_to_zod = () => {};
|
|
174
|
+
|
|
175
|
+
// src/tools/tool-adapter.ts
|
|
176
|
+
import { tool } from "ai";
|
|
177
|
+
function specToolToAISDKTool(specTool, handler, context = {}) {
|
|
178
|
+
return tool({
|
|
179
|
+
description: specTool.description ?? specTool.name,
|
|
180
|
+
inputSchema: jsonSchemaToZodSafe(specTool.schema),
|
|
181
|
+
needsApproval: specTool.requiresApproval ?? !specTool.automationSafe,
|
|
182
|
+
execute: async (input) => {
|
|
183
|
+
const result = await handler(input, {
|
|
184
|
+
agentId: context.agentId ?? "unknown",
|
|
185
|
+
sessionId: context.sessionId ?? "unknown",
|
|
186
|
+
tenantId: context.tenantId,
|
|
187
|
+
actorId: context.actorId,
|
|
188
|
+
metadata: context.metadata,
|
|
189
|
+
signal: context.signal
|
|
190
|
+
});
|
|
191
|
+
return typeof result === "string" ? result : JSON.stringify(result);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
function specToolsToAISDKTools(specTools, handlers, context = {}) {
|
|
196
|
+
const tools = {};
|
|
197
|
+
for (const specTool of specTools) {
|
|
198
|
+
const handler = handlers.get(specTool.name);
|
|
199
|
+
if (!handler) {
|
|
200
|
+
throw new Error(`Missing handler for tool: ${specTool.name}`);
|
|
201
|
+
}
|
|
202
|
+
tools[specTool.name] = specToolToAISDKTool(specTool, handler, context);
|
|
203
|
+
}
|
|
204
|
+
return tools;
|
|
205
|
+
}
|
|
206
|
+
function createToolHandler(handler) {
|
|
207
|
+
return async (input, context) => {
|
|
208
|
+
return handler(input, context);
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function buildToolHandlers(handlersObj) {
|
|
212
|
+
return new Map(Object.entries(handlersObj));
|
|
213
|
+
}
|
|
214
|
+
var init_tool_adapter = __esm(() => {
|
|
215
|
+
init_json_schema_to_zod();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// src/tools/knowledge-tool.ts
|
|
219
|
+
import { tool as tool2 } from "ai";
|
|
220
|
+
import * as z2 from "zod";
|
|
221
|
+
function createKnowledgeQueryTool(retriever, knowledgeRefs) {
|
|
222
|
+
const optionalSpaces = knowledgeRefs.filter((k) => !k.required).map((k) => k.key).filter((key) => retriever.supportsSpace(key));
|
|
223
|
+
if (optionalSpaces.length === 0) {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
const spaceDescriptions = knowledgeRefs.filter((k) => !k.required && retriever.supportsSpace(k.key)).map((k) => `- ${k.key}: ${k.instructions ?? "Knowledge space"}`).join(`
|
|
227
|
+
`);
|
|
228
|
+
return tool2({
|
|
229
|
+
description: `Query knowledge bases for relevant information. Use this tool when you need to look up specific information that may not be in your context.
|
|
230
|
+
|
|
231
|
+
Available knowledge spaces:
|
|
232
|
+
${spaceDescriptions}`,
|
|
233
|
+
inputSchema: z2.object({
|
|
234
|
+
query: z2.string().describe("The question or search query to find relevant information"),
|
|
235
|
+
spaceKey: z2.enum(optionalSpaces).optional().describe("Specific knowledge space to query. If omitted, searches all available spaces."),
|
|
236
|
+
topK: z2.number().optional().default(5).describe("Maximum number of results to return")
|
|
237
|
+
}),
|
|
238
|
+
execute: async ({ query, spaceKey, topK }) => {
|
|
239
|
+
const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;
|
|
240
|
+
const allResults = [];
|
|
241
|
+
for (const space of spacesToSearch) {
|
|
242
|
+
try {
|
|
243
|
+
const results = await retriever.retrieve(query, {
|
|
244
|
+
spaceKey: space,
|
|
245
|
+
topK: topK ?? 5
|
|
246
|
+
});
|
|
247
|
+
for (const result of results) {
|
|
248
|
+
allResults.push({
|
|
249
|
+
space,
|
|
250
|
+
content: result.content,
|
|
251
|
+
score: result.score
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
} catch (error) {
|
|
255
|
+
console.warn(`Failed to query knowledge space ${space}:`, error);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (allResults.length === 0) {
|
|
259
|
+
return "No relevant information found in the knowledge bases.";
|
|
260
|
+
}
|
|
261
|
+
allResults.sort((a, b) => b.score - a.score);
|
|
262
|
+
const topResults = allResults.slice(0, topK ?? 5);
|
|
263
|
+
return topResults.map((r, i) => `[Source ${i + 1} - ${r.space}] (relevance: ${(r.score * 100).toFixed(0)}%)
|
|
264
|
+
${r.content}`).join(`
|
|
265
|
+
|
|
266
|
+
---
|
|
267
|
+
|
|
268
|
+
`);
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
var init_knowledge_tool = () => {};
|
|
273
|
+
|
|
274
|
+
// src/knowledge/injector.ts
|
|
275
|
+
async function injectStaticKnowledge(instructions, knowledgeRefs, retriever) {
|
|
276
|
+
if (!retriever)
|
|
277
|
+
return instructions;
|
|
278
|
+
const requiredRefs = knowledgeRefs.filter((ref) => ref.required);
|
|
279
|
+
if (requiredRefs.length === 0)
|
|
280
|
+
return instructions;
|
|
281
|
+
const blocks = [];
|
|
282
|
+
for (const ref of requiredRefs) {
|
|
283
|
+
if (!retriever.supportsSpace(ref.key)) {
|
|
284
|
+
console.warn(`Required knowledge space "${ref.key}" is not available`);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
const content = await retriever.getStatic(ref.key);
|
|
289
|
+
if (content) {
|
|
290
|
+
const header = ref.instructions ? `## ${ref.key}
|
|
291
|
+
${ref.instructions}` : `## ${ref.key}`;
|
|
292
|
+
blocks.push(`${header}
|
|
293
|
+
|
|
294
|
+
${content}`);
|
|
295
|
+
}
|
|
296
|
+
} catch (error) {
|
|
297
|
+
console.warn(`Failed to load required knowledge "${ref.key}":`, error);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (blocks.length === 0)
|
|
301
|
+
return instructions;
|
|
302
|
+
return `${instructions}
|
|
303
|
+
|
|
304
|
+
---
|
|
305
|
+
|
|
306
|
+
# Reference Knowledge
|
|
307
|
+
|
|
308
|
+
The following information is provided for your reference. Use it to inform your responses.
|
|
309
|
+
|
|
310
|
+
${blocks.join(`
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
314
|
+
`)}`;
|
|
315
|
+
}
|
|
316
|
+
function createKnowledgeInjector(retriever) {
|
|
317
|
+
return {
|
|
318
|
+
inject: (instructions, knowledgeRefs) => injectStaticKnowledge(instructions, knowledgeRefs, retriever),
|
|
319
|
+
hasSpace: (spaceKey) => retriever?.supportsSpace(spaceKey) ?? false,
|
|
320
|
+
listSpaces: () => retriever?.listSpaces() ?? []
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/session/store.ts
|
|
325
|
+
class InMemorySessionStore {
|
|
326
|
+
sessions = new Map;
|
|
327
|
+
async get(sessionId) {
|
|
328
|
+
return this.sessions.get(sessionId) ?? null;
|
|
329
|
+
}
|
|
330
|
+
async create(session) {
|
|
331
|
+
const now = new Date;
|
|
332
|
+
const fullSession = {
|
|
333
|
+
...session,
|
|
334
|
+
createdAt: now,
|
|
335
|
+
updatedAt: now
|
|
336
|
+
};
|
|
337
|
+
this.sessions.set(session.sessionId, fullSession);
|
|
338
|
+
return fullSession;
|
|
339
|
+
}
|
|
340
|
+
async appendStep(sessionId, step) {
|
|
341
|
+
const session = this.sessions.get(sessionId);
|
|
342
|
+
if (session) {
|
|
343
|
+
session.steps.push(step);
|
|
344
|
+
session.updatedAt = new Date;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
async appendMessage(sessionId, message) {
|
|
348
|
+
const session = this.sessions.get(sessionId);
|
|
349
|
+
if (session) {
|
|
350
|
+
session.messages.push(message);
|
|
351
|
+
session.updatedAt = new Date;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
async update(sessionId, updates) {
|
|
355
|
+
const session = this.sessions.get(sessionId);
|
|
356
|
+
if (session) {
|
|
357
|
+
Object.assign(session, updates, { updatedAt: new Date });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
async delete(sessionId) {
|
|
361
|
+
return this.sessions.delete(sessionId);
|
|
362
|
+
}
|
|
363
|
+
async listByAgent(agentId, limit = 100) {
|
|
364
|
+
const results = [];
|
|
365
|
+
for (const session of this.sessions.values()) {
|
|
366
|
+
if (session.agentId === agentId) {
|
|
367
|
+
results.push(session);
|
|
368
|
+
if (results.length >= limit)
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
373
|
+
}
|
|
374
|
+
async listByTenant(tenantId, limit = 100) {
|
|
375
|
+
const results = [];
|
|
376
|
+
for (const session of this.sessions.values()) {
|
|
377
|
+
if (session.tenantId === tenantId) {
|
|
378
|
+
results.push(session);
|
|
379
|
+
if (results.length >= limit)
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
384
|
+
}
|
|
385
|
+
clear() {
|
|
386
|
+
this.sessions.clear();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function createInMemorySessionStore() {
|
|
390
|
+
return new InMemorySessionStore;
|
|
391
|
+
}
|
|
392
|
+
function generateSessionId() {
|
|
393
|
+
return `sess_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/telemetry/adapter.ts
|
|
397
|
+
function parseAgentId(agentId) {
|
|
398
|
+
const match = agentId.match(/^(.+)\.v(\s+)$/);
|
|
399
|
+
if (match) {
|
|
400
|
+
return { name: match[1], version: match[2] };
|
|
401
|
+
}
|
|
402
|
+
return { name: agentId, version: "1.0.0" };
|
|
403
|
+
}
|
|
404
|
+
async function trackAgentStep(collector, agentId, step, durationMs) {
|
|
405
|
+
const { name, version } = parseAgentId(agentId);
|
|
406
|
+
for (const toolCall of step.toolCalls ?? []) {
|
|
407
|
+
const toolSample = {
|
|
408
|
+
operation: { name: `${name}.${toolCall.toolName}`, version },
|
|
409
|
+
durationMs: durationMs ?? 0,
|
|
410
|
+
success: step.toolResults?.some((r) => r.toolCallId === toolCall.toolCallId && r.output !== undefined) ?? false,
|
|
411
|
+
timestamp: new Date,
|
|
412
|
+
metadata: {
|
|
413
|
+
agentId,
|
|
414
|
+
toolName: toolCall.toolName,
|
|
415
|
+
finishReason: step.finishReason
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
await collector.collect(toolSample);
|
|
419
|
+
}
|
|
420
|
+
const stepSample = {
|
|
421
|
+
operation: { name, version },
|
|
422
|
+
durationMs: durationMs ?? 0,
|
|
423
|
+
success: step.finishReason !== "error",
|
|
424
|
+
timestamp: new Date,
|
|
425
|
+
metadata: {
|
|
426
|
+
agentId,
|
|
427
|
+
finishReason: step.finishReason,
|
|
428
|
+
tokenUsage: step.usage,
|
|
429
|
+
toolCallCount: step.toolCalls?.length ?? 0
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
await collector.collect(stepSample);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
class InMemoryTelemetryCollector {
|
|
436
|
+
samples = [];
|
|
437
|
+
async collect(sample) {
|
|
438
|
+
this.samples.push(sample);
|
|
439
|
+
}
|
|
440
|
+
getSamples() {
|
|
441
|
+
return [...this.samples];
|
|
442
|
+
}
|
|
443
|
+
getSamplesForOperation(operationName) {
|
|
444
|
+
return this.samples.filter((s) => s.operation.name === operationName);
|
|
445
|
+
}
|
|
446
|
+
clear() {
|
|
447
|
+
this.samples.length = 0;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function createInMemoryTelemetryCollector() {
|
|
451
|
+
return new InMemoryTelemetryCollector;
|
|
452
|
+
}
|
|
453
|
+
var noopTelemetryCollector;
|
|
454
|
+
var init_adapter = __esm(() => {
|
|
455
|
+
noopTelemetryCollector = {
|
|
456
|
+
collect: async () => {}
|
|
457
|
+
};
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// src/agent/contract-spec-agent.ts
|
|
461
|
+
var exports_contract_spec_agent = {};
|
|
462
|
+
__export(exports_contract_spec_agent, {
|
|
463
|
+
ContractSpecAgent: () => ContractSpecAgent
|
|
464
|
+
});
|
|
465
|
+
import {
|
|
466
|
+
Experimental_Agent as ToolLoopAgent,
|
|
467
|
+
stepCountIs
|
|
468
|
+
} from "ai";
|
|
469
|
+
import * as z3 from "zod";
|
|
470
|
+
|
|
471
|
+
class ContractSpecAgent {
|
|
472
|
+
version = "agent-v1";
|
|
473
|
+
id;
|
|
474
|
+
spec;
|
|
475
|
+
tools;
|
|
476
|
+
inner;
|
|
477
|
+
config;
|
|
478
|
+
instructions;
|
|
479
|
+
constructor(config, instructions, tools) {
|
|
480
|
+
this.config = config;
|
|
481
|
+
this.spec = config.spec;
|
|
482
|
+
this.id = agentKey(config.spec.meta);
|
|
483
|
+
this.tools = tools;
|
|
484
|
+
this.instructions = instructions;
|
|
485
|
+
this.inner = new ToolLoopAgent({
|
|
486
|
+
model: config.model,
|
|
487
|
+
instructions,
|
|
488
|
+
tools,
|
|
489
|
+
stopWhen: stepCountIs(config.spec.maxSteps ?? 10),
|
|
490
|
+
callOptionsSchema: ContractSpecCallOptionsSchema,
|
|
491
|
+
onStepFinish: async (step) => {
|
|
492
|
+
await this.handleStepFinish(step);
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
static async create(config) {
|
|
497
|
+
const instructions = await injectStaticKnowledge(config.spec.instructions, config.spec.knowledge ?? [], config.knowledgeRetriever);
|
|
498
|
+
const specTools = specToolsToAISDKTools(config.spec.tools, config.toolHandlers, { agentId: agentKey(config.spec.meta) });
|
|
499
|
+
const knowledgeTool = config.knowledgeRetriever ? createKnowledgeQueryTool(config.knowledgeRetriever, config.spec.knowledge ?? []) : null;
|
|
500
|
+
const tools = {
|
|
501
|
+
...specTools,
|
|
502
|
+
...knowledgeTool ? { query_knowledge: knowledgeTool } : {},
|
|
503
|
+
...config.additionalTools ?? {}
|
|
504
|
+
};
|
|
505
|
+
return new ContractSpecAgent(config, instructions, tools);
|
|
506
|
+
}
|
|
507
|
+
async generate(params) {
|
|
508
|
+
const sessionId = params.options?.sessionId ?? generateSessionId();
|
|
509
|
+
if (this.config.sessionStore) {
|
|
510
|
+
const existing = await this.config.sessionStore.get(sessionId);
|
|
511
|
+
if (!existing) {
|
|
512
|
+
await this.config.sessionStore.create({
|
|
513
|
+
sessionId,
|
|
514
|
+
agentId: this.id,
|
|
515
|
+
tenantId: params.options?.tenantId,
|
|
516
|
+
actorId: params.options?.actorId,
|
|
517
|
+
status: "running",
|
|
518
|
+
messages: [],
|
|
519
|
+
steps: [],
|
|
520
|
+
metadata: params.options?.metadata
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
const prompt = params.systemOverride ? `${this.instructions}
|
|
525
|
+
|
|
526
|
+
${params.systemOverride}
|
|
527
|
+
|
|
528
|
+
${params.prompt}` : params.prompt;
|
|
529
|
+
const result = await this.inner.generate({
|
|
530
|
+
prompt,
|
|
531
|
+
abortSignal: params.signal,
|
|
532
|
+
options: {
|
|
533
|
+
tenantId: params.options?.tenantId,
|
|
534
|
+
actorId: params.options?.actorId,
|
|
535
|
+
sessionId,
|
|
536
|
+
metadata: params.options?.metadata
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
if (this.config.sessionStore) {
|
|
540
|
+
await this.config.sessionStore.update(sessionId, {
|
|
541
|
+
status: "completed"
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
text: result.text,
|
|
546
|
+
steps: result.steps,
|
|
547
|
+
toolCalls: result.toolCalls.map((tc) => ({
|
|
548
|
+
type: "tool-call",
|
|
549
|
+
toolCallId: tc.toolCallId,
|
|
550
|
+
toolName: tc.toolName,
|
|
551
|
+
args: "args" in tc ? tc.args : ("input" in tc) ? tc.input : undefined
|
|
552
|
+
})),
|
|
553
|
+
toolResults: result.toolResults.map((tr) => ({
|
|
554
|
+
type: "tool-result",
|
|
555
|
+
toolCallId: tr.toolCallId,
|
|
556
|
+
toolName: tr.toolName,
|
|
557
|
+
output: tr.output
|
|
558
|
+
})),
|
|
559
|
+
finishReason: result.finishReason,
|
|
560
|
+
usage: result.usage
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
async stream(params) {
|
|
564
|
+
const sessionId = params.options?.sessionId ?? generateSessionId();
|
|
565
|
+
const prompt = params.systemOverride ? `${this.instructions}
|
|
566
|
+
|
|
567
|
+
${params.systemOverride}
|
|
568
|
+
|
|
569
|
+
${params.prompt}` : params.prompt;
|
|
570
|
+
return this.inner.stream({
|
|
571
|
+
prompt,
|
|
572
|
+
abortSignal: params.signal,
|
|
573
|
+
options: {
|
|
574
|
+
tenantId: params.options?.tenantId,
|
|
575
|
+
actorId: params.options?.actorId,
|
|
576
|
+
sessionId,
|
|
577
|
+
metadata: params.options?.metadata
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
async handleStepFinish(step) {
|
|
582
|
+
const sessionId = step.options?.sessionId;
|
|
583
|
+
if (sessionId && this.config.sessionStore) {
|
|
584
|
+
await this.config.sessionStore.appendStep(sessionId, step);
|
|
585
|
+
}
|
|
586
|
+
if (this.config.telemetryCollector) {
|
|
587
|
+
await trackAgentStep(this.config.telemetryCollector, this.id, step);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
var ContractSpecCallOptionsSchema;
|
|
592
|
+
var init_contract_spec_agent = __esm(() => {
|
|
593
|
+
init_tool_adapter();
|
|
594
|
+
init_knowledge_tool();
|
|
595
|
+
init_adapter();
|
|
596
|
+
ContractSpecCallOptionsSchema = z3.object({
|
|
597
|
+
tenantId: z3.string().optional(),
|
|
598
|
+
actorId: z3.string().optional(),
|
|
599
|
+
sessionId: z3.string().optional(),
|
|
600
|
+
metadata: z3.record(z3.string(), z3.unknown()).optional()
|
|
601
|
+
});
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
// src/providers/types.ts
|
|
605
|
+
var ExternalProviderError, ProviderNotAvailableError, ProviderExecutionError, ContextCreationError;
|
|
606
|
+
var init_types = __esm(() => {
|
|
607
|
+
ExternalProviderError = class ExternalProviderError extends Error {
|
|
608
|
+
provider;
|
|
609
|
+
code;
|
|
610
|
+
cause;
|
|
611
|
+
constructor(message, provider, code, cause) {
|
|
612
|
+
super(message);
|
|
613
|
+
this.provider = provider;
|
|
614
|
+
this.code = code;
|
|
615
|
+
this.cause = cause;
|
|
616
|
+
this.name = "ExternalProviderError";
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
ProviderNotAvailableError = class ProviderNotAvailableError extends ExternalProviderError {
|
|
620
|
+
constructor(provider, reason) {
|
|
621
|
+
super(`Provider '${provider}' is not available${reason ? `: ${reason}` : ""}`, provider, "PROVIDER_NOT_AVAILABLE");
|
|
622
|
+
this.name = "ProviderNotAvailableError";
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
ProviderExecutionError = class ProviderExecutionError extends ExternalProviderError {
|
|
626
|
+
constructor(provider, message, cause) {
|
|
627
|
+
super(message, provider, "EXECUTION_FAILED", cause);
|
|
628
|
+
this.name = "ProviderExecutionError";
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
ContextCreationError = class ContextCreationError extends ExternalProviderError {
|
|
632
|
+
constructor(provider, message, cause) {
|
|
633
|
+
super(message, provider, "CONTEXT_CREATION_FAILED", cause);
|
|
634
|
+
this.name = "ContextCreationError";
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
// src/providers/claude-agent-sdk/tool-bridge.ts
|
|
640
|
+
function specToolToClaudeAgentTool(tool3, handler, context) {
|
|
641
|
+
return {
|
|
642
|
+
name: tool3.name,
|
|
643
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
644
|
+
input_schema: normalizeSchema(tool3.schema),
|
|
645
|
+
requires_confirmation: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
646
|
+
execute: async (input) => {
|
|
647
|
+
const fullContext = {
|
|
648
|
+
agentId: context.agentId ?? "unknown",
|
|
649
|
+
sessionId: context.sessionId ?? "unknown",
|
|
650
|
+
tenantId: context.tenantId,
|
|
651
|
+
actorId: context.actorId,
|
|
652
|
+
metadata: context.metadata,
|
|
653
|
+
signal: context.signal
|
|
654
|
+
};
|
|
655
|
+
return handler(input, fullContext);
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
function specToolsToClaudeAgentTools(tools, handlers, context) {
|
|
660
|
+
return tools.filter((tool3) => handlers.has(tool3.name)).map((tool3) => {
|
|
661
|
+
const handler = handlers.get(tool3.name);
|
|
662
|
+
if (!handler) {
|
|
663
|
+
throw new Error(`Handler not found for tool ${tool3.name}`);
|
|
664
|
+
}
|
|
665
|
+
return specToolToClaudeAgentTool(tool3, handler, context);
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
function claudeAgentToolToSpecTool(claudeTool, execute) {
|
|
669
|
+
const config = {
|
|
670
|
+
name: claudeTool.name,
|
|
671
|
+
description: claudeTool.description,
|
|
672
|
+
schema: claudeTool.input_schema,
|
|
673
|
+
requiresApproval: claudeTool.requires_confirmation,
|
|
674
|
+
automationSafe: !claudeTool.requires_confirmation
|
|
675
|
+
};
|
|
676
|
+
const handler = execute ? async (input, _ctx) => String(await execute(input)) : undefined;
|
|
677
|
+
return { config, handler };
|
|
678
|
+
}
|
|
679
|
+
function claudeAgentToolsToSpecTools(claudeTools) {
|
|
680
|
+
const configs = [];
|
|
681
|
+
const handlers = new Map;
|
|
682
|
+
for (const claudeTool of claudeTools) {
|
|
683
|
+
const { config, handler } = claudeAgentToolToSpecTool(claudeTool, claudeTool.execute);
|
|
684
|
+
configs.push(config);
|
|
685
|
+
if (handler) {
|
|
686
|
+
handlers.set(config.name, handler);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return { configs, handlers };
|
|
690
|
+
}
|
|
691
|
+
function specToolToExternalTool(tool3, handler, context) {
|
|
692
|
+
return {
|
|
693
|
+
name: tool3.name,
|
|
694
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
695
|
+
inputSchema: tool3.schema ?? { type: "object" },
|
|
696
|
+
requiresApproval: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
697
|
+
execute: handler ? async (input) => {
|
|
698
|
+
const fullContext = {
|
|
699
|
+
agentId: context?.agentId ?? "unknown",
|
|
700
|
+
sessionId: context?.sessionId ?? "unknown",
|
|
701
|
+
tenantId: context?.tenantId,
|
|
702
|
+
actorId: context?.actorId,
|
|
703
|
+
metadata: context?.metadata,
|
|
704
|
+
signal: context?.signal
|
|
705
|
+
};
|
|
706
|
+
return handler(input, fullContext);
|
|
707
|
+
} : undefined
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
function normalizeSchema(schema) {
|
|
711
|
+
if (!schema) {
|
|
712
|
+
return { type: "object" };
|
|
713
|
+
}
|
|
714
|
+
if (schema.type === "object") {
|
|
715
|
+
return schema;
|
|
716
|
+
}
|
|
717
|
+
return {
|
|
718
|
+
type: "object",
|
|
719
|
+
properties: {
|
|
720
|
+
value: schema
|
|
721
|
+
},
|
|
722
|
+
required: ["value"]
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function extractToolCalls(response) {
|
|
726
|
+
if (!response.content) {
|
|
727
|
+
return [];
|
|
728
|
+
}
|
|
729
|
+
return response.content.filter((block) => block.type === "tool_use").map((block) => ({
|
|
730
|
+
toolCallId: block.id ?? "",
|
|
731
|
+
toolName: block.name ?? "",
|
|
732
|
+
args: block.input
|
|
733
|
+
}));
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/providers/claude-agent-sdk/session-bridge.ts
|
|
737
|
+
function toClaudeAgentSession(state) {
|
|
738
|
+
const messages = [];
|
|
739
|
+
for (const msg of state.messages) {
|
|
740
|
+
if (msg.role === "user" || msg.role === "assistant") {
|
|
741
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
|
|
742
|
+
messages.push({
|
|
743
|
+
role: msg.role,
|
|
744
|
+
content
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return {
|
|
749
|
+
sessionId: state.sessionId,
|
|
750
|
+
messages,
|
|
751
|
+
metadata: {
|
|
752
|
+
agentId: state.agentId,
|
|
753
|
+
tenantId: state.tenantId,
|
|
754
|
+
actorId: state.actorId
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
function createClaudeAgentSession(options) {
|
|
759
|
+
return {
|
|
760
|
+
sessionId: options?.sessionId,
|
|
761
|
+
messages: [],
|
|
762
|
+
metadata: {
|
|
763
|
+
tenantId: options?.tenantId,
|
|
764
|
+
actorId: options?.actorId,
|
|
765
|
+
...options?.metadata
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
function createEmptyClaudeSession() {
|
|
770
|
+
return createClaudeAgentSession();
|
|
771
|
+
}
|
|
772
|
+
function buildClaudeAgentContext(options) {
|
|
773
|
+
return {
|
|
774
|
+
tenantId: options?.tenantId,
|
|
775
|
+
actorId: options?.actorId,
|
|
776
|
+
sessionId: options?.sessionId,
|
|
777
|
+
...options?.metadata
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
function appendUserMessage(session, content) {
|
|
781
|
+
return {
|
|
782
|
+
...session,
|
|
783
|
+
messages: [...session.messages, { role: "user", content }]
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
function appendAssistantMessage(session, content) {
|
|
787
|
+
return {
|
|
788
|
+
...session,
|
|
789
|
+
messages: [...session.messages, { role: "assistant", content }]
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
function clearSession(session) {
|
|
793
|
+
return {
|
|
794
|
+
...session,
|
|
795
|
+
messages: []
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function getRecentMessages(session, count) {
|
|
799
|
+
return session.messages.slice(-count);
|
|
800
|
+
}
|
|
801
|
+
function extractToolUseBlocks(content) {
|
|
802
|
+
if (typeof content === "string") {
|
|
803
|
+
return [];
|
|
804
|
+
}
|
|
805
|
+
return content.filter((block) => block.type === "tool_use");
|
|
806
|
+
}
|
|
807
|
+
function createToolResultBlock(toolUseId, result, isError = false) {
|
|
808
|
+
return {
|
|
809
|
+
type: "tool_result",
|
|
810
|
+
tool_use_id: toolUseId,
|
|
811
|
+
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
812
|
+
is_error: isError
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
function updateSessionMetadata(session, metadata) {
|
|
816
|
+
return {
|
|
817
|
+
...session,
|
|
818
|
+
metadata: {
|
|
819
|
+
...session.metadata,
|
|
820
|
+
...metadata
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
function getMessageCount(session) {
|
|
825
|
+
return session.messages.length;
|
|
826
|
+
}
|
|
827
|
+
function estimateTokens(session) {
|
|
828
|
+
let chars = 0;
|
|
829
|
+
for (const msg of session.messages) {
|
|
830
|
+
if (typeof msg.content === "string") {
|
|
831
|
+
chars += msg.content.length;
|
|
832
|
+
} else {
|
|
833
|
+
chars += JSON.stringify(msg.content).length;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return Math.ceil(chars / 4);
|
|
837
|
+
}
|
|
838
|
+
function summarizeSession(session) {
|
|
839
|
+
let userMessages = 0;
|
|
840
|
+
let assistantMessages = 0;
|
|
841
|
+
for (const msg of session.messages) {
|
|
842
|
+
if (msg.role === "user") {
|
|
843
|
+
userMessages++;
|
|
844
|
+
} else {
|
|
845
|
+
assistantMessages++;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
return {
|
|
849
|
+
messageCount: session.messages.length,
|
|
850
|
+
userMessages,
|
|
851
|
+
assistantMessages,
|
|
852
|
+
estimatedTokens: estimateTokens(session)
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// src/providers/claude-agent-sdk/adapter.ts
|
|
857
|
+
class ClaudeAgentSDKProvider {
|
|
858
|
+
name = "claude-agent-sdk";
|
|
859
|
+
version = "1.0.0";
|
|
860
|
+
config;
|
|
861
|
+
sdkAvailable = null;
|
|
862
|
+
constructor(config = {}) {
|
|
863
|
+
this.config = {
|
|
864
|
+
model: "claude-sonnet-4-20250514",
|
|
865
|
+
extendedThinking: false,
|
|
866
|
+
computerUse: false,
|
|
867
|
+
maxTokens: 4096,
|
|
868
|
+
temperature: 0.7,
|
|
869
|
+
...config
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
isAvailable() {
|
|
873
|
+
if (this.sdkAvailable !== null) {
|
|
874
|
+
return this.sdkAvailable;
|
|
875
|
+
}
|
|
876
|
+
try {
|
|
877
|
+
__require.resolve("@anthropic-ai/claude-agent-sdk");
|
|
878
|
+
const apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY;
|
|
879
|
+
this.sdkAvailable = Boolean(apiKey);
|
|
880
|
+
} catch {
|
|
881
|
+
this.sdkAvailable = false;
|
|
882
|
+
}
|
|
883
|
+
return this.sdkAvailable;
|
|
884
|
+
}
|
|
885
|
+
async createContext(spec) {
|
|
886
|
+
if (!this.isAvailable()) {
|
|
887
|
+
throw new ProviderNotAvailableError(this.name, "SDK not installed or API key not configured");
|
|
888
|
+
}
|
|
889
|
+
try {
|
|
890
|
+
const toolSet = {};
|
|
891
|
+
for (const tool3 of spec.tools) {
|
|
892
|
+
toolSet[tool3.name] = specToolToExternalTool(tool3);
|
|
893
|
+
}
|
|
894
|
+
const instructions = await injectStaticKnowledge(spec.instructions, spec.knowledge ?? [], undefined);
|
|
895
|
+
const contextId = `claude-${agentKey(spec.meta)}-${Date.now()}`;
|
|
896
|
+
const metadata = {
|
|
897
|
+
computerUseEnabled: this.config.computerUse ?? false,
|
|
898
|
+
extendedThinkingEnabled: this.config.extendedThinking ?? false,
|
|
899
|
+
mcpServerIds: this.config.mcpServers?.map((s) => s.name) ?? []
|
|
900
|
+
};
|
|
901
|
+
return {
|
|
902
|
+
id: contextId,
|
|
903
|
+
spec: {
|
|
904
|
+
...spec,
|
|
905
|
+
instructions
|
|
906
|
+
},
|
|
907
|
+
tools: toolSet,
|
|
908
|
+
metadata,
|
|
909
|
+
cleanup: async () => {}
|
|
910
|
+
};
|
|
911
|
+
} catch (error) {
|
|
912
|
+
throw new ContextCreationError(this.name, `Failed to create context: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
async execute(context, params) {
|
|
916
|
+
try {
|
|
917
|
+
const sdk = await this.loadSDK();
|
|
918
|
+
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
919
|
+
|
|
920
|
+
${params.systemOverride}` : context.spec.instructions;
|
|
921
|
+
const claudeContext = buildClaudeAgentContext(params.options);
|
|
922
|
+
let session = createEmptyClaudeSession();
|
|
923
|
+
session = appendUserMessage(session, params.prompt);
|
|
924
|
+
const claudeTools = this.prepareToolsForSDK(context, params);
|
|
925
|
+
const rawResponse = await sdk.execute({
|
|
926
|
+
model: this.config.model,
|
|
927
|
+
system: systemPrompt,
|
|
928
|
+
messages: session.messages,
|
|
929
|
+
tools: claudeTools,
|
|
930
|
+
max_tokens: this.config.maxTokens,
|
|
931
|
+
temperature: this.config.temperature,
|
|
932
|
+
metadata: claudeContext,
|
|
933
|
+
extended_thinking: this.config.extendedThinking,
|
|
934
|
+
computer_use: this.config.computerUse
|
|
935
|
+
});
|
|
936
|
+
const response = rawResponse;
|
|
937
|
+
const toolCalls = extractToolCalls(response);
|
|
938
|
+
const toolResults = await this.executeTools(toolCalls, context, params);
|
|
939
|
+
if (response.content) {
|
|
940
|
+
const content = response.content;
|
|
941
|
+
session = appendAssistantMessage(session, content);
|
|
942
|
+
}
|
|
943
|
+
return {
|
|
944
|
+
text: this.extractTextContent(response),
|
|
945
|
+
toolCalls: toolCalls.map((tc) => ({
|
|
946
|
+
type: "tool-call",
|
|
947
|
+
toolCallId: tc.toolCallId,
|
|
948
|
+
toolName: tc.toolName,
|
|
949
|
+
args: tc.args
|
|
950
|
+
})),
|
|
951
|
+
toolResults: toolResults.map((tr) => ({
|
|
952
|
+
type: "tool-result",
|
|
953
|
+
toolCallId: tr.toolCallId,
|
|
954
|
+
toolName: tr.toolName,
|
|
955
|
+
output: tr.output
|
|
956
|
+
})),
|
|
957
|
+
usage: {
|
|
958
|
+
inputTokens: response.usage?.input_tokens ?? 0,
|
|
959
|
+
outputTokens: response.usage?.output_tokens ?? 0
|
|
960
|
+
},
|
|
961
|
+
finishReason: this.mapStopReason(response.stop_reason),
|
|
962
|
+
metadata: {
|
|
963
|
+
sessionId: context.metadata?.sessionId,
|
|
964
|
+
model: response.model
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
} catch (error) {
|
|
968
|
+
throw new ProviderExecutionError(this.name, `Execution failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
async* stream(context, params) {
|
|
972
|
+
try {
|
|
973
|
+
const sdk = await this.loadSDK();
|
|
974
|
+
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
975
|
+
|
|
976
|
+
${params.systemOverride}` : context.spec.instructions;
|
|
977
|
+
const claudeContext = buildClaudeAgentContext(params.options);
|
|
978
|
+
const claudeTools = this.prepareToolsForSDK(context, params);
|
|
979
|
+
const stream = await sdk.stream({
|
|
980
|
+
model: this.config.model,
|
|
981
|
+
system: systemPrompt,
|
|
982
|
+
messages: [{ role: "user", content: params.prompt }],
|
|
983
|
+
tools: claudeTools,
|
|
984
|
+
max_tokens: this.config.maxTokens,
|
|
985
|
+
temperature: this.config.temperature,
|
|
986
|
+
metadata: claudeContext,
|
|
987
|
+
extended_thinking: this.config.extendedThinking,
|
|
988
|
+
computer_use: this.config.computerUse
|
|
989
|
+
});
|
|
990
|
+
let fullText = "";
|
|
991
|
+
const allToolCalls = [];
|
|
992
|
+
const allToolResults = [];
|
|
993
|
+
let stepIndex = 0;
|
|
994
|
+
for await (const event of stream) {
|
|
995
|
+
if (event.type === "content_block_delta" && event.delta?.type === "text_delta") {
|
|
996
|
+
const text = event.delta.text ?? "";
|
|
997
|
+
fullText += text;
|
|
998
|
+
yield { type: "text", text };
|
|
999
|
+
}
|
|
1000
|
+
if (event.type === "content_block_start" && event.content_block?.type === "tool_use") {
|
|
1001
|
+
const toolCall = {
|
|
1002
|
+
toolCallId: event.content_block.id ?? "",
|
|
1003
|
+
toolName: event.content_block.name ?? "",
|
|
1004
|
+
args: event.content_block.input
|
|
1005
|
+
};
|
|
1006
|
+
allToolCalls.push(toolCall);
|
|
1007
|
+
yield {
|
|
1008
|
+
type: "tool-call",
|
|
1009
|
+
toolCall: {
|
|
1010
|
+
type: "tool-call",
|
|
1011
|
+
...toolCall
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
if (event.type === "message_stop") {
|
|
1016
|
+
stepIndex++;
|
|
1017
|
+
yield { type: "step-complete", stepIndex };
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
for (const toolCall of allToolCalls) {
|
|
1021
|
+
const result = await this.executeTool(toolCall, context, params);
|
|
1022
|
+
allToolResults.push(result);
|
|
1023
|
+
yield {
|
|
1024
|
+
type: "tool-result",
|
|
1025
|
+
toolResult: {
|
|
1026
|
+
type: "tool-result",
|
|
1027
|
+
...result
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
yield {
|
|
1032
|
+
type: "done",
|
|
1033
|
+
result: {
|
|
1034
|
+
text: fullText,
|
|
1035
|
+
toolCalls: allToolCalls.map((tc) => ({
|
|
1036
|
+
type: "tool-call",
|
|
1037
|
+
...tc
|
|
1038
|
+
})),
|
|
1039
|
+
toolResults: allToolResults.map((tr) => ({
|
|
1040
|
+
type: "tool-result",
|
|
1041
|
+
...tr
|
|
1042
|
+
})),
|
|
1043
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
1044
|
+
finishReason: "stop"
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
throw new ProviderExecutionError(this.name, `Stream failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
async loadSDK() {
|
|
1052
|
+
try {
|
|
1053
|
+
const module = __require("@anthropic-ai/claude-agent-sdk");
|
|
1054
|
+
return module.default ?? module;
|
|
1055
|
+
} catch {
|
|
1056
|
+
throw new ProviderNotAvailableError(this.name, "@anthropic-ai/claude-agent-sdk is not installed");
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
prepareToolsForSDK(context, params) {
|
|
1060
|
+
const handlers = new Map;
|
|
1061
|
+
for (const tool3 of context.spec.tools) {
|
|
1062
|
+
const externalTool = context.tools[tool3.name];
|
|
1063
|
+
if (externalTool?.execute) {
|
|
1064
|
+
handlers.set(tool3.name, async (input) => {
|
|
1065
|
+
if (!externalTool.execute) {
|
|
1066
|
+
throw new Error(`Tool ${tool3.name} has no execute handler`);
|
|
1067
|
+
}
|
|
1068
|
+
const result = await externalTool.execute(input);
|
|
1069
|
+
return typeof result === "string" ? result : JSON.stringify(result);
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
return specToolsToClaudeAgentTools(context.spec.tools, handlers, {
|
|
1074
|
+
agentId: context.id,
|
|
1075
|
+
sessionId: params.options?.sessionId,
|
|
1076
|
+
tenantId: params.options?.tenantId,
|
|
1077
|
+
actorId: params.options?.actorId,
|
|
1078
|
+
metadata: params.options?.metadata,
|
|
1079
|
+
signal: params.signal
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
async executeTool(toolCall, context, _params) {
|
|
1083
|
+
const tool3 = context.tools[toolCall.toolName];
|
|
1084
|
+
if (!tool3?.execute) {
|
|
1085
|
+
return {
|
|
1086
|
+
toolCallId: toolCall.toolCallId,
|
|
1087
|
+
toolName: toolCall.toolName,
|
|
1088
|
+
output: `Error: Tool '${toolCall.toolName}' not found or has no handler`
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
try {
|
|
1092
|
+
const output = await tool3.execute(toolCall.args);
|
|
1093
|
+
return {
|
|
1094
|
+
toolCallId: toolCall.toolCallId,
|
|
1095
|
+
toolName: toolCall.toolName,
|
|
1096
|
+
output
|
|
1097
|
+
};
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
return {
|
|
1100
|
+
toolCallId: toolCall.toolCallId,
|
|
1101
|
+
toolName: toolCall.toolName,
|
|
1102
|
+
output: `Error: ${error instanceof Error ? error.message : String(error)}`
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
async executeTools(toolCalls, context, params) {
|
|
1107
|
+
return Promise.all(toolCalls.map((tc) => this.executeTool(tc, context, params)));
|
|
1108
|
+
}
|
|
1109
|
+
extractTextContent(response) {
|
|
1110
|
+
if (!response.content) {
|
|
1111
|
+
return "";
|
|
1112
|
+
}
|
|
1113
|
+
return response.content.filter((block) => typeof block === "object" && block !== null && block.type === "text").map((block) => block.text).join("");
|
|
1114
|
+
}
|
|
1115
|
+
mapStopReason(stopReason) {
|
|
1116
|
+
switch (stopReason) {
|
|
1117
|
+
case "end_turn":
|
|
1118
|
+
case "stop_sequence":
|
|
1119
|
+
return "stop";
|
|
1120
|
+
case "tool_use":
|
|
1121
|
+
return "tool-calls";
|
|
1122
|
+
case "max_tokens":
|
|
1123
|
+
return "length";
|
|
1124
|
+
default:
|
|
1125
|
+
return "stop";
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
var init_adapter2 = __esm(() => {
|
|
1130
|
+
init_types();
|
|
1131
|
+
});
|
|
1132
|
+
|
|
1133
|
+
// src/providers/claude-agent-sdk/index.ts
|
|
1134
|
+
var exports_claude_agent_sdk = {};
|
|
1135
|
+
__export(exports_claude_agent_sdk, {
|
|
1136
|
+
updateSessionMetadata: () => updateSessionMetadata,
|
|
1137
|
+
toClaudeAgentSession: () => toClaudeAgentSession,
|
|
1138
|
+
summarizeSession: () => summarizeSession,
|
|
1139
|
+
specToolsToClaudeAgentTools: () => specToolsToClaudeAgentTools,
|
|
1140
|
+
specToolToExternalTool: () => specToolToExternalTool,
|
|
1141
|
+
specToolToClaudeAgentTool: () => specToolToClaudeAgentTool,
|
|
1142
|
+
getRecentMessages: () => getRecentMessages,
|
|
1143
|
+
getMessageCount: () => getMessageCount,
|
|
1144
|
+
extractToolUseBlocks: () => extractToolUseBlocks,
|
|
1145
|
+
extractToolCalls: () => extractToolCalls,
|
|
1146
|
+
estimateTokens: () => estimateTokens,
|
|
1147
|
+
createToolResultBlock: () => createToolResultBlock,
|
|
1148
|
+
createEmptyClaudeSession: () => createEmptyClaudeSession,
|
|
1149
|
+
createClaudeAgentSession: () => createClaudeAgentSession,
|
|
1150
|
+
clearSession: () => clearSession,
|
|
1151
|
+
claudeAgentToolsToSpecTools: () => claudeAgentToolsToSpecTools,
|
|
1152
|
+
claudeAgentToolToSpecTool: () => claudeAgentToolToSpecTool,
|
|
1153
|
+
buildClaudeAgentContext: () => buildClaudeAgentContext,
|
|
1154
|
+
appendUserMessage: () => appendUserMessage,
|
|
1155
|
+
appendAssistantMessage: () => appendAssistantMessage,
|
|
1156
|
+
ClaudeAgentSDKProvider: () => ClaudeAgentSDKProvider
|
|
1157
|
+
});
|
|
1158
|
+
var init_claude_agent_sdk = __esm(() => {
|
|
1159
|
+
init_adapter2();
|
|
1160
|
+
});
|
|
1161
|
+
|
|
1162
|
+
// src/providers/opencode-sdk/tool-bridge.ts
|
|
1163
|
+
function specToolToOpenCodeTool(tool3) {
|
|
1164
|
+
return {
|
|
1165
|
+
name: tool3.name,
|
|
1166
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
1167
|
+
parameters: normalizeToOpenCodeParameters(tool3.schema),
|
|
1168
|
+
permission: getPermissionLevel(tool3)
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function specToolsToOpenCodeTools(tools) {
|
|
1172
|
+
return tools.map(specToolToOpenCodeTool);
|
|
1173
|
+
}
|
|
1174
|
+
function getPermissionLevel(tool3) {
|
|
1175
|
+
if (tool3.requiresApproval) {
|
|
1176
|
+
return "ask";
|
|
1177
|
+
}
|
|
1178
|
+
if (tool3.automationSafe === false) {
|
|
1179
|
+
return "ask";
|
|
1180
|
+
}
|
|
1181
|
+
return "allow";
|
|
1182
|
+
}
|
|
1183
|
+
function openCodeToolToSpecTool(openCodeTool) {
|
|
1184
|
+
return {
|
|
1185
|
+
name: openCodeTool.name,
|
|
1186
|
+
description: openCodeTool.description,
|
|
1187
|
+
schema: openCodeTool.parameters,
|
|
1188
|
+
requiresApproval: openCodeTool.permission === "ask",
|
|
1189
|
+
automationSafe: openCodeTool.permission === "allow"
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
function openCodeToolsToSpecTools(openCodeTools) {
|
|
1193
|
+
return openCodeTools.map(openCodeToolToSpecTool);
|
|
1194
|
+
}
|
|
1195
|
+
function specToolToExternalToolForOpenCode(tool3, handler, context) {
|
|
1196
|
+
return {
|
|
1197
|
+
name: tool3.name,
|
|
1198
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
1199
|
+
inputSchema: tool3.schema ?? { type: "object" },
|
|
1200
|
+
requiresApproval: tool3.requiresApproval ?? !tool3.automationSafe,
|
|
1201
|
+
execute: handler ? async (input) => {
|
|
1202
|
+
const fullContext = {
|
|
1203
|
+
agentId: context?.agentId ?? "unknown",
|
|
1204
|
+
sessionId: context?.sessionId ?? "unknown",
|
|
1205
|
+
tenantId: context?.tenantId,
|
|
1206
|
+
actorId: context?.actorId,
|
|
1207
|
+
metadata: context?.metadata,
|
|
1208
|
+
signal: context?.signal
|
|
1209
|
+
};
|
|
1210
|
+
return handler(input, fullContext);
|
|
1211
|
+
} : undefined
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
function normalizeToOpenCodeParameters(schema) {
|
|
1215
|
+
if (!schema) {
|
|
1216
|
+
return { type: "object" };
|
|
1217
|
+
}
|
|
1218
|
+
if (schema.type === "object") {
|
|
1219
|
+
return {
|
|
1220
|
+
type: "object",
|
|
1221
|
+
properties: schema.properties,
|
|
1222
|
+
required: schema.required
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
return {
|
|
1226
|
+
type: "object",
|
|
1227
|
+
properties: {
|
|
1228
|
+
value: convertToOpenCodeParameter(schema)
|
|
1229
|
+
},
|
|
1230
|
+
required: ["value"]
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
function convertToOpenCodeParameter(schema) {
|
|
1234
|
+
const param = {
|
|
1235
|
+
type: schema.type ?? "string"
|
|
1236
|
+
};
|
|
1237
|
+
if (schema.description) {
|
|
1238
|
+
param.description = schema.description;
|
|
1239
|
+
}
|
|
1240
|
+
if (schema.enum) {
|
|
1241
|
+
param.enum = schema.enum;
|
|
1242
|
+
}
|
|
1243
|
+
if (schema.default !== undefined) {
|
|
1244
|
+
param.default = schema.default;
|
|
1245
|
+
}
|
|
1246
|
+
return param;
|
|
1247
|
+
}
|
|
1248
|
+
function createToolHandlerMap(tools) {
|
|
1249
|
+
const handlers = new Map;
|
|
1250
|
+
for (const [name, tool3] of Object.entries(tools)) {
|
|
1251
|
+
if (tool3.execute) {
|
|
1252
|
+
handlers.set(name, tool3.execute);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
return handlers;
|
|
1256
|
+
}
|
|
1257
|
+
async function executeToolCall(toolCall, handlers) {
|
|
1258
|
+
const handler = handlers.get(toolCall.name);
|
|
1259
|
+
if (!handler) {
|
|
1260
|
+
return {
|
|
1261
|
+
tool_call_id: toolCall.id,
|
|
1262
|
+
output: `Error: Tool '${toolCall.name}' not found`,
|
|
1263
|
+
is_error: true
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
try {
|
|
1267
|
+
const result = await handler(toolCall.arguments);
|
|
1268
|
+
return {
|
|
1269
|
+
tool_call_id: toolCall.id,
|
|
1270
|
+
output: typeof result === "string" ? result : JSON.stringify(result)
|
|
1271
|
+
};
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
return {
|
|
1274
|
+
tool_call_id: toolCall.id,
|
|
1275
|
+
output: `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
1276
|
+
is_error: true
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// src/providers/opencode-sdk/agent-bridge.ts
|
|
1282
|
+
function inferAgentType(spec) {
|
|
1283
|
+
const hasCodeTools = spec.tools.some((tool3) => [
|
|
1284
|
+
"write_file",
|
|
1285
|
+
"edit_file",
|
|
1286
|
+
"create_file",
|
|
1287
|
+
"delete_file",
|
|
1288
|
+
"bash",
|
|
1289
|
+
"execute",
|
|
1290
|
+
"run_command",
|
|
1291
|
+
"terminal"
|
|
1292
|
+
].includes(tool3.name.toLowerCase()));
|
|
1293
|
+
const instructionsLower = spec.instructions.toLowerCase();
|
|
1294
|
+
const hasPlanningKeywords = /\b(plan|design|architect|strategy|analyze|review|assess|evaluate)\b/.test(instructionsLower);
|
|
1295
|
+
const hasExplorationKeywords = /\b(search|find|explore|discover|locate|grep|pattern)\b/.test(instructionsLower);
|
|
1296
|
+
const hasResearchKeywords = /\b(research|investigate|understand|learn|gather|collect)\b/.test(instructionsLower);
|
|
1297
|
+
if (hasCodeTools) {
|
|
1298
|
+
return "build";
|
|
1299
|
+
}
|
|
1300
|
+
if (hasPlanningKeywords && !hasCodeTools) {
|
|
1301
|
+
return "plan";
|
|
1302
|
+
}
|
|
1303
|
+
if (hasExplorationKeywords && !hasResearchKeywords) {
|
|
1304
|
+
return "explore";
|
|
1305
|
+
}
|
|
1306
|
+
return "general";
|
|
1307
|
+
}
|
|
1308
|
+
function specToOpenCodeConfig(spec, options) {
|
|
1309
|
+
const agentType = options?.agentType ?? inferAgentType(spec);
|
|
1310
|
+
return {
|
|
1311
|
+
name: spec.meta.key,
|
|
1312
|
+
version: spec.meta.version,
|
|
1313
|
+
description: spec.description ?? spec.meta.description,
|
|
1314
|
+
instructions: spec.instructions,
|
|
1315
|
+
agent_type: agentType,
|
|
1316
|
+
tools: specToolsToOpenCodeTools(spec.tools),
|
|
1317
|
+
config: {
|
|
1318
|
+
max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
|
|
1319
|
+
temperature: options?.temperature ?? 0.7,
|
|
1320
|
+
model: options?.model,
|
|
1321
|
+
permissions: buildPermissions(spec)
|
|
1322
|
+
}
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
function buildPermissions(spec) {
|
|
1326
|
+
const permissions = {};
|
|
1327
|
+
for (const tool3 of spec.tools) {
|
|
1328
|
+
if (tool3.requiresApproval) {
|
|
1329
|
+
permissions[tool3.name] = "ask";
|
|
1330
|
+
} else if (tool3.automationSafe === false) {
|
|
1331
|
+
permissions[tool3.name] = "ask";
|
|
1332
|
+
} else {
|
|
1333
|
+
permissions[tool3.name] = "allow";
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return permissions;
|
|
1337
|
+
}
|
|
1338
|
+
function specToOpenCodeMarkdown(spec, options) {
|
|
1339
|
+
const agentType = options?.agentType ?? inferAgentType(spec);
|
|
1340
|
+
return {
|
|
1341
|
+
frontmatter: {
|
|
1342
|
+
name: spec.meta.key,
|
|
1343
|
+
type: agentType,
|
|
1344
|
+
version: spec.meta.version,
|
|
1345
|
+
model: options?.model,
|
|
1346
|
+
temperature: options?.temperature ?? 0.7,
|
|
1347
|
+
max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
|
|
1348
|
+
tools: spec.tools.map((t) => t.name)
|
|
1349
|
+
},
|
|
1350
|
+
body: buildMarkdownBody(spec)
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
function buildMarkdownBody(spec) {
|
|
1354
|
+
const lines = [];
|
|
1355
|
+
lines.push(`# ${spec.meta.key}`);
|
|
1356
|
+
lines.push("");
|
|
1357
|
+
if (spec.description ?? spec.meta.description) {
|
|
1358
|
+
lines.push(spec.description ?? spec.meta.description ?? "");
|
|
1359
|
+
lines.push("");
|
|
1360
|
+
}
|
|
1361
|
+
lines.push("## Instructions");
|
|
1362
|
+
lines.push("");
|
|
1363
|
+
lines.push(spec.instructions);
|
|
1364
|
+
lines.push("");
|
|
1365
|
+
if (spec.tools.length > 0) {
|
|
1366
|
+
lines.push("## Tools");
|
|
1367
|
+
lines.push("");
|
|
1368
|
+
for (const tool3 of spec.tools) {
|
|
1369
|
+
const permission = tool3.requiresApproval ? "(requires approval)" : tool3.automationSafe === false ? "(ask mode)" : "";
|
|
1370
|
+
lines.push(`- **${tool3.name}**: ${tool3.description ?? "No description"} ${permission}`.trim());
|
|
1371
|
+
}
|
|
1372
|
+
lines.push("");
|
|
1373
|
+
}
|
|
1374
|
+
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
1375
|
+
lines.push("## Knowledge Sources");
|
|
1376
|
+
lines.push("");
|
|
1377
|
+
for (const k of spec.knowledge) {
|
|
1378
|
+
const required = k.required ? "(required)" : "(optional)";
|
|
1379
|
+
lines.push(`- ${k.key} ${required}`);
|
|
1380
|
+
}
|
|
1381
|
+
lines.push("");
|
|
1382
|
+
}
|
|
1383
|
+
return lines.join(`
|
|
1384
|
+
`);
|
|
1385
|
+
}
|
|
1386
|
+
function serializeOpenCodeMarkdown(markdown) {
|
|
1387
|
+
const lines = [];
|
|
1388
|
+
lines.push("---");
|
|
1389
|
+
lines.push(`name: ${markdown.frontmatter.name}`);
|
|
1390
|
+
lines.push(`type: ${markdown.frontmatter.type}`);
|
|
1391
|
+
if (markdown.frontmatter.version) {
|
|
1392
|
+
lines.push(`version: ${markdown.frontmatter.version}`);
|
|
1393
|
+
}
|
|
1394
|
+
if (markdown.frontmatter.model) {
|
|
1395
|
+
lines.push(`model: ${markdown.frontmatter.model}`);
|
|
1396
|
+
}
|
|
1397
|
+
if (markdown.frontmatter.temperature !== undefined) {
|
|
1398
|
+
lines.push(`temperature: ${markdown.frontmatter.temperature}`);
|
|
1399
|
+
}
|
|
1400
|
+
if (markdown.frontmatter.max_steps !== undefined) {
|
|
1401
|
+
lines.push(`max_steps: ${markdown.frontmatter.max_steps}`);
|
|
1402
|
+
}
|
|
1403
|
+
if (markdown.frontmatter.tools && markdown.frontmatter.tools.length > 0) {
|
|
1404
|
+
lines.push(`tools:`);
|
|
1405
|
+
for (const tool3 of markdown.frontmatter.tools) {
|
|
1406
|
+
lines.push(` - ${tool3}`);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
lines.push("---");
|
|
1410
|
+
lines.push("");
|
|
1411
|
+
lines.push(markdown.body);
|
|
1412
|
+
return lines.join(`
|
|
1413
|
+
`);
|
|
1414
|
+
}
|
|
1415
|
+
function openCodeConfigToSpec(config) {
|
|
1416
|
+
return {
|
|
1417
|
+
meta: {
|
|
1418
|
+
key: config.name,
|
|
1419
|
+
version: config.version ?? "1.0.0",
|
|
1420
|
+
description: config.description ?? "",
|
|
1421
|
+
stability: "experimental",
|
|
1422
|
+
owners: [],
|
|
1423
|
+
tags: []
|
|
1424
|
+
},
|
|
1425
|
+
description: config.description,
|
|
1426
|
+
instructions: config.instructions ?? "",
|
|
1427
|
+
tools: config.tools?.map((tool3) => ({
|
|
1428
|
+
name: tool3.name,
|
|
1429
|
+
description: tool3.description,
|
|
1430
|
+
schema: tool3.parameters,
|
|
1431
|
+
requiresApproval: tool3.permission === "ask",
|
|
1432
|
+
automationSafe: tool3.permission === "allow"
|
|
1433
|
+
})) ?? [],
|
|
1434
|
+
maxSteps: config.config?.max_steps ?? 10
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
var init_agent_bridge = () => {};
|
|
1438
|
+
|
|
1439
|
+
// src/providers/opencode-sdk/adapter.ts
|
|
1440
|
+
class OpenCodeSDKProvider {
|
|
1441
|
+
name = "opencode-sdk";
|
|
1442
|
+
version = "1.0.0";
|
|
1443
|
+
config;
|
|
1444
|
+
sdkAvailable = null;
|
|
1445
|
+
constructor(config = {}) {
|
|
1446
|
+
this.config = {
|
|
1447
|
+
serverUrl: "http://127.0.0.1:4096",
|
|
1448
|
+
port: 4096,
|
|
1449
|
+
agentType: "general",
|
|
1450
|
+
temperature: 0.7,
|
|
1451
|
+
timeout: 30000,
|
|
1452
|
+
...config
|
|
1453
|
+
};
|
|
1454
|
+
if (!config.serverUrl && config.port) {
|
|
1455
|
+
this.config.serverUrl = `http://127.0.0.1:${config.port}`;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
isAvailable() {
|
|
1459
|
+
if (this.sdkAvailable !== null) {
|
|
1460
|
+
return this.sdkAvailable;
|
|
1461
|
+
}
|
|
1462
|
+
try {
|
|
1463
|
+
__require.resolve("@opencode-ai/sdk");
|
|
1464
|
+
this.sdkAvailable = true;
|
|
1465
|
+
} catch {
|
|
1466
|
+
this.sdkAvailable = false;
|
|
1467
|
+
}
|
|
1468
|
+
return this.sdkAvailable;
|
|
1469
|
+
}
|
|
1470
|
+
async createContext(spec) {
|
|
1471
|
+
if (!this.isAvailable()) {
|
|
1472
|
+
throw new ProviderNotAvailableError(this.name, "SDK not installed");
|
|
1473
|
+
}
|
|
1474
|
+
try {
|
|
1475
|
+
const sdk = await this.loadSDK();
|
|
1476
|
+
const { client } = await sdk.createOpencode({
|
|
1477
|
+
hostname: this.getHostname(),
|
|
1478
|
+
port: this.config.port ?? 4096,
|
|
1479
|
+
timeout: this.config.timeout
|
|
1480
|
+
});
|
|
1481
|
+
const session = await client.session.create({
|
|
1482
|
+
agent: this.config.agentType ?? inferAgentType(spec),
|
|
1483
|
+
model: this.config.model
|
|
1484
|
+
});
|
|
1485
|
+
const toolSet = {};
|
|
1486
|
+
for (const tool3 of spec.tools) {
|
|
1487
|
+
toolSet[tool3.name] = specToolToExternalToolForOpenCode(tool3);
|
|
1488
|
+
}
|
|
1489
|
+
const instructions = await injectStaticKnowledge(spec.instructions, spec.knowledge ?? [], undefined);
|
|
1490
|
+
const contextId = `opencode-${agentKey(spec.meta)}-${Date.now()}`;
|
|
1491
|
+
const metadata = {
|
|
1492
|
+
sessionId: session.id,
|
|
1493
|
+
agentType: this.config.agentType ?? inferAgentType(spec),
|
|
1494
|
+
serverUrl: this.config.serverUrl ?? `http://127.0.0.1:${this.config.port ?? 4096}`
|
|
1495
|
+
};
|
|
1496
|
+
return {
|
|
1497
|
+
id: contextId,
|
|
1498
|
+
spec: {
|
|
1499
|
+
...spec,
|
|
1500
|
+
instructions
|
|
1501
|
+
},
|
|
1502
|
+
tools: toolSet,
|
|
1503
|
+
metadata,
|
|
1504
|
+
cleanup: async () => {
|
|
1505
|
+
try {
|
|
1506
|
+
await client.session.delete({ id: session.id });
|
|
1507
|
+
} catch {}
|
|
1508
|
+
}
|
|
1509
|
+
};
|
|
1510
|
+
} catch (error) {
|
|
1511
|
+
throw new ContextCreationError(this.name, `Failed to create context: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
async execute(context, params) {
|
|
1515
|
+
try {
|
|
1516
|
+
const sdk = await this.loadSDK();
|
|
1517
|
+
const metadata = context.metadata;
|
|
1518
|
+
const { client } = await sdk.createOpencodeClient({
|
|
1519
|
+
baseUrl: metadata.serverUrl
|
|
1520
|
+
});
|
|
1521
|
+
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
1522
|
+
|
|
1523
|
+
${params.systemOverride}` : context.spec.instructions;
|
|
1524
|
+
const response = await client.session.prompt({
|
|
1525
|
+
id: metadata.sessionId,
|
|
1526
|
+
body: {
|
|
1527
|
+
content: params.prompt,
|
|
1528
|
+
system: systemPrompt
|
|
1529
|
+
}
|
|
1530
|
+
});
|
|
1531
|
+
const toolCalls = this.extractToolCalls(response);
|
|
1532
|
+
const toolHandlers = createToolHandlerMap(context.tools);
|
|
1533
|
+
const toolResults = await Promise.all(toolCalls.map((tc) => executeToolCall(tc, toolHandlers)));
|
|
1534
|
+
return {
|
|
1535
|
+
text: this.extractTextContent(response),
|
|
1536
|
+
toolCalls: toolCalls.map((tc) => ({
|
|
1537
|
+
type: "tool-call",
|
|
1538
|
+
toolCallId: tc.id,
|
|
1539
|
+
toolName: tc.name,
|
|
1540
|
+
args: tc.arguments
|
|
1541
|
+
})),
|
|
1542
|
+
toolResults: toolResults.map((tr) => ({
|
|
1543
|
+
type: "tool-result",
|
|
1544
|
+
toolCallId: tr.tool_call_id,
|
|
1545
|
+
toolName: toolCalls.find((tc) => tc.id === tr.tool_call_id)?.name ?? "",
|
|
1546
|
+
output: tr.output
|
|
1547
|
+
})),
|
|
1548
|
+
usage: {
|
|
1549
|
+
inputTokens: response.usage?.input_tokens ?? 0,
|
|
1550
|
+
outputTokens: response.usage?.output_tokens ?? 0
|
|
1551
|
+
},
|
|
1552
|
+
finishReason: this.mapFinishReason(response.finish_reason),
|
|
1553
|
+
metadata: {
|
|
1554
|
+
sessionId: metadata.sessionId,
|
|
1555
|
+
agentType: metadata.agentType
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
} catch (error) {
|
|
1559
|
+
throw new ProviderExecutionError(this.name, `Execution failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
async* stream(context, params) {
|
|
1563
|
+
try {
|
|
1564
|
+
const sdk = await this.loadSDK();
|
|
1565
|
+
const metadata = context.metadata;
|
|
1566
|
+
const { client } = await sdk.createOpencodeClient({
|
|
1567
|
+
baseUrl: metadata.serverUrl
|
|
1568
|
+
});
|
|
1569
|
+
const systemPrompt = params.systemOverride ? `${context.spec.instructions}
|
|
1570
|
+
|
|
1571
|
+
${params.systemOverride}` : context.spec.instructions;
|
|
1572
|
+
const events = client.session.subscribe({
|
|
1573
|
+
id: metadata.sessionId
|
|
1574
|
+
});
|
|
1575
|
+
await client.session.prompt({
|
|
1576
|
+
id: metadata.sessionId,
|
|
1577
|
+
body: {
|
|
1578
|
+
content: params.prompt,
|
|
1579
|
+
system: systemPrompt
|
|
1580
|
+
}
|
|
1581
|
+
});
|
|
1582
|
+
let fullText = "";
|
|
1583
|
+
const allToolCalls = [];
|
|
1584
|
+
const toolHandlers = createToolHandlerMap(context.tools);
|
|
1585
|
+
let stepIndex = 0;
|
|
1586
|
+
for await (const event of events) {
|
|
1587
|
+
if (event.type === "message.delta") {
|
|
1588
|
+
const text = event.delta?.content ?? "";
|
|
1589
|
+
fullText += text;
|
|
1590
|
+
yield { type: "text", text };
|
|
1591
|
+
}
|
|
1592
|
+
if (event.type === "tool.call") {
|
|
1593
|
+
const toolCall = {
|
|
1594
|
+
id: event.tool_call_id ?? `tc-${Date.now()}`,
|
|
1595
|
+
name: event.tool_name ?? "",
|
|
1596
|
+
arguments: event.arguments ?? {}
|
|
1597
|
+
};
|
|
1598
|
+
allToolCalls.push(toolCall);
|
|
1599
|
+
yield {
|
|
1600
|
+
type: "tool-call",
|
|
1601
|
+
toolCall: {
|
|
1602
|
+
type: "tool-call",
|
|
1603
|
+
toolCallId: toolCall.id,
|
|
1604
|
+
toolName: toolCall.name,
|
|
1605
|
+
args: toolCall.arguments
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
if (event.type === "step.complete") {
|
|
1610
|
+
stepIndex++;
|
|
1611
|
+
yield { type: "step-complete", stepIndex };
|
|
1612
|
+
}
|
|
1613
|
+
if (event.type === "message.complete") {
|
|
1614
|
+
break;
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
for (const toolCall of allToolCalls) {
|
|
1618
|
+
const result = await executeToolCall(toolCall, toolHandlers);
|
|
1619
|
+
yield {
|
|
1620
|
+
type: "tool-result",
|
|
1621
|
+
toolResult: {
|
|
1622
|
+
type: "tool-result",
|
|
1623
|
+
toolCallId: result.tool_call_id,
|
|
1624
|
+
toolName: toolCall.name,
|
|
1625
|
+
output: result.output
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
yield {
|
|
1630
|
+
type: "done",
|
|
1631
|
+
result: {
|
|
1632
|
+
text: fullText,
|
|
1633
|
+
toolCalls: allToolCalls.map((tc) => ({
|
|
1634
|
+
type: "tool-call",
|
|
1635
|
+
toolCallId: tc.id,
|
|
1636
|
+
toolName: tc.name,
|
|
1637
|
+
args: tc.arguments
|
|
1638
|
+
})),
|
|
1639
|
+
toolResults: [],
|
|
1640
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
1641
|
+
finishReason: "stop"
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
} catch (error) {
|
|
1645
|
+
throw new ProviderExecutionError(this.name, `Stream failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
async loadSDK() {
|
|
1649
|
+
try {
|
|
1650
|
+
const module = __require("@opencode-ai/sdk");
|
|
1651
|
+
return module;
|
|
1652
|
+
} catch {
|
|
1653
|
+
throw new ProviderNotAvailableError(this.name, "@opencode-ai/sdk is not installed");
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
getHostname() {
|
|
1657
|
+
if (!this.config.serverUrl) {
|
|
1658
|
+
return "127.0.0.1";
|
|
1659
|
+
}
|
|
1660
|
+
try {
|
|
1661
|
+
const url = new URL(this.config.serverUrl);
|
|
1662
|
+
return url.hostname;
|
|
1663
|
+
} catch {
|
|
1664
|
+
return "127.0.0.1";
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
extractToolCalls(response) {
|
|
1668
|
+
if (!response.tool_calls) {
|
|
1669
|
+
return [];
|
|
1670
|
+
}
|
|
1671
|
+
return response.tool_calls.map((tc) => ({
|
|
1672
|
+
id: tc.id,
|
|
1673
|
+
name: tc.name,
|
|
1674
|
+
arguments: tc.arguments ?? {}
|
|
1675
|
+
}));
|
|
1676
|
+
}
|
|
1677
|
+
extractTextContent(response) {
|
|
1678
|
+
return response.content ?? response.message?.content ?? "";
|
|
1679
|
+
}
|
|
1680
|
+
mapFinishReason(finishReason) {
|
|
1681
|
+
switch (finishReason) {
|
|
1682
|
+
case "stop":
|
|
1683
|
+
case "end":
|
|
1684
|
+
return "stop";
|
|
1685
|
+
case "tool_use":
|
|
1686
|
+
case "tool_calls":
|
|
1687
|
+
return "tool-calls";
|
|
1688
|
+
case "length":
|
|
1689
|
+
case "max_tokens":
|
|
1690
|
+
return "length";
|
|
1691
|
+
default:
|
|
1692
|
+
return "stop";
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
var init_adapter3 = __esm(() => {
|
|
1697
|
+
init_types();
|
|
1698
|
+
init_agent_bridge();
|
|
1699
|
+
});
|
|
1700
|
+
|
|
1701
|
+
// src/providers/opencode-sdk/index.ts
|
|
1702
|
+
var exports_opencode_sdk = {};
|
|
1703
|
+
__export(exports_opencode_sdk, {
|
|
1704
|
+
specToolsToOpenCodeTools: () => specToolsToOpenCodeTools,
|
|
1705
|
+
specToolToOpenCodeTool: () => specToolToOpenCodeTool,
|
|
1706
|
+
specToolToExternalToolForOpenCode: () => specToolToExternalToolForOpenCode,
|
|
1707
|
+
specToOpenCodeMarkdown: () => specToOpenCodeMarkdown,
|
|
1708
|
+
specToOpenCodeConfig: () => specToOpenCodeConfig,
|
|
1709
|
+
serializeOpenCodeMarkdown: () => serializeOpenCodeMarkdown,
|
|
1710
|
+
openCodeToolsToSpecTools: () => openCodeToolsToSpecTools,
|
|
1711
|
+
openCodeToolToSpecTool: () => openCodeToolToSpecTool,
|
|
1712
|
+
openCodeConfigToSpec: () => openCodeConfigToSpec,
|
|
1713
|
+
inferAgentType: () => inferAgentType,
|
|
1714
|
+
executeToolCall: () => executeToolCall,
|
|
1715
|
+
createToolHandlerMap: () => createToolHandlerMap,
|
|
1716
|
+
OpenCodeSDKProvider: () => OpenCodeSDKProvider
|
|
1717
|
+
});
|
|
1718
|
+
var init_opencode_sdk = __esm(() => {
|
|
1719
|
+
init_adapter3();
|
|
1720
|
+
init_agent_bridge();
|
|
1721
|
+
});
|
|
1722
|
+
|
|
1723
|
+
// src/agent/json-runner.ts
|
|
1724
|
+
init_contract_spec_agent();
|
|
1725
|
+
import { createProvider } from "@contractspec/lib.ai-providers/factory";
|
|
1726
|
+
import { StabilityEnum } from "@contractspec/lib.contracts/ownership";
|
|
1727
|
+
var JSON_ONLY_RULES = [
|
|
1728
|
+
"You MUST output valid JSON ONLY.",
|
|
1729
|
+
"Do not wrap the output in markdown fences.",
|
|
1730
|
+
"Do not include commentary or explanation.",
|
|
1731
|
+
"Use double quotes for all keys and string values.",
|
|
1732
|
+
"Do not include trailing commas."
|
|
1733
|
+
].join(`
|
|
1734
|
+
`);
|
|
1735
|
+
var DEFAULT_SPEC = {
|
|
1736
|
+
meta: {
|
|
1737
|
+
key: "agent.json-runner",
|
|
1738
|
+
version: "1.0.0",
|
|
1739
|
+
description: "JSON-only agent runner for deterministic pipelines.",
|
|
1740
|
+
stability: StabilityEnum.Experimental,
|
|
1741
|
+
owners: ["platform.core"],
|
|
1742
|
+
tags: ["json", "agent"]
|
|
1743
|
+
},
|
|
1744
|
+
instructions: "You are a precise JSON generator.",
|
|
1745
|
+
tools: []
|
|
1746
|
+
};
|
|
1747
|
+
function resolveModel(options) {
|
|
1748
|
+
if (options.model)
|
|
1749
|
+
return options.model;
|
|
1750
|
+
if (options.provider) {
|
|
1751
|
+
return createProvider(options.provider).getModel();
|
|
1752
|
+
}
|
|
1753
|
+
throw new Error("createAgentJsonRunner requires a model or provider config");
|
|
1754
|
+
}
|
|
1755
|
+
function applyModelSettings(model, settings) {
|
|
1756
|
+
const { temperature } = settings;
|
|
1757
|
+
if (temperature === undefined)
|
|
1758
|
+
return model;
|
|
1759
|
+
const withSettings = model;
|
|
1760
|
+
if (typeof withSettings.withSettings === "function") {
|
|
1761
|
+
return withSettings.withSettings({ temperature });
|
|
1762
|
+
}
|
|
1763
|
+
return model;
|
|
1764
|
+
}
|
|
1765
|
+
function buildInstructions(base, system) {
|
|
1766
|
+
return [base, JSON_ONLY_RULES, system].filter(Boolean).join(`
|
|
1767
|
+
|
|
1768
|
+
`);
|
|
1769
|
+
}
|
|
1770
|
+
function ensureToolHandlers(spec, handlers) {
|
|
1771
|
+
for (const tool3 of spec.tools) {
|
|
1772
|
+
if (!handlers.has(tool3.name)) {
|
|
1773
|
+
throw new Error(`Missing handler for tool: ${tool3.name}`);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
async function createAgentJsonRunner(options) {
|
|
1778
|
+
const model = applyModelSettings(resolveModel(options), {
|
|
1779
|
+
temperature: options.temperature ?? 0
|
|
1780
|
+
});
|
|
1781
|
+
const baseSpec = options.spec ?? DEFAULT_SPEC;
|
|
1782
|
+
const spec = {
|
|
1783
|
+
...baseSpec,
|
|
1784
|
+
instructions: buildInstructions(baseSpec.instructions, options.system),
|
|
1785
|
+
maxSteps: options.maxSteps ?? baseSpec.maxSteps
|
|
1786
|
+
};
|
|
1787
|
+
const toolHandlers = options.toolHandlers ?? new Map;
|
|
1788
|
+
ensureToolHandlers(spec, toolHandlers);
|
|
1789
|
+
const agent = await ContractSpecAgent.create({
|
|
1790
|
+
spec,
|
|
1791
|
+
model,
|
|
1792
|
+
toolHandlers
|
|
1793
|
+
});
|
|
1794
|
+
return {
|
|
1795
|
+
async generateJson(prompt) {
|
|
1796
|
+
const result = await agent.generate({ prompt });
|
|
1797
|
+
return result.text;
|
|
1798
|
+
}
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// src/agent/unified-agent.ts
|
|
1803
|
+
import { createProvider as createProvider2 } from "@contractspec/lib.ai-providers/factory";
|
|
1804
|
+
|
|
1805
|
+
class UnifiedAgent {
|
|
1806
|
+
spec;
|
|
1807
|
+
config;
|
|
1808
|
+
tools;
|
|
1809
|
+
provider;
|
|
1810
|
+
context;
|
|
1811
|
+
state;
|
|
1812
|
+
constructor(spec, config) {
|
|
1813
|
+
this.spec = spec;
|
|
1814
|
+
this.config = config;
|
|
1815
|
+
this.tools = config.tools ?? new Map;
|
|
1816
|
+
this.state = {
|
|
1817
|
+
backend: config.backend,
|
|
1818
|
+
isReady: false,
|
|
1819
|
+
messageCount: 0
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
async initialize() {
|
|
1823
|
+
const backend = this.config.backend;
|
|
1824
|
+
try {
|
|
1825
|
+
switch (backend) {
|
|
1826
|
+
case "ai-sdk":
|
|
1827
|
+
this.state.isReady = true;
|
|
1828
|
+
break;
|
|
1829
|
+
case "claude-agent-sdk":
|
|
1830
|
+
await this.initializeClaudeAgentSDK();
|
|
1831
|
+
break;
|
|
1832
|
+
case "opencode-sdk":
|
|
1833
|
+
await this.initializeOpenCodeSDK();
|
|
1834
|
+
break;
|
|
1835
|
+
default:
|
|
1836
|
+
throw new Error(`Unknown backend: ${backend}`);
|
|
1837
|
+
}
|
|
1838
|
+
} catch (error) {
|
|
1839
|
+
this.state.lastError = error instanceof Error ? error : new Error(String(error));
|
|
1840
|
+
if (this.config.fallbackBackend && this.config.fallbackBackend !== backend) {
|
|
1841
|
+
console.warn(`[UnifiedAgent] ${backend} failed, falling back to ${this.config.fallbackBackend}`);
|
|
1842
|
+
this.state.backend = this.config.fallbackBackend;
|
|
1843
|
+
await this.initialize();
|
|
1844
|
+
} else {
|
|
1845
|
+
throw error;
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
async initializeClaudeAgentSDK() {
|
|
1850
|
+
try {
|
|
1851
|
+
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
1852
|
+
const config = this.config.config;
|
|
1853
|
+
this.provider = new ClaudeAgentSDKProvider2(config ?? {});
|
|
1854
|
+
if (!this.provider.isAvailable()) {
|
|
1855
|
+
throw new Error("Claude Agent SDK not available. Install @anthropic-ai/claude-agent-sdk");
|
|
1856
|
+
}
|
|
1857
|
+
this.context = await this.provider.createContext(this.spec);
|
|
1858
|
+
this.state.isReady = true;
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
if (error.code === "MODULE_NOT_FOUND") {
|
|
1861
|
+
throw new Error("Claude Agent SDK not installed. Run: npm install @anthropic-ai/claude-agent-sdk");
|
|
1862
|
+
}
|
|
1863
|
+
throw error;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
async initializeOpenCodeSDK() {
|
|
1867
|
+
try {
|
|
1868
|
+
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
1869
|
+
const config = this.config.config;
|
|
1870
|
+
this.provider = new OpenCodeSDKProvider2(config ?? {});
|
|
1871
|
+
if (!this.provider.isAvailable()) {
|
|
1872
|
+
throw new Error("OpenCode SDK not available. Install @opencode-ai/sdk");
|
|
1873
|
+
}
|
|
1874
|
+
this.context = await this.provider.createContext(this.spec);
|
|
1875
|
+
this.state.isReady = true;
|
|
1876
|
+
} catch (error) {
|
|
1877
|
+
if (error.code === "MODULE_NOT_FOUND") {
|
|
1878
|
+
throw new Error("OpenCode SDK not installed. Run: npm install @opencode-ai/sdk");
|
|
1879
|
+
}
|
|
1880
|
+
throw error;
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
async run(message, options) {
|
|
1884
|
+
if (!this.state.isReady) {
|
|
1885
|
+
await this.initialize();
|
|
1886
|
+
}
|
|
1887
|
+
const backend = options?.backend ?? this.state.backend;
|
|
1888
|
+
this.state.messageCount++;
|
|
1889
|
+
try {
|
|
1890
|
+
switch (backend) {
|
|
1891
|
+
case "ai-sdk":
|
|
1892
|
+
return await this.runWithAISDK(message, options);
|
|
1893
|
+
case "claude-agent-sdk":
|
|
1894
|
+
case "opencode-sdk":
|
|
1895
|
+
return await this.runWithExternalProvider(message, options);
|
|
1896
|
+
default:
|
|
1897
|
+
throw new Error(`Unknown backend: ${backend}`);
|
|
1898
|
+
}
|
|
1899
|
+
} catch (error) {
|
|
1900
|
+
this.state.lastError = error instanceof Error ? error : new Error(String(error));
|
|
1901
|
+
throw error;
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
async runWithAISDK(message, options) {
|
|
1905
|
+
const { ContractSpecAgent: ContractSpecAgent2 } = await Promise.resolve().then(() => (init_contract_spec_agent(), exports_contract_spec_agent));
|
|
1906
|
+
const model = await this.resolveAISDKModel();
|
|
1907
|
+
const agent = await ContractSpecAgent2.create({
|
|
1908
|
+
spec: this.spec,
|
|
1909
|
+
model,
|
|
1910
|
+
toolHandlers: this.tools
|
|
1911
|
+
});
|
|
1912
|
+
return await agent.generate({
|
|
1913
|
+
prompt: message,
|
|
1914
|
+
options
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
async runWithExternalProvider(message, options) {
|
|
1918
|
+
if (!this.provider || !this.context) {
|
|
1919
|
+
throw new Error("Provider not initialized");
|
|
1920
|
+
}
|
|
1921
|
+
const result = await this.provider.execute(this.context, {
|
|
1922
|
+
prompt: message,
|
|
1923
|
+
options
|
|
1924
|
+
});
|
|
1925
|
+
return this.convertExternalResult(result);
|
|
1926
|
+
}
|
|
1927
|
+
convertExternalResult(result) {
|
|
1928
|
+
return {
|
|
1929
|
+
text: result.text,
|
|
1930
|
+
steps: [],
|
|
1931
|
+
toolCalls: result.toolCalls.map((tc) => ({
|
|
1932
|
+
type: "tool-call",
|
|
1933
|
+
toolCallId: tc.toolCallId,
|
|
1934
|
+
toolName: tc.toolName,
|
|
1935
|
+
args: tc.args
|
|
1936
|
+
})),
|
|
1937
|
+
toolResults: result.toolResults.map((tr) => ({
|
|
1938
|
+
type: "tool-result",
|
|
1939
|
+
toolCallId: tr.toolCallId,
|
|
1940
|
+
toolName: tr.toolName,
|
|
1941
|
+
output: tr.output
|
|
1942
|
+
})),
|
|
1943
|
+
finishReason: result.finishReason,
|
|
1944
|
+
usage: result.usage ? {
|
|
1945
|
+
promptTokens: result.usage.inputTokens,
|
|
1946
|
+
completionTokens: result.usage.outputTokens,
|
|
1947
|
+
totalTokens: result.usage.totalTokens ?? result.usage.inputTokens + result.usage.outputTokens
|
|
1948
|
+
} : undefined
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
getAISDKConfig() {
|
|
1952
|
+
if (this.config.backend !== "ai-sdk")
|
|
1953
|
+
return;
|
|
1954
|
+
return this.config.config;
|
|
1955
|
+
}
|
|
1956
|
+
async resolveAISDKModel() {
|
|
1957
|
+
const backendConfig = this.getAISDKConfig();
|
|
1958
|
+
let model;
|
|
1959
|
+
if (backendConfig?.modelInstance) {
|
|
1960
|
+
model = backendConfig.modelInstance;
|
|
1961
|
+
} else if (backendConfig?.provider) {
|
|
1962
|
+
model = createProvider2(backendConfig.provider).getModel();
|
|
1963
|
+
} else {
|
|
1964
|
+
const { anthropic } = await import("@ai-sdk/anthropic");
|
|
1965
|
+
model = anthropic(backendConfig?.model ?? "claude-3-5-sonnet-20240620");
|
|
1966
|
+
}
|
|
1967
|
+
return this.applyModelSettings(model, {
|
|
1968
|
+
temperature: backendConfig?.temperature,
|
|
1969
|
+
maxTokens: backendConfig?.maxTokens
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
applyModelSettings(model, settings) {
|
|
1973
|
+
if (settings.temperature === undefined && settings.maxTokens === undefined) {
|
|
1974
|
+
return model;
|
|
1975
|
+
}
|
|
1976
|
+
const withSettings = model;
|
|
1977
|
+
if (typeof withSettings.withSettings === "function") {
|
|
1978
|
+
return withSettings.withSettings({
|
|
1979
|
+
temperature: settings.temperature,
|
|
1980
|
+
maxTokens: settings.maxTokens
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
return model;
|
|
1984
|
+
}
|
|
1985
|
+
getState() {
|
|
1986
|
+
return { ...this.state };
|
|
1987
|
+
}
|
|
1988
|
+
getSpec() {
|
|
1989
|
+
return this.spec;
|
|
1990
|
+
}
|
|
1991
|
+
getBackend() {
|
|
1992
|
+
return this.state.backend;
|
|
1993
|
+
}
|
|
1994
|
+
async isBackendAvailable(backend) {
|
|
1995
|
+
switch (backend) {
|
|
1996
|
+
case "ai-sdk":
|
|
1997
|
+
return true;
|
|
1998
|
+
case "claude-agent-sdk":
|
|
1999
|
+
try {
|
|
2000
|
+
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
2001
|
+
const provider = new ClaudeAgentSDKProvider2({});
|
|
2002
|
+
return provider.isAvailable();
|
|
2003
|
+
} catch {
|
|
2004
|
+
return false;
|
|
2005
|
+
}
|
|
2006
|
+
case "opencode-sdk":
|
|
2007
|
+
try {
|
|
2008
|
+
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
2009
|
+
const provider = new OpenCodeSDKProvider2({});
|
|
2010
|
+
return provider.isAvailable();
|
|
2011
|
+
} catch {
|
|
2012
|
+
return false;
|
|
2013
|
+
}
|
|
2014
|
+
default:
|
|
2015
|
+
return false;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
async switchBackend(backend) {
|
|
2019
|
+
if (backend === this.state.backend) {
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
this.state.backend = backend;
|
|
2023
|
+
this.state.isReady = false;
|
|
2024
|
+
this.provider = undefined;
|
|
2025
|
+
this.context = undefined;
|
|
2026
|
+
await this.initialize();
|
|
2027
|
+
}
|
|
2028
|
+
reset() {
|
|
2029
|
+
this.state.messageCount = 0;
|
|
2030
|
+
this.state.sessionId = undefined;
|
|
2031
|
+
this.state.lastError = undefined;
|
|
2032
|
+
this.context = undefined;
|
|
2033
|
+
}
|
|
2034
|
+
addTool(name, handler) {
|
|
2035
|
+
this.tools.set(name, handler);
|
|
2036
|
+
}
|
|
2037
|
+
removeTool(name) {
|
|
2038
|
+
return this.tools.delete(name);
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
function createUnifiedAgent(spec, config) {
|
|
2042
|
+
return new UnifiedAgent(spec, config);
|
|
2043
|
+
}
|
|
2044
|
+
function createAISDKAgent(spec, options) {
|
|
2045
|
+
return new UnifiedAgent(spec, {
|
|
2046
|
+
backend: "ai-sdk",
|
|
2047
|
+
tools: options?.tools,
|
|
2048
|
+
config: {
|
|
2049
|
+
model: options?.model,
|
|
2050
|
+
modelInstance: options?.modelInstance,
|
|
2051
|
+
provider: options?.provider,
|
|
2052
|
+
temperature: options?.temperature,
|
|
2053
|
+
maxTokens: options?.maxTokens
|
|
2054
|
+
}
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
function createClaudeAgentSDKAgent(spec, config) {
|
|
2058
|
+
const { tools, ...sdkConfig } = config ?? {};
|
|
2059
|
+
return new UnifiedAgent(spec, {
|
|
2060
|
+
backend: "claude-agent-sdk",
|
|
2061
|
+
tools,
|
|
2062
|
+
config: sdkConfig
|
|
2063
|
+
});
|
|
2064
|
+
}
|
|
2065
|
+
function createOpenCodeSDKAgent(spec, config) {
|
|
2066
|
+
const { tools, ...sdkConfig } = config ?? {};
|
|
2067
|
+
return new UnifiedAgent(spec, {
|
|
2068
|
+
backend: "opencode-sdk",
|
|
2069
|
+
tools,
|
|
2070
|
+
config: sdkConfig
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
async function getAvailableBackends() {
|
|
2074
|
+
const backends = ["ai-sdk"];
|
|
2075
|
+
try {
|
|
2076
|
+
const { ClaudeAgentSDKProvider: ClaudeAgentSDKProvider2 } = await Promise.resolve().then(() => (init_claude_agent_sdk(), exports_claude_agent_sdk));
|
|
2077
|
+
const provider = new ClaudeAgentSDKProvider2({});
|
|
2078
|
+
if (provider.isAvailable()) {
|
|
2079
|
+
backends.push("claude-agent-sdk");
|
|
2080
|
+
}
|
|
2081
|
+
} catch {}
|
|
2082
|
+
try {
|
|
2083
|
+
const { OpenCodeSDKProvider: OpenCodeSDKProvider2 } = await Promise.resolve().then(() => (init_opencode_sdk(), exports_opencode_sdk));
|
|
2084
|
+
const provider = new OpenCodeSDKProvider2({});
|
|
2085
|
+
if (provider.isAvailable()) {
|
|
2086
|
+
backends.push("opencode-sdk");
|
|
2087
|
+
}
|
|
2088
|
+
} catch {}
|
|
2089
|
+
return backends;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
// src/agent/index.ts
|
|
2093
|
+
init_contract_spec_agent();
|
|
2094
|
+
|
|
2095
|
+
// src/approval/workflow.ts
|
|
2096
|
+
import { randomUUID } from "node:crypto";
|
|
2097
|
+
|
|
2098
|
+
class InMemoryApprovalStore {
|
|
2099
|
+
items = new Map;
|
|
2100
|
+
async create(request) {
|
|
2101
|
+
this.items.set(request.id, request);
|
|
2102
|
+
}
|
|
2103
|
+
async get(id) {
|
|
2104
|
+
return this.items.get(id) ?? null;
|
|
2105
|
+
}
|
|
2106
|
+
async getByToolCallId(toolCallId) {
|
|
2107
|
+
for (const request of this.items.values()) {
|
|
2108
|
+
if (request.toolCallId === toolCallId) {
|
|
2109
|
+
return request;
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
return null;
|
|
2113
|
+
}
|
|
2114
|
+
async update(id, updates) {
|
|
2115
|
+
const existing = this.items.get(id);
|
|
2116
|
+
if (existing) {
|
|
2117
|
+
this.items.set(id, { ...existing, ...updates });
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
async list(options) {
|
|
2121
|
+
let results = [...this.items.values()];
|
|
2122
|
+
if (options?.status) {
|
|
2123
|
+
results = results.filter((r) => r.status === options.status);
|
|
2124
|
+
}
|
|
2125
|
+
if (options?.agentId) {
|
|
2126
|
+
results = results.filter((r) => r.agentId === options.agentId);
|
|
2127
|
+
}
|
|
2128
|
+
if (options?.tenantId) {
|
|
2129
|
+
results = results.filter((r) => r.tenantId === options.tenantId);
|
|
2130
|
+
}
|
|
2131
|
+
return results.sort((a, b) => b.requestedAt.getTime() - a.requestedAt.getTime());
|
|
2132
|
+
}
|
|
2133
|
+
clear() {
|
|
2134
|
+
this.items.clear();
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
class ApprovalWorkflow {
|
|
2139
|
+
store;
|
|
2140
|
+
constructor(store = new InMemoryApprovalStore) {
|
|
2141
|
+
this.store = store;
|
|
2142
|
+
}
|
|
2143
|
+
async requestApproval(params) {
|
|
2144
|
+
const request = {
|
|
2145
|
+
id: randomUUID(),
|
|
2146
|
+
sessionId: params.sessionId,
|
|
2147
|
+
agentId: params.agentId,
|
|
2148
|
+
tenantId: params.tenantId,
|
|
2149
|
+
toolName: params.toolName,
|
|
2150
|
+
toolCallId: params.toolCallId,
|
|
2151
|
+
toolArgs: params.toolArgs,
|
|
2152
|
+
reason: params.reason,
|
|
2153
|
+
requestedAt: new Date,
|
|
2154
|
+
status: "pending",
|
|
2155
|
+
payload: params.payload
|
|
2156
|
+
};
|
|
2157
|
+
await this.store.create(request);
|
|
2158
|
+
return request;
|
|
2159
|
+
}
|
|
2160
|
+
async requestApprovalFromToolCall(toolCall, context) {
|
|
2161
|
+
return this.requestApproval({
|
|
2162
|
+
sessionId: context.sessionId,
|
|
2163
|
+
agentId: context.agentId,
|
|
2164
|
+
tenantId: context.tenantId,
|
|
2165
|
+
toolName: toolCall.toolName,
|
|
2166
|
+
toolCallId: toolCall.toolCallId,
|
|
2167
|
+
toolArgs: toolCall.args,
|
|
2168
|
+
reason: context.reason ?? `Tool "${toolCall.toolName}" requires approval`
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
async approve(id, reviewer, notes) {
|
|
2172
|
+
await this.store.update(id, {
|
|
2173
|
+
status: "approved",
|
|
2174
|
+
reviewer,
|
|
2175
|
+
resolvedAt: new Date,
|
|
2176
|
+
notes
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
async reject(id, reviewer, notes) {
|
|
2180
|
+
await this.store.update(id, {
|
|
2181
|
+
status: "rejected",
|
|
2182
|
+
reviewer,
|
|
2183
|
+
resolvedAt: new Date,
|
|
2184
|
+
notes
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
async getStatus(toolCallId) {
|
|
2188
|
+
const request = await this.store.getByToolCallId(toolCallId);
|
|
2189
|
+
return request?.status ?? null;
|
|
2190
|
+
}
|
|
2191
|
+
async isApproved(toolCallId) {
|
|
2192
|
+
const status = await this.getStatus(toolCallId);
|
|
2193
|
+
return status === "approved";
|
|
2194
|
+
}
|
|
2195
|
+
async listPending(options) {
|
|
2196
|
+
return this.store.list({ ...options, status: "pending" });
|
|
2197
|
+
}
|
|
2198
|
+
async get(id) {
|
|
2199
|
+
return this.store.get(id);
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
function createApprovalWorkflow(store) {
|
|
2203
|
+
return new ApprovalWorkflow(store);
|
|
2204
|
+
}
|
|
2205
|
+
// src/exporters/claude-agent-exporter.ts
|
|
2206
|
+
class ClaudeAgentExporter {
|
|
2207
|
+
format = "claude-agent";
|
|
2208
|
+
export(spec, options = {}) {
|
|
2209
|
+
const tools = this.exportTools(spec);
|
|
2210
|
+
const config = this.buildConfig(spec, tools, options);
|
|
2211
|
+
const claudeMd = options.generateClaudeMd ? this.generateClaudeMd(spec, options) : undefined;
|
|
2212
|
+
return {
|
|
2213
|
+
config,
|
|
2214
|
+
claudeMd,
|
|
2215
|
+
tools,
|
|
2216
|
+
exportedAt: new Date,
|
|
2217
|
+
sourceSpec: agentKey(spec.meta)
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
exportMany(specs, options = {}) {
|
|
2221
|
+
return specs.map((spec) => this.export(spec, options));
|
|
2222
|
+
}
|
|
2223
|
+
validate(spec) {
|
|
2224
|
+
const errors = [];
|
|
2225
|
+
if (!spec.meta?.key) {
|
|
2226
|
+
errors.push("Spec must have a meta.key");
|
|
2227
|
+
}
|
|
2228
|
+
if (!spec.instructions) {
|
|
2229
|
+
errors.push("Spec must have instructions");
|
|
2230
|
+
}
|
|
2231
|
+
if (!spec.tools || spec.tools.length === 0) {
|
|
2232
|
+
errors.push("Spec must have at least one tool");
|
|
2233
|
+
}
|
|
2234
|
+
for (const tool3 of spec.tools ?? []) {
|
|
2235
|
+
if (!tool3.name) {
|
|
2236
|
+
errors.push("All tools must have a name");
|
|
2237
|
+
}
|
|
2238
|
+
if (!tool3.description && !tool3.name) {
|
|
2239
|
+
errors.push(`Tool must have a description or name`);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
return { valid: errors.length === 0, errors };
|
|
2243
|
+
}
|
|
2244
|
+
buildConfig(spec, tools, options) {
|
|
2245
|
+
const config = {
|
|
2246
|
+
model: options.model ?? "claude-sonnet-4-20250514",
|
|
2247
|
+
system: this.buildSystemPrompt(spec, options),
|
|
2248
|
+
tools,
|
|
2249
|
+
max_turns: spec.maxSteps ?? 10
|
|
2250
|
+
};
|
|
2251
|
+
if (options.computerUse) {
|
|
2252
|
+
config.computer_use = true;
|
|
2253
|
+
}
|
|
2254
|
+
if (options.extendedThinking) {
|
|
2255
|
+
config.extended_thinking = true;
|
|
2256
|
+
}
|
|
2257
|
+
if (options.mcpServers && options.mcpServers.length > 0) {
|
|
2258
|
+
config.mcp_servers = options.mcpServers;
|
|
2259
|
+
}
|
|
2260
|
+
return config;
|
|
2261
|
+
}
|
|
2262
|
+
buildSystemPrompt(spec, options) {
|
|
2263
|
+
const parts = [];
|
|
2264
|
+
parts.push(spec.instructions);
|
|
2265
|
+
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
2266
|
+
parts.push("");
|
|
2267
|
+
parts.push("## Knowledge Sources");
|
|
2268
|
+
for (const k of spec.knowledge) {
|
|
2269
|
+
if (k.instructions) {
|
|
2270
|
+
parts.push(`- ${k.key}: ${k.instructions}`);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
if (spec.policy) {
|
|
2275
|
+
parts.push("");
|
|
2276
|
+
parts.push("## Policy");
|
|
2277
|
+
if (spec.policy.confidence?.min) {
|
|
2278
|
+
parts.push(`- Minimum confidence: ${spec.policy.confidence.min}`);
|
|
2279
|
+
}
|
|
2280
|
+
if (spec.policy.escalation) {
|
|
2281
|
+
parts.push("- Escalation policy is configured");
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
if (options.metadata) {
|
|
2285
|
+
parts.push("");
|
|
2286
|
+
parts.push("## Additional Context");
|
|
2287
|
+
for (const [key, value] of Object.entries(options.metadata)) {
|
|
2288
|
+
parts.push(`- ${key}: ${String(value)}`);
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
return parts.join(`
|
|
2292
|
+
`);
|
|
2293
|
+
}
|
|
2294
|
+
exportTools(spec) {
|
|
2295
|
+
return spec.tools.map((tool3) => ({
|
|
2296
|
+
name: tool3.name,
|
|
2297
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
2298
|
+
input_schema: this.normalizeSchema(tool3.schema),
|
|
2299
|
+
requires_confirmation: tool3.requiresApproval ?? !tool3.automationSafe
|
|
2300
|
+
}));
|
|
2301
|
+
}
|
|
2302
|
+
normalizeSchema(schema) {
|
|
2303
|
+
if (!schema) {
|
|
2304
|
+
return { type: "object" };
|
|
2305
|
+
}
|
|
2306
|
+
if (schema.type === "object") {
|
|
2307
|
+
return {
|
|
2308
|
+
type: "object",
|
|
2309
|
+
properties: schema.properties,
|
|
2310
|
+
required: schema.required
|
|
2311
|
+
};
|
|
2312
|
+
}
|
|
2313
|
+
return {
|
|
2314
|
+
type: "object",
|
|
2315
|
+
properties: { value: schema },
|
|
2316
|
+
required: ["value"]
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
generateClaudeMd(spec, options) {
|
|
2320
|
+
const lines = [];
|
|
2321
|
+
lines.push("# Agent Configuration");
|
|
2322
|
+
lines.push("");
|
|
2323
|
+
if (spec.description) {
|
|
2324
|
+
lines.push(`> ${spec.description}`);
|
|
2325
|
+
lines.push("");
|
|
2326
|
+
}
|
|
2327
|
+
lines.push("## Metadata");
|
|
2328
|
+
lines.push("");
|
|
2329
|
+
lines.push(`- **Name**: ${spec.meta.key}`);
|
|
2330
|
+
lines.push(`- **Version**: ${spec.meta.version}`);
|
|
2331
|
+
if (spec.meta.owners && spec.meta.owners.length > 0) {
|
|
2332
|
+
lines.push(`- **Owners**: ${spec.meta.owners.join(", ")}`);
|
|
2333
|
+
}
|
|
2334
|
+
if (options.model) {
|
|
2335
|
+
lines.push(`- **Model**: ${options.model}`);
|
|
2336
|
+
}
|
|
2337
|
+
lines.push("");
|
|
2338
|
+
lines.push("## Instructions");
|
|
2339
|
+
lines.push("");
|
|
2340
|
+
lines.push(spec.instructions);
|
|
2341
|
+
lines.push("");
|
|
2342
|
+
if (spec.tools.length > 0) {
|
|
2343
|
+
lines.push("## Available Tools");
|
|
2344
|
+
lines.push("");
|
|
2345
|
+
for (const tool3 of spec.tools) {
|
|
2346
|
+
const flags = [];
|
|
2347
|
+
if (tool3.requiresApproval) {
|
|
2348
|
+
flags.push("requires approval");
|
|
2349
|
+
}
|
|
2350
|
+
if (tool3.automationSafe === false) {
|
|
2351
|
+
flags.push("not automation safe");
|
|
2352
|
+
}
|
|
2353
|
+
const flagStr = flags.length > 0 ? ` (${flags.join(", ")})` : "";
|
|
2354
|
+
lines.push(`### ${tool3.name}${flagStr}`);
|
|
2355
|
+
lines.push("");
|
|
2356
|
+
if (tool3.description) {
|
|
2357
|
+
lines.push(tool3.description);
|
|
2358
|
+
lines.push("");
|
|
2359
|
+
}
|
|
2360
|
+
if (tool3.schema) {
|
|
2361
|
+
lines.push("**Parameters:**");
|
|
2362
|
+
lines.push("```json");
|
|
2363
|
+
lines.push(JSON.stringify(tool3.schema, null, 2));
|
|
2364
|
+
lines.push("```");
|
|
2365
|
+
lines.push("");
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
2370
|
+
lines.push("## Knowledge Sources");
|
|
2371
|
+
lines.push("");
|
|
2372
|
+
for (const k of spec.knowledge) {
|
|
2373
|
+
const required = k.required ? "(required)" : "(optional)";
|
|
2374
|
+
lines.push(`- **${k.key}** ${required}`);
|
|
2375
|
+
if (k.instructions) {
|
|
2376
|
+
lines.push(` - ${k.instructions}`);
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
lines.push("");
|
|
2380
|
+
}
|
|
2381
|
+
if (spec.policy) {
|
|
2382
|
+
lines.push("## Policy");
|
|
2383
|
+
lines.push("");
|
|
2384
|
+
if (spec.policy.confidence?.min) {
|
|
2385
|
+
lines.push(`- Minimum confidence: ${spec.policy.confidence.min}`);
|
|
2386
|
+
}
|
|
2387
|
+
if (spec.policy.escalation) {
|
|
2388
|
+
lines.push("- Escalation policy configured");
|
|
2389
|
+
}
|
|
2390
|
+
if (spec.policy.flags && spec.policy.flags.length > 0) {
|
|
2391
|
+
lines.push(`- Feature flags: ${spec.policy.flags.join(", ")}`);
|
|
2392
|
+
}
|
|
2393
|
+
lines.push("");
|
|
2394
|
+
}
|
|
2395
|
+
if (options.mcpServers && options.mcpServers.length > 0) {
|
|
2396
|
+
lines.push("## MCP Servers");
|
|
2397
|
+
lines.push("");
|
|
2398
|
+
for (const server of options.mcpServers) {
|
|
2399
|
+
lines.push(`- **${server.name}**: \`${server.command}${server.args ? " " + server.args.join(" ") : ""}\``);
|
|
2400
|
+
}
|
|
2401
|
+
lines.push("");
|
|
2402
|
+
}
|
|
2403
|
+
lines.push("---");
|
|
2404
|
+
lines.push("");
|
|
2405
|
+
lines.push(`*Generated from ContractSpec: ${agentKey(spec.meta)}*`);
|
|
2406
|
+
return lines.join(`
|
|
2407
|
+
`);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
function exportToClaudeAgent(spec, options) {
|
|
2411
|
+
const exporter = new ClaudeAgentExporter;
|
|
2412
|
+
return exporter.export(spec, options);
|
|
2413
|
+
}
|
|
2414
|
+
function generateClaudeMd(spec, options) {
|
|
2415
|
+
const exporter = new ClaudeAgentExporter;
|
|
2416
|
+
const result = exporter.export(spec, { ...options, generateClaudeMd: true });
|
|
2417
|
+
return result.claudeMd ?? "";
|
|
2418
|
+
}
|
|
2419
|
+
function validateForClaudeAgent(spec) {
|
|
2420
|
+
const exporter = new ClaudeAgentExporter;
|
|
2421
|
+
return exporter.validate(spec);
|
|
2422
|
+
}
|
|
2423
|
+
// src/exporters/opencode-exporter.ts
|
|
2424
|
+
init_agent_bridge();
|
|
2425
|
+
|
|
2426
|
+
class OpenCodeExporter {
|
|
2427
|
+
format = "opencode";
|
|
2428
|
+
export(spec, options = {}) {
|
|
2429
|
+
const jsonConfig = this.buildJsonConfig(spec, options);
|
|
2430
|
+
const markdownConfig = this.generateMarkdown(spec, jsonConfig, options);
|
|
2431
|
+
return {
|
|
2432
|
+
jsonConfig,
|
|
2433
|
+
markdownConfig,
|
|
2434
|
+
exportedAt: new Date,
|
|
2435
|
+
sourceSpec: agentKey(spec.meta)
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
exportMany(specs, options = {}) {
|
|
2439
|
+
return specs.map((spec) => this.export(spec, options));
|
|
2440
|
+
}
|
|
2441
|
+
validate(spec) {
|
|
2442
|
+
const errors = [];
|
|
2443
|
+
if (!spec.meta?.key) {
|
|
2444
|
+
errors.push("Spec must have a meta.key");
|
|
2445
|
+
}
|
|
2446
|
+
if (!spec.instructions) {
|
|
2447
|
+
errors.push("Spec must have instructions");
|
|
2448
|
+
}
|
|
2449
|
+
for (const tool3 of spec.tools ?? []) {
|
|
2450
|
+
if (!tool3.name) {
|
|
2451
|
+
errors.push("All tools must have a name");
|
|
2452
|
+
}
|
|
2453
|
+
if (tool3.name && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tool3.name)) {
|
|
2454
|
+
errors.push(`Tool name '${tool3.name}' should be a valid identifier (letters, numbers, underscores)`);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
return { valid: errors.length === 0, errors };
|
|
2458
|
+
}
|
|
2459
|
+
buildJsonConfig(spec, options) {
|
|
2460
|
+
const agentType = options.agentType ?? inferAgentType(spec);
|
|
2461
|
+
return {
|
|
2462
|
+
name: spec.meta.key,
|
|
2463
|
+
version: spec.meta.version,
|
|
2464
|
+
description: spec.description,
|
|
2465
|
+
type: agentType,
|
|
2466
|
+
instructions: spec.instructions,
|
|
2467
|
+
tools: this.exportTools(spec),
|
|
2468
|
+
config: {
|
|
2469
|
+
max_steps: options.maxSteps ?? spec.maxSteps ?? 10,
|
|
2470
|
+
temperature: options.temperature ?? 0.7,
|
|
2471
|
+
model: options.model
|
|
2472
|
+
}
|
|
2473
|
+
};
|
|
2474
|
+
}
|
|
2475
|
+
exportTools(spec) {
|
|
2476
|
+
return spec.tools.map((tool3) => ({
|
|
2477
|
+
name: tool3.name,
|
|
2478
|
+
description: tool3.description ?? `Execute ${tool3.name}`,
|
|
2479
|
+
schema: tool3.schema ?? { type: "object" },
|
|
2480
|
+
requires_approval: tool3.requiresApproval ?? !tool3.automationSafe
|
|
2481
|
+
}));
|
|
2482
|
+
}
|
|
2483
|
+
generateMarkdown(spec, jsonConfig, options) {
|
|
2484
|
+
const lines = [];
|
|
2485
|
+
lines.push("---");
|
|
2486
|
+
lines.push(`name: ${jsonConfig.name}`);
|
|
2487
|
+
lines.push(`type: ${jsonConfig.type}`);
|
|
2488
|
+
if (jsonConfig.version) {
|
|
2489
|
+
lines.push(`version: ${jsonConfig.version}`);
|
|
2490
|
+
}
|
|
2491
|
+
if (jsonConfig.config.model) {
|
|
2492
|
+
lines.push(`model: ${jsonConfig.config.model}`);
|
|
2493
|
+
}
|
|
2494
|
+
if (jsonConfig.config.temperature !== undefined) {
|
|
2495
|
+
lines.push(`temperature: ${jsonConfig.config.temperature}`);
|
|
2496
|
+
}
|
|
2497
|
+
if (jsonConfig.config.max_steps !== undefined) {
|
|
2498
|
+
lines.push(`max_steps: ${jsonConfig.config.max_steps}`);
|
|
2499
|
+
}
|
|
2500
|
+
if (jsonConfig.tools.length > 0) {
|
|
2501
|
+
lines.push("tools:");
|
|
2502
|
+
for (const tool3 of jsonConfig.tools) {
|
|
2503
|
+
const permission = tool3.requires_approval ? " # requires approval" : "";
|
|
2504
|
+
lines.push(` - ${tool3.name}${permission}`);
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
lines.push("---");
|
|
2508
|
+
lines.push("");
|
|
2509
|
+
lines.push(`# ${spec.meta.key}`);
|
|
2510
|
+
lines.push("");
|
|
2511
|
+
if (spec.description) {
|
|
2512
|
+
lines.push(spec.description);
|
|
2513
|
+
lines.push("");
|
|
2514
|
+
}
|
|
2515
|
+
lines.push(`> Agent type: **${jsonConfig.type}**`);
|
|
2516
|
+
lines.push("");
|
|
2517
|
+
lines.push(this.getAgentTypeDescription(jsonConfig.type));
|
|
2518
|
+
lines.push("");
|
|
2519
|
+
lines.push("## Instructions");
|
|
2520
|
+
lines.push("");
|
|
2521
|
+
lines.push(spec.instructions);
|
|
2522
|
+
lines.push("");
|
|
2523
|
+
if (spec.tools.length > 0) {
|
|
2524
|
+
lines.push("## Tools");
|
|
2525
|
+
lines.push("");
|
|
2526
|
+
for (const tool3 of spec.tools) {
|
|
2527
|
+
const approval = tool3.requiresApproval ? " *(requires approval)*" : "";
|
|
2528
|
+
const safe = tool3.automationSafe === false ? " *(not automation safe)*" : "";
|
|
2529
|
+
lines.push(`### ${tool3.name}${approval}${safe}`);
|
|
2530
|
+
lines.push("");
|
|
2531
|
+
if (tool3.description) {
|
|
2532
|
+
lines.push(tool3.description);
|
|
2533
|
+
lines.push("");
|
|
2534
|
+
}
|
|
2535
|
+
if (tool3.schema && options.includeComments !== false) {
|
|
2536
|
+
lines.push("**Parameters:**");
|
|
2537
|
+
lines.push("");
|
|
2538
|
+
lines.push("```json");
|
|
2539
|
+
lines.push(JSON.stringify(tool3.schema, null, options.prettyPrint !== false ? 2 : 0));
|
|
2540
|
+
lines.push("```");
|
|
2541
|
+
lines.push("");
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
if (spec.knowledge && spec.knowledge.length > 0) {
|
|
2546
|
+
lines.push("## Knowledge Sources");
|
|
2547
|
+
lines.push("");
|
|
2548
|
+
for (const k of spec.knowledge) {
|
|
2549
|
+
const required = k.required ? "(required)" : "(optional)";
|
|
2550
|
+
lines.push(`- **${k.key}** ${required}`);
|
|
2551
|
+
if (k.instructions) {
|
|
2552
|
+
lines.push(` - ${k.instructions}`);
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
lines.push("");
|
|
2556
|
+
}
|
|
2557
|
+
if (spec.policy) {
|
|
2558
|
+
lines.push("## Policy");
|
|
2559
|
+
lines.push("");
|
|
2560
|
+
if (spec.policy.confidence?.min) {
|
|
2561
|
+
lines.push(`- Minimum confidence: ${spec.policy.confidence.min}`);
|
|
2562
|
+
}
|
|
2563
|
+
if (spec.policy.escalation) {
|
|
2564
|
+
lines.push("- Escalation policy configured");
|
|
2565
|
+
}
|
|
2566
|
+
lines.push("");
|
|
2567
|
+
}
|
|
2568
|
+
lines.push("## Configuration");
|
|
2569
|
+
lines.push("");
|
|
2570
|
+
lines.push("```json");
|
|
2571
|
+
lines.push(JSON.stringify(jsonConfig.config, null, options.prettyPrint !== false ? 2 : 0));
|
|
2572
|
+
lines.push("```");
|
|
2573
|
+
lines.push("");
|
|
2574
|
+
lines.push("---");
|
|
2575
|
+
lines.push("");
|
|
2576
|
+
lines.push(`*Generated from ContractSpec: ${agentKey(spec.meta)}*`);
|
|
2577
|
+
lines.push(`*Exported at: ${new Date().toISOString()}*`);
|
|
2578
|
+
return lines.join(`
|
|
2579
|
+
`);
|
|
2580
|
+
}
|
|
2581
|
+
getAgentTypeDescription(type) {
|
|
2582
|
+
switch (type) {
|
|
2583
|
+
case "build":
|
|
2584
|
+
return "Primary agent with full tool access for code generation and modification.";
|
|
2585
|
+
case "plan":
|
|
2586
|
+
return "Restricted agent for analysis and planning. File edits and bash commands require approval.";
|
|
2587
|
+
case "general":
|
|
2588
|
+
return "General-purpose subagent for complex questions and multi-step tasks.";
|
|
2589
|
+
case "explore":
|
|
2590
|
+
return "Fast subagent optimized for codebase exploration and pattern searching.";
|
|
2591
|
+
default:
|
|
2592
|
+
return "";
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
function exportToOpenCode(spec, options) {
|
|
2597
|
+
const exporter = new OpenCodeExporter;
|
|
2598
|
+
return exporter.export(spec, options);
|
|
2599
|
+
}
|
|
2600
|
+
function generateOpenCodeMarkdown(spec, options) {
|
|
2601
|
+
const exporter = new OpenCodeExporter;
|
|
2602
|
+
const result = exporter.export(spec, options);
|
|
2603
|
+
return result.markdownConfig;
|
|
2604
|
+
}
|
|
2605
|
+
function generateOpenCodeJSON(spec, options) {
|
|
2606
|
+
const exporter = new OpenCodeExporter;
|
|
2607
|
+
const result = exporter.export(spec, options);
|
|
2608
|
+
return result.jsonConfig;
|
|
2609
|
+
}
|
|
2610
|
+
function validateForOpenCode(spec) {
|
|
2611
|
+
const exporter = new OpenCodeExporter;
|
|
2612
|
+
return exporter.validate(spec);
|
|
2613
|
+
}
|
|
2614
|
+
// src/spec/registry.ts
|
|
2615
|
+
import { compareVersions } from "compare-versions";
|
|
2616
|
+
import { SpecContractRegistry } from "@contractspec/lib.contracts/registry";
|
|
2617
|
+
|
|
2618
|
+
class AgentRegistry extends SpecContractRegistry {
|
|
2619
|
+
constructor(items) {
|
|
2620
|
+
super("agent", items);
|
|
2621
|
+
}
|
|
2622
|
+
listNames() {
|
|
2623
|
+
const names = new Set;
|
|
2624
|
+
for (const spec of this.items.values()) {
|
|
2625
|
+
names.add(spec.meta.key);
|
|
2626
|
+
}
|
|
2627
|
+
return [...names];
|
|
2628
|
+
}
|
|
2629
|
+
require(name, version) {
|
|
2630
|
+
const spec = this.get(name, version);
|
|
2631
|
+
if (!spec) {
|
|
2632
|
+
throw new Error(`Agent spec not found for ${name}${version != null ? `.v${version}` : ""}`);
|
|
2633
|
+
}
|
|
2634
|
+
return spec;
|
|
2635
|
+
}
|
|
2636
|
+
has(name, version) {
|
|
2637
|
+
return this.get(name, version) !== undefined;
|
|
2638
|
+
}
|
|
2639
|
+
getVersions(name) {
|
|
2640
|
+
const versions = [];
|
|
2641
|
+
for (const spec of this.items.values()) {
|
|
2642
|
+
if (spec.meta.key === name) {
|
|
2643
|
+
versions.push(spec);
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
return versions.sort((a, b) => compareVersions(a.meta.version, b.meta.version));
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
function createAgentRegistry() {
|
|
2650
|
+
return new AgentRegistry;
|
|
2651
|
+
}
|
|
2652
|
+
// src/tools/mcp-client.ts
|
|
2653
|
+
import { experimental_createMCPClient } from "@ai-sdk/mcp";
|
|
2654
|
+
import { Experimental_StdioMCPTransport as StdioClientTransport } from "@ai-sdk/mcp/mcp-stdio";
|
|
2655
|
+
async function mcpServerToTools(config) {
|
|
2656
|
+
const transport = new StdioClientTransport({
|
|
2657
|
+
command: config.command,
|
|
2658
|
+
args: config.args,
|
|
2659
|
+
env: config.env
|
|
2660
|
+
});
|
|
2661
|
+
const client = await experimental_createMCPClient({ transport });
|
|
2662
|
+
const tools = await client.tools();
|
|
2663
|
+
return {
|
|
2664
|
+
tools,
|
|
2665
|
+
cleanup: () => client.close()
|
|
2666
|
+
};
|
|
2667
|
+
}
|
|
2668
|
+
async function createMcpToolsets(configs) {
|
|
2669
|
+
const results = await Promise.all(configs.map(mcpServerToTools));
|
|
2670
|
+
const combinedTools = {};
|
|
2671
|
+
for (const result of results) {
|
|
2672
|
+
Object.assign(combinedTools, result.tools);
|
|
2673
|
+
}
|
|
2674
|
+
return {
|
|
2675
|
+
tools: combinedTools,
|
|
2676
|
+
cleanup: async () => {
|
|
2677
|
+
await Promise.all(results.map((r) => r.cleanup()));
|
|
2678
|
+
}
|
|
2679
|
+
};
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
// src/tools/mcp-server.ts
|
|
2683
|
+
init_json_schema_to_zod();
|
|
2684
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2685
|
+
import * as z4 from "zod";
|
|
2686
|
+
function agentToMcpServer(agent, spec2) {
|
|
2687
|
+
const server = new McpServer({
|
|
2688
|
+
name: spec2.meta.key,
|
|
2689
|
+
version: `${spec2.meta.version}`
|
|
2690
|
+
});
|
|
2691
|
+
server.registerTool(spec2.meta.key, {
|
|
2692
|
+
description: spec2.description ?? `Interact with ${spec2.meta.key} agent`,
|
|
2693
|
+
inputSchema: z4.object({
|
|
2694
|
+
message: z4.string().describe("The message or query to send to the agent"),
|
|
2695
|
+
sessionId: z4.string().optional().describe("Optional session ID to continue a conversation")
|
|
2696
|
+
})
|
|
2697
|
+
}, async (args) => {
|
|
2698
|
+
const { message, sessionId } = args;
|
|
2699
|
+
const result = await agent.generate({
|
|
2700
|
+
prompt: message,
|
|
2701
|
+
options: { sessionId }
|
|
2702
|
+
});
|
|
2703
|
+
return {
|
|
2704
|
+
content: [
|
|
2705
|
+
{
|
|
2706
|
+
type: "text",
|
|
2707
|
+
text: result.text
|
|
2708
|
+
}
|
|
2709
|
+
]
|
|
2710
|
+
};
|
|
2711
|
+
});
|
|
2712
|
+
for (const toolConfig of spec2.tools) {
|
|
2713
|
+
const inputSchema = toolConfig.schema ? jsonSchemaToZodSafe(toolConfig.schema) : z4.object({});
|
|
2714
|
+
server.registerTool(`${spec2.meta.key}.${toolConfig.name}`, {
|
|
2715
|
+
description: toolConfig.description ?? `Execute ${toolConfig.name} tool`,
|
|
2716
|
+
inputSchema
|
|
2717
|
+
}, async (args) => {
|
|
2718
|
+
const result = await agent.generate({
|
|
2719
|
+
prompt: `Execute the ${toolConfig.name} tool with the following arguments: ${JSON.stringify(args)}`
|
|
2720
|
+
});
|
|
2721
|
+
return {
|
|
2722
|
+
content: [
|
|
2723
|
+
{
|
|
2724
|
+
type: "text",
|
|
2725
|
+
text: result.text
|
|
2726
|
+
}
|
|
2727
|
+
]
|
|
2728
|
+
};
|
|
2729
|
+
});
|
|
2730
|
+
}
|
|
2731
|
+
return server;
|
|
2732
|
+
}
|
|
2733
|
+
function createAgentMcpServer(config) {
|
|
2734
|
+
return agentToMcpServer(config.agent, config.spec);
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
// src/tools/index.ts
|
|
2738
|
+
init_tool_adapter();
|
|
2739
|
+
init_knowledge_tool();
|
|
2740
|
+
|
|
2741
|
+
// src/schema/schema-output.ts
|
|
2742
|
+
init_json_schema_to_zod();
|
|
2743
|
+
import { Output } from "ai";
|
|
2744
|
+
function jsonSchemaToOutput(schema) {
|
|
2745
|
+
const zodSchema = jsonSchemaToZod(schema);
|
|
2746
|
+
return Output.object({
|
|
2747
|
+
schema: zodSchema
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
function jsonSchemaToArrayOutput(itemSchema) {
|
|
2751
|
+
const zodSchema = jsonSchemaToZod(itemSchema);
|
|
2752
|
+
return Output.array({
|
|
2753
|
+
element: zodSchema
|
|
2754
|
+
});
|
|
2755
|
+
}
|
|
2756
|
+
function enumToChoiceOutput(choices) {
|
|
2757
|
+
return Output.choice({
|
|
2758
|
+
options: choices
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
function zodToOutput(schema) {
|
|
2762
|
+
return Output.object({
|
|
2763
|
+
schema
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
function textOutput() {
|
|
2767
|
+
return Output.text();
|
|
2768
|
+
}
|
|
2769
|
+
var SchemaOutput = {
|
|
2770
|
+
fromJsonSchema: jsonSchemaToOutput,
|
|
2771
|
+
arrayFromJsonSchema: jsonSchemaToArrayOutput,
|
|
2772
|
+
fromEnum: enumToChoiceOutput,
|
|
2773
|
+
fromZod: zodToOutput,
|
|
2774
|
+
text: textOutput
|
|
2775
|
+
};
|
|
2776
|
+
|
|
2777
|
+
// src/schema/index.ts
|
|
2778
|
+
init_json_schema_to_zod();
|
|
2779
|
+
// src/telemetry/index.ts
|
|
2780
|
+
init_adapter();
|
|
2781
|
+
|
|
2782
|
+
// src/providers/registry.ts
|
|
2783
|
+
init_types();
|
|
2784
|
+
|
|
2785
|
+
class InMemoryProviderRegistry {
|
|
2786
|
+
providers = new Map;
|
|
2787
|
+
get(name) {
|
|
2788
|
+
return this.providers.get(name);
|
|
2789
|
+
}
|
|
2790
|
+
register(name, provider) {
|
|
2791
|
+
this.providers.set(name, provider);
|
|
2792
|
+
}
|
|
2793
|
+
list() {
|
|
2794
|
+
return Array.from(this.providers.keys());
|
|
2795
|
+
}
|
|
2796
|
+
isAvailable(name) {
|
|
2797
|
+
const provider = this.providers.get(name);
|
|
2798
|
+
return provider !== undefined && provider.isAvailable();
|
|
2799
|
+
}
|
|
2800
|
+
require(name) {
|
|
2801
|
+
const provider = this.providers.get(name);
|
|
2802
|
+
if (!provider) {
|
|
2803
|
+
throw new ProviderNotAvailableError(name, "not registered");
|
|
2804
|
+
}
|
|
2805
|
+
if (!provider.isAvailable()) {
|
|
2806
|
+
throw new ProviderNotAvailableError(name, "dependencies not installed or not configured");
|
|
2807
|
+
}
|
|
2808
|
+
return provider;
|
|
2809
|
+
}
|
|
2810
|
+
clear() {
|
|
2811
|
+
this.providers.clear();
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
function createProviderRegistry() {
|
|
2815
|
+
return new InMemoryProviderRegistry;
|
|
2816
|
+
}
|
|
2817
|
+
var defaultProviderRegistry = createProviderRegistry();
|
|
2818
|
+
|
|
2819
|
+
// src/providers/index.ts
|
|
2820
|
+
init_claude_agent_sdk();
|
|
2821
|
+
init_opencode_sdk();
|
|
2822
|
+
init_types();
|
|
2823
|
+
// src/interop/spec-consumer.ts
|
|
2824
|
+
class ContractSpecConsumer {
|
|
2825
|
+
specs;
|
|
2826
|
+
includeMetadata;
|
|
2827
|
+
baseUrl;
|
|
2828
|
+
constructor(config) {
|
|
2829
|
+
this.specs = new Map;
|
|
2830
|
+
this.includeMetadata = config.includeMetadata ?? true;
|
|
2831
|
+
this.baseUrl = config.baseUrl;
|
|
2832
|
+
for (const spec2 of config.specs) {
|
|
2833
|
+
const key = agentKey(spec2.meta);
|
|
2834
|
+
this.specs.set(key, spec2);
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
getSpecMarkdown(specKey, options) {
|
|
2838
|
+
const spec2 = this.specs.get(specKey);
|
|
2839
|
+
if (!spec2) {
|
|
2840
|
+
throw new Error(`Spec not found: ${specKey}`);
|
|
2841
|
+
}
|
|
2842
|
+
const sections = [];
|
|
2843
|
+
const opts = {
|
|
2844
|
+
includeToc: options?.includeToc ?? true,
|
|
2845
|
+
includeTools: options?.includeTools ?? true,
|
|
2846
|
+
...options
|
|
2847
|
+
};
|
|
2848
|
+
if (opts.customHeader) {
|
|
2849
|
+
sections.push(opts.customHeader);
|
|
2850
|
+
sections.push("");
|
|
2851
|
+
}
|
|
2852
|
+
const specName = spec2.meta.key;
|
|
2853
|
+
sections.push(`# ${specName}`);
|
|
2854
|
+
sections.push("");
|
|
2855
|
+
if (spec2.description) {
|
|
2856
|
+
sections.push(spec2.description);
|
|
2857
|
+
sections.push("");
|
|
2858
|
+
}
|
|
2859
|
+
if (opts.includeToc) {
|
|
2860
|
+
sections.push("## Table of Contents");
|
|
2861
|
+
sections.push("");
|
|
2862
|
+
sections.push("- [Overview](#overview)");
|
|
2863
|
+
sections.push("- [Instructions](#instructions)");
|
|
2864
|
+
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
2865
|
+
sections.push("- [Tools](#tools)");
|
|
2866
|
+
}
|
|
2867
|
+
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
2868
|
+
sections.push("- [Knowledge](#knowledge)");
|
|
2869
|
+
}
|
|
2870
|
+
sections.push("");
|
|
2871
|
+
}
|
|
2872
|
+
sections.push("## Overview");
|
|
2873
|
+
sections.push("");
|
|
2874
|
+
if (this.includeMetadata) {
|
|
2875
|
+
sections.push(`- **Key**: \`${spec2.meta.key}\``);
|
|
2876
|
+
sections.push(`- **Version**: ${spec2.meta.version}`);
|
|
2877
|
+
if (spec2.meta.stability) {
|
|
2878
|
+
sections.push(`- **Stability**: ${spec2.meta.stability}`);
|
|
2879
|
+
}
|
|
2880
|
+
if (spec2.meta.owners && spec2.meta.owners.length > 0) {
|
|
2881
|
+
sections.push(`- **Owners**: ${spec2.meta.owners.join(", ")}`);
|
|
2882
|
+
}
|
|
2883
|
+
if (spec2.tags && spec2.tags.length > 0) {
|
|
2884
|
+
sections.push(`- **Tags**: ${spec2.tags.join(", ")}`);
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
sections.push("");
|
|
2888
|
+
sections.push("## Instructions");
|
|
2889
|
+
sections.push("");
|
|
2890
|
+
sections.push(spec2.instructions);
|
|
2891
|
+
sections.push("");
|
|
2892
|
+
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
2893
|
+
sections.push("## Tools");
|
|
2894
|
+
sections.push("");
|
|
2895
|
+
for (const tool3 of spec2.tools) {
|
|
2896
|
+
sections.push(`### ${tool3.name}`);
|
|
2897
|
+
sections.push("");
|
|
2898
|
+
if (tool3.description) {
|
|
2899
|
+
sections.push(tool3.description);
|
|
2900
|
+
sections.push("");
|
|
2901
|
+
}
|
|
2902
|
+
if (tool3.schema) {
|
|
2903
|
+
sections.push("**Schema:**");
|
|
2904
|
+
sections.push("");
|
|
2905
|
+
sections.push("```json");
|
|
2906
|
+
sections.push(JSON.stringify(tool3.schema, null, 2));
|
|
2907
|
+
sections.push("```");
|
|
2908
|
+
sections.push("");
|
|
2909
|
+
}
|
|
2910
|
+
if (tool3.automationSafe !== undefined) {
|
|
2911
|
+
sections.push(`**Automation Safe**: ${tool3.automationSafe ? "Yes" : "No"}`);
|
|
2912
|
+
sections.push("");
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
}
|
|
2916
|
+
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
2917
|
+
sections.push("## Knowledge");
|
|
2918
|
+
sections.push("");
|
|
2919
|
+
for (const k of spec2.knowledge) {
|
|
2920
|
+
sections.push(`- **${k.key}**${k.required ? " (required)" : ""}`);
|
|
2921
|
+
if (k.instructions) {
|
|
2922
|
+
sections.push(` - ${k.instructions}`);
|
|
2923
|
+
}
|
|
2924
|
+
}
|
|
2925
|
+
sections.push("");
|
|
2926
|
+
}
|
|
2927
|
+
if (spec2.policy) {
|
|
2928
|
+
sections.push("## Policy");
|
|
2929
|
+
sections.push("");
|
|
2930
|
+
if (spec2.policy.confidence) {
|
|
2931
|
+
sections.push(`- **Minimum Confidence**: ${spec2.policy.confidence.min ?? 0.7}`);
|
|
2932
|
+
}
|
|
2933
|
+
if (spec2.policy.escalation) {
|
|
2934
|
+
const esc = spec2.policy.escalation;
|
|
2935
|
+
if (esc.confidenceThreshold) {
|
|
2936
|
+
sections.push(`- **Escalation Threshold**: ${esc.confidenceThreshold}`);
|
|
2937
|
+
}
|
|
2938
|
+
if (esc.onToolFailure) {
|
|
2939
|
+
sections.push("- **Escalate on Tool Failure**: Yes");
|
|
2940
|
+
}
|
|
2941
|
+
if (esc.onTimeout) {
|
|
2942
|
+
sections.push("- **Escalate on Timeout**: Yes");
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
sections.push("");
|
|
2946
|
+
}
|
|
2947
|
+
return sections.join(`
|
|
2948
|
+
`);
|
|
2949
|
+
}
|
|
2950
|
+
getSpecPrompt(specKey, options) {
|
|
2951
|
+
const spec2 = this.specs.get(specKey);
|
|
2952
|
+
if (!spec2) {
|
|
2953
|
+
throw new Error(`Spec not found: ${specKey}`);
|
|
2954
|
+
}
|
|
2955
|
+
const sections = [];
|
|
2956
|
+
const opts = {
|
|
2957
|
+
includeTools: options?.includeTools ?? true,
|
|
2958
|
+
format: options?.format ?? "structured",
|
|
2959
|
+
...options
|
|
2960
|
+
};
|
|
2961
|
+
sections.push("# Agent Identity");
|
|
2962
|
+
sections.push("");
|
|
2963
|
+
sections.push(`You are ${spec2.meta.key} (v${spec2.meta.version}).`);
|
|
2964
|
+
sections.push("");
|
|
2965
|
+
if (spec2.description) {
|
|
2966
|
+
sections.push("## Description");
|
|
2967
|
+
sections.push("");
|
|
2968
|
+
sections.push(spec2.description);
|
|
2969
|
+
sections.push("");
|
|
2970
|
+
}
|
|
2971
|
+
sections.push("## Instructions");
|
|
2972
|
+
sections.push("");
|
|
2973
|
+
sections.push(spec2.instructions);
|
|
2974
|
+
sections.push("");
|
|
2975
|
+
if (opts.includeTools && spec2.tools && spec2.tools.length > 0) {
|
|
2976
|
+
sections.push("## Available Tools");
|
|
2977
|
+
sections.push("");
|
|
2978
|
+
sections.push("You have access to the following tools:");
|
|
2979
|
+
sections.push("");
|
|
2980
|
+
for (const tool3 of spec2.tools) {
|
|
2981
|
+
sections.push(`### ${tool3.name}`);
|
|
2982
|
+
sections.push("");
|
|
2983
|
+
if (tool3.description) {
|
|
2984
|
+
sections.push(tool3.description);
|
|
2985
|
+
sections.push("");
|
|
2986
|
+
}
|
|
2987
|
+
if (tool3.schema && opts.format === "structured") {
|
|
2988
|
+
sections.push("Parameters:");
|
|
2989
|
+
sections.push("```json");
|
|
2990
|
+
sections.push(JSON.stringify(tool3.schema, null, 2));
|
|
2991
|
+
sections.push("```");
|
|
2992
|
+
sections.push("");
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
if (spec2.knowledge && spec2.knowledge.length > 0) {
|
|
2997
|
+
const requiredKnowledge = spec2.knowledge.filter((k) => k.required);
|
|
2998
|
+
if (requiredKnowledge.length > 0) {
|
|
2999
|
+
sections.push("## Knowledge Context");
|
|
3000
|
+
sections.push("");
|
|
3001
|
+
for (const k of requiredKnowledge) {
|
|
3002
|
+
if (k.instructions) {
|
|
3003
|
+
sections.push(k.instructions);
|
|
3004
|
+
sections.push("");
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
if (options?.customContext) {
|
|
3010
|
+
sections.push("## Additional Context");
|
|
3011
|
+
sections.push("");
|
|
3012
|
+
sections.push(options.customContext);
|
|
3013
|
+
sections.push("");
|
|
3014
|
+
}
|
|
3015
|
+
return sections.join(`
|
|
3016
|
+
`);
|
|
3017
|
+
}
|
|
3018
|
+
listSpecs(options) {
|
|
3019
|
+
const results = [];
|
|
3020
|
+
for (const [key, spec2] of this.specs) {
|
|
3021
|
+
if (options?.stability && spec2.meta.stability !== options.stability) {
|
|
3022
|
+
continue;
|
|
3023
|
+
}
|
|
3024
|
+
if (options?.tags && options.tags.length > 0) {
|
|
3025
|
+
const specTags = spec2.tags ?? [];
|
|
3026
|
+
const hasMatchingTag = options.tags.some((tag) => specTags.includes(tag));
|
|
3027
|
+
if (!hasMatchingTag) {
|
|
3028
|
+
continue;
|
|
3029
|
+
}
|
|
3030
|
+
}
|
|
3031
|
+
results.push({
|
|
3032
|
+
key,
|
|
3033
|
+
name: spec2.meta.key,
|
|
3034
|
+
version: spec2.meta.version,
|
|
3035
|
+
description: spec2.description,
|
|
3036
|
+
stability: spec2.meta.stability,
|
|
3037
|
+
tags: spec2.tags,
|
|
3038
|
+
toolCount: spec2.tools?.length ?? 0
|
|
3039
|
+
});
|
|
3040
|
+
}
|
|
3041
|
+
return results;
|
|
3042
|
+
}
|
|
3043
|
+
querySpec(specKey) {
|
|
3044
|
+
const spec2 = this.specs.get(specKey);
|
|
3045
|
+
if (!spec2) {
|
|
3046
|
+
return;
|
|
3047
|
+
}
|
|
3048
|
+
return {
|
|
3049
|
+
key: specKey,
|
|
3050
|
+
spec: spec2,
|
|
3051
|
+
markdown: this.getSpecMarkdown(specKey),
|
|
3052
|
+
prompt: this.getSpecPrompt(specKey)
|
|
3053
|
+
};
|
|
3054
|
+
}
|
|
3055
|
+
hasSpec(specKey) {
|
|
3056
|
+
return this.specs.has(specKey);
|
|
3057
|
+
}
|
|
3058
|
+
getSpec(specKey) {
|
|
3059
|
+
return this.specs.get(specKey);
|
|
3060
|
+
}
|
|
3061
|
+
getAllSpecs() {
|
|
3062
|
+
return Array.from(this.specs.values());
|
|
3063
|
+
}
|
|
3064
|
+
getSpecCount() {
|
|
3065
|
+
return this.specs.size;
|
|
3066
|
+
}
|
|
3067
|
+
addSpec(spec2) {
|
|
3068
|
+
const key = agentKey(spec2.meta);
|
|
3069
|
+
this.specs.set(key, spec2);
|
|
3070
|
+
}
|
|
3071
|
+
removeSpec(specKey) {
|
|
3072
|
+
return this.specs.delete(specKey);
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
function createSpecConsumer(config) {
|
|
3076
|
+
return new ContractSpecConsumer(config);
|
|
3077
|
+
}
|
|
3078
|
+
function createSingleSpecConsumer(spec2, options) {
|
|
3079
|
+
return new ContractSpecConsumer({
|
|
3080
|
+
specs: [spec2],
|
|
3081
|
+
...options
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
|
|
3085
|
+
// src/interop/tool-consumer.ts
|
|
3086
|
+
class MCPToolServer {
|
|
3087
|
+
tools;
|
|
3088
|
+
name;
|
|
3089
|
+
version;
|
|
3090
|
+
running = false;
|
|
3091
|
+
constructor(config) {
|
|
3092
|
+
this.tools = new Map;
|
|
3093
|
+
this.name = config.name ?? "contractspec-tools";
|
|
3094
|
+
this.version = config.version ?? "1.0.0";
|
|
3095
|
+
for (const tool3 of config.tools) {
|
|
3096
|
+
this.tools.set(tool3.config.name, tool3);
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
async start() {
|
|
3100
|
+
if (this.running) {
|
|
3101
|
+
return;
|
|
3102
|
+
}
|
|
3103
|
+
this.running = true;
|
|
3104
|
+
console.log(`[MCPToolServer] Started ${this.name}@${this.version} with ${this.tools.size} tools`);
|
|
3105
|
+
}
|
|
3106
|
+
async stop() {
|
|
3107
|
+
if (!this.running) {
|
|
3108
|
+
return;
|
|
3109
|
+
}
|
|
3110
|
+
this.running = false;
|
|
3111
|
+
console.log(`[MCPToolServer] Stopped ${this.name}`);
|
|
3112
|
+
}
|
|
3113
|
+
isRunning() {
|
|
3114
|
+
return this.running;
|
|
3115
|
+
}
|
|
3116
|
+
getTools() {
|
|
3117
|
+
return Array.from(this.tools.values()).map((t) => t.config);
|
|
3118
|
+
}
|
|
3119
|
+
async executeTool(toolName, args, context) {
|
|
3120
|
+
const tool3 = this.tools.get(toolName);
|
|
3121
|
+
if (!tool3) {
|
|
3122
|
+
throw new Error(`Tool not found: ${toolName}`);
|
|
3123
|
+
}
|
|
3124
|
+
if (!tool3.handler) {
|
|
3125
|
+
throw new Error(`No handler registered for tool: ${toolName}`);
|
|
3126
|
+
}
|
|
3127
|
+
const fullContext = {
|
|
3128
|
+
agentId: context?.agentId ?? "mcp-server",
|
|
3129
|
+
sessionId: context?.sessionId ?? "mcp-session",
|
|
3130
|
+
tenantId: context?.tenantId,
|
|
3131
|
+
actorId: context?.actorId,
|
|
3132
|
+
metadata: context?.metadata,
|
|
3133
|
+
signal: context?.signal
|
|
3134
|
+
};
|
|
3135
|
+
return await tool3.handler(args, fullContext);
|
|
3136
|
+
}
|
|
3137
|
+
getMCPToolDefinitions() {
|
|
3138
|
+
const definitions = [];
|
|
3139
|
+
for (const [name, tool3] of this.tools) {
|
|
3140
|
+
definitions.push({
|
|
3141
|
+
name,
|
|
3142
|
+
description: tool3.config.description ?? "",
|
|
3143
|
+
inputSchema: tool3.config.schema ?? { type: "object", properties: {} }
|
|
3144
|
+
});
|
|
3145
|
+
}
|
|
3146
|
+
return definitions;
|
|
3147
|
+
}
|
|
3148
|
+
getServerInfo() {
|
|
3149
|
+
return {
|
|
3150
|
+
name: this.name,
|
|
3151
|
+
version: this.version,
|
|
3152
|
+
tools: this.tools.size,
|
|
3153
|
+
running: this.running
|
|
3154
|
+
};
|
|
3155
|
+
}
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
class ContractSpecToolConsumer {
|
|
3159
|
+
tools;
|
|
3160
|
+
constructor(config) {
|
|
3161
|
+
this.tools = new Map;
|
|
3162
|
+
for (const tool3 of config.tools) {
|
|
3163
|
+
this.tools.set(tool3.config.name, tool3);
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
createToolServer(config) {
|
|
3167
|
+
return new MCPToolServer({
|
|
3168
|
+
tools: Array.from(this.tools.values()),
|
|
3169
|
+
...config
|
|
3170
|
+
});
|
|
3171
|
+
}
|
|
3172
|
+
exportToolsForSDK(format) {
|
|
3173
|
+
const tools = Array.from(this.tools.values());
|
|
3174
|
+
const defaultContext = {
|
|
3175
|
+
agentId: "export",
|
|
3176
|
+
sessionId: "export"
|
|
3177
|
+
};
|
|
3178
|
+
switch (format) {
|
|
3179
|
+
case "claude-agent":
|
|
3180
|
+
return tools.filter((tool3) => !!tool3.handler).map((tool3) => specToolToClaudeAgentTool(tool3.config, tool3.handler, defaultContext));
|
|
3181
|
+
case "opencode":
|
|
3182
|
+
return tools.map((tool3) => specToolToOpenCodeTool(tool3.config));
|
|
3183
|
+
case "mcp":
|
|
3184
|
+
return tools.map((tool3) => ({
|
|
3185
|
+
name: tool3.config.name,
|
|
3186
|
+
description: tool3.config.description ?? "",
|
|
3187
|
+
inputSchema: tool3.config.schema ?? { type: "object", properties: {} }
|
|
3188
|
+
}));
|
|
3189
|
+
case "openai":
|
|
3190
|
+
return tools.map((tool3) => ({
|
|
3191
|
+
type: "function",
|
|
3192
|
+
function: {
|
|
3193
|
+
name: tool3.config.name,
|
|
3194
|
+
description: tool3.config.description ?? "",
|
|
3195
|
+
parameters: tool3.config.schema ?? {
|
|
3196
|
+
type: "object",
|
|
3197
|
+
properties: {}
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
}));
|
|
3201
|
+
default:
|
|
3202
|
+
throw new Error(`Unknown export format: ${format}`);
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
createBridgedHandler(toolName, _format) {
|
|
3206
|
+
const tool3 = this.tools.get(toolName);
|
|
3207
|
+
if (!tool3 || !tool3.handler) {
|
|
3208
|
+
return;
|
|
3209
|
+
}
|
|
3210
|
+
const handler = tool3.handler;
|
|
3211
|
+
return async (args) => {
|
|
3212
|
+
const context = {
|
|
3213
|
+
agentId: "bridge",
|
|
3214
|
+
sessionId: "bridge"
|
|
3215
|
+
};
|
|
3216
|
+
return handler(args, context);
|
|
3217
|
+
};
|
|
3218
|
+
}
|
|
3219
|
+
getTools() {
|
|
3220
|
+
return Array.from(this.tools.values()).map((t) => t.config);
|
|
3221
|
+
}
|
|
3222
|
+
getTool(name) {
|
|
3223
|
+
return this.tools.get(name)?.config;
|
|
3224
|
+
}
|
|
3225
|
+
hasTool(name) {
|
|
3226
|
+
return this.tools.has(name);
|
|
3227
|
+
}
|
|
3228
|
+
async executeTool(name, args, context) {
|
|
3229
|
+
const tool3 = this.tools.get(name);
|
|
3230
|
+
if (!tool3) {
|
|
3231
|
+
throw new Error(`Tool not found: ${name}`);
|
|
3232
|
+
}
|
|
3233
|
+
if (!tool3.handler) {
|
|
3234
|
+
throw new Error(`No handler for tool: ${name}`);
|
|
3235
|
+
}
|
|
3236
|
+
const fullContext = {
|
|
3237
|
+
agentId: context?.agentId ?? "consumer",
|
|
3238
|
+
sessionId: context?.sessionId ?? "consumer-session",
|
|
3239
|
+
tenantId: context?.tenantId,
|
|
3240
|
+
actorId: context?.actorId,
|
|
3241
|
+
metadata: context?.metadata,
|
|
3242
|
+
signal: context?.signal
|
|
3243
|
+
};
|
|
3244
|
+
return await tool3.handler(args, fullContext);
|
|
3245
|
+
}
|
|
3246
|
+
addTool(config, handler) {
|
|
3247
|
+
this.tools.set(config.name, { config, handler });
|
|
3248
|
+
}
|
|
3249
|
+
removeTool(name) {
|
|
3250
|
+
return this.tools.delete(name);
|
|
3251
|
+
}
|
|
3252
|
+
getToolCount() {
|
|
3253
|
+
return this.tools.size;
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
function createToolConsumer(config) {
|
|
3257
|
+
return new ContractSpecToolConsumer(config);
|
|
3258
|
+
}
|
|
3259
|
+
function createToolServer(config) {
|
|
3260
|
+
return new MCPToolServer(config);
|
|
3261
|
+
}
|
|
3262
|
+
function exportToolsForExternalSDK(tools, format) {
|
|
3263
|
+
const consumer = new ContractSpecToolConsumer({
|
|
3264
|
+
tools: tools.map((config) => ({ config }))
|
|
3265
|
+
});
|
|
3266
|
+
return consumer.exportToolsForSDK(format);
|
|
3267
|
+
}
|
|
3268
|
+
// src/index.ts
|
|
3269
|
+
import { Experimental_Agent } from "ai";
|
|
3270
|
+
export {
|
|
3271
|
+
zodToOutput,
|
|
3272
|
+
validateForOpenCode,
|
|
3273
|
+
validateForClaudeAgent,
|
|
3274
|
+
trackAgentStep,
|
|
3275
|
+
textOutput,
|
|
3276
|
+
specToolsToAISDKTools,
|
|
3277
|
+
specToolToAISDKTool,
|
|
3278
|
+
noopTelemetryCollector,
|
|
3279
|
+
mcpServerToTools,
|
|
3280
|
+
jsonSchemaToZodSafe,
|
|
3281
|
+
jsonSchemaToZod,
|
|
3282
|
+
jsonSchemaToOutput,
|
|
3283
|
+
jsonSchemaToArrayOutput,
|
|
3284
|
+
injectStaticKnowledge,
|
|
3285
|
+
getAvailableBackends,
|
|
3286
|
+
generateSessionId,
|
|
3287
|
+
generateOpenCodeMarkdown,
|
|
3288
|
+
generateOpenCodeJSON,
|
|
3289
|
+
generateClaudeMd,
|
|
3290
|
+
exportToolsForExternalSDK,
|
|
3291
|
+
exportToOpenCode,
|
|
3292
|
+
exportToClaudeAgent,
|
|
3293
|
+
enumToChoiceOutput,
|
|
3294
|
+
defineAgent,
|
|
3295
|
+
defaultProviderRegistry,
|
|
3296
|
+
createUnifiedAgent,
|
|
3297
|
+
createToolServer,
|
|
3298
|
+
createToolHandler,
|
|
3299
|
+
createToolConsumer,
|
|
3300
|
+
createSpecConsumer,
|
|
3301
|
+
createSingleSpecConsumer,
|
|
3302
|
+
createProviderRegistry,
|
|
3303
|
+
createOpenCodeSDKAgent,
|
|
3304
|
+
createMcpToolsets,
|
|
3305
|
+
createKnowledgeQueryTool,
|
|
3306
|
+
createKnowledgeInjector,
|
|
3307
|
+
createInMemoryTelemetryCollector,
|
|
3308
|
+
createInMemorySessionStore,
|
|
3309
|
+
createClaudeAgentSDKAgent,
|
|
3310
|
+
createApprovalWorkflow,
|
|
3311
|
+
createAgentRegistry,
|
|
3312
|
+
createAgentMcpServer,
|
|
3313
|
+
createAgentJsonRunner,
|
|
3314
|
+
createAISDKAgent,
|
|
3315
|
+
buildToolHandlers,
|
|
3316
|
+
agentToMcpServer,
|
|
3317
|
+
agentKey,
|
|
3318
|
+
UnifiedAgent,
|
|
3319
|
+
Experimental_Agent as ToolLoopAgent,
|
|
3320
|
+
SchemaOutput,
|
|
3321
|
+
ProviderNotAvailableError,
|
|
3322
|
+
ProviderExecutionError,
|
|
3323
|
+
OpenCodeSDKProvider,
|
|
3324
|
+
OpenCodeExporter,
|
|
3325
|
+
InMemoryTelemetryCollector,
|
|
3326
|
+
InMemorySessionStore,
|
|
3327
|
+
InMemoryApprovalStore,
|
|
3328
|
+
ExternalProviderError,
|
|
3329
|
+
ContractSpecToolConsumer,
|
|
3330
|
+
ContractSpecConsumer,
|
|
3331
|
+
ContractSpecAgent,
|
|
3332
|
+
ContextCreationError,
|
|
3333
|
+
ClaudeAgentSDKProvider,
|
|
3334
|
+
ClaudeAgentExporter,
|
|
3335
|
+
ApprovalWorkflow,
|
|
3336
|
+
AgentRegistry
|
|
3337
|
+
};
|