@theokit/agents 0.43.0 → 0.44.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,8 +1,8 @@
1
1
  import { ExecutionContext } from '@theokit/http';
2
2
  import { A as AgentOptions, g as ToolOptions, M as MainLoopMeta, a as ApprovalOptions, B as BudgetOptions, H as HumanInTheLoopOptions, t as GatewayOptions, z as MemoryOptions, O as SkillsOptions, r as ContextWindowOptions, K as ProjectContextOptions, x as McpServersMap, G as Guardrail, o as CompactionDecoratorConfig, j as CheckpointOptions, R as ReasoningEffort } from './types-DVA4LQsA.js';
3
- import { InlineSkill, SystemPromptResolver, SettingSource, SkillsSettings, ContextSettings, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, CustomTool, ModelSelection } from '@theokit/sdk';
4
- import { UIMessageChunk } from 'ai';
3
+ import { InlineSkill, SystemPromptResolver, SettingSource, SkillsSettings, ContextSettings, CustomTool, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, ModelSelection } from '@theokit/sdk';
5
4
  import { z } from 'zod';
5
+ import { UIMessageChunk } from 'ai';
6
6
  import { RetryOptions } from '@theokit/sdk/retry';
7
7
 
8
8
  /**
@@ -513,6 +513,114 @@ interface AgentRouteContext {
513
513
  /** Generate HTTP routes for a single agent. Returns Web Standard handlers. */
514
514
  declare function generateAgentRoutes(ctx: AgentRouteContext): AgentRoute[];
515
515
 
