Repository navigation
Expand file tree
/
Copy pathcli.mjs
More file actions
879 lines (810 loc) · 39.1 KB
/
Copy pathcli.mjs
File metadata and controls
879 lines (810 loc) · 39.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
#!/usr/bin/env node
// create-dsh-bundle — zero-dependency scaffold generator + verifier for DeepSeek Harness plugin bundles.
//
// Two modes, both fully non-interactive (Node's built-in `util.parseArgs`, no readline):
//
// generate : node cli.mjs --name dsh-xxx --desc "..." [--with-tool] [--out <dir>]
// verify : node cli.mjs --verify <dir> [--with-tool]
//
// No npm dependencies, no LLM calls, no API keys, no network, no npm publish.
//
// Every reference to "does DSH start" below means: a GLOBAL `dsh` against a clean,
// isolated DSH_HOME, installed the way an outside user would install it. Running
// `pnpm dsh` inside a deepseek-harness source check-out is a different resolution
// path (tsx launcher) and proves nothing about a user installing the package.
import { parseArgs } from 'node:util'
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { builtinModules } from 'node:module'
import { join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
const USAGE = `create-dsh-bundle — scaffold and verify a DeepSeek Harness plugin bundle
Usage:
create-dsh-bundle --name <plugin-name> [--desc <description>] [--with-tool] [--out <output-dir>]
create-dsh-bundle --verify <plugin-dir> [--with-tool]
From a source checkout the same commands run as: node cli.mjs <args>
Required (generate):
--name <plugin-name> Plugin (package) name, e.g. dsh-demo-x.
Optional (generate):
--desc <description> Package description (default: a one-liner).
--with-tool Include the greet tool example (defineTool + inject ['tools']).
Omit for a minimal skeleton (apply + console.log only).
--out <output-dir> Output directory (default: ./<plugin-name>).
Must not exist — the generator refuses to overwrite.
Verify:
--verify <plugin-dir> Check an already generated bundle in place (writes nothing).
Checks: all five bundle files exist (SOP §3: package.json,
index.js, cordis.patch.yml, README.md, .gitignore);
package.json parses; name matches the cordis.patch.yml
insert (startup-fatal when it does not); cordis.patch.yml
parses; dsh.bundle.patch target exists; index.js has no
default export (function-plugin requirement); every bare
import in index.js is declared in package.json (startup-fatal
when it is not — this is the check that keeps a bundle which
kills 'dsh --profile <name>' out of a green run);
inject contains 'tools' when the tool example is present.
Exit code 0 = all PASS, 1 = at least one FAIL.
-h, --help Show this help.
Examples:
create-dsh-bundle --name dsh-demo-x --desc "Demo plugin" --with-tool --out /tmp/dsh-demo-x
create-dsh-bundle --verify /tmp/dsh-demo-x
`
const DEFAULT_DESC = 'A DeepSeek Harness plugin bundle generated by create-dsh-bundle.'
// dsh-base already provides these services; re-inserting them aborts startup
// with `service "tools" has been registered` (SOP §8.2).
const BASE_SERVICE_PACKAGES = ['@deepseek-ai/dsh-tools', '@deepseek-ai/dsh-system-prompt']
// The single bare import in the --with-tool skeleton.
const DSH_TOOLS_PACKAGE = '@deepseek-ai/dsh-tools'
// Range emitted as a peerDependency by --with-tool. Measured, not guessed:
// npm view @deepseek-ai/dsh-tools@'^0.1.6-alpha.1 || ^0.1.5-rc.2' version
// -> 0.1.5-rc.2, 0.1.6-alpha.1, 0.1.6-alpha.2
// Why `||` at all: semver only lets a prerelease satisfy a range if some comparator
// in the set carries a prerelease *on the same major.minor.patch*. Every published
// dsh-tools version is a prerelease, so `^0.1.5-rc.2` resolves to 0.1.5-rc.2 alone and
// `>=0.1.1-rc.2` to 0.1.1-rc.2 alone — both "install" but neither covers the DSH
// generation in use. An OR chain is what the ecosystem does (dsh-plugin-subscriptions
// ships `^0.1.1-rc.2 || ^0.1.2-alpha.1`). Refresh this when the official line moves:
// the generated README says so, and `--verify` only cares that *some* declaration exists.
const DSH_TOOLS_PEER_RANGE = '^0.1.6-alpha.1 || ^0.1.5-rc.2'
// Version stamped into every generated bundle's package.json. The generated README quotes the
// matching `npm pack` filename, so the two share this constant.
const GENERATED_BUNDLE_VERSION = '0.1.0'
// Version of this generator itself, quoted in the generated README's static-check command
// (`npx -y create-dsh-bundle@<version> --verify …`) so an outside user can re-run the check
// without a source check-out. Read from our own package.json — npm always ships it, `files`
// or not. Falls back to `latest` if it cannot be read (e.g. cli.mjs copied out on its own).
let GENERATOR_VERSION = 'latest'
try {
const self = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
if (self && typeof self.version === 'string' && self.version !== '') GENERATOR_VERSION = self.version
} catch {
// keep the 'latest' fallback
}
// Node's built-in modules, both bare ('fs') and prefixed ('node:fs').
// Declared up here (not next to the scan helpers below) because verify mode runs at
// module top level: a `const` further down would still be in its temporal dead zone.
const BUILTIN_MODULES = new Set([
...builtinModules,
...builtinModules.map((m) => `node:${m}`),
])
// The manifest fields a bare import may be declared in (checked in this order).
const DECLARATION_FIELDS = ['dependencies', 'peerDependencies', 'optionalDependencies', 'devDependencies']
function fail(message) {
console.error(`Error: ${message}`)
process.exit(1)
}
let values
try {
({ values } = parseArgs({
options: {
name: { type: 'string' },
desc: { type: 'string' },
'with-tool': { type: 'boolean', default: false },
out: { type: 'string' },
verify: { type: 'string' },
help: { type: 'boolean', short: 'h', default: false },
},
allowPositionals: false,
strict: true,
}))
} catch (err) {
console.error(`Error: ${err.message}`)
console.error(USAGE)
process.exit(1)
}
if (values.help) {
console.log(USAGE)
process.exit(0)
}
const withTool = values['with-tool'] === true
const name = values.name
const desc = values.desc || DEFAULT_DESC
// ---- verify mode (no writes) -----------------------------------------------
if (values.verify !== undefined) {
process.exit(await verifyBundle(resolve(values.verify), { expectTool: withTool, expectedName: name }))
}
// ---- generate mode ---------------------------------------------------------
if (!name) fail('--name is required.')
// Validate name: lowercase letters / digits / hyphens, must start with a letter.
if (!/^[a-z][a-z0-9-]*$/.test(name)) {
fail(
`--name "${name}" is not a valid package name ` +
'(lowercase letters, digits, hyphens; must start with a letter).',
)
}
const outDir = resolve(values.out || `./${name}`)
if (existsSync(outDir)) {
fail(
`output directory already exists: ${outDir}\n` +
' refusing to overwrite — pass a different --out, or remove that path first.',
)
}
// Derive display identifiers from the package name, matching the dsh-hello
// convention: dsh-hello-plugin -> export name "hello-plugin" -> id "hello"
const exportName = name.replace(/^dsh-/, '')
const id = exportName.replace(/-plugin$/, '')
// ---- templates -------------------------------------------------------------
function minimalIndex(exportName) {
return [
`export const name = '${exportName}'`,
'',
'export function apply(ctx) {',
` console.log('[${exportName}] plugin loaded!')`,
` console.log('[${exportName}] hello from my first plugin')`,
'}',
'',
].join('\n')
}
function withToolIndex(exportName) {
return [
"import { defineTool } from '@deepseek-ai/dsh-tools'",
'',
`export const name = '${exportName}'`,
"export const inject = ['tools']",
'',
'export function apply(ctx) {',
` console.log('[${exportName}] plugin loaded!')`,
` console.log('[${exportName}] hello from my first plugin')`,
'',
' // Register a model-callable tool into the harness `tools` service.',
' ctx.tools.register(defineTool({',
" name: 'greet',",
" description: 'Greet the named person.',",
' parameters: {',
" name: { type: 'string', required: true, description: 'Who to greet' },",
' },',
' output: {',
" schema: { type: 'string' },",
" render: (_args, value) => [{ type: 'text', text: value }],",
' },',
' async execute(args) {',
' return `Hello, ${args.name}!`',
' },',
' }))',
'',
' // Drive one call through the real execution pipeline, standing in for the',
' // model (no key, no LLM call). `tools/result` observers fire before this',
` // promise resolves, so the [${exportName}] line below is logged after any`,
' // listeners such as tool-logger.',
' void (async () => {',
' const result = await ctx.tools.execute({',
" callId: 'demo-1',",
" name: 'greet',",
" arguments: { name: 'Cordis' },",
' signal: new AbortController().signal,',
' })',
` console.log('[${exportName}] greet replied:', JSON.stringify(result.content))`,
' })()',
'}',
'',
].join('\n')
}
function packageJson(name, desc, withTool) {
const manifest = {
name,
version: GENERATED_BUNDLE_VERSION,
description: desc,
type: 'module',
main: 'index.js',
files: ['index.js', 'cordis.patch.yml'],
dsh: { bundle: { patch: './cordis.patch.yml' } },
}
// The skeleton's only bare import must be declared, or the local (link:) route dies
// with ERR_MODULE_NOT_FOUND and takes the whole profile down (exit 1). peerDependencies
// — not dependencies — because the package is meant to run against the harness's own
// copy, matching the community plugins (dsh-airdrop, dsh-plugin-subscriptions).
if (withTool) manifest.peerDependencies = { [DSH_TOOLS_PACKAGE]: DSH_TOOLS_PEER_RANGE }
return JSON.stringify(manifest, null, 2) + '\n'
}
function cordisPatch(id, name) {
return `- insert:\n - id: ${id}\n name: ${name}\n`
}
const GITIGNORE = [
'# Local dsh home created by `dsh plugin --profile demo add` during the walkthrough.',
'.dsh-home/',
'node_modules/',
'',
].join('\n')
function readme(name, desc, withTool) {
const exportName = name.replace(/^dsh-/, '')
const toolLine = withTool
? '- Registers a `greet` tool through the harness `tools` service, driving one real call (no key, no LLM).'
: '- Minimal skeleton: `export const name` + `export function apply(ctx)` only (no tool).'
return [
`# ${name} — DeepSeek Harness plugin bundle`,
'',
`> ${desc}`,
'',
'A minimal DeepSeek Harness third-party plugin **bundle**, generated by `create-dsh-bundle`.',
'Runs the full loop: write plugin → bundle manifest → `dsh plugin add` → verify layer → start.',
'',
toolLine,
'',
'## Directory structure',
'',
'```',
'├── package.json # dsh.bundle manifest (bundle.patch -> ./cordis.patch.yml)',
'├── index.js # plugin entry: name + apply(ctx)',
'├── cordis.patch.yml # bundle config layer (single insert)',
'├── .gitignore # ignores .dsh-home/ and node_modules/',
'└── README.md',
'```',
'',
'## Install',
'',
'Prerequisites: DSH itself (`dsh -V` prints a version) and pnpm on `PATH`.',
'Both routes below were run end-to-end against a **global** `dsh` with a clean, isolated',
'`DSH_HOME` (that is the only configuration that says anything about an outside user; see',
'pitfall 8).',
'',
'### Route B — the published package (the only route to recommend to other people)',
'',
'```sh',
'npm publish --registry=https://registry.npmjs.org # from this directory, once',
' # pass --registry explicitly: a machine whose',
' # default registry is a mirror would publish there',
`dsh plugin --profile demo add ${name}`,
'timeout 20 dsh --profile demo # expect: [' + exportName + '] plugin loaded!',
'```',
'',
'Not published yet, or no registry account? A recipient does not have to wait for the',
'publish: `npm pack` turns the bundle into a tarball, and `add` takes that file directly.',
'',
'```sh',
`npm pack # -> ${name}-${GENERATED_BUNDLE_VERSION}.tgz (it prints the name)`,
`dsh plugin --profile demo add ./${name}-${GENERATED_BUNDLE_VERSION}.tgz`,
'timeout 20 dsh --profile demo # expect: [' + exportName + '] plugin loaded!',
'```',
'',
'`dsh plugin add <package-name>` installs a real package into',
'`$DSH_HOME/profiles/demo/` (pnpm runs inside the profile directory), which lives *inside*',
'the DSH home. The harness\u2019s shared fallback links are reachable from there, so the',
'`@deepseek-ai/*` imports resolve against the harness\u2019s own copy — no declaration and no',
'install step on your side. Nothing about this route depends on this machine.',
'',
'### Route A — local directory, development only (NOT for distribution)',
'',
'`dsh plugin add <directory>` records a pnpm `link:` — a symlink to your source tree. Node',
'resolves the plugin through the **real** path of that directory, which is outside the DSH',
'home, so the fallback links are unreachable: every bare import (`@deepseek-ai/dsh-tools`, …)',
'has to exist in **this directory\u2019s own `node_modules`** before the profile can start.',
'',
'```sh',
`cd /path/to/${name}`,
'pnpm install # prerequisite: pulls in the peerDependencies',
' # declared in package.json into ./node_modules',
'pnpm ls @deepseek-ai/dsh-tools # if this prints nothing, install it explicitly',
" # (same range as package.json's peerDependencies):",
"pnpm add '@deepseek-ai/dsh-tools@^0.1.6-alpha.1 || ^0.1.5-rc.2'",
' # no -D: this is a runtime dependency of the',
' # plugin, not dev-only (the same range is already',
" # declared under peerDependencies above)",
'',
'export DSH_HOME=/tmp/dsh-demo-home # isolated home, keep ~/.dsh clean',
'dsh plugin --profile demo add "$PWD" # absolute path required',
`timeout 20 dsh --profile demo # expect: [${exportName}] plugin loaded!`,
'',
'# day-to-day: edit index.js and just re-run `dsh --profile demo` (the link follows you);',
`# rescue: dsh plugin --profile demo remove ${name}`,
'```',
'',
'Route A is **not** distributable: `link:` points at a path only you have, and a recipient',
'with the same source check-out still has to satisfy the dependency step above. Publish',
'(route B) instead.',
'',
'## Static check before installing',
'',
'```sh',
`npx -y create-dsh-bundle@${GENERATOR_VERSION} --verify /path/to/${name}`,
'```',
'',
'No source checkout needed: `npx` fetches the checker for you, pinned to the generator',
'version this bundle came from. This re-reads the generated files only — it is a',
'static/generated-artifact check, **not** an install-and-load verification. Installing',
'into a profile is one of the two routes above.',
'',
'## Runtime dependencies',
'',
...(withTool
? [
'`index.js` imports `' + DSH_TOOLS_PACKAGE + '`, and `package.json` declares it:',
'',
'```json',
'"peerDependencies": {',
` "${DSH_TOOLS_PACKAGE}": "${DSH_TOOLS_PEER_RANGE}"`,
'}',
'```',
'',
'- `peerDependencies` (not `dependencies`) matches the community plugins — the harness',
' provides this module at runtime; you are only stating which generation you were',
' written against, and you do not want a second copy dragged into every profile.',
`- The \`||\` is deliberate: \`${DSH_TOOLS_PEER_RANGE}\` covers the 0.1.5 and 0.1.6 lines.`,
' Every published version of this package is a prerelease, and semver only lets a',
' prerelease satisfy a range when a comparator carries a prerelease on the same',
' `major.minor.patch` — so `^0.1.5-rc.2` alone resolves to `0.1.5-rc.2` alone, and',
' `>=0.1.1-rc.2` to `0.1.1-rc.2` alone. Neither would match the DSH you are running.',
' (`npm view @deepseek-ai/dsh-tools@\'^0.1.6-alpha.1 || ^0.1.5-rc.2\' version` printed',
' `0.1.5-rc.2, 0.1.6-alpha.1, 0.1.6-alpha.2`.)',
'- Refresh it when the official line moves (`npm view @deepseek-ai/dsh-tools dist-tags`).',
' `--verify` only checks that the import is declared *somewhere* in `package.json`;',
' keeping the range honest is your call.',
]
: [
'The minimal skeleton imports nothing, so it declares no dependencies.',
'The moment you add a bare import, declare it — `--verify` fails the bundle otherwise',
'(and an undeclared import is startup-fatal, pitfall 4).',
]),
'',
'## Pitfalls (learned the hard way)',
'',
'1. **A plugin that fails to load takes the entire profile down.** DSH resolves every',
' layer while starting; one `ERR_MODULE_NOT_FOUND`, one bad patch insert, and',
' `dsh --profile demo` terminates with **exit code 1** — nothing loads, and there is no',
' partial success to inspect. Rescue command (also your escape hatch from a profile that',
' now refuses to boot):',
'',
' ```sh',
` dsh plugin --profile demo remove ${name}`,
' ```',
'2. **`cordis.patch.yml`\u2019s insert `name` must equal the package name.** It is what the',
' loader imports; a mismatch is startup-fatal (exit 1), not a warning. `--verify` check 4.',
'3. **Do not re-insert `@deepseek-ai/dsh-tools` / `@deepseek-ai/dsh-system-prompt`** in',
' `cordis.patch.yml` — dsh-base already provides the `tools` service. Just declare',
" `export const inject = ['tools']` in the plugin. Re-inserting throws",
' `service "tools" has been registered`.',
'4. **Declare every bare import in `package.json`.** Route A resolves imports from this',
' directory, so an undeclared `@deepseek-ai/*` import means',
' `ERR_MODULE_NOT_FOUND` → profile exit 1 (see pitfall 1). `--verify` fails such a bundle',
' on purpose.',
'5. **`dsh --profile demo` does not exit after loading** (agent-loop has `agents: []`, the',
' event loop stays idle). That is expected — wrap it in `timeout`; exit 124 is normal, and',
' the plugin log lines are the evidence.',
'6. **No `default export` next to the named exports.** A function plugin mixing `export',
' default` loses its namespace in the Loader (official postmortem 0001). `--verify`',
' fails on this.',
'7. **`--dump-config` is long** (full dsh-base layer); grep for your plugin name to see only',
' your own layer:',
'',
' ```sh',
` dsh --profile demo --dump-config | grep -A3 '${name}'`,
' ```',
'8. **State the mode when you claim "it loads".** `pnpm dsh` inside a deepseek-harness',
' source check-out (the tsx launcher) and a **global** `dsh` (fallback links inside',
' `DSH_HOME`) are two different resolution paths: passing in the first says nothing about',
' the second. Only **global `dsh` + a clean `DSH_HOME` + the install route an outside user',
' actually has** supports an availability claim. Check-out-mode success is not evidence',
' for the published package.',
'',
].join('\n')
}
// ---- write files -----------------------------------------------------------
const files = {
'package.json': packageJson(name, desc, withTool),
'index.js': withTool ? withToolIndex(exportName) : minimalIndex(exportName),
'cordis.patch.yml': cordisPatch(id, name),
'README.md': readme(name, desc, withTool),
'.gitignore': GITIGNORE,
}
mkdirSync(outDir, { recursive: true })
for (const [fileName, content] of Object.entries(files)) {
writeFileSync(resolve(outDir, fileName), content)
}
console.log(`✔ Scaffolded plugin bundle in ${outDir}`)
console.log(` package name : ${name}`)
console.log(` export name : ${exportName}`)
console.log(` cordis id : ${id}`)
console.log(` tool example : ${withTool ? 'yes (greet)' : 'no (minimal skeleton)'}`)
console.log(` files : ${Object.keys(files).join(', ')}`)
console.log('')
console.log(`Next: create-dsh-bundle --verify ${outDir}`)
// ---- verify mode -----------------------------------------------------------
//
// Everything below is a STATIC / generated-artifact check: it re-reads the files
// that were generated and never installs anything into a DSH profile. Passing
// it is NOT the same as "installed and loaded in a DSH profile" — that is the
// two install routes in the generated README (B: published package; A: local
// directory + the dependency prerequisite).
// dsh-base already provides these services; re-inserting them aborts startup
// with `service "tools" has been registered` (SOP §8.2). Declared at the top of
// the file: verify mode runs before later module-level declarations are
// initialised, so a const down here would hit the temporal dead zone.
// Dependency-free YAML subset parser: block mappings + block sequences with
// plain scalars (and single/double quoted strings, booleans, null, numbers),
// full-line and trailing `#` comments. Flow style ({a: 1} / [1, 2]), anchors,
// tags and multi-line blocks are NOT supported — unsupported input raises an
// error instead of being silently mis-parsed.
function parseYamlSubset(text) {
const lines = []
text.split(/\r?\n/).forEach((raw, index) => {
const withoutComment = raw.replace(/(^|\s)#.*$/, '$1')
if (withoutComment.trim() === '') return
lines.push({
indent: withoutComment.match(/^ */)[0].length,
text: withoutComment.trim(),
line: index + 1,
})
})
if (lines.length === 0) throw new Error('empty document')
let pos = 0
function scalar(raw, line) {
const v = raw.trim()
if (v.startsWith('[') || v.startsWith('{')) {
throw new Error(`line ${line}: flow style is not supported by this subset parser`)
}
if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))) return v.slice(1, -1)
if (v === 'true') return true
if (v === 'false') return false
if (v === 'null' || v === '~') return null
if (/^-?\d+$/.test(v)) return Number(v)
return v
}
function keyValue(body, line) {
const m = body.match(/^([^:#]+):(.*)$/)
if (!m) throw new Error(`line ${line}: expected "key: value", got "${body}"`)
return { key: m[1].trim(), value: m[2].trim() }
}
function childOf(indent, line) {
return pos < lines.length && lines[pos].indent > indent ? parseNode(indent + 1) : null
}
function parseNode(minIndent) {
if (pos >= lines.length || lines[pos].indent < minIndent) return null
return lines[pos].text.startsWith('-') ? parseSeq(lines[pos].indent) : parseMap(lines[pos].indent)
}
function parseMap(indent, target = {}) {
while (pos < lines.length && lines[pos].indent === indent && !lines[pos].text.startsWith('-')) {
const { text, line } = lines[pos]
pos += 1
const { key, value } = keyValue(text, line)
target[key] = value === '' ? childOf(indent, line) : scalar(value, line)
}
return target
}
function parseSeq(indent) {
const seq = []
while (pos < lines.length && lines[pos].indent === indent && lines[pos].text.startsWith('-')) {
const { text, line } = lines[pos]
const rest = text.slice(1)
const body = rest.trim()
const keyIndent = indent + 1 + rest.match(/^ */)[0].length
pos += 1
if (body === '') {
seq.push(childOf(indent, line))
continue
}
if (!/^[^:#]+:/.test(body)) {
seq.push(scalar(body, line))
continue
}
const { key, value } = keyValue(body, line)
const item = {}
item[key] = value === '' ? childOf(keyIndent, line) : scalar(value, line)
// Sibling keys of the same sequence item continue at keyIndent.
while (pos < lines.length && lines[pos].indent === keyIndent && !lines[pos].text.startsWith('-')) {
const next = lines[pos]
pos += 1
const kv = keyValue(next.text, next.line)
item[kv.key] = kv.value === '' ? childOf(keyIndent, next.line) : scalar(kv.value, next.line)
}
seq.push(item)
}
return seq
}
const root = parseNode(0)
if (pos < lines.length) {
throw new Error(`line ${lines[pos].line}: unexpected indentation near "${lines[pos].text}"`)
}
return root
}
function existsFile(path) {
try {
return statSync(path).isFile()
} catch {
return false
}
}
function insertsOf(patch) {
const out = []
if (!Array.isArray(patch)) return out
for (const item of patch) {
if (item && typeof item === 'object' && Array.isArray(item.insert)) {
for (const insert of item.insert) if (insert && typeof insert === 'object') out.push(insert)
}
}
return out
}
function describePatchProblems(patch) {
const problems = []
if (!Array.isArray(patch)) return ['root is not a block sequence ("- insert:")']
const inserts = insertsOf(patch)
if (inserts.length === 0) problems.push('no "- insert:" list entry found')
inserts.forEach((insert, i) => {
if (typeof insert.id !== 'string' || insert.id === '') problems.push(`insert[${i}] has no string "id"`)
if (typeof insert.name !== 'string' || insert.name === '') problems.push(`insert[${i}] has no string "name"`)
})
return problems
}
function extractExportedArray(source, exportName) {
const m = source.match(new RegExp(`export\\s+const\\s+${exportName}\\s*=\\s*\\[([^\\]]*)\\]`))
if (!m) return null
return m[1]
.split(',')
.map((s) => s.trim().replace(/^\s*['"]|['"]\s*$/g, ''))
.filter(Boolean)
}
// Every module specifier the file imports, across the forms a plugin actually uses:
// `import x from 's'`, `import 's'`, `import {a, b} from 's'`, `export … from 's'`,
// and dynamic `import('s')`. Deliberately a regex scan, not a parser: the point is to
// catch an undeclared dependency, and a missed exotic form only ever costs a false PASS
// in a file we also scan for a default export at line level.
function collectModuleSpecifiers(source) {
const specs = new Set()
const patterns = [
/\bimport\s+(?:[\w*{}\s,$]*?\s+from\s+)?['"]([^'"]+)['"]/g,
/\bexport\s+(?:\*|\{[\s\S]*?\})\s+from\s*['"]([^'"]+)['"]/g,
/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
]
for (const re of patterns) {
for (const m of source.matchAll(re)) specs.add(m[1])
}
return [...specs]
}
// './x' | '../x' | '/x' | 'node:fs' | 'fs' (builtin) -> null; else the package name
// ('@scope/pkg' for scoped, 'pkg' for unscoped, subpaths stripped).
function barePackageName(spec) {
if (!spec || spec.startsWith('.') || spec.startsWith('/') || BUILTIN_MODULES.has(spec)) return null
const parts = spec.split('/')
if (spec.startsWith('@')) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : spec
return parts[0]
}
function declaredIn(manifest, pkg) {
for (const field of DECLARATION_FIELDS) {
const table = manifest[field]
if (table && typeof table === 'object' && Object.prototype.hasOwnProperty.call(table, pkg)) return field
}
return null
}
async function verifyBundle(dir, { expectTool, expectedName }) {
const results = []
const record = (label, status, detail) => results.push({ label, status, detail })
const firstLine = (s) => String(s).split('\n')[0]
console.log(`create-dsh-bundle --verify ${dir}`)
console.log('')
// [1] Generated-artifact completeness (SOP §3): all five files must be present.
// Checked FIRST and independently of the checks below — those only open the files
// they happen to look at, so a generator that silently drops a file (e.g. README.md)
// used to verify green. Declared here (not at module level) on purpose: verify mode
// runs before later module-level declarations are initialised.
const REQUIRED_FILES = ['package.json', 'index.js', 'cordis.patch.yml', 'README.md', '.gitignore']
const missingFiles = REQUIRED_FILES.filter((f) => !existsFile(join(dir, f)))
const COMPLETE_LABEL = 'All five generated files present (SOP §3)'
if (missingFiles.length) {
record(
COMPLETE_LABEL,
'FAIL',
`missing ${missingFiles.length}/${REQUIRED_FILES.length}: ${missingFiles.join(', ')} ` +
`— expected all of [${REQUIRED_FILES.join(', ')}]`,
)
} else {
record(COMPLETE_LABEL, 'PASS', `all ${REQUIRED_FILES.length} present: ${REQUIRED_FILES.join(', ')}`)
}
// [2] package.json parses.
const manifestPath = join(dir, 'package.json')
let manifest = null
if (!existsFile(manifestPath)) {
record('package.json parses', 'FAIL', `not found: ${manifestPath}`)
} else {
try {
manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
throw new Error('root value is not a JSON object')
}
record('package.json parses', 'PASS', `name=${manifest.name} version=${manifest.version}`)
} catch (err) {
manifest = null
record('package.json parses', 'FAIL', firstLine(err.message))
}
}
// [3] cordis.patch.yml exists and parses as the expected block structure.
const PATCH_LABEL = 'cordis.patch.yml exists and is well formed'
const patchPath = join(dir, 'cordis.patch.yml')
let patch = null
if (!existsFile(patchPath)) {
record(PATCH_LABEL, 'FAIL', `not found: ${patchPath}`)
} else {
try {
patch = parseYamlSubset(readFileSync(patchPath, 'utf8'))
const problems = describePatchProblems(patch)
if (problems.length) record(PATCH_LABEL, 'FAIL', problems.join('; '))
else record(PATCH_LABEL, 'PASS', `block sequence, ${insertsOf(patch).length} insert(s)`)
} catch (err) {
patch = null
record(PATCH_LABEL, 'FAIL', firstLine(err.message))
}
}
// [4] package.json name === the name of a cordis.patch.yml insert.
const NAME_LABEL = 'package.json name matches a patch insert name'
const insertNames = patch ? insertsOf(patch).map((i) => i.name) : []
if (!manifest || !patch) {
record(NAME_LABEL, 'FAIL', 'cannot compare: package.json or cordis.patch.yml unreadable')
} else if (insertNames.includes(manifest.name)) {
record(NAME_LABEL, 'PASS', manifest.name)
} else {
record(
NAME_LABEL,
'FAIL',
`package.json name=${JSON.stringify(manifest.name)} is not among patch insert names ` +
`[${insertNames.map((n) => JSON.stringify(n)).join(', ')}] — startup-fatal (SOP §5.6): ` +
'the insert name is what the loader imports, so `dsh --profile <name>` exits 1',
)
}
// [5] dsh.bundle.patch is declared and its target exists.
const BUNDLE_LABEL = 'dsh.bundle.patch points at an existing file'
const patchRef = manifest && manifest.dsh && manifest.dsh.bundle ? manifest.dsh.bundle.patch : undefined
if (!manifest) {
record(BUNDLE_LABEL, 'FAIL', 'skipped: package.json unreadable')
} else if (typeof patchRef !== 'string' || patchRef === '') {
record(
BUNDLE_LABEL,
'FAIL',
'no dsh.bundle.patch string — dsh would install this as a plain dependency, not a profile layer',
)
} else if (existsFile(resolve(dir, patchRef))) {
record(BUNDLE_LABEL, 'PASS', `${patchRef} -> ${resolve(dir, patchRef)}`)
} else {
record(BUNDLE_LABEL, 'FAIL', `${patchRef} does not exist (resolved: ${resolve(dir, patchRef)})`)
}
// [6] index.js: static scan for a default export (fatal for the function form).
const entry = join(dir, 'index.js')
const DEF_LABEL = 'index.js has no default export (function plugin)'
let source = null
if (!existsFile(entry)) {
record(DEF_LABEL, 'FAIL', `not found: ${entry}`)
} else {
source = readFileSync(entry, 'utf8')
const hits = [
[/^\s*export\s+default\b/m, 'export default'],
[/^\s*export\s*\{[^}]*\bas\s+default\b/m, 'export { ... as default }'],
[/\bmodule\.exports\s*=/m, 'module.exports = ...'],
[/\bexports\.default\s*=/m, 'exports.default = ...'],
]
.filter(([re]) => re.test(source))
.map(([, label]) => label)
if (hits.length) record(DEF_LABEL, 'FAIL', `found ${hits.join(', ')} — the Loader drops the namespace (postmortem 0001)`)
else record(DEF_LABEL, 'PASS', 'static scan: no default-export form found')
}
// [6b] every bare import must be declared in package.json. This is the gate that
// keeps a bundle which kills the whole profile out of a green run: in the local
// (link:) route the plugin resolves imports from its own directory, so an undeclared
// `@deepseek-ai/*` import is ERR_MODULE_NOT_FOUND at startup -> `dsh --profile <name>`
// terminates with exit 1. The old check set reported that state as WARN + exit 0.
const IMPORTS_LABEL = 'every bare import in index.js is declared in package.json'
if (source === null) {
record(IMPORTS_LABEL, 'FAIL', 'skipped: index.js unreadable')
} else if (!manifest) {
record(IMPORTS_LABEL, 'FAIL', 'skipped: package.json unreadable')
} else {
const bare = [...new Set(collectModuleSpecifiers(source).map(barePackageName).filter(Boolean))]
const undeclared = bare.filter((pkg) => declaredIn(manifest, pkg) === null)
if (undeclared.length === 0) {
const how = bare.map((pkg) => `${pkg} -> ${declaredIn(manifest, pkg)}`).join(', ')
record(IMPORTS_LABEL, 'PASS', bare.length ? `${bare.length} bare import(s), all declared: ${how}` : 'no bare imports')
} else {
record(
IMPORTS_LABEL,
'FAIL',
`undeclared bare import(s): ${undeclared.join(', ')} — in the local (link:) route these ` +
'resolve from the plugin directory, so the import fails with ERR_MODULE_NOT_FOUND and ' +
`\`dsh --profile <name>\` exits 1 before anything loads. Add them to ` +
`dependencies/peerDependencies in package.json (the --with-tool skeleton declares ` +
`'${DSH_TOOLS_PACKAGE}' as a peerDependency for exactly this reason)`,
)
}
const devOnly = bare.filter((pkg) => declaredIn(manifest, pkg) === 'devDependencies')
if (devOnly.length) {
record(
'declared for consumers, not only for local dev',
'WARN',
`${devOnly.join(', ')} declared in devDependencies only — resolvable after a local ` +
'install, but a consumer installing this package will not get it; prefer ' +
'peerDependencies (community convention)',
)
}
}
// [6c] best-effort runtime import: real namespace, no DSH profile involved.
const RT_LABEL = 'index.js runtime namespace (best effort)'
if (existsFile(entry)) {
try {
const ns = await import(pathToFileURL(entry).href)
const keys = Object.keys(ns)
const applyOk = typeof ns.apply === 'function'
if (keys.includes('default')) {
record(RT_LABEL, 'FAIL', `imported OK but the namespace exposes 'default' (keys=[${keys.join(', ')}])`)
} else if (!applyOk) {
record(RT_LABEL, 'WARN', `imported OK, no default export, but no callable apply() (keys=[${keys.join(', ')}])`)
} else {
record(RT_LABEL, 'PASS', `imported OK, no default export, apply() present, keys=[${keys.join(', ')}]`)
}
} catch (err) {
const code = err && err.code ? err.code : err && err.name
const detail = `SKIPPED (${code}: ${firstLine(err.message)}) — static scan only, nothing was executed`
if (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_UNKNOWN_BUILTIN_MODULE') {
record(
RT_LABEL,
'WARN',
`${detail}. This is about *installed*, not *declared*: a static check never installs. ` +
'Route B (published package) does not need the module locally; route A (local `link:`) ' +
'needs the `pnpm install` prerequisite in the generated README. An undeclared import ' +
'is a different (fatal) matter — see the bare-import check above.',
)
} else record(RT_LABEL, 'FAIL', detail)
}
}
// [7] inject contains 'tools' whenever the tool example is present.
const toolDetected = expectTool ||
(source !== null && /ctx\.tools\.register|from '@deepseek-ai\/dsh-tools'/.test(source))
if (toolDetected) {
const INJECT_LABEL = "inject contains 'tools' (tool example)"
if (source === null) {
record(INJECT_LABEL, 'FAIL', 'index.js unreadable')
} else {
const inject = extractExportedArray(source, 'inject')
if (inject === null) record(INJECT_LABEL, 'FAIL', 'no `export const inject = [...]` found')
else if (inject.includes('tools')) record(INJECT_LABEL, 'PASS', `inject=[${inject.join(', ')}]`)
else record(INJECT_LABEL, 'FAIL', `inject=[${inject.join(', ')}] does not include 'tools'`)
}
}
// [8] FAIL when a base-service package is re-inserted (SOP §8.2). Measured, not guessed:
// a re-inserted base service aborts startup with `service "tools" has been registered at
// <ToolRuntime>` and `dsh --profile <name>` exits 1 — an unstartable bundle. The previous
// WARN + exit 0 let exactly such an artifact verify green.
const reinserted = insertNames.filter((n) => BASE_SERVICE_PACKAGES.includes(n))
if (reinserted.length) {
record(
'no re-insert of a service package dsh-base already provides',
'FAIL',
`${reinserted.join(', ')} re-inserted — dsh-base already provides these; ` +
'`dsh --profile <name>` exits 1 with `service "..." has been registered` (SOP §8.2)',
)
}
// [9] Cross-check against --name when the caller passed one.
if (typeof expectedName === 'string' && expectedName !== '') {
const CROSS_LABEL = 'cross-check against --name'
if (manifest && manifest.name === expectedName) record(CROSS_LABEL, 'PASS', `--name ${expectedName} matches package.json`)
else record(CROSS_LABEL, 'FAIL', `--name ${expectedName} != package.json name ${manifest ? JSON.stringify(manifest.name) : '(unreadable)'}`)
}
// ---- summary -------------------------------------------------------------
let fails = 0
results.forEach((r, i) => {
if (r.status === 'FAIL') fails += 1
console.log(`[${i + 1}/${results.length}] ${r.status.padEnd(4)} ${r.label} — ${r.detail}`)
})
const passed = results.filter((r) => r.status === 'PASS').length
const warned = results.filter((r) => r.status === 'WARN').length
console.log('')
console.log(`Summary: ${passed} PASS / ${fails} FAIL / ${warned} WARN`)
console.log('Note: this is a static check of the generated files (plus one best-effort local import) — it is NOT "installed into a DSH profile and loaded successfully".')
console.log(' Install/load evidence only counts when it states its mode: global `dsh` + a clean DSH_HOME + the')
console.log(' install route an outside user actually has (the generated README route B). `pnpm dsh` in a source')
console.log(' check-out is a different resolution path and does not stand in for it.')
console.log(`verify exit code: ${fails > 0 ? 1 : 0}`)
return fails > 0 ? 1 : 0
}