@spencerboucher/switchyard 0.10.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 (129) hide show
  1. package/README.md +4 -1
  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/pi-model.js +12 -0
  6. package/dist/bridge/policy.js +213 -0
  7. package/dist/bridge/switchyard-bridge.js +73 -3
  8. package/dist/bridge/switchyard-terminal.js +143 -12
  9. package/dist/bridge/tool-preflight.js +155 -0
  10. package/dist/policies/worker.js +2877 -0
  11. package/dist/switchyard.mjs +19268 -10196
  12. package/dist/terminal/holder.js +47 -1
  13. package/package.json +3 -1
  14. package/web-dist/assets/AutomationView-BRVq9y-T.js +2 -0
  15. package/web-dist/assets/AutomationView-BRVq9y-T.js.map +1 -0
  16. package/web-dist/assets/{Card-CAFxHoHd.js → Card-BqrWFEYY.js} +2 -2
  17. package/web-dist/assets/{Card-CAFxHoHd.js.map → Card-BqrWFEYY.js.map} +1 -1
  18. package/web-dist/assets/{Checkbox-rDvnQnxc.js → Checkbox-DExv3fUO.js} +2 -2
  19. package/web-dist/assets/{Checkbox-rDvnQnxc.js.map → Checkbox-DExv3fUO.js.map} +1 -1
  20. package/web-dist/assets/{Copy-D8xhl7eJ.js → Copy-BuBbxEQI.js} +2 -2
  21. package/web-dist/assets/{Copy-D8xhl7eJ.js.map → Copy-BuBbxEQI.js.map} +1 -1
  22. package/web-dist/assets/{InteractionCard-Yu5wgLC3.js → InteractionCard-0PH6pIkH.js} +4 -4
  23. package/web-dist/assets/{InteractionCard-Yu5wgLC3.js.map → InteractionCard-0PH6pIkH.js.map} +1 -1
  24. package/web-dist/assets/{Menu-euseM8yR.js → Menu-BJ3Gyh5V.js} +2 -2
  25. package/web-dist/assets/{Menu-euseM8yR.js.map → Menu-BJ3Gyh5V.js.map} +1 -1
  26. package/web-dist/assets/Overlay-BgqVqKc6.js +2 -0
  27. package/web-dist/assets/Overlay-BgqVqKc6.js.map +1 -0
  28. package/web-dist/assets/Priority-B2tdgI2D.js +2 -0
  29. package/web-dist/assets/{Priority-Ca1B2yFr.js.map → Priority-B2tdgI2D.js.map} +1 -1
  30. package/web-dist/assets/{SegmentedControl-D2d-NEr-.js → SegmentedControl-DzwdZG6q.js} +2 -2
  31. package/web-dist/assets/{SegmentedControl-D2d-NEr-.js.map → SegmentedControl-DzwdZG6q.js.map} +1 -1
  32. package/web-dist/assets/{Select-C9L1HKMm.js → Select-DZ-qJ_AO.js} +2 -2
  33. package/web-dist/assets/{Select-C9L1HKMm.js.map → Select-DZ-qJ_AO.js.map} +1 -1
  34. package/web-dist/assets/{Switch-DAcUcSbH.js → Switch-DKiwAXXz.js} +2 -2
  35. package/web-dist/assets/{Switch-DAcUcSbH.js.map → Switch-DKiwAXXz.js.map} +1 -1
  36. package/web-dist/assets/{Tabs-xtagjtA5.js → Tabs-HOeWNnHD.js} +4 -4
  37. package/web-dist/assets/{Tabs-xtagjtA5.js.map → Tabs-HOeWNnHD.js.map} +1 -1
  38. package/web-dist/assets/{TextArea-CKGHwURx.js → TextArea-DK1uv3xX.js} +2 -2
  39. package/web-dist/assets/{TextArea-CKGHwURx.js.map → TextArea-DK1uv3xX.js.map} +1 -1
  40. package/web-dist/assets/{TextLink-Bub7sMxr.js → TextLink-BoFPQuaH.js} +2 -2
  41. package/web-dist/assets/{TextLink-Bub7sMxr.js.map → TextLink-BoFPQuaH.js.map} +1 -1
  42. package/web-dist/assets/attention-D1G0KCOr.js +2 -0
  43. package/web-dist/assets/attention-D1G0KCOr.js.map +1 -0
  44. package/web-dist/assets/automations-DUUAfMK8.js +2 -0
  45. package/web-dist/assets/{automations-BzpsJoa3.js.map → automations-DUUAfMK8.js.map} +1 -1
  46. package/web-dist/assets/board-tIuyEKO0.js +10 -0
  47. package/web-dist/assets/board-tIuyEKO0.js.map +1 -0
  48. package/web-dist/assets/code-B1njb2Cr.css +1 -0
  49. package/web-dist/assets/code-O-DyPB50.js +25 -0
  50. package/web-dist/assets/code-O-DyPB50.js.map +1 -0
  51. package/web-dist/assets/describe-BW5uUuvy.js +5 -0
  52. package/web-dist/assets/{describe-CVXeUClF.js.map → describe-BW5uUuvy.js.map} +1 -1
  53. package/web-dist/assets/enroll-CL0BGGhd.js +2 -0
  54. package/web-dist/assets/{enroll-jnKygG4L.js.map → enroll-CL0BGGhd.js.map} +1 -1
  55. package/web-dist/assets/index-D-JHf__5.css +2 -0
  56. package/web-dist/assets/index-K0QOY1Li.js +11 -0
  57. package/web-dist/assets/index-K0QOY1Li.js.map +1 -0
  58. package/web-dist/assets/more-DNN_mtX8.js +2 -0
  59. package/web-dist/assets/{more-DvKHMdBk.js.map → more-DNN_mtX8.js.map} +1 -1
  60. package/web-dist/assets/plus-BLP-wIYD.js +2 -0
  61. package/web-dist/assets/plus-BLP-wIYD.js.map +1 -0
  62. package/web-dist/assets/policyLogic-BKSj6mhC.js +2 -0
  63. package/web-dist/assets/policyLogic-BKSj6mhC.js.map +1 -0
  64. package/web-dist/assets/preload-helper-BudhqmWi.js +13 -0
  65. package/web-dist/assets/preload-helper-BudhqmWi.js.map +1 -0
  66. package/web-dist/assets/queue-k4o-I9uY.js +2 -0
  67. package/web-dist/assets/{queue-B2Vl0uSh.js.map → queue-k4o-I9uY.js.map} +1 -1
  68. package/web-dist/assets/repo-CSQAnBaF.js +2 -0
  69. package/web-dist/assets/repo-CSQAnBaF.js.map +1 -0
  70. package/web-dist/assets/settings-CrYZRJ7E.js +7 -0
  71. package/web-dist/assets/settings-CrYZRJ7E.js.map +1 -0
  72. package/web-dist/assets/shared-DIA598ns.js +3 -0
  73. package/web-dist/assets/shared-DIA598ns.js.map +1 -0
  74. package/web-dist/assets/states-C8oEFqek.js +58 -0
  75. package/web-dist/assets/states-C8oEFqek.js.map +1 -0
  76. package/web-dist/assets/{terminal-login-BK5UjUir.js → terminal-login-M5orrPPe.js} +2 -2
  77. package/web-dist/assets/{terminal-login-BK5UjUir.js.map → terminal-login-M5orrPPe.js.map} +1 -1
  78. package/web-dist/assets/timer-BCIucSXh.js +2 -0
  79. package/web-dist/assets/timer-BCIucSXh.js.map +1 -0
  80. package/web-dist/assets/useBreakpoint-CA0Mbmvv.js +2 -0
  81. package/web-dist/assets/useBreakpoint-CA0Mbmvv.js.map +1 -0
  82. package/web-dist/assets/useNow-Dx0MCCez.js +2 -0
  83. package/web-dist/assets/useNow-Dx0MCCez.js.map +1 -0
  84. package/web-dist/assets/{useResource-BBqCoY2q.js → useResource-BTjwa4tV.js} +2 -2
  85. package/web-dist/assets/{useResource-BBqCoY2q.js.map → useResource-BTjwa4tV.js.map} +1 -1
  86. package/web-dist/index.html +10 -7
  87. package/web-dist/sw.js +1 -1
  88. package/web-dist/sw.js.map +1 -1
  89. package/web-dist/assets/AutomationView-BsTwLnMp.js +0 -2
  90. package/web-dist/assets/AutomationView-BsTwLnMp.js.map +0 -1
  91. package/web-dist/assets/Field-Dbg_8KTt.js +0 -2
  92. package/web-dist/assets/Field-Dbg_8KTt.js.map +0 -1
  93. package/web-dist/assets/Overlay-BNPvMjLX.js +0 -2
  94. package/web-dist/assets/Overlay-BNPvMjLX.js.map +0 -1
  95. package/web-dist/assets/Priority-Ca1B2yFr.js +0 -2
  96. package/web-dist/assets/StatusChip-BYuVxYS7.js +0 -2
  97. package/web-dist/assets/StatusChip-BYuVxYS7.js.map +0 -1
  98. package/web-dist/assets/attention-CI4dHY81.js +0 -2
  99. package/web-dist/assets/attention-CI4dHY81.js.map +0 -1
  100. package/web-dist/assets/auth-308hUVgi.js +0 -2
  101. package/web-dist/assets/auth-308hUVgi.js.map +0 -1
  102. package/web-dist/assets/automations-BzpsJoa3.js +0 -2
  103. package/web-dist/assets/bell-DSwa2PAb.js +0 -2
  104. package/web-dist/assets/bell-DSwa2PAb.js.map +0 -1
  105. package/web-dist/assets/board-CeJxBVHC.js +0 -10
  106. package/web-dist/assets/board-CeJxBVHC.js.map +0 -1
  107. package/web-dist/assets/code-DkNQvMI9.js +0 -12
  108. package/web-dist/assets/code-DkNQvMI9.js.map +0 -1
  109. package/web-dist/assets/describe-CVXeUClF.js +0 -5
  110. package/web-dist/assets/enroll-jnKygG4L.js +0 -2
  111. package/web-dist/assets/index-BHGZTS2e.js +0 -16
  112. package/web-dist/assets/index-BHGZTS2e.js.map +0 -1
  113. package/web-dist/assets/index-D2ml031z.css +0 -2
  114. package/web-dist/assets/more-DvKHMdBk.js +0 -2
  115. package/web-dist/assets/queue-B2Vl0uSh.js +0 -2
  116. package/web-dist/assets/repo-BDS8RBxq.js +0 -2
  117. package/web-dist/assets/repo-BDS8RBxq.js.map +0 -1
  118. package/web-dist/assets/server-BqZ-w6M8.js +0 -2
  119. package/web-dist/assets/server-BqZ-w6M8.js.map +0 -1
  120. package/web-dist/assets/settings-CLt7x9u8.js +0 -8
  121. package/web-dist/assets/settings-CLt7x9u8.js.map +0 -1
  122. package/web-dist/assets/states-C773NlHo.js +0 -56
  123. package/web-dist/assets/states-C773NlHo.js.map +0 -1
  124. package/web-dist/assets/useBackTo-BIrCq3W2.js +0 -2
  125. package/web-dist/assets/useBackTo-BIrCq3W2.js.map +0 -1
  126. package/web-dist/assets/useBreakpoint-BphHBrzF.js +0 -2
  127. package/web-dist/assets/useBreakpoint-BphHBrzF.js.map +0 -1
  128. package/web-dist/assets/useNow-Cm-tdyod.js +0 -2
  129. package/web-dist/assets/useNow-Cm-tdyod.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)
