@theokit/agents 15.1.1 → 16.0.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.
@@ -574,6 +574,285 @@ function reasoningEffortOf(model) {
574
574
  }
575
575
  __name(reasoningEffortOf, "reasoningEffortOf");
576
576
 
577
+ // src/bridge/event-translator.ts
578
+ function asString(value, fallback) {
579
+ if (typeof value === "string") return value;
580
+ return fallback;
581
+ }
582
+ __name(asString, "asString");
583
+ function toolResultExitCode(value) {
584
+ if (typeof value !== "object" || value === null) return void 0;
585
+ const code = value.exitCode;
586
+ return typeof code === "number" ? code : void 0;
587
+ }
588
+ __name(toolResultExitCode, "toolResultExitCode");
589
+ function reportsToolFailure(result) {
590
+ return (toolResultExitCode(result) ?? 0) !== 0;
591
+ }
592
+ __name(reportsToolFailure, "reportsToolFailure");
593
+ function serializeToolOutput(value, fallback) {
594
+ if (typeof value === "string") return value;
595
+ if (value === void 0 || value === null) return fallback;
596
+ try {
597
+ return JSON.stringify(value);
598
+ } catch {
599
+ return typeof value === "bigint" ? value.toString() : fallback;
600
+ }
601
+ }
602
+ __name(serializeToolOutput, "serializeToolOutput");
603
+ function translateSystemEvent(msg, runId) {
604
+ return [
605
+ {
606
+ type: "run_started",
607
+ runId,
608
+ agentName: asString(msg.agent_id, "agent"),
609
+ model: asString(msg.model, "unknown")
610
+ }
611
+ ];
612
+ }
613
+ __name(translateSystemEvent, "translateSystemEvent");
614
+ function translateAssistantEvent(msg) {
615
+ const events = [];
616
+ const message = msg.message;
617
+ const content = message?.content;
618
+ if (!Array.isArray(content)) return events;
619
+ for (const block of content) {
620
+ const b = block;
621
+ if (b.type === "text" && b.text) {
622
+ events.push({
623
+ type: "text_delta",
624
+ content: b.text
625
+ });
626
+ }
627
+ if (b.type === "tool_use") {
628
+ events.push({
629
+ type: "tool_call",
630
+ // #138 — this was `tc-${Date.now()}`. A fresh id on every call is NEVER in the dedup set, so
631
+ // the fallback defeated dedup by construction — and still looked like a real id to a reader.
632
+ // An empty string is honest: `isDuplicatedByDelta` treats it as "I cannot identify this" and
633
+ // prefers a visible double render to a silent suppression.
634
+ callId: b.id ?? "",
635
+ toolName: b.name ?? "unknown",
636
+ input: b.input ?? {}
637
+ });
638
+ }
639
+ }
640
+ return events;
641
+ }
642
+ __name(translateAssistantEvent, "translateAssistantEvent");
643
+ function translateToolCallEvent(msg) {
644
+ const status = msg.status;
645
+ const callId = asString(msg.call_id, "");
646
+ const toolName = asString(msg.name, "unknown");
647
+ if (status === "completed") {
648
+ return [
649
+ {
650
+ type: "tool_result",
651
+ callId,
652
+ toolName,
653
+ output: serializeToolOutput(msg.result, ""),
654
+ durationMs: 0,
655
+ // #388 — `completed` is the SDK's word for "the call is over", not for "the call worked".
656
+ // The exit code is the part that says which, and it was being thrown away here.
657
+ isError: reportsToolFailure(msg.result)
658
+ }
659
+ ];
660
+ }
661
+ if (status === "error") {
662
+ return [
663
+ {
664
+ type: "tool_result",
665
+ callId,
666
+ toolName,
667
+ output: serializeToolOutput(msg.result, "Tool failed"),
668
+ durationMs: 0,
669
+ isError: true
670
+ }
671
+ ];
672
+ }
673
+ if (status === "running") {
674
+ return [
675
+ {
676
+ type: "tool_call",
677
+ callId,
678
+ toolName,
679
+ input: msg.args ?? msg.input ?? msg.arguments ?? {}
680
+ }
681
+ ];
682
+ }
683
+ return [];
684
+ }
685
+ __name(translateToolCallEvent, "translateToolCallEvent");
686
+ function knownCost(cost) {
687
+ const amountUsd = cost?.amountUsd;
688
+ return typeof amountUsd === "number" && Number.isFinite(amountUsd) ? {
689
+ cost: amountUsd
690
+ } : {};
691
+ }
692
+ __name(knownCost, "knownCost");
693
+ function costOf(result) {
694
+ return typeof result === "object" && result !== null && "cost" in result ? result.cost : void 0;
695
+ }
696
+ __name(costOf, "costOf");
697
+ function translateStatusEvent(msg) {
698
+ const s = msg.status;
699
+ if (s === "FINISHED" || s === "CANCELLED") {
700
+ return [
701
+ {
702
+ type: "done",
703
+ result: "",
704
+ usage: {
705
+ inputTokens: 0,
706
+ outputTokens: 0,
707
+ totalTokens: 0
708
+ },
709
+ durationMs: 0,
710
+ // A status message carries no price of its own; one whose `result` carries the SDK's cost
711
+ // reports it, and otherwise the key is left out, never written as 0 (B-424).
712
+ ...knownCost(costOf(msg.result))
713
+ }
714
+ ];
715
+ }
716
+ if (s === "ERROR" || s === "EXPIRED") {
717
+ return [
718
+ {
719
+ type: "error",
720
+ code: "AGENT_ERROR",
721
+ message: asString(msg.message, "Agent error"),
722
+ retryable: false
723
+ }
724
+ ];
725
+ }
726
+ return [];
727
+ }
728
+ __name(translateStatusEvent, "translateStatusEvent");
729
+ var alreadyWarned = /* @__PURE__ */ new Set();
730
+ function warnIfUnknown(type, deliberatelyIgnored) {
731
+ if (deliberatelyIgnored.has(type) || alreadyWarned.has(type)) return;
732
+ alreadyWarned.add(type);
733
+ 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).`);
734
+ }
735
+ __name(warnIfUnknown, "warnIfUnknown");
736
+ var SDK_MESSAGE_IGNORED = /* @__PURE__ */ new Set([
737
+ "user"
738
+ ]);
739
+ var INTERACTION_UPDATE_IGNORED = /* @__PURE__ */ new Set([
740
+ "thinking-completed",
741
+ "token-delta",
742
+ "step-started",
743
+ "step-completed"
744
+ ]);
745
+ function translateSdkEvent(msg, runId) {
746
+ switch (msg.type) {
747
+ case "system":
748
+ return translateSystemEvent(msg, runId);
749
+ case "assistant":
750
+ return translateAssistantEvent(msg);
751
+ case "tool_call":
752
+ return translateToolCallEvent(msg);
753
+ case "thinking":
754
+ return [
755
+ {
756
+ type: "thinking",
757
+ content: asString(msg.text, "")
758
+ }
759
+ ];
760
+ case "status":
761
+ return translateStatusEvent(msg);
762
+ case "request":
763
+ return [
764
+ {
765
+ type: "input_requested",
766
+ requestId: asString(msg.request_id, "")
767
+ }
768
+ ];
769
+ case "task": {
770
+ const status = typeof msg.status === "string" ? msg.status : void 0;
771
+ const text = typeof msg.text === "string" ? msg.text : void 0;
772
+ if (status === void 0 && text === void 0) return [];
773
+ return [
774
+ {
775
+ type: "task_progress",
776
+ ...status !== void 0 ? {
777
+ status
778
+ } : {},
779
+ ...text !== void 0 ? {
780
+ text
781
+ } : {}
782
+ }
783
+ ];
784
+ }
785
+ default:
786
+ warnIfUnknown(msg.type, SDK_MESSAGE_IGNORED);
787
+ return [];
788
+ }
789
+ }
790
+ __name(translateSdkEvent, "translateSdkEvent");
791
+ function translateInteractionUpdate(update) {
792
+ switch (update.type) {
793
+ case "text-delta":
794
+ return update.text ? [
795
+ {
796
+ type: "text_delta",
797
+ content: update.text
798
+ }
799
+ ] : [];
800
+ case "thinking-delta":
801
+ return update.text ? [
802
+ {
803
+ type: "thinking",
804
+ content: update.text
805
+ }
806
+ ] : [];
807
+ case "tool-call-started":
808
+ return [
809
+ {
810
+ type: "tool_call",
811
+ callId: update.callId,
812
+ toolName: update.toolCall.name,
813
+ input: update.toolCall.args ?? {}
814
+ }
815
+ ];
816
+ case "partial-tool-call":
817
+ return [
818
+ {
819
+ type: "partial_tool_call",
820
+ callId: update.callId,
821
+ toolName: update.toolCall.name,
822
+ input: update.toolCall.args ?? {}
823
+ }
824
+ ];
825
+ case "tool-call-completed":
826
+ return [
827
+ {
828
+ type: "tool_result",
829
+ callId: update.callId,
830
+ toolName: update.toolCall.name,
831
+ output: serializeToolOutput(update.toolCall.result, ""),
832
+ durationMs: 0,
833
+ // #388 — the same predicate, and on this shape it answers `false` for a reason rather
834
+ // than by decree: `ToolCall` (`@theokit/sdk/dist/types/updates.d.ts`) declares only
835
+ // `{callId, name, args?, result?}`, and the SDK fills `result` with `renderToolResult()`
836
+ // — a rendered string — so the exit code structurally cannot travel here. The message-
837
+ // shaped report of the same call is the one that carries it, and `dedupeTools` is what
838
+ // lets it contribute (`sdk-timeline.ts`).
839
+ isError: reportsToolFailure(update.toolCall.result)
840
+ }
841
+ ];
842
+ case "shell-output-delta":
843
+ return [
844
+ {
845
+ type: "shell_output",
846
+ event: update.event
847
+ }
848
+ ];
849
+ default:
850
+ warnIfUnknown(update.type, INTERACTION_UPDATE_IGNORED);
851
+ return [];
852
+ }
853
+ }
854
+ __name(translateInteractionUpdate, "translateInteractionUpdate");
855
+
577
856
  // src/bridge/sdk-adapter-create-options.ts
578
857
  import { createRequire } from "module";
579
858
  import { PermissionEngine, PermissionPlugin } from "@theokit/sdk";
@@ -802,344 +1081,84 @@ function assembleM8CreateOptions(compiled, deps = {}) {
802
1081
  options.context = compiled.context;
803
1082
  applied.push("context");
804
1083
  }
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
- });
939
- }
940
- }
941
- return events;
942
- }
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
- ];
961
- }
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
- ];
1084
+ if (compiled.projectContext) {
1085
+ options.systemPrompt = compileProjectContext(compiled.projectContext, base);
1086
+ applied.push("projectContext");
1087
+ } else if (base !== void 0) {
1088
+ options.systemPrompt = base;
973
1089
  }
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
- ];
1090
+ if (compiled.mcpServers && Object.keys(compiled.mcpServers).length > 0) {
1091
+ options.mcpServers = compiled.mcpServers;
1092
+ applied.push("mcpServers");
983
1093
  }
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
1094
+ if (compiled.memory !== void 0) {
1095
+ if ("enabled" in compiled.memory) {
1096
+ options.memory = compiled.memory;
1097
+ } else {
1098
+ const dropped = Object.keys(compiled.memory);
1099
+ if (dropped.length > 0) {
1100
+ process.stderr.write(`[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
1101
+ `);
1001
1102
  }
1002
- ];
1103
+ options.memory = {
1104
+ enabled: true
1105
+ };
1106
+ }
1107
+ applied.push("memory");
1003
1108
  }
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
- ];
1109
+ if (compiled.telemetry !== void 0) {
1110
+ options.telemetry = compiled.telemetry;
1111
+ applied.push("telemetry");
1013
1112
  }
1014
- return [];
1113
+ return {
1114
+ options,
1115
+ applied
1116
+ };
1015
1117
  }
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).`);
1118
+ __name(assembleM8CreateOptions, "assembleM8CreateOptions");
1119
+ function stopReasonOf(result) {
1120
+ if (result.stoppedByDoomLoop === true) return "no_progress";
1121
+ if (result.stoppedAtIterationLimit === true) return "step_limit";
1122
+ return void 0;
1022
1123
  }
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
- ];
1072
- }
1073
- default:
1074
- warnIfUnknown(msg.type, SDK_MESSAGE_IGNORED);
1075
- return [];
1076
- }
1124
+ __name(stopReasonOf, "stopReasonOf");
1125
+ function doneUsage(sdkUsage) {
1126
+ const usage = sdkUsage ?? {};
1127
+ const inputTokens = countOrZero(usage.inputTokens);
1128
+ const outputTokens = countOrZero(usage.outputTokens);
1129
+ return {
1130
+ inputTokens,
1131
+ outputTokens,
1132
+ totalTokens: inputTokens + outputTokens,
1133
+ reasoningTokens: countOrZero(usage.reasoningTokens),
1134
+ cacheReadTokens: countOrZero(usage.cacheReadTokens),
1135
+ cacheWriteTokens: countOrZero(usage.cacheWriteTokens)
1136
+ };
1077
1137
  }
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 [];
1140
- }
1138
+ __name(doneUsage, "doneUsage");
1139
+ function countOrZero(count) {
1140
+ return count ?? 0;
1141
1141
  }
