@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

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 (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { S as scopeFromInstalledProfile, _ as installedPackageRootFromEntry, h as bindProcessSeat, i as cleanupOwnedFiles, m as LocalScopeError, p as LOCAL_PROTOCOL, v as readInstalledDshVersion, x as removeOwnedScratch, y as readLinuxStarttime } from "./local-discovery-C9VMjc0K.mjs";
3
- import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-DnduyDiw.mjs";
4
- import { t as PI_TUI_WEB_ACCESS_ROWS } from "./web-roster-CjqnUXNk.mjs";
2
+ import { d as readInstalledDshVersion, h as scopeFromInstalledProfile, m as removeOwnedScratch, n as LocalScopeError, o as bindProfileKernelSeat, t as LOCAL_PROTOCOL, u as installedPackageRootFromEntry } from "./local-scope-DamiMqPd.mjs";
3
+ import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-DjNsE3I0.mjs";
4
+ import { t as PI_TUI_WEB_ACCESS_ROWS } from "./web-roster-Dis7BhrA.mjs";
5
5
  import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
6
6
  import { r as PI_TUI_WEB_ACCESS_NAMESPACE } from "./pi-tui-web-access-contract-BN8Cc_Ho.mjs";
7
+ import { n as createWorkspaceObjectHandler, t as LOCAL_WORKSPACE_OBJECT_ROUTE } from "./local-workspace-object-D06GL0UO.mjs";
8
+ import { a as ACP_IMAGE_MEDIA_TYPES, c as LOCAL_ACP_STATUS_ROUTE, i as startLocalAcpListener, l as createLocalAcpStatusHandler, o as AcpSessionViewRegistry, r as parseAcpMaxConnections, s as AcpSessionModelService, t as LocalAcpError } from "./local-acp-listener-B65J0Bx4.mjs";
9
+ import { a as buildHostInstanceRecord, d as readHostProcessIdentity, o as cleanupOwnedFiles, r as assertRecordedHostKernelIdentityCurrent } from "./local-discovery-DOSsCh9q.mjs";
7
10
  import { createRequire } from "node:module";
8
11
  import { randomUUID } from "node:crypto";
9
12
  import { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
@@ -47,7 +50,7 @@ user-questions=@deepseek-ai/dsh-user-questions agent=@deepseek-ai/dsh-agent
47
50
  plugin-package-inventory-deepseek=@deepseek-ai/dsh-plugin-package-inventory-deepseek agent-default-model=@deepseek-ai/dsh-agent-default-model
48
51
  jobs=@deepseek-ai/dsh-jobs-local llm-retry=@deepseek-ai/dsh-llm-retry
49
52
  config-editor=@deepseek-ai/dsh-config-editor settings=@deepseek-ai/dsh-settings
50
- authorization=@deepseek-ai/dsh-authorization deepseek-account=@deepseek-ai/dsh-deepseek-account-platform
53
+ authorization=@deepseek-ai/dsh-authorization deepseek-account=@deepseek-ai/dsh-deepseek-account
51
54
  credentials=@deepseek-ai/dsh-credentials-local llm-pi-ai=@deepseek-ai/dsh-llm-pi-ai
52
55
  session-persistence-jsonl=@deepseek-ai/dsh-session-persistence-jsonl attachment-local=@deepseek-ai/dsh-attachment-local
53
56
  session-query-sqlite=@deepseek-ai/dsh-session-query-sqlite working-directory=@deepseek-ai/dsh-working-directory
@@ -84,7 +87,8 @@ split-host-connection=@deepseek-ai/dsh-client-connection split-host-api-remotes=
84
87
  split-host-file-upload=@deepseek-ai/dsh-client-file-upload split-host-session-stats=@deepseek-ai/dsh-session-stats
85
88
  split-host-turn-outline=@deepseek-ai/dsh-session-turn-outline split-host-session-controller=@deepseek-ai/dsh-api-session-controller
86
89
  split-host-settings-controller=@deepseek-ai/dsh-api-settings-controller split-host-session-log-download=@deepseek-ai/dsh-session-log-export
87
- split-host-pi-tui-runtime=@xmoon76/dsh-pi-tui/host-runtime schedule=@deepseek-ai/dsh-schedule`.trim().split(/\s+/u).map((entry) => {
90
+ split-host-pi-tui-runtime=@xmoon76/dsh-pi-tui/host-runtime schedule=@deepseek-ai/dsh-schedule
91
+ agent-team=@deepseek-ai/dsh-agent-team tool-agent-team=@deepseek-ai/dsh-tool-agent-team`.trim().split(/\s+/u).map((entry) => {
88
92
  const separator = entry.indexOf("=");
89
93
  return [entry.slice(0, separator), entry.slice(separator + 1)];
90
94
  }));
@@ -225,12 +229,15 @@ var HostActivityObserver = class {
225
229
  readable: false
226
230
  };
227
231
  }
228
- let roots;
229
- if (typeof registry.roots === "function") try {
230
- roots = new Set(registry.roots());
231
- } catch {
232
- roots = void 0;
233
- }
232
+ const subagents = this.context.reflect.get("subagents");
233
+ const rootRelation = (agent) => {
234
+ if (subagents === void 0) return "unknown";
235
+ try {
236
+ return subagents.rootOf(agent) === agent ? "root" : "child";
237
+ } catch {
238
+ return "unknown";
239
+ }
240
+ };
234
241
  let state = "IDLE";
235
242
  let maintenanceGap = false;
236
243
  for (const agent of agents) {
@@ -255,8 +262,11 @@ var HostActivityObserver = class {
255
262
  reasons.add("agent-inbox");
256
263
  state = "ACTIVE";
257
264
  }
258
- if (!running && pending === 0) maintenanceGap = true;
259
- if (roots !== void 0 && !roots.has(agent) && (running || pending > 0)) reasons.add("child-active");
265
+ if (running || pending > 0) {
266
+ const relation = rootRelation(agent);
267
+ if (relation === "child") reasons.add("child-active");
268
+ else if (relation === "unknown") reasons.add("source-unavailable");
269
+ } else maintenanceGap = true;
260
270
  }
261
271
  if (maintenanceGap) {
262
272
  reasons.add("agent-maintenance-unproven");
@@ -432,6 +442,157 @@ var HostActivityObserver = class {
432
442
  for (const dispose of subscriptions.reverse()) dispose();
433
443
  }
434
444
  };
