@aiwayds/dsh-opentui 0.21.0 → 0.22.0

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.
@@ -0,0 +1,1229 @@
1
+ #!/usr/bin/env node
2
+ // provision-inproc-profile.mjs — idempotent provisioning of the fixed
3
+ // `opentui-inproc` host profile (ADR-0009 decision 3; T3 of the in-process
4
+ // bridge plan).
5
+ //
6
+ // Invoked by the launcher ONLY when DSH_OPENTUI_INPROC=1
7
+ // (bin/dsh-opentui.mjs); the default `opentui` profile path is untouched.
8
+ // Seven local-FS steps (the first is the host-version gate), no pnpm/npm, no install scripts:
9
+ //
10
+ // [1/7] host — detect the running dsh version. OUTSIDE the supported
11
+ // window (>=0.2.2-rc.3 <0.3.0) => fail-fast with the three
12
+ // fail-fast elements: the host would otherwise skip the
13
+ // bridge bundle silently (it only records the conflict in
14
+ // `skippedBundles`) and bridge.hello would time out. INSIDE
15
+ // the window but not yet exempted => grant the profile-local
16
+ // exact-version exemption in compatibility.json. Never
17
+ // grants outside the window: --accept-risk is not a way to
18
+ // mask a genuine incompatibility.
19
+ // [2/7] manifest — write $DSH_HOME/profiles/opentui-inproc/package.json with
20
+ // dsh.profile.bundles = [@deepseek-ai/dsh-base,
21
+ // @aiwayds/dsh-opentui-bridge]. NO @deepseek-ai/* dependency
22
+ // is ever written: the host's installation-first bundle
23
+ // resolution supplies those bundles from the running dsh
24
+ // closure (wild-package shadowing is the historical
25
+ // incident this guard prevents).
26
+ // [3/7] symlink — create node_modules/@aiwayds/dsh-opentui-bridge as an
27
+ // ABSOLUTE symlink to THIS installation's dist/bridge
28
+ // (realpath). No link:/file: protocol, no copying.
29
+ // [4/7] verify — re-read the link and confirm it resolves to dist/bridge;
30
+ // refuse any @deepseek-ai copy in the profile.
31
+ // [5/7] identity — T5 guard: hash the RESOLVED bridge's index.js and compare
32
+ // with the build-time fingerprint shipped in THIS
33
+ // installation's dist/bridge/bundle-fingerprint.json, plus
34
+ // name / version. No realpath-prefix hard binding.
35
+ // [6/7] patch — ONLY when DSH_OPENTUI_INPROC=1: generate
36
+ // $DSH_HOME/profiles/opentui-inproc/cordis.patch.yml from
37
+ // the embedded inproc-only template (web-app compensation
38
+ // rows removed, profileRevision stamped). The template also
39
+ // registers the standalone sessionController shim plus the
40
+ // real @deepseek-ai/dsh-api-session-controller plugin — no
41
+ // dsh-web-app bundle is pulled in. Without the env this step
42
+ // is skipped entirely — old behavior unchanged.
43
+ // [7/7] shim — ONLY when DSH_OPENTUI_INPROC=1: generate the local shim
44
+ // package under the profile's node_modules (@aiwayds scope)
45
+ // that the patch row above resolves. Its @deepseek-ai/cordis
46
+ // import is resolved by the host against the profile scope,
47
+ // exactly like the bridge. revision + backup converge it.
48
+ //
49
+ // T4 — cross-instance mutual exclusion:
50
+ // The whole provisioning run is serialized by `.provision.lock` in the
51
+ // profile dir, created with O_EXCL ("wx"). A live holder makes late
52
+ // instances wait briefly (bounded retries) and then SKIP; a stale lock
53
+ // (holder pid gone, age over threshold, corrupt, or self-leftover) is
54
+ // taken over. The lock is released in `finally`, including on failure.
55
+ // Same-machine only: no cross-host / cross-user semantics.
56
+ //
57
+ // Idempotency: an existing symlink that resolves to the exact expected target
58
+ // is left untouched. An existing entry that points somewhere else is NOT
59
+ // overwritten: a conflict is reported (the identity guard below still runs
60
+ // and decides whether the resolved artifact is acceptable).
61
+ //
62
+ // T7 — repair mode (`--repair`, invoked by `dsh-opentui --repair-bridge`):
63
+ // In the normal path the conflict above is report-only. With --repair the
64
+ // SAME lock and the SAME pass are used, but a wrong symlink target (or a
65
+ // non-symlink entry) is replaced with the absolute link to this install's
66
+ // dist/bridge; a missing / wrong manifest is still converged as usual. The
67
+ // T5 identity guard runs afterwards either way — repair fixes the LINK,
68
+ // never the artifact CONTENT, so a fingerprint mismatch still fails.
69
+ //
70
+ // Hard guard: this script only ever touches the ONE profile named
71
+ // `opentui-inproc`. It never runs a package manager and never writes a
72
+ // dependency into the manifest.
73
+
74
+ import { createHash } from 'node:crypto'
75
+ import {
76
+ closeSync,
77
+ existsSync,
78
+ lstatSync,
79
+ mkdirSync,
80
+ openSync,
81
+ readFileSync,
82
+ readlinkSync,
83
+ realpathSync,
84
+ renameSync,
85
+ rmSync,
86
+ statSync,
87
+ symlinkSync,
88
+ unlinkSync,
89
+ writeFileSync,
90
+ writeSync,
91
+ } from 'node:fs'
92
+ import { homedir } from 'node:os'
93
+ import { dirname, join, resolve as resolvePath } from 'node:path'
94
+ import { fileURLToPath } from 'node:url'
95
+ // P0 fail-fast: ONE text source shared with the handshake path in
96
+ // src/client/seam-bootstrap.ts. Both ProvisionError (fingerprint) and
97
+ // BridgeBootstrapError (handshake) now carry the same three elements.
98
+ import {
99
+ BRIDGE_APPEND_PRESET_NOTICE,
100
+ BRIDGE_REPAIR_HINT,
101
+ } from './lib/bridge-failfast-text.mjs'
102
+ // Host-version gate. The host only records an incompatible profile bundle in
103
+ // `skippedBundles` (no stderr on this path), so the pre-boot check here is the
104
+ // point where a mismatch becomes an explicit, actionable failure.
105
+ import {
106
+ HOST_PEER_RANGE,
107
+ HOST_VERSION_ENV,
108
+ detectHostVersion,
109
+ ensureHostExemption,
110
+ isHostVersionSupported,
111
+ } from './lib/host-compat.mjs'
112
+
113
+ const PREFIX = 'dsh-opentui(inproc): '
114
+ const PROFILE = 'opentui-inproc'
115
+ const BRIDGE_NAME = '@aiwayds/dsh-opentui-bridge'
116
+ const BUNDLES = ['@deepseek-ai/dsh-base', BRIDGE_NAME]
117
+
118
+ // --- T4 lock tuning (same-machine only) -------------------------------------
119
+ const LOCK_NAME = '.provision.lock'
120
+ const LOCK_STALE_MS = 30_000 // a live holder older than 30s is treated as stale
121
+ const LOCK_RETRY_MS = 25 // backoff between attempts while a peer holds the lock
122
+ const LOCK_MAX_ATTEMPTS = 40 // <= ~1s of waiting before a peer is skipped
123
+
124
+ const pkgRoot = dirname(dirname(fileURLToPath(import.meta.url)))
125
+ const bridgeDirRaw = join(pkgRoot, 'dist', 'bridge')
126
+ const fingerprintPath = join(bridgeDirRaw, 'bundle-fingerprint.json')
127
+
128
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
129
+ const profileDir = join(dshHome, 'profiles', PROFILE)
130
+ const manifestPath = join(profileDir, 'package.json')
131
+ const linkPath = join(profileDir, 'node_modules', ...BRIDGE_NAME.split('/'))
132
+ const lockPath = join(profileDir, LOCK_NAME)
133
+
134
+ // --- Inproc patch ownership (gated by DSH_OPENTUI_INPROC=1) -----------------
135
+ // The launcher sets this on the opt-in startup path; --repair-bridge and direct
136
+ // invocation do not. Keeping the gate HERE makes those paths byte-for-byte
137
+ // identical to the pre-patch behavior.
138
+ const INPROC_MODE = process.env.DSH_OPENTUI_INPROC === '1'
139
+ const TOTAL_STEPS = INPROC_MODE ? 7 : 5
140
+ const PATCH_NAME = 'cordis.patch.yml'
141
+ const patchPath = join(profileDir, PATCH_NAME)
142
+ const PATCH_REVISION_MARKER = '# profileRevision: '
143
+ // Local shim package generated under the profile's node_modules. It lives in
144
+ // the @aiwayds scope (never @deepseek-ai — see the guard in step [4/7]) so the
145
+ // host resolves it from the profile scope; its own @deepseek-ai/cordis import
146
+ // is routed by the host's runtime interception to the same dsh closure that
147
+ // serves the bridge. The patch row uses this bare package name.
148
+ const SHIM_PACKAGE = '@aiwayds/dsh-opentui-session-shim'
149
+ const SHIM_DIR = join(profileDir, 'node_modules', ...SHIM_PACKAGE.split('/'))
150
+ const SHIM_INDEX_PATH = join(SHIM_DIR, 'index.mjs')
151
+ const SHIM_PKG_PATH = join(SHIM_DIR, 'package.json')
152
+ const SHIM_REVISION_MARKER = '// shimRevision: '
153
+ const PATCH_TEMPLATE = `# model route (managed by provision-opentui-profile.mjs — provider zai-coding-cn, key read by the host from ZAI_CODING_CN_API_KEY):
154
+ - id: llm-pi-ai
155
+ name: "@deepseek-ai/dsh-llm-pi-ai"
156
+ config:
157
+ providers:
158
+ zai-coding-cn:
159
+ apiKeyEnv: ZAI_CODING_CN_API_KEY
160
+ models:
161
+ - id: glm-4.5
162
+ name: glm-4.5
163
+ input:
164
+ - text
165
+ - id: glm-4.5-air
166
+ name: glm-4.5-air
167
+ input:
168
+ - text
169
+ - id: glm-4.6
170
+ name: glm-4.6
171
+ input:
172
+ - text
173
+ - id: glm-4.6v
174
+ - id: glm-4.7
175
+ name: glm-4.7
176
+ input:
177
+ - text
178
+ - id: glm-5
179
+ name: glm-5
180
+ input:
181
+ - text
182
+ - id: glm-5-turbo
183
+ name: glm-5-turbo
184
+ input:
185
+ - text
186
+ - id: glm-5.1
187
+ name: glm-5.1
188
+ input:
189
+ - text
190
+ - id: glm-5.2
191
+ name: GLM 5.2
192
+ input:
193
+ - text
194
+ - id: glm-5.3
195
+ name: GLM 5.3
196
+ input:
197
+ - text
198
+ - id: glm-5.3-flash
199
+ name: glm-5.3-flash
200
+ input:
201
+ - text
202
+ - id: glm-5.3-flashx
203
+ name: glm-5.3-flashx
204
+ input:
205
+ - text
206
+ - id: glm-5.3-flashx-legal
207
+ name: glm-5.3-flashx-legal
208
+ input:
209
+ - text
210
+ - id: glm-5.3-highspeed
211
+ xiaomi-token-plan-cn:
212
+ models:
213
+ - id: mimo-v2.5-asr
214
+ name: mimo-v2.5-asr
215
+ input:
216
+ - text
217
+ - id: mimo-v2.5-tts
218
+ name: mimo-v2.5-tts
219
+ input:
220
+ - text
221
+ - id: mimo-v2.5-tts-voiceclone
222
+ name: mimo-v2.5-tts-voiceclone
223
+ input:
224
+ - text
225
+ - id: mimo-v2.5-tts-voicedesign
226
+ name: mimo-v2.5-tts-voicedesign
227
+ input:
228
+ - text
229
+ - id: mimo-v2.6-flash
230
+ name: MiMo-V2.6-Flash
231
+ contextWindow: 1048576
232
+ input:
233
+ - text
234
+ - image
235
+ compat:
236
+ thinkingFormat: deepseek
237
+ supportsReasoningEffort: false
238
+ - id: mimo-v2.6-pro
239
+ name: MiMo-V2.6-Pro
240
+ contextWindow: 1048576
241
+ input:
242
+ - text
243
+ - image
244
+ compat:
245
+ thinkingFormat: deepseek
246
+ supportsReasoningEffort: false
247
+ opencode-go:
248
+ apiKeyEnv: OPENCODE_GO_API_KEY
249
+ models:
250
+ - id: beam-free
251
+ name: Beam Free
252
+ contextWindow: 1048576
253
+ input:
254
+ - text
255
+ - id: claude-haiku-5-5
256
+ name: Claude Haiku 5.5
257
+ contextWindow: 1000000
258
+ input:
259
+ - text
260
+ - image
261
+ - id: deepseek-v4-pro
262
+ name: DeepSeek V4 Pro
263
+ contextWindow: 1000000
264
+ input:
265
+ - text
266
+ reasoningEfforts:
267
+ high: high
268
+ max: max
269
+ compat:
270
+ thinkingFormat: deepseek
271
+ - id: deepseek-v4.1-flash
272
+ name: DeepSeek V4.1 Flash 1017
273
+ contextWindow: 1000000
274
+ input:
275
+ - text
276
+ - image
277
+ reasoningEfforts:
278
+ low: low
279
+ high: high
280
+ max: max
281
+ compat:
282
+ thinkingFormat: deepseek
283
+ - id: gemini-4-argon
284
+ name: Gemini 4 Argon
285
+ contextWindow: 1048576
286
+ input:
287
+ - text
288
+ - image
289
+ - id: glm-5.2
290
+ name: GLM-5.2
291
+ contextWindow: 1000000
292
+ input:
293
+ - text
294
+ - id: glm-5.3
295
+ name: GLM-5.3
296
+ contextWindow: 1000000
297
+ input:
298
+ - text
299
+ - id: glm-5.3-flash
300
+ name: GLM-5.3-Flash
301
+ contextWindow: 1000000
302
+ input:
303
+ - text
304
+ - image
305
+ - id: gpt-5.6-luna
306
+ name: GPT-5.6 Luna
307
+ contextWindow: 1050000
308
+ input:
309
+ - text
310
+ - image
311
+ - id: gpt-6-luna
312
+ name: GPT-6 Luna
313
+ contextWindow: 1050000
314
+ input:
315
+ - text
316
+ - image
317
+ - id: grok-4.7
318
+ name: Grok 4.7
319
+ contextWindow: 500000
320
+ input:
321
+ - text
322
+ - image
323
+ - id: hy3
324
+ name: Hy3
325
+ contextWindow: 256000
326
+ input:
327
+ - text
328
+ - id: hy4
329
+ name: Hy4
330
+ contextWindow: 1048576
331
+ input:
332
+ - text
333
+ - image
334
+ - id: hy4-preview
335
+ name: Hy4 preview
336
+ contextWindow: 1024000
337
+ input:
338
+ - text
339
+ - id: iceman-contributor-free
340
+ name: Iceman Contributor Free
341
+ contextWindow: 262144
342
+ input:
343
+ - text
344
+ - id: kimi-k2.7-code
345
+ name: Kimi K2.7 Code
346
+ contextWindow: 262144
347
+ input:
348
+ - text
349
+ - image
350
+ - id: kimi-k3
351
+ name: Kimi K3
352
+ contextWindow: 1048576
353
+ input:
354
+ - text
355
+ - image
356
+ - id: kimi-k3.1-pro
357
+ name: Kimi K3.1 Pro
358
+ contextWindow: 1048576
359
+ input:
360
+ - text
361
+ - image
362
+ - id: longcat-2.0
363
+ name: LongCat-2.0
364
+ contextWindow: 1000000
365
+ input:
366
+ - text
367
+ - id: longcat-2.5-free
368
+ name: LongCat 2.5 Free
369
+ contextWindow: 1000000
370
+ input:
371
+ - text
372
+ - image
373
+ - id: mimo-v2.5
374
+ name: MiMo V2.5
375
+ contextWindow: 1000000
376
+ input:
377
+ - text
378
+ - image
379
+ - id: mimo-v2.5-pro
380
+ name: MiMo V2.5 Pro
381
+ contextWindow: 1048576
382
+ input:
383
+ - text
384
+ - id: mimo-v2.6-flash
385
+ name: MiMo-V2.6-Flash
386
+ contextWindow: 1048576
387
+ input:
388
+ - text
389
+ - image
390
+ - id: mimo-v2.6-pro
391
+ name: MiMo-V2.6-Pro
392
+ contextWindow: 1048576
393
+ input:
394
+ - text
395
+ - image
396
+ - id: minimax-m3
397
+ name: MiniMax-M3
398
+ contextWindow: 1000000
399
+ input:
400
+ - text
401
+ - image
402
+ - id: minimax-m3.1-flash
403
+ name: MiniMax M3.1 Flash
404
+ contextWindow: 1000000
405
+ input:
406
+ - text
407
+ - image
408
+ - id: muse-spark-1.2-contributor
409
+ name: Muse Spark 1.2 Contributor
410
+ contextWindow: 1048576
411
+ input:
412
+ - text
413
+ - image
414
+ - id: muse-spark-1.3-contributor
415
+ name: Muse Spark 1.3 Contributor
416
+ contextWindow: 1048576
417
+ input:
418
+ - text
419
+ - image
420
+ - id: qwen3.7-plus
421
+ name: Qwen3.7 Plus
422
+ contextWindow: 1000000
423
+ input:
424
+ - text
425
+ - image
426
+ - id: qwen3.8-flash
427
+ name: Qwen3.8 Flash
428
+ contextWindow: 1000000
429
+ input:
430
+ - text
431
+ - image
432
+ - id: qwen3.8-max
433
+ name: Qwen3.8 Max
434
+ contextWindow: 1000000
435
+ input:
436
+ - text
437
+ - image
438
+ - id: step-5-preview
439
+ name: Step 5 Preview
440
+ contextWindow: 1000000
441
+ input:
442
+ - text
443
+ - image
444
+ # Toolface restore (toolfix 2026-11-08), mirroring the tui profile's ambient
445
+ # tool rows. The @deepseek-ai/dsh-web-app bundle disables the dsh-base ambient
446
+ # tool rows (tool-bash/tool-todo/…) and recomposes them per agent preset, but
447
+ # this profile's effective default preset resolves to \`native\` = ambient
448
+ # composition (registry 0.19.0 agent-preset-registry default), which left the
449
+ # main session without todo and subagent sessions without bash. These rows are
450
+ # the last patch layer, so they win per id. Forms copied verbatim from the
451
+ # dsh-base/tui ambient rows.
452
+ - id: tool-bash
453
+ name: '@deepseek-ai/dsh-tool-bash'
454
+ disabled: !!js process.platform === 'win32'
455
+ - id: tool-todo
456
+ name: '@deepseek-ai/dsh-tool-todo'
457
+ # disabled: false must be stated explicitly — id-targeted patch rows merge
458
+ # per key (config replaces wholesale), so an omitted \`disabled\` inherits the
459
+ # web-app's \`disabled: true\` on the ambient row.
460
+ disabled: false
461
+ config:
462
+ allowParallelInProgress: true
463
+ # The subagent face also composes from the ambient rows, and the web-app
464
+ # disabled the file tools + instructions service the tui ambient face has on:
465
+ # without these, spawned agents get bash but no read/write/search surface.
466
+ # Forms copied verbatim from the dsh-base rows (tui ambient state).
467
+ - id: tool-fs
468
+ name: '@deepseek-ai/dsh-tool-fs'
469
+ disabled: false
470
+ config:
471
+ applyPatch: false
472
+ - id: tool-fs-search
473
+ name: '@deepseek-ai/dsh-tool-fs-search'
474
+ disabled: false
475
+ config:
476
+ sampleOverCapGlobResults: false
477
+ - id: agent-instructions
478
+ name: '@deepseek-ai/dsh-agent-instructions'
479
+ disabled: false
480
+ config:
481
+ maxBytes: 65536
482
+ - id: tool-result-pruner
483
+ name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
484
+ disabled: false
485
+ config:
486
+ thresholdChars: 8192
487
+ headChars: 4096
488
+ tailChars: 1024
489
+ # tui mounts ask_user ambient via its dsh-tui-pi bundle; this profile has no
490
+ # equivalent bundle (its @aiwayds/dsh-opentui bundle is skipped by the host),
491
+ # so the row is inserted here instead of overridden.
492
+ - insert:
493
+ - id: tool-ask-user
494
+ name: '@deepseek-ai/dsh-tool-ask-user'
495
+ # Web search restore (webtool 2026-11-10). The dsh-web-app bundle disables the
496
+ # ambient tool-web row and the effective default preset is \`native\` (ambient
497
+ # composition), so the main session had no web_search/web_fetch tool. This row
498
+ # is the last patch layer and wins per id. Form copied verbatim from dsh-base.
499
+ - id: tool-web
500
+ name: '@deepseek-ai/dsh-tool-web'
501
+ disabled: false
502
+ config:
503
+ fetch: true
504
+ searchTimeoutMs: 60000
505
+ - id: permission
506
+ name: "@deepseek-ai/dsh-permission-presets"
507
+ config:
508
+ presets:
509
+ read-only:
510
+ sandbox: read-only
511
+ approval: ask
512
+ workspace-write:
513
+ sandbox: workspace-write
514
+ approval: ask
515
+ danger-full-access:
516
+ sandbox: danger-full-access
517
+ approval: never
518
+ # T9 (ADR-0011): default to the confined + ask preset. Escape hatch: set
519
+ # DSH_OPENTUI_APPROVAL_GATE=off to restore the pre-T9 permissive default.
520
+ defaultPreset: !!js process.env.DSH_OPENTUI_APPROVAL_GATE === 'off' && 'danger-full-access' || 'workspace-write'
521
+
522
+ # Pre-execute approval gate (ADR-0011 T9). Armed BY DEFAULT for the write tools
523
+ # the host actually registers (verified in dsh-tool-bash/src/index.ts:393 and
524
+ # dsh-tool-fs/src/{write,edit,apply-patch}.ts): it returns {kind:'ask'} for them,
525
+ # driving approval.request -> bridge answerer -> ask.request -> TUI approval card.
526
+ # Read-only tools (read/search/glob/...) are untouched and pass via next().
527
+ # Escape hatch: DSH_OPENTUI_APPROVAL_GATE=off sets enabled=false (and reverts the
528
+ # preset above), restoring the old frictionless behavior. Never default to off.
529
+ # See tickets/2026-11-18-approval-trigger-mechanism.md.
530
+ - insert:
531
+ - id: dsh-opentui-approval-gate
532
+ name: '@aiwayds/dsh-opentui-bridge/approval-gate'
533
+ config:
534
+ enabled: !!js process.env.DSH_OPENTUI_APPROVAL_GATE !== 'off'
535
+ reason: 'Write operations require human approval'
536
+ tools:
537
+ bash: ask
538
+ write: ask
539
+ edit: ask
540
+ apply_patch: ask
541
+
542
+ # MCP (managed by provision-opentui-profile.mjs — the adapter's mcp_list/mcp_call need a client row; context7 needs no key and a failed/offline connection is non-fatal):
543
+ - insert:
544
+ - id: mcp-context7
545
+ name: '@deepseek-ai/dsh-mcp-client'
546
+ config:
547
+ serverName: context7
548
+ transport: streamable-http
549
+ url: https://mcp.context7.com/mcp
550
+ - id: agent-default-model
551
+ name: "@deepseek-ai/dsh-agent-default-model"
552
+ config:
553
+ provider: opencode-go
554
+ model: deepseek-v4.1-flash
555
+ reasoningEffort: high
556
+
557
+ - id: subagent
558
+ name: "@deepseek-ai/dsh-subagent"
559
+ config:
560
+ maxActiveSubagents: 3
561
+
562
+ # Standalone sessionController support (no dsh-web-app bundle). The real
563
+ # controller needs 13 injects; 11 come from dsh-base, and the two web-only ones
564
+ # (fileUploads, workspaceRegistry) are satisfied by the local shim package
565
+ # generated in step [7/7]. No connection shim: dsh-api-gateway's optional
566
+ # ctx.inject(['connection']) calls connection.rpc.intercept(...), which a no-op
567
+ # stub cannot honor; leaving connection absent only keeps the controller's
568
+ # SessionMediaReferences sub-plugin pending, which does not block list().
569
+ - insert:
570
+ - id: dsh-opentui-session-shim
571
+ name: '@aiwayds/dsh-opentui-session-shim'
572
+ - id: session-controller
573
+ name: '@deepseek-ai/dsh-api-session-controller'
574
+ `
575
+ const PATCH_REVISION = createHash('sha256').update(PATCH_TEMPLATE).digest('hex').slice(0, 16)
576
+ const PATCH_HEADER = `# dsh-opentui inproc profile patch — GENERATED by provision-inproc-profile.mjs; edit the script, not this file.\n${PATCH_REVISION_MARKER}${PATCH_REVISION}\n`
577
+ const PATCH_CONTENT = `${PATCH_HEADER}${PATCH_TEMPLATE}`
578
+ // MD5 of the web/opentui template this profile used to copy verbatim (see
579
+ // tickets/2026-11-18-inproc-profile-inventory.md §0). A local file matching it
580
+ // is an unowned legacy copy and is replaced without a backup.
581
+ const KNOWN_PATCH_MD5 = new Set(['54b66bf37fbbb93a6f9dd204a24473f7'])
582
+
583
+ // --- Standalone sessionController shim template -----------------------------
584
+ // Generated into the profile's node_modules (step [7/7]) so its runtime imports
585
+ // are resolved from the profile scope by the host, exactly like the bridge.
586
+ // The real controller imports fileUploads / workspaceRegistry as TYPES ONLY;
587
+ // only the narrow methods below are ever called, so no dsh-web-app closure is
588
+ // needed. No `connection` shim on purpose (see the patch template comment).
589
+ const SHIM_INDEX_TEMPLATE = `// Standalone sessionController support for the opentui-inproc profile.
590
+ // GENERATED by provision-inproc-profile.mjs; edit the script, not this file.
591
+ import { Service } from '@deepseek-ai/cordis'
592
+
593
+ class FileUploadsShim extends Service {
594
+ constructor(ctx) {
595
+ super(ctx, 'fileUploads')
596
+ }
597
+
598
+ // SessionController[Service.init] registers its Agent resolver via
599
+ // ctx.effect, which uses the return value as a disposer. No uploads happen
600
+ // in the inproc profile, so both resolver and disposer are no-ops.
601
+ registerAgentResolver(_resolve) {
602
+ return () => {}
603
+ }
604
+
605
+ // Unknown/unstaged receipt: the real service returns undefined for an id it
606
+ // never staged. Returning undefined is the faithful value, not a fabricated
607
+ // empty upload that could be mistaken for a real attachment.
608
+ resolve(_agent, _receiptId) {
609
+ return undefined
610
+ }
611
+
612
+ // Commands uses \`using binding = ...\` then commit(). A no-op binding with
613
+ // both commit() and Symbol.dispose keeps the prompt flow from throwing if a
614
+ // non-list RPC ever reaches it (the inproc bridge only exposes session.list).
615
+ bindPrompt(_agent, _receiptIds, _requestId) {
616
+ return {
617
+ commit() {},
618
+ [Symbol.dispose]() {},
619
+ }
620
+ }
621
+
622
+ retirePrompt(_agent, _requestId) {}
623
+ }
624
+
625
+ class WorkspaceRegistryShim extends Service {
626
+ constructor(ctx) {
627
+ super(ctx, 'workspaceRegistry')
628
+ }
629
+
630
+ // ArchivedSessionGate reads this at init. An empty array means no session is
631
+ // archived, so list() needs no archive filtering.
632
+ get archivedSessionIds() {
633
+ return []
634
+ }
635
+
636
+ // session.create / fork RPCs (not exposed by the inproc bridge) would reach
637
+ // these; empty / undefined is the honest "no workspaces exist" answer.
638
+ get(_id) {
639
+ return undefined
640
+ }
641
+
642
+ list() {
643
+ return []
644
+ }
645
+ }
646
+
647
+ export function apply(ctx) {
648
+ ctx.plugin(FileUploadsShim)
649
+ ctx.plugin(WorkspaceRegistryShim)
650
+ }
651
+ `
652
+ const SHIM_REVISION = createHash('sha256').update(SHIM_INDEX_TEMPLATE).digest('hex').slice(0, 16)
653
+ const SHIM_INDEX_CONTENT = `${SHIM_REVISION_MARKER}${SHIM_REVISION}\n${SHIM_INDEX_TEMPLATE}`
654
+ const SHIM_PKG_CONTENT = `${JSON.stringify({
655
+ name: SHIM_PACKAGE,
656
+ version: '0.1.0',
657
+ type: 'module',
658
+ main: './index.mjs',
659
+ private: true,
660
+ }, null, 2)}\n`
661
+
662
+ const say = (step, label, value = '') => console.log(`${PREFIX}[${step}/${TOTAL_STEPS}] ${label}${value ? ` — ${value}` : ''}`)
663
+ const warn = (message) => console.error(`${PREFIX}WARN ${message}`)
664
+ const note = (message) => console.log(`${PREFIX}${message}`)
665
+
666
+ class ProvisionError extends Error {
667
+ constructor(message, detail = '') {
668
+ super(message)
669
+ this.detail = detail
670
+ }
671
+ }
672
+
673
+ // Throw instead of process.exit so a `finally` block can always release the
674
+ // lock. The top-level handler sets a non-zero exit code after cleanup.
675
+ //
676
+ // P0 fail-fast: EVERY failure is self-contained with all three elements.
677
+ // Element 1 (diagnosis, incl. the identity guard's expected/actual lines) is
678
+ // the caller's `message`/`detail`; elements 2 + 3 now come from the ONE shared
679
+ // source so the fingerprint path can never again omit the mode notice that
680
+ // the handshake path alone used to print.
681
+ function fail(message, detail = '') {
682
+ const fullDetail = [detail, BRIDGE_REPAIR_HINT, BRIDGE_APPEND_PRESET_NOTICE]
683
+ .filter(Boolean)
684
+ .join('\n')
685
+ throw new ProvisionError(message, fullDetail)
686
+ }
687
+
688
+ // Synchronous sleep: the whole script is synchronous, so a blocking wait is
689
+ // appropriate here. Atomics.wait is permitted on the Node.js main thread.
690
+ function sleepSync(ms) {
691
+ const buf = new Int32Array(new SharedArrayBuffer(4))
692
+ Atomics.wait(buf, 0, 0, ms)
693
+ }
694
+
695
+ // --- T4: lock helpers -------------------------------------------------------
696
+ function readJsonObject(path) {
697
+ try {
698
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
699
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined
700
+ } catch {
701
+ return undefined
702
+ }
703
+ }
704
+
705
+ function readLock() {
706
+ const raw = readJsonObject(lockPath)
707
+ if (!raw || !Number.isInteger(raw.pid) || !Number.isFinite(raw.ts)) return undefined
708
+ return raw
709
+ }
710
+
711
+ /** process.kill(pid, 0) probes existence without signalling. EPERM means the
712
+ * process exists but belongs to another user — treat it as alive (no
713
+ * cross-user takeover semantics by design). */
714
+ function pidAlive(pid) {
715
+ if (!Number.isInteger(pid) || pid <= 0) return false
716
+ try {
717
+ process.kill(pid, 0)
718
+ return true
719
+ } catch (error) {
720
+ return error?.code === 'EPERM'
721
+ }
722
+ }
723
+
724
+ function staleReason(lock) {
725
+ if (lock === undefined) return 'lock file is unreadable or corrupt'
726
+ if (lock.pid === process.pid) return `held by self (pid ${lock.pid})`
727
+ if (!pidAlive(lock.pid)) return `holder pid ${lock.pid} no longer exists`
728
+ return `holder pid ${lock.pid} alive but lock age ${Date.now() - lock.ts}ms > ${LOCK_STALE_MS}ms`
729
+ }
730
+
731
+ function isStale(lock) {
732
+ if (lock === undefined) return true
733
+ if (lock.pid === process.pid) return true
734
+ if (!pidAlive(lock.pid)) return true
735
+ return Date.now() - lock.ts > LOCK_STALE_MS
736
+ }
737
+
738
+ /** Exclusive-create the lock. Returns the owned token, or undefined when a
739
+ * live peer kept it through all retries (caller then SKIPs). Stale locks are
740
+ * removed and re-contended. Ownership is re-read after create so a concurrent
741
+ * stale-takeover cannot make two processes both believe they hold it. */
742
+ function acquireLock() {
743
+ for (let attempt = 1; attempt <= LOCK_MAX_ATTEMPTS; attempt++) {
744
+ const token = { pid: process.pid, ts: Date.now() }
745
+ let created = false
746
+ try {
747
+ const fd = openSync(lockPath, 'wx', 0o600)
748
+ try {
749
+ writeSync(fd, JSON.stringify(token))
750
+ } finally {
751
+ closeSync(fd)
752
+ }
753
+ created = true
754
+ } catch (error) {
755
+ if (error?.code !== 'EEXIST') throw error
756
+ }
757
+
758
+ if (created) {
759
+ const held = readLock()
760
+ if (held && held.pid === token.pid && held.ts === token.ts) {
761
+ if (attempt > 1) note(`acquired provisioning lock on attempt ${attempt}`)
762
+ return token
763
+ }
764
+ // Our create was immediately replaced by another process — do NOT
765
+ // unlink (the lock now belongs to them); just retry.
766
+ sleepSync(LOCK_RETRY_MS)
767
+ continue
768
+ }
769
+
770
+ // EEXIST: inspect the holder.
771
+ const lock = readLock()
772
+ if (isStale(lock)) {
773
+ note(`stale provisioning lock (${staleReason(lock)}); taking over`)
774
+ try {
775
+ unlinkSync(lockPath)
776
+ } catch (error) {
777
+ if (error?.code !== 'ENOENT') throw error
778
+ }
779
+ continue
780
+ }
781
+ if (attempt === 1 || attempt % 5 === 0) {
782
+ note(`waiting for provisioning lock (holder pid ${lock.pid}, age ${Date.now() - lock.ts}ms) — attempt ${attempt}/${LOCK_MAX_ATTEMPTS}`)
783
+ }
784
+ sleepSync(LOCK_RETRY_MS)
785
+ }
786
+ return undefined
787
+ }
788
+
789
+ /** Only unlink a lock that is still ours, so a peer that took over after our
790
+ * stale threshold never loses its own lock to our cleanup. */
791
+ function releaseLock(token) {
792
+ if (!token) return
793
+ try {
794
+ const held = readLock()
795
+ if (held && held.pid === token.pid && held.ts === token.ts) unlinkSync(lockPath)
796
+ } catch {
797
+ /* best effort cleanup: never mask the primary provisioning result */
798
+ }
799
+ }
800
+
801
+ // --- Provisioning helpers ---------------------------------------------------
802
+ function readManifest() {
803
+ return readJsonObject(manifestPath)
804
+ }
805
+
806
+ const desiredManifest = (existing) => ({
807
+ ...existing,
808
+ dsh: {
809
+ ...(existing?.dsh ?? {}),
810
+ profile: {
811
+ ...(existing?.dsh?.profile ?? {}),
812
+ bundles: [...BUNDLES],
813
+ },
814
+ },
815
+ })
816
+
817
+ function linkState(path) {
818
+ let lst
819
+ try {
820
+ lst = lstatSync(path)
821
+ } catch (error) {
822
+ if (error?.code === 'ENOENT') return { kind: 'absent' }
823
+ throw error
824
+ }
825
+ if (!lst.isSymbolicLink()) return { kind: 'not-symlink' }
826
+ const raw = readlinkSync(path)
827
+ // Resolve a relative target against the link's own directory so comparison
828
+ // is meaningful; a realpath (when resolvable) also collapses link chains.
829
+ const abs = resolvePath(dirname(path), raw)
830
+ let resolved = abs
831
+ try {
832
+ resolved = realpathSync(path)
833
+ } catch {
834
+ /* dangling link — fall back to the lexical absolute target */
835
+ }
836
+ return { kind: 'symlink', raw, abs, resolved }
837
+ }
838
+
839
+ /** Remove whatever occupies `path` (symlink, file or directory) so the correct
840
+ * symlink can be created in its place. Repair mode only; ENOENT is a no-op. */
841
+ function removePath(path) {
842
+ let st
843
+ try {
844
+ st = lstatSync(path)
845
+ } catch (error) {
846
+ if (error?.code === 'ENOENT') return
847
+ throw error
848
+ }
849
+ if (st.isDirectory()) rmSync(path, { recursive: true, force: true })
850
+ else unlinkSync(path)
851
+ }
852
+
853
+ // --- T5: bridge identity guard ---------------------------------------------
854
+ function sha256File(path) {
855
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
856
+ }
857
+
858
+ /** Validate the RESOLVED bridge against the build-time fingerprint shipped in
859
+ * THIS installation. The fingerprint is the authority (not the bridge's own
860
+ * package.json, which would be self-attestation), and there is deliberately
861
+ * NO realpath-prefix check: a repointed link is accepted iff name, version
862
+ * and index.js hash all match — a 0.23.0 split-package install must work. */
863
+ function verifyBridgeIdentity() {
864
+ const fp = readJsonObject(fingerprintPath)
865
+ if (
866
+ !fp ||
867
+ typeof fp.name !== 'string' ||
868
+ typeof fp.version !== 'string' ||
869
+ typeof fp.sha256 !== 'string'
870
+ ) {
871
+ fail(
872
+ 'build-time bridge fingerprint is missing or malformed',
873
+ `Expected ${fingerprintPath} with string fields name/version/sha256. Rebuild with: bun scripts/build-bridge.mjs`,
874
+ )
875
+ }
876
+
877
+ let resolved
878
+ try {
879
+ resolved = realpathSync(linkPath)
880
+ } catch (error) {
881
+ fail(
882
+ `bridge symlink cannot be resolved: ${linkPath}`,
883
+ `${error?.message ?? error}`,
884
+ )
885
+ }
886
+
887
+ const resolvedPkg = readJsonObject(join(resolved, 'package.json'))
888
+ const actualName = resolvedPkg?.name
889
+ const actualVersion = resolvedPkg?.version
890
+ let actualHash
891
+ try {
892
+ actualHash = sha256File(join(resolved, 'index.js'))
893
+ } catch (error) {
894
+ actualHash = `<unreadable: ${error?.code ?? error?.message ?? error}>`
895
+ }
896
+
897
+ const mismatches = []
898
+ const add = (field, expected, actual) => mismatches.push({ field, expected, actual: String(actual) })
899
+ if (actualName !== fp.name) add('name', fp.name, actualName)
900
+ if (actualVersion !== fp.version) add('version', fp.version, actualVersion)
901
+ if (actualHash !== fp.sha256) add('sha256(index.js)', fp.sha256, actualHash)
902
+
903
+ if (mismatches.length > 0) {
904
+ const fields = mismatches.map((m) => m.field).join(', ')
905
+ const detail = mismatches.map((m) => ` ${m.field}: expected "${m.expected}", actual "${m.actual}"`).join('\n')
906
+ fail(
907
+ `bridge identity check failed — ${fields} mismatch`,
908
+ `Resolved bridge: ${resolved}\n${detail}`,
909
+ )
910
+ }
911
+
912
+ say(5, 'identity', `name=${fp.name} version=${fp.version} sha256=${fp.sha256.slice(0, 12)}…`)
913
+ note(`bridge identity OK — ${resolved}`)
914
+ }
915
+
916
+ // --- Host-version gate ------------------------------------------------------
917
+ /** Fail loud on an unsupported host; grant the exact exemption when in-window.
918
+ * Diagnosis carries expected/actual; fail() appends repair + no-append. The
919
+ * check runs before any profile mutation so a bad host never leaves a
920
+ * half-provisioned profile behind. */
921
+ function verifyHostCompatibility(bridgeDir) {
922
+ let hostVersion
923
+ try {
924
+ hostVersion = detectHostVersion()
925
+ } catch (error) {
926
+ fail(
927
+ 'cannot verify the dsh host version before loading the bridge',
928
+ `${error instanceof Error ? error.message : String(error)}\nDetected with \`dsh --version\` (override: ${HOST_VERSION_ENV}=<exact version>).`,
929
+ )
930
+ }
931
+
932
+ if (!isHostVersionSupported(hostVersion)) {
933
+ fail(
934
+ `dsh host version is outside the bridge support window — expected ${HOST_PEER_RANGE}, actual ${hostVersion}`,
935
+ `The host would skip ${BRIDGE_NAME} without a usable error and bridge.hello would time out (BRIDGE_TIMEOUT). `
936
+ + `Install a dsh host in ${HOST_PEER_RANGE}, or upgrade dsh-opentui. `
937
+ + `Detection override: ${HOST_VERSION_ENV}=${process.env[HOST_VERSION_ENV] ?? '(unset)'}.`,
938
+ )
939
+ }
940
+
941
+ const bridgePkg = readJsonObject(join(bridgeDir, 'package.json'))
942
+ const packageName = bridgePkg?.name
943
+ const packageVersion = bridgePkg?.version
944
+ if (typeof packageName !== 'string' || typeof packageVersion !== 'string') {
945
+ fail(
946
+ 'bridge manifest has no name/version for the host-version exemption',
947
+ `${join(bridgeDir, 'package.json')} must declare string name and version.`,
948
+ )
949
+ }
950
+
951
+ try {
952
+ const { changed, key } = ensureHostExemption({ profileDir, packageName, packageVersion, hostVersion })
953
+ say(1, 'host', changed
954
+ ? `granted exact-version exemption ${key} for dsh ${hostVersion}`
955
+ : `supported host ${hostVersion}; exemption ${key} already present`)
956
+ } catch (error) {
957
+ fail(
958
+ `could not grant the host-version exemption for ${BRIDGE_NAME} on dsh ${hostVersion}`,
959
+ error instanceof Error ? error.message : String(error),
960
+ )
961
+ }
962
+ }
963
+
964
+ // --- Inproc cordis.patch.yml ownership ------------------------------------
965
+ /** Read the profileRevision stamped by this script, if present. */
966
+ function readPatchRevision(content) {
967
+ const match = typeof content === 'string' ? content.match(/^# profileRevision: ([0-9a-f]+)$/m) : null
968
+ return match ? match[1] : undefined
969
+ }
970
+
971
+ /** Converge the profile patch to the embedded inproc template.
972
+ * - exact current content (revision matches) -> no-op (idempotent, no write)
973
+ * - known web/opentui template copy -> replace silently (legacy template)
974
+ * - anything else, incl. a hand-edited output -> timestamped backup + WARN
975
+ *
976
+ * Marker presence alone is NOT proof of ownership: a user can edit a generated
977
+ * file while leaving the marker intact. Only a byte-for-byte match with the
978
+ * current generated content counts as "this script's own output". */
979
+ function provisionPatch() {
980
+ let current
981
+ try {
982
+ current = readFileSync(patchPath, 'utf8')
983
+ } catch (error) {
984
+ if (error?.code !== 'ENOENT') throw error
985
+ current = undefined
986
+ }
987
+
988
+ const localRevision = readPatchRevision(current)
989
+ if (current === PATCH_CONTENT && localRevision === PATCH_REVISION) {
990
+ say(6, 'patch', 'already current, skipping')
991
+ return
992
+ }
993
+
994
+ if (current !== undefined && current.length > 0) {
995
+ const md5 = createHash('md5').update(current).digest('hex')
996
+ if (!KNOWN_PATCH_MD5.has(md5)) {
997
+ const backupPath = `${patchPath}.bak-${Date.now()}`
998
+ renameSync(patchPath, backupPath)
999
+ warn(`cordis.patch.yml was modified outside provisioning (local revision ${localRevision ?? 'absent'}, md5 ${md5} matches neither a known web/opentui template nor the current generated profileRevision ${PATCH_REVISION}); backed up to ${backupPath}`)
1000
+ }
1001
+ }
1002
+
1003
+ // Atomic write: temp file in the same dir, then rename.
1004
+ const tmpPath = `${patchPath}.tmp-${process.pid}-${Date.now()}`
1005
+ writeFileSync(tmpPath, PATCH_CONTENT)
1006
+ renameSync(tmpPath, patchPath)
1007
+ say(6, 'patch', `wrote ${patchPath} (profileRevision ${PATCH_REVISION})`)
1008
+ }
1009
+
1010
+ // --- Standalone sessionController shim ownership ---------------------------
1011
+ /** Read the shimRevision stamped by this script, if present. */
1012
+ function readShimRevision(content) {
1013
+ const match = typeof content === 'string' ? content.match(/^\/\/ shimRevision: ([0-9a-f]+)$/m) : null
1014
+ return match ? match[1] : undefined
1015
+ }
1016
+
1017
+ /** Converge one generated shim file with the same revision + backup policy as
1018
+ * the patch. Only a byte-for-byte match with the current generated content
1019
+ * counts as this script's own output; any other content is backed up with a
1020
+ * WARN before the authoritative bytes are written atomically.
1021
+ * @returns true when a file was written. */
1022
+ function convergeShimFile(path, content, label, expectedRevision) {
1023
+ let current
1024
+ try {
1025
+ current = readFileSync(path, 'utf8')
1026
+ } catch (error) {
1027
+ if (error?.code !== 'ENOENT') throw error
1028
+ current = undefined
1029
+ }
1030
+
1031
+ const localRevision = expectedRevision === undefined ? undefined : readShimRevision(current)
1032
+ if (current === content && localRevision === expectedRevision) return false
1033
+
1034
+ if (current !== undefined && current.length > 0) {
1035
+ const backupPath = `${path}.bak-${Date.now()}`
1036
+ renameSync(path, backupPath)
1037
+ warn(`${label} content differs from the generated form (shimRevision local ${localRevision ?? 'absent'}, expected ${expectedRevision ?? 'n/a'}); backed up to ${backupPath}`)
1038
+ }
1039
+
1040
+ mkdirSync(dirname(path), { recursive: true })
1041
+ const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`
1042
+ writeFileSync(tmpPath, content)
1043
+ renameSync(tmpPath, path)
1044
+ return true
1045
+ }
1046
+
1047
+ /** Generate the local shim package the patch's session-controller row resolves.
1048
+ * Mirrors the patch's convergence policy: exact -> no-op, else backup + WARN
1049
+ * + atomic write. index.mjs carries a shimRevision marker; package.json is a
1050
+ * fixed manifest converged by exact content. */
1051
+ function provisionShim() {
1052
+ const indexChanged = convergeShimFile(SHIM_INDEX_PATH, SHIM_INDEX_CONTENT, 'session controller shim index.mjs', SHIM_REVISION)
1053
+ const pkgChanged = convergeShimFile(SHIM_PKG_PATH, SHIM_PKG_CONTENT, 'session controller shim package.json', undefined)
1054
+ if (!indexChanged && !pkgChanged) {
1055
+ say(7, 'shim', 'already current, skipping')
1056
+ return
1057
+ }
1058
+ say(7, 'shim', `wrote ${SHIM_DIR} (shimRevision ${SHIM_REVISION})`)
1059
+ }
1060
+
1061
+ // --- The provision pass itself (runs under the lock) ------------------------
1062
+ function runProvision({ repair = false } = {}) {
1063
+ if (repair) note('repair mode — a wrong bridge symlink will be rebuilt (content is never repaired)')
1064
+ // Prerequisites (read-only) are checked before any mutation.
1065
+ if (!existsSync(bridgeDirRaw) || !statSync(bridgeDirRaw).isDirectory()) {
1066
+ fail(
1067
+ `bridge artifact directory not found: ${bridgeDirRaw}`,
1068
+ 'Rebuild the bridge (bun scripts/build-bridge.mjs) or reinstall @aiwayds/dsh-opentui so dist/bridge ships with the package.',
1069
+ )
1070
+ }
1071
+ for (const required of ['package.json', 'index.js', 'bundle-fingerprint.json']) {
1072
+ if (!existsSync(join(bridgeDirRaw, required))) {
1073
+ fail(
1074
+ `bridge artifact is incomplete: ${join(bridgeDirRaw, required)} not found`,
1075
+ 'Expected package.json, index.js and bundle-fingerprint.json in dist/bridge; rebuild with bun scripts/build-bridge.mjs.',
1076
+ )
1077
+ }
1078
+ }
1079
+ // The symlink must carry a REAL resolved (absolute) path, never a relative
1080
+ // or symlinked-in path that could drift with cwd or a moved install.
1081
+ const bridgeDir = realpathSync(bridgeDirRaw)
1082
+
1083
+ // [1/7] Host compatibility: fail loud when the running dsh is outside the
1084
+ // supported window (the host would otherwise skip the bridge silently), and
1085
+ // grant the exact-version exemption when it is in-window but not exempted.
1086
+ verifyHostCompatibility(bridgeDir)
1087
+
1088
+ // [2/7] Manifest: write / converge the profile manifest. Only
1089
+ // dsh.profile.bundles is managed; every other field is preserved.
1090
+ {
1091
+ const existing = existsSync(manifestPath) ? readManifest() : undefined
1092
+ if (existsSync(manifestPath) && existing === undefined) {
1093
+ fail(`${manifestPath} is not a valid JSON object manifest — leaving it untouched`)
1094
+ }
1095
+ const desired = desiredManifest(existing ?? { name: `dsh-profile-${PROFILE}`, private: true })
1096
+ if (existing !== undefined && JSON.stringify(existing) === JSON.stringify(desired)) {
1097
+ say(2, 'manifest', 'already correct, skipping')
1098
+ } else {
1099
+ mkdirSync(profileDir, { recursive: true })
1100
+ if (existsSync(manifestPath)) {
1101
+ const backupPath = `${manifestPath}.bak-${Date.now()}`
1102
+ renameSync(manifestPath, backupPath)
1103
+ console.log(`${PREFIX}backed up ${manifestPath} to ${backupPath}`)
1104
+ }
1105
+ // Atomic write: a temp file in the same dir, then rename, so a
1106
+ // concurrent reader never observes a partially written package.json.
1107
+ const tmpPath = `${manifestPath}.tmp-${process.pid}-${Date.now()}`
1108
+ writeFileSync(tmpPath, `${JSON.stringify(desired, null, 2)}\n`)
1109
+ renameSync(tmpPath, manifestPath)
1110
+ say(2, 'manifest', `wrote bundles [${BUNDLES.join(', ')}]`)
1111
+ }
1112
+ }
1113
+
1114
+ // [3/7] Symlink: create the absolute link, skip when already correct, and
1115
+ // ONLY in repair mode replace a wrong target / non-symlink entry. Normal
1116
+ // startup stays report-only (a conflict is a WARN, never an overwrite).
1117
+ let conflict = null
1118
+ {
1119
+ const state = linkState(linkPath)
1120
+ if (state.kind === 'absent') {
1121
+ mkdirSync(dirname(linkPath), { recursive: true })
1122
+ try {
1123
+ symlinkSync(bridgeDir, linkPath, 'dir')
1124
+ } catch (error) {
1125
+ fail(`could not create symlink ${linkPath}: ${error?.message ?? error}`)
1126
+ }
1127
+ say(3, 'symlink', `created ${linkPath} -> ${bridgeDir}`)
1128
+ } else if (state.kind === 'symlink' && (state.resolved === bridgeDir || state.abs === bridgeDir)) {
1129
+ say(3, 'symlink', 'already points at the bridge artifact, skipping')
1130
+ } else if (repair) {
1131
+ const desc = state.kind === 'not-symlink'
1132
+ ? `${linkPath} is not a symlink`
1133
+ : `${linkPath} -> ${state.raw}`
1134
+ note(`repairing bridge link (${desc})`)
1135
+ try {
1136
+ removePath(linkPath)
1137
+ mkdirSync(dirname(linkPath), { recursive: true })
1138
+ symlinkSync(bridgeDir, linkPath, 'dir')
1139
+ } catch (error) {
1140
+ fail(`could not repair symlink ${linkPath}: ${error?.message ?? error}`)
1141
+ }
1142
+ say(3, 'symlink', `repaired ${linkPath} -> ${bridgeDir}`)
1143
+ } else if (state.kind === 'not-symlink') {
1144
+ conflict = `${linkPath} exists and is NOT a symlink`
1145
+ } else {
1146
+ conflict = `${linkPath} -> ${state.raw} (expected ${bridgeDir})`
1147
+ }
1148
+ }
1149
+
1150
+ // [4/7] Verify: report-only for a conflict; never overwrite.
1151
+ if (conflict !== null) {
1152
+ warn(`conflict, not overwriting: ${conflict}`)
1153
+ warn('the profile link was left untouched; the identity guard below decides whether the resolved artifact is acceptable')
1154
+ console.log(`${PREFIX}REPORT — conflict detected, no change made to the link`)
1155
+ } else {
1156
+ const finalState = linkState(linkPath)
1157
+ if (finalState.kind !== 'symlink' || (finalState.resolved !== bridgeDir && finalState.abs !== bridgeDir)) {
1158
+ fail(`post-write verification failed for ${linkPath}: link does not resolve to ${bridgeDir}`)
1159
+ }
1160
+ // Explicit guard: no @deepseek-ai package may be present in the profile.
1161
+ const deepseekDir = join(profileDir, 'node_modules', '@deepseek-ai')
1162
+ if (existsSync(deepseekDir)) {
1163
+ fail(
1164
+ `forbidden @deepseek-ai packages found in profile: ${deepseekDir}`,
1165
+ 'The host closure supplies @deepseek-ai/* bundles; they must never be copied into a profile directory.',
1166
+ )
1167
+ }
1168
+ say(4, 'verify', `bridge resolves to ${bridgeDir}; no @deepseek-ai copy in profile`)
1169
+ }
1170
+
1171
+ // [5/7] Identity guard always runs, including on the conflict path, so a
1172
+ // repointed / replaced bridge cannot slip through as a mere WARN.
1173
+ verifyBridgeIdentity()
1174
+
1175
+ // [6/7] Inproc-only patch generation. The gate is here (not just in the
1176
+ // launcher) so --repair-bridge / direct runs without the env stay unchanged.
1177
+ // [7/7] generates the local shim package that the patch row resolves.
1178
+ if (INPROC_MODE) {
1179
+ provisionPatch()
1180
+ provisionShim()
1181
+ }
1182
+
1183
+ console.log(`${PREFIX}PASS`)
1184
+ }
1185
+
1186
+ function main(argv = []) {
1187
+ // --repair is passed by `dsh-opentui --repair-bridge`; accept the long form
1188
+ // too so the underlying mode is unambiguous when invoked directly.
1189
+ const repair = argv.includes('--repair') || argv.includes('--repair-bridge')
1190
+ console.log(`${PREFIX}dsh home ${dshHome}`)
1191
+ if (!existsSync(dshHome)) {
1192
+ fail(
1193
+ `DSH_HOME directory does not exist: ${dshHome}`,
1194
+ `Create it first (e.g. mkdir -p "${dshHome}"). The opentui-inproc profile must share the existing Harness home, not create an isolated one.`,
1195
+ )
1196
+ }
1197
+ if (!statSync(dshHome).isDirectory()) {
1198
+ fail(`DSH_HOME is not a directory: ${dshHome}`)
1199
+ }
1200
+
1201
+ // The lock lives inside the profile dir, so make sure it exists first.
1202
+ mkdirSync(profileDir, { recursive: true })
1203
+
1204
+ const token = acquireLock()
1205
+ if (!token) {
1206
+ // A live peer kept the lock: it is provisioning the same profile, so this
1207
+ // instance skips its own pass rather than corrupting the shared state.
1208
+ note(`SKIP — could not acquire provisioning lock after ${LOCK_MAX_ATTEMPTS} attempts (${LOCK_RETRY_MS}ms backoff); another live instance is provisioning; skipping.`)
1209
+ return
1210
+ }
1211
+
1212
+ try {
1213
+ runProvision({ repair })
1214
+ } finally {
1215
+ releaseLock(token)
1216
+ }
1217
+ }
1218
+
1219
+ try {
1220
+ main(process.argv.slice(2))
1221
+ } catch (error) {
1222
+ if (error instanceof ProvisionError) {
1223
+ console.error(`${PREFIX}FAIL — ${error.message}`)
1224
+ if (error.detail) console.error(error.detail.trimEnd())
1225
+ } else {
1226
+ console.error(`${PREFIX}FAIL — unexpected error: ${error?.stack ?? String(error)}`)
1227
+ }
1228
+ process.exitCode = 1
1229
+ }