@xmoon76/dsh-pi-tui 0.5.8 → 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 (77) hide show
  1. package/README.en.md +61 -25
  2. package/README.md +61 -25
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-CMIjGyuk.mjs → bootstrap-CVyHGQDX.mjs} +21901 -6575
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-BjGPc-DM.mjs → client-bootstrap-4UoeVIHE.mjs} +2488 -2734
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-Dult7Jxv.mjs → daemon-launcher-DxIgjBHW.mjs} +1549 -172
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/{local-profile-daemon-admin-BmQSdzT0.mjs → diagnostics-Db5iVcuJ.mjs} +3 -90
  14. package/dist/{entry-control-DjNsE3I0.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-B4uLpSTv.mjs → extensions-Dx7ncPNA.mjs} +1 -1
  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-DMNTmNrH.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 +22334 -6695
  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 +292 -63
  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-uOBfFq5j.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-egN4_gsQ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-DOSsCh9q.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +952 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DamiMqPd.mjs → local-scope-5DEKA_lW.mjs} +1023 -96
  43. package/dist/{local-transport-Iwo0mtu3.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DMrjwCkl.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-C6tSs86s.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-CstInGIA.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-EG5UqIcd.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-CpfpQO_h.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -332
  70. package/dist/{transcript-view-CuJYWkhp.mjs → transcript-view-B6vCnukn.mjs} +2096 -977
  71. package/dist/{transcript-view-C1YtJ49Y.mjs → transcript-view-DSSdE2vK.mjs} +2078 -651
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +20 -3
  74. package/dist/local-acp-listener-B65J0Bx4.mjs +0 -3115
  75. package/dist/local-daemon-control-C14q9KnD.mjs +0 -1588
  76. package/dist/local-daemon-control-TCnERL7n.mjs +0 -1424
  77. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,3115 +0,0 @@
1
- import "./local-scope-DamiMqPd.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-model-selection.ts
130
- const JSONRPC_INVALID_PARAMS$1 = -32602;
131
- const JSONRPC_MODEL_UNAVAILABLE = -32042;
132
- const JSONRPC_MODEL_BUSY = -32046;
133
- /** One classified model-configuration rejection. */
134
- var AcpModelError = class extends Error {
135
- code;
136
- rpcCode;
137
- data;
138
- constructor(code, message, rpcCode, data = {}) {
139
- super(message);
140
- this.name = "AcpModelError";
141
- this.code = code;
142
- this.rpcCode = rpcCode;
143
- this.data = data;
144
- }
145
- };
146
- const MODEL_CONFIG_ID = "model";
147
- const THOUGHT_LEVEL_CONFIG_ID = "thought_level";
148
- const MODEL_OPTION_NAME = "Model";
149
- const THOUGHT_LEVEL_OPTION_NAME = "Reasoning effort";
150
- const MODEL_DEFAULT_EFFORT_NAME = "Model default";
151
- const CURRENT_MODEL_PLACEHOLDER = "Current (unavailable) — choose another model";
152
- const CURRENT_EFFORT_PLACEHOLDER = "Current effort (unavailable)";
153
- const NO_MODEL_PLACEHOLDER = "No model selected";
154
- const UNAVAILABLE_GROUP_NAME = "Unavailable";
155
- /** Encode one exact model route as an opaque ACP select value. */
156
- function modelValue(providerId, modelId) {
157
- return JSON.stringify([providerId, modelId]);
158
- }
159
- /** Encode the "omit explicit effort, use the adapter default" choice. */
160
- function defaultEffortValue() {
161
- return JSON.stringify(["default"]);
162
- }
163
- /** Encode one explicit official reasoning effort id. */
164
- function effortValue(effortId) {
165
- return JSON.stringify(["effort", effortId]);
166
- }
167
- /** Presentation-only selector value for a current effort the catalog no longer advertises. */
168
- function unavailableEffortValue(effortId) {
169
- return JSON.stringify(["unavailable", effortId]);
170
- }
171
- /** The one internal presentation-only value that no valid model route uses. */
172
- const UNSET_MODEL_VALUE = JSON.stringify(["unset"]);
173
- function invalidOption(message) {
174
- return new AcpModelError("LOCAL_ACP_MODEL_INVALID_OPTION", message, JSONRPC_INVALID_PARAMS$1);
175
- }
176
- function modelUnavailable(message) {
177
- return new AcpModelError("LOCAL_ACP_MODEL_UNAVAILABLE", message, JSONRPC_MODEL_UNAVAILABLE);
178
- }
179
- function agentBusy() {
180
- return new AcpModelError("LOCAL_ACP_MODEL_AGENT_BUSY", "the session agent is busy", JSONRPC_MODEL_BUSY);
181
- }
182
- function viewBusy() {
183
- return new AcpModelError("LOCAL_ACP_MODEL_VIEW_BUSY", "a prompt is already in flight for this session view", JSONRPC_MODEL_BUSY);
184
- }
185
- function staleSelection() {
186
- return new AcpModelError("LOCAL_ACP_MODEL_STALE", "the attached session changed during the model request", JSONRPC_MODEL_UNAVAILABLE);
187
- }
188
- function conflictingSelection() {
189
- return new AcpModelError("LOCAL_ACP_MODEL_CONFLICT", "the session model changed during the request", JSONRPC_MODEL_BUSY);
190
- }
191
- /** A detached copy so a later Agent mutation can never rewrite the baseline. */
192
- function copySelection(selection) {
193
- if (selection === void 0) return void 0;
194
- return {
195
- provider: selection.provider,
196
- model: selection.model,
197
- ...selection.reasoningEffort === void 0 ? {} : { reasoningEffort: selection.reasoningEffort }
198
- };
199
- }
200
- /** Compare the complete selection; an absent effort is its own value. */
201
- function sameSelection(left, right) {
202
- if (left === void 0 || right === void 0) return left === right;
203
- return left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort;
204
- }
205
- function parseModelValue(value) {
206
- if (typeof value !== "string") return void 0;
207
- let parsed;
208
- try {
209
- parsed = JSON.parse(value);
210
- } catch {
211
- return;
212
- }
213
- if (!Array.isArray(parsed) || parsed.length !== 2) return void 0;
214
- const [provider, model] = parsed;
215
- if (typeof provider !== "string" || provider.length === 0 || typeof model !== "string" || model.length === 0) return void 0;
216
- return {
217
- provider,
218
- model
219
- };
220
- }
221
- function parseEffortValue(value) {
222
- if (typeof value !== "string") return void 0;
223
- let parsed;
224
- try {
225
- parsed = JSON.parse(value);
226
- } catch {
227
- return;
228
- }
229
- if (!Array.isArray(parsed)) return void 0;
230
- if (parsed.length === 1 && parsed[0] === "default") return { kind: "default" };
231
- if (parsed.length === 2 && parsed[0] === "effort" && typeof parsed[1] === "string" && parsed[1].length > 0) return {
232
- kind: "effort",
233
- effortId: parsed[1]
234
- };
235
- }
236
- /**
237
- * Project one official catalog plus the exact current selection into the full
238
- * standard ACP option list. Pure and detached: every call re-reads the caller's
239
- * catalog snapshot and never remembers a previous option table.
240
- */
241
- function projectModelState(catalog, current) {
242
- const groups = [];
243
- const modelChoices = /* @__PURE__ */ new Map();
244
- const reasoningByModel = /* @__PURE__ */ new Map();
245
- const presentationOnlyValues = /* @__PURE__ */ new Set();
246
- for (const group of catalog.groups) {
247
- const entries = [];
248
- for (const model of group.models) {
249
- const value = modelValue(group.id, model.id);
250
- modelChoices.set(value, {
251
- provider: group.id,
252
- model: model.id
253
- });
254
- if (model.reasoning !== void 0 && model.reasoning.efforts.length > 0) reasoningByModel.set(value, model.reasoning);
255
- entries.push({
256
- value,
257
- name: model.name,
258
- ...model.description === void 0 ? {} : { description: model.description }
259
- });
260
- }
261
- if (entries.length > 0) groups.push({
262
- group: `group:${group.id}`,
263
- name: group.name,
264
- options: entries
265
- });
266
- }
267
- let currentModelValue;
268
- if (current === void 0) {
269
- currentModelValue = UNSET_MODEL_VALUE;
270
- presentationOnlyValues.add(currentModelValue);
271
- groups.push({
272
- group: "group:unavailable",
273
- name: UNAVAILABLE_GROUP_NAME,
274
- options: [{
275
- value: currentModelValue,
276
- name: NO_MODEL_PLACEHOLDER
277
- }]
278
- });
279
- } else {
280
- currentModelValue = modelValue(current.provider, current.model);
281
- if (!modelChoices.has(currentModelValue)) {
282
- presentationOnlyValues.add(currentModelValue);
283
- const groupId = `group:${current.provider}`;
284
- let group = groups.find((candidate) => candidate.group === groupId);
285
- if (group === void 0) {
286
- group = {
287
- group: groupId,
288
- name: current.provider,
289
- options: []
290
- };
291
- groups.push(group);
292
- }
293
- group.options.unshift({
294
- value: currentModelValue,
295
- name: CURRENT_MODEL_PLACEHOLDER
296
- });
297
- }
298
- }
299
- const options = [{
300
- id: MODEL_CONFIG_ID,
301
- name: MODEL_OPTION_NAME,
302
- category: "model",
303
- type: "select",
304
- currentValue: currentModelValue,
305
- options: groups
306
- }];
307
- if (current !== void 0) {
308
- const reasoning = reasoningByModel.get(modelValue(current.provider, current.model));
309
- if (reasoning !== void 0 && reasoning.efforts.length > 0) {
310
- const thoughtOptions = [{
311
- value: defaultEffortValue(),
312
- name: MODEL_DEFAULT_EFFORT_NAME
313
- }];
314
- for (const effort of reasoning.efforts) thoughtOptions.push({
315
- value: effortValue(effort.id),
316
- name: effort.name,
317
- ...effort.description === void 0 ? {} : { description: effort.description }
318
- });
319
- let currentThoughtValue;
320
- if (current.reasoningEffort === void 0) currentThoughtValue = defaultEffortValue();
321
- else if (reasoning.efforts.some((effort) => effort.id === current.reasoningEffort)) currentThoughtValue = effortValue(current.reasoningEffort);
322
- else {
323
- currentThoughtValue = unavailableEffortValue(current.reasoningEffort);
324
- presentationOnlyValues.add(currentThoughtValue);
325
- thoughtOptions.unshift({
326
- value: currentThoughtValue,
327
- name: CURRENT_EFFORT_PLACEHOLDER
328
- });
329
- }
330
- options.push({
331
- id: THOUGHT_LEVEL_CONFIG_ID,
332
- name: THOUGHT_LEVEL_OPTION_NAME,
333
- category: "thought_level",
334
- type: "select",
335
- currentValue: currentThoughtValue,
336
- options: thoughtOptions
337
- });
338
- }
339
- }
340
- return {
341
- options,
342
- modelChoices,
343
- reasoningByModel,
344
- presentationOnlyValues
345
- };
346
- }
347
- /** Read one stable host error code without exposing its message or stack. */
348
- function hostErrorCode$1(error) {
349
- if (typeof error === "object" && error !== null && "code" in error) {
350
- const code = error.code;
351
- if (typeof code === "string" && code.length > 0) return code;
352
- }
353
- }
354
- /**
355
- * The internal Session-only model service bound once per Host ACP access.
356
- * It owns no persistent state: every request re-reads the Host authority.
357
- */
358
- var AcpSessionModelService = class {
359
- host;
360
- constructor(host) {
361
- this.host = host;
362
- }
363
- /**
364
- * Read the complete standard option state for one exact attached Agent.
365
- * A missing catalog is a real failure; the caller may omit optional display.
366
- */
367
- async readOptions(expectedAgent, expectedSession) {
368
- this.assertExact(expectedAgent, expectedSession);
369
- try {
370
- const catalog = await this.readCatalog();
371
- this.assertExact(expectedAgent, expectedSession);
372
- return projectModelState(catalog, copySelection(expectedAgent.model.current())).options;
373
- } catch (error) {
374
- this.assertExact(expectedAgent, expectedSession);
375
- throw error;
376
- }
377
- }
378
- /**
379
- * Validate and commit one Session-only model/effort selection.
380
- *
381
- * All provider/catalog reads happen BEFORE `runMaintenance`. The maintenance
382
- * callback itself performs only synchronous identity, baseline and abort
383
- * checks followed by the official `agent.model.select()` and a readback; it
384
- * never awaits provider I/O, so a slow catalog cannot block a TUI turn.
385
- */
386
- async selectSessionOnly(expectedAgent, expectedSession, request, signal, stillCurrent) {
387
- this.validateRequestShape(request);
388
- this.assertCurrent(expectedAgent, expectedSession, signal, stillCurrent);
389
- const baseline = copySelection(expectedAgent.model.current());
390
- if (expectedAgent.status !== "idle") throw agentBusy();
391
- const catalog = await this.readCatalog();
392
- this.assertCurrent(expectedAgent, expectedSession, signal, stillCurrent);
393
- const projected = projectModelState(catalog, baseline);
394
- let intended;
395
- if (request.configId === MODEL_CONFIG_ID) {
396
- if (typeof request.value !== "string" || projected.presentationOnlyValues.has(request.value)) throw invalidOption("the requested model option is not selectable");
397
- const choice = projected.modelChoices.get(request.value);
398
- if (choice === void 0) {
399
- const parsed = parseModelValue(request.value);
400
- if (parsed !== void 0 && this.catalogKnowsProvider(catalog, parsed.provider)) throw modelUnavailable("the requested model is not available from the Host");
401
- throw invalidOption("the requested model option is unknown");
402
- }
403
- await this.assertModelRoutable(choice.provider, choice.model, signal);
404
- this.assertCurrent(expectedAgent, expectedSession, signal, stillCurrent);
405
- intended = baseline !== void 0 && baseline.provider === choice.provider && baseline.model === choice.model ? copySelection(baseline) : {
406
- provider: choice.provider,
407
- model: choice.model
408
- };
409
- } else {
410
- const baselineSelection = baseline;
411
- if (baselineSelection === void 0) throw invalidOption("no model is selected for this session");
412
- const reasoning = projected.reasoningByModel.get(modelValue(baselineSelection.provider, baselineSelection.model));
413
- if (reasoning === void 0 || reasoning.efforts.length === 0) throw invalidOption("the selected model declares no reasoning efforts");
414
- const parsed = parseEffortValue(request.value);
415
- if (parsed === void 0) throw invalidOption("the requested reasoning effort is unknown");
416
- if (parsed.kind === "effort" && !reasoning.efforts.some((effort) => effort.id === parsed.effortId)) throw invalidOption("the requested reasoning effort is not available for this model");
417
- intended = {
418
- provider: baselineSelection.provider,
419
- model: baselineSelection.model,
420
- ...parsed.kind === "effort" ? { reasoningEffort: parsed.effortId } : {}
421
- };
422
- await this.assertModelRoute(intended, signal);
423
- this.assertCurrent(expectedAgent, expectedSession, signal, stillCurrent);
424
- }
425
- return projectModelState(catalog, await this.commitIfCurrent(expectedAgent, expectedSession, intended, baseline, signal, stillCurrent)).options;
426
- }
427
- /** Reject everything outside the standard select subset for the two known config ids. */
428
- validateRequestShape(request) {
429
- if (request.type === "boolean") throw invalidOption("boolean session config options are not supported");
430
- if (request.configId !== MODEL_CONFIG_ID && request.configId !== THOUGHT_LEVEL_CONFIG_ID) throw invalidOption("unknown session config option");
431
- if (typeof request.value !== "string" || request.value.length === 0) throw invalidOption("the session config option requires a non-empty select value");
432
- }
433
- /** The exact live Agent/Session must still be the ones this View attached. */
434
- assertExact(expectedAgent, expectedSession) {
435
- const sessionId = expectedAgent.id;
436
- if (this.host.currentAgent(sessionId) !== expectedAgent || this.host.currentSession(sessionId) !== expectedSession) throw staleSelection();
437
- }
438
- /** Exact identity + View claim + request abort fence after an await. */
439
- assertCurrent(expectedAgent, expectedSession, signal, stillCurrent) {
440
- if (signal.aborted) throw staleSelection();
441
- const currentness = stillCurrent();
442
- if (currentness === "view-busy") throw viewBusy();
443
- if (currentness !== "current") throw staleSelection();
444
- this.assertExact(expectedAgent, expectedSession);
445
- }
446
- /** Read the official Host catalog; any failure is the stable unavailable class. */
447
- async readCatalog() {
448
- try {
449
- return await this.host.modelCatalog();
450
- } catch {
451
- throw modelUnavailable("the Host model catalog is unavailable");
452
- }
453
- }
454
- /** Whether the provider is a real catalog route that currently failed or holds no such model. */
455
- catalogKnowsProvider(catalog, providerId) {
456
- return catalog.groups.some((group) => group.id === providerId) || (catalog.failures ?? []).some((failure) => failure.id === providerId);
457
- }
458
- /** Model selection validation: the fresh provider/model directory plus adapter defaults. */
459
- async assertModelRoutable(providerId, modelId, signal) {
460
- await this.assertModelRoute({
461
- provider: providerId,
462
- model: modelId
463
- }, signal);
464
- }
465
- /**
466
- * Validate one exact route against the live LLM registry. A missing route is
467
- * `UNAVAILABLE`; an unsupported explicit effort is `INVALID_OPTION` because it
468
- * is the caller's option value that is wrong for the model, not a vanished
469
- * provider.
470
- */
471
- async assertModelRoute(route, signal) {
472
- let providers;
473
- try {
474
- providers = this.host.listProviders();
475
- } catch {
476
- throw modelUnavailable("the Host model provider list is unavailable");
477
- }
478
- if (!providers.some((provider) => provider.id === route.provider)) throw modelUnavailable("the requested model provider is not available");
479
- let models;
480
- try {
481
- models = await this.host.listModels(route.provider);
482
- } catch {
483
- throw modelUnavailable("the requested model provider catalog is unavailable");
484
- }
485
- if (signal.aborted) throw staleSelection();
486
- if (!models.some((model) => model.id === route.model)) throw modelUnavailable("the requested model is not available");
487
- try {
488
- await this.host.resolveCallConfig(route, signal);
489
- } catch (error) {
490
- if (route.reasoningEffort !== void 0 && hostErrorCode$1(error) === "UNSUPPORTED_REASONING_EFFORT") throw invalidOption("the requested reasoning effort is not supported by this model");
491
- throw modelUnavailable("the requested model configuration is not available");
492
- }
493
- if (signal.aborted) throw staleSelection();
494
- }
495
- /**
496
- * Claim the true idle phase, re-check every currentness fence synchronously,
497
- * then perform the one official Session-only write and an authority readback.
498
- */
499
- async commitIfCurrent(expectedAgent, expectedSession, intended, baseline, signal, stillCurrent) {
500
- const sessionId = expectedAgent.id;
501
- let maintenance;
502
- try {
503
- maintenance = expectedAgent.runMaintenance(async (maintenanceSignal) => {
504
- if (signal.aborted || maintenanceSignal.aborted) throw staleSelection();
505
- const currentness = stillCurrent();
506
- if (currentness === "view-busy") throw viewBusy();
507
- if (currentness !== "current") throw staleSelection();
508
- if (this.host.currentAgent(sessionId) !== expectedAgent || this.host.currentSession(sessionId) !== expectedSession) throw staleSelection();
509
- if (!sameSelection(expectedAgent.model.current(), baseline)) throw conflictingSelection();
510
- expectedAgent.model.select(intended);
511
- const committed = expectedAgent.model.current();
512
- if (!sameSelection(committed, intended)) throw staleSelection();
513
- return copySelection(committed);
514
- });
515
- } catch {
516
- throw agentBusy();
517
- }
518
- return await maintenance;
519
- }
520
- };
521
- //#endregion
522
- //#region src/app/remote-process/local-acp-session-view.ts
523
- /**
524
- * Connection-scoped Host ACP Session View.
525
- *
526
- * The Host-owned local ACP v1 listener (PO-1/PO-1B) is a protocol front door
527
- * that owns NO Agent, Session or business method. PO-2 adds the narrowest
528
- * shared-Session capability on top of that same `<scope.dir>/acp.sock`: one
529
- * ACP connection may BORROW at most one live Host Session, while the Session's
530
- * own Agent/Session/Writer authority stays entirely with the official Host
531
- * services. This module owns ONLY the ephemeral, per-listener reservation map
532
- * and the pure connection View lifecycle; it never subscribes to, resumes on
533
- * its own, cancels, disposes or flushes any Host Agent, and it never persists
534
- * an ACP mapping.
535
- *
536
- * The authority boundaries this module must respect:
537
- * - Session create/resume is `sessionController.create` / `resolveAgent`
538
- * (the SAME Host services), never `ctx.agents.create/resume`.
539
- * - The Host Workspace Controller is the only directory authority for
540
- * `session/new`; the client cwd is a proposal only.
541
- * - `close` detaches ONLY this connection's View. It never touches a shared
542
- * Agent so a human Split TUI Client that also references the Session keeps
543
- * working, and a later connection may attach again.
544
- *
545
- * A single connection follows the transient protocol view
546
- * `idle -> attaching -> attached -> idle|closed`. The reservation is committed
547
- * with a synchronous `Map.set()` BEFORE any official Host await, so a second
548
- * request on the same connection, or a competing connection, is refused before
549
- * it can create a second Host business resource. A late async result only
550
- * commits when its own connection state is still the same live one.
551
- *
552
- * PO-3A adds ONE prompt flight per attached View. The View mints the official
553
- * `requestId`, submits the official Session Controller prompt exactly once in
554
- * queue mode, and correlates the real Host facts back to that exact request:
555
- * `source.rpcId === requestId` at `agent/inbox/inserted`, the claimed
556
- * `agent/inbox/claimed` turn for that exact message id, and the committed
557
- * Session events carrying that same `data.turn`. It projects only that turn's
558
- * committed output as standard ACP `session/update` notifications, drains them,
559
- * and only then answers a real ACP StopReason. A turn that also claims another
560
- * user's message is a MIXED turn: no further output is projected and the
561
- * request fails closed instead of returning a fabricated success.
562
- *
563
- * PO-4C widens that projection to the standard committed content of
564
- * `assistant/message` and `tool/result`: ordered text, thought chunks and
565
- * images, where every image is re-read and integrity-verified by the official
566
- * Host Attachment Store before its canonical Base64 reaches the wire. The
567
- * conversion runs INSIDE the flight's single `outputTail`, so a committed
568
- * event's asynchronous image read never lets a later event overtake it; a
569
- * content conversion failure fails the request instead of sending a partial
570
- * event as success.
571
- *
572
- * @module app/remote-process/local-acp-session-view
573
- */
574
- /**
575
- * One classified View rejection. `rpcCode` is the JSON-RPC error code the
576
- * listener maps onto an ACP `RequestError`; `code` is the stable data code.
577
- * `data` carries non-sensitive structured facts the caller may act on — most
578
- * importantly the authoritative `sessionId` of a Session the Host already
579
- * created before a later step failed.
580
- */
581
- var LocalAcpViewError = class extends Error {
582
- code;
583
- rpcCode;
584
- data;
585
- constructor(code, message, rpcCode, data = {}) {
586
- super(message);
587
- this.name = "LocalAcpViewError";
588
- this.code = code;
589
- this.rpcCode = rpcCode;
590
- this.data = data;
591
- }
592
- };
593
- /** Raster MIME vocabulary shared by the ACP wire and official Host admission. */
594
- const ACP_IMAGE_MEDIA_TYPES = [
595
- "image/png",
596
- "image/jpeg",
597
- "image/webp",
598
- "image/gif"
599
- ];
600
- /** The maximum number of not-yet-written notifications ONE prompt flight may queue. */
601
- const MAX_PENDING_OUTPUT_UPDATES = 64;
602
- const JSONRPC_INVALID_PARAMS = -32602;
603
- const JSONRPC_INTERNAL_ERROR = -32603;
604
- /** One standard classified prompt failure. */
605
- function promptError(code, message, rpcCode, data = {}) {
606
- return new LocalAcpViewError(code, message, rpcCode, data);
607
- }
608
- /** The stable rejection when an attached View/Agent/Session identity changed mid-request. */
609
- function staleModelSelection() {
610
- return new LocalAcpViewError("LOCAL_ACP_MODEL_STALE", "the attached session changed during the model request", -32042);
611
- }
612
- /** A stable code from a rejecting Host call, never its message or stack. */
613
- function hostErrorCode(error) {
614
- if (typeof error === "object" && error !== null && "code" in error) {
615
- const code = error.code;
616
- if (typeof code === "string" && code.length > 0) return code;
617
- }
618
- }
619
- /** The committed turn reason facts the View reads (`TurnEndReason` is wider). */
620
- function turnEndReasonKind(data) {
621
- const reason = data?.reason;
622
- return typeof reason?.kind === "string" ? reason.kind : void 0;
623
- }
624
- /**
625
- * Whether one committed `turn/end` proves a USER cancellation: the official
626
- * `aborted` reason whose nested cause is exactly `{kind:'user'}`. Any other
627
- * abort cause (parent/hook/disposed/legacy) is NOT this user's cancellation.
628
- */
629
- function turnEndUserAborted(data) {
630
- const reason = data?.reason;
631
- return reason?.kind === "aborted" && reason.reason?.kind === "user";
632
- }
633
- /**
634
- * The pure View/claim lifecycle. The registry's lifetime is owned by its
635
- * OWNER: the ACP controller holds ONE registry across listener rebinds so a
636
- * retired-turn approval fence and the one-View-per-Session rule survive an
637
- * Off -> On cycle, and that same registry carries the ONE Host fact/approval
638
- * subscription; a raw-socket listener without a controller creates a
639
- * bind-local registry and owns both its claims and its subscription.
640
- */
641
- var AcpSessionViewRegistry = class {
642
- claims = /* @__PURE__ */ new Map();
643
- /** Waiters for "every claim's Host work settled" (listener retirement). */
644
- workWaiters = /* @__PURE__ */ new Set();
645
- /** The ONE Host fact/approval subscription of this registry (R701-03). */
646
- factsDisposer;
647
- diag;
648
- /**
649
- * The Host access the fact callbacks may act through. It is bound exactly
650
- * once when the listener installs its fact subscription (the same lifetime
651
- * that owns these callbacks) and is never a second authority.
652
- */
653
- access;
654
- constructor(diag) {
655
- this.diag = diag;
656
- }
657
- /**
658
- * Install the ONE Host fact/approval subscription for this registry, if it
659
- * is not installed yet. The subscription belongs to the REGISTRY's owner
660
- * (a bind-local registry is owned by its listener; the controller-owned
661
- * registry outlives listener rebinds), never to an individual bind — an
662
- * Off -> On overlap must not register the same registry twice (R701-03).
663
- */
664
- observeFacts(access) {
665
- this.bindAccess(access);
666
- if (this.factsDisposer !== void 0) return;
667
- this.factsDisposer = access.observePromptFacts(this);
668
- }
669
- /** Whether the ONE Host fact subscription is currently installed. */
670
- hasFactsObserver() {
671
- return this.factsDisposer !== void 0;
672
- }
673
- /** Dispose the ONE Host fact subscription (idempotent). */
674
- disposeFacts() {
675
- const dispose = this.factsDisposer;
676
- this.factsDisposer = void 0;
677
- dispose?.();
678
- }
679
- /** Bind the ONE Host access the prompt-fact lifecycle may act through. */
680
- bindAccess(access) {
681
- this.access = access;
682
- }
683
- /** Create a fresh connection-scoped view state. */
684
- createConnection() {
685
- return {
686
- phase: "idle",
687
- op: 0
688
- };
689
- }
690
- /** The number of live reservations/attachments (qualification diagnosis only). */
691
- claimCount() {
692
- return this.claims.size;
693
- }
694
- /**
695
- * Whether ANY claim still owns unsettled Host work that the prompt-fact
696
- * subscription must keep observing: an open flight (pending admission,
697
- * queued message, running turn or its drain) or a detached retired-turn
698
- * approval fence. When this is false, retiring the Host fact subscription
699
- * can no longer strand any accepted ACP work (R701-01).
700
- */
701
- hasUnsettledHostWork() {
702
- for (const claim of this.claims.values()) {
703
- if (claim.inflight !== void 0 && !claim.inflight.settledDone) return true;
704
- if (claim.retiringTurn !== void 0) return true;
705
- if (claim.unclaimedHostObligation !== void 0) return true;
706
- }
707
- return false;
708
- }
709
- /**
710
- * Resolve when every claim's Host work has settled: flights completed or
711
- * failed, detached fences ended at their own death facts. Event-driven: the
712
- * settlement transitions notify the waiters, no polling.
713
- */
714
- whenHostWorkSettled() {
715
- if (!this.hasUnsettledHostWork()) return Promise.resolve();
716
- const waiter = Promise.withResolvers();
717
- this.workWaiters.add(waiter);
718
- return waiter.promise;
719
- }
720
- /** Notify (and drop) every work waiter after a settlement transition. */
721
- notifyWorkSettled() {
722
- if (this.hasUnsettledHostWork()) return;
723
- const waiters = [...this.workWaiters];
724
- this.workWaiters.clear();
725
- for (const waiter of waiters) waiter.resolve();
726
- }
727
- /** Whether a Session is currently reserved or attached by ANY connection. */
728
- hasClaim(sessionId) {
729
- return this.claims.has(sessionId);
730
- }
731
- /** The current phase of one connection (qualification diagnosis only). */
732
- phaseOf(state) {
733
- return state.phase;
734
- }
735
- /**
736
- * The ONE attached claim this connection owns for a Session. An idle,
737
- * closed, re-bound or foreign View holds no model capability.
738
- */
739
- attachedClaim(state, sessionId) {
740
- const claim = this.claims.get(sessionId);
741
- 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);
742
- return claim;
743
- }
744
- /** Whether this exact claim is still the live attached View of this connection. */
745
- isStillAttached(state, claim, agent, session) {
746
- return this.claims.get(claim.sessionId) === claim && claim.connectionIdentity === state && state.phase === "attached" && !claim.detachedWithFence && claim.exactAgent === agent && claim.exactSession === session;
747
- }
748
- /** Map one typed Host model rejection onto the existing View error boundary. */
749
- async callModelAccess(operation) {
750
- try {
751
- return await operation();
752
- } catch (error) {
753
- if (error instanceof AcpModelError) throw new LocalAcpViewError(error.code, error.message, error.rpcCode, error.data);
754
- throw error;
755
- }
756
- }
757
- /**
758
- * Read the complete standard config-option state of the EXACT attached View.
759
- * The async Host read is fenced against a close/re-bind/rebind before its
760
- * result is returned to the connection.
761
- */
762
- async modelOptions(state, access, sessionId) {
763
- const claim = this.attachedClaim(state, sessionId);
764
- const agent = claim.exactAgent;
765
- const session = claim.exactSession;
766
- try {
767
- const options = await this.callModelAccess(() => access.modelOptions(agent, session));
768
- if (!this.isStillAttached(state, claim, agent, session)) throw staleModelSelection();
769
- return options;
770
- } catch (error) {
771
- if (!this.isStillAttached(state, claim, agent, session)) throw staleModelSelection();
772
- throw error;
773
- }
774
- }
775
- /**
776
- * Commit ONE Session-only model/effort selection on the EXACT attached View.
777
- * A View with any unsettled prompt obligation is refused before the Host
778
- * service is reached; the Host service re-checks the exact Agent/Session
779
- * identity and the View claim after every asynchronous validation step.
780
- */
781
- async setModelOption(state, access, request, signal) {
782
- const claim = this.attachedClaim(state, request.sessionId);
783
- if (claim.inflight !== void 0 || claim.unclaimedHostObligation !== void 0) throw new LocalAcpViewError("LOCAL_ACP_MODEL_VIEW_BUSY", "a prompt is already in flight for this session view", -32046);
784
- const agent = claim.exactAgent;
785
- const session = claim.exactSession;
786
- const stillCurrent = () => {
787
- if (!this.isStillAttached(state, claim, agent, session)) return "stale";
788
- if (claim.inflight !== void 0 || claim.unclaimedHostObligation !== void 0) return "view-busy";
789
- return "current";
790
- };
791
- const options = await this.callModelAccess(() => access.selectModelOnly(agent, session, {
792
- configId: request.configId,
793
- ...request.type === void 0 ? {} : { type: request.type },
794
- value: request.value
795
- }, signal, stillCurrent));
796
- const currentness = stillCurrent();
797
- if (currentness === "view-busy") throw new LocalAcpViewError("LOCAL_ACP_MODEL_VIEW_BUSY", "a prompt is already in flight for this session view", -32046);
798
- if (currentness !== "current") throw staleModelSelection();
799
- return options;
800
- }
801
- /**
802
- * Attach a freshly created Host Session to this connection's View. `session/new`
803
- * creates ONE Host Workspace, then ONE Host Session, then borrows the official
804
- * live Agent. The failure category is decided by the HOST result: a definite
805
- * directory rejection, a peer-visible attachment failure that PRESERVES the
806
- * real created Session id, an unconfirmed outcome, or success. It is never
807
- * retried and never rolled back.
808
- */
809
- async newSession(state, access, request, notifyConfigOptions) {
810
- const op = this.beginAttach(state);
811
- try {
812
- this.validateNew(request);
813
- } catch (error) {
814
- this.resetIdleIfCurrent(state, op);
815
- throw error;
816
- }
817
- const workspace = await access.createWorkspace(request.cwd);
818
- if (workspace.kind === "indeterminate") {
819
- this.resetIdleIfCurrent(state, op);
820
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_WORKSPACE_UNAVAILABLE", "the Host could not register the workspace; the outcome is unconfirmed", JSONRPC_INTERNAL_ERROR);
821
- }
822
- if (!this.isCurrentOp(state, op)) throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection closed before the session was created", JSONRPC_INVALID_PARAMS);
823
- const created = await access.createSession(workspace.workspaceId);
824
- if (created.kind === "rejected") {
825
- this.resetIdleIfCurrent(state, op);
826
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_INVALID_REQUEST", "the Host rejected the session create request", JSONRPC_INVALID_PARAMS);
827
- }
828
- if (created.kind === "published-with-error") {
829
- this.resetIdleIfCurrent(state, op);
830
- 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 });
831
- }
832
- if (created.kind === "indeterminate") {
833
- this.resetIdleIfCurrent(state, op);
834
- 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);
835
- }
836
- const sessionId = created.sessionId;
837
- 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 });
838
- if (this.claims.has(sessionId)) {
839
- this.resetIdleIfCurrent(state, op);
840
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_ALREADY_ATTACHED", "the new session is already attached to an ACP view", JSONRPC_INVALID_PARAMS);
841
- }
842
- const claim = {
843
- connectionIdentity: state,
844
- sessionId
845
- };
846
- this.claims.set(sessionId, claim);
847
- const agent = await this.resolveForView(access, state, op, claim);
848
- this.commitAttached(state, op, claim, access, agent, notifyConfigOptions);
849
- return { sessionId };
850
- }
851
- /**
852
- * Attach an EXISTING Session to this connection's View. The official
853
- * `resolveAgent` is the only cold-resume owner; a live Session borrows the
854
- * same Agent object. The request cwd never changes the Host Session.
855
- */
856
- async resumeSession(state, access, request, notifyConfigOptions) {
857
- const op = this.beginAttach(state);
858
- try {
859
- this.validateResume(request);
860
- } catch (error) {
861
- this.resetIdleIfCurrent(state, op);
862
- throw error;
863
- }
864
- const sessionId = request.sessionId;
865
- if (this.claims.has(sessionId)) {
866
- this.resetIdleIfCurrent(state, op);
867
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_ALREADY_ATTACHED", "the session is already attached to an ACP view", JSONRPC_INVALID_PARAMS);
868
- }
869
- const claim = {
870
- connectionIdentity: state,
871
- sessionId
872
- };
873
- this.claims.set(sessionId, claim);
874
- const agent = await this.resolveForView(access, state, op, claim);
875
- if (agent.session.header.cwd !== request.cwd) this.diag.warn("local-acp.view.cwd-mismatch", { mismatch: true });
876
- this.commitAttached(state, op, claim, access, agent, notifyConfigOptions);
877
- return {};
878
- }
879
- /**
880
- * Detach ONLY this connection's View for one Session. PO-3B: when a prompt
881
- * flight is still open, the close FIRST drives the same scoped cancellation
882
- * and waits for its real settlement (durable queued removal or the exact
883
- * running turn's terminal plus the output drain); only a proven settlement
884
- * detaches the View. A repeated close awaits the SAME settlement; a close of
885
- * a Session this connection never held is still refused. The Host Agent and
886
- * Session always stay alive; no other connection's claim is touched.
887
- */
888
- async closeSession(state, access, sessionId) {
889
- const claim = this.claims.get(sessionId);
890
- if (claim === void 0 || claim.connectionIdentity !== state) {
891
- if (state.lastClosedSessionId === sessionId) return {};
892
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_NOT_OWNED", "this ACP connection holds no view for that session", JSONRPC_INVALID_PARAMS);
893
- }
894
- if (claim.detachedWithFence) return {};
895
- const inFlightAttempt = claim.closing;
896
- if (inFlightAttempt !== void 0) return await inFlightAttempt;
897
- const attempt = this.closeClaim(state, sessionId, claim, access);
898
- claim.closing = attempt;
899
- try {
900
- return await attempt;
901
- } finally {
902
- if (claim.closing === attempt) claim.closing = void 0;
903
- }
904
- }
905
- /**
906
- * One close attempt against the CURRENT official Host facts (v1.1 §4): a
907
- * safe detach needs a real terminal proof — an exact queued removal, the
908
- * owned turn's `turn/end` (or its exact Agent's disposal), or a definite
909
- * pre-insertion admission rejection. A local flight having disappeared is
910
- * never such a proof.
911
- */
912
- async closeClaim(state, sessionId, claim, access) {
913
- const obligation = claim.unclaimedHostObligation;
914
- if (obligation !== void 0) {
915
- if (obligation.messageId !== void 0 && claim.exactAgent !== void 0 && claim.exactSession !== void 0) {
916
- if (access.cancelPending(sessionId, claim.exactAgent, claim.exactSession, obligation.messageId) === "removed") this.dropUnclaimedObligation(claim);
917
- }
918
- 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);
919
- }
920
- const flight = claim.inflight;
921
- if (flight !== void 0) {
922
- const outcome = await this.cancelOwnedFlight(claim, flight, access, "closing").then(() => "ok", (error) => error);
923
- if (outcome !== "ok") {
924
- if (!(flight.ownTurnEnded || flight.failureCode === "LOCAL_ACP_PROMPT_HOST_REJECTED")) throw outcome;
925
- }
926
- }
927
- 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);
928
- return this.finishClose(state, sessionId, claim);
929
- }
930
- /** End one unclaimed obligation on a real terminal fact. A discarded notice
931
- * only schedules a checkpoint; official pending absence is verified later.
932
- */
933
- dropUnclaimedObligation(claim) {
934
- claim.unclaimedHostObligation = void 0;
935
- this.releaseDetachedIfSettled(claim);
936
- this.notifyWorkSettled();
937
- }
938
- /**
939
- * The official admission of a flight that already settled while its
940
- * obligation was still `pending`: a definite pre-insertion rejection proves
941
- * nothing was admitted (terminal), while an accepted admission keeps the
942
- * obligation for the exact late-insertion/terminal fact (v1.1 §5.A.4).
943
- */
944
- settleUnclaimedAdmission(claim, flight) {
945
- const obligation = claim.unclaimedHostObligation;
946
- if (obligation === void 0 || obligation.requestId !== flight.requestId) return;
947
- if (obligation.admission !== "pending") return;
948
- if (flight.failureCode === "LOCAL_ACP_PROMPT_HOST_REJECTED") {
949
- this.dropUnclaimedObligation(claim);
950
- return;
951
- }
952
- obligation.admission = "accepted";
953
- this.notifyWorkSettled();
954
- }
955
- retainRetiringTurn(claim, turn) {
956
- const existing = claim.retiringTurn;
957
- if (existing !== void 0 && existing.turn !== turn.turn) {
958
- const current = claim.exactAgent !== void 0 && claim.exactSession !== void 0 ? this.access?.currentTurn(claim.sessionId, claim.exactAgent, claim.exactSession) : void 0;
959
- if (current?.kind === "current" && current.openTurn === existing.turn) return;
960
- }
961
- claim.retiringTurn = turn;
962
- }
963
- /** Release a detached claim once no Host obligation or fence remains. */
964
- releaseDetachedIfSettled(claim) {
965
- if (!claim.detachedWithFence) return;
966
- if (claim.inflight !== void 0) return;
967
- if (claim.retiringTurn !== void 0) return;
968
- if (claim.unclaimedHostObligation !== void 0) return;
969
- if (this.claims.get(claim.sessionId) === claim) this.claims.delete(claim.sessionId);
970
- }
971
- /** Release one settled claim and record the idempotent close fact. */
972
- finishClose(state, sessionId, claim) {
973
- if (this.claims.get(sessionId) !== claim || claim.detachedWithFence || state.phase === "closed") return {};
974
- claim.notifyConfigOptions = void 0;
975
- if (claim.retiringTurn !== void 0) claim.detachedWithFence = true;
976
- else if (this.claims.get(sessionId) === claim) {
977
- this.claims.delete(sessionId);
978
- this.notifyWorkSettled();
979
- }
980
- state.phase = "idle";
981
- state.lastClosedSessionId = sessionId;
982
- return {};
983
- }
984
- /**
985
- * PO-3B scoped `session/cancel`: ONLY this connection's own unsettled flight
986
- * is addressed — a queued message by its exact durable inbox removal, a
987
- * running turn by the official same-stack user cancel of that exact current
988
- * turn. An idle View (and any Session this connection does not own) is a
989
- * no-op that never touches a Host Agent; a mixed owned turn is NOT cancelled
990
- * (the TUI steer inside it keeps its authority) and keeps the D23 failure.
991
- */
992
- cancelSession(state, access, sessionId) {
993
- const claim = this.claims.get(sessionId);
994
- if (claim === void 0 || claim.connectionIdentity !== state || claim.detachedWithFence) return;
995
- const flight = claim.inflight;
996
- if (flight === void 0 || flight.settledDone) return;
997
- flight.cancelRequested = true;
998
- this.addressCancelIntent(claim, flight, access);
999
- }
1000
- /**
1001
- * Drive ONE scoped cancellation to its real settlement. The returned promise
1002
- * resolves only when the cancellation is PROVEN (durable removal committed
1003
- * and the admission classified, or the exact turn's real `turn/end` plus the
1004
- * output drain); it rejects with `LOCAL_ACP_PROMPT_CANCEL_UNCONFIRMED` when
1005
- * no legal proof can be obtained. The ACP request's own settlement (a real
1006
- * `cancelled` stop reason or its true failure) happens through the SAME
1007
- * flight settlement path this method feeds, never beside it.
1008
- */
1009
- async cancelOwnedFlight(claim, flight, access, reason) {
1010
- if (reason === "disconnect" || reason === "closing") {
1011
- flight.deliveryClosed = true;
1012
- this.stopFlightOutput(flight);
1013
- }
1014
- flight.cancelRequested = true;
1015
- this.addressCancelIntent(claim, flight, access);
1016
- 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)) {
1017
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_ABORTED", "the ACP prompt request was aborted before a real Host settlement", JSONRPC_INTERNAL_ERROR));
1018
- return;
1019
- }
1020
- const outcome = await flight.settled.promise.then(() => "settled", (error) => error);
1021
- if (reason === "disconnect") return;
1022
- if (outcome === "settled") return;
1023
- if (flight.ownTurnEnded) return;
1024
- throw outcome;
1025
- }
1026
- /**
1027
- * Address the cancellation intent against the CURRENT Host facts. This is
1028
- * the single decision point for every entry (notification, close, insert
1029
- * callback, claim callback): a queued message is removed exactly; a running
1030
- * owned turn is user-cancelled in the same stack only when the official
1031
- * current-turn fence still matches; a mixed turn is never cancelled; an
1032
- * admission still in flight keeps its intent for the insertion callback.
1033
- */
1034
- addressCancelIntent(claim, flight, access) {
1035
- if (flight.settledDone || flight.cancelKind !== void 0) return;
1036
- const session = claim.exactSession;
1037
- const agent = claim.exactAgent;
1038
- const sessionId = claim.sessionId;
1039
- if (session === void 0 || agent === void 0) return;
1040
- if (flight.turn === void 0) {
1041
- if (flight.messageId === void 0) return;
1042
- if (flight.mixed) return;
1043
- const removed = access.cancelPending(sessionId, agent, session, flight.messageId);
1044
- if (removed === "removed") {
1045
- flight.cancelKind = "queued-removed";
1046
- this.stopFlightOutput(flight);
1047
- this.settleQueuedRemoval(claim, flight);
1048
- return;
1049
- }
1050
- if (removed === "stale") {
1051
- 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));
1052
- return;
1053
- }
1054
- return;
1055
- }
1056
- if (flight.mixed) return;
1057
- const addressed = access.cancelCurrentTurn(sessionId, agent, session, flight.turn);
1058
- if (addressed === "addressed") {
1059
- flight.cancelKind = "running-addressed";
1060
- this.stopFlightOutput(flight);
1061
- return;
1062
- }
1063
- if (addressed === "stale") {
1064
- 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));
1065
- return;
1066
- }
1067
- }
1068
- /**
1069
- * Complete a proven queued removal: the durable splice committed. The
1070
- * completion waits for the admission path's classification (accepted or a
1071
- * definite rejection) through the flight's `admissionSettled` promise so the
1072
- * client never learns "cancelled" for a prompt the Host actually rejected.
1073
- */
1074
- settleQueuedRemoval(claim, flight) {
1075
- runDetached("local acp: queued-cancel settlement", async () => {
1076
- await flight.admissionSettledPromise;
1077
- await flight.outputTail;
1078
- if (flight.settledDone) return;
1079
- this.completePrompt(claim, flight, { stopReason: "cancelled" });
1080
- }, { diag: this.diag });
1081
- }
1082
- /**
1083
- * Admit one ACP text/resource_link/image prompt on this connection's attached View and
1084
- * settle it on the exact Host facts. The slot and the View-minted `requestId` are committed
1085
- * BEFORE the official prompt call, so a synchronous inbox notice or a second
1086
- * pipelined request can never be attributed to a later flight.
1087
- *
1088
- * The returned promise settles only from real Host facts: the claimed turn of
1089
- * THIS message id, that turn's committed events, its `turn/end`, and the
1090
- * ordered notification drain. No status, text, timestamp or ACK is treated as
1091
- * a completed turn.
1092
- */
1093
- async promptSession(state, access, request, requestSignal, imageEnabled, sendUpdate, requestPermission) {
1094
- 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);
1095
- const claim = this.claims.get(request.sessionId);
1096
- 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);
1097
- 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);
1098
- const content = validatePromptContent(request.prompt, imageEnabled);
1099
- if (requestSignal.aborted) throw promptError("LOCAL_ACP_PROMPT_ABORTED", "the ACP prompt request was aborted before admission", JSONRPC_INVALID_PARAMS);
1100
- 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);
1101
- const currentAtFlightStart = access.currentTurn(request.sessionId, claim.exactAgent, claim.exactSession);
1102
- if (currentAtFlightStart.kind === "stale") throw promptError("LOCAL_ACP_PROMPT_STALE_AGENT", "the borrowed turn identity changed before admission", JSONRPC_INVALID_PARAMS);
1103
- const admission = Promise.withResolvers();
1104
- const outputAbort = new AbortController();
1105
- const flight = {
1106
- requestId: randomUUID(),
1107
- phase: "admitting",
1108
- ...currentAtFlightStart.openTurn === null ? {} : { turnProvenance: {
1109
- turn: currentAtFlightStart.openTurn,
1110
- origin: claim.retiringTurn?.turn === currentAtFlightStart.openTurn ? claim.retiringTurn.origin : "tui"
1111
- } },
1112
- mixed: false,
1113
- assistantVisibleOutput: false,
1114
- pendingUpdates: 0,
1115
- outputTail: Promise.resolve(),
1116
- sendUpdate,
1117
- requestPermission,
1118
- settled: Promise.withResolvers(),
1119
- settledDone: false,
1120
- cancelRequested: false,
1121
- admissionSettled: false,
1122
- admissionSettledPromise: admission.promise,
1123
- settleAdmission: () => {
1124
- if (flight.admissionSettled) return;
1125
- flight.admissionSettled = true;
1126
- admission.resolve();
1127
- },
1128
- deliveryClosed: false,
1129
- outputAbort,
1130
- outputSignal: outputAbort.signal,
1131
- outputStopped: false,
1132
- outputTasksQueued: 0,
1133
- ownTurnEnded: false,
1134
- permissionRequests: /* @__PURE__ */ new Map()
1135
- };
1136
- observeSettled(flight.settled.promise, () => {});
1137
- const onAbort = () => {
1138
- flight.deliveryClosed = true;
1139
- this.stopFlightOutput(flight);
1140
- this.abortPermissionRequests(flight);
1141
- if (!flight.settledDone && !flight.cancelRequested) {
1142
- flight.cancelRequested = true;
1143
- if (this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
1144
- }
1145
- };
1146
- requestSignal.addEventListener("abort", onAbort, { once: true });
1147
- flight.detachAbort = () => requestSignal.removeEventListener("abort", onAbort);
1148
- claim.inflight = flight;
1149
- try {
1150
- await access.prompt({
1151
- requestId: flight.requestId,
1152
- sessionId: request.sessionId,
1153
- mode: "queue",
1154
- content
1155
- }, requestSignal);
1156
- if (!flight.settledDone) {
1157
- const stillExact = Object.is(access.currentAgent(request.sessionId), claim.exactAgent) && Object.is(access.currentSession(request.sessionId), claim.exactSession);
1158
- 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));
1159
- 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));
1160
- else flight.phase = "queued";
1161
- }
1162
- } catch (error) {
1163
- if (!flight.settledDone) {
1164
- 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));
1165
- else {
1166
- const hostCode = hostErrorCode(error);
1167
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_HOST_REJECTED", "the Host did not accept the prompt", JSONRPC_INTERNAL_ERROR, hostCode === void 0 ? {} : { hostCode }));
1168
- }
1169
- }
1170
- } finally {
1171
- flight.settleAdmission();
1172
- this.settleUnclaimedAdmission(claim, flight);
1173
- }
1174
- return await flight.settled.promise;
1175
- }
1176
- /** The source of a turn already open when this exact ACP message is inserted. */
1177
- turnProvenanceAtOwnInsertion(claim, agent) {
1178
- const session = claim.exactSession;
1179
- const access = this.access;
1180
- if (session === void 0 || access === void 0) return void 0;
1181
- const checkpoint = access.currentTurn(claim.sessionId, agent, session);
1182
- if (checkpoint.kind === "stale") return {
1183
- turn: null,
1184
- origin: "unknown"
1185
- };
1186
- if (checkpoint.openTurn === null) return void 0;
1187
- return {
1188
- turn: checkpoint.openTurn,
1189
- origin: claim.retiringTurn?.turn === checkpoint.openTurn ? claim.retiringTurn.origin : "tui"
1190
- };
1191
- }
1192
- /** One message entered or re-entered the live inbox: correlate the View-minted request id. */
1193
- onInboxInserted(agent, message) {
1194
- const rpcId = message.source?.kind === "user" ? message.source.rpcId : void 0;
1195
- for (const claim of this.claims.values()) {
1196
- const obligation = claim.unclaimedHostObligation;
1197
- if (obligation !== void 0 && claim.exactAgent === agent && (obligation.messageId === message.id || obligation.messageId === void 0 && rpcId !== void 0 && rpcId === obligation.requestId)) {
1198
- const firstInsertion = obligation.messageId === void 0;
1199
- obligation.messageId = message.id;
1200
- obligation.turnProvenance = this.turnProvenanceAtOwnInsertion(claim, agent);
1201
- if (firstInsertion && claim.exactSession !== void 0 && this.access !== void 0) {
1202
- if (this.access.cancelPending(claim.sessionId, agent, claim.exactSession, message.id) === "removed") this.dropUnclaimedObligation(claim);
1203
- }
1204
- }
1205
- const flight = claim.inflight;
1206
- if (flight === void 0 || flight.settledDone) continue;
1207
- if (claim.exactAgent !== agent) {
1208
- 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));
1209
- continue;
1210
- }
1211
- if (flight.messageId !== message.id && (flight.messageId !== void 0 || rpcId === void 0 || rpcId !== flight.requestId)) continue;
1212
- flight.messageId = message.id;
1213
- flight.turnProvenance = this.turnProvenanceAtOwnInsertion(claim, agent);
1214
- if (flight.cancelRequested && this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
1215
- }
1216
- }
1217
- /**
1218
- * One message was claimed. The exact message id (never text or timing) links
1219
- * the prompt to its turn; any other user message claimed into that same turn
1220
- * proves the turn is MIXED.
1221
- */
1222
- onInboxClaimed(agent, message, turn) {
1223
- for (const claim of this.claims.values()) {
1224
- if (claim.exactAgent !== agent) continue;
1225
- const obligation = claim.unclaimedHostObligation;
1226
- if (obligation !== void 0 && obligation.messageId === message.id) {
1227
- claim.unclaimedHostObligation = void 0;
1228
- this.retainRetiringTurn(claim, {
1229
- turn,
1230
- origin: obligation.turnProvenance?.turn === turn ? obligation.turnProvenance.origin : "acp"
1231
- });
1232
- this.notifyWorkSettled();
1233
- }
1234
- const flight = claim.inflight;
1235
- if (flight === void 0 || flight.settledDone) continue;
1236
- if (flight.messageId !== void 0 && message.id === flight.messageId) {
1237
- if (flight.turn === void 0) {
1238
- flight.turn = turn;
1239
- if (flight.phase === "admitting" || flight.phase === "queued") flight.phase = "claimed";
1240
- if (flight.turnProvenance?.turn === turn || flight.foreignTurn === turn) this.markFlightMixed(flight);
1241
- flight.foreignTurn = void 0;
1242
- if (flight.cancelRequested && this.access !== void 0) this.addressCancelIntent(claim, flight, this.access);
1243
- }
1244
- continue;
1245
- }
1246
- if (flight.turn !== void 0) {
1247
- if (flight.turn === turn) this.markFlightMixed(flight);
1248
- continue;
1249
- }
1250
- flight.foreignTurn = turn;
1251
- }
1252
- }
1253
- /**
1254
- * One committed Session event. Only the exact Session object and the owned
1255
- * turn are projected; every other event is inert for this View.
1256
- */
1257
- onSessionEvent(session, event) {
1258
- for (const claim of this.claims.values()) {
1259
- if (claim.exactSession !== session) continue;
1260
- if (event.type === "model/selection" && claim.notifyConfigOptions !== void 0) this.enqueueConfigNotification(claim, session);
1261
- const data = event.data;
1262
- if (event.type === "turn/end" && typeof data?.turn === "number" && claim.retiringTurn?.turn === data.turn) this.endRetiringFence(claim.sessionId, claim);
1263
- const flight = claim.inflight;
1264
- if (flight === void 0 || flight.settledDone) continue;
1265
- if (typeof data?.turn !== "number" || flight.turn === void 0 || data.turn !== flight.turn) continue;
1266
- if (event.type === "turn/end") flight.ownTurnEnded = true;
1267
- if (flight.mixed) {
1268
- if (event.type === "turn/end") this.settleTurnEnd(claim, flight, data);
1269
- continue;
1270
- }
1271
- switch (event.type) {
1272
- case "assistant/message":
1273
- this.projectAssistantMessage(claim, flight, data);
1274
- break;
1275
- case "tool/call":
1276
- this.projectToolCall(claim, flight, data);
1277
- break;
1278
- case "tool/result":
1279
- this.projectToolResult(claim, flight, data);
1280
- break;
1281
- case "turn/end": this.settleTurnEnd(claim, flight, data);
1282
- }
1283
- }
1284
- }
1285
- /**
1286
- * Queue ONE full-option refresh on the claim's ordered notification chain.
1287
- * The chain is transient and per claim: a close/re-bind/teardown clears the
1288
- * callback, a late catalog read never reaches a newer View, and a delivery
1289
- * failure retires only this callback instead of becoming a Host failure.
1290
- */
1291
- enqueueConfigNotification(claim, session) {
1292
- const notify = claim.notifyConfigOptions;
1293
- const agent = claim.exactAgent;
1294
- if (notify === void 0 || agent === void 0) return;
1295
- claim.configNotifyTail = (claim.configNotifyTail ?? Promise.resolve()).then(async () => {
1296
- if (claim.notifyConfigOptions !== notify) return;
1297
- if (this.claims.get(claim.sessionId) !== claim || claim.exactSession !== session || claim.exactAgent !== agent) return;
1298
- if (claim.connectionIdentity.phase !== "attached" || claim.detachedWithFence) return;
1299
- const access = this.access;
1300
- if (access === void 0) return;
1301
- let options;
1302
- try {
1303
- options = await access.modelOptions(agent, session);
1304
- } catch {
1305
- return;
1306
- }
1307
- if (claim.notifyConfigOptions !== notify) return;
1308
- if (this.claims.get(claim.sessionId) !== claim || claim.exactSession !== session || claim.exactAgent !== agent) return;
1309
- if (claim.connectionIdentity.phase !== "attached" || claim.detachedWithFence) return;
1310
- try {
1311
- await notify(claim.sessionId, options);
1312
- } catch {
1313
- claim.notifyConfigOptions = void 0;
1314
- }
1315
- }).catch(() => {});
1316
- }
1317
- /**
1318
- * A discard only triggers verification: edit/steer can reinsert the same id
1319
- * within the current synchronous Host mutation. Cross it once, then read the
1320
- * official pending projection and the CURRENT responsibility of this claim.
1321
- */
1322
- onInboxDiscarded(agent, message) {
1323
- const messageId = message.id;
1324
- for (const claim of this.claims.values()) {
1325
- if (claim.exactAgent !== agent || claim.exactSession === void 0) continue;
1326
- if (claim.inflight?.messageId !== messageId && claim.unclaimedHostObligation?.messageId !== messageId) continue;
1327
- const session = claim.exactSession;
1328
- const sessionId = claim.sessionId;
1329
- runDetached("local acp: inbox discard checkpoint", async () => {
1330
- await Promise.resolve();
1331
- if (this.claims.get(sessionId) !== claim || claim.exactAgent !== agent || claim.exactSession !== session) return;
1332
- const flight = claim.inflight;
1333
- const obligation = claim.unclaimedHostObligation;
1334
- if (flight?.messageId !== messageId && obligation?.messageId !== messageId) return;
1335
- if (this.access?.pendingMessage(sessionId, agent, session, messageId) !== "absent") return;
1336
- if (flight?.messageId === messageId) {
1337
- if (flight.settledDone || flight.turn !== void 0 || flight.cancelKind !== void 0) return;
1338
- flight.cancelKind = "queued-removed";
1339
- this.settleQueuedRemoval(claim, flight);
1340
- } else if (obligation?.messageId === messageId) this.dropUnclaimedObligation(claim);
1341
- }, { diag: this.diag });
1342
- }
1343
- }
1344
- /** One Agent interval failure: only the owned turn of the exact Agent is attributed. */
1345
- onAgentError(agent, turn) {
1346
- for (const claim of this.claims.values()) {
1347
- if (claim.exactAgent !== agent) continue;
1348
- const flight = claim.inflight;
1349
- if (flight === void 0 || flight.settledDone) continue;
1350
- 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" }));
1351
- }
1352
- }
1353
- /** The exact live Agent was disposed: its in-flight prompt can never settle. */
1354
- onAgentDisposed(agent) {
1355
- for (const claim of this.claims.values()) {
1356
- if (claim.exactAgent !== agent) continue;
1357
- const flight = claim.inflight;
1358
- if (flight !== void 0 && !flight.settledDone) {
1359
- flight.ownTurnEnded = true;
1360
- 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" }));
1361
- }
1362
- if (claim.unclaimedHostObligation !== void 0) this.dropUnclaimedObligation(claim);
1363
- this.endRetiringFence(claim.sessionId, claim);
1364
- }
1365
- }
1366
- /**
1367
- * PO-3B approval classification entry (the ONE prepended waterfall seat).
1368
- *
1369
- * The decision is made ONLY from authoritative facts: the request's exact
1370
- * Agent against every claim's exact identity, the claim's live flight turn
1371
- * or its transient retired-turn fence, and the official current-turn fence.
1372
- * A turn proven ACP-owned is answered here — standard reverse
1373
- * `session/request_permission` when the channel allows it, `'unavailable'`
1374
- * (fail closed) when it does not — and NEVER delegated through `next()`. A
1375
- * turn proven NOT owned by any ACP View is delegated exactly once.
1376
- */
1377
- async onApprovalRequest(request, next) {
1378
- const agent = request.agent;
1379
- let owner;
1380
- for (const claim of this.claims.values()) if (claim.exactAgent === agent) {
1381
- owner = claim;
1382
- break;
1383
- }
1384
- if (owner === void 0) return await next();
1385
- const session = owner.exactSession;
1386
- const fence = session === void 0 || this.access === void 0 ? void 0 : this.access.currentTurn(owner.sessionId, agent, session);
1387
- if (fence === void 0 || fence.kind === "stale") return "unavailable";
1388
- const flight = owner.inflight;
1389
- const currentTurn = fence.openTurn;
1390
- if (currentTurn === null) return flight?.turn !== void 0 || owner.retiringTurn !== void 0 ? "unavailable" : await next();
1391
- const declaredTurn = owner.retiringTurn?.turn === currentTurn ? owner.retiringTurn : flight !== void 0 && !flight.settledDone && flight.turn === currentTurn ? {
1392
- turn: currentTurn,
1393
- origin: flight.turnProvenance?.turn === currentTurn ? flight.turnProvenance.origin : "acp"
1394
- } : flight?.turnProvenance?.turn === currentTurn ? flight.turnProvenance : void 0;
1395
- if (declaredTurn === void 0) return await next();
1396
- if (declaredTurn.origin === "unknown") return "unavailable";
1397
- if (declaredTurn.origin === "tui") return await next();
1398
- if (flight === void 0 || flight.settledDone || flight.cancelRequested || flight.mixed || request.callId === void 0 || flight.turn !== currentTurn) return "unavailable";
1399
- const pending = flight.permissionRequests.get(request.callId);
1400
- if (pending !== void 0) return await pending.promise;
1401
- const channel = flight.requestPermission;
1402
- if (channel === void 0) return "unavailable";
1403
- const asked = this.askPermission(flight, owner, request, channel);
1404
- flight.permissionRequests.set(request.callId, asked);
1405
- try {
1406
- return await asked.promise;
1407
- } finally {
1408
- flight.permissionRequests.delete(request.callId);
1409
- }
1410
- }
1411
- /** Issue ONE reverse permission request on the flight's own channel. */
1412
- askPermission(flight, owner, request, channel) {
1413
- const upstreamSignal = request.signal;
1414
- const cancellation = new AbortController();
1415
- const onUpstreamAbort = () => {
1416
- cancellation.abort();
1417
- };
1418
- upstreamSignal?.addEventListener("abort", onUpstreamAbort, { once: true });
1419
- return {
1420
- promise: (async () => {
1421
- if (upstreamSignal?.aborted === true) return "cancelled";
1422
- try {
1423
- await flight.outputTail;
1424
- if (flight.settledDone || flight.deliveryClosed) return "unavailable";
1425
- const response = await channel({
1426
- sessionId: owner.sessionId,
1427
- toolCall: { toolCallId: request.callId },
1428
- options: [{
1429
- optionId: "allow-once",
1430
- name: "Allow once",
1431
- kind: "allow_once"
1432
- }, {
1433
- optionId: "reject-once",
1434
- name: "Reject",
1435
- kind: "reject_once"
1436
- }]
1437
- }, { signal: cancellation.signal });
1438
- if (flight.settledDone || flight.deliveryClosed) return "unavailable";
1439
- if ((upstreamSignal?.aborted ?? false) === true) return "cancelled";
1440
- const outcome = response?.outcome;
1441
- if (outcome?.outcome === "cancelled") return "cancelled";
1442
- if (outcome?.outcome === "selected") {
1443
- if (outcome.optionId === "allow-once") return "allowed-once";
1444
- if (outcome.optionId === "reject-once") return "rejected";
1445
- }
1446
- return "unavailable";
1447
- } catch {
1448
- return (upstreamSignal?.aborted ?? false) || cancellation.signal.aborted ? "cancelled" : "unavailable";
1449
- } finally {
1450
- upstreamSignal?.removeEventListener("abort", onUpstreamAbort);
1451
- }
1452
- })(),
1453
- abort: () => {
1454
- cancellation.abort();
1455
- }
1456
- };
1457
- }
1458
- /**
1459
- * Release every claim owned by one connection and mark it closed. Used by
1460
- * BOTH an explicit teardown completion and a physical `socket`
1461
- * end/error/destroy or Host Off; it is idempotent and never touches another
1462
- * connection's claim or any Host Agent/Session.
1463
- *
1464
- * PO-3B: a flight with a durable message fact drives the SAME scoped
1465
- * cancellation (queued removal or exact-turn user cancel). A pending
1466
- * admission retains its request identity and claim for late insertion;
1467
- * only proven Host settlement, or classified admission with no inserted
1468
- * message on the exact identity, releases the responsibility. Without any
1469
- * bound Host access, raw-socket contracts retain the PO-3A fail-closed path.
1470
- */
1471
- releaseConnection(state, access) {
1472
- state.phase = "closed";
1473
- state.op += 1;
1474
- for (const [sessionId, claim] of this.claims) {
1475
- if (claim.connectionIdentity !== state) continue;
1476
- claim.notifyConfigOptions = void 0;
1477
- const flight = claim.inflight;
1478
- if (flight !== void 0) {
1479
- const bound = access ?? this.access;
1480
- if (bound === void 0) {
1481
- this.failPrompt(claim, flight, new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection closed before the prompt settled", JSONRPC_INTERNAL_ERROR));
1482
- this.releaseClaimIfUnfenced(sessionId, claim);
1483
- continue;
1484
- }
1485
- runDetached("local acp: disconnect cancellation", async () => {
1486
- try {
1487
- await this.cancelOwnedFlight(claim, flight, bound, "disconnect");
1488
- } catch {}
1489
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
1490
- claim.detachedWithFence = true;
1491
- this.notifyWorkSettled();
1492
- return;
1493
- }
1494
- this.releaseClaimAfterDisconnect(sessionId, claim);
1495
- }, { diag: this.diag });
1496
- continue;
1497
- }
1498
- const obligation = claim.unclaimedHostObligation;
1499
- const bound = access ?? this.access;
1500
- if (obligation !== void 0 && obligation.messageId !== void 0 && claim.exactAgent !== void 0 && claim.exactSession !== void 0 && bound !== void 0) {
1501
- if (bound.cancelPending(sessionId, claim.exactAgent, claim.exactSession, obligation.messageId) === "removed") this.dropUnclaimedObligation(claim);
1502
- }
1503
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
1504
- claim.detachedWithFence = true;
1505
- continue;
1506
- }
1507
- if (this.claims.get(sessionId) === claim) this.claims.delete(sessionId);
1508
- }
1509
- this.notifyWorkSettled();
1510
- }
1511
- /**
1512
- * End one retired-turn fence: clear it and, when the View already detached
1513
- * (a close/disconnect left the claim alive ONLY for this fence), release
1514
- * the claim so the Session can be attached again (RFL-006).
1515
- */
1516
- endRetiringFence(sessionId, claim) {
1517
- claim.retiringTurn = void 0;
1518
- this.releaseDetachedIfSettled(claim);
1519
- this.notifyWorkSettled();
1520
- }
1521
- /**
1522
- * Release one claim after a fail-closed flight UNLESS it still carries a
1523
- * retired-turn fence that must survive until its own facts end it.
1524
- */
1525
- releaseClaimIfUnfenced(sessionId, claim) {
1526
- if (claim.retiringTurn !== void 0 || claim.unclaimedHostObligation !== void 0) {
1527
- claim.detachedWithFence = true;
1528
- return;
1529
- }
1530
- if (this.claims.get(sessionId) === claim) {
1531
- this.claims.delete(sessionId);
1532
- this.notifyWorkSettled();
1533
- }
1534
- }
1535
- /** Release one disconnect claim after its flight settled. */
1536
- releaseClaimAfterDisconnect(sessionId, claim) {
1537
- if (this.claims.get(sessionId) === claim) this.claims.delete(sessionId);
1538
- this.notifyWorkSettled();
1539
- }
1540
- /**
1541
- * Enforce `idle -> attaching` BEFORE any Host await; a busy/closed view
1542
- * refuses. Returns the attach-operation generation captured by the caller.
1543
- */
1544
- beginAttach(state) {
1545
- if (state.phase === "closed") throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP connection is closed", JSONRPC_INVALID_PARAMS);
1546
- if (state.phase !== "idle") throw new LocalAcpViewError("LOCAL_ACP_VIEW_BUSY", "this ACP connection already holds or is attaching a view", JSONRPC_INVALID_PARAMS);
1547
- state.op += 1;
1548
- state.phase = "attaching";
1549
- state.lastClosedSessionId = void 0;
1550
- return state.op;
1551
- }
1552
- /** Whether `op` is still this connection's live attach generation. */
1553
- isCurrentOp(state, op) {
1554
- return state.op === op && state.phase === "attaching";
1555
- }
1556
- /** Reset to idle ONLY while `op` is still this connection's attaching generation. */
1557
- resetIdleIfCurrent(state, op) {
1558
- if (state.op === op && state.phase === "attaching") state.phase = "idle";
1559
- }
1560
- /**
1561
- * Resolve one Session to its live Agent through the sole official owner,
1562
- * releasing the reservation and classifying every failure. A closed,
1563
- * superseded or already-released operation owns no claim even if its await
1564
- * resolves later, and its continuation never mutates the connection state.
1565
- */
1566
- async resolveForView(access, state, op, claim) {
1567
- let resolved;
1568
- try {
1569
- resolved = await access.resolveAgent(claim.sessionId);
1570
- } catch {
1571
- this.onResolveFailure(state, op, claim);
1572
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_HOST_ERROR", "the Host could not resolve the session", JSONRPC_INTERNAL_ERROR, { sessionId: claim.sessionId });
1573
- }
1574
- if ("error" in resolved) {
1575
- this.onResolveFailure(state, op, claim);
1576
- throw mapResolveError(resolved.error, claim.sessionId);
1577
- }
1578
- if (!this.isCurrentOp(state, op) || this.claims.get(claim.sessionId) !== claim) {
1579
- this.releaseReservation(state, claim);
1580
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP view was released before it attached", JSONRPC_INVALID_PARAMS, { sessionId: claim.sessionId });
1581
- }
1582
- return resolved.agent;
1583
- }
1584
- /** Release a failed resolution's OWN exact reservation without touching a newer op's claim. */
1585
- onResolveFailure(state, op, claim) {
1586
- this.releaseReservation(state, claim);
1587
- this.resetIdleIfCurrent(state, op);
1588
- }
1589
- /**
1590
- * Commit an attached View only when `op` is still the connection's live
1591
- * generation, the claim is still this connection's, AND the borrowed
1592
- * Agent/Session are the EXACT live Host objects. Any mismatch releases ONLY
1593
- * this exact claim instead of publishing a stale View, and never mutates a
1594
- * state now owned by a newer/closed operation.
1595
- */
1596
- commitAttached(state, op, claim, access, agent, notifyConfigOptions) {
1597
- if (state.op !== op || this.claims.get(claim.sessionId) !== claim || claim.connectionIdentity !== state) {
1598
- this.releaseReservation(state, claim);
1599
- throw new LocalAcpViewError("LOCAL_ACP_VIEW_CLOSED", "the ACP view was released before it attached", JSONRPC_INVALID_PARAMS, { sessionId: claim.sessionId });
1600
- }
1601
- if (!(Object.is(access.currentAgent(claim.sessionId), agent) && Object.is(access.currentSession(claim.sessionId), agent.session))) {
1602
- this.releaseReservation(state, claim);
1603
- this.resetIdleIfCurrent(state, op);
1604
- 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 });
1605
- }
1606
- state.phase = "attached";
1607
- claim.exactAgent = agent;
1608
- claim.exactSession = agent.session;
1609
- claim.notifyConfigOptions = notifyConfigOptions;
1610
- }
1611
- /**
1612
- * Remove ONE exact reservation. Identity is by the CLAIM OBJECT (and its
1613
- * owning connection), never by `sessionId` alone: a close-then-re-attach of
1614
- * the SAME Session produces a NEW claim for the same connection+sessionId, so
1615
- * a stale operation's late release must not delete the newer claim.
1616
- */
1617
- releaseReservation(state, claim) {
1618
- if (this.claims.get(claim.sessionId) === claim && claim.connectionIdentity === state) {
1619
- this.claims.delete(claim.sessionId);
1620
- this.notifyWorkSettled();
1621
- }
1622
- }
1623
- /**
1624
- * Validate ONE committed assistant message synchronously and reserve its
1625
- * ordered output units on this flight's single tail. Shapes are checked here
1626
- * (a malformed/unsupported event fails before anything is queued); the image
1627
- * reads and the sends happen inside the tail so no later event can overtake
1628
- * this one.
1629
- */
1630
- projectAssistantMessage(claim, flight, data) {
1631
- const message = data.message;
1632
- if (message === void 0 || typeof message.id !== "string" || !Array.isArray(message.content)) {
1633
- this.failPrompt(claim, flight, unsupportedContent());
1634
- return;
1635
- }
1636
- const entries = [];
1637
- for (const block of message.content) {
1638
- const type = block?.type;
1639
- const text = block?.text;
1640
- if (type === "reasoning") {
1641
- if (typeof text !== "string") {
1642
- this.failPrompt(claim, flight, unsupportedContent());
1643
- return;
1644
- }
1645
- if (text.length > 0) entries.push({
1646
- kind: "thought",
1647
- text
1648
- });
1649
- continue;
1650
- }
1651
- if (type === "text") {
1652
- if (typeof text !== "string") {
1653
- this.failPrompt(claim, flight, unsupportedContent());
1654
- return;
1655
- }
1656
- if (text.length === 0) continue;
1657
- entries.push({
1658
- kind: "message",
1659
- text
1660
- });
1661
- flight.assistantVisibleOutput = true;
1662
- continue;
1663
- }
1664
- if (type === "image") {
1665
- const ref = committedImageRef(block);
1666
- if (ref === void 0) {
1667
- this.failPrompt(claim, flight, unsupportedContent());
1668
- return;
1669
- }
1670
- entries.push({
1671
- kind: "message-image",
1672
- ref
1673
- });
1674
- flight.assistantVisibleOutput = true;
1675
- continue;
1676
- }
1677
- if (type === "tool-call") continue;
1678
- this.failPrompt(claim, flight, unsupportedContent());
1679
- return;
1680
- }
1681
- const messageId = message.id;
1682
- const toUpdates = async () => {
1683
- const updates = [];
1684
- for (const entry of entries) if (entry.kind === "thought") updates.push({
1685
- sessionUpdate: "agent_thought_chunk",
1686
- messageId,
1687
- content: {
1688
- type: "text",
1689
- text: entry.text
1690
- }
1691
- });
1692
- else if (entry.kind === "message") updates.push({
1693
- sessionUpdate: "agent_message_chunk",
1694
- messageId,
1695
- content: {
1696
- type: "text",
1697
- text: entry.text
1698
- }
1699
- });
1700
- else if (entry.kind === "message-image") {
1701
- const stored = await this.readOutputImage(flight, entry.ref);
1702
- updates.push({
1703
- sessionUpdate: "agent_message_chunk",
1704
- messageId,
1705
- content: {
1706
- type: "image",
1707
- data: Buffer.from(stored.data).toString("base64"),
1708
- mimeType: stored.mediaType
1709
- }
1710
- });
1711
- }
1712
- return updates;
1713
- };
1714
- if (entries.every((entry) => entry.kind !== "message-image")) {
1715
- this.enqueueOutputTask(claim, flight, entries.length, () => {
1716
- const updates = [];
1717
- for (const entry of entries) if (entry.kind === "thought") updates.push({
1718
- sessionUpdate: "agent_thought_chunk",
1719
- messageId,
1720
- content: {
1721
- type: "text",
1722
- text: entry.text
1723
- }
1724
- });
1725
- else if (entry.kind === "message") updates.push({
1726
- sessionUpdate: "agent_message_chunk",
1727
- messageId,
1728
- content: {
1729
- type: "text",
1730
- text: entry.text
1731
- }
1732
- });
1733
- return updates;
1734
- });
1735
- return;
1736
- }
1737
- this.enqueueOutputTask(claim, flight, entries.length, toUpdates);
1738
- }
1739
- /** Project one committed tool call of the owned turn as a standard start update. */
1740
- projectToolCall(claim, flight, data) {
1741
- const call = data;
1742
- if (typeof call.callId !== "string" || typeof call.name !== "string") {
1743
- this.failPrompt(claim, flight, unsupportedContent());
1744
- return;
1745
- }
1746
- const rawInput = typeof call.arguments === "string" ? parseToolArguments(call.arguments) : void 0;
1747
- const update = {
1748
- sessionUpdate: "tool_call",
1749
- toolCallId: call.callId,
1750
- title: call.name,
1751
- kind: "other",
1752
- status: "in_progress",
1753
- ...rawInput === void 0 ? {} : { rawInput }
1754
- };
1755
- this.enqueueOutputTask(claim, flight, 1, () => [update]);
1756
- }
1757
- /**
1758
- * Project ONE committed tool result as a single standard `tool_call_update`.
1759
- * Its `content` keeps the committed block order (non-empty text and verified
1760
- * images); the status comes only from the official `isError` fact and the
1761
- * `toolCallId` only from the durable message.
1762
- */
1763
- projectToolResult(claim, flight, data) {
1764
- const message = data.message;
1765
- if (message === void 0 || typeof message.toolCallId !== "string" || !Array.isArray(message.content)) {
1766
- this.failPrompt(claim, flight, unsupportedContent());
1767
- return;
1768
- }
1769
- const entries = [];
1770
- for (const block of message.content) {
1771
- const type = block?.type;
1772
- const text = block?.text;
1773
- if (type === "text") {
1774
- if (typeof text !== "string") {
1775
- this.failPrompt(claim, flight, unsupportedContent());
1776
- return;
1777
- }
1778
- if (text.length > 0) entries.push({
1779
- kind: "tool",
1780
- text
1781
- });
1782
- continue;
1783
- }
1784
- if (type === "image") {
1785
- const ref = committedImageRef(block);
1786
- if (ref === void 0) {
1787
- this.failPrompt(claim, flight, unsupportedContent());
1788
- return;
1789
- }
1790
- entries.push({
1791
- kind: "tool-image",
1792
- ref
1793
- });
1794
- continue;
1795
- }
1796
- this.failPrompt(claim, flight, unsupportedContent());
1797
- return;
1798
- }
1799
- const toolCallId = message.toolCallId;
1800
- const status = message.isError === true ? "failed" : "completed";
1801
- const toUpdate = async () => {
1802
- const content = [];
1803
- for (const entry of entries) if (entry.kind === "tool") content.push({
1804
- type: "content",
1805
- content: {
1806
- type: "text",
1807
- text: entry.text
1808
- }
1809
- });
1810
- else if (entry.kind === "tool-image") {
1811
- const stored = await this.readOutputImage(flight, entry.ref);
1812
- content.push({
1813
- type: "content",
1814
- content: {
1815
- type: "image",
1816
- data: Buffer.from(stored.data).toString("base64"),
1817
- mimeType: stored.mediaType
1818
- }
1819
- });
1820
- }
1821
- return [{
1822
- sessionUpdate: "tool_call_update",
1823
- toolCallId,
1824
- status,
1825
- content
1826
- }];
1827
- };
1828
- if (entries.every((entry) => entry.kind !== "tool-image")) {
1829
- this.enqueueOutputTask(claim, flight, 1, () => {
1830
- const content = [];
1831
- for (const entry of entries) if (entry.kind === "tool") content.push({
1832
- type: "content",
1833
- content: {
1834
- type: "text",
1835
- text: entry.text
1836
- }
1837
- });
1838
- return [{
1839
- sessionUpdate: "tool_call_update",
1840
- toolCallId,
1841
- status,
1842
- content
1843
- }];
1844
- });
1845
- return;
1846
- }
1847
- this.enqueueOutputTask(claim, flight, 1, toUpdate);
1848
- }
1849
- /**
1850
- * Read ONE committed image through the official Host Attachment Store. The
1851
- * Store owns the ID/format/byte/dimension verification; the View only encodes
1852
- * the verified bytes. Every Store rejection keeps ONE stable content class —
1853
- * never a partial event, a fabricated image or a leaked path/exception.
1854
- */
1855
- async readOutputImage(flight, ref) {
1856
- const access = this.access;
1857
- if (access === void 0) throw attachmentReadFailed();
1858
- try {
1859
- return await access.readOutputImage(ref, flight.outputSignal);
1860
- } catch {
1861
- throw attachmentReadFailed();
1862
- }
1863
- }
1864
- /**
1865
- * Append ONE committed event's conversion to this flight's single ordered
1866
- * output tail. `reserve` is the event's synchronously known update count: the
1867
- * FIFO position and the bounded pending counter are committed BEFORE any
1868
- * await, the whole event is converted (official image reads included) inside
1869
- * the tail, and only then are its updates handed to the transport. The
1870
- * bounded pending counter is the ONLY additional queue: exceeding it fails
1871
- * this View's request instead of growing without limit.
1872
- */
1873
- enqueueOutputTask(claim, flight, reserve, build) {
1874
- if (reserve === 0 || flight.settledDone) return;
1875
- const taskIndex = flight.outputTasksQueued;
1876
- flight.outputTasksQueued += 1;
1877
- flight.pendingUpdates += reserve;
1878
- if (flight.pendingUpdates > MAX_PENDING_OUTPUT_UPDATES) {
1879
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_OUTPUT_BACKPRESSURE", "the ACP output queue exceeded its bounded capacity", JSONRPC_INTERNAL_ERROR));
1880
- return;
1881
- }
1882
- flight.outputTail = flight.outputTail.then(async () => {
1883
- try {
1884
- if (flight.settledDone || flight.mixed || flight.deliveryClosed || flight.outputStoppedAtTask !== void 0 && taskIndex < flight.outputStoppedAtTask) return;
1885
- const built = build();
1886
- const updates = Array.isArray(built) ? built : await built;
1887
- for (const update of updates) {
1888
- if (flight.settledDone || flight.mixed || flight.deliveryClosed || flight.outputStoppedAtTask !== void 0 && taskIndex < flight.outputStoppedAtTask) return;
1889
- try {
1890
- await flight.sendUpdate(update);
1891
- } catch {
1892
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_OUTPUT_FAILED", "an ACP session/update notification could not be delivered", JSONRPC_INTERNAL_ERROR));
1893
- return;
1894
- }
1895
- }
1896
- } catch (error) {
1897
- if (flight.outputStopped || flight.settledDone || flight.mixed || flight.deliveryClosed) return;
1898
- this.failPrompt(claim, flight, error instanceof LocalAcpViewError ? error : promptError("LOCAL_ACP_PROMPT_OUTPUT_FAILED", "the committed output could not be delivered", JSONRPC_INTERNAL_ERROR));
1899
- } finally {
1900
- flight.pendingUpdates -= reserve;
1901
- }
1902
- });
1903
- }
1904
- /**
1905
- * Settle the owned turn after `turn/end`: first drain every notification this
1906
- * flight queued, then answer one real legal StopReason or a stable failure.
1907
- */
1908
- settleTurnEnd(claim, flight, data) {
1909
- flight.phase = "settling";
1910
- runDetached("local acp: prompt settlement", async () => {
1911
- await flight.outputTail;
1912
- if (flight.settledDone) return;
1913
- if (flight.mixed) {
1914
- 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));
1915
- return;
1916
- }
1917
- if (flight.cancelKind === "running-addressed" && turnEndUserAborted(data)) {
1918
- this.completePrompt(claim, flight, { stopReason: "cancelled" });
1919
- return;
1920
- }
1921
- const kind = turnEndReasonKind(data);
1922
- if (kind !== "completed" && kind !== "max-tokens") {
1923
- 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 }));
1924
- return;
1925
- }
1926
- if (!flight.assistantVisibleOutput) {
1927
- this.failPrompt(claim, flight, promptError("LOCAL_ACP_PROMPT_NO_ASSISTANT_TEXT", "the owned turn ended without any visible assistant output", JSONRPC_INTERNAL_ERROR));
1928
- return;
1929
- }
1930
- this.completePrompt(claim, flight, { stopReason: kind === "completed" ? "end_turn" : "max_tokens" });
1931
- }, { diag: this.diag });
1932
- }
1933
- /**
1934
- * Stop ONLY this flight's own output IO. Already delivered notifications stay
1935
- * delivered; a queued read is abandoned and its rejection is classified as a
1936
- * closure by the tail, never as a content failure. The Host Agent, Session
1937
- * and writer keep their authority.
1938
- */
1939
- stopFlightOutput(flight) {
1940
- flight.outputStopped = true;
1941
- flight.outputStoppedAtTask ??= flight.outputTasksQueued;
1942
- flight.outputAbort.abort();
1943
- }
1944
- /**
1945
- * Commit the MIXED fact of one flight: no output committed from now on is
1946
- * projected, and this flight's own not-yet-finished output IO stops (an
1947
- * in-flight official image read is abandoned) so a stalled read can never
1948
- * hold the `turn/end` settlement forever. Already handed-off notifications
1949
- * stay delivered; queued-but-unsent output is dropped at its send check (the
1950
- * accepted PO-3A contract). The Host Agent/Session/Writer are untouched.
1951
- */
1952
- markFlightMixed(flight) {
1953
- flight.mixed = true;
1954
- this.stopFlightOutput(flight);
1955
- }
1956
- /** Fail one flight exactly once and release its slot and correlation state. */
1957
- failPrompt(claim, flight, error) {
1958
- if (flight.settledDone) return;
1959
- flight.settledDone = true;
1960
- flight.phase = "settling";
1961
- flight.detachAbort?.();
1962
- flight.detachAbort = void 0;
1963
- flight.foreignTurn = void 0;
1964
- flight.deliveryClosed = true;
1965
- this.stopFlightOutput(flight);
1966
- this.abortPermissionRequests(flight);
1967
- flight.failureCode = error.code;
1968
- if (flight.turn !== void 0 && !flight.ownTurnEnded) this.retainRetiringTurn(claim, {
1969
- turn: flight.turn,
1970
- origin: flight.turnProvenance?.turn === flight.turn ? flight.turnProvenance.origin : "acp"
1971
- });
1972
- if (flight.turn === void 0 && !flight.ownTurnEnded && flight.cancelKind !== "queued-removed") {
1973
- if (flight.messageId !== void 0) claim.unclaimedHostObligation = {
1974
- requestId: flight.requestId,
1975
- messageId: flight.messageId,
1976
- admission: flight.admissionSettled ? "unconfirmed" : "accepted",
1977
- ...flight.turnProvenance === void 0 ? {} : { turnProvenance: flight.turnProvenance }
1978
- };
1979
- else if (!flight.admissionSettled) claim.unclaimedHostObligation = {
1980
- requestId: flight.requestId,
1981
- admission: "pending",
1982
- ...flight.turnProvenance === void 0 ? {} : { turnProvenance: flight.turnProvenance }
1983
- };
1984
- }
1985
- if (claim.inflight === flight) claim.inflight = void 0;
1986
- this.notifyWorkSettled();
1987
- flight.settled.reject(error);
1988
- }
1989
- /** Complete one flight with its real ACP StopReason and release its slot. */
1990
- completePrompt(claim, flight, result) {
1991
- if (flight.settledDone) return;
1992
- flight.settledDone = true;
1993
- flight.phase = "settling";
1994
- flight.detachAbort?.();
1995
- flight.detachAbort = void 0;
1996
- flight.foreignTurn = void 0;
1997
- flight.deliveryClosed = true;
1998
- this.stopFlightOutput(flight);
1999
- this.abortPermissionRequests(flight);
2000
- if (claim.inflight === flight) claim.inflight = void 0;
2001
- this.notifyWorkSettled();
2002
- flight.settled.resolve(result);
2003
- }
2004
- /** Abort every pending reverse permission request of one settling flight. */
2005
- abortPermissionRequests(flight) {
2006
- for (const pending of flight.permissionRequests.values()) pending.abort();
2007
- flight.permissionRequests.clear();
2008
- }
2009
- validateNew(request) {
2010
- validateCwd(request.cwd);
2011
- 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);
2012
- 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);
2013
- }
2014
- validateResume(request) {
2015
- 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);
2016
- validateCwd(request.cwd);
2017
- 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);
2018
- 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);
2019
- }
2020
- };
2021
- /** A `session/new|resume` cwd is a non-empty Linux absolute path with no NUL. */
2022
- function validateCwd(cwd) {
2023
- 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);
2024
- }
2025
- /**
2026
- * Validate and normalize standard ACP prompt blocks in client order.
2027
- * `resource_link` blocks become official bracketed text hints; inline images
2028
- * require this connection's negotiated Host capability. Embedded resource,
2029
- * audio, unknown blocks, empty prompts and whitespace-only text stay rejected
2030
- * before any Host dispatch.
2031
- */
2032
- function validatePromptContent(prompt, imageEnabled) {
2033
- 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);
2034
- const content = [];
2035
- let pendingText = "";
2036
- const flushText = () => {
2037
- if (pendingText.length === 0) return;
2038
- content.push({
2039
- type: "text",
2040
- text: pendingText
2041
- });
2042
- pendingText = "";
2043
- };
2044
- for (const block of prompt) {
2045
- const wireBlock = block;
2046
- if (wireBlock === null || wireBlock === void 0) throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "the prompt contains an invalid content block", JSONRPC_INVALID_PARAMS);
2047
- const type = wireBlock.type;
2048
- if (type === "text") {
2049
- if (typeof wireBlock.text !== "string") throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "the prompt contains an invalid text block", JSONRPC_INVALID_PARAMS);
2050
- pendingText += wireBlock.text;
2051
- continue;
2052
- }
2053
- if (type === "resource_link") {
2054
- 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);
2055
- pendingText += `\n[resource_link name=${JSON.stringify(wireBlock.name)} uri=${JSON.stringify(wireBlock.uri)}]\n`;
2056
- continue;
2057
- }
2058
- if (type === "image") {
2059
- 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);
2060
- flushText();
2061
- content.push({
2062
- type: "image",
2063
- mediaType: wireBlock.mimeType,
2064
- data: wireBlock.data
2065
- });
2066
- continue;
2067
- }
2068
- throw promptError("LOCAL_ACP_PROMPT_INVALID_CONTENT", "this Host accepts standard ACP text, resource_link and negotiated image blocks only", JSONRPC_INVALID_PARAMS);
2069
- }
2070
- flushText();
2071
- 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);
2072
- return content;
2073
- }
2074
- /** One stable "the official Store could not read this committed image" failure. */
2075
- function attachmentReadFailed() {
2076
- return promptError("LOCAL_ACP_PROMPT_ATTACHMENT_READ_FAILED", "a committed image attachment could not be read and verified", JSONRPC_INTERNAL_ERROR);
2077
- }
2078
- /**
2079
- * The structural official `ImageAttachmentRef` of one committed image block.
2080
- * Only the reference SHAPE is checked here; the official Host Attachment Store
2081
- * remains the authority that verifies the object named by this reference.
2082
- */
2083
- function committedImageRef(block) {
2084
- const attachment = block?.attachment;
2085
- if (attachment === null || typeof attachment !== "object") return void 0;
2086
- const ref = attachment;
2087
- if (typeof ref.attachmentId !== "string" || typeof ref.mediaType !== "string" || typeof ref.bytes !== "number" || typeof ref.width !== "number" || typeof ref.height !== "number") return;
2088
- return {
2089
- attachmentId: ref.attachmentId,
2090
- mediaType: ref.mediaType,
2091
- bytes: ref.bytes,
2092
- width: ref.width,
2093
- height: ref.height
2094
- };
2095
- }
2096
- /** One stable "this committed block has no PO-3A projection" failure. */
2097
- function unsupportedContent() {
2098
- return promptError("LOCAL_ACP_PROMPT_UNSUPPORTED_CONTENT", "a committed content block has no standard ACP projection in this phase", JSONRPC_INTERNAL_ERROR);
2099
- }
2100
- /** Preserve malformed model tool arguments as opaque input instead of dropping them. */
2101
- function parseToolArguments(value) {
2102
- try {
2103
- return JSON.parse(value);
2104
- } catch {
2105
- return value;
2106
- }
2107
- }
2108
- /** Map an official Session-domain failure onto a stable View rejection. */
2109
- function mapResolveError(error, sessionId) {
2110
- const data = { sessionId };
2111
- switch (error.code) {
2112
- 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);
2113
- case "session/agent-busy": return new LocalAcpViewError("LOCAL_ACP_VIEW_SUBAGENT_OWNED", "the session is owned by subagent routing", JSONRPC_INVALID_PARAMS, data);
2114
- case "session/writer-held": return new LocalAcpViewError("LOCAL_ACP_VIEW_WRITER_HELD", "the session is written by another owner", JSONRPC_INVALID_PARAMS, data);
2115
- default: return new LocalAcpViewError("LOCAL_ACP_VIEW_HOST_ERROR", "the Host could not resolve the session", JSONRPC_INTERNAL_ERROR, data);
2116
- }
2117
- }
2118
- //#endregion
2119
- //#region src/app/remote-process/local-acp-listener.ts
2120
- /**
2121
- * Host-owned local ACP v1 front door over a pathname Unix domain socket.
2122
- *
2123
- * The one Host process that already owns a canonical profile scope opens a
2124
- * bounded `acp.sock` on ONE platform-specific physical endpoint: Linux keeps the
2125
- * 0700 scope directory and binds through `/proc/self/fd` so an over-long scope
2126
- * pathname still fits the kernel `sun_path`; Darwin publishes the same
2127
- * private-bind inode onto a short profile-scoped
2128
- * `/private/tmp/dpt-<uid>-<scope40>/acp.sock` pathname that stays within the
2129
- * Darwin `sockaddr_un.sun_path` byte limit. The listener speaks ACP v1 with
2130
- * the official `@agentclientprotocol/sdk` stream and request/notification
2131
- * dispatch, but it owns NO Agent, Session or business method in this phase: a
2132
- * valid `initialize` is answered with the installed bundle's own identity and
2133
- * every Session request fails closed with a machine-readable code. The listener
2134
- * is a Host-entry-local lifecycle object (`startLocalAcpListener()`), never a
2135
- * package export and never a second Host authority: the existing entry keeps the
2136
- * one Ready commit (`writeLocalRecord`) and the one shutdown owner, and the
2137
- * listener is bound BEFORE that Ready commit so a published registry never
2138
- * points at a socket that is not yet accepting.
2139
- *
2140
- * The SDK's default NDJSON stream uses an unbounded `LineBuffer` and no output
2141
- * backpressure, so this module wraps the socket in TWO bounded streams: an
2142
- * input reader that scans raw UTF-8 bytes for newlines under a per-frame and a
2143
- * queued-byte cap, and an output writer that refuses a frame or a buffered
2144
- * total above its cap. A cap breach closes only the offending connection.
2145
- *
2146
- * @module app/remote-process/local-acp-listener
2147
- */
2148
- /** The ACP agent identity this front door advertises (never a copied brand). */
2149
- const AGENT_NAME = "dsh-pi-tui";
2150
- /** One input line (a single NDJSON frame) may not exceed one mebibyte. */
2151
- const MAX_INPUT_FRAME_BYTES = 1048576;
2152
- /**
2153
- * Total unconsumed input on ONE connection is bounded: the current partial
2154
- * line plus complete frames awaiting the SDK plus frames already enqueued into
2155
- * the bounded ReadableStream. All three are summed in bytes against this cap.
2156
- */
2157
- const MAX_INPUT_UNCONSUMED_BYTES = 2097152;
2158
- /** At most this many requests may be dispatched concurrently on ONE connection. */
2159
- const MAX_PENDING_REQUESTS = 8;
2160
- /** Bytes reserved per image block for JSON metadata around its encoded data. */
2161
- const IMAGE_METADATA_BYTES = 65536;
2162
- /** Bytes reserved for the JSON-RPC envelope and its trailing newline. */
2163
- const JSON_ENVELOPE_BYTES = 4096;
2164
- /**
2165
- * Text allowance of ONE outbound committed event when the connection derives
2166
- * its frame budget from Host attachment limits: a larger derived budget must
2167
- * not reject ordinary large text output that the legacy wire already bounded.
2168
- */
2169
- const OUTPUT_TEXT_BYTES = 1048576;
2170
- /** The legacy text-only bounds every connection uses until it negotiates image. */
2171
- const TEXT_ONLY_BOUNDS = {
2172
- maxFrameBytes: MAX_INPUT_FRAME_BYTES,
2173
- maxUnconsumedBytes: MAX_INPUT_UNCONSUMED_BYTES
2174
- };
2175
- /**
2176
- * Derive the bounded input budget of an image-negotiated connection from the
2177
- * Host's OWN boot-frozen attachment limits. The arithmetic models canonical
2178
- * base64, one configured count of image metadata allowances, the preserved
2179
- * text/wire budget and one JSON-RPC envelope. It is not a second image policy:
2180
- * real count/byte/pixel admission remains the official Attachment Store's.
2181
- *
2182
- * @param limits - the exact Host attachment limits, or undefined without a store.
2183
- * @returns the bounds, or undefined when a safe bound cannot be represented.
2184
- */
2185
- function deriveImageInputBounds(limits) {
2186
- if (limits === void 0) return void 0;
2187
- const { maxMessageImageBytes, maxImagesPerMessage } = limits;
2188
- if (!Number.isSafeInteger(maxMessageImageBytes) || maxMessageImageBytes <= 0 || !Number.isSafeInteger(maxImagesPerMessage) || maxImagesPerMessage <= 0 || !Number.isSafeInteger(limits.maxImageBytes) || limits.maxImageBytes <= 0) return;
2189
- const encoded = 4 * Math.ceil(maxMessageImageBytes / 3);
2190
- const imageFrameBytes = encoded + MAX_INPUT_FRAME_BYTES + IMAGE_METADATA_BYTES * maxImagesPerMessage + JSON_ENVELOPE_BYTES;
2191
- const maxFrameBytes = Math.max(MAX_INPUT_FRAME_BYTES, imageFrameBytes);
2192
- const maxUnconsumedBytes = maxFrameBytes + MAX_INPUT_FRAME_BYTES;
2193
- if (!Number.isSafeInteger(encoded) || !Number.isSafeInteger(imageFrameBytes) || !Number.isSafeInteger(maxFrameBytes) || !Number.isSafeInteger(maxUnconsumedBytes) || maxFrameBytes > constants$1.MAX_LENGTH || maxUnconsumedBytes > constants$1.MAX_LENGTH) return;
2194
- return {
2195
- maxFrameBytes,
2196
- maxUnconsumedBytes
2197
- };
2198
- }
2199
- /**
2200
- * Derive ONE connection's outbound single-frame budget from the Host's OWN
2201
- * boot-frozen attachment limits. A committed image arrives from the official
2202
- * Store as ONE independently Base64-encoded object, and the Store's
2203
- * `maxMessageImageBytes` is a PROMPT-batch admission limit that does not bound
2204
- * a stored output image. The allowance therefore bounds each image by the
2205
- * Store's per-object admission ceiling (`maxImageBytes`), encodes every image
2206
- * separately and sums those encoded ceilings, then adds one metadata allowance
2207
- * per image, the JSON-RPC envelope and the preserved text allowance.
2208
- *
2209
- * This is a TRANSPORT resource bound, never an image acceptance policy and never
2210
- * a reason to drop, shrink or re-encode content: the official Attachment Store
2211
- * keeps every byte/pixel limit, and its normalization may even produce a stored
2212
- * image larger than `maxImageBytes` (the accepted upstream limitation). A frame
2213
- * above this allowance fails closed with `LOCAL_ACP_OUTPUT_FRAME_TOO_LARGE`
2214
- * before any byte of that frame is written.
2215
- *
2216
- * @param limits - the exact Host attachment limits, or undefined without a store.
2217
- * @returns the per-frame byte budget, or undefined when it cannot be represented.
2218
- */
2219
- function deriveImageOutputBounds(limits) {
2220
- if (limits === void 0) return void 0;
2221
- const { maxImagesPerMessage, maxImageBytes } = limits;
2222
- if (!Number.isSafeInteger(maxImageBytes) || maxImageBytes <= 0 || !Number.isSafeInteger(maxImagesPerMessage) || maxImagesPerMessage <= 0) return;
2223
- const encodedPerImage = 4 * Math.ceil(maxImageBytes / 3);
2224
- const encoded = maxImagesPerMessage * encodedPerImage;
2225
- const candidate = encoded + IMAGE_METADATA_BYTES * maxImagesPerMessage + JSON_ENVELOPE_BYTES + OUTPUT_TEXT_BYTES;
2226
- const maxFrameBytes = Math.max(MAX_OUTPUT_FRAME_BYTES, candidate);
2227
- if (!Number.isSafeInteger(encodedPerImage) || !Number.isSafeInteger(encoded) || !Number.isSafeInteger(candidate) || !Number.isSafeInteger(maxFrameBytes) || maxFrameBytes > constants$1.MAX_LENGTH) return;
2228
- return maxFrameBytes;
2229
- }
2230
- /** The legacy single outbound ACP frame cap (unchanged for a text-only Host). */
2231
- const MAX_OUTPUT_FRAME_BYTES = 262144;
2232
- /** Total bytes buffered in the socket awaiting flush on ONE connection. */
2233
- const MAX_OUTPUT_BUFFER_BYTES = 262144;
2234
- /** A frame above the legacy cap is written to the socket in bounded chunks. */
2235
- const OUTPUT_WRITE_CHUNK_BYTES = 65536;
2236
- /** The longest ONE kernel-drain wait of a chunked frame may block the writer. */
2237
- const OUTPUT_DRAIN_TIMEOUT_MS = 3e4;
2238
- /** How long a short stale-socket connect probe may run before it is treated as inert-unknown. */
2239
- const CONNECT_PROBE_TIMEOUT_MS = 500;
2240
- /** The logical socket file name inside the 0700 scope directory. */
2241
- const SOCKET_FILE = "acp.sock";
2242
- /** Owner-only private subdirectory (inside the 0700 scope) where the server is
2243
- * actually BOUND before its inode is hard-linked onto the contract path. Node's
2244
- * server.close() unlink always targets this private dir, so it can never delete
2245
- * a foreign inode at the contract path. */
2246
- const PRIVATE_DIR = ".acp-priv";
2247
- /** The trusted, OS-owned sticky parent of the Darwin profile-scoped endpoint. Never
2248
- * `$TMPDIR`, `DSH_HOME` or the user home: those are variable and unbounded. */
2249
- const DARWIN_SOCKET_PARENT = "/private/tmp";
2250
- /** Darwin `sockaddr_un.sun_path` capacity in bytes INCLUDING the trailing NUL. */
2251
- const DARWIN_SUN_PATH_BYTES = 104;
2252
- /** Prefix of the one deterministic Darwin endpoint root per profile scope. */
2253
- const DARWIN_ROOT_PREFIX = "dpt-";
2254
- /** Scope-id hex characters kept in the Darwin root name (the existing 160-bit
2255
- * collision budget the local seats already use). */
2256
- const DARWIN_SCOPE_PREFIX_HEX = 40;
2257
- const NEWLINE = 10;
2258
- /** The fixed capacity rejection an over-limit connection receives before it is ended. */
2259
- const CAPACITY_ERROR_LINE = `${JSON.stringify({
2260
- jsonrpc: "2.0",
2261
- id: null,
2262
- error: {
2263
- code: -32041,
2264
- message: "ACP connection capacity exceeded",
2265
- data: { code: "LOCAL_ACP_CAPACITY_EXCEEDED" }
2266
- }
2267
- })}\n`;
2268
- /** A startup failure that carries one stable local-ACP classification code. */
2269
- var LocalAcpError = class extends Error {
2270
- /** Stable classification asserted by the Host entry failure record. */
2271
- code;
2272
- constructor(code, message, cause) {
2273
- super(message, cause === void 0 ? void 0 : { cause });
2274
- this.name = "LocalAcpError";
2275
- this.code = code;
2276
- }
2277
- };
2278
- /**
2279
- * Parse the Host start-time connection limit from the raw environment value.
2280
- *
2281
- * Missing means the default of 4. Any present value MUST match `1..16` with no
2282
- * surrounding noise; a malformed value is a hard startup failure so a typo
2283
- * cannot silently widen or collapse the bound.
2284
- */
2285
- function parseAcpMaxConnections(raw) {
2286
- if (raw === void 0) return 4;
2287
- 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");
2288
- return Number(raw);
2289
- }
2290
- /** The ACP Session methods PO-1 must fail closed (business capability does not exist yet). */
2291
- function rejectSessionNotReady() {
2292
- throw new RequestError(-32042, "ACP Session operations are not available on this connection", { code: "LOCAL_ACP_SESSION_NOT_READY" });
2293
- }
2294
- /** Build the bounded input side: raw UTF-8 byte lines under the connection's current caps. */
2295
- /** @internal The owner test feeds real Unix-socket bytes while holding the stream reader. */
2296
- function createBoundedInput(socket, state, fail) {
2297
- /** Fragments of the current, not-yet-terminated line. */
2298
- const line = [];
2299
- let lineBytes = 0;
2300
- const queue = [];
2301
- let queuedByteCount = 0;
2302
- let controller;
2303
- let finished = false;
2304
- let controllerClosed = false;
2305
- let paused = false;
2306
- const closeController = () => {
2307
- if (controllerClosed || controller === void 0) return;
2308
- controllerClosed = true;
2309
- try {
2310
- controller.close();
2311
- } catch {}
2312
- };
2313
- /** The stream's OWN already-enqueued bytes, measured against its fixed high-water mark. */
2314
- const streamBufferedBytes = () => controller === void 0 ? 0 : Math.max(0, MAX_INPUT_FRAME_BYTES - (controller.desiredSize ?? MAX_INPUT_FRAME_BYTES));
2315
- const pump = () => {
2316
- if (controller === void 0) return;
2317
- while (queue.length > 0) {
2318
- if ((controller.desiredSize ?? 1) <= 0) break;
2319
- const frame = queue.shift();
2320
- if (frame !== void 0) {
2321
- queuedByteCount -= frame.byteLength;
2322
- controller.enqueue(frame);
2323
- }
2324
- }
2325
- if (queue.length > 0) {
2326
- if (!paused) {
2327
- paused = true;
2328
- socket.pause();
2329
- }
2330
- return;
2331
- }
2332
- if (paused) {
2333
- paused = false;
2334
- socket.resume();
2335
- }
2336
- if (finished) closeController();
2337
- };
2338
- const detach = () => {
2339
- socket.off("data", onData);
2340
- socket.off("end", onEnd);
2341
- socket.off("close", onClose);
2342
- socket.off("error", onError);
2343
- };
2344
- const failConnection = (code) => {
2345
- finished = true;
2346
- detach();
2347
- fail(code);
2348
- };
2349
- const completeLine = (end) => {
2350
- if (lineBytes - 1 > state.inputBounds.maxFrameBytes) {
2351
- failConnection("LOCAL_ACP_INPUT_FRAME_TOO_LARGE");
2352
- return;
2353
- }
2354
- line.push(end);
2355
- const frame = line.length === 1 ? Uint8Array.prototype.slice.call(line[0]) : Buffer.concat(line);
2356
- line.length = 0;
2357
- lineBytes = 0;
2358
- queue.push(frame);
2359
- queuedByteCount += frame.byteLength;
2360
- };
2361
- /**
2362
- * Scan one raw chunk by UTF-8 bytes. Every byte is forwarded verbatim; a
2363
- * newline completes exactly one NDJSON frame, so truncated or multi-byte
2364
- * characters stay intact across chunks.
2365
- */
2366
- const onData = (chunk) => {
2367
- if (finished) return;
2368
- let offset = 0;
2369
- while (offset < chunk.length) {
2370
- const newline = chunk.indexOf(NEWLINE, offset);
2371
- if (newline === -1) {
2372
- const rest = chunk.subarray(offset);
2373
- line.push(rest);
2374
- lineBytes += rest.length;
2375
- break;
2376
- }
2377
- lineBytes += newline + 1 - offset;
2378
- completeLine(chunk.subarray(offset, newline + 1));
2379
- if (finished) return;
2380
- offset = newline + 1;
2381
- }
2382
- if (lineBytes > state.inputBounds.maxFrameBytes) {
2383
- failConnection("LOCAL_ACP_INPUT_FRAME_TOO_LARGE");
2384
- return;
2385
- }
2386
- if (queuedByteCount + lineBytes + streamBufferedBytes() > state.inputBounds.maxUnconsumedBytes) {
2387
- failConnection("LOCAL_ACP_INPUT_OVERFLOW");
2388
- return;
2389
- }
2390
- pump();
2391
- };
2392
- const onEnd = () => {
2393
- finished = true;
2394
- pump();
2395
- };
2396
- const onClose = () => {
2397
- finished = true;
2398
- closeController();
2399
- };
2400
- const onError = () => {
2401
- finished = true;
2402
- closeController();
2403
- };
2404
- return new ReadableStream({
2405
- start(streamController) {
2406
- controller = streamController;
2407
- socket.on("data", onData);
2408
- socket.on("end", onEnd);
2409
- socket.on("close", onClose);
2410
- socket.on("error", onError);
2411
- },
2412
- pull() {
2413
- pump();
2414
- },
2415
- cancel() {
2416
- finished = true;
2417
- detach();
2418
- socket.destroy();
2419
- }
2420
- }, new ByteLengthQueuingStrategy({ highWaterMark: MAX_INPUT_FRAME_BYTES }));
2421
- }
2422
- /**
2423
- * Wait for ONE `drain` of this socket under a fixed deadline. A socket
2424
- * `close`/`error` ends the wait immediately (the connection is gone), and the
2425
- * deadline fails this connection alone with the existing backpressure class.
2426
- * Every exit path removes the listeners and the timer.
2427
- */
2428
- function waitForOutputDrain(socket, fail) {
2429
- return new Promise((resolve, reject) => {
2430
- let timer;
2431
- let finished = false;
2432
- const cleanup = () => {
2433
- if (timer !== void 0) clearTimeout(timer);
2434
- socket.off("drain", onDrain);
2435
- socket.off("close", onClose);
2436
- socket.off("error", onError);
2437
- };
2438
- const finish = (outcome) => {
2439
- if (finished) return;
2440
- finished = true;
2441
- cleanup();
2442
- if (outcome === "drained") resolve();
2443
- else if (outcome === "closed") reject(/* @__PURE__ */ new Error("local acp: output socket closed while draining"));
2444
- else {
2445
- fail("LOCAL_ACP_OUTPUT_BACKPRESSURE");
2446
- reject(/* @__PURE__ */ new Error("local acp: output drain exceeded its bounded wait"));
2447
- }
2448
- };
2449
- const onDrain = () => {
2450
- finish("drained");
2451
- };
2452
- const onClose = () => {
2453
- finish("closed");
2454
- };
2455
- const onError = () => {
2456
- finish("closed");
2457
- };
2458
- timer = setTimeout(() => {
2459
- finish("timeout");
2460
- }, OUTPUT_DRAIN_TIMEOUT_MS);
2461
- socket.once("drain", onDrain);
2462
- socket.once("close", onClose);
2463
- socket.once("error", onError);
2464
- });
2465
- }
2466
- /**
2467
- * Write ONE frame above the legacy cap in bounded chunks. The connection's
2468
- * unwritten backlog may never exceed `MAX_OUTPUT_BUFFER_BYTES`: before each
2469
- * chunk the writer waits (bounded) for the kernel to drain, and a refused
2470
- * `socket.write()` waits for its own `drain` before the next chunk. A reader
2471
- * that never drains the socket therefore closes THIS connection on the existing
2472
- * backpressure class; the Host, the Agent and every sibling connection are
2473
- * untouched, and no Host prompt is retried.
2474
- */
2475
- async function writeChunkedFrame(socket, frame, fail) {
2476
- let offset = 0;
2477
- while (offset < frame.byteLength) {
2478
- const end = Math.min(offset + OUTPUT_WRITE_CHUNK_BYTES, frame.byteLength);
2479
- while (!socket.destroyed && socket.writableLength + (end - offset) > MAX_OUTPUT_BUFFER_BYTES) await waitForOutputDrain(socket, fail);
2480
- if (socket.destroyed) throw new Error("local acp: output socket closed while writing a frame");
2481
- const accepted = socket.write(frame.subarray(offset, end));
2482
- offset = end;
2483
- if (!accepted) await waitForOutputDrain(socket, fail);
2484
- }
2485
- }
2486
- /**
2487
- * Build the bounded output side.
2488
- *
2489
- * Node reflects bytes accepted but not yet flushed to the kernel in
2490
- * `socket.writableLength`, so the pre-write cap on `writableLength + frame` is
2491
- * the enforced bound on "unwritten output": it closes a slow reader's
2492
- * connection instead of letting the queue grow without limit. Frames up to the
2493
- * legacy cap keep the original accept-then-resolve behavior. A larger frame —
2494
- * only possible when the connection derived a bounded budget from the Host's
2495
- * attachment limits — is written in 64 KiB chunks under the same backlog bound
2496
- * and a bounded kernel drain, so ONE legal committed image can reach a reading
2497
- * client without letting a stalled reader grow memory.
2498
- */
2499
- function createBoundedOutput(socket, fail, maxOutputFrameBytes) {
2500
- return new WritableStream({ async write(frame) {
2501
- if (socket.destroyed) throw new Error("local acp: output socket already closed");
2502
- if (frame.byteLength > maxOutputFrameBytes) {
2503
- fail("LOCAL_ACP_OUTPUT_FRAME_TOO_LARGE");
2504
- throw new Error("local acp: output frame exceeds the connection frame budget");
2505
- }
2506
- if (frame.byteLength <= MAX_OUTPUT_FRAME_BYTES) {
2507
- if (socket.writableLength + frame.byteLength > MAX_OUTPUT_BUFFER_BYTES) {
2508
- fail("LOCAL_ACP_OUTPUT_BACKPRESSURE");
2509
- throw new Error("local acp: output backlog exceeds the connection cap");
2510
- }
2511
- socket.write(frame);
2512
- return;
2513
- }
2514
- await writeChunkedFrame(socket, frame, fail);
2515
- } }, new ByteLengthQueuingStrategy({ highWaterMark: MAX_OUTPUT_BUFFER_BYTES }));
2516
- }
2517
- /** Build the per-connection ACP agent app whose handlers own only connection-local state. */
2518
- function buildAgentApp(state, view, context, fail) {
2519
- const app = agent({ name: AGENT_NAME });
2520
- let initializeComplete = false;
2521
- const beginRequest = () => {
2522
- state.pendingRequests += 1;
2523
- if (state.pendingRequests > MAX_PENDING_REQUESTS) {
2524
- state.pendingRequests -= 1;
2525
- fail("LOCAL_ACP_TOO_MANY_PENDING_REQUESTS");
2526
- throw new RequestError(-32044, "too many outstanding ACP requests on this connection", { code: "LOCAL_ACP_TOO_MANY_PENDING_REQUESTS" });
2527
- }
2528
- };
2529
- app.onRequest(methods.agent.initialize, async (request) => {
2530
- beginRequest();
2531
- try {
2532
- if (state.initialized) throw new RequestError(-32043, "ACP connection is already initialized", { code: "LOCAL_ACP_ALREADY_INITIALIZED" });
2533
- const requested = request.params?.protocolVersion;
2534
- if (requested !== PROTOCOL_VERSION) throw RequestError.invalidParams({ code: "LOCAL_ACP_PROTOCOL_UNSUPPORTED" }, `unsupported ACP protocol version ${String(requested)}; this endpoint supports ${String(PROTOCOL_VERSION)}`);
2535
- state.initialized = true;
2536
- if (context.sessionAccess !== void 0 && state.view !== void 0) {
2537
- const bounds = await context.sessionAccess.supportsImagePrompts() ? deriveImageInputBounds(context.sessionAccess.imageLimits()) : void 0;
2538
- if (bounds !== void 0) {
2539
- state.imageEnabled = true;
2540
- state.inputBounds = bounds;
2541
- }
2542
- }
2543
- initializeComplete = true;
2544
- return {
2545
- protocolVersion: PROTOCOL_VERSION,
2546
- agentInfo: {
2547
- name: AGENT_NAME,
2548
- title: AGENT_NAME,
2549
- version: context.bundleVersion
2550
- },
2551
- agentCapabilities: {
2552
- loadSession: false,
2553
- promptCapabilities: {
2554
- image: state.imageEnabled,
2555
- audio: false,
2556
- embeddedContext: false
2557
- },
2558
- mcpCapabilities: {
2559
- http: false,
2560
- sse: false
2561
- },
2562
- sessionCapabilities: context.sessionAccess !== void 0 ? {
2563
- resume: {},
2564
- close: {}
2565
- } : {}
2566
- },
2567
- authMethods: []
2568
- };
2569
- } finally {
2570
- state.pendingRequests -= 1;
2571
- }
2572
- });
2573
- const rejectSessionOperation = (_request) => {
2574
- beginRequest();
2575
- try {
2576
- rejectSessionNotReady();
2577
- } finally {
2578
- state.pendingRequests -= 1;
2579
- }
2580
- };
2581
- const acceptAnyParams = (params) => params;
2582
- const access = context.sessionAccess;
2583
- const views = context.views;
2584
- if (access !== void 0 && views !== void 0 && view !== void 0) {
2585
- const requireInitialized = () => {
2586
- if (!state.initialized || !initializeComplete) throw new RequestError(-32042, "ACP Session operations require a completed initialize", { code: "LOCAL_ACP_VIEW_NOT_INITIALIZED" });
2587
- };
2588
- const asRequestError = (error) => error instanceof LocalAcpViewError ? new RequestError(error.rpcCode, error.message, {
2589
- ...error.data,
2590
- code: error.code
2591
- }) : error;
2592
- /**
2593
- * Read the optional config options of an already-attached View. ONLY a real
2594
- * model-catalog unavailability may omit the optional display; a stale,
2595
- * closed or foreign View identity is a lifecycle failure and must propagate
2596
- * through the normal JSON-RPC error boundary instead of falsely confirming
2597
- * an attachment that no longer exists.
2598
- */
2599
- const readConfigOptionsOrLog = async (sessionId) => {
2600
- try {
2601
- return await views.modelOptions(view, access, sessionId);
2602
- } catch (error) {
2603
- if (!(error instanceof LocalAcpViewError && error.code === "LOCAL_ACP_MODEL_UNAVAILABLE")) throw error;
2604
- context.diag.warn("local-acp.model-catalog-unavailable", {
2605
- code: "LOCAL_ACP_MODEL_CATALOG_UNAVAILABLE",
2606
- reason: error.code
2607
- });
2608
- return;
2609
- }
2610
- };
2611
- /** The transient notification sink of ONE connection's attached View. */
2612
- const configNotifierFor = (client) => async (sessionId, configOptions) => {
2613
- await client.notify(methods.client.session.update, {
2614
- sessionId,
2615
- update: {
2616
- sessionUpdate: "config_option_update",
2617
- configOptions: [...configOptions]
2618
- }
2619
- });
2620
- };
2621
- app.onRequest(methods.agent.session.new, async ({ params, client }) => {
2622
- beginRequest();
2623
- try {
2624
- requireInitialized();
2625
- const result = await views.newSession(view, access, params, configNotifierFor(client));
2626
- const configOptions = await readConfigOptionsOrLog(result.sessionId);
2627
- return {
2628
- ...result,
2629
- ...configOptions === void 0 ? {} : { configOptions }
2630
- };
2631
- } catch (error) {
2632
- throw asRequestError(error);
2633
- } finally {
2634
- state.pendingRequests -= 1;
2635
- }
2636
- });
2637
- app.onRequest(methods.agent.session.resume, async ({ params, client }) => {
2638
- beginRequest();
2639
- try {
2640
- requireInitialized();
2641
- const result = await views.resumeSession(view, access, params, configNotifierFor(client));
2642
- const configOptions = await readConfigOptionsOrLog(params.sessionId);
2643
- return {
2644
- ...result,
2645
- ...configOptions === void 0 ? {} : { configOptions }
2646
- };
2647
- } catch (error) {
2648
- throw asRequestError(error);
2649
- } finally {
2650
- state.pendingRequests -= 1;
2651
- }
2652
- });
2653
- app.onRequest(methods.agent.session.close, async ({ params }) => {
2654
- beginRequest();
2655
- try {
2656
- requireInitialized();
2657
- return await views.closeSession(view, access, params.sessionId);
2658
- } catch (error) {
2659
- throw asRequestError(error);
2660
- } finally {
2661
- state.pendingRequests -= 1;
2662
- }
2663
- });
2664
- app.onRequest(methods.agent.session.prompt, async ({ params, signal, client }) => {
2665
- beginRequest();
2666
- try {
2667
- requireInitialized();
2668
- return await views.promptSession(view, access, params, signal, state.imageEnabled, async (update) => {
2669
- await client.notify(methods.client.session.update, {
2670
- sessionId: params.sessionId,
2671
- update
2672
- });
2673
- }, async (permissionParams, options) => {
2674
- return await client.request(methods.client.session.requestPermission, {
2675
- sessionId: permissionParams.sessionId,
2676
- toolCall: permissionParams.toolCall,
2677
- options: permissionParams.options
2678
- }, options === void 0 ? void 0 : { cancellationSignal: options.signal });
2679
- });
2680
- } catch (error) {
2681
- throw asRequestError(error);
2682
- } finally {
2683
- state.pendingRequests -= 1;
2684
- }
2685
- });
2686
- app.onRequest(methods.agent.session.setConfigOption, async ({ params, signal }) => {
2687
- beginRequest();
2688
- try {
2689
- requireInitialized();
2690
- return { configOptions: await views.setModelOption(view, access, params, signal) };
2691
- } catch (error) {
2692
- throw asRequestError(error);
2693
- } finally {
2694
- state.pendingRequests -= 1;
2695
- }
2696
- });
2697
- } else {
2698
- app.onRequest(methods.agent.session.new, acceptAnyParams, rejectSessionOperation);
2699
- app.onRequest(methods.agent.session.resume, acceptAnyParams, rejectSessionOperation);
2700
- app.onRequest(methods.agent.session.close, acceptAnyParams, rejectSessionOperation);
2701
- app.onRequest(methods.agent.session.prompt, acceptAnyParams, rejectSessionOperation);
2702
- app.onRequest(methods.agent.session.setConfigOption, acceptAnyParams, rejectSessionOperation);
2703
- }
2704
- app.onRequest(methods.agent.session.list, acceptAnyParams, rejectSessionOperation);
2705
- if (access !== void 0 && views !== void 0 && view !== void 0) app.onNotification(methods.agent.session.cancel, ({ params }) => {
2706
- if (!state.initialized) return;
2707
- if (typeof params?.sessionId !== "string" || params.sessionId === "") return;
2708
- views.cancelSession(view, access, params.sessionId);
2709
- });
2710
- else app.onNotification(methods.agent.session.cancel, () => {});
2711
- return app;
2712
- }
2713
- /** Wire one accepted socket to its own SDK connection; only this connection is affected by a fault. */
2714
- function serveConnection(socket, context) {
2715
- const view = context.views?.createConnection();
2716
- const state = {
2717
- initialized: false,
2718
- pendingRequests: 0,
2719
- closed: false,
2720
- imageEnabled: false,
2721
- inputBounds: TEXT_ONLY_BOUNDS,
2722
- maxOutputFrameBytes: deriveImageOutputBounds(context.sessionAccess?.imageLimits()) ?? MAX_OUTPUT_FRAME_BYTES,
2723
- ...view === void 0 ? {} : { view }
2724
- };
2725
- context.connectionStates.set(socket, state);
2726
- let tornDown = false;
2727
- let connection;
2728
- const fail = (code) => {
2729
- if (state.closed) return;
2730
- state.closed = true;
2731
- context.diag.warn("local-acp.error", {
2732
- code,
2733
- connections: context.connections.size
2734
- });
2735
- socket.destroy();
2736
- };
2737
- const teardown = () => {
2738
- if (tornDown) return;
2739
- tornDown = true;
2740
- state.closed = true;
2741
- if (view !== void 0) context.views?.releaseConnection(view, context.sessionAccess);
2742
- try {
2743
- connection?.close();
2744
- } catch {}
2745
- if (!socket.destroyed) socket.destroy();
2746
- context.connections.delete(socket);
2747
- context.connectionStates.delete(socket);
2748
- context.diag.info("local-acp.connection.close", { connections: context.connections.size });
2749
- };
2750
- socket.on("error", (error) => {
2751
- context.diag.warn("local-acp.error", {
2752
- code: error.code ?? "LOCAL_ACP_SOCKET_ERROR",
2753
- connections: context.connections.size
2754
- });
2755
- socket.destroy();
2756
- });
2757
- socket.on("close", teardown);
2758
- const input = createBoundedInput(socket, state, fail);
2759
- const output = createBoundedOutput(socket, fail, state.maxOutputFrameBytes);
2760
- const app = buildAgentApp(state, view, context, fail);
2761
- const stream = ndJsonStream(output, input);
2762
- connection = app.connect(stream);
2763
- const connected = connection;
2764
- runDetached("local acp: connection teardown", () => connected.closed.then(teardown, teardown), { diag: context.diag });
2765
- }
2766
- /** Open the scope directory and require `/proc/self/fd` so a long path can be bound by short fd path. */
2767
- function openScopeDirFd(scope) {
2768
- let dirFd;
2769
- try {
2770
- dirFd = openSync(scope.dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
2771
- } catch (error) {
2772
- throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the scope directory could not be opened without following a link", error);
2773
- }
2774
- if (process.platform !== "linux") {
2775
- closeSync(dirFd);
2776
- throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the fd-shortened socket path requires Linux /proc/self/fd");
2777
- }
2778
- return dirFd;
2779
- }
2780
- /** The short kernel-bind path derived from an open directory fd (Linux only). */
2781
- function fdSocketPath(dirFd) {
2782
- return `/proc/self/fd/${String(dirFd)}/${SOCKET_FILE}`;
2783
- }
2784
- /**
2785
- * Compute the FROZEN Darwin endpoint from the real profile scope id and the
2786
- * current OS uid: `/private/tmp/dpt-<decimal-uid>-<scope40>` holds one 0700 root
2787
- * whose `acp.sock` is the public address and whose `.acp-priv/acp.sock` is the
2788
- * private bind name. No configuration, environment variable or user path can
2789
- * change it, and both names must fit `sun_path[104]` INCLUDING the NUL. The
2790
- * caller creates/admits the root; this function performs no filesystem IO.
2791
- *
2792
- * @param scope - the canonical profile scope (its `scopeId` is a 64-hex SHA-256).
2793
- * @param uid - the current process uid; the root is scoped to this exact uid.
2794
- * @returns the public, root and private bind pathnames.
2795
- * @throws {LocalAcpError} `LOCAL_ACP_SOCKET_PATH_UNSUPPORTED` when a name exceeds
2796
- * the Darwin kernel path capacity.
2797
- */
2798
- function darwinAcpSocketPaths(scope, uid) {
2799
- const privateRoot = join(DARWIN_SOCKET_PARENT, `${DARWIN_ROOT_PREFIX}${String(uid)}-${scope.scopeId.slice(0, DARWIN_SCOPE_PREFIX_HEX)}`);
2800
- const publicPath = join(privateRoot, SOCKET_FILE);
2801
- const privateBindPath = join(privateRoot, PRIVATE_DIR, SOCKET_FILE);
2802
- 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");
2803
- return {
2804
- publicPath,
2805
- privateRoot,
2806
- privateBindPath
2807
- };
2808
- }
2809
- /**
2810
- * Admit the trusted Darwin parent and create/reuse the ONE deterministic 0700
2811
- * root of this profile scope. `/private/tmp` must be the OS-owned, root-owned
2812
- * sticky directory the frozen endpoint contract relies on; the root itself must
2813
- * be a real directory owned by this uid (a symlink, file, foreign-owned entry or
2814
- * an EXISTING directory that is not 0700 is refused and never written through or
2815
- * silently repaired). The root is REUSED across ACP Off/On and Host crashes —
2816
- * only this scope's root is ever touched.
2817
- */
2818
- function ensureDarwinSocketRoot(privateRoot, uid) {
2819
- let parent;
2820
- try {
2821
- parent = lstatSync(DARWIN_SOCKET_PARENT);
2822
- } catch (error) {
2823
- throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin socket parent is not available", error);
2824
- }
2825
- 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");
2826
- let created = true;
2827
- try {
2828
- mkdirSync(privateRoot, { mode: 448 });
2829
- } catch (error) {
2830
- if (error.code !== "EEXIST") throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the Darwin endpoint root could not be created", error);
2831
- created = false;
2832
- }
2833
- const info = lstatSync(privateRoot);
2834
- 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");
2835
- if (created) {
2836
- chmodSync(privateRoot, 448);
2837
- return;
2838
- }
2839
- 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");
2840
- }
2841
- /** A ≤500ms connect probe used only to distinguish an inert stale socket from a live one. */
2842
- function probeSocket(path) {
2843
- return new Promise((resolve) => {
2844
- let settled = false;
2845
- const target = connect(path);
2846
- const finish = (verdict) => {
2847
- if (settled) return;
2848
- settled = true;
2849
- clearTimeout(timer);
2850
- target.destroy();
2851
- resolve(verdict);
2852
- };
2853
- const timer = setTimeout(() => finish("unknown"), CONNECT_PROBE_TIMEOUT_MS);
2854
- target.once("connect", () => finish("open"));
2855
- target.once("error", (error) => {
2856
- finish(error.code === "ECONNREFUSED" ? "refused" : "unknown");
2857
- });
2858
- });
2859
- }
2860
- /** Read the socket inode identity at one path, or reject a non-socket / foreign / symlink entry. */
2861
- function readSavedInode(path, uid) {
2862
- const info = lstatSync(path);
2863
- 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");
2864
- return {
2865
- dev: info.dev,
2866
- ino: info.ino,
2867
- uid: info.uid
2868
- };
2869
- }
2870
- /**
2871
- * Start the one Host-owned local ACP listener for this scope.
2872
- *
2873
- * Ordering: probe/reclaim the logical path, bind the fd-shortened path, force
2874
- * the inode to 0600 and prove it, and only then return. The caller is
2875
- * responsible for committing Ready AFTER this resolves.
2876
- */
2877
- async function startLocalAcpListener(options) {
2878
- const { scope, maxConnections, diag, sessionAccess, views: sharedViews } = options;
2879
- const uid = process.getuid?.();
2880
- if (typeof uid !== "number") throw new LocalAcpError("LOCAL_ACP_SOCKET_PATH_UNSUPPORTED", "local acp: the current uid is unavailable");
2881
- 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");
2882
- const platform = process.platform;
2883
- const darwin = platform === "darwin";
2884
- 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");
2885
- const darwinPaths = darwin ? darwinAcpSocketPaths(scope, uid) : void 0;
2886
- const logicalPath = darwinPaths === void 0 ? join(scope.dir, SOCKET_FILE) : darwinPaths.publicPath;
2887
- let scopeDirFd;
2888
- if (darwinPaths === void 0) scopeDirFd = openScopeDirFd(scope);
2889
- else ensureDarwinSocketRoot(darwinPaths.privateRoot, uid);
2890
- const scopeProbePath = scopeDirFd === void 0 ? logicalPath : fdSocketPath(scopeDirFd);
2891
- const privDir = darwinPaths === void 0 ? join(scope.dir, PRIVATE_DIR) : join(darwinPaths.privateRoot, PRIVATE_DIR);
2892
- let privFd;
2893
- let scopeDirFdClosed = false;
2894
- let privFdClosed = false;
2895
- let saved;
2896
- let server;
2897
- let stopping = false;
2898
- let closed;
2899
- const context = {
2900
- diag,
2901
- bundleVersion: scope.bundleVersion,
2902
- connections: /* @__PURE__ */ new Set(),
2903
- connectionStates: /* @__PURE__ */ new Map(),
2904
- ...sessionAccess === void 0 ? {} : {
2905
- sessionAccess,
2906
- views: sharedViews ?? new AcpSessionViewRegistry(diag)
2907
- }
2908
- };
2909
- const views = context.views;
2910
- const ownsFacts = views !== void 0 && sessionAccess !== void 0 && sharedViews === void 0;
2911
- if (views !== void 0 && sessionAccess !== void 0) views.observeFacts(sessionAccess);
2912
- const releasePromptFacts = () => {
2913
- if (!ownsFacts) return;
2914
- views?.disposeFacts();
2915
- };
2916
- const closeScopeDirFd = () => {
2917
- if (scopeDirFdClosed || scopeDirFd === void 0) return;
2918
- scopeDirFdClosed = true;
2919
- try {
2920
- closeSync(scopeDirFd);
2921
- } catch {}
2922
- };
2923
- const closePrivFd = () => {
2924
- if (privFdClosed || privFd === void 0) return;
2925
- privFdClosed = true;
2926
- try {
2927
- closeSync(privFd);
2928
- } catch {}
2929
- };
2930
- const removePrivDir = () => {
2931
- try {
2932
- rmdirSync(privDir);
2933
- } catch {}
2934
- };
2935
- /**
2936
- * Remove ONLY this process's owned socket inode. Identity-checked against the
2937
- * exact saved (dev, ino, uid): a foreign inode that has since replaced the
2938
- * pathname is never unlinked. Used by graceful retire, bind-failure cleanup and
2939
- * the synchronous process-exit mirror.
2940
- */
2941
- const cleanupSync = () => {
2942
- if (saved === void 0) return;
2943
- let current;
2944
- try {
2945
- current = lstatSync(logicalPath);
2946
- } catch {
2947
- return;
2948
- }
2949
- if (!current.isSocket() || current.uid !== saved.uid) return;
2950
- if (current.dev !== saved.dev || current.ino !== saved.ino) return;
2951
- try {
2952
- unlinkSync(logicalPath);
2953
- } catch {}
2954
- };
2955
- const retireServer = () => {
2956
- if (closed !== void 0) return closed;
2957
- stopping = true;
2958
- closed = (async () => {
2959
- for (const socket of context.connections) socket.destroy();
2960
- if (server !== void 0) await new Promise((resolveClose) => {
2961
- server.close(() => resolveClose());
2962
- });
2963
- cleanupSync();
2964
- closeScopeDirFd();
2965
- closePrivFd();
2966
- removePrivDir();
2967
- disposeFactsWhenSettled();
2968
- })();
2969
- return closed;
2970
- };
2971
- /**
2972
- * Dispose the ONE Host fact subscription once every ACCEPTED piece of work
2973
- * has settled on real Host facts (a pending admission inserted/classified,
2974
- * a queued removal committed, the owned turn's terminal drained, or a
2975
- * retired-turn fence ended). It never cancels work the ACP View may not
2976
- * cancel (D23 mixed turns) and never guesses with a timer: the registry's
2977
- * own settlement transitions resolve it. Detached, so retirement and Host
2978
- * shutdown are never blocked by a shared turn's duration.
2979
- */
2980
- const disposeFactsWhenSettled = () => {
2981
- if (views === void 0 || !ownsFacts) return;
2982
- runDetached("local acp: Host fact subscription retirement", async () => {
2983
- await views.whenHostWorkSettled();
2984
- releasePromptFacts();
2985
- }, { diag });
2986
- };
2987
- try {
2988
- let existing;
2989
- try {
2990
- existing = lstatSync(logicalPath);
2991
- } catch (error) {
2992
- if (error.code !== "ENOENT") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket path is not accessible", error);
2993
- }
2994
- if (existing !== void 0) {
2995
- 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");
2996
- const verdict = await probeSocket(scopeProbePath);
2997
- if (verdict === "open") throw new LocalAcpError("LOCAL_ACP_SOCKET_IN_USE", "local acp: a live listener already answers on the socket path");
2998
- if (verdict !== "refused") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the existing socket path could not be proven stale");
2999
- const recheck = readSavedInode(logicalPath, uid);
3000
- 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");
3001
- unlinkSync(logicalPath);
3002
- }
3003
- let privCreated = true;
3004
- try {
3005
- mkdirSync(privDir, { mode: 448 });
3006
- } catch (error) {
3007
- if (error.code !== "EEXIST") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind directory could not be created", error);
3008
- privCreated = false;
3009
- }
3010
- if (!privCreated) {
3011
- const dirInfo = lstatSync(privDir);
3012
- 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");
3013
- }
3014
- chmodSync(privDir, 448);
3015
- let privBindPath;
3016
- if (darwinPaths === void 0) {
3017
- privFd = openSync(privDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
3018
- privBindPath = fdSocketPath(privFd);
3019
- } else privBindPath = darwinPaths.privateBindPath;
3020
- let privExisting;
3021
- try {
3022
- privExisting = lstatSync(privBindPath);
3023
- } catch (error) {
3024
- if (error.code !== "ENOENT") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path is not accessible", error);
3025
- }
3026
- if (privExisting !== void 0) {
3027
- 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");
3028
- const privVerdict = await probeSocket(privBindPath);
3029
- if (privVerdict === "open") throw new LocalAcpError("LOCAL_ACP_SOCKET_IN_USE", "local acp: a live listener already occupies the private bind path");
3030
- if (privVerdict !== "refused") throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the private bind path could not be proven stale");
3031
- const privRecheck = readSavedInode(privBindPath, uid);
3032
- 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");
3033
- unlinkSync(privBindPath);
3034
- }
3035
- server = createServer((socket) => {
3036
- if (stopping) {
3037
- socket.destroy();
3038
- return;
3039
- }
3040
- if (context.connections.size >= maxConnections) {
3041
- diag.warn("local-acp.connection.reject", {
3042
- code: "LOCAL_ACP_CAPACITY_EXCEEDED",
3043
- connections: context.connections.size
3044
- });
3045
- socket.on("error", () => socket.destroy());
3046
- socket.end(CAPACITY_ERROR_LINE, () => socket.destroy());
3047
- return;
3048
- }
3049
- context.connections.add(socket);
3050
- diag.info("local-acp.connection.open", { connections: context.connections.size });
3051
- serveConnection(socket, context);
3052
- });
3053
- await new Promise((resolveListen, rejectListen) => {
3054
- server.once("error", rejectListen);
3055
- server.listen(privBindPath, () => {
3056
- server.off("error", rejectListen);
3057
- resolveListen();
3058
- });
3059
- });
3060
- server.on("error", (error) => {
3061
- diag.warn("local-acp.error", { code: error.code ?? "LOCAL_ACP_SERVER_ERROR" });
3062
- });
3063
- chmodSync(join(privDir, SOCKET_FILE), 384);
3064
- try {
3065
- linkSync(join(privDir, SOCKET_FILE), logicalPath);
3066
- } catch (error) {
3067
- 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)");
3068
- throw new LocalAcpError("LOCAL_ACP_UNSAFE_SOCKET", "local acp: the socket path could not be published", error);
3069
- }
3070
- const linked = lstatSync(logicalPath);
3071
- saved = {
3072
- dev: linked.dev,
3073
- ino: linked.ino,
3074
- uid: linked.uid
3075
- };
3076
- 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");
3077
- unlinkSync(join(privDir, SOCKET_FILE));
3078
- 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");
3079
- closeScopeDirFd();
3080
- diag.info("local-acp.listen", { connections: 0 });
3081
- } catch (error) {
3082
- for (const socket of context.connections) socket.destroy();
3083
- releasePromptFacts();
3084
- if (server !== void 0) try {
3085
- await new Promise((resolveClose) => {
3086
- server.close(() => resolveClose());
3087
- });
3088
- } catch {}
3089
- cleanupSync();
3090
- closeScopeDirFd();
3091
- closePrivFd();
3092
- removePrivDir();
3093
- throw error;
3094
- }
3095
- const isListening = () => {
3096
- if (stopping || closed !== void 0 || server === void 0 || !server.listening) return false;
3097
- if (saved === void 0) return false;
3098
- let current;
3099
- try {
3100
- current = lstatSync(logicalPath);
3101
- } catch {
3102
- return false;
3103
- }
3104
- return current.isSocket() && current.uid === saved.uid && current.dev === saved.dev && current.ino === saved.ino;
3105
- };
3106
- return {
3107
- socketPath: logicalPath,
3108
- connectionCount: () => context.connections.size,
3109
- isListening,
3110
- close: retireServer,
3111
- cleanupSync
3112
- };
3113
- }
3114
- //#endregion
3115
- export { ACP_IMAGE_MEDIA_TYPES as a, LOCAL_ACP_STATUS_ROUTE as c, startLocalAcpListener as i, createLocalAcpStatusHandler as l, darwinAcpSocketPaths as n, AcpSessionViewRegistry as o, parseAcpMaxConnections as r, AcpSessionModelService as s, LocalAcpError as t, observeAuthenticatedLocalAcpStatus as u };