@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.
Files changed (232) hide show
  1. package/dist/agent/agent-factory.d.ts +67 -71
  2. package/dist/agent/agent-factory.d.ts.map +1 -1
  3. package/dist/agent/agent-factory.js +658 -100
  4. package/dist/agent/agent.test.d.ts +2 -0
  5. package/dist/agent/agent.test.d.ts.map +1 -0
  6. package/dist/agent/contract-spec-agent.d.ts +48 -52
  7. package/dist/agent/contract-spec-agent.d.ts.map +1 -1
  8. package/dist/agent/contract-spec-agent.js +605 -146
  9. package/dist/agent/index.d.ts +4 -4
  10. package/dist/agent/index.d.ts.map +1 -0
  11. package/dist/agent/index.js +2102 -4
  12. package/dist/agent/json-runner.d.ts +15 -19
  13. package/dist/agent/json-runner.d.ts.map +1 -1
  14. package/dist/agent/json-runner.js +672 -57
  15. package/dist/agent/json-runner.test.d.ts +2 -0
  16. package/dist/agent/json-runner.test.d.ts.map +1 -0
  17. package/dist/agent/unified-agent.d.ts +132 -109
  18. package/dist/agent/unified-agent.d.ts.map +1 -1
  19. package/dist/agent/unified-agent.js +2011 -293
  20. package/dist/approval/index.d.ts +3 -2
  21. package/dist/approval/index.d.ts.map +1 -0
  22. package/dist/approval/index.js +128 -2
  23. package/dist/approval/workflow.d.ts +106 -110
  24. package/dist/approval/workflow.d.ts.map +1 -1
  25. package/dist/approval/workflow.js +126 -157
  26. package/dist/exporters/claude-agent-exporter.d.ts +50 -48
  27. package/dist/exporters/claude-agent-exporter.d.ts.map +1 -1
  28. package/dist/exporters/claude-agent-exporter.js +258 -203
  29. package/dist/exporters/index.d.ts +28 -4
  30. package/dist/exporters/index.d.ts.map +1 -0
  31. package/dist/exporters/index.js +737 -3
  32. package/dist/exporters/opencode-exporter.d.ts +47 -45
  33. package/dist/exporters/opencode-exporter.d.ts.map +1 -1
  34. package/dist/exporters/opencode-exporter.js +507 -191
  35. package/dist/exporters/types.d.ts +171 -169
  36. package/dist/exporters/types.d.ts.map +1 -1
  37. package/dist/exporters/types.js +1 -0
  38. package/dist/index.d.ts +15 -39
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +3337 -32
  41. package/dist/interop/index.d.ts +48 -4
  42. package/dist/interop/index.d.ts.map +1 -0
  43. package/dist/interop/index.js +709 -3
  44. package/dist/interop/spec-consumer.d.ts +57 -53
  45. package/dist/interop/spec-consumer.d.ts.map +1 -1
  46. package/dist/interop/spec-consumer.js +302 -282
  47. package/dist/interop/tool-consumer.d.ts +57 -53
  48. package/dist/interop/tool-consumer.d.ts.map +1 -1
  49. package/dist/interop/tool-consumer.js +412 -213
  50. package/dist/interop/types.d.ts +173 -171
  51. package/dist/interop/types.d.ts.map +1 -1
  52. package/dist/interop/types.js +1 -0
  53. package/dist/knowledge/index.d.ts +2 -2
  54. package/dist/knowledge/index.d.ts.map +1 -0
  55. package/dist/knowledge/index.js +66 -2
  56. package/dist/knowledge/injector.d.ts +16 -20
  57. package/dist/knowledge/injector.d.ts.map +1 -1
  58. package/dist/knowledge/injector.js +56 -47
  59. package/dist/memory/in-memory.d.ts +15 -19
  60. package/dist/memory/in-memory.d.ts.map +1 -1
  61. package/dist/memory/in-memory.js +152 -46
  62. package/dist/memory/index.d.ts +3 -3
  63. package/dist/memory/index.d.ts.map +1 -0
  64. package/dist/memory/index.js +155 -3
  65. package/dist/memory/manager.d.ts +32 -36
  66. package/dist/memory/manager.d.ts.map +1 -1
  67. package/dist/memory/manager.js +96 -70
  68. package/dist/memory/memory.test.d.ts +2 -0
  69. package/dist/memory/memory.test.d.ts.map +1 -0
  70. package/dist/node/agent/agent-factory.js +661 -0
  71. package/dist/node/agent/contract-spec-agent.js +607 -0
  72. package/dist/node/agent/index.js +2103 -0
  73. package/dist/node/agent/json-runner.js +684 -0
  74. package/dist/node/agent/unified-agent.js +2019 -0
  75. package/dist/node/approval/index.js +129 -0
  76. package/dist/node/approval/workflow.js +129 -0
  77. package/dist/node/exporters/claude-agent-exporter.js +265 -0
  78. package/dist/node/exporters/index.js +738 -0
  79. package/dist/node/exporters/opencode-exporter.js +516 -0
  80. package/dist/node/exporters/types.js +0 -0
  81. package/dist/node/index.js +3337 -0
  82. package/dist/node/interop/index.js +710 -0
  83. package/dist/node/interop/spec-consumer.js +307 -0
  84. package/dist/node/interop/tool-consumer.js +419 -0
  85. package/dist/node/interop/types.js +0 -0
  86. package/dist/node/knowledge/index.js +67 -0
  87. package/dist/node/knowledge/injector.js +67 -0
  88. package/dist/node/memory/in-memory.js +154 -0
  89. package/dist/node/memory/index.js +156 -0
  90. package/dist/node/memory/manager.js +105 -0
  91. package/dist/node/providers/claude-agent-sdk/adapter.js +624 -0
  92. package/dist/node/providers/claude-agent-sdk/index.js +673 -0
  93. package/dist/node/providers/claude-agent-sdk/session-bridge.js +149 -0
  94. package/dist/node/providers/claude-agent-sdk/tool-bridge.js +118 -0
  95. package/dist/node/providers/index.js +1261 -0
  96. package/dist/node/providers/opencode-sdk/adapter.js +669 -0
  97. package/dist/node/providers/opencode-sdk/agent-bridge.js +299 -0
  98. package/dist/node/providers/opencode-sdk/index.js +703 -0
  99. package/dist/node/providers/opencode-sdk/tool-bridge.js +141 -0
  100. package/dist/node/providers/registry.js +89 -0
  101. package/dist/node/providers/types.js +56 -0
  102. package/dist/node/schema/index.js +195 -0
  103. package/dist/node/schema/json-schema-to-zod.js +152 -0
  104. package/dist/node/schema/schema-output.js +190 -0
  105. package/dist/node/session/index.js +90 -0
  106. package/dist/node/session/store.js +90 -0
  107. package/dist/node/spec/index.js +85 -0
  108. package/dist/node/spec/registry.js +56 -0
  109. package/dist/node/spec/spec.js +44 -0
  110. package/dist/node/telemetry/adapter.js +85 -0
  111. package/dist/node/telemetry/index.js +86 -0
  112. package/dist/node/tools/index.js +345 -0
  113. package/dist/node/tools/knowledge-tool.js +74 -0
  114. package/dist/node/tools/mcp-client.js +47 -0
  115. package/dist/node/tools/mcp-server.js +205 -0
  116. package/dist/node/tools/tool-adapter.js +197 -0
  117. package/dist/node/types.js +0 -0
  118. package/dist/providers/claude-agent-sdk/adapter.d.ts +60 -52
  119. package/dist/providers/claude-agent-sdk/adapter.d.ts.map +1 -1
  120. package/dist/providers/claude-agent-sdk/adapter.js +622 -304
  121. package/dist/providers/claude-agent-sdk/index.d.ts +22 -4
  122. package/dist/providers/claude-agent-sdk/index.d.ts.map +1 -0
  123. package/dist/providers/claude-agent-sdk/index.js +672 -4
  124. package/dist/providers/claude-agent-sdk/session-bridge.d.ts +43 -40
  125. package/dist/providers/claude-agent-sdk/session-bridge.d.ts.map +1 -1
  126. package/dist/providers/claude-agent-sdk/session-bridge.js +121 -130
  127. package/dist/providers/claude-agent-sdk/tool-bridge.d.ts +63 -60
  128. package/dist/providers/claude-agent-sdk/tool-bridge.d.ts.map +1 -1
  129. package/dist/providers/claude-agent-sdk/tool-bridge.js +104 -108
  130. package/dist/providers/index.d.ts +28 -7
  131. package/dist/providers/index.d.ts.map +1 -0
  132. package/dist/providers/index.js +1261 -8
  133. package/dist/providers/opencode-sdk/adapter.d.ts +56 -48
  134. package/dist/providers/opencode-sdk/adapter.d.ts.map +1 -1
  135. package/dist/providers/opencode-sdk/adapter.js +667 -274
  136. package/dist/providers/opencode-sdk/agent-bridge.d.ts +62 -57
  137. package/dist/providers/opencode-sdk/agent-bridge.d.ts.map +1 -1
  138. package/dist/providers/opencode-sdk/agent-bridge.js +289 -155
  139. package/dist/providers/opencode-sdk/index.d.ts +22 -4
  140. package/dist/providers/opencode-sdk/index.d.ts.map +1 -0
  141. package/dist/providers/opencode-sdk/index.js +702 -4
  142. package/dist/providers/opencode-sdk/tool-bridge.d.ts +41 -42
  143. package/dist/providers/opencode-sdk/tool-bridge.d.ts.map +1 -1
  144. package/dist/providers/opencode-sdk/tool-bridge.js +121 -107
  145. package/dist/providers/registry.d.ts +10 -11
  146. package/dist/providers/registry.d.ts.map +1 -1
  147. package/dist/providers/registry.js +86 -49
  148. package/dist/providers/types.d.ts +169 -166
  149. package/dist/providers/types.d.ts.map +1 -1
  150. package/dist/providers/types.js +54 -42
  151. package/dist/schema/index.d.ts +3 -3
  152. package/dist/schema/index.d.ts.map +1 -0
  153. package/dist/schema/index.js +194 -3
  154. package/dist/schema/json-schema-to-zod.d.ts +23 -26
  155. package/dist/schema/json-schema-to-zod.d.ts.map +1 -1
  156. package/dist/schema/json-schema-to-zod.js +138 -110
  157. package/dist/schema/schema-output.d.ts +29 -32
  158. package/dist/schema/schema-output.d.ts.map +1 -1
  159. package/dist/schema/schema-output.js +178 -53
  160. package/dist/session/index.d.ts +2 -2
  161. package/dist/session/index.d.ts.map +1 -0
  162. package/dist/session/index.js +89 -2
  163. package/dist/session/store.d.ts +51 -55
  164. package/dist/session/store.d.ts.map +1 -1
  165. package/dist/session/store.js +85 -74
  166. package/dist/spec/index.d.ts +3 -3
  167. package/dist/spec/index.d.ts.map +1 -0
  168. package/dist/spec/index.js +84 -3
  169. package/dist/spec/registry.d.ts +32 -36
  170. package/dist/spec/registry.d.ts.map +1 -1
  171. package/dist/spec/registry.js +51 -60
  172. package/dist/spec/spec.d.ts +80 -84
  173. package/dist/spec/spec.d.ts.map +1 -1
  174. package/dist/spec/spec.js +40 -26
  175. package/dist/telemetry/adapter.d.ts +33 -37
  176. package/dist/telemetry/adapter.d.ts.map +1 -1
  177. package/dist/telemetry/adapter.js +78 -96
  178. package/dist/telemetry/index.d.ts +2 -2
  179. package/dist/telemetry/index.d.ts.map +1 -0
  180. package/dist/telemetry/index.js +85 -2
  181. package/dist/tools/index.d.ts +5 -5
  182. package/dist/tools/index.d.ts.map +1 -0
  183. package/dist/tools/index.js +344 -5
  184. package/dist/tools/knowledge-tool.d.ts +4 -8
  185. package/dist/tools/knowledge-tool.d.ts.map +1 -1
  186. package/dist/tools/knowledge-tool.js +68 -48
  187. package/dist/tools/mcp-client.d.ts +17 -21
  188. package/dist/tools/mcp-client.d.ts.map +1 -1
  189. package/dist/tools/mcp-client.js +42 -53
  190. package/dist/tools/mcp-server.d.ts +14 -18
  191. package/dist/tools/mcp-server.d.ts.map +1 -1
  192. package/dist/tools/mcp-server.js +200 -64
  193. package/dist/tools/tool-adapter.d.ts +7 -11
  194. package/dist/tools/tool-adapter.d.ts.map +1 -1
  195. package/dist/tools/tool-adapter.js +187 -70
  196. package/dist/tools/tools.test.d.ts +2 -0
  197. package/dist/tools/tools.test.d.ts.map +1 -0
  198. package/dist/types.d.ts +108 -111
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/types.js +1 -0
  201. package/package.json +448 -90
  202. package/dist/_virtual/_rolldown/runtime.js +0 -8
  203. package/dist/agent/agent-factory.js.map +0 -1
  204. package/dist/agent/contract-spec-agent.js.map +0 -1
  205. package/dist/agent/json-runner.js.map +0 -1
  206. package/dist/agent/unified-agent.js.map +0 -1
  207. package/dist/approval/workflow.js.map +0 -1
  208. package/dist/exporters/claude-agent-exporter.js.map +0 -1
  209. package/dist/exporters/opencode-exporter.js.map +0 -1
  210. package/dist/interop/spec-consumer.js.map +0 -1
  211. package/dist/interop/tool-consumer.js.map +0 -1
  212. package/dist/knowledge/injector.js.map +0 -1
  213. package/dist/memory/in-memory.js.map +0 -1
  214. package/dist/memory/manager.js.map +0 -1
  215. package/dist/providers/claude-agent-sdk/adapter.js.map +0 -1
  216. package/dist/providers/claude-agent-sdk/session-bridge.js.map +0 -1
  217. package/dist/providers/claude-agent-sdk/tool-bridge.js.map +0 -1
  218. package/dist/providers/opencode-sdk/adapter.js.map +0 -1
  219. package/dist/providers/opencode-sdk/agent-bridge.js.map +0 -1
  220. package/dist/providers/opencode-sdk/tool-bridge.js.map +0 -1
  221. package/dist/providers/registry.js.map +0 -1
  222. package/dist/providers/types.js.map +0 -1
  223. package/dist/schema/json-schema-to-zod.js.map +0 -1
  224. package/dist/schema/schema-output.js.map +0 -1
  225. package/dist/session/store.js.map +0 -1
  226. package/dist/spec/registry.js.map +0 -1
  227. package/dist/spec/spec.js.map +0 -1
  228. package/dist/telemetry/adapter.js.map +0 -1
  229. package/dist/tools/knowledge-tool.js.map +0 -1
  230. package/dist/tools/mcp-client.js.map +0 -1
  231. package/dist/tools/mcp-server.js.map +0 -1
  232. package/dist/tools/tool-adapter.js.map +0 -1
