@kraken-ai/platform 0.0.4 → 0.0.7
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/{chunk-PPT6GGYL.js → chunk-FTLOWV2N.js} +244 -67
- package/dist/chunk-FTLOWV2N.js.map +1 -0
- package/dist/cli.js +1103 -374
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +416 -240
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1107 -368
- package/dist/index.d.ts +1107 -368
- package/dist/index.js +183 -172
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +220 -45
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +265 -28
- package/dist/server.d.ts +265 -28
- package/dist/server.js +15 -20
- package/dist/server.js.map +1 -1
- package/package.json +20 -16
- package/dist/chunk-PPT6GGYL.js.map +0 -1
- package/dist/types-_lfbhFJH.d.cts +0 -451
- package/dist/types-_lfbhFJH.d.ts +0 -451
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,EA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EAEA,cAAgC;AAC9B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,KAAK,MAAc,QAAmD;AAC1E,QAAI,CAAC,KAAK,UAAU,IAAI,IAAI,GAAG;AAC7B,YAAM,IAAI,MAAM,iBAAiB,IAAI,EAAE;AAAA,IACzC;AAEA,UAAM,WAAW,KAAK,UAAU,IAAI;AACpC,QAAI,UAAU;AACZ,aAAO,SAAS,MAAM;AAAA,IACxB;AAEA,WAAO,CAAC;AAAA,EACV;AACF;","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 type { PlatformAgent } from \"@kraken-ai/platform-core\";\nimport { Agent, type AgentLike } from \"kraken-ai\";\nimport { buildActionOutputSchema } from \"./agents/define-actions\";\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(`src/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 const actions = Object.entries(pa.actionZodSchemas).map(([name, zodSchema]) => ({\n __type: \"PlatformAction\" as const,\n name,\n config: { schema: {} as Record<string, unknown>, hasHandler: false },\n zodSchema,\n }));\n outputSchema = buildActionOutputSchema(actions);\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: string) => {\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 try {\n const dispatched = await dispatchDevAction(\n result.output,\n agent.actionZodSchemas,\n agent.actionHandlers,\n agent.actionWebhooks ?? {},\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 {\n type ConnectorHandlerContext,\n type GetPromptResult,\n isValidPrimitiveName,\n type PlatformConnector,\n PRIMITIVE_NAME_REGEX,\n type ReadResourceResult,\n} from \"@kraken-ai/platform-core\";\nimport { type Tool, tool } from \"kraken-ai\";\nimport { wrapToolError, wrapToolResult } from \"./agents/connector-wrap\";\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 `src/connectors/<name>/index.ts` first (tsx), then `src/connectors/<name>/index.js`.\n */\nconst importConnector = async (\n name: string,\n projectRoot: string,\n): Promise<PlatformConnector | null> => {\n const basePath = resolve(projectRoot, \"src\", \"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 PRIMITIVE_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 (!isValidPrimitiveName(name)) {\n console.warn(\n `[connector] Invalid connector name \"${name}\" — must match ${PRIMITIVE_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;AAEhC,SAAS,aAA6B;;;ACG/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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I Platform SDK — PlatformClient and kraken CLI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -21,26 +21,30 @@
|
|
|
21
21
|
"bin": {
|
|
22
22
|
"kraken": "./dist/cli.js"
|
|
23
23
|
},
|
|
24
|
-
"scripts": {
|
|
25
|
-
"build": "tsup && chmod +x dist/cli.js",
|
|
26
|
-
"test": "vitest run",
|
|
27
|
-
"test:watch": "vitest",
|
|
28
|
-
"check": "tsc --noEmit && biome check",
|
|
29
|
-
"check:write": "biome check --write"
|
|
30
|
-
},
|
|
31
24
|
"dependencies": {
|
|
32
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
33
|
-
"
|
|
34
|
-
"
|
|
25
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
26
|
+
"zod": "^4.3.6",
|
|
27
|
+
"kraken-ai": "0.0.6"
|
|
35
28
|
},
|
|
36
29
|
"devDependencies": {
|
|
37
|
-
"@types/node": "^25.5.
|
|
30
|
+
"@types/node": "^25.5.2",
|
|
31
|
+
"dts-bundle-generator": "^9.5.1",
|
|
38
32
|
"tsup": "^8.5.1",
|
|
39
|
-
"typescript": "^
|
|
40
|
-
"vitest": "^4.1.
|
|
33
|
+
"typescript": "^6.0.2",
|
|
34
|
+
"vitest": "^4.1.3",
|
|
35
|
+
"@kraken-ai/platform-core": "0.0.1"
|
|
41
36
|
},
|
|
42
37
|
"files": [
|
|
43
38
|
"dist"
|
|
44
39
|
],
|
|
45
|
-
"license": "BUSL-1.1"
|
|
46
|
-
|
|
40
|
+
"license": "BUSL-1.1",
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup && chmod +x dist/cli.js && pnpm run build:dts",
|
|
43
|
+
"build:dts": "dts-bundle-generator --config dts-bundle-generator.config.cjs && cp dist/index.d.ts dist/index.d.cts && cp dist/server.d.ts dist/server.d.cts",
|
|
44
|
+
"pack:verify": "node ./scripts/verify-packed-manifest.mjs",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"test:watch": "vitest",
|
|
47
|
+
"check": "tsc --noEmit && biome check",
|
|
48
|
+
"check:write": "biome check --write"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agents/errors.ts","../src/agents/connector-wrap.ts","../src/agents/connector-server.ts","../src/agents/types/action.ts","../src/agents/define-actions.ts","../src/cli/log.ts","../src/cli/validate.ts"],"sourcesContent":["// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nexport class SecurityError extends Error {\n readonly code = \"SECURITY_VIOLATION\";\n\n constructor(message: string) {\n super(message);\n this.name = \"SecurityError\";\n }\n}\n\nexport class ConnectorError extends Error {\n readonly code = \"CONNECTOR_ERROR\";\n\n constructor(message: string) {\n super(message);\n this.name = \"ConnectorError\";\n }\n}\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { ConnectorError } from \"./errors\";\nimport type { McpContent } from \"./types/connector\";\n\nconst MAX_TOOL_RESULT_SIZE = 10 * 1024 * 1024; // 10MB\n\ninterface ToolResultContent {\n readonly type: string;\n [key: string]: unknown;\n}\n\ninterface ToolResult {\n readonly content: ReadonlyArray<ToolResultContent>;\n readonly isError?: boolean;\n}\n\nconst isMcpContent = (val: unknown): val is McpContent =>\n typeof val === \"object\" &&\n val !== null &&\n \"__mcpPassThrough\" in val &&\n (val as McpContent).__mcpPassThrough === true;\n\n/** Wrap a handler return value into MCP CallToolResult format */\nexport const wrapToolResult = (value: unknown): ToolResult => {\n if (value === null || value === undefined) {\n return { content: [] };\n }\n\n if (typeof value === \"string\") {\n return { content: [{ type: \"text\", text: value }] };\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return { content: [{ type: \"text\", text: String(value) }] };\n }\n\n if (isMcpContent(value)) {\n const result: ToolResult = { content: value.content };\n if (value.isError) {\n return { ...result, isError: true };\n }\n return result;\n }\n\n const json = JSON.stringify(value, null, 2);\n if (json.length > MAX_TOOL_RESULT_SIZE) {\n return {\n content: [{ type: \"text\", text: `[Result truncated: ${json.length} bytes]` }],\n isError: true,\n };\n }\n return { content: [{ type: \"text\", text: json }] };\n};\n\n/** Wrap a thrown error into MCP CallToolResult format with isError: true */\nexport const wrapToolError = (error: unknown): ToolResult => {\n if (error instanceof ConnectorError) {\n return {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n };\n }\n\n if (error instanceof Error) {\n console.error(\"[connector] Internal handler error:\", error.message, error.stack);\n } else {\n console.error(\"[connector] Internal handler error:\", String(error));\n }\n\n return {\n content: [{ type: \"text\", text: \"Internal handler error\" }],\n isError: true,\n };\n};\n\n/** Create an explicit MCP content pass-through result */\nexport const mcpResult = (content: McpContent[\"content\"], isError?: boolean): McpContent => ({\n __mcpPassThrough: true as const,\n content,\n isError,\n});\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport { randomUUID } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\n\nimport * as z from \"zod\";\nimport { wrapToolError, wrapToolResult } from \"./connector-wrap\";\nimport type { ConnectorPromptDef, PlatformConnector } from \"./types/connector\";\n\nconst DEFAULT_HANDLER_TIMEOUT_MS = 30_000;\nconst MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB\n\nexport interface ConnectorServerOptions {\n readonly port?: number;\n readonly host?: string;\n readonly handlerTimeoutMs?: number;\n}\n\nexport interface ConnectorServerHandle {\n readonly port: number;\n readonly close: () => Promise<void>;\n}\n\nconst withTimeout = <T>(promise: Promise<T>, ms: number): Promise<T> =>\n Promise.race([\n promise,\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(`Handler timed out after ${ms}ms`)), ms),\n ),\n ]);\n\nconst readBody = (req: IncomingMessage, maxSize: number): Promise<string> =>\n new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n req.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > maxSize) {\n req.destroy();\n reject(new Error(\"Request body too large\"));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n req.on(\"error\", reject);\n });\n\n/** Convert ConnectorPromptDef.arguments array to a raw shape for MCP SDK */\nconst buildPromptArgsSchema = (\n def: ConnectorPromptDef,\n): Record<string, z.ZodString | z.ZodOptional<z.ZodString>> | undefined => {\n if (!def.arguments?.length) return undefined;\n const shape: Record<string, z.ZodString | z.ZodOptional<z.ZodString>> = {};\n for (const arg of def.arguments) {\n shape[arg.name] = arg.required ? z.string() : z.string().optional();\n }\n return shape;\n};\n\nexport const startConnectorServer = async (\n connector: PlatformConnector,\n options?: ConnectorServerOptions,\n): Promise<ConnectorServerHandle> => {\n const mcpServerModule = await import(\"@modelcontextprotocol/sdk/server/mcp.js\").catch(() => {\n throw new Error(\n \"@modelcontextprotocol/sdk is required for startConnectorServer. \" +\n \"Install it: pnpm add @modelcontextprotocol/sdk\",\n );\n });\n const transportModule = await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\").catch(\n () => {\n throw new Error(\n \"@modelcontextprotocol/sdk is required for startConnectorServer. \" +\n \"Install it: pnpm add @modelcontextprotocol/sdk\",\n );\n },\n );\n\n const { McpServer } = mcpServerModule;\n const { StreamableHTTPServerTransport } = transportModule;\n\n const timeoutMs = options?.handlerTimeoutMs ?? DEFAULT_HANDLER_TIMEOUT_MS;\n\n const mcpServer = new McpServer(\n { name: connector.name, version: \"0.0.0\" },\n { capabilities: { tools: {}, resources: {}, prompts: {} } },\n );\n\n const tools = connector.tools ?? {};\n const toolEntries = Object.entries(tools);\n\n if (toolEntries.length === 0) {\n console.warn(\n `[connector:${connector.name}] No tools defined — server will start with zero tools`,\n );\n }\n\n for (const [name, def] of toolEntries) {\n mcpServer.registerTool(\n name,\n {\n description: def.description,\n inputSchema: def.input,\n ...(def.annotations ? { annotations: def.annotations } : {}),\n },\n async (args: unknown) => {\n try {\n // args is already validated by the MCP SDK against the Zod schema\n const result = await withTimeout(Promise.resolve(def.handler(args)), timeoutMs);\n const wrapped = wrapToolResult(result);\n return {\n content: wrapped.content.map((c) => ({\n type: \"text\" as const,\n text: String(\"text\" in c ? c.text : \"\"),\n })),\n ...(wrapped.isError === true ? { isError: true as const } : {}),\n };\n } catch (error: unknown) {\n const wrapped = wrapToolError(error);\n return {\n content: wrapped.content.map((c) => ({\n type: \"text\" as const,\n text: String(\"text\" in c ? c.text : \"\"),\n })),\n isError: true as const,\n };\n }\n },\n );\n }\n\n const resources = connector.resources ?? {};\n for (const [name, def] of Object.entries(resources)) {\n mcpServer.registerResource(\n name,\n def.uri,\n {\n description: def.description,\n ...(def.mimeType ? { mimeType: def.mimeType } : {}),\n },\n async (_uri: URL, extra: { signal: AbortSignal }) => {\n try {\n const result = await withTimeout(\n Promise.resolve(def.read({ signal: extra.signal })),\n timeoutMs,\n );\n return { contents: [...result.contents] };\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error(`[connector:${connector.name}] Resource read error:`, error.message);\n }\n throw error;\n }\n },\n );\n }\n\n const prompts = connector.prompts ?? {};\n for (const [name, def] of Object.entries(prompts)) {\n const argsSchema = buildPromptArgsSchema(def);\n mcpServer.registerPrompt(\n name,\n {\n description: def.description,\n ...(argsSchema ? { argsSchema } : {}),\n },\n async (args: Record<string, string | undefined>, extra: { signal: AbortSignal }) => {\n try {\n const cleanArgs: Record<string, string> = {};\n for (const [k, v] of Object.entries(args)) {\n if (v !== undefined) cleanArgs[k] = v;\n }\n const result = await withTimeout(\n Promise.resolve(def.get(cleanArgs, { signal: extra.signal })),\n timeoutMs,\n );\n return { messages: [...result.messages] };\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error(`[connector:${connector.name}] Prompt get error:`, error.message);\n }\n throw error;\n }\n },\n );\n }\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n\n const host = options?.host ?? \"127.0.0.1\";\n const port = options?.port ?? 0;\n\n const httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\n if (req.url === \"/health\" && req.method === \"GET\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ status: \"ok\" }));\n return;\n }\n\n if (\n req.url === \"/mcp\" &&\n (req.method === \"POST\" || req.method === \"GET\" || req.method === \"DELETE\")\n ) {\n if (req.method === \"POST\") {\n // Check Content-Length before reading body (fast reject for oversized payloads)\n const contentLength = parseInt(req.headers[\"content-length\"] ?? \"0\", 10);\n if (contentLength > MAX_BODY_SIZE) {\n req.resume(); // drain the request body to prevent EPIPE\n res.writeHead(413, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Request body too large\" }));\n return;\n }\n\n try {\n const body = await readBody(req, MAX_BODY_SIZE);\n const parsed: unknown = JSON.parse(body);\n await transport.handleRequest(req, res, parsed);\n } catch (err: unknown) {\n if (!res.headersSent) {\n const isTooLarge = err instanceof Error && err.message === \"Request body too large\";\n res.writeHead(isTooLarge ? 413 : 400, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: isTooLarge ? \"Request body too large\" : \"Invalid request body\",\n }),\n );\n }\n }\n return;\n }\n\n // GET (SSE) and DELETE (session end)\n try {\n await transport.handleRequest(req, res);\n } catch {\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n }\n }\n return;\n }\n\n res.writeHead(404);\n res.end(\"Not found\");\n });\n\n // Connect MCP server to transport AFTER tool registration\n await mcpServer.connect(transport);\n\n await new Promise<void>((resolve) => {\n httpServer.listen(port, host, () => resolve());\n });\n\n const addr = httpServer.address();\n if (!addr || typeof addr === \"string\") {\n throw new Error(\"Failed to get server address\");\n }\n\n return {\n port: (addr as AddressInfo).port,\n close: async () => {\n await mcpServer.close();\n await new Promise<void>((resolve, reject) => {\n httpServer.close((err) => (err ? reject(err) : resolve()));\n });\n },\n };\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport * as z from \"zod\";\n\n/** Action names follow entity naming convention: lowercase alphanumeric with hyphens, 1-64 chars. */\nexport const ACTION_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;\n\n/** Validates an action name (allows single-char names like \"a\"). */\nexport const isValidActionName = (name: string): boolean =>\n name.length === 1 ? /^[a-z0-9]$/.test(name) : ACTION_NAME_REGEX.test(name);\n\n/** Input for a single action variant in defineActions(). */\nexport interface ActionVariantInput<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> {\n schema: S;\n webhook?: string;\n // Method syntax → bivariant parameter checking, so specific handler args\n // (e.g. { reason: string }) are assignable to the default (z.infer<ZodObject>).\n handler?(payload: z.infer<S>): Promise<void>;\n}\n\n/** Serializable config for a single action variant (stored in manifest/DB). */\nexport interface ActionVariantConfig {\n schema: Record<string, unknown>;\n webhook?: string;\n hasHandler: boolean;\n}\n\n/** Serializable portion of action definitions (stored in agent config). */\nexport interface PlatformActionsConfig {\n variants: Record<string, ActionVariantConfig>;\n}\n\n/** Full action definitions including in-memory schemas and handlers for runtime use. */\nexport interface PlatformActions {\n readonly __type: \"PlatformActions\";\n readonly config: PlatformActionsConfig;\n readonly zodSchemas: Record<string, z.ZodObject<z.ZodRawShape>>;\n readonly handlers: Readonly<Record<string, (payload: unknown) => Promise<void>>>;\n}\n\nexport const actionVariantConfigSchema = z.object({\n schema: z.record(z.string(), z.unknown()),\n webhook: z.string().url().optional(),\n hasHandler: z.boolean(),\n});\n\nexport const actionsConfigSchema = z\n .object({\n variants: z.record(z.string(), actionVariantConfigSchema),\n })\n .strict();\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport * as z from \"zod\";\nimport {\n type ActionVariantConfig,\n type ActionVariantInput,\n isValidActionName,\n type PlatformActions,\n} from \"./types/action\";\n\n/**\n * Define an action variant.\n *\n * Infers handler payload types from the schema.\n *\n * @example\n * ```ts\n * defineAction({\n * schema: z.object({ reason: z.string() }),\n * handler: async (payload) => {\n * payload.reason; // string — fully typed\n * },\n * });\n * ```\n */\nexport const defineAction = <S extends z.ZodObject<z.ZodRawShape>>(\n input: ActionVariantInput<S>,\n): ActionVariantInput<S> => input;\n\n/**\n * Define action variants for a platform agent. Actions are typed terminal\n * outputs — the agent's final decision as structured output.\n *\n * Each variant has a name and an object schema. Schemas are serialized\n * to JSON Schema for discovery/storage, and the originals are preserved\n * in-memory for runtime validation.\n *\n * Handler payload types are inferred from the schema automatically:\n *\n * @example\n * ```ts\n * const actions = defineActions({\n * approve: {\n * schema: z.object({ reason: z.string() }),\n * handler: async (payload) => {\n * payload.reason; // string — fully typed\n * },\n * },\n * reject: { schema: z.object({ reason: z.string(), severity: z.number() }) },\n * });\n * ```\n */\nexport const defineActions = <V extends Record<string, ActionVariantInput>>(\n variants: V,\n): PlatformActions => {\n const entries = Object.entries(variants);\n\n if (entries.length === 0) {\n throw new Error(\"defineActions() requires at least one action variant\");\n }\n\n if (entries.length > 20) {\n throw new Error(\"defineActions() supports a maximum of 20 action variants\");\n }\n\n const serialized: Record<string, ActionVariantConfig> = {};\n const zodSchemas: Record<string, z.ZodObject<z.ZodRawShape>> = {};\n const handlers: Record<string, (payload: unknown) => Promise<void>> = {};\n\n for (const [name, variant] of entries) {\n if (!isValidActionName(name)) {\n throw new Error(\n `Invalid action name \"${name}\": must be lowercase alphanumeric with hyphens, 1-64 chars`,\n );\n }\n const v = variant as ActionVariantInput;\n serialized[name] = {\n schema: z.toJSONSchema(v.schema, { target: \"draft-2020-12\" }) as Record<string, unknown>,\n webhook: v.webhook,\n hasHandler: !!v.handler,\n };\n zodSchemas[name] = v.schema;\n if (v.handler) {\n // Safe: runtime validates payload against Zod schema before calling handler\n handlers[name] = v.handler as (payload: unknown) => Promise<void>;\n }\n }\n\n return Object.freeze({\n __type: \"PlatformActions\" as const,\n config: Object.freeze({ variants: Object.freeze(serialized) }),\n zodSchemas: Object.freeze(zodSchemas),\n handlers: Object.freeze(handlers),\n });\n};\n\n/**\n * Build a discriminated-union schema from action definitions.\n * Each variant becomes `z.object({ action: z.literal(name), ...variantSchema })`.\n * Used as the agent's outputSchema to constrain LLM structured output.\n */\nexport const buildActionOutputSchema = (actions: PlatformActions) => {\n const entries = Object.entries(actions.zodSchemas);\n\n if (entries.length === 0) {\n throw new Error(\"Cannot build output schema from empty action definitions\");\n }\n\n const variants = entries.map(([name, schema]) =>\n z.object({ action: z.literal(name) }).extend(schema.shape),\n );\n\n const [first, ...rest] = variants;\n if (!first) {\n throw new Error(\"Cannot build output schema from empty action definitions\");\n }\n return z.discriminatedUnion(\"action\", [first, ...rest]);\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nconst supportsColor =\n !(\"NO_COLOR\" in process.env) &&\n process.env.FORCE_COLOR !== \"0\" &&\n (process.stderr.isTTY ?? false);\n\nconst code = (open: number, close: number) => {\n const openStr = `\\x1b[${open}m`;\n const closeStr = `\\x1b[${close}m`;\n return (s: string): string => (supportsColor ? `${openStr}${s}${closeStr}` : s);\n};\n\nexport const bold = code(1, 22);\nexport const dim = code(2, 22);\nexport const red = code(31, 39);\nexport const yellow = code(33, 39);\nexport const green = code(32, 39);\nexport const cyan = code(36, 39);\n\nexport const info = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${cyan(\"info\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const warn = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${yellow(\"warn\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const error = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${red(\"error\")}${dim(\"]\")} ${msg}\\n`);\n};\n\nexport const success = (msg: string): void => {\n process.stderr.write(` ${dim(\"[kraken-ai:\")} ${green(\"ok\")}${dim(\"]\")} ${msg}\\n`);\n};\n","// Copyright (c) Optima Engineering LLC\n// SPDX-License-Identifier: BUSL-1.1\n\nimport type { SchemaBundle } from \"./codegen\";\n\n// ─── Entity Name Validation ───\n\nexport const ENTITY_NAME_REGEX = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;\n\n/** Single-char names (e.g. \"a\") are valid — the regex requires min 2 chars, so we also allow /^[a-z0-9]$/ */\nexport const isValidEntityName = (name: string): boolean =>\n name.length === 1 ? /^[a-z0-9]$/.test(name) : ENTITY_NAME_REGEX.test(name);\n\n// ─── Skill Name Validation ───\n\n/** Skill filenames allow uppercase: e.g. someFile-name.md, Research.md */\nexport const SKILL_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}[a-zA-Z0-9]$/;\n\nexport const isValidSkillName = (basename: string): boolean =>\n basename.length === 1 ? /^[a-zA-Z0-9]$/.test(basename) : SKILL_NAME_REGEX.test(basename);\n\n/** Skill IDs from remote may include .md extension */\nexport const isValidSkillId = (id: string): boolean => {\n const base = id.endsWith(\".md\") ? id.slice(0, -3) : id;\n return isValidSkillName(base);\n};\n\n// ─── Tool Name Validation ───\n\n/** Tool names allow underscores (e.g., fs_read, fs_write) */\nexport const TOOL_NAME_REGEX = /^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;\n\nexport const isValidToolName = (name: string): boolean =>\n name.length === 1 ? /^[a-z]$/.test(name) : TOOL_NAME_REGEX.test(name);\n\n// ─── Property Name Validation ───\n\n/** JS/TS property names with 255-char length cap to prevent DoS */\nexport const PROPERTY_NAME_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]{0,254}$/;\n\nconst FORBIDDEN_PROPS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n]);\n\nexport const isValidPropertyName = (name: string): boolean =>\n PROPERTY_NAME_REGEX.test(name) && !FORBIDDEN_PROPS.has(name);\n\n// ─── Schema Bundle Validation ───\n\nconst MAX_SCHEMA_DEPTH = 20;\nconst MAX_OBJECT_BREADTH = 200;\n\n/**\n * Validates all identifiers in a SchemaBundle before codegen.\n * Throws on the first invalid identifier — fail-fast.\n *\n * Checks:\n * - Entity names (agent IDs, connector IDs, pipeline names, query names)\n * - Skill IDs (allows .md extension)\n * - Tool names (allows underscores)\n * - Property names in JSON Schema (recursive, with depth/breadth limits)\n * - Column names in query schemas\n * - Rejects `$ref` keys in pipeline schemas\n * - Strips `pattern` keys from pipeline schemas (ReDoS prevention)\n */\nexport const validateSchemaBundle = (bundle: SchemaBundle): void => {\n for (const agent of bundle.agents) {\n assertValidEntity(\"agent id\", agent.id);\n validateJsonSchemaProperties(\"agent input schema\", agent.input, 0);\n validateJsonSchemaProperties(\"agent output schema\", agent.output, 0);\n if (agent.actions) {\n for (const [actionName, actionSchema] of Object.entries(agent.actions)) {\n assertValidEntity(\"agent action name\", actionName);\n validateJsonSchemaProperties(\"agent action schema\", actionSchema, 0);\n }\n }\n }\n\n for (const query of bundle.queries) {\n assertValidEntity(\"query name\", query.name);\n validateJsonSchemaProperties(\"query params schema\", query.params, 0);\n for (const col of query.columns) {\n assertValidProperty(\"query column name\", col.name);\n }\n }\n\n for (const connector of bundle.connectors) {\n assertValidEntity(\"connector id\", connector.id);\n for (const tool of connector.tools) {\n assertValidTool(\"connector tool name\", tool.name);\n validateJsonSchemaProperties(\"connector tool parameters\", tool.parameters, 0);\n }\n }\n\n for (const pipeline of bundle.pipelines) {\n assertValidEntity(\"pipeline name\", pipeline.pipeline);\n for (const query of pipeline.queries) {\n assertValidEntity(\"pipeline query name\", query.name);\n validatePipelineSchema(\"pipeline query params\", query.params, 0);\n validatePipelineSchema(\"pipeline query returns\", query.returns, 0);\n }\n }\n\n for (const skill of bundle.skills) {\n assertValidSkill(\"skill id\", skill.id);\n }\n};\n\n// ─── Internal Assertion Helpers ───\n\nconst assertValidEntity = (entityType: string, value: string): void => {\n if (!isValidEntityName(value)) {\n throw new Error(\n `Invalid remote schema: ${entityType} \"${value}\". Must match ${ENTITY_NAME_REGEX}`,\n );\n }\n};\n\nconst assertValidTool = (entityType: string, value: string): void => {\n if (!isValidToolName(value)) {\n throw new Error(\n `Invalid remote schema: ${entityType} \"${value}\". Must match ${TOOL_NAME_REGEX}`,\n );\n }\n};\n\nconst assertValidProperty = (entityType: string, value: string): void => {\n if (!isValidPropertyName(value)) {\n throw new Error(\n `Invalid remote schema: ${entityType} \"${value}\". Must match ${PROPERTY_NAME_REGEX} and not be a forbidden property`,\n );\n }\n};\n\nconst assertValidSkill = (entityType: string, value: string): void => {\n if (!isValidSkillId(value)) {\n throw new Error(\n `Invalid remote schema: ${entityType} \"${value}\". Must match ${SKILL_NAME_REGEX} (with optional .md extension)`,\n );\n }\n};\n\n/**\n * Validates property names in a JSON Schema node recursively.\n * Used for agent/query/connector schemas where we only need property name validation.\n */\nconst validateJsonSchemaProperties = (\n context: string,\n schema: Record<string, unknown>,\n depth: number,\n): void => {\n if (!schema || typeof schema !== \"object\") return;\n if (depth > MAX_SCHEMA_DEPTH) {\n throw new Error(\n `Invalid remote schema: ${context} exceeds maximum nesting depth of ${MAX_SCHEMA_DEPTH}`,\n );\n }\n\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (props) {\n const keys = Object.keys(props);\n if (keys.length > MAX_OBJECT_BREADTH) {\n throw new Error(\n `Invalid remote schema: ${context} has ${keys.length} properties, exceeding limit of ${MAX_OBJECT_BREADTH}`,\n );\n }\n for (const key of keys) {\n assertValidProperty(`${context} property name`, key);\n validateJsonSchemaProperties(context, props[key] ?? {}, depth + 1);\n }\n }\n\n const items = schema.items as Record<string, unknown> | undefined;\n if (items) {\n validateJsonSchemaProperties(context, items, depth + 1);\n }\n\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\"] as const) {\n const variants = schema[keyword] as Record<string, unknown>[] | undefined;\n if (variants) {\n for (const variant of variants) {\n validateJsonSchemaProperties(context, variant, depth + 1);\n }\n }\n }\n};\n\n/**\n * Validates pipeline JSON Schema nodes with stricter checks:\n * - All property name validation from validateJsonSchemaProperties\n * - Rejects `$ref` keys (prevents circular reference bypass in z.fromJSONSchema())\n * - Strips `pattern` keys (prevents ReDoS in z.fromJSONSchema() line 328)\n */\nconst validatePipelineSchema = (\n context: string,\n schema: Record<string, unknown>,\n depth: number,\n): void => {\n if (!schema || typeof schema !== \"object\") return;\n if (depth > MAX_SCHEMA_DEPTH) {\n throw new Error(\n `Invalid remote schema: ${context} exceeds maximum nesting depth of ${MAX_SCHEMA_DEPTH}`,\n );\n }\n\n if (\"$ref\" in schema) {\n throw new Error(\n `Invalid remote schema: ${context} contains \"$ref\" which is not supported in pipeline schemas`,\n );\n }\n\n // Strip `pattern` keys to prevent ReDoS in z.fromJSONSchema()\n if (\"pattern\" in schema) {\n delete schema.pattern;\n }\n\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (props) {\n const keys = Object.keys(props);\n if (keys.length > MAX_OBJECT_BREADTH) {\n throw new Error(\n `Invalid remote schema: ${context} has ${keys.length} properties, exceeding limit of ${MAX_OBJECT_BREADTH}`,\n );\n }\n for (const key of keys) {\n assertValidProperty(`${context} property name`, key);\n validatePipelineSchema(context, props[key] ?? {}, depth + 1);\n }\n }\n\n const items = schema.items as Record<string, unknown> | undefined;\n if (items) {\n validatePipelineSchema(context, items, depth + 1);\n }\n\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\"] as const) {\n const variants = schema[keyword] as Record<string, unknown>[] | undefined;\n if (variants) {\n for (const variant of variants) {\n validatePipelineSchema(context, variant, depth + 1);\n }\n }\n }\n};\n"],"mappings":";AAGO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B,OAAO;AAAA,EAEhB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B,OAAO;AAAA,EAEhB,YAAY,SAAiB;AAC3B,U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