@theokit/agents 0.27.0 → 0.29.0

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,9 +1,9 @@
1
1
  import { ExecutionContext } from '@theokit/http';
2
2
  import { A as AgentOptions, T as ToolOptions, g as MainLoopMeta, a as ApprovalOptions, B as BudgetOptions, f as GatewayOptions, l as MemoryOptions, t as SkillsOptions, e as ContextWindowOptions, q as ProjectContextOptions, j as McpServersMap, b as CompactionDecoratorConfig, R as ReasoningEffort } from './skills-FcUdNDbn.js';
3
- import { SystemPromptResolver, SkillsSettings, ContextSettings, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, ConversationStorageAdapter, CustomTool, ModelSelection } from '@theokit/sdk';
3
+ import { SystemPromptResolver, SkillsSettings, ContextSettings, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, ConversationStorageAdapter, CustomTool, ModelSelection } from '@theokit/sdk';
4
4
  import { UIMessageChunk } from 'ai';
5
- import { RetryOptions } from '@theokit/sdk/retry';
6
5
  import { z } from 'zod';
6
+ import { RetryOptions } from '@theokit/sdk/retry';
7
7
 
8
8
  /**
9
9
  * AgentExecutionContext — extends http-decorators' ExecutionContext with agent-specific methods.
@@ -469,7 +469,7 @@ interface RuntimeOverrides {
469
469
  /** Per-run provider routing. */
470
470
  providers?: ProviderRoutingSettings;
471
471
  /** Per-run sub-agent definitions (opts-only; `compiled.agents` stays deferred — ADR D3). */
472
- agents?: Record<string, AgentDefinition>;
472
+ agents?: Record<string, AgentDefinition$1>;
473
473
  /** Per-run SDK budget tracker (inner tool-loop cap; distinct from the loop's USD `budget`). */
474
474
  budgetTracker?: BudgetTracker;
475
475
  /**
@@ -578,40 +578,94 @@ interface SdkMessage {
578
578
  */
579
579
  declare function translateSdkEvent(msg: SdkMessage, runId: string): StreamEvent[];
580
580
 
