@xmoon76/dsh-pi-tui 0.5.3 → 0.5.5

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 (59) hide show
  1. package/README.en.md +195 -150
  2. package/README.md +137 -103
  3. package/cordis.patch.yml +54 -2
  4. package/dist/application-runtime-CbBO4bY-.mjs +6860 -0
  5. package/dist/bootstrap-DLOydLLj.mjs +108410 -0
  6. package/dist/builtins.mjs +2 -3
  7. package/dist/client-bootstrap-DwSFzcTW.mjs +872 -0
  8. package/dist/context-summary-Bz0AGXa1.mjs +12027 -0
  9. package/dist/context-summary-D9mhxPXL.mjs +10015 -0
  10. package/dist/custom-items-CKrOBCox.mjs +655 -0
  11. package/dist/disposal-BYBbEpVY.mjs +54 -0
  12. package/dist/dispose-cause-BzcXo4hu.mjs +123 -0
  13. package/dist/dispose-cause-CNFuUnjR.mjs +24 -0
  14. package/dist/dist-C7QMk0ws.mjs +15431 -0
  15. package/dist/entry-control-DnduyDiw.mjs +92 -0
  16. package/dist/extension/advanced.d.mts +1 -1
  17. package/dist/extension/unstable.d.mts +1 -1
  18. package/dist/{extensions-DzpBiiYb.d.mts → extensions-Bte3XOt5.d.mts} +1 -1
  19. package/dist/{extensions-a-rxanjw.mjs → extensions-pcFiH7Qe.mjs} +1498 -410
  20. package/dist/extensions.d.mts +2 -2
  21. package/dist/extensions.mjs +1 -1
  22. package/dist/host-bootstrap-CKdfLkNS.mjs +188 -0
  23. package/dist/host-foundation-probe-CYHsbAw6.mjs +143 -0
  24. package/dist/host-prerequisites-9JBTtVNu.mjs +36 -0
  25. package/dist/host-runtime.d.mts +26 -0
  26. package/dist/host-runtime.mjs +450 -0
  27. package/dist/index.d.mts +9 -2
  28. package/dist/index.mjs +45779 -24480
  29. package/dist/local-client.mjs +1816 -0
  30. package/dist/local-discovery-CXnLT4GF.mjs +755 -0
  31. package/dist/local-discovery-DVFFpfBG.mjs +2 -0
  32. package/dist/local-host.mjs +1025 -0
  33. package/dist/local-transport-C9aonplC.mjs +513 -0
  34. package/dist/performance-host.d.mts +2 -2
  35. package/dist/performance-host.mjs +258 -1
  36. package/dist/{performance-view-jvvd8Jn7.mjs → performance-view-CfGvLZyD.mjs} +1 -1
  37. package/dist/pi-tui-remote-contribution-DRk6Tl3J.mjs +78 -0
  38. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +70 -0
  39. package/dist/pi-tui-terminal-progress-contract-XTQKj-WW.mjs +905 -0
  40. package/dist/{public-types-gZi3iFNh.d.mts → public-types-Dgf1bDke.d.mts} +3 -3
  41. package/dist/{runtime-BtPH-UUb.mjs → runtime-Bh5OsftD.mjs} +1311 -1024
  42. package/dist/runtime-C5ROZqFj.mjs +2 -0
  43. package/dist/runtime-status-0lp9CM0V.mjs +1923 -0
  44. package/dist/session-4keoXjk0.mjs +10869 -0
  45. package/dist/session-B2zqv4wr.mjs +10869 -0
  46. package/dist/{startup-D5Xu8diR.mjs → startup-Ct2UUjUL.mjs} +55 -13
  47. package/dist/startup.d.mts +2 -1
  48. package/dist/startup.mjs +1 -1
  49. package/dist/terminal-progress-source-BhufrZ74.mjs +6000 -0
  50. package/dist/terminal-progress-source-CsBinCJ_.mjs +965 -0
  51. package/dist/visual-tools.d.mts +62 -0
  52. package/dist/visual-tools.mjs +556 -0
  53. package/generated/dsh-presets/README.md +1 -1
  54. package/package.json +145 -117
  55. package/dist/context-summary-CxUpNkA9.mjs +0 -2951
  56. package/dist/performance-host-BJT6scGF.mjs +0 -266
  57. package/dist/rolldown-runtime-8H4AJuhK.mjs +0 -14
  58. package/dist/session-BZLxhrPQ.mjs +0 -5697
  59. package/dist/terminal-progress-source-BlmksrSD.mjs +0 -2200
