agentbox-sdk 0.1.1 → 0.1.3

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,5 +1,5 @@
1
- import { l as SandboxProviderName, i as SandboxOptions, a as CommandOptions, b as CommandResult, A as AsyncCommandHandle, h as SandboxListOptions, g as SandboxDescriptor, G as GitCloneOptions } from '../Sandbox-BQX-sWzs.js';
2
- export { C as CommandEvent, D as DaytonaProviderOptions, c as DaytonaSandboxOptions, E as E2bProviderOptions, d as E2bSandboxOptions, L as LocalDockerProviderOptions, e as LocalDockerSandboxOptions, M as ModalProviderOptions, f as ModalSandboxOptions, S as Sandbox, j as SandboxOptionsBase, k as SandboxOptionsMap, m as SandboxRaw, n as SandboxRawMap, o as SandboxResourceSpec, V as VercelGitSource, p as VercelProviderOptions, q as VercelSandboxOptions } from '../Sandbox-BQX-sWzs.js';
1
+ import { l as SandboxProviderName, i as SandboxOptions, a as CommandOptions, b as CommandResult, A as AsyncCommandHandle, h as SandboxListOptions, g as SandboxDescriptor, T as TarballEntry, G as GitCloneOptions } from '../Sandbox-CByFJI8X.js';
2
+ export { C as CommandEvent, D as DaytonaProviderOptions, c as DaytonaSandboxOptions, E as E2bProviderOptions, d as E2bSandboxOptions, L as LocalDockerProviderOptions, e as LocalDockerSandboxOptions, M as ModalProviderOptions, f as ModalSandboxOptions, S as Sandbox, j as SandboxOptionsBase, k as SandboxOptionsMap, m as SandboxRaw, n as SandboxRawMap, o as SandboxResourceSpec, V as VercelGitSource, p as VercelProviderOptions, q as VercelSandboxOptions } from '../Sandbox-CByFJI8X.js';
3
3
  export { SandboxProvider } from '../enums.js';
4
4
  import 'e2b';
5
5
  import '@vercel/sandbox';
@@ -13,6 +13,13 @@ declare abstract class SandboxAdapter<TProvider extends SandboxProviderName = Sa
13
13
  protected readonly baseEnv: Record<string, string>;
14
14
  private provisioned;
15
15
  private provisioning?;
16
+ /**
17
+ * Whether `provision()` warm-attached to a pre-existing tagged sandbox
18
+ * (true) or had to create a fresh one (false). Set by adapter
19
+ * `provision()` implementations. Stays `false` until `findOrProvision()`
20
+ * has resolved.
21
+ */
22
+ protected wasFoundFlag: boolean;
16
23
  constructor(options: TOptions);
17
24
  abstract get provider(): TProvider;
18
25
  abstract get raw(): TRaw | undefined;
@@ -28,9 +35,46 @@ declare abstract class SandboxAdapter<TProvider extends SandboxProviderName = Sa
28
35
  abstract getPreviewLink(port: number): Promise<string>;
29
36
  uploadFile(_content: Buffer | string, _targetPath: string): Promise<void>;
30
37
  downloadFile(_sourcePath: string): Promise<Buffer>;
31
- protected ensureProvisioned(): Promise<void>;
38
+ /**
39
+ * Upload a tarball of files into the sandbox and execute a command in
40
+ * the same round-trip. Used by setup paths that would otherwise need one
41
+ * sandbox RPC per file plus another to run the install script — Modal-
42
+ * style providers pay ~700ms per RPC, so collapsing N+1 calls into one
43
+ * is the single biggest win on cold setup.
44
+ *
45
+ * Default implementation falls back to `uploadFile` per entry + a final
46
+ * `run`. Providers that support stdin streaming (Modal) override this to
47
+ * do the upload + extract + exec in a single sandbox `exec` call.
48
+ */
49
+ uploadAndRun(files: TarballEntry[], command: string, options?: CommandOptions): Promise<CommandResult>;
50
+ /**
51
+ * Public hook that callers must invoke before they touch the sandbox
52
+ * (running commands, cloning repos, uploading files, opening preview
53
+ * links, …). It either attaches to an existing tagged sandbox or creates
54
+ * a new one. The result is cached so repeated calls are cheap.
55
+ *
56
+ * Provisioning is no longer triggered implicitly by `run`, `runAsync`,
57
+ * `gitClone`, `uploadAndRun`, etc. Those methods now throw a clear error
58
+ * when the adapter has not been provisioned yet, which makes the
59
+ * lifecycle explicit and gives callers control over when the
60
+ * (potentially slow) sandbox attach / create happens.
61
+ */
62
+ findOrProvision(): Promise<void>;
63
+ /**
64
+ * Throw a consistent error when a method that needs a provisioned
65
+ * sandbox is called before `findOrProvision()`. Provider adapters call
66
+ * this at the top of `run`, `runAsync`, `uploadFile`, etc.
67
+ */
68
+ protected requireProvisioned(): void;
32
69
  get tags(): Record<string, string>;