581
+ declare function translateToUIMessageStream(events: AsyncIterable<AgentStreamEvent>, opts: {
582
+ textId: string;
583
+ }): AsyncGenerator<UIMessageChunk, void, unknown>;
584
+
581
585
  /**
582
- * M0 (theokit-ai-first) — translate a theokit `AgentStreamEvent` stream into the
583
- * Vercel ai-sdk `UIMessageStream` protocol, TEXT ONLY.
586
+ * M2 (theokit-ai-first) — `defineAgent`, the zero-config imperative agent surface.
584
587
  *
585
- * This is a PURE mapping (D1): it consumes the ALREADY-deduped bridge event
586
- * stream (downstream of `mergeDeltaStream`) and yields `UIMessageChunk`s. It
587
- * NEVER calls an LLM and does NOT re-run the agent loop (sdk-runtime.md / G2) —
588
- * `@theokit/sdk` remains the only runtime.
588
+ * ADR-B1: `defineAgent({...})` (default-exported from a top-level `agents/<name>.ts`) is
589
+ * the canonical zero-config surface; the `@Agent` class decorator stays the advanced/DI
590
+ * surface. Both compile to {@link CompiledAgentOptions} and run through the same SDK
591
+ * runtime (`createSdkAgentStream`) one runtime, two syntaxes.
589
592
  *
590
- * Chunk sequence for a text run:
591
- *
592
- * start text-start{id} text-delta{id,delta}*text-end{id} finish
593
+ * This module is PURE metadata (sdk-runtime.md / G2): `defineAgent` describes an agent, it
594
+ * NEVER calls an LLM. It imports only `zod` (types) + the compiler shape — no `theokit`
595
+ * core, preserving the agents(nothing) dependency direction (G1).
596
+ */
597
+
598
+ /**
599
+ * Brand tag for a `defineAgent` value. `Symbol.for` (global registry, not `Symbol()`) so
600
+ * the brand survives duplicate module instances (dual-package / bundling) — the scanner's
601
+ * brand-check then works regardless of which copy created the definition.
602
+ */
603
+ declare const AGENT_BRAND: unique symbol;
604
+ /** Config accepted by {@link defineAgent}. */
605
+ interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
606
+ /** Zod schema for the request body — lifted into the typed client (M2, {@link InferAgentInput}). */
607
+ input?: TInput;
608
+ /** Model id (e.g. `claude-sonnet-4-6`). Falls back to the SDK default when omitted. */
609
+ model?: string;
610
+ /** Static system prompt. */
611
+ system?: string;
612
+ /** Extended-thinking effort (mirrors `@Agent({ reasoningEffort })`). */
613
+ reasoningEffort?: ReasoningEffort;
614
+ /** Pre-built tools (SDK-ready `CompiledTool` shape). */
615
+ tools?: CompiledTool[];
616
+ }
617
+ /** A branded agent definition — the value {@link defineAgent} returns. */
618
+ type AgentDefinition<TInput extends z.ZodType = z.ZodType> = DefineAgentConfig<TInput> & {
619
+ readonly [AGENT_BRAND]: true;
620
+ };
621
+ /** Infer the request type of an agent definition from its `input` Zod schema. */
622
+ type InferAgentInput<T> = T extends AgentDefinition<infer S> ? (S extends z.ZodType ? z.infer<S> : never) : never;
623
+ /**
624
+ * Define a zero-config agent. Identity/normalizer (like `defineRoute`) — returns the config
625
+ * branded so the scanner recognizes it. Compilation is deferred to {@link compileAgentDefinition}.
626
+ */
627
+ declare function defineAgent<TInput extends z.ZodType = z.ZodType>(config: DefineAgentConfig<TInput>): AgentDefinition<TInput>;
628
+ /** Brand-check: is `value` a {@link defineAgent} result? */
629
+ declare function isAgentDefinition(value: unknown): value is AgentDefinition;
630
+ /**
631
+ * Lower a definition to the SDK-ready {@link CompiledAgentOptions} — the same shape
632
+ * `compileAgent` (decorator path) produces, so both surfaces converge on one runtime.
633
+ */
634
+ declare function compileAgentDefinition(def: AgentDefinition): CompiledAgentOptions;
635
+
636
+ /**
637
+ * M2 (theokit-ai-first) — the file-convention runtime bridge.
593
638
  *
594
- * Invariants:
595
- * - Exactly one `start` and one `finish` per run.
596
- * - `text-end` is emitted ONLY if a `text-start` was emitted (no orphan close).
597
- * - A single shared `id` (`opts.textId`) for the whole text block — injected for
598
- * deterministic tests (D3).
599
- * - Every emitted chunk carries ONLY the fields required by ai-sdk's
600
- * `uiMessageChunkSchema` (a z.strictObject union — extra keys are rejected).
639
+ * Turns a loaded `agents/<name>.ts` module into the M0/M1 canonical `UIMessageStream`:
601
640
  *
602
- * Error handling (error-handling.md fail-clear, surface don't swallow, never
603
- * throw past the boundary): an `error` event OR a thrown/aborted underlying
604
- * iterable is SURFACED as an ai-sdk `error` chunk (`{ type: 'error', errorText }`),
605
- * then closes an open text (`text-end`) and terminates with `finish`. The error is
606
- * not re-thrown — the transport still produces a well-formed, terminated stream the
607
- * client can render as a failed turn.
641
+ * module (defineAgent value | @Agent class) ──compileAgentModule──▶ CompiledAgentOptions
642
+ * CompiledAgentOptions ──createSdkAgentStream──▶ AgentStreamEvent* ──translate──▶ UIMessageChunk*
608
643
  *
609
- * Tool / reasoning / file chunks are intentionally out of scope for M0 (YAGNI);
610
- * non-text events are ignored here and widen the mapping in M1.
644
+ * Both agent surfaces converge here (ADR-B1): a `defineAgent` value lowers via
645
+ * `compileAgentDefinition`, an `@Agent`-decorated class lowers via `compileAgent`
646
+ * (which requires the full `@MainLoop` decoration — its existing errors surface for
647
+ * DI-heavy classes). Neither runs an LLM directly — `@theokit/sdk` stays the sole
648
+ * runtime (G2 / sdk-runtime.md); this module only wires its output onto the wire.
611
649
  */