1142
- __name(translateInteractionUpdate, "translateInteractionUpdate");
1142
+ __name(countOrZero, "countOrZero");
1143
+ function realUsageDone(result, t0, model) {
1144
+ const stopReason = stopReasonOf(result);
1145
+ return {
1146
+ type: "done",
1147
+ result: result.result ?? "",
1148
+ usage: doneUsage(result.usage),
1149
+ durationMs: Date.now() - t0,
1150
+ ...knownCost(result.cost),
1151
+ ...terminalExtras(stopReason, model)
1152
+ };
1153
+ }
1154
+ __name(realUsageDone, "realUsageDone");
1155
+ function terminalExtras(stopReason, model) {
1156
+ const extras = {};
1157
+ if (stopReason !== void 0) extras.stopReason = stopReason;
1158
+ if (model !== void 0) extras.model = model;
1159
+ return extras;
1160
+ }
1161
+ __name(terminalExtras, "terminalExtras");
1143
1162
 
1144
1163
  // src/bridge/think-tag-extractor.ts
1145
1164
  var TAG = "think";
@@ -1987,6 +2006,20 @@ var noopReflectionStrategy = {
1987
2006
 
1988
2007
  // src/bridge/delegation-types.ts
1989
2008
  import { TheokitAgentError as TheokitAgentError4 } from "@theokit/sdk/errors";
2009
+ function budgetMessage(agentName, actualCost, budgetLimit, refusal) {
2010
+ const limit = `$${budgetLimit.toFixed(4)}`;
2011
+ if (refusal === void 0) {
2012
+ return `Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > ${limit}`;
2013
+ }
2014
+ if ("nothingToSpend" in refusal) {
2015
+ return `Agent "${agentName}" stopped before its first round: its ${limit} limit leaves nothing to spend`;
2016
+ }
2017
+ if ("costUnknown" in refusal) {
2018
+ return `Agent "${agentName}" stopped before its next round: the cost of its last round is not known, so the ${limit} limit cannot be enforced (known spend $${actualCost.toFixed(4)})`;
2019
+ }
2020
+ return `Agent "${agentName}" stopped before its next round: spent $${actualCost.toFixed(4)}, next round projected at $${refusal.projectedRoundCost.toFixed(4)}, which would pass the ${limit} limit`;
2021
+ }
2022
+ __name(budgetMessage, "budgetMessage");
1990
2023
  var DelegationBudgetExceededError = class extends TheokitAgentError4 {
1991
2024
  static {
1992
2025
  __name(this, "DelegationBudgetExceededError");
@@ -1995,12 +2028,25 @@ var DelegationBudgetExceededError = class extends TheokitAgentError4 {
1995
2028
  actualCost;
1996
2029
  budgetLimit;
1997
2030
  name = "DelegationBudgetExceededError";
1998
- constructor(agentName, actualCost, budgetLimit) {
1999
- super(`Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`, {
2031
+ /** The cost the refused round was projected at; absent when the spend already passed the limit. */
2032
+ projectedRoundCost;
2033
+ constructor(agentName, actualCost, budgetLimit, refusal) {
2034
+ super(budgetMessage(agentName, actualCost, budgetLimit, refusal), {
2000
2035
  code: "DELEGATION_BUDGET_EXCEEDED",
2001
2036
  // The budget does not refill on retry.
2002
2037
  isRetryable: false
2003
2038
  }), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
2039
+ this.projectedRoundCost = refusal !== void 0 && "projectedRoundCost" in refusal ? refusal.projectedRoundCost : void 0;
2040
+ }
2041
+ };
2042
+ var DelegationBudgetCostUnknownError = class extends DelegationBudgetExceededError {
2043
+ static {
2044
+ __name(this, "DelegationBudgetCostUnknownError");
2045
+ }
2046
+ constructor(agentName, knownSpend, budgetLimit) {
2047
+ super(agentName, knownSpend, budgetLimit, {
2048
+ costUnknown: true
2049
+ });
2004
2050
  }
2005
2051
  };
2006
2052
  var BudgetExceededError = DelegationBudgetExceededError;
@@ -2049,15 +2095,101 @@ async function* mirrorModeratedText(inner) {
2049
2095
  }
2050
2096
  __name(mirrorModeratedText, "mirrorModeratedText");
2051
2097
 
2098
+ // src/loop/run-budget.ts
2099
+ function refuseNextRound(spent, lastRound, ceiling, agentName) {
2100
+ if (!Number.isFinite(ceiling)) return void 0;
2101
+ if (!lastRound.costKnown) return new DelegationBudgetCostUnknownError(agentName, spent, ceiling);
2102
+ if (spent + lastRound.cost > ceiling) {
2103
+ return new DelegationBudgetExceededError(agentName, spent, ceiling, {
2104
+ projectedRoundCost: lastRound.cost
2105
+ });
2106
+ }
2107
+ return void 0;
2108
+ }
2109
+ __name(refuseNextRound, "refuseNextRound");
2110
+ function throwIfNextRoundRefused(spent, lastRound, ceiling, agentName, signal) {
2111
+ if (signal?.aborted) return;
2112
+ const refusal = refuseNextRound(spent, lastRound, ceiling, agentName);
2113
+ if (refusal) throw refusal;
2114
+ }
2115
+ __name(throwIfNextRoundRefused, "throwIfNextRoundRefused");
2116
+ function resolveRunBudget(budget, agentName, name = "budget") {
2117
+ if (budget == null) return void 0;
2118
+ let field = name;
2119
+ let ceiling = budget;
2120
+ if (typeof budget !== "number") {
2121
+ if (budget.window !== void 0) {
2122
+ throw new DelegationError(agentName, new Error(`${name}.window is not supported: a rolling budget needs spend persisted across runs`));
2123
+ }
2124
+ field = `${name}.maxCostUsd`;
2125
+ ceiling = budget.maxCostUsd;
2126
+ }
2127
+ if (typeof ceiling !== "number" || Number.isNaN(ceiling)) {
2128
+ throw new DelegationError(agentName, new Error(`${field} must be a number, got ${String(ceiling)}`));
2129
+ }
2130
+ if (ceiling <= 0) {
2131
+ throw new DelegationBudgetExceededError(agentName, 0, ceiling, {
2132
+ nothingToSpend: true
2133
+ });
2134
+ }
2135
+ return ceiling;
2136
+ }
2137
+ __name(resolveRunBudget, "resolveRunBudget");
2138
+
2139
+ // src/loop/round-usage.ts
2140
+ var TOKEN_BUCKETS = [
2141
+ "tokensInput",
2142
+ "tokensOutput",
2143
+ "reasoningTokens",
2144
+ "cacheReadTokens",
2145
+ "cacheWriteTokens"
2146
+ ];
2147
+ var DONE_USAGE_FIELDS = [
2148
+ [
2149
+ "tokens",
2150
+ "totalTokens"
2151
+ ],
2152
+ [
2153
+ "tokensInput",
2154
+ "inputTokens"
2155
+ ],
2156
+ [
2157
+ "tokensOutput",
2158
+ "outputTokens"
2159
+ ],
2160
+ [
2161
+ "reasoningTokens",
2162
+ "reasoningTokens"
2163
+ ],
2164
+ [
2165
+ "cacheReadTokens",
2166
+ "cacheReadTokens"
2167
+ ],
2168
+ [
2169
+ "cacheWriteTokens",
2170
+ "cacheWriteTokens"
2171
+ ]
2172
+ ];
2173
+ function applyDone(event, r) {
2174
+ r.costKnown = typeof event.cost === "number" && Number.isFinite(event.cost);
2175
+ r.cost = r.costKnown ? event.cost : 0;
2176
+ const usage = event.usage ?? {};
2177
+ for (const [field, key] of DONE_USAGE_FIELDS) r[field] = usage[key] ?? 0;
2178
+ }
2179
+ __name(applyDone, "applyDone");
2180
+ function accumulateUsage(acc, r) {
2181
+ acc.cost += r.cost;
2182
+ if (!r.costKnown) acc.costUnknown = true;
2183
+ acc.tokens += r.tokens;
2184
+ for (const bucket of TOKEN_BUCKETS) acc[bucket] = (acc[bucket] ?? 0) + r[bucket];
2185
+ }
2186
+ __name(accumulateUsage, "accumulateUsage");
2187
+
2052
2188
  // src/loop/run-reflective-loop.ts
2053
2189
  function asString2(value, fallback) {
2054
2190
  return typeof value === "string" ? value : fallback;
2055
2191
  }
2056
2192
  __name(asString2, "asString");
2057
- function asNumber(value, fallback) {
2058
- return typeof value === "number" ? value : fallback;
2059
- }
2060
- __name(asNumber, "asNumber");
2061
2193
  var NO_PROGRESS_THRESHOLD = 2;
2062
2194
  var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
2063
2195
  var TOOL_CALLS = "tool-calls";
@@ -2102,16 +2234,6 @@ async function* consumeRoundOrThrow(inputs, agentName) {
2102
2234
  }
2103
2235
  }
2104
2236
  __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
2237
  function finalize(acc, round, reason, strategyName) {
2116
2238
  acc.rounds = round;
2117
2239
  acc.finishReason = reason;
@@ -2143,17 +2265,6 @@ function pushToolResult(event, r, callInputs) {
2143
2265
  });
2144
2266
  }
2145
2267
  __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
2268
  function accumulateEvent(event, r, signals, callInputs) {
2158
2269
  if (event.type === "text_delta" && typeof event.content === "string") {
2159
2270
  r.responseText += event.content;
@@ -2201,6 +2312,7 @@ async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
2201
2312
  responseText: "",
2202
2313
  toolCalls: [],
2203
2314
  cost: 0,
2315
+ costKnown: false,
2204
2316
  tokens: 0,
2205
2317
  tokensInput: 0,
2206
2318
  tokensOutput: 0,
@@ -2292,6 +2404,7 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2292
2404
  const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
2293
2405
  return finalize(acc, round, reason, loop.name);
2294
2406
  }
2407
+ throwIfNextRoundRefused(acc.cost, r, budget, agentName, signal);
2295
2408
  feedback = reflectionResult.feedback;
2296
2409
  round += 1;
2297
2410
  }
@@ -2355,9 +2468,13 @@ var AgentRunner = class {
2355
2468
  * builder set `.stream(false)`, callers should use {@link run} instead.
2356
2469
  */
2357
2470
  stream(message, opts) {
2471
+ const runOpts = {
2472
+ ...opts,
2473
+ budget: resolveRunBudget(opts.budget, this.agentName)
2474
+ };
2358
2475
  const guardrails = this.compiled.guardrails;
2359
2476
  if (guardrails && guardrails.length > 0) {
2360
- const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, opts), "runUnguarded");
2477
+ const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, runOpts), "runUnguarded");
2361
2478
  return (/* @__PURE__ */ __name(async function* guarded() {
2362
2479
  const safe = await runInputGuards(message, guardrails);
2363
2480
  return yield* mirrorModeratedText(
@@ -2409,7 +2526,7 @@ var AgentRunner = class {
2409
2526
  );
2410
2527
  }, "guarded"))();
2411
2528
  }
2412
- return this.streamUnguarded(message, opts);
2529
+ return this.streamUnguarded(message, runOpts);
2413
2530
  }
2414
2531
  /** The core stream path, after input guardrails have run (M9). */
2415
2532
  streamUnguarded(message, opts) {
@@ -2702,6 +2819,7 @@ function mergeTools(parentTools, subTools) {
2702
2819
  __name(mergeTools, "mergeTools");
2703
2820
  async function delegate(spec, message, opts = {}) {
2704
2821
  const apiKey = requireApiKey(opts, spec.name);
2822
+ const budget = Math.min(resolveRunBudget(opts.budget, spec.name) ?? Infinity, resolveRunBudget(opts.parentBudgetRemaining, spec.name, "parentBudgetRemaining") ?? Infinity);
2705
2823
  const rewritten = opts.onDelegationStart ? await opts.onDelegationStart({
2706
2824
  subAgent: spec.name,
2707
2825
  input: message
@@ -2710,7 +2828,6 @@ async function delegate(spec, message, opts = {}) {
2710
2828
  const guardrails = compiled.guardrails ?? [];
2711
2829
  const effectiveMessage = await runInputGuards(rewritten, guardrails);
2712
2830
  const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
2713
- const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
2714
2831
  const compiledForMember = withInheritedHooks(compiled, opts.parentHooks);
2715
2832
  const streamFactory = opts.streamFactory ?? createSdkAgentStream(compiledForMember, allTools, apiKey, {
2716
2833
  model: opts.model ?? compiled.model,
@@ -2887,9 +3004,9 @@ export {
2887
3004
  textPayloadExtractor,
2888
3005
  buildModelSelection,
2889
3006
  reasoningEffortOf,
3007
+ translateSdkEvent,
2890
3008
  HookGateUnsupportedError,
2891
3009
  CompatImportUnsupportedError,
2892
- translateSdkEvent,
2893
3010
  createThinkTagExtractor,
2894
3011
  extractThinkTagStream,
2895
3012
  createSdkAgentStream,
@@ -2905,6 +3022,7 @@ export {
2905
3022
  ladderReflectionStrategy,
2906
3023
  noopReflectionStrategy,
2907
3024
  DelegationBudgetExceededError,
3025
+ DelegationBudgetCostUnknownError,
2908
3026
  BudgetExceededError,
2909
3027
  DelegationError,
2910
3028
  AgentRunner,
@@ -2924,4 +3042,4 @@ export {
2924
3042
  delegateBackground,
2925
3043
  delegateWithScoring
2926
3044
  };
2927
- //# sourceMappingURL=chunk-RAN4PBUL.js.map
3045
+ //# sourceMappingURL=chunk-4PHZ25JN.js.map