@kraken-ai/platform 0.0.1 → 0.0.2

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/server.js CHANGED
@@ -1,7 +1,456 @@
1
1
  import {
2
- startConnectorServer
3
- } from "./chunk-HGJSK6MW.js";
2
+ ENTITY_NAME_REGEX,
3
+ buildActionOutputSchema,
4
+ cyan,
5
+ dim,
6
+ green,
7
+ isValidEntityName,
8
+ startConnectorServer,
9
+ wrapToolError,
10
+ wrapToolResult,
11
+ yellow
12
+ } from "./chunk-PPT6GGYL.js";
13
+
14
+ // src/dev.ts
15
+ import { readFileSync } from "fs";
16
+ import { createInterface } from "readline";
17
+ import { Agent } from "kraken-ai";
18
+
19
+ // src/dev-actions.ts
20
+ var buildActionInstructions = (zodSchemas) => {
21
+ const entries = Object.entries(zodSchemas);
22
+ if (entries.length === 0) return "";
23
+ const variants = entries.map(([name, schema]) => {
24
+ const fields = Object.keys(schema.shape).join(", ");
25
+ return ` - "${name}": { ${fields} }`;
26
+ });
27
+ return [
28
+ 'You MUST respond with a JSON object containing an "action" field set to one of the following action names, plus the fields for that action:',
29
+ "",
30
+ ...variants,
31
+ "",
32
+ 'Example: { "action": "<name>", ...fields }'
33
+ ].join("\n");
34
+ };
35
+ var dispatchDevAction = async (output, zodSchemas, handlers, webhooks) => {
36
+ if (output == null || typeof output !== "object" || !("action" in output)) {
37
+ throw new Error('Action output must contain an "action" field');
38
+ }
39
+ const { action: actionName, ...rest } = output;
40
+ if (typeof actionName !== "string") {
41
+ throw new Error('Action output "action" field must be a string');
42
+ }
43
+ const schema = zodSchemas[actionName];
44
+ if (!schema) {
45
+ throw new Error(
46
+ `Unknown action "${actionName}". Expected one of: ${Object.keys(zodSchemas).join(", ")}`
47
+ );
48
+ }
49
+ const parsed = schema.parse(rest);
50
+ const payload = parsed;
51
+ let handlerCalled = false;
52
+ const handler = handlers?.[actionName];
53
+ if (handler) {
54
+ await handler(payload);
55
+ handlerCalled = true;
56
+ }
57
+ return {
58
+ actionName,
59
+ payload,
60
+ handlerCalled,
61
+ webhookUrl: webhooks[actionName]
62
+ };
63
+ };
64
+
65
+ // src/dev-connectors.ts
66
+ import { resolve } from "path";
67
+ import { tool } from "kraken-ai";
68
+ var isPlatformConnector = (v) => v != null && typeof v === "object" && v.__type === "PlatformConnector";
69
+ var importConnector = async (name, projectRoot) => {
70
+ const basePath = resolve(projectRoot, "connectors", name, "index");
71
+ for (const ext of [".ts", ".js"]) {
72
+ try {
73
+ const mod = await import(`${basePath}${ext}`);
74
+ const connector = mod.default;
75
+ if (!isPlatformConnector(connector)) {
76
+ console.warn(`[connector:${name}] Default export is not a PlatformConnector \u2014 skipping`);
77
+ return null;
78
+ }
79
+ return connector;
80
+ } catch (err) {
81
+ if (ext === ".ts") continue;
82
+ const message = err instanceof Error ? err.message : String(err);
83
+ console.warn(`[connector:${name}] Failed to import \u2014 skipping. Error: ${message}`);
84
+ return null;
85
+ }
86
+ }
87
+ return null;
88
+ };
89
+ var createToolsFromConnector = (connector) => {
90
+ const tools = connector.tools ?? {};
91
+ return Object.entries(tools).map(
92
+ ([name, def]) => tool({
93
+ name,
94
+ description: def.description,
95
+ parameters: def.input,
96
+ execute: async (args) => {
97
+ try {
98
+ const result = await Promise.resolve(def.handler(args));
99
+ return wrapToolResult(result);
100
+ } catch (error) {
101
+ return wrapToolError(error);
102
+ }
103
+ }
104
+ })
105
+ );
106
+ };
107
+ var buildConnectorTools = (connectors) => {
108
+ const toolOwners = /* @__PURE__ */ new Map();
109
+ for (const { name, connector } of connectors) {
110
+ for (const toolName of Object.keys(connector.tools ?? {})) {
111
+ const existing = toolOwners.get(toolName);
112
+ if (existing) {
113
+ throw new Error(
114
+ `Tool name collision: "${toolName}" is defined by both connectors "${existing}" and "${name}". Rename one of the tools or use a unique prefix.`
115
+ );
116
+ }
117
+ toolOwners.set(toolName, name);
118
+ }
119
+ }
120
+ const resourceOwners = /* @__PURE__ */ new Map();
121
+ for (const { name, connector } of connectors) {
122
+ for (const resourceName of Object.keys(connector.resources ?? {})) {
123
+ const existing = resourceOwners.get(resourceName);
124
+ if (existing) {
125
+ throw new Error(
126
+ `Resource name collision: "${resourceName}" is defined by both connectors "${existing}" and "${name}". Rename one of the resources or use a unique prefix.`
127
+ );
128
+ }
129
+ resourceOwners.set(resourceName, name);
130
+ }
131
+ }
132
+ const promptOwners = /* @__PURE__ */ new Map();
133
+ for (const { name, connector } of connectors) {
134
+ for (const promptName of Object.keys(connector.prompts ?? {})) {
135
+ const existing = promptOwners.get(promptName);
136
+ if (existing) {
137
+ throw new Error(
138
+ `Prompt name collision: "${promptName}" is defined by both connectors "${existing}" and "${name}". Rename one of the prompts or use a unique prefix.`
139
+ );
140
+ }
141
+ promptOwners.set(promptName, name);
142
+ }
143
+ }
144
+ const allTools = [];
145
+ const allResources = [];
146
+ const allPrompts = [];
147
+ const allInstructions = [];
148
+ for (const { name, connector } of connectors) {
149
+ const tools = createToolsFromConnector(connector);
150
+ allTools.push(...tools);
151
+ for (const [resName, resDef] of Object.entries(connector.resources ?? {})) {
152
+ allResources.push({
153
+ name: resName,
154
+ uri: resDef.uri,
155
+ description: resDef.description,
156
+ mimeType: resDef.mimeType,
157
+ read: (ctx) => resDef.read(ctx)
158
+ });
159
+ }
160
+ for (const [promptName, promptDef] of Object.entries(connector.prompts ?? {})) {
161
+ allPrompts.push({
162
+ name: promptName,
163
+ description: promptDef.description,
164
+ arguments: promptDef.arguments,
165
+ get: (args, ctx) => promptDef.get(args, ctx)
166
+ });
167
+ }
168
+ const toolCount = Object.keys(connector.tools ?? {}).length;
169
+ const resourceCount = Object.keys(connector.resources ?? {}).length;
170
+ const promptCount = Object.keys(connector.prompts ?? {}).length;
171
+ const parts = [
172
+ `${toolCount} tool${toolCount !== 1 ? "s" : ""}`,
173
+ `${resourceCount} resource${resourceCount !== 1 ? "s" : ""}`,
174
+ `${promptCount} prompt${promptCount !== 1 ? "s" : ""}`
175
+ ];
176
+ console.log(` Connector: ${name} (${parts.join(", ")})`);
177
+ if (connector.instructions) {
178
+ allInstructions.push(connector.instructions);
179
+ }
180
+ }
181
+ return {
182
+ tools: allTools,
183
+ resources: allResources,
184
+ prompts: allPrompts,
185
+ instructions: allInstructions
186
+ };
187
+ };
188
+ var loadConnectorTools = async (connectorNames, projectRoot) => {
189
+ if (connectorNames.length === 0) {
190
+ return { tools: [], resources: [], prompts: [], instructions: [] };
191
+ }
192
+ const root = projectRoot ?? process.cwd();
193
+ const connectors = [];
194
+ for (const name of connectorNames) {
195
+ if (!isValidEntityName(name)) {
196
+ console.warn(
197
+ `[connector] Invalid connector name "${name}" \u2014 must match ${ENTITY_NAME_REGEX}. Skipping.`
198
+ );
199
+ continue;
200
+ }
201
+ const connector = await importConnector(name, root);
202
+ if (connector) {
203
+ connectors.push({ name, connector });
204
+ }
205
+ }
206
+ return buildConnectorTools(connectors);
207
+ };
208
+
209
+ // src/dev.ts
210
+ var loadDotenv = () => {
211
+ try {
212
+ const content = readFileSync(".env", "utf-8");
213
+ for (const line of content.split("\n")) {
214
+ const trimmed = line.trim();
215
+ if (!trimmed || trimmed.startsWith("#")) continue;
216
+ const eqIdx = trimmed.indexOf("=");
217
+ if (eqIdx === -1) continue;
218
+ const key = trimmed.slice(0, eqIdx).trim();
219
+ const value = trimmed.slice(eqIdx + 1).trim();
220
+ if (!process.env[key]) {
221
+ process.env[key] = value;
222
+ }
223
+ }
224
+ } catch {
225
+ }
226
+ };
227
+ var FRONTMATTER_RE = /^---\n[\s\S]*?\n---\n([\s\S]*)$/;
228
+ var resolveSkillContent = (refs) => refs.map((ref) => {
229
+ try {
230
+ return readFileSync(`skills/${ref}`, "utf-8");
231
+ } catch {
232
+ return ref;
233
+ }
234
+ });
235
+ var buildInstructions = (base, skillContent) => {
236
+ if (skillContent.length === 0) return base;
237
+ const bodies = skillContent.map((s) => {
238
+ const m = FRONTMATTER_RE.exec(s);
239
+ return m?.[1]?.trim() ?? s;
240
+ });
241
+ return `${base}
242
+
243
+ ${bodies.join("\n\n")}`;
244
+ };
245
+ var buildDevAgent = async (pa) => {
246
+ const {
247
+ name,
248
+ model,
249
+ instructions,
250
+ skills,
251
+ temperature,
252
+ thinkingLevel,
253
+ maxOutputTokens,
254
+ logLevel
255
+ } = pa.config.agent;
256
+ const connectorNames = pa.config.connectors ?? [];
257
+ const { tools: connectorTools, instructions: connectorInstructions } = await loadConnectorTools(connectorNames);
258
+ const skillContent = resolveSkillContent(skills ?? []);
259
+ let fullInstructions = buildInstructions(instructions, skillContent);
260
+ if (connectorInstructions.length > 0) {
261
+ fullInstructions = `${fullInstructions}
262
+
263
+ ${connectorInstructions.join("\n\n")}`;
264
+ }
265
+ let outputSchema;
266
+ if (pa.actionZodSchemas && Object.keys(pa.actionZodSchemas).length > 0) {
267
+ const actionInstructions = buildActionInstructions(pa.actionZodSchemas);
268
+ if (actionInstructions) {
269
+ fullInstructions = `${fullInstructions}
270
+
271
+ ${actionInstructions}`;
272
+ }
273
+ outputSchema = buildActionOutputSchema({
274
+ __type: "PlatformActions",
275
+ config: pa.config.actions ?? { variants: {} },
276
+ zodSchemas: pa.actionZodSchemas,
277
+ handlers: pa.actionHandlers ?? {}
278
+ });
279
+ }
280
+ let team;
281
+ if (pa.teamAgents && pa.teamAgents.length > 0) {
282
+ team = await Promise.all(pa.teamAgents.map(buildDevAgent));
283
+ }
284
+ return new Agent({
285
+ name,
286
+ model,
287
+ instructions: fullInstructions,
288
+ tools: connectorTools.length > 0 ? connectorTools : void 0,
289
+ outputSchema,
290
+ team,
291
+ temperature,
292
+ thinkingLevel,
293
+ maxOutputTokens,
294
+ logLevel
295
+ });
296
+ };
297
+ var runDev = async (agent) => {
298
+ loadDotenv();
299
+ const hasActions = agent.actionZodSchemas && Object.keys(agent.actionZodSchemas).length > 0;
300
+ const sdkAgent = await buildDevAgent(agent);
301
+ const { name, model } = agent.config.agent;
302
+ const connectorNames = agent.config.connectors ?? [];
303
+ try {
304
+ await sdkAgent.preflight();
305
+ } catch (err) {
306
+ console.error(`
307
+ ${err instanceof Error ? err.message : String(err)}
308
+ `);
309
+ process.exit(1);
310
+ }
311
+ console.log(`
312
+ Agent: ${name}`);
313
+ console.log(` Model: ${model}`);
314
+ if (connectorNames.length > 0) {
315
+ console.log(` Connectors: ${connectorNames.join(", ")}`);
316
+ }
317
+ if (agent.teamAgents && agent.teamAgents.length > 0) {
318
+ console.log(` Team: ${agent.teamAgents.map((a) => a.config.agent.name).join(", ")}`);
319
+ }
320
+ if (hasActions && agent.actionZodSchemas) {
321
+ console.log(` Actions: ${Object.keys(agent.actionZodSchemas).join(", ")}`);
322
+ }
323
+ console.log(`
324
+ Type a message to start. Ctrl+C to exit.
325
+ `);
326
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
327
+ const messages = [];
328
+ const cleanup = () => {
329
+ rl.close();
330
+ process.exit(0);
331
+ };
332
+ process.on("SIGINT", cleanup);
333
+ process.on("SIGTERM", cleanup);
334
+ const ask = () => {
335
+ rl.question("You: ", (input) => {
336
+ if (!input.trim()) {
337
+ ask();
338
+ return;
339
+ }
340
+ messages.push({ role: "user", content: input });
341
+ void (async () => {
342
+ try {
343
+ const result = await sdkAgent.run(messages, {
344
+ onEvent: (event) => {
345
+ if (event.type === "thought") {
346
+ console.log(
347
+ ` [thinking] ${event.text.slice(0, 120)}${event.text.length > 120 ? "\u2026" : ""}`
348
+ );
349
+ }
350
+ if (event.type === "tool_call" && event.status === "success") {
351
+ console.log(` [tool] ${event.toolName}`);
352
+ }
353
+ }
354
+ });
355
+ if (result.status === "complete") {
356
+ const output = typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2);
357
+ if (hasActions && agent.actionZodSchemas && result.output != null && typeof result.output === "object" && "action" in result.output) {
358
+ const webhooks = {};
359
+ if (agent.config.actions?.variants) {
360
+ for (const [k, v] of Object.entries(agent.config.actions.variants)) {
361
+ webhooks[k] = v.webhook;
362
+ }
363
+ }
364
+ try {
365
+ const dispatched = await dispatchDevAction(
366
+ result.output,
367
+ agent.actionZodSchemas,
368
+ agent.actionHandlers,
369
+ webhooks
370
+ );
371
+ console.log(`
372
+ ${cyan("Action:")} ${green(dispatched.actionName)}`);
373
+ console.log(` ${dim("Payload:")} ${JSON.stringify(dispatched.payload, null, 2)}`);
374
+ if (dispatched.handlerCalled) {
375
+ console.log(` ${dim("Handler:")} ${green("called")}`);
376
+ }
377
+ if (dispatched.webhookUrl) {
378
+ console.log(
379
+ ` ${dim("Webhook:")} ${yellow(dispatched.webhookUrl)} ${dim("(skipped in dev)")}`
380
+ );
381
+ }
382
+ console.log();
383
+ } catch (err) {
384
+ console.error(
385
+ `
386
+ Action dispatch error: ${err instanceof Error ? err.message : String(err)}
387
+ `
388
+ );
389
+ }
390
+ } else {
391
+ console.log(`
392
+ Agent: ${output}
393
+ `);
394
+ }
395
+ messages.push({ role: "assistant", content: output });
396
+ } else if (result.status === "interrupted") {
397
+ console.log(`
398
+ [Interrupted: ${result.interrupt.toolName} requires approval]
399
+ `);
400
+ }
401
+ } catch (err) {
402
+ console.error(`
403
+ Error: ${err instanceof Error ? err.message : String(err)}
404
+ `);
405
+ }
406
+ ask();
407
+ })();
408
+ });
409
+ };
410
+ ask();
411
+ return new Promise(() => {
412
+ });
413
+ };
414
+
415
+ // src/mock-tool-set.ts
416
+ var MockToolSet = class _MockToolSet {
417
+ defs;
418
+ overrides;
419
+ toolNames;
420
+ constructor(tools, overrides = {}) {
421
+ this.defs = tools;
422
+ this.overrides = overrides;
423
+ this.toolNames = new Set(tools.map((t) => t.name));
424
+ }
425
+ static fromConnectors(connectors, opts) {
426
+ const include = opts?.include;
427
+ const filtered = include ? connectors.filter((c) => include.includes(c.id)) : connectors;
428
+ const tools = filtered.flatMap(
429
+ (c) => c.tools.map((t) => ({
430
+ name: t.name,
431
+ description: t.description,
432
+ parameters: t.parameters
433
+ }))
434
+ );
435
+ return new _MockToolSet(tools, opts?.overrides);
436
+ }
437
+ definitions() {
438
+ return this.defs;
439
+ }
440
+ async call(name, params) {
441
+ if (!this.toolNames.has(name)) {
442
+ throw new Error(`Unknown tool: ${name}`);
443
+ }
444
+ const override = this.overrides[name];
445
+ if (override) {
446
+ return override(params);
447
+ }
448
+ return {};
449
+ }
450
+ };
4
451
  export {
452
+ MockToolSet,
453
+ runDev,
5
454
  startConnectorServer
6
455
  };