@@ -130,6 +174,14 @@ export default function switchyardTerminal(pi) {
130
174
  .filter(Boolean),
131
175
  });
132
176
  const sendQueue = () => send({ type: "queue_update", ...queue });
177
+ const sendLeaf = () => {
178
+ try {
179
+ send({ type: "leaf", leafId: ctx?.sessionManager?.getLeafId?.() ?? null });
180
+ }
181
+ catch {
182
+ // never throw into Pi
183
+ }
184
+ };
133
185
  /** Announce this session (and whether dialogs are remote-backed) to the host. */
134
186
  const hello = () => {
135
187
  if (!ctx)
@@ -569,6 +621,53 @@ export default function switchyardTerminal(pi) {
569
621
  }
570
622
  });
571
623
  return;
624
+ case "navigate_tree": {
625
+ const entryId = String(cmd.entryId ?? "");
626
+ if ((cmd.sessionFile ?? null) !== (ctx.sessionManager.getSessionFile() ?? null)) {
627
+ respond(id, type, undefined, "The session changed; reload and try again");
628
+ return;
629
+ }
630
+ if (!ctx.isIdle()) {
631
+ respond(id, type, undefined, "Wait for the current reply to finish");
632
+ return;
633
+ }
634
+ if (pending.size > 0) {
635
+ respond(id, type, undefined, "Answer the open dialog first");
636
+ return;
637
+ }
638
+ const target = ctx.sessionManager.getEntry?.(entryId);
639
+ if (!target) {
640
+ respond(id, type, undefined, "That message is not in this session");
641
+ return;
642
+ }
643
+ const summarize = cmd.summarize === true;
644
+ runInternal(async (c) => {
645
+ try {
646
+ const r = await c.navigateTree(entryId, {
647
+ summarize,
648
+ customInstructions: cmd.instructions || undefined,
649
+ });
650
+ if (r?.cancelled) {
651
+ respond(id, type, undefined, summarize ? "Summary cancelled" : "Rewind cancelled");
652
+ return;
653
+ }
654
+ const editorText = target.type === "message" && target.message?.role === "user"
655
+ ? messageText(target.message)
656
+ : null;
657
+ respond(id, type, {
658
+ leafId: ctx.sessionManager.getLeafId() ?? null,
659
+ editorText,
660
+ entries: ctx.sessionManager.getBranch(),
661
+ });
662
+ }
663
+ catch (e) {
664
+ respond(id, type, undefined, e?.message ?? String(e));
665
+ }
666
+ flushEntries();
667
+ sendLeaf();
668
+ });
669
+ return;
670
+ }
572
671
  case "reload":