@@ -0,0 +1,1025 @@
1
+ #!/usr/bin/env node
2
+ import { S as scopeFromInstalledProfile, _ as installedPackageRootFromEntry, h as bindProcessSeat, i as cleanupOwnedFiles, m as LocalScopeError, p as LOCAL_PROTOCOL, v as readInstalledDshVersion, x as removeOwnedScratch, y as readLinuxStarttime } from "./local-discovery-CXnLT4GF.mjs";
3
+ import { n as createEntryDiag, r as writeEntryRecord, t as attachEntryControl } from "./entry-control-DnduyDiw.mjs";
4
+ import { i as runDetached } from "./tasks-D_z5Yjjr.mjs";
5
+ import { createRequire } from "node:module";
6
+ import { randomUUID } from "node:crypto";
7
+ import { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ //#region src/app/remote-process/host-activity.ts
11
+ /** Every source key always present in a snapshot. */
12
+ const HOST_ACTIVITY_SOURCES = [
13
+ "agent",
14
+ "jobs",
15
+ "goal",
16
+ "schedule",
17
+ "pending",
18
+ "write",
19
+ "other"
20
+ ];
21
+ /** Cordis `FiberState` values used by Loader source qualification. */
22
+ const FIBER_PENDING = 0;
23
+ const FIBER_LOADING = 1;
24
+ const FIBER_ACTIVE = 2;
25
+ const FIBER_FAILED = 3;
26
+ const FIBER_DISPOSED = 4;
27
+ const FIBER_UNLOADING = 5;
28
+ /**
29
+ * Loader rows explicitly qualified as passive in the pinned stock Host
30
+ * composition, bound to BOTH their row id and the exact plugin identity.
31
+ * The map is the rc.4 Host-only roster that was reviewed as passive or as
32
+ * belonging to one of the observer's own source families; `schedule` is
33
+ * qualified when a profile mounts the official Schedule row. A row id reused
34
+ * with a different plugin, an unknown active row, a custom plugin or a future
35
+ * official autonomous service fails closed as an unqualified Host source.
36
+ */
37
+ const QUALIFIED_HOST_ROWS = new Map(`include=cordis:include plugin-manager=@deepseek-ai/dsh-plugin-manager
38
+ timer=@deepseek-ai/cordis-plugin-timer hmr=@deepseek-ai/dsh-hmr
39
+ llm=@deepseek-ai/dsh-llm deepseek-llm-api-extensions=@deepseek-ai/dsh-deepseek-llm-api-extensions
40
+ session=@deepseek-ai/dsh-session session-log-deepseek=@deepseek-ai/dsh-session-log-deepseek
41
+ typert=@deepseek-ai/dsh-typert-registry typert-loader=@deepseek-ai/dsh-typert-loader
42
+ typert-gateway=@deepseek-ai/dsh-api-gateway remote-access=@deepseek-ai/dsh-api-remote-access
43
+ session-title=@deepseek-ai/dsh-session-title session-title-llm=@deepseek-ai/dsh-session-title-first-prompt-llm
44
+ user-questions=@deepseek-ai/dsh-user-questions agent=@deepseek-ai/dsh-agent
45
+ plugin-package-inventory-deepseek=@deepseek-ai/dsh-plugin-package-inventory-deepseek agent-default-model=@deepseek-ai/dsh-agent-default-model
46
+ jobs=@deepseek-ai/dsh-jobs-local llm-retry=@deepseek-ai/dsh-llm-retry
47
+ config-editor=@deepseek-ai/dsh-config-editor settings=@deepseek-ai/dsh-settings
48
+ authorization=@deepseek-ai/dsh-authorization deepseek-account=@deepseek-ai/dsh-deepseek-account-platform
49
+ credentials=@deepseek-ai/dsh-credentials-local llm-pi-ai=@deepseek-ai/dsh-llm-pi-ai
50
+ session-persistence-jsonl=@deepseek-ai/dsh-session-persistence-jsonl attachment-local=@deepseek-ai/dsh-attachment-local
51
+ session-query-sqlite=@deepseek-ai/dsh-session-query-sqlite working-directory=@deepseek-ai/dsh-working-directory
52
+ tool-working-directory=@deepseek-ai/dsh-tool-working-directory session-projection=@deepseek-ai/dsh-session-projection
53
+ storage=@deepseek-ai/dsh-storage storage-json=@deepseek-ai/dsh-storage-json
54
+ storage-domain=@deepseek-ai/dsh-storage-domain session-projection-cache=@deepseek-ai/dsh-session-projection-cache
55
+ otel=@deepseek-ai/dsh-otel session-telemetry-otel=@deepseek-ai/dsh-session-telemetry-otel
56
+ subprocess=@deepseek-ai/dsh-subprocess-local sandbox=@deepseek-ai/dsh-sandbox-local
57
+ sandbox-policy=@deepseek-ai/dsh-sandbox-policy bash-sandbox=@deepseek-ai/dsh-bash-sandbox
58
+ approval=@deepseek-ai/dsh-user-approval permission=@deepseek-ai/dsh-permission-presets
59
+ shell-env=@deepseek-ai/dsh-shell-env fs-observation-policy=@deepseek-ai/dsh-fs-observation-policy
60
+ skill=@deepseek-ai/dsh-skill commands=@deepseek-ai/dsh-commands
61
+ command-feedback=@deepseek-ai/dsh-command-feedback goal=@deepseek-ai/dsh-goal
62
+ goal-round-driver=@deepseek-ai/dsh-goal-round-driver token-meter=@deepseek-ai/dsh-token-meter
63
+ subagent=@deepseek-ai/dsh-subagent subagent-spawn-in-process=@deepseek-ai/dsh-subagent-spawn-in-process
64
+ subagent-fork-in-process=@deepseek-ai/dsh-subagent-fork-in-process ptc-runtime=@deepseek-ai/dsh-ptc-runtime-node
65
+ timeout-policy=@deepseek-ai/dsh-tool-call-timeout-policy spill-local=@deepseek-ai/dsh-spill-local
66
+ spill-policy=@deepseek-ai/dsh-spill-policy session-checkpoint-policy=@deepseek-ai/dsh-session-checkpoint-policy
67
+ image-offload=@deepseek-ai/dsh-compaction-image-offload repeat-tool-reminder=@deepseek-ai/dsh-repeat-tool-reminder
68
+ web=@deepseek-ai/dsh-web web-search-deepseek=@deepseek-ai/dsh-web-search-deepseek
69
+ web-deepseek-api=@deepseek-ai/dsh-web-deepseek-api web-fetch-http=@deepseek-ai/dsh-web-fetch-http
70
+ mcp-resources=@deepseek-ai/dsh-mcp-resources tools=@deepseek-ai/dsh-tools
71
+ system-prompt=@deepseek-ai/dsh-system-prompt agent-loop=@deepseek-ai/dsh-agent-loop
72
+ fs-sandbox=@deepseek-ai/dsh-fs-sandbox llm-deepseek=@deepseek-ai/dsh-llm-deepseek-api-key
73
+ llm-deepseek-account=@deepseek-ai/dsh-llm-deepseek-account tui-startup=@xmoon76/dsh-pi-tui/startup
74
+ pi-tui-performance-host=@xmoon76/dsh-pi-tui/performance-host workspace-files=@deepseek-ai/dsh-api-workspace-files
75
+ pi-tui-visual-tools=@xmoon76/dsh-pi-tui/visual-tools webserver=@deepseek-ai/dsh-host-webserver
76
+ job-controller=@deepseek-ai/dsh-api-job-controller workspace=@deepseek-ai/dsh-workspace
77
+ file-reference-local=@deepseek-ai/dsh-file-reference-local agent-preset-registry=@deepseek-ai/dsh-agent-preset-registry
78
+ subagent-model-selection-settings=@deepseek-ai/dsh-tool-subagent/model-selection-settings cordis-host-runner=@deepseek-ai/dsh-cordis-host-runner
79
+ preset-standard=@deepseek-ai/dsh-agent-preset preset-ptc=@deepseek-ai/dsh-agent-preset
80
+ preset-minimal=@deepseek-ai/dsh-agent-preset preset-cordis=@deepseek-ai/dsh-agent-preset
81
+ split-host-connection=@deepseek-ai/dsh-client-connection split-host-api-remotes=@deepseek-ai/dsh-api-remotes
82
+ split-host-file-upload=@deepseek-ai/dsh-client-file-upload split-host-session-stats=@deepseek-ai/dsh-session-stats
83
+ split-host-turn-outline=@deepseek-ai/dsh-session-turn-outline split-host-session-controller=@deepseek-ai/dsh-api-session-controller
84
+ split-host-settings-controller=@deepseek-ai/dsh-api-settings-controller split-host-session-log-download=@deepseek-ai/dsh-session-log-export
85
+ split-host-pi-tui-runtime=@xmoon76/dsh-pi-tui/host-runtime schedule=@deepseek-ai/dsh-schedule`.trim().split(/\s+/u).map((entry) => {
86
+ const separator = entry.indexOf("=");
87
+ return [entry.slice(0, separator), entry.slice(separator + 1)];
88
+ }));
89
+ /** Reasons that positively establish current work or a future keepalive obligation. */
90
+ const BLOCKING_REASONS = /* @__PURE__ */ new Set([
91
+ "agent-running",
92
+ "agent-inbox",
93
+ "goal-armed",
94
+ "job-running",
95
+ "job-stopping",
96
+ "child-active",
97
+ "schedule-active"
98
+ ]);
99
+ /** The dedicated timeout marker: a hung read is UNKNOWN, never an empty source. */
100
+ const OBSERVATION_TIMEOUT = Symbol("host-activity-observation-timeout");
101
+ /** Reject a source read after the caller's bound. */
102
+ async function withDeadline(operation, deadlineMs) {
103
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return operation;
104
+ let timer;
105
+ const deadline = new Promise((_resolve, reject) => {
106
+ timer = setTimeout(() => {
107
+ reject(OBSERVATION_TIMEOUT);
108
+ }, deadlineMs);
109
+ });
110
+ try {
111
+ return await Promise.race([operation, deadline]);
112
+ } finally {
113
+ if (timer !== void 0) clearTimeout(timer);
114
+ }
115
+ }
116
+ /** Build one ordered, deduplicated reason list. */
117
+ function reasonList(reasons) {
118
+ return [...reasons];
119
+ }
120
+ /** A snapshot that claims nothing after the observer stopped reading. */
121
+ function closedSnapshot(epoch) {
122
+ return {
123
+ verdict: "UNKNOWN",
124
+ epoch,
125
+ reasons: ["source-unavailable"],
126
+ sourceStates: Object.fromEntries(HOST_ACTIVITY_SOURCES.map((source) => [source, "UNKNOWN"]))
127
+ };
128
+ }
129
+ /**
130
+ * The Host-process observer. Construction only subscribes to official live
131
+ * signals and starts no work; snapshot() performs the reads.
132
+ */
133
+ var HostActivityObserver = class {
134
+ context;
135
+ observationDeadlineMs;
136
+ subscriptions = [];
137
+ /** Short-lived active Job identity hints: official list reads stay authoritative. */
138
+ jobHints = /* @__PURE__ */ new Map();
139
+ /** Services observed in this Host process; a later absence is UNKNOWN, not ABSENT. */
140
+ seenSources = /* @__PURE__ */ new Set();
141
+ currentEpoch = 0;
142
+ closed = false;
143
+ constructor(context, options = {}) {
144
+ this.context = context;
145
+ this.observationDeadlineMs = options.observationDeadlineMs ?? 3e3;
146
+ try {
147
+ this.subscribe();
148
+ } catch (error) {
149
+ this.closed = true;
150
+ for (const dispose of this.subscriptions.splice(0).reverse()) dispose();
151
+ throw error;
152
+ }
153
+ }
154
+ /** Subscribe to the official change signals that invalidate a snapshot. */
155
+ subscribe() {
156
+ const invalidate = () => {
157
+ this.invalidate();
158
+ };
159
+ for (const event of [
160
+ "agent/created",
161
+ "agent/disposed",
162
+ "agent/status",
163
+ "agent/inbox/inserted",
164
+ "agent/inbox/claimed",
165
+ "agent/inbox/discarded",
166
+ "goal/changed",
167
+ "schedule/changed",
168
+ "internal/status"
169
+ ]) this.subscriptions.push(this.context.on(event, invalidate));
170
+ const jobs = this.context.reflect.get("jobs");
171
+ if (jobs === void 0) return;
172
+ this.seenSources.add("jobs");
173
+ this.subscriptions.push(jobs.events.subscribe({ owners: "all" }, (event) => {
174
+ if (event.type === "output" || event.type === "progress") return;
175
+ const job = event.job;
176
+ if (job !== void 0) {
177
+ if (event.type === "registered") this.jobHints.set(job.id, job.status === "stopping" ? "stopping" : "running");
178
+ else if (event.type === "stopping") this.jobHints.set(job.id, "stopping");
179
+ else if (event.type === "settled" || event.type === "removed") this.jobHints.delete(job.id);
180
+ }
181
+ this.invalidate();
182
+ }));
183
+ }
184
+ /** Advance the epoch and refresh which services are currently mounted. */
185
+ invalidate() {
186
+ if (this.closed) return;
187
+ this.currentEpoch += 1;
188
+ this.noteMountedSources();
189
+ }
190
+ /** Remember every source service seen in this process. */
191
+ noteMountedSources() {
192
+ if (this.context.reflect.get("jobs") !== void 0) this.seenSources.add("jobs");
193
+ if (this.context.reflect.get("goals") !== void 0) this.seenSources.add("goal");
194
+ if (this.context.reflect.get("schedule") !== void 0) this.seenSources.add("schedule");
195
+ if (this.context.reflect.get("typertGateway") !== void 0) this.seenSources.add("pending");
196
+ if (this.context.reflect.get("sessionPersistence") !== void 0) this.seenSources.add("write");
197
+ }
198
+ /** Map a missing service to ABSENT (never mounted) or UNKNOWN (mounted earlier). */
199
+ unavailableState(source, reasons) {
200
+ if (!this.seenSources.has(source)) return "ABSENT";
201
+ reasons.add("source-unavailable");
202
+ return "UNKNOWN";
203
+ }
204
+ /** Read every live Agent (children included) and classify current work. */
205
+ readAgents(reasons) {
206
+ const registry = this.context.reflect.get("agents");
207
+ if (registry === void 0) {
208
+ reasons.add("source-unavailable");
209
+ return {
210
+ state: "UNKNOWN",
211
+ agents: [],
212
+ readable: false
213
+ };
214
+ }
215
+ let agents;
216
+ try {
217
+ agents = registry.list();
218
+ } catch {
219
+ reasons.add("source-unavailable");
220
+ return {
221
+ state: "UNKNOWN",
222
+ agents: [],
223
+ readable: false
224
+ };
225
+ }
226
+ let roots;
227
+ if (typeof registry.roots === "function") try {
228
+ roots = new Set(registry.roots());
229
+ } catch {
230
+ roots = void 0;
231
+ }
232
+ let state = "IDLE";
233
+ let maintenanceGap = false;
234
+ for (const agent of agents) {
235
+ let running;
236
+ let pending;
237
+ try {
238
+ running = agent.status === "running";
239
+ pending = agent.inbox.nextTurn.length + agent.inbox.nextStep.length;
240
+ } catch {
241
+ reasons.add("source-unavailable");
242
+ return {
243
+ state: "UNKNOWN",
244
+ agents,
245
+ readable: false
246
+ };
247
+ }
248
+ if (running) {
249
+ reasons.add("agent-running");
250
+ state = "ACTIVE";
251
+ }
252
+ if (pending > 0) {
253
+ reasons.add("agent-inbox");
254
+ state = "ACTIVE";
255
+ }
256
+ if (!running && pending === 0) maintenanceGap = true;
257
+ if (roots !== void 0 && !roots.has(agent) && (running || pending > 0)) reasons.add("child-active");
258
+ }
259
+ if (maintenanceGap) {
260
+ reasons.add("agent-maintenance-unproven");
261
+ if (state === "IDLE") state = "UNKNOWN";
262
+ }
263
+ return {
264
+ state,
265
+ agents,
266
+ readable: true
267
+ };
268
+ }
269
+ /** Read the official Goal view for every live Agent. */
270
+ readGoals(agents, agentsReadable, reasons) {
271
+ const goals = this.context.reflect.get("goals");
272
+ if (goals === void 0) return this.unavailableState("goal", reasons);
273
+ this.seenSources.add("goal");
274
+ if (!agentsReadable) {
275
+ reasons.add("source-unavailable");
276
+ return "UNKNOWN";
277
+ }
278
+ let state = "IDLE";
279
+ for (const agent of agents) {
280
+ let goal;
281
+ try {
282
+ goal = goals.get(agent);
283
+ } catch {
284
+ reasons.add("source-unavailable");
285
+ return "UNKNOWN";
286
+ }
287
+ if (goal !== void 0 && goal.phase === "active" && goal.activation === "armed") {
288
+ reasons.add("goal-armed");
289
+ state = "ACTIVE";
290
+ }
291
+ }
292
+ return state;
293
+ }
294
+ /** Merge the unowned list, every live Agent's owner-scoped list, and job hints. */
295
+ readJobs(agents, agentsReadable, reasons) {
296
+ const jobs = this.context.reflect.get("jobs");
297
+ if (jobs === void 0) return this.unavailableState("jobs", reasons);
298
+ this.seenSources.add("jobs");
299
+ const byId = /* @__PURE__ */ new Map();
300
+ try {
301
+ for (const job of jobs.list()) byId.set(job.id, job);
302
+ if (agentsReadable) for (const agent of agents) for (const job of jobs.list(agent.id)) byId.set(job.id, job);
303
+ } catch {
304
+ reasons.add("source-unavailable");
305
+ return "UNKNOWN";
306
+ }
307
+ for (const [id, status] of this.jobHints) if (!byId.has(id)) byId.set(id, {
308
+ id,
309
+ status
310
+ });
311
+ let state = "IDLE";
312
+ for (const job of byId.values()) if (job.status === "running") {
313
+ reasons.add("job-running");
314
+ state = "ACTIVE";
315
+ } else if (job.status === "stopping") {
316
+ reasons.add("job-stopping");
317
+ state = "ACTIVE";
318
+ }
319
+ if (!agentsReadable) {
320
+ reasons.add("source-unavailable");
321
+ if (state === "IDLE") return "UNKNOWN";
322
+ }
323
+ return state;
324
+ }
325
+ /** Read the official Host Schedule catalog when the service is actually mounted. */
326
+ async readSchedule(reasons) {
327
+ const schedule = this.context.reflect.get("schedule");
328
+ if (schedule === void 0) return this.unavailableState("schedule", reasons);
329
+ this.seenSources.add("schedule");
330
+ let entries;
331
+ try {
332
+ entries = await withDeadline(schedule.catalog(), this.observationDeadlineMs);
333
+ } catch {
334
+ reasons.add("source-unavailable");
335
+ return "UNKNOWN";
336
+ }
337
+ let state = "IDLE";
338
+ for (const entry of entries) if (entry.status === "active") {
339
+ reasons.add("schedule-active");
340
+ state = "ACTIVE";
341
+ }
342
+ return state;
343
+ }
344
+ /** rc.4 cannot enumerate Gateway pending interactions. */
345
+ readPending(reasons) {
346
+ if (this.context.reflect.get("typertGateway") === void 0) return this.unavailableState("pending", reasons);
347
+ this.seenSources.add("pending");
348
+ reasons.add("pending-interaction-unobservable");
349
+ return "UNKNOWN";
350
+ }
351
+ /** rc.4 cannot enumerate in-flight Session writes. */
352
+ readWrite(reasons) {
353
+ if (this.context.reflect.get("sessionPersistence") === void 0) return this.unavailableState("write", reasons);
354
+ this.seenSources.add("write");
355
+ reasons.add("inflight-write-unproven");
356
+ return "UNKNOWN";
357
+ }
358
+ /** Active Loader rows outside the official/xmoon namespaces are unqualified. */
359
+ readOther(reasons) {
360
+ const loader = this.context.loader;
361
+ if (loader === void 0) {
362
+ reasons.add("source-unavailable");
363
+ return "UNKNOWN";
364
+ }
365
+ let entries;
366
+ try {
367
+ entries = [...loader.entries()];
368
+ } catch {
369
+ reasons.add("source-unavailable");
370
+ return "UNKNOWN";
371
+ }
372
+ for (const entry of entries) {
373
+ const state = entry.fiber?.state;
374
+ if (state === void 0 || state === FIBER_PENDING || state === FIBER_DISPOSED) continue;
375
+ const id = entry.options?.id ?? "";
376
+ const name = entry.options?.name ?? "";
377
+ const qualified = QUALIFIED_HOST_ROWS.get(id) === name;
378
+ if (state === FIBER_FAILED) {
379
+ reasons.add("source-unavailable");
380
+ return "UNKNOWN";
381
+ }
382
+ if (state === FIBER_ACTIVE) {
383
+ if (qualified) continue;
384
+ reasons.add("unqualified-host-source");
385
+ return "UNKNOWN";
386
+ }
387
+ if (state === FIBER_LOADING || state === FIBER_UNLOADING) {
388
+ reasons.add(qualified ? "source-unavailable" : "unqualified-host-source");
389
+ return "UNKNOWN";
390
+ }
391
+ reasons.add("source-unavailable");
392
+ return "UNKNOWN";
393
+ }
394
+ return "IDLE";
395
+ }
396
+ /** Read one bounded snapshot from the real Host services. */
397
+ async snapshot() {
398
+ if (this.closed) return closedSnapshot(this.currentEpoch);
399
+ const startEpoch = this.currentEpoch;
400
+ this.noteMountedSources();
401
+ const reasons = /* @__PURE__ */ new Set();
402
+ const sourceStates = {};
403
+ const agents = this.readAgents(reasons);
404
+ sourceStates.agent = agents.state;
405
+ sourceStates.goal = this.readGoals(agents.agents, agents.readable, reasons);
406
+ sourceStates.jobs = this.readJobs(agents.agents, agents.readable, reasons);
407
+ sourceStates.schedule = await this.readSchedule(reasons);
408
+ sourceStates.pending = this.readPending(reasons);
409
+ sourceStates.write = this.readWrite(reasons);
410
+ sourceStates.other = this.readOther(reasons);
411
+ if (this.closed) return closedSnapshot(this.currentEpoch);
412
+ const endEpoch = this.currentEpoch;
413
+ if (startEpoch !== endEpoch) reasons.add("observation-changed");
414
+ let verdict;
415
+ if ([...reasons].some((reason) => BLOCKING_REASONS.has(reason))) verdict = "BLOCKED";
416
+ else if (reasons.size > 0) verdict = "UNKNOWN";
417
+ else verdict = "OBSERVED_QUIESCENT";
418
+ return {
419
+ verdict,
420
+ epoch: endEpoch,
421
+ reasons: reasonList(reasons),
422
+ sourceStates
423
+ };
424
+ }
425
+ /** Release every subscription synchronously and ignore late callbacks. */
426
+ close() {
427
+ if (this.closed) return;
428
+ this.closed = true;
429
+ const subscriptions = this.subscriptions.splice(0);
430
+ for (const dispose of subscriptions.reverse()) dispose();
431
+ }
432
+ };
433
+ //#endregion
434
+ //#region src/app/remote-process/local-host-entry.ts
435
+ /**
436
+ * M4-B1 Host-only process entry.
437
+ *
438
+ * Boots the ordinary DSH profile through the real launcher
439
+ * (`@deepseek-ai/dsh/profile-boot` → `@deepseek-ai/dsh-app-boot` → Loader /
440
+ * Include) rather than a hand-built Context. The launcher-owned Host-only
441
+ * overlay disables exactly the TUI runner and the Client extension host /
442
+ * builtins and adds exactly one official Connection row and one API-remotes
443
+ * event source. Every other Host-plane row keeps its production source.
444
+ *
445
+ * Before the profile Context exists this process claims one Linux abstract
446
+ * socket for the canonical DSH profile; losing that kernel claim is a clean
447
+ * non-fault exit. After boot it registers one authenticated identity Fetch
448
+ * route, publishes the private launch material, and commits `instance.json`
449
+ * as its last Ready step. Process-lifetime SIGTERM/SIGINT admission is
450
+ * installed before the registry becomes discoverable: a signal observed while
451
+ * publication is still in flight is kept as one pending stop intent and runs
452
+ * the ordinary owner-governed shutdown once the published identity and the
453
+ * official shutdown owner are both available, never emitting Ready for a
454
+ * stop-requested Host.
455
+ *
456
+ * The entry is an internal qualification artifact, not a package export or a
457
+ * CLI command: the launcher supplies the DSH installation anchor, profile name
458
+ * and scratch directory through `SPLIT_PROCESS_DSH_ANCHOR` /
459
+ * `SPLIT_PROCESS_PROFILE` / `SPLIT_PROCESS_SCRATCH`.
460
+ *
461
+ * @module app/remote-process/local-host-entry
462
+ */
463
+ /**
464
+ * The Host-only overlay applied over the profile's own patch stack. It keeps
465
+ * `tui-startup` mounted for the consumers that genuinely need its parsed
466
+ * startup facts, but the Host execution rows never use that mutable provider
467
+ * as their Dispose gate: reloading `tui-startup` must not dispose
468
+ * already-accepted Host Session/Agent/Connection ownership. It disables only
469
+ * the three surface rows that must not exist in a Host-only PID, then adds the
470
+ * two B1 rows plus the official Session-serving rows and the ONE built-in
471
+ * PiTui Host Runtime row. The base Gateway, webserver, workspace-files,
472
+ * credentials, agents, sessions and jobs are reused, never mounted twice.
473
+ */
474
+ const HOST_ONLY_PATCH = `# M4-B1 Host-only profile overlay: production Host rows only.
475
+ - id: tui-app
476
+ disabled: true
477
+ - id: pi-tui-extension-host
478
+ disabled: true
479
+ - id: pi-tui-builtins
480
+ disabled: true
481
+
482
+ # Infrastructure lifetime is independent of the mutable tuiStartup provider.
483
+ - id: webserver
484
+ inject: []
485
+ - id: workspace-files
486
+ inject: []
487
+
488
+ - insert:
489
+ # One official Connection owner (loopback /connect + /api) behind the
490
+ # profile's existing webserver (whose Host-only lifetime is independent of
491
+ # tuiStartup). trustedHosts stays empty: loopback and the listener's own
492
+ # bind IP are the only accepted authorities.
493
+ - id: split-host-connection
494
+ name: '@deepseek-ai/dsh-client-connection'
495
+ inject: [credentials, webServer]
496
+ config:
497
+ trustedHosts: []
498
+
499
+ # One forwarded-event source on the base typert-gateway row. It registers
500
+ # host.home and the private $events stream; the gateway is not remounted.
501
+ - id: split-host-api-remotes
502
+ name: '@deepseek-ai/dsh-api-remotes'
503
+ inject: [typertGateway, connection]
504
+
505
+ # Official Session-serving Host rows (rc.4): each is mounted ONCE here and
506
+ # never re-mounted by the built-in PiTui Host Runtime or the Client.
507
+ - id: split-host-file-upload
508
+ name: '@deepseek-ai/dsh-client-file-upload'
509
+ inject: [agents, attachments, commands, connection]
510
+
511
+ - id: split-host-session-stats
512
+ name: '@deepseek-ai/dsh-session-stats'
513
+ inject: [sessionProjections]
514
+
515
+ - id: split-host-turn-outline
516
+ name: '@deepseek-ai/dsh-session-turn-outline'
517
+ inject: [sessionProjections]
518
+
519
+ - id: split-host-session-controller
520
+ name: '@deepseek-ai/dsh-api-session-controller'
521
+ inject: [agentDefaultModel, agents, attachments, fileUploads, fs, llm, remoteAccess, sessions, sessionProjections, sessionQuery, typert, workspaceRegistry]
522
+ config:
523
+ nativeOpen: false
524
+
525
+ - id: split-host-settings-controller
526
+ name: '@deepseek-ai/dsh-api-settings-controller'
527
+ inject: [typert]
528
+
529
+ - id: split-host-session-log-download
530
+ name: '@deepseek-ai/dsh-session-log-export'
531
+ inject: [commands, connection]
532
+
533
+ # The package's ONE built-in Host Runtime row: the private contribution plus
534
+ # the two private business services. Business features are NOT separate
535
+ # Loader rows or package subpaths.
536
+ - id: split-host-pi-tui-runtime
537
+ name: '@xmoon76/dsh-pi-tui/host-runtime'
538
+ inject: [typert, agents, fileReferences, workingDirectory]
539
+ `;
540
+ /** Resolve one published DSH subpath from the installation anchor supplied by the launcher. */
541
+ async function loadOfficialDsh(anchor) {
542
+ const requireFromDsh = createRequire(realpathSync(anchor));
543
+ const importResolved = async (specifier) => import(pathToFileURL(requireFromDsh.resolve(specifier)).href);
544
+ const profileBoot = await importResolved("@deepseek-ai/dsh/profile-boot");
545
+ const appBoot = await importResolved("@deepseek-ai/dsh-app-boot");
546
+ const homePaths = await importResolved("@deepseek-ai/dsh-home-paths");
547
+ return {
548
+ runProfile: profileBoot.runProfile,
549
+ loadLayeredEnv: appBoot.loadLayeredEnv,
550
+ resolveDshHome: homePaths.resolveDshHome,
551
+ resolveProfileDir: appBoot.resolveProfileDir
552
+ };
553
+ }
554
+ /** Wait for one unauthenticated route to answer with the expected refusal. */
555
+ async function waitForRefusal(url, timeoutMs = 1e4) {
556
+ const deadline = Date.now() + timeoutMs;
557
+ while (Date.now() < deadline) {
558
+ try {
559
+ const response = await fetch(url, {
560
+ method: "GET",
561
+ redirect: "manual",
562
+ cache: "no-store"
563
+ });
564
+ await response.body?.cancel();
565
+ if (response.status === 401) return;
566
+ } catch {}
567
+ await new Promise((resolve) => setTimeout(resolve, 100));
568
+ }
569
+ throw new Error(`local host entry: the official route did not become ready: ${url}`);
570
+ }
571
+ /** Qualification-only publication/stop barrier; production never sets either path. */
572
+ async function waitForQualificationBarrier(path) {
573
+ const deadline = Date.now() + 3e4;
574
+ while (!existsSync(path)) {
575
+ if (Date.now() > deadline) throw new Error(`local host entry: the qualification barrier was not released: ${path}`);
576
+ await new Promise((resolve) => setTimeout(resolve, 20));
577
+ }
578
+ }
579
+ /**
580
+ * Publish the authenticated identity and private launch material, then commit
581
+ * the registry as the Ready step. The route is registered before the registry
582
+ * so no Client can observe a registry whose identity route is missing.
583
+ */
584
+ async function publishLocalHost(context, scope, processStarttime) {
585
+ const connection = context.get("connection");
586
+ 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");
587
+ const webServer = context.get("webServer");
588
+ 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");
589
+ const origin = webServer.getOrigin();
590
+ 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");
591
+ await waitForRefusal(`${origin}/connect`);
592
+ const instanceId = randomUUID();
593
+ const identity = {
594
+ schema: 1,
595
+ scopeId: scope.scopeId,
596
+ profileRealpath: scope.profileRealpath,
597
+ instanceId,
598
+ hostPid: process.pid,
599
+ hostStarttime: processStarttime,
600
+ origin,
601
+ protocol: LOCAL_PROTOCOL,
602
+ bundleVersion: scope.bundleVersion,
603
+ dshVersion: scope.dshVersion,
604
+ buildId: scope.buildId
605
+ };
606
+ const connectUrl = connection.authenticatedUrl(`${origin}/connect`);
607
+ const connectProbe = new URL(connectUrl);
608
+ 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");
609
+ const { writeLaunchMaterial, writeLocalRecord } = await import("./local-discovery-DVFFpfBG.mjs");
610
+ writeLaunchMaterial(scope, identity, {
611
+ schema: 1,
612
+ instanceId,
613
+ connectUrl
614
+ });
615
+ let unregister;
616
+ try {
617
+ unregister = connection.fetch.register({
618
+ path: "/api/pi-tui.local-host",
619
+ methods: ["GET"],
620
+ requestBody: "buffered",
621
+ fetch: async () => Response.json(identity, { headers: {
622
+ "content-type": "application/json",
623
+ "cache-control": "no-store"
624
+ } })
625
+ });
626
+ await waitForRefusal(`${origin}/api/pi-tui.local-host`);
627
+ writeLocalRecord(scope, identity);
628
+ const barrier = process.env.SPLIT_PROCESS_HOST_PUBLISH_BARRIER;
629
+ if (barrier !== void 0 && barrier !== "") await waitForQualificationBarrier(barrier);
630
+ } catch (error) {
631
+ try {
632
+ await unregister?.();
633
+ } catch {}
634
+ cleanupOwnedFiles(scope, instanceId);
635
+ throw error;
636
+ }
637
+ return {
638
+ identity,
639
+ async unregisterIdentity() {
640
+ await unregister?.();
641
+ }
642
+ };
643
+ }
644
+ /**
645
+ * Run one Host-only process and remove only the scratch this process created
646
+ * under its independently derived real scope. A failure anywhere before the
647
+ * post-boot controller (official-module load, scope construction, kernel seat,
648
+ * overlay write, starttime read or profile boot) still passes through this
649
+ * owner-safe finally; the launcher-supplied path and another live Host's
650
+ * scratch are never deletion authority. A forced `process.exit()` from the
651
+ * launcher's native signal handler during `runProfile` bypasses the async
652
+ * finally, so a synchronous exit mirror below removes the same owned scratch.
653
+ */
654
+ async function runLocalHostEntry(options) {
655
+ const owned = {};
656
+ process.once("exit", () => {
657
+ if (owned.scopeDir !== void 0 && owned.scratchDir !== void 0) removeOwnedScratch(owned.scopeDir, owned.scratchDir);
658
+ });
659
+ try {
660
+ await runLocalHostEntryOwned(options, owned);
661
+ } finally {
662
+ if (owned.scopeDir !== void 0 && owned.scratchDir !== void 0) removeOwnedScratch(owned.scopeDir, owned.scratchDir);
663
+ }
664
+ }
665
+ /**
666
+ * Run one Host-only process until its launcher requests shutdown. Exported so
667
+ * the process-level qualification harness can document its exact contract; the
668
+ * module's `import.meta.main` block is the only caller in production.
669
+ */
670
+ async function runLocalHostEntryOwned(options, scratchOwner) {
671
+ const dsh = await loadOfficialDsh(options.dshAnchor);
672
+ const dshHome = dsh.resolveDshHome();
673
+ const scope = scopeFromInstalledProfile({
674
+ dshHome,
675
+ profileDir: dsh.resolveProfileDir(options.profile, dshHome),
676
+ packageRoot: installedPackageRootFromEntry(import.meta.url),
677
+ dshVersion: readInstalledDshVersion(options.dshAnchor)
678
+ });
679
+ scratchOwner.scopeDir = scope.dir;
680
+ let seat;
681
+ try {
682
+ seat = await bindProcessSeat(scope.hostSocketName, "HOST_ALREADY_OWNED");
683
+ } catch (error) {
684
+ if (error instanceof LocalScopeError && error.code === "HOST_ALREADY_OWNED") {
685
+ writeEntryRecord({
686
+ m4a0: "host-seat-conflict",
687
+ processRole: "host",
688
+ pid: process.pid,
689
+ scopeId: scope.scopeId,
690
+ error: error.code
691
+ });
692
+ return;
693
+ }
694
+ throw error;
695
+ }
696
+ let handle;
697
+ let registration;
698
+ let liveness;
699
+ try {
700
+ const scratchDir = mkdtempSync(join(scope.dir, "host-scratch-"));
701
+ scratchOwner.scratchDir = scratchDir;
702
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_EARLY_EXIT === "1") process.exit(1);
703
+ const overlayPath = join(scratchDir, "host-only.patch.yml");
704
+ writeFileSync(overlayPath, HOST_ONLY_PATCH, { mode: 384 });
705
+ const processStartIdentity = readLinuxStarttime();
706
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_BOOT_FAILURE === "before-profile") throw new Error("local host entry: qualification forced pre-profile failure");
707
+ process.env.DSH_PI_TUI_ROLE = "host";
708
+ if (process.argv[1] !== void 0) process.env.DSH_PI_TUI_HOST_ENTRY = realpathSync(process.argv[1]);
709
+ const priorSigterm = process.listeners("SIGTERM");
710
+ const priorSigint = process.listeners("SIGINT");
711
+ handle = await dsh.runProfile({
712
+ environment: dsh.loadLayeredEnv("dsh", process.cwd()),
713
+ profile: options.profile,
714
+ patchFiles: [overlayPath, ...options.extraPatchFiles ?? []],
715
+ args: []
716
+ });
717
+ const shutdownOwner = handle.shutdown;
718
+ try {
719
+ writeEntryRecord({
720
+ m4a0: "profile-booted",
721
+ processRole: "host",
722
+ pid: process.pid,
723
+ phase: "profile-booted"
724
+ });
725
+ const { settleHostEntries, collectHostEntryStatus } = await import("./host-bootstrap-CKdfLkNS.mjs");
726
+ await settleHostEntries(handle.ctx);
727
+ const status = collectHostEntryStatus(handle.ctx, {
728
+ profile: options.profile,
729
+ processStartIdentity
730
+ });
731
+ liveness = new HostActivityObserver(handle.ctx);
732
+ let published;
733
+ let stopping;
734
+ let shuttingDown = false;
735
+ let resolveStopped;
736
+ const stopped = new Promise((resolve) => {
737
+ resolveStopped = resolve;
738
+ });
739
+ const stop = (code, owner) => {
740
+ if (stopping !== void 0) return stopping;
741
+ shuttingDown = true;
742
+ stopping = (async () => {
743
+ const errors = [];
744
+ try {
745
+ liveness?.close();
746
+ } catch (error) {
747
+ errors.push({
748
+ step: "liveness-close",
749
+ error
750
+ });
751
+ }
752
+ try {
753
+ if (process.env.SPLIT_PROCESS_HOST_FORCE_SCRATCH_REMOVE_FAILURE === "1") throw new Error("local host entry: qualification forced scratch removal failure");
754
+ removeOwnedScratch(scope.dir, scratchDir);
755
+ } catch (error) {
756
+ errors.push({
757
+ step: "scratch-remove",
758
+ error
759
+ });
760
+ }
761
+ try {
762
+ await owner.unregisterIdentity();
763
+ } catch (error) {
764
+ errors.push({
765
+ step: "identity-unregister",
766
+ error
767
+ });
768
+ }
769
+ try {
770
+ await shutdownOwner.shutdown(code);
771
+ } catch (error) {
772
+ errors.push({
773
+ step: "shutdown",
774
+ error
775
+ });
776
+ }
777
+ cleanupOwnedFiles(scope, owner.identity.instanceId);
778
+ if (errors.length > 0) {
779
+ const first = errors[0];
780
+ const primary = first.error instanceof Error ? first.error : new Error(String(first.error));
781
+ writeEntryRecord({
782
+ m4a0: "cleanup-failure",
783
+ processRole: "host",
784
+ phase: "shutdown",
785
+ pid: process.pid,
786
+ error: primary.message,
787
+ step: first.step
788
+ });
789
+ process.exitCode = 1;
790
+ } else {
791
+ writeEntryRecord({
792
+ m4a0: "cleanup",
793
+ processRole: "host",
794
+ phase: "shutdown",
795
+ pid: process.pid,
796
+ status: "completed"
797
+ });
798
+ process.exitCode = code;
799
+ }
800
+ const stopBarrier = process.env.SPLIT_PROCESS_HOST_STOP_BARRIER;
801
+ if (stopBarrier !== void 0 && stopBarrier !== "") await waitForQualificationBarrier(stopBarrier);
802
+ resolveStopped?.();
803
+ })();
804
+ return stopping;
805
+ };
806
+ let pendingStop;
807
+ const requestStop = (code, signal) => {
808
+ const owner = published;
809
+ if (pendingStop !== void 0) {
810
+ writeEntryRecord({
811
+ m4a0: "stop-repeat-ignored",
812
+ processRole: "host",
813
+ pid: process.pid,
814
+ signal,
815
+ phase: shuttingDown ? "shutdown" : owner === void 0 ? "publication" : "running"
816
+ });
817
+ return;
818
+ }
819
+ pendingStop = code;
820
+ writeEntryRecord({
821
+ m4a0: "stop-requested",
822
+ processRole: "host",
823
+ pid: process.pid,
824
+ signal,
825
+ phase: shuttingDown ? "shutdown" : owner === void 0 ? "publication" : "running"
826
+ });
827
+ if (owner !== void 0) runDetached(`local host: ${signal} shutdown`, () => stop(code, owner), { diag: createEntryDiag("host") });
828
+ };
829
+ const launcherSigterm = process.listeners("SIGTERM").find((listener) => !priorSigterm.includes(listener));
830
+ if (launcherSigterm !== void 0) process.removeListener("SIGTERM", launcherSigterm);
831
+ const launcherSigint = process.listeners("SIGINT").find((listener) => !priorSigint.includes(listener));
832
+ if (launcherSigint !== void 0) process.removeListener("SIGINT", launcherSigint);
833
+ const onSigterm = () => {
834
+ requestStop(0, "SIGTERM");
835
+ };
836
+ const onSigint = () => {
837
+ requestStop(130, "SIGINT");
838
+ };
839
+ process.on("SIGTERM", onSigterm);
840
+ process.on("SIGINT", onSigint);
841
+ const releaseSignalAdmission = () => {
842
+ process.removeListener("SIGTERM", onSigterm);
843
+ process.removeListener("SIGINT", onSigint);
844
+ };
845
+ const publishedHost = await publishLocalHost(handle.ctx, scope, processStartIdentity);
846
+ published = publishedHost;
847
+ registration = publishedHost;
848
+ process.once("exit", () => {
849
+ cleanupOwnedFiles(scope, publishedHost.identity.instanceId);
850
+ });
851
+ if (pendingStop !== void 0) {
852
+ await stop(pendingStop, publishedHost);
853
+ releaseSignalAdmission();
854
+ return;
855
+ }
856
+ const initialLivenessPromise = liveness.snapshot();
857
+ const livenessBarrier = process.env.SPLIT_PROCESS_HOST_LIVENESS_BARRIER;
858
+ if (livenessBarrier !== void 0 && livenessBarrier !== "") {
859
+ writeEntryRecord({
860
+ m4a0: "qualification",
861
+ processRole: "host",
862
+ op: "liveness-barrier",
863
+ pid: process.pid
864
+ });
865
+ await waitForQualificationBarrier(livenessBarrier);
866
+ }
867
+ const initialLiveness = await initialLivenessPromise;
868
+ if (stopping !== void 0 || pendingStop !== void 0) {
869
+ await stopped;
870
+ releaseSignalAdmission();
871
+ return;
872
+ }
873
+ writeEntryRecord({
874
+ m4a0: "ready",
875
+ ...status,
876
+ liveness: initialLiveness,
877
+ localHost: publishedHost.identity
878
+ });
879
+ attachEntryControl(async (request) => {
880
+ if (request.op === "status") {
881
+ const snapshot = await liveness.snapshot();
882
+ writeEntryRecord({
883
+ m4a0: "status",
884
+ ...request.requestId === void 0 ? {} : { requestId: request.requestId },
885
+ ...collectHostEntryStatus(handle.ctx, {
886
+ profile: options.profile,
887
+ processStartIdentity
888
+ }),
889
+ liveness: snapshot,
890
+ localHost: publishedHost.identity
891
+ });
892
+ return false;
893
+ }
894
+ if (request.op === "shutdown") {
895
+ await stop(0, publishedHost);
896
+ return true;
897
+ }
898
+ writeEntryRecord({
899
+ m4a0: "control-error",
900
+ error: `local host entry: unknown op ${JSON.stringify(request.op)}`
901
+ });
902
+ return false;
903
+ });
904
+ await stopped;
905
+ releaseSignalAdmission();
906
+ } catch (error) {
907
+ writeEntryRecord({
908
+ m4a0: "failure",
909
+ processRole: "host",
910
+ phase: "after-boot",
911
+ pid: process.pid,
912
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
913
+ error: error instanceof Error ? error.message : String(error),
914
+ ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
915
+ });
916
+ let priorCleanupFailure;
917
+ try {
918
+ const loader = handle.ctx.loader;
919
+ if (loader !== void 0) await Promise.race([loader.await(), new Promise((_, reject) => {
920
+ setTimeout(() => reject(/* @__PURE__ */ new Error("local host entry: profile entries did not settle before failure cleanup")), 5e3);
921
+ })]);
922
+ } catch (settleError) {
923
+ priorCleanupFailure = settleError instanceof Error ? settleError.message : String(settleError);
924
+ writeEntryRecord({
925
+ m4a0: "cleanup-failure",
926
+ processRole: "host",
927
+ phase: "after-boot",
928
+ pid: process.pid,
929
+ step: "settle-before-shutdown",
930
+ error: priorCleanupFailure
931
+ });
932
+ }
933
+ try {
934
+ liveness?.close();
935
+ } catch (cleanupError) {
936
+ priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
937
+ writeEntryRecord({
938
+ m4a0: "cleanup-failure",
939
+ processRole: "host",
940
+ phase: "after-boot",
941
+ pid: process.pid,
942
+ step: "liveness-close",
943
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
944
+ });
945
+ }
946
+ try {
947
+ await registration?.unregisterIdentity();
948
+ } catch (cleanupError) {
949
+ priorCleanupFailure ??= cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
950
+ writeEntryRecord({
951
+ m4a0: "cleanup-failure",
952
+ processRole: "host",
953
+ phase: "after-boot",
954
+ pid: process.pid,
955
+ step: "identity-unregister",
956
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
957
+ });
958
+ }
959
+ await finishHostFailureCleanup(shutdownOwner, writeEntryRecord, priorCleanupFailure === void 0 ? void 0 : { priorCleanupFailure });
960
+ if (registration !== void 0) cleanupOwnedFiles(scope, registration.identity.instanceId);
961
+ process.exitCode = 1;
962
+ }
963
+ } finally {
964
+ await seat.close();
965
+ }
966
+ }
967
+ async function finishHostFailureCleanup(shutdownOwner, emit = writeEntryRecord, options = {}) {
968
+ try {
969
+ await shutdownOwner.shutdown(1);
970
+ if (options.priorCleanupFailure !== void 0) {
971
+ emit({
972
+ m4a0: "cleanup-failure",
973
+ processRole: "host",
974
+ phase: "after-boot",
975
+ pid: process.pid,
976
+ step: "prior-cleanup",
977
+ error: options.priorCleanupFailure
978
+ });
979
+ return false;
980
+ }
981
+ emit({
982
+ m4a0: "cleanup",
983
+ processRole: "host",
984
+ phase: "after-boot",
985
+ pid: process.pid,
986
+ status: "completed"
987
+ });
988
+ return true;
989
+ } catch (cleanupError) {
990
+ emit({
991
+ m4a0: "cleanup-failure",
992
+ processRole: "host",
993
+ phase: "after-boot",
994
+ pid: process.pid,
995
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
996
+ });
997
+ return false;
998
+ }
999
+ }
1000
+ /** Read the launcher environment; a missing anchor is a hard startup failure. */
1001
+ function optionsFromEnvironment() {
1002
+ const dshAnchor = process.env.SPLIT_PROCESS_DSH_ANCHOR;
1003
+ if (dshAnchor === void 0 || dshAnchor === "") throw new Error("local host entry: SPLIT_PROCESS_DSH_ANCHOR must name the installed @deepseek-ai/dsh/package.json");
1004
+ return {
1005
+ dshAnchor,
1006
+ profile: process.env.SPLIT_PROCESS_PROFILE ?? "pi-tui",
1007
+ ...process.env.SPLIT_PROCESS_EXTRA_PATCH === void 0 || process.env.SPLIT_PROCESS_EXTRA_PATCH === "" ? {} : { extraPatchFiles: [process.env.SPLIT_PROCESS_EXTRA_PATCH] }
1008
+ };
1009
+ }
1010
+ if (import.meta.main) try {
1011
+ await runLocalHostEntry(optionsFromEnvironment());
1012
+ } catch (error) {
1013
+ writeEntryRecord({
1014
+ m4a0: "failure",
1015
+ processRole: "host",
1016
+ phase: "startup",
1017
+ pid: process.pid,
1018
+ ...error instanceof LocalScopeError ? { code: error.code } : {},
1019
+ error: error instanceof Error ? error.message : String(error),
1020
+ ...error instanceof Error && error.stack !== void 0 ? { stack: error.stack } : {}
1021
+ });
1022
+ process.exit(1);
1023
+ }
1024
+ //#endregion
1025
+ export { HOST_ONLY_PATCH, finishHostFailureCleanup, runLocalHostEntry };