@xmoon76/dsh-pi-tui 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.en.md +64 -26
  2. package/README.md +64 -26
  3. package/cordis.patch.yml +13 -0
  4. package/dist/acp-stdio.mjs +151 -0
  5. package/dist/{bootstrap-C9nl6e13.mjs → bootstrap-CVyHGQDX.mjs} +22330 -6888
  6. package/dist/browser-CDUSHIIr.mjs +76 -0
  7. package/dist/builtins.mjs +2 -2
  8. package/dist/{client-bootstrap-CGezi85O.mjs → client-bootstrap-4UoeVIHE.mjs} +2407 -1830
  9. package/dist/client-runtime-BHBlVUf5.mjs +1376 -0
  10. package/dist/{daemon-launcher-H_1r5Cqs.mjs → daemon-launcher-DxIgjBHW.mjs} +1551 -57
  11. package/dist/daemon-launcher.d.mts +85 -14
  12. package/dist/daemon-launcher.mjs +2 -2
  13. package/dist/diagnostics-Db5iVcuJ.mjs +123 -0
  14. package/dist/{entry-control-jBfKn1qO.mjs → entry-control-BDLZgg4m.mjs} +1 -1
  15. package/dist/{extensions-6a5vvJUT.mjs → extensions-Dx7ncPNA.mjs} +1 -4
  16. package/dist/extensions.mjs +1 -1
  17. package/dist/handoff-BjoEy3f8.mjs +106 -0
  18. package/dist/history-search-limits-Cx2UvRC2.mjs +16 -0
  19. package/dist/history-search-remote-BHuoellG.mjs +113 -0
  20. package/dist/history-search-remote-BzXdvrxk.mjs +26 -0
  21. package/dist/history-search-seat-BcHJTpeB.mjs +639 -0
  22. package/dist/history-search-seat-rZcq0XV6.mjs +639 -0
  23. package/dist/{host-bootstrap-MVxks641.mjs → host-bootstrap-BfnufpnW.mjs} +37 -72
  24. package/dist/{host-foundation-probe-DK7n5jDu.mjs → host-foundation-probe-DlD8-N_Q.mjs} +2 -2
  25. package/dist/host-runtime.mjs +5611 -290
  26. package/dist/index.d.mts +13 -6
  27. package/dist/index.mjs +22766 -6893
  28. package/dist/installed-dsh-BjUiJSwR.mjs +142 -0
  29. package/dist/interaction-port-D1Yv9zgu.mjs +45 -0
  30. package/dist/local-acp-control-CC5z4Xbq.mjs +304 -0
  31. package/dist/local-acp-endpoint-D1jYdJdv.mjs +41 -0
  32. package/dist/local-acp-listener-Cmgb5M0H.mjs +9493 -0
  33. package/dist/local-acp-status-B_25Q6kU.mjs +101 -0
  34. package/dist/local-client.mjs +719 -93
  35. package/dist/local-daemon-control-BFJAC8Kg.mjs +2199 -0
  36. package/dist/local-daemon-control-Bm3imctD.mjs +2101 -0
  37. package/dist/{local-discovery-BPZw1wEd.mjs → local-discovery-BMhaGIiJ.mjs} +254 -544
  38. package/dist/{local-discovery-BMoNXZjJ.mjs → local-discovery-Ba7_-NNC.mjs} +1 -1
  39. package/dist/{local-discovery-Bq3jLAn1.mjs → local-discovery-QSbFpjK2.mjs} +301 -544
  40. package/dist/local-host.mjs +970 -501
  41. package/dist/local-profile-daemon-admin-otpm69R6.mjs +469 -0
  42. package/dist/{local-scope-DEuGAy8l.mjs → local-scope-5DEKA_lW.mjs} +1075 -31
  43. package/dist/{local-transport-X4ZCe2uE.mjs → local-transport-DeWmdZ5E.mjs} +14 -3
  44. package/dist/{local-web-control-DKWtXIkr.mjs → local-web-control-Dny93N-r.mjs} +10 -7
  45. package/dist/{local-workspace-object-D06GL0UO.mjs → local-workspace-object-D0RVQt8U.mjs} +33 -9
  46. package/dist/model-selection-CYlqg2DV.mjs +83 -0
  47. package/dist/native-client-domains-Dg4srzYt.mjs +2 -0
  48. package/dist/native-client.d.mts +735 -0
  49. package/dist/native-client.mjs +3534 -0
  50. package/dist/{open-CmOBxSjN.mjs → open-QQva8-ar.mjs} +24 -20
  51. package/dist/{pi-tui-remote-contribution-Do8ECrUy.mjs → pi-tui-remote-contribution-565wiLWp.mjs} +741 -150
  52. package/dist/preferences.mjs +1 -1
  53. package/dist/{profile-preferences-migration-CThz4rHH.mjs → profile-preferences-migration-CNOWIdnr.mjs} +1 -1
  54. package/dist/{profile-preferences-migration-BfUGdPZx.mjs → profile-preferences-migration-IrnXcJWK.mjs} +10 -8
  55. package/dist/{prompt-sections-DXmjB58H.mjs → prompt-sections-Bi-9_Gr_.mjs} +28 -10
  56. package/dist/{prompt-sections-DUKmWb8g.mjs → prompt-sections-DFS1dqsY.mjs} +342 -56
  57. package/dist/{dist-BFgC-5tL.mjs → recall-scope-9Nuoto_i.mjs} +353 -1
  58. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  59. package/dist/schema-CCLvDa7Q.mjs +177 -0
  60. package/dist/{schema-qE_P09zJ.mjs → schema-t97l3aK8.mjs} +56 -3
  61. package/dist/{session-DC0XQr5O.mjs → session-Cs8iLCEx.mjs} +784 -342
  62. package/dist/{session-Cihe8PPS.mjs → session-EBRZF6Ow.mjs} +783 -341
  63. package/dist/session-create-facts-CkfG5DpQ.mjs +20 -0
  64. package/dist/{startup-CarQxWwi.d.mts → startup-Dti3Udne.d.mts} +30 -3
  65. package/dist/{startup-CARqn3kV.mjs → startup-UtFQSDe_.mjs} +90 -15
  66. package/dist/startup.d.mts +2 -2
  67. package/dist/startup.mjs +1 -1
  68. package/dist/task-read-remote-DRtkXDrZ.mjs +1083 -0
  69. package/dist/{terminal-progress-source-D4DHyXDo.mjs → terminal-progress-source-VsczdXA-.mjs} +610 -335
  70. package/dist/{transcript-view-a7cROAaI.mjs → transcript-view-B6vCnukn.mjs} +2284 -1166
  71. package/dist/{transcript-view-hvNVkPtv.mjs → transcript-view-DSSdE2vK.mjs} +2191 -765
  72. package/dist/write-failure-xNKczXH7.mjs +189 -0
  73. package/package.json +25 -8
  74. package/dist/local-acp-listener-CNkguN5-.mjs +0 -2566
  75. package/dist/local-daemon-control-Bg9s2aYi.mjs +0 -1424
  76. package/dist/local-daemon-control-Cu_4FIdd.mjs +0 -1585
  77. package/dist/local-profile-daemon-admin-AXgVH-6y.mjs +0 -91
  78. package/dist/preset-BcWqOtY7.mjs +0 -46
@@ -1,447 +1,342 @@
1
1
  #!/usr/bin/env node
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-DEuGAy8l.mjs";
3
- import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-jBfKn1qO.mjs";
2
+ import { T as createWin32StopWaiter, _ as scopeFromInstalledProfile, d as installedPackageRootFromEntry, g as removeOwnedScratch, n as LocalScopeError, o as bindProfileKernelSeat, p as readInstalledDshVersion, t as LOCAL_PROTOCOL } from "./local-scope-5DEKA_lW.mjs";
3
+ import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-BDLZgg4m.mjs";
4
+ import { _ as AcpSessionModelService, a as ACP_IMAGE_MEDIA_TYPES, c as AcpSessionViewRegistry, d as EMPTY_COMMAND_CATALOG, f as AcpScopedMcpError, g as stalePolicy, h as AcpSessionPolicyService, i as startLocalAcpListener, l as AcpSystemPromptAppendError, m as retireAcpScopedMcp, o as ACP_SYSTEM_PROMPT_SECTION_NAME, p as mountAcpScopedMcp, r as parseAcpMaxConnections, s as ACP_SYSTEM_PROMPT_SECTION_ORDER, t as LocalAcpError, u as AcpHostCommandError, v as LOCAL_ACP_STATUS_ROUTE, x as isAbsolutePath, y as createLocalAcpStatusHandler } from "./local-acp-listener-Cmgb5M0H.mjs";
5
+ import { t as publishedSessionIdOfCreateError } from "./session-create-facts-CkfG5DpQ.mjs";
6
+ import { a as scrubProgramResumeEnvironment } from "./handoff-BjoEy3f8.mjs";
4
7
  import { t as PI_TUI_WEB_ACCESS_ROWS } from "./web-roster-Dis7BhrA.mjs";
5
8
  import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
6
9
  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 createLocalAcpStatusHandler, i as startLocalAcpListener, o as AcpSessionViewRegistry, r as parseAcpMaxConnections, s as LOCAL_ACP_STATUS_ROUTE, t as LocalAcpError } from "./local-acp-listener-CNkguN5-.mjs";
9
- import { a as buildHostInstanceRecord, d as readHostProcessIdentity, o as cleanupOwnedFiles, r as assertRecordedHostKernelIdentityCurrent } from "./local-discovery-Bq3jLAn1.mjs";
10
+ import { n as createWorkspaceObjectHandler, t as LOCAL_WORKSPACE_OBJECT_ROUTE } from "./local-workspace-object-D0RVQt8U.mjs";
11
+ import { a as buildHostInstanceRecord, d as readHostProcessIdentity, o as cleanupOwnedFiles, r as assertRecordedHostKernelIdentityCurrent } from "./local-discovery-QSbFpjK2.mjs";
10
12
  import { createRequire } from "node:module";
11
13
  import { randomUUID } from "node:crypto";
