@spencerboucher/switchyard 0.11.0 → 0.12.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 (101) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/agent-channel.js +449 -0
  3. package/dist/bridge/agent-tools.js +235 -0
  4. package/dist/bridge/message-delivery.js +185 -0
  5. package/dist/bridge/policy.js +213 -0
  6. package/dist/bridge/switchyard-bridge.js +73 -3
  7. package/dist/bridge/switchyard-terminal.js +77 -11
  8. package/dist/bridge/tool-preflight.js +155 -0
  9. package/dist/policies/worker.js +2877 -0
  10. package/dist/switchyard.mjs +15943 -7214
  11. package/package.json +3 -1
  12. package/web-dist/assets/AutomationView-BRVq9y-T.js +2 -0
  13. package/web-dist/assets/AutomationView-BRVq9y-T.js.map +1 -0
  14. package/web-dist/assets/{Card-XMb6DfZU.js → Card-BqrWFEYY.js} +2 -2
  15. package/web-dist/assets/{Card-XMb6DfZU.js.map → Card-BqrWFEYY.js.map} +1 -1
  16. package/web-dist/assets/{Checkbox-CeUPbVi7.js → Checkbox-DExv3fUO.js} +2 -2
  17. package/web-dist/assets/{Checkbox-CeUPbVi7.js.map → Checkbox-DExv3fUO.js.map} +1 -1
  18. package/web-dist/assets/{Copy-CGnl0Vga.js → Copy-BuBbxEQI.js} +2 -2
  19. package/web-dist/assets/{Copy-CGnl0Vga.js.map → Copy-BuBbxEQI.js.map} +1 -1
  20. package/web-dist/assets/{InteractionCard-1ePc4XOF.js → InteractionCard-0PH6pIkH.js} +4 -4
  21. package/web-dist/assets/{InteractionCard-1ePc4XOF.js.map → InteractionCard-0PH6pIkH.js.map} +1 -1
  22. package/web-dist/assets/{Menu-CYZQ97c0.js → Menu-BJ3Gyh5V.js} +2 -2
  23. package/web-dist/assets/{Menu-CYZQ97c0.js.map → Menu-BJ3Gyh5V.js.map} +1 -1
  24. package/web-dist/assets/{Overlay-DlLhg1cK.js → Overlay-BgqVqKc6.js} +2 -2
  25. package/web-dist/assets/{Overlay-DlLhg1cK.js.map → Overlay-BgqVqKc6.js.map} +1 -1
  26. package/web-dist/assets/{Priority-BCHLJqWN.js → Priority-B2tdgI2D.js} +2 -2
  27. package/web-dist/assets/{Priority-BCHLJqWN.js.map → Priority-B2tdgI2D.js.map} +1 -1
  28. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js → SegmentedControl-DzwdZG6q.js} +2 -2
  29. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js.map → SegmentedControl-DzwdZG6q.js.map} +1 -1
  30. package/web-dist/assets/{Select-Dgmnmpz3.js → Select-DZ-qJ_AO.js} +2 -2
  31. package/web-dist/assets/{Select-Dgmnmpz3.js.map → Select-DZ-qJ_AO.js.map} +1 -1
  32. package/web-dist/assets/{Switch-DS4NRENd.js → Switch-DKiwAXXz.js} +2 -2
  33. package/web-dist/assets/{Switch-DS4NRENd.js.map → Switch-DKiwAXXz.js.map} +1 -1
  34. package/web-dist/assets/{Tabs-9xp-tGja.js → Tabs-HOeWNnHD.js} +2 -2
  35. package/web-dist/assets/{Tabs-9xp-tGja.js.map → Tabs-HOeWNnHD.js.map} +1 -1
  36. package/web-dist/assets/{TextArea-PfVKaz29.js → TextArea-DK1uv3xX.js} +2 -2
  37. package/web-dist/assets/{TextArea-PfVKaz29.js.map → TextArea-DK1uv3xX.js.map} +1 -1
  38. package/web-dist/assets/{TextLink-CYqiAUlK.js → TextLink-BoFPQuaH.js} +2 -2
  39. package/web-dist/assets/{TextLink-CYqiAUlK.js.map → TextLink-BoFPQuaH.js.map} +1 -1
  40. package/web-dist/assets/attention-D1G0KCOr.js +2 -0
  41. package/web-dist/assets/{attention-CTkX5JXq.js.map → attention-D1G0KCOr.js.map} +1 -1
  42. package/web-dist/assets/automations-DUUAfMK8.js +2 -0
  43. package/web-dist/assets/{automations-CsdtA3xp.js.map → automations-DUUAfMK8.js.map} +1 -1
  44. package/web-dist/assets/board-tIuyEKO0.js +10 -0
  45. package/web-dist/assets/board-tIuyEKO0.js.map +1 -0
  46. package/web-dist/assets/code-O-DyPB50.js +25 -0
  47. package/web-dist/assets/code-O-DyPB50.js.map +1 -0
  48. package/web-dist/assets/{describe-DjRsBpcB.js → describe-BW5uUuvy.js} +3 -3
  49. package/web-dist/assets/{describe-DjRsBpcB.js.map → describe-BW5uUuvy.js.map} +1 -1
  50. package/web-dist/assets/enroll-CL0BGGhd.js +2 -0
  51. package/web-dist/assets/{enroll-DcEYGgoX.js.map → enroll-CL0BGGhd.js.map} +1 -1
  52. package/web-dist/assets/index-D-JHf__5.css +2 -0
  53. package/web-dist/assets/{index-DSJZdQ79.js → index-K0QOY1Li.js} +4 -4
  54. package/web-dist/assets/{index-DSJZdQ79.js.map → index-K0QOY1Li.js.map} +1 -1
  55. package/web-dist/assets/{more-BQSa_-H6.js → more-DNN_mtX8.js} +2 -2
  56. package/web-dist/assets/{more-BQSa_-H6.js.map → more-DNN_mtX8.js.map} +1 -1
  57. package/web-dist/assets/policyLogic-BKSj6mhC.js +2 -0
  58. package/web-dist/assets/policyLogic-BKSj6mhC.js.map +1 -0
  59. package/web-dist/assets/{preload-helper-Huh16h6r.js → preload-helper-BudhqmWi.js} +4 -4
  60. package/web-dist/assets/{preload-helper-Huh16h6r.js.map → preload-helper-BudhqmWi.js.map} +1 -1
  61. package/web-dist/assets/{queue-CCjBjQhT.js → queue-k4o-I9uY.js} +2 -2
  62. package/web-dist/assets/{queue-CCjBjQhT.js.map → queue-k4o-I9uY.js.map} +1 -1
  63. package/web-dist/assets/{repo-pkFfpra6.js → repo-CSQAnBaF.js} +2 -2
  64. package/web-dist/assets/{repo-pkFfpra6.js.map → repo-CSQAnBaF.js.map} +1 -1
  65. package/web-dist/assets/settings-CrYZRJ7E.js +7 -0
  66. package/web-dist/assets/settings-CrYZRJ7E.js.map +1 -0
  67. package/web-dist/assets/shared-DIA598ns.js +3 -0
  68. package/web-dist/assets/shared-DIA598ns.js.map +1 -0
  69. package/web-dist/assets/states-C8oEFqek.js +58 -0
  70. package/web-dist/assets/states-C8oEFqek.js.map +1 -0
  71. package/web-dist/assets/{terminal-login-D9enO0EH.js → terminal-login-M5orrPPe.js} +2 -2
  72. package/web-dist/assets/{terminal-login-D9enO0EH.js.map → terminal-login-M5orrPPe.js.map} +1 -1
  73. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js → useBreakpoint-CA0Mbmvv.js} +2 -2
  74. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js.map → useBreakpoint-CA0Mbmvv.js.map} +1 -1
  75. package/web-dist/assets/useNow-Dx0MCCez.js +2 -0
  76. package/web-dist/assets/useNow-Dx0MCCez.js.map +1 -0
  77. package/web-dist/assets/{useResource-Dul6MTDM.js → useResource-BTjwa4tV.js} +2 -2
  78. package/web-dist/assets/{useResource-Dul6MTDM.js.map → useResource-BTjwa4tV.js.map} +1 -1
  79. package/web-dist/index.html +8 -8
  80. package/web-dist/sw.js +1 -1
  81. package/web-dist/sw.js.map +1 -1
  82. package/web-dist/assets/AutomationView-CrKqim2i.js +0 -2
  83. package/web-dist/assets/AutomationView-CrKqim2i.js.map +0 -1
  84. package/web-dist/assets/Field-DVurWE-E.js +0 -2
  85. package/web-dist/assets/Field-DVurWE-E.js.map +0 -1
  86. package/web-dist/assets/attention-CTkX5JXq.js +0 -2
  87. package/web-dist/assets/automations-CsdtA3xp.js +0 -2
  88. package/web-dist/assets/board-CJL75uGb.js +0 -10
  89. package/web-dist/assets/board-CJL75uGb.js.map +0 -1
  90. package/web-dist/assets/code-CEYPZt-J.js +0 -21
  91. package/web-dist/assets/code-CEYPZt-J.js.map +0 -1
  92. package/web-dist/assets/enroll-DcEYGgoX.js +0 -2
  93. package/web-dist/assets/index-BeJqGnFE.css +0 -2
  94. package/web-dist/assets/settings-vrxspmWN.js +0 -7
  95. package/web-dist/assets/settings-vrxspmWN.js.map +0 -1
  96. package/web-dist/assets/shared-Bm6Rhfqw.js +0 -3
  97. package/web-dist/assets/shared-Bm6Rhfqw.js.map +0 -1
  98. package/web-dist/assets/states-BQxrRFdh.js +0 -56
  99. package/web-dist/assets/states-BQxrRFdh.js.map +0 -1
  100. package/web-dist/assets/useNow-BUvGqrfn.js +0 -2
  101. package/web-dist/assets/useNow-BUvGqrfn.js.map +0 -1