7
456
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../src/dev.ts","../src/dev-actions.ts","../src/dev-connectors.ts","../src/mock-tool-set.ts"],"sourcesContent":["// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { readFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport { Agent, type AgentLike } from \"kraken-ai\";\nimport { buildActionOutputSchema } from \"./agents/define-actions\";\nimport type { PlatformAgent } from \"./agents/types/platform-agent\";\nimport { cyan, dim, green, yellow } from \"./cli/log\";\nimport { buildActionInstructions, dispatchDevAction } from \"./dev-actions\";\nimport { loadConnectorTools } from \"./dev-connectors\";\n\nconst loadDotenv = (): void => {\n try {\n const content = readFileSync(\".env\", \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx === -1) continue;\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n if (!process.env[key]) {\n process.env[key] = value;\n }\n }\n } catch {\n // .env not found, that's fine\n }\n};\n\nconst FRONTMATTER_RE = /^---\\n[\\s\\S]*?\\n---\\n([\\s\\S]*)$/;\n\nconst resolveSkillContent = (refs: string[]): string[] =>\n refs.map((ref) => {\n try {\n return readFileSync(`skills/${ref}`, \"utf-8\");\n } catch {\n return ref;\n }\n });\n\nconst buildInstructions = (base: string, skillContent: string[]): string => {\n if (skillContent.length === 0) return base;\n const bodies = skillContent.map((s) => {\n const m = FRONTMATTER_RE.exec(s);\n return m?.[1]?.trim() ?? s;\n });\n return `${base}\\n\\n${bodies.join(\"\\n\\n\")}`;\n};\n\n/** Recursively build a kraken-ai Agent from a PlatformAgent, wiring connectors, skills, and team. */\nconst buildDevAgent = async (pa: PlatformAgent): Promise<Agent> => {\n const {\n name,\n model,\n instructions,\n skills,\n temperature,\n thinkingLevel,\n maxOutputTokens,\n logLevel,\n } = pa.config.agent;\n\n const connectorNames = pa.config.connectors ?? [];\n const { tools: connectorTools, instructions: connectorInstructions } =\n await loadConnectorTools(connectorNames);\n\n const skillContent = resolveSkillContent(skills ?? []);\n let fullInstructions = buildInstructions(instructions, skillContent);\n if (connectorInstructions.length > 0) {\n fullInstructions = `${fullInstructions}\\n\\n${connectorInstructions.join(\"\\n\\n\")}`;\n }\n\n // Wire action output schema and instructions\n let outputSchema: ReturnType<typeof buildActionOutputSchema> | undefined;\n if (pa.actionZodSchemas && Object.keys(pa.actionZodSchemas).length > 0) {\n const actionInstructions = buildActionInstructions(pa.actionZodSchemas);\n if (actionInstructions) {\n fullInstructions = `${fullInstructions}\\n\\n${actionInstructions}`;\n }\n outputSchema = buildActionOutputSchema({\n __type: \"PlatformActions\",\n config: pa.config.actions ?? { variants: {} },\n zodSchemas: pa.actionZodSchemas,\n handlers: pa.actionHandlers ?? {},\n });\n }\n\n // Recursively build team member agents\n let team: AgentLike[] | undefined;\n if (pa.teamAgents && pa.teamAgents.length > 0) {\n team = await Promise.all(pa.teamAgents.map(buildDevAgent));\n }\n\n return new Agent({\n name,\n model,\n instructions: fullInstructions,\n tools: connectorTools.length > 0 ? connectorTools : undefined,\n outputSchema,\n team,\n temperature,\n thinkingLevel,\n maxOutputTokens,\n logLevel,\n });\n};\n\nexport const runDev = async (agent: PlatformAgent): Promise<never> => {\n loadDotenv();\n\n const hasActions = agent.actionZodSchemas && Object.keys(agent.actionZodSchemas).length > 0;\n const sdkAgent = await buildDevAgent(agent);\n\n const { name, model } = agent.config.agent;\n const connectorNames = agent.config.connectors ?? [];\n\n try {\n await sdkAgent.preflight();\n } catch (err) {\n console.error(`\\n ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exit(1);\n }\n\n console.log(`\\n Agent: ${name}`);\n console.log(` Model: ${model}`);\n if (connectorNames.length > 0) {\n console.log(` Connectors: ${connectorNames.join(\", \")}`);\n }\n if (agent.teamAgents && agent.teamAgents.length > 0) {\n console.log(` Team: ${agent.teamAgents.map((a) => a.config.agent.name).join(\", \")}`);\n }\n if (hasActions && agent.actionZodSchemas) {\n console.log(` Actions: ${Object.keys(agent.actionZodSchemas).join(\", \")}`);\n }\n console.log(`\\n Type a message to start. Ctrl+C to exit.\\n`);\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const messages: Array<{ role: \"user\" | \"assistant\"; content: string }> = [];\n\n const cleanup = (): void => {\n rl.close();\n process.exit(0);\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n const ask = (): void => {\n rl.question(\"You: \", (input) => {\n if (!input.trim()) {\n ask();\n return;\n }\n\n messages.push({ role: \"user\", content: input });\n\n void (async () => {\n try {\n const result = await sdkAgent.run(messages, {\n onEvent: (event) => {\n if (event.type === \"thought\") {\n console.log(\n ` [thinking] ${event.text.slice(0, 120)}${event.text.length > 120 ? \"…\" : \"\"}`,\n );\n }\n if (event.type === \"tool_call\" && event.status === \"success\") {\n console.log(` [tool] ${event.toolName}`);\n }\n },\n });\n\n if (result.status === \"complete\") {\n const output =\n typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n\n // Dispatch action if structured output has an action field\n if (\n hasActions &&\n agent.actionZodSchemas &&\n result.output != null &&\n typeof result.output === \"object\" &&\n \"action\" in (result.output as Record<string, unknown>)\n ) {\n const webhooks: Record<string, string | undefined> = {};\n if (agent.config.actions?.variants) {\n for (const [k, v] of Object.entries(agent.config.actions.variants)) {\n webhooks[k] = v.webhook;\n }\n }\n try {\n const dispatched = await dispatchDevAction(\n result.output,\n agent.actionZodSchemas,\n agent.actionHandlers,\n webhooks,\n );\n console.log(`\\n ${cyan(\"Action:\")} ${green(dispatched.actionName)}`);\n console.log(` ${dim(\"Payload:\")} ${JSON.stringify(dispatched.payload, null, 2)}`);\n if (dispatched.handlerCalled) {\n console.log(` ${dim(\"Handler:\")} ${green(\"called\")}`);\n }\n if (dispatched.webhookUrl) {\n console.log(\n ` ${dim(\"Webhook:\")} ${yellow(dispatched.webhookUrl)} ${dim(\"(skipped in dev)\")}`,\n );\n }\n console.log();\n } catch (err) {\n console.error(\n `\\n Action dispatch error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n } else {\n console.log(`\\nAgent: ${output}\\n`);\n }\n\n messages.push({ role: \"assistant\", content: output });\n } else if (result.status === \"interrupted\") {\n console.log(`\\n[Interrupted: ${result.interrupt.toolName} requires approval]\\n`);\n }\n } catch (err) {\n console.error(`\\nError: ${err instanceof Error ? err.message : String(err)}\\n`);\n }\n\n ask();\n })();\n });\n };\n\n ask();\n\n return new Promise(() => {});\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport type * as z from \"zod\";\n\n/**\n * Build instructions that describe available action variants to the LLM.\n * Appended to the agent's system prompt when actions are configured.\n */\nexport const buildActionInstructions = (\n zodSchemas: Record<string, z.ZodObject<z.ZodRawShape>>,\n): string => {\n const entries = Object.entries(zodSchemas);\n if (entries.length === 0) return \"\";\n\n const variants = entries.map(([name, schema]) => {\n const fields = Object.keys(schema.shape).join(\", \");\n return ` - \"${name}\": { ${fields} }`;\n });\n\n return [\n 'You MUST respond with a JSON object containing an \"action\" field set to one of the following action names, plus the fields for that action:',\n \"\",\n ...variants,\n \"\",\n 'Example: { \"action\": \"<name>\", ...fields }',\n ].join(\"\\n\");\n};\n\nexport interface ActionDispatchResult {\n actionName: string;\n payload: Record<string, unknown>;\n handlerCalled: boolean;\n webhookUrl?: string;\n}\n\n/**\n * Validate and dispatch a structured action output from the LLM.\n * In dev mode, handlers are called directly; webhooks are logged but not called.\n */\nexport const dispatchDevAction = async (\n output: unknown,\n zodSchemas: Record<string, z.ZodObject<z.ZodRawShape>>,\n handlers: Readonly<Record<string, (payload: unknown) => Promise<void>>> | undefined,\n webhooks: Record<string, string | undefined>,\n): Promise<ActionDispatchResult> => {\n if (output == null || typeof output !== \"object\" || !(\"action\" in output)) {\n throw new Error('Action output must contain an \"action\" field');\n }\n\n const { action: actionName, ...rest } = output as Record<string, unknown>;\n if (typeof actionName !== \"string\") {\n throw new Error('Action output \"action\" field must be a string');\n }\n\n const schema = zodSchemas[actionName];\n if (!schema) {\n throw new Error(\n `Unknown action \"${actionName}\". Expected one of: ${Object.keys(zodSchemas).join(\", \")}`,\n );\n }\n\n const parsed = schema.parse(rest);\n const payload = parsed as Record<string, unknown>;\n\n let handlerCalled = false;\n const handler = handlers?.[actionName];\n if (handler) {\n await handler(payload);\n handlerCalled = true;\n }\n\n return {\n actionName,\n payload,\n handlerCalled,\n webhookUrl: webhooks[actionName],\n };\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { resolve } from \"node:path\";\nimport { type Tool, tool } from \"kraken-ai\";\nimport { wrapToolError, wrapToolResult } from \"./agents/connector-wrap\";\nimport type {\n ConnectorHandlerContext,\n GetPromptResult,\n PlatformConnector,\n ReadResourceResult,\n} from \"./agents/types/connector\";\nimport { ENTITY_NAME_REGEX, isValidEntityName } from \"./cli/validate\";\n\nconst isPlatformConnector = (v: unknown): v is PlatformConnector =>\n v != null &&\n typeof v === \"object\" &&\n (v as Record<string, unknown>).__type === \"PlatformConnector\";\n\nexport interface LoadedResource {\n readonly name: string;\n readonly uri: string;\n readonly description: string;\n readonly mimeType?: string;\n read(ctx: ConnectorHandlerContext): Promise<ReadResourceResult> | ReadResourceResult;\n}\n\nexport interface LoadedPrompt {\n readonly name: string;\n readonly description: string;\n readonly arguments?: ReadonlyArray<{\n readonly name: string;\n readonly description?: string;\n readonly required?: boolean;\n }>;\n get(\n args: Record<string, string>,\n ctx: ConnectorHandlerContext,\n ): Promise<GetPromptResult> | GetPromptResult;\n}\n\nexport interface LoadedConnectors {\n readonly tools: Tool[];\n readonly resources: LoadedResource[];\n readonly prompts: LoadedPrompt[];\n readonly instructions: string[];\n}\n\n/**\n * Import a single connector module by name.\n * Tries `connectors/<name>/index.ts` first (tsx), then `connectors/<name>/index.js`.\n */\nconst importConnector = async (\n name: string,\n projectRoot: string,\n): Promise<PlatformConnector | null> => {\n const basePath = resolve(projectRoot, \"connectors\", name, \"index\");\n\n for (const ext of [\".ts\", \".js\"]) {\n try {\n const mod: Record<string, unknown> = await import(`${basePath}${ext}`);\n const connector = mod.default;\n\n if (!isPlatformConnector(connector)) {\n console.warn(`[connector:${name}] Default export is not a PlatformConnector — skipping`);\n return null;\n }\n\n return connector;\n } catch (err: unknown) {\n // If .ts fails, try .js next\n if (ext === \".ts\") continue;\n\n // Both extensions failed\n const message = err instanceof Error ? err.message : String(err);\n console.warn(`[connector:${name}] Failed to import — skipping. Error: ${message}`);\n return null;\n }\n }\n\n return null;\n};\n\n/**\n * Create SDK Tool wrappers from a PlatformConnector's tool definitions.\n * Each tool validates input, calls the handler, and wraps the result.\n */\nconst createToolsFromConnector = (connector: PlatformConnector): Tool[] => {\n const tools = connector.tools ?? {};\n return Object.entries(tools).map(([name, def]) =>\n tool({\n name,\n description: def.description,\n parameters: def.input,\n execute: async (args) => {\n try {\n const result = await Promise.resolve(def.handler(args));\n return wrapToolResult(result);\n } catch (error: unknown) {\n return wrapToolError(error);\n }\n },\n }),\n );\n};\n\n/**\n * Build SDK tools from already-loaded PlatformConnector objects.\n *\n * - Detects tool name collisions across connectors\n * - Creates SDK Tool wrappers for direct function calls (no HTTP)\n * - Collects connector instructions\n * - Logs connector name and tool count\n */\nexport const buildConnectorTools = (\n connectors: ReadonlyArray<{ readonly name: string; readonly connector: PlatformConnector }>,\n): LoadedConnectors => {\n // Check for tool name collisions across all connectors\n const toolOwners = new Map<string, string>();\n for (const { name, connector } of connectors) {\n for (const toolName of Object.keys(connector.tools ?? {})) {\n const existing = toolOwners.get(toolName);\n if (existing) {\n throw new Error(\n `Tool name collision: \"${toolName}\" is defined by both connectors \"${existing}\" and \"${name}\". ` +\n `Rename one of the tools or use a unique prefix.`,\n );\n }\n toolOwners.set(toolName, name);\n }\n }\n\n // Check for resource name collisions\n const resourceOwners = new Map<string, string>();\n for (const { name, connector } of connectors) {\n for (const resourceName of Object.keys(connector.resources ?? {})) {\n const existing = resourceOwners.get(resourceName);\n if (existing) {\n throw new Error(\n `Resource name collision: \"${resourceName}\" is defined by both connectors \"${existing}\" and \"${name}\". ` +\n `Rename one of the resources or use a unique prefix.`,\n );\n }\n resourceOwners.set(resourceName, name);\n }\n }\n\n // Check for prompt name collisions\n const promptOwners = new Map<string, string>();\n for (const { name, connector } of connectors) {\n for (const promptName of Object.keys(connector.prompts ?? {})) {\n const existing = promptOwners.get(promptName);\n if (existing) {\n throw new Error(\n `Prompt name collision: \"${promptName}\" is defined by both connectors \"${existing}\" and \"${name}\". ` +\n `Rename one of the prompts or use a unique prefix.`,\n );\n }\n promptOwners.set(promptName, name);\n }\n }\n\n const allTools: Tool[] = [];\n const allResources: LoadedResource[] = [];\n const allPrompts: LoadedPrompt[] = [];\n const allInstructions: string[] = [];\n\n for (const { name, connector } of connectors) {\n const tools = createToolsFromConnector(connector);\n allTools.push(...tools);\n\n for (const [resName, resDef] of Object.entries(connector.resources ?? {})) {\n allResources.push({\n name: resName,\n uri: resDef.uri,\n description: resDef.description,\n mimeType: resDef.mimeType,\n read: (ctx) => resDef.read(ctx),\n });\n }\n\n for (const [promptName, promptDef] of Object.entries(connector.prompts ?? {})) {\n allPrompts.push({\n name: promptName,\n description: promptDef.description,\n arguments: promptDef.arguments,\n get: (args, ctx) => promptDef.get(args, ctx),\n });\n }\n\n const toolCount = Object.keys(connector.tools ?? {}).length;\n const resourceCount = Object.keys(connector.resources ?? {}).length;\n const promptCount = Object.keys(connector.prompts ?? {}).length;\n\n const parts = [\n `${toolCount} tool${toolCount !== 1 ? \"s\" : \"\"}`,\n `${resourceCount} resource${resourceCount !== 1 ? \"s\" : \"\"}`,\n `${promptCount} prompt${promptCount !== 1 ? \"s\" : \"\"}`,\n ];\n console.log(` Connector: ${name} (${parts.join(\", \")})`);\n\n if (connector.instructions) {\n allInstructions.push(connector.instructions);\n }\n }\n\n return {\n tools: allTools,\n resources: allResources,\n prompts: allPrompts,\n instructions: allInstructions,\n };\n};\n\n/**\n * Load connector tools from an agent's connector name list.\n *\n * - Validates connector names against ENTITY_NAME_REGEX\n * - Dynamically imports each connector module\n * - Delegates to buildConnectorTools for collision detection, wrapping, and instructions\n */\nexport const loadConnectorTools = async (\n connectorNames: string[],\n projectRoot?: string,\n): Promise<LoadedConnectors> => {\n if (connectorNames.length === 0) {\n return { tools: [], resources: [], prompts: [], instructions: [] };\n }\n\n const root = projectRoot ?? process.cwd();\n const connectors: Array<{ name: string; connector: PlatformConnector }> = [];\n\n for (const name of connectorNames) {\n if (!isValidEntityName(name)) {\n console.warn(\n `[connector] Invalid connector name \"${name}\" — must match ${ENTITY_NAME_REGEX}. Skipping.`,\n );\n continue;\n }\n\n const connector = await importConnector(name, root);\n if (connector) {\n connectors.push({ name, connector });\n }\n }\n\n return buildConnectorTools(connectors);\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport type { ToolDefinition } from \"kraken-ai\";\nimport type { ConnectorSchema } from \"./platform/types\";\n\ntype ToolOverride = (args: Record<string, unknown>) => Promise<unknown> | unknown;\n\nexport class MockToolSet {\n private readonly defs: ToolDefinition[];\n private readonly overrides: Record<string, ToolOverride>;\n private readonly toolNames: Set<string>;\n\n constructor(tools: ToolDefinition[], overrides: Record<string, ToolOverride> = {}) {\n this.defs = tools;\n this.overrides = overrides;\n this.toolNames = new Set(tools.map((t) => t.name));\n }\n\n static fromConnectors(\n connectors: ConnectorSchema[],\n opts?: { include?: string[]; overrides?: Record<string, ToolOverride> },\n ): MockToolSet {\n const include = opts?.include;\n const filtered = include ? connectors.filter((c) => include.includes(c.id)) : connectors;\n\n const tools: ToolDefinition[] = filtered.flatMap((c) =>\n c.tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n })),\n );\n\n return new MockToolSet(tools, opts?.overrides);\n }\n\n definitions(): ToolDefinition[] {\n return this.defs;\n }\n\n async call(name: string, params: Record<string, unknown>): Promise<unknown> {\n if (!this.toolNames.has(name)) {\n throw new Error(`Unknown tool: ${name}`);\n }\n\n const override = this.overrides[name];\n if (override) {\n return override(params);\n }\n\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAGA,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,aAA6B;;;ACI/B,IAAM,0BAA0B,CACrC,eACW;AACX,QAAM,UAAU,OAAO,QAAQ,UAAU;AACzC,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,QAAM,WAAW,QAAQ,IAAI,CAAC,CAAC,MAAM,MAAM,MAAM;AAC/C,UAAM,SAAS,OAAO,KAAK,OAAO,KAAK,EAAE,KAAK,IAAI;AAClD,WAAO,QAAQ,IAAI,QAAQ,MAAM;AAAA,EACnC,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAaO,IAAM,oBAAoB,OAC/B,QACA,YACA,UACA,aACkC;AAClC,MAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,EAAE,YAAY,SAAS;AACzE,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AAEA,QAAM,EAAE,QAAQ,YAAY,GAAG,KAAK,IAAI;AACxC,MAAI,OAAO,eAAe,UAAU;AAClC,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACjE;AAEA,QAAM,SAAS,WAAW,UAAU;AACpC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AA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