@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +33 -0
  2. package/README.en.md +103 -814
  3. package/README.md +102 -711
  4. package/cordis.patch.yml +186 -0
  5. package/dist/acp-preferences.d.mts +29 -0
  6. package/dist/acp-preferences.mjs +15 -0
  7. package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
  8. package/dist/builtins.mjs +3 -3
  9. package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
  10. package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
  11. package/dist/command-trust-DChWUamk.mjs +406 -0
  12. package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
  13. package/dist/daemon-launcher.d.mts +159 -0
  14. package/dist/daemon-launcher.mjs +2 -0
  15. package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
  16. package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
  17. package/dist/entry-control-DjNsE3I0.mjs +190 -0
  18. package/dist/extension/advanced.d.mts +1 -1
  19. package/dist/extension/unstable.d.mts +1 -1
  20. package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
  21. package/dist/extension-config.d.mts +29 -0
  22. package/dist/extension-config.mjs +22 -0
  23. package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
  24. package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
  25. package/dist/extensions.d.mts +2 -2
  26. package/dist/extensions.mjs +1 -1
  27. package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
  28. package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
  29. package/dist/host-runtime.d.mts +11 -5
  30. package/dist/host-runtime.mjs +4171 -920
  31. package/dist/index.d.mts +86 -174
  32. package/dist/index.mjs +38087 -9967
  33. package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
  34. package/dist/local-client.mjs +1158 -59
  35. package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
  36. package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
  37. package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
  38. package/dist/local-discovery-egN4_gsQ.mjs +2 -0
  39. package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
  40. package/dist/local-host.mjs +812 -89
  41. package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
  42. package/dist/local-scope-DamiMqPd.mjs +1340 -0
  43. package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
  44. package/dist/local-web-control-DMrjwCkl.mjs +454 -0
  45. package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
  46. package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  47. package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  48. package/dist/open-CmOBxSjN.mjs +63 -0
  49. package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
  50. package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
  51. package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
  52. package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
  53. package/dist/preferences.d.mts +17 -0
  54. package/dist/preferences.mjs +20 -0
  55. package/dist/preset-BcWqOtY7.mjs +46 -0
  56. package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
  57. package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
  58. package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
  59. package/dist/prompt-sections-DXmjB58H.mjs +634 -0
  60. package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
  61. package/dist/row-id-DPbyt9Nn.mjs +24 -0
  62. package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
  63. package/dist/schema-BTGYn8_X.d.mts +54 -0
  64. package/dist/schema-qE_P09zJ.mjs +124 -0
  65. package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
  66. package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
  67. package/dist/startup-CarQxWwi.d.mts +213 -0
  68. package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
  69. package/dist/startup.d.mts +2 -99
  70. package/dist/startup.mjs +2 -2
  71. package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
  72. package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
  73. package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
  74. package/dist/version-B9yC7bBk.mjs +83 -0
  75. package/dist/visual-tools.d.mts +1 -1
  76. package/dist/visual-tools.mjs +1 -1
  77. package/dist/web-preferences.d.mts +1 -1
  78. package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
  79. package/generated/dsh-presets/cordis.patch.yml +4 -2
  80. package/generated/dsh-presets/ptc.patch.yml +4 -0
  81. package/generated/dsh-presets/standard.patch.yml +7 -0
  82. package/generated/web-access/cordis.patch.yml +239 -0
  83. package/package.json +217 -170
  84. package/dist/entry-control-DnduyDiw.mjs +0 -92
  85. package/dist/local-discovery-C9VMjc0K.mjs +0 -759
  86. package/dist/local-discovery-CDaQHA_R.mjs +0 -2
  87. package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
  88. package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
  89. package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
  90. package/dist/version-a-eF-QER.mjs +0 -80
