kraken-ai 0.0.2 → 0.0.4

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProviderError
3
- } from "./chunk-4OPFQWI5.js";
3
+ } from "./chunk-RBQ2PPDE.js";
4
4
 
5
5
  // src/providers/google.ts
6
6
  var DEFAULT_RETRY = {
@@ -194,4 +194,3 @@ var google = (modelId, config) => {
194
194
  export {
195
195
  google
196
196
  };
197
- //# sourceMappingURL=chunk-FPQKOIPU.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProviderError
3
- } from "./chunk-4OPFQWI5.js";
3
+ } from "./chunk-RBQ2PPDE.js";
4
4
 
5
5
  // src/providers/openai.ts
6
6
  var openai = (_modelId) => {
@@ -10,4 +10,3 @@ var openai = (_modelId) => {
10
10
  export {
11
11
  openai
12
12
  };
13
- //# sourceMappingURL=chunk-QOSMK22V.js.map
@@ -61,4 +61,3 @@ export {
61
61
  ToolInputValidationError,
62
62
  OutputValidationError
63
63
  };
64
- //# sourceMappingURL=chunk-4OPFQWI5.js.map
@@ -0,0 +1,7 @@
1
+ import {
2
+ google
3
+ } from "./chunk-4X5NFWDA.js";
4
+ import "./chunk-RBQ2PPDE.js";
5
+ export {
6
+ google
7
+ };
package/dist/index.cjs CHANGED
@@ -1106,4 +1106,3 @@ Hint: The LLM provided arguments that don't match the tool's parameter schema. T
1106
1106
  openai,
1107
1107
  tool
1108
1108
  });
1109
- //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  google
3
- } from "./chunk-FPQKOIPU.js";
3
+ } from "./chunk-4X5NFWDA.js";
4
4
  import {
5
5
  openai
6
- } from "./chunk-QOSMK22V.js";
6
+ } from "./chunk-5XNFMNJL.js";
7
7
  import {
8
8
  KrakenError,
9
9
  OutputValidationError,
@@ -11,7 +11,7 @@ import {
11
11
  ToolError,
12
12
  ToolInputValidationError,
13
13
  ValidationError
14
- } from "./chunk-4OPFQWI5.js";
14
+ } from "./chunk-RBQ2PPDE.js";
15
15
 
16
16
  // src/agent.ts
17
17
  import * as z2 from "zod";