12
- import { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
13
- import { join } from "node:path";
14
+ import { existsSync, mkdtempSync, realpathSync, statSync, writeFileSync } from "node:fs";
15
+ import { join, posix } from "node:path";
14
16
  import { pathToFileURL } from "node:url";
15
- //#region src/app/remote-process/host-activity.ts
16
- /** Every source key always present in a snapshot. */
17
- const HOST_ACTIVITY_SOURCES = [
18
- "agent",
19
- "jobs",
20
- "goal",
21
- "schedule",
22
- "pending",
23
- "write",
24
- "other"
25
- ];
26
- /** Cordis `FiberState` values used by Loader source qualification. */
27
- const FIBER_PENDING = 0;
28
- const FIBER_LOADING = 1;
29
- const FIBER_ACTIVE = 2;
30
- const FIBER_FAILED = 3;
31
- const FIBER_DISPOSED = 4;
32
- const FIBER_UNLOADING = 5;
17
+ import { userInfo } from "node:os";
18
+ //#region src/app/remote-process/host-environment.ts
33
19
  /**
34
- * Loader rows explicitly qualified as passive in the pinned stock Host
35
- * composition, bound to BOTH their row id and the exact plugin identity.
36
- * The map is the rc.4 Host-only roster that was reviewed as passive or as
37
- * belonging to one of the observer's own source families; `schedule` is
38
- * qualified when a profile mounts the official Schedule row. A row id reused
39
- * with a different plugin, an unknown active row, a custom plugin or a future
40
- * official autonomous service fails closed as an unqualified Host source.
20
+ * Host process startup environment bootstrap.
21
+ *
22
+ * A daemon Host is started by an OS manager or by a detached spawn, not by an
23
+ * interactive login shell, so its inherited PATH can omit the user tool
24
+ * directories a shell would have added. This module answers ONE question at
25
+ * Host startup: given the inherited environment, which common tool directories
26
+ * that already exist should be appended to this process's PATH?
27
+ *
28
+ * It never imports a shell, a shell snapshot, DSH, Cordis, Client or TUI code,
29
+ * and performs no I/O when loaded. The real process entry calls it once before
30
+ * the official profile boot; only `process.env.PATH` changes. The inherited
31
+ * environment keeps its exact bytes and order, other variables are never read
32
+ * back, written or imported, and a missing directory is a normal skip.
33
+ *
34
+ * `inherit` (`DSH_PI_TUI_HOST_PATH_MODE=inherit`) skips all candidate work and
35
+ * leaves PATH alone. An unrecognized mode is a startup failure with a fixed
36
+ * message that never echoes the supplied value.
37
+ *
38
+ * @module app/remote-process/host-environment
41
39
  */
42
- const QUALIFIED_HOST_ROWS = new Map(`include=cordis:include plugin-manager=@deepseek-ai/dsh-plugin-manager
43
- timer=@deepseek-ai/cordis-plugin-timer hmr=@deepseek-ai/dsh-hmr
44
- llm=@deepseek-ai/dsh-llm deepseek-llm-api-extensions=@deepseek-ai/dsh-deepseek-llm-api-extensions
45
- session=@deepseek-ai/dsh-session session-log-deepseek=@deepseek-ai/dsh-session-log-deepseek
46
- typert=@deepseek-ai/dsh-typert-registry typert-loader=@deepseek-ai/dsh-typert-loader
47
- typert-gateway=@deepseek-ai/dsh-api-gateway remote-access=@deepseek-ai/dsh-api-remote-access
48
- session-title=@deepseek-ai/dsh-session-title session-title-llm=@deepseek-ai/dsh-session-title-first-prompt-llm
49
- user-questions=@deepseek-ai/dsh-user-questions agent=@deepseek-ai/dsh-agent
50
- plugin-package-inventory-deepseek=@deepseek-ai/dsh-plugin-package-inventory-deepseek agent-default-model=@deepseek-ai/dsh-agent-default-model
51
- jobs=@deepseek-ai/dsh-jobs-local llm-retry=@deepseek-ai/dsh-llm-retry
52
- config-editor=@deepseek-ai/dsh-config-editor settings=@deepseek-ai/dsh-settings
53
- authorization=@deepseek-ai/dsh-authorization deepseek-account=@deepseek-ai/dsh-deepseek-account
54
- credentials=@deepseek-ai/dsh-credentials-local llm-pi-ai=@deepseek-ai/dsh-llm-pi-ai
55
- session-persistence-jsonl=@deepseek-ai/dsh-session-persistence-jsonl attachment-local=@deepseek-ai/dsh-attachment-local
56
- session-query-sqlite=@deepseek-ai/dsh-session-query-sqlite working-directory=@deepseek-ai/dsh-working-directory
57
- tool-working-directory=@deepseek-ai/dsh-tool-working-directory session-projection=@deepseek-ai/dsh-session-projection
58
- storage=@deepseek-ai/dsh-storage storage-json=@deepseek-ai/dsh-storage-json
59
- storage-domain=@deepseek-ai/dsh-storage-domain session-projection-cache=@deepseek-ai/dsh-session-projection-cache
60
- otel=@deepseek-ai/dsh-otel session-telemetry-otel=@deepseek-ai/dsh-session-telemetry-otel
61
- subprocess=@deepseek-ai/dsh-subprocess-local sandbox=@deepseek-ai/dsh-sandbox-local
62
- sandbox-policy=@deepseek-ai/dsh-sandbox-policy bash-sandbox=@deepseek-ai/dsh-bash-sandbox
63
- approval=@deepseek-ai/dsh-user-approval permission=@deepseek-ai/dsh-permission-presets
64
- shell-env=@deepseek-ai/dsh-shell-env fs-observation-policy=@deepseek-ai/dsh-fs-observation-policy
65
- skill=@deepseek-ai/dsh-skill commands=@deepseek-ai/dsh-commands
66
- command-feedback=@deepseek-ai/dsh-command-feedback goal=@deepseek-ai/dsh-goal
67
- goal-round-driver=@deepseek-ai/dsh-goal-round-driver token-meter=@deepseek-ai/dsh-token-meter
68
- subagent=@deepseek-ai/dsh-subagent subagent-spawn-in-process=@deepseek-ai/dsh-subagent-spawn-in-process
69
- subagent-fork-in-process=@deepseek-ai/dsh-subagent-fork-in-process ptc-runtime=@deepseek-ai/dsh-ptc-runtime-node
70
- timeout-policy=@deepseek-ai/dsh-tool-call-timeout-policy spill-local=@deepseek-ai/dsh-spill-local
71
- spill-policy=@deepseek-ai/dsh-spill-policy session-checkpoint-policy=@deepseek-ai/dsh-session-checkpoint-policy
72
- image-offload=@deepseek-ai/dsh-compaction-image-offload repeat-tool-reminder=@deepseek-ai/dsh-repeat-tool-reminder
73
- web=@deepseek-ai/dsh-web web-search-deepseek=@deepseek-ai/dsh-web-search-deepseek
74
- web-deepseek-api=@deepseek-ai/dsh-web-deepseek-api web-fetch-http=@deepseek-ai/dsh-web-fetch-http
75
- mcp-resources=@deepseek-ai/dsh-mcp-resources tools=@deepseek-ai/dsh-tools
76
- system-prompt=@deepseek-ai/dsh-system-prompt agent-loop=@deepseek-ai/dsh-agent-loop
77
- fs-sandbox=@deepseek-ai/dsh-fs-sandbox llm-deepseek=@deepseek-ai/dsh-llm-deepseek-api-key
78
- llm-deepseek-account=@deepseek-ai/dsh-llm-deepseek-account tui-startup=@xmoon76/dsh-pi-tui/startup
79
- pi-tui-performance-host=@xmoon76/dsh-pi-tui/performance-host workspace-files=@deepseek-ai/dsh-api-workspace-files
80
- pi-tui-visual-tools=@xmoon76/dsh-pi-tui/visual-tools webserver=@deepseek-ai/dsh-host-webserver
81
- job-controller=@deepseek-ai/dsh-api-job-controller workspace=@deepseek-ai/dsh-workspace
82
- file-reference-local=@deepseek-ai/dsh-file-reference-local agent-preset-registry=@deepseek-ai/dsh-agent-preset-registry
83
- subagent-model-selection-settings=@deepseek-ai/dsh-tool-subagent/model-selection-settings cordis-host-runner=@deepseek-ai/dsh-cordis-host-runner
84
- preset-standard=@deepseek-ai/dsh-agent-preset preset-ptc=@deepseek-ai/dsh-agent-preset
85
- preset-minimal=@deepseek-ai/dsh-agent-preset preset-cordis=@deepseek-ai/dsh-agent-preset
86
- split-host-connection=@deepseek-ai/dsh-client-connection split-host-api-remotes=@deepseek-ai/dsh-api-remotes
87
- split-host-file-upload=@deepseek-ai/dsh-client-file-upload split-host-session-stats=@deepseek-ai/dsh-session-stats
88
- split-host-turn-outline=@deepseek-ai/dsh-session-turn-outline split-host-session-controller=@deepseek-ai/dsh-api-session-controller
89
- split-host-settings-controller=@deepseek-ai/dsh-api-settings-controller split-host-session-log-download=@deepseek-ai/dsh-session-log-export
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) => {
92
- const separator = entry.indexOf("=");
93
- return [entry.slice(0, separator), entry.slice(separator + 1)];
94
- }));
95
- /** Reasons that positively establish current work or a future keepalive obligation. */
96
- const BLOCKING_REASONS = /* @__PURE__ */ new Set([
97
- "agent-running",
98
- "agent-inbox",
99
- "goal-armed",
100
- "job-running",
101
- "job-stopping",
102
- "child-active",
103
- "schedule-active"
40
+ /** The fixed startup failure for an unrecognized mode value. */
41
+ const INVALID_HOST_PATH_MODE = "Invalid DSH_PI_TUI_HOST_PATH_MODE: expected augment or inherit";
42
+ /** The platform package-manager group, in contract order. */
43
+ const PLATFORM_DIRECTORIES = {
44
+ linux: ["/home/linuxbrew/.linuxbrew/bin", "/home/linuxbrew/.linuxbrew/sbin"],
45
+ darwin: ["/opt/homebrew/bin", "/opt/homebrew/sbin"]
46
+ };
47
+ /** The fixed system directory group shared by both platforms. */
48
+ const SYSTEM_DIRECTORIES = [
49
+ "/usr/local/bin",
50
+ "/usr/local/sbin",
51
+ "/usr/bin",
52
+ "/usr/sbin",
53
+ "/bin",
54
+ "/sbin"
55
+ ];
56
+ /** Failures that mean "this candidate cannot be inspected", never a silent absence. */
57
+ const INACCESSIBLE_STAT_CODES = /* @__PURE__ */ new Set([
58
+ "EACCES",
59
+ "EPERM",
60
+ "ELOOP",
61
+ "ENAMETOOLONG"
104
62
  ]);
105
- /** The dedicated timeout marker: a hung read is UNKNOWN, never an empty source. */
106
- const OBSERVATION_TIMEOUT = Symbol("host-activity-observation-timeout");
107
- /** Reject a source read after the caller's bound. */
108
- async function withDeadline(operation, deadlineMs) {
109
- if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return operation;
110
- let timer;
111
- const deadline = new Promise((_resolve, reject) => {
112
- timer = setTimeout(() => {
113
- reject(OBSERVATION_TIMEOUT);
114
- }, deadlineMs);
115
- });
116
- try {
117
- return await Promise.race([operation, deadline]);
118
- } finally {
119
- if (timer !== void 0) clearTimeout(timer);
120
- }
63
+ /** A non-empty, absolute POSIX path usable as a PATH entry. */
64
+ function isUsablePath(value) {
65
+ return value !== "" && value.startsWith("/") && !value.includes(":") && !value.includes("\0");
121
66
  }
122
- /** Build one ordered, deduplicated reason list. */
123
- function reasonList(reasons) {
124
- return [...reasons];
67
+ /** Resolve the requested policy, rejecting everything else with the fixed message. */
68
+ function resolveMode(value) {
69
+ if (value === void 0 || value === "augment") return "augment";
70
+ if (value === "inherit") return "inherit";
71
+ throw new Error(INVALID_HOST_PATH_MODE);
125
72
  }
126
- /** A snapshot that claims nothing after the observer stopped reading. */
127
- function closedSnapshot(epoch) {
128
- return {
129
- verdict: "UNKNOWN",
130
- epoch,
131
- reasons: ["source-unavailable"],
132
- sourceStates: Object.fromEntries(HOST_ACTIVITY_SOURCES.map((source) => [source, "UNKNOWN"]))
133
- };
73
+ /** The default probe: a real stat that follows a legal directory symlink. */
74
+ function statDirectory(path) {
75
+ return statSync(path);
76
+ }
77
+ /** Classify one candidate without turning an unexpected filesystem failure into absence. */
78
+ function probeDirectory(probe, path) {
79
+ try {
80
+ return probe(path).isDirectory() ? "directory" : "missing";
81
+ } catch (error) {
82
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
83
+ if (code === "ENOENT" || code === "ENOTDIR") return "missing";
84
+ if (INACCESSIBLE_STAT_CODES.has(code)) return "inaccessible";
85
+ throw error;
86
+ }
134
87
  }
135
88
  /**
136
- * The Host-process observer. Construction only subscribes to official live
137
- * signals and starts no work; snapshot() performs the reads.
89
+ * Build the ordered candidate plan from the authoritative inherited `env`.
90
+ * Invalid explicit values are counted and skipped; each tool then uses its
91
+ * regular default, and a usable override never falls back to that default.
138
92
  */
139
- var HostActivityObserver = class {
140
- context;
141
- observationDeadlineMs;
142
- subscriptions = [];
143
- /** Short-lived active Job identity hints: official list reads stay authoritative. */
144
- jobHints = /* @__PURE__ */ new Map();
145
- /** Services observed in this Host process; a later absence is UNKNOWN, not ABSENT. */
146
- seenSources = /* @__PURE__ */ new Set();
147
- currentEpoch = 0;
148
- closed = false;
149
- constructor(context, options = {}) {
150
- this.context = context;
151
- this.observationDeadlineMs = options.observationDeadlineMs ?? 3e3;
152
- try {
153
- this.subscribe();
154
- } catch (error) {
155
- this.closed = true;
156
- for (const dispose of this.subscriptions.splice(0).reverse()) dispose();
157
- throw error;
93
+ function planCandidates(options) {
94
+ const { env, platform, home, countInvalid } = options;
95
+ /** One explicit value: unset, unusable, or a usable path (with suffix applied by the caller). */
96
+ const explicit = (value, suffix) => {
97
+ if (value === void 0 || value === "") return void 0;
98
+ if (!isUsablePath(value)) {
99
+ countInvalid();
100
+ return;
158
101
  }
159
- }
160
- /** Subscribe to the official change signals that invalidate a snapshot. */
161
- subscribe() {
162
- const invalidate = () => {
163
- this.invalidate();
102
+ return {
103
+ path: suffix === void 0 ? value : posix.join(value, suffix),
104
+ explicit: true
164
105
  };
165
- for (const event of [
166
- "agent/created",
167
- "agent/disposed",
168
- "agent/status",
169
- "agent/inbox/inserted",
170
- "agent/inbox/claimed",
171
- "agent/inbox/discarded",
172
- "goal/changed",
173
- "schedule/changed",
174
- "internal/status"
175
- ]) this.subscriptions.push(this.context.on(event, invalidate));
176
- const jobs = this.context.reflect.get("jobs");
177
- if (jobs === void 0) return;
178
- this.seenSources.add("jobs");
179
- this.subscriptions.push(jobs.events.subscribe({ owners: "all" }, (event) => {
180
- if (event.type === "output" || event.type === "progress") return;
181
- const job = event.job;
182
- if (job !== void 0) {
183
- if (event.type === "registered") this.jobHints.set(job.id, job.status === "stopping" ? "stopping" : "running");
184
- else if (event.type === "stopping") this.jobHints.set(job.id, "stopping");
185
- else if (event.type === "settled" || event.type === "removed") this.jobHints.delete(job.id);
186
- }
187
- this.invalidate();
188
- }));
189
- }
190
- /** Advance the epoch and refresh which services are currently mounted. */
191
- invalidate() {
192
- if (this.closed) return;
193
- this.currentEpoch += 1;
194
- this.noteMountedSources();
195
- }
196
- /** Remember every source service seen in this process. */
197
- noteMountedSources() {
198
- if (this.context.reflect.get("jobs") !== void 0) this.seenSources.add("jobs");
199
- if (this.context.reflect.get("goals") !== void 0) this.seenSources.add("goal");
200
- if (this.context.reflect.get("schedule") !== void 0) this.seenSources.add("schedule");
201
- if (this.context.reflect.get("typertGateway") !== void 0) this.seenSources.add("pending");
202
- if (this.context.reflect.get("sessionPersistence") !== void 0) this.seenSources.add("write");
106
+ };
107
+ const fallback = (path) => path === void 0 ? void 0 : {
108
+ path,
109
+ explicit: false
110
+ };
111
+ const first = (...selected) => selected.find((candidate) => candidate !== void 0);
112
+ let dataHome;
113
+ const xdgDataHome = env.XDG_DATA_HOME;
114
+ if (xdgDataHome !== void 0 && xdgDataHome !== "") dataHome = explicit(xdgDataHome) ?? fallback(home === void 0 ? void 0 : posix.join(home, ".local/share"));
115
+ else dataHome = fallback(home === void 0 ? void 0 : posix.join(home, ".local/share"));
116
+ const mise = first(explicit(env.MISE_SHIMS_DIR), explicit(env.MISE_DATA_DIR, "shims"), dataHome === void 0 ? void 0 : {
117
+ path: posix.join(dataHome.path, "mise", "shims"),
118
+ explicit: dataHome.explicit
119
+ });
120
+ const asdf = first(explicit(env.ASDF_DATA_DIR, "shims"), fallback(home === void 0 ? void 0 : posix.join(home, ".asdf", "shims")));
121
+ const cargo = first(explicit(env.CARGO_HOME, "bin"), fallback(home === void 0 ? void 0 : posix.join(home, ".cargo", "bin")));
122
+ const go = first(explicit(env.GOBIN), fallback(home === void 0 ? void 0 : posix.join(home, "go", "bin")));
123
+ const volta = first(explicit(env.VOLTA_HOME, "bin"), fallback(home === void 0 ? void 0 : posix.join(home, ".volta", "bin")));
124
+ const bun = first(explicit(env.BUN_INSTALL, "bin"), fallback(home === void 0 ? void 0 : posix.join(home, ".bun", "bin")));
125
+ const pnpm = first(explicit(env.PNPM_HOME), platform === "linux" ? dataHome === void 0 ? void 0 : {
126
+ path: posix.join(dataHome.path, "pnpm"),
127
+ explicit: dataHome.explicit
128
+ } : fallback(home === void 0 ? void 0 : posix.join(home, "Library", "pnpm")));
129
+ const rows = [
130
+ fallback(home === void 0 ? void 0 : posix.join(home, ".local/bin")),
131
+ fallback(home === void 0 ? void 0 : posix.join(home, "bin")),
132
+ mise,
133
+ asdf,
134
+ cargo,
135
+ go,
136
+ volta,
137
+ bun,
138
+ pnpm
139
+ ];
140
+ const candidates = [];
141
+ for (const selected of rows) {
142
+ if (selected === void 0) continue;
143
+ candidates.push({
144
+ path: selected.path,
145
+ explicit: selected.explicit
146
+ });
203
147
  }
204
- /** Map a missing service to ABSENT (never mounted) or UNKNOWN (mounted earlier). */
205
- unavailableState(source, reasons) {
206
- if (!this.seenSources.has(source)) return "ABSENT";
207
- reasons.add("source-unavailable");
208
- return "UNKNOWN";
148
+ for (const path of PLATFORM_DIRECTORIES[platform]) candidates.push({
149
+ path,
150
+ explicit: false
151
+ });
152
+ for (const path of SYSTEM_DIRECTORIES) candidates.push({
153
+ path,
154
+ explicit: false
155
+ });
156
+ return candidates;
157
+ }
158
+ /**
159
+ * Resolve the Host startup PATH decision without touching the real process.
160
+ *
161
+ * The original non-empty PATH is preserved byte for byte, including relative,
162
+ * empty and duplicate entries; only candidates whose exact string is not
163
+ * already present are stat-probed and appended. Explicit user tool
164
+ * configuration is appended before the regular user defaults, which are
165
+ * followed by the platform package-manager and system directories.
166
+ */
167
+ function resolveHostPath(options) {
168
+ const { env, platform } = options;
169
+ const mode = resolveMode(env.DSH_PI_TUI_HOST_PATH_MODE);
170
+ if (mode === "inherit") return {
171
+ mode,
172
+ path: env.PATH,
173
+ addedPathCount: 0,
174
+ skippedInvalidCount: 0,
175
+ skippedInaccessibleCount: 0,
176
+ homeAvailable: void 0
177
+ };
178
+ let skippedInvalidCount = 0;
179
+ const countInvalid = () => {
180
+ skippedInvalidCount += 1;
181
+ };
182
+ let home = env.HOME;
183
+ if (home === void 0 || !isUsablePath(home)) {
184
+ const accountHome = (options.accountHome ?? (() => userInfo().homedir))();
185
+ home = isUsablePath(accountHome) ? accountHome : void 0;
209
186
  }
210
- /** Read every live Agent (children included) and classify current work. */
211
- readAgents(reasons) {
212
- const registry = this.context.reflect.get("agents");
213
- if (registry === void 0) {
214
- reasons.add("source-unavailable");
215
- return {
216
- state: "UNKNOWN",
217
- agents: [],
218
- readable: false
219
- };
220
- }
221
- let agents;
222
- try {
223
- agents = registry.list();
224
- } catch {
225
- reasons.add("source-unavailable");
226
- return {
227
- state: "UNKNOWN",
228
- agents: [],
229
- readable: false
230
- };
231
- }
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
- };
241
- let state = "IDLE";
242
- let maintenanceGap = false;
243
- for (const agent of agents) {
244
- let running;
245
- let pending;
246
- try {
247
- running = agent.status === "running";
248
- pending = agent.inbox.nextTurn.length + agent.inbox.nextStep.length;
249
- } catch {
250
- reasons.add("source-unavailable");
251
- return {
252
- state: "UNKNOWN",
253
- agents,
254
- readable: false
255
- };
256
- }
257
- if (running) {
258
- reasons.add("agent-running");
259
- state = "ACTIVE";
260
- }
261
- if (pending > 0) {
262
- reasons.add("agent-inbox");
263
- state = "ACTIVE";
264
- }
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;
270
- }
271
- if (maintenanceGap) {
272
- reasons.add("agent-maintenance-unproven");
273
- if (state === "IDLE") state = "UNKNOWN";
187
+ const probe = options.statDirectory ?? statDirectory;
188
+ const inherited = env.PATH === void 0 || env.PATH === "" ? [] : env.PATH.split(":");
189
+ const seen = new Set(inherited);
190
+ let skippedInaccessibleCount = 0;
191
+ const appended = [];
192
+ const candidates = planCandidates({
193
+ env,
194
+ platform,
195
+ home,
196
+ countInvalid
197
+ });
198
+ const ordered = [...candidates.filter((candidate) => candidate.explicit), ...candidates.filter((candidate) => !candidate.explicit)];
199
+ for (const candidate of ordered) {
200
+ if (seen.has(candidate.path)) continue;
201
+ const outcome = probeDirectory(probe, candidate.path);
202
+ if (outcome === "missing") continue;
203
+ if (outcome === "inaccessible") {
204
+ skippedInaccessibleCount += 1;
205
+ continue;
274
206
  }
275
- return {
276
- state,
277
- agents,
278
- readable: true
279
- };
207
+ appended.push(candidate.path);
208
+ seen.add(candidate.path);
280
209
  }
281
- /** Read the official Goal view for every live Agent. */
282
- readGoals(agents, agentsReadable, reasons) {
283
- const goals = this.context.reflect.get("goals");
284
- if (goals === void 0) return this.unavailableState("goal", reasons);
285
- this.seenSources.add("goal");
286
- if (!agentsReadable) {
287
- reasons.add("source-unavailable");
288
- return "UNKNOWN";
289
- }
290
- let state = "IDLE";
291
- for (const agent of agents) {
292
- let goal;
293
- try {
294
- goal = goals.get(agent);
295
- } catch {
296
- reasons.add("source-unavailable");
297
- return "UNKNOWN";
298
- }
299
- if (goal !== void 0 && goal.phase === "active" && goal.activation === "armed") {
300
- reasons.add("goal-armed");
301
- state = "ACTIVE";
210
+ let path = env.PATH;
211
+ if (appended.length > 0) path = env.PATH === void 0 || env.PATH === "" ? appended.join(":") : `${env.PATH}:${appended.join(":")}`;
212
+ return {
213
+ mode,
214
+ path,
215
+ addedPathCount: appended.length,
216
+ skippedInvalidCount,
217
+ skippedInaccessibleCount,
218
+ homeAvailable: home !== void 0
219
+ };
220
+ }
221
+ /**
222
+ * Apply the real startup decision to this Host process exactly once. The
223
+ * entry owns the resulting log record and warning; this function only reads
224
+ * `process.env` and writes PATH when the value actually changes.
225
+ */
226
+ function initializeHostEnvironment(platform) {
227
+ const environment = resolveHostPath({
228
+ env: process.env,
229
+ platform
230
+ });
231
+ if (environment.path !== void 0 && environment.path !== process.env.PATH) process.env.PATH = environment.path;
232
+ return environment;
233
+ }
234
+ //#endregion
235
+ //#region src/app/remote-process/local-acp-control-route.ts
236
+ /** The one Owner-only authenticated management route of the headless ACP CLI. */
237
+ const LOCAL_ACP_CONTROL_ROUTE = "/api/pi-tui.acp-control";
238
+ const OP_VALUES$1 = /* @__PURE__ */ new Set(["enable", "disable"]);
239
+ function isRecord$1(value) {
240
+ return value !== null && typeof value === "object" && !Array.isArray(value);
241
+ }
242
+ function hasExactKeys$1(record, keys) {
243
+ const actual = Object.keys(record).sort();
244
+ const expected = [...keys].sort();
245
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
246
+ }
247
+ /** Read at most `maxBytes`; an oversize or unreadable body is `undefined`. */
248
+ async function readBoundedBody$1(request, maxBytes) {
249
+ const declared = request.headers.get("content-length");
250
+ if (declared !== null && Number(declared) > maxBytes) return void 0;
251
+ if (request.body === null) return "";
252
+ const reader = request.body.getReader();
253
+ const chunks = [];
254
+ let total = 0;
255
+ try {
256
+ for (;;) {
257
+ const { done, value } = await reader.read();
258
+ if (done) break;
259
+ total += value.byteLength;
260
+ if (total > maxBytes) {
261
+ await reader.cancel();
262
+ return;
302
263
  }
264
+ chunks.push(value);
303
265
  }
304
- return state;
305
- }
306
- /** Merge the unowned list, every live Agent's owner-scoped list, and job hints. */
307
- readJobs(agents, agentsReadable, reasons) {
308
- const jobs = this.context.reflect.get("jobs");
309
- if (jobs === void 0) return this.unavailableState("jobs", reasons);
310
- this.seenSources.add("jobs");
311
- const byId = /* @__PURE__ */ new Map();
312
- try {
313
- for (const job of jobs.list()) byId.set(job.id, job);
314
- if (agentsReadable) for (const agent of agents) for (const job of jobs.list(agent.id)) byId.set(job.id, job);
315
- } catch {
316
- reasons.add("source-unavailable");
317
- return "UNKNOWN";
318
- }
319
- for (const [id, status] of this.jobHints) if (!byId.has(id)) byId.set(id, {
320
- id,
321
- status
322
- });
323
- let state = "IDLE";
324
- for (const job of byId.values()) if (job.status === "running") {
325
- reasons.add("job-running");
326
- state = "ACTIVE";
327
- } else if (job.status === "stopping") {
328
- reasons.add("job-stopping");
329
- state = "ACTIVE";
330
- }
331
- if (!agentsReadable) {
332
- reasons.add("source-unavailable");
333
- if (state === "IDLE") return "UNKNOWN";
334
- }
335
- return state;
266
+ } finally {
267
+ reader.releaseLock();
336
268
  }
337
- /** Read the official Host Schedule catalog when the service is actually mounted. */
338
- async readSchedule(reasons) {
339
- const schedule = this.context.reflect.get("schedule");
340
- if (schedule === void 0) return this.unavailableState("schedule", reasons);
341
- this.seenSources.add("schedule");
342
- let entries;
343
- try {
344
- entries = await withDeadline(schedule.catalog(), this.observationDeadlineMs);
345
- } catch {
346
- reasons.add("source-unavailable");
347
- return "UNKNOWN";
348
- }
349
- let state = "IDLE";
350
- for (const entry of entries) if (entry.status === "active") {
351
- reasons.add("schedule-active");
352
- state = "ACTIVE";
269
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
270
+ }
271
+ /** The fixed response headers for every route reply, success or failure. */
272
+ function jsonResponse$1(body, status = 200) {
273
+ return new Response(JSON.stringify(body), {
274
+ status,
275
+ headers: {
276
+ "content-type": "application/json",
277
+ "cache-control": "no-store",
278
+ "referrer-policy": "no-referrer",
279
+ "x-content-type-options": "nosniff"
353
280
  }
354
- return state;
355
- }
356
- /** rc.4 cannot enumerate Gateway pending interactions. */
357
- readPending(reasons) {
358
- if (this.context.reflect.get("typertGateway") === void 0) return this.unavailableState("pending", reasons);
359
- this.seenSources.add("pending");
360
- reasons.add("pending-interaction-unobservable");
361
- return "UNKNOWN";
362
- }
363
- /** rc.4 cannot enumerate in-flight Session writes. */
364
- readWrite(reasons) {
365
- if (this.context.reflect.get("sessionPersistence") === void 0) return this.unavailableState("write", reasons);
366
- this.seenSources.add("write");
367
- reasons.add("inflight-write-unproven");
368
- return "UNKNOWN";
281
+ });
282
+ }
283
+ function errorResponse$1(error, status) {
284
+ return jsonResponse$1({
285
+ schema: 1,
286
+ error
287
+ }, status);
288
+ }
289
+ /** Parse the exact POST body; `undefined` means invalid input. */
290
+ function parseRequestBody$1(text) {
291
+ let value;
292
+ try {
293
+ value = JSON.parse(text);
294
+ } catch {
295
+ return;
369
296
  }
370
- /** Active Loader rows outside the official/xmoon namespaces are unqualified. */
371
- readOther(reasons) {
372
- const loader = this.context.loader;
373
- if (loader === void 0) {
374
- reasons.add("source-unavailable");
375
- return "UNKNOWN";
376
- }
377
- let entries;
297
+ if (!isRecord$1(value) || !hasExactKeys$1(value, [
298
+ "schema",
299
+ "instanceId",
300
+ "op"
301
+ ])) return void 0;
302
+ if (value.schema !== 1 || typeof value.instanceId !== "string" || value.instanceId === "") return void 0;
303
+ if (typeof value.op !== "string" || !OP_VALUES$1.has(value.op)) return void 0;
304
+ return {
305
+ schema: 1,
306
+ instanceId: value.instanceId,
307
+ op: value.op
308
+ };
309
+ }
310
+ /**
311
+ * Build the ONE Host route handler. It answers only for the CURRENT Host
312
+ * instance and calls the existing ACP runtime controller once per request.
313
+ * @param instanceId - this Host's published instance id.
314
+ * @param controller - the Host-entry-owned ACP runtime controller.
315
+ * @returns the registered route's `fetch` callback.
316
+ */
317
+ function createLocalAcpControlHandler(instanceId, controller) {
318
+ return async (request) => {
319
+ if (request.method !== "POST") return errorResponse$1("ACP_INVALID_REQUEST", 405);
320
+ const contentType = request.headers.get("content-type") ?? "";
321
+ if (!/^application\/json\b/iu.test(contentType)) return errorResponse$1("ACP_INVALID_REQUEST", 415);
322
+ const text = await readBoundedBody$1(request, 512);
323
+ if (text === void 0) return errorResponse$1("ACP_INVALID_REQUEST", 400);
324
+ const body = parseRequestBody$1(text);
325
+ if (body === void 0) return errorResponse$1("ACP_INVALID_REQUEST", 400);
326
+ if (body.instanceId !== instanceId) return errorResponse$1("ACP_INSTANCE_MISMATCH", 409);
327
+ let status;
378
328
  try {
379
- entries = [...loader.entries()];
329
+ status = await controller.setEnabled(body.op === "enable");
380
330
  } catch {
381
- reasons.add("source-unavailable");
382
- return "UNKNOWN";
331
+ return errorResponse$1("ACP_CLI_UNAVAILABLE", 503);
383
332
  }
384
- for (const entry of entries) {
385
- const state = entry.fiber?.state;
386
- if (state === void 0 || state === FIBER_PENDING || state === FIBER_DISPOSED) continue;
387
- const id = entry.options?.id ?? "";
388
- const name = entry.options?.name ?? "";
389
- const qualified = QUALIFIED_HOST_ROWS.get(id) === name;
390
- if (state === FIBER_FAILED) {
391
- reasons.add("source-unavailable");
392
- return "UNKNOWN";
393
- }
394
- if (state === FIBER_ACTIVE) {
395
- if (qualified) continue;
396
- reasons.add("unqualified-host-source");
397
- return "UNKNOWN";
398
- }
399
- if (state === FIBER_LOADING || state === FIBER_UNLOADING) {
400
- reasons.add(qualified ? "source-unavailable" : "unqualified-host-source");
401
- return "UNKNOWN";
402
- }
403
- reasons.add("source-unavailable");
404
- return "UNKNOWN";
405
- }
406
- return "IDLE";
407
- }
408
- /** Read one bounded snapshot from the real Host services. */
409
- async snapshot() {
410
- if (this.closed) return closedSnapshot(this.currentEpoch);
411
- const startEpoch = this.currentEpoch;
412
- this.noteMountedSources();
413
- const reasons = /* @__PURE__ */ new Set();
414
- const sourceStates = {};
415
- const agents = this.readAgents(reasons);
416
- sourceStates.agent = agents.state;
417
- sourceStates.goal = this.readGoals(agents.agents, agents.readable, reasons);
418
- sourceStates.jobs = this.readJobs(agents.agents, agents.readable, reasons);
419
- sourceStates.schedule = await this.readSchedule(reasons);
420
- sourceStates.pending = this.readPending(reasons);
421
- sourceStates.write = this.readWrite(reasons);
422
- sourceStates.other = this.readOther(reasons);
423
- if (this.closed) return closedSnapshot(this.currentEpoch);
424
- const endEpoch = this.currentEpoch;
425
- if (startEpoch !== endEpoch) reasons.add("observation-changed");
426
- let verdict;
427
- if ([...reasons].some((reason) => BLOCKING_REASONS.has(reason))) verdict = "BLOCKED";
428
- else if (reasons.size > 0) verdict = "UNKNOWN";
429
- else verdict = "OBSERVED_QUIESCENT";
430
- return {
431
- verdict,
432
- epoch: endEpoch,
433
- reasons: reasonList(reasons),
434
- sourceStates
435
- };
436
- }
437
- /** Release every subscription synchronously and ignore late callbacks. */
438
- close() {
439
- if (this.closed) return;
440
- this.closed = true;
441
- const subscriptions = this.subscriptions.splice(0);
442
- for (const dispose of subscriptions.reverse()) dispose();
443
- }
444
- };
333
+ return jsonResponse$1({
334
+ schema: 1,
335
+ instanceId,
336
+ state: status.state
337
+ });
338
+ };
339
+ }
445
340
  //#endregion
446
341
  //#region src/app/remote-process/local-web-control-route.ts
447
342
  /** The one Owner-only authenticated route of the headless Web CLI. */
@@ -642,6 +537,12 @@ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows
642
537
  # here would register the directory-picker seam twice.
643
538
  - id: directory-picker
644
539
  inject: []
540
+ # The bundle's ONE official whole-log session-stats row stays the bundle's row
541
+ # too: the overlay only drops its Direct tuiStartup admission gate so the
542
+ # long-lived Host keeps serving complete sessionStats after the TUI Client is
543
+ # gone. A second declaration here would register the projection twice.
544
+ - id: split-host-session-stats
545
+ inject: [sessionProjections]
645
546
 
646
547
  # Host Schedule management (S5-PR4): the bundle's ONE official Schedule row
647
548
  # stays this bundle's row; the overlay only drops its Direct tuiStartup
@@ -685,10 +586,6 @@ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows
685
586
  name: '@deepseek-ai/dsh-client-file-upload'
686
587
  inject: [agents, attachments, commands, connection]
687
588
 
688
- - id: split-host-session-stats
689
- name: '@deepseek-ai/dsh-session-stats'
690
- inject: [sessionProjections]
691
-
692
589
  - id: split-host-turn-outline
693
590
  name: '@deepseek-ai/dsh-session-turn-outline'
694
591
  inject: [sessionProjections]
@@ -767,7 +664,22 @@ async function loadOfficialDsh(anchor) {
767
664
  const profileBoot = await importResolved("@deepseek-ai/dsh/profile-boot");
768
665
  const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
769
666
  const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
667
+ const commands = await importResolved("@deepseek-ai/dsh-commands");
668
+ let compactionEngineClass;
669
+ try {
670
+ const candidate = (await importResolved("@deepseek-ai/dsh-compaction-basic")).BasicCompactionEngine;
671
+ if (typeof candidate === "function") compactionEngineClass = candidate;
672
+ } catch {}
673
+ let planModeClass;
674
+ try {
675
+ const planMode = await importResolved("@deepseek-ai/dsh-plan-mode");
676
+ const candidate = planMode.PlanModeController ?? planMode.default;
677
+ if (typeof candidate === "function") planModeClass = candidate;
678
+ } catch {}
770
679
  return {
680
+ parseCommand: commands.parseCommand,
681
+ ...compactionEngineClass === void 0 ? {} : { compactionEngineClass },
682
+ ...planModeClass === void 0 ? {} : { planModeClass },
771
683
  runProfile: profileBoot.runProfile,
772
684
  loadLayeredEnv: appBoot.loadLayeredEnv,
773
685
  resolveDshHome: homePaths.resolveDshHome,
@@ -775,18 +687,15 @@ async function loadOfficialDsh(anchor) {
775
687
  };
776
688
  }
777
689
  /** Wait for one unauthenticated route to answer with the expected refusal. */
778
- async function waitForRefusal(url, timeoutMs = 1e4, init = {}) {
690
+ async function waitForRefusal(url, timeoutMs = 1e4) {
779
691
  const deadline = Date.now() + timeoutMs;
780
692
  while (Date.now() < deadline) {
781
693
  try {
782
- const request = {
783
- method: init.method ?? "GET",
694
+ const response = await fetch(url, {
695
+ method: "GET",
784
696
  redirect: "manual",
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);
697
+ cache: "no-store"
698
+ });
790
699
  await response.body?.cancel();
791
700
  if (response.status === 401 || response.status === 403) return;
792
701
  } catch {}
@@ -875,6 +784,117 @@ function imageRouteError(reason, message) {
875
784
  details: { reason }
876
785
  });
877
786
  }
787
+ /** The official command definition identities this Host may advertise. */
788
+ const FEEDBACK_DEFINITION_ID = "@deepseek-ai/dsh-command-feedback";
789
+ const COMPACT_DEFINITION_ID = "@deepseek-ai/dsh-command-compact";
790
+ /** Official generated preset identities whose compaction composition is audited. */
791
+ const AUDITED_COMPACTION_PRESETS = /* @__PURE__ */ new Set([
792
+ "standard",
793
+ "ptc",
794
+ "minimal",
795
+ "cordis"
796
+ ]);
797
+ /** The audited official compaction modules of one isolated preset group. */
798
+ const AUDITED_COMPACTION_MODULES = /* @__PURE__ */ new Set([
799
+ "@deepseek-ai/dsh-compaction-basic",
800
+ "@deepseek-ai/dsh-command-compact",
801
+ "@deepseek-ai/dsh-compaction-tool-result-pruner"
802
+ ]);
803
+ /** Fail closed unless the exact Agent/Session objects are still the live pair. */
804
+ function assertExactHostIdentity(agents, sessions, agent, session) {
805
+ if (agents.get(agent.id) !== agent || sessions.get(agent.id) !== session || agent.session !== session) throw new AcpHostCommandError("stale", "the exact Host Agent/Session identity is no longer current");
806
+ }
807
+ /** Whether this Agent exposes the exact Cordis context required for preset reads. */
808
+ function hasContext(agent) {
809
+ return typeof agent.ctx === "object" && agent.ctx !== null;
810
+ }
811
+ /**
812
+ * Resolve the official `systemPrompt` service THROUGH the exact Agent's own
813
+ * Cordis context, so `section()` registers in that Agent's scope and the
814
+ * returned disposer is owned by that exact scope. Never the root service.
815
+ */
816
+ function scopedSystemPromptOf(agent) {
817
+ if (!hasContext(agent)) return void 0;
818
+ const getter = agent.ctx.get;
819
+ if (typeof getter !== "function") return void 0;
820
+ const service = getter.call(agent.ctx, "systemPrompt");
821
+ if (service === null || typeof service !== "object") return void 0;
822
+ return typeof service.section === "function" ? service : void 0;
823
+ }
824
+ /** The active modules of the exact retained preset revision. */
825
+ function retainedInspection(agent, presets) {
826
+ if (!hasContext(agent)) return void 0;
827
+ let inspections;
828
+ try {
829
+ inspections = presets.inspectCompositions(agent.ctx);
830
+ } catch {
831
+ throw new AcpHostCommandError("unavailable", "the retained preset composition could not be inspected");
832
+ }
833
+ if (inspections.length !== 1) return void 0;
834
+ return inspections[0];
835
+ }
836
+ function retainedModules(agent, presets) {
837
+ return retainedInspection(agent, presets)?.modules.map((module) => module.moduleName);
838
+ }
839
+ /** Whether the exact retained revision mounts the native human Skill loader. */
840
+ function hasNativeSkillLoader(agent, presets) {
841
+ return retainedModules(agent, presets)?.includes("@deepseek-ai/dsh-tool-skill") === true;
842
+ }
843
+ /**
844
+ * Resolve the registry the exact retained loader actually consumes. The
845
+ * standard composition mounts `tool-skill` against the global `skills`
846
+ * service (there is no scoped isolate), while a custom composition may
847
+ * publish an Agent-scoped registry. Prefer the scoped registry when it
848
+ * exists; otherwise the official global service is the effective registry.
849
+ * A missing/unusable registry is absent, never a third authority.
850
+ */
851
+ function readSkillRegistry(agent, presets, global) {
852
+ if (!hasContext(agent)) return void 0;
853
+ let scoped;
854
+ try {
855
+ scoped = presets.serviceFor(agent, "skills");
856
+ } catch {
857
+ throw new AcpHostCommandError("unavailable", "the retained Skill service could not be resolved");
858
+ }
859
+ const registry = scoped ?? global;
860
+ return registry !== void 0 && typeof registry.snapshot === "function" ? registry : void 0;
861
+ }
862
+ /**
863
+ * The ONE audited compaction composition gate: exactly one retained revision,
864
+ * the official basic engine + command definition modules, no other compaction
865
+ * engine module, and the exact scoped service object.
866
+ */
867
+ function auditedCompactionEngine(agent, presets, expectedEngineClass) {
868
+ if (presets === void 0 || !hasContext(agent)) return void 0;
869
+ const inspection = retainedInspection(agent, presets);
870
+ if (inspection === void 0 || !AUDITED_COMPACTION_PRESETS.has(inspection.id)) return void 0;
871
+ const modules = inspection.modules.map((module) => module.moduleName);
872
+ if (!modules.includes("@deepseek-ai/dsh-compaction-basic") || !modules.includes("@deepseek-ai/dsh-command-compact") || !modules.filter((name) => name.includes("compaction")).every((name) => AUDITED_COMPACTION_MODULES.has(name))) return;
873
+ let service;
874
+ try {
875
+ service = presets.serviceFor(agent, "compaction");
876
+ } catch {
877
+ throw new AcpHostCommandError("unavailable", "the retained compaction service could not be resolved");
878
+ }
879
+ const engine = service;
880
+ if (engine === void 0 || typeof engine.compactNow !== "function") return void 0;
881
+ if (expectedEngineClass === void 0) return void 0;
882
+ try {
883
+ if (!(engine instanceof expectedEngineClass)) return void 0;
884
+ } catch {
885
+ return;
886
+ }
887
+ return engine;
888
+ }
889
+ /** Project one official command definition onto the detached wire row. */
890
+ function commandRow(definition) {
891
+ return {
892
+ kind: "command",
893
+ name: definition.name,
894
+ description: definition.description,
895
+ ...definition.input?.hint === void 0 ? {} : { inputHint: definition.input.hint }
896
+ };
897
+ }
878
898
  /**
879
899
  * Bind the narrow {@link HostAcpSessionAccess} from the ONE already-settled Host
880
900
  * Context. The official Workspace/Session/Agent/Session services stay the sole
@@ -889,15 +909,90 @@ function imageRouteError(reason, message) {
889
909
  * @param context - the settled Host context.
890
910
  * @returns the narrow Session access the listener borrows from.
891
911
  */
892
- function createHostAcpSessionAccess(context) {
912
+ function createHostAcpSessionAccess(context, parseCommand, compactionEngineClass, planModeClass) {
893
913
  const workspaceController = context.reflect.get("workspaceController");
894
914
  const sessionController = context.reflect.get("sessionController");
895
915
  const agents = context.reflect.get("agents");
896
916
  const sessions = context.reflect.get("sessions");
897
917
  const attachments = context.reflect.get("attachments");
918
+ const fileUploads = context.reflect.get("fileUploads");
898
919
  const llm = context.reflect.get("llm");
899
920
  const agentDefaultModel = context.reflect.get("agentDefaultModel");
900
- if (workspaceController === void 0 || sessionController === void 0 || agents === void 0 || sessions === void 0) throw new Error("local host entry: the Host ACP Session View requires the live workspaceController, sessionController, agents and sessions services");
921
+ const tools = context.reflect.get("tools");
922
+ const userQuestions = context.reflect.get("userQuestions");
923
+ const sessionProjections = context.reflect.get("sessionProjections");
924
+ const commands = context.reflect.get("commands");
925
+ const agentPresets = context.reflect.get("agentPresets");
926
+ const workingDirectory = context.reflect.get("workingDirectory");
927
+ const skills = context.reflect.get("skills");
928
+ const sessionQuery = context.reflect.get("sessionQuery");
929
+ if (workspaceController === void 0 || sessionController === void 0 || agents === void 0 || sessions === void 0 || llm === void 0 || tools === void 0) throw new Error("local host entry: the Host ACP Session View requires the live workspaceController, sessionController, agents, sessions, llm and tools services");
930
+ if (typeof sessionController.modelCatalog !== "function") throw new Error("local host entry: the Host ACP Session View requires the official sessionController.modelCatalog service");
931
+ const modelService = new AcpSessionModelService({
932
+ modelCatalog: async () => await sessionController.modelCatalog(),
933
+ listProviders: () => llm.listProviders(),
934
+ listModels: async (providerId) => await llm.listModels(providerId),
935
+ resolveCallConfig: async (selection, signal) => {
936
+ const resolved = await llm.resolveCallConfig(selection, signal);
937
+ return {
938
+ provider: resolved.provider,
939
+ model: resolved.model,
940
+ ...resolved.reasoningEffort === void 0 ? {} : { reasoningEffort: resolved.reasoningEffort }
941
+ };
942
+ },
943
+ currentAgent: (sessionId) => agents.get(sessionId),
944
+ currentSession: (sessionId) => sessions.get(sessionId)
945
+ });
946
+ const currentAgentTeams = () => context.reflect.get("agentTeams");
947
+ const currentSubagents = () => context.reflect.get("subagents");
948
+ const currentProjections = () => context.reflect.get("sessionProjections");
949
+ const policyService = new AcpSessionPolicyService({
950
+ currentAgent: (sessionId) => agents.get(sessionId),
951
+ currentSession: (sessionId) => sessions.get(sessionId),
952
+ planMode: (agent) => {
953
+ if (planModeClass === void 0 || agentPresets === void 0 || !hasContext(agent)) return;
954
+ let service;
955
+ try {
956
+ service = agentPresets.serviceFor(agent, "planMode");
957
+ } catch {
958
+ throw new Error("local host entry: the retained plan-mode service could not be resolved");
959
+ }
960
+ if (service === void 0) return void 0;
961
+ try {
962
+ if (!(service instanceof planModeClass)) return void 0;
963
+ } catch {
964
+ return;
965
+ }
966
+ const candidate = service;
967
+ if (typeof candidate.get !== "function" || typeof candidate.set !== "function") return void 0;
968
+ return service;
969
+ },
970
+ team: (agent) => {
971
+ const agentTeams = currentAgentTeams();
972
+ const subagents = currentSubagents();
973
+ const projections = currentProjections();
974
+ if (agentTeams === void 0 || subagents === void 0 || projections === void 0) return void 0;
975
+ let root;
976
+ try {
977
+ root = subagents.rootOf(agent);
978
+ } catch {
979
+ throw new Error("local host entry: the Agent Team root could not be resolved");
980
+ }
981
+ if (root !== agent) return void 0;
982
+ return agentTeams;
983
+ },
984
+ teamEnabled: (session) => {
985
+ const projections = currentProjections();
986
+ if (projections === void 0) return void 0;
987
+ const value = projectionValueOf(projections, session, "agentTeam");
988
+ if (value === void 0) return void 0;
989
+ if (value === null || typeof value !== "object") throw new Error("local host entry: the official Agent Team projection is malformed");
990
+ const enabled = value.enabled;
991
+ if (typeof enabled !== "boolean") throw new Error("local host entry: the official Agent Team projection carries no boolean");
992
+ return enabled;
993
+ },
994
+ noOpenTurn: (session) => agents.turnBoundaryOf(session).openTurnStartSeq === null
995
+ });
901
996
  return {
902
997
  async createWorkspace(path) {
903
998
  try {
@@ -926,8 +1021,8 @@ function createHostAcpSessionAccess(context) {
926
1021
  kind: "rejected",
927
1022
  code
928
1023
  };
929
- const sessionId = remoteErrorSessionId(error);
930
- if (code === "session/workspace-attach-failed" && sessionId !== void 0) return {
1024
+ const sessionId = publishedSessionIdOfCreateError(error);
1025
+ if (sessionId !== void 0) return {
931
1026
  kind: "published-with-error",
932
1027
  sessionId,
933
1028
  code
@@ -941,6 +1036,62 @@ function createHostAcpSessionAccess(context) {
941
1036
  resolveAgent: (sessionId) => sessionController.resolveAgent(sessionId),
942
1037
  currentAgent: (sessionId) => agents.get(sessionId),
943
1038
  currentSession: (sessionId) => sessions.get(sessionId),
1039
+ supportsSessionRead: () => sessionQuery !== void 0,
1040
+ readSessionList: async (signal) => await readAuthorizedSessionRows(sessionController, sessionQuery, signal),
1041
+ readSessionHistory: async (sessionId, signal) => {
1042
+ if (sessionQuery === void 0) throw new Error("local host entry: no official sessionQuery service can read canonical Session history");
1043
+ signal?.throwIfAborted();
1044
+ const snapshot = await sessionQuery.readSession(sessionId);
1045
+ signal?.throwIfAborted();
1046
+ return {
1047
+ header: headerFactsOf(snapshot.session),
1048
+ events: snapshot.events.map((event) => ({
1049
+ seq: event.seq,
1050
+ type: event.type,
1051
+ data: event.data,
1052
+ time: event.time
1053
+ }))
1054
+ };
1055
+ },
1056
+ sessionHeaderFacts: async (sessionId, signal) => {
1057
+ const live = sessions.get(sessionId);
1058
+ if (live !== void 0) return headerFactsOf(live.header);
1059
+ if (sessionQuery === void 0) return void 0;
1060
+ const [result] = await sessionQuery.readTitleSnapshots([sessionId], signal);
1061
+ if (result === void 0 || result.status !== "fulfilled") return void 0;
1062
+ const facts = headerFactsOf(result.value.session);
1063
+ return facts.sessionId === sessionId ? facts : void 0;
1064
+ },
1065
+ contextPressure: (session) => projectionValueOf(sessionProjections, session, "contextPressure"),
1066
+ sessionTodos: (session) => projectionValueOf(sessionProjections, session, "todos"),
1067
+ mountScopedMcp: async (agent, session, servers, stillCurrent, signal) => {
1068
+ const liveAgent = agents.get(agent.id);
1069
+ const liveSession = sessions.get(agent.id);
1070
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) throw new AcpScopedMcpError("STALE", "the exact Host Agent/Session is no longer current");
1071
+ return await mountAcpScopedMcp({
1072
+ agent,
1073
+ session,
1074
+ servers,
1075
+ tools: { definitions: (scope) => scope === void 0 ? tools.definitions() : tools.definitions(scope) },
1076
+ stillCurrent,
1077
+ signal
1078
+ });
1079
+ },
1080
+ requestRetireScopedMcp: async (lease) => await retireAcpScopedMcp(lease),
1081
+ modelOptions: async (agent, session) => await modelService.readOptions(agent, session),
1082
+ selectModelOnly: async (agent, session, request, signal, stillCurrent) => await modelService.selectSessionOnly(agent, session, request, signal, stillCurrent),
1083
+ readSessionPolicy: (agent, session) => {
1084
+ if (agents.get(agent.id) !== agent || sessions.get(agent.id) !== session || agent.session !== session) throw stalePolicy();
1085
+ return policyService.read(agent);
1086
+ },
1087
+ readSessionMode: (agent, session) => {
1088
+ if (agents.get(agent.id) !== agent || sessions.get(agent.id) !== session || agent.session !== session) throw stalePolicy();
1089
+ return policyService.readMode(agent);
1090
+ },
1091
+ selectSessionPolicy: async (agent, session, request, signal, stillCurrent) => {
1092
+ if (agents.get(agent.id) !== agent || sessions.get(agent.id) !== session || agent.session !== session) throw stalePolicy();
1093
+ await policyService.select(agent, request, signal, stillCurrent);
1094
+ },
944
1095
  imageLimits: () => attachments?.imageLimits,
945
1096
  readOutputImage: async (ref, signal) => {
946
1097
  if (attachments === void 0) throw new Error("local host entry: no official attachment store can read a committed output image");
@@ -950,6 +1101,10 @@ function createHostAcpSessionAccess(context) {
950
1101
  mediaType: stored.ref.mediaType
951
1102
  };
952
1103
  },
1104
+ readOutputFile: (ref, signal) => {
1105
+ if (attachments === void 0) throw new Error("local host entry: no official attachment store can read a committed output file");
1106
+ return attachments.readFileStream(ref, signal);
1107
+ },
953
1108
  supportsImagePrompts: async () => {
954
1109
  if (attachments === void 0 || llm === void 0 || agentDefaultModel === void 0) return false;
955
1110
  try {
@@ -960,8 +1115,11 @@ function createHostAcpSessionAccess(context) {
960
1115
  return false;
961
1116
  }
962
1117
  },
963
- prompt: async (request, signal) => {
964
- if (!request.content.some((part) => part.type === "image")) return await sessionController.prompt(request, signal);
1118
+ prompt: async (request, signal, finalCheck) => {
1119
+ if (!request.content.some((part) => part.type === "image")) {
1120
+ finalCheck?.();
1121
+ return await sessionController.prompt(request, signal);
1122
+ }
965
1123
  signal.throwIfAborted();
966
1124
  const agent = agents.get(request.sessionId);
967
1125
  const session = sessions.get(request.sessionId);
@@ -980,8 +1138,60 @@ function createHostAcpSessionAccess(context) {
980
1138
  const currentSession = sessions.get(request.sessionId);
981
1139
  const currentRoute = currentAgent?.model?.current();
982
1140
  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");
1141
+ finalCheck?.();
983
1142
  return await sessionController.prompt(request, signal);
984
1143
  },
1144
+ supportsFileInput: () => fileUploads !== void 0 && attachments !== void 0 && sessionController !== void 0 && typeof fileUploads.upload === "function" && typeof fileUploads.resolve === "function" && typeof fileUploads.bindPrompt === "function" && typeof fileUploads.retirePrompt === "function",
1145
+ supportsSystemPromptAppend: () => {
1146
+ const service = context.reflect.get("systemPrompt");
1147
+ return service !== void 0 && typeof service.section === "function";
1148
+ },
1149
+ registerSystemPromptAppend: (agent, session, text, stillCurrent) => {
1150
+ const liveAgent = agents.get(agent.id);
1151
+ const liveSession = sessions.get(agent.id);
1152
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) throw new AcpSystemPromptAppendError("stale", "the captured Agent/Session is no longer the live Host identity");
1153
+ const service = scopedSystemPromptOf(agent);
1154
+ if (service === void 0) throw new AcpSystemPromptAppendError("unavailable", "the exact Agent cannot resolve the official scoped systemPrompt service");
1155
+ try {
1156
+ return { dispose: service.section({
1157
+ name: ACP_SYSTEM_PROMPT_SECTION_NAME,
1158
+ order: ACP_SYSTEM_PROMPT_SECTION_ORDER,
1159
+ interpolate: false,
1160
+ text: (assembly) => assembly?.scope === agent && stillCurrent() ? text : ""
1161
+ }) };
1162
+ } catch {
1163
+ throw new AcpSystemPromptAppendError("registration-failed", "the official scoped systemPrompt section could not be registered");
1164
+ }
1165
+ },
1166
+ stageFile: async (agent, session, data, name, signal) => {
1167
+ if (fileUploads === void 0) throw new Error("local host entry: the official fileUploads service is unavailable");
1168
+ const liveAgent = agents.get(agent.id);
1169
+ const liveSession = sessions.get(agent.id);
1170
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) throw Object.assign(/* @__PURE__ */ new Error("the captured Agent/Session is no longer the live host identity"), {
1171
+ isDSHRemoteError: true,
1172
+ code: "session/not-found",
1173
+ details: { reason: "STALE_AGENT" }
1174
+ });
1175
+ return { receiptId: (await fileUploads.upload(agent, {
1176
+ data,
1177
+ ...name === void 0 ? {} : { name }
1178
+ }, signal)).receiptId };
1179
+ },
1180
+ cleanupStagedFiles: (agent, requestId, receiptIds) => {
1181
+ if (fileUploads === void 0) throw new Error("local host entry: the official fileUploads service is unavailable");
1182
+ const live = [...new Set(receiptIds)].filter((receiptId) => fileUploads.resolve(agent, receiptId) !== void 0);
1183
+ if (live.length === 0) return;
1184
+ const guard = fileUploads.bindPrompt(agent, live, requestId);
1185
+ try {
1186
+ fileUploads.retirePrompt(agent, requestId);
1187
+ } finally {
1188
+ guard[Symbol.dispose]();
1189
+ }
1190
+ },
1191
+ retirePromptReceipts: (agent, requestId) => {
1192
+ if (fileUploads === void 0) throw new Error("local host entry: the official fileUploads service is unavailable");
1193
+ fileUploads.retirePrompt(agent, requestId);
1194
+ },
985
1195
  cancelPending: (sessionId, agent, session, messageId) => {
986
1196
  const liveAgent = agents.get(sessionId);
987
1197
  const liveSession = sessions.get(sessionId);
@@ -1015,6 +1225,155 @@ function createHostAcpSessionAccess(context) {
1015
1225
  openTurn: boundary.openTurnStartSeq === null ? null : boundary.lastTurn
1016
1226
  };
1017
1227
  },
1228
+ hasQuestionService: () => userQuestions !== void 0 && sessionProjections !== void 0,
1229
+ questionSnapshot: (sessionId, agent, session) => {
1230
+ const liveAgent = agents.get(sessionId);
1231
+ const liveSession = sessions.get(sessionId);
1232
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return { kind: "stale" };
1233
+ if (sessionProjections === void 0) return { kind: "unavailable" };
1234
+ const state = sessionProjections.stateOf(session, "userQuestions");
1235
+ if (state === void 0) return { kind: "unavailable" };
1236
+ return {
1237
+ kind: "current",
1238
+ continued: state.questions.active.filter((question) => question.state === "continued").map((question) => ({
1239
+ callId: question.callId,
1240
+ questions: question.questions
1241
+ })),
1242
+ settled: new Set(state.questions.settled.map((question) => question.callId))
1243
+ };
1244
+ },
1245
+ answerContinued: (sessionId, agent, session, callId, answer, stillCurrent) => {
1246
+ if (!stillCurrent()) return { kind: "stale" };
1247
+ const liveAgent = agents.get(sessionId);
1248
+ const liveSession = sessions.get(sessionId);
1249
+ if (liveAgent !== agent || liveSession !== session || agent.session !== session) return { kind: "stale" };
1250
+ if (userQuestions === void 0) return { kind: "unavailable" };
1251
+ try {
1252
+ return userQuestions.answer(agent, callId, { answers: answer.answers.map((item) => ({
1253
+ id: item.id,
1254
+ selected: [...item.selected],
1255
+ ...item.custom === void 0 ? {} : { custom: item.custom }
1256
+ })) }) ? { kind: "queued" } : { kind: "not-continued" };
1257
+ } catch (error) {
1258
+ return {
1259
+ kind: "rejected",
1260
+ code: remoteErrorCode(error) ?? "question/answer-failed"
1261
+ };
1262
+ }
1263
+ },
1264
+ /**
1265
+ * Read the effective official command registry. Only the audited
1266
+ * `feedback` identity and the audited retained compact composition are
1267
+ * advertised; other effective Host names remain visible for precedence and
1268
+ * explicit unsupported routing.
1269
+ */
1270
+ readCommandCatalog(agent, session) {
1271
+ assertExactHostIdentity(agents, sessions, agent, session);
1272
+ if (commands === void 0) return EMPTY_COMMAND_CATALOG;
1273
+ let effective;
1274
+ let feedback;
1275
+ let compact;
1276
+ try {
1277
+ effective = commands.list(agent);
1278
+ feedback = commands.find(agent, "feedback");
1279
+ compact = commands.find(agent, "compact");
1280
+ } catch {
1281
+ throw new AcpHostCommandError("unavailable", "the official command registry could not be read");
1282
+ }
1283
+ const feedbackState = feedback === void 0 ? "missing" : String(feedback.definitionId) === FEEDBACK_DEFINITION_ID ? "available" : "shadowed";
1284
+ let compactState;
1285
+ if (compact === void 0) compactState = "missing";
1286
+ else if (String(compact.definitionId) !== COMPACT_DEFINITION_ID) compactState = "shadowed";
1287
+ else compactState = auditedCompactionEngine(agent, agentPresets, compactionEngineClass) === void 0 ? "unavailable" : "available";
1288
+ const rows = [];
1289
+ if (feedbackState === "available" && feedback !== void 0) rows.push(commandRow(feedback));
1290
+ if (compactState === "available" && compact !== void 0) rows.push(commandRow(compact));
1291
+ return {
1292
+ effectiveNames: effective.map((descriptor) => descriptor.name),
1293
+ feedback: feedbackState,
1294
+ compact: compactState,
1295
+ rows
1296
+ };
1297
+ },
1298
+ /**
1299
+ * Read the native Skill catalog from the exact retained loader composition
1300
+ * and the official committed working directory. No list() fallback, no
1301
+ * header cwd and no same-name tool heuristic is accepted.
1302
+ */
1303
+ async readNativeSkills(agent, session, signal) {
1304
+ assertExactHostIdentity(agents, sessions, agent, session);
1305
+ signal.throwIfAborted();
1306
+ if (agentPresets === void 0 || !hasContext(agent) || !hasNativeSkillLoader(agent, agentPresets)) return { kind: "absent" };
1307
+ if (workingDirectory === void 0) return { kind: "absent" };
1308
+ const registry = readSkillRegistry(agent, agentPresets, skills);
1309
+ if (registry === void 0) return { kind: "absent" };
1310
+ const cwd = workingDirectory.get(session);
1311
+ if (!isAbsolutePath(cwd)) throw new AcpHostCommandError("unavailable", "the exact Session has no effective working directory");
1312
+ let observed;
1313
+ try {
1314
+ observed = await registry.snapshot({
1315
+ cwd,
1316
+ scope: agent,
1317
+ signal
1318
+ });
1319
+ } catch (error) {
1320
+ if (signal.aborted) throw error;
1321
+ throw new AcpHostCommandError("unavailable", "the native Skill catalog could not be read");
1322
+ }
1323
+ signal.throwIfAborted();
1324
+ assertExactHostIdentity(agents, sessions, agent, session);
1325
+ if (workingDirectory.get(session) !== cwd || !hasNativeSkillLoader(agent, agentPresets)) throw new AcpHostCommandError("stale", "the native Skill scope changed during the catalog read");
1326
+ if (readSkillRegistry(agent, agentPresets, skills) !== registry) throw new AcpHostCommandError("stale", "the native Skill registry changed during the catalog read");
1327
+ if (observed.complete !== true) throw new AcpHostCommandError("unavailable", "the native Skill catalog is incomplete");
1328
+ return {
1329
+ kind: "available",
1330
+ cwd,
1331
+ skills: observed.skills.filter((skill) => skill.invocation?.userInvocable === true).map((skill) => {
1332
+ if (typeof skill.name !== "string" || skill.name.length === 0 || typeof skill.description !== "string") return void 0;
1333
+ return {
1334
+ kind: "skill",
1335
+ name: skill.name,
1336
+ description: skill.description
1337
+ };
1338
+ }).filter((row) => row !== void 0).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)
1339
+ };
1340
+ },
1341
+ /** Execute the ONE approved standalone command through the official runtime. */
1342
+ executeStandaloneCommand(agent, session, line, signal) {
1343
+ assertExactHostIdentity(agents, sessions, agent, session);
1344
+ if (commands === void 0) throw new AcpHostCommandError("unavailable", "the official command runtime is unavailable");
1345
+ let definition;
1346
+ try {
1347
+ definition = commands.find(agent, "feedback");
1348
+ } catch {
1349
+ throw new AcpHostCommandError("unavailable", "the official command registry could not be read");
1350
+ }
1351
+ if (definition === void 0) throw new AcpHostCommandError("unavailable", "the approved command is no longer registered");
1352
+ if (String(definition.definitionId) !== FEEDBACK_DEFINITION_ID) throw new AcpHostCommandError("unsupported", "the effective command is not the approved definition");
1353
+ return commands.execute(agent, line, [], signal);
1354
+ },
1355
+ /** Enter the exact retained official manual-compaction engine. */
1356
+ parseCommand: (line) => parseCommand?.(line),
1357
+ executeManualCompact(agent, session, signal) {
1358
+ assertExactHostIdentity(agents, sessions, agent, session);
1359
+ if (commands === void 0) throw new AcpHostCommandError("unavailable", "the official command runtime is unavailable");
1360
+ let definition;
1361
+ let engine;
1362
+ try {
1363
+ definition = commands.find(agent, "compact");
1364
+ engine = auditedCompactionEngine(agent, agentPresets, compactionEngineClass);
1365
+ } catch {
1366
+ throw new AcpHostCommandError("unavailable", "the official compaction composition could not be read");
1367
+ }
1368
+ if (definition === void 0) throw new AcpHostCommandError("unavailable", "the approved compact command is no longer registered");
1369
+ if (String(definition.definitionId) !== COMPACT_DEFINITION_ID) throw new AcpHostCommandError("unsupported", "the effective compact command is not the approved definition");
1370
+ if (engine === void 0) throw new AcpHostCommandError("unavailable", "the exact retained compaction engine is unavailable");
1371
+ try {
1372
+ return engine.compactNow(agent, signal);
1373
+ } catch (error) {
1374
+ return Promise.reject(error);
1375
+ }
1376
+ },
1018
1377
  /**
1019
1378
  * Subscribe the View owner to the exact Host facts a prompt flight is
1020
1379
  * correlated against. The Host Context, registries and Agent/Session objects
@@ -1038,12 +1397,53 @@ function createHostAcpSessionAccess(context) {
1038
1397
  context.on("session/event", (session, event) => {
1039
1398
  listener.onSessionEvent(session, event);
1040
1399
  }),
1400
+ context.on("commands/change", () => {
1401
+ listener.onCommandCatalogInvalidated();
1402
+ }),
1403
+ context.on("skills/change", () => {
1404
+ listener.onSkillCatalogInvalidated();
1405
+ }),
1406
+ context.on("tools/change", () => {
1407
+ listener.onSkillCatalogInvalidated();
1408
+ listener.onPolicyAvailabilityInvalidated();
1409
+ }),
1410
+ context.on("agent/assistant-stream", (payload) => {
1411
+ listener.onAssistantStream(payload.agent, payload.frame);
1412
+ }),
1413
+ ...sessionProjections === void 0 ? [] : [sessionProjections.onChanged((session, key) => {
1414
+ listener.onQuestionProjection(session, key);
1415
+ })],
1041
1416
  context.on("agent/error", (payload) => {
1042
1417
  listener.onAgentError(payload.agent, payload.turn);
1043
1418
  }),
1044
1419
  context.on("agent/disposed", (payload) => {
1045
1420
  listener.onAgentDisposed(payload.agent);
1046
1421
  }),
1422
+ context.on("subagent/start", (info) => {
1423
+ listener.onSubagentStart({
1424
+ runId: String(info.runId),
1425
+ id: String(info.id),
1426
+ parentSessionId: String(info.parentSessionId),
1427
+ local: info.local
1428
+ });
1429
+ }),
1430
+ context.on("subagent/end", (info) => {
1431
+ listener.onSubagentEnd({
1432
+ runId: String(info.runId),
1433
+ id: String(info.id),
1434
+ parentSessionId: String(info.parentSessionId),
1435
+ local: info.local,
1436
+ stopReason: String(info.stopReason)
1437
+ });
1438
+ }),
1439
+ context.on("user-questions/request", async (request, next) => {
1440
+ return detachAnswerBatch(await listener.onQuestionRequest({
1441
+ ...request.agent === void 0 ? {} : { agent: request.agent },
1442
+ questions: request.questions,
1443
+ ...request.signal === void 0 ? {} : { signal: request.signal },
1444
+ ...request.wait === void 0 ? {} : { wait: request.wait }
1445
+ }, async () => await next()));
1446
+ }, { prepend: true }),
1047
1447
  context.on("approval/request", (request, next) => {
1048
1448
  return listener.onApprovalRequest({
1049
1449
  agent: request.agent,
@@ -1060,6 +1460,57 @@ function createHostAcpSessionAccess(context) {
1060
1460
  }
1061
1461
  };
1062
1462
  }
1463
+ /**
1464
+ * Read the official authorized Session roster plus the durable title fold of
1465
+ * EXACTLY those ids. Titles are read only for ids the Session Controller
1466
+ * already admitted, so an ACP client can never receive an unauthorized title.
1467
+ * A per-session title failure leaves that row without a title instead of
1468
+ * failing the whole roster.
1469
+ */
1470
+ async function readAuthorizedSessionRows(sessionController, sessionQuery, signal) {
1471
+ const rows = (await sessionController.list({}, signal ?? new AbortController().signal)).items.map((item) => ({
1472
+ sessionId: item.sessionId,
1473
+ updatedAt: item.updatedAt,
1474
+ ...item.cwd === void 0 ? {} : { cwd: item.cwd },
1475
+ ...item.origin === void 0 ? {} : { origin: item.origin }
1476
+ }));
1477
+ if (sessionQuery === void 0 || rows.length === 0) return rows;
1478
+ const titles = /* @__PURE__ */ new Map();
1479
+ for (const result of await sessionQuery.readTitleSnapshots(rows.map((row) => row.sessionId), signal)) {
1480
+ if (result.status !== "fulfilled") continue;
1481
+ const title = result.value.title?.title;
1482
+ if (title !== void 0 && title.length > 0) titles.set(result.sessionId, title);
1483
+ }
1484
+ return rows.map((row) => {
1485
+ const title = titles.get(row.sessionId);
1486
+ return title === void 0 ? row : {
1487
+ ...row,
1488
+ title
1489
+ };
1490
+ });
1491
+ }
1492
+ /** Project one official Session header onto the neutral history facts. */
1493
+ function headerFactsOf(header) {
1494
+ return {
1495
+ sessionId: header.id,
1496
+ ...header.cwd === void 0 ? {} : { cwd: header.cwd },
1497
+ ...header.origin === void 0 ? {} : { origin: header.origin },
1498
+ ...header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession }
1499
+ };
1500
+ }
1501
+ /** Read ONE detached official projection value of the exact Session, or `undefined`. */
1502
+ function projectionValueOf(projections, session, key) {
1503
+ if (projections === void 0) return void 0;
1504
+ return projections.snapshot(session, [key]).values[key];
1505
+ }
1506
+ /** Detach one official answer batch into the mutable wire shape consumers expect. */
1507
+ function detachAnswerBatch(answer) {
1508
+ return { answers: answer.answers.map((item) => ({
1509
+ id: item.id,
1510
+ selected: [...item.selected],
1511
+ ...item.custom === void 0 ? {} : { custom: item.custom }
1512
+ })) };
1513
+ }
1063
1514
  /** A stable code from an official RemoteError without importing its class. */
1064
1515
  function remoteErrorCode(error) {
1065
1516
  if (typeof error === "object" && error !== null && "code" in error) {
@@ -1067,13 +1518,6 @@ function remoteErrorCode(error) {
1067
1518
  if (typeof code === "string") return code;
1068
1519
  }
1069
1520
  }
1070
- /** The authoritative created Session id an official `published-with-error` carries. */
1071
- function remoteErrorSessionId(error) {
1072
- if (typeof error === "object" && error !== null && "details" in error) {
1073
- const sessionId = error.details?.sessionId;
1074
- if (typeof sessionId === "string" && sessionId !== "") return sessionId;
1075
- }
1076
- }
1077
1521
  /**
1078
1522
  * Create the ONE Host-entry-owned ACP runtime controller.
1079
1523
  *
@@ -1266,7 +1710,7 @@ async function applyAcpStartupPreference(context, controller, emit = writeEntryR
1266
1710
  * the registry as the Ready step. The route is registered before the registry
1267
1711
  * so no Client can observe a registry whose identity route is missing.
1268
1712
  */
1269
- async function publishLocalHost(context, scope, hostIdentity, seat, acpController) {
1713
+ async function publishLocalHost(context, scope, hostIdentity, seat, instanceId, acpController, publicationGuard) {
1270
1714
  const connection = context.get("connection");
1271
1715
  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");
1272
1716
  const webServer = context.get("webServer");
@@ -1276,7 +1720,6 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1276
1720
  const origin = webServer.getOrigin();
1277
1721
  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");
1278
1722
  await waitForRefusal(`${origin}/connect`);
1279
- const instanceId = randomUUID();
1280
1723
  const shared = {
1281
1724
  scopeId: scope.scopeId,
1282
1725
  profileRealpath: scope.profileRealpath,
@@ -1292,7 +1735,7 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1292
1735
  const connectUrl = connection.authenticatedUrl(`${origin}/connect`);
1293
1736
  const connectProbe = new URL(connectUrl);
1294
1737
  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");
1295
- const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-BMoNXZjJ.mjs");
1738
+ const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-Ba7_-NNC.mjs");
1296
1739
  writeLaunchMaterial(scope, identity, {
1297
1740
  schema: 1,
1298
1741
  instanceId,
@@ -1301,6 +1744,7 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1301
1744
  let unregisterIdentity;
1302
1745
  let unregisterWorkspaceObject;
1303
1746
  let unregisterAcpStatus;
1747
+ let unregisterAcpControl;
1304
1748
  let unregisterWebControl;
1305
1749
  try {
1306
1750
  unregisterIdentity = connection.fetch.register({
@@ -1324,34 +1768,21 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1324
1768
  requestBody: "buffered",
1325
1769
  fetch: createLocalAcpStatusHandler(instanceId, acpController)
1326
1770
  });
1771
+ unregisterAcpControl = connection.fetch.register({
1772
+ path: LOCAL_ACP_CONTROL_ROUTE,
1773
+ methods: ["POST"],
1774
+ requestBody: "buffered",
1775
+ fetch: createLocalAcpControlHandler(instanceId, acpController)
1776
+ });
1327
1777
  unregisterWebControl = connection.fetch.register({
1328
1778
  path: LOCAL_WEB_CONTROL_ROUTE,
1329
1779
  methods: ["GET", "POST"],
1330
1780
  requestBody: "buffered",
1331
1781
  fetch: createLocalWebControlHandler(instanceId, webAccess)
1332
1782
  });
1333
- await waitForRefusal(`${origin}/api/pi-tui.local-host`);
1334
- await waitForRefusal(`${origin}${LOCAL_WORKSPACE_OBJECT_ROUTE}`, 1e4, {
1335
- method: "POST",
1336
- headers: { "content-type": "application/json" },
1337
- body: JSON.stringify({
1338
- instanceId,
1339
- path: scope.profileRealpath
1340
- })
1341
- });
1342
- await waitForRefusal(`${origin}${LOCAL_ACP_STATUS_ROUTE}`);
1343
- await waitForRefusal(`${origin}${LOCAL_WEB_CONTROL_ROUTE}`);
1344
- await waitForRefusal(`${origin}${LOCAL_WEB_CONTROL_ROUTE}`, 1e4, {
1345
- method: "POST",
1346
- headers: { "content-type": "application/json" },
1347
- body: JSON.stringify({
1348
- schema: 1,
1349
- instanceId,
1350
- op: "url"
1351
- })
1352
- });
1353
1783
  seat.assertCurrent();
1354
1784
  assertRecordedHostKernelIdentityCurrent(identity);
1785
+ publicationGuard?.();
1355
1786
  writeLocalRecord(scope, identity);
1356
1787
  const barrier = process.env.SPLIT_PROCESS_HOST_PUBLISH_BARRIER;
1357
1788
  if (barrier !== void 0 && barrier !== "") await waitForQualificationBarrier(barrier);
@@ -1359,6 +1790,9 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1359
1790
  try {
1360
1791
  await unregisterWebControl?.();
1361
1792
  } catch {}
1793
+ try {
1794
+ await unregisterAcpControl?.();
1795
+ } catch {}
1362
1796
  try {
1363
1797
  await unregisterAcpStatus?.();
1364
1798
  } catch {}
@@ -1375,6 +1809,7 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1375
1809
  identity,
1376
1810
  async unregisterRoutes() {
1377
1811
  await unregisterWebControl?.();
1812
+ await unregisterAcpControl?.();
1378
1813
  await unregisterAcpStatus?.();
1379
1814
  await unregisterWorkspaceObject?.();
1380
1815
  await unregisterIdentity?.();
@@ -1391,7 +1826,25 @@ async function publishLocalHost(context, scope, hostIdentity, seat, acpControlle
1391
1826
  * launcher's native signal handler during `runProfile` bypasses the async
1392
1827
  * finally, so a synchronous exit mirror below removes the same owned scratch.
1393
1828
  */
1829
+ /**
1830
+ * Route the Host-side native waiter settlement into the existing stop owner.
1831
+ * A native failure is not a diagnostic-only event: it requests the same
1832
+ * pending/owner-governed stop, then still rejects so the detached-task owner
1833
+ * records the failure. Success requests the same stop exactly once.
1834
+ */
1835
+ async function routeNativeStopWaiter(stopped, requestStop, onFailure) {
1836
+ try {
1837
+ await stopped;
1838
+ requestStop();
1839
+ } catch (error) {
1840
+ const failure = error instanceof Error ? error : new Error(String(error));
1841
+ requestStop();
1842
+ onFailure(failure);
1843
+ throw failure;
1844
+ }
1845
+ }
1394
1846
  async function runLocalHostEntry(options) {
1847
+ scrubProgramResumeEnvironment(process.env);
1395
1848
  const owned = {};
1396
1849
  process.once("exit", () => {
1397
1850
  owned.acpController?.cleanupSync();
@@ -1436,8 +1889,9 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1436
1889
  }
1437
1890
  let handle;
1438
1891
  let registration;
1439
- let liveness;
1440
1892
  let acpController;
1893
+ let nativeStopWaiter;
1894
+ const instanceId = randomUUID();
1441
1895
  try {
1442
1896
  const scratchDir = mkdtempSync(join(scope.dir, "host-scratch-"));
1443
1897
  scratchOwner.scratchDir = scratchDir;
@@ -1465,13 +1919,13 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1465
1919
  pid: process.pid,
1466
1920
  phase: "profile-booted"
1467
1921
  });
1468
- const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-MVxks641.mjs");
1922
+ const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-BfnufpnW.mjs");
1469
1923
  await settleHostEntries(handle.ctx);
1470
1924
  const settled = handle;
1471
1925
  if (settled === void 0) throw new Error("local host entry: the profile handle disappeared before migration");
1472
1926
  const profileContext = settled.ctx.get("profileContext");
1473
1927
  if (profileContext === void 0) throw new Error("local host entry: the Host profile context is missing");
1474
- const { migrateProfileTuiPreferences } = await import("./profile-preferences-migration-CThz4rHH.mjs");
1928
+ const { migrateProfileTuiPreferences } = await import("./profile-preferences-migration-CNOWIdnr.mjs");
1475
1929
  await migrateProfileTuiPreferences({
1476
1930
  patchPath: profileContext.patchPath,
1477
1931
  configEditor: settled.ctx.get("configEditor"),
@@ -1490,7 +1944,6 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1490
1944
  profile: options.profile,
1491
1945
  processStartIdentity
1492
1946
  });
1493
- liveness = new HostActivityObserver(handle.ctx);
1494
1947
  let published;
1495
1948
  let stopping;
1496
1949
  let shuttingDown = false;
@@ -1513,14 +1966,6 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1513
1966
  error
1514
1967
  });
1515
1968
  }
1516
- try {
1517
- liveness?.close();
1518
- } catch (error) {
1519
- errors.push({
1520
- step: "liveness-close",
1521
- error
1522
- });
1523
- }
1524
1969
  try {
1525
1970
  if (process.env.SPLIT_PROCESS_HOST_FORCE_SCRATCH_REMOVE_FAILURE === "1") throw new Error("local host entry: qualification forced scratch removal failure");
1526
1971
  removeOwnedScratch(scope.dir, scratchDir);
@@ -1547,6 +1992,14 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1547
1992
  });
1548
1993
  }
1549
1994
  if (owner !== void 0) cleanupOwnedFiles(scope, owner.identity.instanceId);
1995
+ try {
1996
+ await nativeStopWaiter?.close();
1997
+ } catch (error) {
1998
+ errors.push({
1999
+ step: "native-stop-waiter-close",
2000
+ error
2001
+ });
2002
+ }
1550
2003
  if (errors.length > 0) {
1551
2004
  const first = errors[0];
1552
2005
  const primary = first.error instanceof Error ? first.error : new Error(String(first.error));
@@ -1616,7 +2069,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1616
2069
  process.removeListener("SIGINT", onSigint);
1617
2070
  };
1618
2071
  const maxConnections = parseAcpMaxConnections(process.env.DSH_PI_TUI_ACP_MAX_CONNECTIONS);
1619
- const sessionAccess = createHostAcpSessionAccess(handle.ctx);
2072
+ const sessionAccess = createHostAcpSessionAccess(handle.ctx, dsh.parseCommand, dsh.compactionEngineClass, dsh.planModeClass);
1620
2073
  acpController = createAcpController({
1621
2074
  scope,
1622
2075
  maxConnections,
@@ -1641,7 +2094,24 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1641
2094
  releaseSignalAdmission();
1642
2095
  return;
1643
2096
  }
1644
- const publishedHost = await publishLocalHost(handle.ctx, scope, hostProcessIdentity, seat, acpController);
2097
+ let nativeStopWaitFailure;
2098
+ if (process.platform === "win32") {
2099
+ nativeStopWaiter = createWin32StopWaiter(scope.scopeId, instanceId);
2100
+ const waiter = nativeStopWaiter;
2101
+ runDetached("local host: native stop event", () => routeNativeStopWaiter(waiter.stopped, () => requestStop(0, "EVENT"), (error) => {
2102
+ nativeStopWaitFailure = error;
2103
+ writeEntryRecord({
2104
+ m4a0: "native-stop-wait-failure",
2105
+ processRole: "host",
2106
+ pid: process.pid,
2107
+ phase: published === void 0 ? "publication" : "running",
2108
+ error: error.message
2109
+ });
2110
+ }), { diag: createEntryDiag("host") });
2111
+ }
2112
+ const publishedHost = await publishLocalHost(handle.ctx, scope, hostProcessIdentity, seat, instanceId, acpController, () => {
2113
+ if (nativeStopWaitFailure !== void 0) throw nativeStopWaitFailure;
2114
+ });
1645
2115
  published = publishedHost;
1646
2116
  registration = publishedHost;
1647
2117
  process.once("exit", () => {
@@ -1652,32 +2122,13 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1652
2122
  releaseSignalAdmission();
1653
2123
  return;
1654
2124
  }
1655
- const initialLivenessPromise = liveness.snapshot();
1656
- const livenessBarrier = process.env.SPLIT_PROCESS_HOST_LIVENESS_BARRIER;
1657
- if (livenessBarrier !== void 0 && livenessBarrier !== "") {
1658
- writeEntryRecord({
1659
- m4a0: "qualification",
1660
- processRole: "host",
1661
- op: "liveness-barrier",
1662
- pid: process.pid
1663
- });
1664
- await waitForQualificationBarrier(livenessBarrier);
1665
- }
1666
- const initialLiveness = await initialLivenessPromise;
1667
- if (stopping !== void 0 || pendingStop !== void 0) {
1668
- await stopped;
1669
- releaseSignalAdmission();
1670
- return;
1671
- }
1672
2125
  writeEntryRecord({
1673
2126
  m4a0: "ready",
1674
2127
  ...status,
1675
- liveness: initialLiveness,
1676
2128
  localHost: publishedHost.identity
1677
2129
  });
1678
2130
  controlChannel = attachEntryControl(async (request) => {
1679
2131
  if (request.op === "status") {
1680
- const snapshot = await liveness.snapshot();
1681
2132
  writeEntryRecord({
1682
2133
  m4a0: "status",
1683
2134
  ...request.requestId === void 0 ? {} : { requestId: request.requestId },
@@ -1685,7 +2136,6 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1685
2136
  profile: options.profile,
1686
2137
  processStartIdentity
1687
2138
  }),
1688
- liveness: snapshot,
1689
2139
  localHost: publishedHost.identity
1690
2140
  });
1691
2141
  return false;
@@ -1743,7 +2193,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1743
2193
  });
1744
2194
  }
1745
2195
  try {
1746
- liveness?.close();
2196
+ await nativeStopWaiter?.close();
1747
2197
  } catch (cleanupError) {
1748
2198
  priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
1749
2199
  writeEntryRecord({
@@ -1751,7 +2201,7 @@ async function runLocalHostEntryOwned(options, scratchOwner) {
1751
2201
  processRole: "host",
1752
2202
  phase: "after-boot",
1753
2203
  pid: process.pid,
1754
- step: "liveness-close",
2204
+ step: "native-stop-waiter-close",
1755
2205
  error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
1756
2206
  });
1757
2207
  }
@@ -1865,7 +2315,26 @@ function optionsFromEnvironment() {
1865
2315
  };
1866
2316
  }
1867
2317
  if (import.meta.main) try {
1868
- await runLocalHostEntry(optionsFromEnvironment());
2318
+ const options = optionsFromEnvironment();
2319
+ const platform = process.platform;
2320
+ if (platform === "linux" || platform === "darwin") {
2321
+ const environment = initializeHostEnvironment(platform);
2322
+ writeEntryRecord({
2323
+ m4a0: "host-environment",
2324
+ processRole: "host",
2325
+ pid: process.pid,
2326
+ mode: environment.mode,
2327
+ addedPathCount: environment.addedPathCount,
2328
+ skippedInvalidCount: environment.skippedInvalidCount,
2329
+ skippedInaccessibleCount: environment.skippedInaccessibleCount
2330
+ });
2331
+ if (environment.skippedInvalidCount > 0 || environment.skippedInaccessibleCount > 0) createEntryDiag("host").warn(`host environment: skipped PATH candidates (invalid=${String(environment.skippedInvalidCount)}, inaccessible=${String(environment.skippedInaccessibleCount)})`, {
2332
+ skippedInvalidCount: environment.skippedInvalidCount,
2333
+ skippedInaccessibleCount: environment.skippedInaccessibleCount
2334
+ });
2335
+ if (environment.homeAvailable === false) createEntryDiag("host").warn("host environment: no usable home directory; only absolute path candidates were considered");
2336
+ }
2337
+ await runLocalHostEntry(options);
1869
2338
  } catch (error) {
1870
2339
  writeEntryRecord({
1871
2340
  m4a0: "failure",
@@ -1879,4 +2348,4 @@ if (import.meta.main) try {
1879
2348
  process.exit(1);
1880
2349
  }
1881
2350
  //#endregion
1882
- export { HOST_ONLY_PATCH, applyAcpStartupPreference, applyWebStartupPreference, createAcpController, createHostAcpSessionAccess, drainHmrTransactions, finishHostFailureCleanup, runLocalHostEntry };
2351
+ export { HOST_ONLY_PATCH, applyAcpStartupPreference, applyWebStartupPreference, createAcpController, createHostAcpSessionAccess, drainHmrTransactions, finishHostFailureCleanup, routeNativeStopWaiter, runLocalHostEntry };