@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
@@ -1,103 +1,661 @@
1
- import { ContractSpecAgent } from "./contract-spec-agent.js";
2
-
3
- //#region src/agent/agent-factory.ts
4
- /**
5
- * Factory for creating ContractSpec agents from specs.
6
- *
7
- * Provides a centralized way to instantiate agents with
8
- * consistent configuration.
9
- *
10
- * @example
11
- * ```typescript
12
- * const factory = createAgentFactory({
13
- * defaultModel: mistral('mistral-large-latest'),
14
- * registry: agentRegistry,
15
- * toolHandlers: globalToolHandlers,
16
- * sessionStore: mySessionStore,
17
- * });
18
- *
19
- * const agent = await factory.create('support.bot');
20
- * const result = await agent.generate({ prompt: 'Help me with...' });
21
- * ```
22
- */
23
- var AgentFactory = class {
24
- config;
25
- cache = /* @__PURE__ */ new Map();
26
- constructor(config) {
27
- this.config = config;
28
- }
29
- /**
30
- * Create an agent by name.
31
- *
32
- * @param name - Agent name (e.g., "support.bot")
33
- * @param version - Optional specific version
34
- * @param options - Optional creation options
35
- */
36
- async create(name, version, options) {
37
- const spec = this.config.registry.require(name, version);
38
- return this.createFromSpec(spec, options);
39
- }
40
- /**
41
- * Create an agent from a spec directly.
42
- *
43
- * @param spec - Agent specification
44
- * @param options - Optional creation options
45
- */
46
- async createFromSpec(spec, options) {
47
- const mergedHandlers = new Map(this.config.toolHandlers);
48
- if (options?.toolHandlers) for (const [key, handler] of options.toolHandlers) mergedHandlers.set(key, handler);
49
- const mergedTools = {
50
- ...this.config.additionalTools,
51
- ...options?.additionalTools
52
- };
53
- return ContractSpecAgent.create({
54
- spec,
55
- model: options?.model ?? this.config.defaultModel,
56
- toolHandlers: mergedHandlers,
57
- knowledgeRetriever: this.config.knowledgeRetriever,
58
- sessionStore: this.config.sessionStore,
59
- telemetryCollector: this.config.telemetryCollector,
60
- additionalTools: mergedTools
61
- });
62
- }
63
- /**
64
- * Get or create a cached agent instance.
65
- *
66
- * Use this when you want to reuse agent instances.
67
- *
68
- * @param name - Agent name
69
- * @param version - Optional specific version
70
- */
71
- async getOrCreate(name, version) {
72
- const spec = this.config.registry.require(name, version);
73
- const cacheKey = `${spec.meta.key}.v${spec.meta.version}`;
74
- let agent = this.cache.get(cacheKey);
75
- if (!agent) {
76
- agent = await this.createFromSpec(spec);
77
- this.cache.set(cacheKey, agent);
78
- }
79
- return agent;
80
- }
81
- /**
82
- * Clear the agent cache.
83
- */
84
- clearCache() {
85
- this.cache.clear();
86
- }
87
- /**
88
- * List all available agent names.
89
- */
90
- listAvailable() {
91
- return this.config.registry.listNames();
92
- }
1
+ // @bun
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
+ });
93
11
  };
94
- /**
95
- * Create an agent factory.
96
- */
97
- function createAgentFactory(config) {
98
- return new AgentFactory(config);
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = import.meta.require;
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
+ }
99
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}
100
527
 
101
- //#endregion
102
- export { AgentFactory, createAgentFactory };
103
- //# sourceMappingURL=agent-factory.js.map
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/agent/agent-factory.ts
605
+ init_contract_spec_agent();
606
+
607
+ class AgentFactory {
608
+ config;
609
+ cache = new Map;
610
+ constructor(config) {
611
+ this.config = config;
612
+ }
613
+ async create(name, version, options) {
614
+ const spec = this.config.registry.require(name, version);
615
+ return this.createFromSpec(spec, options);
616
+ }
617
+ async createFromSpec(spec, options) {
618
+ const mergedHandlers = new Map(this.config.toolHandlers);
619
+ if (options?.toolHandlers) {
620
+ for (const [key, handler] of options.toolHandlers) {
621
+ mergedHandlers.set(key, handler);
622
+ }
623
+ }
624
+ const mergedTools = {
625
+ ...this.config.additionalTools,
626
+ ...options?.additionalTools
627
+ };
628
+ return ContractSpecAgent.create({
629
+ spec,
630
+ model: options?.model ?? this.config.defaultModel,
631
+ toolHandlers: mergedHandlers,
632
+ knowledgeRetriever: this.config.knowledgeRetriever,
633
+ sessionStore: this.config.sessionStore,
634
+ telemetryCollector: this.config.telemetryCollector,
635
+ additionalTools: mergedTools
636
+ });
637
+ }
638
+ async getOrCreate(name, version) {
639
+ const spec = this.config.registry.require(name, version);
640
+ const cacheKey = `${spec.meta.key}.v${spec.meta.version}`;
641
+ let agent = this.cache.get(cacheKey);
642
+ if (!agent) {
643
+ agent = await this.createFromSpec(spec);
644
+ this.cache.set(cacheKey, agent);
645
+ }
646
+ return agent;
647
+ }
648
+ clearCache() {
649
+ this.cache.clear();
650
+ }
651
+ listAvailable() {
652
+ return this.config.registry.listNames();
653
+ }
654
+ }
655
+ function createAgentFactory(config) {
656
+ return new AgentFactory(config);
657
+ }
658
+ export {
659
+ createAgentFactory,
660
+ AgentFactory
661
+ };