@@ -40,10 +40,10 @@ var createLazyModel = (provider, modelId) => {
40
40
  const ensureResolved = async () => {
41
41
  if (resolvedModel) return resolvedModel;
42
42
  if (provider === "google") {
43
- const { google: google2 } = await import("./google-7W6YAEI6.js");
43
+ const { google: google2 } = await import("./google-GNB46G6S.js");
44
44
  resolvedModel = google2(modelId);
45
45
  } else if (provider === "openai") {
46
- const { openai: openai2 } = await import("./openai-RC7BMWQY.js");
46
+ const { openai: openai2 } = await import("./openai-HXIIBATW.js");
47
47
  resolvedModel = openai2(modelId);
48
48
  } else {
49
49
  throw new ValidationError(`Unknown provider "${provider}".`);
@@ -778,4 +778,3 @@ export {
778
778
  openai,
779
779
  tool
780
780
  };
781
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ import {
2
+ openai
3
+ } from "./chunk-5XNFMNJL.js";
4
+ import "./chunk-RBQ2PPDE.js";
5
+ export {
6
+ openai
7
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kraken-ai",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Kraken AI SDK: a very lightweight, fully-typed multi-model AI agent framework",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -57,7 +57,7 @@
57
57
  "build": "tsup && pnpm install --lockfile-only --ignore-workspace",
58
58
  "test": "vitest run",
59
59
  "test:watch": "vitest",
60
- "check": "biome check && tsc --noEmit && tsc -p tsconfig.check.json --noEmit",
60
+ "check": "tsc --noEmit && tsc -p tsconfig.check.json --noEmit && biome check",
61
61
  "check:write": "biome check --write"
62
62
  }
63
63
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/** Base error class for all kraken-ai errors. */\nexport class KrakenError<C extends string = \"KRAKEN_ERROR\"> extends Error {\n readonly code: C;\n\n constructor(message: string, code?: C) {\n super(message);\n this.name = \"KrakenError\";\n this.code = (code ?? \"KRAKEN_ERROR\") as C;\n }\n}\n\n/** Error from an LLM provider (API failure, rate limit, etc.). */\nexport class ProviderError extends KrakenError<\"PROVIDER_ERROR\"> {\n constructor(message: string) {\n super(message, \"PROVIDER_ERROR\");\n this.name = \"ProviderError\";\n }\n}\n\n/** Error during tool execution. */\nexport class ToolError extends KrakenError<\"TOOL_ERROR\"> {\n constructor(\n message: string,\n readonly toolName: string,\n ) {\n super(message, \"TOOL_ERROR\");\n this.name = \"ToolError\";\n }\n}\n\n/** Error for invalid configuration or input. */\nexport class ValidationError extends KrakenError<\"VALIDATION_ERROR\"> {\n constructor(message: string) {\n super(message, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the LLM provides tool arguments that don't match the parameter schema.\n *\n * Contains the expected JSON Schema, received arguments, and per-field validation\n * errors so that LLM coding assistants (Cursor, Claude Code, etc.) can self-correct.\n */\nexport class ToolInputValidationError extends KrakenError<\"TOOL_INPUT_VALIDATION_ERROR\"> {\n readonly toolName: string;\n readonly expected: Record<string, unknown>;\n readonly received: unknown;\n\n constructor(\n message: string,\n toolName: string,\n expected: Record<string, unknown>,\n received: unknown,\n ) {\n super(message, \"TOOL_INPUT_VALIDATION_ERROR\");\n this.name = \"ToolInputValidationError\";\n this.toolName = toolName;\n this.expected = expected;\n this.received = received;\n }\n}\n\n/**\n * Thrown when the LLM's structured output doesn't match the agent's outputSchema.\n *\n * Contains the raw LLM text and validation details so the caller can diagnose\n * whether the model doesn't support structured output or the schema is too complex.\n */\nexport class OutputValidationError extends KrakenError<\"OUTPUT_VALIDATION_ERROR\"> {\n readonly rawOutput: string;\n /** Which attempt failed (1-indexed). Present when retries were attempted. */\n readonly attempt?: number;\n /** Total attempts configured. Present when retries were attempted. */\n readonly totalAttempts?: number;\n\n constructor(\n message: string,\n rawOutput: string,\n retryContext?: { attempt: number; totalAttempts: number },\n ) {\n super(message, \"OUTPUT_VALIDATION_ERROR\");\n this.name = \"OutputValidationError\";\n this.rawOutput = rawOutput;\n this.attempt = retryContext?.attempt;\n this.totalAttempts = retryContext?.totalAttempts;\n }\n}\n"],"mappings":";AACO,IAAM,cAAN,cAA6D,MAAM;AAAA,EAC/D;AAAA,EAET,YAAY,SAAiB,MAAU;AACrC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAQ,QAAQ;AAAA,EACvB;AACF;AAGO,IAAM,gBAAN,cAA4B,YAA8B;AAAA,EAC/D,YAAY,SAAiB;AAC3B,UAAM,SAAS,gBAAgB;AAC/B,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,YAAN,cAAwB,YAA0B;AAAA,EACvD,YACE,SACS,UACT;AACA,UAAM,SAAS,YAAY;AAFlB;AAGT,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,kBAAN,cAA8B,YAAgC;AAAA,EACnE,YAAY,SAAiB;AAC3B,UAAM,SAAS,kBAAkB;AACjC,SAAK,OAAO;AAAA,EACd;AACF;AAQO,IAAM,2BAAN,cAAuC,YAA2C;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,UACA,UACA,UACA;AACA,UAAM,SAAS,6BAA6B;AAC5C,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,WAAW;AAAA,EAClB;AACF;AAQO,IAAM,wBAAN,cAAoC,YAAuC;AAAA,EACvE;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YACE,SACA,WACA,cACA;AACA,UAAM,SAAS,yBAAyB;AACxC,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,UAAU,cAAc;AAC7B,SAAK,gBAAgB,cAAc;AAAA,EACrC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/google.ts"],"sourcesContent":["import { ProviderError } from \"../errors\";\nimport type { GoogleModelConfig, RetryConfig } from \"../model\";\nimport type {\n GenerateParams,\n GenerateResponse,\n GoogleModelId,\n Model,\n StreamChunk,\n ToolCall,\n} from \"../types\";\n\nexport type { GoogleModelConfig } from \"../model\";\nexport type { GoogleModelId } from \"../types\";\n\nconst DEFAULT_RETRY: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 500,\n maxDelayMs: 30_000,\n jitter: true,\n};\n\nconst RETRYABLE_STATUS_CODES = new Set([408, 429, 500, 502, 503]);\n\nconst retryWithBackoff = async <T>(\n fn: () => Promise<T>,\n config: RetryConfig,\n signal?: AbortSignal,\n): Promise<T> => {\n let lastError: unknown;\n for (let attempt = 0; attempt <= config.maxRetries; attempt++) {\n try {\n signal?.throwIfAborted();\n return await fn();\n } catch (err: unknown) {\n lastError = err;\n const status = (err as { status?: number }).status;\n if (status && !RETRYABLE_STATUS_CODES.has(status)) throw err;\n if (attempt === config.maxRetries) break;\n\n const delay = Math.min(config.baseDelayMs * 2 ** attempt, config.maxDelayMs);\n const jittered = config.jitter ? delay * (0.5 + Math.random() * 0.5) : delay;\n await new Promise((resolve) => setTimeout(resolve, jittered));\n }\n }\n throw lastError;\n};\n\ntype ResponsePart = {\n text?: string;\n thought?: boolean;\n functionCall?: { name: string; args: Record<string, unknown> };\n thoughtSignature?: string;\n};\n\ntype StreamResponseChunk = {\n candidates?: Array<{\n content?: { parts?: ResponsePart[] };\n }>;\n functionCalls?: Array<{ name: string; args: Record<string, unknown> }>;\n usageMetadata?: { promptTokenCount?: number; candidatesTokenCount?: number };\n};\n\ntype GenAIClient = {\n models: {\n generateContent: (params: Record<string, unknown>) => Promise<{\n text?: string;\n functionCalls?: Array<{ name: string; args: Record<string, unknown> }>;\n usageMetadata?: { promptTokenCount?: number; candidatesTokenCount?: number };\n candidates?: Array<{\n content?: { parts?: ResponsePart[] };\n }>;\n }>;\n generateContentStream: (\n params: Record<string, unknown>,\n ) => Promise<AsyncGenerator<StreamResponseChunk>>;\n };\n};\n\nlet cachedClient: GenAIClient | undefined;\nlet cachedApiKey: string | undefined;\n\nconst getClient = async (apiKey?: string): Promise<GenAIClient> => {\n const key = apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;\n if (!key)\n throw new ProviderError(\"Missing API key. Set GEMINI_API_KEY or pass apiKey in config.\");\n\n if (cachedClient && cachedApiKey === key) return cachedClient;\n\n const { GoogleGenAI } = await import(\"@google/genai\");\n cachedClient = new GoogleGenAI({ apiKey: key }) as unknown as GenAIClient;\n cachedApiKey = key;\n return cachedClient;\n};\n\ntype GeminiPart = Record<string, unknown>;\ntype GeminiContent = { role: string; parts: GeminiPart[] };\n\nconst convertMessages = (messages: GenerateParams[\"messages\"]): GeminiContent[] =>\n messages.map((m) => {\n const parts: GeminiPart[] = [];\n\n if (m.content) {\n parts.push({ text: m.content });\n }\n\n if (m.toolCalls) {\n for (const tc of m.toolCalls) {\n const part: GeminiPart = {\n functionCall: {\n name: tc.name,\n args: (tc.args ?? {}) as Record<string, unknown>,\n },\n };\n if (tc._meta?.thoughtSignature) {\n part.thoughtSignature = tc._meta.thoughtSignature;\n }\n parts.push(part);\n }\n }\n\n if (m.toolResults) {\n for (const tr of m.toolResults) {\n parts.push({\n functionResponse: {\n id: tr.toolCallId,\n name: tr.name,\n response: { output: tr.result },\n },\n });\n }\n }\n\n return {\n role: m.role === \"assistant\" ? \"model\" : \"user\",\n parts: parts.length > 0 ? parts : [{ text: \"\" }],\n };\n });\n\nconst extractToolCalls = (parts: ResponsePart[]): ToolCall[] | undefined => {\n const fcParts = parts.filter(\n (p): p is ResponsePart & { functionCall: NonNullable<ResponsePart[\"functionCall\"]> } =>\n !!p.functionCall,\n );\n if (!fcParts.length) return undefined;\n return fcParts.map((p, i) => ({\n id: `fc_${i}_${Date.now()}`,\n name: p.functionCall.name,\n args: p.functionCall.args,\n _meta: p.thoughtSignature ? { thoughtSignature: p.thoughtSignature } : undefined,\n }));\n};\n\n/**\n * Create a Google Gemini model.\n *\n * @example\n * ```ts\n * const model = google(\"gemini-2.5-flash\");\n * ```\n */\nconst buildRequestConfig = (params: GenerateParams) => {\n const tools = params.tools?.length\n ? [\n {\n functionDeclarations: params.tools.map((t) => ({\n name: t.name,\n description: t.description,\n parametersJsonSchema: t.parameters,\n })),\n },\n ]\n : undefined;\n\n const thinkingConfig: Record<string, unknown> = { includeThoughts: true };\n if (params.thinkingLevel) {\n thinkingConfig.thinkingLevel = params.thinkingLevel.toUpperCase();\n }\n const generateConfig: Record<string, unknown> = { thinkingConfig };\n if (params.system) generateConfig.systemInstruction = params.system;\n if (params.temperature != null) generateConfig.temperature = params.temperature;\n if (params.maxOutputTokens != null) generateConfig.maxOutputTokens = params.maxOutputTokens;\n if (params.responseSchema) {\n generateConfig.responseMimeType = \"application/json\";\n generateConfig.responseSchema = params.responseSchema;\n }\n if (tools) generateConfig.tools = tools;\n return generateConfig;\n};\n\nexport const google = (modelId: GoogleModelId, config?: GoogleModelConfig): Model => {\n const retryConfig: RetryConfig = { ...DEFAULT_RETRY, ...config?.retry };\n\n return {\n provider: \"google\",\n modelId,\n preflight: async () => {\n await getClient(config?.apiKey);\n },\n generate: async (params) => {\n const client = await getClient(config?.apiKey);\n const generateConfig = buildRequestConfig(params);\n\n const response = await retryWithBackoff(\n () =>\n client.models.generateContent({\n model: modelId,\n contents: convertMessages(params.messages),\n config: generateConfig,\n }),\n retryConfig,\n params.signal,\n );\n\n const allParts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = extractToolCalls(allParts);\n\n const thoughtParts = allParts.filter((p) => p.thought && p.text).map((p) => p.text ?? \"\");\n const thoughts = thoughtParts.length > 0 ? thoughtParts.join(\"\\n\") : undefined;\n\n return {\n text: response.text ?? \"\",\n thoughts,\n toolCalls,\n usage: {\n inputTokens: response.usageMetadata?.promptTokenCount ?? 0,\n outputTokens: response.usageMetadata?.candidatesTokenCount ?? 0,\n },\n } satisfies GenerateResponse;\n },\n\n async *generateStream(params) {\n const client = await getClient(config?.apiKey);\n const generateConfig = buildRequestConfig(params);\n\n const stream = await client.models.generateContentStream({\n model: modelId,\n contents: convertMessages(params.messages),\n config: generateConfig,\n });\n\n let fullText = \"\";\n let fullThoughts = \"\";\n const allFcParts: ResponsePart[] = [];\n let lastUsage: { promptTokenCount?: number; candidatesTokenCount?: number } | undefined;\n\n for await (const chunk of stream) {\n const parts = chunk.candidates?.[0]?.content?.parts ?? [];\n for (const part of parts) {\n if (part.functionCall) {\n allFcParts.push(part);\n continue;\n }\n if (!part.text) continue;\n if (part.thought) {\n fullThoughts += part.text;\n yield { thoughts: part.text } satisfies StreamChunk;\n } else {\n fullText += part.text;\n yield { text: part.text } satisfies StreamChunk;\n }\n }\n if (chunk.usageMetadata) {\n lastUsage = chunk.usageMetadata;\n }\n }\n\n return {\n text: fullText,\n thoughts: fullThoughts || undefined,\n toolCalls: extractToolCalls(allFcParts),\n usage: {\n inputTokens: lastUsage?.promptTokenCount ?? 0,\n outputTokens: lastUsage?.candidatesTokenCount ?? 0,\n },\n } satisfies GenerateResponse;\n },\n };\n};\n"],"mappings":";;;;;AAcA,IAAM,gBAA6B;AAAA,EACjC,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,QAAQ;AACV;AAEA,IAAM,yBAAyB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAEhE,IAAM,mBAAmB,OACvB,IACA,QACA,WACe;AACf,MAAI;AACJ,WAAS,UAAU,GAAG,WAAW,OAAO,YAAY,WAAW;AAC7D,QAAI;AACF,cAAQ,eAAe;AACvB,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,KAAc;AACrB,kBAAY;AACZ,YAAM,SAAU,IAA4B;AAC5C,UAAI,UAAU,CAAC,uBAAuB,IAAI,MAAM,EAAG,OAAM;AACzD,UAAI,YAAY,OAAO,WAAY;AAEnC,YAAM,QAAQ,KAAK,IAAI,OAAO,cAAc,KAAK,SAAS,OAAO,UAAU;AAC3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,aAA6B,CAAC;AACpC,UAAI;AAEJ,uBAAiB,SAAS,QAAQ;AAChC,cAAM,QAAQ,MAAM,aAAa,CAAC,GAAG,SAAS,SAAS,CAAC;AACxD,mBAAW,QAAQ,OAAO;AACxB,cAAI,KAAK,cAAc;AACrB,uBAAW,KAAK,IAAI;AACpB;AAAA,UACF;AACA,cAAI,CAAC,KAAK,KAAM;AAChB,cAAI,KAAK,SAAS;AAChB,4BAAgB,KAAK;AACrB,kBAAM,EAAE,UAAU,KAAK,KAAK;AAAA,UAC9B,OAAO;AACL,wBAAY,KAAK;AACjB,kBAAM,EAAE,MAAM,KAAK,KAAK;AAAA,UAC1B;AAAA,QACF;AACA,YAAI,MAAM,eAAe;AACvB,sBAAY,MAAM;AAAA,QACpB;AAAA,MACF;AAEA,aAAO;AAAA,QACL,MAAM;AAAA,QACN,UAAU,gBAAgB;AAAA,QAC1B,WAAW,iBAAiB,UAAU;AAAA,QACtC,OAAO;AAAA,UACL,aAAa,WAAW,oBAAoB;AAAA,UAC5C,cAAc,WAAW,wBAAwB;AAAA,QACnD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/openai.ts"],"sourcesContent":["import { ProviderError } from \"../errors\";\nimport type { Model, OpenAIModelId } from \"../types\";\n\nexport type { OpenAIModelId } from \"../types\";\n\n/**\n * Create an OpenAI model (not yet implemented).\n *\n * @throws {ProviderError} Always — OpenAI support is planned for a future release.\n */\nexport const openai = (_modelId: OpenAIModelId): Model => {\n throw new ProviderError(\"OpenAI provider is not yet implemented.\");\n};\n"],"mappings":";;;;;AAUO,IAAM,SAAS,CAAC,aAAmC;AACxD,QAAM,IAAI,cAAc,yCAAyC;AACnE;","names":[]}
@@ -1,8 +0,0 @@
1
- import {
2
- google
3
- } from "./chunk-FPQKOIPU.js";
4
- import "./chunk-4OPFQWI5.js";
5
- export {
6
- google
7
- };
8
- //# sourceMappingURL=google-7W6YAEI6.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/providers/google.ts","../src/providers/openai.ts","../src/index.ts","../src/agent.ts","../src/model.ts","../src/runtime/delegation.ts","../src/runtime/logger.ts","../src/runtime/runner.ts","../src/runtime/events.ts","../src/runtime/lifecycle.ts","../src/configure.ts","../src/format-event.ts","../src/kernel.ts","../src/providers/mock.ts","../src/tool.ts"],"sourcesContent":["/** Base error class for all kraken-ai errors. */\nexport class KrakenError<C extends string = \"KRAKEN_ERROR\"> extends Error {\n readonly code: C;\n\n constructor(message: string, code?: C) {\n super(message);\n this.name = \"KrakenError\";\n this.code = (code ?? \"KRAKEN_ERROR\") as C;\n }\n}\n\n/** Error from an LLM provider (API failure, rate limit, etc.). */\nexport class ProviderError extends KrakenError<\"PROVIDER_ERROR\"> {\n constructor(message: string) {\n super(message, \"PROVIDER_ERROR\");\n this.name = \"ProviderError\";\n }\n}\n\n/** Error during tool execution. */\nexport class ToolError extends KrakenError<\"TOOL_ERROR\"> {\n constructor(\n message: string,\n readonly toolName: string,\n ) {\n super(message, \"TOOL_ERROR\");\n this.name = \"ToolError\";\n }\n}\n\n/** Error for invalid configuration or input. */\nexport class ValidationError extends KrakenError<\"VALIDATION_ERROR\"> {\n constructor(message: string) {\n super(message, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the LLM provides tool arguments that don't match the parameter schema.\n *\n * Contains the expected JSON Schema, received arguments, and per-field validation\n * errors so that LLM coding assistants (Cursor, Claude Code, etc.) can self-correct.\n */\nexport class ToolInputValidationError extends KrakenError<\"TOOL_INPUT_VALIDATION_ERROR\"> {\n readonly toolName: string;\n readonly expected: Record<string, unknown>;\n readonly received: unknown;\n\n constructor(\n message: string,\n toolName: string,\n expected: Record<string, unknown>,\n received: unknown,\n ) {\n super(message, \"TOOL_INPUT_VALIDATION_ERROR\");\n this.name = \"ToolInputValidationError\";\n this.toolName = toolName;\n this.expected = expected;\n this.received = received;\n }\n}\n\n/**\n * Thrown when the LLM's structured output doesn't match the agent's outputSchema.\n *\n * Contains the raw LLM text and validation details so the caller can diagnose\n * whether the model doesn't support structured output or the schema is too complex.\n */\nexport class OutputValidationError extends KrakenError<\"OUTPUT_VALIDATION_ERROR\"> {\n readonly rawOutput: string;\n /** Which attempt failed (1-indexed). Present when retries were attempted. */\n readonly attempt?: number;\n /** Total attempts configured. Present when retries were attempted. */\n readonly totalAttempts?: number;\n\n constructor(\n message: string,\n rawOutput: string,\n retryContext?: { attempt: number; totalAttempts: number },\n ) {\n super(message, \"OUTPUT_VALIDATION_ERROR\");\n this.name = \"OutputValidationError\";\n this.rawOutput = rawOutput;\n this.attempt = retryContext?.attempt;\n this.totalAttempts = retryContext?.totalAttempts;\n }\n}\n","import { ProviderError } from \"../errors\";\nimport type { GoogleModelConfig, RetryConfig } from \"../model\";\nimport type {\n GenerateParams,\n GenerateResponse,\n GoogleModelId,\n Model,\n StreamChunk,\n ToolCall,\n} from \"../types\";\n\nexport type { GoogleModelConfig } from \"../model\";\nexport type { GoogleModelId } from \"../types\";\n\nconst DEFAULT_RETRY: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 500,\n maxDelayMs: 30_000,\n jitter: true,\n};\n\nconst RETRYABLE_STATUS_CODES = new Set([408, 429, 500, 502, 503]);\n\nconst retryWithBackoff = async <T>(\n fn: () => Promise<T>,\n config: RetryConfig,\n signal?: AbortSignal,\n): Promise<T> => {\n let lastError: unknown;\n for (let attempt = 0; attempt <= config.maxRetries; attempt++) {\n try {\n signal?.throwIfAborted();\n return await fn();\n } catch (err: unknown) {\n lastError = err;\n const status = (err as { status?: number }).status;\n if (status && !RETRYABLE_STATUS_CODES.has(status)) throw err;\n if (attempt === config.maxRetries) break;\n\n const delay = Math.min(config.baseDelayMs * 2 ** attempt, config.maxDelayMs);\n const jittered = config.jitter ? delay * (0.5 + Math.random() * 0.5) : delay;\n await new Promise((resolve) => setTimeout(resolve, jittered));\n }\n }\n throw lastError;\n};\n\ntype ResponsePart = {\n text?: string;\n thought?: boolean;\n functionCall?: { name: string; args: Record<string, unknown> };\n thoughtSignature?: string;\n};\n\ntype StreamResponseChunk = {\n candidates?: Array<{\n content?: { parts?: ResponsePart[] };\n }>;\n functionCalls?: Array<{ name: string; args: Record<string, unknown> }>;\n usageMetadata?: { promptTokenCount?: number; candidatesTokenCount?: number };\n};\n\ntype GenAIClient = {\n models: {\n generateContent: (params: Record<string, unknown>) => Promise<{\n text?: string;\n functionCalls?: Array<{ name: string; args: Record<string, unknown> }>;\n usageMetadata?: { promptTokenCount?: number; candidatesTokenCount?: number };\n candidates?: Array<{\n content?: { parts?: ResponsePart[] };\n }>;\n }>;\n generateContentStream: (\n params: Record<string, unknown>,\n ) => Promise<AsyncGenerator<StreamResponseChunk>>;\n };\n};\n\nlet cachedClient: GenAIClient | undefined;\nlet cachedApiKey: string | undefined;\n\nconst getClient = async (apiKey?: string): Promise<GenAIClient> => {\n const key = apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;\n if (!key)\n throw new ProviderError(\"Missing API key. Set GEMINI_API_KEY or pass apiKey in config.\");\n\n if (cachedClient && cachedApiKey === key) return cachedClient;\n\n const { GoogleGenAI } = await import(\"@google/genai\");\n cachedClient = new GoogleGenAI({ apiKey: key }) as unknown as GenAIClient;\n cachedApiKey = key;\n return cachedClient;\n};\n\ntype GeminiPart = Record<string, unknown>;\ntype GeminiContent = { role: string; parts: GeminiPart[] };\n\nconst convertMessages = (messages: GenerateParams[\"messages\"]): GeminiContent[] =>\n messages.map((m) => {\n const parts: GeminiPart[] = [];\n\n if (m.content) {\n parts.push({ text: m.content });\n }\n\n if (m.toolCalls) {\n for (const tc of m.toolCalls) {\n const part: GeminiPart = {\n functionCall: {\n name: tc.name,\n args: (tc.args ?? {}) as Record<string, unknown>,\n },\n };\n if (tc._meta?.thoughtSignature) {\n part.thoughtSignature = tc._meta.thoughtSignature;\n }\n parts.push(part);\n }\n }\n\n if (m.toolResults) {\n for (const tr of m.toolResults) {\n parts.push({\n functionResponse: {\n id: tr.toolCallId,\n name: tr.name,\n response: { output: tr.result },\n },\n });\n }\n }\n\n return {\n role: m.role === \"assistant\" ? \"model\" : \"user\",\n parts: parts.length > 0 ? parts : [{ text: \"\" }],\n };\n });\n\nconst extractToolCalls = (parts: ResponsePart[]): ToolCall[] | undefined => {\n const fcParts = parts.filter(\n (p): p is ResponsePart & { functionCall: NonNullable<ResponsePart[\"functionCall\"]> } =>\n !!p.functionCall,\n );\n if (!fcParts.length) return undefined;\n return fcParts.map((p, i) => ({\n id: `fc_${i}_${Date.now()}`,\n name: p.functionCall.name,\n args: p.functionCall.args,\n _meta: p.thoughtSignature ? { thoughtSignature: p.thoughtSignature } : undefined,\n }));\n};\n\n/**\n * Create a Google Gemini model.\n *\n * @example\n * ```ts\n * const model = google(\"gemini-2.5-flash\");\n * ```\n */\nconst buildRequestConfig = (params: GenerateParams) => {\n const tools = params.tools?.length\n ? [\n {\n functionDeclarations: params.tools.map((t) => ({\n name: t.name,\n description: t.description,\n parametersJsonSchema: t.parameters,\n })),\n },\n ]\n : undefined;\n\n const thinkingConfig: Record<string, unknown> = { includeThoughts: true };\n if (params.thinkingLevel) {\n thinkingConfig.thinkingLevel = params.thinkingLevel.toUpperCase();\n }\n const generateConfig: Record<string, unknown> = { thinkingConfig };\n if (params.system) generateConfig.systemInstruction = params.system;\n if (params.temperature != null) generateConfig.temperature = params.temperature;\n if (params.maxOutputTokens != null) generateConfig.maxOutputTokens = params.maxOutputTokens;\n if (params.responseSchema) {\n generateConfig.responseMimeType = \"application/json\";\n generateConfig.responseSchema = params.responseSchema;\n }\n if (tools) generateConfig.tools = tools;\n return generateConfig;\n};\n\nexport const google = (modelId: GoogleModelId, config?: GoogleModelConfig): Model => {\n const retryConfig: RetryConfig = { ...DEFAULT_RETRY, ...config?.retry };\n\n return {\n provider: \"google\",\n modelId,\n preflight: async () => {\n await getClient(config?.apiKey);\n },\n generate: async (params) => {\n const client = await getClient(config?.apiKey);\n const generateConfig = buildRequestConfig(params);\n\n const response = await retryWithBackoff(\n () =>\n client.models.generateContent({\n model: modelId,\n contents: convertMessages(params.messages),\n config: generateConfig,\n }),\n retryConfig,\n params.signal,\n );\n\n const allParts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = extractToolCalls(allParts);\n\n const thoughtParts = allParts.filter((p) => p.thought && p.text).map((p) => p.text ?? \"\");\n const thoughts = thoughtParts.length > 0 ? thoughtParts.join(\"\\n\") : undefined;\n\n return {\n text: response.text ?? \"\",\n thoughts,\n toolCalls,\n usage: {\n inputTokens: response.usageMetadata?.promptTokenCount ?? 0,\n outputTokens: response.usageMetadata?.candidatesTokenCount ?? 0,\n },\n } satisfies GenerateResponse;\n },\n\n async *generateStream(params) {\n const client = await getClient(config?.apiKey);\n const generateConfig = buildRequestConfig(params);\n\n const stream = await client.models.generateContentStream({\n model: modelId,\n contents: convertMessages(params.messages),\n config: generateConfig,\n });\n\n let fullText = \"\";\n let fullThoughts = \"\";\n const allFcParts: ResponsePart[] = [];\n let lastUsage: { promptTokenCount?: number; candidatesTokenCount?: number } | undefined;\n\n for await (const chunk of stream) {\n const parts = chunk.candidates?.[0]?.content?.parts ?? [];\n for (const part of parts) {\n if (part.functionCall) {\n allFcParts.push(part);\n continue;\n }\n if (!part.text) continue;\n if (part.thought) {\n fullThoughts += part.text;\n yield { thoughts: part.text } satisfies StreamChunk;\n } else {\n fullText += part.text;\n yield { text: part.text } satisfies StreamChunk;\n }\n }\n if (chunk.usageMetadata) {\n lastUsage = chunk.usageMetadata;\n }\n }\n\n return {\n text: fullText,\n thoughts: fullThoughts || undefined,\n toolCalls: extractToolCalls(allFcParts),\n usage: {\n inputTokens: lastUsage?.promptTokenCount ?? 0,\n outputTokens: lastUsage?.candidatesTokenCount ?? 0,\n },\n } satisfies GenerateResponse;\n },\n };\n};\n","import { ProviderError } from \"../errors\";\nimport type { Model, OpenAIModelId } from \"../types\";\n\nexport type { OpenAIModelId } from \"../types\";\n\n/**\n * Create an OpenAI model (not yet implemented).\n *\n * @throws {ProviderError} Always — OpenAI support is planned for a future release.\n */\nexport const openai = (_modelId: OpenAIModelId): Model => {\n throw new ProviderError(\"OpenAI provider is not yet implemented.\");\n};\n","// src/index.ts — public API\n\n// Core\nexport { Agent } from \"./agent\";\nexport type { GlobalConfig } from \"./configure\";\n// Configuration\nexport { configure } from \"./configure\";\n// Errors\nexport {\n KrakenError,\n OutputValidationError,\n ProviderError,\n ToolError,\n ToolInputValidationError,\n ValidationError,\n} from \"./errors\";\n// Events\nexport { formatEvent } from \"./format-event\";\n// Kernel\nexport { defineKernel } from \"./kernel\";\n// Middleware\nexport type { Middleware, MiddlewareContext } from \"./middleware\";\nexport type { GoogleModelConfig, RetryConfig } from \"./model\";\n// Model\nexport { google } from \"./providers/google\";\nexport { mock } from \"./providers/mock\";\nexport { openai } from \"./providers/openai\";\nexport type { ToolConfig } from \"./tool\";\n// Tools\nexport { tool } from \"./tool\";\n// Types\nexport type {\n AgentConfig,\n AgentConfigEvent,\n AgentDelegationEvent,\n AgentErrorEvent,\n AgentEvent,\n AgentEventBase,\n AgentEventPayload,\n AgentEventType,\n AgentInterruptEvent,\n AgentKillEvent,\n AgentLifecycleEvent,\n AgentLike,\n AgentLLMCallEvent,\n AgentNotificationEvent,\n AgentRef,\n AgentState,\n AgentStructuredOutputCompleteEvent,\n AgentThoughtEvent,\n AgentToolCallEvent,\n ExecutionContext,\n GenerateParams,\n GenerateResponse,\n GoogleModelId,\n HumanDecision,\n Interrupt,\n Kernel,\n KernelSignal,\n LogLevel,\n Message,\n Model,\n ModelParams,\n ModelString,\n OpenAIModelId,\n RunnerResponse,\n RunOptions,\n RunResult,\n SpawnSpec,\n StreamChunk,\n TeamAccessor,\n ThinkingLevel,\n Tool,\n ToolCall,\n ToolDefinition,\n ToolResult,\n TransitionRecord,\n Usage,\n} from \"./types\";\n","import * as z from \"zod\";\nimport { OutputValidationError } from \"./errors\";\nimport { resolveModel } from \"./model\";\nimport { createDelegationTools } from \"./runtime/delegation\";\nimport { createLogger } from \"./runtime/logger\";\nimport { createRunner } from \"./runtime/runner\";\nimport type {\n AgentConfig,\n AgentLike,\n LogLevel,\n Message,\n Model,\n RunOptions,\n RunResult,\n ThinkingLevel,\n Tool,\n Usage,\n} from \"./types\";\n\n/**\n * An AI agent with optional tools and team.\n *\n * @typeParam TOutput - Schema for structured output. When provided via\n * `outputSchema`, the `run()` result's `output` field is typed as\n * `z.infer<TOutput>`. Inferred automatically — no need to specify manually.\n *\n * @example\n * ```ts\n * // Unstructured output (output: unknown)\n * const agent = new Agent({\n * name: \"assistant\",\n * model: \"google/gemini-3.1-pro-preview\",\n * instructions: \"You are a helpful assistant.\",\n * });\n *\n * // Structured typed output (output: { sentiment: string })\n * const analyzer = new Agent({\n * name: \"analyzer\",\n * model: \"google/gemini-3.1-pro-preview\",\n * instructions: \"Analyze sentiment.\",\n * outputSchema: z.object({ sentiment: z.string() }),\n * });\n * const result = await analyzer.run([{ role: \"user\", content: \"I love this!\" }]);\n * if (result.status === \"complete\") {\n * result.output.sentiment; // string — fully typed!\n * }\n * ```\n */\nexport class Agent<TOutput extends z.ZodType = z.ZodType> implements AgentLike {\n readonly name: string;\n readonly description?: string;\n private readonly config: AgentConfig<TOutput>;\n private readonly resolvedModel: Model;\n\n constructor(config: AgentConfig<TOutput>) {\n this.config = config;\n this.name = config.name;\n this.description = config.description;\n this.resolvedModel = resolveModel(config.model);\n }\n\n /** Eagerly validate configuration (API keys, provider availability) before the first run. */\n async preflight(): Promise<void> {\n await this.resolvedModel.preflight?.();\n }\n\n /** Returns the agent definition as a plain serializable object (no tools, team, or kernel). */\n get definition(): {\n name: string;\n model: string;\n instructions: string;\n description?: string;\n temperature?: number;\n allowTemperatureOverride?: boolean;\n maxOutputTokens?: number;\n thinkingLevel?: ThinkingLevel;\n logLevel?: LogLevel;\n } {\n const model =\n typeof this.config.model === \"string\"\n ? this.config.model\n : `${this.config.model.provider}/${this.config.model.modelId}`;\n\n const def: Record<string, unknown> = {\n name: this.config.name,\n model,\n instructions: this.config.instructions,\n };\n\n if (this.config.description !== undefined) def.description = this.config.description;\n if (this.config.temperature !== undefined) def.temperature = this.config.temperature;\n if (this.config.allowTemperatureOverride !== undefined)\n def.allowTemperatureOverride = this.config.allowTemperatureOverride;\n if (this.config.maxOutputTokens !== undefined)\n def.maxOutputTokens = this.config.maxOutputTokens;\n if (this.config.thinkingLevel !== undefined) def.thinkingLevel = this.config.thinkingLevel;\n if (this.config.logLevel !== undefined) def.logLevel = this.config.logLevel;\n\n return def as Agent[\"definition\"];\n }\n\n /**\n * Run the agent with a message history.\n *\n * @param messages - Non-empty array of conversation messages.\n * @param options - Run options (middleware, signal, onEvent, runId).\n * @returns RunResult — either complete or interrupted for HITL.\n * When `outputSchema` is configured, the `output` field of a complete\n * result is parsed and validated against the schema at runtime.\n */\n async run(messages: Message[], options?: RunOptions): Promise<RunResult<z.infer<TOutput>>> {\n const allTools: Tool[] = [...(this.config.tools ?? [])];\n const logger = createLogger(this.config.logLevel);\n const runId = options?.runId ?? crypto.randomUUID();\n\n // Resolve temperature: respect allowTemperatureOverride flag\n let resolvedTemperature: number | undefined;\n if (this.config.allowTemperatureOverride === false && this.config.temperature != null) {\n resolvedTemperature = this.config.temperature;\n if (options?.temperature != null) {\n logger.warn(\n `Agent \"${this.name}\" has temperature locked to ${this.config.temperature}, ignoring override`,\n );\n }\n } else {\n resolvedTemperature = options?.temperature ?? this.config.temperature;\n }\n const resolvedThinkingLevel = options?.thinkingLevel ?? this.config.thinkingLevel;\n const resolvedMaxOutputTokens = options?.maxOutputTokens ?? this.config.maxOutputTokens;\n\n const childRunIds = new Map<string, string[]>();\n\n if (this.config.team?.length) {\n const propagated: Partial<RunOptions> = {\n middleware: options?.middleware,\n signal: options?.signal,\n onEvent: options?.onEvent,\n parentRunId: runId,\n ...(resolvedTemperature != null ? { temperature: resolvedTemperature } : {}),\n ...(resolvedThinkingLevel ? { thinkingLevel: resolvedThinkingLevel } : {}),\n ...(resolvedMaxOutputTokens != null ? { maxOutputTokens: resolvedMaxOutputTokens } : {}),\n };\n const delegationTools = createDelegationTools(this.config.team, propagated, childRunIds);\n allTools.push(...delegationTools);\n }\n\n const runner = createRunner({\n agent: {\n name: this.name,\n description: this.description,\n instructions: this.config.instructions,\n },\n model: this.resolvedModel,\n tools: allTools,\n temperature: resolvedTemperature,\n maxOutputTokens: resolvedMaxOutputTokens,\n thinkingLevel: resolvedThinkingLevel,\n responseSchema: this.config.outputSchema\n ? (z.toJSONSchema(this.config.outputSchema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >)\n : undefined,\n logLevel: this.config.logLevel,\n });\n\n const result = await runner.run(messages, { ...options, runId, _childRunIds: childRunIds });\n\n if (result.status === \"complete\" && this.config.outputSchema) {\n const validated = await this.produceStructuredOutput(result, options);\n options?.onEvent?.({\n type: \"structured_output_complete\",\n agentName: this.name,\n runId,\n timestamp: new Date().toISOString(),\n seq: -1,\n output: validated.data,\n });\n return {\n ...result,\n output: validated.data,\n usage: validated.usage,\n };\n }\n\n return result as RunResult<z.infer<TOutput>>;\n }\n\n /**\n * Validate structured output with retry. On validation failure, feeds the error\n * back to the LLM and retries (up to 3 total attempts). Retry messages are kept\n * in a separate array to avoid polluting RunResult.messages.\n */\n private async produceStructuredOutput(\n runnerResult: Extract<RunResult, { status: \"complete\" }>,\n options?: RunOptions,\n ): Promise<{ data: z.infer<TOutput>; usage: Usage }> {\n const schema = this.config.outputSchema as z.ZodType;\n const jsonSchema = z.toJSONSchema(schema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >;\n const maxAttempts = 3;\n const accumulatedUsage = { ...runnerResult.usage };\n\n // Separate messages array for retries — original runnerResult.messages stays clean\n const retryMessages: Message[] = [...runnerResult.messages];\n let rawOutput = runnerResult.output as string;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const validationResult = this.tryParseOutput(rawOutput, schema, jsonSchema);\n\n if (validationResult.success) {\n return { data: validationResult.data, usage: accumulatedUsage };\n }\n\n if (attempt === maxAttempts) {\n throw new OutputValidationError(\n `Agent \"${this.name}\" structured output validation failed after ${maxAttempts} attempts.\\n\\n` +\n `${validationResult.error}`,\n rawOutput,\n { attempt, totalAttempts: maxAttempts },\n );\n }\n\n // Feed error back to LLM for retry\n retryMessages.push(\n { role: \"assistant\", content: rawOutput },\n {\n role: \"user\",\n content:\n `Schema validation error: ${validationResult.error}\\n\\n` +\n `Please produce valid JSON output matching the required schema.`,\n },\n );\n\n const response = await this.resolvedModel.generate({\n system: this.config.instructions,\n messages: retryMessages,\n responseSchema: jsonSchema,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n thinkingLevel: this.config.thinkingLevel,\n signal: options?.signal,\n });\n\n accumulatedUsage.inputTokens += response.usage.inputTokens;\n accumulatedUsage.outputTokens += response.usage.outputTokens;\n rawOutput = response.text;\n }\n\n // Unreachable — loop always returns or throws\n throw new Error(\"Unreachable\");\n }\n\n private tryParseOutput(\n rawText: string,\n schema: z.ZodType,\n jsonSchema: Record<string, unknown>,\n ): { success: true; data: z.infer<TOutput> } | { success: false; error: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawText);\n } catch {\n return {\n success: false,\n error:\n `LLM returned invalid JSON.\\n\\n` +\n `Expected output matching schema:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Raw LLM response:\\n${rawText}`,\n };\n }\n\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues;\n return {\n success: false,\n error:\n `Zod validation failed.\\n\\n` +\n `Expected:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Received:\\n${JSON.stringify(parsed, null, 2)}\\n\\n` +\n `Errors:\\n${issues.map((i) => ` - ${String(i.path.join(\".\"))}: ${i.message}`).join(\"\\n\")}`,\n };\n }\n\n return { success: true, data: result.data as z.infer<TOutput> };\n }\n}\n","import { ValidationError } from \"./errors\";\nimport type { GoogleModelId, Model, ModelString, OpenAIModelId } from \"./types\";\n\nexport type { GoogleModelId, Model, ModelString, OpenAIModelId } from \"./types\";\n\n/** Retry configuration for provider API calls. */\nexport interface RetryConfig {\n maxRetries: number;\n baseDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}\n\n/** Configuration for the Google provider factory. */\nexport interface GoogleModelConfig {\n apiKey?: string;\n retry?: Partial<RetryConfig>;\n}\n\nconst SUPPORTED_PROVIDERS = new Set([\"google\", \"openai\"]);\n\n/**\n * Resolve a model string or Model instance into a concrete Model.\n *\n * @remarks\n * String format: `\"provider/model-id\"` — splits on the first `/`.\n * A Model instance is returned as-is.\n */\nexport const resolveModel = (model: Model | ModelString): Model => {\n if (typeof model !== \"string\") return model;\n\n const slashIndex = model.indexOf(\"/\");\n if (slashIndex === -1) {\n throw new ValidationError(\n `Invalid model string \"${model}\". Expected format: \"provider/model-id\" (e.g. \"google/gemini-3.1-pro-preview\").`,\n );\n }\n\n const provider = model.slice(0, slashIndex);\n const modelId = model.slice(slashIndex + 1);\n\n if (!SUPPORTED_PROVIDERS.has(provider)) {\n throw new ValidationError(\n `Unknown provider \"${provider}\". Supported providers: ${[...SUPPORTED_PROVIDERS].join(\", \")}.`,\n );\n }\n\n return createLazyModel(provider, modelId);\n};\n\nconst createLazyModel = (provider: string, modelId: string): Model => {\n let resolvedModel: Model | undefined;\n\n const ensureResolved = async (): Promise<Model> => {\n if (resolvedModel) return resolvedModel;\n if (provider === \"google\") {\n const { google } = await import(\"./providers/google\");\n resolvedModel = google(modelId as GoogleModelId);\n } else if (provider === \"openai\") {\n const { openai } = await import(\"./providers/openai\");\n resolvedModel = openai(modelId as OpenAIModelId);\n } else {\n throw new ValidationError(`Unknown provider \"${provider}\".`);\n }\n return resolvedModel;\n };\n\n return {\n provider,\n modelId,\n preflight: async () => {\n const resolved = await ensureResolved();\n await resolved.preflight?.();\n },\n generate: async (params) => (await ensureResolved()).generate(params),\n async *generateStream(params) {\n const resolved = await ensureResolved();\n if (!resolved.generateStream) {\n return resolved.generate(params);\n }\n return yield* resolved.generateStream(params);\n },\n };\n};\n","import * as z from \"zod\";\nimport type { AgentLike, RunOptions, Tool, ToolDefinition } from \"../types\";\n\nconst delegationSchema = z.object({\n task: z.string().describe(\"The task to delegate to this team member\"),\n});\n\n/**\n * Create delegation tools from an agent's team.\n *\n * @remarks\n * Each team member becomes a `delegate_to_{name}` tool.\n * The runner routes these through the onToolCall middleware chain.\n *\n * @param childRunIds - Shared queue map populated by the runner with pre-generated\n * child runIds. Keyed by member name → FIFO queue of runIds.\n */\nexport const createDelegationTools = (\n team: AgentLike[],\n propagatedOptions?: Partial<RunOptions>,\n childRunIds?: Map<string, string[]>,\n): Tool[] =>\n team.map((member) => ({\n name: `delegate_to_${member.name}`,\n description: member.description ?? `Delegate a task to ${member.name}`,\n execute: async (args: unknown) => {\n const { task } = delegationSchema.parse(args);\n const childRunId = childRunIds?.get(member.name)?.shift();\n const childOptions: Partial<RunOptions> = {\n ...propagatedOptions,\n ...(childRunId ? { runId: childRunId } : {}),\n };\n const result = await member.run([{ role: \"user\", content: task }], childOptions);\n if (result.status === \"complete\") return result.output;\n throw new Error(`Delegation to ${member.name} was interrupted`);\n },\n toDefinition(): ToolDefinition {\n return {\n name: `delegate_to_${member.name}`,\n description: member.description ?? `Delegate a task to ${member.name}`,\n parameters: z.toJSONSchema(delegationSchema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >,\n };\n },\n }));\n","import type { LogLevel } from \"../types\";\n\nexport type { LogLevel } from \"../types\";\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\nconst LEVELS: Record<string, number> = { silent: 0, debug: 1, info: 2, warn: 3, error: 4 };\nconst noop = () => {};\nconst format = (level: string, message: string): string =>\n `[${new Date().toISOString()}][kraken-ai][${level}] ${message}`;\n\n/** Create a logger. Silent by default. */\nexport const createLogger = (level: LogLevel = \"silent\"): Logger => {\n const threshold = LEVELS[level] ?? 0;\n const active = threshold > 0;\n return {\n debug: active && threshold <= 1 ? (msg, ...a) => console.log(format(\"DEBUG\", msg), ...a) : noop,\n info: active && threshold <= 2 ? (msg, ...a) => console.log(format(\"INFO\", msg), ...a) : noop,\n warn: active && threshold <= 3 ? (msg, ...a) => console.warn(format(\"WARN\", msg), ...a) : noop,\n error:\n active && threshold <= 4 ? (msg, ...a) => console.error(format(\"ERROR\", msg), ...a) : noop,\n };\n};\n","import { ToolError, ToolInputValidationError, ValidationError } from \"../errors\";\nimport type { Middleware, MiddlewareContext } from \"../middleware\";\nimport type {\n GenerateParams,\n GenerateResponse,\n HumanDecision,\n LogLevel,\n Message,\n Model,\n RunOptions,\n RunResult,\n ThinkingLevel,\n Tool,\n ToolDefinition,\n ToolResult,\n Usage,\n} from \"../types\";\nimport { createEventEmitter } from \"./events\";\nimport { LifecycleManager } from \"./lifecycle\";\nimport { createLogger } from \"./logger\";\n\nexport interface RunnerConfig {\n agent: { name: string; description?: string; instructions: string };\n model: Model;\n tools: Tool[];\n temperature?: number;\n maxOutputTokens?: number;\n thinkingLevel?: ThinkingLevel;\n responseSchema?: Record<string, unknown>;\n logLevel?: LogLevel;\n}\n\nconst composeOnLLMCall = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n coreFn: (params: GenerateParams) => Promise<GenerateResponse>,\n): ((params: GenerateParams) => Promise<GenerateResponse>) => {\n let fn = coreFn;\n for (let i = middleware.length - 1; i >= 0; i--) {\n const mw = middleware[i];\n if (mw?.onLLMCall) {\n const prev = fn;\n const hook = mw.onLLMCall;\n fn = (params) => hook(ctx, params, () => prev(params));\n }\n }\n return fn;\n};\n\nconst composeOnToolCall = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n coreFn: () => Promise<unknown>,\n toolName: string,\n args: unknown,\n): (() => Promise<unknown>) => {\n let fn = coreFn;\n for (let i = middleware.length - 1; i >= 0; i--) {\n const mw = middleware[i];\n if (mw?.onToolCall) {\n const prev = fn;\n const hook = mw.onToolCall;\n fn = () => hook(ctx, toolName, args, prev);\n }\n }\n return fn;\n};\n\nconst applyTransformTools = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n tools: ToolDefinition[],\n): ToolDefinition[] => {\n let result = tools;\n for (const mw of middleware) {\n if (mw.transformTools) result = mw.transformTools(ctx, result);\n }\n return result;\n};\n\nexport const createRunner = (config: RunnerConfig) => {\n const { agent, model, tools } = config;\n const toolMap = new Map(tools.map((t) => [t.name, t]));\n const logger = createLogger(config.logLevel);\n\n return {\n run: async (inputMessages: Message[], options?: RunOptions): Promise<RunResult> => {\n if (!inputMessages.length) {\n throw new ValidationError(\"messages must be a non-empty array.\");\n }\n for (const m of inputMessages) {\n if (typeof m.content !== \"string\") {\n throw new ValidationError(\"message content must be a string.\");\n }\n }\n\n const runId = options?.runId ?? crypto.randomUUID();\n const middleware = options?.middleware ?? [];\n const ctx: MiddlewareContext = {\n agent: { name: agent.name, description: agent.description },\n runId,\n parentRunId: options?.parentRunId,\n };\n const emitter = createEventEmitter(agent.name, runId, options?.onEvent, options?.parentRunId);\n const lifecycle = new LifecycleManager((from, to) => {\n emitter.emit({ type: \"lifecycle\", from, to });\n for (const mw of middleware) mw.onTransition?.(ctx, from, to);\n });\n\n const baseDefinitions = tools.map((t) => t.toDefinition());\n const definitions = applyTransformTools(middleware, ctx, baseDefinitions);\n\n lifecycle.transition(\"running\");\n\n emitter.emit({\n type: \"config\",\n model: { provider: model.provider, modelId: model.modelId },\n tools: tools.map((t) => t.name),\n ...(config.temperature != null ? { temperature: config.temperature } : {}),\n ...(config.maxOutputTokens != null ? { maxOutputTokens: config.maxOutputTokens } : {}),\n ...(config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {}),\n hasOutputSchema: Boolean(config.responseSchema),\n });\n\n const usage: Usage = { inputTokens: 0, outputTokens: 0 };\n const conversationMessages = [...inputMessages];\n\n let currentRound = 0;\n\n const coreFn = async (params: GenerateParams): Promise<GenerateResponse> => {\n if (!model.generateStream) return model.generate(params);\n\n const gen = model.generateStream(params);\n let result = await gen.next();\n while (!result.done) {\n const chunk = result.value;\n if (chunk.thoughts) {\n emitter.emit({ type: \"thought\", text: chunk.thoughts, callIndex: currentRound });\n }\n result = await gen.next();\n }\n return result.value;\n };\n\n const wrappedGenerate = composeOnLLMCall(middleware, ctx, coreFn);\n\n async function* executeLoop(): AsyncGenerator<\n RunResult,\n RunResult,\n HumanDecision | undefined\n > {\n const MAX_ROUNDS = 50;\n for (let round = 0; round < MAX_ROUNDS; round++) {\n options?.signal?.throwIfAborted();\n currentRound = round;\n\n const params: GenerateParams = {\n system: agent.instructions,\n messages: conversationMessages,\n tools: definitions.length > 0 ? definitions : undefined,\n signal: options?.signal,\n temperature: config.temperature,\n maxOutputTokens: config.maxOutputTokens,\n thinkingLevel: config.thinkingLevel,\n responseSchema: config.responseSchema,\n };\n\n const response = await wrappedGenerate(params);\n usage.inputTokens += response.usage.inputTokens;\n usage.outputTokens += response.usage.outputTokens;\n emitter.emit({\n type: \"llm_call\",\n inputTokens: response.usage.inputTokens,\n outputTokens: response.usage.outputTokens,\n output: response.text,\n toolCalls: response.toolCalls?.map((tc) => ({\n name: tc.name,\n args: tc.args as Record<string, unknown>,\n })),\n });\n\n // Non-streaming fallback: emit thoughts from completed response\n if (!model.generateStream && response.thoughts) {\n emitter.emit({ type: \"thought\", text: response.thoughts, callIndex: round });\n }\n\n if (!response.toolCalls?.length) {\n lifecycle.transition(\"completed\");\n return {\n status: \"complete\" as const,\n output: response.text,\n messages: conversationMessages,\n usage,\n transitions: lifecycle.transitions,\n };\n }\n\n // Record the model's tool-calling response with structured tool calls\n conversationMessages.push({\n role: \"assistant\",\n content: response.text ?? \"\",\n toolCalls: response.toolCalls,\n });\n\n // ── Pass 1: HITL gate (serial) ──────────────────────────────\n type ApprovedCall = {\n tc: (typeof response.toolCalls)[number];\n executeFn: () => Promise<unknown>;\n };\n const approved: ApprovedCall[] = [];\n\n for (const tc of response.toolCalls) {\n const foundTool = toolMap.get(tc.name);\n\n if (foundTool?.requiresApproval) {\n const needsApproval =\n typeof foundTool.requiresApproval === \"function\"\n ? foundTool.requiresApproval(tc.args)\n : foundTool.requiresApproval;\n\n if (needsApproval) {\n emitter.emit({\n type: \"interrupt\",\n toolName: tc.name,\n toolCallId: tc.id,\n args: tc.args as Record<string, unknown>,\n });\n\n const decision: HumanDecision | undefined = yield {\n status: \"interrupted\" as const,\n interrupt: { toolName: tc.name, args: tc.args, toolCallId: tc.id },\n resume: null as unknown as (d: HumanDecision) => Promise<RunResult>,\n };\n\n if (\n decision === \"reject\" ||\n (typeof decision === \"object\" && \"feedback\" in decision)\n ) {\n const feedback =\n typeof decision === \"object\"\n ? decision.feedback\n : \"Tool call rejected by user.\";\n conversationMessages.push({\n role: \"user\",\n content: `Tool ${tc.name} was rejected: ${feedback}`,\n });\n continue;\n }\n }\n }\n\n const executeFn = foundTool\n ? () => foundTool.execute(tc.args)\n : () => Promise.resolve(`Unknown tool: ${tc.name}`);\n\n approved.push({ tc, executeFn });\n }\n\n if (!approved.length) continue;\n\n // ── Pass 2: Parallel execution ──────────────────────────────\n const hasDelegation = approved.some(({ tc }) => tc.name.startsWith(\"delegate_to_\"));\n if (hasDelegation) {\n lifecycle.transition(\"awaiting_children\");\n for (const { tc } of approved) {\n if (tc.name.startsWith(\"delegate_to_\")) {\n const targetName = tc.name.replace(\"delegate_to_\", \"\");\n const childRunId = crypto.randomUUID();\n emitter.emit({\n type: \"delegation\",\n childRunId,\n childAgentName: targetName,\n });\n const queue = options?._childRunIds?.get(targetName);\n if (queue) {\n queue.push(childRunId);\n } else {\n options?._childRunIds?.set(targetName, [childRunId]);\n }\n }\n }\n }\n\n type ToolOutcome = {\n tc: (typeof response.toolCalls)[number];\n result?: unknown;\n error?: unknown;\n durationMs: number;\n };\n\n const outcomes = await Promise.allSettled(\n approved.map(async ({ tc, executeFn }): Promise<ToolOutcome> => {\n const wrappedExecute = composeOnToolCall(\n middleware,\n ctx,\n executeFn,\n tc.name,\n tc.args,\n );\n const startTime = Date.now();\n try {\n logger.debug(`executing tool: ${tc.name}`);\n const result = await wrappedExecute();\n return { tc, result, durationMs: Date.now() - startTime };\n } catch (error) {\n return { tc, error, durationMs: Date.now() - startTime };\n }\n }),\n );\n\n if (hasDelegation && lifecycle.state === \"awaiting_children\") {\n lifecycle.transition(\"running\");\n }\n\n // Process results in original order, collecting structured tool results\n let hardError: { error: unknown; toolName: string } | undefined;\n const toolResults: ToolResult[] = [];\n\n for (const settled of outcomes) {\n // Promise.allSettled with our inner try/catch always fulfills\n const outcome = (settled as PromiseFulfilledResult<ToolOutcome>).value;\n const { tc, result, error, durationMs } = outcome;\n\n if (error !== undefined) {\n if (error instanceof ToolInputValidationError) {\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n error: (error as Error).message,\n status: \"validation_error\",\n toolCallId: tc.id,\n durationMs,\n });\n logger.warn(`tool validation error in ${tc.name}: ${(error as Error).message}`);\n toolResults.push({\n name: tc.name,\n toolCallId: tc.id,\n result: `Validation error: ${(error as Error).message}`,\n });\n } else {\n const toolError =\n error instanceof ToolError\n ? error\n : new ToolError(\n error instanceof Error ? (error as Error).message : String(error),\n tc.name,\n );\n\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n error: toolError.message,\n status: \"error\",\n toolCallId: tc.id,\n durationMs,\n });\n logger.warn(`tool error in ${tc.name}: ${toolError.message}`);\n if (!hardError) hardError = { error: toolError, toolName: tc.name };\n }\n } else {\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n result,\n status: \"success\",\n toolCallId: tc.id,\n durationMs,\n });\n toolResults.push({\n name: tc.name,\n toolCallId: tc.id,\n result,\n });\n }\n }\n\n if (toolResults.length > 0) {\n conversationMessages.push({\n role: \"user\",\n content: \"\",\n toolResults,\n });\n }\n\n if (hardError) {\n lifecycle.transition(\"failed\");\n throw hardError.error;\n }\n }\n\n lifecycle.transition(\"failed\");\n throw new Error(\"Tool call loop exceeded maximum rounds\");\n }\n\n const gen = executeLoop();\n const runGenerator = async (decision?: HumanDecision): Promise<RunResult> => {\n const { value, done } = await gen.next(decision);\n if (done) return value;\n if (value.status === \"interrupted\") {\n return {\n status: \"interrupted\",\n interrupt: value.interrupt,\n resume: (d: HumanDecision) => runGenerator(d),\n };\n }\n return value;\n };\n\n try {\n return await runGenerator();\n } catch (err) {\n if (options?.signal?.aborted) {\n const reason =\n typeof options.signal.reason === \"string\" ? options.signal.reason : \"unknown\";\n emitter.emit({ type: \"kill\", reason });\n const s = lifecycle.state;\n if (s !== \"completed\" && s !== \"failed\" && s !== \"cancelled\") {\n lifecycle.transition(\"cancelled\");\n }\n }\n throw err;\n }\n },\n };\n};\n","import type { AgentEvent, AgentEventPayload, Tool } from \"../types\";\n\n/** A named collection of tools keyed by tool name. */\nexport type ToolSet = Map<string, Tool>;\n\n/** Interface for emitting agent events. */\nexport interface EventEmitter {\n emit(event: AgentEventPayload): void;\n}\n\n/** Create an event emitter with monotonic seq numbers. */\nexport const createEventEmitter = (\n agentName: string,\n runId: string,\n onEvent?: (event: AgentEvent) => void,\n parentRunId?: string,\n): EventEmitter => {\n let seq = 0;\n return {\n emit: (partial) => {\n seq += 1;\n const event = {\n ...partial,\n agentName,\n runId,\n timestamp: new Date().toISOString(),\n seq,\n ...(parentRunId ? { parentRunId } : {}),\n } as AgentEvent;\n onEvent?.(event);\n },\n };\n};\n","import type { AgentState, TransitionRecord } from \"../types\";\n\nexport type LifecycleState = AgentState;\n\nconst VALID: Record<string, Set<string>> = {\n idle: new Set([\"running\"]),\n running: new Set([\"awaiting_children\", \"completed\", \"failed\", \"cancelled\"]),\n awaiting_children: new Set([\"running\", \"failed\", \"cancelled\"]),\n};\n\n/** State machine tracking agent lifecycle transitions. */\nexport class LifecycleManager {\n private _state: LifecycleState = \"idle\";\n private readonly _transitions: TransitionRecord[] = [];\n\n constructor(private readonly onTransition?: (from: AgentState, to: AgentState) => void) {}\n\n get state(): LifecycleState {\n return this._state;\n }\n\n get transitions(): TransitionRecord[] {\n return [...this._transitions];\n }\n\n transition(to: LifecycleState): void {\n if (!VALID[this._state]?.has(to)) {\n throw new Error(`Invalid lifecycle transition: ${this._state} -> ${to}`);\n }\n const from = this._state;\n this._state = to;\n this._transitions.push({ from, to, timestamp: new Date().toISOString() });\n this.onTransition?.(from, to);\n }\n}\n","import type { LogLevel } from \"./types\";\n\n/** Global SDK configuration. */\nexport interface GlobalConfig {\n defaultModel?: string;\n logLevel?: LogLevel;\n}\n\nlet config: GlobalConfig = {};\n\n/** Set global SDK defaults. */\nexport const configure = (overrides: GlobalConfig): void => {\n config = { ...config, ...overrides };\n};\n\n/** Read the current global config. */\nexport const getConfig = (): GlobalConfig => ({ ...config });\n\n/** @internal Reset global config (for testing). */\nexport const resetConfig = (): void => {\n config = {};\n};\n","import type { AgentEvent } from \"./types\";\n\n/** Format an agent event as a human-readable one-liner for logging. */\nexport const formatEvent = (e: AgentEvent): string => {\n const tag = `[${e.agentName}]`;\n switch (e.type) {\n case \"config\":\n return `${tag} config ${e.model.provider}/${e.model.modelId}`;\n case \"lifecycle\":\n return `${tag} ${e.from} → ${e.to}`;\n case \"llm_call\":\n return `${tag} llm ${e.inputTokens}→${e.outputTokens} tokens`;\n case \"thought\":\n return `${tag} thought (call ${e.callIndex})`;\n case \"tool_call\":\n return `${tag} ${e.toolName}() ${e.status} (${e.durationMs}ms)`;\n case \"delegation\":\n return `${tag} → ${e.childAgentName}`;\n case \"interrupt\":\n return `${tag} interrupt: ${e.toolName} awaiting approval`;\n case \"kill\":\n return `${tag} killed${e.reason ? `: ${e.reason}` : \"\"}`;\n case \"error\":\n return `${tag} error: ${e.message}`;\n case \"notification\":\n return `${tag} notification: ${e.title}`;\n case \"structured_output_complete\":\n return `${tag} structured output complete`;\n }\n};\n","import type { ExecutionContext, Kernel, KernelSignal, RunnerResponse } from \"./types\";\n\nexport type {\n AgentRef,\n ExecutionContext,\n Kernel,\n KernelSignal,\n RunnerResponse,\n SpawnSpec,\n TeamAccessor,\n} from \"./types\";\n\n/**\n * Define a custom kernel for full manual control of agent execution.\n *\n * @example\n * ```ts\n * const kernel = defineKernel({\n * async *execute(ctx) {\n * const plan = await ctx.model.generate({ messages: ctx.input });\n * yield { kind: \"complete\", result: plan.text };\n * },\n * });\n * ```\n */\nexport const defineKernel = (definition: {\n execute: (ctx: ExecutionContext) => AsyncGenerator<KernelSignal, void, RunnerResponse>;\n}): Kernel => definition;\n","import type { GenerateParams, GenerateResponse, Model } from \"../types\";\n\n/** Handler for matching and responding to mock requests. */\nexport interface MockHandler {\n match: (params: GenerateParams) => boolean;\n respond: (params: GenerateParams) => GenerateResponse;\n}\n\n/** Configuration for the mock model factory. */\nexport interface MockModelConfig {\n response?: GenerateResponse;\n handlers?: MockHandler[];\n}\n\nconst DEFAULT_RESPONSE: GenerateResponse = {\n text: \"\",\n usage: { inputTokens: 0, outputTokens: 0 },\n};\n\n/** Mock model with call tracking. */\nexport interface MockModel extends Model {\n readonly calls: GenerateParams[];\n}\n\n/**\n * Create a mock model for testing.\n *\n * @example\n * ```ts\n * const model = mock({ response: { text: \"hi\", usage: { inputTokens: 1, outputTokens: 1 } } });\n * ```\n */\nexport const mock = (config?: MockModelConfig): MockModel => {\n const defaultResponse = config?.response ?? DEFAULT_RESPONSE;\n const handlers = config?.handlers ?? [];\n const calls: GenerateParams[] = [];\n\n return {\n provider: \"mock\",\n modelId: \"mock\",\n calls,\n generate: async (params) => {\n calls.push(params);\n for (const handler of handlers) {\n if (handler.match(params)) return handler.respond(params);\n }\n return defaultResponse;\n },\n };\n};\n","import * as z from \"zod\";\nimport { ToolInputValidationError } from \"./errors\";\nimport type { Tool, ToolDefinition } from \"./types\";\n\nexport type { Tool } from \"./types\";\n\n/**\n * Configuration for creating a tool.\n *\n * @typeParam TParams - Schema type for the tool's parameters.\n * The `execute` callback receives `z.infer<TParams>` as its argument.\n * @typeParam TReturn - Inferred return type of the `execute` callback.\n *\n * @example\n * ```ts\n * const calc = tool({\n * name: \"calculator\",\n * description: \"Add two numbers\",\n * parameters: z.object({\n * a: z.number().describe(\"First operand\"),\n * b: z.number().describe(\"Second operand\"),\n * }),\n * execute: async ({ a, b }) => a + b,\n * });\n * ```\n */\nexport interface ToolConfig<TParams extends z.ZodType, TReturn = unknown> {\n name: string;\n description: string;\n parameters: TParams;\n execute: (args: z.infer<TParams>) => Promise<TReturn>;\n /** Require human approval. Boolean or per-invocation predicate. */\n requiresApproval?: boolean | ((args: z.infer<TParams>) => boolean);\n}\n\n/**\n * Create a tool for an agent.\n *\n * @remarks\n * The `parameters` schema is converted to JSON Schema for the LLM,\n * and used at runtime to validate arguments before `execute` is called.\n * If the LLM provides invalid arguments, a `ToolInputValidationError` is\n * thrown with a detailed message including the expected schema, received\n * values, and per-field validation errors.\n *\n * @example\n * ```ts\n * const calc = tool({\n * name: \"calculator\",\n * description: \"Add two numbers\",\n * parameters: z.object({ a: z.number(), b: z.number() }),\n * execute: async ({ a, b }) => a + b,\n * });\n * ```\n */\nexport const tool = <TParams extends z.ZodType, TReturn>(\n config: ToolConfig<TParams, TReturn>,\n): Tool => {\n const jsonSchema = z.toJSONSchema(config.parameters, {\n target: \"draft-2020-12\",\n }) as Record<string, unknown>;\n\n return {\n name: config.name,\n description: config.description,\n\n execute: async (args: unknown) => {\n const result = config.parameters.safeParse(args);\n if (!result.success) {\n const issues = result.error.issues;\n const message =\n `Tool \"${config.name}\" received invalid arguments.\\n\\n` +\n `Expected parameters:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Received:\\n${JSON.stringify(args, null, 2)}\\n\\n` +\n `Validation errors:\\n${issues.map((i) => ` - ${i.path.join(\".\")}: ${i.message}`).join(\"\\n\")}\\n\\n` +\n `Hint: The LLM provided arguments that don't match the tool's parameter schema. ` +\n `This typically means the model misunderstood the tool definition.`;\n throw new ToolInputValidationError(message, config.name, jsonSchema, args);\n }\n return config.execute(result.data);\n },\n\n requiresApproval: config.requiresApproval as Tool[\"requiresApproval\"],\n\n toDefinition(): ToolDefinition {\n return {\n name: config.name,\n description: config.description,\n parameters: jsonSchema,\n };\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IACa,aAWA,eAQA,WAWA,iBAaA,0BAyBA;AArEb;AAAA;AAAA;AACO,IAAM,cAAN,cAA6D,MAAM;AAAA,MAC/D;AAAA,MAET,YAAY,SAAiB,MAAU;AACrC,cAAM,OAAO;AACb,aAAK,OAAO;AACZ,aAAK,OAAQ,QAAQ;AAAA,MACvB;AAAA,IACF;AAGO,IAAM,gBAAN,cAA4B,YAA8B;AAAA,MAC/D,YAAY,SAAiB;AAC3B,cAAM,SAAS,gBAAgB;AAC/B,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAGO,IAAM,YAAN,cAAwB,YAA0B;AAAA,MACvD,YACE,SACS,UACT;AACA,cAAM,SAAS,YAAY;AAFlB;AAGT,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAGO,IAAM,kBAAN,cAA8B,YAAgC;AAAA,MACnE,YAAY,SAAiB;AAC3B,cAAM,SAAS,kBAAkB;AACjC,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAQO,IAAM,2BAAN,cAAuC,YAA2C;AAAA,MAC9E;AAAA,MACA;AAAA,MACA;AAAA,MAET,YACE,SACA,UACA,UACA,UACA;AACA,cAAM,SAAS,6BAA6B;AAC5C,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,WAAW;AAChB,aAAK,WAAW;AAAA,MAClB;AAAA,IACF;AAQO,IAAM,wBAAN,cAAoC,YAAuC;AAAA,MACvE;AAAA;AAAA,MAEA;AAAA;AAAA,MAEA;AAAA,MAET,YACE,SACA,WACA,cACA;AACA,cAAM,SAAS,yBAAyB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AM,EAAG,QAAO,QAAQ,QAAQ,MAAM;AAAA,MAC1D;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;AXvBA;;;AY1BA,IAAAC,KAAmB;AACnB;AAsDO,IAAM,OAAO,CAClBC,YACS;AACT,QAAM,aAAe,gBAAaA,QAAO,YAAY;AAAA,IACnD,QAAQ;AAAA,EACV,CAAC;AAED,SAAO;AAAA,IACL,MAAMA,QAAO;AAAA,IACb,aAAaA,QAAO;AAAA,IAEpB,SAAS,OAAO,SAAkB;AAChC,YAAM,SAASA,QAAO,WAAW,UAAU,IAAI;AAC/C,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,SAAS,OAAO,MAAM;AAC5B,cAAM,UACJ,SAASA,QAAO,IAAI;AAAA;AAAA;AAAA,EACK,KAAK,UAAU,YAAY,MAAM,CAAC,CAAC;AAAA;AAAA;AAAA,EAC9C,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AAAA;AAAA,EACpB,OAAO,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,KAAK,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAAA;AAG9F,cAAM,IAAI,yBAAyB,SAASA,QAAO,MAAM,YAAY,IAAI;AAAA,MAC3E;AACA,aAAOA,QAAO,QAAQ,OAAO,IAAI;AAAA,IACnC;AAAA,IAEA,kBAAkBA,QAAO;AAAA,IAEzB,eAA+B;AAC7B,aAAO;AAAA,QACL,MAAMA,QAAO;AAAA,QACb,aAAaA,QAAO;AAAA,QACpB,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":["config","z","google","openai","config","gen","config","config","z","config"]}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/agent.ts","../src/model.ts","../src/runtime/delegation.ts","../src/runtime/logger.ts","../src/runtime/events.ts","../src/runtime/lifecycle.ts","../src/runtime/runner.ts","../src/configure.ts","../src/format-event.ts","../src/kernel.ts","../src/providers/mock.ts","../src/tool.ts"],"sourcesContent":["import * as z from \"zod\";\nimport { OutputValidationError } from \"./errors\";\nimport { resolveModel } from \"./model\";\nimport { createDelegationTools } from \"./runtime/delegation\";\nimport { createLogger } from \"./runtime/logger\";\nimport { createRunner } from \"./runtime/runner\";\nimport type {\n AgentConfig,\n AgentLike,\n LogLevel,\n Message,\n Model,\n RunOptions,\n RunResult,\n ThinkingLevel,\n Tool,\n Usage,\n} from \"./types\";\n\n/**\n * An AI agent with optional tools and team.\n *\n * @typeParam TOutput - Schema for structured output. When provided via\n * `outputSchema`, the `run()` result's `output` field is typed as\n * `z.infer<TOutput>`. Inferred automatically — no need to specify manually.\n *\n * @example\n * ```ts\n * // Unstructured output (output: unknown)\n * const agent = new Agent({\n * name: \"assistant\",\n * model: \"google/gemini-3.1-pro-preview\",\n * instructions: \"You are a helpful assistant.\",\n * });\n *\n * // Structured typed output (output: { sentiment: string })\n * const analyzer = new Agent({\n * name: \"analyzer\",\n * model: \"google/gemini-3.1-pro-preview\",\n * instructions: \"Analyze sentiment.\",\n * outputSchema: z.object({ sentiment: z.string() }),\n * });\n * const result = await analyzer.run([{ role: \"user\", content: \"I love this!\" }]);\n * if (result.status === \"complete\") {\n * result.output.sentiment; // string — fully typed!\n * }\n * ```\n */\nexport class Agent<TOutput extends z.ZodType = z.ZodType> implements AgentLike {\n readonly name: string;\n readonly description?: string;\n private readonly config: AgentConfig<TOutput>;\n private readonly resolvedModel: Model;\n\n constructor(config: AgentConfig<TOutput>) {\n this.config = config;\n this.name = config.name;\n this.description = config.description;\n this.resolvedModel = resolveModel(config.model);\n }\n\n /** Eagerly validate configuration (API keys, provider availability) before the first run. */\n async preflight(): Promise<void> {\n await this.resolvedModel.preflight?.();\n }\n\n /** Returns the agent definition as a plain serializable object (no tools, team, or kernel). */\n get definition(): {\n name: string;\n model: string;\n instructions: string;\n description?: string;\n temperature?: number;\n allowTemperatureOverride?: boolean;\n maxOutputTokens?: number;\n thinkingLevel?: ThinkingLevel;\n logLevel?: LogLevel;\n } {\n const model =\n typeof this.config.model === \"string\"\n ? this.config.model\n : `${this.config.model.provider}/${this.config.model.modelId}`;\n\n const def: Record<string, unknown> = {\n name: this.config.name,\n model,\n instructions: this.config.instructions,\n };\n\n if (this.config.description !== undefined) def.description = this.config.description;\n if (this.config.temperature !== undefined) def.temperature = this.config.temperature;\n if (this.config.allowTemperatureOverride !== undefined)\n def.allowTemperatureOverride = this.config.allowTemperatureOverride;\n if (this.config.maxOutputTokens !== undefined)\n def.maxOutputTokens = this.config.maxOutputTokens;\n if (this.config.thinkingLevel !== undefined) def.thinkingLevel = this.config.thinkingLevel;\n if (this.config.logLevel !== undefined) def.logLevel = this.config.logLevel;\n\n return def as Agent[\"definition\"];\n }\n\n /**\n * Run the agent with a message history.\n *\n * @param messages - Non-empty array of conversation messages.\n * @param options - Run options (middleware, signal, onEvent, runId).\n * @returns RunResult — either complete or interrupted for HITL.\n * When `outputSchema` is configured, the `output` field of a complete\n * result is parsed and validated against the schema at runtime.\n */\n async run(messages: Message[], options?: RunOptions): Promise<RunResult<z.infer<TOutput>>> {\n const allTools: Tool[] = [...(this.config.tools ?? [])];\n const logger = createLogger(this.config.logLevel);\n const runId = options?.runId ?? crypto.randomUUID();\n\n // Resolve temperature: respect allowTemperatureOverride flag\n let resolvedTemperature: number | undefined;\n if (this.config.allowTemperatureOverride === false && this.config.temperature != null) {\n resolvedTemperature = this.config.temperature;\n if (options?.temperature != null) {\n logger.warn(\n `Agent \"${this.name}\" has temperature locked to ${this.config.temperature}, ignoring override`,\n );\n }\n } else {\n resolvedTemperature = options?.temperature ?? this.config.temperature;\n }\n const resolvedThinkingLevel = options?.thinkingLevel ?? this.config.thinkingLevel;\n const resolvedMaxOutputTokens = options?.maxOutputTokens ?? this.config.maxOutputTokens;\n\n const childRunIds = new Map<string, string[]>();\n\n if (this.config.team?.length) {\n const propagated: Partial<RunOptions> = {\n middleware: options?.middleware,\n signal: options?.signal,\n onEvent: options?.onEvent,\n parentRunId: runId,\n ...(resolvedTemperature != null ? { temperature: resolvedTemperature } : {}),\n ...(resolvedThinkingLevel ? { thinkingLevel: resolvedThinkingLevel } : {}),\n ...(resolvedMaxOutputTokens != null ? { maxOutputTokens: resolvedMaxOutputTokens } : {}),\n };\n const delegationTools = createDelegationTools(this.config.team, propagated, childRunIds);\n allTools.push(...delegationTools);\n }\n\n const runner = createRunner({\n agent: {\n name: this.name,\n description: this.description,\n instructions: this.config.instructions,\n },\n model: this.resolvedModel,\n tools: allTools,\n temperature: resolvedTemperature,\n maxOutputTokens: resolvedMaxOutputTokens,\n thinkingLevel: resolvedThinkingLevel,\n responseSchema: this.config.outputSchema\n ? (z.toJSONSchema(this.config.outputSchema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >)\n : undefined,\n logLevel: this.config.logLevel,\n });\n\n const result = await runner.run(messages, { ...options, runId, _childRunIds: childRunIds });\n\n if (result.status === \"complete\" && this.config.outputSchema) {\n const validated = await this.produceStructuredOutput(result, options);\n options?.onEvent?.({\n type: \"structured_output_complete\",\n agentName: this.name,\n runId,\n timestamp: new Date().toISOString(),\n seq: -1,\n output: validated.data,\n });\n return {\n ...result,\n output: validated.data,\n usage: validated.usage,\n };\n }\n\n return result as RunResult<z.infer<TOutput>>;\n }\n\n /**\n * Validate structured output with retry. On validation failure, feeds the error\n * back to the LLM and retries (up to 3 total attempts). Retry messages are kept\n * in a separate array to avoid polluting RunResult.messages.\n */\n private async produceStructuredOutput(\n runnerResult: Extract<RunResult, { status: \"complete\" }>,\n options?: RunOptions,\n ): Promise<{ data: z.infer<TOutput>; usage: Usage }> {\n const schema = this.config.outputSchema as z.ZodType;\n const jsonSchema = z.toJSONSchema(schema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >;\n const maxAttempts = 3;\n const accumulatedUsage = { ...runnerResult.usage };\n\n // Separate messages array for retries — original runnerResult.messages stays clean\n const retryMessages: Message[] = [...runnerResult.messages];\n let rawOutput = runnerResult.output as string;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const validationResult = this.tryParseOutput(rawOutput, schema, jsonSchema);\n\n if (validationResult.success) {\n return { data: validationResult.data, usage: accumulatedUsage };\n }\n\n if (attempt === maxAttempts) {\n throw new OutputValidationError(\n `Agent \"${this.name}\" structured output validation failed after ${maxAttempts} attempts.\\n\\n` +\n `${validationResult.error}`,\n rawOutput,\n { attempt, totalAttempts: maxAttempts },\n );\n }\n\n // Feed error back to LLM for retry\n retryMessages.push(\n { role: \"assistant\", content: rawOutput },\n {\n role: \"user\",\n content:\n `Schema validation error: ${validationResult.error}\\n\\n` +\n `Please produce valid JSON output matching the required schema.`,\n },\n );\n\n const response = await this.resolvedModel.generate({\n system: this.config.instructions,\n messages: retryMessages,\n responseSchema: jsonSchema,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n thinkingLevel: this.config.thinkingLevel,\n signal: options?.signal,\n });\n\n accumulatedUsage.inputTokens += response.usage.inputTokens;\n accumulatedUsage.outputTokens += response.usage.outputTokens;\n rawOutput = response.text;\n }\n\n // Unreachable — loop always returns or throws\n throw new Error(\"Unreachable\");\n }\n\n private tryParseOutput(\n rawText: string,\n schema: z.ZodType,\n jsonSchema: Record<string, unknown>,\n ): { success: true; data: z.infer<TOutput> } | { success: false; error: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawText);\n } catch {\n return {\n success: false,\n error:\n `LLM returned invalid JSON.\\n\\n` +\n `Expected output matching schema:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Raw LLM response:\\n${rawText}`,\n };\n }\n\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues;\n return {\n success: false,\n error:\n `Zod validation failed.\\n\\n` +\n `Expected:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Received:\\n${JSON.stringify(parsed, null, 2)}\\n\\n` +\n `Errors:\\n${issues.map((i) => ` - ${String(i.path.join(\".\"))}: ${i.message}`).join(\"\\n\")}`,\n };\n }\n\n return { success: true, data: result.data as z.infer<TOutput> };\n }\n}\n","import { ValidationError } from \"./errors\";\nimport type { GoogleModelId, Model, ModelString, OpenAIModelId } from \"./types\";\n\nexport type { GoogleModelId, Model, ModelString, OpenAIModelId } from \"./types\";\n\n/** Retry configuration for provider API calls. */\nexport interface RetryConfig {\n maxRetries: number;\n baseDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n}\n\n/** Configuration for the Google provider factory. */\nexport interface GoogleModelConfig {\n apiKey?: string;\n retry?: Partial<RetryConfig>;\n}\n\nconst SUPPORTED_PROVIDERS = new Set([\"google\", \"openai\"]);\n\n/**\n * Resolve a model string or Model instance into a concrete Model.\n *\n * @remarks\n * String format: `\"provider/model-id\"` — splits on the first `/`.\n * A Model instance is returned as-is.\n */\nexport const resolveModel = (model: Model | ModelString): Model => {\n if (typeof model !== \"string\") return model;\n\n const slashIndex = model.indexOf(\"/\");\n if (slashIndex === -1) {\n throw new ValidationError(\n `Invalid model string \"${model}\". Expected format: \"provider/model-id\" (e.g. \"google/gemini-3.1-pro-preview\").`,\n );\n }\n\n const provider = model.slice(0, slashIndex);\n const modelId = model.slice(slashIndex + 1);\n\n if (!SUPPORTED_PROVIDERS.has(provider)) {\n throw new ValidationError(\n `Unknown provider \"${provider}\". Supported providers: ${[...SUPPORTED_PROVIDERS].join(\", \")}.`,\n );\n }\n\n return createLazyModel(provider, modelId);\n};\n\nconst createLazyModel = (provider: string, modelId: string): Model => {\n let resolvedModel: Model | undefined;\n\n const ensureResolved = async (): Promise<Model> => {\n if (resolvedModel) return resolvedModel;\n if (provider === \"google\") {\n const { google } = await import(\"./providers/google\");\n resolvedModel = google(modelId as GoogleModelId);\n } else if (provider === \"openai\") {\n const { openai } = await import(\"./providers/openai\");\n resolvedModel = openai(modelId as OpenAIModelId);\n } else {\n throw new ValidationError(`Unknown provider \"${provider}\".`);\n }\n return resolvedModel;\n };\n\n return {\n provider,\n modelId,\n preflight: async () => {\n const resolved = await ensureResolved();\n await resolved.preflight?.();\n },\n generate: async (params) => (await ensureResolved()).generate(params),\n async *generateStream(params) {\n const resolved = await ensureResolved();\n if (!resolved.generateStream) {\n return resolved.generate(params);\n }\n return yield* resolved.generateStream(params);\n },\n };\n};\n","import * as z from \"zod\";\nimport type { AgentLike, RunOptions, Tool, ToolDefinition } from \"../types\";\n\nconst delegationSchema = z.object({\n task: z.string().describe(\"The task to delegate to this team member\"),\n});\n\n/**\n * Create delegation tools from an agent's team.\n *\n * @remarks\n * Each team member becomes a `delegate_to_{name}` tool.\n * The runner routes these through the onToolCall middleware chain.\n *\n * @param childRunIds - Shared queue map populated by the runner with pre-generated\n * child runIds. Keyed by member name → FIFO queue of runIds.\n */\nexport const createDelegationTools = (\n team: AgentLike[],\n propagatedOptions?: Partial<RunOptions>,\n childRunIds?: Map<string, string[]>,\n): Tool[] =>\n team.map((member) => ({\n name: `delegate_to_${member.name}`,\n description: member.description ?? `Delegate a task to ${member.name}`,\n execute: async (args: unknown) => {\n const { task } = delegationSchema.parse(args);\n const childRunId = childRunIds?.get(member.name)?.shift();\n const childOptions: Partial<RunOptions> = {\n ...propagatedOptions,\n ...(childRunId ? { runId: childRunId } : {}),\n };\n const result = await member.run([{ role: \"user\", content: task }], childOptions);\n if (result.status === \"complete\") return result.output;\n throw new Error(`Delegation to ${member.name} was interrupted`);\n },\n toDefinition(): ToolDefinition {\n return {\n name: `delegate_to_${member.name}`,\n description: member.description ?? `Delegate a task to ${member.name}`,\n parameters: z.toJSONSchema(delegationSchema, { target: \"draft-2020-12\" }) as Record<\n string,\n unknown\n >,\n };\n },\n }));\n","import type { LogLevel } from \"../types\";\n\nexport type { LogLevel } from \"../types\";\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\nconst LEVELS: Record<string, number> = { silent: 0, debug: 1, info: 2, warn: 3, error: 4 };\nconst noop = () => {};\nconst format = (level: string, message: string): string =>\n `[${new Date().toISOString()}][kraken-ai][${level}] ${message}`;\n\n/** Create a logger. Silent by default. */\nexport const createLogger = (level: LogLevel = \"silent\"): Logger => {\n const threshold = LEVELS[level] ?? 0;\n const active = threshold > 0;\n return {\n debug: active && threshold <= 1 ? (msg, ...a) => console.log(format(\"DEBUG\", msg), ...a) : noop,\n info: active && threshold <= 2 ? (msg, ...a) => console.log(format(\"INFO\", msg), ...a) : noop,\n warn: active && threshold <= 3 ? (msg, ...a) => console.warn(format(\"WARN\", msg), ...a) : noop,\n error:\n active && threshold <= 4 ? (msg, ...a) => console.error(format(\"ERROR\", msg), ...a) : noop,\n };\n};\n","import type { AgentEvent, AgentEventPayload, Tool } from \"../types\";\n\n/** A named collection of tools keyed by tool name. */\nexport type ToolSet = Map<string, Tool>;\n\n/** Interface for emitting agent events. */\nexport interface EventEmitter {\n emit(event: AgentEventPayload): void;\n}\n\n/** Create an event emitter with monotonic seq numbers. */\nexport const createEventEmitter = (\n agentName: string,\n runId: string,\n onEvent?: (event: AgentEvent) => void,\n parentRunId?: string,\n): EventEmitter => {\n let seq = 0;\n return {\n emit: (partial) => {\n seq += 1;\n const event = {\n ...partial,\n agentName,\n runId,\n timestamp: new Date().toISOString(),\n seq,\n ...(parentRunId ? { parentRunId } : {}),\n } as AgentEvent;\n onEvent?.(event);\n },\n };\n};\n","import type { AgentState, TransitionRecord } from \"../types\";\n\nexport type LifecycleState = AgentState;\n\nconst VALID: Record<string, Set<string>> = {\n idle: new Set([\"running\"]),\n running: new Set([\"awaiting_children\", \"completed\", \"failed\", \"cancelled\"]),\n awaiting_children: new Set([\"running\", \"failed\", \"cancelled\"]),\n};\n\n/** State machine tracking agent lifecycle transitions. */\nexport class LifecycleManager {\n private _state: LifecycleState = \"idle\";\n private readonly _transitions: TransitionRecord[] = [];\n\n constructor(private readonly onTransition?: (from: AgentState, to: AgentState) => void) {}\n\n get state(): LifecycleState {\n return this._state;\n }\n\n get transitions(): TransitionRecord[] {\n return [...this._transitions];\n }\n\n transition(to: LifecycleState): void {\n if (!VALID[this._state]?.has(to)) {\n throw new Error(`Invalid lifecycle transition: ${this._state} -> ${to}`);\n }\n const from = this._state;\n this._state = to;\n this._transitions.push({ from, to, timestamp: new Date().toISOString() });\n this.onTransition?.(from, to);\n }\n}\n","import { ToolError, ToolInputValidationError, ValidationError } from \"../errors\";\nimport type { Middleware, MiddlewareContext } from \"../middleware\";\nimport type {\n GenerateParams,\n GenerateResponse,\n HumanDecision,\n LogLevel,\n Message,\n Model,\n RunOptions,\n RunResult,\n ThinkingLevel,\n Tool,\n ToolDefinition,\n ToolResult,\n Usage,\n} from \"../types\";\nimport { createEventEmitter } from \"./events\";\nimport { LifecycleManager } from \"./lifecycle\";\nimport { createLogger } from \"./logger\";\n\nexport interface RunnerConfig {\n agent: { name: string; description?: string; instructions: string };\n model: Model;\n tools: Tool[];\n temperature?: number;\n maxOutputTokens?: number;\n thinkingLevel?: ThinkingLevel;\n responseSchema?: Record<string, unknown>;\n logLevel?: LogLevel;\n}\n\nconst composeOnLLMCall = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n coreFn: (params: GenerateParams) => Promise<GenerateResponse>,\n): ((params: GenerateParams) => Promise<GenerateResponse>) => {\n let fn = coreFn;\n for (let i = middleware.length - 1; i >= 0; i--) {\n const mw = middleware[i];\n if (mw?.onLLMCall) {\n const prev = fn;\n const hook = mw.onLLMCall;\n fn = (params) => hook(ctx, params, () => prev(params));\n }\n }\n return fn;\n};\n\nconst composeOnToolCall = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n coreFn: () => Promise<unknown>,\n toolName: string,\n args: unknown,\n): (() => Promise<unknown>) => {\n let fn = coreFn;\n for (let i = middleware.length - 1; i >= 0; i--) {\n const mw = middleware[i];\n if (mw?.onToolCall) {\n const prev = fn;\n const hook = mw.onToolCall;\n fn = () => hook(ctx, toolName, args, prev);\n }\n }\n return fn;\n};\n\nconst applyTransformTools = (\n middleware: Middleware[],\n ctx: MiddlewareContext,\n tools: ToolDefinition[],\n): ToolDefinition[] => {\n let result = tools;\n for (const mw of middleware) {\n if (mw.transformTools) result = mw.transformTools(ctx, result);\n }\n return result;\n};\n\nexport const createRunner = (config: RunnerConfig) => {\n const { agent, model, tools } = config;\n const toolMap = new Map(tools.map((t) => [t.name, t]));\n const logger = createLogger(config.logLevel);\n\n return {\n run: async (inputMessages: Message[], options?: RunOptions): Promise<RunResult> => {\n if (!inputMessages.length) {\n throw new ValidationError(\"messages must be a non-empty array.\");\n }\n for (const m of inputMessages) {\n if (typeof m.content !== \"string\") {\n throw new ValidationError(\"message content must be a string.\");\n }\n }\n\n const runId = options?.runId ?? crypto.randomUUID();\n const middleware = options?.middleware ?? [];\n const ctx: MiddlewareContext = {\n agent: { name: agent.name, description: agent.description },\n runId,\n parentRunId: options?.parentRunId,\n };\n const emitter = createEventEmitter(agent.name, runId, options?.onEvent, options?.parentRunId);\n const lifecycle = new LifecycleManager((from, to) => {\n emitter.emit({ type: \"lifecycle\", from, to });\n for (const mw of middleware) mw.onTransition?.(ctx, from, to);\n });\n\n const baseDefinitions = tools.map((t) => t.toDefinition());\n const definitions = applyTransformTools(middleware, ctx, baseDefinitions);\n\n lifecycle.transition(\"running\");\n\n emitter.emit({\n type: \"config\",\n model: { provider: model.provider, modelId: model.modelId },\n tools: tools.map((t) => t.name),\n ...(config.temperature != null ? { temperature: config.temperature } : {}),\n ...(config.maxOutputTokens != null ? { maxOutputTokens: config.maxOutputTokens } : {}),\n ...(config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {}),\n hasOutputSchema: Boolean(config.responseSchema),\n });\n\n const usage: Usage = { inputTokens: 0, outputTokens: 0 };\n const conversationMessages = [...inputMessages];\n\n let currentRound = 0;\n\n const coreFn = async (params: GenerateParams): Promise<GenerateResponse> => {\n if (!model.generateStream) return model.generate(params);\n\n const gen = model.generateStream(params);\n let result = await gen.next();\n while (!result.done) {\n const chunk = result.value;\n if (chunk.thoughts) {\n emitter.emit({ type: \"thought\", text: chunk.thoughts, callIndex: currentRound });\n }\n result = await gen.next();\n }\n return result.value;\n };\n\n const wrappedGenerate = composeOnLLMCall(middleware, ctx, coreFn);\n\n async function* executeLoop(): AsyncGenerator<\n RunResult,\n RunResult,\n HumanDecision | undefined\n > {\n const MAX_ROUNDS = 50;\n for (let round = 0; round < MAX_ROUNDS; round++) {\n options?.signal?.throwIfAborted();\n currentRound = round;\n\n const params: GenerateParams = {\n system: agent.instructions,\n messages: conversationMessages,\n tools: definitions.length > 0 ? definitions : undefined,\n signal: options?.signal,\n temperature: config.temperature,\n maxOutputTokens: config.maxOutputTokens,\n thinkingLevel: config.thinkingLevel,\n responseSchema: config.responseSchema,\n };\n\n const response = await wrappedGenerate(params);\n usage.inputTokens += response.usage.inputTokens;\n usage.outputTokens += response.usage.outputTokens;\n emitter.emit({\n type: \"llm_call\",\n inputTokens: response.usage.inputTokens,\n outputTokens: response.usage.outputTokens,\n output: response.text,\n toolCalls: response.toolCalls?.map((tc) => ({\n name: tc.name,\n args: tc.args as Record<string, unknown>,\n })),\n });\n\n // Non-streaming fallback: emit thoughts from completed response\n if (!model.generateStream && response.thoughts) {\n emitter.emit({ type: \"thought\", text: response.thoughts, callIndex: round });\n }\n\n if (!response.toolCalls?.length) {\n lifecycle.transition(\"completed\");\n return {\n status: \"complete\" as const,\n output: response.text,\n messages: conversationMessages,\n usage,\n transitions: lifecycle.transitions,\n };\n }\n\n // Record the model's tool-calling response with structured tool calls\n conversationMessages.push({\n role: \"assistant\",\n content: response.text ?? \"\",\n toolCalls: response.toolCalls,\n });\n\n // ── Pass 1: HITL gate (serial) ──────────────────────────────\n type ApprovedCall = {\n tc: (typeof response.toolCalls)[number];\n executeFn: () => Promise<unknown>;\n };\n const approved: ApprovedCall[] = [];\n\n for (const tc of response.toolCalls) {\n const foundTool = toolMap.get(tc.name);\n\n if (foundTool?.requiresApproval) {\n const needsApproval =\n typeof foundTool.requiresApproval === \"function\"\n ? foundTool.requiresApproval(tc.args)\n : foundTool.requiresApproval;\n\n if (needsApproval) {\n emitter.emit({\n type: \"interrupt\",\n toolName: tc.name,\n toolCallId: tc.id,\n args: tc.args as Record<string, unknown>,\n });\n\n const decision: HumanDecision | undefined = yield {\n status: \"interrupted\" as const,\n interrupt: { toolName: tc.name, args: tc.args, toolCallId: tc.id },\n resume: null as unknown as (d: HumanDecision) => Promise<RunResult>,\n };\n\n if (\n decision === \"reject\" ||\n (typeof decision === \"object\" && \"feedback\" in decision)\n ) {\n const feedback =\n typeof decision === \"object\"\n ? decision.feedback\n : \"Tool call rejected by user.\";\n conversationMessages.push({\n role: \"user\",\n content: `Tool ${tc.name} was rejected: ${feedback}`,\n });\n continue;\n }\n }\n }\n\n const executeFn = foundTool\n ? () => foundTool.execute(tc.args)\n : () => Promise.resolve(`Unknown tool: ${tc.name}`);\n\n approved.push({ tc, executeFn });\n }\n\n if (!approved.length) continue;\n\n // ── Pass 2: Parallel execution ──────────────────────────────\n const hasDelegation = approved.some(({ tc }) => tc.name.startsWith(\"delegate_to_\"));\n if (hasDelegation) {\n lifecycle.transition(\"awaiting_children\");\n for (const { tc } of approved) {\n if (tc.name.startsWith(\"delegate_to_\")) {\n const targetName = tc.name.replace(\"delegate_to_\", \"\");\n const childRunId = crypto.randomUUID();\n emitter.emit({\n type: \"delegation\",\n childRunId,\n childAgentName: targetName,\n });\n const queue = options?._childRunIds?.get(targetName);\n if (queue) {\n queue.push(childRunId);\n } else {\n options?._childRunIds?.set(targetName, [childRunId]);\n }\n }\n }\n }\n\n type ToolOutcome = {\n tc: (typeof response.toolCalls)[number];\n result?: unknown;\n error?: unknown;\n durationMs: number;\n };\n\n const outcomes = await Promise.allSettled(\n approved.map(async ({ tc, executeFn }): Promise<ToolOutcome> => {\n const wrappedExecute = composeOnToolCall(\n middleware,\n ctx,\n executeFn,\n tc.name,\n tc.args,\n );\n const startTime = Date.now();\n try {\n logger.debug(`executing tool: ${tc.name}`);\n const result = await wrappedExecute();\n return { tc, result, durationMs: Date.now() - startTime };\n } catch (error) {\n return { tc, error, durationMs: Date.now() - startTime };\n }\n }),\n );\n\n if (hasDelegation && lifecycle.state === \"awaiting_children\") {\n lifecycle.transition(\"running\");\n }\n\n // Process results in original order, collecting structured tool results\n let hardError: { error: unknown; toolName: string } | undefined;\n const toolResults: ToolResult[] = [];\n\n for (const settled of outcomes) {\n // Promise.allSettled with our inner try/catch always fulfills\n const outcome = (settled as PromiseFulfilledResult<ToolOutcome>).value;\n const { tc, result, error, durationMs } = outcome;\n\n if (error !== undefined) {\n if (error instanceof ToolInputValidationError) {\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n error: (error as Error).message,\n status: \"validation_error\",\n toolCallId: tc.id,\n durationMs,\n });\n logger.warn(`tool validation error in ${tc.name}: ${(error as Error).message}`);\n toolResults.push({\n name: tc.name,\n toolCallId: tc.id,\n result: `Validation error: ${(error as Error).message}`,\n });\n } else {\n const toolError =\n error instanceof ToolError\n ? error\n : new ToolError(\n error instanceof Error ? (error as Error).message : String(error),\n tc.name,\n );\n\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n error: toolError.message,\n status: \"error\",\n toolCallId: tc.id,\n durationMs,\n });\n logger.warn(`tool error in ${tc.name}: ${toolError.message}`);\n if (!hardError) hardError = { error: toolError, toolName: tc.name };\n }\n } else {\n emitter.emit({\n type: \"tool_call\",\n toolName: tc.name,\n args: tc.args as Record<string, unknown>,\n result,\n status: \"success\",\n toolCallId: tc.id,\n durationMs,\n });\n toolResults.push({\n name: tc.name,\n toolCallId: tc.id,\n result,\n });\n }\n }\n\n if (toolResults.length > 0) {\n conversationMessages.push({\n role: \"user\",\n content: \"\",\n toolResults,\n });\n }\n\n if (hardError) {\n lifecycle.transition(\"failed\");\n throw hardError.error;\n }\n }\n\n lifecycle.transition(\"failed\");\n throw new Error(\"Tool call loop exceeded maximum rounds\");\n }\n\n const gen = executeLoop();\n const runGenerator = async (decision?: HumanDecision): Promise<RunResult> => {\n const { value, done } = await gen.next(decision);\n if (done) return value;\n if (value.status === \"interrupted\") {\n return {\n status: \"interrupted\",\n interrupt: value.interrupt,\n resume: (d: HumanDecision) => runGenerator(d),\n };\n }\n return value;\n };\n\n try {\n return await runGenerator();\n } catch (err) {\n if (options?.signal?.aborted) {\n const reason =\n typeof options.signal.reason === \"string\" ? options.signal.reason : \"unknown\";\n emitter.emit({ type: \"kill\", reason });\n const s = lifecycle.state;\n if (s !== \"completed\" && s !== \"failed\" && s !== \"cancelled\") {\n lifecycle.transition(\"cancelled\");\n }\n }\n throw err;\n }\n },\n };\n};\n","import type { LogLevel } from \"./types\";\n\n/** Global SDK configuration. */\nexport interface GlobalConfig {\n defaultModel?: string;\n logLevel?: LogLevel;\n}\n\nlet config: GlobalConfig = {};\n\n/** Set global SDK defaults. */\nexport const configure = (overrides: GlobalConfig): void => {\n config = { ...config, ...overrides };\n};\n\n/** Read the current global config. */\nexport const getConfig = (): GlobalConfig => ({ ...config });\n\n/** @internal Reset global config (for testing). */\nexport const resetConfig = (): void => {\n config = {};\n};\n","import type { AgentEvent } from \"./types\";\n\n/** Format an agent event as a human-readable one-liner for logging. */\nexport const formatEvent = (e: AgentEvent): string => {\n const tag = `[${e.agentName}]`;\n switch (e.type) {\n case \"config\":\n return `${tag} config ${e.model.provider}/${e.model.modelId}`;\n case \"lifecycle\":\n return `${tag} ${e.from} → ${e.to}`;\n case \"llm_call\":\n return `${tag} llm ${e.inputTokens}→${e.outputTokens} tokens`;\n case \"thought\":\n return `${tag} thought (call ${e.callIndex})`;\n case \"tool_call\":\n return `${tag} ${e.toolName}() ${e.status} (${e.durationMs}ms)`;\n case \"delegation\":\n return `${tag} → ${e.childAgentName}`;\n case \"interrupt\":\n return `${tag} interrupt: ${e.toolName} awaiting approval`;\n case \"kill\":\n return `${tag} killed${e.reason ? `: ${e.reason}` : \"\"}`;\n case \"error\":\n return `${tag} error: ${e.message}`;\n case \"notification\":\n return `${tag} notification: ${e.title}`;\n case \"structured_output_complete\":\n return `${tag} structured output complete`;\n }\n};\n","import type { ExecutionContext, Kernel, KernelSignal, RunnerResponse } from \"./types\";\n\nexport type {\n AgentRef,\n ExecutionContext,\n Kernel,\n KernelSignal,\n RunnerResponse,\n SpawnSpec,\n TeamAccessor,\n} from \"./types\";\n\n/**\n * Define a custom kernel for full manual control of agent execution.\n *\n * @example\n * ```ts\n * const kernel = defineKernel({\n * async *execute(ctx) {\n * const plan = await ctx.model.generate({ messages: ctx.input });\n * yield { kind: \"complete\", result: plan.text };\n * },\n * });\n * ```\n */\nexport const defineKernel = (definition: {\n execute: (ctx: ExecutionContext) => AsyncGenerator<KernelSignal, void, RunnerResponse>;\n}): Kernel => definition;\n","import type { GenerateParams, GenerateResponse, Model } from \"../types\";\n\n/** Handler for matching and responding to mock requests. */\nexport interface MockHandler {\n match: (params: GenerateParams) => boolean;\n respond: (params: GenerateParams) => GenerateResponse;\n}\n\n/** Configuration for the mock model factory. */\nexport interface MockModelConfig {\n response?: GenerateResponse;\n handlers?: MockHandler[];\n}\n\nconst DEFAULT_RESPONSE: GenerateResponse = {\n text: \"\",\n usage: { inputTokens: 0, outputTokens: 0 },\n};\n\n/** Mock model with call tracking. */\nexport interface MockModel extends Model {\n readonly calls: GenerateParams[];\n}\n\n/**\n * Create a mock model for testing.\n *\n * @example\n * ```ts\n * const model = mock({ response: { text: \"hi\", usage: { inputTokens: 1, outputTokens: 1 } } });\n * ```\n */\nexport const mock = (config?: MockModelConfig): MockModel => {\n const defaultResponse = config?.response ?? DEFAULT_RESPONSE;\n const handlers = config?.handlers ?? [];\n const calls: GenerateParams[] = [];\n\n return {\n provider: \"mock\",\n modelId: \"mock\",\n calls,\n generate: async (params) => {\n calls.push(params);\n for (const handler of handlers) {\n if (handler.match(params)) return handler.respond(params);\n }\n return defaultResponse;\n },\n };\n};\n","import * as z from \"zod\";\nimport { ToolInputValidationError } from \"./errors\";\nimport type { Tool, ToolDefinition } from \"./types\";\n\nexport type { Tool } from \"./types\";\n\n/**\n * Configuration for creating a tool.\n *\n * @typeParam TParams - Schema type for the tool's parameters.\n * The `execute` callback receives `z.infer<TParams>` as its argument.\n * @typeParam TReturn - Inferred return type of the `execute` callback.\n *\n * @example\n * ```ts\n * const calc = tool({\n * name: \"calculator\",\n * description: \"Add two numbers\",\n * parameters: z.object({\n * a: z.number().describe(\"First operand\"),\n * b: z.number().describe(\"Second operand\"),\n * }),\n * execute: async ({ a, b }) => a + b,\n * });\n * ```\n */\nexport interface ToolConfig<TParams extends z.ZodType, TReturn = unknown> {\n name: string;\n description: string;\n parameters: TParams;\n execute: (args: z.infer<TParams>) => Promise<TReturn>;\n /** Require human approval. Boolean or per-invocation predicate. */\n requiresApproval?: boolean | ((args: z.infer<TParams>) => boolean);\n}\n\n/**\n * Create a tool for an agent.\n *\n * @remarks\n * The `parameters` schema is converted to JSON Schema for the LLM,\n * and used at runtime to validate arguments before `execute` is called.\n * If the LLM provides invalid arguments, a `ToolInputValidationError` is\n * thrown with a detailed message including the expected schema, received\n * values, and per-field validation errors.\n *\n * @example\n * ```ts\n * const calc = tool({\n * name: \"calculator\",\n * description: \"Add two numbers\",\n * parameters: z.object({ a: z.number(), b: z.number() }),\n * execute: async ({ a, b }) => a + b,\n * });\n * ```\n */\nexport const tool = <TParams extends z.ZodType, TReturn>(\n config: ToolConfig<TParams, TReturn>,\n): Tool => {\n const jsonSchema = z.toJSONSchema(config.parameters, {\n target: \"draft-2020-12\",\n }) as Record<string, unknown>;\n\n return {\n name: config.name,\n description: config.description,\n\n execute: async (args: unknown) => {\n const result = config.parameters.safeParse(args);\n if (!result.success) {\n const issues = result.error.issues;\n const message =\n `Tool \"${config.name}\" received invalid arguments.\\n\\n` +\n `Expected parameters:\\n${JSON.stringify(jsonSchema, null, 2)}\\n\\n` +\n `Received:\\n${JSON.stringify(args, null, 2)}\\n\\n` +\n `Validation errors:\\n${issues.map((i) => ` - ${i.path.join(\".\")}: ${i.message}`).join(\"\\n\")}\\n\\n` +\n `Hint: The LLM provided arguments that don't match the tool's parameter schema. ` +\n `This typically means the model misunderstood the tool definition.`;\n throw new ToolInputValidationError(message, config.name, jsonSchema, args);\n }\n return config.execute(result.data);\n },\n\n requiresApproval: config.requiresApproval as Tool[\"requiresApproval\"],\n\n toDefinition(): ToolDefinition {\n return {\n name: config.name,\n description: config.description,\n parameters: jsonSchema,\n };\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,YAAYA,QAAO;;;ACmBnB,IAAM,sBAAsB,oBAAI,IAAI,CAAC,UAAU,QAAQ,CAAC;AASjD,IAAM,eAAe,CAAC,UAAsC;AACjE,MAAI,OAAO,UAAU,SAAU,QAAO;AAEtC,QAAM,aAAa,MAAM,QAAQ,GAAG;AACpC,MAAI,eAAe,IAAI;AACrB,UAAM,IAAI;AAAA,MACR,yBAAyB,KAAK;AAAA,IAChC;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,MAAM,GAAG,UAAU;AAC1C,QAAM,UAAU,MAAM,MAAM,aAAa,CAAC;AAE1C,MAAI,CAAC,oBAAoB,IAAI,QAAQ,GAAG;AACtC,UAAM,IAAI;AAAA,MACR,qBAAqB,QAAQ,2BAA2B,CAAC,GAAG,mBAAmB,EAAE,KAAK,IAAI,CAAC;AAAA,IAC7F;AAAA,EACF;AAEA,SAAO,gBAAgB,UAAU,OAAO;AAC1C;AAEA,IAAM,kBAAkB,CAAC,UAAkB,YAA2B;AACpE,MAAI;AAEJ,QAAM,iBAAiB,YAA4B;AACjD,QAAI,cAAe,QAAO;AAC1B,QAAI,aAAa,UAAU;AACzB,YAAM,EAAE,QAAAC,QAAO,IAAI,MAAM,OAAO,sBAAoB;AACpD,sBAAgBA,QAAO,OAAwB;AAAA,IACjD,WAAW,aAAa,UAAU;AAChC,YAAM,EAAE,QAAAC,QAAO,IAAI,MAAM,OAAO,sBAAoB;AACpD,sBAAgBA,QAAO,OAAwB;AAAA,IACjD,OAAO;AACL,YAAM,IAA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UAAU,IAAI;AAC/C,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,SAAS,OAAO,MAAM;AAC5B,cAAM,UACJ,SAASA,QAAO,IAAI;AAAA;AAAA;AAAA,EACK,KAAK,UAAU,YAAY,MAAM,CAAC,CAAC;AAAA;AAAA;AAAA,EAC9C,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AAAA;AAAA,EACpB,OAAO,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,KAAK,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAAA;AAG9F,cAAM,IAAI,yBAAyB,SAASA,QAAO,MAAM,YAAY,IAAI;AAAA,MAC3E;AACA,aAAOA,QAAO,QAAQ,OAAO,IAAI;AAAA,IACnC;AAAA,IAEA,kBAAkBA,QAAO;AAAA,IAEzB,eAA+B;AAC7B,aAAO;AAAA,QACL,MAAMA,QAAO;AAAA,QACb,aAAaA,QAAO;AAAA,QACpB,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":["z","google","openai","config","gen","config","config","z","config"]}
@@ -1,8 +0,0 @@
1
- import {
2
- openai
3
- } from "./chunk-QOSMK22V.js";
4
- import "./chunk-4OPFQWI5.js";
5
- export {
6
- openai
7
- };
8
- //# sourceMappingURL=openai-RC7BMWQY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}