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