516
+ /**
517
+ * M2 (theokit-ai-first) — `defineAgent`, the zero-config imperative agent surface.
518
+ *
519
+ * ADR-B1: `defineAgent({...})` (default-exported from a top-level `agents/<name>.ts`) is
520
+ * the canonical zero-config surface; the `@Agent` class decorator stays the advanced/DI
521
+ * surface. Both compile to {@link CompiledAgentOptions} and run through the same SDK
522
+ * runtime (`createSdkAgentStream`) — one runtime, two syntaxes.
523
+ *
524
+ * This module is PURE metadata (sdk-runtime.md / G2): `defineAgent` describes an agent, it
525
+ * NEVER calls an LLM. It imports only `zod` (types) + the compiler shape — no `theokit`
526
+ * core, preserving the agents → (nothing) dependency direction (G1).
527
+ */
528
+
529
+ /**
530
+ * Brand tag for a `defineAgent` value. `Symbol.for` (global registry, not `Symbol()`) so
531
+ * the brand survives duplicate module instances (dual-package / bundling) — the scanner's
532
+ * brand-check then works regardless of which copy created the definition.
533
+ */
534
+ declare const AGENT_BRAND: unique symbol;
535
+ /** Config accepted by {@link defineAgent}. */
536
+ interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
537
+ /** Zod schema for the request body — lifted into the typed client (M2, {@link InferAgentInput}). */
538
+ input?: TInput;
539
+ /** Model id (e.g. `claude-sonnet-4-6`). Falls back to the SDK default when omitted. */
540
+ model?: string;
541
+ /** Static system prompt. */
542
+ system?: string;
543
+ /** Extended-thinking effort (mirrors `@Agent({ reasoningEffort })`). */
544
+ reasoningEffort?: ReasoningEffort;
545
+ /**
546
+ * Pre-built tools. Accepts the `@theokit/sdk` `CustomTool` that `defineAgentTool`
547
+ * (theokit/server) and every `@theokit/sdk-tools` factory return (issue #81) — they are
548
+ * normalized to the internal {@link CompiledTool} shape at compile time.
549
+ */
550
+ tools?: readonly CustomTool[];
551
+ /**
552
+ * M7 — run-context: an opaque, per-agent object forwarded to every tool handler's
553
+ * `ctx.context` at run time (injected by the theokit adapter's tool wrapper). Set shared config
554
+ * (e.g. `{ projectRoot }`) ONCE at the agent level instead of baking it into each tool
555
+ * factory. Mirrors ai-sdk `experimental_context`, mastra `RuntimeContext`, and
556
+ * openai-agents-js `RunContext`. Distinct from `@Agent`'s context-window `context`.
557
+ */
558
+ context?: Record<string, unknown>;
559
+ /**
560
+ * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).
561
+ * Input guards run on the user message before the SDK runtime; a `block` fails the run fast.
562
+ * Built-ins live in `@theokit/agents` (`promptInjectionDetector`, `piiDetector`, `costGuard`,
563
+ * `unicodeNormalizer`, `outputModeration`).
564
+ */
565
+ guardrails?: readonly Guardrail[];
566
+ /**
567
+ * M14 — HITL approvals keyed by tool name. Each gated tool pauses the run and emits an
568
+ * `approval_required` event until approved (reuses the same `compiled.hitl` wiring the `@Agent`
569
+ * + `@HumanInTheLoop` path produces). A key that does not match a declared tool fails fast at
570
+ * compile time.
571
+ */
572
+ approvals?: Record<string, HumanInTheLoopOptions>;
573
+ /**
574
+ * M13 — skills selection: a static list (compiled straight to the SDK `skills.enabled`) OR a
575
+ * per-request resolver `(ctx) => string[]` (carried on `compiled.skillsResolver`, resolved by the
576
+ * request path against the run-context). Absent ⇒ the SDK enables every discovered skill.
577
+ */
578
+ skills?: SkillsSelection;
579
+ /**
580
+ * theokit-file-based-config — opt into `.theokit/` file-based config (skills, subagents, hooks,
581
+ * MCP, context, cron). The SDK discovers config from these roots under the app's `cwd`:
582
+ * `"project"` = `<cwd>/.theokit/`, `"user"` = `~/.theokit/`. Absent ⇒ inline (code) config only.
583
+ * SECURITY: enabling `"project"` enables shell-executing hooks from `.theokit/hooks.json` — this
584
+ * is opt-in because `.theokit/` is the app's own repo (informed consent). The SDK owns discovery
585
+ * + execution (G2 / ADR-0040); theokit only wires this into `Agent.create({ local.settingSources })`.
586
+ */
587
+ settingSources?: readonly SettingSource[];
588
+ /**
589
+ * MCP servers available to the agent — the builder-chain equivalent of the `@MCP` class
590
+ * decorator. Each key is a server name; the value is the server configuration. Forwarded
591
+ * unchanged to `Agent.create({ mcpServers })` (the SDK owns MCP execution). Absent ⇒ no MCP.
592
+ */
593
+ mcpServers?: McpServersMap;
594
+ }
595
+ /**
596
+ * A branded agent definition — the value {@link defineAgent} returns.
597
+ *
598
+ * `TTools` (M8) is a phantom type parameter carrying the tool-name union: the `agent()` builder
599
+ * threads its accumulated literal tool names here (`.build()` returns `AgentDefinition<TInput,
600
+ * 'a' | 'b'>`), so the generated client (`.theokit/agents.d.ts`) can expose them via
601
+ * {@link InferAgentToolNames}. `defineAgent` leaves it `string` (its tools array carries no literal
602
+ * names). Never present at runtime.
603
+ */
604
+ type AgentDefinition<TInput extends z.ZodType = z.ZodType, TTools extends string = string> = DefineAgentConfig<TInput> & {
605
+ readonly [AGENT_BRAND]: true;
606
+ readonly __toolNames?: TTools;
607
+ };
608
+ /** Infer the request type of an agent definition from its `input` Zod schema. */
609
+ type InferAgentInput<T> = T extends AgentDefinition<infer S> ? (S extends z.ZodType ? z.infer<S> : never) : never;
610
+ /**
611
+ * Infer the tool-name union of an agent definition (M8). Yields the literal union for agents built
612
+ * with the `agent()` builder (`'read_file' | 'count_lines'`), or `string` for `defineAgent` agents
613
+ * whose tools array carries no literal names.
614
+ */
615
+ type InferAgentToolNames<T> = T extends AgentDefinition<z.ZodType, infer N> ? N : never;
616
+ /** Brand-check: is `value` a {@link defineAgent} result? */
617
+ declare function isAgentDefinition(value: unknown): value is AgentDefinition;
618
+ /**
619
+ * Lower a definition to the SDK-ready {@link CompiledAgentOptions} — the same shape
620
+ * `compileAgent` (decorator path) produces, so both surfaces converge on one runtime.
621
+ */
622
+ declare function compileAgentDefinition(def: AgentDefinition): CompiledAgentOptions;
623
+
516
624
  /**
517
625
  * SDK Adapter — bridges @theokit/agents decorators → @theokit/sdk runtime.
518
626
  *
@@ -597,6 +705,33 @@ interface RuntimeOverrides {
597
705
  declare function createSdkAgentStream(compiled: CompiledAgentOptions, compiledTools: CompiledTool[], apiKey: string, overrides?: RuntimeOverrides): (message: string, sessionId: string, factoryOpts?: {
598
706
  disableTools?: boolean;
599
707
  }) => AsyncIterable<StreamEvent>;
708
+ /**
709
+ * The minimal `SDKAgent` surface a serving host needs (ACP checks `agentId: string` + `send: fn`).
710
+ * `Agent.getOrCreate` returns the real SDK agent — this alias just types what {@link toAgentFactory}
711
+ * hands back without re-exporting the full `@theokit/sdk` `Agent` type.
712
+ */
713
+ interface SdkAgentHandle {
714
+ readonly agentId: string;
715
+ send: (msg: string, opts?: unknown) => unknown;
716
+ dispose: () => Promise<void>;
717
+ }
718
+ /**
719
+ * #12 — bridge a builder/`defineAgent` {@link TheokitAgentDefinition} to a real `SDKAgent` FACTORY,
720
+ * so surfaces that require an `SDKAgent` (or `(sessionId) => SDKAgent`) — notably `theokit acp`,
721
+ * whose entry default-export must be one — can serve an agent defined with the `agent()` chain.
722
+ *
723
+ * The factory reuses the SAME projection the streaming path uses (`compileAgentDefinition` → tools /
724
+ * model / `assembleM8CreateOptions`), so the served agent has identical tools, model, system prompt,
725
+ * skills, and `mcpServers`. Keyed per `sessionId` via `Agent.getOrCreate` (matches the run path).
726
+ *
727
+ * NOTE: HITL approvals (`.approval(...)`) are driven by the framework's streaming runner, not by
728
+ * `Agent.create`; a raw `SDKAgent` from this factory does not auto-pause gated tools — the serving
729
+ * surface (e.g. the ACP client) owns approval. Tools still execute; they are simply not HITL-gated here.
730
+ */
731
+ declare function toAgentFactory(def: AgentDefinition, opts: {
732
+ apiKey: string;
733
+ overrides?: RuntimeOverrides;
734
+ }): (sessionId: string) => Promise<SdkAgentHandle>;
600
735
 