33
70
  get workingDir(): string;
71
+ /**
72
+ * Whether `findOrProvision()` warm-attached to a pre-existing tagged
73
+ * sandbox (`true`) or created a fresh one (`false`). Useful to skip
74
+ * idempotent setup that the previous run already performed (e.g.
75
+ * `agent.setup()`). Always `false` before `findOrProvision()` resolves.
76
+ */
77
+ get wasFound(): boolean;
34
78
  /**
35
79
  * Headers that callers should attach to HTTP / WebSocket requests they make
36
80
  * against this sandbox's preview URL. Default is empty; providers like
@@ -45,4 +89,4 @@ declare abstract class SandboxAdapter<TProvider extends SandboxProviderName = Sa
45
89
 
46
90
  declare function buildGitCloneCommand(options: GitCloneOptions): string;
47
91
 
48
- export { AsyncCommandHandle, CommandOptions, CommandResult, GitCloneOptions, SandboxAdapter, SandboxDescriptor, SandboxListOptions, SandboxOptions, SandboxProviderName, buildGitCloneCommand };
92
+ export { AsyncCommandHandle, CommandOptions, CommandResult, GitCloneOptions, SandboxAdapter, SandboxDescriptor, SandboxListOptions, SandboxOptions, SandboxProviderName, TarballEntry, buildGitCloneCommand };
@@ -2,12 +2,12 @@ import {
2
2
  Sandbox,
3
3
  SandboxAdapter,
4
4
  buildGitCloneCommand
5
- } from "../chunk-X7AWPYDK.js";
6
- import "../chunk-O7HCJXKW.js";
5
+ } from "../chunk-LPKKT6YT.js";
6
+ import "../chunk-INMA52FV.js";
7
7
  import "../chunk-NSJM57Z4.js";
8
8
  import {
9
9
  SandboxProvider
10
- } from "../chunk-2NKMDGYH.js";
10
+ } from "../chunk-GOFJNFAD.js";
11
11
  export {
12
12
  Sandbox,
13
13
  SandboxAdapter,
@@ -1,5 +1,5 @@
1
1
  import { AgentProvider } from './enums.js';
2
- import { S as Sandbox } from './Sandbox-BQX-sWzs.js';
2
+ import { S as Sandbox } from './Sandbox-CByFJI8X.js';
3
3
 
4
4
  interface RawAgentEvent<TPayload = unknown> {
5
5
  provider: string;
@@ -23,10 +23,24 @@ interface RunStartedEvent extends NormalizedAgentEventBase {
23
23
  }
24
24
  interface MessageStartedEvent extends NormalizedAgentEventBase {
25
25
  type: "message.started";
26
+ /**
27
+ * Provider-assigned identifier for the user message that started this turn.
28
+ * Opaque to callers.
29
+ *
30
+ * - claude-code: the user message UUID written to the session JSONL
31
+ * - codex: the turn id from `turn/started`
32
+ * - open-code: the message id from `message.updated` (role=user)
33
+ */
34
+ messageId?: string;
26
35
  }
27
36
  interface MessageInjectedEvent extends NormalizedAgentEventBase {
28
37
  type: "message.injected";
29
38
  content: string;
39
+ /**
40
+ * Provider-assigned identifier for the injected user message. See
41
+ * `MessageStartedEvent.messageId` for provider-specific semantics.
42
+ */
43
+ messageId?: string;
30
44
  }