@@ -8,7 +8,12 @@
8
8
  * never throws: any socket error disables forwarding for the rest of the process.
9
9
  */
10
10
  import { createConnection } from "node:net";
11
+ import { createAgentChannel } from "./agent-channel.js";
12
+ import { registerAgentTools } from "./agent-tools.js";
13
+ import { LineSplitter } from "./lines.js";
14
+ import { createMessageDelivery } from "./message-delivery.js";
11
15
  import { modelInfo } from "./pi-model.js";
16
+ import { installPolicyHooks } from "./policy.js";
12
17
  export default function switchyardBridge(pi) {
13
18
  const socketPath = process.env.SWITCHYARD_BRIDGE_SOCKET;
14
19
  if (!socketPath)
@@ -16,6 +21,40 @@ export default function switchyardBridge(pi) {
16
21
  let socket = null;
17
22
  let disabled = false;
18
23
  let seq = 0;
24
+ let ctx = null;
25
+ let dialogs = 0;
26
+ let toolPolicy = false;
27
+ const channel = createAgentChannel({
28
+ send: (record) => {
29
+ try {
30
+ if (!socket || socket.destroyed || socket.connecting)
31
+ return false;
32
+ socket.write(`${JSON.stringify(record)}\n`);
33
+ return true;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ },
39
+ getContext: () => ctx,
40
+ appendEntry: (customType, data) => pi.appendEntry(customType, data),
41
+ mode: "rpc",
42
+ getCapabilities: () => ({
43
+ agentTools: true,
44
+ messageDelivery: true,
45
+ editorDraftGuard: true,
46
+ toolPolicy,
47
+ }),
48
+ policyRequired: process.env.SWITCHYARD_POLICY_REQUIRED === "1",
49
+ });
50
+ toolPolicy = installPolicyHooks(pi, channel);
51
+ registerAgentTools(pi, channel);
52
+ const delivery = createMessageDelivery(pi, {
53
+ channel,
54
+ getContext: () => ctx,
55
+ isDialogOpen: () => dialogs > 0,
56
+ mode: "rpc",
57
+ });
19
58
  const ensureSocket = () => {
20
59
  if (disabled)
21
60
  return null;
@@ -23,7 +62,23 @@ export default function switchyardBridge(pi) {
23
62
  return socket;
24
63
  try {
25
64
  const s = createConnection(socketPath);
65
+ const lines = new LineSplitter((line) => {
66
+ try {
67
+ const record = JSON.parse(line);
68
+ if (record?.type === "control_attached")
69
+ channel.onControlAttached();
70
+ else
71
+ channel.receive(record);
72
+ }
73
+ catch {
74
+ // Ignore malformed records.
75
+ }
76
+ });
77
+ s.setEncoding("utf8");
78
+ s.on("data", (chunk) => lines.push(chunk));
79
+ s.on("connect", () => channel.onConnect());
26
80
  s.on("error", () => {
81
+ channel.onDisconnect();
27
82
  disabled = true;
28
83
  try {
29
84
  s.destroy();
@@ -33,6 +88,7 @@ export default function switchyardBridge(pi) {
33
88
  }
34
89
  });
35
90
  s.on("close", () => {
91
+ channel.onDisconnect();
36
92
  // A clean close (session_shutdown) allows a later reconnect; errors disabled us above.
37
93
  if (socket === s)
38
94
  socket = null;
@@ -97,7 +153,8 @@ export default function switchyardBridge(pi) {
97
153
  }
98
154
  };
99
155
  try {
100
- pi.on("session_start", (_event, ctx) => {
156
+ pi.on("session_start", (_event, current) => {
157
+ ctx = current;
101
158
  try {
102
159
  ensureSocket();
103
160
  }
@@ -105,12 +162,25 @@ export default function switchyardBridge(pi) {
105
162
  disabled = true;
106
163
  }
107
164
  sendModelState(ctx);
165
+ channel.announce();
108
166
  });
109
167
  pi.on("model_select", (_event, ctx) => sendModelState(ctx));
110
168
  pi.on("thinking_level_select", (_event, ctx) => sendModelState(ctx));
111
- pi.on("ui_prompt_start", forward);
112
- pi.on("ui_prompt_end", forward);
169
+ pi.on("ui_prompt_start", (event) => {
170
+ dialogs++;
171
+ forward(event);
172
+ });
173
+ pi.on("ui_prompt_end", (event) => {
174
+ dialogs = Math.max(0, dialogs - 1);
175
+ forward(event);
176
+ });
177
+ pi.on("input", (event) => {
178
+ if (event?.source === "interactive")
179
+ channel.noteHumanInput();
180
+ });
113
181
  pi.on("session_shutdown", () => {
182
+ delivery.close();
183
+ channel.close();
114
184
  try {
115
185
  socket?.end();
116
186
  }
@@ -17,8 +17,12 @@
17
17
  */
18
18
  import { randomUUID } from "node:crypto";
19
19
  import { createConnection } from "node:net";
20
+ import { createAgentChannel } from "./agent-channel.js";
21
+ import { registerAgentTools } from "./agent-tools.js";
20
22
  import { LineSplitter } from "./lines.js";
23
+ import { createMessageDelivery } from "./message-delivery.js";
21
24
  import { modelInfo } from "./pi-model.js";
25
+ import { installPolicyHooks } from "./policy.js";
22
26
  const PATCHED = Symbol.for("switchyard.terminal");
23
27
  const WRAPPED = Symbol.for("switchyard.terminal.wrapped");
24
28
  const REMOTE_UI_CHANNEL = "switchyard.remote-ui.v1";
@@ -111,6 +115,46 @@ export default function switchyardTerminal(pi) {
111
115
  const queue = { steering: [], followUp: [] };
112
116
  let socket = null;
113
117
  let remoteBacked = 0;
118
+ let nativeDialogs = 0;
119
+ let toolPolicy = false;
120
+ const channel = createAgentChannel({
121
+ send: (record) => {
122
+ try {
123
+ if (!socket || socket.destroyed || socket.connecting)
124
+ return false;
125
+ socket.write(`${JSON.stringify(record)}\n`);
126
+ return true;
127
+ }
128
+ catch {
129
+ return false;
130
+ }
131
+ },
132
+ getContext: () => ctx,
133
+ appendEntry: (customType, data) => pi.appendEntry(customType, data),
134
+ mode: "terminal",
135
+ getCapabilities: () => ({
136
+ agentTools: true,
137
+ messageDelivery: true,
138
+ editorDraftGuard: (() => {
139
+ try {
140
+ return typeof ctx?.ui?.getEditorText?.() === "string";
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ })(),
146
+ toolPolicy,
147
+ }),
148
+ policyRequired: process.env.SWITCHYARD_POLICY_REQUIRED === "1",
149
+ });
150
+ toolPolicy = installPolicyHooks(pi, channel);
151
+ registerAgentTools(pi, channel);
152
+ const delivery = createMessageDelivery(pi, {
153
+ channel,
154
+ getContext: () => ctx,
155
+ isDialogOpen: () => nativeDialogs > 0 || pending.size > 0,
156
+ mode: "terminal",
157
+ });
114
158
  const send = (obj) => {
115
159
  try {
116
160
  if (!socket || socket.destroyed)
@@ -685,6 +729,8 @@ export default function switchyardTerminal(pi) {
685
729
  }
686
730
  if (!msg || typeof msg !== "object")
687
731
  return;
732
+ if (channel.receive(msg))
733
+ return;
688
734
  if (msg.type === "extension_ui_response") {
689
735
  pending.get(String(msg.id))?.onRemote(msg);
690
736
  return;
@@ -693,6 +739,7 @@ export default function switchyardTerminal(pi) {
693
739
  // A controller re-attached (host agent restart): it starts from scratch, so announce the
694
740
  // session again before re-sending the dialogs it has not answered.
695
741
  announce();
742
+ channel.onControlAttached();
696
743
  return;
697
744
  }
698
745
  if (typeof msg.type === "string" && msg.id !== undefined)
@@ -720,14 +767,19 @@ export default function switchyardTerminal(pi) {
720
767
  connected = true;
721
768
  if (attempt > 1)
722
769
  announce();
770
+ channel.onConnect();
723
771
  });
724
772
  s.on("error", () => {
725
- if (socket === s)
773
+ if (socket === s) {
774
+ channel.onDisconnect();
726
775
  socket = null;
776
+ }
727
777
  });
728
778
  s.on("close", () => {
729
- if (socket === s)
779
+ if (socket === s) {
780
+ channel.onDisconnect();
730
781
  socket = null;
782
+ }
731
783
  if (!connected && attempt < CONNECT_ATTEMPTS) {
732
784
  setTimeout(() => connect(attempt + 1), CONNECT_RETRY_MS).unref();
733
785
  }
@@ -783,6 +835,7 @@ export default function switchyardTerminal(pi) {
783
835
  hello();
784
836
  sendModelState();
785
837
  sendLeaf();
838
+ channel.announce();
786
839
  if (event?.reason && event.reason !== "startup") {
787
840
  send({ type: "switchyard_native", sessionId, sessionFile });
788
841
  }
@@ -848,16 +901,29 @@ export default function switchyardTerminal(pi) {
848
901
  on("model_select", () => sendModelState());
849
902
  on("thinking_level_select", () => sendModelState());
850
903
  on("session_before_compact", (event) => send({ type: "compaction_start", reason: event?.reason ?? "manual" }));
851
- on("ui_prompt_start", (event) => send({
852
- type: "ui_prompt",
853
- event: event.type,
854
- kind: event.kind,
855
- title: event.title ?? null,
856
- remoteBacked: event.kind === "custom" && remoteBacked > 0,
857
- }));
858
- on("ui_prompt_end", (event) => send({ type: "ui_prompt", event: event.type, kind: event.kind, title: event.title ?? null }));
904
+ on("ui_prompt_start", (event) => {
905
+ nativeDialogs++;
906
+ send({
907
+ type: "ui_prompt",
908
+ event: event.type,
909
+ kind: event.kind,
910
+ title: event.title ?? null,
911
+ remoteBacked: event.kind === "custom" && remoteBacked > 0,
912
+ });
913
+ });
914
+ on("ui_prompt_end", (event) => {
915
+ nativeDialogs = Math.max(0, nativeDialogs - 1);
916
+ send({ type: "ui_prompt", event: event.type, kind: event.kind, title: event.title ?? null });
917
+ });
918
+ on("session_shutdown", () => {
919
+ delivery.close();
920
+ channel.close();
921
+ });
859
922
  on("input", (event) => {
860
- if (event?.source !== "interactive" || !event.streamingBehavior)
923
+ if (event?.source !== "interactive")
924
+ return;
925
+ channel.noteHumanInput();
926
+ if (!event.streamingBehavior)
861
927
  return;
862
928
  (event.streamingBehavior === "steer" ? queue.steering : queue.followUp).push(String(event.text ?? ""));
863
929
  sendQueue();
@@ -0,0 +1,155 @@
1
+ import { channelError } from "./agent-channel.js";
2
+ export class DuplicateAgentToolPreflightError extends Error {
3
+ constructor() {
4
+ super("Tool preflight is already active");
5
+ this.name = "DuplicateAgentToolPreflightError";
6
+ }
7
+ }
8
+ const states = new WeakMap();
9
+ const key = (method, toolCallId) => JSON.stringify([method, toolCallId]);
10
+ function state(channel) {
11
+ let value = states.get(channel);
12
+ if (!value) {
13
+ value = { methods: new Map(), invocations: new Map(), protected: false };
14
+ states.set(channel, value);
15
+ }
16
+ return value;
17
+ }
18
+ /** Register only names belonging to the actual Switchyard tool adapters. */
19
+ export function registerAgentToolMethod(channel, name, method) {
20
+ state(channel).methods.set(name, method);
21
+ }
22
+ export function agentToolMethod(channel, name) {
23
+ return state(channel).methods.get(name);
24
+ }
25
+ export function requireAgentToolPreflight(channel) {
26
+ state(channel).protected = true;
27
+ }
28
+ export function agentToolPreflightRequired(channel) {
29
+ const current = channel.snapshot();
30
+ return (state(channel).protected ||
31
+ current.policyRequired ||
32
+ current.policyState === "active" ||
33
+ current.policyState === "lost");
34
+ }
35
+ function cloneJson(value, ancestors = new Set(), depth = 0) {
36
+ if (depth > 20)
37
+ throw new Error("Policy tool input is too deeply nested.");
38
+ if (value === null || typeof value === "string" || typeof value === "boolean")
39
+ return value;
40
+ if (typeof value === "number" &&
41
+ Number.isFinite(value) &&
42
+ (!Number.isInteger(value) || Number.isSafeInteger(value)))
43
+ return value;
44
+ if (typeof value !== "object" || value === null || ancestors.has(value))
45
+ throw new Error("Policy tool input must be JSON.");
46
+ const prototype = Object.getPrototypeOf(value);
47
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
48
+ throw new Error("Policy tool input must be a plain JSON object.");
49
+ ancestors.add(value);
50
+ try {
51
+ if (Array.isArray(value))
52
+ return Array.from(value, (v) => cloneJson(v, ancestors, depth + 1));
53
+ const result = {};
54
+ for (const k of Object.keys(value).sort()) {
55
+ if (k === "__proto__" || k === "constructor" || k === "prototype")
56
+ throw new Error("Policy tool input contains a forbidden key.");
57
+ result[k] = cloneJson(value[k], ancestors, depth + 1);
58
+ }
59
+ return result;
60
+ }
61
+ finally {
62
+ ancestors.delete(value);
63
+ }
64
+ }
65
+ export function toolArgs(input) {
66
+ const args = cloneJson(input);
67
+ if (!args || typeof args !== "object" || Array.isArray(args))
68
+ throw new Error("Policy tool input must be a JSON object.");
69
+ return args;
70
+ }
71
+ function sameBinding(a, b) {
72
+ return (a.sessionId === b.sessionId &&
73
+ a.runtimeId === b.runtimeId &&
74
+ a.nativeSessionId === b.nativeSessionId &&
75
+ a.bindingId === b.bindingId);
76
+ }
77
+ /** Reserve before awaiting lookup/approval; active records are never evicted or overwritten. */
78
+ export function beginAgentToolPreflight(channel, method, toolCallId, args, signal) {
79
+ const invocations = state(channel).invocations;
80
+ const id = key(method, toolCallId);
81
+ if (invocations.has(id))
82
+ throw new DuplicateAgentToolPreflightError();
83
+ if (signal?.aborted)
84
+ throw channelError("conflict", "Policy approval canceled");
85
+ if (invocations.size >= 64)
86
+ throw channelError("rate_limited", "Too many active tool preflights");
87
+ const immutableArgs = JSON.stringify(toolArgs(args));
88
+ const configuration = channel.snapshot().configuration;
89
+ const owner = Object.freeze({ method, toolCallId, token: Symbol("tool-preflight") });
90
+ const abort = () => releaseAgentToolPreflight(channel, owner);
91
+ invocations.set(id, {
92
+ owner,
93
+ phase: "checking",
94
+ preflight: null,
95
+ args: immutableArgs,
96
+ binding: configuration ? Object.freeze({ ...configuration }) : null,
97
+ cleanup: () => signal?.removeEventListener("abort", abort),
98
+ });
99
+ signal?.addEventListener("abort", abort, { once: true });
100
+ return owner;
101
+ }
102
+ export function rememberAgentToolPreflight(channel, owner, preflight) {
103
+ const invocation = state(channel).invocations.get(key(owner.method, owner.toolCallId));
104
+ if (invocation?.owner.token !== owner.token || invocation.phase !== "checking")
105
+ throw channelError("conflict", "Tool preflight is missing or already finalized");
106
+ const current = channel.snapshot().configuration;
107
+ if (preflight.method !== owner.method ||
108
+ preflight.toolCallId !== owner.toolCallId ||
109
+ !current ||
110
+ !sameBinding(current, preflight.binding) ||
111
+ (invocation.binding && !sameBinding(invocation.binding, preflight.binding)))
112
+ throw channelError("conflict", "Tool action does not match its preflight binding");
113
+ if (preflight.mode === "receipt" && !/^[a-f0-9]{64}$/.test(preflight.requestHash))
114
+ throw channelError("invalid_request", "Invalid recorded tool result hash");
115
+ invocation.preflight = Object.freeze({
116
+ ...preflight,
117
+ binding: Object.freeze({ ...preflight.binding }),
118
+ });
119
+ invocation.phase = "armed";
120
+ }
121
+ export function consumeAgentToolPreflight(channel, method, toolCallId, args) {
122
+ const invocation = state(channel).invocations.get(key(method, toolCallId));
123
+ if (!invocation)
124
+ return undefined;
125
+ // Checking, executing and mismatched records stay restrictive, including across rebinding.
126
+ if (invocation.phase !== "armed" ||
127
+ !invocation.preflight ||
128
+ invocation.args !== JSON.stringify(toolArgs(args)))
129
+ throw channelError("conflict", "Tool action does not match its completed preflight");
130
+ invocation.phase = "executing";
131
+ return { owner: invocation.owner, preflight: invocation.preflight };
132
+ }
133
+ export function releaseAgentToolPreflight(channel, owner) {
134
+ const invocations = state(channel).invocations;
135
+ const id = key(owner.method, owner.toolCallId);
136
+ const invocation = invocations.get(id);
137
+ if (invocation?.owner.token !== owner.token)
138
+ return false;
139
+ invocations.delete(id);
140
+ invocation.cleanup();
141
+ return true;
142
+ }
143
+ /** Only call at a proven final-idle boundary, never for an ambiguous tool_execution_end. */
144
+ export function sweepUnclaimedAgentToolPreflights(channel) {
145
+ for (const invocation of [...state(channel).invocations.values()]) {
146
+ if (invocation.phase !== "executing")
147
+ releaseAgentToolPreflight(channel, invocation.owner);
148
+ }
149
+ }
150
+ /** Genuine teardown is scoped to this channel, not another extension/runtime. */
151
+ export function clearAgentToolPreflights(channel) {
152
+ for (const { owner } of [...state(channel).invocations.values()])
153
+ releaseAgentToolPreflight(channel, owner);
154
+ }
155
+ //# sourceMappingURL=tool-preflight.js.map