@xmoon76/dsh-pi-tui 0.5.4 → 0.5.6

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 (50) hide show
  1. package/README.en.md +46 -42
  2. package/README.md +46 -27
  3. package/cordis.patch.yml +77 -7
  4. package/dist/bootstrap-DQ4YPL-7.mjs +113583 -0
  5. package/dist/builtins.mjs +3 -9
  6. package/dist/{runtime-vc4mdr-R.mjs → client-bootstrap-Cr1JCaF5.mjs} +3670 -2277
  7. package/dist/disposal-BYBbEpVY.mjs +54 -0
  8. package/dist/dist-CIsR7cz4.mjs +15717 -0
  9. package/dist/{entry-control-DvSrndWd.mjs → entry-control-DnduyDiw.mjs} +12 -31
  10. package/dist/{extensions-CcuMY4n2.mjs → extensions-Bp0L37lP.mjs} +1239 -271
  11. package/dist/extensions.mjs +1 -1
  12. package/dist/host-bootstrap-DilsvA6f.mjs +281 -0
  13. package/dist/host-foundation-probe--5jtvHVe.mjs +413 -0
  14. package/dist/host-runtime.d.mts +30 -0
  15. package/dist/host-runtime.mjs +1317 -0
  16. package/dist/index.d.mts +19 -18
  17. package/dist/index.mjs +18410 -8836
  18. package/dist/local-client.mjs +2027 -187
  19. package/dist/local-discovery-C9VMjc0K.mjs +759 -0
  20. package/dist/local-discovery-CDaQHA_R.mjs +2 -0
  21. package/dist/local-host.mjs +1088 -87
  22. package/dist/local-transport-BVwFYq_Y.mjs +513 -0
  23. package/dist/{context-summary-DAisTA_7.mjs → pasted-path-range-CMnxuGPx.mjs} +7613 -216
  24. package/dist/pasted-path-range-r6qzV_tC.mjs +17510 -0
  25. package/dist/performance-host.d.mts +2 -2
  26. package/dist/performance-host.mjs +258 -1
  27. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +85 -0
  28. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  29. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +905 -0
  30. package/dist/pi-tui-web-access-contract-BN8Cc_Ho.mjs +118 -0
  31. package/dist/{runtime-status-0lp9CM0V.mjs → runtime-status-Cj1nFOdS.mjs} +72 -214
  32. package/dist/session-BKGXyh80.mjs +15794 -0
  33. package/dist/{session-tdJHLnJR.mjs → session-CPt_U8_f.mjs} +10707 -3657
  34. package/dist/{startup-JaVZoTIl.mjs → startup-7BYWuvBU.mjs} +124 -8
  35. package/dist/startup.d.mts +1 -1
  36. package/dist/startup.mjs +1 -1
  37. package/dist/{client-bootstrap-F5DHFI9t.mjs → terminal-progress-source-DrqQhtT8.mjs} +3653 -2969
  38. package/dist/visual-tools.d.mts +2 -2
  39. package/dist/visual-tools.mjs +26 -31
  40. package/dist/web-preferences.d.mts +29 -0
  41. package/dist/web-preferences.mjs +15 -0
  42. package/dist/web-roster-CjqnUXNk.mjs +285 -0
  43. package/generated/dsh-presets/cordis.patch.yml +5 -3
  44. package/generated/dsh-presets/ptc.patch.yml +7 -7
  45. package/generated/dsh-presets/standard.patch.yml +6 -4
  46. package/package.json +195 -172
  47. package/dist/host-bootstrap-DAgKknbY.mjs +0 -119
  48. package/dist/performance-host-CcDJjjVA.mjs +0 -266
  49. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  50. package/dist/terminal-progress-source-xor3vakJ.mjs +0 -2256
@@ -1,41 +1,583 @@
1
1
  #!/usr/bin/env node
2
- import { i as writeEntryRecord, r as readProcessStartIdentity, t as attachEntryControl } from "./entry-control-DvSrndWd.mjs";
2
+ import { S as scopeFromInstalledProfile, _ as installedPackageRootFromEntry, h as bindProcessSeat, i as cleanupOwnedFiles, m as LocalScopeError, p as LOCAL_PROTOCOL, v as readInstalledDshVersion, x as removeOwnedScratch, y as readLinuxStarttime } from "./local-discovery-C9VMjc0K.mjs";
3
+ import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-DnduyDiw.mjs";
4
+ import { t as PI_TUI_WEB_ACCESS_ROWS } from "./web-roster-CjqnUXNk.mjs";
5
+ import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
6
+ import { r as PI_TUI_WEB_ACCESS_NAMESPACE } from "./pi-tui-web-access-contract-BN8Cc_Ho.mjs";
3
7
  import { createRequire } from "node:module";