445
+ //#endregion
446
+ //#region src/app/remote-process/local-web-control-route.ts
447
+ /** The one Owner-only authenticated route of the headless Web CLI. */
448
+ const LOCAL_WEB_CONTROL_ROUTE = "/api/pi-tui.web-control";
449
+ const OP_VALUES = /* @__PURE__ */ new Set([
450
+ "enable",
451
+ "disable",
452
+ "url"
453
+ ]);
454
+ function isRecord(value) {
455
+ return value !== null && typeof value === "object" && !Array.isArray(value);
456
+ }
457
+ function hasExactKeys(record, keys) {
458
+ const actual = Object.keys(record).sort();
459
+ const expected = [...keys].sort();
460
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
461
+ }
462
+ /** Read at most `maxBytes`; an oversize or unreadable body is `undefined`. */
463
+ async function readBoundedBody(request, maxBytes) {
464
+ const declared = request.headers.get("content-length");
465
+ if (declared !== null && Number(declared) > maxBytes) return void 0;
466
+ if (request.body === null) return "";
467
+ const reader = request.body.getReader();
468
+ const chunks = [];
469
+ let total = 0;
470
+ try {
471
+ for (;;) {
472
+ const { done, value } = await reader.read();
473
+ if (done) break;
474
+ total += value.byteLength;
475
+ if (total > maxBytes) {
476
+ await reader.cancel();
477
+ return;
478
+ }
479
+ chunks.push(value);
480
+ }
481
+ } finally {
482
+ reader.releaseLock();
483
+ }
484
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
485
+ }
486
+ /** The fixed response headers for every route reply, success or failure. */
487
+ function jsonResponse(body, status = 200) {
488
+ return new Response(JSON.stringify(body), {
489
+ status,
490
+ headers: {
491
+ "content-type": "application/json",
492
+ "cache-control": "no-store",
493
+ "referrer-policy": "no-referrer",
494
+ "x-content-type-options": "nosniff"
495
+ }
496
+ });
497
+ }
498
+ function errorResponse(error, status) {
499
+ return jsonResponse({
500
+ schema: 1,
501
+ error
502
+ }, status);
503
+ }
504
+ /** Parse the exact POST body; `undefined` means invalid input. */
505
+ function parseRequestBody(text) {
506
+ let value;
507
+ try {
508
+ value = JSON.parse(text);
509
+ } catch {
510
+ return;
511
+ }
512
+ if (!isRecord(value) || !hasExactKeys(value, [
513
+ "schema",
514
+ "instanceId",
515
+ "op"
516
+ ])) return void 0;
517
+ if (value.schema !== 1 || typeof value.instanceId !== "string" || value.instanceId === "") return void 0;
518
+ if (typeof value.op !== "string" || !OP_VALUES.has(value.op)) return void 0;
519
+ return {
520
+ schema: 1,
521
+ instanceId: value.instanceId,
522
+ op: value.op
523
+ };
524
+ }
525
+ /**
526
+ * Build the ONE Host route handler. It answers only for the CURRENT Host
527
+ * instance and calls the existing Web authority once per request.
528
+ * @param instanceId - this Host's published instance id.
529
+ * @param webAccess - the Host-entry-owned Web access service.
530
+ * @returns the registered route's `fetch` callback.
531
+ */
532
+ function createLocalWebControlHandler(instanceId, webAccess) {
533
+ return async (request) => {
534
+ if (request.method === "GET") {
535
+ let status;
536
+ try {
537
+ status = await webAccess.getStatus();
538
+ } catch {
539
+ return errorResponse("WEB_CLI_UNAVAILABLE", 503);
540
+ }
541
+ return jsonResponse({
542
+ schema: 1,
543
+ instanceId,
544
+ state: status.state
545
+ });
546
+ }
547
+ if (request.method !== "POST") return errorResponse("WEB_INVALID_REQUEST", 405);
548
+ const contentType = request.headers.get("content-type") ?? "";
549
+ if (!/^application\/json\b/iu.test(contentType)) return errorResponse("WEB_INVALID_REQUEST", 415);
550
+ const text = await readBoundedBody(request, 512);
551
+ if (text === void 0) return errorResponse("WEB_INVALID_REQUEST", 400);
552
+ const body = parseRequestBody(text);
553
+ if (body === void 0) return errorResponse("WEB_INVALID_REQUEST", 400);
554
+ if (body.instanceId !== instanceId) return errorResponse("WEB_INSTANCE_MISMATCH", 409);
555
+ if (body.op === "enable" || body.op === "disable") {
556
+ let status;
557
+ try {
558
+ status = await webAccess.setEnabled(body.op === "enable");
559
+ } catch {
560
+ return errorResponse("WEB_CLI_UNAVAILABLE", 503);
561
+ }
562
+ return jsonResponse({
563
+ schema: 1,
564
+ instanceId,
565
+ state: status.state
566
+ });
567
+ }
568
+ let status;
569
+ try {
570
+ status = await webAccess.getStatus();
571
+ } catch {
572
+ return errorResponse("WEB_CLI_UNAVAILABLE", 503);
573
+ }
574
+ if (status.state === "disabled") return jsonResponse({
575
+ schema: 1,
576
+ error: "WEB_DISABLED"
577
+ });
578
+ if (status.state === "changing") return jsonResponse({
579
+ schema: 1,
580
+ error: "WEB_CHANGING"
581
+ });
582
+ if (status.state === "unavailable") return errorResponse("WEB_CLI_UNAVAILABLE", 503);
583
+ let result;
584
+ try {
585
+ result = await webAccess.getAuthenticatedUrl();
586
+ } catch {
587
+ return errorResponse("WEB_CLI_UNAVAILABLE", 503);
588
+ }
589
+ return jsonResponse({
590
+ schema: 1,
591
+ instanceId,
592
+ url: result.url
593
+ });
594
+ };
595
+ }
435
596
  /**
436
597
  * The Host-only overlay applied over the profile's own patch stack. It keeps
437
598
  * `tui-startup` mounted for the consumers that genuinely need its parsed
@@ -439,7 +600,7 @@ var HostActivityObserver = class {
439
600
  * as their Dispose gate: reloading `tui-startup` must not dispose
440
601
  * already-accepted Host Session/Agent/Connection ownership. It disables only
441
602
  * the three surface rows that must not exist in a Host-only PID, then adds the
442
- * two B1 rows plus the official Session-serving rows and the ONE built-in
603
+ * two B1 rows plus the official Session-serving and Account Controller rows and the ONE built-in
443
604
  * PiTui Host Runtime row. The base Gateway, webserver, workspace-files,
444
605
  * workspace-controller, credentials, agents, sessions and jobs are reused,
445
606
  * never mounted twice.
@@ -452,6 +613,16 @@ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows
452
613
  - id: pi-tui-builtins
453
614
  disabled: true
454
615
 
616
+ # The Split Host's ONE Host Runtime row. The bundle DECLARES it (disabled by
617
+ # default); this overlay only ENABLES it. Keeping the declaration — and its
618
+ # config — out of this command-line overlay is required: the official
619
+ # ConfigEditor refuses to persist an entry whose config a home patch or
620
+ # command-line overlay overrides. The row owns the Split Host's private
621
+ # business services; the profile-owned TUI preferences it reads live in the
622
+ # canonical 'pi-tui-preferences' row.
623
+ - id: split-host-pi-tui-runtime
624
+ disabled: false
625
+
455
626
  # Infrastructure lifetime is independent of the mutable tuiStartup provider.
456
627
  - id: webserver
457
628
  inject: []
@@ -464,6 +635,13 @@ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows
464
635
  # row here would register the \`workspace\` namespace twice.
465
636
  - id: workspace-controller
466
637
  inject: []
638
+ # The bundle's ONE official Host directory-browse backend stays the bundle's
639
+ # row too: the overlay only drops its Direct tuiStartup admission gate so the
640
+ # Workspace Controller's DirectoryPickerController keeps serving
641
+ # 'directoryPicker/list' after the TUI Client is gone. A second picker row
642
+ # here would register the directory-picker seam twice.
643
+ - id: directory-picker
644
+ inject: []
467
645
 
468
646
  # Host Schedule management (S5-PR4): the bundle's ONE official Schedule row
469
647
  # stays this bundle's row; the overlay only drops its Direct tuiStartup
@@ -529,55 +707,58 @@ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows
529
707
  name: '@deepseek-ai/dsh-session-log-export'
530
708
  inject: [commands, connection]
531
709
 
710
+ # One process-global provider registration for the existing Cordis inspect
711
+ # registry. Never put this row in the Web toggle roster or mount a second
712
+ # runner: the registry rejects a duplicate provider id.
713
+ - id: split-host-cordis-inspect-providers
714
+ name: '@deepseek-ai/dsh-tool-cordis/host'
715
+ inject: [cordisInspect, tools]
716
+
532
717
  # The package's ONE built-in Host Runtime row: the private contribution plus
533
- # the three private business services. Business features are NOT separate
534
- # Loader rows or package subpaths.
535
- - id: split-host-pi-tui-runtime
536
- name: '@xmoon76/dsh-pi-tui/host-runtime'
537
- inject: [typert, agents, fileReferences, workingDirectory]
718
+ # the private business services. Business features are NOT separate Loader
719
+ # rows or package subpaths. The sandbox policy/provider are resolved PER
720
+ # CALL by the features that need them (M6-1 F8), so a Host without the
721
+ # sandbox provider still becomes Ready and reports that side truthfully.
722
+ #
723
+ # The row itself is DECLARED by the bundle patch (disabled by default), so
724
+ # its config stays USER-profile owned. This overlay only ENABLES it: the
725
+ # official ConfigEditor refuses to persist an entry whose config a home
726
+ # patch or command-line overlay overrides. Its legacy TUI preference fields
727
+ # are a migration source only; runtime behavior reads the canonical
728
+ # 'piTuiPreferences' service.
538
729
 
539
- # ── Official Web composition (M5-W PR-A/PR-B/PR-C) ──────────────────────────
540
- # The official Browser Web rows, declared here ONCE and DISABLED BY DEFAULT.
541
- # This declaration is the ONE roster the private 'piTuiWebAccess' Host service
542
- # toggles at runtime: it flips 'disabled' on exactly these rows through
543
- # 'Entry.update', never a second declaration, never a profile patch write, and
544
- # never a separate Web process. The toggle is per Host lifetime; a cold boot
545
- # starts from this default-off state UNLESS the profile's own
546
- # 'pi-tui-web-preferences.autoStart' preference is on, in which case the boot
547
- # sequence below enables the same roster before Ready ('/web' remains the
548
- # immediate control of a running Host).
549
- # Only the isolated qualification runs additionally override rows through
550
- # SPLIT_PROCESS_EXTRA_PATCH; that internal test channel is not a user API.
551
- #
552
- # The roster is the official browser graph of the installed DSH family minus
553
- # every row whose authority ALREADY exists in this Host: the second
554
- # 'connection', 'api-remotes', 'file-upload', 'workspace'/'workspace-controller',
555
- # 'session-controller', 'settings-controller', 'webserver', 'frontend-static'
556
- # fallback and 'web-startup' parser are NOT declared here. The mandatory
557
- # client-dependency closure of the official UIs ('ui-context-menu',
558
- # 'ui-file-drag'), the official Client file-actions / message-quotes features
559
- # and the 'workspace-changes' Host recorder that 'ui-deliverables' injects are
560
- # part of it. 'workspace-changes' is declared BEFORE its consumer because the
561
- # toggle activates one row at a time and awaits each fiber.
562
- # 'terminal-controller' is the ONE official Host row added on top of the
563
- # browser roster (the real Browser x TUI composition needs it).
730
+ # ── Official Web composition (M5-W PR-A/PR-B/PR-C, PR-A profile-writable) ──
731
+ # The complete Browser Web roster is declared in the BUNDLE
732
+ # (generated/web-access/cordis.patch.yml, generated from the ONE production
733
+ # table). It is NOT inserted here: a command-line overlay config override makes
734
+ # the official ConfigEditor refuse that entry's user writes, which is exactly
735
+ # why the official Web pages could not persist their volatile settings.
736
+ # Every roster row arrives DISABLED from the bundle. The private
737
+ # 'piTuiWebAccess' Host service flips exactly those rows through
738
+ # 'Entry.update'; a cold boot starts from the default-off bundle state UNLESS
739
+ # the profile's own 'pi-tui-web-preferences.autoStart' is on, in which case the
740
+ # boot sequence below enables the same roster before Ready ('/web' remains the
741
+ # immediate control of a running Host). Only the isolated qualification runs
742
+ # additionally override rows through SPLIT_PROCESS_EXTRA_PATCH; that internal
743
+ # test channel is not a user API.
564
744
  #
565
- # 'web-runtime' owns the single 'frontend-static' fallback over the official
566
- # dist and is explicitly told to stay silent: no browser launch, no printed
567
- # token URL and no DSH_WEB_URL shell variable.
568
- - insert:
569
- ${PI_TUI_WEB_ACCESS_ROWS.map(({ id, name }) => [
570
- ` - id: ${id}`,
571
- ` name: '${name}'`,
572
- " disabled: true",
573
- ...id === "web-runtime" ? [
574
- " inject: [webServer]",
575
- " config:",
576
- " openBrowser: false",
577
- " printUrl: false",
578
- " surfaceContext: false"
579
- ] : []
580
- ].join("\n")).join("\n")}
745
+ # The three rows below keep their official non-desktop safety values at this
746
+ # layer so a profile patch cannot relax them. They carry NO volatile Settings
747
+ # form in the pinned DSH family, so the in-place override cannot block a user
748
+ # save, and no writable UI row is overridden here.
749
+ ${[
750
+ "web-runtime",
751
+ "office-kit",
752
+ "skill-office"
753
+ ].map((id) => {
754
+ const row = PI_TUI_WEB_ACCESS_ROWS.find((candidate) => candidate.id === id);
755
+ if (row === void 0) throw new Error(`local host entry: the Web roster lost its "${id}" row`);
756
+ return [
757
+ `- id: ${row.id}`,
758
+ ...row.config === void 0 ? [] : [" config:", ...Object.entries(row.config).map(([key, value]) => ` ${key}: ${String(value)}`)],
759
+ ...(row.yaml ?? []).map((line) => line.replace(/^ {4}/u, ""))
760
+ ].join("\n");
761
+ }).join("\n")}
581
762
  `;
582
763
  /** Resolve one published DSH subpath from the installation anchor supplied by the launcher. */
