@theokit/agents 15.1.1 → 16.1.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +48 -1
  3. package/dist/a2a.d.ts +37 -0
  4. package/dist/a2a.js +90 -0
  5. package/dist/a2a.js.map +1 -0
  6. package/dist/{agent-compiler-DMQcLHIs.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  7. package/dist/agent-orchestrator-BFWg2URC.d.ts +449 -0
  8. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  9. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  10. package/dist/{bridge-entry-CDFRjtbb.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  11. package/dist/bridge.d.ts +8 -5
  12. package/dist/bridge.js +21 -15
  13. package/dist/{chunk-RAN4PBUL.js → chunk-3TE4PJZL.js} +569 -1526
  14. package/dist/chunk-3TE4PJZL.js.map +1 -0
  15. package/dist/{chunk-ULC47RCQ.js → chunk-4SXVNI5O.js} +7 -7
  16. package/dist/{chunk-ULC47RCQ.js.map → chunk-4SXVNI5O.js.map} +1 -1
  17. package/dist/chunk-A2UVVEB3.js +799 -0
  18. package/dist/chunk-A2UVVEB3.js.map +1 -0
  19. package/dist/chunk-FBCT4B2L.js +86 -0
  20. package/dist/chunk-FBCT4B2L.js.map +1 -0
  21. package/dist/{chunk-DZH5F4PP.js → chunk-KXE52FP2.js} +12 -67
  22. package/dist/chunk-KXE52FP2.js.map +1 -0
  23. package/dist/chunk-Z5SYU6Z6.js +353 -0
  24. package/dist/chunk-Z5SYU6Z6.js.map +1 -0
  25. package/dist/client-react.js +2 -1
  26. package/dist/client-react.js.map +1 -1
  27. package/dist/client.d.ts +12 -2
  28. package/dist/client.js +5 -3
  29. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  30. package/dist/evals.d.ts +84 -0
  31. package/dist/evals.js +191 -0
  32. package/dist/evals.js.map +1 -0
  33. package/dist/handoff.d.ts +91 -0
  34. package/dist/handoff.js +268 -0
  35. package/dist/handoff.js.map +1 -0
  36. package/dist/index.d.ts +61 -401
  37. package/dist/index.js +142 -111
  38. package/dist/index.js.map +1 -1
  39. package/dist/mcp-health.d.ts +1 -1
  40. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  41. package/dist/testing.d.ts +2 -2
  42. package/dist/tools.d.ts +5 -3
  43. package/dist/tools.js +10 -6
  44. package/dist/tools.js.map +1 -1
  45. package/dist/{types-CxI2x6mU.d.ts → types-D5cHmSLi.d.ts} +10 -4
  46. package/docs/capability-map.md +44 -5
  47. package/package.json +16 -2
  48. package/dist/chunk-DZH5F4PP.js.map +0 -1
  49. package/dist/chunk-RAN4PBUL.js.map +0 -1
  50. package/dist/delegation-scoring-CSe_C-iX.d.ts +0 -809
@@ -1,16 +1,12 @@
1
- import {
2
- hooksPlugin,
3
- inheritHooks
4
- } from "./chunk-MJ6FRILJ.js";
5
- import {
6
- compileAgentDefinition
7
- } from "./chunk-NIQJ4GZX.js";
8
1
  import {
9
2
  debugLog
10
3
  } from "./chunk-M5J3Q6YC.js";
11
4
  import {
12
5
  ConfigurationError
13
6
  } from "./chunk-Q65ZIFNK.js";
7
+ import {
8
+ compileAgentDefinition
9
+ } from "./chunk-NIQJ4GZX.js";
14
10
  import {
15
11
  createRunUsageMeter
16
12
  } from "./chunk-OXNDJSAJ.js";
@@ -574,144 +570,423 @@ function reasoningEffortOf(model) {
574
570
  }
575
571
  __name(reasoningEffortOf, "reasoningEffortOf");
576
572
 
577
- // src/bridge/sdk-adapter-create-options.ts
578
- import { createRequire } from "module";
579
- import { PermissionEngine, PermissionPlugin } from "@theokit/sdk";
580
- import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
581
-
582
- // src/bridge/code-plugins.ts
583
- var CAPABILITY_KEYS = [
584
- "register",
585
- "profile",
586
- "createProvider"
587
- ];
588
- var BUNDLE_KEYS = [
589
- "path",
590
- "type",
591
- "source",
592
- "marketplace"
593
- ];
594
- function assertCodePlugins(list) {
595
- for (const entry of list) {
596
- if (isCodePlugin(entry)) continue;
597
- const looksLikeBundle = typeof entry === "object" && entry !== null && BUNDLE_KEYS.some((k) => k in entry);
598
- throw new ConfigurationError(looksLikeBundle ? "plugins() takes CODE plugins \u2014 { name, register } objects registered with the runtime's lifecycle seam. The entry given describes a filesystem bundle, which is not declared here: put the bundle in a `plugins/` directory under `.theokit/` or `.claude/`, where its `skills/` and `agents/` are discovered. Note that the manifest (`.claude-plugin/plugin.json`), marketplaces, hooks, MCP servers, output styles and LSP servers are NOT read from a bundle by this runtime." : `plugins() takes { name, register } objects; received ${describe(entry)}.`, {
599
- code: "plugins_expects_code_objects"
600
- });
601
- }
573
+ // src/bridge/event-translator.ts
574
+ function asString(value, fallback) {
575
+ if (typeof value === "string") return value;
576
+ return fallback;
602
577
  }
603
- __name(assertCodePlugins, "assertCodePlugins");
604
- function describe(entry) {
605
- return entry === null ? "null" : typeof entry;
578
+ __name(asString, "asString");
579
+ function toolResultExitCode(value) {
580
+ if (typeof value !== "object" || value === null) return void 0;
581
+ const code = value.exitCode;
582
+ return typeof code === "number" ? code : void 0;
606
583
  }
607
- __name(describe, "describe");
608
- function isCodePlugin(entry) {
609
- if (typeof entry !== "object" || entry === null) return false;
610
- const candidate = entry;
611
- if (typeof candidate.name !== "string") return false;
612
- return CAPABILITY_KEYS.some((key) => candidate[key] !== void 0);
584
+ __name(toolResultExitCode, "toolResultExitCode");
585
+ function reportsToolFailure(result) {
586
+ return (toolResultExitCode(result) ?? 0) !== 0;
613
587
  }
614
- __name(isCodePlugin, "isCodePlugin");
615
-
616
- // src/bridge/sdk-adapter-create-options.ts
617
- var HOOK_GATE_SINCE = {
618
- major: 5,
619
- minor: 4
620
- };
621
- var COMPAT_IMPORT_SINCE = {
622
- major: 5,
623
- minor: 4
624
- };
625
- var COMPAT_ROOT_SINCE_MAJOR = 5;
626
- var HookGateUnsupportedError = class extends TheokitAgentError2 {
627
- static {
628
- __name(this, "HookGateUnsupportedError");
629
- }
630
- name = "HookGateUnsupportedError";
631
- constructor(version) {
632
- super(`a hook approval gate was declared, but the installed @theokit/sdk (${version ?? "version unreadable"}) cannot honour it: \`local.hooks\` landed in ${String(HOOK_GATE_SINCE.major)}.${String(HOOK_GATE_SINCE.minor)}.0. Forwarding it anyway would leave every hook spawning unreviewed while the gate reports as installed. Upgrade @theokit/sdk, or remove \`hookApproval\` and keep whatever refusal you have today (usetheokit/theokit#686).`, {
633
- code: "hook_gate_unsupported",
634
- isRetryable: false
635
- });
636
- }
637
- };
638
- var CompatRootUnsupportedError = class CompatRootUnsupportedError2 extends TheokitAgentError2 {
639
- static {
640
- __name(this, "CompatRootUnsupportedError");
588
+ __name(reportsToolFailure, "reportsToolFailure");
589
+ function serializeToolOutput(value, fallback) {
590
+ if (typeof value === "string") return value;
591
+ if (value === void 0 || value === null) return fallback;
592
+ try {
593
+ return JSON.stringify(value);
594
+ } catch {
595
+ return typeof value === "bigint" ? value.toString() : fallback;
641
596
  }
642
- name = "CompatRootUnsupportedError";
643
- constructor(version) {
644
- super(`\`compatSources\` asks for a foreign configuration root to be read, but the installed @theokit/sdk (${version ?? "version unreadable"}) does not know that option and drops it in silence \u2014 so EVERY foreign surface would be unavailable while the package resolves, compiles and runs. It landed in ${String(COMPAT_ROOT_SINCE_MAJOR)}.0.0, and this package declares a floor above it, so reaching this error means an override pinned the SDK lower. Remove the override, or drop \`compatSources\` if the foreign root is not wanted (usetheokit/theokit#739).`);
597
+ }
598
+ __name(serializeToolOutput, "serializeToolOutput");
599
+ function translateSystemEvent(msg, runId) {
600
+ return [
601
+ {
602
+ type: "run_started",
603
+ runId,
604
+ agentName: asString(msg.agent_id, "agent"),
605
+ model: asString(msg.model, "unknown")
606
+ }
607
+ ];
608
+ }
609
+ __name(translateSystemEvent, "translateSystemEvent");
610
+ function translateAssistantEvent(msg) {
611
+ const events = [];
612
+ const message = msg.message;
613
+ const content = message?.content;
614
+ if (!Array.isArray(content)) return events;
615
+ for (const block of content) {
616
+ const b = block;
617
+ if (b.type === "text" && b.text) {
618
+ events.push({
619
+ type: "text_delta",
620
+ content: b.text
621
+ });
622
+ }
623
+ if (b.type === "tool_use") {
624
+ events.push({
625
+ type: "tool_call",
626
+ // #138 — this was `tc-${Date.now()}`. A fresh id on every call is NEVER in the dedup set, so
627
+ // the fallback defeated dedup by construction — and still looked like a real id to a reader.
628
+ // An empty string is honest: `isDuplicatedByDelta` treats it as "I cannot identify this" and
629
+ // prefers a visible double render to a silent suppression.
630
+ callId: b.id ?? "",
631
+ toolName: b.name ?? "unknown",
632
+ input: b.input ?? {}
633
+ });
634
+ }
645
635
  }
646
- };
647
- var CompatImportUnsupportedError = class extends TheokitAgentError2 {
648
- static {
649
- __name(this, "CompatImportUnsupportedError");
636
+ return events;
637
+ }
638
+ __name(translateAssistantEvent, "translateAssistantEvent");
639
+ function translateToolCallEvent(msg) {
640
+ const status = msg.status;
641
+ const callId = asString(msg.call_id, "");
642
+ const toolName = asString(msg.name, "unknown");
643
+ if (status === "completed") {
644
+ return [
645
+ {
646
+ type: "tool_result",
647
+ callId,
648
+ toolName,
649
+ output: serializeToolOutput(msg.result, ""),
650
+ durationMs: 0,
651
+ // #388 — `completed` is the SDK's word for "the call is over", not for "the call worked".
652
+ // The exit code is the part that says which, and it was being thrown away here.
653
+ isError: reportsToolFailure(msg.result)
654
+ }
655
+ ];
650
656
  }
651
- name = "CompatImportUnsupportedError";
652
- constructor(version) {
653
- super(`\`claudeCode.import\` narrows WHICH surfaces of a foreign configuration root to read, but the installed @theokit/sdk (${version ?? "version unreadable"}) cannot honour it: the narrowed shape landed in ${String(COMPAT_IMPORT_SINCE.major)}.${String(COMPAT_IMPORT_SINCE.minor)}.0. An older runtime drops the unrecognised shape in silence, so the root would not be read AT ALL \u2014 less than you asked for, not more. Upgrade @theokit/sdk, or omit \`import\` to read every surface of the root (usetheokit/theokit#686).`, {
654
- code: "compat_import_unsupported",
655
- isRetryable: false
656
- });
657
+ if (status === "error") {
658
+ return [
659
+ {
660
+ type: "tool_result",
661
+ callId,
662
+ toolName,
663
+ output: serializeToolOutput(msg.result, "Tool failed"),
664
+ durationMs: 0,
665
+ isError: true
666
+ }
667
+ ];
657
668
  }
658
- };
659
- function compatSourcesForSdk(sources) {
660
- const out = [];
661
- for (const source of sources) {
662
- if (typeof source === "string") {
663
- out.push(source);
664
- continue;
665
- }
666
- const forSdk = source.import.filter((surface) => surface !== "commands");
667
- if (forSdk.length > 0) out.push({
668
- kind: source.kind,
669
- import: forSdk
670
- });
669
+ if (status === "running") {
670
+ return [
671
+ {
672
+ type: "tool_call",
673
+ callId,
674
+ toolName,
675
+ input: msg.args ?? msg.input ?? msg.arguments ?? {}
676
+ }
677
+ ];
671
678
  }
672
- return out;
679
+ return [];
673
680
  }
674
- __name(compatSourcesForSdk, "compatSourcesForSdk");
675
- function assertSdkCanReadNarrowedImport(version) {
676
- const [major, minor] = (version ?? "").split(".").map((n) => Number.parseInt(n, 10));
677
- const known = Number.isFinite(major) && Number.isFinite(minor);
678
- const supported = known && (major > COMPAT_IMPORT_SINCE.major || major === COMPAT_IMPORT_SINCE.major && minor >= COMPAT_IMPORT_SINCE.minor);
679
- if (!supported) throw new CompatImportUnsupportedError(version);
681
+ __name(translateToolCallEvent, "translateToolCallEvent");
682
+ function knownCost(cost) {
683
+ const amountUsd = cost?.amountUsd;
684
+ return typeof amountUsd === "number" && Number.isFinite(amountUsd) ? {
685
+ cost: amountUsd
686
+ } : {};
680
687
  }
681
- __name(assertSdkCanReadNarrowedImport, "assertSdkCanReadNarrowedImport");
682
- function assertSdkCanGateHooks(version) {
683
- const [major, minor] = (version ?? "").split(".").map((n) => Number.parseInt(n, 10));
684
- const known = Number.isFinite(major) && Number.isFinite(minor);
685
- const supported = known && (major > HOOK_GATE_SINCE.major || major === HOOK_GATE_SINCE.major && minor >= HOOK_GATE_SINCE.minor);
686
- if (!supported) throw new HookGateUnsupportedError(version);
688
+ __name(knownCost, "knownCost");
689
+ function costOf(result) {
690
+ return typeof result === "object" && result !== null && "cost" in result ? result.cost : void 0;
687
691
  }
688
- __name(assertSdkCanGateHooks, "assertSdkCanGateHooks");
689
- function installedSdkVersion() {
690
- try {
691
- return createRequire(import.meta.url)("@theokit/sdk/package.json").version;
692
- } catch {
693
- return void 0;
692
+ __name(costOf, "costOf");
693
+ function translateStatusEvent(msg) {
694
+ const s = msg.status;
695
+ if (s === "FINISHED" || s === "CANCELLED") {
696
+ return [
697
+ {
698
+ type: "done",
699
+ result: "",
700
+ usage: {
701
+ inputTokens: 0,
702
+ outputTokens: 0,
703
+ totalTokens: 0
704
+ },
705
+ durationMs: 0,
706
+ // A status message carries no price of its own; one whose `result` carries the SDK's cost
707
+ // reports it, and otherwise the key is left out, never written as 0 (B-424).
708
+ ...knownCost(costOf(msg.result))
709
+ }
710
+ ];
694
711
  }
695
- }
696
- __name(installedSdkVersion, "installedSdkVersion");
697
- function refuseIfSdkCannotReadCompatSources() {
698
- let version;
699
- try {
700
- version = createRequire(import.meta.url)("@theokit/sdk/package.json").version;
701
- } catch {
702
- return;
712
+ if (s === "ERROR" || s === "EXPIRED") {
713
+ return [
714
+ {
715
+ type: "error",
716
+ code: "AGENT_ERROR",
717
+ message: asString(msg.message, "Agent error"),
718
+ retryable: false
719
+ }
720
+ ];
703
721
  }
704
- assertSdkCanReadCompatSources(version);
705
- }
706
- __name(refuseIfSdkCannotReadCompatSources, "refuseIfSdkCannotReadCompatSources");
707
- function assertSdkCanReadCompatSources(version) {
708
- const major = Number.parseInt(version?.split(".")[0] ?? "", 10);
709
- if (!Number.isFinite(major)) return;
710
- if (major >= COMPAT_ROOT_SINCE_MAJOR) return;
711
- throw new CompatRootUnsupportedError(version);
722
+ return [];
712
723
  }
713
- __name(assertSdkCanReadCompatSources, "assertSdkCanReadCompatSources");
714
- function applyPlugins(compiled, options, applied) {
724
+ __name(translateStatusEvent, "translateStatusEvent");
725
+ var alreadyWarned = /* @__PURE__ */ new Set();
726
+ function warnIfUnknown(type, deliberatelyIgnored) {
727
+ if (deliberatelyIgnored.has(type) || alreadyWarned.has(type)) return;
728
+ alreadyWarned.add(type);
729
+ console.warn(`[theokit] agents.bridge: SDK event "${type}" is not translated and was discarded. If it carries information the UI needs, the translator needs a case for it (#141).`);
730
+ }
731
+ __name(warnIfUnknown, "warnIfUnknown");
732
+ var SDK_MESSAGE_IGNORED = /* @__PURE__ */ new Set([
733
+ "user"
734
+ ]);
735
+ var INTERACTION_UPDATE_IGNORED = /* @__PURE__ */ new Set([
736
+ "thinking-completed",
737
+ "token-delta",
738
+ "step-started",
739
+ "step-completed"
740
+ ]);
741
+ function translateSdkEvent(msg, runId) {
742
+ switch (msg.type) {
743
+ case "system":
744
+ return translateSystemEvent(msg, runId);
745
+ case "assistant":
746
+ return translateAssistantEvent(msg);
747
+ case "tool_call":
748
+ return translateToolCallEvent(msg);
749
+ case "thinking":
750
+ return [
751
+ {
752
+ type: "thinking",
753
+ content: asString(msg.text, "")
754
+ }
755
+ ];
756
+ case "status":
757
+ return translateStatusEvent(msg);
758
+ case "request":
759
+ return [
760
+ {
761
+ type: "input_requested",
762
+ requestId: asString(msg.request_id, "")
763
+ }
764
+ ];
765
+ case "task": {
766
+ const status = typeof msg.status === "string" ? msg.status : void 0;
767
+ const text = typeof msg.text === "string" ? msg.text : void 0;
768
+ if (status === void 0 && text === void 0) return [];
769
+ return [
770
+ {
771
+ type: "task_progress",
772
+ ...status !== void 0 ? {
773
+ status
774
+ } : {},
775
+ ...text !== void 0 ? {
776
+ text
777
+ } : {}
778
+ }
779
+ ];
780
+ }
781
+ default:
782
+ warnIfUnknown(msg.type, SDK_MESSAGE_IGNORED);
783
+ return [];
784
+ }
785
+ }
786
+ __name(translateSdkEvent, "translateSdkEvent");
787
+ function translateInteractionUpdate(update) {
788
+ switch (update.type) {
789
+ case "text-delta":
790
+ return update.text ? [
791
+ {
792
+ type: "text_delta",
793
+ content: update.text
794
+ }
795
+ ] : [];
796
+ case "thinking-delta":
797
+ return update.text ? [
798
+ {
799
+ type: "thinking",
800
+ content: update.text
801
+ }
802
+ ] : [];
803
+ case "tool-call-started":
804
+ return [
805
+ {
806
+ type: "tool_call",
807
+ callId: update.callId,
808
+ toolName: update.toolCall.name,
809
+ input: update.toolCall.args ?? {}
810
+ }
811
+ ];
812
+ case "partial-tool-call":
813
+ return [
814
+ {
815
+ type: "partial_tool_call",
816
+ callId: update.callId,
817
+ toolName: update.toolCall.name,
818
+ input: update.toolCall.args ?? {}
819
+ }
820
+ ];
821
+ case "tool-call-completed":
822
+ return [
823
+ {
824
+ type: "tool_result",
825
+ callId: update.callId,
826
+ toolName: update.toolCall.name,
827
+ output: serializeToolOutput(update.toolCall.result, ""),
828
+ durationMs: 0,
829
+ // #388 — the same predicate, and on this shape it answers `false` for a reason rather
830
+ // than by decree: `ToolCall` (`@theokit/sdk/dist/types/updates.d.ts`) declares only
831
+ // `{callId, name, args?, result?}`, and the SDK fills `result` with `renderToolResult()`
832
+ // — a rendered string — so the exit code structurally cannot travel here. The message-
833
+ // shaped report of the same call is the one that carries it, and `dedupeTools` is what
834
+ // lets it contribute (`sdk-timeline.ts`).
835
+ isError: reportsToolFailure(update.toolCall.result)
836
+ }
837
+ ];
838
+ case "shell-output-delta":
839
+ return [
840
+ {
841
+ type: "shell_output",
842
+ event: update.event
843
+ }
844
+ ];
845
+ default:
846
+ warnIfUnknown(update.type, INTERACTION_UPDATE_IGNORED);
847
+ return [];
848
+ }
849
+ }
850
+ __name(translateInteractionUpdate, "translateInteractionUpdate");
851
+
852
+ // src/bridge/sdk-adapter-create-options.ts
853
+ import { createRequire } from "module";
854
+ import { PermissionEngine, PermissionPlugin } from "@theokit/sdk";
855
+ import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
856
+
857
+ // src/bridge/code-plugins.ts
858
+ var CAPABILITY_KEYS = [
859
+ "register",
860
+ "profile",
861
+ "createProvider"
862
+ ];
863
+ var BUNDLE_KEYS = [
864
+ "path",
865
+ "type",
866
+ "source",
867
+ "marketplace"
868
+ ];
869
+ function assertCodePlugins(list) {
870
+ for (const entry of list) {
871
+ if (isCodePlugin(entry)) continue;
872
+ const looksLikeBundle = typeof entry === "object" && entry !== null && BUNDLE_KEYS.some((k) => k in entry);
873
+ throw new ConfigurationError(looksLikeBundle ? "plugins() takes CODE plugins \u2014 { name, register } objects registered with the runtime's lifecycle seam. The entry given describes a filesystem bundle, which is not declared here: put the bundle in a `plugins/` directory under `.theokit/` or `.claude/`, where its `skills/` and `agents/` are discovered. Note that the manifest (`.claude-plugin/plugin.json`), marketplaces, hooks, MCP servers, output styles and LSP servers are NOT read from a bundle by this runtime." : `plugins() takes { name, register } objects; received ${describe(entry)}.`, {
874
+ code: "plugins_expects_code_objects"
875
+ });
876
+ }
877
+ }
878
+ __name(assertCodePlugins, "assertCodePlugins");
879
+ function describe(entry) {
880
+ return entry === null ? "null" : typeof entry;
881
+ }
882
+ __name(describe, "describe");
883
+ function isCodePlugin(entry) {
884
+ if (typeof entry !== "object" || entry === null) return false;
885
+ const candidate = entry;
886
+ if (typeof candidate.name !== "string") return false;
887
+ return CAPABILITY_KEYS.some((key) => candidate[key] !== void 0);
888
+ }
889
+ __name(isCodePlugin, "isCodePlugin");
890
+
891
+ // src/bridge/sdk-adapter-create-options.ts
892
+ var HOOK_GATE_SINCE = {
893
+ major: 5,
894
+ minor: 4
895
+ };
896
+ var COMPAT_IMPORT_SINCE = {
897
+ major: 5,
898
+ minor: 4
899
+ };
900
+ var COMPAT_ROOT_SINCE_MAJOR = 5;
901
+ var HookGateUnsupportedError = class extends TheokitAgentError2 {
902
+ static {
903
+ __name(this, "HookGateUnsupportedError");
904
+ }
905
+ name = "HookGateUnsupportedError";
906
+ constructor(version) {
907
+ super(`a hook approval gate was declared, but the installed @theokit/sdk (${version ?? "version unreadable"}) cannot honour it: \`local.hooks\` landed in ${String(HOOK_GATE_SINCE.major)}.${String(HOOK_GATE_SINCE.minor)}.0. Forwarding it anyway would leave every hook spawning unreviewed while the gate reports as installed. Upgrade @theokit/sdk, or remove \`hookApproval\` and keep whatever refusal you have today (usetheokit/theokit#686).`, {
908
+ code: "hook_gate_unsupported",
909
+ isRetryable: false
910
+ });
911
+ }
912
+ };
913
+ var CompatRootUnsupportedError = class CompatRootUnsupportedError2 extends TheokitAgentError2 {
914
+ static {
915
+ __name(this, "CompatRootUnsupportedError");
916
+ }
917
+ name = "CompatRootUnsupportedError";
918
+ constructor(version) {
919
+ super(`\`compatSources\` asks for a foreign configuration root to be read, but the installed @theokit/sdk (${version ?? "version unreadable"}) does not know that option and drops it in silence \u2014 so EVERY foreign surface would be unavailable while the package resolves, compiles and runs. It landed in ${String(COMPAT_ROOT_SINCE_MAJOR)}.0.0, and this package declares a floor above it, so reaching this error means an override pinned the SDK lower. Remove the override, or drop \`compatSources\` if the foreign root is not wanted (usetheokit/theokit#739).`);
920
+ }
921
+ };
922
+ var CompatImportUnsupportedError = class extends TheokitAgentError2 {
923
+ static {
924
+ __name(this, "CompatImportUnsupportedError");
925
+ }
926
+ name = "CompatImportUnsupportedError";
927
+ constructor(version) {
928
+ super(`\`claudeCode.import\` narrows WHICH surfaces of a foreign configuration root to read, but the installed @theokit/sdk (${version ?? "version unreadable"}) cannot honour it: the narrowed shape landed in ${String(COMPAT_IMPORT_SINCE.major)}.${String(COMPAT_IMPORT_SINCE.minor)}.0. An older runtime drops the unrecognised shape in silence, so the root would not be read AT ALL \u2014 less than you asked for, not more. Upgrade @theokit/sdk, or omit \`import\` to read every surface of the root (usetheokit/theokit#686).`, {
929
+ code: "compat_import_unsupported",
930
+ isRetryable: false
931
+ });
932
+ }
933
+ };
934
+ function compatSourcesForSdk(sources) {
935
+ const out = [];
936
+ for (const source of sources) {
937
+ if (typeof source === "string") {
938
+ out.push(source);
939
+ continue;
940
+ }
941
+ const forSdk = source.import.filter((surface) => surface !== "commands");
942
+ if (forSdk.length > 0) out.push({
943
+ kind: source.kind,
944
+ import: forSdk
945
+ });
946
+ }
947
+ return out;
948
+ }
949
+ __name(compatSourcesForSdk, "compatSourcesForSdk");
950
+ function assertSdkCanReadNarrowedImport(version) {
951
+ const [major, minor] = (version ?? "").split(".").map((n) => Number.parseInt(n, 10));
952
+ const known = Number.isFinite(major) && Number.isFinite(minor);
953
+ const supported = known && (major > COMPAT_IMPORT_SINCE.major || major === COMPAT_IMPORT_SINCE.major && minor >= COMPAT_IMPORT_SINCE.minor);
954
+ if (!supported) throw new CompatImportUnsupportedError(version);
955
+ }
956
+ __name(assertSdkCanReadNarrowedImport, "assertSdkCanReadNarrowedImport");
957
+ function assertSdkCanGateHooks(version) {
958
+ const [major, minor] = (version ?? "").split(".").map((n) => Number.parseInt(n, 10));
959
+ const known = Number.isFinite(major) && Number.isFinite(minor);
960
+ const supported = known && (major > HOOK_GATE_SINCE.major || major === HOOK_GATE_SINCE.major && minor >= HOOK_GATE_SINCE.minor);
961
+ if (!supported) throw new HookGateUnsupportedError(version);
962
+ }
963
+ __name(assertSdkCanGateHooks, "assertSdkCanGateHooks");
964
+ function installedSdkVersion() {
965
+ try {
966
+ return createRequire(import.meta.url)("@theokit/sdk/package.json").version;
967
+ } catch {
968
+ return void 0;
969
+ }
970
+ }
971
+ __name(installedSdkVersion, "installedSdkVersion");
972
+ function refuseIfSdkCannotReadCompatSources() {
973
+ let version;
974
+ try {
975
+ version = createRequire(import.meta.url)("@theokit/sdk/package.json").version;
976
+ } catch {
977
+ return;
978
+ }
979
+ assertSdkCanReadCompatSources(version);
980
+ }
981
+ __name(refuseIfSdkCannotReadCompatSources, "refuseIfSdkCannotReadCompatSources");
982
+ function assertSdkCanReadCompatSources(version) {
983
+ const major = Number.parseInt(version?.split(".")[0] ?? "", 10);
984
+ if (!Number.isFinite(major)) return;
985
+ if (major >= COMPAT_ROOT_SINCE_MAJOR) return;
986
+ throw new CompatRootUnsupportedError(version);
987
+ }
988
+ __name(assertSdkCanReadCompatSources, "assertSdkCanReadCompatSources");
989
+ function applyPlugins(compiled, options, applied) {
715
990
  if (compiled.plugins) {
716
991
  assertCodePlugins(compiled.plugins);
717
992
  options.plugins = compiled.plugins;
@@ -765,381 +1040,121 @@ function applyLocalSources(compiled, options, applied, sdkVersion) {
765
1040
  if (forSdk.length > 0) {
766
1041
  options.local = {
767
1042
  ...options.local,
768
- compatSources: forSdk
769
- };
770
- applied.push("compatSources");
771
- refuseIfSdkCannotReadCompatSources();
772
- }
773
- }
774
- }
775
- __name(applyLocalSources, "applyLocalSources");
776
- function applyHookApproval(compiled, options, applied, sdkVersion) {
777
- if (compiled.hookApproval === void 0) return;
778
- assertSdkCanGateHooks(sdkVersion ?? installedSdkVersion());
779
- options.local = {
780
- ...options.local,
781
- hooks: compiled.hookApproval
782
- };
783
- applied.push("hookApproval");
784
- }
785
- __name(applyHookApproval, "applyHookApproval");
786
- function assembleM8CreateOptions(compiled, deps = {}) {
787
- const options = {};
788
- const applied = [];
789
- const base = compiled.systemPrompt;
790
- if (compiled.skills) {
791
- options.skills = compiled.skills;
792
- applied.push("skills");
793
- }
794
- applyPlugins(compiled, options, applied);
795
- if (compiled.agents !== void 0 && Object.keys(compiled.agents).length > 0) {
796
- options.agents = compiled.agents;
797
- applied.push("agents");
798
- }
799
- applyLocalSources(compiled, options, applied, deps.sdkVersion);
800
- applyHookApproval(compiled, options, applied, deps.sdkVersion);
801
- if (compiled.context) {
802
- options.context = compiled.context;
803
- applied.push("context");
804
- }
805
- if (compiled.projectContext) {
806
- options.systemPrompt = compileProjectContext(compiled.projectContext, base);
807
- applied.push("projectContext");
808
- } else if (base !== void 0) {
809
- options.systemPrompt = base;
810
- }
811
- if (compiled.mcpServers && Object.keys(compiled.mcpServers).length > 0) {
812
- options.mcpServers = compiled.mcpServers;
813
- applied.push("mcpServers");
814
- }
815
- if (compiled.memory !== void 0) {
816
- if ("enabled" in compiled.memory) {
817
- options.memory = compiled.memory;
818
- } else {
819
- const dropped = Object.keys(compiled.memory);
820
- if (dropped.length > 0) {
821
- process.stderr.write(`[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
822
- `);
823
- }
824
- options.memory = {
825
- enabled: true
826
- };
827
- }
828
- applied.push("memory");
829
- }
830
- if (compiled.telemetry !== void 0) {
831
- options.telemetry = compiled.telemetry;
832
- applied.push("telemetry");
833
- }
834
- return {
835
- options,
836
- applied
837
- };
838
- }
839
- __name(assembleM8CreateOptions, "assembleM8CreateOptions");
840
- function stopReasonOf(result) {
841
- if (result.stoppedByDoomLoop === true) return "no_progress";
842
- if (result.stoppedAtIterationLimit === true) return "step_limit";
843
- return void 0;
844
- }
845
- __name(stopReasonOf, "stopReasonOf");
846
- function realUsageDone(result, t0, model) {
847
- const u = result.usage;
848
- const inputTokens = u?.inputTokens ?? 0;
849
- const outputTokens = u?.outputTokens ?? 0;
850
- const stopReason = stopReasonOf(result);
851
- return {
852
- type: "done",
853
- result: result.result ?? "",
854
- // V4-O: forward the SDK reasoning/cache buckets (0 when the provider omits them) so a
855
- // consumer keeps full per-turn usage through the loop into DelegationResult (passthrough — ADR D1).
856
- usage: {
857
- inputTokens,
858
- outputTokens,
859
- totalTokens: inputTokens + outputTokens,
860
- reasoningTokens: u?.reasoningTokens ?? 0,
861
- cacheReadTokens: u?.cacheReadTokens ?? 0,
862
- cacheWriteTokens: u?.cacheWriteTokens ?? 0
863
- },
864
- durationMs: Date.now() - t0,
865
- cost: result.cost?.amount ?? 0,
866
- ...terminalExtras(stopReason, model)
867
- };
868
- }
869
- __name(realUsageDone, "realUsageDone");
870
- function terminalExtras(stopReason, model) {
871
- const extras = {};
872
- if (stopReason !== void 0) extras.stopReason = stopReason;
873
- if (model !== void 0) extras.model = model;
874
- return extras;
875
- }
876
- __name(terminalExtras, "terminalExtras");
877
-
878
- // src/bridge/event-translator.ts
879
- function asString(value, fallback) {
880
- if (typeof value === "string") return value;
881
- return fallback;
882
- }
883
- __name(asString, "asString");
884
- function toolResultExitCode(value) {
885
- if (typeof value !== "object" || value === null) return void 0;
886
- const code = value.exitCode;
887
- return typeof code === "number" ? code : void 0;
888
- }
889
- __name(toolResultExitCode, "toolResultExitCode");
890
- function reportsToolFailure(result) {
891
- return (toolResultExitCode(result) ?? 0) !== 0;
892
- }
893
- __name(reportsToolFailure, "reportsToolFailure");
894
- function serializeToolOutput(value, fallback) {
895
- if (typeof value === "string") return value;
896
- if (value === void 0 || value === null) return fallback;
897
- try {
898
- return JSON.stringify(value);
899
- } catch {
900
- return typeof value === "bigint" ? value.toString() : fallback;
901
- }
902
- }
903
- __name(serializeToolOutput, "serializeToolOutput");
904
- function translateSystemEvent(msg, runId) {
905
- return [
906
- {
907
- type: "run_started",
908
- runId,
909
- agentName: asString(msg.agent_id, "agent"),
910
- model: asString(msg.model, "unknown")
911
- }
912
- ];
913
- }
914
- __name(translateSystemEvent, "translateSystemEvent");
915
- function translateAssistantEvent(msg) {
916
- const events = [];
917
- const message = msg.message;
918
- const content = message?.content;
919
- if (!Array.isArray(content)) return events;
920
- for (const block of content) {
921
- const b = block;
922
- if (b.type === "text" && b.text) {
923
- events.push({
924
- type: "text_delta",
925
- content: b.text
926
- });
927
- }
928
- if (b.type === "tool_use") {
929
- events.push({
930
- type: "tool_call",
931
- // #138 — this was `tc-${Date.now()}`. A fresh id on every call is NEVER in the dedup set, so
932
- // the fallback defeated dedup by construction — and still looked like a real id to a reader.
933
- // An empty string is honest: `isDuplicatedByDelta` treats it as "I cannot identify this" and
934
- // prefers a visible double render to a silent suppression.
935
- callId: b.id ?? "",
936
- toolName: b.name ?? "unknown",
937
- input: b.input ?? {}
938
- });
1043
+ compatSources: forSdk
1044
+ };
1045
+ applied.push("compatSources");
1046
+ refuseIfSdkCannotReadCompatSources();
939
1047
  }
940
1048
  }
941
- return events;
942
1049
  }
943
- __name(translateAssistantEvent, "translateAssistantEvent");
944
- function translateToolCallEvent(msg) {
945
- const status = msg.status;
946
- const callId = asString(msg.call_id, "");
947
- const toolName = asString(msg.name, "unknown");
948
- if (status === "completed") {
949
- return [
950
- {
951
- type: "tool_result",
952
- callId,
953
- toolName,
954
- output: serializeToolOutput(msg.result, ""),
955
- durationMs: 0,
956
- // #388 — `completed` is the SDK's word for "the call is over", not for "the call worked".
957
- // The exit code is the part that says which, and it was being thrown away here.
958
- isError: reportsToolFailure(msg.result)
959
- }
960
- ];
1050
+ __name(applyLocalSources, "applyLocalSources");
1051
+ function applyHookApproval(compiled, options, applied, sdkVersion) {
1052
+ if (compiled.hookApproval === void 0) return;
1053
+ assertSdkCanGateHooks(sdkVersion ?? installedSdkVersion());
1054
+ options.local = {
1055
+ ...options.local,
1056
+ hooks: compiled.hookApproval
1057
+ };
1058
+ applied.push("hookApproval");
1059
+ }
1060
+ __name(applyHookApproval, "applyHookApproval");
1061
+ function assembleM8CreateOptions(compiled, deps = {}) {
1062
+ const options = {};
1063
+ const applied = [];
1064
+ const base = compiled.systemPrompt;
1065
+ if (compiled.skills) {
1066
+ options.skills = compiled.skills;
1067
+ applied.push("skills");
961
1068
  }
962
- if (status === "error") {
963
- return [
964
- {
965
- type: "tool_result",
966
- callId,
967
- toolName,
968
- output: serializeToolOutput(msg.result, "Tool failed"),
969
- durationMs: 0,
970
- isError: true
971
- }
972
- ];
1069
+ applyPlugins(compiled, options, applied);
1070
+ if (compiled.agents !== void 0 && Object.keys(compiled.agents).length > 0) {
1071
+ options.agents = compiled.agents;
1072
+ applied.push("agents");
973
1073
  }
974
- if (status === "running") {
975
- return [
976
- {
977
- type: "tool_call",
978
- callId,
979
- toolName,
980
- input: msg.args ?? msg.input ?? msg.arguments ?? {}
981
- }
982
- ];
1074
+ applyLocalSources(compiled, options, applied, deps.sdkVersion);
1075
+ applyHookApproval(compiled, options, applied, deps.sdkVersion);
1076
+ if (compiled.context) {
1077
+ options.context = compiled.context;
1078
+ applied.push("context");
983
1079
  }
984
- return [];
985
- }
986
- __name(translateToolCallEvent, "translateToolCallEvent");
987
- function translateStatusEvent(msg) {
988
- const s = msg.status;
989
- if (s === "FINISHED" || s === "CANCELLED") {
990
- return [
991
- {
992
- type: "done",
993
- result: "",
994
- usage: {
995
- inputTokens: 0,
996
- outputTokens: 0,
997
- totalTokens: 0
998
- },
999
- durationMs: 0,
1000
- cost: 0
1001
- }
1002
- ];
1080
+ if (compiled.projectContext) {
1081
+ options.systemPrompt = compileProjectContext(compiled.projectContext, base);
1082
+ applied.push("projectContext");
1083
+ } else if (base !== void 0) {
1084
+ options.systemPrompt = base;
1003
1085
  }
1004
- if (s === "ERROR" || s === "EXPIRED") {
1005
- return [
1006
- {
1007
- type: "error",
1008
- code: "AGENT_ERROR",
1009
- message: asString(msg.message, "Agent error"),
1010
- retryable: false
1011
- }
1012
- ];
1086
+ if (compiled.mcpServers && Object.keys(compiled.mcpServers).length > 0) {
1087
+ options.mcpServers = compiled.mcpServers;
1088
+ applied.push("mcpServers");
1013
1089
  }
1014
- return [];
1015
- }
1016
- __name(translateStatusEvent, "translateStatusEvent");
1017
- var alreadyWarned = /* @__PURE__ */ new Set();
1018
- function warnIfUnknown(type, deliberatelyIgnored) {
1019
- if (deliberatelyIgnored.has(type) || alreadyWarned.has(type)) return;
1020
- alreadyWarned.add(type);
1021
- console.warn(`[theokit] agents.bridge: SDK event "${type}" is not translated and was discarded. If it carries information the UI needs, the translator needs a case for it (#141).`);
1022
- }
1023
- __name(warnIfUnknown, "warnIfUnknown");
1024
- var SDK_MESSAGE_IGNORED = /* @__PURE__ */ new Set([
1025
- "user"
1026
- ]);
1027
- var INTERACTION_UPDATE_IGNORED = /* @__PURE__ */ new Set([
1028
- "thinking-completed",
1029
- "token-delta",
1030
- "step-started",
1031
- "step-completed"
1032
- ]);
1033
- function translateSdkEvent(msg, runId) {
1034
- switch (msg.type) {
1035
- case "system":
1036
- return translateSystemEvent(msg, runId);
1037
- case "assistant":
1038
- return translateAssistantEvent(msg);
1039
- case "tool_call":
1040
- return translateToolCallEvent(msg);
1041
- case "thinking":
1042
- return [
1043
- {
1044
- type: "thinking",
1045
- content: asString(msg.text, "")
1046
- }
1047
- ];
1048
- case "status":
1049
- return translateStatusEvent(msg);
1050
- case "request":
1051
- return [
1052
- {
1053
- type: "input_requested",
1054
- requestId: asString(msg.request_id, "")
1055
- }
1056
- ];
1057
- case "task": {
1058
- const status = typeof msg.status === "string" ? msg.status : void 0;
1059
- const text = typeof msg.text === "string" ? msg.text : void 0;
1060
- if (status === void 0 && text === void 0) return [];
1061
- return [
1062
- {
1063
- type: "task_progress",
1064
- ...status !== void 0 ? {
1065
- status
1066
- } : {},
1067
- ...text !== void 0 ? {
1068
- text
1069
- } : {}
1070
- }
1071
- ];
1090
+ if (compiled.memory !== void 0) {
1091
+ if ("enabled" in compiled.memory) {
1092
+ options.memory = compiled.memory;
1093
+ } else {
1094
+ const dropped = Object.keys(compiled.memory);
1095
+ if (dropped.length > 0) {
1096
+ process.stderr.write(`[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
1097
+ `);
1098
+ }
1099
+ options.memory = {
1100
+ enabled: true
1101
+ };
1072
1102
  }
1073
- default:
1074
- warnIfUnknown(msg.type, SDK_MESSAGE_IGNORED);
1075
- return [];
1103
+ applied.push("memory");
1076
1104
  }
1077
- }
1078
- __name(translateSdkEvent, "translateSdkEvent");
1079
- function translateInteractionUpdate(update) {
1080
- switch (update.type) {
1081
- case "text-delta":
1082
- return update.text ? [
1083
- {
1084
- type: "text_delta",
1085
- content: update.text
1086
- }
1087
- ] : [];
1088
- case "thinking-delta":
1089
- return update.text ? [
1090
- {
1091
- type: "thinking",
1092
- content: update.text
1093
- }
1094
- ] : [];
1095
- case "tool-call-started":
1096
- return [
1097
- {
1098
- type: "tool_call",
1099
- callId: update.callId,
1100
- toolName: update.toolCall.name,
1101
- input: update.toolCall.args ?? {}
1102
- }
1103
- ];
1104
- case "partial-tool-call":
1105
- return [
1106
- {
1107
- type: "partial_tool_call",
1108
- callId: update.callId,
1109
- toolName: update.toolCall.name,
1110
- input: update.toolCall.args ?? {}
1111
- }
1112
- ];
1113
- case "tool-call-completed":
1114
- return [
1115
- {
1116
- type: "tool_result",
1117
- callId: update.callId,
1118
- toolName: update.toolCall.name,
1119
- output: serializeToolOutput(update.toolCall.result, ""),
1120
- durationMs: 0,
1121
- // #388 — the same predicate, and on this shape it answers `false` for a reason rather
1122
- // than by decree: `ToolCall` (`@theokit/sdk/dist/types/updates.d.ts`) declares only
1123
- // `{callId, name, args?, result?}`, and the SDK fills `result` with `renderToolResult()`
1124
- // — a rendered string — so the exit code structurally cannot travel here. The message-
1125
- // shaped report of the same call is the one that carries it, and `dedupeTools` is what
1126
- // lets it contribute (`sdk-timeline.ts`).
1127
- isError: reportsToolFailure(update.toolCall.result)
1128
- }
1129
- ];
1130
- case "shell-output-delta":
1131
- return [
1132
- {
1133
- type: "shell_output",
1134
- event: update.event
1135
- }
1136
- ];
1137
- default:
1138
- warnIfUnknown(update.type, INTERACTION_UPDATE_IGNORED);
1139
- return [];
1105
+ if (compiled.telemetry !== void 0) {
1106
+ options.telemetry = compiled.telemetry;
1107
+ applied.push("telemetry");
1140
1108
  }
1109
+ return {
1110
+ options,
1111
+ applied
1112
+ };
1113
+ }
1114
+ __name(assembleM8CreateOptions, "assembleM8CreateOptions");
1115
+ function stopReasonOf(result) {
1116
+ if (result.stoppedByDoomLoop === true) return "no_progress";
1117
+ if (result.stoppedAtIterationLimit === true) return "step_limit";
1118
+ return void 0;
1119
+ }
1120
+ __name(stopReasonOf, "stopReasonOf");
1121
+ function doneUsage(sdkUsage) {
1122
+ const usage = sdkUsage ?? {};
1123
+ const inputTokens = countOrZero(usage.inputTokens);
1124
+ const outputTokens = countOrZero(usage.outputTokens);
1125
+ return {
1126
+ inputTokens,
1127
+ outputTokens,
1128
+ totalTokens: inputTokens + outputTokens,
1129
+ reasoningTokens: countOrZero(usage.reasoningTokens),
1130
+ cacheReadTokens: countOrZero(usage.cacheReadTokens),
1131
+ cacheWriteTokens: countOrZero(usage.cacheWriteTokens)
1132
+ };
1141
1133
  }
1142
- __name(translateInteractionUpdate, "translateInteractionUpdate");
1134
+ __name(doneUsage, "doneUsage");
1135
+ function countOrZero(count) {
1136
+ return count ?? 0;
1137
+ }
1138
+ __name(countOrZero, "countOrZero");
1139
+ function realUsageDone(result, t0, model) {
1140
+ const stopReason = stopReasonOf(result);
1141
+ return {
1142
+ type: "done",
1143
+ result: result.result ?? "",
1144
+ usage: doneUsage(result.usage),
1145
+ durationMs: Date.now() - t0,
1146
+ ...knownCost(result.cost),
1147
+ ...terminalExtras(stopReason, model)
1148
+ };
1149
+ }
1150
+ __name(realUsageDone, "realUsageDone");
1151
+ function terminalExtras(stopReason, model) {
1152
+ const extras = {};
1153
+ if (stopReason !== void 0) extras.stopReason = stopReason;
1154
+ if (model !== void 0) extras.model = model;
1155
+ return extras;
1156
+ }
1157
+ __name(terminalExtras, "terminalExtras");
1143
1158
 
1144
1159
  // src/bridge/think-tag-extractor.ts
1145
1160
  var TAG = "think";
@@ -1254,10 +1269,7 @@ function withStepCeiling(handle, maxIterations) {
1254
1269
  return handle.agentId;
1255
1270
  },
1256
1271
  dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
1257
- // Forwarded — see {@link SdkAgentHandle.generate} for why, and why it is not guarded.
1258
- ...handle.generate === void 0 ? {} : {
1259
- generate: handle.generate.bind(handle)
1260
- },
1272
+ ...forwardedMembers(handle),
1261
1273
  send: /* @__PURE__ */ __name((msg, sendOpts) => handle.send(msg, {
1262
1274
  maxIterations,
1263
1275
  ...sendOpts
@@ -1272,27 +1284,68 @@ function withGuardrails(handle, guardrails) {
1272
1284
  return handle.agentId;
1273
1285
  },
1274
1286
  dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
1275
- // Forwarded — see {@link SdkAgentHandle.generate} for why, and why it is not guarded.
1276
- ...handle.generate === void 0 ? {} : {
1277
- generate: handle.generate.bind(handle)
1278
- },
1287
+ ...forwardedMembers(handle),
1279
1288
  send: /* @__PURE__ */ __name(async (msg, sendOpts) => {
1280
1289
  const guarded = await runInputGuards(msg, guardrails);
1281
- const turn = await handle.send(guarded, sendOpts);
1282
- return {
1283
- wait: /* @__PURE__ */ __name(async () => {
1284
- const out = await turn.wait();
1285
- if (out.result === void 0) return out;
1286
- return {
1287
- ...out,
1288
- result: await runOutputGuards(out.result, guardrails)
1289
- };
1290
- }, "wait")
1291
- };
1290
+ return guardTurn(await handle.send(guarded, sendOpts), guardrails);
1292
1291
  }, "send")
1293
1292
  };
1294
1293
  }
1295
1294
  __name(withGuardrails, "withGuardrails");
1295
+ function forwardedMembers(handle) {
1296
+ return {
1297
+ ...handle.generate === void 0 ? {} : {
1298
+ generate: handle.generate.bind(handle)
1299
+ },
1300
+ ...handle.pluginManager === void 0 ? {} : {
1301
+ pluginManager: handle.pluginManager.bind(handle)
1302
+ }
1303
+ };
1304
+ }
1305
+ __name(forwardedMembers, "forwardedMembers");
1306
+ function guardTurn(turn, guardrails) {
1307
+ let outcome;
1308
+ const guardedOutcome = /* @__PURE__ */ __name(() => outcome ??= turn.wait().then(async (out) => out.result === void 0 ? out : {
1309
+ ...out,
1310
+ result: await runOutputGuards(out.result, guardrails)
1311
+ }), "guardedOutcome");
1312
+ return {
1313
+ wait: guardedOutcome,
1314
+ async *stream() {
1315
+ let out;
1316
+ try {
1317
+ out = await guardedOutcome();
1318
+ } catch (err) {
1319
+ if (!(err instanceof GuardrailError)) throw err;
1320
+ yield errorStatus(err.message);
1321
+ return;
1322
+ }
1323
+ if (out.result !== void 0) {
1324
+ yield {
1325
+ type: "assistant",
1326
+ message: {
1327
+ content: [
1328
+ {
1329
+ type: "text",
1330
+ text: out.result
1331
+ }
1332
+ ]
1333
+ }
1334
+ };
1335
+ }
1336
+ if (out.status === "error") yield errorStatus(out.error?.message ?? "run error");
1337
+ }
1338
+ };
1339
+ }
1340
+ __name(guardTurn, "guardTurn");
1341
+ function errorStatus(message) {
1342
+ return {
1343
+ type: "status",
1344
+ status: "ERROR",
1345
+ message
1346
+ };
1347
+ }
1348
+ __name(errorStatus, "errorStatus");
1296
1349
 
1297
1350
  // src/bridge/sdk-error.ts
1298
1351
  function sdkErrorEvent(err) {
@@ -1880,987 +1933,6 @@ function toAgentFactory(def, opts) {
1880
1933
  }
1881
1934
  __name(toAgentFactory, "toAgentFactory");
1882
1935
 
1883
- // src/loop/compaction-strategy.ts
1884
- import { compactTranscript } from "@theokit/sdk/compaction";
1885
- import { z } from "zod";
1886
- var DEFAULT_KEEP_TOKENS = 8e3;
1887
- var compactionStrategyConfigSchema = z.object({
1888
- name: z.literal("token-budget"),
1889
- keepTokens: z.number().int().positive()
1890
- });
1891
- function resolveCompactionStrategy(name, config) {
1892
- const cfg = compactionStrategyConfigSchema.parse({
1893
- name,
1894
- keepTokens: config.keepTokens
1895
- });
1896
- return {
1897
- name: cfg.name,
1898
- keepTokens: cfg.keepTokens,
1899
- compact: /* @__PURE__ */ __name((messages, options) => compactTranscript(messages, {
1900
- keepTokens: options?.keepTokens ?? cfg.keepTokens,
1901
- summarize: options?.summarize,
1902
- marker: options?.marker,
1903
- summaryTemplate: options?.summaryTemplate,
1904
- // Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).
1905
- failSafe: options?.failSafe ?? true
1906
- }), "compact")
1907
- };
1908
- }
1909
- __name(resolveCompactionStrategy, "resolveCompactionStrategy");
1910
- var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
1911
- keepTokens: DEFAULT_KEEP_TOKENS
1912
- });
1913
-
1914
- // src/loop/loop-strategy.ts
1915
- import { z as z2 } from "zod";
1916
- var DEFAULT_MAX_ITERATIONS = 8;
1917
- var maxIterationsSchema = z2.number().int().min(1);
1918
- var loopStrategyConfigSchema = z2.object({
1919
- name: z2.enum([
1920
- "simple-chat",
1921
- "plan-act-reflect",
1922
- "react"
1923
- ]),
1924
- maxIterations: maxIterationsSchema
1925
- });
1926
- function assertValidCustomLoopStrategy(strategy) {
1927
- const result = maxIterationsSchema.safeParse(strategy.maxIterations);
1928
- if (!result.success) {
1929
- throw new Error(`loopStrategy: invalid maxIterations (${String(strategy.maxIterations)}) \u2014 must be a finite integer \u2265 1 (otherwise the round < maxIterations ceiling never terminates)`);
1930
- }
1931
- }
1932
- __name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
1933
- function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
1934
- const cfg = loopStrategyConfigSchema.parse({
1935
- name: strategy,
1936
- maxIterations
1937
- });
1938
- if (cfg.name === "simple-chat") {
1939
- return {
1940
- name: cfg.name,
1941
- maxIterations: cfg.maxIterations,
1942
- shouldContinue: /* @__PURE__ */ __name(() => false, "shouldContinue")
1943
- };
1944
- }
1945
- if (cfg.name === "plan-act-reflect") {
1946
- return {
1947
- name: cfg.name,
1948
- maxIterations: cfg.maxIterations,
1949
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.round < cfg.maxIterations, "shouldContinue")
1950
- };
1951
- }
1952
- return {
1953
- name: cfg.name,
1954
- maxIterations: cfg.maxIterations,
1955
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations, "shouldContinue")
1956
- };
1957
- }
1958
- __name(resolveLoopStrategy, "resolveLoopStrategy");
1959
-
1960
- // src/loop/reflection-strategy.ts
1961
- import { z as z3 } from "zod";
1962
- var reflectionStrategyConfigSchema = z3.object({
1963
- name: z3.string().min(1)
1964
- });
1965
- var ladderReflectionStrategy = {
1966
- name: "ladder",
1967
- reflect(outcome) {
1968
- if (outcome.finishReason === "tool-calls") {
1969
- return {
1970
- feedback: `Tool results received (round ${outcome.round}). Reflect on whether the goal is met; if not, refine the approach and continue.`,
1971
- continue: true
1972
- };
1973
- }
1974
- return {
1975
- continue: false
1976
- };
1977
- }
1978
- };
1979
- var noopReflectionStrategy = {
1980
- name: "noop",
1981
- reflect() {
1982
- return {
1983
- continue: true
1984
- };
1985
- }
1986
- };
1987
-
1988
- // src/bridge/delegation-types.ts
1989
- import { TheokitAgentError as TheokitAgentError4 } from "@theokit/sdk/errors";
1990
- var DelegationBudgetExceededError = class extends TheokitAgentError4 {
1991
- static {
1992
- __name(this, "DelegationBudgetExceededError");
1993
- }
1994
- agentName;
1995
- actualCost;
1996
- budgetLimit;
1997
- name = "DelegationBudgetExceededError";
1998
- constructor(agentName, actualCost, budgetLimit) {
1999
- super(`Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`, {
2000
- code: "DELEGATION_BUDGET_EXCEEDED",
2001
- // The budget does not refill on retry.
2002
- isRetryable: false
2003
- }), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
2004
- }
2005
- };
2006
- var BudgetExceededError = DelegationBudgetExceededError;
2007
- var DelegationError = class extends TheokitAgentError4 {
2008
- static {
2009
- __name(this, "DelegationError");
2010
- }
2011
- agentName;
2012
- cause;
2013
- name = "DelegationError";
2014
- constructor(agentName, cause) {
2015
- super(`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
2016
- code: "DELEGATION_FAILED",
2017
- // Not retryable AT THIS LEVEL: whether the underlying cause is transient is the cause's own
2018
- // answer, and `cause` is carried so a caller can ask it rather than guess from the wrapper.
2019
- isRetryable: false,
2020
- cause
2021
- }), this.agentName = agentName, this.cause = cause;
2022
- }
2023
- };
2024
-
2025
- // src/guardrails/terminal-frame.ts
2026
- async function* mirrorModeratedText(inner) {
2027
- let round = "";
2028
- let sawText = false;
2029
- let step = await inner.next();
2030
- while (!step.done) {
2031
- const event = step.value;
2032
- if (event.type === "text_delta" && typeof event.content === "string") {
2033
- round += event.content;
2034
- sawText = true;
2035
- }
2036
- if (event.type === "done") {
2037
- yield sawText ? {
2038
- ...event,
2039
- result: round
2040
- } : event;
2041
- round = "";
2042
- sawText = false;
2043
- } else {
2044
- yield event;
2045
- }
2046
- step = await inner.next();
2047
- }
2048
- return step.value;
2049
- }
2050
- __name(mirrorModeratedText, "mirrorModeratedText");
2051
-
2052
- // src/loop/run-reflective-loop.ts
2053
- function asString2(value, fallback) {
2054
- return typeof value === "string" ? value : fallback;
2055
- }
2056
- __name(asString2, "asString");
2057
- function asNumber(value, fallback) {
2058
- return typeof value === "number" ? value : fallback;
2059
- }
2060
- __name(asNumber, "asNumber");
2061
- var NO_PROGRESS_THRESHOLD = 2;
2062
- var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
2063
- var TOOL_CALLS = "tool-calls";
2064
- var STEP_LIMIT_HINT = "This is your final round \u2014 do not call any more tools; summarize the work done so far and list any remaining tasks.";
2065
- function stableStringify(value) {
2066
- if (value === void 0) return "undefined";
2067
- if (value === null || typeof value !== "object") return JSON.stringify(value);
2068
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
2069
- const obj = value;
2070
- const entries = Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
2071
- return `{${entries.join(",")}}`;
2072
- }
2073
- __name(stableStringify, "stableStringify");
2074
- function roundSignature(toolCalls) {
2075
- return toolCalls.map((tc) => `${tc.name}:${stableStringify(tc.input)}`).sort((a, b) => a.localeCompare(b)).join(",");
2076
- }
2077
- __name(roundSignature, "roundSignature");
2078
- function terminalReason(reflectionContinue, roundReason, round, maxIterations) {
2079
- if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations) return "step_limit";
2080
- if (roundReason === TOOL_CALLS) return "stop";
2081
- return roundReason;
2082
- }
2083
- __name(terminalReason, "terminalReason");
2084
- var CONTINUE_PROMPT = "Continue from the prior turns above; finish the task and give a final answer.";
2085
- function buildPrompt(round, maxIterations, message, feedback) {
2086
- const hint = round === maxIterations ? `${STEP_LIMIT_HINT}
2087
-
2088
- ` : "";
2089
- const continuation = feedback ? `[reflection] ${feedback}` : CONTINUE_PROMPT;
2090
- const body = round === 1 ? message : continuation;
2091
- return hint + body;
2092
- }
2093
- __name(buildPrompt, "buildPrompt");
2094
- async function* consumeRoundOrThrow(inputs, agentName) {
2095
- try {
2096
- return yield* consumeOneRound(inputs.factory, inputs.prompt, inputs.sessionId, inputs.signal, inputs.retry);
2097
- } catch (err) {
2098
- if (err instanceof DelegationBudgetExceededError || err instanceof DelegationError || err instanceof GuardrailError) {
2099
- throw err;
2100
- }
2101
- throw new DelegationError(agentName, err);
2102
- }
2103
- }
2104
- __name(consumeRoundOrThrow, "consumeRoundOrThrow");
2105
- function accumulateUsage(acc, r) {
2106
- acc.cost += r.cost;
2107
- acc.tokens += r.tokens;
2108
- acc.tokensInput = (acc.tokensInput ?? 0) + r.tokensInput;
2109
- acc.tokensOutput = (acc.tokensOutput ?? 0) + r.tokensOutput;
2110
- acc.reasoningTokens = (acc.reasoningTokens ?? 0) + r.reasoningTokens;
2111
- acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + r.cacheReadTokens;
2112
- acc.cacheWriteTokens = (acc.cacheWriteTokens ?? 0) + r.cacheWriteTokens;
2113
- }
2114
- __name(accumulateUsage, "accumulateUsage");
2115
- function finalize(acc, round, reason, strategyName) {
2116
- acc.rounds = round;
2117
- acc.finishReason = reason;
2118
- debugLog(MAINLOOP_METRIC, {
2119
- strategy: strategyName,
2120
- rounds: round,
2121
- terminal: reason
2122
- });
2123
- return acc;
2124
- }
2125
- __name(finalize, "finalize");
2126
- function deriveFinishReason(signals) {
2127
- if (signals.sawError) return "error";
2128
- if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS;
2129
- if (signals.sawToolResult) return TOOL_CALLS;
2130
- return "stop";
2131
- }
2132
- __name(deriveFinishReason, "deriveFinishReason");
2133
- function pushToolResult(event, r, callInputs) {
2134
- const id = asString2(event.callId, "");
2135
- const call = callInputs.get(id);
2136
- r.toolCalls.push({
2137
- id,
2138
- name: call?.name ?? asString2(event.toolName, "unknown"),
2139
- // Prefer the correlated tool_call input (real SDK shape); fall back to an input on the
2140
- // result event itself (some streams/tests carry it there), else {}.
2141
- input: call?.input ?? event.input ?? {},
2142
- output: asString2(event.output, "")
2143
- });
2144
- }
2145
- __name(pushToolResult, "pushToolResult");
2146
- function applyDone(event, r) {
2147
- r.cost = asNumber(event.cost, 0);
2148
- const usage = event.usage;
2149
- r.tokens = usage?.totalTokens ?? 0;
2150
- r.tokensInput = usage?.inputTokens ?? 0;
2151
- r.tokensOutput = usage?.outputTokens ?? 0;
2152
- r.reasoningTokens = usage?.reasoningTokens ?? 0;
2153
- r.cacheReadTokens = usage?.cacheReadTokens ?? 0;
2154
- r.cacheWriteTokens = usage?.cacheWriteTokens ?? 0;
2155
- }
2156
- __name(applyDone, "applyDone");
2157
- function accumulateEvent(event, r, signals, callInputs) {
2158
- if (event.type === "text_delta" && typeof event.content === "string") {
2159
- r.responseText += event.content;
2160
- } else if (event.type === "tool_call") {
2161
- callInputs.set(asString2(event.callId, ""), {
2162
- name: asString2(event.toolName, "unknown"),
2163
- input: event.input ?? {}
2164
- });
2165
- } else if (event.type === "tool_result") {
2166
- signals.sawToolResult = true;
2167
- pushToolResult(event, r, callInputs);
2168
- } else if (event.type === "done") {
2169
- signals.sawDone = true;
2170
- signals.doneFinishReason = asString2(event.finishReason, "");
2171
- applyDone(event, r);
2172
- } else if (event.type === "error") {
2173
- signals.sawError = true;
2174
- r.errorMessage = asString2(event.message, "Unknown agent error");
2175
- }
2176
- }
2177
- __name(accumulateEvent, "accumulateEvent");
2178
- async function startRound(factory, prompt, sessionId, signal, retry) {
2179
- const open = /* @__PURE__ */ __name(async () => {
2180
- const it = factory(prompt, sessionId)[Symbol.asyncIterator]();
2181
- try {
2182
- return {
2183
- it,
2184
- first: await it.next()
2185
- };
2186
- } catch (err) {
2187
- await it.return?.(void 0);
2188
- throw err;
2189
- }
2190
- }, "open");
2191
- if (!retry) return open();
2192
- const { Retry } = await import("@theokit/sdk/retry");
2193
- return Retry.run(open, {
2194
- ...retry,
2195
- signal: retry.signal ?? signal
2196
- });
2197
- }
2198
- __name(startRound, "startRound");
2199
- async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
2200
- const r = {
2201
- responseText: "",
2202
- toolCalls: [],
2203
- cost: 0,
2204
- tokens: 0,
2205
- tokensInput: 0,
2206
- tokensOutput: 0,
2207
- reasoningTokens: 0,
2208
- cacheReadTokens: 0,
2209
- cacheWriteTokens: 0,
2210
- finishReason: "stop",
2211
- errorMessage: ""
2212
- };
2213
- const signals = {
2214
- sawError: false,
2215
- sawDone: false,
2216
- doneFinishReason: "",
2217
- sawToolResult: false
2218
- };
2219
- const callInputs = /* @__PURE__ */ new Map();
2220
- const { it, first } = await startRound(factory, prompt, sessionId, signal, retry);
2221
- let next = first;
2222
- while (!next.done) {
2223
- if (signal?.aborted) {
2224
- await it.return?.(void 0);
2225
- break;
2226
- }
2227
- yield next.value;
2228
- accumulateEvent(next.value, r, signals, callInputs);
2229
- next = await it.next();
2230
- }
2231
- r.finishReason = deriveFinishReason(signals);
2232
- return r;
2233
- }
2234
- __name(consumeOneRound, "consumeOneRound");
2235
- function ceilingRoundFactory(factory, round, maxIterations) {
2236
- if (round !== maxIterations) return factory;
2237
- return (m, s) => factory(m, s, {
2238
- disableTools: true
2239
- });
2240
- }
2241
- __name(ceilingRoundFactory, "ceilingRoundFactory");
2242
- async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2243
- const { loop, reflection, budget = Number.POSITIVE_INFINITY, signal, agentName = loop.name, retry } = config;
2244
- const acc = {
2245
- response: "",
2246
- toolCalls: [],
2247
- cost: 0,
2248
- tokens: 0,
2249
- tokensInput: 0,
2250
- tokensOutput: 0,
2251
- reasoningTokens: 0,
2252
- cacheReadTokens: 0,
2253
- cacheWriteTokens: 0,
2254
- rounds: 0
2255
- };
2256
- const reflectionContext = {};
2257
- let round = 1;
2258
- let feedback;
2259
- let prevSig;
2260
- let stuck = 0;
2261
- while (!signal?.aborted) {
2262
- const prompt = buildPrompt(round, loop.maxIterations, message, feedback);
2263
- const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations);
2264
- const r = yield* consumeRoundOrThrow({
2265
- factory: roundFactory,
2266
- prompt,
2267
- sessionId,
2268
- signal,
2269
- retry
2270
- }, agentName);
2271
- acc.response += r.responseText;
2272
- acc.toolCalls.push(...r.toolCalls);
2273
- accumulateUsage(acc, r);
2274
- if (r.finishReason === "error") throw new DelegationError(agentName, r.errorMessage);
2275
- if (Number.isFinite(budget) && acc.cost > budget) {
2276
- throw new DelegationBudgetExceededError(agentName, acc.cost, budget);
2277
- }
2278
- if (r.finishReason === TOOL_CALLS && r.toolCalls.length > 0) {
2279
- const sig = roundSignature(r.toolCalls);
2280
- stuck = sig === prevSig ? stuck + 1 : 0;
2281
- if (stuck >= NO_PROGRESS_THRESHOLD) return finalize(acc, round, "no_progress", loop.name);
2282
- prevSig = sig;
2283
- }
2284
- const outcome = {
2285
- finishReason: r.finishReason,
2286
- round,
2287
- toolCalls: r.toolCalls,
2288
- responseText: r.responseText
2289
- };
2290
- const reflectionResult = reflection.reflect(outcome, reflectionContext);
2291
- if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
2292
- const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
2293
- return finalize(acc, round, reason, loop.name);
2294
- }
2295
- feedback = reflectionResult.feedback;
2296
- round += 1;
2297
- }
2298
- acc.rounds = round - 1;
2299
- return acc;
2300
- }
2301
- __name(runReflectiveLoopStream, "runReflectiveLoopStream");
2302
- async function runReflectiveLoop(factory, message, sessionId, config) {
2303
- const gen = runReflectiveLoopStream(factory, message, sessionId, config);
2304
- let res = await gen.next();
2305
- while (!res.done) res = await gen.next();
2306
- return res.value;
2307
- }
2308
- __name(runReflectiveLoop, "runReflectiveLoop");
2309
-
2310
- // src/loop/agent-runner.ts
2311
- var AgentRunner = class {
2312
- static {
2313
- __name(this, "AgentRunner");
2314
- }
2315
- compiled;
2316
- agentName;
2317
- /** The resolved terminal-decision strategy (parity with `delegate()`). */
2318
- loopStrategy;
2319
- /** M54 — whether {@link loopStrategy} is a caller-injected custom (see {@link AgentRunnerState}). */
2320
- loopStrategyIsCustom;
2321
- /** The resolved between-round reflection (default or `.reflection(custom)` override). */
2322
- reflectionStrategy;
2323
- /**
2324
- * Recorded streaming preference. The reflective loop currently always streams via
2325
- * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
2326
- * captured + exposed here, not yet branched on (honest per G10: documented, not a
2327
- * silent no-op).
2328
- */
2329
- streamEnabled;
2330
- /**
2331
- * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
2332
- * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
2333
- * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
2334
- * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
2335
- */
2336
- compaction;
2337
- constructor(state) {
2338
- this.compiled = state.compiled;
2339
- this.agentName = state.agentName;
2340
- this.loopStrategy = state.loopStrategy;
2341
- this.loopStrategyIsCustom = state.loopStrategyIsCustom ?? false;
2342
- this.reflectionStrategy = state.reflectionStrategy;
2343
- this.streamEnabled = state.streamEnabled;
2344
- this.compaction = state.compaction;
2345
- }
2346
- /** Start a fluent builder from an already-compiled spec. */
2347
- static fromSpec(spec) {
2348
- return new AgentRunnerBuilder(spec);
2349
- }
2350
- /**
2351
- * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
2352
- * the aggregated {@link DelegationResult} as the generator's return value. This is the
2353
- * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
2354
- * round's events before the loop terminates. `streamEnabled` is honored: when the
2355
- * builder set `.stream(false)`, callers should use {@link run} instead.
2356
- */
2357
- stream(message, opts) {
2358
- const guardrails = this.compiled.guardrails;
2359
- if (guardrails && guardrails.length > 0) {
2360
- const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, opts), "runUnguarded");
2361
- return (/* @__PURE__ */ __name(async function* guarded() {
2362
- const safe = await runInputGuards(message, guardrails);
2363
- return yield* mirrorModeratedText(
2364
- // #732 — the fourth channel, and the one the `done` fix cannot reach. A milestone is not
2365
- // a mirror of anything: it carries text the model writes through `task-tools`, so it gets
2366
- // its own pass like the two below. One pass per kind, because two kinds under one
2367
- // extractor collapse into a single event.
2368
- //
2369
- // `task-tools.ts` claimed B-018 had already shipped this. It had not — `agent-endpoint.ts`
2370
- // said in the same tree that the channel was NOT covered, and the claim is corrected there
2371
- // rather than deleted.
2372
- moderateOutputStream(
2373
- moderateOutputStream(
2374
- moderateOutputStream(
2375
- runUnguarded(safe),
2376
- guardrails,
2377
- // B-021 — the shared extractor, so "this kind, content unreadable" throws instead of
2378
- // sharing a return value with "not this kind". The hand-written form here returned
2379
- // `undefined` for a non-string, which reads as "carries no text": the payload was
2380
- // never shown to a guard and was yielded verbatim.
2381
- textPayloadExtractor("text_delta", (e) => e.content),
2382
- (content) => ({
2383
- type: "text_delta",
2384
- content
2385
- }),
2386
- (content, result) => ({
2387
- ...result,
2388
- response: content
2389
- })
2390
- ),
2391
- guardrails,
2392
- textPayloadExtractor("thinking", (e) => e.content),
2393
- (content) => ({
2394
- type: "thinking",
2395
- content
2396
- }),
2397
- // The reasoning pass does NOT touch the aggregate — the visible pass already did.
2398
- (_content, result) => result
2399
- ),
2400
- guardrails,
2401
- textPayloadExtractor("task_progress", (e) => e.text),
2402
- (text) => ({
2403
- type: "task_progress",
2404
- text
2405
- }),
2406
- // A milestone is not the answer — the visible pass owns the aggregate.
2407
- (_text, result) => result
2408
- )
2409
- );
2410
- }, "guarded"))();
2411
- }
2412
- return this.streamUnguarded(message, opts);
2413
- }
2414
- /** The core stream path, after input guardrails have run (M9). */
2415
- streamUnguarded(message, opts) {
2416
- const tools = opts.tools ? [
2417
- ...opts.tools
2418
- ] : this.compiled.tools;
2419
- const loop = this.resolvePerRunLoop(opts.maxIterations);
2420
- const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
2421
- model: opts.model,
2422
- reasoningEffort: opts.reasoningEffort,
2423
- parseThinkTags: opts.parseThinkTags,
2424
- stripToolDialect: opts.stripToolDialect,
2425
- recoverLeakedToolCalls: opts.recoverLeakedToolCalls,
2426
- cwd: opts.cwd,
2427
- baseDir: opts.baseDir,
2428
- plugins: opts.plugins,
2429
- providers: opts.providers,
2430
- agents: opts.agents,
2431
- budgetTracker: opts.budgetTracker,
2432
- sdkTools: opts.sdkTools
2433
- });
2434
- const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`;
2435
- return runReflectiveLoopStream(streamFactory, message, sessionId, {
2436
- loop,
2437
- reflection: this.reflectionStrategy,
2438
- budget: opts.budget,
2439
- agentName: this.agentName,
2440
- signal: opts.signal,
2441
- retry: opts.retry
2442
- });
2443
- }
2444
- /** Run the agent to a terminal result via the shared reflective loop (collect mode). */
2445
- /**
2446
- * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
2447
- * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
2448
- * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
2449
- * overriding just that field bounds a custom without touching its logic. A built-in keeps the
2450
- * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
2451
- */
2452
- resolvePerRunLoop(maxIterations) {
2453
- if (maxIterations == null) return this.loopStrategy;
2454
- if (this.loopStrategyIsCustom) {
2455
- const base = this.loopStrategy;
2456
- return Object.assign(Object.create(Object.getPrototypeOf(base)), base, {
2457
- maxIterations
2458
- });
2459
- }
2460
- return resolveLoopStrategy(this.loopStrategy.name, maxIterations);
2461
- }
2462
- async run(message, opts) {
2463
- const gen = this.stream(message, opts);
2464
- let res = await gen.next();
2465
- while (!res.done) res = await gen.next();
2466
- return res.value;
2467
- }
2468
- };
2469
- var AgentRunnerBuilder = class {
2470
- static {
2471
- __name(this, "AgentRunnerBuilder");
2472
- }
2473
- spec;
2474
- reflectionOverride;
2475
- streamEnabled = true;
2476
- compactionOverride;
2477
- loopStrategyOverride;
2478
- constructor(spec) {
2479
- this.spec = spec;
2480
- }
2481
- /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
2482
- reflection(strategy) {
2483
- if (strategy) this.reflectionOverride = strategy;
2484
- return this;
2485
- }
2486
- /**
2487
- * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
2488
- * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
2489
- * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
2490
- * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
2491
- * infinite loop.
2492
- *
2493
- * @example
2494
- * ```ts
2495
- * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
2496
- * const stopWhenConfident: LoopStrategy = {
2497
- * name: 'confident',
2498
- * maxIterations: 8,
2499
- * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
2500
- * }
2501
- * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
2502
- * ```
2503
- */
2504
- loopStrategy(custom) {
2505
- assertValidCustomLoopStrategy(custom);
2506
- this.loopStrategyOverride = custom;
2507
- return this;
2508
- }
2509
- /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */
2510
- stream(enabled = true) {
2511
- this.streamEnabled = enabled;
2512
- return this;
2513
- }
2514
- /**
2515
- * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
2516
- * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
2517
- * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
2518
- */
2519
- compaction(name, options = {}) {
2520
- this.compactionOverride = {
2521
- name,
2522
- keepTokens: options.keepTokens
2523
- };
2524
- return this;
2525
- }
2526
- /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
2527
- build() {
2528
- const { spec } = this;
2529
- const strategy = spec.strategy ?? "simple-chat";
2530
- const loopStrategyIsCustom = this.loopStrategyOverride !== void 0;
2531
- const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
2532
- const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2533
- const compactionDecl = this.compactionOverride ?? spec.compaction;
2534
- const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
2535
- keepTokens: compactionDecl.keepTokens
2536
- }) : void 0;
2537
- return new AgentRunner({
2538
- compiled: spec.compiled,
2539
- agentName: spec.name,
2540
- loopStrategy,
2541
- loopStrategyIsCustom,
2542
- reflectionStrategy,
2543
- streamEnabled: this.streamEnabled,
2544
- compaction
2545
- });
2546
- }
2547
- };
2548
-
2549
- // src/loop/goal-runner.ts
2550
- import { runGoalLoop } from "@theokit/sdk";
2551
- import { JudgeCredentialError } from "@theokit/sdk";
2552
- var GoalRunner = class {
2553
- static {
2554
- __name(this, "GoalRunner");
2555
- }
2556
- agent;
2557
- constructor(agent) {
2558
- this.agent = agent;
2559
- }
2560
- /**
2561
- * Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`
2562
- * returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads
2563
- * straight through; a test seam for the judge lives there, exactly as on the free function.
2564
- */
2565
- run(goal, options, deps) {
2566
- return runGoalLoop(this.agent, goal, options, deps);
2567
- }
2568
- };
2569
-
2570
- // src/loop/format-goal-event.ts
2571
- function formatGoalEvent(event) {
2572
- const candidate = event;
2573
- if (candidate === null || typeof candidate !== "object" || typeof candidate.type !== "string") {
2574
- return "[goal] unrecognised event (malformed)";
2575
- }
2576
- switch (event.type) {
2577
- case "turn_start":
2578
- return `[goal] turn ${event.turn} started \u2014 ${event.goal}`;
2579
- case "agent_response":
2580
- return `[goal] turn ${event.turn} response: ${event.content}`;
2581
- case "judge_verdict":
2582
- return `[goal] turn ${event.turn} judged ${event.verdict}: ${event.reason}` + // Surfaced rather than hidden: a verdict the judge could not parse reached a decision by
2583
- // fallback, and an operator reading the log needs to know which of the two happened.
2584
- (event.parseFailed ? " (verdict could not be parsed)" : "");
2585
- case "continuation":
2586
- return `[goal] turn ${event.turn} continuing: ${event.prompt}`;
2587
- case "status_change":
2588
- return `[goal] status ${event.status}: ${event.reason}`;
2589
- default:
2590
- return formatUnrecognised(event);
2591
- }
2592
- }
2593
- __name(formatGoalEvent, "formatGoalEvent");
2594
- function formatUnrecognised(event) {
2595
- const { type } = event;
2596
- return `[goal] unrecognised event: ${String(type)}`;
2597
- }
2598
- __name(formatUnrecognised, "formatUnrecognised");
2599
-
2600
- // src/loop/pre-compaction.ts
2601
- import { TheokitAgentError as TheokitAgentError5 } from "@theokit/sdk/errors";
2602
- var DEFAULT_HANDLER_TIMEOUT_MS = 3e4;
2603
- var PreCompactionHandlerError = class extends TheokitAgentError5 {
2604
- static {
2605
- __name(this, "PreCompactionHandlerError");
2606
- }
2607
- name = "PreCompactionHandlerError";
2608
- /** `'timeout'` when the bound was exceeded, `'threw'` when the handler failed on its own. */
2609
- reason;
2610
- constructor(message, reason, options) {
2611
- super(message, {
2612
- code: "PRE_COMPACTION_HANDLER_FAILED",
2613
- ...options ?? {}
2614
- });
2615
- this.reason = reason;
2616
- }
2617
- };
2618
- function assertUsableTimeout(timeoutMs) {
2619
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2620
- throw new TypeError(`withPreCompaction: timeoutMs must be a finite number greater than 0, received ${String(timeoutMs)}`);
2621
- }
2622
- }
2623
- __name(assertUsableTimeout, "assertUsableTimeout");
2624
- async function runHandlerBounded(handler, messages, timeoutMs, onError) {
2625
- let timer;
2626
- const controller = new AbortController();
2627
- try {
2628
- await Promise.race([
2629
- Promise.resolve(handler(messages, controller.signal)),
2630
- new Promise((_resolve, reject) => {
2631
- timer = setTimeout(() => {
2632
- controller.abort();
2633
- reject(new PreCompactionHandlerError(`pre-compaction handler exceeded its ${String(timeoutMs)}ms bound; compaction proceeded without it`, "timeout"));
2634
- }, timeoutMs);
2635
- })
2636
- ]);
2637
- } catch (cause) {
2638
- const detail = cause instanceof Error ? cause.message : String(cause);
2639
- const reported = cause instanceof PreCompactionHandlerError ? cause : new PreCompactionHandlerError(`pre-compaction handler failed: ${detail}`, "threw", {
2640
- cause
2641
- });
2642
- onError?.(reported);
2643
- } finally {
2644
- if (timer !== void 0) clearTimeout(timer);
2645
- }
2646
- }
2647
- __name(runHandlerBounded, "runHandlerBounded");
2648
- function withPreCompaction(strategy, handler, options) {
2649
- const timeoutMs = options?.timeoutMs ?? DEFAULT_HANDLER_TIMEOUT_MS;
2650
- assertUsableTimeout(timeoutMs);
2651
- const onError = options?.onError;
2652
- return {
2653
- name: strategy.name,
2654
- keepTokens: strategy.keepTokens,
2655
- compact: /* @__PURE__ */ __name(async (messages, callOptions) => {
2656
- await runHandlerBounded(handler, [
2657
- ...messages
2658
- ], timeoutMs, onError);
2659
- return strategy.compact(messages, callOptions);
2660
- }, "compact")
2661
- };
2662
- }
2663
- __name(withPreCompaction, "withPreCompaction");
2664
-
2665
- // src/loop/decomposition.ts
2666
- function resolveDecomposition(callerSubgoals, declared) {
2667
- if (declared.length > 0) return declared;
2668
- return callerSubgoals;
2669
- }
2670
- __name(resolveDecomposition, "resolveDecomposition");
2671
-
2672
- // src/bridge/agent-orchestrator.ts
2673
- function requireApiKey(opts, agentName) {
2674
- if (opts.apiKey === null) return "";
2675
- const apiKey = opts.apiKey ?? "";
2676
- if (!apiKey) {
2677
- throw new DelegationError(agentName, "No API key provided. Pass apiKey in DelegateOptions, or `apiKey: null` when the provider takes no credential (a local model).");
2678
- }
2679
- return apiKey;
2680
- }
2681
- __name(requireApiKey, "requireApiKey");
2682
- function withInheritedHooks(compiled, parentHooks) {
2683
- const plugin = hooksPlugin(inheritHooks(parentHooks, void 0));
2684
- if (plugin === void 0) return compiled;
2685
- return {
2686
- ...compiled,
2687
- plugins: [
2688
- ...compiled.plugins ?? [],
2689
- plugin
2690
- ]
2691
- };
2692
- }
2693
- __name(withInheritedHooks, "withInheritedHooks");
2694
- function mergeTools(parentTools, subTools) {
2695
- const subToolNames = new Set(subTools.map((t) => t.name));
2696
- const inherited = parentTools.filter((t) => !subToolNames.has(t.name));
2697
- return [
2698
- ...inherited,
2699
- ...subTools
2700
- ];
2701
- }
2702
- __name(mergeTools, "mergeTools");
2703
- async function delegate(spec, message, opts = {}) {
2704
- const apiKey = requireApiKey(opts, spec.name);
2705
- const rewritten = opts.onDelegationStart ? await opts.onDelegationStart({
2706
- subAgent: spec.name,
2707
- input: message
2708
- }) : message;
2709
- const { compiled } = spec;
2710
- const guardrails = compiled.guardrails ?? [];
2711
- const effectiveMessage = await runInputGuards(rewritten, guardrails);
2712
- const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
2713
- const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
2714
- const compiledForMember = withInheritedHooks(compiled, opts.parentHooks);
2715
- const streamFactory = opts.streamFactory ?? createSdkAgentStream(compiledForMember, allTools, apiKey, {
2716
- model: opts.model ?? compiled.model,
2717
- cwd: opts.cwd,
2718
- plugins: opts.plugins,
2719
- providers: opts.providers,
2720
- agents: opts.agents,
2721
- budgetTracker: opts.budgetTracker,
2722
- sdkTools: opts.sdkTools
2723
- });
2724
- const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
2725
- const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
2726
- const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2727
- const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
2728
- loop: loopStrategy,
2729
- reflection,
2730
- budget,
2731
- agentName: spec.name,
2732
- signal: opts.signal,
2733
- retry: opts.retry
2734
- });
2735
- const transformed = opts.onDelegationComplete ? await opts.onDelegationComplete({
2736
- subAgent: spec.name,
2737
- result
2738
- }) : result;
2739
- return await moderateDelegationResult(transformed, guardrails);
2740
- }
2741
- __name(delegate, "delegate");
2742
- async function moderateDelegationResult(result, guardrails) {
2743
- if (guardrails.length === 0) return result;
2744
- return {
2745
- ...result,
2746
- response: await runOutputGuards(result.response, guardrails)
2747
- };
2748
- }
2749
- __name(moderateDelegationResult, "moderateDelegationResult");
2750
-
2751
- // src/bridge/delegation-lifecycle.ts
2752
- import { TheokitAgentError as TheokitAgentError6 } from "@theokit/sdk/errors";
2753
- var DelegationTimeoutError = class extends TheokitAgentError6 {
2754
- static {
2755
- __name(this, "DelegationTimeoutError");
2756
- }
2757
- name = "DelegationTimeoutError";
2758
- constructor(subAgent, timeoutMs) {
2759
- super(`delegation to "${subAgent}" exceeded its ${String(timeoutMs)} ms clock cap. This is a WALL CLOCK limit, not a budget: the run may have been progressing and simply slow, or hung. Raise \`timeoutMs\` if the work legitimately takes longer.`, {
2760
- code: "DELEGATION_TIMEOUT",
2761
- // A hang is often transient — the model, a tool or a network call. Unlike the budget errors,
2762
- // this one is worth another attempt, which is exactly why it is a separate class.
2763
- isRetryable: true
2764
- });
2765
- }
2766
- };
2767
- async function withClockCap(promise, timeoutMs, subAgent) {
2768
- let timer;
2769
- const clock = new Promise((_resolve, reject) => {
2770
- timer = setTimeout(() => {
2771
- reject(new DelegationTimeoutError(subAgent, timeoutMs));
2772
- }, timeoutMs);
2773
- });
2774
- try {
2775
- return await Promise.race([
2776
- promise,
2777
- clock
2778
- ]);
2779
- } finally {
2780
- if (timer !== void 0) clearTimeout(timer);
2781
- }
2782
- }
2783
- __name(withClockCap, "withClockCap");
2784
- async function withEphemeralAgent(create, body, options = {}) {
2785
- const { agent, dispose } = await create();
2786
- try {
2787
- return await body(agent);
2788
- } finally {
2789
- try {
2790
- await dispose();
2791
- } catch (error) {
2792
- options.onDisposeError?.(error);
2793
- }
2794
- }
2795
- }
2796
- __name(withEphemeralAgent, "withEphemeralAgent");
2797
-
2798
- // src/bridge/delegation-scoring.ts
2799
- function isPort(target) {
2800
- if ("compiled" in target) return false;
2801
- return typeof target.run === "function";
2802
- }
2803
- __name(isPort, "isPort");
2804
- async function runOnce(target, message, delegateFn, opts) {
2805
- const port = isPort(target);
2806
- const started = port ? target.run(message) : delegateFn(target, message, opts);
2807
- if (opts.timeoutMs === void 0) return started;
2808
- return withClockCap(started, opts.timeoutMs, port ? "port" : target.name);
2809
- }
2810
- __name(runOnce, "runOnce");
2811
- function delegateBackground(subAgent, message, opts = {}) {
2812
- const { delegateFn = delegate, ...delegateOpts } = opts;
2813
- let isSettled = false;
2814
- const promise = runOnce(subAgent, message, delegateFn, delegateOpts).finally(() => {
2815
- isSettled = true;
2816
- });
2817
- promise.catch(() => void 0);
2818
- return {
2819
- wait: /* @__PURE__ */ __name(() => promise, "wait"),
2820
- settled: /* @__PURE__ */ __name(() => isSettled, "settled")
2821
- };
2822
- }
2823
- __name(delegateBackground, "delegateBackground");
2824
- var DEFAULT_MAX_ROUNDS = 3;
2825
- function defaultFeedbackTemplate(message, feedback) {
2826
- return `${message}
2827
-
2828
- Feedback from the reviewer (address this): ${feedback}`;
2829
- }
2830
- __name(defaultFeedbackTemplate, "defaultFeedbackTemplate");
2831
- async function delegateWithScoring(subAgent, message, opts) {
2832
- const { scorer, maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS, delegateFn = delegate, feedbackTemplate = defaultFeedbackTemplate, ...delegateOpts } = opts;
2833
- const maxRounds = Math.max(1, maxRoundsOpt);
2834
- const verdicts = [];
2835
- let currentMessage = message;
2836
- let lastResult;
2837
- for (let round = 1; round <= maxRounds; round++) {
2838
- const result = await runOnce(subAgent, currentMessage, delegateFn, delegateOpts);
2839
- lastResult = result;
2840
- const verdict = await scorer(result);
2841
- verdicts.push(verdict);
2842
- if (verdict.pass) {
2843
- return {
2844
- result,
2845
- rounds: round,
2846
- passed: true,
2847
- verdicts
2848
- };
2849
- }
2850
- if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
2851
- }
2852
- if (lastResult === void 0) {
2853
- throw new Error("[@theokit/agents] delegateWithScoring: no round ran (maxRounds < 1)");
2854
- }
2855
- return {
2856
- result: lastResult,
2857
- rounds: maxRounds,
2858
- passed: false,
2859
- verdicts
2860
- };
2861
- }
2862
- __name(delegateWithScoring, "delegateWithScoring");
2863
-
2864
1936
  export {
2865
1937
  projectContextMetadataOnlyKnobs,
2866
1938
  compileProjectContext,
@@ -2887,41 +1959,12 @@ export {
2887
1959
  textPayloadExtractor,
2888
1960
  buildModelSelection,
2889
1961
  reasoningEffortOf,
1962
+ translateSdkEvent,
2890
1963
  HookGateUnsupportedError,
2891
1964
  CompatImportUnsupportedError,
2892
- translateSdkEvent,
2893
1965
  createThinkTagExtractor,
2894
1966
  extractThinkTagStream,
2895
1967
  createSdkAgentStream,
2896
- toAgentFactory,
2897
- DEFAULT_KEEP_TOKENS,
2898
- compactionStrategyConfigSchema,
2899
- resolveCompactionStrategy,
2900
- tokenBudgetCompactionStrategy,
2901
- DEFAULT_MAX_ITERATIONS,
2902
- loopStrategyConfigSchema,
2903
- resolveLoopStrategy,
2904
- reflectionStrategyConfigSchema,
2905
- ladderReflectionStrategy,
2906
- noopReflectionStrategy,
2907
- DelegationBudgetExceededError,
2908
- BudgetExceededError,
2909
- DelegationError,
2910
- AgentRunner,
2911
- AgentRunnerBuilder,
2912
- GoalRunner,
2913
- JudgeCredentialError,
2914
- formatGoalEvent,
2915
- DEFAULT_HANDLER_TIMEOUT_MS,
2916
- PreCompactionHandlerError,
2917
- withPreCompaction,
2918
- resolveDecomposition,
2919
- delegate,
2920
- DelegationTimeoutError,
2921
- withClockCap,
2922
- withEphemeralAgent,
2923
- isPort,
2924
- delegateBackground,
2925
- delegateWithScoring
1968
+ toAgentFactory
2926
1969
  };
2927
- //# sourceMappingURL=chunk-RAN4PBUL.js.map
1970
+ //# sourceMappingURL=chunk-3TE4PJZL.js.map