601
736
  /**
602
737
  * Model-selection mapping (M1 reasoning-visibility) — the single site that turns a
@@ -685,108 +820,6 @@ declare function translateToUIMessageStream(events: AsyncIterable<AgentStreamEve
685
820
  textId: string;
686
821
  }): AsyncGenerator<UIMessageChunk, void, unknown>;
687
822
 
688
- /**
689
- * M2 (theokit-ai-first) — `defineAgent`, the zero-config imperative agent surface.
690
- *
691
- * ADR-B1: `defineAgent({...})` (default-exported from a top-level `agents/<name>.ts`) is
692
- * the canonical zero-config surface; the `@Agent` class decorator stays the advanced/DI
693
- * surface. Both compile to {@link CompiledAgentOptions} and run through the same SDK
694
- * runtime (`createSdkAgentStream`) — one runtime, two syntaxes.
695
- *
696
- * This module is PURE metadata (sdk-runtime.md / G2): `defineAgent` describes an agent, it
697
- * NEVER calls an LLM. It imports only `zod` (types) + the compiler shape — no `theokit`
698
- * core, preserving the agents → (nothing) dependency direction (G1).
699
- */
700
-
701
- /**
702
- * Brand tag for a `defineAgent` value. `Symbol.for` (global registry, not `Symbol()`) so
703
- * the brand survives duplicate module instances (dual-package / bundling) — the scanner's
704
- * brand-check then works regardless of which copy created the definition.
705
- */
706
- declare const AGENT_BRAND: unique symbol;
707
- /** Config accepted by {@link defineAgent}. */
708
- interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
709
- /** Zod schema for the request body — lifted into the typed client (M2, {@link InferAgentInput}). */
710
- input?: TInput;
711
- /** Model id (e.g. `claude-sonnet-4-6`). Falls back to the SDK default when omitted. */
712
- model?: string;
713
- /** Static system prompt. */
714
- system?: string;
715
- /** Extended-thinking effort (mirrors `@Agent({ reasoningEffort })`). */
716
- reasoningEffort?: ReasoningEffort;
717
- /**
718
- * Pre-built tools. Accepts the `@theokit/sdk` `CustomTool` that `defineAgentTool`
719
- * (theokit/server) and every `@theokit/sdk-tools` factory return (issue #81) — they are
720
- * normalized to the internal {@link CompiledTool} shape at compile time.
721
- */
722
- tools?: readonly CustomTool[];
723
- /**
724
- * M7 — run-context: an opaque, per-agent object forwarded to every tool handler's
725
- * `ctx.context` at run time (injected by the theokit adapter's tool wrapper). Set shared config
726
- * (e.g. `{ projectRoot }`) ONCE at the agent level instead of baking it into each tool
727
- * factory. Mirrors ai-sdk `experimental_context`, mastra `RuntimeContext`, and
728
- * openai-agents-js `RunContext`. Distinct from `@Agent`'s context-window `context`.
729
- */
730
- context?: Record<string, unknown>;
731
- /**
732
- * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).
733
- * Input guards run on the user message before the SDK runtime; a `block` fails the run fast.
734
- * Built-ins live in `@theokit/agents` (`promptInjectionDetector`, `piiDetector`, `costGuard`,
735
- * `unicodeNormalizer`, `outputModeration`).
736
- */
737
- guardrails?: readonly Guardrail[];
738
- /**
739
- * M14 — HITL approvals keyed by tool name. Each gated tool pauses the run and emits an
740
- * `approval_required` event until approved (reuses the same `compiled.hitl` wiring the `@Agent`
741
- * + `@HumanInTheLoop` path produces). A key that does not match a declared tool fails fast at
742
- * compile time.
743
- */
744
- approvals?: Record<string, HumanInTheLoopOptions>;
745
- /**
746
- * M13 — skills selection: a static list (compiled straight to the SDK `skills.enabled`) OR a
747
- * per-request resolver `(ctx) => string[]` (carried on `compiled.skillsResolver`, resolved by the
748
- * request path against the run-context). Absent ⇒ the SDK enables every discovered skill.
749
- */
750
- skills?: SkillsSelection;
751
- /**
752
- * theokit-file-based-config — opt into `.theokit/` file-based config (skills, subagents, hooks,
753
- * MCP, context, cron). The SDK discovers config from these roots under the app's `cwd`:
754
- * `"project"` = `<cwd>/.theokit/`, `"user"` = `~/.theokit/`. Absent ⇒ inline (code) config only.
755
- * SECURITY: enabling `"project"` enables shell-executing hooks from `.theokit/hooks.json` — this
756
- * is opt-in because `.theokit/` is the app's own repo (informed consent). The SDK owns discovery
757
- * + execution (G2 / ADR-0040); theokit only wires this into `Agent.create({ local.settingSources })`.
758
- */
759
- settingSources?: readonly SettingSource[];
760
- }
761
- /**
762
- * A branded agent definition — the value {@link defineAgent} returns.
763
- *
764
- * `TTools` (M8) is a phantom type parameter carrying the tool-name union: the `agent()` builder
765
- * threads its accumulated literal tool names here (`.build()` returns `AgentDefinition<TInput,
766
- * 'a' | 'b'>`), so the generated client (`.theokit/agents.d.ts`) can expose them via
767
- * {@link InferAgentToolNames}. `defineAgent` leaves it `string` (its tools array carries no literal
768
- * names). Never present at runtime.
769
- */
770
- type AgentDefinition<TInput extends z.ZodType = z.ZodType, TTools extends string = string> = DefineAgentConfig<TInput> & {
771
- readonly [AGENT_BRAND]: true;
772
- readonly __toolNames?: TTools;
773
- };
774
- /** Infer the request type of an agent definition from its `input` Zod schema. */
775
- type InferAgentInput<T> = T extends AgentDefinition<infer S> ? (S extends z.ZodType ? z.infer<S> : never) : never;
776
- /**
777
- * Infer the tool-name union of an agent definition (M8). Yields the literal union for agents built
778
- * with the `agent()` builder (`'read_file' | 'count_lines'`), or `string` for `defineAgent` agents
779
- * whose tools array carries no literal names.
780
- */
781
- type InferAgentToolNames<T> = T extends AgentDefinition<z.ZodType, infer N> ? N : never;
782
- /** Brand-check: is `value` a {@link defineAgent} result? */
783
- declare function isAgentDefinition(value: unknown): value is AgentDefinition;
784
- /**
785
- * Lower a definition to the SDK-ready {@link CompiledAgentOptions} — the same shape
786
- * `compileAgent` (decorator path) produces, so both surfaces converge on one runtime.
787
- */
788
- declare function compileAgentDefinition(def: AgentDefinition): CompiledAgentOptions;
789
-
790
823
  /**
791
824
  * M8 — `agent()`, the fluent agent builder with accumulative **type-state**.
792
825
  *
@@ -894,6 +927,13 @@ interface AgentBuilder<TInput extends z.ZodType | UnsetMarker = UnsetMarker, TMo
894
927
  * shell-executing hooks from `.theokit/hooks.json` — opt-in because `.theokit/` is your own repo.
895
928
  */