583
764
  async function loadOfficialDsh(anchor) {
@@ -594,17 +775,20 @@ async function loadOfficialDsh(anchor) {
594
775
  };
595
776
  }
596
777
  /** Wait for one unauthenticated route to answer with the expected refusal. */
597
- async function waitForRefusal(url, timeoutMs = 1e4) {
778
+ async function waitForRefusal(url, timeoutMs = 1e4, init = {}) {
598
779
  const deadline = Date.now() + timeoutMs;
599
780
  while (Date.now() < deadline) {
600
781
  try {
601
- const response = await fetch(url, {
602
- method: "GET",
782
+ const request = {
783
+ method: init.method ?? "GET",
603
784
  redirect: "manual",
604
- cache: "no-store"
605
- });
785
+ cache: "no-store",
786
+ ...init.headers === void 0 ? {} : { headers: init.headers },
787
+ ...init.body === void 0 ? {} : { body: init.body }
788
+ };
789
+ const response = await fetch(url, request);
606
790
  await response.body?.cancel();
607
- if (response.status === 401) return;
791
+ if (response.status === 401 || response.status === 403) return;
608
792
  } catch {}
609
793
  await new Promise((resolve) => setTimeout(resolve, 100));
610
794
  }
@@ -682,45 +866,462 @@ async function applyWebStartupPreference(context, emit = writeEntryRecord) {
682
866
  status: "enabled"
683
867
  });
684
868
  }