4
- import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
5
- import { tmpdir } from "node:os";
8
+ import { randomUUID } from "node:crypto";
9
+ import { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
6
10
  import { join } from "node:path";
7
11
  import { pathToFileURL } from "node:url";
8
- //#region src/app/remote-process/local-host-entry.ts
12
+ //#region src/app/remote-process/host-activity.ts
13
+ /** Every source key always present in a snapshot. */
14
+ const HOST_ACTIVITY_SOURCES = [
15
+ "agent",
16
+ "jobs",
17
+ "goal",
18
+ "schedule",
19
+ "pending",
20
+ "write",
21
+ "other"
22
+ ];
23
+ /** Cordis `FiberState` values used by Loader source qualification. */
24
+ const FIBER_PENDING = 0;
25
+ const FIBER_LOADING = 1;
26
+ const FIBER_ACTIVE = 2;
27
+ const FIBER_FAILED = 3;
28
+ const FIBER_DISPOSED = 4;
29
+ const FIBER_UNLOADING = 5;
9
30
  /**
10
- * M4-A0 Host-only process entry.
11
- *
12
- * Boots the ordinary DSH profile through the real launcher owner
13
- * (`@deepseek-ai/dsh/profile-boot` → `@deepseek-ai/dsh-app-boot` → Loader /
14
- * Include) rather than a hand-built Context. The launcher-owned Host-only
15
- * overlay disables exactly the TUI runner and the Client extension host /
16
- * builtins; every Host-plane row (including `tuiStartup`-gated workspace files,
17
- * the loopback webserver and the performance projection) keeps its production
18
- * source.
19
- *
20
- * The entry is an internal qualification artifact, not a package export or a
21
- * CLI command: the launcher supplies the DSH installation anchor, profile name
22
- * and scratch directory through `SPLIT_PROCESS_DSH_ANCHOR` / `SPLIT_PROCESS_PROFILE` / `SPLIT_PROCESS_SCRATCH`.
23
- *
24
- * @module app/remote-process/local-host-entry
31
+ * Loader rows explicitly qualified as passive in the pinned stock Host
32
+ * composition, bound to BOTH their row id and the exact plugin identity.
33
+ * The map is the rc.4 Host-only roster that was reviewed as passive or as
34
+ * belonging to one of the observer's own source families; `schedule` is
35
+ * qualified when a profile mounts the official Schedule row. A row id reused
36
+ * with a different plugin, an unknown active row, a custom plugin or a future
37
+ * official autonomous service fails closed as an unqualified Host source.
25
38
  */
39
+ const QUALIFIED_HOST_ROWS = new Map(`include=cordis:include plugin-manager=@deepseek-ai/dsh-plugin-manager
40
+ timer=@deepseek-ai/cordis-plugin-timer hmr=@deepseek-ai/dsh-hmr
41
+ llm=@deepseek-ai/dsh-llm deepseek-llm-api-extensions=@deepseek-ai/dsh-deepseek-llm-api-extensions
42
+ session=@deepseek-ai/dsh-session session-log-deepseek=@deepseek-ai/dsh-session-log-deepseek
43
+ typert=@deepseek-ai/dsh-typert-registry typert-loader=@deepseek-ai/dsh-typert-loader
44
+ typert-gateway=@deepseek-ai/dsh-api-gateway remote-access=@deepseek-ai/dsh-api-remote-access
45
+ session-title=@deepseek-ai/dsh-session-title session-title-llm=@deepseek-ai/dsh-session-title-first-prompt-llm
46
+ user-questions=@deepseek-ai/dsh-user-questions agent=@deepseek-ai/dsh-agent
47
+ plugin-package-inventory-deepseek=@deepseek-ai/dsh-plugin-package-inventory-deepseek agent-default-model=@deepseek-ai/dsh-agent-default-model
48
+ jobs=@deepseek-ai/dsh-jobs-local llm-retry=@deepseek-ai/dsh-llm-retry
49
+ config-editor=@deepseek-ai/dsh-config-editor settings=@deepseek-ai/dsh-settings
50
+ authorization=@deepseek-ai/dsh-authorization deepseek-account=@deepseek-ai/dsh-deepseek-account-platform
51
+ credentials=@deepseek-ai/dsh-credentials-local llm-pi-ai=@deepseek-ai/dsh-llm-pi-ai
52
+ session-persistence-jsonl=@deepseek-ai/dsh-session-persistence-jsonl attachment-local=@deepseek-ai/dsh-attachment-local
53
+ session-query-sqlite=@deepseek-ai/dsh-session-query-sqlite working-directory=@deepseek-ai/dsh-working-directory
54
+ tool-working-directory=@deepseek-ai/dsh-tool-working-directory session-projection=@deepseek-ai/dsh-session-projection
55
+ storage=@deepseek-ai/dsh-storage storage-json=@deepseek-ai/dsh-storage-json
56
+ storage-domain=@deepseek-ai/dsh-storage-domain session-projection-cache=@deepseek-ai/dsh-session-projection-cache
57
+ otel=@deepseek-ai/dsh-otel session-telemetry-otel=@deepseek-ai/dsh-session-telemetry-otel
58
+ subprocess=@deepseek-ai/dsh-subprocess-local sandbox=@deepseek-ai/dsh-sandbox-local
59
+ sandbox-policy=@deepseek-ai/dsh-sandbox-policy bash-sandbox=@deepseek-ai/dsh-bash-sandbox
60
+ approval=@deepseek-ai/dsh-user-approval permission=@deepseek-ai/dsh-permission-presets
61
+ shell-env=@deepseek-ai/dsh-shell-env fs-observation-policy=@deepseek-ai/dsh-fs-observation-policy
62
+ skill=@deepseek-ai/dsh-skill commands=@deepseek-ai/dsh-commands
63
+ command-feedback=@deepseek-ai/dsh-command-feedback goal=@deepseek-ai/dsh-goal
64
+ goal-round-driver=@deepseek-ai/dsh-goal-round-driver token-meter=@deepseek-ai/dsh-token-meter
65
+ subagent=@deepseek-ai/dsh-subagent subagent-spawn-in-process=@deepseek-ai/dsh-subagent-spawn-in-process
66
+ subagent-fork-in-process=@deepseek-ai/dsh-subagent-fork-in-process ptc-runtime=@deepseek-ai/dsh-ptc-runtime-node
67
+ timeout-policy=@deepseek-ai/dsh-tool-call-timeout-policy spill-local=@deepseek-ai/dsh-spill-local
68
+ spill-policy=@deepseek-ai/dsh-spill-policy session-checkpoint-policy=@deepseek-ai/dsh-session-checkpoint-policy
69
+ image-offload=@deepseek-ai/dsh-compaction-image-offload repeat-tool-reminder=@deepseek-ai/dsh-repeat-tool-reminder
70
+ web=@deepseek-ai/dsh-web web-search-deepseek=@deepseek-ai/dsh-web-search-deepseek
71
+ web-deepseek-api=@deepseek-ai/dsh-web-deepseek-api web-fetch-http=@deepseek-ai/dsh-web-fetch-http
72
+ mcp-resources=@deepseek-ai/dsh-mcp-resources tools=@deepseek-ai/dsh-tools
73
+ system-prompt=@deepseek-ai/dsh-system-prompt agent-loop=@deepseek-ai/dsh-agent-loop
74
+ fs-sandbox=@deepseek-ai/dsh-fs-sandbox llm-deepseek=@deepseek-ai/dsh-llm-deepseek-api-key
75
+ llm-deepseek-account=@deepseek-ai/dsh-llm-deepseek-account tui-startup=@xmoon76/dsh-pi-tui/startup
76
+ pi-tui-performance-host=@xmoon76/dsh-pi-tui/performance-host workspace-files=@deepseek-ai/dsh-api-workspace-files
77
+ pi-tui-visual-tools=@xmoon76/dsh-pi-tui/visual-tools webserver=@deepseek-ai/dsh-host-webserver
78
+ job-controller=@deepseek-ai/dsh-api-job-controller workspace=@deepseek-ai/dsh-workspace
79
+ file-reference-local=@deepseek-ai/dsh-file-reference-local agent-preset-registry=@deepseek-ai/dsh-agent-preset-registry
80
+ subagent-model-selection-settings=@deepseek-ai/dsh-tool-subagent/model-selection-settings cordis-host-runner=@deepseek-ai/dsh-cordis-host-runner
81
+ preset-standard=@deepseek-ai/dsh-agent-preset preset-ptc=@deepseek-ai/dsh-agent-preset
82
+ preset-minimal=@deepseek-ai/dsh-agent-preset preset-cordis=@deepseek-ai/dsh-agent-preset
83
+ split-host-connection=@deepseek-ai/dsh-client-connection split-host-api-remotes=@deepseek-ai/dsh-api-remotes
84
+ split-host-file-upload=@deepseek-ai/dsh-client-file-upload split-host-session-stats=@deepseek-ai/dsh-session-stats
85
+ split-host-turn-outline=@deepseek-ai/dsh-session-turn-outline split-host-session-controller=@deepseek-ai/dsh-api-session-controller
86
+ split-host-settings-controller=@deepseek-ai/dsh-api-settings-controller split-host-session-log-download=@deepseek-ai/dsh-session-log-export
87
+ split-host-pi-tui-runtime=@xmoon76/dsh-pi-tui/host-runtime schedule=@deepseek-ai/dsh-schedule`.trim().split(/\s+/u).map((entry) => {
88
+ const separator = entry.indexOf("=");
89
+ return [entry.slice(0, separator), entry.slice(separator + 1)];
90
+ }));
91
+ /** Reasons that positively establish current work or a future keepalive obligation. */
92
+ const BLOCKING_REASONS = /* @__PURE__ */ new Set([
93
+ "agent-running",
94
+ "agent-inbox",
95
+ "goal-armed",
96
+ "job-running",
97
+ "job-stopping",
98
+ "child-active",
99
+ "schedule-active"
100
+ ]);
101
+ /** The dedicated timeout marker: a hung read is UNKNOWN, never an empty source. */
102
+ const OBSERVATION_TIMEOUT = Symbol("host-activity-observation-timeout");
103
+ /** Reject a source read after the caller's bound. */
104
+ async function withDeadline(operation, deadlineMs) {
105
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return operation;
106
+ let timer;
107
+ const deadline = new Promise((_resolve, reject) => {
108
+ timer = setTimeout(() => {
109
+ reject(OBSERVATION_TIMEOUT);
110
+ }, deadlineMs);
111
+ });
112
+ try {
113
+ return await Promise.race([operation, deadline]);
114
+ } finally {
115
+ if (timer !== void 0) clearTimeout(timer);
116
+ }
117
+ }
118
+ /** Build one ordered, deduplicated reason list. */
119
+ function reasonList(reasons) {
120
+ return [...reasons];
121
+ }
122
+ /** A snapshot that claims nothing after the observer stopped reading. */
123
+ function closedSnapshot(epoch) {
124
+ return {
125
+ verdict: "UNKNOWN",
126
+ epoch,
127
+ reasons: ["source-unavailable"],
128
+ sourceStates: Object.fromEntries(HOST_ACTIVITY_SOURCES.map((source) => [source, "UNKNOWN"]))
129
+ };
130
+ }
131
+ /**
132
+ * The Host-process observer. Construction only subscribes to official live
133
+ * signals and starts no work; snapshot() performs the reads.
134
+ */
135
+ var HostActivityObserver = class {
136
+ context;
137
+ observationDeadlineMs;
138
+ subscriptions = [];
139
+ /** Short-lived active Job identity hints: official list reads stay authoritative. */
140
+ jobHints = /* @__PURE__ */ new Map();
141
+ /** Services observed in this Host process; a later absence is UNKNOWN, not ABSENT. */
142
+ seenSources = /* @__PURE__ */ new Set();
143
+ currentEpoch = 0;
144
+ closed = false;
145
+ constructor(context, options = {}) {
146
+ this.context = context;
147
+ this.observationDeadlineMs = options.observationDeadlineMs ?? 3e3;
148
+ try {
149
+ this.subscribe();
150
+ } catch (error) {
151
+ this.closed = true;
152
+ for (const dispose of this.subscriptions.splice(0).reverse()) dispose();
153
+ throw error;
154
+ }
155
+ }
156
+ /** Subscribe to the official change signals that invalidate a snapshot. */
157
+ subscribe() {
158
+ const invalidate = () => {
159
+ this.invalidate();
160
+ };
161
+ for (const event of [
162
+ "agent/created",
163
+ "agent/disposed",
164
+ "agent/status",
165
+ "agent/inbox/inserted",
166
+ "agent/inbox/claimed",
167
+ "agent/inbox/discarded",
168
+ "goal/changed",
169
+ "schedule/changed",
170
+ "internal/status"
171
+ ]) this.subscriptions.push(this.context.on(event, invalidate));
172
+ const jobs = this.context.reflect.get("jobs");
173
+ if (jobs === void 0) return;
174
+ this.seenSources.add("jobs");
175
+ this.subscriptions.push(jobs.events.subscribe({ owners: "all" }, (event) => {
176
+ if (event.type === "output" || event.type === "progress") return;
177
+ const job = event.job;
178
+ if (job !== void 0) {
179
+ if (event.type === "registered") this.jobHints.set(job.id, job.status === "stopping" ? "stopping" : "running");
180
+ else if (event.type === "stopping") this.jobHints.set(job.id, "stopping");
181
+ else if (event.type === "settled" || event.type === "removed") this.jobHints.delete(job.id);
182
+ }
183
+ this.invalidate();
184
+ }));
185
+ }
186
+ /** Advance the epoch and refresh which services are currently mounted. */
187
+ invalidate() {
188
+ if (this.closed) return;
189
+ this.currentEpoch += 1;
190
+ this.noteMountedSources();
191
+ }
192
+ /** Remember every source service seen in this process. */
193
+ noteMountedSources() {
194
+ if (this.context.reflect.get("jobs") !== void 0) this.seenSources.add("jobs");
195
+ if (this.context.reflect.get("goals") !== void 0) this.seenSources.add("goal");
196
+ if (this.context.reflect.get("schedule") !== void 0) this.seenSources.add("schedule");
197
+ if (this.context.reflect.get("typertGateway") !== void 0) this.seenSources.add("pending");
198
+ if (this.context.reflect.get("sessionPersistence") !== void 0) this.seenSources.add("write");
199
+ }
200
+ /** Map a missing service to ABSENT (never mounted) or UNKNOWN (mounted earlier). */
201
+ unavailableState(source, reasons) {
202
+ if (!this.seenSources.has(source)) return "ABSENT";
203
+ reasons.add("source-unavailable");
204
+ return "UNKNOWN";
205
+ }
206
+ /** Read every live Agent (children included) and classify current work. */
207
+ readAgents(reasons) {
208
+ const registry = this.context.reflect.get("agents");
209
+ if (registry === void 0) {
210
+ reasons.add("source-unavailable");
211
+ return {
212
+ state: "UNKNOWN",
213
+ agents: [],
214
+ readable: false
215
+ };
216
+ }
217
+ let agents;
218
+ try {
219
+ agents = registry.list();
220
+ } catch {
221
+ reasons.add("source-unavailable");
222
+ return {
223
+ state: "UNKNOWN",
224
+ agents: [],
225
+ readable: false
226
+ };
227
+ }
228
+ let roots;
229
+ if (typeof registry.roots === "function") try {
230
+ roots = new Set(registry.roots());
231
+ } catch {
232
+ roots = void 0;
233
+ }
234
+ let state = "IDLE";
235
+ let maintenanceGap = false;
236
+ for (const agent of agents) {
237
+ let running;
238
+ let pending;
239
+ try {
240
+ running = agent.status === "running";
241
+ pending = agent.inbox.nextTurn.length + agent.inbox.nextStep.length;
242
+ } catch {
243
+ reasons.add("source-unavailable");
244
+ return {
245
+ state: "UNKNOWN",
246
+ agents,
247
+ readable: false
248
+ };
249
+ }
250
+ if (running) {
251
+ reasons.add("agent-running");
252
+ state = "ACTIVE";
253
+ }
254
+ if (pending > 0) {
255
+ reasons.add("agent-inbox");
256
+ state = "ACTIVE";
257
+ }
258
+ if (!running && pending === 0) maintenanceGap = true;
259
+ if (roots !== void 0 && !roots.has(agent) && (running || pending > 0)) reasons.add("child-active");
260
+ }
261
+ if (maintenanceGap) {
262
+ reasons.add("agent-maintenance-unproven");
263
+ if (state === "IDLE") state = "UNKNOWN";
264
+ }
265
+ return {
266
+ state,
267
+ agents,
268
+ readable: true
269
+ };
270
+ }
271
+ /** Read the official Goal view for every live Agent. */
272
+ readGoals(agents, agentsReadable, reasons) {
273
+ const goals = this.context.reflect.get("goals");
274
+ if (goals === void 0) return this.unavailableState("goal", reasons);
275
+ this.seenSources.add("goal");
276
+ if (!agentsReadable) {
277
+ reasons.add("source-unavailable");
278
+ return "UNKNOWN";
279
+ }
280
+ let state = "IDLE";
281
+ for (const agent of agents) {
282
+ let goal;
283
+ try {
284
+ goal = goals.get(agent);
285
+ } catch {
286
+ reasons.add("source-unavailable");
287
+ return "UNKNOWN";
288
+ }
289
+ if (goal !== void 0 && goal.phase === "active" && goal.activation === "armed") {
290
+ reasons.add("goal-armed");
291
+ state = "ACTIVE";
292
+ }
293
+ }
294
+ return state;
295
+ }
296
+ /** Merge the unowned list, every live Agent's owner-scoped list, and job hints. */
297
+ readJobs(agents, agentsReadable, reasons) {
298
+ const jobs = this.context.reflect.get("jobs");
299
+ if (jobs === void 0) return this.unavailableState("jobs", reasons);
300
+ this.seenSources.add("jobs");
301
+ const byId = /* @__PURE__ */ new Map();
302
+ try {
303
+ for (const job of jobs.list()) byId.set(job.id, job);
304
+ if (agentsReadable) for (const agent of agents) for (const job of jobs.list(agent.id)) byId.set(job.id, job);
305
+ } catch {
306
+ reasons.add("source-unavailable");
307
+ return "UNKNOWN";
308
+ }
309
+ for (const [id, status] of this.jobHints) if (!byId.has(id)) byId.set(id, {
310
+ id,
311
+ status
312
+ });
313
+ let state = "IDLE";
314
+ for (const job of byId.values()) if (job.status === "running") {
315
+ reasons.add("job-running");
316
+ state = "ACTIVE";
317
+ } else if (job.status === "stopping") {
318
+ reasons.add("job-stopping");
319
+ state = "ACTIVE";
320
+ }
321
+ if (!agentsReadable) {
322
+ reasons.add("source-unavailable");
323
+ if (state === "IDLE") return "UNKNOWN";
324
+ }
325
+ return state;
326
+ }
327
+ /** Read the official Host Schedule catalog when the service is actually mounted. */
328
+ async readSchedule(reasons) {
329
+ const schedule = this.context.reflect.get("schedule");
330
+ if (schedule === void 0) return this.unavailableState("schedule", reasons);
331
+ this.seenSources.add("schedule");
332
+ let entries;
333
+ try {
334
+ entries = await withDeadline(schedule.catalog(), this.observationDeadlineMs);
335
+ } catch {
336
+ reasons.add("source-unavailable");
337
+ return "UNKNOWN";
338
+ }
339
+ let state = "IDLE";
340
+ for (const entry of entries) if (entry.status === "active") {
341
+ reasons.add("schedule-active");
342
+ state = "ACTIVE";
343
+ }
344
+ return state;
345
+ }
346
+ /** rc.4 cannot enumerate Gateway pending interactions. */
347
+ readPending(reasons) {
348
+ if (this.context.reflect.get("typertGateway") === void 0) return this.unavailableState("pending", reasons);
349
+ this.seenSources.add("pending");
350
+ reasons.add("pending-interaction-unobservable");
351
+ return "UNKNOWN";
352
+ }
353
+ /** rc.4 cannot enumerate in-flight Session writes. */
354
+ readWrite(reasons) {
355
+ if (this.context.reflect.get("sessionPersistence") === void 0) return this.unavailableState("write", reasons);
356
+ this.seenSources.add("write");
357
+ reasons.add("inflight-write-unproven");
358
+ return "UNKNOWN";
359
+ }
360
+ /** Active Loader rows outside the official/xmoon namespaces are unqualified. */
361
+ readOther(reasons) {
362
+ const loader = this.context.loader;
363
+ if (loader === void 0) {
364
+ reasons.add("source-unavailable");
365
+ return "UNKNOWN";
366
+ }
367
+ let entries;
368
+ try {
369
+ entries = [...loader.entries()];
370
+ } catch {
371
+ reasons.add("source-unavailable");
372
+ return "UNKNOWN";
373
+ }
374
+ for (const entry of entries) {
375
+ const state = entry.fiber?.state;
376
+ if (state === void 0 || state === FIBER_PENDING || state === FIBER_DISPOSED) continue;
377
+ const id = entry.options?.id ?? "";
378
+ const name = entry.options?.name ?? "";
379
+ const qualified = QUALIFIED_HOST_ROWS.get(id) === name;
380
+ if (state === FIBER_FAILED) {
381
+ reasons.add("source-unavailable");
382
+ return "UNKNOWN";
383
+ }
384
+ if (state === FIBER_ACTIVE) {
385
+ if (qualified) continue;
386
+ reasons.add("unqualified-host-source");
387
+ return "UNKNOWN";
388
+ }
389
+ if (state === FIBER_LOADING || state === FIBER_UNLOADING) {
390
+ reasons.add(qualified ? "source-unavailable" : "unqualified-host-source");
391
+ return "UNKNOWN";
392
+ }
393
+ reasons.add("source-unavailable");
394
+ return "UNKNOWN";
395
+ }
396
+ return "IDLE";
397
+ }
398
+ /** Read one bounded snapshot from the real Host services. */
399
+ async snapshot() {
400
+ if (this.closed) return closedSnapshot(this.currentEpoch);
401
+ const startEpoch = this.currentEpoch;
402
+ this.noteMountedSources();
403
+ const reasons = /* @__PURE__ */ new Set();
404
+ const sourceStates = {};
405
+ const agents = this.readAgents(reasons);
406
+ sourceStates.agent = agents.state;
407
+ sourceStates.goal = this.readGoals(agents.agents, agents.readable, reasons);
408
+ sourceStates.jobs = this.readJobs(agents.agents, agents.readable, reasons);
409
+ sourceStates.schedule = await this.readSchedule(reasons);
410
+ sourceStates.pending = this.readPending(reasons);
411
+ sourceStates.write = this.readWrite(reasons);
412
+ sourceStates.other = this.readOther(reasons);
413
+ if (this.closed) return closedSnapshot(this.currentEpoch);
414
+ const endEpoch = this.currentEpoch;
415
+ if (startEpoch !== endEpoch) reasons.add("observation-changed");
416
+ let verdict;
417
+ if ([...reasons].some((reason) => BLOCKING_REASONS.has(reason))) verdict = "BLOCKED";
418
+ else if (reasons.size > 0) verdict = "UNKNOWN";
419
+ else verdict = "OBSERVED_QUIESCENT";
420
+ return {
421
+ verdict,
422
+ epoch: endEpoch,
423
+ reasons: reasonList(reasons),
424
+ sourceStates
425
+ };
426
+ }
427
+ /** Release every subscription synchronously and ignore late callbacks. */
428
+ close() {
429
+ if (this.closed) return;
430
+ this.closed = true;
431
+ const subscriptions = this.subscriptions.splice(0);
432
+ for (const dispose of subscriptions.reverse()) dispose();
433
+ }
434
+ };
26
435
  /**
27
436
  * The Host-only overlay applied over the profile's own patch stack. It keeps
28
- * `tui-startup` mounted (the Host rows gated on `tuiStartup` need its parsed
29
- * facts) and disables only the three surface rows that must not exist in a
30
- * Host-only PID.
437
+ * `tui-startup` mounted for the consumers that genuinely need its parsed
438
+ * startup facts, but the Host execution rows never use that mutable provider
439
+ * as their Dispose gate: reloading `tui-startup` must not dispose
440
+ * already-accepted Host Session/Agent/Connection ownership. It disables only
441
+ * the three surface rows that must not exist in a Host-only PID, then adds the
442
+ * two B1 rows plus the official Session-serving rows and the ONE built-in
443
+ * PiTui Host Runtime row. The base Gateway, webserver, workspace-files,
444
+ * workspace-controller, credentials, agents, sessions and jobs are reused,
445
+ * never mounted twice.
31
446
  */
32
- const HOST_ONLY_PATCH = `# M4-A0 Host-only profile overlay: production Host rows only.
447
+ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows only.
33
448
  - id: tui-app
34
449
  disabled: true
35
450
  - id: pi-tui-extension-host
36
451
  disabled: true
37
452
  - id: pi-tui-builtins
38
453
  disabled: true
454
+
455
+ # Infrastructure lifetime is independent of the mutable tuiStartup provider.
456
+ - id: webserver
457
+ inject: []
458
+ - id: workspace-files
459
+ inject: []
460
+ # The bundle's ONE official Workspace Controller row, retuned IN PLACE: the
461
+ # Host is a long-lived Workspace Remote owner, not a CLI startup side effect,
462
+ # yet the row (its ID, package, config and the class's own
463
+ # remoteAccess/typert/workspaceRegistry injects) stays the bundle's. A second
464
+ # row here would register the \`workspace\` namespace twice.
465
+ - id: workspace-controller
466
+ inject: []
467
+
468
+ # Host Schedule management (S5-PR4): the bundle's ONE official Schedule row
469
+ # stays this bundle's row; the overlay only drops its Direct tuiStartup
470
+ # admission gate so the Host timer keeps running after the Client and the Web
471
+ # UI are gone. sessionController remains the readiness barrier and resolves to
472
+ # the existing split-host-session-controller below. Never insert a second
473
+ # Schedule row here.
474
+ - id: pi-tui-schedule
475
+ inject: [sessionController]
476
+ # The three Direct-only activation prerequisites are DISABLED here: the
477
+ # overlay already mounts the split-host-connection / split-host-file-upload /
478
+ # split-host-session-controller rows exactly once, and a second Connection,
479
+ # FileUploads or Session controller would give one Host PID two owners.
480
+ - id: pi-tui-direct-connection
481
+ disabled: true
482
+ - id: pi-tui-direct-file-upload
483
+ disabled: true
484
+ - id: pi-tui-direct-session-controller
485
+ disabled: true
486
+
487
+ - insert:
488
+ # One official Connection owner (loopback /connect + /api) behind the
489
+ # profile's existing webserver (whose Host-only lifetime is independent of
490
+ # tuiStartup). trustedHosts stays empty: loopback and the listener's own
491
+ # bind IP are the only accepted authorities.
492
+ - id: split-host-connection
493
+ name: '@deepseek-ai/dsh-client-connection'
494
+ inject: [credentials, webServer]
495
+ config:
496
+ trustedHosts: []
497
+
498
+ # One forwarded-event source on the base typert-gateway row. It registers
499
+ # host.home and the private $events stream; the gateway is not remounted.
500
+ - id: split-host-api-remotes
501
+ name: '@deepseek-ai/dsh-api-remotes'
502
+ inject: [typertGateway, connection]
503
+
504
+ # Official Session-serving Host rows (rc.4): each is mounted ONCE here and
505
+ # never re-mounted by the built-in PiTui Host Runtime or the Client.
506
+ - id: split-host-file-upload
507
+ name: '@deepseek-ai/dsh-client-file-upload'
508
+ inject: [agents, attachments, commands, connection]
509
+
510
+ - id: split-host-session-stats
511
+ name: '@deepseek-ai/dsh-session-stats'
512
+ inject: [sessionProjections]
513
+
514
+ - id: split-host-turn-outline
515
+ name: '@deepseek-ai/dsh-session-turn-outline'
516
+ inject: [sessionProjections]
517
+
518
+ - id: split-host-session-controller
519
+ name: '@deepseek-ai/dsh-api-session-controller'
520
+ inject: [agentDefaultModel, agents, attachments, fileUploads, fs, llm, remoteAccess, sessions, sessionProjections, sessionQuery, typert, workspaceRegistry]
521
+ config:
522
+ nativeOpen: false
523
+
524
+ - id: split-host-settings-controller
525
+ name: '@deepseek-ai/dsh-api-settings-controller'
526
+ inject: [typert]
527
+
528
+ - id: split-host-session-log-download
529
+ name: '@deepseek-ai/dsh-session-log-export'
530
+ inject: [commands, connection]
531
+
532
+ # The package's ONE built-in Host Runtime row: the private contribution plus
533
+ # the three private business services. Business features are NOT separate
534
+ # Loader rows or package subpaths.
535
+ - id: split-host-pi-tui-runtime
536
+ name: '@xmoon76/dsh-pi-tui/host-runtime'
537
+ inject: [typert, agents, fileReferences, workingDirectory]
538
+
539
+ # ── Official Web composition (M5-W PR-A/PR-B/PR-C) ──────────────────────────
540
+ # The official Browser Web rows, declared here ONCE and DISABLED BY DEFAULT.
541
+ # This declaration is the ONE roster the private 'piTuiWebAccess' Host service
542
+ # toggles at runtime: it flips 'disabled' on exactly these rows through
543
+ # 'Entry.update', never a second declaration, never a profile patch write, and
544
+ # never a separate Web process. The toggle is per Host lifetime; a cold boot
545
+ # starts from this default-off state UNLESS the profile's own
546
+ # 'pi-tui-web-preferences.autoStart' preference is on, in which case the boot
547
+ # sequence below enables the same roster before Ready ('/web' remains the
548
+ # immediate control of a running Host).
549
+ # Only the isolated qualification runs additionally override rows through
550
+ # SPLIT_PROCESS_EXTRA_PATCH; that internal test channel is not a user API.
551
+ #
552
+ # The roster is the official browser graph of the installed DSH family minus
553
+ # every row whose authority ALREADY exists in this Host: the second
554
+ # 'connection', 'api-remotes', 'file-upload', 'workspace'/'workspace-controller',
555
+ # 'session-controller', 'settings-controller', 'webserver', 'frontend-static'
556
+ # fallback and 'web-startup' parser are NOT declared here. The mandatory
557
+ # client-dependency closure of the official UIs ('ui-context-menu',
558
+ # 'ui-file-drag'), the official Client file-actions / message-quotes features
559
+ # and the 'workspace-changes' Host recorder that 'ui-deliverables' injects are
560
+ # part of it. 'workspace-changes' is declared BEFORE its consumer because the
561
+ # toggle activates one row at a time and awaits each fiber.
562
+ # 'terminal-controller' is the ONE official Host row added on top of the
563
+ # browser roster (the real Browser x TUI composition needs it).
564
+ #
565
+ # 'web-runtime' owns the single 'frontend-static' fallback over the official
566
+ # dist and is explicitly told to stay silent: no browser launch, no printed
567
+ # token URL and no DSH_WEB_URL shell variable.
568
+ - insert:
569
+ ${PI_TUI_WEB_ACCESS_ROWS.map(({ id, name }) => [
570
+ ` - id: ${id}`,
571
+ ` name: '${name}'`,
572
+ " disabled: true",
573
+ ...id === "web-runtime" ? [
574
+ " inject: [webServer]",
575
+ " config:",
576
+ " openBrowser: false",
577
+ " printUrl: false",
578
+ " surfaceContext: false"
579
+ ] : []
580
+ ].join("\n")).join("\n")}
39
581
  `;
40
582
  /** Resolve one published DSH subpath from the installation anchor supplied by the launcher. */
41
583
  async function loadOfficialDsh(anchor) {
@@ -43,92 +585,551 @@ async function loadOfficialDsh(anchor) {
43
585
  const importResolved = async (specifier) => import(pathToFileURL(requireFromDsh.resolve(specifier)).href);
44
586
  const profileBoot = await importResolved("@deepseek-ai/dsh/profile-boot");
45
587
  const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
588
+ const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
46
589
  return {
47
590
  runProfile: profileBoot.runProfile,
48
- loadLayeredEnv: appBoot.loadLayeredEnv
591
+ loadLayeredEnv: appBoot.loadLayeredEnv,
592
+ resolveDshHome: homePaths.resolveDshHome,
593
+ resolveProfileDir: appBoot.resolveProfileDir
594
+ };
595
+ }
596
+ /** Wait for one unauthenticated route to answer with the expected refusal. */
597
+ async function waitForRefusal(url, timeoutMs = 1e4) {
598
+ const deadline = Date.now() + timeoutMs;
599
+ while (Date.now() < deadline) {
600
+ try {
601
+ const response = await fetch(url, {
602
+ method: "GET",
603
+ redirect: "manual",
604
+ cache: "no-store"
605
+ });
606
+ await response.body?.cancel();
607
+ if (response.status === 401) return;
608
+ } catch {}
609
+ await new Promise((resolve) => setTimeout(resolve, 100));
610
+ }
611
+ throw new Error(`local host entry: the official route did not become ready: ${url}`);
612
+ }
613
+ /** Qualification-only publication/stop barrier; production never sets either path. */
614
+ async function waitForQualificationBarrier(path) {
615
+ const deadline = Date.now() + 3e4;
616
+ while (!existsSync(path)) {
617
+ if (Date.now() > deadline) throw new Error(`local host entry: the qualification barrier was not released: ${path}`);
618
+ await new Promise((resolve) => setTimeout(resolve, 20));
619
+ }
620
+ }
621
+ /** The profile entry that owns the Web startup preference. */
622
+ const WEB_STARTUP_PREFERENCE_NAMESPACE = "pi-tui-web-preferences";
623
+ /**
624
+ * Apply the profile-owned Web startup preference BEFORE the Host becomes Ready.
625
+ *
626
+ * `autoStart` is read from the SAME `ctx` that already settled the profile: a
627
+ * missing settings service or a missing `pi-tui-web-preferences` section is a
628
+ * corrupted composition and fails the Host startup loudly (never "treated as
629
+ * Off"), while a failing Web enable is a bounded diagnostic: the Host keeps its
630
+ * Session/Agent/Gateway graph and publishes Ready with the Web frontend in
631
+ * whatever state the private service truthfully reports.
632
+ *
633
+ * The diagnostic is a FIXED record: a failure category and (when the service
634
+ * answered at all) the Host's own small state vocabulary. It never carries an
635
+ * exception message — a Host, Connection, Loader or plugin error text could
636
+ * contain a URL, launch token, cookie or profile path, which this pre-Ready path
637
+ * must never publish.
638
+ *
639
+ * @param context - the Host context that already settled the profile.
640
+ * @param emit - the structured record sink (the entry emits on its control channel).
641
+ */
642
+ async function applyWebStartupPreference(context, emit = writeEntryRecord) {
643
+ const settings = context.get("settings");
644
+ if (settings === void 0 || typeof settings.describe !== "function") throw new Error("local host entry: the Host has no settings service, so the Web startup preference cannot be read");
645
+ const descriptor = (settings.describe() ?? []).find((entry) => entry.ns === WEB_STARTUP_PREFERENCE_NAMESPACE);
646
+ if (descriptor === void 0) throw new Error("local host entry: the profile projects no \"pi-tui-web-preferences\" settings section");
647
+ const value = descriptor.value;
648
+ const autoStart = typeof value === "object" && value !== null && !Array.isArray(value) ? value.autoStart : void 0;
649
+ if (typeof autoStart !== "boolean") throw new Error("local host entry: \"pi-tui-web-preferences.autoStart\" is not a boolean");
650
+ if (!autoStart) return;
651
+ const unavailable = (failure, state) => {
652
+ emit({
653
+ m4a0: "diagnostic",
654
+ processRole: "host",
655
+ pid: process.pid,
656
+ code: "web-autostart-unavailable",
657
+ failure,
658
+ ...state === void 0 ? {} : { state }
659
+ });
660
+ };
661
+ const service = context.get(PI_TUI_WEB_ACCESS_NAMESPACE);
662
+ if (service === void 0) {
663
+ unavailable("service-missing");
664
+ return;
665
+ }
666
+ let status;
667
+ try {
668
+ status = await service.setEnabled(true);
669
+ } catch {
670
+ unavailable("mutation-failed");
671
+ return;
672
+ }
673
+ if (status.state !== "enabled") {
674
+ unavailable("not-enabled", status.state);
675
+ return;
676
+ }
677
+ emit({
678
+ m4a0: "web-autostart",
679
+ processRole: "host",
680
+ pid: process.pid,
681
+ phase: "pre-ready",
682
+ status: "enabled"
683
+ });
684
+ }
685
+ /**
686
+ * Publish the authenticated identity and private launch material, then commit
687
+ * the registry as the Ready step. The route is registered before the registry
688
+ * so no Client can observe a registry whose identity route is missing.
689
+ */
690
+ async function publishLocalHost(context, scope, processStarttime) {
691
+ const connection = context.get("connection");
692
+ if (connection === void 0 || typeof connection.authenticatedUrl !== "function" || typeof connection.fetch?.register !== "function") throw new Error("local host entry: the official Connection service is not live");
693
+ const webServer = context.get("webServer");
694
+ if (webServer === void 0 || webServer.host !== "127.0.0.1" || webServer.port < 1) throw new Error("local host entry: the official webserver is not a bound loopback listener");
695
+ const origin = webServer.getOrigin();
696
+ if (!origin.startsWith("http://127.0.0.1:") || !/^\d+$/u.test(origin.slice(17))) throw new Error("local host entry: B1 requires one canonical loopback HTTP origin");
697
+ await waitForRefusal(`${origin}/connect`);
698
+ const instanceId = randomUUID();
699
+ const identity = {
700
+ schema: 1,
701
+ scopeId: scope.scopeId,
702
+ profileRealpath: scope.profileRealpath,
703
+ instanceId,
704
+ hostPid: process.pid,
705
+ hostStarttime: processStarttime,
706
+ origin,
707
+ protocol: LOCAL_PROTOCOL,
708
+ bundleVersion: scope.bundleVersion,
709
+ dshVersion: scope.dshVersion,
710
+ buildId: scope.buildId
711
+ };
712
+ const connectUrl = connection.authenticatedUrl(`${origin}/connect`);
713
+ const connectProbe = new URL(connectUrl);
714
+ if (connectProbe.origin !== origin || connectProbe.pathname !== "/connect" || connectProbe.searchParams.getAll("token").length !== 1 || [...connectProbe.searchParams.keys()].length !== 1) throw new Error("local host entry: the Connection owner returned an unexpected launch URL");
715
+ const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-CDaQHA_R.mjs");
716
+ writeLaunchMaterial(scope, identity, {
717
+ schema: 1,
718
+ instanceId,
719
+ connectUrl
720
+ });
721
+ let unregister;
722
+ try {
723
+ unregister = connection.fetch.register({
724
+ path: "/api/pi-tui.local-host",
725
+ methods: ["GET"],
726
+ requestBody: "buffered",
727
+ fetch: async () => Response.json(identity, { headers: {
728
+ "content-type": "application/json",
729
+ "cache-control": "no-store"
730
+ } })
731
+ });
732
+ await waitForRefusal(`${origin}/api/pi-tui.local-host`);
733
+ writeLocalRecord(scope, identity);
734
+ const barrier = process.env.SPLIT_PROCESS_HOST_PUBLISH_BARRIER;
735
+ if (barrier !== void 0 && barrier !== "") await waitForQualificationBarrier(barrier);
736
+ } catch (error) {
737
+ try {
738
+ await unregister?.();
739
+ } catch {}
740
+ cleanupOwnedFiles(scope, instanceId);
741
+ throw error;
742
+ }
743
+ return {
744
+ identity,
745
+ async unregisterIdentity() {
746
+ await unregister?.();
747
+ }
49
748
  };
50
749
  }
51
750
  /**
751
+ * Run one Host-only process and remove only the scratch this process created
752
+ * under its independently derived real scope. A failure anywhere before the
753
+ * post-boot controller (official-module load, scope construction, kernel seat,
754
+ * overlay write, starttime read or profile boot) still passes through this
755
+ * owner-safe finally; the launcher-supplied path and another live Host's
756
+ * scratch are never deletion authority. A forced `process.exit()` from the
757
+ * launcher's native signal handler during `runProfile` bypasses the async
758
+ * finally, so a synchronous exit mirror below removes the same owned scratch.
759
+ */
760
+ async function runLocalHostEntry(options) {
761
+ const owned = {};
762
+ process.once("exit", () => {
763
+ if (owned.scopeDir !== void 0 && owned.scratchDir !== void 0) removeOwnedScratch(owned.scopeDir, owned.scratchDir);
764
+ });
765
+ try {
766
+ await runLocalHostEntryOwned(options, owned);
767
+ } finally {
768
+ if (owned.scopeDir !== void 0 && owned.scratchDir !== void 0) removeOwnedScratch(owned.scopeDir, owned.scratchDir);
769
+ }
770
+ }
771
+ /**
52
772
  * Run one Host-only process until its launcher requests shutdown. Exported so
53
773
  * the process-level qualification harness can document its exact contract; the
54
774
  * module's `import.meta.main` block is the only caller in production.
55
775
  */
56
- async function runLocalHostEntry(options) {
57
- const { dshAnchor, profile, scratchDir } = options;
58
- mkdirSync(scratchDir, { recursive: true });
59
- const overlayPath = join(scratchDir, "host-only.patch.yml");
60
- writeFileSync(overlayPath, HOST_ONLY_PATCH);
61
- const dsh = await loadOfficialDsh(dshAnchor);
62
- const processStartIdentity = readProcessStartIdentity();
63
- process.env.DSH_PI_TUI_ROLE = "host";
64
- if (process.argv[1] !== void 0) process.env.DSH_PI_TUI_HOST_ENTRY = realpathSync(process.argv[1]);
65
- const handle = await dsh.runProfile({
66
- environment: dsh.loadLayeredEnv("dsh", process.cwd()),
67
- profile,
68
- patchFiles: [overlayPath, ...options.extraPatchFiles ?? []],
69
- args: []
776
+ async function runLocalHostEntryOwned(options, scratchOwner) {
777
+ const dsh = await loadOfficialDsh(options.dshAnchor);
778
+ const dshHome = dsh.resolveDshHome();
779
+ const scope = scopeFromInstalledProfile({
780
+ dshHome,
781
+ profileDir: dsh.resolveProfileDir(options.profile, dshHome),
782
+ packageRoot: installedPackageRootFromEntry(import.meta.url),
783
+ dshVersion: readInstalledDshVersion(options.dshAnchor)
70
784
  });
785
+ scratchOwner.scopeDir = scope.dir;
786
+ let seat;
71
787
  try {
72
- writeEntryRecord({
73
- m4a0: "profile-booted",
74
- processRole: "host",
75
- pid: process.pid,
76
- phase: "profile-booted"
77
- });
78
- const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-DAgKknbY.mjs");
79
- await settleHostEntries(handle.ctx);
80
- const status = collectHostEntryStatus(handle.ctx, {
81
- profile,
82
- processStartIdentity
83
- });
84
- writeEntryRecord({
85
- m4a0: "ready",
86
- ...status
788
+ seat = await bindProcessSeat(scope.hostSocketName, "HOST_ALREADY_OWNED");
789
+ } catch (error) {
790
+ if (error instanceof LocalScopeError && error.code === "HOST_ALREADY_OWNED") {
791
+ writeEntryRecord({
792
+ m4a0: "host-seat-conflict",
793
+ processRole: "host",
794
+ pid: process.pid,
795
+ scopeId: scope.scopeId,
796
+ error: error.code
797
+ });
798
+ return;
799
+ }
800
+ throw error;
801
+ }
802
+ let handle;
803
+ let registration;
804
+ let liveness;
805
+ try {
806
+ const scratchDir = mkdtempSync(join(scope.dir, "host-scratch-"));
807
+ scratchOwner.scratchDir = scratchDir;
808
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_EARLY_EXIT === "1") process.exit(1);
809
+ const overlayPath = join(scratchDir, "host-only.patch.yml");
810
+ writeFileSync(overlayPath, HOST_ONLY_PATCH, { mode: 384 });
811
+ const processStartIdentity = readLinuxStarttime();
812
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_BOOT_FAILURE === "before-profile") throw new Error("local host entry: qualification forced pre-profile failure");
813
+ process.env.DSH_PI_TUI_ROLE = "host";
814
+ if (process.argv[1] !== void 0) process.env.DSH_PI_TUI_HOST_ENTRY = realpathSync(process.argv[1]);
815
+ const priorSigterm = process.listeners("SIGTERM");
816
+ const priorSigint = process.listeners("SIGINT");
817
+ handle = await dsh.runProfile({
818
+ environment: dsh.loadLayeredEnv("dsh", process.cwd()),
819
+ profile: options.profile,
820
+ patchFiles: [overlayPath, ...options.extraPatchFiles ?? []],
821
+ args: []
87
822
  });
88
- attachEntryControl(async (request) => {
89
- if (request.op === "status") {
823
+ const shutdownOwner = handle.shutdown;
824
+ try {
825
+ writeEntryRecord({
826
+ m4a0: "profile-booted",
827
+ processRole: "host",
828
+ pid: process.pid,
829
+ phase: "profile-booted"
830
+ });
831
+ const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-DilsvA6f.mjs");
832
+ await settleHostEntries(handle.ctx);
833
+ await applyWebStartupPreference(handle.ctx);
834
+ const status = collectHostEntryStatus(handle.ctx, {
835
+ profile: options.profile,
836
+ processStartIdentity
837
+ });
838
+ liveness = new HostActivityObserver(handle.ctx);
839
+ let published;
840
+ let stopping;
841
+ let shuttingDown = false;
842
+ let resolveStopped;
843
+ const stopped = new Promise((resolve) => {
844
+ resolveStopped = resolve;
845
+ });
846
+ const stop = (code, owner) => {
847
+ if (stopping !== void 0) return stopping;
848
+ shuttingDown = true;
849
+ stopping = (async () => {
850
+ const errors = [];
851
+ try {
852
+ liveness?.close();
853
+ } catch (error) {
854
+ errors.push({
855
+ step: "liveness-close",
856
+ error
857
+ });
858
+ }
859
+ try {
860
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_SCRATCH_REMOVE_FAILURE === "1") throw new Error("local host entry: qualification forced scratch removal failure");
861
+ removeOwnedScratch(scope.dir, scratchDir);
862
+ } catch (error) {
863
+ errors.push({
864
+ step: "scratch-remove",
865
+ error
866
+ });
867
+ }
868
+ try {
869
+ await owner.unregisterIdentity();
870
+ } catch (error) {
871
+ errors.push({
872
+ step: "identity-unregister",
873
+ error
874
+ });
875
+ }
876
+ try {
877
+ await shutdownOwner.shutdown(code);
878
+ } catch (error) {
879
+ errors.push({
880
+ step: "shutdown",
881
+ error
882
+ });
883
+ }
884
+ cleanupOwnedFiles(scope, owner.identity.instanceId);
885
+ if (errors.length > 0) {
886
+ const first = errors[0];
887
+ const primary = first.error instanceof Error ? first.error : new Error(String(first.error));
888
+ writeEntryRecord({
889
+ m4a0: "cleanup-failure",
890
+ processRole: "host",
891
+ phase: "shutdown",
892
+ pid: process.pid,
893
+ error: primary.message,
894
+ step: first.step
895
+ });
896
+ process.exitCode = 1;
897
+ } else {
898
+ writeEntryRecord({
899
+ m4a0: "cleanup",
900
+ processRole: "host",
901
+ phase: "shutdown",
902
+ pid: process.pid,
903
+ status: "completed"
904
+ });
905
+ process.exitCode = code;
906
+ }
907
+ const stopBarrier = process.env.SPLIT_PROCESS_HOST_STOP_BARRIER;
908
+ if (stopBarrier !== void 0 && stopBarrier !== "") await waitForQualificationBarrier(stopBarrier);
909
+ resolveStopped?.();
910
+ })();
911
+ return stopping;
912
+ };
913
+ let pendingStop;
914
+ const requestStop = (code, signal) => {
915
+ const owner = published;
916
+ if (pendingStop !== void 0) {
917
+ writeEntryRecord({
918
+ m4a0: "stop-repeat-ignored",
919
+ processRole: "host",
920
+ pid: process.pid,
921
+ signal,
922
+ phase: shuttingDown ? "shutdown" : owner === void 0 ? "publication" : "running"
923
+ });
924
+ return;
925
+ }
926
+ pendingStop = code;
90
927
  writeEntryRecord({
91
- m4a0: "status",
92
- ...request.requestId === void 0 ? {} : { requestId: request.requestId },
93
- ...collectHostEntryStatus(handle.ctx, {
94
- profile,
95
- processStartIdentity
96
- })
928
+ m4a0: "stop-requested",
929
+ processRole: "host",
930
+ pid: process.pid,
931
+ signal,
932
+ phase: shuttingDown ? "shutdown" : owner === void 0 ? "publication" : "running"
97
933
  });
98
- return false;
934
+ if (owner !== void 0) runDetached(`local host: ${signal} shutdown`, () => stop(code, owner), { diag: createEntryDiag("host") });
935
+ };
936
+ const launcherSigterm = process.listeners("SIGTERM").find((listener) => !priorSigterm.includes(listener));
937
+ if (launcherSigterm !== void 0) process.removeListener("SIGTERM", launcherSigterm);
938
+ const launcherSigint = process.listeners("SIGINT").find((listener) => !priorSigint.includes(listener));
939
+ if (launcherSigint !== void 0) process.removeListener("SIGINT", launcherSigint);
940
+ const onSigterm = () => {
941
+ requestStop(0, "SIGTERM");
942
+ };
943
+ const onSigint = () => {
944
+ requestStop(130, "SIGINT");
945
+ };
946
+ process.on("SIGTERM", onSigterm);
947
+ process.on("SIGINT", onSigint);
948
+ const releaseSignalAdmission = () => {
949
+ process.removeListener("SIGTERM", onSigterm);
950
+ process.removeListener("SIGINT", onSigint);
951
+ };
952
+ const publishedHost = await publishLocalHost(handle.ctx, scope, processStartIdentity);
953
+ published = publishedHost;
954
+ registration = publishedHost;
955
+ process.once("exit", () => {
956
+ cleanupOwnedFiles(scope, publishedHost.identity.instanceId);
957
+ });
958
+ if (pendingStop !== void 0) {
959
+ await stop(pendingStop, publishedHost);
960
+ releaseSignalAdmission();
961
+ return;
962
+ }
963
+ const initialLivenessPromise = liveness.snapshot();
964
+ const livenessBarrier = process.env.SPLIT_PROCESS_HOST_LIVENESS_BARRIER;
965
+ if (livenessBarrier !== void 0 && livenessBarrier !== "") {
966
+ writeEntryRecord({
967
+ m4a0: "qualification",
968
+ processRole: "host",
969
+ op: "liveness-barrier",
970
+ pid: process.pid
971
+ });
972
+ await waitForQualificationBarrier(livenessBarrier);
99
973
  }
100
- if (request.op === "shutdown") {
101
- await handle.shutdown.shutdown(0);
102
- return true;
974
+ const initialLiveness = await initialLivenessPromise;
975
+ if (stopping !== void 0 || pendingStop !== void 0) {
976
+ await stopped;
977
+ releaseSignalAdmission();
978
+ return;
103
979
  }
104
980
  writeEntryRecord({
105
- m4a0: "control-error",
106
- error: `local host entry: unknown op ${JSON.stringify(request.op)}`
981
+ m4a0: "ready",
982
+ ...status,
983
+ liveness: initialLiveness,
984
+ localHost: publishedHost.identity
107
985
  });
108
- return false;
109
- });
110
- } catch (error) {
111
- writeEntryRecord({
112
- m4a0: "failure",
113
- processRole: "host",
114
- phase: "after-boot",
115
- pid: process.pid,
116
- error: error instanceof Error ? error.message : String(error),
117
- ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
118
- });
119
- await finishHostFailureCleanup(handle.shutdown);
120
- process.exitCode = 1;
986
+ attachEntryControl(async (request) => {
987
+ if (request.op === "status") {
988
+ const snapshot = await liveness.snapshot();
989
+ writeEntryRecord({
990
+ m4a0: "status",
991
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId },
992
+ ...collectHostEntryStatus(handle.ctx, {
993
+ profile: options.profile,
994
+ processStartIdentity
995
+ }),
996
+ liveness: snapshot,
997
+ localHost: publishedHost.identity
998
+ });
999
+ return false;
1000
+ }
1001
+ if (request.op === "shutdown") {
1002
+ await stop(0, publishedHost);
1003
+ return true;
1004
+ }
1005
+ writeEntryRecord({
1006
+ m4a0: "control-error",
1007
+ error: `local host entry: unknown op ${JSON.stringify(request.op)}`
1008
+ });
1009
+ return false;
1010
+ });
1011
+ await stopped;
1012
+ releaseSignalAdmission();
1013
+ } catch (error) {
1014
+ writeEntryRecord({
1015
+ m4a0: "failure",
1016
+ processRole: "host",
1017
+ phase: "after-boot",
1018
+ pid: process.pid,
1019
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
1020
+ error: error instanceof Error ? error.message : String(error),
1021
+ ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1022
+ });
1023
+ let priorCleanupFailure;
1024
+ try {
1025
+ const loader = handle.ctx.loader;
1026
+ if (loader !== void 0) await Promise.race([loader.await(), new Promise((_, reject) => {
1027
+ setTimeout(() => reject(/* @__PURE__ */ new Error("local host entry: profile entries did not settle before failure cleanup")), 5e3);
1028
+ })]);
1029
+ } catch (settleError) {
1030
+ priorCleanupFailure = settleError instanceof Error ? settleError.message : String(settleError);
1031
+ writeEntryRecord({
1032
+ m4a0: "cleanup-failure",
1033
+ processRole: "host",
1034
+ phase: "after-boot",
1035
+ pid: process.pid,
1036
+ step: "settle-before-shutdown",
1037
+ error: priorCleanupFailure
1038
+ });
1039
+ }
1040
+ try {
1041
+ liveness?.close();
1042
+ } catch (cleanupError) {
1043
+ priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
1044
+ writeEntryRecord({
1045
+ m4a0: "cleanup-failure",
1046
+ processRole: "host",
1047
+ phase: "after-boot",
1048
+ pid: process.pid,
1049
+ step: "liveness-close",
1050
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
1051
+ });
1052
+ }
1053
+ try {
1054
+ await registration?.unregisterIdentity();
1055
+ } catch (cleanupError) {
1056
+ priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
1057
+ writeEntryRecord({
1058
+ m4a0: "cleanup-failure",
1059
+ processRole: "host",
1060
+ phase: "after-boot",
1061
+ pid: process.pid,
1062
+ step: "identity-unregister",
1063
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
1064
+ });
1065
+ }
1066
+ try {
1067
+ await drainHmrTransactions(handle?.ctx);
1068
+ } catch (drainError) {
1069
+ const message = drainError instanceof Error ? drainError.message : String(drainError);
1070
+ priorCleanupFailure ??= message;
1071
+ writeEntryRecord({
1072
+ m4a0: "cleanup-failure",
1073
+ processRole: "host",
1074
+ phase: "after-boot",
1075
+ pid: process.pid,
1076
+ step: "hmr-drain",
1077
+ error: message
1078
+ });
1079
+ }
1080
+ await finishHostFailureCleanup(shutdownOwner, writeEntryRecord, priorCleanupFailure === void 0 ? void 0 : { priorCleanupFailure });
1081
+ if (registration !== void 0) cleanupOwnedFiles(scope, registration.identity.instanceId);
1082
+ process.exitCode = 1;
1083
+ }
1084
+ } finally {
1085
+ await seat.close();
121
1086
  }
122
1087
  }
123
1088
  /**
124
- * Finish one failed Host startup with the launcher's official shutdown owner.
125
- * A successful disposal emits exactly one `cleanup: completed`; a rejecting
126
- * disposal emits one `cleanup-failure` and NEVER a completed record. Exported
127
- * for the review-fix negative control.
1089
+ * Drain the HMR service's serialized reload transactions before the failed
1090
+ * Host disposes its application tree.
1091
+ *
1092
+ * Cordis 4.1 unloads a provider fiber only after its dependent fibers finish,
1093
+ * and the built-in HMR service's own unload drains the reload queue that is
1094
+ * still holding the boot-time configuration refresh. Disposing the tree while
1095
+ * that refresh is queued therefore deadlocks: the HMR fiber waits for the
1096
+ * refresh, and the refresh waits for the Loader that is being disposed. The
1097
+ * launcher's shutdown then force-exits after its 5s grace before the cleanup
1098
+ * classification can be recorded. `runExclusive` is the public serialization
1099
+ * seam, so an empty operation joins the queue and resolves after the in-flight
1100
+ * transaction settled. A missing HMR service is a no-op; a queue that cannot
1101
+ * drain within the bound rejects so the caller reports a truthful cleanup
1102
+ * failure instead of claiming completion.
1103
+ *
1104
+ * @param context - the Host context whose HMR service (if any) is drained.
1105
+ * @param timeoutMs - the bound on the drain, so a stuck queue cannot hang exit.
128
1106
  */
129
- async function finishHostFailureCleanup(shutdownOwner, emit = writeEntryRecord) {
1107
+ async function drainHmrTransactions(context, timeoutMs = 3e3) {
1108
+ const hmr = context.get?.("hmr");
1109
+ if (typeof hmr?.runExclusive !== "function") return;
1110
+ let timer;
1111
+ try {
1112
+ await Promise.race([hmr.runExclusive(async () => void 0), new Promise((_resolve, reject) => {
1113
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("local host entry: HMR transactions did not drain before failure cleanup")), timeoutMs);
1114
+ })]);
1115
+ } finally {
1116
+ if (timer !== void 0) clearTimeout(timer);
1117
+ }
1118
+ }
1119
+ async function finishHostFailureCleanup(shutdownOwner, emit = writeEntryRecord, options = {}) {
130
1120
  try {
131
1121
  await shutdownOwner.shutdown(1);
1122
+ if (options.priorCleanupFailure !== void 0) {
1123
+ emit({
1124
+ m4a0: "cleanup-failure",
1125
+ processRole: "host",
1126
+ phase: "after-boot",
1127
+ pid: process.pid,
1128
+ step: "prior-cleanup",
1129
+ error: options.priorCleanupFailure
1130
+ });
1131
+ return false;
1132
+ }
132
1133
  emit({
133
1134
  m4a0: "cleanup",
134
1135
  processRole: "host",
@@ -155,7 +1156,6 @@ function optionsFromEnvironment() {
155
1156
  return {
156
1157
  dshAnchor,
157
1158
  profile: process.env.SPLIT_PROCESS_PROFILE ?? "pi-tui",
158
- scratchDir: process.env.SPLIT_PROCESS_SCRATCH ?? mkdtempSync(join(tmpdir(), "split-process-host-")),
159
1159
  ...process.env.SPLIT_PROCESS_EXTRA_PATCH === void 0 || process.env.SPLIT_PROCESS_EXTRA_PATCH === "" ? {} : { extraPatchFiles: [process.env.SPLIT_PROCESS_EXTRA_PATCH] }
160
1160
  };
161
1161
  }
@@ -167,10 +1167,11 @@ if (import.meta.main) try {
167
1167
  processRole: "host",
168
1168
  phase: "startup",
169
1169
  pid: process.pid,
1170
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
170
1171
  error: error instanceof Error ? error.message : String(error),
171
1172
  ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
172
1173
  });
173
1174
  process.exit(1);
174
1175
  }
175
1176
  //#endregion
176
- export { HOST_ONLY_PATCH, finishHostFailureCleanup, runLocalHostEntry };
1177
+ export { HOST_ONLY_PATCH, applyWebStartupPreference, drainHmrTransactions, finishHostFailureCleanup, runLocalHostEntry };