@@ -0,0 +1,703 @@
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/knowledge/injector.ts
43
+ async function injectStaticKnowledge(instructions, knowledgeRefs, retriever) {
44
+ if (!retriever)
45
+ return instructions;
46
+ const requiredRefs = knowledgeRefs.filter((ref) => ref.required);
47
+ if (requiredRefs.length === 0)
48
+ return instructions;
49
+ const blocks = [];
50
+ for (const ref of requiredRefs) {
51
+ if (!retriever.supportsSpace(ref.key)) {
52
+ console.warn(`Required knowledge space "${ref.key}" is not available`);
53
+ continue;
54
+ }
55
+ try {
56
+ const content = await retriever.getStatic(ref.key);
57
+ if (content) {
58
+ const header = ref.instructions ? `## ${ref.key}
59
+ ${ref.instructions}` : `## ${ref.key}`;
60
+ blocks.push(`${header}
61
+
62
+ ${content}`);
63
+ }
64
+ } catch (error) {
65
+ console.warn(`Failed to load required knowledge "${ref.key}":`, error);
66
+ }
67
+ }
68
+ if (blocks.length === 0)
69
+ return instructions;
70
+ return `${instructions}
71
+
72
+ ---
73
+
74
+ # Reference Knowledge
75
+
76
+ The following information is provided for your reference. Use it to inform your responses.
77
+
78
+ ${blocks.join(`
79
+
80
+ ---
81
+
82
+ `)}`;
83
+ }
84
+ function createKnowledgeInjector(retriever) {
85
+ return {
86
+ inject: (instructions, knowledgeRefs) => injectStaticKnowledge(instructions, knowledgeRefs, retriever),
87
+ hasSpace: (spaceKey) => retriever?.supportsSpace(spaceKey) ?? false,
88
+ listSpaces: () => retriever?.listSpaces() ?? []
89
+ };
90
+ }
91
+
92
+ // src/providers/types.ts
93
+ var ExternalProviderError, ProviderNotAvailableError, ProviderExecutionError, ContextCreationError;
94
+ var init_types = __esm(() => {
95
+ ExternalProviderError = class ExternalProviderError extends Error {
96
+ provider;
97
+ code;
98
+ cause;
99
+ constructor(message, provider, code, cause) {
100
+ super(message);
101
+ this.provider = provider;
102
+ this.code = code;
103
+ this.cause = cause;
104
+ this.name = "ExternalProviderError";
105
+ }
106
+ };
107
+ ProviderNotAvailableError = class ProviderNotAvailableError extends ExternalProviderError {
108
+ constructor(provider, reason) {
109
+ super(`Provider '${provider}' is not available${reason ? `: ${reason}` : ""}`, provider, "PROVIDER_NOT_AVAILABLE");
110
+ this.name = "ProviderNotAvailableError";
111
+ }
112
+ };
113
+ ProviderExecutionError = class ProviderExecutionError extends ExternalProviderError {
114
+ constructor(provider, message, cause) {
115
+ super(message, provider, "EXECUTION_FAILED", cause);
116
+ this.name = "ProviderExecutionError";
117
+ }
118
+ };
119
+ ContextCreationError = class ContextCreationError extends ExternalProviderError {
120
+ constructor(provider, message, cause) {
121
+ super(message, provider, "CONTEXT_CREATION_FAILED", cause);
122
+ this.name = "ContextCreationError";
123
+ }
124
+ };
125
+ });
126
+
127
+ // src/providers/opencode-sdk/tool-bridge.ts
128
+ function specToolToOpenCodeTool(tool) {
129
+ return {
130
+ name: tool.name,
131
+ description: tool.description ?? `Execute ${tool.name}`,
132
+ parameters: normalizeToOpenCodeParameters(tool.schema),
133
+ permission: getPermissionLevel(tool)
134
+ };
135
+ }
136
+ function specToolsToOpenCodeTools(tools) {
137
+ return tools.map(specToolToOpenCodeTool);
138
+ }
139
+ function getPermissionLevel(tool) {
140
+ if (tool.requiresApproval) {
141
+ return "ask";
142
+ }
143
+ if (tool.automationSafe === false) {
144
+ return "ask";
145
+ }
146
+ return "allow";
147
+ }
148
+ function openCodeToolToSpecTool(openCodeTool) {
149
+ return {
150
+ name: openCodeTool.name,
151
+ description: openCodeTool.description,
152
+ schema: openCodeTool.parameters,
153
+ requiresApproval: openCodeTool.permission === "ask",
154
+ automationSafe: openCodeTool.permission === "allow"
155
+ };
156
+ }
157
+ function openCodeToolsToSpecTools(openCodeTools) {
158
+ return openCodeTools.map(openCodeToolToSpecTool);
159
+ }
160
+ function specToolToExternalToolForOpenCode(tool, handler, context) {
161
+ return {
162
+ name: tool.name,
163
+ description: tool.description ?? `Execute ${tool.name}`,
164
+ inputSchema: tool.schema ?? { type: "object" },
165
+ requiresApproval: tool.requiresApproval ?? !tool.automationSafe,
166
+ execute: handler ? async (input) => {
167
+ const fullContext = {
168
+ agentId: context?.agentId ?? "unknown",
169
+ sessionId: context?.sessionId ?? "unknown",
170
+ tenantId: context?.tenantId,
171
+ actorId: context?.actorId,
172
+ metadata: context?.metadata,
173
+ signal: context?.signal
174
+ };
175
+ return handler(input, fullContext);
176
+ } : undefined
177
+ };
178
+ }
179
+ function normalizeToOpenCodeParameters(schema) {
180
+ if (!schema) {
181
+ return { type: "object" };
182
+ }
183
+ if (schema.type === "object") {
184
+ return {
185
+ type: "object",
186
+ properties: schema.properties,
187
+ required: schema.required
188
+ };
189
+ }
190
+ return {
191
+ type: "object",
192
+ properties: {
193
+ value: convertToOpenCodeParameter(schema)
194
+ },
195
+ required: ["value"]
196
+ };
197
+ }
198
+ function convertToOpenCodeParameter(schema) {
199
+ const param = {
200
+ type: schema.type ?? "string"
201
+ };
202
+ if (schema.description) {
203
+ param.description = schema.description;
204
+ }
205
+ if (schema.enum) {
206
+ param.enum = schema.enum;
207
+ }
208
+ if (schema.default !== undefined) {
209
+ param.default = schema.default;
210
+ }
211
+ return param;
212
+ }
213
+ function createToolHandlerMap(tools) {
214
+ const handlers = new Map;
215
+ for (const [name, tool] of Object.entries(tools)) {
216
+ if (tool.execute) {
217
+ handlers.set(name, tool.execute);
218
+ }
219
+ }
220
+ return handlers;
221
+ }
222
+ async function executeToolCall(toolCall, handlers) {
223
+ const handler = handlers.get(toolCall.name);
224
+ if (!handler) {
225
+ return {
226
+ tool_call_id: toolCall.id,
227
+ output: `Error: Tool '${toolCall.name}' not found`,
228
+ is_error: true
229
+ };
230
+ }
231
+ try {
232
+ const result = await handler(toolCall.arguments);
233
+ return {
234
+ tool_call_id: toolCall.id,
235
+ output: typeof result === "string" ? result : JSON.stringify(result)
236
+ };
237
+ } catch (error) {
238
+ return {
239
+ tool_call_id: toolCall.id,
240
+ output: `Error: ${error instanceof Error ? error.message : String(error)}`,
241
+ is_error: true
242
+ };
243
+ }
244
+ }
245
+
246
+ // src/providers/opencode-sdk/agent-bridge.ts
247
+ function inferAgentType(spec) {
248
+ const hasCodeTools = spec.tools.some((tool) => [
249
+ "write_file",
250
+ "edit_file",
251
+ "create_file",
252
+ "delete_file",
253
+ "bash",
254
+ "execute",
255
+ "run_command",
256
+ "terminal"
257
+ ].includes(tool.name.toLowerCase()));
258
+ const instructionsLower = spec.instructions.toLowerCase();
259
+ const hasPlanningKeywords = /\b(plan|design|architect|strategy|analyze|review|assess|evaluate)\b/.test(instructionsLower);
260
+ const hasExplorationKeywords = /\b(search|find|explore|discover|locate|grep|pattern)\b/.test(instructionsLower);
261
+ const hasResearchKeywords = /\b(research|investigate|understand|learn|gather|collect)\b/.test(instructionsLower);
262
+ if (hasCodeTools) {
263
+ return "build";
264
+ }
265
+ if (hasPlanningKeywords && !hasCodeTools) {
266
+ return "plan";
267
+ }
268
+ if (hasExplorationKeywords && !hasResearchKeywords) {
269
+ return "explore";
270
+ }
271
+ return "general";
272
+ }
273
+ function specToOpenCodeConfig(spec, options) {
274
+ const agentType = options?.agentType ?? inferAgentType(spec);
275
+ return {
276
+ name: spec.meta.key,
277
+ version: spec.meta.version,
278
+ description: spec.description ?? spec.meta.description,
279
+ instructions: spec.instructions,
280
+ agent_type: agentType,
281
+ tools: specToolsToOpenCodeTools(spec.tools),
282
+ config: {
283
+ max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
284
+ temperature: options?.temperature ?? 0.7,
285
+ model: options?.model,
286
+ permissions: buildPermissions(spec)
287
+ }
288
+ };
289
+ }
290
+ function buildPermissions(spec) {
291
+ const permissions = {};
292
+ for (const tool of spec.tools) {
293
+ if (tool.requiresApproval) {
294
+ permissions[tool.name] = "ask";
295
+ } else if (tool.automationSafe === false) {
296
+ permissions[tool.name] = "ask";
297
+ } else {
298
+ permissions[tool.name] = "allow";
299
+ }
300
+ }
301
+ return permissions;
302
+ }
303
+ function specToOpenCodeMarkdown(spec, options) {
304
+ const agentType = options?.agentType ?? inferAgentType(spec);
305
+ return {
306
+ frontmatter: {
307
+ name: spec.meta.key,
308
+ type: agentType,
309
+ version: spec.meta.version,
310
+ model: options?.model,
311
+ temperature: options?.temperature ?? 0.7,
312
+ max_steps: options?.maxSteps ?? spec.maxSteps ?? 10,
313
+ tools: spec.tools.map((t) => t.name)
314
+ },
315
+ body: buildMarkdownBody(spec)
316
+ };
317
+ }
318
+ function buildMarkdownBody(spec) {
319
+ const lines = [];
320
+ lines.push(`# ${spec.meta.key}`);
321
+ lines.push("");
322
+ if (spec.description ?? spec.meta.description) {
323
+ lines.push(spec.description ?? spec.meta.description ?? "");
324
+ lines.push("");
325
+ }
326
+ lines.push("## Instructions");
327
+ lines.push("");
328
+ lines.push(spec.instructions);
329
+ lines.push("");
330
+ if (spec.tools.length > 0) {
331
+ lines.push("## Tools");
332
+ lines.push("");
333
+ for (const tool of spec.tools) {
334
+ const permission = tool.requiresApproval ? "(requires approval)" : tool.automationSafe === false ? "(ask mode)" : "";
335
+ lines.push(`- **${tool.name}**: ${tool.description ?? "No description"} ${permission}`.trim());
336
+ }
337
+ lines.push("");
338
+ }
339
+ if (spec.knowledge && spec.knowledge.length > 0) {
340
+ lines.push("## Knowledge Sources");
341
+ lines.push("");
342
+ for (const k of spec.knowledge) {
343
+ const required = k.required ? "(required)" : "(optional)";
344
+ lines.push(`- ${k.key} ${required}`);
345
+ }
346
+ lines.push("");
347
+ }
348
+ return lines.join(`
349
+ `);
350
+ }
351
+ function serializeOpenCodeMarkdown(markdown) {
352
+ const lines = [];
353
+ lines.push("---");
354
+ lines.push(`name: ${markdown.frontmatter.name}`);
355
+ lines.push(`type: ${markdown.frontmatter.type}`);
356
+ if (markdown.frontmatter.version) {
357
+ lines.push(`version: ${markdown.frontmatter.version}`);
358
+ }
359
+ if (markdown.frontmatter.model) {
360
+ lines.push(`model: ${markdown.frontmatter.model}`);
361
+ }
362
+ if (markdown.frontmatter.temperature !== undefined) {
363
+ lines.push(`temperature: ${markdown.frontmatter.temperature}`);
364
+ }
365
+ if (markdown.frontmatter.max_steps !== undefined) {
366
+ lines.push(`max_steps: ${markdown.frontmatter.max_steps}`);
367
+ }
368
+ if (markdown.frontmatter.tools && markdown.frontmatter.tools.length > 0) {
369
+ lines.push(`tools:`);
370
+ for (const tool of markdown.frontmatter.tools) {
371
+ lines.push(` - ${tool}`);
372
+ }
373
+ }
374
+ lines.push("---");
375
+ lines.push("");
376
+ lines.push(markdown.body);
377
+ return lines.join(`
378
+ `);
379
+ }
380
+ function openCodeConfigToSpec(config) {
381
+ return {
382
+ meta: {
383
+ key: config.name,
384
+ version: config.version ?? "1.0.0",
385
+ description: config.description ?? "",
386
+ stability: "experimental",
387
+ owners: [],
388
+ tags: []
389
+ },
390
+ description: config.description,
391
+ instructions: config.instructions ?? "",
392
+ tools: config.tools?.map((tool) => ({
393
+ name: tool.name,
394
+ description: tool.description,
395
+ schema: tool.parameters,
396
+ requiresApproval: tool.permission === "ask",
397
+ automationSafe: tool.permission === "allow"
398
+ })) ?? [],
399
+ maxSteps: config.config?.max_steps ?? 10
400
+ };
401
+ }
402
+ var init_agent_bridge = () => {};
403
+
404
+ // src/providers/opencode-sdk/adapter.ts
405
+ class OpenCodeSDKProvider {
406
+ name = "opencode-sdk";
407
+ version = "1.0.0";
408
+ config;
409
+ sdkAvailable = null;
410
+ constructor(config = {}) {
411
+ this.config = {
412
+ serverUrl: "http://127.0.0.1:4096",
413
+ port: 4096,
414
+ agentType: "general",
415
+ temperature: 0.7,
416
+ timeout: 30000,
417
+ ...config
418
+ };
419
+ if (!config.serverUrl && config.port) {
420
+ this.config.serverUrl = `http://127.0.0.1:${config.port}`;
421
+ }
422
+ }
423
+ isAvailable() {
424
+ if (this.sdkAvailable !== null) {
425
+ return this.sdkAvailable;
426
+ }
427
+ try {
428
+ __require.resolve("@opencode-ai/sdk");
429
+ this.sdkAvailable = true;
430
+ } catch {
431
+ this.sdkAvailable = false;
432
+ }
433
+ return this.sdkAvailable;
434
+ }
435
+ async createContext(spec) {
436
+ if (!this.isAvailable()) {
437
+ throw new ProviderNotAvailableError(this.name, "SDK not installed");
438
+ }
439
+ try {
440
+ const sdk = await this.loadSDK();
441
+ const { client } = await sdk.createOpencode({
442
+ hostname: this.getHostname(),
443
+ port: this.config.port ?? 4096,
444
+ timeout: this.config.timeout
445
+ });
446
+ const session = await client.session.create({
447
+ agent: this.config.agentType ?? inferAgentType(spec),
448
+ model: this.config.model
449
+ });
450
+ const toolSet = {};
451
+ for (const tool of spec.tools) {
452
+ toolSet[tool.name] = specToolToExternalToolForOpenCode(tool);
453
+ }
454
+ const instructions = await injectStaticKnowledge(spec.instructions, spec.knowledge ?? [], undefined);
455
+ const contextId = `opencode-${agentKey(spec.meta)}-${Date.now()}`;
456
+ const metadata = {
457
+ sessionId: session.id,
458
+ agentType: this.config.agentType ?? inferAgentType(spec),
459
+ serverUrl: this.config.serverUrl ?? `http://127.0.0.1:${this.config.port ?? 4096}`
460
+ };
461
+ return {
462
+ id: contextId,
463
+ spec: {
464
+ ...spec,
465
+ instructions
466
+ },
467
+ tools: toolSet,
468
+ metadata,
469
+ cleanup: async () => {
470
+ try {
471
+ await client.session.delete({ id: session.id });
472
+ } catch {}
473
+ }
474
+ };
475
+ } catch (error) {
476
+ throw new ContextCreationError(this.name, `Failed to create context: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
477
+ }
478
+ }
479
+ async execute(context, params) {
480
+ try {
481
+ const sdk = await this.loadSDK();
482
+ const metadata = context.metadata;
483
+ const { client } = await sdk.createOpencodeClient({
484
+ baseUrl: metadata.serverUrl
485
+ });
486
+ const systemPrompt = params.systemOverride ? `${context.spec.instructions}
487
+
488
+ ${params.systemOverride}` : context.spec.instructions;
489
+ const response = await client.session.prompt({
490
+ id: metadata.sessionId,
491
+ body: {
492
+ content: params.prompt,
493
+ system: systemPrompt
494
+ }
495
+ });
496
+ const toolCalls = this.extractToolCalls(response);
497
+ const toolHandlers = createToolHandlerMap(context.tools);
498
+ const toolResults = await Promise.all(toolCalls.map((tc) => executeToolCall(tc, toolHandlers)));
499
+ return {
500
+ text: this.extractTextContent(response),
501
+ toolCalls: toolCalls.map((tc) => ({
502
+ type: "tool-call",
503
+ toolCallId: tc.id,
504
+ toolName: tc.name,
505
+ args: tc.arguments
506
+ })),
507
+ toolResults: toolResults.map((tr) => ({
508
+ type: "tool-result",
509
+ toolCallId: tr.tool_call_id,
510
+ toolName: toolCalls.find((tc) => tc.id === tr.tool_call_id)?.name ?? "",
511
+ output: tr.output
512
+ })),
513
+ usage: {
514
+ inputTokens: response.usage?.input_tokens ?? 0,
515
+ outputTokens: response.usage?.output_tokens ?? 0
516
+ },
517
+ finishReason: this.mapFinishReason(response.finish_reason),
518
+ metadata: {
519
+ sessionId: metadata.sessionId,
520
+ agentType: metadata.agentType
521
+ }
522
+ };
523
+ } catch (error) {
524
+ throw new ProviderExecutionError(this.name, `Execution failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
525
+ }
526
+ }
527
+ async* stream(context, params) {
528
+ try {
529
+ const sdk = await this.loadSDK();
530
+ const metadata = context.metadata;
531
+ const { client } = await sdk.createOpencodeClient({
532
+ baseUrl: metadata.serverUrl
533
+ });
534
+ const systemPrompt = params.systemOverride ? `${context.spec.instructions}
535
+
536
+ ${params.systemOverride}` : context.spec.instructions;
537
+ const events = client.session.subscribe({
538
+ id: metadata.sessionId
539
+ });
540
+ await client.session.prompt({
541
+ id: metadata.sessionId,
542
+ body: {
543
+ content: params.prompt,
544
+ system: systemPrompt
545
+ }
546
+ });
547
+ let fullText = "";
548
+ const allToolCalls = [];
549
+ const toolHandlers = createToolHandlerMap(context.tools);
550
+ let stepIndex = 0;
551
+ for await (const event of events) {
552
+ if (event.type === "message.delta") {
553
+ const text = event.delta?.content ?? "";
554
+ fullText += text;
555
+ yield { type: "text", text };
556
+ }
557
+ if (event.type === "tool.call") {
558
+ const toolCall = {
559
+ id: event.tool_call_id ?? `tc-${Date.now()}`,
560
+ name: event.tool_name ?? "",
561
+ arguments: event.arguments ?? {}
562
+ };
563
+ allToolCalls.push(toolCall);
564
+ yield {
565
+ type: "tool-call",
566
+ toolCall: {
567
+ type: "tool-call",
568
+ toolCallId: toolCall.id,
569
+ toolName: toolCall.name,
570
+ args: toolCall.arguments
571
+ }
572
+ };
573
+ }
574
+ if (event.type === "step.complete") {
575
+ stepIndex++;
576
+ yield { type: "step-complete", stepIndex };
577
+ }
578
+ if (event.type === "message.complete") {
579
+ break;
580
+ }
581
+ }
582
+ for (const toolCall of allToolCalls) {
583
+ const result = await executeToolCall(toolCall, toolHandlers);
584
+ yield {
585
+ type: "tool-result",
586
+ toolResult: {
587
+ type: "tool-result",
588
+ toolCallId: result.tool_call_id,
589
+ toolName: toolCall.name,
590
+ output: result.output
591
+ }
592
+ };
593
+ }
594
+ yield {
595
+ type: "done",
596
+ result: {
597
+ text: fullText,
598
+ toolCalls: allToolCalls.map((tc) => ({
599
+ type: "tool-call",
600
+ toolCallId: tc.id,
601
+ toolName: tc.name,
602
+ args: tc.arguments
603
+ })),
604
+ toolResults: [],
605
+ usage: { inputTokens: 0, outputTokens: 0 },
606
+ finishReason: "stop"
607
+ }
608
+ };
609
+ } catch (error) {
610
+ throw new ProviderExecutionError(this.name, `Stream failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : undefined);
611
+ }
612
+ }
613
+ async loadSDK() {
614
+ try {
615
+ const module = __require("@opencode-ai/sdk");
616
+ return module;
617
+ } catch {
618
+ throw new ProviderNotAvailableError(this.name, "@opencode-ai/sdk is not installed");
619
+ }
620
+ }
621
+ getHostname() {
622
+ if (!this.config.serverUrl) {
623
+ return "127.0.0.1";
624
+ }
625
+ try {
626
+ const url = new URL(this.config.serverUrl);
627
+ return url.hostname;
628
+ } catch {
629
+ return "127.0.0.1";
630
+ }
631
+ }
632
+ extractToolCalls(response) {
633
+ if (!response.tool_calls) {
634
+ return [];
635
+ }
636
+ return response.tool_calls.map((tc) => ({
637
+ id: tc.id,
638
+ name: tc.name,
639
+ arguments: tc.arguments ?? {}
640
+ }));
641
+ }
642
+ extractTextContent(response) {
643
+ return response.content ?? response.message?.content ?? "";
644
+ }
645
+ mapFinishReason(finishReason) {
646
+ switch (finishReason) {
647
+ case "stop":
648
+ case "end":
649
+ return "stop";
650
+ case "tool_use":
651
+ case "tool_calls":
652
+ return "tool-calls";
653
+ case "length":
654
+ case "max_tokens":
655
+ return "length";
656
+ default:
657
+ return "stop";
658
+ }
659
+ }
660
+ }
661
+ var init_adapter = __esm(() => {
662
+ init_types();
663
+ init_agent_bridge();
664
+ });
665
+
666
+ // src/providers/opencode-sdk/index.ts
667
+ var exports_opencode_sdk = {};
668
+ __export(exports_opencode_sdk, {
669
+ specToolsToOpenCodeTools: () => specToolsToOpenCodeTools,
670
+ specToolToOpenCodeTool: () => specToolToOpenCodeTool,
671
+ specToolToExternalToolForOpenCode: () => specToolToExternalToolForOpenCode,
672
+ specToOpenCodeMarkdown: () => specToOpenCodeMarkdown,
673
+ specToOpenCodeConfig: () => specToOpenCodeConfig,
674
+ serializeOpenCodeMarkdown: () => serializeOpenCodeMarkdown,
675
+ openCodeToolsToSpecTools: () => openCodeToolsToSpecTools,
676
+ openCodeToolToSpecTool: () => openCodeToolToSpecTool,
677
+ openCodeConfigToSpec: () => openCodeConfigToSpec,
678
+ inferAgentType: () => inferAgentType,
679
+ executeToolCall: () => executeToolCall,
680
+ createToolHandlerMap: () => createToolHandlerMap,
681
+ OpenCodeSDKProvider: () => OpenCodeSDKProvider
682
+ });
683
+ var init_opencode_sdk = __esm(() => {
684
+ init_adapter();
685
+ init_agent_bridge();
686
+ });
687
+ init_opencode_sdk();
688
+
689
+ export {
690
+ specToolsToOpenCodeTools,
691
+ specToolToOpenCodeTool,
692
+ specToolToExternalToolForOpenCode,
693
+ specToOpenCodeMarkdown,
694
+ specToOpenCodeConfig,
695
+ serializeOpenCodeMarkdown,
696
+ openCodeToolsToSpecTools,
697
+ openCodeToolToSpecTool,
698
+ openCodeConfigToSpec,
699
+ inferAgentType,
700
+ executeToolCall,
701
+ createToolHandlerMap,
702
+ OpenCodeSDKProvider
703
+ };