869
+ /** The profile entry that owns the ACP startup preference. */
870
+ const ACP_STARTUP_PREFERENCE_NAMESPACE = "pi-tui-acp-preferences";
871
+ function imageRouteError(reason, message) {
872
+ return Object.assign(new Error(message), {
873
+ isDSHRemoteError: true,
874
+ code: "session/attachment-invalid",
875
+ details: { reason }
876
+ });
877
+ }
878
+ /**
879
+ * Bind the narrow {@link HostAcpSessionAccess} from the ONE already-settled Host
880
+ * Context. The official Workspace/Session/Agent/Session services stay the sole
881
+ * authority: this only forwards their callable methods, never their objects,
882
+ * Context or lifecycle. A missing service is a Host composition failure (the
883
+ * readiness audit already requires all four), never a silent fallback.
884
+ *
885
+ * `reflect.get` is used (not `ctx.<service>`) so this Host composition root does
886
+ * not add client-boundary coupling debt; the service identities remain the
887
+ * official ones the readiness audit asserts.
888
+ *
889
+ * @param context - the settled Host context.
890
+ * @returns the narrow Session access the listener borrows from.
891
+ */
892
+ function createHostAcpSessionAccess(context) {
893
+ const workspaceController = context.reflect.get("workspaceController");
894
+ const sessionController = context.reflect.get("sessionController");
895
+ const agents = context.reflect.get("agents");
896
+ const sessions = context.reflect.get("sessions");
897
+ const attachments = context.reflect.get("attachments");
898
+ const llm = context.reflect.get("llm");
899
+ const agentDefaultModel = context.reflect.get("agentDefaultModel");
900
+ if (workspaceController === void 0 || sessionController === void 0 || agents === void 0 || sessions === void 0 || llm === void 0) throw new Error("local host entry: the Host ACP Session View requires the live workspaceController, sessionController, agents, sessions and llm services");
901
+ if (typeof sessionController.modelCatalog !== "function") throw new Error("local host entry: the Host ACP Session View requires the official sessionController.modelCatalog service");
902
+ const modelService = new AcpSessionModelService({
903
+ modelCatalog: async () => await sessionController.modelCatalog(),
904
+ listProviders: () => llm.listProviders(),
905
+ listModels: async (providerId) => await llm.listModels(providerId),
906
+ resolveCallConfig: async (selection, signal) => {
907
+ const resolved = await llm.resolveCallConfig(selection, signal);
908
+ return {
909
+ provider: resolved.provider,
910
+ model: resolved.model,
911
+ ...resolved.reasoningEffort === void 0 ? {} : { reasoningEffort: resolved.reasoningEffort }
912
+ };
913
+ },
914
+ currentAgent: (sessionId) => agents.get(sessionId),
915
+ currentSession: (sessionId) => sessions.get(sessionId)
916
+ });
917
+ return {
918
+ async createWorkspace(path) {
919
+ try {
920
+ const result = await workspaceController.create({ path });
921
+ return {
922
+ kind: "created",
923
+ workspaceId: result.workspace.workspaceId,
924
+ path: result.workspace.path
925
+ };
926
+ } catch (error) {
927
+ return {
928
+ kind: "indeterminate",
929
+ code: remoteErrorCode(error) ?? "workspace/internal"
930
+ };
931
+ }
932
+ },
933
+ async createSession(workspaceId) {
934
+ try {
935
+ return {
936
+ kind: "created",
937
+ sessionId: (await sessionController.create({ workspaceId })).sessionId
938
+ };
939
+ } catch (error) {
940
+ const code = remoteErrorCode(error) ?? "session/internal";
941
+ if (code === "gateway/bad-request" || code === "workspace/not-found") return {
942
+ kind: "rejected",
943
+ code
944
+ };
945
+ const sessionId = remoteErrorSessionId(error);
946
+ if (code === "session/workspace-attach-failed" && sessionId !== void 0) return {
947
+ kind: "published-with-error",
948
+ sessionId,
949
+ code
950
+ };
951
+ return {
952
+ kind: "indeterminate",
953
+ code
954
+ };
955
+ }
956
+ },
957
+ resolveAgent: (sessionId) => sessionController.resolveAgent(sessionId),
958
+ currentAgent: (sessionId) => agents.get(sessionId),
959
+ currentSession: (sessionId) => sessions.get(sessionId),
960
+ modelOptions: async (agent, session) => await modelService.readOptions(agent, session),
961
+ selectModelOnly: async (agent, session, request, signal, stillCurrent) => await modelService.selectSessionOnly(agent, session, request, signal, stillCurrent),
962
+ imageLimits: () => attachments?.imageLimits,
963
+ readOutputImage: async (ref, signal) => {
964
+ if (attachments === void 0) throw new Error("local host entry: no official attachment store can read a committed output image");
965
+ const stored = await attachments.readImage(ref, signal);
966
+ return {
967
+ data: stored.data,
968
+ mediaType: stored.ref.mediaType
969
+ };
970
+ },
971
+ supportsImagePrompts: async () => {
972
+ if (attachments === void 0 || llm === void 0 || agentDefaultModel === void 0) return false;
973
+ try {
974
+ const route = agentDefaultModel.currentSelection();
975
+ if (route === void 0 || !attachments.imageLimits.mediaTypes.some((mediaType) => ACP_IMAGE_MEDIA_TYPES.includes(mediaType))) return false;
976
+ return (await llm.resolveModelInfo(route.provider, route.model)).inputModalities?.includes("image") === true;
977
+ } catch {
978
+ return false;
979
+ }
980
+ },
981
+ prompt: async (request, signal) => {
982
+ if (!request.content.some((part) => part.type === "image")) return await sessionController.prompt(request, signal);
983
+ signal.throwIfAborted();
984
+ const agent = agents.get(request.sessionId);
985
+ const session = sessions.get(request.sessionId);
986
+ if (agent === void 0 || session === void 0 || agent.session !== session || agent.model === void 0) throw imageRouteError("IMAGE_ROUTE_UNKNOWN", "the attached Agent route is unavailable for image input");
987
+ const route = agent.model.current();
988
+ if (route === void 0 || route.provider.length === 0 || route.model.length === 0 || llm === void 0) throw imageRouteError("IMAGE_ROUTE_UNKNOWN", "the attached Agent route is unavailable for image input");
989
+ let model;
990
+ try {
991
+ model = await llm.resolveModelInfo(route.provider, route.model);
992
+ } catch {
993
+ throw imageRouteError("IMAGE_ROUTE_UNKNOWN", "the attached Agent route could not be verified for image input");
994
+ }
995
+ if (model.inputModalities?.includes("image") !== true) throw imageRouteError("MODEL_DOES_NOT_SUPPORT_IMAGES", "the attached Agent route does not declare image input");
996
+ signal.throwIfAborted();
997
+ const currentAgent = agents.get(request.sessionId);
998
+ const currentSession = sessions.get(request.sessionId);
999
+ const currentRoute = currentAgent?.model?.current();
1000
+ if (currentAgent !== agent || currentSession !== session || agent.session !== session || currentRoute?.provider !== route.provider || currentRoute.model !== route.model) throw imageRouteError("IMAGE_ROUTE_CHANGED", "the attached Agent route changed during image capability verification");
1001
+ return await sessionController.prompt(request, signal);
1002
+ },
1003
+ cancelPending: (sessionId, agent, session, messageId) => {
1004
+ const liveAgent = agents.get(sessionId);
1005
+ const liveSession = sessions.get(sessionId);
1006
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return "stale";
1007
+ return agent.inbox.remove(messageId) === true ? "removed" : "not-pending";
1008
+ },
1009
+ pendingMessage: (sessionId, agent, session, messageId) => {
1010
+ const liveAgent = agents.get(sessionId);
1011
+ const liveSession = sessions.get(sessionId);
1012
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return "stale";
1013
+ const inbox = agent.inbox;
1014
+ return inbox.nextTurn.some((message) => message.id === messageId) || inbox.nextStep.some((message) => message.id === messageId) ? "pending" : "absent";
1015
+ },
1016
+ cancelCurrentTurn: (sessionId, agent, session, turn) => {
1017
+ const liveAgent = agents.get(sessionId);
1018
+ const liveSession = sessions.get(sessionId);
1019
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return "stale";
1020
+ const boundary = agents.turnBoundaryOf(session);
1021
+ if (boundary.openTurnStartSeq === null || boundary.lastTurn !== turn) return "not-current";
1022
+ if (agent.status !== "running") return "not-current";
1023
+ agent.cancel({ kind: "user" }, { keepInbox: true });
1024
+ return "addressed";
1025
+ },
1026
+ currentTurn: (sessionId, agent, session) => {
1027
+ const liveAgent = agents.get(sessionId);
1028
+ const liveSession = sessions.get(sessionId);
1029
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return { kind: "stale" };
1030
+ const boundary = agents.turnBoundaryOf(session);
1031
+ return {
1032
+ kind: "current",
1033
+ openTurn: boundary.openTurnStartSeq === null ? null : boundary.lastTurn
1034
+ };
1035
+ },
1036
+ /**
1037
+ * Subscribe the View owner to the exact Host facts a prompt flight is
1038
+ * correlated against. The Host Context, registries and Agent/Session objects
1039
+ * stay on this side: only the observed identity payloads are forwarded, and
1040
+ * the returned disposer removes exactly these listeners. The ONE approval
1041
+ * classification seat is registered with `prepend: true` so it runs AHEAD
1042
+ * of the TUI forwarding listener: a proven ACP-owned approval is answered
1043
+ * (or fail-closed) without ever reaching `next()`.
1044
+ */
1045
+ observePromptFacts(listener) {
1046
+ const disposers = [
1047
+ context.on("agent/inbox/inserted", (payload) => {
1048
+ listener.onInboxInserted(payload.agent, payload.message);
1049
+ }),
1050
+ context.on("agent/inbox/claimed", (payload) => {
1051
+ listener.onInboxClaimed(payload.agent, payload.message, payload.turn);
1052
+ }),
1053
+ context.on("agent/inbox/discarded", (payload) => {
1054
+ listener.onInboxDiscarded(payload.agent, payload.message);
1055
+ }),
1056
+ context.on("session/event", (session, event) => {
1057
+ listener.onSessionEvent(session, event);
1058
+ }),
1059
+ context.on("agent/error", (payload) => {
1060
+ listener.onAgentError(payload.agent, payload.turn);
1061
+ }),
1062
+ context.on("agent/disposed", (payload) => {
1063
+ listener.onAgentDisposed(payload.agent);
1064
+ }),
1065
+ context.on("approval/request", (request, next) => {
1066
+ return listener.onApprovalRequest({
1067
+ agent: request.agent,
1068
+ toolName: request.toolName,
1069
+ ...request.callId === void 0 ? {} : { callId: request.callId },
1070
+ ...request.reason === void 0 ? {} : { reason: request.reason },
1071
+ ...request.signal === void 0 ? {} : { signal: request.signal }
1072
+ }, async () => await next());
1073
+ }, { prepend: true })
1074
+ ];
1075
+ return () => {
1076
+ for (const dispose of disposers) dispose();
1077
+ };
1078
+ }
1079
+ };
1080
+ }
1081
+ /** A stable code from an official RemoteError without importing its class. */
1082
+ function remoteErrorCode(error) {
1083
+ if (typeof error === "object" && error !== null && "code" in error) {
1084
+ const code = error.code;
1085
+ if (typeof code === "string") return code;
1086
+ }
1087
+ }
1088
+ /** The authoritative created Session id an official `published-with-error` carries. */
1089
+ function remoteErrorSessionId(error) {
1090
+ if (typeof error === "object" && error !== null && "details" in error) {
1091
+ const sessionId = error.details?.sessionId;
1092
+ if (typeof sessionId === "string" && sessionId !== "") return sessionId;
1093
+ }
1094
+ }
1095
+ /**
1096
+ * Create the ONE Host-entry-owned ACP runtime controller.
1097
+ *
1098
+ * The controller owns no durable "enabled" flag: the ONLY authority is the live
1099
+ * `LocalAcpListener` handle plus its own `isListening()` (a real `net.Server`
1100
+ * listening with the exact saved socket inode). `getStatus` therefore reports
1101
+ * `enabled` only when the socket really is serving and `disabled` only when no
1102
+ * listener handle exists; a bind/close in flight is `changing`; a handle that is
1103
+ * no longer listening is a truthful `unavailable`. Every bind/close joins ONE
1104
+ * serialized promise chain so at most one transition runs at a time.
1105
+ */
1106
+ function createAcpController(options) {
1107
+ const { scope, maxConnections, diag, sessionAccess } = options;
1108
+ const views = sessionAccess === void 0 ? void 0 : new AcpSessionViewRegistry(diag);
1109
+ let listener;
1110
+ let tail = Promise.resolve();
1111
+ let inFlight = 0;
1112
+ let quiescing = false;
1113
+ const describe = () => {
1114
+ if (inFlight > 0) return { state: "changing" };
1115
+ if (listener === void 0) return { state: "disabled" };
1116
+ return listener.isListening() ? { state: "enabled" } : {
1117
+ state: "unavailable",
1118
+ reason: "the local ACP listener is not accepting connections"
1119
+ };
1120
+ };
1121
+ const apply = async (enabled) => {
1122
+ if (quiescing) return {
1123
+ state: "unavailable",
1124
+ reason: "the Host is shutting down"
1125
+ };
1126
+ inFlight += 1;
1127
+ try {
1128
+ const mutationBarrier = process.env.SPLIT_PROCESS_HOST_ACP_MUTATION_BARRIER;
1129
+ if (mutationBarrier !== void 0 && mutationBarrier !== "") {
1130
+ writeEntryRecord({
1131
+ m4a0: "qualification",
1132
+ processRole: "host",
1133
+ op: "acp-mutation-start",
1134
+ pid: process.pid
1135
+ });
1136
+ await waitForQualificationBarrier(mutationBarrier);
1137
+ }
1138
+ if (enabled) {
1139
+ if (listener !== void 0 && listener.isListening()) return { state: "enabled" };
1140
+ if (listener !== void 0) {
1141
+ const stale = listener;
1142
+ listener = void 0;
1143
+ try {
1144
+ await stale.close();
1145
+ } catch (error) {
1146
+ diag.warn("local-acp.error", {
1147
+ code: "LOCAL_ACP_CLOSE_FAILED",
1148
+ cause: String(error)
1149
+ });
1150
+ }
1151
+ }
1152
+ listener = await startLocalAcpListener({
1153
+ scope,
1154
+ maxConnections,
1155
+ diag,
1156
+ ...sessionAccess === void 0 ? {} : {
1157
+ sessionAccess,
1158
+ views
1159
+ }
1160
+ });
1161
+ return listener.isListening() ? { state: "enabled" } : {
1162
+ state: "unavailable",
1163
+ reason: "the local ACP listener failed to bind"
1164
+ };
1165
+ }
1166
+ if (listener === void 0) return { state: "disabled" };
1167
+ const current = listener;
1168
+ listener = void 0;
1169
+ try {
1170
+ await current.close();
1171
+ } catch (error) {
1172
+ diag.warn("local-acp.error", {
1173
+ code: "LOCAL_ACP_CLOSE_FAILED",
1174
+ cause: String(error)
1175
+ });
1176
+ return {
1177
+ state: "unavailable",
1178
+ reason: "the local ACP listener could not be closed"
1179
+ };
1180
+ }
1181
+ return { state: "disabled" };
1182
+ } finally {
1183
+ inFlight -= 1;
1184
+ }
1185
+ };
1186
+ const serialize = (operation) => {
1187
+ const run = tail.then(operation);
1188
+ tail = run.then(() => void 0, () => void 0);
1189
+ return run;
1190
+ };
1191
+ return {
1192
+ getStatus: async () => describe(),
1193
+ setEnabled: (enabled) => serialize(() => apply(enabled)),
1194
+ quiesce: () => {
1195
+ quiescing = true;
1196
+ },
1197
+ close: () => serialize(async () => {
1198
+ quiescing = true;
1199
+ if (listener !== void 0) {
1200
+ const current = listener;
1201
+ listener = void 0;
1202
+ try {
1203
+ await current.close();
1204
+ } catch (error) {
1205
+ diag.warn("local-acp.error", {
1206
+ code: "LOCAL_ACP_CLOSE_FAILED",
1207
+ cause: String(error)
1208
+ });
1209
+ }
1210
+ }
1211
+ const viewsToRetire = views;
1212
+ if (viewsToRetire !== void 0 && viewsToRetire.hasFactsObserver()) runDetached("local acp: shared fact subscription retirement", async () => {
1213
+ await viewsToRetire.whenHostWorkSettled();
1214
+ viewsToRetire.disposeFacts();
1215
+ }, { diag });
1216
+ return { state: "disabled" };
1217
+ }).then(() => void 0),
1218
+ cleanupSync: () => {
1219
+ listener?.cleanupSync();
1220
+ }
1221
+ };
1222
+ }
1223
+ /**
1224
+ * Apply the profile-owned ACP startup preference BEFORE the Host becomes Ready.
1225
+ *
1226
+ * `autoStart` is read from the SAME `ctx` that already settled the profile: a
1227
+ * missing settings service, a missing `pi-tui-acp-preferences` section or a
1228
+ * non-boolean value is a corrupted composition and fails Host startup loudly
1229
+ * (never "treated as Off"). A failing ACP enable is a bounded diagnostic: the
1230
+ * ACP listener is an optional add-on, so the Host keeps its Session/Agent/
1231
+ * Gateway graph and publishes Ready with the listener in whatever state the
1232
+ * controller truthfully reports. The diagnostic is a FIXED record (a failure
1233
+ * category plus the small state vocabulary), never an exception message or a
1234
+ * socket path.
1235
+ *
1236
+ * @param context - the Host context that already settled the profile.
1237
+ * @param controller - the entry-owned ACP runtime controller.
1238
+ * @param emit - the structured record sink (the entry emits on its control channel).
1239
+ */
1240
+ async function applyAcpStartupPreference(context, controller, emit = writeEntryRecord) {
1241
+ const settings = context.get("settings");
1242
+ if (settings === void 0 || typeof settings.describe !== "function") throw new Error("local host entry: the Host has no settings service, so the ACP startup preference cannot be read");
1243
+ const descriptor = (settings.describe() ?? []).find((entry) => entry.ns === ACP_STARTUP_PREFERENCE_NAMESPACE);
1244
+ if (descriptor === void 0) throw new Error("local host entry: the profile projects no \"pi-tui-acp-preferences\" settings section");
1245
+ const value = descriptor.value;
1246
+ const autoStart = typeof value === "object" && value !== null && !Array.isArray(value) ? value.autoStart : void 0;
1247
+ if (typeof autoStart !== "boolean") throw new Error("local host entry: \"pi-tui-acp-preferences.autoStart\" is not a boolean");
1248
+ if (!autoStart) return;
1249
+ const unavailable = (failure, state) => {
1250
+ emit({
1251
+ m4a0: "diagnostic",
1252
+ processRole: "host",
1253
+ pid: process.pid,
1254
+ code: "acp-autostart-unavailable",
1255
+ failure,
1256
+ ...state === void 0 ? {} : { state }
1257
+ });
1258
+ };
1259
+ if (controller === void 0) {
1260
+ unavailable("controller-missing");
1261
+ return;
1262
+ }
1263
+ let status;
1264
+ try {
1265
+ status = await controller.setEnabled(true);
1266
+ } catch {
1267
+ unavailable("mutation-failed");
1268
+ return;
1269
+ }
1270
+ if (status.state !== "enabled") {
1271
+ unavailable("not-enabled", status.state);
1272
+ return;
1273
+ }
1274
+ emit({
1275
+ m4a0: "acp-autostart",
1276
+ processRole: "host",
1277
+ pid: process.pid,
1278
+ phase: "pre-ready",
1279
+ status: "enabled"
1280
+ });
1281
+ }
685
1282
  /**
686
1283
  * Publish the authenticated identity and private launch material, then commit
687
1284
  * the registry as the Ready step. The route is registered before the registry
688
1285
  * so no Client can observe a registry whose identity route is missing.
689
1286
  */