31
45
  interface TextDeltaEvent extends NormalizedAgentEventBase {
32
46
  type: "text.delta";
@@ -72,6 +86,12 @@ interface PermissionResolvedEvent extends NormalizedAgentEventBase {
72
86
  interface MessageCompletedEvent extends NormalizedAgentEventBase {
73
87
  type: "message.completed";
74
88
  text?: string;
89
+ /**
90
+ * Provider-assigned identifier for the assistant message that just
91
+ * completed. Format mirrors `MessageStartedEvent.messageId` but identifies
92
+ * the assistant turn rather than the user one.
93
+ */
94
+ messageId?: string;
75
95
  }
76
96
  interface RunCompletedEvent extends NormalizedAgentEventBase {
77
97
  type: "run.completed";
@@ -280,12 +300,23 @@ interface FilePart {
280
300
  }
281
301
  type UserContentPart = TextPart | ImagePart | FilePart;
282
302
  type UserContent = string | UserContentPart[];
303
+ type AgentReasoningEffort = "low" | "medium" | "high" | "xhigh";
283
304
  interface AgentRunConfig {
284
305
  input: UserContent;
306
+ runId?: string;
285
307
  model?: string;
286
308
  systemPrompt?: string;
287
309
  resumeSessionId?: string;
288
- }
310
+ reasoning?: AgentReasoningEffort;
311
+ }
312
+ /**
313
+ * Subset of {@link AgentRunConfig} that needs to be committed at
314
+ * `agent.setup()` time so the runtime can pre-bake artifacts that
315
+ * reference it (codex `model_instructions_file`, opencode agent config,
316
+ * etc.). Unlike `AgentRunConfig`, this never carries per-turn input or
317
+ * a resumed session id.
318
+ */
319
+ type AgentSetupConfig = Pick<AgentRunConfig, "systemPrompt" | "model" | "reasoning">;
289
320
  type AgentApprovalMode = "auto" | "interactive";
290
321
  type AgentPermissionKind = "bash" | "edit" | "tool" | "network" | "file-change" | "unknown";
291
322
  type AgentPermissionDecision = "allow" | "deny";
@@ -310,6 +341,14 @@ interface CodexProviderOptions {
310
341
  brokerEndpoint?: string;
311
342
  useBroker?: boolean;
312
343
  hooks?: CodexHooksConfig;
344
+ /**
345
+ * When `false`, writes `supports_websockets = false` into Codex's
346
+ * config.toml. Useful in environments where outbound WebSocket
347
+ * connections from the Codex CLI aren't available (proxies, network
348
+ * policies). When `true` or omitted, no key is emitted and Codex
349
+ * uses its built-in default.
350
+ */
351
+ supportsWebsockets?: boolean;
313
352
  }
314
353
  interface OpenCodeProviderOptions {
315
354
  binary?: string;
@@ -336,10 +375,22 @@ interface ClaudeCodeAgentOptions extends AgentOptionsBase {
336
375
  }
337
376
  type AgentOptionsMap = {
338
377
  codex: CodexAgentOptions;
339
- opencode: OpenCodeAgentOptions;
378
+ "open-code": OpenCodeAgentOptions;
340
379
  "claude-code": ClaudeCodeAgentOptions;
341
380
  };
342
381
  type AgentOptions<P extends AgentProviderName = AgentProviderName> = AgentOptionsMap[P];
382
+ interface AgentCostData {
383
+ total_cost_usd?: number;
384
+ duration_ms?: number;
385
+ duration_api_ms?: number;
386
+ num_turns?: number;
387
+ usage?: {
388
+ input_tokens?: number;
389
+ output_tokens?: number;
390
+ cache_creation_input_tokens?: number;
391
+ cache_read_input_tokens?: number;
392
+ };
393
+ }
343
394
  interface AgentResult {
344
395
  id: string;
345
396
  provider: AgentProviderName;
@@ -347,6 +398,7 @@ interface AgentResult {
347
398
  text: string;
348
399
  rawEvents: RawAgentEvent[];
349
400
  events: NormalizedAgentEvent[];
401
+ costData?: AgentCostData | null;
350
402
  }
351
403
  interface AgentRun extends AsyncIterable<NormalizedAgentEvent> {
352
404
  id: string;
@@ -368,20 +420,108 @@ interface AgentRunSink {
368
420
  emitRaw(event: RawAgentEvent): void;
369
421
  emitEvent(event: NormalizedAgentEvent): void;
370
422
  requestPermission(event: PermissionRequestedEvent): Promise<AgentPermissionResponse>;
371
- onMessage(handler: (content: UserContent) => Promise<void>): void;
423
+ onMessage(handler: (content: UserContent) => Promise<{
424
+ messageId?: string;
425
+ } | void>): void;
372
426
  complete(result?: {
373
427
  text?: string;
428
+ costData?: AgentCostData | null;
374
429
  }): void;
375
430
  fail(error: unknown): void;
376
431
  }
432
+ interface AgentSetupRequest<P extends AgentProviderName = AgentProviderName> {
433
+ provider: P;
434
+ options: AgentOptions<P>;
435
+ config: AgentSetupConfig;
436
+ }
377
437
  interface AgentExecutionRequest<P extends AgentProviderName = AgentProviderName> {
378
438
  runId: string;
379
439
  provider: P;
380
440
  options: AgentOptions<P>;
381
441
  run: AgentRunConfig;
382
442
  }
443
+ /**
444
+ * Stateless attach request used by {@link Agent.attach} to issue control
445
+ * commands (abort, sendMessage) against a run that lives on a different
446
+ * Twill instance.
447
+ *
448
+ * The attach call dials the in-sandbox provider server directly via
449
+ * `sandbox.getPreviewLink(...)` — no shared in-memory state, no broker.
450
+ * The originating instance still owns the run's event stream and reacts
451
+ * naturally to whatever the provider emits as a consequence of the
452
+ * attached command (e.g. `turn/aborted` for codex, message events for
453
+ * claude-code/opencode).
454
+ */
455
+ interface AgentAttachRequest<P extends AgentProviderName = AgentProviderName> {
456
+ provider: P;
457
+ sandbox: Sandbox;
458
+ /**
459
+ * The {@link AgentRunConfig.runId} the originating instance used in
460
+ * `agent.stream({ runId, ... })`. Required for claude-code (the relay
461
+ * keys channels by runId) and useful as an idempotency / log id for
462
+ * the other providers.
463
+ */
464
+ runId: string;
465
+ /**
466
+ * Provider-native session id captured from {@link AgentRun.sessionIdReady}.
467
+ *
468
+ * - codex: the threadId
469
+ * - opencode: the sessionId
470
+ * - claude-code: the claude session uuid (optional — runId is the
471
+ * primary key inside the relay)
472
+ */
473
+ sessionId?: string;
474
+ /**
475
+ * Codex only: the in-flight turn id, captured by the originating
476
+ * caller from the {@link NormalizedAgentEvent} `message.started`
477
+ * event (whose `messageId` is the codex turnId). `attachAbort` uses
478
+ * it for `turn/interrupt`. When omitted the codex attach is a no-op.
479
+ *
480
+ * The SDK does not persist this itself — bookkeeping it across
481
+ * processes is the caller's responsibility (e.g. Redis), since
482
+ * sandbox-side files don't compose well under concurrency.
483
+ */
484
+ turnId?: string;
485
+ }
486
+ /**
487
+ * Thin handle returned by {@link Agent.attach}. Methods are short-lived:
488
+ * each call opens a fresh transport to the in-sandbox server, performs
489
+ * the operation, and tears the transport down. There is no "close" —
490
+ * the handle holds no resources between calls.
491
+ */
492
+ interface AttachedRun {
493
+ abort(): Promise<void>;
494
+ sendMessage(content: UserContent): Promise<void>;
495
+ }
383
496
  interface AgentProviderAdapter<P extends AgentProviderName = AgentProviderName> {
497
+ /**
498
+ * Sandbox-side preparation work that does not depend on per-run input:
499
+ * upload artifacts (skills/commands/mcp/hook config), boot any
500
+ * provider server / relay the run will need.
501
+ *
502
+ * Required before {@link AgentProviderAdapter.execute} for sandbox-backed
503
+ * runs. {@link execute} does not read any setup output and does not
504
+ * re-do this work — it assumes the relay/server is up and dials it
505
+ * directly. If `setup` was never called against a remote sandbox the
506
+ * connect retry inside `execute` fails naturally.
507
+ *
508
+ * Idempotent: `applyDifferentialSetup` short-circuits unchanged
509
+ * artifacts, and the relay/server probes short-circuit when something
510
+ * is already listening.
511
+ */
512
+ setup(request: AgentSetupRequest<P>): Promise<void>;
384
513
  execute(request: AgentExecutionRequest<P>, sink: AgentRunSink): Promise<() => Promise<void> | void>;
514
+ /**
515
+ * Stateless abort. Dial the in-sandbox provider server, issue the
516
+ * provider's "interrupt the in-flight turn" primitive, close.
517
+ */
518
+ attachAbort(request: AgentAttachRequest<P>): Promise<void>;
519
+ /**
520
+ * Stateless message injection. Dial the in-sandbox provider server,
521
+ * append `content` as a new user turn against the existing session,
522
+ * close.
523
+ */
524
+ attachSendMessage(request: AgentAttachRequest<P>, content: UserContent): Promise<void>;
385
525
  }
386
526
 
387
- export { type RepoSkillConfig as $, type AISDKEvent as A, type CodexAgentOptions as B, type ClaudeCodeAgentOptions as C, type CodexCommandHook as D, type CodexHookEvent as E, type CodexHookMatcherGroup as F, type CodexHooksConfig as G, type CodexProviderOptions as H, type DataContent as I, type EmbeddedSkillConfig as J, type FilePart as K, type ImagePart as L, type MessageCompletedEvent as M, type MessageInjectedEvent as N, type MessageStartedEvent as O, type NormalizedAgentEvent as P, type NormalizedAgentEventBase as Q, type NormalizedAgentEventType as R, type OpenCodeAgentOptions as S, type OpenCodePluginConfig as T, type OpenCodePluginEvent as U, type OpenCodePluginHookConfig as V, type OpenCodeProviderOptions as W, type PermissionRequestedEvent as X, type PermissionResolvedEvent as Y, type RawAgentEvent as Z, type ReasoningDeltaEvent as _, type AgentApprovalMode as a, type RunCompletedEvent as a0, type RunErrorEvent as a1, type RunStartedEvent as a2, type TextDeltaEvent as a3, type TextPart as a4, type ToolCallCompletedEvent as a5, type ToolCallDeltaEvent as a6, type ToolCallStartedEvent as a7, type UserContent as a8, type UserContentPart as a9, createNormalizedEvent as aa, normalizeRawAgentEvent as ab, toAISDKEvent as ac, toAISDKStream as ad, type AgentCommandConfig as b, type AgentExecutionRequest as c, type AgentLocalMcpConfig as d, type AgentMcpConfig as e, type AgentOptions as f, type AgentOptionsBase as g, type AgentOptionsMap as h, type AgentPermissionDecision as i, type AgentPermissionKind as j, type AgentPermissionResponse as k, type AgentProviderAdapter as l, type AgentProviderName as m, type AgentRemoteMcpConfig as n, type AgentResult as o, type AgentRun as p, type AgentRunConfig as q, type AgentRunSink as r, type AgentSkillConfig as s, type AgentSubAgentConfig as t, type ClaudeCodeHookConfig as u, type ClaudeCodeHookEvent as v, type ClaudeCodeHookHandler as w, type ClaudeCodeHookMatcherGroup as x, type ClaudeCodeHooksConfig as y, type ClaudeCodeProviderOptions as z };
527
+ export { type OpenCodePluginHookConfig as $, type AISDKEvent as A, type ClaudeCodeHookConfig as B, type ClaudeCodeAgentOptions as C, type ClaudeCodeHookEvent as D, type ClaudeCodeHookHandler as E, type ClaudeCodeHookMatcherGroup as F, type ClaudeCodeHooksConfig as G, type ClaudeCodeProviderOptions as H, type CodexAgentOptions as I, type CodexCommandHook as J, type CodexHookEvent as K, type CodexHookMatcherGroup as L, type CodexHooksConfig as M, type CodexProviderOptions as N, type DataContent as O, type EmbeddedSkillConfig as P, type FilePart as Q, type ImagePart as R, type MessageCompletedEvent as S, type MessageInjectedEvent as T, type MessageStartedEvent as U, type NormalizedAgentEvent as V, type NormalizedAgentEventBase as W, type NormalizedAgentEventType as X, type OpenCodeAgentOptions as Y, type OpenCodePluginConfig as Z, type OpenCodePluginEvent as _, type AgentApprovalMode as a, type OpenCodeProviderOptions as a0, type PermissionRequestedEvent as a1, type PermissionResolvedEvent as a2, type RawAgentEvent as a3, type ReasoningDeltaEvent as a4, type RepoSkillConfig as a5, type RunCompletedEvent as a6, type RunErrorEvent as a7, type RunStartedEvent as a8, type TextDeltaEvent as a9, type TextPart as aa, type ToolCallCompletedEvent as ab, type ToolCallDeltaEvent as ac, type ToolCallStartedEvent as ad, type UserContent as ae, type UserContentPart as af, createNormalizedEvent as ag, normalizeRawAgentEvent as ah, toAISDKEvent as ai, toAISDKStream as aj, type AgentAttachRequest as b, type AgentCommandConfig as c, type AgentCostData as d, type AgentExecutionRequest as e, type AgentLocalMcpConfig as f, type AgentMcpConfig as g, type AgentOptions as h, type AgentOptionsBase as i, type AgentOptionsMap as j, type AgentPermissionDecision as k, type AgentPermissionKind as l, type AgentPermissionResponse as m, type AgentProviderAdapter as n, type AgentProviderName as o, type AgentReasoningEffort as p, type AgentRemoteMcpConfig as q, type AgentResult as r, type AgentRun as s, type AgentRunConfig as t, type AgentRunSink as u, type AgentSetupConfig as v, type AgentSetupRequest as w, type AgentSkillConfig as x, type AgentSubAgentConfig as y, type AttachedRun as z };
@@ -43,13 +43,13 @@ export default {
43
43
  run: [
44
44
  `apt-get update && apt-get install -y --no-install-recommends ${aptPackages.join(" ")} && rm -rf /var/lib/apt/lists/*`,
45
45
  "npm cache clean --force",
46
- "npm install -g pnpm @anthropic-ai/claude-code @openai/codex opencode-ai agent-browser",
46
+ "npm install -g pnpm @anthropic-ai/claude-code @anthropic-ai/claude-agent-sdk @anthropic-ai/claude-agent-sdk @openai/codex opencode-ai agent-browser",
47
47
  "agent-browser set viewport 1980 1080",
48
48
  ],
49
49
  workdir: "/workspace",
50
50
  cmd: ["sleep", "infinity"],
51
51
  resources: {
52
- cpu: 4,
53
- memoryMiB: 8192,
52
+ cpu: 1,
53
+ memoryMiB: 1024,
54
54
  },
55
55
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentbox-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Swappable coding agents and sandbox providers for Bun and TypeScript.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -51,15 +51,18 @@
51
51
  "test:watch": "vitest",
52
52
  "check": "npm run typecheck && npm run lint && npm run test",
53
53
  "hooks:install": "lefthook install",
54
- "prepare": "if [ -d .git ]; then lefthook install; else echo 'Skipping lefthook install (no .git directory)'; fi"
54
+ "prepare": "if [ -n \"$CI\" ] || [ ! -d .git ]; then echo 'Skipping lefthook install (CI or no .git directory)'; else lefthook install || echo 'Skipping lefthook install (binary unavailable)'; fi"
55
55
  },
56
56
  "engines": {
57
57
  "node": ">=20.0.0",
58
58
  "bun": ">=1.1.0"
59
59
  },
60
60
  "dependencies": {
61
+ "@anthropic-ai/claude-agent-sdk": "^0.2.123",
61
62
  "@daytonaio/sdk": "^0.161.0",
63
+ "@types/debug": "^4.1.13",
62
64
  "@vercel/sandbox": "2.0.0-beta.13",
65
+ "debug": "^4.4.3",
63
66
  "dockerode": "^4.0.10",
64
67
  "e2b": "^2.19.0",
65
68
  "eventsource-parser": "^3.0.6",
@@ -1,185 +0,0 @@
1
- // src/events/normalized.ts
2
- function createNormalizedEvent(type, base, extra) {
3
- return {
4
- type,
5
- provider: base.provider,
6
- runId: base.runId,
7
- timestamp: base.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
8
- raw: base.raw,
9
- meta: base.meta,
10
- ...extra ?? {}
11
- };
12
- }
13
- function normalizeRawAgentEvent(event) {
14
- const payload = event.payload;
15
- const common = {
16
- provider: event.provider,
17
- runId: event.runId,
18
- raw: event,
19
- timestamp: event.timestamp
20
- };
21
- if (event.type === "assistant" && Array.isArray(
22
- payload?.message?.content
23
- )) {
24
- const blocks = (payload?.message).content;
25
- const text = blocks.filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("");
26
- return [
27
- createNormalizedEvent("message.started", common),
28
- ...text ? [createNormalizedEvent("text.delta", common, { delta: text })] : [],
29
- createNormalizedEvent("message.completed", common, { text }),
30
- createNormalizedEvent("run.completed", common, { text })
31
- ];
32
- }
33
- if (event.type.includes("delta")) {
34
- const delta = String(
35
- payload?.delta ?? payload?.text ?? payload?.["content"] ?? ""
36
- );
37
- const normalizedType = event.type.includes("reasoning") ? "reasoning.delta" : "text.delta";
38
- return [createNormalizedEvent(normalizedType, common, { delta })];
39
- }
40
- if (event.type.includes("tool")) {
41
- const toolName = String(payload?.toolName ?? payload?.tool_name ?? "tool");
42
- if (event.type.includes("completed") || event.type.includes("summary")) {
43
- return [
44
- createNormalizedEvent("tool.call.completed", common, {
45
- toolName,
46
- callId: payload?.callId ?? payload?.tool_use_id,
47
- output: payload?.output ?? payload?.result
48
- })
49
- ];
50
- }
51
- return [
52
- createNormalizedEvent("tool.call.started", common, {
53
- toolName,
54
- callId: payload?.callId ?? payload?.tool_use_id,
55
- input: payload?.input
56
- })
57
- ];
58
- }
59
- if (event.type === "result") {
60
- const text = String(payload?.result ?? payload?.text ?? "");
61
- return [createNormalizedEvent("run.completed", common, { text })];
62
- }
63
- if (event.type === "error") {
64
- return [
65
- createNormalizedEvent("run.error", common, {
66
- error: String(
67
- payload?.message ?? payload?.error ?? "Unknown agent error"
68
- )
69
- })
70
- ];
71
- }
72
- return [];
73
- }
74
-
75
- // src/events/ai-sdk.ts
76
- function toAISDKEvent(event) {
77
- switch (event.type) {
78
- case "run.started":
79
- return {
80
- type: "response-start",
81
- id: event.runId,
82
- provider: event.provider
83
- };
84
- case "message.injected":
85
- return {
86
- type: "message-injected",
87
- id: event.runId,
88
- provider: event.provider,
89
- content: event.content
90
- };
91
- case "text.delta":
92
- return {
93
- type: "text-delta",
94
- id: event.runId,
95
- provider: event.provider,
96
- textDelta: event.delta
97
- };
98
- case "reasoning.delta":
99
- return {
100
- type: "reasoning-delta",
101
- id: event.runId,
102
- provider: event.provider,
103
- textDelta: event.delta
104
- };
105
- case "tool.call.started":
106
- return {
107
- type: "tool-input-start",
108
- id: event.runId,
109
- provider: event.provider,
110
- toolName: event.toolName,
111
- callId: event.callId
112
- };
113
- case "tool.call.delta":
114
- return {
115
- type: "tool-input-delta",
116
- id: event.runId,
117
- provider: event.provider,
118
- toolName: event.toolName,
119
- callId: event.callId,
120
- inputTextDelta: event.delta
121
- };
122
- case "tool.call.completed":
123
- return {
124
- type: "tool-output-available",
125
- id: event.runId,
126
- provider: event.provider,
127
- toolName: event.toolName,
128
- callId: event.callId,
129
- output: event.output
130
- };
131
- case "permission.requested":
132
- return {
133
- type: "permission-requested",
134
- id: event.runId,
135
- provider: event.provider,
136
- requestId: event.requestId,
137
- kind: event.kind,
138
- title: event.title,
139
- message: event.message,
140
- input: event.input,
141
- canRemember: event.canRemember
142
- };
143
- case "permission.resolved":
144
- return {
145
- type: "permission-resolved",
146
- id: event.runId,
147
- provider: event.provider,
148
- requestId: event.requestId,
149
- decision: event.decision,
150
- remember: event.remember
151
- };
152
- case "message.completed":
153
- case "run.completed":
154
- return {
155
- type: "response-finish",
156
- id: event.runId,
157
- provider: event.provider,
158
- text: event.text
159
- };
160
- case "run.error":
161
- return {
162
- type: "response-error",
163
- id: event.runId,
164
- provider: event.provider,
165
- error: event.error
166
- };
167
- default:
168
- return null;
169
- }
170
- }
171
- async function* toAISDKStream(events) {
172
- for await (const event of events) {
173
- const mapped = toAISDKEvent(event);
174
- if (mapped) {
175
- yield mapped;
176
- }
177
- }
178
- }
179
-
180
- export {
181
- createNormalizedEvent,
182
- normalizeRawAgentEvent,
183
- toAISDKEvent,
184
- toAISDKStream
185
- };