612
- declare function translateToUIMessageStream(events: AsyncIterable<AgentStreamEvent>, opts: {
613
- textId: string;
614
- }): AsyncGenerator<UIMessageChunk, void, unknown>;
650
+
651
+ /** Thrown when an `agents/` file default-exports neither a `defineAgent` value nor an `@Agent` class. */
652
+ declare class AgentDefinitionError extends Error {
653
+ constructor(source: string);
654
+ }
655
+ /**
656
+ * Compile a loaded `agents/` module to SDK-ready options. Accepts a `defineAgent` value
657
+ * (zero-config surface) OR an `@Agent`-decorated class (advanced surface). `source` labels
658
+ * the fail-fast error (typically the file path).
659
+ */
660
+ declare function compileAgentModule(mod: unknown, source?: string): CompiledAgentOptions;
661
+ /**
662
+ * Run a compiled agent and yield the M0/M1 `UIMessageStream` chunks. `apiKey` is resolved
663
+ * by the caller (`resolveProvider`). One `textId` per run (G8: `crypto.randomUUID`).
664
+ */
665
+ declare function streamAgentUIMessages(compiled: CompiledAgentOptions, apiKey: string, input: {
666
+ message: string;
667
+ sessionId: string;
668
+ }): AsyncGenerator<UIMessageChunk>;
615
669
 
616
670
  /**
617
671
  * LoopStrategy — the per-round terminal-decision contract that gives runtime to
@@ -832,7 +886,7 @@ interface DelegateOptions {
832
886
  /** Per-run provider routing (e.g. OpenRouter). */
833
887
  providers?: ProviderRoutingSettings;
834
888
  /** Per-run sub-agent definitions. */
835
- agents?: Record<string, AgentDefinition>;
889
+ agents?: Record<string, AgentDefinition$1>;
836
890
  /** Per-run SDK budget tracker (inner tool-loop cap). */
837
891
  budgetTracker?: BudgetTracker;
838
892
  /** Per-run conversation store (cross-round history). */
@@ -943,4 +997,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
943
997
  register(app: PluginApp): void;
944
998
  };
945
999
 