690
- async function publishLocalHost(context, scope, processStarttime) {
1287
+ async function publishLocalHost(context, scope, hostIdentity, seat, acpController) {
691
1288
  const connection = context.get("connection");
692
1289
  if (connection === void 0 || typeof connection.authenticatedUrl !== "function" || typeof connection.fetch?.register !== "function") throw new Error("local host entry: the official Connection service is not live");
693
1290
  const webServer = context.get("webServer");
694
1291
  if (webServer === void 0 || webServer.host !== "127.0.0.1" || webServer.port < 1) throw new Error("local host entry: the official webserver is not a bound loopback listener");
1292
+ const webAccess = context.get(PI_TUI_WEB_ACCESS_NAMESPACE);
1293
+ if (webAccess === void 0) throw new Error("local host entry: the private piTuiWebAccess Host service is not live");
695
1294
  const origin = webServer.getOrigin();
696
1295
  if (!origin.startsWith("http://127.0.0.1:") || !/^\d+$/u.test(origin.slice(17))) throw new Error("local host entry: B1 requires one canonical loopback HTTP origin");
697
1296
  await waitForRefusal(`${origin}/connect`);
698
1297
  const instanceId = randomUUID();
699
- const identity = {
700
- schema: 1,
1298
+ const shared = {
701
1299
  scopeId: scope.scopeId,
702
1300
  profileRealpath: scope.profileRealpath,
703
1301
  instanceId,
704
1302
  hostPid: process.pid,
705
- hostStarttime: processStarttime,
706
1303
  origin,
707
1304
  protocol: LOCAL_PROTOCOL,
708
1305
  bundleVersion: scope.bundleVersion,
709
1306
  dshVersion: scope.dshVersion,
710
1307
  buildId: scope.buildId
711
1308
  };
1309
+ const identity = buildHostInstanceRecord(shared, hostIdentity);
712
1310
  const connectUrl = connection.authenticatedUrl(`${origin}/connect`);
713
1311
  const connectProbe = new URL(connectUrl);
714
1312
  if (connectProbe.origin !== origin || connectProbe.pathname !== "/connect" || connectProbe.searchParams.getAll("token").length !== 1 || [...connectProbe.searchParams.keys()].length !== 1) throw new Error("local host entry: the Connection owner returned an unexpected launch URL");
715
- const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-CDaQHA_R.mjs");
1313
+ const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-egN4_gsQ.mjs");
716
1314
  writeLaunchMaterial(scope, identity, {
717
1315
  schema: 1,
718
1316
  instanceId,
719
1317
  connectUrl
720
1318
  });
721
- let unregister;
1319
+ let unregisterIdentity;
1320
+ let unregisterWorkspaceObject;
1321
+ let unregisterAcpStatus;
1322
+ let unregisterWebControl;
722
1323
  try {
723
- unregister = connection.fetch.register({
1324
+ unregisterIdentity = connection.fetch.register({
724
1325
  path: "/api/pi-tui.local-host",
725
1326
  methods: ["GET"],
726
1327
  requestBody: "buffered",
@@ -729,21 +1330,72 @@ async function publishLocalHost(context, scope, processStarttime) {
729
1330
  "cache-control": "no-store"
730
1331
  } })
731
1332
  });
1333
+ unregisterWorkspaceObject = connection.fetch.register({
1334
+ path: LOCAL_WORKSPACE_OBJECT_ROUTE,
1335
+ methods: ["POST"],
1336
+ requestBody: "buffered",
1337
+ fetch: createWorkspaceObjectHandler(instanceId)
1338
+ });
1339
+ unregisterAcpStatus = connection.fetch.register({
1340
+ path: LOCAL_ACP_STATUS_ROUTE,
1341
+ methods: ["GET"],
1342
+ requestBody: "buffered",
1343
+ fetch: createLocalAcpStatusHandler(instanceId, acpController)
1344
+ });
1345
+ unregisterWebControl = connection.fetch.register({
1346
+ path: LOCAL_WEB_CONTROL_ROUTE,
1347
+ methods: ["GET", "POST"],
1348
+ requestBody: "buffered",
1349
+ fetch: createLocalWebControlHandler(instanceId, webAccess)
1350
+ });
732
1351
  await waitForRefusal(`${origin}/api/pi-tui.local-host`);
1352
+ await waitForRefusal(`${origin}${LOCAL_WORKSPACE_OBJECT_ROUTE}`, 1e4, {
1353
+ method: "POST",
1354
+ headers: { "content-type": "application/json" },
1355
+ body: JSON.stringify({
1356
+ instanceId,
1357
+ path: scope.profileRealpath
1358
+ })
1359
+ });
1360
+ await waitForRefusal(`${origin}${LOCAL_ACP_STATUS_ROUTE}`);
1361
+ await waitForRefusal(`${origin}${LOCAL_WEB_CONTROL_ROUTE}`);
1362
+ await waitForRefusal(`${origin}${LOCAL_WEB_CONTROL_ROUTE}`, 1e4, {
1363
+ method: "POST",
1364
+ headers: { "content-type": "application/json" },
1365
+ body: JSON.stringify({
1366
+ schema: 1,
1367
+ instanceId,
1368
+ op: "url"
1369
+ })
1370
+ });
1371
+ seat.assertCurrent();
1372
+ assertRecordedHostKernelIdentityCurrent(identity);
733
1373
  writeLocalRecord(scope, identity);
734
1374
  const barrier = process.env.SPLIT_PROCESS_HOST_PUBLISH_BARRIER;
735
1375
  if (barrier !== void 0 && barrier !== "") await waitForQualificationBarrier(barrier);
736
1376
  } catch (error) {
737
1377
  try {
738
- await unregister?.();
1378
+ await unregisterWebControl?.();
1379
+ } catch {}
1380
+ try {
1381
+ await unregisterAcpStatus?.();
1382
+ } catch {}
1383
+ try {
1384
+ await unregisterWorkspaceObject?.();
1385
+ } catch {}
1386
+ try {
1387
+ await unregisterIdentity?.();
739
1388
  } catch {}
740
1389
  cleanupOwnedFiles(scope, instanceId);
741
1390
  throw error;
742
1391
  }
743
1392
  return {
744
1393
  identity,
745
- async unregisterIdentity() {
746
- await unregister?.();
1394
+ async unregisterRoutes() {
1395
+ await unregisterWebControl?.();
1396
+ await unregisterAcpStatus?.();
1397
+ await unregisterWorkspaceObject?.();
1398
+ await unregisterIdentity?.();
747
1399
  }
748
1400
  };
749
1401
  }
@@ -760,6 +1412,7 @@ async function publishLocalHost(context, scope, processStarttime) {
760
1412
  async function runLocalHostEntry(options) {
761
1413
  const owned = {};
762
1414
  process.once("exit", () => {
1415
+ owned.acpController?.cleanupSync();
763
1416
  if (owned.scopeDir !== void 0 && owned.scratchDir !== void 0) removeOwnedScratch(owned.scopeDir, owned.scratchDir);
764
1417
  });
765
1418
  try {
@@ -779,13 +1432,13 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
779
1432
  const scope = scopeFromInstalledProfile({
780
1433
  dshHome,
781
1434
  profileDir: dsh.resolveProfileDir(options.profile, dshHome),
782
- packageRoot: installedPackageRootFromEntry(import.meta.url),
1435
+ packageRoot: installedPackageRootFromEntry(process.argv[1] === void 0 ? import.meta.url : pathToFileURL(process.argv[1]).href),
783
1436
  dshVersion: readInstalledDshVersion(options.dshAnchor)
784
1437
  });
785
1438
  scratchOwner.scopeDir = scope.dir;
786
1439
  let seat;
787
1440
  try {
788
- seat = await bindProcessSeat(scope.hostSocketName, "HOST_ALREADY_OWNED");
1441
+ seat = await bindProfileKernelSeat(scope, "host", "HOST_ALREADY_OWNED");
789
1442
  } catch (error) {
790
1443
  if (error instanceof LocalScopeError && error.code === "HOST_ALREADY_OWNED") {
791
1444
  writeEntryRecord({
@@ -802,13 +1455,15 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
802
1455
  let handle;
803
1456
  let registration;
804
1457
  let liveness;
1458
+ let acpController;
805
1459
  try {
806
1460
  const scratchDir = mkdtempSync(join(scope.dir, "host-scratch-"));
807
1461
  scratchOwner.scratchDir = scratchDir;
808
1462
  if (process.env.SPLIT_PROCESS_HOST_FORCE_EARLY_EXIT === "1") process.exit(1);
809
1463
  const overlayPath = join(scratchDir, "host-only.patch.yml");
810
1464
  writeFileSync(overlayPath, HOST_ONLY_PATCH, { mode: 384 });
811
- const processStartIdentity = readLinuxStarttime();
1465
+ const hostProcessIdentity = readHostProcessIdentity();
1466
+ const processStartIdentity = hostProcessIdentity.schema === 1 ? hostProcessIdentity.hostStarttime : void 0;
812
1467
  if (process.env.SPLIT_PROCESS_HOST_FORCE_BOOT_FAILURE === "before-profile") throw new Error("local host entry: qualification forced pre-profile failure");
813
1468
  process.env.DSH_PI_TUI_ROLE = "host";
814
1469
  if (process.argv[1] !== void 0) process.env.DSH_PI_TUI_HOST_ENTRY = realpathSync(process.argv[1]);
@@ -828,8 +1483,26 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
828
1483
  pid: process.pid,
829
1484
  phase: "profile-booted"
830
1485
  });
831
- const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-DilsvA6f.mjs");
1486
+ const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-MVxks641.mjs");
832
1487
  await settleHostEntries(handle.ctx);
1488
+ const settled = handle;
1489
+ if (settled === void 0) throw new Error("local host entry: the profile handle disappeared before migration");
1490
+ const profileContext = settled.ctx.get("profileContext");
1491
+ if (profileContext === void 0) throw new Error("local host entry: the Host profile context is missing");
1492
+ const { migrateProfileTuiPreferences } = await import("./profile-preferences-migration-CThz4rHH.mjs");
1493
+ await migrateProfileTuiPreferences({
1494
+ patchPath: profileContext.patchPath,
1495
+ configEditor: settled.ctx.get("configEditor"),
1496
+ forms: settled.ctx.get("settings"),
1497
+ home: profileContext.home,
1498
+ resolvePreset: async (id) => {
1499
+ const presets = settled.ctx.get("agentPresets");
1500
+ if (presets === void 0) throw new Error("agent presets unavailable in this deployment");
1501
+ const resolved = await presets.resolve(id);
1502
+ if (resolved.broken !== void 0) throw Object.assign(new Error(resolved.broken), { code: "agent-preset/invalid" });
1503
+ },
1504
+ diag: createEntryDiag("host")
1505
+ });
833
1506
  await applyWebStartupPreference(handle.ctx);
834
1507
  const status = collectHostEntryStatus(handle.ctx, {
835
1508
  profile: options.profile,
@@ -839,6 +1512,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
839
1512
  let published;
840
1513
  let stopping;
841
1514
  let shuttingDown = false;
1515
+ let controlChannel;
842
1516
  let resolveStopped;
843
1517
  const stopped = new Promise((resolve) => {
844
1518
  resolveStopped = resolve;
@@ -846,8 +1520,17 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
846
1520
  const stop = (code, owner) => {
847
1521
  if (stopping !== void 0) return stopping;
848
1522
  shuttingDown = true;
1523
+ acpController?.quiesce();
849
1524
  stopping = (async () => {
850
1525
  const errors = [];
1526
+ try {
1527
+ await acpController?.close();
1528
+ } catch (error) {
1529
+ errors.push({
1530
+ step: "local-acp-close",
1531
+ error
1532
+ });
1533
+ }
851
1534
  try {
852
1535
  liveness?.close();
853
1536
  } catch (error) {
@@ -865,8 +1548,8 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
865
1548
  error
866
1549
  });
867
1550
  }
868
- try {
869
- await owner.unregisterIdentity();
1551
+ if (owner !== void 0) try {
1552
+ await owner.unregisterRoutes();
870
1553
  } catch (error) {
871
1554
  errors.push({
872
1555
  step: "identity-unregister",
@@ -881,7 +1564,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
881
1564
  error
882
1565
  });
883
1566
  }
884
- cleanupOwnedFiles(scope, owner.identity.instanceId);
1567
+ if (owner !== void 0) cleanupOwnedFiles(scope, owner.identity.instanceId);
885
1568
  if (errors.length > 0) {
886
1569
  const first = errors[0];
887
1570
  const primary = first.error instanceof Error ? first.error : new Error(String(first.error));
@@ -906,6 +1589,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
906
1589
  }
907
1590
  const stopBarrier = process.env.SPLIT_PROCESS_HOST_STOP_BARRIER;
908
1591
  if (stopBarrier !== void 0 && stopBarrier !== "") await waitForQualificationBarrier(stopBarrier);
1592
+ controlChannel?.release();
909
1593
  resolveStopped?.();
910
1594
  })();
911
1595
  return stopping;
@@ -949,7 +1633,33 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
949
1633
  process.removeListener("SIGTERM", onSigterm);
950
1634
  process.removeListener("SIGINT", onSigint);
951
1635
  };
952
- const publishedHost = await publishLocalHost(handle.ctx, scope, processStartIdentity);
1636
+ const maxConnections = parseAcpMaxConnections(process.env.DSH_PI_TUI_ACP_MAX_CONNECTIONS);
1637
+ const sessionAccess = createHostAcpSessionAccess(handle.ctx);
1638
+ acpController = createAcpController({
1639
+ scope,
1640
+ maxConnections,
1641
+ diag: createEntryDiag("host"),
1642
+ sessionAccess
1643
+ });
1644
+ scratchOwner.acpController = acpController;
1645
+ handle.ctx.provide("piTuiAcpOwner", acpController);
1646
+ await applyAcpStartupPreference(handle.ctx, acpController);
1647
+ const acpBoundBarrier = process.env.SPLIT_PROCESS_HOST_ACP_BOUND_BARRIER;
1648
+ if (acpBoundBarrier !== void 0 && acpBoundBarrier !== "") {
1649
+ writeEntryRecord({
1650
+ m4a0: "qualification",
1651
+ processRole: "host",
1652
+ op: "acp-bound-barrier",
1653
+ pid: process.pid
1654
+ });
1655
+ await waitForQualificationBarrier(acpBoundBarrier);
1656
+ }
1657
+ if (pendingStop !== void 0) {
1658
+ await stop(pendingStop, void 0);
1659
+ releaseSignalAdmission();
1660
+ return;
1661
+ }
1662
+ const publishedHost = await publishLocalHost(handle.ctx, scope, hostProcessIdentity, seat, acpController);
953
1663
  published = publishedHost;
954
1664
  registration = publishedHost;
955
1665
  process.once("exit", () => {
@@ -983,7 +1693,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
983
1693
  liveness: initialLiveness,
984
1694
  localHost: publishedHost.identity
985
1695
  });
986
- attachEntryControl(async (request) => {
1696
+ controlChannel = attachEntryControl(async (request) => {
987
1697
  if (request.op === "status") {
988
1698
  const snapshot = await liveness.snapshot();
989
1699
  writeEntryRecord({
@@ -1016,7 +1726,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1016
1726
  processRole: "host",
1017
1727
  phase: "after-boot",
1018
1728
  pid: process.pid,
1019
- ...error instanceof LocalScopeError ? { code: error.code } : {},
1729
+ ...error instanceof LocalScopeError || error instanceof LocalAcpError ? { code: error.code } : {},
1020
1730
  error: error instanceof Error ? error.message : String(error),
1021
1731
  ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1022
1732
  });
@@ -1037,6 +1747,19 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1037
1747
  error: priorCleanupFailure
1038
1748
  });
1039
1749
  }
1750
+ try {
1751
+ await acpController?.close();
1752
+ } catch (cleanupError) {
1753
+ priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
1754
+ writeEntryRecord({
1755
+ m4a0: "cleanup-failure",
1756
+ processRole: "host",
1757
+ phase: "after-boot",
1758
+ pid: process.pid,
1759
+ step: "local-acp-close",
1760
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
1761
+ });
1762
+ }
1040
1763
  try {
1041
1764
  liveness?.close();
1042
1765
  } catch (cleanupError) {
@@ -1051,7 +1774,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1051
1774
  });
1052
1775
  }
1053
1776
  try {
1054
- await registration?.unregisterIdentity();
1777
+ await registration?.unregisterRoutes();
1055
1778
  } catch (cleanupError) {
1056
1779
  priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
1057
1780
  writeEntryRecord({
@@ -1167,11 +1890,11 @@ if (import.meta.main) try {
1167
1890
  processRole: "host",
1168
1891
  phase: "startup",
1169
1892
  pid: process.pid,
1170
- ...error instanceof LocalScopeError ? { code: error.code } : {},
1893
+ ...error instanceof LocalScopeError || error instanceof LocalAcpError ? { code: error.code } : {},
1171
1894
  error: error instanceof Error ? error.message : String(error),
1172
1895
  ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1173
1896
  });
1174
1897
  process.exit(1);
1175
1898
  }
1176
1899
  //#endregion
1177
- export { HOST_ONLY_PATCH, applyWebStartupPreference, drainHmrTransactions, finishHostFailureCleanup, runLocalHostEntry };
1900
+ export { HOST_ONLY_PATCH, applyAcpStartupPreference, applyWebStartupPreference, createAcpController, createHostAcpSessionAccess, drainHmrTransactions, finishHostFailureCleanup, runLocalHostEntry };