896
929
  settingSources(sources: readonly SettingSource[]): AgentBuilder<TInput, TModel, TContext, TTools>;
930
+ /**
931
+ * Declare MCP (Model Context Protocol) servers available to this agent — the builder-chain
932
+ * equivalent of the `@MCP` class decorator. Each key is a server name; the value is its config
933
+ * (`command` / `args` / `env` / `cwd`). Forwarded to `Agent.create({ mcpServers })`; the SDK owns
934
+ * MCP execution. Call once — a later call replaces the map.
935
+ */
936
+ mcp(servers: McpServersMap): AgentBuilder<TInput, TModel, TContext, TTools>;
897
937
  /**
898
938
  * Apply a reusable partial chain (Spring-Boot-style composition). `preset` receives the current
899
939
  * builder and returns an advanced one; its accumulated type-state flows through.
@@ -1656,4 +1696,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
1656
1696
  register(app: PluginApp): void;
1657
1697
  };
1658
1698
 
1659
- export { type McpRegistryConfig as $, type AgentManifestEntry as A, type BackgroundDelegation as B, type CompiledAgentOptions as C, type DelegationResult as D, type CheckpointSavedEvent as E, type CompiledContextWindow as F, type ContextualTool as G, DEFAULT_MAX_ITERATIONS as H, type DefineAgentConfig as I, type DelegateFn as J, type DelegateOptions as K, type LoopStrategy as L, DelegationError as M, type DoneEvent as N, type ErrorEvent as O, type FileEditEvent as P, type HitlDecision as Q, type ReflectionStrategy as R, type StreamEvent as S, type InferAgentInput as T, type InferAgentToolNames as U, type IterationEvent as V, type LLMCallContext as W, type LoopFinishReason as X, type LoopOutcome as Y, type LoopStrategyConfig as Z, type McpApprovalSpec as _, type CompiledTool as a, resolveEnabledSkills as a$, type McpRequestContext as a0, type McpSelection as a1, type PartialToolCallEvent as a2, type ProcessInputContext as a3, type ReflectionContext as a4, type ReflectionResult as a5, type ReflectionStrategyConfig as a6, type RunStartedEvent as a7, type ScoreVerdict as a8, type ScoredDelegation as a9, createAgentExecutionContext as aA, createApiErrorHandler as aB, createSdkAgentStream as aC, createThinkTagExtractor as aD, createToolHooksPlugin as aE, delegate as aF, delegateBackground as aG, delegateWithScoring as aH, extractThinkTagStream as aI, generateAgentManifest as aJ, generateAgentRoutes as aK, isAgentContext as aL, isAgentDefinition as aM, isApprovalRequired as aN, isDone as aO, isError as aP, isPartialToolCall as aQ, isTextDelta as aR, isToolCall as aS, isToolResult as aT, ladderReflectionStrategy as aU, loopStrategyConfigSchema as aV, mcpRegistry as aW, mcpToolApprovals as aX, noopReflectionStrategy as aY, projectContextMetadataOnlyKnobs as aZ, reflectionStrategyConfigSchema as a_, type Scorer as aa, type SdkMessage as ab, type Segment as ac, type SkillsRequestContext as ad, type SkillsSelection as ae, type StateUpdateEvent as af, type TextDeltaEvent as ag, type ThinkingEvent as ah, type ToolCallEvent as ai, type ToolCallVeto as aj, type ToolHooks as ak, type ToolHooksPlugin as al, type ToolResultEvent as am, type ToolWalkResult as an, type ToolboxWalkResult as ao, agent as ap, agentsPlugin as aq, buildModelSelection as ar, compileAgent as as, compileAgentDefinition as at, compileAgentModule as au, compileContextWindow as av, compileProjectContext as aw, compileSkills as ax, compileTools as ay, contextualTool as az, type RoundStreamFactory as b, resolveLoopStrategy as b0, resolveMcpServers as b1, runWithApiErrorHandling as b2, streamAgentResponse as b3, streamAgentUIMessages as b4, translateSdkEvent as b5, translateToUIMessageStream as b6, validateUniqueRoutes as b7, walkAgentMetadata as b8, AGENT_BRAND as c, type AfterToolCallContext as d, type AgentBuilder as e, type AgentDefinition as f, AgentDefinitionError as g, type AgentExecutionContext as h, type AgentManifest as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentStreamEvent as n, type AgentTurnMetadata as o, type AgentWalkResult as p, AgentWarningCode as q, type AgentsPluginOptions as r, type ApiErrorContext as s, type ApiErrorDecision as t, type ApiErrorPolicy as u, type ApprovalRequiredEvent as v, type ArtifactChunkEvent as w, type ArtifactStartEvent as x, type BeforeToolCallContext as y, BudgetExceededError as z };
1699
+ export { type McpRegistryConfig as $, type AgentManifestEntry as A, type BackgroundDelegation as B, type CompiledAgentOptions as C, type DelegationResult as D, type CheckpointSavedEvent as E, type CompiledContextWindow as F, type ContextualTool as G, DEFAULT_MAX_ITERATIONS as H, type DefineAgentConfig as I, type DelegateFn as J, type DelegateOptions as K, type LoopStrategy as L, DelegationError as M, type DoneEvent as N, type ErrorEvent as O, type FileEditEvent as P, type HitlDecision as Q, type ReflectionStrategy as R, type StreamEvent as S, type InferAgentInput as T, type InferAgentToolNames as U, type IterationEvent as V, type LLMCallContext as W, type LoopFinishReason as X, type LoopOutcome as Y, type LoopStrategyConfig as Z, type McpApprovalSpec as _, type CompiledTool as a, reflectionStrategyConfigSchema as a$, type McpRequestContext as a0, type McpSelection as a1, type PartialToolCallEvent as a2, type ProcessInputContext as a3, type ReflectionContext as a4, type ReflectionResult as a5, type ReflectionStrategyConfig as a6, type RunStartedEvent as a7, type ScoreVerdict as a8, type ScoredDelegation as a9, contextualTool as aA, createAgentExecutionContext as aB, createApiErrorHandler as aC, createSdkAgentStream as aD, createThinkTagExtractor as aE, createToolHooksPlugin as aF, delegate as aG, delegateBackground as aH, delegateWithScoring as aI, extractThinkTagStream as aJ, generateAgentManifest as aK, generateAgentRoutes as aL, isAgentContext as aM, isAgentDefinition as aN, isApprovalRequired as aO, isDone as aP, isError as aQ, isPartialToolCall as aR, isTextDelta as aS, isToolCall as aT, isToolResult as aU, ladderReflectionStrategy as aV, loopStrategyConfigSchema as aW, mcpRegistry as aX, mcpToolApprovals as aY, noopReflectionStrategy as aZ, projectContextMetadataOnlyKnobs as a_, type Scorer as aa, type SdkAgentHandle as ab, type SdkMessage as ac, type Segment as ad, type SkillsRequestContext as ae, type SkillsSelection as af, type StateUpdateEvent as ag, type TextDeltaEvent as ah, type ThinkingEvent as ai, type ToolCallEvent as aj, type ToolCallVeto as ak, type ToolHooks as al, type ToolHooksPlugin as am, type ToolResultEvent as an, type ToolWalkResult as ao, type ToolboxWalkResult as ap, agent as aq, agentsPlugin as ar, buildModelSelection as as, compileAgent as at, compileAgentDefinition as au, compileAgentModule as av, compileContextWindow as aw, compileProjectContext as ax, compileSkills as ay, compileTools as az, type RoundStreamFactory as b, resolveEnabledSkills as b0, resolveLoopStrategy as b1, resolveMcpServers as b2, runWithApiErrorHandling as b3, streamAgentResponse as b4, streamAgentUIMessages as b5, toAgentFactory as b6, translateSdkEvent as b7, translateToUIMessageStream as b8, validateUniqueRoutes as b9, walkAgentMetadata as ba, AGENT_BRAND as c, type AfterToolCallContext as d, type AgentBuilder as e, type AgentDefinition as f, AgentDefinitionError as g, type AgentExecutionContext as h, type AgentManifest as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentStreamEvent as n, type AgentTurnMetadata as o, type AgentWalkResult as p, AgentWarningCode as q, type AgentsPluginOptions as r, type ApiErrorContext as s, type ApiErrorDecision as t, type ApiErrorPolicy as u, type ApprovalRequiredEvent as v, type ArtifactChunkEvent as w, type ArtifactStartEvent as x, type BeforeToolCallContext as y, BudgetExceededError as z };
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, A as AgentManifestEntry, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentWalkResult, q as AgentWarningCode, r as AgentsPluginOptions, s as ApiErrorContext, t as ApiErrorDecision, u as ApiErrorPolicy, v as ApprovalRequiredEvent, w as ArtifactChunkEvent, x as ArtifactStartEvent, B as BackgroundDelegation, y as BeforeToolCallContext, z as BudgetExceededError, E as CheckpointSavedEvent, C as CompiledAgentOptions, F as CompiledContextWindow, a as CompiledTool, G as ContextualTool, I as DefineAgentConfig, J as DelegateFn, K as DelegateOptions, M as DelegationError, D as DelegationResult, N as DoneEvent, O as ErrorEvent, P as FileEditEvent, T as InferAgentInput, U as InferAgentToolNames, V as IterationEvent, W as LLMCallContext, _ as McpApprovalSpec, $ as McpRegistryConfig, a0 as McpRequestContext, a1 as McpSelection, a2 as PartialToolCallEvent, a3 as ProcessInputContext, a7 as RunStartedEvent, a8 as ScoreVerdict, a9 as ScoredDelegation, aa as Scorer, ab as SdkMessage, ac as Segment, af as StateUpdateEvent, S as StreamEvent, ag as TextDeltaEvent, ah as ThinkingEvent, ai as ToolCallEvent, aj as ToolCallVeto, ak as ToolHooks, al as ToolHooksPlugin, am as ToolResultEvent, an as ToolWalkResult, ao as ToolboxWalkResult, ap as agent, aq as agentsPlugin, ar as buildModelSelection, as as compileAgent, at as compileAgentDefinition, au as compileAgentModule, av as compileContextWindow, aw as compileProjectContext, ax as compileSkills, ay as compileTools, az as contextualTool, aA as createAgentExecutionContext, aB as createApiErrorHandler, aC as createSdkAgentStream, aD as createThinkTagExtractor, aE as createToolHooksPlugin, aF as delegate, aG as delegateBackground, aH as delegateWithScoring, aI as extractThinkTagStream, aJ as generateAgentManifest, aK as generateAgentRoutes, aL as isAgentContext, aM as isAgentDefinition, aN as isApprovalRequired, aO as isDone, aP as isError, aQ as isPartialToolCall, aR as isTextDelta, aS as isToolCall, aT as isToolResult, aW as mcpRegistry, aX as mcpToolApprovals, aZ as projectContextMetadataOnlyKnobs, b1 as resolveMcpServers, b2 as runWithApiErrorHandling, b3 as streamAgentResponse, b4 as streamAgentUIMessages, b5 as translateSdkEvent, b6 as translateToUIMessageStream, b7 as validateUniqueRoutes, b8 as walkAgentMetadata } from './bridge-entry-Bo3LsMQF.js';
1
+ export { c as AGENT_BRAND, d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinition, g as AgentDefinitionError, h as AgentExecutionContext, i as AgentManifest, A as AgentManifestEntry, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentWalkResult, q as AgentWarningCode, r as AgentsPluginOptions, s as ApiErrorContext, t as ApiErrorDecision, u as ApiErrorPolicy, v as ApprovalRequiredEvent, w as ArtifactChunkEvent, x as ArtifactStartEvent, B as BackgroundDelegation, y as BeforeToolCallContext, z as BudgetExceededError, E as CheckpointSavedEvent, C as CompiledAgentOptions, F as CompiledContextWindow, a as CompiledTool, G as ContextualTool, I as DefineAgentConfig, J as DelegateFn, K as DelegateOptions, M as DelegationError, D as DelegationResult, N as DoneEvent, O as ErrorEvent, P as FileEditEvent, T as InferAgentInput, U as InferAgentToolNames, V as IterationEvent, W as LLMCallContext, _ as McpApprovalSpec, $ as McpRegistryConfig, a0 as McpRequestContext, a1 as McpSelection, a2 as PartialToolCallEvent, a3 as ProcessInputContext, a7 as RunStartedEvent, a8 as ScoreVerdict, a9 as ScoredDelegation, aa as Scorer, ab as SdkAgentHandle, ac as SdkMessage, ad as Segment, ag as StateUpdateEvent, S as StreamEvent, ah as TextDeltaEvent, ai as ThinkingEvent, aj as ToolCallEvent, ak as ToolCallVeto, al as ToolHooks, am as ToolHooksPlugin, an as ToolResultEvent, ao as ToolWalkResult, ap as ToolboxWalkResult, aq as agent, ar as agentsPlugin, as as buildModelSelection, at as compileAgent, au as compileAgentDefinition, av as compileAgentModule, aw as compileContextWindow, ax as compileProjectContext, ay as compileSkills, az as compileTools, aA as contextualTool, aB as createAgentExecutionContext, aC as createApiErrorHandler, aD as createSdkAgentStream, aE as createThinkTagExtractor, aF as createToolHooksPlugin, aG as delegate, aH as delegateBackground, aI as delegateWithScoring, aJ as extractThinkTagStream, aK as generateAgentManifest, aL as generateAgentRoutes, aM as isAgentContext, aN as isAgentDefinition, aO as isApprovalRequired, aP as isDone, aQ as isError, aR as isPartialToolCall, aS as isTextDelta, aT as isToolCall, aU as isToolResult, aX as mcpRegistry, aY as mcpToolApprovals, a_ as projectContextMetadataOnlyKnobs, b2 as resolveMcpServers, b3 as runWithApiErrorHandling, b4 as streamAgentResponse, b5 as streamAgentUIMessages, b6 as toAgentFactory, b7 as translateSdkEvent, b8 as translateToUIMessageStream, b9 as validateUniqueRoutes, ba as walkAgentMetadata } from './bridge-entry-BW1ifbWg.js';
2
2
  import '@theokit/http';
3
3
  import './types-DVA4LQsA.js';
4
4
  import '@theokit/sdk';
package/dist/bridge.js CHANGED
@@ -42,11 +42,12 @@ import {
42
42
  runWithApiErrorHandling,
43
43
  streamAgentResponse,
44
44
  streamAgentUIMessages,
45
+ toAgentFactory,
45
46
  translateSdkEvent,
46
47
  translateToUIMessageStream,
47
48
  validateUniqueRoutes,
48
49
  walkAgentMetadata
49
- } from "./chunk-5VK63XGX.js";
50
+ } from "./chunk-6WOLHCZB.js";
50
51
  import "./chunk-NERDIS45.js";
51
52
  import "./chunk-7QVYU63E.js";
52
53
  export {
@@ -93,6 +94,7 @@ export {
93
94
  runWithApiErrorHandling,
94
95
  streamAgentResponse,
95
96
  streamAgentUIMessages,
97
+ toAgentFactory,
96
98
  translateSdkEvent,
97
99
  translateToUIMessageStream,
98
100
  validateUniqueRoutes,
@@ -506,6 +506,107 @@ function generateAgentRoutes(ctx) {
506
506
  }
507
507
  __name(generateAgentRoutes, "generateAgentRoutes");
508
508
 
509
+ // src/bridge/define-agent.ts
510
+ var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
511
+ function defineAgent(config) {
512
+ return {
513
+ ...config,
514
+ [AGENT_BRAND]: true
515
+ };
516
+ }
517
+ __name(defineAgent, "defineAgent");
518
+ function isAgentDefinition(value) {
519
+ return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
520
+ }
521
+ __name(isAgentDefinition, "isAgentDefinition");
522
+ function toCompiledTool(tool) {
523
+ const handler = tool.handler;
524
+ const compiled = {
525
+ name: tool.name,
526
+ description: tool.description,
527
+ inputSchema: tool.inputSchema,
528
+ handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
529
+ };
530
+ for (const sym of Object.getOwnPropertySymbols(tool)) {
531
+ ;
532
+ compiled[sym] = tool[sym];
533
+ }
534
+ return compiled;
535
+ }
536
+ __name(toCompiledTool, "toCompiledTool");
537
+ function compileAgentDefinition(def) {
538
+ return {
539
+ model: def.model,
540
+ reasoningEffort: def.reasoningEffort,
541
+ systemPrompt: def.system,
542
+ tools: (def.tools ?? []).map(toCompiledTool),
543
+ agents: {},
544
+ stream: true,
545
+ // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
546
+ // context-window `context` field the decorator path uses); absent ⇒ no key.
547
+ ...def.context !== void 0 ? {
548
+ runContext: def.context
549
+ } : {},
550
+ // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
551
+ ...def.guardrails !== void 0 ? {
552
+ guardrails: def.guardrails
553
+ } : {},
554
+ // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
555
+ ...def.approvals !== void 0 ? {
556
+ hitl: compileApprovals(def)
557
+ } : {},
558
+ // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
559
+ ...compileSkillsSelection(def.skills),
560
+ // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
561
+ // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
562
+ ...def.settingSources !== void 0 ? {
563
+ settingSources: def.settingSources
564
+ } : {},
565
+ // MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`
566
+ // decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.
567
+ ...def.mcpServers !== void 0 ? {
568
+ mcpServers: def.mcpServers
569
+ } : {}
570
+ };
571
+ }
572
+ __name(compileAgentDefinition, "compileAgentDefinition");
573
+ function compileSkillsSelection(skills) {
574
+ if (skills === void 0) return {};
575
+ if (typeof skills === "function") return {
576
+ skillsResolver: skills
577
+ };
578
+ const enabled = [];
579
+ const inline = [];
580
+ for (const entry of skills) {
581
+ if (typeof entry === "string") enabled.push(entry);
582
+ else inline.push(entry);
583
+ }
584
+ return {
585
+ skills: {
586
+ enabled,
587
+ autoInject: true,
588
+ ...inline.length > 0 ? {
589
+ inline
590
+ } : {}
591
+ }
592
+ };
593
+ }
594
+ __name(compileSkillsSelection, "compileSkillsSelection");
595
+ function compileApprovals(def) {
596
+ const toolNames = new Set((def.tools ?? []).map((t) => t.name));
597
+ const gates = /* @__PURE__ */ new Map();
598
+ for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
599
+ if (!toolNames.has(toolName)) {
600
+ throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
601
+ ...toolNames
602
+ ].join(", ") || "(none)"}.`);
603
+ }
604
+ gates.set(toolName, options);
605
+ }
606
+ return gates;
607
+ }
608
+ __name(compileApprovals, "compileApprovals");
609
+
509
610
  // src/bridge/event-translator.ts
510
611
  function asString(value, fallback) {
511
612
  if (typeof value === "string") return value;
@@ -1301,6 +1402,43 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
1301
1402
  }
1302
1403
  }
1303
1404
  __name(streamSdkAgent, "streamSdkAgent");
1405
+ function toAgentFactory(def, opts) {
1406
+ const compiled = compileAgentDefinition(def);
1407
+ const overrides = opts.overrides ?? {};
1408
+ const model = overrides.model ?? compiled.model ?? "openai/gpt-4o-mini";
1409
+ const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort;
1410
+ const runContext = overrides.runContext ?? compiled.runContext;
1411
+ return async (sessionId) => {
1412
+ const rt = await loadSdkRuntime();
1413
+ if (!rt) {
1414
+ throw new Error("[@theokit/agents] @theokit/sdk is not installed \u2014 run: pnpm add @theokit/sdk");
1415
+ }
1416
+ const sdkTools = buildSdkTools(compiled.tools, rt.defineTool, overrides.sdkTools, runContext);
1417
+ const inlineSkills = compiled.skills?.inline;
1418
+ if (inlineSkills !== void 0 && inlineSkills.length > 0 && rt.defineSkillReadTool !== void 0 && !compiled.tools.some((t) => t.name === "skill_read")) {
1419
+ sdkTools.push(rt.defineSkillReadTool(inlineSkills));
1420
+ }
1421
+ const { options: m8 } = assembleM8CreateOptions(compiled);
1422
+ if (overrides.cwd !== void 0) m8.local = {
1423
+ ...m8.local,
1424
+ cwd: overrides.cwd
1425
+ };
1426
+ if (overrides.baseDir !== void 0) m8.local = {
1427
+ ...m8.local,
1428
+ baseDir: overrides.baseDir
1429
+ };
1430
+ const extra = buildExtraCreateOptions(overrides, compiled);
1431
+ const agent2 = await rt.Agent.getOrCreate(sessionId, {
1432
+ apiKey: opts.apiKey,
1433
+ model: buildModelSelection(model, reasoningEffort),
1434
+ tools: sdkTools,
1435
+ ...m8,
1436
+ ...extra
1437
+ });
1438
+ return agent2;
1439
+ };
1440
+ }
1441
+ __name(toAgentFactory, "toAgentFactory");
1304
1442
 
1305
1443
  // src/bridge/ui-message-stream-translator.ts
1306
1444
  function* closeOpenBlock(state, textId) {
@@ -1487,97 +1625,6 @@ function doneToMetadata(event) {
1487
1625
  }
1488
1626
  __name(doneToMetadata, "doneToMetadata");
1489
1627
 
1490
- // src/bridge/define-agent.ts
1491
- var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
1492
- function defineAgent(config) {
1493
- return {
1494
- ...config,
1495
- [AGENT_BRAND]: true
1496
- };
1497
- }
1498
- __name(defineAgent, "defineAgent");
1499
- function isAgentDefinition(value) {
1500
- return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
1501
- }
1502
- __name(isAgentDefinition, "isAgentDefinition");
1503
- function toCompiledTool(tool) {
1504
- const handler = tool.handler;
1505
- return {
1506
- name: tool.name,
1507
- description: tool.description,
1508
- inputSchema: tool.inputSchema,
1509
- handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
1510
- };
1511
- }
1512
- __name(toCompiledTool, "toCompiledTool");
1513
- function compileAgentDefinition(def) {
1514
- return {
1515
- model: def.model,
1516
- reasoningEffort: def.reasoningEffort,
1517
- systemPrompt: def.system,
1518
- tools: (def.tools ?? []).map(toCompiledTool),
1519
- agents: {},
1520
- stream: true,
1521
- // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
1522
- // context-window `context` field the decorator path uses); absent ⇒ no key.
1523
- ...def.context !== void 0 ? {
1524
- runContext: def.context
1525
- } : {},
1526
- // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
1527
- ...def.guardrails !== void 0 ? {
1528
- guardrails: def.guardrails
1529
- } : {},
1530
- // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
1531
- ...def.approvals !== void 0 ? {
1532
- hitl: compileApprovals(def)
1533
- } : {},
1534
- // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
1535
- ...compileSkillsSelection(def.skills),
1536
- // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
1537
- // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
1538
- ...def.settingSources !== void 0 ? {
1539
- settingSources: def.settingSources
1540
- } : {}
1541
- };
1542
- }
1543
- __name(compileAgentDefinition, "compileAgentDefinition");
1544
- function compileSkillsSelection(skills) {
1545
- if (skills === void 0) return {};
1546
- if (typeof skills === "function") return {
1547
- skillsResolver: skills
1548
- };
1549
- const enabled = [];
1550
- const inline = [];
1551
- for (const entry of skills) {
1552
- if (typeof entry === "string") enabled.push(entry);
1553
- else inline.push(entry);
1554
- }
1555
- return {
1556
- skills: {
1557
- enabled,
1558
- autoInject: true,
1559
- ...inline.length > 0 ? {
1560
- inline
1561
- } : {}
1562
- }
1563
- };
1564
- }
1565
- __name(compileSkillsSelection, "compileSkillsSelection");
1566
- function compileApprovals(def) {
1567
- const toolNames = new Set((def.tools ?? []).map((t) => t.name));
1568
- const gates = /* @__PURE__ */ new Map();
1569
- for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
1570
- if (!toolNames.has(toolName)) {
1571
- throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
1572
- ...toolNames
1573
- ].join(", ") || "(none)"}.`);
1574
- }
1575
- gates.set(toolName, options);
1576
- }
1577
- return gates;
1578
- }
1579
- __name(compileApprovals, "compileApprovals");
1580
-
1581
1628
  // src/bridge/agent-builder.ts