946
- export { compileTools as $, type AgentExecutionContext as A, BudgetExceededError as B, type CompiledAgentOptions as C, type DelegationResult as D, type ErrorEvent as E, type FileEditEvent as F, type RunStartedEvent as G, type SdkMessage as H, type IterationEvent as I, type Segment as J, type StateUpdateEvent as K, type LoopStrategy as L, type ThinkingEvent as M, type ToolCallEvent as N, type ToolResultEvent as O, type PartialToolCallEvent as P, type ToolWalkResult as Q, type ReflectionStrategy as R, type StreamEvent as S, type TextDeltaEvent as T, type ToolboxWalkResult as U, agentsPlugin as V, buildModelSelection as W, compileAgent as X, compileContextWindow as Y, compileProjectContext as Z, compileSkills as _, type CompiledTool as a, createAgentExecutionContext as a0, createSdkAgentStream as a1, createThinkTagExtractor as a2, delegate as a3, extractThinkTagStream as a4, generateAgentManifest as a5, generateAgentRoutes as a6, isAgentContext as a7, isApprovalRequired as a8, isDone as a9, isError as aa, isPartialToolCall as ab, isTextDelta as ac, isToolCall as ad, isToolResult as ae, ladderReflectionStrategy as af, loopStrategyConfigSchema as ag, noopReflectionStrategy as ah, projectContextMetadataOnlyKnobs as ai, reflectionStrategyConfigSchema as aj, resolveLoopStrategy as ak, streamAgentResponse as al, translateSdkEvent as am, translateToUIMessageStream as an, validateUniqueRoutes as ao, walkAgentMetadata as ap, type AgentManifest as b, type AgentManifestEntry as c, type AgentManifestTool as d, type AgentRoute as e, type AgentRouteContext as f, type AgentRunInfo as g, type AgentStreamEvent as h, type AgentWalkResult as i, AgentWarningCode as j, type AgentsPluginOptions as k, type ApprovalRequiredEvent as l, type ArtifactChunkEvent as m, type ArtifactStartEvent as n, type CheckpointSavedEvent as o, type CompiledContextWindow as p, DEFAULT_MAX_ITERATIONS as q, type DelegateOptions as r, DelegationError as s, type DoneEvent as t, type LoopFinishReason as u, type LoopOutcome as v, type LoopStrategyConfig as w, type ReflectionContext as x, type ReflectionResult as y, type ReflectionStrategyConfig as z };
1000
+ export { buildModelSelection as $, AGENT_BRAND as A, BudgetExceededError as B, type CompiledAgentOptions as C, type DelegationResult as D, type ErrorEvent as E, type FileEditEvent as F, type LoopOutcome as G, type LoopStrategyConfig as H, type InferAgentInput as I, type ReflectionContext as J, type ReflectionResult as K, type LoopStrategy as L, type ReflectionStrategyConfig as M, type RunStartedEvent as N, type SdkMessage as O, type PartialToolCallEvent as P, type Segment as Q, type ReflectionStrategy as R, type StreamEvent as S, type StateUpdateEvent as T, type TextDeltaEvent as U, type ThinkingEvent as V, type ToolCallEvent as W, type ToolResultEvent as X, type ToolWalkResult as Y, type ToolboxWalkResult as Z, agentsPlugin as _, type CompiledTool as a, compileAgent as a0, compileAgentDefinition as a1, compileAgentModule as a2, compileContextWindow as a3, compileProjectContext as a4, compileSkills as a5, compileTools as a6, createAgentExecutionContext as a7, createSdkAgentStream as a8, createThinkTagExtractor as a9, defineAgent as aa, delegate as ab, extractThinkTagStream as ac, generateAgentManifest as ad, generateAgentRoutes as ae, isAgentContext as af, isAgentDefinition as ag, isApprovalRequired as ah, isDone as ai, isError as aj, isPartialToolCall as ak, isTextDelta as al, isToolCall as am, isToolResult as an, ladderReflectionStrategy as ao, loopStrategyConfigSchema as ap, noopReflectionStrategy as aq, projectContextMetadataOnlyKnobs as ar, reflectionStrategyConfigSchema as as, resolveLoopStrategy as at, streamAgentResponse as au, streamAgentUIMessages as av, translateSdkEvent as aw, translateToUIMessageStream as ax, validateUniqueRoutes as ay, walkAgentMetadata as az, type AgentDefinition as b, AgentDefinitionError as c, type AgentExecutionContext as d, type AgentManifest as e, type AgentManifestEntry as f, type AgentManifestTool as g, type AgentRoute as h, type AgentRouteContext as i, type AgentRunInfo as j, type AgentStreamEvent as k, type AgentWalkResult as l, AgentWarningCode as m, type AgentsPluginOptions as n, type ApprovalRequiredEvent as o, type ArtifactChunkEvent as p, type ArtifactStartEvent as q, type CheckpointSavedEvent as r, type CompiledContextWindow as s, DEFAULT_MAX_ITERATIONS as t, type DefineAgentConfig as u, type DelegateOptions as v, DelegationError as w, type DoneEvent as x, type IterationEvent as y, type LoopFinishReason as z };
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AgentExecutionContext, b as AgentManifest, c as AgentManifestEntry, d as AgentManifestTool, e as AgentRoute, f as AgentRouteContext, g as AgentRunInfo, h as AgentStreamEvent, i as AgentWalkResult, j as AgentWarningCode, k as AgentsPluginOptions, l as ApprovalRequiredEvent, m as ArtifactChunkEvent, n as ArtifactStartEvent, B as BudgetExceededError, o as CheckpointSavedEvent, C as CompiledAgentOptions, p as CompiledContextWindow, a as CompiledTool, r as DelegateOptions, s as DelegationError, D as DelegationResult, t as DoneEvent, E as ErrorEvent, F as FileEditEvent, I as IterationEvent, P as PartialToolCallEvent, G as RunStartedEvent, H as SdkMessage, J as Segment, K as StateUpdateEvent, S as StreamEvent, T as TextDeltaEvent, M as ThinkingEvent, N as ToolCallEvent, O as ToolResultEvent, Q as ToolWalkResult, U as ToolboxWalkResult, V as agentsPlugin, W as buildModelSelection, X as compileAgent, Y as compileContextWindow, Z as compileProjectContext, _ as compileSkills, $ as compileTools, a0 as createAgentExecutionContext, a1 as createSdkAgentStream, a2 as createThinkTagExtractor, a3 as delegate, a4 as extractThinkTagStream, a5 as generateAgentManifest, a6 as generateAgentRoutes, a7 as isAgentContext, a8 as isApprovalRequired, a9 as isDone, aa as isError, ab as isPartialToolCall, ac as isTextDelta, ad as isToolCall, ae as isToolResult, ai as projectContextMetadataOnlyKnobs, al as streamAgentResponse, am as translateSdkEvent, an as translateToUIMessageStream, ao as validateUniqueRoutes, ap as walkAgentMetadata } from './bridge-entry-QmUEnkn7.js';
1
+ export { A as AGENT_BRAND, b as AgentDefinition, c as AgentDefinitionError, d as AgentExecutionContext, e as AgentManifest, f as AgentManifestEntry, g as AgentManifestTool, h as AgentRoute, i as AgentRouteContext, j as AgentRunInfo, k as AgentStreamEvent, l as AgentWalkResult, m as AgentWarningCode, n as AgentsPluginOptions, o as ApprovalRequiredEvent, p as ArtifactChunkEvent, q as ArtifactStartEvent, B as BudgetExceededError, r as CheckpointSavedEvent, C as CompiledAgentOptions, s as CompiledContextWindow, a as CompiledTool, u as DefineAgentConfig, v as DelegateOptions, w as DelegationError, D as DelegationResult, x as DoneEvent, E as ErrorEvent, F as FileEditEvent, I as InferAgentInput, y as IterationEvent, P as PartialToolCallEvent, N as RunStartedEvent, O as SdkMessage, Q as Segment, T as StateUpdateEvent, S as StreamEvent, U as TextDeltaEvent, V as ThinkingEvent, W as ToolCallEvent, X as ToolResultEvent, Y as ToolWalkResult, Z as ToolboxWalkResult, _ as agentsPlugin, $ as buildModelSelection, a0 as compileAgent, a1 as compileAgentDefinition, a2 as compileAgentModule, a3 as compileContextWindow, a4 as compileProjectContext, a5 as compileSkills, a6 as compileTools, a7 as createAgentExecutionContext, a8 as createSdkAgentStream, a9 as createThinkTagExtractor, aa as defineAgent, ab as delegate, ac as extractThinkTagStream, ad as generateAgentManifest, ae as generateAgentRoutes, af as isAgentContext, ag as isAgentDefinition, ah as isApprovalRequired, ai as isDone, aj as isError, ak as isPartialToolCall, al as isTextDelta, am as isToolCall, an as isToolResult, ar as projectContextMetadataOnlyKnobs, au as streamAgentResponse, av as streamAgentUIMessages, aw as translateSdkEvent, ax as translateToUIMessageStream, ay as validateUniqueRoutes, az as walkAgentMetadata } from './bridge-entry-BlS01zM3.js';
2
2
  import '@theokit/http';