@@ -0,0 +1,454 @@
1
+ import { n as openerFor } from "./open-CmOBxSjN.mjs";
2
+ import { v as inspectInstalledProfileScope } from "./daemon-launcher-Dult7Jxv.mjs";
3
+ import { a as inspectHostProcess, n as assertRecordedHostKernelIdentityCurrent, o as readLocalRecord, r as authenticateLocalHost, s as sameLocalInstanceRecord, t as assertClientHostCompatible } from "./local-discovery-uOBfFq5j.mjs";
4
+ import { spawn } from "node:child_process";
5
+ //#region src/app/remote-process/local-web-control-route.ts
6
+ /** The one Owner-only authenticated route of the headless Web CLI. */
7
+ const LOCAL_WEB_CONTROL_ROUTE = "/api/pi-tui.web-control";
8
+ /** Hard response-body bound the CLI accepts. */
9
+ const LOCAL_WEB_CONTROL_MAX_RESPONSE_BYTES = 4096;
10
+ /** Bound on one CLI request after authentication has completed. */
11
+ const LOCAL_WEB_CONTROL_TIMEOUT_MS = 1e4;
12
+ const STATE_VALUES = /* @__PURE__ */ new Set([
13
+ "enabled",
14
+ "disabled",
15
+ "changing",
16
+ "unavailable"
17
+ ]);
18
+ const ERROR_CODES = /* @__PURE__ */ new Set([
19
+ "WEB_INVALID_REQUEST",
20
+ "WEB_INSTANCE_MISMATCH",
21
+ "WEB_DISABLED",
22
+ "WEB_CHANGING",
23
+ "WEB_CLI_UNAVAILABLE"
24
+ ]);
25
+ function isRecord(value) {
26
+ return value !== null && typeof value === "object" && !Array.isArray(value);
27
+ }
28
+ function hasExactKeys(record, keys) {
29
+ const actual = Object.keys(record).sort();
30
+ const expected = [...keys].sort();
31
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
32
+ }
33
+ function isErrorCode(value) {
34
+ return typeof value === "string" && ERROR_CODES.has(value);
35
+ }
36
+ function isState(value) {
37
+ return typeof value === "string" && STATE_VALUES.has(value);
38
+ }
39
+ /**
40
+ * Parse one strict route response body. Both the route tests and the CLI use
41
+ * this ONE validator, so the wire shape cannot drift into two implementations.
42
+ * @param text - the raw UTF-8 response body.
43
+ * @returns the discriminated reply.
44
+ */
45
+ function parseLocalWebControlReply(text) {
46
+ let value;
47
+ try {
48
+ value = JSON.parse(text);
49
+ } catch {
50
+ throw new TypeError("local web control: the reply is not JSON");
51
+ }
52
+ if (!isRecord(value) || value.schema !== 1) throw new TypeError("local web control: the reply must be a schema-1 object");
53
+ if (hasExactKeys(value, ["schema", "error"])) {
54
+ if (!isErrorCode(value.error)) throw new TypeError("local web control: unknown error code");
55
+ return {
56
+ kind: "error",
57
+ error: value.error
58
+ };
59
+ }
60
+ if (hasExactKeys(value, [
61
+ "schema",
62
+ "instanceId",
63
+ "state"
64
+ ])) {
65
+ if (typeof value.instanceId !== "string" || value.instanceId === "") throw new TypeError("local web control: the reply has no instance id");
66
+ if (!isState(value.state)) throw new TypeError("local web control: unknown Web state");
67
+ return {
68
+ kind: "state",
69
+ instanceId: value.instanceId,
70
+ state: value.state
71
+ };
72
+ }
73
+ if (hasExactKeys(value, [
74
+ "schema",
75
+ "instanceId",
76
+ "url"
77
+ ])) {
78
+ if (typeof value.instanceId !== "string" || value.instanceId === "") throw new TypeError("local web control: the reply has no instance id");
79
+ if (typeof value.url !== "string" || value.url === "") throw new TypeError("local web control: the reply has no URL");
80
+ return {
81
+ kind: "url",
82
+ instanceId: value.instanceId,
83
+ url: value.url
84
+ };
85
+ }
86
+ throw new TypeError("local web control: unexpected reply shape");
87
+ }
88
+ //#endregion
89
+ //#region src/app/remote-process/local-web-control.ts
90
+ /**
91
+ * The headless Web CLI runner (M6 Web CLI).
92
+ *
93
+ * One short-lived management process reads the installed Profile through the
94
+ * existing read-only scope inspection, authenticates the ONE live Host with the
95
+ * official `/connect` Cookie + identity + fresh kernel check, performs exactly
96
+ * ONE request against the Owner-only `/api/pi-tui.web-control` adapter, and
97
+ * maps the reply to the fixed stdout/stderr/exit contract. It never starts a
98
+ * Host, never opens a TUI/Client, never creates a Session/Agent/Writer and never
99
+ * caches a Web state.
100
+ *
101
+ * ```text
102
+ * runLocalWebControl -> inspectInstalledProfileScope -> authenticateLocalHost
103
+ * -> ONE GET/POST /api/pi-tui.web-control -> typed result
104
+ * ```
105
+ *
106
+ * The URL produced by `web url` is the official Host-built authenticated URL;
107
+ * this module never synthesizes a token, never logs the URL, and passes it
108
+ * unchanged to stdout (or to the local OS opener, which runs on the CLI machine).
109
+ *
110
+ * @module app/remote-process/local-web-control
111
+ */
112
+ const EXIT_CODE = {
113
+ UNSUPPORTED_PLATFORM: 3,
114
+ HOST_NOT_RUNNING: 3,
115
+ HOST_IDENTITY_REFUSED: 3,
116
+ HOST_AUTH_FAILED: 3,
117
+ WEB_DISABLED: 4,
118
+ WEB_CHANGING: 5,
119
+ WEB_CLI_UNAVAILABLE: 4,
120
+ WEB_UNAVAILABLE: 4,
121
+ WEB_OUTCOME_UNCONFIRMED: 5,
122
+ BROWSER_LAUNCH_UNAVAILABLE: 4
123
+ };
124
+ /** One stable failure with its fixed exit class and a local-only reason. */
125
+ var WebControlError = class extends Error {
126
+ code;
127
+ exitCode;
128
+ reason;
129
+ constructor(code, reason, cause) {
130
+ super(reason, cause === void 0 ? void 0 : { cause });
131
+ this.name = "WebControlError";
132
+ this.code = code;
133
+ this.exitCode = EXIT_CODE[code];
134
+ this.reason = reason;
135
+ }
136
+ };
137
+ /** POSIX-safe single-argument quoting for the copy-paste hint. */
138
+ function shellQuote(value) {
139
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/u.test(value)) return value;
140
+ return `'${value.replace(/'/gu, `'\\''`)}'`;
141
+ }
142
+ /** Replace private paths/URLs and control characters in a human reason. */
143
+ function sanitizeReason(text) {
144
+ return (text.split(/\r?\n/u).map((part) => part.trim()).find((part) => part !== "") ?? "").replace(/\/[^\s"']+/gu, "<path>").replace(/https?:\/\/[^\s"']+/giu, "<url>").replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, 200);
145
+ }
146
+ function formatWebControlError(error) {
147
+ return `dsh-pi-tui web: ${error.code}: ${sanitizeReason(error.reason)}\n`;
148
+ }
149
+ /**
150
+ * Classify a read request that produced no response. A live authenticated Host
151
+ * can be slow or briefly unreachable, so a missing response is never proof that
152
+ * it stopped: only a fresh same-scope record plus a dead process (or a removed
153
+ * record) may claim HOST_NOT_RUNNING. A replaced instance is an identity
154
+ * refusal; every unprovable case stays WEB_CLI_UNAVAILABLE.
155
+ */
156
+ function readRequestFailure(verified, scope, deps) {
157
+ try {
158
+ const readRecord = deps.readRecord ?? readLocalRecord;
159
+ const inspect = deps.inspectProcess ?? inspectHostProcess;
160
+ const current = readRecord(scope);
161
+ if (current === void 0) return new WebControlError("HOST_NOT_RUNNING", "the Host for this Profile is no longer running");
162
+ if (!sameLocalInstanceRecord(current, verified.record)) return new WebControlError("HOST_IDENTITY_REFUSED", "the Host identity changed while the request was in flight");
163
+ if (inspect(verified.record) === "dead") return new WebControlError("HOST_NOT_RUNNING", "the Host for this Profile is no longer running");
164
+ } catch {}
165
+ return new WebControlError("WEB_CLI_UNAVAILABLE", "the authenticated Host did not answer the Web CLI request");
166
+ }
167
+ function platformOf(deps) {
168
+ return deps.platform ?? process.platform;
169
+ }
170
+ function notRunningReason(profile) {
171
+ return `the Host for this Profile is not running; start it with: dsh --profile ${shellQuote(profile.name)} daemon start`;
172
+ }
173
+ function disabledReason(profile) {
174
+ return `Web access is disabled for this Profile; run: dsh --profile ${shellQuote(profile.name)} web enable`;
175
+ }
176
+ /** Map a lower-level failure to the fixed Web CLI taxonomy. */
177
+ function toWebControlError(error) {
178
+ if (error instanceof WebControlError) return error;
179
+ switch (error?.code) {
180
+ case "B1_PLATFORM_UNSUPPORTED": return new WebControlError("UNSUPPORTED_PLATFORM", "the web CLI is only supported on Linux and macOS");
181
+ case "SCOPE_DIRECTORY_UNSAFE":
182
+ case "LOCAL_FILE_UNSAFE":
183
+ case "HOST_PROTOCOL_INCOMPATIBLE":
184
+ case "HOST_BUILD_INCOMPATIBLE":
185
+ case "HOST_IDENTITY_MISMATCH":
186
+ case "PROCESS_STARTTIME_UNAVAILABLE": return new WebControlError("HOST_IDENTITY_REFUSED", "the local Host identity could not be verified for this Profile", error);
187
+ case "HOST_HANDOFF_UNAVAILABLE": return new WebControlError("HOST_NOT_RUNNING", "the Host for this Profile is not running", error);
188
+ case "HOST_AUTH_FAILED":
189
+ case "HOST_UNRESPONSIVE": return new WebControlError("HOST_AUTH_FAILED", "the local Host did not accept the authenticated handshake", error);
190
+ default: return new WebControlError("WEB_CLI_UNAVAILABLE", "an unexpected local Web CLI failure occurred", error);
191
+ }
192
+ }
193
+ /** Read at most `maxBytes` of a response body; an oversize/unreadable body is `undefined`. */
194
+ async function readBoundedResponse(response, maxBytes) {
195
+ if (response.body === null) return "";
196
+ const reader = response.body.getReader();
197
+ const chunks = [];
198
+ let total = 0;
199
+ try {
200
+ for (;;) {
201
+ const { done, value } = await reader.read();
202
+ if (done) break;
203
+ total += value.byteLength;
204
+ if (total > maxBytes) {
205
+ await reader.cancel();
206
+ return;
207
+ }
208
+ chunks.push(value);
209
+ }
210
+ } finally {
211
+ reader.releaseLock();
212
+ }
213
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
214
+ }
215
+ /** One bounded request against the ONE Owner-only route. */
216
+ async function callWebControl(verified, op, deps) {
217
+ const signal = deps.signal === void 0 ? AbortSignal.timeout(LOCAL_WEB_CONTROL_TIMEOUT_MS) : AbortSignal.any([deps.signal, AbortSignal.timeout(LOCAL_WEB_CONTROL_TIMEOUT_MS)]);
218
+ const init = op === "status" ? {
219
+ method: "GET",
220
+ headers: { cookie: verified.cookie },
221
+ redirect: "manual",
222
+ cache: "no-store",
223
+ signal
224
+ } : {
225
+ method: "POST",
226
+ headers: {
227
+ cookie: verified.cookie,
228
+ "content-type": "application/json"
229
+ },
230
+ body: JSON.stringify({
231
+ schema: 1,
232
+ instanceId: verified.identity.instanceId,
233
+ op
234
+ }),
235
+ redirect: "manual",
236
+ cache: "no-store",
237
+ signal
238
+ };
239
+ const fetchImpl = deps.fetch ?? fetch;
240
+ let response;
241
+ try {
242
+ response = await fetchImpl(`${verified.record.origin}${LOCAL_WEB_CONTROL_ROUTE}`, init);
243
+ } catch {
244
+ return { status: 0 };
245
+ }
246
+ let text;
247
+ try {
248
+ text = await readBoundedResponse(response, LOCAL_WEB_CONTROL_MAX_RESPONSE_BYTES);
249
+ } catch {
250
+ text = void 0;
251
+ }
252
+ const contentType = response.headers.get("content-type") ?? "";
253
+ const cacheControl = response.headers.get("cache-control") ?? "";
254
+ if (text === void 0 || !/^application\/json\b/iu.test(contentType) || !/\bno-store\b/iu.test(cacheControl)) return { status: response.status };
255
+ try {
256
+ return {
257
+ status: response.status,
258
+ reply: parseLocalWebControlReply(text)
259
+ };
260
+ } catch {
261
+ return { status: response.status };
262
+ }
263
+ }
264
+ /**
265
+ * Prove the reply still belongs to the authenticated Host: the reply must echo
266
+ * THIS instance, the same-scope registry must still name the SAME instance and
267
+ * the fresh kernel identity must still be that process. A host replaced during
268
+ * the request cannot lend its answer to this CLI.
269
+ */
270
+ function assertReplyBelongsToAuthenticatedHost(verified, reply, scope, deps) {
271
+ if (reply.instanceId !== verified.identity.instanceId) throw new WebControlError("HOST_IDENTITY_REFUSED", "the Host reply names a different instance");
272
+ const current = (deps.readRecord ?? readLocalRecord)(scope);
273
+ if (current === void 0 || !sameLocalInstanceRecord(current, verified.record)) throw new WebControlError("HOST_IDENTITY_REFUSED", "the Host identity changed while the request was in flight");
274
+ (deps.assertKernelIdentity ?? assertRecordedHostKernelIdentityCurrent)(verified.record);
275
+ }
276
+ /** Validate the official authenticated URL before printing/opening it. */
277
+ function assertAuthenticatedWebUrl(raw, origin) {
278
+ let url;
279
+ try {
280
+ url = new URL(raw);
281
+ } catch {
282
+ throw new WebControlError("WEB_CLI_UNAVAILABLE", "the Host returned an unparsable Web URL");
283
+ }
284
+ const tokens = url.searchParams.getAll("token");
285
+ const keys = [...url.searchParams.keys()];
286
+ if (url.protocol !== "http:" || url.origin !== origin || url.pathname !== "/" || url.username !== "" || url.password !== "" || url.hash !== "" || tokens.length !== 1 || tokens[0] === "" || keys.length !== 1) throw new WebControlError("WEB_CLI_UNAVAILABLE", "the Host returned an unexpected Web URL");
287
+ return raw;
288
+ }
289
+ /**
290
+ * Ask the local OS opener to open one URL. Success means the OS accepted the
291
+ * launch request, never that a Browser page loaded. A synchronously observable
292
+ * spawn error or immediate non-zero exit is a real failure.
293
+ */
294
+ async function launchBrowser(url, deps) {
295
+ const { command, args } = openerFor(url, platformOf(deps));
296
+ const spawnImpl = deps.spawn ?? spawn;
297
+ let child;
298
+ try {
299
+ child = spawnImpl(command, args, {
300
+ shell: false,
301
+ stdio: "ignore",
302
+ detached: true
303
+ });
304
+ } catch (error) {
305
+ throw new WebControlError("BROWSER_LAUNCH_UNAVAILABLE", "the local browser opener could not be started", error);
306
+ }
307
+ await new Promise((resolve, reject) => {
308
+ let settled = false;
309
+ let spawnTimer;
310
+ let exitTimer;
311
+ const finish = (failure) => {
312
+ if (settled) return;
313
+ settled = true;
314
+ if (spawnTimer !== void 0) clearTimeout(spawnTimer);
315
+ if (exitTimer !== void 0) clearTimeout(exitTimer);
316
+ child.removeListener("error", onError);
317
+ child.removeListener("exit", onExit);
318
+ if (failure === void 0) resolve();
319
+ else reject(new WebControlError("BROWSER_LAUNCH_UNAVAILABLE", failure));
320
+ };
321
+ const onError = () => {
322
+ finish("the local browser opener could not be started");
323
+ };
324
+ const onExit = (code, _signal) => {
325
+ if (code === 0) finish();
326
+ else finish("the local browser opener exited with an error");
327
+ };
328
+ child.once("error", onError);
329
+ child.once("exit", onExit);
330
+ spawnTimer = setTimeout(() => {
331
+ finish("the local browser opener did not accept the request");
332
+ }, 2e3);
333
+ child.once("spawn", () => {
334
+ if (spawnTimer !== void 0) clearTimeout(spawnTimer);
335
+ try {
336
+ child.unref();
337
+ } catch {}
338
+ exitTimer = setTimeout(() => {
339
+ finish();
340
+ }, deps.openerWaitMs ?? 250);
341
+ });
342
+ });
343
+ }
344
+ /** Map one write result to the fixed settle/unknown contract. */
345
+ function writeResult(verb, state, profile) {
346
+ if (state === (verb === "enable" ? "enabled" : "disabled")) return {
347
+ code: 0,
348
+ stdout: `web=${state}\n`,
349
+ stderr: ""
350
+ };
351
+ if (state === "unavailable") return {
352
+ code: 4,
353
+ stdout: "web=unavailable\n",
354
+ stderr: "dsh-pi-tui web: WEB_UNAVAILABLE: the Host could not reach a settled Web state\n"
355
+ };
356
+ return {
357
+ code: 5,
358
+ stdout: `web=${state}\n`,
359
+ stderr: `dsh-pi-tui web: WEB_OUTCOME_UNCONFIRMED: the Host did not confirm the requested Web state; run: dsh --profile ${shellQuote(profile.name)} web status\n`
360
+ };
361
+ }
362
+ /** The unreached-write outcome: the request may have been committed. */
363
+ function unknownWriteOutcome(profile) {
364
+ return new WebControlError("WEB_OUTCOME_UNCONFIRMED", `the Web write result is unknown; run: dsh --profile ${shellQuote(profile.name)} web status before retrying`);
365
+ }
366
+ /**
367
+ * Run ONE headless Web command for ONE official Profile. Every failure is
368
+ * mapped to a fixed code/exit; no raw Error message, Host response body,
369
+ * Cookie, authenticated URL or private path reaches stdout/stderr.
370
+ */
371
+ async function runLocalWebControl(intent, profile, deps = {}) {
372
+ try {
373
+ const platform = platformOf(deps);
374
+ if (platform !== "linux" && platform !== "darwin") throw new WebControlError("UNSUPPORTED_PLATFORM", "the web CLI is only supported on Linux and macOS");
375
+ const scope = inspectInstalledProfileScope({
376
+ dshHome: profile.home,
377
+ profileDir: profile.dir,
378
+ packageRoot: profile.packageRoot,
379
+ dshVersion: profile.dshVersion
380
+ });
381
+ const record = (deps.readRecord ?? readLocalRecord)(scope);
382
+ if (record === void 0) throw new WebControlError("HOST_NOT_RUNNING", notRunningReason(profile));
383
+ if ((deps.inspectProcess ?? inspectHostProcess)(record) === "dead") throw new WebControlError("HOST_NOT_RUNNING", notRunningReason(profile));
384
+ assertClientHostCompatible(record, scope);
385
+ const verified = await (deps.authenticate ?? authenticateLocalHost)(record, scope, deps.signal);
386
+ deps.signal?.throwIfAborted();
387
+ switch (intent.verb) {
388
+ case "status": {
389
+ const result = await callWebControl(verified, "status", deps);
390
+ if (result.status === 0) throw readRequestFailure(verified, scope, deps);
391
+ if (result.status === 401 || result.status === 403) throw new WebControlError("HOST_AUTH_FAILED", "the Host rejected the authenticated Web CLI request");
392
+ if (result.status === 404) throw new WebControlError("WEB_CLI_UNAVAILABLE", "this Host build does not support the web CLI; restart the Host from the current install");
393
+ if (result.status === 409) throw new WebControlError("HOST_IDENTITY_REFUSED", "the Host reply names a different instance");
394
+ if (result.status !== 200 || result.reply?.kind !== "state") throw new WebControlError("WEB_CLI_UNAVAILABLE", "the Host returned no readable Web status");
395
+ assertReplyBelongsToAuthenticatedHost(verified, result.reply, scope, deps);
396
+ return {
397
+ code: 0,
398
+ stdout: `web=${result.reply.state}\n`,
399
+ stderr: ""
400
+ };
401
+ }
402
+ case "enable":
403
+ case "disable": {
404
+ const result = await callWebControl(verified, intent.verb, deps);
405
+ if (result.status === 401 || result.status === 403) throw new WebControlError("HOST_AUTH_FAILED", "the Host rejected the authenticated Web CLI request");
406
+ if (result.status === 404) throw new WebControlError("WEB_CLI_UNAVAILABLE", "this Host build does not support the web CLI; restart the Host from the current install");
407
+ if (result.status !== 200 || result.reply?.kind !== "state") throw unknownWriteOutcome(profile);
408
+ try {
409
+ assertReplyBelongsToAuthenticatedHost(verified, result.reply, scope, deps);
410
+ } catch {
411
+ throw unknownWriteOutcome(profile);
412
+ }
413
+ return writeResult(intent.verb, result.reply.state, profile);
414
+ }
415
+ case "url":
416
+ case "open": {
417
+ const result = await callWebControl(verified, "url", deps);
418
+ if (result.status === 0) throw readRequestFailure(verified, scope, deps);
419
+ if (result.status === 401 || result.status === 403) throw new WebControlError("HOST_AUTH_FAILED", "the Host rejected the authenticated Web CLI request");
420
+ if (result.status === 404) throw new WebControlError("WEB_CLI_UNAVAILABLE", "this Host build does not support the web CLI; restart the Host from the current install");
421
+ if (result.reply?.kind === "error") {
422
+ if (result.reply.error === "WEB_DISABLED") throw new WebControlError("WEB_DISABLED", disabledReason(profile));
423
+ if (result.reply.error === "WEB_CHANGING") throw new WebControlError("WEB_CHANGING", "the Host is still changing its Web state; retry: dsh-pi-tui web status");
424
+ if (result.reply.error === "WEB_INSTANCE_MISMATCH") throw new WebControlError("HOST_IDENTITY_REFUSED", "the Host instance changed before the Web URL was read");
425
+ throw new WebControlError("WEB_CLI_UNAVAILABLE", "the Host could not produce the authenticated Web URL");
426
+ }
427
+ if (result.status === 409) throw new WebControlError("HOST_IDENTITY_REFUSED", "the Host reply names a different instance");
428
+ if (result.status !== 200 || result.reply?.kind !== "url") throw new WebControlError("WEB_CLI_UNAVAILABLE", "the Host returned no readable authenticated Web URL");
429
+ assertReplyBelongsToAuthenticatedHost(verified, result.reply, scope, deps);
430
+ const url = assertAuthenticatedWebUrl(result.reply.url, verified.record.origin);
431
+ if (intent.verb === "url") return {
432
+ code: 0,
433
+ stdout: `${url}\n`,
434
+ stderr: ""
435
+ };
436
+ await launchBrowser(url, deps);
437
+ return {
438
+ code: 0,
439
+ stdout: "browser=requested\n",
440
+ stderr: ""
441
+ };
442
+ }
443
+ }
444
+ } catch (error) {
445
+ const failure = toWebControlError(error);
446
+ return {
447
+ code: failure.exitCode,
448
+ stdout: "",
449
+ stderr: formatWebControlError(failure)
450
+ };
451
+ }
452
+ }
453
+ //#endregion
454
+ export { runLocalWebControl };