@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

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 (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,2566 +0,0 @@
1
- import "./local-scope-DEuGAy8l.mjs";
2
- import { i as runDetached, r as observeSettled } from "./tasks-D_z5Yjjr.mjs";
3
- import { i as parsePiTuiAcpAccessStatus } from "./pi-tui-acp-access-contract-BdLwduU6.mjs";
4
- import { randomUUID } from "node:crypto";
5
- import { chmodSync, closeSync, constants, linkSync, lstatSync, mkdirSync, openSync, rmdirSync, unlinkSync } from "node:fs";
6
- import { join } from "node:path";
7
- import { connect, createServer } from "node:net";
8
- import { constants as constants$1 } from "node:buffer";
9
- import { PROTOCOL_VERSION, RequestError, agent, methods, ndJsonStream } from "@agentclientprotocol/sdk";
10
- //#region src/app/remote-process/local-acp-status.ts
11
- /** The one Owner-only authenticated route of the live ACP status observation. */
12
- const LOCAL_ACP_STATUS_ROUTE = "/api/pi-tui.acp-status";
13
- /** Hard cap on the status response body; the DTO is a few hundred bytes. */
14
- const LOCAL_ACP_STATUS_MAX_BYTES = 1024;
15
- /** Bound on the one observation request. */
16
- const LOCAL_ACP_STATUS_TIMEOUT_MS = 3e3;
17
- /**
18
- * The route handler. It is registered under the official Connection Owner's
19
- * authenticated admission (the SAME owner as the identity echo), so an
20
- * unauthenticated request is refused BEFORE this handler. It reads the live
21
- * controller ONCE and performs no mutation.
22
- *
23
- * @param instanceId - this Host's published instance id (the observer's echo).
24
- * @param controller - the Host-entry-owned runtime ACP controller.
25
- * @returns the registered route's `fetch` callback.
26
- */
27
- function createLocalAcpStatusHandler(instanceId, controller) {
28
- return async () => {
29
- const payload = {
30
- schema: 1,
31
- instanceId,
32
- status: await controller.getStatus()
33
- };
34
- return Response.json(payload, { headers: {
35
- "content-type": "application/json",
36
- "cache-control": "no-store"
37
- } });
38
- };
39
- }
40
- /** Drain the body within the byte cap; an oversized/unreadable body is absent. */
41
- async function readBoundedBody(response) {
42
- if (response.body === null) return "";
43
- const reader = response.body.getReader();
44
- const chunks = [];
45
- let total = 0;
46
- try {
47
- for (;;) {
48
- const { done, value } = await reader.read();
49
- if (done) break;
50
- total += value.byteLength;
51
- if (total > LOCAL_ACP_STATUS_MAX_BYTES) {
52
- await reader.cancel();
53
- return;
54
- }
55
- chunks.push(value);
56
- }
57
- } finally {
58
- reader.releaseLock();
59
- }
60
- return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
61
- }
62
- /** Cancel an unread body without observing it. */
63
- async function discard(response) {
64
- try {
65
- await response.body?.cancel();
66
- } catch {}
67
- }
68
- /**
69
- * Observe the running Host's live ACP listener status through the authenticated
70
- * read-only route. This is the ONLY headless observation; it never creates a
71
- * controller, never calls `setEnabled`, and never caches the result.
72
- *
73
- * Every external-boundary failure category is `undefined` (the caller's
74
- * `unavailable`), including an instance id that does not match the Host the
75
- * Cookie was issued for: a response from a replaced/foreign Host can never be
76
- * attributed to this observation.
77
- *
78
- * @param verified - the already authenticated Host record and in-memory cookie.
79
- * @returns the validated live listener status, or `undefined` when unprovable.
80
- */
81
- async function observeAuthenticatedLocalAcpStatus(verified) {
82
- const request = {
83
- method: "GET",
84
- headers: { cookie: verified.cookie },
85
- redirect: "manual",
86
- cache: "no-store",
87
- signal: AbortSignal.timeout(LOCAL_ACP_STATUS_TIMEOUT_MS)
88
- };
89
- let response;
90
- try {
91
- response = await fetch(`${verified.record.origin}${LOCAL_ACP_STATUS_ROUTE}`, request);
92
- } catch {
93
- return;
94
- }
95
- if (response.status !== 200) {
96
- await discard(response);
97
- return;
98
- }
99
- const contentType = response.headers.get("content-type") ?? "";
100
- const cacheControl = response.headers.get("cache-control") ?? "";
101
- if (!/^application\/json\b/iu.test(contentType) || !/\bno-store\b/iu.test(cacheControl)) {
102
- await discard(response);
103
- return;
104
- }
105
- let text;
106
- try {
107
- const body = await readBoundedBody(response);
108
- if (body === void 0) return void 0;
109
- text = body;
110
- } catch {
111
- return;
112
- }
113
- let value;
114
- try {
115
- value = JSON.parse(text);
116
- } catch {
117
- return;
118
- }
119
- if (typeof value !== "object" || value === null) return void 0;
120
- const record = value;
121
- if (Object.keys(record).length !== 3 || record.schema !== 1 || typeof record.instanceId !== "string" || record.instanceId !== verified.identity.instanceId) return;
122
- try {
123
- return parsePiTuiAcpAccessStatus(record.status);
124
- } catch {
125
- return;
126
- }
127
- }
128
- //#endregion
129
- //#region src/app/remote-process/local-acp-session-view.ts
130
- /**
131
- * Connection-scoped Host ACP Session View.
132
- *
133
- * The Host-owned local ACP v1 listener (PO-1/PO-1B) is a protocol front door
134
- * that owns NO Agent, Session or business method. PO-2 adds the narrowest
135
- * shared-Session capability on top of that same `<scope.dir>/acp.sock`: one
136
- * ACP connection may BORROW at most one live Host Session, while the Session's
137
- * own Agent/Session/Writer authority stays entirely with the official Host
138
- * services. This module owns ONLY the ephemeral, per-listener reservation map
139
- * and the pure connection View lifecycle; it never subscribes to, resumes on
140
- * its own, cancels, disposes or flushes any Host Agent, and it never persists
141
- * an ACP mapping.
142
- *
143
- * The authority boundaries this module must respect:
144
- * - Session create/resume is `sessionController.create` / `resolveAgent`
145
- * (the SAME Host services), never `ctx.agents.create/resume`.
146
- * - The Host Workspace Controller is the only directory authority for
147
- * `session/new`; the client cwd is a proposal only.
148
- * - `close` detaches ONLY this connection's View. It never touches a shared
149
- * Agent so a human Split TUI Client that also references the Session keeps
150
- * working, and a later connection may attach again.
151
- *
152
- * A single connection follows the transient protocol view
153
- * `idle -> attaching -> attached -> idle|closed`. The reservation is committed
154
- * with a synchronous `Map.set()` BEFORE any official Host await, so a second
155
- * request on the same connection, or a competing connection, is refused before
156
- * it can create a second Host business resource. A late async result only
157
- * commits when its own connection state is still the same live one.
158
- *
159
- * PO-3A adds ONE prompt flight per attached View. The View mints the official
160
- * `requestId`, submits the official Session Controller prompt exactly once in
161
- * queue mode, and correlates the real Host facts back to that exact request:
162
- * `source.rpcId === requestId` at `agent/inbox/inserted`, the claimed
163
- * `agent/inbox/claimed` turn for that exact message id, and the committed
164
- * Session events carrying that same `data.turn`. It projects only that turn's
165
- * committed output as standard ACP `session/update` notifications, drains them,
166
- * and only then answers a real ACP StopReason. A turn that also claims another
167
- * user's message is a MIXED turn: no further output is projected and the
168
- * request fails closed instead of returning a fabricated success.
169
- *
170
- * PO-4C widens that projection to the standard committed content of
171
- * `assistant/message` and `tool/result`: ordered text, thought chunks and
172
- * images, where every image is re-read and integrity-verified by the official
173
- * Host Attachment Store before its canonical Base64 reaches the wire. The
174
- * conversion runs INSIDE the flight's single `outputTail`, so a committed
175
- * event's asynchronous image read never lets a later event overtake it; a
176
- * content conversion failure fails the request instead of sending a partial
177
- * event as success.
178
- *
179
- * @module app/remote-process/local-acp-session-view
180
- */
181
- /**
182
- * One classified View rejection. `rpcCode` is the JSON-RPC error code the
183
- * listener maps onto an ACP `RequestError`; `code` is the stable data code.
184
- * `data` carries non-sensitive structured facts the caller may act on — most
185
- * importantly the authoritative `sessionId` of a Session the Host already
186
- * created before a later step failed.
187
- */
188
- var LocalAcpViewError = class extends Error {
189
- code;
190
- rpcCode;
191
- data;
192
- constructor(code, message, rpcCode, data = {}) {
193
- super(message);
194
- this.name = "LocalAcpViewError";
195
- this.code = code;
196
- this.rpcCode = rpcCode;
197
- this.data = data;
198
- }
199
- };
200
- /** Raster MIME vocabulary shared by the ACP wire and official Host admission. */
201
- const ACP_IMAGE_MEDIA_TYPES = [
202
- "image/png",
203
- "image/jpeg",
204
- "image/webp",
205
- "image/gif"
206
- ];
207
- /** The maximum number of not-yet-written notifications ONE prompt flight may queue. */
208
- const MAX_PENDING_OUTPUT_UPDATES = 64;
209
- const JSONRPC_INVALID_PARAMS = -32602;
210
- const JSONRPC_INTERNAL_ERROR = -32603;
211
- /** One standard classified prompt failure. */
212
- function promptError(code, message, rpcCode, data = {}) {
213
- return new LocalAcpViewError(code, message, rpcCode, data);
214
- }
215
- /** A stable code from a rejecting Host call, never its message or stack. */
216
- function hostErrorCode(error) {
217
- if (typeof error === "object" && error !== null && "code" in error) {
218
- const code = error.code;
219
- if (typeof code === "string" && code.length > 0) return code;
220
- }
221
- }
222
- /** The committed turn reason facts the View reads (`TurnEndReason` is wider). */
223
- function turnEndReasonKind(data) {
224
- const reason = data?.reason;
225
- return typeof reason?.kind === "string" ? reason.kind : void 0;
226
- }
227
- /**
228
- * Whether one committed `turn/end` proves a USER cancellation: the official
229
- * `aborted` reason whose nested cause is exactly `{kind:'user'}`. Any other
230
- * abort cause (parent/hook/disposed/legacy) is NOT this user's cancellation.
231
- */
232
- function turnEndUserAborted(data) {
233
- const reason = data?.reason;
234
- return reason?.kind === "aborted" && reason.reason?.kind === "user";
235
- }
236
- /**
237
- * The pure View/claim lifecycle. The registry's lifetime is owned by its
238
- * OWNER: the ACP controller holds ONE registry across listener rebinds so a
239
- * retired-turn approval fence and the one-View-per-Session rule survive an
240
- * Off -> On cycle, and that same registry carries the ONE Host fact/approval
241
- * subscription; a raw-socket listener without a controller creates a
242
- * bind-local registry and owns both its claims and its subscription.
243
- */
244
- var AcpSessionViewRegistry = class {
245
- claims = /* @__PURE__ */ new Map();
246
- /** Waiters for "every claim's Host work settled" (listener retirement). */
247
- workWaiters = /* @__PURE__ */ new Set();
248
- /** The ONE Host fact/approval subscription of this registry (R701-03). */
249
- factsDisposer;
250
- diag;
251
- /**
252
- * The Host access the fact callbacks may act through. It is bound exactly
253
- * once when the listener installs its fact subscription (the same lifetime
254
- * that owns these callbacks) and is never a second authority.
255
- */
256
- access;
257
- constructor(diag) {
258
- this.diag = diag;
259
- }
260
- /**
261
- * Install the ONE Host fact/approval subscription for this registry, if it
262
- * is not installed yet. The subscription belongs to the REGISTRY's owner
263
- * (a bind-local registry is owned by its listener; the controller-owned
264
- * registry outlives listener rebinds), never to an individual bind — an
265
- * Off -> On overlap must not register the same registry twice (R701-03).
266
- */
267
- observeFacts(access) {
268
- this.bindAccess(access);
269
- if (this.factsDisposer !== void 0) return;
270
- this.factsDisposer = access.observePromptFacts(this);
271
- }
272
- /** Whether the ONE Host fact subscription is currently installed. */
273
- hasFactsObserver() {
274
- return this.factsDisposer !== void 0;
275
- }
276
- /** Dispose the ONE Host fact subscription (idempotent). */
277
- disposeFacts() {
278
- const dispose = this.factsDisposer;
279
- this.factsDisposer = void 0;
280
- dispose?.();
281
- }
282
- /** Bind the ONE Host access the prompt-fact lifecycle may act through. */
283
- bindAccess(access) {
284
- this.access = access;
285
- }
286
- /** Create a fresh connection-scoped view state. */
287
- createConnection() {
288
- return {
289
- phase: "idle",
290
- op: 0
291
- };
292
- }
293
- /** The number of live reservations/attachments (qualification diagnosis only). */
294
- claimCount() {
295
- return this.claims.size;
296
- }
297
- /**
298
- * Whether ANY claim still owns unsettled Host work that the prompt-fact
299
- * subscription must keep observing: an open flight (pending admission,
300
- * queued message, running turn or its drain) or a detached retired-turn
301
- * approval fence. When this is false, retiring the Host fact subscription
302
- * can no longer strand any accepted ACP work (R701-01).
303
- */
304
- hasUnsettledHostWork() {
305
- for (const claim of this.claims.values()) {
306
- if (claim.inflight !== void 0 && !claim.inflight.settledDone) return true;
307
- if (claim.retiringTurn !== void 0) return true;
308
- if (claim.unclaimedHostObligation !== void 0) return true;
309
- }
310
- return false;
311
- }
312
- /**
313
- * Resolve when every claim's Host work has settled: flights completed or
314
- * failed, detached fences ended at their own death facts. Event-driven: the
315
- * settlement transitions notify the waiters, no polling.
316
- */
317
- whenHostWorkSettled() {
318
- if (!this.hasUnsettledHostWork()) return Promise.resolve();
319
- const waiter = Promise.withResolvers();
320
- this.workWaiters.add(waiter);
321
- return waiter.promise;
322
- }
323
- /** Notify (and drop) every work waiter after a settlement transition. */
324
- notifyWorkSettled() {
325
- if (this.hasUnsettledHostWork()) return;
326
- const waiters = [...this.workWaiters];
327
- this.workWaiters.clear();
328
- for (const waiter of waiters) waiter.resolve();
329
- }
330
- /** Whether a Session is currently reserved or attached by ANY connection. */
331
- hasClaim(sessionId) {
332
- return this.claims.has(sessionId);
333
- }
334
- /** The current phase of one connection (qualification diagnosis only). */
335
- phaseOf(state) {
336
- return state.phase;
337
- }
338
- /**
339
- * Attach a freshly created Host Session to this connection's View. `session/new`
340
- * creates ONE Host Workspace, then ONE Host Session, then borrows the official
341
- * live Agent. The failure category is decided by the HOST result: a definite
342
- * directory rejection, a peer-visible attachment failure that PRESERVES the
343
- * real created Session id, an unconfirmed outcome, or success. It is never
344
- * retried and never rolled back.
345
- */
346
- async newSession(state, access, request) {
347
- const op = this.beginAttach(state);
348
- try {
349
- this.validateNew(request);
350
- } catch (error) {
351
- this.resetIdleIfCurrent(state, op);
352
- throw error;
353
- }
354
- const workspace = await access.createWorkspace(request.cwd);
355
- if (workspace.kind === "indeterminate") {
356
- this.resetIdleIfCurrent(state, op);
357
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_WORKSPACE_UNAVAILABLE", "the Host could not register the workspace; the outcome is unconfirmed", JSONRPC_INTERNAL_ERROR);
358
- }
359
- if (!this.isCurrentOp(state, op)) throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection closed before the session was created", JSONRPC_INVALID_PARAMS);
360
- const created = await access.createSession(workspace.workspaceId);
361
- if (created.kind === "rejected") {
362
- this.resetIdleIfCurrent(state, op);
363
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "the Host rejected the session create request", JSONRPC_INVALID_PARAMS);
364
- }
365
- if (created.kind === "published-with-error") {
366
- this.resetIdleIfCurrent(state, op);
367
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CREATE_ATTACH_FAILED", "the Host created the session but a later step failed", JSONRPC_INTERNAL_ERROR, { sessionId: created.sessionId });
368
- }
369
- if (created.kind === "indeterminate") {
370
- this.resetIdleIfCurrent(state, op);
371
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CREATE_INDETERMINATE", "the Host did not confirm the new session; it may or may not exist", JSONRPC_INTERNAL_ERROR);
372
- }
373
- const sessionId = created.sessionId;
374
- if (!this.isCurrentOp(state, op)) throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection closed before the session view attached", JSONRPC_INVALID_PARAMS, { sessionId });
375
- if (this.claims.has(sessionId)) {
376
- this.resetIdleIfCurrent(state, op);
377
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_ALREADY_ATTACHED", "the new session is already attached to an ACP view", JSONRPC_INVALID_PARAMS);
378
- }
379
- const claim = {
380
- connectionIdentity: state,
381
- sessionId
382
- };
383
- this.claims.set(sessionId, claim);
384
- const agent = await this.resolveForView(access, state, op, claim);
385
- this.commitAttached(state, op, claim, access, agent);
386
- return { sessionId };
387
- }
388
- /**
389
- * Attach an EXISTING Session to this connection's View. The official
390
- * `resolveAgent` is the only cold-resume owner; a live Session borrows the
391
- * same Agent object. The request cwd never changes the Host Session.
392
- */
393
- async resumeSession(state, access, request) {
394
- const op = this.beginAttach(state);
395
- try {
396
- this.validateResume(request);
397
- } catch (error) {
398
- this.resetIdleIfCurrent(state, op);
399
- throw error;
400
- }
401
- const sessionId = request.sessionId;
402
- if (this.claims.has(sessionId)) {
403
- this.resetIdleIfCurrent(state, op);
404
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_ALREADY_ATTACHED", "the session is already attached to an ACP view", JSONRPC_INVALID_PARAMS);
405
- }
406
- const claim = {
407
- connectionIdentity: state,
408
- sessionId
409
- };
410
- this.claims.set(sessionId, claim);
411
- const agent = await this.resolveForView(access, state, op, claim);
412
- if (agent.session.header.cwd !== request.cwd) this.diag.warn("local-acp.view.cwd-mismatch", { mismatch: true });
413
- this.commitAttached(state, op, claim, access, agent);
414
- return {};
415
- }
416
- /**
417
- * Detach ONLY this connection's View for one Session. PO-3B: when a prompt
418
- * flight is still open, the close FIRST drives the same scoped cancellation
419
- * and waits for its real settlement (durable queued removal or the exact
420
- * running turn's terminal plus the output drain); only a proven settlement
421
- * detaches the View. A repeated close awaits the SAME settlement; a close of
422
- * a Session this connection never held is still refused. The Host Agent and
423
- * Session always stay alive; no other connection's claim is touched.
424
- */
425
- async closeSession(state, access, sessionId) {
426
- const claim = this.claims.get(sessionId);
427
- if (claim === void 0 || claim.connectionIdentity !== state) {
428
- if (state.lastClosedSessionId === sessionId) return {};
429
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_NOT_OWNED", "this ACP connection holds no view for that session", JSONRPC_INVALID_PARAMS);
430
- }
431
- if (claim.detachedWithFence) return {};
432
- const inFlightAttempt = claim.closing;
433
- if (inFlightAttempt !== void 0) return await inFlightAttempt;
434
- const attempt = this.closeClaim(state, sessionId, claim, access);
435
- claim.closing = attempt;
436
- try {
437
- return await attempt;
438
- } finally {
439
- if (claim.closing === attempt) claim.closing = void 0;
440
- }
441
- }
442
- /**
443
- * One close attempt against the CURRENT official Host facts (v1.1 §4): a
444
- * safe detach needs a real terminal proof — an exact queued removal, the
445
- * owned turn's `turn/end` (or its exact Agent's disposal), or a definite
446
- * pre-insertion admission rejection. A local flight having disappeared is
447
- * never such a proof.
448
- */
449
- async closeClaim(state, sessionId, claim, access) {
450
- const obligation = claim.unclaimedHostObligation;
451
- if (obligation !== void 0) {
452
- if (obligation.messageId !== void 0 && claim.exactAgent !== void 0 && claim.exactSession !== void 0) {
453
- if (access.cancelPending(sessionId, claim.exactAgent, claim.exactSession, obligation.messageId) === "removed") this.dropUnclaimedObligation(claim);
454
- }
455
- if (claim.unclaimedHostObligation !== void 0) throw promptError("LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED", "the accepted prompt has no proven Host terminal status yet", JSONRPC_INTERNAL_ERROR);
456
- }
457
- const flight = claim.inflight;
458
- if (flight !== void 0) {
459
- const outcome = await this.cancelOwnedFlight(claim, flight, access, "closing").then(() => "ok", (error) => error);
460
- if (outcome !== "ok") {
461
- if (!(flight.ownTurnEnded || flight.failureCode === "LOCAL_ACP_PROMPT_HOST_REJECTED")) throw outcome;
462
- }
463
- }
464
- if (claim.unclaimedHostObligation !== void 0) throw promptError("LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED", "the accepted prompt has no proven Host terminal status yet", JSONRPC_INTERNAL_ERROR);
465
- return this.finishClose(state, sessionId, claim);
466
- }
467
- /** End one unclaimed obligation on a real terminal fact. A discarded notice
468
- * only schedules a checkpoint; official pending absence is verified later.
469
- */
470
- dropUnclaimedObligation(claim) {
471
- claim.unclaimedHostObligation = void 0;
472
- this.releaseDetachedIfSettled(claim);
473
- this.notifyWorkSettled();
474
- }
475
- /**
476
- * The official admission of a flight that already settled while its
477
- * obligation was still `pending`: a definite pre-insertion rejection proves
478
- * nothing was admitted (terminal), while an accepted admission keeps the
479
- * obligation for the exact late-insertion/terminal fact (v1.1 §5.A.4).
480
- */
481
- settleUnclaimedAdmission(claim, flight) {
482
- const obligation = claim.unclaimedHostObligation;
483
- if (obligation === void 0 || obligation.requestId !== flight.requestId) return;
484
- if (obligation.admission !== "pending") return;
485
- if (flight.failureCode === "LOCAL_ACP_PROMPT_HOST_REJECTED") {
486
- this.dropUnclaimedObligation(claim);
487
- return;
488
- }
489
- obligation.admission = "accepted";
490
- this.notifyWorkSettled();
491
- }
492
- retainRetiringTurn(claim, turn) {
493
- const existing = claim.retiringTurn;
494
- if (existing !== void 0 && existing.turn !== turn.turn) {
495
- const current = claim.exactAgent !== void 0 && claim.exactSession !== void 0 ? this.access?.currentTurn(claim.sessionId, claim.exactAgent, claim.exactSession) : void 0;
496
- if (current?.kind === "current" && current.openTurn === existing.turn) return;
497
- }
498
- claim.retiringTurn = turn;
499
- }
500
- /** Release a detached claim once no Host obligation or fence remains. */
501
- releaseDetachedIfSettled(claim) {
502
- if (!claim.detachedWithFence) return;
503
- if (claim.inflight !== void 0) return;
504
- if (claim.retiringTurn !== void 0) return;
505
- if (claim.unclaimedHostObligation !== void 0) return;
506
- if (this.claims.get(claim.sessionId) === claim) this.claims.delete(claim.sessionId);
507
- }
508
- /** Release one settled claim and record the idempotent close fact. */
509
- finishClose(state, sessionId, claim) {
510
- if (this.claims.get(sessionId) !== claim || claim.detachedWithFence || state.phase === "closed") return {};
511
- if (claim.retiringTurn !== void 0) claim.detachedWithFence = true;
512
- else if (this.claims.get(sessionId) === claim) {
513
- this.claims.delete(sessionId);
514
- this.notifyWorkSettled();
515
- }
516
- state.phase = "idle";
517
- state.lastClosedSessionId = sessionId;
518
- return {};
519
- }
520
- /**
521
- * PO-3B scoped `session/cancel`: ONLY this connection's own unsettled flight
522
- * is addressed — a queued message by its exact durable inbox removal, a
523
- * running turn by the official same-stack user cancel of that exact current
524
- * turn. An idle View (and any Session this connection does not own) is a
525
- * no-op that never touches a Host Agent; a mixed owned turn is NOT cancelled
526
- * (the TUI steer inside it keeps its authority) and keeps the D23 failure.
527
- */
528
- cancelSession(state, access, sessionId) {
529
- const claim = this.claims.get(sessionId);
530
- if (claim === void 0 || claim.connectionIdentity !== state || claim.detachedWithFence) return;
531
- const flight = claim.inflight;
532
- if (flight === void 0 || flight.settledDone) return;
533
- flight.cancelRequested = true;
534
- this.addressCancelIntent(claim, flight, access);
535
- }
536
- /**
537
- * Drive ONE scoped cancellation to its real settlement. The returned promise
538
- * resolves only when the cancellation is PROVEN (durable removal committed
539
- * and the admission classified, or the exact turn's real `turn/end` plus the
540
- * output drain); it rejects with `LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED` when
541
- * no legal proof can be obtained. The ACP request's own settlement (a real
542
- * `cancelled` stop reason or its true failure) happens through the SAME
543
- * flight settlement path this method feeds, never beside it.
544
- */
545
- async cancelOwnedFlight(claim, flight, access, reason) {
546
- if (reason === "disconnect" || reason === "closing") {
547
- flight.deliveryClosed = true;
548
- this.stopFlightOutput(flight);
549
- }
550
- flight.cancelRequested = true;
551
- this.addressCancelIntent(claim, flight, access);
552
- if (flight.admissionSettled && flight.messageId === void 0 && flight.cancelKind === void 0 && !flight.settledDone && Object.is(access.currentAgent(claim.sessionId), claim.exactAgent) && Object.is(access.currentSession(claim.sessionId), claim.exactSession)) {
553
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_ABORTED", "the ACP prompt request was aborted before a real Host settlement", JSONRPC_INTERNAL_ERROR));
554
- return;
555
- }
556
- const outcome = await flight.settled.promise.then(() => "settled", (error) => error);
557
- if (reason === "disconnect") return;
558
- if (outcome === "settled") return;
559
- if (flight.ownTurnEnded) return;
560
- throw outcome;
561
- }
562
- /**
563
- * Address the cancellation intent against the CURRENT Host facts. This is
564
- * the single decision point for every entry (notification, close, insert
565
- * callback, claim callback): a queued message is removed exactly; a running
566
- * owned turn is user-cancelled in the same stack only when the official
567
- * current-turn fence still matches; a mixed turn is never cancelled; an
568
- * admission still in flight keeps its intent for the insertion callback.
569
- */
570
- addressCancelIntent(claim, flight, access) {
571
- if (flight.settledDone || flight.cancelKind !== void 0) return;
572
- const session = claim.exactSession;
573
- const agent = claim.exactAgent;
574
- const sessionId = claim.sessionId;
575
- if (session === void 0 || agent === void 0) return;
576
- if (flight.turn === void 0) {
577
- if (flight.messageId === void 0) return;
578
- if (flight.mixed) return;
579
- const removed = access.cancelPending(sessionId, agent, session, flight.messageId);
580
- if (removed === "removed") {
581
- flight.cancelKind = "queued-removed";
582
- this.stopFlightOutput(flight);
583
- this.settleQueuedRemoval(claim, flight);
584
- return;
585
- }
586
- if (removed === "stale") {
587
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED", "the queued cancellation could not be proven on the exact live Agent", JSONRPC_INTERNAL_ERROR));
588
- return;
589
- }
590
- return;
591
- }
592
- if (flight.mixed) return;
593
- const addressed = access.cancelCurrentTurn(sessionId, agent, session, flight.turn);
594
- if (addressed === "addressed") {
595
- flight.cancelKind = "running-addressed";
596
- this.stopFlightOutput(flight);
597
- return;
598
- }
599
- if (addressed === "stale") {
600
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED", "the running-turn cancellation could not be proven on the exact live Agent", JSONRPC_INTERNAL_ERROR));
601
- return;
602
- }
603
- }
604
- /**
605
- * Complete a proven queued removal: the durable splice committed. The
606
- * completion waits for the admission path's classification (accepted or a
607
- * definite rejection) through the flight's `admissionSettled` promise so the
608
- * client never learns "cancelled" for a prompt the Host actually rejected.
609
- */
610
- settleQueuedRemoval(claim, flight) {
611
- runDetached("local acp: queued-cancel settlement", async () => {
612
- await flight.admissionSettledPromise;
613
- await flight.outputTail;
614
- if (flight.settledDone) return;
615
- this.completePrompt(claim, flight, { stopReason: "cancelled" });
616
- }, { diag: this.diag });
617
- }
618
- /**
619
- * Admit one ACP text/resource_link/image prompt on this connection's attached View and
620
- * settle it on the exact Host facts. The slot and the View-minted `requestId` are committed
621
- * BEFORE the official prompt call, so a synchronous inbox notice or a second
622
- * pipelined request can never be attributed to a later flight.
623
- *
624
- * The returned promise settles only from real Host facts: the claimed turn of
625
- * THIS message id, that turn's committed events, its `turn/end`, and the
626
- * ordered notification drain. No status, text, timestamp or ACK is treated as
627
- * a completed turn.
628
- */
629
- async promptSession(state, access, request, requestSignal, imageEnabled, sendUpdate, requestPermission) {
630
- if (typeof request.sessionId !== "string" || request.sessionId.length === 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "a non-empty sessionId is required", JSONRPC_INVALID_PARAMS);
631
- const claim = this.claims.get(request.sessionId);
632
- if (state.phase !== "attached" || claim === void 0 || claim.connectionIdentity !== state || claim.detachedWithFence || claim.exactAgent === void 0 || claim.exactSession === void 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_NOT_OWNED", "this ACP connection holds no view for that session", JSONRPC_INVALID_PARAMS);
633
- if (claim.inflight !== void 0 || claim.unclaimedHostObligation !== void 0) throw promptError("LOCAL_ACP_PROMPT_IN_FLIGHT", "a prompt is already in flight for this session view", JSONRPC_INVALID_PARAMS);
634
- const content = validatePromptContent(request.prompt, imageEnabled);
635
- if (requestSignal.aborted) throw promptError("LOCAL_ACP_PROMPT_ABORTED", "the ACP prompt request was aborted before admission", JSONRPC_INVALID_PARAMS);
636
- if (!Object.is(access.currentAgent(request.sessionId), claim.exactAgent) || !Object.is(access.currentSession(request.sessionId), claim.exactSession)) throw promptError("LOCAL_ACP_PROMPT_STALE_AGENT", "the borrowed Session Agent changed since this View attached; the prompt was not dispatched", JSONRPC_INVALID_PARAMS);
637
- const currentAtFlightStart = access.currentTurn(request.sessionId, claim.exactAgent, claim.exactSession);
638
- if (currentAtFlightStart.kind === "stale") throw promptError("LOCAL_ACP_PROMPT_STALE_AGENT", "the borrowed turn identity changed before admission", JSONRPC_INVALID_PARAMS);
639
- const admission = Promise.withResolvers();
640
- const outputAbort = new AbortController();
641
- const flight = {
642
- requestId: randomUUID(),
643
- phase: "admitting",
644
- ...currentAtFlightStart.openTurn === null ? {} : { turnProvenance: {
645
- turn: currentAtFlightStart.openTurn,
646
- origin: claim.retiringTurn?.turn === currentAtFlightStart.openTurn ? claim.retiringTurn.origin : "tui"
647
- } },
648
- mixed: false,
649
- assistantVisibleOutput: false,
650
- pendingUpdates: 0,
651
- outputTail: Promise.resolve(),
652
- sendUpdate,
653
- requestPermission,
654
- settled: Promise.withResolvers(),
655
- settledDone: false,
656
- cancelRequested: false,
657
- admissionSettled: false,
658
- admissionSettledPromise: admission.promise,
659
- settleAdmission: () => {
660
- if (flight.admissionSettled) return;
661
- flight.admissionSettled = true;
662
- admission.resolve();
663
- },
664
- deliveryClosed: false,
665
- outputAbort,
666
- outputSignal: outputAbort.signal,
667
- outputStopped: false,
668
- outputTasksQueued: 0,
669
- ownTurnEnded: false,
670
- permissionRequests: /* @__PURE__ */ new Map()
671
- };
672
- observeSettled(flight.settled.promise, () => {});
673
- const onAbort = () => {
674
- flight.deliveryClosed = true;
675
- this.stopFlightOutput(flight);
676
- this.abortPermissionRequests(flight);
677
- if (!flight.settledDone && !flight.cancelRequested) {
678
- flight.cancelRequested = true;
679
- if (this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
680
- }
681
- };
682
- requestSignal.addEventListener("abort", onAbort, { once: true });
683
- flight.detachAbort = () => requestSignal.removeEventListener("abort", onAbort);
684
- claim.inflight = flight;
685
- try {
686
- await access.prompt({
687
- requestId: flight.requestId,
688
- sessionId: request.sessionId,
689
- mode: "queue",
690
- content
691
- }, requestSignal);
692
- if (!flight.settledDone) {
693
- const stillExact = Object.is(access.currentAgent(request.sessionId), claim.exactAgent) && Object.is(access.currentSession(request.sessionId), claim.exactSession);
694
- if (flight.messageId === void 0 && !stillExact) this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_STALE_AGENT", "the accepted prompt was not observed on the Agent generation this View attached; it was not re-dispatched", JSONRPC_INTERNAL_ERROR));
695
- else if (flight.messageId === void 0 && flight.deliveryClosed && flight.cancelRequested) this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_ABORTED", "the ACP prompt request was aborted before a real Host settlement", JSONRPC_INTERNAL_ERROR));
696
- else flight.phase = "queued";
697
- }
698
- } catch (error) {
699
- if (!flight.settledDone) {
700
- if (flight.messageId !== void 0) this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_DISPATCH_INDETERMINATE", "the Host prompt outcome could not be confirmed after dispatch; it was not retried", JSONRPC_INTERNAL_ERROR));
701
- else {
702
- const hostCode = hostErrorCode(error);
703
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_HOST_REJECTED", "the Host did not accept the prompt", JSONRPC_INTERNAL_ERROR, hostCode === void 0 ? {} : { hostCode }));
704
- }
705
- }
706
- } finally {
707
- flight.settleAdmission();
708
- this.settleUnclaimedAdmission(claim, flight);
709
- }
710
- return await flight.settled.promise;
711
- }
712
- /** The source of a turn already open when this exact ACP message is inserted. */
713
- turnProvenanceAtOwnInsertion(claim, agent) {
714
- const session = claim.exactSession;
715
- const access = this.access;
716
- if (session === void 0 || access === void 0) return void 0;
717
- const checkpoint = access.currentTurn(claim.sessionId, agent, session);
718
- if (checkpoint.kind === "stale") return {
719
- turn: null,
720
- origin: "unknown"
721
- };
722
- if (checkpoint.openTurn === null) return void 0;
723
- return {
724
- turn: checkpoint.openTurn,
725
- origin: claim.retiringTurn?.turn === checkpoint.openTurn ? claim.retiringTurn.origin : "tui"
726
- };
727
- }
728
- /** One message entered or re-entered the live inbox: correlate the View-minted request id. */
729
- onInboxInserted(agent, message) {
730
- const rpcId = message.source?.kind === "user" ? message.source.rpcId : void 0;
731
- for (const claim of this.claims.values()) {
732
- const obligation = claim.unclaimedHostObligation;
733
- if (obligation !== void 0 && claim.exactAgent === agent && (obligation.messageId === message.id || obligation.messageId === void 0 && rpcId !== void 0 && rpcId === obligation.requestId)) {
734
- const firstInsertion = obligation.messageId === void 0;
735
- obligation.messageId = message.id;
736
- obligation.turnProvenance = this.turnProvenanceAtOwnInsertion(claim, agent);
737
- if (firstInsertion && claim.exactSession !== void 0 && this.access !== void 0) {
738
- if (this.access.cancelPending(claim.sessionId, agent, claim.exactSession, message.id) === "removed") this.dropUnclaimedObligation(claim);
739
- }
740
- }
741
- const flight = claim.inflight;
742
- if (flight === void 0 || flight.settledDone) continue;
743
- if (claim.exactAgent !== agent) {
744
- if (rpcId !== void 0 && rpcId === flight.requestId && flight.messageId === void 0) this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_STALE_AGENT", "the prompt was accepted by a different Agent generation than this View attached", JSONRPC_INTERNAL_ERROR));
745
- continue;
746
- }
747
- if (flight.messageId !== message.id && (flight.messageId !== void 0 || rpcId === void 0 || rpcId !== flight.requestId)) continue;
748
- flight.messageId = message.id;
749
- flight.turnProvenance = this.turnProvenanceAtOwnInsertion(claim, agent);
750
- if (flight.cancelRequested && this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
751
- }
752
- }
753
- /**
754
- * One message was claimed. The exact message id (never text or timing) links
755
- * the prompt to its turn; any other user message claimed into that same turn
756
- * proves the turn is MIXED.
757
- */
758
- onInboxClaimed(agent, message, turn) {
759
- for (const claim of this.claims.values()) {
760
- if (claim.exactAgent !== agent) continue;
761
- const obligation = claim.unclaimedHostObligation;
762
- if (obligation !== void 0 && obligation.messageId === message.id) {
763
- claim.unclaimedHostObligation = void 0;
764
- this.retainRetiringTurn(claim, {
765
- turn,
766
- origin: obligation.turnProvenance?.turn === turn ? obligation.turnProvenance.origin : "acp"
767
- });
768
- this.notifyWorkSettled();
769
- }
770
- const flight = claim.inflight;
771
- if (flight === void 0 || flight.settledDone) continue;
772
- if (flight.messageId !== void 0 && message.id === flight.messageId) {
773
- if (flight.turn === void 0) {
774
- flight.turn = turn;
775
- if (flight.phase === "admitting" || flight.phase === "queued") flight.phase = "claimed";
776
- if (flight.turnProvenance?.turn === turn || flight.foreignTurn === turn) this.markFlightMixed(flight);
777
- flight.foreignTurn = void 0;
778
- if (flight.cancelRequested && this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
779
- }
780
- continue;
781
- }
782
- if (flight.turn !== void 0) {
783
- if (flight.turn === turn) this.markFlightMixed(flight);
784
- continue;
785
- }
786
- flight.foreignTurn = turn;
787
- }
788
- }
789
- /**
790
- * One committed Session event. Only the exact Session object and the owned
791
- * turn are projected; every other event is inert for this View.
792
- */
793
- onSessionEvent(session, event) {
794
- for (const claim of this.claims.values()) {
795
- if (claim.exactSession !== session) continue;
796
- const data = event.data;
797
- if (event.type === "turn/end" && typeof data?.turn === "number" && claim.retiringTurn?.turn === data.turn) this.endRetiringFence(claim.sessionId, claim);
798
- const flight = claim.inflight;
799
- if (flight === void 0 || flight.settledDone) continue;
800
- if (typeof data?.turn !== "number" || flight.turn === void 0 || data.turn !== flight.turn) continue;
801
- if (event.type === "turn/end") flight.ownTurnEnded = true;
802
- if (flight.mixed) {
803
- if (event.type === "turn/end") this.settleTurnEnd(claim, flight, data);
804
- continue;
805
- }
806
- switch (event.type) {
807
- case "assistant/message":
808
- this.projectAssistantMessage(claim, flight, data);
809
- break;
810
- case "tool/call":
811
- this.projectToolCall(claim, flight, data);
812
- break;
813
- case "tool/result":
814
- this.projectToolResult(claim, flight, data);
815
- break;
816
- case "turn/end": this.settleTurnEnd(claim, flight, data);
817
- }
818
- }
819
- }
820
- /**
821
- * A discard only triggers verification: edit/steer can reinsert the same id
822
- * within the current synchronous Host mutation. Cross it once, then read the
823
- * official pending projection and the CURRENT responsibility of this claim.
824
- */
825
- onInboxDiscarded(agent, message) {
826
- const messageId = message.id;
827
- for (const claim of this.claims.values()) {
828
- if (claim.exactAgent !== agent || claim.exactSession === void 0) continue;
829
- if (claim.inflight?.messageId !== messageId && claim.unclaimedHostObligation?.messageId !== messageId) continue;
830
- const session = claim.exactSession;
831
- const sessionId = claim.sessionId;
832
- runDetached("local acp: inbox discard checkpoint", async () => {
833
- await Promise.resolve();
834
- if (this.claims.get(sessionId) !== claim || claim.exactAgent !== agent || claim.exactSession !== session) return;
835
- const flight = claim.inflight;
836
- const obligation = claim.unclaimedHostObligation;
837
- if (flight?.messageId !== messageId && obligation?.messageId !== messageId) return;
838
- if (this.access?.pendingMessage(sessionId, agent, session, messageId) !== "absent") return;
839
- if (flight?.messageId === messageId) {
840
- if (flight.settledDone || flight.turn !== void 0 || flight.cancelKind !== void 0) return;
841
- flight.cancelKind = "queued-removed";
842
- this.settleQueuedRemoval(claim, flight);
843
- } else if (obligation?.messageId === messageId) this.dropUnclaimedObligation(claim);
844
- }, { diag: this.diag });
845
- }
846
- }
847
- /** One Agent interval failure: only the owned turn of the exact Agent is attributed. */
848
- onAgentError(agent, turn) {
849
- for (const claim of this.claims.values()) {
850
- if (claim.exactAgent !== agent) continue;
851
- const flight = claim.inflight;
852
- if (flight === void 0 || flight.settledDone) continue;
853
- if (flight.turn !== void 0 && flight.turn === turn) this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_TURN_FAILED", "the owned turn reported an Agent failure", JSONRPC_INTERNAL_ERROR, { reason: "agent-error" }));
854
- }
855
- }
856
- /** The exact live Agent was disposed: its in-flight prompt can never settle. */
857
- onAgentDisposed(agent) {
858
- for (const claim of this.claims.values()) {
859
- if (claim.exactAgent !== agent) continue;
860
- const flight = claim.inflight;
861
- if (flight !== void 0 && !flight.settledDone) {
862
- flight.ownTurnEnded = true;
863
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_TURN_FAILED", "the owned Agent was disposed before the prompt settled", JSONRPC_INTERNAL_ERROR, { reason: "agent-disposed" }));
864
- }
865
- if (claim.unclaimedHostObligation !== void 0) this.dropUnclaimedObligation(claim);
866
- this.endRetiringFence(claim.sessionId, claim);
867
- }
868
- }
869
- /**
870
- * PO-3B approval classification entry (the ONE prepended waterfall seat).
871
- *
872
- * The decision is made ONLY from authoritative facts: the request's exact
873
- * Agent against every claim's exact identity, the claim's live flight turn
874
- * or its transient retired-turn fence, and the official current-turn fence.
875
- * A turn proven ACP-owned is answered here — standard reverse
876
- * `session/request_permission` when the channel allows it, `'unavailable'`
877
- * (fail closed) when it does not — and NEVER delegated through `next()`. A
878
- * turn proven NOT owned by any ACP View is delegated exactly once.
879
- */
880
- async onApprovalRequest(request, next) {
881
- const agent = request.agent;
882
- let owner;
883
- for (const claim of this.claims.values()) if (claim.exactAgent === agent) {
884
- owner = claim;
885
- break;
886
- }
887
- if (owner === void 0) return await next();
888
- const session = owner.exactSession;
889
- const fence = session === void 0 || this.access === void 0 ? void 0 : this.access.currentTurn(owner.sessionId, agent, session);
890
- if (fence === void 0 || fence.kind === "stale") return "unavailable";
891
- const flight = owner.inflight;
892
- const currentTurn = fence.openTurn;
893
- if (currentTurn === null) return flight?.turn !== void 0 || owner.retiringTurn !== void 0 ? "unavailable" : await next();
894
- const declaredTurn = owner.retiringTurn?.turn === currentTurn ? owner.retiringTurn : flight !== void 0 && !flight.settledDone && flight.turn === currentTurn ? {
895
- turn: currentTurn,
896
- origin: flight.turnProvenance?.turn === currentTurn ? flight.turnProvenance.origin : "acp"
897
- } : flight?.turnProvenance?.turn === currentTurn ? flight.turnProvenance : void 0;
898
- if (declaredTurn === void 0) return await next();
899
- if (declaredTurn.origin === "unknown") return "unavailable";
900
- if (declaredTurn.origin === "tui") return await next();
901
- if (flight === void 0 || flight.settledDone || flight.cancelRequested || flight.mixed || request.callId === void 0 || flight.turn !== currentTurn) return "unavailable";
902
- const pending = flight.permissionRequests.get(request.callId);
903
- if (pending !== void 0) return await pending.promise;
904
- const channel = flight.requestPermission;
905
- if (channel === void 0) return "unavailable";
906
- const asked = this.askPermission(flight, owner, request, channel);
907
- flight.permissionRequests.set(request.callId, asked);
908
- try {
909
- return await asked.promise;
910
- } finally {
911
- flight.permissionRequests.delete(request.callId);
912
- }
913
- }
914
- /** Issue ONE reverse permission request on the flight's own channel. */
915
- askPermission(flight, owner, request, channel) {
916
- const upstreamSignal = request.signal;
917
- const cancellation = new AbortController();
918
- const onUpstreamAbort = () => {
919
- cancellation.abort();
920
- };
921
- upstreamSignal?.addEventListener("abort", onUpstreamAbort, { once: true });
922
- return {
923
- promise: (async () => {
924
- if (upstreamSignal?.aborted === true) return "cancelled";
925
- try {
926
- await flight.outputTail;
927
- if (flight.settledDone || flight.deliveryClosed) return "unavailable";
928
- const response = await channel({
929
- sessionId: owner.sessionId,
930
- toolCall: { toolCallId: request.callId },
931
- options: [{
932
- optionId: "allow-once",
933
- name: "Allow once",
934
- kind: "allow_once"
935
- }, {
936
- optionId: "reject-once",
937
- name: "Reject",
938
- kind: "reject_once"
939
- }]
940
- }, { signal: cancellation.signal });
941
- if (flight.settledDone || flight.deliveryClosed) return "unavailable";
942
- if ((upstreamSignal?.aborted ?? false) === true) return "cancelled";
943
- const outcome = response?.outcome;
944
- if (outcome?.outcome === "cancelled") return "cancelled";
945
- if (outcome?.outcome === "selected") {
946
- if (outcome.optionId === "allow-once") return "allowed-once";
947
- if (outcome.optionId === "reject-once") return "rejected";
948
- }
949
- return "unavailable";
950
- } catch {
951
- return (upstreamSignal?.aborted ?? false) || cancellation.signal.aborted ? "cancelled" : "unavailable";
952
- } finally {
953
- upstreamSignal?.removeEventListener("abort", onUpstreamAbort);
954
- }
955
- })(),
956
- abort: () => {
957
- cancellation.abort();
958
- }
959
- };
960
- }
961
- /**
962
- * Release every claim owned by one connection and mark it closed. Used by
963
- * BOTH an explicit teardown completion and a physical `socket`
964
- * end/error/destroy or Host Off; it is idempotent and never touches another
965
- * connection's claim or any Host Agent/Session.
966
- *
967
- * PO-3B: a flight with a durable message fact drives the SAME scoped
968
- * cancellation (queued removal or exact-turn user cancel). A pending
969
- * admission retains its request identity and claim for late insertion;
970
- * only proven Host settlement, or classified admission with no inserted
971
- * message on the exact identity, releases the responsibility. Without any
972
- * bound Host access, raw-socket contracts retain the PO-3A fail-closed path.
973
- */
974
- releaseConnection(state, access) {
975
- state.phase = "closed";
976
- state.op += 1;
977
- for (const [sessionId, claim] of this.claims) {
978
- if (claim.connectionIdentity !== state) continue;
979
- const flight = claim.inflight;
980
- if (flight !== void 0) {
981
- const bound = access ?? this.access;
982
- if (bound === void 0) {
983
- this.failPrompt(claim, flight, new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection closed before the prompt settled", JSONRPC_INTERNAL_ERROR));
984
- this.releaseClaimIfUnfenced(sessionId, claim);
985
- continue;
986
- }
987
- runDetached("local acp: disconnect cancellation", async () => {
988
- try {
989
- await this.cancelOwnedFlight(claim, flight, bound, "disconnect");
990
- } catch {}
991
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
992
- claim.detachedWithFence = true;
993
- this.notifyWorkSettled();
994
- return;
995
- }
996
- this.releaseClaimAfterDisconnect(sessionId, claim);
997
- }, { diag: this.diag });
998
- continue;
999
- }
1000
- const obligation = claim.unclaimedHostObligation;
1001
- const bound = access ?? this.access;
1002
- if (obligation !== void 0 && obligation.messageId !== void 0 && claim.exactAgent !== void 0 && claim.exactSession !== void 0 && bound !== void 0) {
1003
- if (bound.cancelPending(sessionId, claim.exactAgent, claim.exactSession, obligation.messageId) === "removed") this.dropUnclaimedObligation(claim);
1004
- }
1005
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
1006
- claim.detachedWithFence = true;
1007
- continue;
1008
- }
1009
- if (this.claims.get(sessionId) === claim) this.claims.delete(sessionId);
1010
- }
1011
- this.notifyWorkSettled();
1012
- }
1013
- /**
1014
- * End one retired-turn fence: clear it and, when the View already detached
1015
- * (a close/disconnect left the claim alive ONLY for this fence), release
1016
- * the claim so the Session can be attached again (RFL-006).
1017
- */
1018
- endRetiringFence(sessionId, claim) {
1019
- claim.retiringTurn = void 0;
1020
- this.releaseDetachedIfSettled(claim);
1021
- this.notifyWorkSettled();
1022
- }
1023
- /**
1024
- * Release one claim after a fail-closed flight UNLESS it still carries a
1025
- * retired-turn fence that must survive until its own facts end it.
1026
- */
1027
- releaseClaimIfUnfenced(sessionId, claim) {
1028
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
1029
- claim.detachedWithFence = true;
1030
- return;
1031
- }
1032
- if (this.claims.get(sessionId) === claim) {
1033
- this.claims.delete(sessionId);
1034
- this.notifyWorkSettled();
1035
- }
1036
- }
1037
- /** Release one disconnect claim after its flight settled. */
1038
- releaseClaimAfterDisconnect(sessionId, claim) {
1039
- if (this.claims.get(sessionId) === claim) this.claims.delete(sessionId);
1040
- this.notifyWorkSettled();
1041
- }
1042
- /**
1043
- * Enforce `idle -> attaching` BEFORE any Host await; a busy/closed view
1044
- * refuses. Returns the attach-operation generation captured by the caller.
1045
- */
1046
- beginAttach(state) {
1047
- if (state.phase === "closed") throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection is closed", JSONRPC_INVALID_PARAMS);
1048
- if (state.phase !== "idle") throw new LocalAcpViewError("LOCAL_ACP_VIEW_BUSY", "this ACP connection already holds or is attaching a view", JSONRPC_INVALID_PARAMS);
1049
- state.op += 1;
1050
- state.phase = "attaching";
1051
- state.lastClosedSessionId = void 0;
1052
- return state.op;
1053
- }
1054
- /** Whether `op` is still this connection's live attach generation. */
1055
- isCurrentOp(state, op) {
1056
- return state.op === op && state.phase === "attaching";
1057
- }
1058
- /** Reset to idle ONLY while `op` is still this connection's attaching generation. */
1059
- resetIdleIfCurrent(state, op) {
1060
- if (state.op === op && state.phase === "attaching") state.phase = "idle";
1061
- }
1062
- /**
1063
- * Resolve one Session to its live Agent through the sole official owner,
1064
- * releasing the reservation and classifying every failure. A closed,
1065
- * superseded or already-released operation owns no claim even if its await
1066
- * resolves later, and its continuation never mutates the connection state.
1067
- */
1068
- async resolveForView(access, state, op, claim) {
1069
- let resolved;
1070
- try {
1071
- resolved = await access.resolveAgent(claim.sessionId);
1072
- } catch {
1073
- this.onResolveFailure(state, op, claim);
1074
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_HOST_ERROR", "the Host could not resolve the session", JSONRPC_INTERNAL_ERROR, { sessionId: claim.sessionId });
1075
- }
1076
- if ("error" in resolved) {
1077
- this.onResolveFailure(state, op, claim);
1078
- throw mapResolveError(resolved.error, claim.sessionId);
1079
- }
1080
- if (!this.isCurrentOp(state, op) || this.claims.get(claim.sessionId) !== claim) {
1081
- this.releaseReservation(state, claim);
1082
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP view was released before it attached", JSONRPC_INVALID_PARAMS, { sessionId: claim.sessionId });
1083
- }
1084
- return resolved.agent;
1085
- }
1086
- /** Release a failed resolution's OWN exact reservation without touching a newer op's claim. */
1087
- onResolveFailure(state, op, claim) {
1088
- this.releaseReservation(state, claim);
1089
- this.resetIdleIfCurrent(state, op);
1090
- }
1091
- /**
1092
- * Commit an attached View only when `op` is still the connection's live
1093
- * generation, the claim is still this connection's, AND the borrowed
1094
- * Agent/Session are the EXACT live Host objects. Any mismatch releases ONLY
1095
- * this exact claim instead of publishing a stale View, and never mutates a
1096
- * state now owned by a newer/closed operation.
1097
- */
1098
- commitAttached(state, op, claim, access, agent) {
1099
- if (state.op !== op || this.claims.get(claim.sessionId) !== claim || claim.connectionIdentity !== state) {
1100
- this.releaseReservation(state, claim);
1101
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP view was released before it attached", JSONRPC_INVALID_PARAMS, { sessionId: claim.sessionId });
1102
- }
1103
- if (!(Object.is(access.currentAgent(claim.sessionId), agent) && Object.is(access.currentSession(claim.sessionId), agent.session))) {
1104
- this.releaseReservation(state, claim);
1105
- this.resetIdleIfCurrent(state, op);
1106
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_AGENT_UNAVAILABLE", "the resolved session agent is no longer the live Host agent", JSONRPC_INTERNAL_ERROR, { sessionId: claim.sessionId });
1107
- }
1108
- state.phase = "attached";
1109
- claim.exactAgent = agent;
1110
- claim.exactSession = agent.session;
1111
- }
1112
- /**
1113
- * Remove ONE exact reservation. Identity is by the CLAIM OBJECT (and its
1114
- * owning connection), never by `sessionId` alone: a close-then-re-attach of
1115
- * the SAME Session produces a NEW claim for the same connection+sessionId, so
1116
- * a stale operation's late release must not delete the newer claim.
1117
- */
1118
- releaseReservation(state, claim) {
1119
- if (this.claims.get(claim.sessionId) === claim && claim.connectionIdentity === state) {
1120
- this.claims.delete(claim.sessionId);
1121
- this.notifyWorkSettled();
1122
- }
1123
- }
1124
- /**
1125
- * Validate ONE committed assistant message synchronously and reserve its
1126
- * ordered output units on this flight's single tail. Shapes are checked here
1127
- * (a malformed/unsupported event fails before anything is queued); the image
1128
- * reads and the sends happen inside the tail so no later event can overtake
1129
- * this one.
1130
- */
1131
- projectAssistantMessage(claim, flight, data) {
1132
- const message = data.message;
1133
- if (message === void 0 || typeof message.id !== "string" || !Array.isArray(message.content)) {
1134
- this.failPrompt(claim, flight, unsupportedContent());
1135
- return;
1136
- }
1137
- const entries = [];
1138
- for (const block of message.content) {
1139
- const type = block?.type;
1140
- const text = block?.text;
1141
- if (type === "reasoning") {
1142
- if (typeof text !== "string") {
1143
- this.failPrompt(claim, flight, unsupportedContent());
1144
- return;
1145
- }
1146
- if (text.length > 0) entries.push({
1147
- kind: "thought",
1148
- text
1149
- });
1150
- continue;
1151
- }
1152
- if (type === "text") {
1153
- if (typeof text !== "string") {
1154
- this.failPrompt(claim, flight, unsupportedContent());
1155
- return;
1156
- }
1157
- if (text.length === 0) continue;
1158
- entries.push({
1159
- kind: "message",
1160
- text
1161
- });
1162
- flight.assistantVisibleOutput = true;
1163
- continue;
1164
- }
1165
- if (type === "image") {
1166
- const ref = committedImageRef(block);
1167
- if (ref === void 0) {
1168
- this.failPrompt(claim, flight, unsupportedContent());
1169
- return;
1170
- }
1171
- entries.push({
1172
- kind: "message-image",
1173
- ref
1174
- });
1175
- flight.assistantVisibleOutput = true;
1176
- continue;
1177
- }
1178
- if (type === "tool-call") continue;
1179
- this.failPrompt(claim, flight, unsupportedContent());
1180
- return;
1181
- }
1182
- const messageId = message.id;
1183
- const toUpdates = async () => {
1184
- const updates = [];
1185
- for (const entry of entries) if (entry.kind === "thought") updates.push({
1186
- sessionUpdate: "agent_thought_chunk",
1187
- messageId,
1188
- content: {
1189
- type: "text",
1190
- text: entry.text
1191
- }
1192
- });
1193
- else if (entry.kind === "message") updates.push({
1194
- sessionUpdate: "agent_message_chunk",
1195
- messageId,
1196
- content: {
1197
- type: "text",
1198
- text: entry.text
1199
- }
1200
- });
1201
- else if (entry.kind === "message-image") {
1202
- const stored = await this.readOutputImage(flight, entry.ref);
1203
- updates.push({
1204
- sessionUpdate: "agent_message_chunk",
1205
- messageId,
1206
- content: {
1207
- type: "image",
1208
- data: Buffer.from(stored.data).toString("base64"),
1209
- mimeType: stored.mediaType
1210
- }
1211
- });
1212
- }
1213
- return updates;
1214
- };
1215
- if (entries.every((entry) => entry.kind !== "message-image")) {
1216
- this.enqueueOutputTask(claim, flight, entries.length, () => {
1217
- const updates = [];
1218
- for (const entry of entries) if (entry.kind === "thought") updates.push({
1219
- sessionUpdate: "agent_thought_chunk",
1220
- messageId,
1221
- content: {
1222
- type: "text",
1223
- text: entry.text
1224
- }
1225
- });
1226
- else if (entry.kind === "message") updates.push({
1227
- sessionUpdate: "agent_message_chunk",
1228
- messageId,
1229
- content: {
1230
- type: "text",
1231
- text: entry.text
1232
- }
1233
- });
1234
- return updates;
1235
- });
1236
- return;
1237
- }
1238
- this.enqueueOutputTask(claim, flight, entries.length, toUpdates);
1239
- }
1240
- /** Project one committed tool call of the owned turn as a standard start update. */
1241
- projectToolCall(claim, flight, data) {
1242
- const call = data;
1243
- if (typeof call.callId !== "string" || typeof call.name !== "string") {
1244
- this.failPrompt(claim, flight, unsupportedContent());
1245
- return;
1246
- }
1247
- const rawInput = typeof call.arguments === "string" ? parseToolArguments(call.arguments) : void 0;
1248
- const update = {
1249
- sessionUpdate: "tool_call",
1250
- toolCallId: call.callId,
1251
- title: call.name,
1252
- kind: "other",
1253
- status: "in_progress",
1254
- ...rawInput === void 0 ? {} : { rawInput }
1255
- };
1256
- this.enqueueOutputTask(claim, flight, 1, () => [update]);
1257
- }
1258
- /**
1259
- * Project ONE committed tool result as a single standard `tool_call_update`.
1260
- * Its `content` keeps the committed block order (non-empty text and verified
1261
- * images); the status comes only from the official `isError` fact and the
1262
- * `toolCallId` only from the durable message.
1263
- */
1264
- projectToolResult(claim, flight, data) {
1265
- const message = data.message;
1266
- if (message === void 0 || typeof message.toolCallId !== "string" || !Array.isArray(message.content)) {
1267
- this.failPrompt(claim, flight, unsupportedContent());
1268
- return;
1269
- }
1270
- const entries = [];
1271
- for (const block of message.content) {
1272
- const type = block?.type;
1273
- const text = block?.text;
1274
- if (type === "text") {
1275
- if (typeof text !== "string") {
1276
- this.failPrompt(claim, flight, unsupportedContent());
1277
- return;
1278
- }
1279
- if (text.length > 0) entries.push({
1280
- kind: "tool",
1281
- text
1282
- });
1283
- continue;
1284
- }
1285
- if (type === "image") {
1286
- const ref = committedImageRef(block);
1287
- if (ref === void 0) {
1288
- this.failPrompt(claim, flight, unsupportedContent());
1289
- return;
1290
- }
1291
- entries.push({
1292
- kind: "tool-image",
1293
- ref
1294
- });
1295
- continue;
1296
- }
1297
- this.failPrompt(claim, flight, unsupportedContent());
1298
- return;
1299
- }
1300
- const toolCallId = message.toolCallId;
1301
- const status = message.isError === true ? "failed" : "completed";
1302
- const toUpdate = async () => {
1303
- const content = [];
1304
- for (const entry of entries) if (entry.kind === "tool") content.push({
1305
- type: "content",
1306
- content: {
1307
- type: "text",
1308
- text: entry.text
1309
- }
1310
- });
1311
- else if (entry.kind === "tool-image") {
1312
- const stored = await this.readOutputImage(flight, entry.ref);
1313
- content.push({
1314
- type: "content",
1315
- content: {
1316
- type: "image",
1317
- data: Buffer.from(stored.data).toString("base64"),
1318
- mimeType: stored.mediaType
1319
- }
1320
- });
1321
- }
1322
- return [{
1323
- sessionUpdate: "tool_call_update",
1324
- toolCallId,
1325
- status,
1326
- content
1327
- }];
1328
- };
1329
- if (entries.every((entry) => entry.kind !== "tool-image")) {
1330
- this.enqueueOutputTask(claim, flight, 1, () => {
1331
- const content = [];
1332
- for (const entry of entries) if (entry.kind === "tool") content.push({
1333
- type: "content",
1334
- content: {
1335
- type: "text",
1336
- text: entry.text
1337
- }
1338
- });
1339
- return [{
1340
- sessionUpdate: "tool_call_update",
1341
- toolCallId,
1342
- status,
1343
- content
1344
- }];
1345
- });
1346
- return;
1347
- }
1348
- this.enqueueOutputTask(claim, flight, 1, toUpdate);
1349
- }
1350
- /**
1351
- * Read ONE committed image through the official Host Attachment Store. The
1352
- * Store owns the ID/format/byte/dimension verification; the View only encodes
1353
- * the verified bytes. Every Store rejection keeps ONE stable content class —
1354
- * never a partial event, a fabricated image or a leaked path/exception.
1355
- */
1356
- async readOutputImage(flight, ref) {
1357
- const access = this.access;
1358
- if (access === void 0) throw attachmentReadFailed();
1359
- try {
1360
- return await access.readOutputImage(ref, flight.outputSignal);
1361
- } catch {
1362
- throw attachmentReadFailed();
1363
- }
1364
- }
1365
- /**
1366
- * Append ONE committed event's conversion to this flight's single ordered
1367
- * output tail. `reserve` is the event's synchronously known update count: the
1368
- * FIFO position and the bounded pending counter are committed BEFORE any
1369
- * await, the whole event is converted (official image reads included) inside
1370
- * the tail, and only then are its updates handed to the transport. The
1371
- * bounded pending counter is the ONLY additional queue: exceeding it fails
1372
- * this View's request instead of growing without limit.
1373
- */
1374
- enqueueOutputTask(claim, flight, reserve, build) {
1375
- if (reserve === 0 || flight.settledDone) return;
1376
- const taskIndex = flight.outputTasksQueued;
1377
- flight.outputTasksQueued += 1;
1378
- flight.pendingUpdates += reserve;
1379
- if (flight.pendingUpdates > MAX_PENDING_OUTPUT_UPDATES) {
1380
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_OUTPUT_BACKPRESSURE", "the ACP output queue exceeded its bounded capacity", JSONRPC_INTERNAL_ERROR));
1381
- return;
1382
- }
1383
- flight.outputTail = flight.outputTail.then(async () => {
1384
- try {
1385
- if (flight.settledDone || flight.mixed || flight.deliveryClosed || flight.outputStoppedAtTask !== void 0 && taskIndex < flight.outputStoppedAtTask) return;
1386
- const built = build();
1387
- const updates = Array.isArray(built) ? built : await built;
1388
- for (const update of updates) {
1389
- if (flight.settledDone || flight.mixed || flight.deliveryClosed || flight.outputStoppedAtTask !== void 0 && taskIndex < flight.outputStoppedAtTask) return;
1390
- try {
1391
- await flight.sendUpdate(update);
1392
- } catch {
1393
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_OUTPUT_FAILED", "an ACP session/update notification could not be delivered", JSONRPC_INTERNAL_ERROR));
1394
- return;
1395
- }
1396
- }
1397
- } catch (error) {
1398
- if (flight.outputStopped || flight.settledDone || flight.mixed || flight.deliveryClosed) return;
1399
- this.failPrompt(claim, flight, error instanceof LocalAcpViewError ? error : promptError("LOCAL_ACP_PROMPT_OUTPUT_FAILED", "the committed output could not be delivered", JSONRPC_INTERNAL_ERROR));
1400
- } finally {
1401
- flight.pendingUpdates -= reserve;
1402
- }
1403
- });
1404
- }
1405
- /**
1406
- * Settle the owned turn after `turn/end`: first drain every notification this
1407
- * flight queued, then answer one real legal StopReason or a stable failure.
1408
- */
1409
- settleTurnEnd(claim, flight, data) {
1410
- flight.phase = "settling";
1411
- runDetached("local acp: prompt settlement", async () => {
1412
- await flight.outputTail;
1413
- if (flight.settledDone) return;
1414
- if (flight.mixed) {
1415
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_MIXED_TURN", "the owned turn also carried another user message, so its output cannot be reported as this prompt", JSONRPC_INTERNAL_ERROR));
1416
- return;
1417
- }
1418
- if (flight.cancelKind === "running-addressed" && turnEndUserAborted(data)) {
1419
- this.completePrompt(claim, flight, { stopReason: "cancelled" });
1420
- return;
1421
- }
1422
- const kind = turnEndReasonKind(data);
1423
- if (kind !== "completed" && kind !== "max-tokens") {
1424
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_TURN_FAILED", "the owned turn did not reach a successful completion", JSONRPC_INTERNAL_ERROR, kind === void 0 ? { reason: "unknown" } : { reason: kind }));
1425
- return;
1426
- }
1427
- if (!flight.assistantVisibleOutput) {
1428
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_NO_ASSISTANT_TEXT", "the owned turn ended without any visible assistant output", JSONRPC_INTERNAL_ERROR));
1429
- return;
1430
- }
1431
- this.completePrompt(claim, flight, { stopReason: kind === "completed" ? "end_turn" : "max_tokens" });
1432
- }, { diag: this.diag });
1433
- }
1434
- /**
1435
- * Stop ONLY this flight's own output IO. Already delivered notifications stay
1436
- * delivered; a queued read is abandoned and its rejection is classified as a
1437
- * closure by the tail, never as a content failure. The Host Agent, Session
1438
- * and writer keep their authority.
1439
- */
1440
- stopFlightOutput(flight) {
1441
- flight.outputStopped = true;
1442
- flight.outputStoppedAtTask ??= flight.outputTasksQueued;
1443
- flight.outputAbort.abort();
1444
- }
1445
- /**
1446
- * Commit the MIXED fact of one flight: no output committed from now on is
1447
- * projected, and this flight's own not-yet-finished output IO stops (an
1448
- * in-flight official image read is abandoned) so a stalled read can never
1449
- * hold the `turn/end` settlement forever. Already handed-off notifications
1450
- * stay delivered; queued-but-unsent output is dropped at its send check (the
1451
- * accepted PO-3A contract). The Host Agent/Session/Writer are untouched.
1452
- */
1453
- markFlightMixed(flight) {
1454
- flight.mixed = true;
1455
- this.stopFlightOutput(flight);
1456
- }
1457
- /** Fail one flight exactly once and release its slot and correlation state. */
1458
- failPrompt(claim, flight, error) {
1459
- if (flight.settledDone) return;
1460
- flight.settledDone = true;
1461
- flight.phase = "settling";
1462
- flight.detachAbort?.();
1463
- flight.detachAbort = void 0;
1464
- flight.foreignTurn = void 0;
1465
- flight.deliveryClosed = true;
1466
- this.stopFlightOutput(flight);
1467
- this.abortPermissionRequests(flight);
1468
- flight.failureCode = error.code;
1469
- if (flight.turn !== void 0 && !flight.ownTurnEnded) this.retainRetiringTurn(claim, {
1470
- turn: flight.turn,
1471
- origin: flight.turnProvenance?.turn === flight.turn ? flight.turnProvenance.origin : "acp"
1472
- });
1473
- if (flight.turn === void 0 && !flight.ownTurnEnded && flight.cancelKind !== "queued-removed") {
1474
- if (flight.messageId !== void 0) claim.unclaimedHostObligation = {
1475
- requestId: flight.requestId,
1476
- messageId: flight.messageId,
1477
- admission: flight.admissionSettled ? "unconfirmed" : "accepted",
1478
- ...flight.turnProvenance === void 0 ? {} : { turnProvenance: flight.turnProvenance }
1479
- };
1480
- else if (!flight.admissionSettled) claim.unclaimedHostObligation = {
1481
- requestId: flight.requestId,
1482
- admission: "pending",
1483
- ...flight.turnProvenance === void 0 ? {} : { turnProvenance: flight.turnProvenance }
1484
- };
1485
- }
1486
- if (claim.inflight === flight) claim.inflight = void 0;
1487
- this.notifyWorkSettled();
1488
- flight.settled.reject(error);
1489
- }
1490
- /** Complete one flight with its real ACP StopReason and release its slot. */
1491
- completePrompt(claim, flight, result) {
1492
- if (flight.settledDone) return;
1493
- flight.settledDone = true;
1494
- flight.phase = "settling";
1495
- flight.detachAbort?.();
1496
- flight.detachAbort = void 0;
1497
- flight.foreignTurn = void 0;
1498
- flight.deliveryClosed = true;
1499
- this.stopFlightOutput(flight);
1500
- this.abortPermissionRequests(flight);
1501
- if (claim.inflight === flight) claim.inflight = void 0;
1502
- this.notifyWorkSettled();
1503
- flight.settled.resolve(result);
1504
- }
1505
- /** Abort every pending reverse permission request of one settling flight. */
1506
- abortPermissionRequests(flight) {
1507
- for (const pending of flight.permissionRequests.values()) pending.abort();
1508
- flight.permissionRequests.clear();
1509
- }
1510
- validateNew(request) {
1511
- validateCwd(request.cwd);
1512
- if (request.mcpServers.length !== 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "ACP MCP servers are not supported by this Host", JSONRPC_INVALID_PARAMS);
1513
- if (request.additionalDirectories !== void 0 && request.additionalDirectories.length !== 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "ACP additional directories are not supported by this Host", JSONRPC_INVALID_PARAMS);
1514
- }
1515
- validateResume(request) {
1516
- if (typeof request.sessionId !== "string" || request.sessionId.length === 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "a non-empty sessionId is required", JSONRPC_INVALID_PARAMS);
1517
- validateCwd(request.cwd);
1518
- if (request.mcpServers !== void 0 && request.mcpServers.length !== 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "ACP MCP servers are not supported by this Host", JSONRPC_INVALID_PARAMS);
1519
- if (request.additionalDirectories !== void 0 && request.additionalDirectories.length !== 0) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "ACP additional directories are not supported by this Host", JSONRPC_INVALID_PARAMS);
1520
- }
1521
- };
1522
- /** A `session/new|resume` cwd is a non-empty Linux absolute path with no NUL. */
1523
- function validateCwd(cwd) {
1524
- if (typeof cwd !== "string" || cwd.length === 0 || !cwd.startsWith("/") || cwd.includes("\0")) throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "cwd must be a non-empty absolute path", JSONRPC_INVALID_PARAMS);
1525
- }
1526
- /**
1527
- * Validate and normalize standard ACP prompt blocks in client order.
1528
- * `resource_link` blocks become official bracketed text hints; inline images
1529
- * require this connection's negotiated Host capability. Embedded resource,
1530
- * audio, unknown blocks, empty prompts and whitespace-only text stay rejected
1531
- * before any Host dispatch.
1532
- */
1533
- function validatePromptContent(prompt, imageEnabled) {
1534
- if (!Array.isArray(prompt) || prompt.length === 0) throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "a prompt must contain non-empty text or an image", JSONRPC_INVALID_PARAMS);
1535
- const content = [];
1536
- let pendingText = "";
1537
- const flushText = () => {
1538
- if (pendingText.length === 0) return;
1539
- content.push({
1540
- type: "text",
1541
- text: pendingText
1542
- });
1543
- pendingText = "";
1544
- };
1545
- for (const block of prompt) {
1546
- const wireBlock = block;
1547
- if (wireBlock === null || wireBlock === void 0) throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "the prompt contains an invalid content block", JSONRPC_INVALID_PARAMS);
1548
- const type = wireBlock.type;
1549
- if (type === "text") {
1550
- if (typeof wireBlock.text !== "string") throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "the prompt contains an invalid text block", JSONRPC_INVALID_PARAMS);
1551
- pendingText += wireBlock.text;
1552
- continue;
1553
- }
1554
- if (type === "resource_link") {
1555
- if (typeof wireBlock.name !== "string" || typeof wireBlock.uri !== "string") throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "the prompt contains an invalid resource link", JSONRPC_INVALID_PARAMS);
1556
- pendingText += `\n[resource_link name=${JSON.stringify(wireBlock.name)} uri=${JSON.stringify(wireBlock.uri)}]\n`;
1557
- continue;
1558
- }
1559
- if (type === "image") {
1560
- if (!imageEnabled || typeof wireBlock.mimeType !== "string" || typeof wireBlock.data !== "string" || !ACP_IMAGE_MEDIA_TYPES.includes(wireBlock.mimeType)) throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "this connection cannot accept the requested image block", JSONRPC_INVALID_PARAMS);
1561
- flushText();
1562
- content.push({
1563
- type: "image",
1564
- mediaType: wireBlock.mimeType,
1565
- data: wireBlock.data
1566
- });
1567
- continue;
1568
- }
1569
- throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "this Host accepts standard ACP text, resource_link and negotiated image blocks only", JSONRPC_INVALID_PARAMS);
1570
- }
1571
- flushText();
1572
- if (!content.some((part) => part.type === "image" || part.type === "text" && part.text.trim().length > 0)) throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "a prompt must include non-whitespace text or an image", JSONRPC_INVALID_PARAMS);
1573
- return content;
1574
- }
1575
- /** One stable "the official Store could not read this committed image" failure. */
1576
- function attachmentReadFailed() {
1577
- return promptError("LOCAL_ACP_PROMPT_ATTACHMENT_READ_FAILED", "a committed image attachment could not be read and verified", JSONRPC_INTERNAL_ERROR);
1578
- }
1579
- /**
1580
- * The structural official `ImageAttachmentRef` of one committed image block.
1581
- * Only the reference SHAPE is checked here; the official Host Attachment Store
1582
- * remains the authority that verifies the object named by this reference.
1583
- */
1584
- function committedImageRef(block) {
1585
- const attachment = block?.attachment;
1586
- if (attachment === null || typeof attachment !== "object") return void 0;
1587
- const ref = attachment;
1588
- if (typeof ref.attachmentId !== "string" || typeof ref.mediaType !== "string" || typeof ref.bytes !== "number" || typeof ref.width !== "number" || typeof ref.height !== "number") return;
1589
- return {
1590
- attachmentId: ref.attachmentId,
1591
- mediaType: ref.mediaType,
1592
- bytes: ref.bytes,
1593
- width: ref.width,
1594
- height: ref.height
1595
- };
1596
- }
1597
- /** One stable "this committed block has no PO-3A projection" failure. */
1598
- function unsupportedContent() {
1599
- return promptError("LOCAL_ACP_PROMPT_UNSUPPORTED_CONTENT", "a committed content block has no standard ACP projection in this phase", JSONRPC_INTERNAL_ERROR);
1600
- }
1601
- /** Preserve malformed model tool arguments as opaque input instead of dropping them. */
1602
- function parseToolArguments(value) {
1603
- try {
1604
- return JSON.parse(value);
1605
- } catch {
1606
- return value;
1607
- }
1608
- }
1609
- /** Map an official Session-domain failure onto a stable View rejection. */
1610
- function mapResolveError(error, sessionId) {
1611
- const data = { sessionId };
1612
- switch (error.code) {
1613
- case "session/not-found": return new LocalAcpViewError("LOCAL_ACP_VIEW_SESSION_NOT_FOUND", "the session does not exist on this Host", JSONRPC_INVALID_PARAMS, data);
1614
- case "session/agent-busy": return new LocalAcpViewError("LOCAL_ACP_VIEW_SUBAGENT_OWNED", "the session is owned by subagent routing", JSONRPC_INVALID_PARAMS, data);
1615
- case "session/writer-held": return new LocalAcpViewError("LOCAL_ACP_VIEW_WRITER_HELD", "the session is written by another owner", JSONRPC_INVALID_PARAMS, data);
1616
- default: return new LocalAcpViewError("LOCAL_ACP_VIEW_HOST_ERROR", "the Host could not resolve the session", JSONRPC_INTERNAL_ERROR, data);
1617
- }
1618
- }
1619
- //#endregion
1620
- //#region src/app/remote-process/local-acp-listener.ts
1621
- /**
1622
- * Host-owned local ACP v1 front door over a pathname Unix domain socket.
1623
- *
1624
- * The one Host process that already owns a canonical profile scope opens a
1625
- * bounded `acp.sock` on ONE platform-specific physical endpoint: Linux keeps the
1626
- * 0700 scope directory and binds through `/proc/self/fd` so an over-long scope
1627
- * pathname still fits the kernel `sun_path`; Darwin publishes the same
1628
- * private-bind inode onto a short profile-scoped
1629
- * `/private/tmp/dpt-<uid>-<scope40>/acp.sock` pathname that stays within the
1630
- * Darwin `sockaddr_un.sun_path` byte limit. The listener speaks ACP v1 with
1631
- * the official `@agentclientprotocol/sdk` stream and request/notification
1632
- * dispatch, but it owns NO Agent, Session or business method in this phase: a
1633
- * valid `initialize` is answered with the installed bundle's own identity and
1634
- * every Session request fails closed with a machine-readable code. The listener
1635
- * is a Host-entry-local lifecycle object (`startLocalAcpListener()`), never a
1636
- * package export and never a second Host authority: the existing entry keeps the
1637
- * one Ready commit (`writeLocalRecord`) and the one shutdown owner, and the
1638
- * listener is bound BEFORE that Ready commit so a published registry never
1639
- * points at a socket that is not yet accepting.
1640
- *
1641
- * The SDK's default NDJSON stream uses an unbounded `LineBuffer` and no output
1642
- * backpressure, so this module wraps the socket in TWO bounded streams: an
1643
- * input reader that scans raw UTF-8 bytes for newlines under a per-frame and a
1644
- * queued-byte cap, and an output writer that refuses a frame or a buffered
1645
- * total above its cap. A cap breach closes only the offending connection.
1646
- *
1647
- * @module app/remote-process/local-acp-listener
1648
- */
1649
- /** The ACP agent identity this front door advertises (never a copied brand). */
1650
- const AGENT_NAME = "dsh-pi-tui";
1651
- /** One input line (a single NDJSON frame) may not exceed one mebibyte. */
1652
- const MAX_INPUT_FRAME_BYTES = 1048576;
1653
- /**
1654
- * Total unconsumed input on ONE connection is bounded: the current partial
1655
- * line plus complete frames awaiting the SDK plus frames already enqueued into
1656
- * the bounded ReadableStream. All three are summed in bytes against this cap.
1657
- */
1658
- const MAX_INPUT_UNCONSUMED_BYTES = 2097152;
1659
- /** At most this many requests may be dispatched concurrently on ONE connection. */
1660
- const MAX_PENDING_REQUESTS = 8;
1661
- /** Bytes reserved per image block for JSON metadata around its encoded data. */
1662
- const IMAGE_METADATA_BYTES = 65536;
1663
- /** Bytes reserved for the JSON-RPC envelope and its trailing newline. */
1664
- const JSON_ENVELOPE_BYTES = 4096;
1665
- /**
1666
- * Text allowance of ONE outbound committed event when the connection derives
1667
- * its frame budget from Host attachment limits: a larger derived budget must
1668
- * not reject ordinary large text output that the legacy wire already bounded.
1669
- */
1670
- const OUTPUT_TEXT_BYTES = 1048576;
1671
- /** The legacy text-only bounds every connection uses until it negotiates image. */
1672
- const TEXT_ONLY_BOUNDS = {
1673
- maxFrameBytes: MAX_INPUT_FRAME_BYTES,
1674
- maxUnconsumedBytes: MAX_INPUT_UNCONSUMED_BYTES
1675
- };
1676
- /**
1677
- * Derive the bounded input budget of an image-negotiated connection from the
1678
- * Host's OWN boot-frozen attachment limits. The arithmetic models canonical
1679
- * base64, one configured count of image metadata allowances, the preserved
1680
- * text/wire budget and one JSON-RPC envelope. It is not a second image policy:
1681
- * real count/byte/pixel admission remains the official Attachment Store's.
1682
- *
1683
- * @param limits - the exact Host attachment limits, or undefined without a store.
1684
- * @returns the bounds, or undefined when a safe bound cannot be represented.
1685
- */
1686
- function deriveImageInputBounds(limits) {
1687
- if (limits === void 0) return void 0;
1688
- const { maxMessageImageBytes, maxImagesPerMessage } = limits;
1689
- if (!Number.isSafeInteger(maxMessageImageBytes) || maxMessageImageBytes <= 0 || !Number.isSafeInteger(maxImagesPerMessage) || maxImagesPerMessage <= 0 || !Number.isSafeInteger(limits.maxImageBytes) || limits.maxImageBytes <= 0) return;
1690
- const encoded = 4 * Math.ceil(maxMessageImageBytes / 3);
1691
- const imageFrameBytes = encoded + MAX_INPUT_FRAME_BYTES + IMAGE_METADATA_BYTES * maxImagesPerMessage + JSON_ENVELOPE_BYTES;
1692
- const maxFrameBytes = Math.max(MAX_INPUT_FRAME_BYTES, imageFrameBytes);
1693
- const maxUnconsumedBytes = maxFrameBytes + MAX_INPUT_FRAME_BYTES;
1694
- if (!Number.isSafeInteger(encoded) || !Number.isSafeInteger(imageFrameBytes) || !Number.isSafeInteger(maxFrameBytes) || !Number.isSafeInteger(maxUnconsumedBytes) || maxFrameBytes > constants$1.MAX_LENGTH || maxUnconsumedBytes > constants$1.MAX_LENGTH) return;
1695
- return {
1696
- maxFrameBytes,
1697
- maxUnconsumedBytes
1698
- };
1699
- }
1700
- /**
1701
- * Derive ONE connection's outbound single-frame budget from the Host's OWN
1702
- * boot-frozen attachment limits. A committed image arrives from the official
1703
- * Store as ONE independently Base64-encoded object, and the Store's
1704
- * `maxMessageImageBytes` is a PROMPT-batch admission limit that does not bound
1705
- * a stored output image. The allowance therefore bounds each image by the
1706
- * Store's per-object admission ceiling (`maxImageBytes`), encodes every image
1707
- * separately and sums those encoded ceilings, then adds one metadata allowance
1708
- * per image, the JSON-RPC envelope and the preserved text allowance.
1709
- *
1710
- * This is a TRANSPORT resource bound, never an image acceptance policy and never
1711
- * a reason to drop, shrink or re-encode content: the official Attachment Store
1712
- * keeps every byte/pixel limit, and its normalization may even produce a stored
1713
- * image larger than `maxImageBytes` (the accepted upstream limitation). A frame
1714
- * above this allowance fails closed with `LOCAL_ACP_OUTPUT_FRAME_TOO_LARGE`
1715
- * before any byte of that frame is written.
1716
- *
1717
- * @param limits - the exact Host attachment limits, or undefined without a store.
1718
- * @returns the per-frame byte budget, or undefined when it cannot be represented.
1719
- */
1720
- function deriveImageOutputBounds(limits) {
1721
- if (limits === void 0) return void 0;
1722
- const { maxImagesPerMessage, maxImageBytes } = limits;
1723
- if (!Number.isSafeInteger(maxImageBytes) || maxImageBytes <= 0 || !Number.isSafeInteger(maxImagesPerMessage) || maxImagesPerMessage <= 0) return;
1724
- const encodedPerImage = 4 * Math.ceil(maxImageBytes / 3);
1725
- const encoded = maxImagesPerMessage * encodedPerImage;
1726
- const candidate = encoded + IMAGE_METADATA_BYTES * maxImagesPerMessage + JSON_ENVELOPE_BYTES + OUTPUT_TEXT_BYTES;
1727
- const maxFrameBytes = Math.max(MAX_OUTPUT_FRAME_BYTES, candidate);
1728
- if (!Number.isSafeInteger(encodedPerImage) || !Number.isSafeInteger(encoded) || !Number.isSafeInteger(candidate) || !Number.isSafeInteger(maxFrameBytes) || maxFrameBytes > constants$1.MAX_LENGTH) return;
1729
- return maxFrameBytes;
1730
- }
1731
- /** The legacy single outbound ACP frame cap (unchanged for a text-only Host). */
1732
- const MAX_OUTPUT_FRAME_BYTES = 262144;
1733
- /** Total bytes buffered in the socket awaiting flush on ONE connection. */
1734
- const MAX_OUTPUT_BUFFER_BYTES = 262144;
1735
- /** A frame above the legacy cap is written to the socket in bounded chunks. */
1736
- const OUTPUT_WRITE_CHUNK_BYTES = 65536;
1737
- /** The longest ONE kernel-drain wait of a chunked frame may block the writer. */
1738
- const OUTPUT_DRAIN_TIMEOUT_MS = 3e4;
1739
- /** How long a short stale-socket connect probe may run before it is treated as inert-unknown. */
1740
- const CONNECT_PROBE_TIMEOUT_MS = 500;
1741
- /** The logical socket file name inside the 0700 scope directory. */
1742
- const SOCKET_FILE = "acp.sock";
1743
- /** Owner-only private subdirectory (inside the 0700 scope) where the server is
1744
- * actually BOUND before its inode is hard-linked onto the contract path. Node's
1745
- * server.close() unlink always targets this private dir, so it can never delete
1746
- * a foreign inode at the contract path. */
1747
- const PRIVATE_DIR = ".acp-priv";
1748
- /** The trusted, OS-owned sticky parent of the Darwin profile-scoped endpoint. Never
1749
- * `$TMPDIR`, `DSH_HOME` or the user home: those are variable and unbounded. */
1750
- const DARWIN_SOCKET_PARENT = "/private/tmp";
1751
- /** Darwin `sockaddr_un.sun_path` capacity in bytes INCLUDING the trailing NUL. */
1752
- const DARWIN_SUN_PATH_BYTES = 104;
1753
- /** Prefix of the one deterministic Darwin endpoint root per profile scope. */
1754
- const DARWIN_ROOT_PREFIX = "dpt-";
1755
- /** Scope-id hex characters kept in the Darwin root name (the existing 160-bit
1756
- * collision budget the local seats already use). */
1757
- const DARWIN_SCOPE_PREFIX_HEX = 40;
1758
- const NEWLINE = 10;
1759
- /** The fixed capacity rejection an over-limit connection receives before it is ended. */
1760
- const CAPACITY_ERROR_LINE = `${JSON.stringify({
1761
- jsonrpc: "2.0",
1762
- id: null,
1763
- error: {
1764
- code: -32041,
1765
- message: "ACP connection capacity exceeded",
1766
- data: { code: "LOCAL_ACP_CAPACITY_EXCEEDED" }
1767
- }
1768
- })}\n`;
1769
- /** A startup failure that carries one stable local-ACP classification code. */
1770
- var LocalAcpError = class extends Error {
1771
- /** Stable classification asserted by the Host entry failure record. */
1772
- code;
1773
- constructor(code, message, cause) {
1774
- super(message, cause === void 0 ? void 0 : { cause });
1775
- this.name = "LocalAcpError";
1776
- this.code = code;
1777
- }
1778
- };
1779
- /**
1780
- * Parse the Host start-time connection limit from the raw environment value.
1781
- *
1782
- * Missing means the default of 4. Any present value MUST match `1..16` with no
1783
- * surrounding noise; a malformed value is a hard startup failure so a typo
1784
- * cannot silently widen or collapse the bound.
1785
- */
1786
- function parseAcpMaxConnections(raw) {
1787
- if (raw === void 0) return 4;
1788
- if (raw === "" || !/^(?:[1-9]|1[0-6])$/u.test(raw)) throw new LocalAcpError("LOCAL_ACP_INVALID_MAX_CONNECTIONS", "local acp: DSH_PI_TUI_ACP_MAX_CONNECTIONS must be an integer in 1..16");
1789
- return Number(raw);
1790
- }
1791
- /** The ACP Session methods PO-1 must fail closed (business capability does not exist yet). */
1792
- function rejectSessionNotReady() {
1793
- throw new RequestError(-32042, "ACP Session operations are not available on this connection", { code: "LOCAL_ACP_SESSION_NOT_READY" });
1794
- }
1795
- /** Build the bounded input side: raw UTF-8 byte lines under the connection's current caps. */
1796
- /** @internal The owner test feeds real Unix-socket bytes while holding the stream reader. */
1797
- function createBoundedInput(socket, state, fail) {
1798
- /** Fragments of the current, not-yet-terminated line. */
1799
- const line = [];
1800
- let lineBytes = 0;
1801
- const queue = [];
1802
- let queuedByteCount = 0;
1803
- let controller;
1804
- let finished = false;
1805
- let controllerClosed = false;
1806
- let paused = false;
1807
- const closeController = () => {
1808
- if (controllerClosed || controller === void 0) return;
1809
- controllerClosed = true;
1810
- try {
1811
- controller.close();
1812
- } catch {}
1813
- };
1814
- /** The stream's OWN already-enqueued bytes, measured against its fixed high-water mark. */
1815
- const streamBufferedBytes = () => controller === void 0 ? 0 : Math.max(0, MAX_INPUT_FRAME_BYTES - (controller.desiredSize ?? MAX_INPUT_FRAME_BYTES));
1816
- const pump = () => {
1817
- if (controller === void 0) return;
1818
- while (queue.length > 0) {
1819
- if ((controller.desiredSize ?? 1) <= 0) break;
1820
- const frame = queue.shift();
1821
- if (frame !== void 0) {
1822
- queuedByteCount -= frame.byteLength;
1823
- controller.enqueue(frame);
1824
- }
1825
- }
1826
- if (queue.length > 0) {
1827
- if (!paused) {
1828
- paused = true;
1829
- socket.pause();
1830
- }
1831
- return;
1832
- }
1833
- if (paused) {
1834
- paused = false;
1835
- socket.resume();
1836
- }
1837
- if (finished) closeController();
1838
- };
1839
- const detach = () => {
1840
- socket.off("data", onData);
1841
- socket.off("end", onEnd);
1842
- socket.off("close", onClose);
1843
- socket.off("error", onError);
1844
- };
1845
- const failConnection = (code) => {
1846
- finished = true;
1847
- detach();
1848
- fail(code);
1849
- };
1850
- const completeLine = (end) => {
1851
- if (lineBytes - 1 > state.inputBounds.maxFrameBytes) {
1852
- failConnection("LOCAL_ACP_INPUT_FRAME_TOO_LARGE");
1853
- return;
1854
- }
1855
- line.push(end);
1856
- const frame = line.length === 1 ? Uint8Array.prototype.slice.call(line[0]) : Buffer.concat(line);
1857
- line.length = 0;
1858
- lineBytes = 0;
1859
- queue.push(frame);
1860
- queuedByteCount += frame.byteLength;
1861
- };
1862
- /**
1863
- * Scan one raw chunk by UTF-8 bytes. Every byte is forwarded verbatim; a
1864
- * newline completes exactly one NDJSON frame, so truncated or multi-byte
1865
- * characters stay intact across chunks.
1866
- */
1867
- const onData = (chunk) => {
1868
- if (finished) return;
1869
- let offset = 0;
1870
- while (offset < chunk.length) {
1871
- const newline = chunk.indexOf(NEWLINE, offset);
1872
- if (newline === -1) {
1873
- const rest = chunk.subarray(offset);
1874
- line.push(rest);
1875
- lineBytes += rest.length;
1876
- break;
1877
- }
1878
- lineBytes += newline + 1 - offset;
1879
- completeLine(chunk.subarray(offset, newline + 1));
1880
- if (finished) return;
1881
- offset = newline + 1;
1882
- }
1883
- if (lineBytes > state.inputBounds.maxFrameBytes) {
1884
- failConnection("LOCAL_ACP_INPUT_FRAME_TOO_LARGE");
1885
- return;
1886
- }
1887
- if (queuedByteCount + lineBytes + streamBufferedBytes() > state.inputBounds.maxUnconsumedBytes) {
1888
- failConnection("LOCAL_ACP_INPUT_OVERFLOW");
1889
- return;
1890
- }
1891
- pump();
1892
- };
1893
- const onEnd = () => {
1894
- finished = true;
1895
- pump();
1896
- };
1897
- const onClose = () => {
1898
- finished = true;
1899
- closeController();
1900
- };
1901
- const onError = () => {
1902
- finished = true;
1903
- closeController();
1904
- };
1905
- return new ReadableStream({
1906
- start(streamController) {
1907
- controller = streamController;
1908
- socket.on("data", onData);
1909
- socket.on("end", onEnd);
1910
- socket.on("close", onClose);
1911
- socket.on("error", onError);
1912
- },
1913
- pull() {
1914
- pump();
1915
- },
1916
- cancel() {
1917
- finished = true;
1918
- detach();
1919
- socket.destroy();
1920
- }
1921
- }, new ByteLengthQueuingStrategy({ highWaterMark: MAX_INPUT_FRAME_BYTES }));
1922
- }
1923
- /**
1924
- * Wait for ONE `drain` of this socket under a fixed deadline. A socket
1925
- * `close`/`error` ends the wait immediately (the connection is gone), and the
1926
- * deadline fails this connection alone with the existing backpressure class.
1927
- * Every exit path removes the listeners and the timer.
1928
- */
1929
- function waitForOutputDrain(socket, fail) {
1930
- return new Promise((resolve, reject) => {
1931
- let timer;
1932
- let finished = false;
1933
- const cleanup = () => {
1934
- if (timer !== void 0) clearTimeout(timer);
1935
- socket.off("drain", onDrain);
1936
- socket.off("close", onClose);
1937
- socket.off("error", onError);
1938
- };
1939
- const finish = (outcome) => {
1940
- if (finished) return;
1941
- finished = true;
1942
- cleanup();
1943
- if (outcome === "drained") resolve();
1944
- else if (outcome === "closed") reject(/* @__PURE__ */ new Error("local acp: output socket closed while draining"));
1945
- else {
1946
- fail("LOCAL_ACP_OUTPUT_BACKPRESSURE");
1947
- reject(/* @__PURE__ */ new Error("local acp: output drain exceeded its bounded wait"));
1948
- }
1949
- };
1950
- const onDrain = () => {
1951
- finish("drained");
1952
- };
1953
- const onClose = () => {
1954
- finish("closed");
1955
- };
1956
- const onError = () => {
1957
- finish("closed");
1958
- };
1959
- timer = setTimeout(() => {
1960
- finish("timeout");
1961
- }, OUTPUT_DRAIN_TIMEOUT_MS);
1962
- socket.once("drain", onDrain);
1963
- socket.once("close", onClose);
1964
- socket.once("error", onError);
1965
- });
1966
- }
1967
- /**
1968
- * Write ONE frame above the legacy cap in bounded chunks. The connection's
1969
- * unwritten backlog may never exceed `MAX_OUTPUT_BUFFER_BYTES`: before each
1970
- * chunk the writer waits (bounded) for the kernel to drain, and a refused
1971
- * `socket.write()` waits for its own `drain` before the next chunk. A reader
1972
- * that never drains the socket therefore closes THIS connection on the existing
1973
- * backpressure class; the Host, the Agent and every sibling connection are
1974
- * untouched, and no Host prompt is retried.
1975
- */
1976
- async function writeChunkedFrame(socket, frame, fail) {
1977
- let offset = 0;
1978
- while (offset < frame.byteLength) {
1979
- const end = Math.min(offset + OUTPUT_WRITE_CHUNK_BYTES, frame.byteLength);
1980
- while (!socket.destroyed && socket.writableLength + (end - offset) > MAX_OUTPUT_BUFFER_BYTES) await waitForOutputDrain(socket, fail);
1981
- if (socket.destroyed) throw new Error("local acp: output socket closed while writing a frame");
1982
- const accepted = socket.write(frame.subarray(offset, end));
1983
- offset = end;
1984
- if (!accepted) await waitForOutputDrain(socket, fail);
1985
- }
1986
- }
1987
- /**
1988
- * Build the bounded output side.
1989
- *
1990
- * Node reflects bytes accepted but not yet flushed to the kernel in
1991
- * `socket.writableLength`, so the pre-write cap on `writableLength + frame` is
1992
- * the enforced bound on "unwritten output": it closes a slow reader's
1993
- * connection instead of letting the queue grow without limit. Frames up to the
1994
- * legacy cap keep the original accept-then-resolve behavior. A larger frame —
1995
- * only possible when the connection derived a bounded budget from the Host's
1996
- * attachment limits — is written in 64 KiB chunks under the same backlog bound
1997
- * and a bounded kernel drain, so ONE legal committed image can reach a reading
1998
- * client without letting a stalled reader grow memory.
1999
- */
2000
- function createBoundedOutput(socket, fail, maxOutputFrameBytes) {
2001
- return new WritableStream({ async write(frame) {
2002
- if (socket.destroyed) throw new Error("local acp: output socket already closed");
2003
- if (frame.byteLength > maxOutputFrameBytes) {
2004
- fail("LOCAL_ACP_OUTPUT_FRAME_TOO_LARGE");
2005
- throw new Error("local acp: output frame exceeds the connection frame budget");
2006
- }
2007
- if (frame.byteLength <= MAX_OUTPUT_FRAME_BYTES) {
2008
- if (socket.writableLength + frame.byteLength > MAX_OUTPUT_BUFFER_BYTES) {
2009
- fail("LOCAL_ACP_OUTPUT_BACKPRESSURE");
2010
- throw new Error("local acp: output backlog exceeds the connection cap");
2011
- }
2012
- socket.write(frame);
2013
- return;
2014
- }
2015
- await writeChunkedFrame(socket, frame, fail);
2016
- } }, new ByteLengthQueuingStrategy({ highWaterMark: MAX_OUTPUT_BUFFER_BYTES }));
2017
- }
2018
- /** Build the per-connection ACP agent app whose handlers own only connection-local state. */
2019
- function buildAgentApp(state, view, context, fail) {
2020
- const app = agent({ name: AGENT_NAME });
2021
- let initializeComplete = false;
2022
- const beginRequest = () => {
2023
- state.pendingRequests += 1;
2024
- if (state.pendingRequests > MAX_PENDING_REQUESTS) {
2025
- state.pendingRequests -= 1;
2026
- fail("LOCAL_ACP_TOO_MANY_PENDING_REQUESTS");
2027
- throw new RequestError(-32044, "too many outstanding ACP requests on this connection", { code: "LOCAL_ACP_TOO_MANY_PENDING_REQUESTS" });
2028
- }
2029
- };
2030
- app.onRequest(methods.agent.initialize, async (request) => {
2031
- beginRequest();
2032
- try {
2033
- if (state.initialized) throw new RequestError(-32043, "ACP connection is already initialized", { code: "LOCAL_ACP_ALREADY_INITIALIZED" });
2034
- const requested = request.params?.protocolVersion;
2035
- if (requested !== PROTOCOL_VERSION) throw RequestError.invalidParams({ code: "LOCAL_ACP_PROTOCOL_UNSUPPORTED" }, `unsupported ACP protocol version ${String(requested)}; this endpoint supports ${String(PROTOCOL_VERSION)}`);
2036
- state.initialized = true;
2037
- if (context.sessionAccess !== void 0 && state.view !== void 0) {
2038
- const bounds = await context.sessionAccess.supportsImagePrompts() ? deriveImageInputBounds(context.sessionAccess.imageLimits()) : void 0;
2039
- if (bounds !== void 0) {
2040
- state.imageEnabled = true;
2041
- state.inputBounds = bounds;
2042
- }
2043
- }
2044
- initializeComplete = true;
2045
- return {
2046
- protocolVersion: PROTOCOL_VERSION,
2047
- agentInfo: {
2048
- name: AGENT_NAME,
2049
- title: AGENT_NAME,
2050
- version: context.bundleVersion
2051
- },
2052
- agentCapabilities: {
2053
- loadSession: false,
2054
- promptCapabilities: {
2055
- image: state.imageEnabled,
2056
- audio: false,
2057
- embeddedContext: false
2058
- },
2059
- mcpCapabilities: {
2060
- http: false,
2061
- sse: false
2062
- },
2063
- sessionCapabilities: context.sessionAccess !== void 0 ? {
2064
- resume: {},
2065
- close: {}
2066
- } : {}
2067
- },
2068
- authMethods: []
2069
- };
2070
- } finally {
2071
- state.pendingRequests -= 1;
2072
- }
2073
- });
2074
- const rejectSessionOperation = (_request) => {
2075
- beginRequest();
2076
- try {
2077
- rejectSessionNotReady();
2078
- } finally {
2079
- state.pendingRequests -= 1;
2080
- }
2081
- };
2082
- const acceptAnyParams = (params) => params;
2083
- const access = context.sessionAccess;
2084
- const views = context.views;
2085
- if (access !== void 0 && views !== void 0 && view !== void 0) {
2086
- const requireInitialized = () => {
2087
- if (!state.initialized || !initializeComplete) throw new RequestError(-32042, "ACP Session operations require a completed initialize", { code: "LOCAL_ACP_VIEW_NOT_INITIALIZED" });
2088
- };
2089
- const asRequestError = (error) => error instanceof LocalAcpViewError ? new RequestError(error.rpcCode, error.message, {
2090
- ...error.data,
2091
- code: error.code
2092
- }) : error;
2093
- app.onRequest(methods.agent.session.new, async ({ params }) => {
2094
- beginRequest();
2095
- try {
2096
- requireInitialized();
2097
- return await views.newSession(view, access, params);
2098
- } catch (error) {
2099
- throw asRequestError(error);
2100
- } finally {
2101
- state.pendingRequests -= 1;
2102
- }
2103
- });
2104
- app.onRequest(methods.agent.session.resume, async ({ params }) => {
2105
- beginRequest();
2106
- try {
2107
- requireInitialized();
2108
- return await views.resumeSession(view, access, params);
2109
- } catch (error) {
2110
- throw asRequestError(error);
2111
- } finally {
2112
- state.pendingRequests -= 1;
2113
- }
2114
- });
2115
- app.onRequest(methods.agent.session.close, async ({ params }) => {
2116
- beginRequest();
2117
- try {
2118
- requireInitialized();
2119
- return await views.closeSession(view, access, params.sessionId);
2120
- } catch (error) {
2121
- throw asRequestError(error);
2122
- } finally {
2123
- state.pendingRequests -= 1;
2124
- }
2125
- });
2126
- app.onRequest(methods.agent.session.prompt, async ({ params, signal, client }) => {
2127
- beginRequest();
2128
- try {
2129
- requireInitialized();
2130
- return await views.promptSession(view, access, params, signal, state.imageEnabled, async (update) => {
2131
- await client.notify(methods.client.session.update, {
2132
- sessionId: params.sessionId,
2133
- update
2134
- });
2135
- }, async (permissionParams, options) => {
2136
- return await client.request(methods.client.session.requestPermission, {
2137
- sessionId: permissionParams.sessionId,
2138
- toolCall: permissionParams.toolCall,
2139
- options: permissionParams.options
2140
- }, options === void 0 ? void 0 : { cancellationSignal: options.signal });
2141
- });
2142
- } catch (error) {
2143
- throw asRequestError(error);
2144
- } finally {
2145
- state.pendingRequests -= 1;
2146
- }
2147
- });
2148
- } else {
2149
- app.onRequest(methods.agent.session.new, acceptAnyParams, rejectSessionOperation);
2150
- app.onRequest(methods.agent.session.resume, acceptAnyParams, rejectSessionOperation);
2151
- app.onRequest(methods.agent.session.close, acceptAnyParams, rejectSessionOperation);
2152
- app.onRequest(methods.agent.session.prompt, acceptAnyParams, rejectSessionOperation);
2153
- }
2154
- app.onRequest(methods.agent.session.list, acceptAnyParams, rejectSessionOperation);
2155
- app.onRequest(methods.agent.session.setConfigOption, acceptAnyParams, rejectSessionOperation);
2156
- if (access !== void 0 && views !== void 0 && view !== void 0) app.onNotification(methods.agent.session.cancel, ({ params }) => {
2157
- if (!state.initialized) return;
2158
- if (typeof params?.sessionId !== "string" || params.sessionId === "") return;
2159
- views.cancelSession(view, access, params.sessionId);
2160
- });
2161
- else app.onNotification(methods.agent.session.cancel, () => {});
2162
- return app;
2163
- }
2164
- /** Wire one accepted socket to its own SDK connection; only this connection is affected by a fault. */
2165
- function serveConnection(socket, context) {
2166
- const view = context.views?.createConnection();
2167
- const state = {
2168
- initialized: false,
2169
- pendingRequests: 0,
2170
- closed: false,
2171
- imageEnabled: false,
2172
- inputBounds: TEXT_ONLY_BOUNDS,
2173
- maxOutputFrameBytes: deriveImageOutputBounds(context.sessionAccess?.imageLimits()) ?? MAX_OUTPUT_FRAME_BYTES,
2174
- ...view === void 0 ? {} : { view }
2175
- };
2176
- context.connectionStates.set(socket, state);
2177
- let tornDown = false;
2178
- let connection;
2179
- const fail = (code) => {
2180
- if (state.closed) return;
2181
- state.closed = true;
2182
- context.diag.warn("local-acp.error", {
2183
- code,
2184
- connections: context.connections.size
2185
- });
2186
- socket.destroy();
2187
- };
2188
- const teardown = () => {
2189
- if (tornDown) return;
2190
- tornDown = true;
2191
- state.closed = true;
2192
- if (view !== void 0) context.views?.releaseConnection(view, context.sessionAccess);
2193
- try {
2194
- connection?.close();
2195
- } catch {}
2196
- if (!socket.destroyed) socket.destroy();
2197
- context.connections.delete(socket);
2198
- context.connectionStates.delete(socket);
2199
- context.diag.info("local-acp.connection.close", { connections: context.connections.size });
2200
- };
2201
- socket.on("error", (error) => {
2202
- context.diag.warn("local-acp.error", {
2203
- code: error.code ?? "LOCAL_ACP_SOCKET_ERROR",
2204
- connections: context.connections.size
2205
- });
2206
- socket.destroy();
2207
- });
2208
- socket.on("close", teardown);
2209
- const input = createBoundedInput(socket, state, fail);
2210
- const output = createBoundedOutput(socket, fail, state.maxOutputFrameBytes);
2211
- const app = buildAgentApp(state, view, context, fail);
2212
- const stream = ndJsonStream(output, input);
2213
- connection = app.connect(stream);
2214
- const connected = connection;
2215
- runDetached("local acp: connection teardown", () => connected.closed.then(teardown, teardown), { diag: context.diag });
2216
- }
2217
- /** Open the scope directory and require `/proc/self/fd` so a long path can be bound by short fd path. */
2218
- function openScopeDirFd(scope) {
2219
- let dirFd;
2220
- try {
2221
- dirFd = openSync(scope.dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
2222
- } catch (error) {
2223
- throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the scope directory could not be opened without following a link", error);
2224
- }
2225
- if (process.platform !== "linux") {
2226
- closeSync(dirFd);
2227
- throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the fd-shortened socket path requires Linux /proc/self/fd");
2228
- }
2229
- return dirFd;
2230
- }
2231
- /** The short kernel-bind path derived from an open directory fd (Linux only). */
2232
- function fdSocketPath(dirFd) {
2233
- return `/proc/self/fd/${String(dirFd)}/${SOCKET_FILE}`;
2234
- }
2235
- /**
2236
- * Compute the FROZEN Darwin endpoint from the real profile scope id and the
2237
- * current OS uid: `/private/tmp/dpt-<decimal-uid>-<scope40>` holds one 0700 root
2238
- * whose `acp.sock` is the public address and whose `.acp-priv/acp.sock` is the
2239
- * private bind name. No configuration, environment variable or user path can
2240
- * change it, and both names must fit `sun_path[104]` INCLUDING the NUL. The
2241
- * caller creates/admits the root; this function performs no filesystem IO.
2242
- *
2243
- * @param scope - the canonical profile scope (its `scopeId` is a 64-hex SHA-256).
2244
- * @param uid - the current process uid; the root is scoped to this exact uid.
2245
- * @returns the public, root and private bind pathnames.
2246
- * @throws {LocalAcpError} `LOCAL_ACP_SOCKET_PATH_UNSUPPORTED` when a name exceeds
2247
- * the Darwin kernel path capacity.
2248
- */
2249
- function darwinAcpSocketPaths(scope, uid) {
2250
- const privateRoot = join(DARWIN_SOCKET_PARENT, `${DARWIN_ROOT_PREFIX}${String(uid)}-${scope.scopeId.slice(0, DARWIN_SCOPE_PREFIX_HEX)}`);
2251
- const publicPath = join(privateRoot, SOCKET_FILE);
2252
- const privateBindPath = join(privateRoot, PRIVATE_DIR, SOCKET_FILE);
2253
- if (Buffer.byteLength(publicPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES || Buffer.byteLength(privateBindPath, "utf8") + 1 > DARWIN_SUN_PATH_BYTES) throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin endpoint exceeds the kernel sun_path byte limit");
2254
- return {
2255
- publicPath,
2256
- privateRoot,
2257
- privateBindPath
2258
- };
2259
- }
2260
- /**
2261
- * Admit the trusted Darwin parent and create/reuse the ONE deterministic 0700
2262
- * root of this profile scope. `/private/tmp` must be the OS-owned, root-owned
2263
- * sticky directory the frozen endpoint contract relies on; the root itself must
2264
- * be a real directory owned by this uid (a symlink, file, foreign-owned entry or
2265
- * an EXISTING directory that is not 0700 is refused and never written through or
2266
- * silently repaired). The root is REUSED across ACP Off/On and Host crashes —
2267
- * only this scope's root is ever touched.
2268
- */
2269
- function ensureDarwinSocketRoot(privateRoot, uid) {
2270
- let parent;
2271
- try {
2272
- parent = lstatSync(DARWIN_SOCKET_PARENT);
2273
- } catch (error) {
2274
- throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin socket parent is not available", error);
2275
- }
2276
- if (parent.isSymbolicLink() || !parent.isDirectory() || parent.uid !== 0 || (parent.mode & 512) === 0) throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin socket parent is not a root-owned sticky directory");
2277
- let created = true;
2278
- try {
2279
- mkdirSync(privateRoot, { mode: 448 });
2280
- } catch (error) {
2281
- if (error.code !== "EEXIST") throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin endpoint root could not be created", error);
2282
- created = false;
2283
- }
2284
- const info = lstatSync(privateRoot);
2285
- if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the Darwin endpoint root is not a private directory owned by this uid");
2286
- if (created) {
2287
- chmodSync(privateRoot, 448);
2288
- return;
2289
- }
2290
- if ((info.mode & 511) !== 448) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the existing Darwin endpoint root is not a 0700 directory owned by this uid");
2291
- }
2292
- /** A ≤500ms connect probe used only to distinguish an inert stale socket from a live one. */
2293
- function probeSocket(path) {
2294
- return new Promise((resolve) => {
2295
- let settled = false;
2296
- const target = connect(path);
2297
- const finish = (verdict) => {
2298
- if (settled) return;
2299
- settled = true;
2300
- clearTimeout(timer);
2301
- target.destroy();
2302
- resolve(verdict);
2303
- };
2304
- const timer = setTimeout(() => finish("unknown"), CONNECT_PROBE_TIMEOUT_MS);
2305
- target.once("connect", () => finish("open"));
2306
- target.once("error", (error) => {
2307
- finish(error.code === "ECONNREFUSED" ? "refused" : "unknown");
2308
- });
2309
- });
2310
- }
2311
- /** Read the socket inode identity at one path, or reject a non-socket / foreign / symlink entry. */
2312
- function readSavedInode(path, uid) {
2313
- const info = lstatSync(path);
2314
- if (info.isSymbolicLink() || !info.isSocket() || info.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket path is not a socket owned by this uid");
2315
- return {
2316
- dev: info.dev,
2317
- ino: info.ino,
2318
- uid: info.uid
2319
- };
2320
- }
2321
- /**
2322
- * Start the one Host-owned local ACP listener for this scope.
2323
- *
2324
- * Ordering: probe/reclaim the logical path, bind the fd-shortened path, force
2325
- * the inode to 0600 and prove it, and only then return. The caller is
2326
- * responsible for committing Ready AFTER this resolves.
2327
- */
2328
- async function startLocalAcpListener(options) {
2329
- const { scope, maxConnections, diag, sessionAccess, views: sharedViews } = options;
2330
- const uid = process.getuid?.();
2331
- if (typeof uid !== "number") throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the current uid is unavailable");
2332
- if (!Number.isInteger(maxConnections) || maxConnections < 1 || maxConnections > 16) throw new LocalAcpError("LOCAL_ACP_INVALID_MAX_CONNECTIONS", "local acp: maxConnections must be an integer in 1..16");
2333
- const platform = process.platform;
2334
- const darwin = platform === "darwin";
2335
- if (platform !== "linux" && !darwin) throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the local ACP endpoint is supported on Linux and macOS only");
2336
- const darwinPaths = darwin ? darwinAcpSocketPaths(scope, uid) : void 0;
2337
- const logicalPath = darwinPaths === void 0 ? join(scope.dir, SOCKET_FILE) : darwinPaths.publicPath;
2338
- let scopeDirFd;
2339
- if (darwinPaths === void 0) scopeDirFd = openScopeDirFd(scope);
2340
- else ensureDarwinSocketRoot(darwinPaths.privateRoot, uid);
2341
- const scopeProbePath = scopeDirFd === void 0 ? logicalPath : fdSocketPath(scopeDirFd);
2342
- const privDir = darwinPaths === void 0 ? join(scope.dir, PRIVATE_DIR) : join(darwinPaths.privateRoot, PRIVATE_DIR);
2343
- let privFd;
2344
- let scopeDirFdClosed = false;
2345
- let privFdClosed = false;
2346
- let saved;
2347
- let server;
2348
- let stopping = false;
2349
- let closed;
2350
- const context = {
2351
- diag,
2352
- bundleVersion: scope.bundleVersion,
2353
- connections: /* @__PURE__ */ new Set(),
2354
- connectionStates: /* @__PURE__ */ new Map(),
2355
- ...sessionAccess === void 0 ? {} : {
2356
- sessionAccess,
2357
- views: sharedViews ?? new AcpSessionViewRegistry(diag)
2358
- }
2359
- };
2360
- const views = context.views;
2361
- const ownsFacts = views !== void 0 && sessionAccess !== void 0 && sharedViews === void 0;
2362
- if (views !== void 0 && sessionAccess !== void 0) views.observeFacts(sessionAccess);
2363
- const releasePromptFacts = () => {
2364
- if (!ownsFacts) return;
2365
- views?.disposeFacts();
2366
- };
2367
- const closeScopeDirFd = () => {
2368
- if (scopeDirFdClosed || scopeDirFd === void 0) return;
2369
- scopeDirFdClosed = true;
2370
- try {
2371
- closeSync(scopeDirFd);
2372
- } catch {}
2373
- };
2374
- const closePrivFd = () => {
2375
- if (privFdClosed || privFd === void 0) return;
2376
- privFdClosed = true;
2377
- try {
2378
- closeSync(privFd);
2379
- } catch {}
2380
- };
2381
- const removePrivDir = () => {
2382
- try {
2383
- rmdirSync(privDir);
2384
- } catch {}
2385
- };
2386
- /**
2387
- * Remove ONLY this process's owned socket inode. Identity-checked against the
2388
- * exact saved (dev, ino, uid): a foreign inode that has since replaced the
2389
- * pathname is never unlinked. Used by graceful retire, bind-failure cleanup and
2390
- * the synchronous process-exit mirror.
2391
- */
2392
- const cleanupSync = () => {
2393
- if (saved === void 0) return;
2394
- let current;
2395
- try {
2396
- current = lstatSync(logicalPath);
2397
- } catch {
2398
- return;
2399
- }
2400
- if (!current.isSocket() || current.uid !== saved.uid) return;
2401
- if (current.dev !== saved.dev || current.ino !== saved.ino) return;
2402
- try {
2403
- unlinkSync(logicalPath);
2404
- } catch {}
2405
- };
2406
- const retireServer = () => {
2407
- if (closed !== void 0) return closed;
2408
- stopping = true;
2409
- closed = (async () => {
2410
- for (const socket of context.connections) socket.destroy();
2411
- if (server !== void 0) await new Promise((resolveClose) => {
2412
- server.close(() => resolveClose());
2413
- });
2414
- cleanupSync();
2415
- closeScopeDirFd();
2416
- closePrivFd();
2417
- removePrivDir();
2418
- disposeFactsWhenSettled();
2419
- })();
2420
- return closed;
2421
- };
2422
- /**
2423
- * Dispose the ONE Host fact subscription once every ACCEPTED piece of work
2424
- * has settled on real Host facts (a pending admission inserted/classified,
2425
- * a queued removal committed, the owned turn's terminal drained, or a
2426
- * retired-turn fence ended). It never cancels work the ACP View may not
2427
- * cancel (D23 mixed turns) and never guesses with a timer: the registry's
2428
- * own settlement transitions resolve it. Detached, so retirement and Host
2429
- * shutdown are never blocked by a shared turn's duration.
2430
- */
2431
- const disposeFactsWhenSettled = () => {
2432
- if (views === void 0 || !ownsFacts) return;
2433
- runDetached("local acp: Host fact subscription retirement", async () => {
2434
- await views.whenHostWorkSettled();
2435
- releasePromptFacts();
2436
- }, { diag });
2437
- };
2438
- try {
2439
- let existing;
2440
- try {
2441
- existing = lstatSync(logicalPath);
2442
- } catch (error) {
2443
- if (error.code !== "ENOENT") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket path is not accessible", error);
2444
- }
2445
- if (existing !== void 0) {
2446
- if (existing.isSymbolicLink() || !existing.isSocket() || existing.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: a non-socket, symlink or foreign-owned entry occupies the socket path");
2447
- const verdict = await probeSocket(scopeProbePath);
2448
- if (verdict === "open") throw new LocalAcpError("LOCAL_ACP_SOCKET_IN_USE", "local acp: a live listener already answers on the socket path");
2449
- if (verdict !== "refused") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the existing socket path could not be proven stale");
2450
- const recheck = readSavedInode(logicalPath, uid);
2451
- if (recheck.dev !== existing.dev || recheck.ino !== existing.ino) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket inode changed during the stale reclaim");
2452
- unlinkSync(logicalPath);
2453
- }
2454
- let privCreated = true;
2455
- try {
2456
- mkdirSync(privDir, { mode: 448 });
2457
- } catch (error) {
2458
- if (error.code !== "EEXIST") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind directory could not be created", error);
2459
- privCreated = false;
2460
- }
2461
- if (!privCreated) {
2462
- const dirInfo = lstatSync(privDir);
2463
- if (dirInfo.isSymbolicLink() || !dirInfo.isDirectory() || dirInfo.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path is not a directory owned by this uid");
2464
- }
2465
- chmodSync(privDir, 448);
2466
- let privBindPath;
2467
- if (darwinPaths === void 0) {
2468
- privFd = openSync(privDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
2469
- privBindPath = fdSocketPath(privFd);
2470
- } else privBindPath = darwinPaths.privateBindPath;
2471
- let privExisting;
2472
- try {
2473
- privExisting = lstatSync(privBindPath);
2474
- } catch (error) {
2475
- if (error.code !== "ENOENT") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path is not accessible", error);
2476
- }
2477
- if (privExisting !== void 0) {
2478
- if (privExisting.isSymbolicLink() || !privExisting.isSocket() || privExisting.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path is occupied by a non-socket, symlink or foreign-owned entry");
2479
- const privVerdict = await probeSocket(privBindPath);
2480
- if (privVerdict === "open") throw new LocalAcpError("LOCAL_ACP_SOCKET_IN_USE", "local acp: a live listener already occupies the private bind path");
2481
- if (privVerdict !== "refused") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path could not be proven stale");
2482
- const privRecheck = readSavedInode(privBindPath, uid);
2483
- if (privRecheck.dev !== privExisting.dev || privRecheck.ino !== privExisting.ino) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private socket inode changed during the stale recover");
2484
- unlinkSync(privBindPath);
2485
- }
2486
- server = createServer((socket) => {
2487
- if (stopping) {
2488
- socket.destroy();
2489
- return;
2490
- }
2491
- if (context.connections.size >= maxConnections) {
2492
- diag.warn("local-acp.connection.reject", {
2493
- code: "LOCAL_ACP_CAPACITY_EXCEEDED",
2494
- connections: context.connections.size
2495
- });
2496
- socket.on("error", () => socket.destroy());
2497
- socket.end(CAPACITY_ERROR_LINE, () => socket.destroy());
2498
- return;
2499
- }
2500
- context.connections.add(socket);
2501
- diag.info("local-acp.connection.open", { connections: context.connections.size });
2502
- serveConnection(socket, context);
2503
- });
2504
- await new Promise((resolveListen, rejectListen) => {
2505
- server.once("error", rejectListen);
2506
- server.listen(privBindPath, () => {
2507
- server.off("error", rejectListen);
2508
- resolveListen();
2509
- });
2510
- });
2511
- server.on("error", (error) => {
2512
- diag.warn("local-acp.error", { code: error.code ?? "LOCAL_ACP_SERVER_ERROR" });
2513
- });
2514
- chmodSync(join(privDir, SOCKET_FILE), 384);
2515
- try {
2516
- linkSync(join(privDir, SOCKET_FILE), logicalPath);
2517
- } catch (error) {
2518
- if (error.code === "EEXIST") throw new LocalAcpError("LOCAL_ACP_SOCKET_IN_USE", "local acp: a foreign entry occupies the socket path (refusing to overwrite it)");
2519
- throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket path could not be published", error);
2520
- }
2521
- const linked = lstatSync(logicalPath);
2522
- saved = {
2523
- dev: linked.dev,
2524
- ino: linked.ino,
2525
- uid: linked.uid
2526
- };
2527
- if (!linked.isSocket() || linked.uid !== uid) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the published socket is not a socket owned by this uid");
2528
- unlinkSync(join(privDir, SOCKET_FILE));
2529
- if ((linked.mode & 511) !== 384) throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the bound socket is not a 0600 socket owned by this uid");
2530
- closeScopeDirFd();
2531
- diag.info("local-acp.listen", { connections: 0 });
2532
- } catch (error) {
2533
- for (const socket of context.connections) socket.destroy();
2534
- releasePromptFacts();
2535
- if (server !== void 0) try {
2536
- await new Promise((resolveClose) => {
2537
- server.close(() => resolveClose());
2538
- });
2539
- } catch {}
2540
- cleanupSync();
2541
- closeScopeDirFd();
2542
- closePrivFd();
2543
- removePrivDir();
2544
- throw error;
2545
- }
2546
- const isListening = () => {
2547
- if (stopping || closed !== void 0 || server === void 0 || !server.listening) return false;
2548
- if (saved === void 0) return false;
2549
- let current;
2550
- try {
2551
- current = lstatSync(logicalPath);
2552
- } catch {
2553
- return false;
2554
- }
2555
- return current.isSocket() && current.uid === saved.uid && current.dev === saved.dev && current.ino === saved.ino;
2556
- };
2557
- return {
2558
- socketPath: logicalPath,
2559
- connectionCount: () => context.connections.size,
2560
- isListening,
2561
- close: retireServer,
2562
- cleanupSync
2563
- };
2564
- }
2565
- //#endregion
2566
- export { ACP_IMAGE_MEDIA_TYPES as a, createLocalAcpStatusHandler as c, startLocalAcpListener as i, observeAuthenticatedLocalAcpStatus as l, darwinAcpSocketPaths as n, AcpSessionViewRegistry as o, parseAcpMaxConnections as r, LOCAL_ACP_STATUS_ROUTE as s, LocalAcpError as t };