@spencerboucher/switchyard 0.11.0 → 0.13.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 (105) hide show
  1. package/README.md +5 -2
  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 +2951 -0
  10. package/dist/switchyard.mjs +15480 -6064
  11. package/package.json +3 -1
  12. package/web-dist/assets/AutomationView-Cg7yk8nb.js +2 -0
  13. package/web-dist/assets/AutomationView-Cg7yk8nb.js.map +1 -0
  14. package/web-dist/assets/{Card-XMb6DfZU.js → Card-sHm0eI2Q.js} +2 -2
  15. package/web-dist/assets/{Card-XMb6DfZU.js.map → Card-sHm0eI2Q.js.map} +1 -1
  16. package/web-dist/assets/{Checkbox-CeUPbVi7.js → Checkbox-CEvKyfJz.js} +2 -2
  17. package/web-dist/assets/{Checkbox-CeUPbVi7.js.map → Checkbox-CEvKyfJz.js.map} +1 -1
  18. package/web-dist/assets/{Copy-CGnl0Vga.js → Copy-BHOLVthK.js} +2 -2
  19. package/web-dist/assets/{Copy-CGnl0Vga.js.map → Copy-BHOLVthK.js.map} +1 -1
  20. package/web-dist/assets/{InteractionCard-1ePc4XOF.js → InteractionCard-B-yhxwKs.js} +4 -4
  21. package/web-dist/assets/{InteractionCard-1ePc4XOF.js.map → InteractionCard-B-yhxwKs.js.map} +1 -1
  22. package/web-dist/assets/{Menu-CYZQ97c0.js → Menu-Cyt18mF2.js} +2 -2
  23. package/web-dist/assets/{Menu-CYZQ97c0.js.map → Menu-Cyt18mF2.js.map} +1 -1
  24. package/web-dist/assets/Overlay-BPNYBq3V.js +2 -0
  25. package/web-dist/assets/{Overlay-DlLhg1cK.js.map → Overlay-BPNYBq3V.js.map} +1 -1
  26. package/web-dist/assets/{Priority-BCHLJqWN.js → Priority-xSUsxoXm.js} +2 -2
  27. package/web-dist/assets/{Priority-BCHLJqWN.js.map → Priority-xSUsxoXm.js.map} +1 -1
  28. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js → SegmentedControl-DaBwumC0.js} +2 -2
  29. package/web-dist/assets/{SegmentedControl-CSO0EMTX.js.map → SegmentedControl-DaBwumC0.js.map} +1 -1
  30. package/web-dist/assets/{Select-Dgmnmpz3.js → Select-C5xlhWYb.js} +2 -2
  31. package/web-dist/assets/{Select-Dgmnmpz3.js.map → Select-C5xlhWYb.js.map} +1 -1
  32. package/web-dist/assets/{Switch-DS4NRENd.js → Switch-dVcf-7Je.js} +2 -2
  33. package/web-dist/assets/{Switch-DS4NRENd.js.map → Switch-dVcf-7Je.js.map} +1 -1
  34. package/web-dist/assets/{Tabs-9xp-tGja.js → Tabs-93APobOB.js} +2 -2
  35. package/web-dist/assets/{Tabs-9xp-tGja.js.map → Tabs-93APobOB.js.map} +1 -1
  36. package/web-dist/assets/{TextArea-PfVKaz29.js → TextArea-D8WB5GD8.js} +2 -2
  37. package/web-dist/assets/{TextArea-PfVKaz29.js.map → TextArea-D8WB5GD8.js.map} +1 -1
  38. package/web-dist/assets/{TextLink-CYqiAUlK.js → TextLink-CrfA8AeH.js} +2 -2
  39. package/web-dist/assets/{TextLink-CYqiAUlK.js.map → TextLink-CrfA8AeH.js.map} +1 -1
  40. package/web-dist/assets/attention-C8rfu6Uw.js +2 -0
  41. package/web-dist/assets/{attention-CTkX5JXq.js.map → attention-C8rfu6Uw.js.map} +1 -1
  42. package/web-dist/assets/{automations-CsdtA3xp.js → automations-DQxUzi5Q.js} +2 -2
  43. package/web-dist/assets/{automations-CsdtA3xp.js.map → automations-DQxUzi5Q.js.map} +1 -1
  44. package/web-dist/assets/board-aS6ooJpx.js +10 -0
  45. package/web-dist/assets/board-aS6ooJpx.js.map +1 -0
  46. package/web-dist/assets/code-Zr5DqwWI.js +25 -0
  47. package/web-dist/assets/code-Zr5DqwWI.js.map +1 -0
  48. package/web-dist/assets/{describe-DjRsBpcB.js → describe-w4KmQFfU.js} +3 -3
  49. package/web-dist/assets/{describe-DjRsBpcB.js.map → describe-w4KmQFfU.js.map} +1 -1
  50. package/web-dist/assets/{enroll-DcEYGgoX.js → enroll-DPKdD0en.js} +2 -2
  51. package/web-dist/assets/{enroll-DcEYGgoX.js.map → enroll-DPKdD0en.js.map} +1 -1
  52. package/web-dist/assets/index-DFNY2EUd.css +2 -0
  53. package/web-dist/assets/index-DPScWz2I.js +11 -0
  54. package/web-dist/assets/index-DPScWz2I.js.map +1 -0
  55. package/web-dist/assets/{more-BQSa_-H6.js → more-CiyGP5GD.js} +2 -2
  56. package/web-dist/assets/{more-BQSa_-H6.js.map → more-CiyGP5GD.js.map} +1 -1
  57. package/web-dist/assets/policyLogic-7OOzM_xa.js +2 -0
  58. package/web-dist/assets/policyLogic-7OOzM_xa.js.map +1 -0
  59. package/web-dist/assets/{preload-helper-Huh16h6r.js → preload-helper-B2m1UyXR.js} +5 -5
  60. package/web-dist/assets/preload-helper-B2m1UyXR.js.map +1 -0
  61. package/web-dist/assets/queue-BcbJqzTY.js +2 -0
  62. package/web-dist/assets/{queue-CCjBjQhT.js.map → queue-BcbJqzTY.js.map} +1 -1
  63. package/web-dist/assets/{repo-pkFfpra6.js → repo-BA_bnCvu.js} +2 -2
  64. package/web-dist/assets/{repo-pkFfpra6.js.map → repo-BA_bnCvu.js.map} +1 -1
  65. package/web-dist/assets/settings-D03MF_Kx.js +7 -0
  66. package/web-dist/assets/settings-D03MF_Kx.js.map +1 -0
  67. package/web-dist/assets/shared-Bxc2JM1K.js +3 -0
  68. package/web-dist/assets/shared-Bxc2JM1K.js.map +1 -0
  69. package/web-dist/assets/states-DynH8-o6.js +58 -0
  70. package/web-dist/assets/states-DynH8-o6.js.map +1 -0
  71. package/web-dist/assets/terminal-login-C0n8cXqn.js +2 -0
  72. package/web-dist/assets/{terminal-login-D9enO0EH.js.map → terminal-login-C0n8cXqn.js.map} +1 -1
  73. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js → useBreakpoint-CYDIV-KM.js} +2 -2
  74. package/web-dist/assets/{useBreakpoint-LY_qlpRG.js.map → useBreakpoint-CYDIV-KM.js.map} +1 -1
  75. package/web-dist/assets/useNow-0tMsLHnB.js +2 -0
  76. package/web-dist/assets/useNow-0tMsLHnB.js.map +1 -0
  77. package/web-dist/assets/{useResource-Dul6MTDM.js → useResource-DHtFcID5.js} +2 -2
  78. package/web-dist/assets/{useResource-Dul6MTDM.js.map → useResource-DHtFcID5.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/Overlay-DlLhg1cK.js +0 -2
  87. package/web-dist/assets/attention-CTkX5JXq.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/index-BeJqGnFE.css +0 -2
  93. package/web-dist/assets/index-DSJZdQ79.js +0 -11
  94. package/web-dist/assets/index-DSJZdQ79.js.map +0 -1
  95. package/web-dist/assets/preload-helper-Huh16h6r.js.map +0 -1
  96. package/web-dist/assets/queue-CCjBjQhT.js +0 -2
  97. package/web-dist/assets/settings-vrxspmWN.js +0 -7
  98. package/web-dist/assets/settings-vrxspmWN.js.map +0 -1
  99. package/web-dist/assets/shared-Bm6Rhfqw.js +0 -3
  100. package/web-dist/assets/shared-Bm6Rhfqw.js.map +0 -1
  101. package/web-dist/assets/states-BQxrRFdh.js +0 -56
  102. package/web-dist/assets/states-BQxrRFdh.js.map +0 -1
  103. package/web-dist/assets/terminal-login-D9enO0EH.js +0 -2
  104. package/web-dist/assets/useNow-BUvGqrfn.js +0 -2
  105. package/web-dist/assets/useNow-BUvGqrfn.js.map +0 -1
package/README.md CHANGED
@@ -118,7 +118,7 @@ switchyard up
118
118
  ```sh
119
119
  docker run -d --name switchyard -p 127.0.0.1:7400:7400 -v switchyard-data:/data \
120
120
  -e SWITCHYARD_PUBLIC_URL=https://switchyard.example.com \
121
- ghcr.io/justmytwospence/switchyard:0.11.0
121
+ ghcr.io/justmytwospence/switchyard:0.12.0
122
122
  # Single sign-on is required off localhost: see docs/auth.md
123
123
  ```
124
124
 
@@ -132,7 +132,7 @@ switchyard host install-service # launchd on macOS, a systemd user service on
132
132
 
133
133
  Settings › Hosts › Add host shows these three commands with your token filled in. To build from source instead, see [docs/development.md](docs/development.md).
134
134
 
135
- [docs/deployment.md](docs/deployment.md) has recipes for Caddy, Traefik, nginx and Tailscale, a compose file, and every setting.
135
+ [docs/deployment.md](docs/deployment.md) has recipes for Caddy, Traefik, nginx and Tailscale, a compose file, and every setting. A typed Node client for scripts and CI is in development for the next release; see [docs/client-sdk.md](docs/client-sdk.md) for its API and limitations.
136
136
 
137
137
  ## Security model
138
138
 
@@ -159,7 +159,10 @@ Switchyard is young and moving quickly. It is tested against Pi `>=1.4.0 <1.6.0`
159
159
  | [CLI](docs/cli.md) | Every `switchyard` command and credentials |
160
160
  | [Terminal sessions](docs/terminal-sessions.md) | Pi's own TUI for every session, from any terminal, and the herdr integration |
161
161
  | [Operations](docs/operations.md) | Backup, restore, migrations, retention, logs, health, diagnostics |
162
+ | [Policies](docs/policies.md) | Agent tools, guardrails, approvals and budgets |
163
+ | [GitHub](docs/github.md) | Host authentication, PR review and merge, issue tasks |
162
164
  | [Adapters](docs/adapters.md) | Rendering a Pi plugin's UI in every client; shipping an adapter with your Pi package |
163
165
  | [Architecture](docs/architecture.md) | Components, data ownership, the host and client protocols, packages |
164
166
  | [Development](docs/development.md) | Building, testing (including against real Pi), contributing |
165
167
  | [Specification](docs/spec.md) | The product specification Switchyard is built to |
168
+ | [Roadmap](docs/roadmap.md) | Phase status and planned plugin slots, SDK and relay |
@@ -0,0 +1,449 @@
1
+ import { randomUUID } from "node:crypto";
2
+ export function channelError(code, message, details) {
3
+ return Object.assign(new Error(message), { code, ...(details === undefined ? {} : { details }) });
4
+ }
5
+ export function createAgentChannel(options) {
6
+ const runtimeId = randomUUID();
7
+ const now = options.now ?? Date.now;
8
+ let configuration = null;
9
+ let required = options.policyRequired;
10
+ let connected = false;
11
+ let closed = false;
12
+ let native = null;
13
+ let lastBinding = null;
14
+ // A controller/native replacement is irreversible for already captured pins, even if
15
+ // a delayed configure later tries to restore an old identity (A -> B -> A).
16
+ const retiredBindings = new Set();
17
+ const bindingKey = (b) => JSON.stringify([b.sessionId, b.runtimeId, b.nativeSessionId, b.bindingId]);
18
+ const retireBinding = () => {
19
+ if (lastBinding)
20
+ retiredBindings.add(bindingKey(lastBinding));
21
+ };
22
+ const handlers = new Map();
23
+ const changes = new Set();
24
+ const pending = new Map();
25
+ let activeRequests = 0;
26
+ const wake = () => {
27
+ for (const cb of [...changes])
28
+ cb();
29
+ };
30
+ const currentNative = () => options.getContext()?.sessionManager?.getSessionId?.() || null;
31
+ const invalidate = () => {
32
+ configuration = null;
33
+ for (const p of pending.values())
34
+ p.resolve(null);
35
+ pending.clear();
36
+ wake();
37
+ };
38
+ const syncNative = () => {
39
+ const value = currentNative();
40
+ if (native !== value) {
41
+ retireBinding();
42
+ native = value;
43
+ invalidate();
44
+ }
45
+ return value;
46
+ };
47
+ const assertBinding = (binding) => {
48
+ if (!binding)
49
+ return;
50
+ const current = syncNative();
51
+ if (binding.nativeSessionId !== current)
52
+ throw channelError("stale_control", "Native session changed");
53
+ if (binding.runtimeId !== runtimeId ||
54
+ retiredBindings.has(bindingKey(binding)) ||
55
+ (lastBinding && bindingKey(lastBinding) !== bindingKey(binding)) ||
56
+ (configuration && bindingKey(configuration) !== bindingKey(binding)))
57
+ throw channelError("stale_control", "Bridge binding changed during tool authorization");
58
+ };
59
+ const contextIds = () => {
60
+ const result = { humanInputId: null, causalMessageId: null };
61
+ const entries = options.getContext()?.sessionManager?.getBranch?.() ?? [];
62
+ for (const e of entries) {
63
+ if (e?.type === "custom" &&
64
+ e.customType === "switchyard-human-input" &&
65
+ typeof e.data?.humanInputId === "string") {
66
+ result.humanInputId = e.data.humanInputId;
67
+ result.causalMessageId = null;
68
+ }
69
+ const m = e?.type === "message" || e?.type === "custom_message" ? (e.message ?? e) : null;
70
+ if ((m?.customType === "switchyard-inbox" || m?.customType === "switchyard-completion") &&
71
+ typeof m.details?.deliveryId === "string")
72
+ result.causalMessageId = m.details.deliveryId;
73
+ }
74
+ return result;
75
+ };
76
+ const state = () => {
77
+ if (!configuration)
78
+ return "initializing";
79
+ const caps = options.getCapabilities();
80
+ if (!(caps.toolPolicy &&
81
+ configuration.features.includes("agentRequests.v1") &&
82
+ configuration.features.includes("policies.v1")))
83
+ return "unsupported";
84
+ return connected && configuration.coordinatorConnected ? "active" : "lost";
85
+ };
86
+ const usable = (c, feature) => feature === "policies"
87
+ ? state() !== "unsupported"
88
+ : options.getCapabilities().agentTools && c.features.includes("agentRequests.v1");
89
+ const delay = (deadline, signal) => new Promise((resolve, reject) => {
90
+ if (closed)
91
+ return reject(channelError("host_unreachable", "Channel closed"));
92
+ if (signal?.aborted)
93
+ return reject(channelError("conflict", "Request canceled"));
94
+ const remaining = deadline - now();
95
+ if (remaining <= 0)
96
+ return reject(channelError("timeout", "Coordinator communication timed out"));
97
+ const cleanup = () => {
98
+ clearTimeout(timer);
99
+ changes.delete(changed);
100
+ signal?.removeEventListener("abort", abort);
101
+ };
102
+ const changed = () => {
103
+ cleanup();
104
+ resolve();
105
+ };
106
+ const abort = () => {
107
+ cleanup();
108
+ reject(channelError("conflict", "Request canceled"));
109
+ };
110
+ const timer = setTimeout(() => {
111
+ cleanup();
112
+ reject(channelError("timeout", "Coordinator communication timed out"));
113
+ }, remaining);
114
+ changes.add(changed);
115
+ signal?.addEventListener("abort", abort, { once: true });
116
+ });
117
+ const deadlineFor = (ms) => now() + Math.min(30000, Math.max(1, Number.isFinite(ms) ? ms : 30000));
118
+ const ready = async (feature, deadline, signal, expectedNative, binding, pinFirst = false) => {
119
+ // Capture startup readiness synchronously on the state change, not in a later
120
+ // promise continuation that could already see a replacement controller.
121
+ const capture = () => {
122
+ if (pinFirst &&
123
+ !binding &&
124
+ configuration &&
125
+ connected &&
126
+ configuration.coordinatorConnected &&
127
+ usable(configuration, feature)) {
128
+ const { sessionId, runtimeId, nativeSessionId, bindingId } = configuration;
129
+ binding = { sessionId, runtimeId, nativeSessionId, bindingId };
130
+ }
131
+ };
132
+ if (pinFirst)
133
+ changes.add(capture);
134
+ capture();
135
+ try {
136
+ while (true) {
137
+ if (closed)
138
+ throw channelError("host_unreachable", "Channel closed");
139
+ if (signal?.aborted)
140
+ throw channelError("conflict", "Request canceled");
141
+ if (now() >= deadline)
142
+ throw channelError("timeout", "Coordinator communication timed out");
143
+ const current = syncNative();
144
+ assertBinding(binding);
145
+ if (expectedNative && current !== expectedNative)
146
+ throw channelError("conflict", "Native session changed");
147
+ if (configuration && !usable(configuration, feature))
148
+ throw channelError("unsupported_capability", "Coordinator or bridge does not support this feature");
149
+ if (configuration && connected && configuration.coordinatorConnected)
150
+ return configuration;
151
+ await delay(deadline, signal);
152
+ }
153
+ }
154
+ finally {
155
+ changes.delete(capture);
156
+ }
157
+ };
158
+ const announce = () => {
159
+ const id = syncNative();
160
+ if (!id || closed || !connected)
161
+ return;
162
+ options.send({
163
+ type: "agent.hello",
164
+ version: 1,
165
+ runtimeId,
166
+ nativeSessionId: id,
167
+ sessionFile: options.getContext()?.sessionManager?.getSessionFile?.() ?? null,
168
+ pid: process.pid,
169
+ mode: options.mode,
170
+ capabilities: options.getCapabilities(),
171
+ context: contextIds(),
172
+ });
173
+ };
174
+ const noteHumanInput = (id = randomUUID()) => {
175
+ const entries = options.getContext()?.sessionManager?.getBranch?.() ?? [];
176
+ const existing = entries.some((entry) => entry?.type === "custom" &&
177
+ entry.customType === "switchyard-human-input" &&
178
+ entry.data?.humanInputId === id);
179
+ if (!existing)
180
+ options.appendEntry("switchyard-human-input", { version: 1, humanInputId: id });
181
+ return id;
182
+ };
183
+ const receipt = (r, result, error) => {
184
+ if (closed)
185
+ return;
186
+ options.send({
187
+ type: "bridge.receipt",
188
+ requestId: r.requestId,
189
+ runtimeId: r.runtimeId,
190
+ nativeSessionId: r.nativeSessionId,
191
+ bindingId: r.bindingId,
192
+ ...(error
193
+ ? {
194
+ ok: false,
195
+ error: {
196
+ code: error.code ?? "internal",
197
+ message: error.message ?? String(error),
198
+ ...(error.details === undefined ? {} : { details: error.details }),
199
+ },
200
+ }
201
+ : { ok: true, result }),
202
+ });
203
+ };
204
+ const channel = {
205
+ runtimeId,
206
+ snapshot() {
207
+ syncNative();
208
+ return { configuration, policyRequired: required, policyState: state() };
209
+ },
210
+ announce,
211
+ onConnect() {
212
+ if (closed)
213
+ return;
214
+ connected = true;
215
+ wake();
216
+ announce();
217
+ },
218
+ onDisconnect() {
219
+ connected = false;
220
+ invalidate();
221
+ },
222
+ onControlAttached() {
223
+ retireBinding();
224
+ invalidate();
225
+ announce();
226
+ },
227
+ receive(record) {
228
+ if (!record || typeof record !== "object")
229
+ return false;
230
+ const r = record;
231
+ if (r.type === "agent.result") {
232
+ const p = pending.get(r.requestId);
233
+ if (p &&
234
+ r.runtimeId === runtimeId &&
235
+ r.bindingId === p.bindingId &&
236
+ configuration?.bindingId === p.bindingId &&
237
+ typeof r.ok === "boolean") {
238
+ pending.delete(r.requestId);
239
+ p.resolve(r);
240
+ }
241
+ return true;
242
+ }
243
+ if (r.type !== "bridge.command")
244
+ return false;
245
+ const validId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200;
246
+ if (![r.requestId, r.runtimeId, r.nativeSessionId, r.bindingId].every(validId) ||
247
+ r.runtimeId !== runtimeId ||
248
+ r.nativeSessionId !== syncNative())
249
+ return true;
250
+ if (r.method !== "configure" && (!configuration || r.bindingId !== configuration.bindingId))
251
+ return true;
252
+ void (async () => {
253
+ try {
254
+ if (r.method === "configure") {
255
+ const c = r.args;
256
+ if (c?.version !== 1 ||
257
+ c.runtimeId !== runtimeId ||
258
+ c.nativeSessionId !== native ||
259
+ c.bindingId !== r.bindingId ||
260
+ !validId(c.sessionId) ||
261
+ !Array.isArray(c.features) ||
262
+ !c.features.every((f) => typeof f === "string") ||
263
+ typeof c.coordinatorConnected !== "boolean" ||
264
+ typeof c.policyRequired !== "boolean" ||
265
+ !(c.sessionUrl === null || typeof c.sessionUrl === "string"))
266
+ throw channelError("invalid_request", "Invalid bridge configuration");
267
+ if (retiredBindings.has(bindingKey(c)))
268
+ throw channelError("stale_control", "Bridge controller binding has been replaced");
269
+ if (lastBinding && bindingKey(lastBinding) !== bindingKey(c))
270
+ retireBinding();
271
+ invalidate();
272
+ configuration = { ...c, features: [...c.features] };
273
+ lastBinding = {
274
+ sessionId: c.sessionId,
275
+ runtimeId: c.runtimeId,
276
+ nativeSessionId: c.nativeSessionId,
277
+ bindingId: c.bindingId,
278
+ };
279
+ required ||= c.policyRequired;
280
+ wake();
281
+ const caps = options.getCapabilities();
282
+ const enabled = caps.agentTools && c.features.includes("agentRequests.v1");
283
+ receipt(r, {
284
+ configured: true,
285
+ agentTools: enabled,
286
+ messageDelivery: caps.messageDelivery &&
287
+ caps.editorDraftGuard &&
288
+ c.features.includes("agentRequests.v1"),
289
+ policyRequired: required,
290
+ policyState: state(),
291
+ policyPhases: state() === "active" ? ["tool_call", "request"] : [],
292
+ });
293
+ }
294
+ else if (r.method === "connection.update") {
295
+ if (typeof r.args?.connected !== "boolean")
296
+ throw channelError("invalid_request", "Invalid connection state");
297
+ configuration.coordinatorConnected = r.args.connected;
298
+ if (!r.args.connected) {
299
+ for (const p of pending.values())
300
+ p.resolve(null);
301
+ pending.clear();
302
+ }
303
+ wake();
304
+ receipt(r, { connected: r.args.connected });
305
+ }
306
+ else if (r.method === "input.human") {
307
+ if (!validId(r.args?.humanInputId))
308
+ throw channelError("invalid_request", "Invalid human input id");
309
+ noteHumanInput(r.args.humanInputId);
310
+ receipt(r, { humanInputId: r.args.humanInputId });
311
+ }
312
+ else {
313
+ const handler = handlers.get(r.method);
314
+ if (!handler)
315
+ throw channelError("unsupported_capability", "Unsupported bridge command");
316
+ const caps = options.getCapabilities();
317
+ if (!caps.messageDelivery ||
318
+ !caps.editorDraftGuard ||
319
+ !configuration.features.includes("agentRequests.v1"))
320
+ throw channelError("unsupported_capability", "Message delivery is unavailable");
321
+ receipt(r, await handler(r.args, r));
322
+ }
323
+ }
324
+ catch (error) {
325
+ receipt(r, null, error);
326
+ }
327
+ })();
328
+ return true;
329
+ },
330
+ waitReady(o) {
331
+ const binding = o.binding ? { ...o.binding } : undefined;
332
+ return ready(o.require, deadlineFor(o.timeoutMs), o.signal, syncNative(), binding, true);
333
+ },
334
+ async request(method, args, opts = {}) {
335
+ const toolMethod = ["task.create", "message.send", "inbox.read"].includes(method);
336
+ const receiptReplay = opts.receiptReplay !== undefined ? { ...opts.receiptReplay } : undefined;
337
+ if (receiptReplay &&
338
+ (!toolMethod ||
339
+ Object.keys(receiptReplay).length !== 1 ||
340
+ typeof receiptReplay.requestHash !== "string" ||
341
+ !/^[a-f0-9]{64}$/.test(receiptReplay.requestHash)))
342
+ throw channelError("invalid_request", "Invalid receipt-only tool request");
343
+ if ((method === "receipt.peek" || receiptReplay) && !opts.toolCallId)
344
+ throw channelError("invalid_request", "Receipt requests require a tool call identity");
345
+ if (activeRequests >= 64)
346
+ throw channelError("rate_limited", "Too many pending agent requests");
347
+ activeRequests++;
348
+ try {
349
+ const deadline = deadlineFor(opts.timeoutMs);
350
+ const deadlineAt = new Date(deadline).toISOString();
351
+ const feature = method.startsWith("policy.") ? "policies" : "agentRequests";
352
+ const binding = opts.binding ? { ...opts.binding } : undefined;
353
+ let initialNative = syncNative();
354
+ while (true) {
355
+ assertBinding(binding);
356
+ const c = await ready(feature, deadline, opts.signal, initialNative, binding);
357
+ assertBinding(binding);
358
+ // An awaited readiness promise may have been invalidated before this continuation.
359
+ if (opts.signal?.aborted)
360
+ throw channelError("conflict", "Request canceled");
361
+ if (now() >= deadline)
362
+ throw channelError("timeout", "Coordinator communication timed out");
363
+ initialNative ??= c.nativeSessionId;
364
+ if (syncNative() !== initialNative)
365
+ throw channelError("conflict", "Native session changed");
366
+ if (configuration !== c || !connected || !c.coordinatorConnected)
367
+ continue;
368
+ if (opts.bindingId !== undefined && c.bindingId !== opts.bindingId)
369
+ throw channelError("conflict", "Bridge binding changed during tool authorization");
370
+ const requestId = randomUUID();
371
+ const result = new Promise((resolve) => pending.set(requestId, { bindingId: c.bindingId, resolve }));
372
+ const sent = options.send({
373
+ type: "agent.request",
374
+ requestId,
375
+ sessionId: c.sessionId,
376
+ nativeSessionId: c.nativeSessionId,
377
+ runtimeId,
378
+ bindingId: c.bindingId,
379
+ context: contextIds(),
380
+ ...(opts.toolCallId ? { toolCallId: opts.toolCallId } : {}),
381
+ ...(receiptReplay ? { receiptReplay } : {}),
382
+ deadlineAt,
383
+ method,
384
+ args,
385
+ });
386
+ if (!sent) {
387
+ pending.delete(requestId);
388
+ connected = false;
389
+ wake();
390
+ continue;
391
+ }
392
+ let response;
393
+ const cancelWait = new AbortController();
394
+ const waitSignal = opts.signal
395
+ ? AbortSignal.any([opts.signal, cancelWait.signal])
396
+ : cancelWait.signal;
397
+ try {
398
+ response = await Promise.race([result, delay(deadline, waitSignal).then(() => null)]);
399
+ }
400
+ finally {
401
+ cancelWait.abort();
402
+ pending.delete(requestId);
403
+ }
404
+ assertBinding(binding);
405
+ if (!response)
406
+ continue;
407
+ if (binding && (!configuration || !connected || !configuration.coordinatorConnected))
408
+ continue;
409
+ if (response.ok)
410
+ return response.result;
411
+ if (response.error?.code === "host_unreachable" || response.error?.code === "timeout") {
412
+ const retryAt = Math.min(deadline, now() + 100);
413
+ try {
414
+ await delay(retryAt, opts.signal);
415
+ }
416
+ catch (error) {
417
+ if (error.code !== "timeout" || now() >= deadline)
418
+ throw error;
419
+ }
420
+ assertBinding(binding);
421
+ continue;
422
+ }
423
+ throw channelError(response.error?.code ?? "internal", response.error?.message ?? "Agent request failed", response.error?.details);
424
+ }
425
+ }
426
+ finally {
427
+ activeRequests--;
428
+ }
429
+ },
430
+ registerCommand(method, handler) {
431
+ if (handlers.has(method))
432
+ throw new Error(`Duplicate bridge handler: ${method}`);
433
+ handlers.set(method, handler);
434
+ return () => {
435
+ if (handlers.get(method) === handler)
436
+ handlers.delete(method);
437
+ };
438
+ },
439
+ noteHumanInput,
440
+ close() {
441
+ if (closed)
442
+ return;
443
+ closed = true;
444
+ invalidate();
445
+ },
446
+ };
447
+ return channel;
448
+ }
449
+ //# sourceMappingURL=agent-channel.js.map