573
672
  if (!ctx) {
574
673
  respond(id, type, undefined, "Session is not ready");
@@ -615,6 +714,7 @@ export default function switchyardTerminal(pi) {
615
714
  hello();
616
715
  sendModelState();
617
716
  sendQueue();
717
+ sendLeaf();
618
718
  }
619
719
  for (const p of pending.values())
620
720
  send(p.request);
@@ -629,6 +729,8 @@ export default function switchyardTerminal(pi) {
629
729
  }
630
730
  if (!msg || typeof msg !== "object")
631
731
  return;
732
+ if (channel.receive(msg))
733
+ return;
632
734
  if (msg.type === "extension_ui_response") {
633
735
  pending.get(String(msg.id))?.onRemote(msg);
634
736
  return;
@@ -637,6 +739,7 @@ export default function switchyardTerminal(pi) {
637
739
  // A controller re-attached (host agent restart): it starts from scratch, so announce the
638
740
  // session again before re-sending the dialogs it has not answered.
639
741
  announce();
742
+ channel.onControlAttached();
640
743
  return;
641
744
  }
642
745
  if (typeof msg.type === "string" && msg.id !== undefined)
@@ -664,14 +767,19 @@ export default function switchyardTerminal(pi) {
664
767
  connected = true;
665
768
  if (attempt > 1)
666
769
  announce();
770
+ channel.onConnect();
667
771
  });
668
772
  s.on("error", () => {
669
- if (socket === s)
773
+ if (socket === s) {
774
+ channel.onDisconnect();
670
775
  socket = null;
776
+ }
671
777
  });
672
778
  s.on("close", () => {
673
- if (socket === s)
779
+ if (socket === s) {
780
+ channel.onDisconnect();
674
781
  socket = null;
782
+ }
675
783
  if (!connected && attempt < CONNECT_ATTEMPTS) {
676
784
  setTimeout(() => connect(attempt + 1), CONNECT_RETRY_MS).unref();
677
785
  }
@@ -726,6 +834,8 @@ export default function switchyardTerminal(pi) {
726
834
  const sessionFile = c.sessionManager.getSessionFile() ?? null;
727
835
  hello();
728
836
  sendModelState();
837
+ sendLeaf();
838
+ channel.announce();
729
839
  if (event?.reason && event.reason !== "startup") {
730
840
  send({ type: "switchyard_native", sessionId, sessionFile });
731
841
  }
@@ -760,10 +870,18 @@ export default function switchyardTerminal(pi) {
760
870
  send(event);
761
871
  flushEntries();
762
872
  });
763
- on("turn_end", () => flushEntries());
873
+ on("turn_end", () => {
874
+ flushEntries();
875
+ sendLeaf();
876
+ });
877
+ on("session_tree", () => {
878
+ flushEntries();
879
+ sendLeaf();
880
+ });
764
881
  on("agent_settled", (event) => {
765
882
  send({ type: "agent_settled", aborted: event?.aborted === true });
766
883
  flushEntries();
884
+ sendLeaf();
767
885
  if (queue.steering.length > 0 || queue.followUp.length > 0) {
768
886
  queue.steering = [];
769
887
  queue.followUp = [];
@@ -783,16 +901,29 @@ export default function switchyardTerminal(pi) {
783
901
  on("model_select", () => sendModelState());
784
902
  on("thinking_level_select", () => sendModelState());
785
903
  on("session_before_compact", (event) => send({ type: "compaction_start", reason: event?.reason ?? "manual" }));
786
- on("ui_prompt_start", (event) => send({
787
- type: "ui_prompt",
788
- event: event.type,
789
- kind: event.kind,
790
- title: event.title ?? null,
791
- remoteBacked: event.kind === "custom" && remoteBacked > 0,
792
- }));
793
- 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
+ });
794
922
  on("input", (event) => {
795
- if (event?.source !== "interactive" || !event.streamingBehavior)
923
+ if (event?.source !== "interactive")
924
+ return;
925
+ channel.noteHumanInput();
926
+ if (!event.streamingBehavior)
796
927
  return;
797
928
  (event.streamingBehavior === "steer" ? queue.steering : queue.followUp).push(String(event.text ?? ""));
798
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