1582
1629
  function contextualTool(tool, _requiredContext) {
1583
1630
  return tool;
@@ -1642,6 +1689,10 @@ function makeBuilder(config) {
1642
1689
  ...config,
1643
1690
  settingSources: sources
1644
1691
  }), "settingSources"),
1692
+ mcp: /* @__PURE__ */ __name((servers) => makeBuilder({
1693
+ ...config,
1694
+ mcpServers: servers
1695
+ }), "mcp"),
1645
1696
  use: /* @__PURE__ */ __name((preset) => preset(runtime), "use"),
1646
1697
  build: /* @__PURE__ */ __name(() => defineAgent(config), "build")
1647
1698
  };
@@ -2966,15 +3017,16 @@ export {
2966
3017
  isError,
2967
3018
  isApprovalRequired,
2968
3019
  generateAgentRoutes,
3020
+ AGENT_BRAND,
3021
+ isAgentDefinition,
3022
+ compileAgentDefinition,
2969
3023
  translateSdkEvent,
2970
3024
  buildModelSelection,
2971
3025
  createThinkTagExtractor,
2972
3026
  extractThinkTagStream,
2973
3027
  createSdkAgentStream,
3028
+ toAgentFactory,
2974
3029
  translateToUIMessageStream,
2975
- AGENT_BRAND,
2976
- isAgentDefinition,
2977
- compileAgentDefinition,
2978
3030
  contextualTool,
2979
3031
  agent,
2980
3032
  AgentDefinitionError,
@@ -3017,4 +3069,4 @@ export {
3017
3069
  generateAgentManifest,
3018
3070
  agentsPlugin
3019
3071
  };
3020
- //# sourceMappingURL=chunk-5VK63XGX.js.map
3072
+ //# sourceMappingURL=chunk-6WOLHCZB.js.map