kraken-ai 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,7 +65,7 @@ if (result.status === "complete") {
65
65
  ## Requirements
66
66
 
67
67
  - Node.js 18+
68
- - TypeScript 5+
68
+ - TypeScript 5+ (TypeScript 6 supported; requires tsup patch in monorepos — see [egoist/tsup#1388](https://github.com/egoist/tsup/issues/1388))
69
69
  - `zod` 4+ (peer dependency)
70
70
  - `@google/genai` 1+ (optional — required for the Google provider)
71
71
 
@@ -19,6 +19,7 @@ var ToolError = class extends KrakenError {
19
19
  this.toolName = toolName;
20
20
  this.name = "ToolError";
21
21
  }
22
+ toolName;
22
23
  };
23
24
  var ValidationError = class extends KrakenError {
24
25
  constructor(message) {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProviderError
3
- } from "./chunk-RBQ2PPDE.js";
3
+ } from "./chunk-3WRAEJP3.js";
4
4
 
5
5
  // src/providers/google.ts
6
6
  var DEFAULT_RETRY = {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ProviderError
3
- } from "./chunk-RBQ2PPDE.js";
3
+ } from "./chunk-3WRAEJP3.js";
4
4
 
5
5
  // src/providers/openai.ts
6
6
  var openai = (_modelId) => {
@@ -0,0 +1,7 @@
1
+ import {
2
+ google
3
+ } from "./chunk-6Q6G4WVJ.js";
4
+ import "./chunk-3WRAEJP3.js";
5
+ export {
6
+ google
7
+ };
package/dist/index.cjs CHANGED
@@ -55,6 +55,7 @@ var init_errors = __esm({
55
55
  this.toolName = toolName;
56
56
  this.name = "ToolError";
57
57
  }
58
+ toolName;
58
59
  };
59
60
  ValidationError = class extends KrakenError {
60
61
  constructor(message) {
@@ -458,6 +459,7 @@ var LifecycleManager = class {
458
459
  constructor(onTransition) {
459
460
  this.onTransition = onTransition;
460
461
  }
462
+ onTransition;
461
463
  _state = "idle";
462
464
  _transitions = [];
463
465
  get state() {
@@ -490,14 +492,14 @@ var composeOnLLMCall = (middleware, ctx, coreFn) => {
490
492
  }
491
493
  return fn;
492
494
  };
493
- var composeOnToolCall = (middleware, ctx, coreFn, toolName, args) => {
495
+ var composeOnToolCall = (middleware, ctx, coreFn, toolName, toolCallId, args) => {
494
496
  let fn = coreFn;
495
497
  for (let i = middleware.length - 1; i >= 0; i--) {
496
498
  const mw = middleware[i];
497
499
  if (mw?.onToolCall) {
498
500
  const prev = fn;
499
501
  const hook = mw.onToolCall;
500
- fn = () => hook(ctx, toolName, args, prev);
502
+ fn = () => hook(ctx, toolName, toolCallId, args, prev);
501
503
  }
502
504
  }
503
505
  return fn;
@@ -509,6 +511,41 @@ var applyTransformTools = (middleware, ctx, tools) => {
509
511
  }
510
512
  return result;
511
513
  };
514
+ var composeOnEvent = (middleware, ctx, sink, warn) => {
515
+ const hooks = [];
516
+ for (const mw of middleware) {
517
+ if (mw.onEvent) hooks.push(mw.onEvent);
518
+ }
519
+ if (hooks.length === 0) return sink;
520
+ return (event) => {
521
+ const origSeq = event.seq;
522
+ const origRunId = event.runId;
523
+ const origAgentName = event.agentName;
524
+ let next = () => {
525
+ if (event.seq !== origSeq || event.runId !== origRunId || event.agentName !== origAgentName) {
526
+ warn?.("onEvent middleware mutated immutable fields (seq/runId/agentName) \u2014 restoring");
527
+ event.seq = origSeq;
528
+ event.runId = origRunId;
529
+ event.agentName = origAgentName;
530
+ }
531
+ sink?.(event);
532
+ };
533
+ for (let i = hooks.length - 1; i >= 0; i--) {
534
+ const hook = hooks[i];
535
+ if (!hook) continue;
536
+ const prev = next;
537
+ next = () => {
538
+ try {
539
+ hook(ctx, event, prev);
540
+ } catch (err) {
541
+ warn?.(`onEvent middleware threw: ${err instanceof Error ? err.message : String(err)}`);
542
+ prev();
543
+ }
544
+ };
545
+ }
546
+ next();
547
+ };
548
+ };
512
549
  var createRunner = (config2) => {
513
550
  const { agent, model, tools } = config2;
514
551
  const toolMap = new Map(tools.map((t) => [t.name, t]));
@@ -530,7 +567,13 @@ var createRunner = (config2) => {
530
567
  runId,
531
568
  parentRunId: options?.parentRunId
532
569
  };
533
- const emitter = createEventEmitter(agent.name, runId, options?.onEvent, options?.parentRunId);
570
+ const composedOnEvent = composeOnEvent(
571
+ middleware,
572
+ ctx,
573
+ options?.onEvent,
574
+ (msg) => logger.warn(msg)
575
+ );
576
+ const emitter = createEventEmitter(agent.name, runId, composedOnEvent, options?.parentRunId);
534
577
  const lifecycle = new LifecycleManager((from, to) => {
535
578
  emitter.emit({ type: "lifecycle", from, to });
536
579
  for (const mw of middleware) mw.onTransition?.(ctx, from, to);
@@ -547,6 +590,11 @@ var createRunner = (config2) => {
547
590
  ...config2.thinkingLevel ? { thinkingLevel: config2.thinkingLevel } : {},
548
591
  hasOutputSchema: Boolean(config2.responseSchema)
549
592
  });
593
+ emitter.emit({
594
+ type: "transcript_init",
595
+ systemPrompt: agent.instructions,
596
+ messages: inputMessages.map((m) => ({ role: m.role, content: m.content }))
597
+ });
550
598
  const usage = { inputTokens: 0, outputTokens: 0 };
551
599
  const conversationMessages = [...inputMessages];
552
600
  let currentRound = 0;
@@ -579,9 +627,24 @@ var createRunner = (config2) => {
579
627
  thinkingLevel: config2.thinkingLevel,
580
628
  responseSchema: config2.responseSchema
581
629
  };
582
- const response = await wrappedGenerate(params);
630
+ let response;
631
+ try {
632
+ response = await wrappedGenerate(params);
633
+ } catch (err) {
634
+ emitter.emit({
635
+ type: "llm_call",
636
+ inputTokens: 0,
637
+ outputTokens: 0,
638
+ output: "",
639
+ error: err instanceof Error ? err.message : String(err)
640
+ });
641
+ throw err;
642
+ }
583
643
  usage.inputTokens += response.usage.inputTokens;
584
644
  usage.outputTokens += response.usage.outputTokens;
645
+ if (!model.generateStream && response.thoughts) {
646
+ emitter.emit({ type: "thought", text: response.thoughts, callIndex: round });
647
+ }
585
648
  emitter.emit({
586
649
  type: "llm_call",
587
650
  inputTokens: response.usage.inputTokens,
@@ -592,9 +655,6 @@ var createRunner = (config2) => {
592
655
  args: tc.args
593
656
  }))
594
657
  });
595
- if (!model.generateStream && response.thoughts) {
596
- emitter.emit({ type: "thought", text: response.thoughts, callIndex: round });
597
- }
598
658
  if (!response.toolCalls?.length) {
599
659
  lifecycle.transition("completed");
600
660
  return {
@@ -669,6 +729,7 @@ var createRunner = (config2) => {
669
729
  ctx,
670
730
  executeFn,
671
731
  tc.name,
732
+ tc.id,
672
733
  tc.args
673
734
  );
674
735
  const startTime = Date.now();
@@ -1007,13 +1068,15 @@ var formatEvent = (e) => {
1007
1068
  case "interrupt":
1008
1069
  return `${tag} interrupt: ${e.toolName} awaiting approval`;
1009
1070
  case "kill":
1010
- return `${tag} killed${e.reason ? `: ${e.reason}` : ""}`;
1071
+ return `${tag} killed: ${e.reason}`;
1011
1072
  case "error":
1012
1073
  return `${tag} error: ${e.message}`;
1013
1074
  case "notification":
1014
1075
  return `${tag} notification: ${e.title}`;
1015
1076
  case "structured_output_complete":
1016
1077
  return `${tag} structured output complete`;
1078
+ case "transcript_init":
1079
+ return `${tag} transcript: system prompt + ${e.messages.length} message(s)`;
1017
1080
  }
1018
1081
  };
1019
1082
 
package/dist/index.d.cts CHANGED
@@ -36,7 +36,7 @@ interface Middleware {
36
36
  /** Augment tool definitions visible to the LLM. Called once at run start. */
37
37
  transformTools?: (ctx: MiddlewareContext, tools: ToolDefinition[]) => ToolDefinition[];
38
38
  /** Wrap tool execution. Called for EVERY tool call including delegation. */
39
- onToolCall?: (ctx: MiddlewareContext, toolName: string, args: unknown, next: () => Promise<unknown>) => Promise<unknown>;
39
+ onToolCall?: (ctx: MiddlewareContext, toolName: string, toolCallId: string, args: unknown, next: () => Promise<unknown>) => Promise<unknown>;
40
40
  /** Wrap LLM generation. Pre-LLM and post-LLM gates via next(). */
41
41
  onLLMCall?: (ctx: MiddlewareContext, params: GenerateParams, next: () => Promise<GenerateResponse>) => Promise<GenerateResponse>;
42
42
  /** Called on every lifecycle transition. */
@@ -174,6 +174,14 @@ interface AgentConfigEvent extends AgentEventBase {
174
174
  thinkingLevel?: string;
175
175
  hasOutputSchema: boolean;
176
176
  }
177
+ interface AgentTranscriptInitEvent extends AgentEventBase {
178
+ type: "transcript_init";
179
+ systemPrompt: string;
180
+ messages: Array<{
181
+ role: string;
182
+ content: string;
183
+ }>;
184
+ }
177
185
  interface AgentLifecycleEvent extends AgentEventBase {
178
186
  type: "lifecycle";
179
187
  from: AgentState;
@@ -188,11 +196,21 @@ interface AgentLLMCallEvent extends AgentEventBase {
188
196
  name: string;
189
197
  args: Record<string, unknown>;
190
198
  }[];
199
+ /** Set when the LLM call failed. */
200
+ error?: string;
201
+ /** Middleware enrichment: correlation ID linking this LLM call to its tool calls. */
202
+ turnId?: string;
203
+ /** Middleware enrichment: wall-clock duration in milliseconds. */
204
+ durationMs?: number;
205
+ /** Middleware enrichment: number of tool calls in the response. */
206
+ toolCallCount?: number;
191
207
  }
192
208
  interface AgentThoughtEvent extends AgentEventBase {
193
209
  type: "thought";
194
210
  text: string;
195
211
  callIndex: number;
212
+ /** Middleware enrichment: correlation ID of the active LLM call turn. */
213
+ turnId?: string;
196
214
  }
197
215
  interface AgentToolCallEvent extends AgentEventBase {
198
216
  type: "tool_call";
@@ -203,6 +221,8 @@ interface AgentToolCallEvent extends AgentEventBase {
203
221
  result?: unknown;
204
222
  error?: string;
205
223
  durationMs: number;
224
+ /** Middleware enrichment: correlation ID linking this tool call to its parent LLM call. */
225
+ turnId?: string;
206
226
  }
207
227
  interface AgentDelegationEvent extends AgentEventBase {
208
228
  type: "delegation";
@@ -219,7 +239,7 @@ interface AgentInterruptEvent extends AgentEventBase {
219
239
  }
220
240
  interface AgentKillEvent extends AgentEventBase {
221
241
  type: "kill";
222
- reason?: string;
242
+ reason: string;
223
243
  }
224
244
  interface AgentErrorEvent extends AgentEventBase {
225
245
  type: "error";
@@ -239,7 +259,7 @@ interface AgentStructuredOutputCompleteEvent extends AgentEventBase {
239
259
  /** All possible agent event type strings. */
240
260
  type AgentEventType = AgentEvent["type"];
241
261
  /** An event emitted during agent execution. Discriminated union on `type`. */
242
- type AgentEvent = AgentConfigEvent | AgentLifecycleEvent | AgentLLMCallEvent | AgentThoughtEvent | AgentToolCallEvent | AgentDelegationEvent | AgentInterruptEvent | AgentKillEvent | AgentErrorEvent | AgentNotificationEvent | AgentStructuredOutputCompleteEvent;
262
+ type AgentEvent = AgentConfigEvent | AgentTranscriptInitEvent | AgentLifecycleEvent | AgentLLMCallEvent | AgentThoughtEvent | AgentToolCallEvent | AgentDelegationEvent | AgentInterruptEvent | AgentKillEvent | AgentErrorEvent | AgentNotificationEvent | AgentStructuredOutputCompleteEvent;
243
263
  /** Distributive Omit that preserves union variants — strips base fields from each event type. */
244
264
  type AgentEventPayload<T = AgentEvent> = T extends AgentEventBase ? Omit<T, keyof AgentEventBase> : never;
245
265
  /** Log verbosity level. */
@@ -367,6 +387,8 @@ interface RunOptions {
367
387
  thinkingLevel?: ThinkingLevel;
368
388
  maxOutputTokens?: number;
369
389
  responseSchema?: Record<string, unknown>;
390
+ /** When true, tool calls are logged but not executed. */
391
+ dryRun?: boolean;
370
392
  /** @internal Shared map for pre-generated child runIds during delegation. */
371
393
  _childRunIds?: Map<string, string[]>;
372
394
  }
@@ -674,4 +696,4 @@ interface ToolConfig<TParams extends z.ZodType, TReturn = unknown> {
674
696
  */
675
697
  declare const tool: <TParams extends z.ZodType, TReturn>(config: ToolConfig<TParams, TReturn>) => Tool;
676
698
 
677
- export { Agent, type AgentConfig, type AgentConfigEvent, type AgentDelegationEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventPayload, type AgentEventType, type AgentInterruptEvent, type AgentKillEvent, type AgentLLMCallEvent, type AgentLifecycleEvent, type AgentLike, type AgentNotificationEvent, type AgentRef, type AgentState, type AgentStructuredOutputCompleteEvent, type AgentThoughtEvent, type AgentToolCallEvent, type ExecutionContext, type GenerateParams, type GenerateResponse, type GlobalConfig, type GoogleModelConfig, type GoogleModelId, type HumanDecision, type Interrupt, type Kernel, type KernelSignal, KrakenError, type LogLevel, type Message, type Middleware, type MiddlewareContext, type Model, type ModelParams, type ModelString, type OpenAIModelId, OutputValidationError, ProviderError, type RetryConfig, type RunOptions, type RunResult, type RunnerResponse, type SpawnSpec, type StreamChunk, type TeamAccessor, type ThinkingLevel, type Tool, type ToolCall, type ToolConfig, type ToolDefinition, ToolError, ToolInputValidationError, type ToolResult, type TransitionRecord, type Usage, ValidationError, configure, defineKernel, formatEvent, google, mock, openai, tool };
699
+ export { Agent, type AgentConfig, type AgentConfigEvent, type AgentDelegationEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventPayload, type AgentEventType, type AgentInterruptEvent, type AgentKillEvent, type AgentLLMCallEvent, type AgentLifecycleEvent, type AgentLike, type AgentNotificationEvent, type AgentRef, type AgentState, type AgentStructuredOutputCompleteEvent, type AgentThoughtEvent, type AgentToolCallEvent, type AgentTranscriptInitEvent, type ExecutionContext, type GenerateParams, type GenerateResponse, type GlobalConfig, type GoogleModelConfig, type GoogleModelId, type HumanDecision, type Interrupt, type Kernel, type KernelSignal, KrakenError, type LogLevel, type Message, type Middleware, type MiddlewareContext, type Model, type ModelParams, type ModelString, type OpenAIModelId, OutputValidationError, ProviderError, type RetryConfig, type RunOptions, type RunResult, type RunnerResponse, type SpawnSpec, type StreamChunk, type TeamAccessor, type ThinkingLevel, type Tool, type ToolCall, type ToolConfig, type ToolDefinition, ToolError, ToolInputValidationError, type ToolResult, type TransitionRecord, type Usage, ValidationError, configure, defineKernel, formatEvent, google, mock, openai, tool };
package/dist/index.d.ts CHANGED
@@ -36,7 +36,7 @@ interface Middleware {
36
36
  /** Augment tool definitions visible to the LLM. Called once at run start. */
37
37
  transformTools?: (ctx: MiddlewareContext, tools: ToolDefinition[]) => ToolDefinition[];
38
38
  /** Wrap tool execution. Called for EVERY tool call including delegation. */
39
- onToolCall?: (ctx: MiddlewareContext, toolName: string, args: unknown, next: () => Promise<unknown>) => Promise<unknown>;
39
+ onToolCall?: (ctx: MiddlewareContext, toolName: string, toolCallId: string, args: unknown, next: () => Promise<unknown>) => Promise<unknown>;
40
40
  /** Wrap LLM generation. Pre-LLM and post-LLM gates via next(). */
41
41
  onLLMCall?: (ctx: MiddlewareContext, params: GenerateParams, next: () => Promise<GenerateResponse>) => Promise<GenerateResponse>;
42
42
  /** Called on every lifecycle transition. */
@@ -174,6 +174,14 @@ interface AgentConfigEvent extends AgentEventBase {
174
174
  thinkingLevel?: string;
175
175
  hasOutputSchema: boolean;
176
176
  }
177
+ interface AgentTranscriptInitEvent extends AgentEventBase {
178
+ type: "transcript_init";
179
+ systemPrompt: string;
180
+ messages: Array<{
181
+ role: string;
182
+ content: string;
183
+ }>;
184
+ }
177
185
  interface AgentLifecycleEvent extends AgentEventBase {
178
186
  type: "lifecycle";
179
187
  from: AgentState;
@@ -188,11 +196,21 @@ interface AgentLLMCallEvent extends AgentEventBase {
188
196
  name: string;
189
197
  args: Record<string, unknown>;
190
198
  }[];
199
+ /** Set when the LLM call failed. */
200
+ error?: string;
201
+ /** Middleware enrichment: correlation ID linking this LLM call to its tool calls. */
202
+ turnId?: string;
203
+ /** Middleware enrichment: wall-clock duration in milliseconds. */
204
+ durationMs?: number;
205
+ /** Middleware enrichment: number of tool calls in the response. */
206
+ toolCallCount?: number;
191
207
  }
192
208
  interface AgentThoughtEvent extends AgentEventBase {
193
209
  type: "thought";
194
210
  text: string;
195
211
  callIndex: number;
212
+ /** Middleware enrichment: correlation ID of the active LLM call turn. */
213
+ turnId?: string;
196
214
  }
197
215
  interface AgentToolCallEvent extends AgentEventBase {
198
216
  type: "tool_call";
@@ -203,6 +221,8 @@ interface AgentToolCallEvent extends AgentEventBase {
203
221
  result?: unknown;
204
222
  error?: string;
205
223
  durationMs: number;
224
+ /** Middleware enrichment: correlation ID linking this tool call to its parent LLM call. */
225
+ turnId?: string;
206
226
  }
207
227
  interface AgentDelegationEvent extends AgentEventBase {
208
228
  type: "delegation";
@@ -219,7 +239,7 @@ interface AgentInterruptEvent extends AgentEventBase {
219
239
  }
220
240
  interface AgentKillEvent extends AgentEventBase {
221
241
  type: "kill";
222
- reason?: string;
242
+ reason: string;
223
243
  }
224
244
  interface AgentErrorEvent extends AgentEventBase {
225
245
  type: "error";
@@ -239,7 +259,7 @@ interface AgentStructuredOutputCompleteEvent extends AgentEventBase {
239
259
  /** All possible agent event type strings. */
240
260
  type AgentEventType = AgentEvent["type"];
241
261
  /** An event emitted during agent execution. Discriminated union on `type`. */
242
- type AgentEvent = AgentConfigEvent | AgentLifecycleEvent | AgentLLMCallEvent | AgentThoughtEvent | AgentToolCallEvent | AgentDelegationEvent | AgentInterruptEvent | AgentKillEvent | AgentErrorEvent | AgentNotificationEvent | AgentStructuredOutputCompleteEvent;
262
+ type AgentEvent = AgentConfigEvent | AgentTranscriptInitEvent | AgentLifecycleEvent | AgentLLMCallEvent | AgentThoughtEvent | AgentToolCallEvent | AgentDelegationEvent | AgentInterruptEvent | AgentKillEvent | AgentErrorEvent | AgentNotificationEvent | AgentStructuredOutputCompleteEvent;
243
263
  /** Distributive Omit that preserves union variants — strips base fields from each event type. */
244
264
  type AgentEventPayload<T = AgentEvent> = T extends AgentEventBase ? Omit<T, keyof AgentEventBase> : never;
245
265
  /** Log verbosity level. */
@@ -367,6 +387,8 @@ interface RunOptions {
367
387
  thinkingLevel?: ThinkingLevel;
368
388
  maxOutputTokens?: number;
369
389
  responseSchema?: Record<string, unknown>;
390
+ /** When true, tool calls are logged but not executed. */
391
+ dryRun?: boolean;
370
392
  /** @internal Shared map for pre-generated child runIds during delegation. */
371
393
  _childRunIds?: Map<string, string[]>;
372
394
  }
@@ -674,4 +696,4 @@ interface ToolConfig<TParams extends z.ZodType, TReturn = unknown> {
674
696
  */
675
697
  declare const tool: <TParams extends z.ZodType, TReturn>(config: ToolConfig<TParams, TReturn>) => Tool;
676
698
 
677
- export { Agent, type AgentConfig, type AgentConfigEvent, type AgentDelegationEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventPayload, type AgentEventType, type AgentInterruptEvent, type AgentKillEvent, type AgentLLMCallEvent, type AgentLifecycleEvent, type AgentLike, type AgentNotificationEvent, type AgentRef, type AgentState, type AgentStructuredOutputCompleteEvent, type AgentThoughtEvent, type AgentToolCallEvent, type ExecutionContext, type GenerateParams, type GenerateResponse, type GlobalConfig, type GoogleModelConfig, type GoogleModelId, type HumanDecision, type Interrupt, type Kernel, type KernelSignal, KrakenError, type LogLevel, type Message, type Middleware, type MiddlewareContext, type Model, type ModelParams, type ModelString, type OpenAIModelId, OutputValidationError, ProviderError, type RetryConfig, type RunOptions, type RunResult, type RunnerResponse, type SpawnSpec, type StreamChunk, type TeamAccessor, type ThinkingLevel, type Tool, type ToolCall, type ToolConfig, type ToolDefinition, ToolError, ToolInputValidationError, type ToolResult, type TransitionRecord, type Usage, ValidationError, configure, defineKernel, formatEvent, google, mock, openai, tool };
699
+ export { Agent, type AgentConfig, type AgentConfigEvent, type AgentDelegationEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventPayload, type AgentEventType, type AgentInterruptEvent, type AgentKillEvent, type AgentLLMCallEvent, type AgentLifecycleEvent, type AgentLike, type AgentNotificationEvent, type AgentRef, type AgentState, type AgentStructuredOutputCompleteEvent, type AgentThoughtEvent, type AgentToolCallEvent, type AgentTranscriptInitEvent, type ExecutionContext, type GenerateParams, type GenerateResponse, type GlobalConfig, type GoogleModelConfig, type GoogleModelId, type HumanDecision, type Interrupt, type Kernel, type KernelSignal, KrakenError, type LogLevel, type Message, type Middleware, type MiddlewareContext, type Model, type ModelParams, type ModelString, type OpenAIModelId, OutputValidationError, ProviderError, type RetryConfig, type RunOptions, type RunResult, type RunnerResponse, type SpawnSpec, type StreamChunk, type TeamAccessor, type ThinkingLevel, type Tool, type ToolCall, type ToolConfig, type ToolDefinition, ToolError, ToolInputValidationError, type ToolResult, type TransitionRecord, type Usage, ValidationError, configure, defineKernel, formatEvent, google, mock, openai, tool };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  google
3
- } from "./chunk-4X5NFWDA.js";
3
+ } from "./chunk-6Q6G4WVJ.js";
4
4
  import {
5
5
  openai
6
- } from "./chunk-5XNFMNJL.js";
6
+ } from "./chunk-D2AU5FGJ.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-RBQ2PPDE.js";
14
+ } from "./chunk-3WRAEJP3.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-GNB46G6S.js");
43
+ const { google: google2 } = await import("./google-W6HDKXTM.js");
44
44
  resolvedModel = google2(modelId);
45
45
  } else if (provider === "openai") {
46
- const { openai: openai2 } = await import("./openai-HXIIBATW.js");
46
+ const { openai: openai2 } = await import("./openai-STUANOLN.js");
47
47
  resolvedModel = openai2(modelId);
48
48
  } else {
49
49
  throw new ValidationError(`Unknown provider "${provider}".`);
@@ -141,6 +141,7 @@ var LifecycleManager = class {
141
141
  constructor(onTransition) {
142
142
  this.onTransition = onTransition;
143
143
  }
144
+ onTransition;
144
145
  _state = "idle";
145
146
  _transitions = [];
146
147
  get state() {
@@ -173,14 +174,14 @@ var composeOnLLMCall = (middleware, ctx, coreFn) => {
173
174
  }
174
175
  return fn;
175
176
  };
176
- var composeOnToolCall = (middleware, ctx, coreFn, toolName, args) => {
177
+ var composeOnToolCall = (middleware, ctx, coreFn, toolName, toolCallId, args) => {
177
178
  let fn = coreFn;
178
179
  for (let i = middleware.length - 1; i >= 0; i--) {
179
180
  const mw = middleware[i];
180
181
  if (mw?.onToolCall) {
181
182
  const prev = fn;
182
183
  const hook = mw.onToolCall;
183
- fn = () => hook(ctx, toolName, args, prev);
184
+ fn = () => hook(ctx, toolName, toolCallId, args, prev);
184
185
  }
185
186
  }
186
187
  return fn;
@@ -192,6 +193,41 @@ var applyTransformTools = (middleware, ctx, tools) => {
192
193
  }
193
194
  return result;
194
195
  };
196
+ var composeOnEvent = (middleware, ctx, sink, warn) => {
197
+ const hooks = [];
198
+ for (const mw of middleware) {
199
+ if (mw.onEvent) hooks.push(mw.onEvent);
200
+ }
201
+ if (hooks.length === 0) return sink;
202
+ return (event) => {
203
+ const origSeq = event.seq;
204
+ const origRunId = event.runId;
205
+ const origAgentName = event.agentName;
206
+ let next = () => {
207
+ if (event.seq !== origSeq || event.runId !== origRunId || event.agentName !== origAgentName) {
208
+ warn?.("onEvent middleware mutated immutable fields (seq/runId/agentName) \u2014 restoring");
209
+ event.seq = origSeq;
210
+ event.runId = origRunId;
211
+ event.agentName = origAgentName;
212
+ }
213
+ sink?.(event);
214
+ };
215
+ for (let i = hooks.length - 1; i >= 0; i--) {
216
+ const hook = hooks[i];
217
+ if (!hook) continue;
218
+ const prev = next;
219
+ next = () => {
220
+ try {
221
+ hook(ctx, event, prev);
222
+ } catch (err) {
223
+ warn?.(`onEvent middleware threw: ${err instanceof Error ? err.message : String(err)}`);
224
+ prev();
225
+ }
226
+ };
227
+ }
228
+ next();
229
+ };
230
+ };
195
231
  var createRunner = (config2) => {
196
232
  const { agent, model, tools } = config2;
197
233
  const toolMap = new Map(tools.map((t) => [t.name, t]));
@@ -213,7 +249,13 @@ var createRunner = (config2) => {
213
249
  runId,
214
250
  parentRunId: options?.parentRunId
215
251
  };
216
- const emitter = createEventEmitter(agent.name, runId, options?.onEvent, options?.parentRunId);
252
+ const composedOnEvent = composeOnEvent(
253
+ middleware,
254
+ ctx,
255
+ options?.onEvent,
256
+ (msg) => logger.warn(msg)
257
+ );
258
+ const emitter = createEventEmitter(agent.name, runId, composedOnEvent, options?.parentRunId);
217
259
  const lifecycle = new LifecycleManager((from, to) => {
218
260
  emitter.emit({ type: "lifecycle", from, to });
219
261
  for (const mw of middleware) mw.onTransition?.(ctx, from, to);
@@ -230,6 +272,11 @@ var createRunner = (config2) => {
230
272
  ...config2.thinkingLevel ? { thinkingLevel: config2.thinkingLevel } : {},
231
273
  hasOutputSchema: Boolean(config2.responseSchema)
232
274
  });
275
+ emitter.emit({
276
+ type: "transcript_init",
277
+ systemPrompt: agent.instructions,
278
+ messages: inputMessages.map((m) => ({ role: m.role, content: m.content }))
279
+ });
233
280
  const usage = { inputTokens: 0, outputTokens: 0 };
234
281
  const conversationMessages = [...inputMessages];
235
282
  let currentRound = 0;
@@ -262,9 +309,24 @@ var createRunner = (config2) => {
262
309
  thinkingLevel: config2.thinkingLevel,
263
310
  responseSchema: config2.responseSchema
264
311
  };
265
- const response = await wrappedGenerate(params);
312
+ let response;
313
+ try {
314
+ response = await wrappedGenerate(params);
315
+ } catch (err) {
316
+ emitter.emit({
317
+ type: "llm_call",
318
+ inputTokens: 0,
319
+ outputTokens: 0,
320
+ output: "",
321
+ error: err instanceof Error ? err.message : String(err)
322
+ });
323
+ throw err;
324
+ }
266
325
  usage.inputTokens += response.usage.inputTokens;
267
326
  usage.outputTokens += response.usage.outputTokens;
327
+ if (!model.generateStream && response.thoughts) {
328
+ emitter.emit({ type: "thought", text: response.thoughts, callIndex: round });
329
+ }
268
330
  emitter.emit({
269
331
  type: "llm_call",
270
332
  inputTokens: response.usage.inputTokens,
@@ -275,9 +337,6 @@ var createRunner = (config2) => {
275
337
  args: tc.args
276
338
  }))
277
339
  });
278
- if (!model.generateStream && response.thoughts) {
279
- emitter.emit({ type: "thought", text: response.thoughts, callIndex: round });
280
- }
281
340
  if (!response.toolCalls?.length) {
282
341
  lifecycle.transition("completed");
283
342
  return {
@@ -352,6 +411,7 @@ var createRunner = (config2) => {
352
411
  ctx,
353
412
  executeFn,
354
413
  tc.name,
414
+ tc.id,
355
415
  tc.args
356
416
  );
357
417
  const startTime = Date.now();
@@ -687,13 +747,15 @@ var formatEvent = (e) => {
687
747
  case "interrupt":
688
748
  return `${tag} interrupt: ${e.toolName} awaiting approval`;
689
749
  case "kill":
690
- return `${tag} killed${e.reason ? `: ${e.reason}` : ""}`;
750
+ return `${tag} killed: ${e.reason}`;
691
751
  case "error":
692
752
  return `${tag} error: ${e.message}`;
693
753
  case "notification":
694
754
  return `${tag} notification: ${e.title}`;
695
755
  case "structured_output_complete":
696
756
  return `${tag} structured output complete`;
757
+ case "transcript_init":
758
+ return `${tag} transcript: system prompt + ${e.messages.length} message(s)`;
697
759
  }
698
760
  };
699
761
 
@@ -0,0 +1,7 @@
1
+ import {
2
+ openai
3
+ } from "./chunk-D2AU5FGJ.js";
4
+ import "./chunk-3WRAEJP3.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.5",
3
+ "version": "0.0.7",
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",
@@ -14,12 +14,12 @@
14
14
  }
15
15
  },
16
16
  "devDependencies": {
17
- "@google/genai": "^1.45.0",
18
- "@types/node": "^25.5.0",
17
+ "@google/genai": "^1.48.0",
18
+ "@types/node": "^25.5.2",
19
19
  "tsup": "^8.5.1",
20
20
  "tsx": "^4.21.0",
21
- "typescript": "^5.9.3",
22
- "vitest": "^4.1.0",
21
+ "typescript": "^6.0.2",
22
+ "vitest": "^4.1.3",
23
23
  "zod": "^4.3.6"
24
24
  },
25
25
  "peerDependencies": {
@@ -1,7 +0,0 @@
1
- import {
2
- google
3
- } from "./chunk-4X5NFWDA.js";
4
- import "./chunk-RBQ2PPDE.js";
5
- export {
6
- google
7
- };
@@ -1,7 +0,0 @@
1
- import {
2
- openai
3
- } from "./chunk-5XNFMNJL.js";
4
- import "./chunk-RBQ2PPDE.js";
5
- export {
6
- openai
7
- };