3
3
  import './skills-FcUdNDbn.js';
4
4
  import '@theokit/sdk';
package/dist/bridge.js CHANGED
@@ -1,10 +1,14 @@
1
1
  import {
2
+ AGENT_BRAND,
3
+ AgentDefinitionError,
2
4
  AgentWarningCode,
3
5
  BudgetExceededError,
4
6
  DelegationError,
5
7
  agentsPlugin,
6
8
  buildModelSelection,
7
9
  compileAgent,
10
+ compileAgentDefinition,
11
+ compileAgentModule,
8
12
  compileContextWindow,
9
13
  compileProjectContext,
10
14
  compileSkills,
@@ -12,11 +16,13 @@ import {
12
16
  createAgentExecutionContext,
13
17
  createSdkAgentStream,
14
18
  createThinkTagExtractor,
19
+ defineAgent,
15
20
  delegate,
16
21
  extractThinkTagStream,
17
22
  generateAgentManifest,
18
23
  generateAgentRoutes,
19
24
  isAgentContext,
25
+ isAgentDefinition,
20
26
  isApprovalRequired,
21
27
  isDone,
22
28
  isError,
@@ -26,20 +32,25 @@ import {
26
32
  isToolResult,
27
33
  projectContextMetadataOnlyKnobs,
28
34
  streamAgentResponse,
35
+ streamAgentUIMessages,
29
36
  translateSdkEvent,
30
37
  translateToUIMessageStream,
31
38
  validateUniqueRoutes,
32
39
  walkAgentMetadata
33
- } from "./chunk-QR5PFBYT.js";
40
+ } from "./chunk-4AN6LDJS.js";
34
41
  import "./chunk-GVPUUKKE.js";
35
42
  import "./chunk-7QVYU63E.js";
36
43
  export {
44
+ AGENT_BRAND,
45
+ AgentDefinitionError,
37
46
  AgentWarningCode,
38
47
  BudgetExceededError,
39
48
  DelegationError,
40
49
  agentsPlugin,
41
50
  buildModelSelection,
42
51
  compileAgent,
52
+ compileAgentDefinition,
53
+ compileAgentModule,
43
54
  compileContextWindow,
44
55
  compileProjectContext,
45
56
  compileSkills,
@@ -47,11 +58,13 @@ export {
47
58
  createAgentExecutionContext,
48
59
  createSdkAgentStream,
49
60
  createThinkTagExtractor,
61
+ defineAgent,
50
62
  delegate,
51
63
  extractThinkTagStream,
52
64
  generateAgentManifest,
53
65
  generateAgentRoutes,
54
66
  isAgentContext,
67
+ isAgentDefinition,
55
68
  isApprovalRequired,
56
69
  isDone,
57
70
  isError,
@@ -61,6 +74,7 @@ export {
61
74
  isToolResult,
62
75
  projectContextMetadataOnlyKnobs,
63
76
  streamAgentResponse,
77
+ streamAgentUIMessages,
64
78
  translateSdkEvent,
65
79
  translateToUIMessageStream,
66
80
  validateUniqueRoutes,
@@ -1167,32 +1167,115 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1167
1167
  __name(createSdkAgentStream, "createSdkAgentStream");
1168
1168
 
1169
1169
  // src/bridge/ui-message-stream-translator.ts
1170
+ function* closeOpenBlock(state, textId) {
1171
+ if (state.openBlock === "text") {
1172
+ yield {
1173
+ type: "text-end",
1174
+ id: textId
1175
+ };
1176
+ } else if (state.openBlock === "reasoning" && state.reasoningId) {
1177
+ yield {
1178
+ type: "reasoning-end",
1179
+ id: state.reasoningId
1180
+ };
1181
+ }
1182
+ state.openBlock = null;
1183
+ state.reasoningId = null;
1184
+ }
1185
+ __name(closeOpenBlock, "closeOpenBlock");
1186
+ function* emitToolCall(event, seen) {
1187
+ seen.add(event.callId);
1188
+ yield {
1189
+ type: "tool-input-available",
1190
+ toolCallId: event.callId,
1191
+ toolName: event.toolName,
1192
+ input: event.input,
1193
+ dynamic: true
1194
+ };
1195
+ }
1196
+ __name(emitToolCall, "emitToolCall");
1197
+ function* emitToolResult(event, seen) {
1198
+ if (!seen.has(event.callId)) {
1199
+ seen.add(event.callId);
1200
+ yield {
1201
+ type: "tool-input-available",
1202
+ toolCallId: event.callId,
1203
+ toolName: event.toolName,
1204
+ input: {},
1205
+ dynamic: true
1206
+ };
1207
+ }
1208
+ if (event.isError) {
1209
+ yield {
1210
+ type: "tool-output-error",
1211
+ toolCallId: event.callId,
1212
+ errorText: event.output
1213
+ };
1214
+ } else {
1215
+ yield {
1216
+ type: "tool-output-available",
1217
+ toolCallId: event.callId,
1218
+ output: event.output
1219
+ };
1220
+ }
1221
+ }
1222
+ __name(emitToolResult, "emitToolResult");
1170
1223
  async function* translateToUIMessageStream(events, opts) {
1171
1224
  yield {
1172
1225
  type: "start"
1173
1226
  };
1174
- let textOpen = false;
1227
+ const state = {
1228
+ openBlock: null,
1229
+ reasoningId: null
1230
+ };
1231
+ const seenToolCallIds = /* @__PURE__ */ new Set();
1175
1232
  try {
1176
1233
  for await (const event of events) {
1177
1234
  if (event.type === "text_delta") {
1178
- if (!textOpen) {
1235
+ if (state.openBlock !== "text") {
1236
+ yield* closeOpenBlock(state, opts.textId);
1179
1237
  yield {
1180
1238
  type: "text-start",
1181
1239
  id: opts.textId
1182
1240
  };
1183
- textOpen = true;
1241
+ state.openBlock = "text";
1184
1242
  }
1185
1243
  yield {
1186
1244
  type: "text-delta",
1187
1245
  id: opts.textId,
1188
1246
  delta: event.content
1189
1247
  };
1248
+ } else if (event.type === "thinking") {
1249
+ let reasoningId = state.openBlock === "reasoning" ? state.reasoningId : null;
1250
+ if (reasoningId === null) {
1251
+ yield* closeOpenBlock(state, opts.textId);
1252
+ reasoningId = crypto.randomUUID();
1253
+ state.reasoningId = reasoningId;
1254
+ yield {
1255
+ type: "reasoning-start",
1256
+ id: reasoningId
1257
+ };
1258
+ state.openBlock = "reasoning";
1259
+ }
1260
+ yield {
1261
+ type: "reasoning-delta",
1262
+ id: reasoningId,
1263
+ delta: event.content
1264
+ };
1265
+ } else if (event.type === "tool_call") {
1266
+ yield* closeOpenBlock(state, opts.textId);
1267
+ yield* emitToolCall(event, seenToolCallIds);
1268
+ } else if (event.type === "tool_result") {
1269
+ yield* closeOpenBlock(state, opts.textId);
1270
+ yield* emitToolResult(event, seenToolCallIds);
1190
1271
  } else if (event.type === "error") {
1191
1272
  yield {
1192
1273
  type: "error",
1193
1274
  errorText: event.message
1194
1275
  };
1195
1276
  break;
1277
+ } else if (event.type === "done") {
1278
+ break;
1196
1279
  }
1197
1280
  }
1198
1281
  } catch (err) {
@@ -1201,18 +1284,78 @@ async function* translateToUIMessageStream(events, opts) {
1201
1284
  errorText: String(err)
1202
1285
  };
1203
1286
  }
1204
- if (textOpen) {
1205
- yield {
1206
- type: "text-end",
1207
- id: opts.textId
1208
- };
1209
- }
1287
+ yield* closeOpenBlock(state, opts.textId);
1210
1288
  yield {
1211
1289
  type: "finish"
1212
1290
  };
1213
1291
  }
1214
1292
  __name(translateToUIMessageStream, "translateToUIMessageStream");
1215
1293
 
1294
+ // src/bridge/define-agent.ts
1295
+ var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
1296
+ function defineAgent(config) {
1297
+ return {
1298
+ ...config,
1299
+ [AGENT_BRAND]: true
1300
+ };
1301
+ }
1302
+ __name(defineAgent, "defineAgent");
1303
+ function isAgentDefinition(value) {
1304
+ return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
1305
+ }
1306
+ __name(isAgentDefinition, "isAgentDefinition");
1307
+ function compileAgentDefinition(def) {
1308
+ return {
1309
+ model: def.model,
1310
+ reasoningEffort: def.reasoningEffort,
1311
+ systemPrompt: def.system,
1312
+ tools: def.tools ?? [],
1313
+ agents: {},
1314
+ stream: true
1315
+ };
1316
+ }
1317
+ __name(compileAgentDefinition, "compileAgentDefinition");
1318
+
1319
+ // src/bridge/agent-endpoint.ts
1320
+ var AgentDefinitionError = class extends Error {
1321
+ static {
1322
+ __name(this, "AgentDefinitionError");
1323
+ }
1324
+ constructor(source) {
1325
+ super(`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`);
1326
+ this.name = "AgentDefinitionError";
1327
+ }
1328
+ };
1329
+ function extractDefaultExport(mod) {
1330
+ if (typeof mod === "object" && mod !== null && "default" in mod) {
1331
+ return mod.default;
1332
+ }
1333
+ return mod;
1334
+ }
1335
+ __name(extractDefaultExport, "extractDefaultExport");
1336
+ function compileAgentModule(mod, source = "agent module") {
1337
+ const def = extractDefaultExport(mod);
1338
+ if (isAgentDefinition(def)) {
1339
+ return compileAgentDefinition(def);
1340
+ }
1341
+ if (typeof def === "function" && getAgentConfig(def) !== void 0) {
1342
+ return compileAgent(walkAgentMetadata(def));
1343
+ }
1344
+ throw new AgentDefinitionError(source);
1345
+ }
1346
+ __name(compileAgentModule, "compileAgentModule");
1347
+ async function* asAgentStream(events) {
1348
+ for await (const e of events) yield e;
1349
+ }
1350
+ __name(asAgentStream, "asAgentStream");
1351
+ function streamAgentUIMessages(compiled, apiKey, input) {
1352
+ const events = createSdkAgentStream(compiled, compiled.tools, apiKey)(input.message, input.sessionId);
1353
+ return translateToUIMessageStream(asAgentStream(events), {
1354
+ textId: crypto.randomUUID()
1355
+ });
1356
+ }
1357
+ __name(streamAgentUIMessages, "streamAgentUIMessages");
1358
+
1216
1359
  // src/loop/compaction-strategy.ts
1217
1360
  import { compactTranscript } from "@theokit/sdk/compaction";
1218
1361
  import { z } from "zod";
@@ -1933,6 +2076,13 @@ export {
1933
2076
  extractThinkTagStream,
1934
2077
  createSdkAgentStream,
1935
2078
  translateToUIMessageStream,
2079
+ AGENT_BRAND,
2080
+ defineAgent,
2081
+ isAgentDefinition,
2082
+ compileAgentDefinition,
2083
+ AgentDefinitionError,
2084
+ compileAgentModule,
2085
+ streamAgentUIMessages,
1936
2086
  DEFAULT_KEEP_TOKENS,
1937
2087
  compactionStrategyConfigSchema,
1938
2088
  resolveCompactionStrategy,
@@ -1951,4 +2101,4 @@ export {
1951
2101
  generateAgentManifest,
1952
2102
  agentsPlugin
1953
2103
  };
1954
- //# sourceMappingURL=chunk-QR5PFBYT.js.map
2104
+ //# sourceMappingURL=chunk-4AN6LDJS.js.map