dsh-plugin-agentdeck 0.0.0-stage → 0.1.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.
package/lib/setup.js ADDED
@@ -0,0 +1,1053 @@
1
+ import { spawn } from 'node:child_process';
2
+ import {
3
+ accessSync,
4
+ constants as fsConstants,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ renameSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { arch, homedir } from 'node:os';
12
+ import { delimiter, dirname, join, resolve } from 'node:path';
13
+ import QRCode from 'qrcode';
14
+ import { parseDocument } from 'yaml';
15
+
16
+ export const DEFAULT_RELAY_URL = 'wss://agentdeck.xianqiao.wang/ws';
17
+ const LEGACY_DEFAULT_RELAY_URL = 'wss://agent-deck.xianqiao.wang/ws';
18
+
19
+ export const ACP_PLUGIN_PACKAGES = [
20
+ '@openma/deepseek-harness-acp',
21
+ '@cnctem/dsh-acp',
22
+ ];
23
+ export const DEFAULT_ACP_PLUGIN = '@openma/deepseek-harness-acp@latest';
24
+
25
+ const BUILTIN_DEEPSEEK_PROVIDERS = new Set([
26
+ 'deepseek-official',
27
+ 'deepseek-account',
28
+ ]);
29
+
30
+ const PATCH_HEADER =
31
+ '# Your patch layer for this dsh profile, applied after every bundle layer:\n' +
32
+ '# a top-level YAML array of loader patch entries (id-targeted config\n' +
33
+ '# overrides, disables, and insert lists; `!!js` expressions allowed).\n';
34
+
35
+ const JS_YAML_TAG = {
36
+ tag: 'tag:yaml.org,2002:js',
37
+ resolve: (str) => str,
38
+ identify: () => false,
39
+ };
40
+
41
+ /**
42
+ * Resolve AgentDeck's local data directory, matching `dirs::data_local_dir()/agentdeck`.
43
+ */
44
+ export function getAgentDeckDataDir({
45
+ platform = process.platform,
46
+ env = process.env,
47
+ home = homedir(),
48
+ } = {}) {
49
+ if (platform === 'darwin') {
50
+ return join(home, 'Library', 'Application Support', 'agentdeck');
51
+ }
52
+ if (platform === 'win32') {
53
+ const localAppData = env.LOCALAPPDATA || join(home, 'AppData', 'Local');
54
+ return join(localAppData, 'agentdeck');
55
+ }
56
+ const xdgDataHome = env.XDG_DATA_HOME || join(home, '.local', 'share');
57
+ return join(xdgDataHome, 'agentdeck');
58
+ }
59
+
60
+ /**
61
+ * Build the AgentDeck pairing URI (`agentdeck://connect?pairingId=...`).
62
+ * Includes `relayUrl` only when using a non-default Relay.
63
+ */
64
+ export function buildPairingUri(relayId, relayUrl) {
65
+ const effectiveRelay =
66
+ relayUrl && relayUrl !== LEGACY_DEFAULT_RELAY_URL
67
+ ? relayUrl
68
+ : DEFAULT_RELAY_URL;
69
+ const url = new URL('agentdeck://connect');
70
+ url.searchParams.set('pairingId', relayId);
71
+ if (effectiveRelay !== DEFAULT_RELAY_URL) {
72
+ url.searchParams.set('relayUrl', effectiveRelay);
73
+ }
74
+ return url.toString();
75
+ }
76
+
77
+ export async function generatePairingQrSvg(pairingUri) {
78
+ return QRCode.toString(pairingUri, {
79
+ type: 'svg',
80
+ margin: 2,
81
+ width: 220,
82
+ errorCorrectionLevel: 'M',
83
+ color: {
84
+ dark: '#111111',
85
+ light: '#ffffff',
86
+ },
87
+ });
88
+ }
89
+
90
+ function isExecutableFile(filePath, platform = process.platform) {
91
+ if (!filePath || !existsSync(filePath)) return false;
92
+ if (platform === 'win32') return true;
93
+ try {
94
+ accessSync(filePath, fsConstants.X_OK);
95
+ return true;
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+
101
+ export function findExecutable(
102
+ name,
103
+ {
104
+ platform = process.platform,
105
+ env = process.env,
106
+ home = homedir(),
107
+ extraDirs = [],
108
+ } = {},
109
+ ) {
110
+ const candidates =
111
+ platform === 'win32'
112
+ ? [`${name}.exe`, `${name}.cmd`, `${name}.bat`, name]
113
+ : [name];
114
+ const pathDirs = (env.PATH || '').split(delimiter).filter(Boolean);
115
+ const fallbackDirs =
116
+ platform === 'win32'
117
+ ? [
118
+ join(home, 'scoop', 'shims'),
119
+ join(env.APPDATA || join(home, 'AppData', 'Roaming'), 'npm'),
120
+ join(home, '.cargo', 'bin'),
121
+ ]
122
+ : [
123
+ join(home, '.local', 'bin'),
124
+ '/opt/homebrew/bin',
125
+ '/usr/local/bin',
126
+ join(home, '.cargo', 'bin'),
127
+ join(home, '.npm-global', 'bin'),
128
+ join(home, 'Library', 'pnpm'),
129
+ join(home, '.local', 'share', 'pnpm'),
130
+ ];
131
+
132
+ const seen = new Set();
133
+ for (const dir of [...extraDirs, ...pathDirs, ...fallbackDirs]) {
134
+ if (!dir || seen.has(dir)) continue;
135
+ seen.add(dir);
136
+ for (const file of candidates) {
137
+ const full = join(dir, file);
138
+ if (isExecutableFile(full, platform)) return full;
139
+ }
140
+ }
141
+ return null;
142
+ }
143
+
144
+ function platformSuffix(platform = process.platform, cpu = arch()) {
145
+ if (platform === 'darwin' && cpu === 'arm64') return 'darwin-arm64';
146
+ if (platform === 'darwin' && cpu === 'x64') return 'darwin-x64';
147
+ if (platform === 'linux' && cpu === 'x64') return 'linux-x64-gnu';
148
+ if (platform === 'win32' && cpu === 'x64') return 'windows-x64';
149
+ return null;
150
+ }
151
+
152
+ /**
153
+ * Find `agentdeckd` executable on PATH, standard package-manager bin dirs,
154
+ * or the plugin's dedicated fallback install prefix (`<dataDir>/cli`).
155
+ */
156
+ export function findAgentDeckDaemon({
157
+ dataDir = getAgentDeckDataDir(),
158
+ platform = process.platform,
159
+ env = process.env,
160
+ home = homedir(),
161
+ } = {}) {
162
+ const onPath = findExecutable('agentdeckd', { platform, env, home });
163
+ if (onPath) return onPath;
164
+
165
+ const cliDir = join(dataDir, 'cli');
166
+ const suffix = platformSuffix(platform);
167
+ const exe = platform === 'win32' ? 'agentdeckd.exe' : 'agentdeckd';
168
+ if (suffix) {
169
+ const directNative = join(
170
+ cliDir,
171
+ 'node_modules',
172
+ `agentdeckd-${suffix}`,
173
+ 'bin',
174
+ exe,
175
+ );
176
+ if (isExecutableFile(directNative, platform)) return directNative;
177
+ const nestedNative = join(
178
+ cliDir,
179
+ 'node_modules',
180
+ 'agentdeckd',
181
+ 'node_modules',
182
+ `agentdeckd-${suffix}`,
183
+ 'bin',
184
+ exe,
185
+ );
186
+ if (isExecutableFile(nestedNative, platform)) return nestedNative;
187
+ }
188
+
189
+ return findExecutable('agentdeckd', {
190
+ platform,
191
+ env,
192
+ home,
193
+ extraDirs: [join(cliDir, 'node_modules', '.bin')],
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Resolve the `dsh` executable path. Works for both CLI installs and
199
+ * DeepSeek Harness Desktop (bundled `runtime/cli/bin/dsh`).
200
+ */
201
+ export function resolveDshCommand({
202
+ platform = process.platform,
203
+ env = process.env,
204
+ home = homedir(),
205
+ resourcesPath = process.resourcesPath,
206
+ argv1 = process.argv[1],
207
+ } = {}) {
208
+ const bundledDirs = [];
209
+ if (resourcesPath) {
210
+ bundledDirs.push(join(resourcesPath, 'runtime', 'cli', 'bin'));
211
+ }
212
+ if (argv1) {
213
+ let cursor = dirname(resolve(argv1));
214
+ for (let i = 0; i < 6; i++) {
215
+ bundledDirs.push(join(cursor, 'bin'));
216
+ bundledDirs.push(join(cursor, 'runtime', 'cli', 'bin'));
217
+ const parent = dirname(cursor);
218
+ if (parent === cursor) break;
219
+ cursor = parent;
220
+ }
221
+ }
222
+
223
+ // Prefer user PATH / ~/.local/bin first, then bundled Desktop CLI.
224
+ const onPath = findExecutable('dsh', { platform, env, home });
225
+ if (onPath) return onPath;
226
+ return findExecutable('dsh', { platform, env, home, extraDirs: bundledDirs });
227
+ }
228
+
229
+ function isPidAlive(pid) {
230
+ if (!Number.isInteger(pid) || pid <= 0) return false;
231
+ try {
232
+ process.kill(pid, 0);
233
+ return true;
234
+ } catch (err) {
235
+ return err?.code === 'EPERM';
236
+ }
237
+ }
238
+
239
+ export async function readDaemonState(
240
+ dataDir,
241
+ { platform = process.platform, env = process.env, home = homedir() } = {},
242
+ ) {
243
+ const binaryPath = findAgentDeckDaemon({ dataDir, platform, env, home });
244
+ const configPath = join(dataDir, 'daemon.json');
245
+ const lockPath = join(dataDir, 'daemon.lock');
246
+
247
+ let pid = null;
248
+ let running = false;
249
+ if (existsSync(lockPath)) {
250
+ try {
251
+ const parsed = Number.parseInt(readFileSync(lockPath, 'utf8').trim(), 10);
252
+ if (Number.isInteger(parsed) && parsed > 0) {
253
+ pid = parsed;
254
+ running = isPidAlive(parsed);
255
+ }
256
+ } catch {
257
+ // Ignore unreadable lock file
258
+ }
259
+ }
260
+
261
+ let relayId = null;
262
+ let relayUrl = DEFAULT_RELAY_URL;
263
+ let hasCustomRelay = false;
264
+ if (existsSync(configPath)) {
265
+ try {
266
+ const raw = JSON.parse(readFileSync(configPath, 'utf8'));
267
+ if (typeof raw?.relay_id === 'string' && raw.relay_id.trim()) {
268
+ relayId = raw.relay_id.trim();
269
+ }
270
+ if (
271
+ typeof raw?.relay_url === 'string' &&
272
+ raw.relay_url.trim() &&
273
+ raw.relay_url.trim() !== LEGACY_DEFAULT_RELAY_URL
274
+ ) {
275
+ relayUrl = raw.relay_url.trim();
276
+ hasCustomRelay = relayUrl !== DEFAULT_RELAY_URL;
277
+ }
278
+ } catch {
279
+ // Ignore corrupt daemon.json
280
+ }
281
+ }
282
+
283
+ let qrSvg = null;
284
+ let maskedPairingId = null;
285
+ if (relayId) {
286
+ const uri = buildPairingUri(relayId, relayUrl);
287
+ qrSvg = await generatePairingQrSvg(uri);
288
+ maskedPairingId =
289
+ relayId.length > 14
290
+ ? `${relayId.slice(0, 9)}…${relayId.slice(-4)}`
291
+ : relayId;
292
+ }
293
+
294
+ return {
295
+ installed: Boolean(binaryPath) || running,
296
+ binaryPath,
297
+ running,
298
+ pid: running ? pid : null,
299
+ pairedReady: Boolean(relayId),
300
+ maskedPairingId,
301
+ relayUrl,
302
+ hasCustomRelay,
303
+ qrSvg,
304
+ };
305
+ }
306
+
307
+ export function readAcpPluginState(dshHome) {
308
+ const acpDir = join(dshHome, 'profiles', 'acp');
309
+ const pkgPath = join(acpDir, 'package.json');
310
+ if (!existsSync(pkgPath)) {
311
+ return { installed: false, packageName: null, version: null, acpDir };
312
+ }
313
+ try {
314
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
315
+ const deps = { ...(pkg.devDependencies || {}), ...(pkg.dependencies || {}) };
316
+ for (const candidate of ACP_PLUGIN_PACKAGES) {
317
+ if (deps[candidate]) {
318
+ const installedPkgJson = join(
319
+ acpDir,
320
+ 'node_modules',
321
+ ...candidate.split('/'),
322
+ 'package.json',
323
+ );
324
+ if (existsSync(installedPkgJson)) {
325
+ let version = deps[candidate];
326
+ try {
327
+ const inner = JSON.parse(readFileSync(installedPkgJson, 'utf8'));
328
+ if (inner.version) version = inner.version;
329
+ } catch {
330
+ // Fall back to declared version range
331
+ }
332
+ return { installed: true, packageName: candidate, version, acpDir };
333
+ }
334
+ }
335
+ }
336
+ } catch {
337
+ // Ignore malformed profile package.json
338
+ }
339
+ return { installed: false, packageName: null, version: null, acpDir };
340
+ }
341
+
342
+ export function parsePatchDocument(text) {
343
+ const doc = parseDocument(text || '[]', {
344
+ customTags: [JS_YAML_TAG],
345
+ keepSourceTokens: false,
346
+ });
347
+ if (!doc.contents || !Array.isArray(doc.contents.items)) {
348
+ doc.contents = doc.createNode([]);
349
+ }
350
+ return doc;
351
+ }
352
+
353
+ function findPatchEntryIndex(items, id) {
354
+ for (let i = 0; i < items.length; i++) {
355
+ const item = items[i];
356
+ if (item && typeof item.get === 'function' && item.get('id') === id) {
357
+ return i;
358
+ }
359
+ }
360
+ return -1;
361
+ }
362
+
363
+ function readPatchFile(patchPath) {
364
+ if (!patchPath || !existsSync(patchPath)) return null;
365
+ try {
366
+ return readFileSync(patchPath, 'utf8');
367
+ } catch {
368
+ return null;
369
+ }
370
+ }
371
+
372
+ export function extractModelSummary(patchPath) {
373
+ const text = readPatchFile(patchPath);
374
+ if (!text) {
375
+ return {
376
+ exists: false,
377
+ defaultModel: null,
378
+ acpPlugin: null,
379
+ hasCustomProviders: false,
380
+ customProviderNames: [],
381
+ };
382
+ }
383
+ try {
384
+ const doc = parsePatchDocument(text);
385
+ const arr = doc.toJS();
386
+ if (!Array.isArray(arr)) {
387
+ return {
388
+ exists: true,
389
+ defaultModel: null,
390
+ acpPlugin: null,
391
+ hasCustomProviders: false,
392
+ customProviderNames: [],
393
+ };
394
+ }
395
+ const defaultEntry = arr.find((e) => e?.id === 'agent-default-model');
396
+ const acpEntry = arr.find((e) => e?.id === 'acp-plugin');
397
+ const piAiEntry = arr.find((e) => e?.id === 'llm-pi-ai');
398
+ const providers =
399
+ piAiEntry?.config?.providers &&
400
+ typeof piAiEntry.config.providers === 'object'
401
+ ? Object.keys(piAiEntry.config.providers)
402
+ : [];
403
+ return {
404
+ exists: true,
405
+ defaultModel: defaultEntry?.config
406
+ ? {
407
+ provider: defaultEntry.config.provider || null,
408
+ model: defaultEntry.config.model || null,
409
+ reasoningEffort: defaultEntry.config.reasoningEffort || null,
410
+ }
411
+ : null,
412
+ acpPlugin: acpEntry?.config
413
+ ? {
414
+ provider: acpEntry.config.provider || null,
415
+ model: acpEntry.config.model || null,
416
+ }
417
+ : null,
418
+ hasCustomProviders: providers.length > 0,
419
+ customProviderNames: providers,
420
+ };
421
+ } catch {
422
+ return {
423
+ exists: true,
424
+ defaultModel: null,
425
+ acpPlugin: null,
426
+ hasCustomProviders: false,
427
+ customProviderNames: [],
428
+ };
429
+ }
430
+ }
431
+
432
+ function writeFileAtomic(filePath, content) {
433
+ mkdirSync(dirname(filePath), { recursive: true });
434
+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
435
+ writeFileSync(tmpPath, content, 'utf8');
436
+ renameSync(tmpPath, filePath);
437
+ }
438
+
439
+ /**
440
+ * Sync model/provider configuration from the active profile into the `acp` profile
441
+ * `cordis.patch.yml`, preserving unrelated entries and `!!js` expressions.
442
+ *
443
+ * Also mirrors non-DeepSeek `provider`/`model` into `acp-plugin.config` so
444
+ * `@openma/deepseek-harness-acp` validates the matching provider credential
445
+ * instead of requiring `DEEPSEEK_API_KEY`.
446
+ */
447
+ export function syncAcpPatch({
448
+ sourcePatchPath,
449
+ acpPatchPath,
450
+ syncModels = false,
451
+ }) {
452
+ const sourceText = readPatchFile(sourcePatchPath);
453
+ const acpText = readPatchFile(acpPatchPath);
454
+
455
+ const acpDoc = parsePatchDocument(acpText || '[]');
456
+ const acpItems = acpDoc.contents.items;
457
+ let changed = false;
458
+
459
+ const acpExistingDefaultIdx = findPatchEntryIndex(
460
+ acpItems,
461
+ 'agent-default-model',
462
+ );
463
+ const shouldSyncFromSource =
464
+ Boolean(sourceText) && (syncModels || acpExistingDefaultIdx === -1);
465
+
466
+ if (shouldSyncFromSource) {
467
+ const sourceDoc = parsePatchDocument(sourceText);
468
+ const sourceItems = sourceDoc.contents.items;
469
+
470
+ for (const id of ['llm-pi-ai', 'agent-default-model']) {
471
+ const srcIdx = findPatchEntryIndex(sourceItems, id);
472
+ if (srcIdx === -1) continue;
473
+ const cloned = sourceItems[srcIdx].clone();
474
+ const dstIdx = findPatchEntryIndex(acpItems, id);
475
+ if (dstIdx === -1) {
476
+ acpItems.push(cloned);
477
+ } else {
478
+ acpItems[dstIdx] = cloned;
479
+ }
480
+ changed = true;
481
+ }
482
+ }
483
+
484
+ const effectiveDefaultIdx = findPatchEntryIndex(
485
+ acpItems,
486
+ 'agent-default-model',
487
+ );
488
+ if (effectiveDefaultIdx !== -1) {
489
+ const defObj = acpItems[effectiveDefaultIdx].toJS(acpDoc);
490
+ const provider = defObj?.config?.provider;
491
+ const model = defObj?.config?.model;
492
+ const acpPluginIdx = findPatchEntryIndex(acpItems, 'acp-plugin');
493
+ const existingAcpPlugin =
494
+ acpPluginIdx !== -1 ? acpItems[acpPluginIdx].toJS(acpDoc) : null;
495
+
496
+ if (provider && !BUILTIN_DEEPSEEK_PROVIDERS.has(provider)) {
497
+ const nextConfig = {
498
+ ...(existingAcpPlugin?.config || {}),
499
+ provider,
500
+ ...(model ? { model } : {}),
501
+ };
502
+ const needsUpdate =
503
+ !existingAcpPlugin ||
504
+ existingAcpPlugin?.config?.provider !== nextConfig.provider ||
505
+ (model && existingAcpPlugin?.config?.model !== nextConfig.model);
506
+ if (needsUpdate) {
507
+ const entryNode = acpDoc.createNode({
508
+ id: 'acp-plugin',
509
+ config: nextConfig,
510
+ });
511
+ if (acpPluginIdx === -1) {
512
+ acpItems.push(entryNode);
513
+ } else {
514
+ acpItems[acpPluginIdx] = entryNode;
515
+ }
516
+ changed = true;
517
+ }
518
+ } else if (
519
+ shouldSyncFromSource &&
520
+ provider &&
521
+ BUILTIN_DEEPSEEK_PROVIDERS.has(provider) &&
522
+ acpPluginIdx !== -1
523
+ ) {
524
+ const nextConfig = { ...(existingAcpPlugin?.config || {}) };
525
+ nextConfig.provider = provider;
526
+ if (model) nextConfig.model = model;
527
+ acpItems[acpPluginIdx] = acpDoc.createNode({
528
+ id: 'acp-plugin',
529
+ config: nextConfig,
530
+ });
531
+ changed = true;
532
+ }
533
+ }
534
+
535
+ if (changed) {
536
+ const body = acpDoc.toString({ lineWidth: 0 });
537
+ const output = acpText ? body : `${PATCH_HEADER}${body}`;
538
+ writeFileAtomic(acpPatchPath, output);
539
+ }
540
+
541
+ return { changed, syncedFromSource: shouldSyncFromSource };
542
+ }
543
+
544
+ export function readCustomAgentState(customAgentsPath) {
545
+ if (!existsSync(customAgentsPath)) {
546
+ return { configured: false, entry: null, path: customAgentsPath };
547
+ }
548
+ try {
549
+ const data = JSON.parse(readFileSync(customAgentsPath, 'utf8'));
550
+ const agents = Array.isArray(data?.agents) ? data.agents : [];
551
+ const entry = agents.find((a) => a?.id === 'dsh') || null;
552
+ const configured = Boolean(
553
+ entry &&
554
+ typeof entry.command === 'string' &&
555
+ entry.command.trim() &&
556
+ Array.isArray(entry.args) &&
557
+ entry.args.includes('--profile') &&
558
+ entry.args.includes('acp'),
559
+ );
560
+ return { configured, entry, path: customAgentsPath };
561
+ } catch {
562
+ return { configured: false, entry: null, path: customAgentsPath };
563
+ }
564
+ }
565
+
566
+ export function upsertCustomAgent({ customAgentsPath, dshCommand }) {
567
+ let data = { agents: [] };
568
+ if (existsSync(customAgentsPath)) {
569
+ try {
570
+ const parsed = JSON.parse(readFileSync(customAgentsPath, 'utf8'));
571
+ if (parsed && typeof parsed === 'object') {
572
+ data = {
573
+ ...parsed,
574
+ agents: Array.isArray(parsed.agents) ? [...parsed.agents] : [],
575
+ };
576
+ }
577
+ } catch {
578
+ // Start fresh if file is empty/corrupt JSON
579
+ }
580
+ }
581
+
582
+ const nextEntry = {
583
+ id: 'dsh',
584
+ name: 'DeepSeek Harness',
585
+ command: dshCommand,
586
+ args: ['--profile', 'acp'],
587
+ };
588
+
589
+ const idx = data.agents.findIndex((a) => a?.id === 'dsh');
590
+ if (idx === -1) {
591
+ data.agents.push(nextEntry);
592
+ } else {
593
+ data.agents[idx] = { ...data.agents[idx], ...nextEntry };
594
+ }
595
+
596
+ writeFileAtomic(customAgentsPath, `${JSON.stringify(data, null, 2)}\n`);
597
+ return nextEntry;
598
+ }
599
+
600
+ function runCommand(
601
+ command,
602
+ args,
603
+ { cwd, env = process.env, timeoutMs = 180_000 } = {},
604
+ ) {
605
+ return new Promise((resolvePromise, reject) => {
606
+ const child = spawn(command, args, {
607
+ cwd,
608
+ env,
609
+ stdio: ['ignore', 'pipe', 'pipe'],
610
+ windowsHide: true,
611
+ });
612
+ let stdout = '';
613
+ let stderr = '';
614
+ const timer = setTimeout(() => {
615
+ child.kill('SIGTERM');
616
+ reject(
617
+ new Error(`Command timed out after ${Math.round(timeoutMs / 1000)}s`),
618
+ );
619
+ }, timeoutMs);
620
+
621
+ child.stdout.on('data', (chunk) => {
622
+ stdout += chunk.toString('utf8');
623
+ if (stdout.length > 16_000) stdout = stdout.slice(-16_000);
624
+ });
625
+ child.stderr.on('data', (chunk) => {
626
+ stderr += chunk.toString('utf8');
627
+ if (stderr.length > 16_000) stderr = stderr.slice(-16_000);
628
+ });
629
+ child.on('error', (err) => {
630
+ clearTimeout(timer);
631
+ reject(err);
632
+ });
633
+ child.on('close', (code) => {
634
+ clearTimeout(timer);
635
+ resolvePromise({ code, stdout, stderr });
636
+ });
637
+ });
638
+ }
639
+
640
+ function sleep(ms) {
641
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
642
+ }
643
+
644
+ /**
645
+ * Install `agentdeckd` automatically:
646
+ * 1. macOS: Homebrew (`mantou132/tap/agentdeckd`) if available (signed native binary)
647
+ * 2. Global `npm install -g agentdeckd --include=optional` (macOS/Linux/Windows)
648
+ * 3. Windows: `scoop` fallback if available
649
+ * 4. Universal user-local fallback in `<dataDir>/cli` via DSH's bundled `packageManager` (pnpm) or `npm`
650
+ */
651
+ export async function installAgentDeckDaemon({
652
+ dataDir = getAgentDeckDataDir(),
653
+ platform = process.platform,
654
+ env = process.env,
655
+ home = homedir(),
656
+ packageManager = null,
657
+ } = {}) {
658
+ const existing = findAgentDeckDaemon({ dataDir, platform, env, home });
659
+ if (existing) {
660
+ return { installed: false, method: 'existing', binaryPath: existing };
661
+ }
662
+
663
+ const errors = [];
664
+ const brewBin =
665
+ platform === 'darwin' || platform === 'linux'
666
+ ? findExecutable('brew', { platform, env, home })
667
+ : null;
668
+ const npmBin = findExecutable('npm', { platform, env, home });
669
+ const scoopBin =
670
+ platform === 'win32'
671
+ ? findExecutable('scoop', { platform, env, home })
672
+ : null;
673
+
674
+ const tryBrew = async () => {
675
+ if (!brewBin) return null;
676
+ const res = await runCommand(
677
+ brewBin,
678
+ ['install', 'mantou132/tap/agentdeckd'],
679
+ {
680
+ env: { ...env, HOMEBREW_NO_AUTO_UPDATE: '1', HOMEBREW_NO_ENV_HINTS: '1' },
681
+ timeoutMs: 240_000,
682
+ },
683
+ );
684
+ if (res.code === 0) {
685
+ const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
686
+ if (bin) return { installed: true, method: 'homebrew', binaryPath: bin };
687
+ }
688
+ errors.push(
689
+ `brew: ${(res.stderr || res.stdout || `exit ${res.code}`).trim().slice(-240)}`,
690
+ );
691
+ return null;
692
+ };
693
+
694
+ const tryNpmGlobal = async () => {
695
+ if (!npmBin) return null;
696
+ const res = await runCommand(
697
+ npmBin,
698
+ ['install', '-g', 'agentdeckd', '--include=optional'],
699
+ { env, timeoutMs: 180_000 },
700
+ );
701
+ if (res.code === 0) {
702
+ const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
703
+ if (bin) return { installed: true, method: 'npm-global', binaryPath: bin };
704
+ }
705
+ errors.push(
706
+ `npm -g: ${(res.stderr || res.stdout || `exit ${res.code}`).trim().slice(-240)}`,
707
+ );
708
+ return null;
709
+ };
710
+
711
+ const tryScoop = async () => {
712
+ if (!scoopBin) return null;
713
+ await runCommand(
714
+ scoopBin,
715
+ ['bucket', 'add', 'mantou132', 'https://github.com/mantou132/scoop-bucket'],
716
+ { env, timeoutMs: 60_000 },
717
+ );
718
+ const res = await runCommand(scoopBin, ['install', 'agentdeckd'], {
719
+ env,
720
+ timeoutMs: 180_000,
721
+ });
722
+ if (res.code === 0) {
723
+ const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
724
+ if (bin) return { installed: true, method: 'scoop', binaryPath: bin };
725
+ }
726
+ errors.push(
727
+ `scoop: ${(res.stderr || res.stdout || `exit ${res.code}`).trim().slice(-240)}`,
728
+ );
729
+ return null;
730
+ };
731
+
732
+ const tryLocalPrefix = async () => {
733
+ const cliDir = join(dataDir, 'cli');
734
+ mkdirSync(cliDir, { recursive: true });
735
+ const pkgPath = join(cliDir, 'package.json');
736
+ if (!existsSync(pkgPath)) {
737
+ writeFileAtomic(
738
+ pkgPath,
739
+ `${JSON.stringify({ name: 'agentdeck-cli', private: true }, null, 2)}\n`,
740
+ );
741
+ }
742
+
743
+ if (packageManager?.command) {
744
+ const res = await runCommand(
745
+ packageManager.command,
746
+ [...(packageManager.args || []), 'add', 'agentdeckd'],
747
+ {
748
+ cwd: cliDir,
749
+ env: { ...env, ...(packageManager.env || {}) },
750
+ timeoutMs: 180_000,
751
+ },
752
+ );
753
+ if (res.code === 0) {
754
+ const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
755
+ if (bin) {
756
+ return { installed: true, method: 'local-pnpm', binaryPath: bin };
757
+ }
758
+ }
759
+ errors.push(
760
+ `bundled pnpm: ${(res.stderr || res.stdout || `exit ${res.code}`).trim().slice(-240)}`,
761
+ );
762
+ }
763
+
764
+ if (npmBin) {
765
+ const res = await runCommand(
766
+ npmBin,
767
+ ['install', '--prefix', cliDir, 'agentdeckd', '--include=optional'],
768
+ { env, timeoutMs: 180_000 },
769
+ );
770
+ if (res.code === 0) {
771
+ const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
772
+ if (bin) {
773
+ return { installed: true, method: 'local-npm', binaryPath: bin };
774
+ }
775
+ }
776
+ errors.push(
777
+ `local npm: ${(res.stderr || res.stdout || `exit ${res.code}`).trim().slice(-240)}`,
778
+ );
779
+ }
780
+ return null;
781
+ };
782
+
783
+ const attempts =
784
+ platform === 'darwin'
785
+ ? [tryBrew, tryNpmGlobal, tryLocalPrefix]
786
+ : platform === 'win32'
787
+ ? [tryNpmGlobal, tryScoop, tryLocalPrefix]
788
+ : [tryNpmGlobal, tryBrew, tryLocalPrefix];
789
+
790
+ for (const attempt of attempts) {
791
+ try {
792
+ const result = await attempt();
793
+ if (result) return result;
794
+ } catch (err) {
795
+ errors.push(err instanceof Error ? err.message : String(err));
796
+ }
797
+ }
798
+
799
+ throw new Error(
800
+ `Failed to install agentdeckd automatically. ${errors.join(' | ')}`,
801
+ );
802
+ }
803
+
804
+ /**
805
+ * Control the local `agentdeckd` autostart service (`start` / `stop` / `restart`).
806
+ * `agentdeckd start` registers OS autostart (launchd / systemd / Task Scheduler),
807
+ * starts the background daemon, and creates `daemon.json` with a Pairing ID.
808
+ */
809
+ export async function controlAgentDeckDaemon({
810
+ action,
811
+ profileName = 'web',
812
+ dshHome = join(homedir(), '.dsh'),
813
+ sourcePatchPath = null,
814
+ dataDir = getAgentDeckDataDir(),
815
+ platform = process.platform,
816
+ packageManager = null,
817
+ } = {}) {
818
+ if (!['start', 'stop', 'restart'].includes(action)) {
819
+ throw new Error(`Unsupported daemon action: ${action}`);
820
+ }
821
+
822
+ let binaryPath = findAgentDeckDaemon({ dataDir, platform });
823
+ if (!binaryPath && action === 'start') {
824
+ const installed = await installAgentDeckDaemon({
825
+ dataDir,
826
+ platform,
827
+ packageManager,
828
+ });
829
+ binaryPath = installed.binaryPath;
830
+ }
831
+ if (!binaryPath) {
832
+ throw new Error(
833
+ 'Could not locate the `agentdeckd` executable. Click One-Click Setup first.',
834
+ );
835
+ }
836
+
837
+ const res = await runCommand(binaryPath, [action], { timeoutMs: 30_000 });
838
+ if (res.code !== 0) {
839
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
840
+ throw new Error(
841
+ `agentdeckd ${action} failed (exit ${res.code})${detail ? `: ${detail}` : ''}`,
842
+ );
843
+ }
844
+
845
+ // Wait briefly for daemon.lock / daemon.json to settle
846
+ const expectRunning = action !== 'stop';
847
+ for (let i = 0; i < 10; i++) {
848
+ const daemonState = await readDaemonState(dataDir, { platform });
849
+ if (daemonState.running === expectRunning) break;
850
+ await sleep(200);
851
+ }
852
+
853
+ const status = await getAgentDeckStatus({
854
+ profileName,
855
+ dshHome,
856
+ sourcePatchPath,
857
+ dataDir,
858
+ platform,
859
+ });
860
+
861
+ return { ok: true, action, status };
862
+ }
863
+
864
+ export async function getAgentDeckStatus({
865
+ profileName = 'web',
866
+ dshHome = join(homedir(), '.dsh'),
867
+ sourcePatchPath = null,
868
+ dataDir = getAgentDeckDataDir(),
869
+ platform = process.platform,
870
+ } = {}) {
871
+ const acpPatchPath = join(dshHome, 'profiles', 'acp', 'cordis.patch.yml');
872
+ const customAgentsPath = join(dataDir, 'custom_agents.json');
873
+ const dshCommand = resolveDshCommand({ platform });
874
+ const acpPlugin = readAcpPluginState(dshHome);
875
+ const sourceModel = extractModelSummary(sourcePatchPath);
876
+ const acpModel = extractModelSummary(acpPatchPath);
877
+ const customAgent = readCustomAgentState(customAgentsPath);
878
+ const daemon = await readDaemonState(dataDir, { platform });
879
+
880
+ const modelMismatch = Boolean(
881
+ sourceModel.defaultModel &&
882
+ acpModel.defaultModel &&
883
+ (sourceModel.defaultModel.provider !== acpModel.defaultModel.provider ||
884
+ sourceModel.defaultModel.model !== acpModel.defaultModel.model),
885
+ );
886
+
887
+ const acpNeedsProviderPin = Boolean(
888
+ acpModel.defaultModel?.provider &&
889
+ !BUILTIN_DEEPSEEK_PROVIDERS.has(acpModel.defaultModel.provider) &&
890
+ acpModel.acpPlugin?.provider !== acpModel.defaultModel.provider,
891
+ );
892
+
893
+ const ready = Boolean(
894
+ acpPlugin.installed &&
895
+ customAgent.configured &&
896
+ !acpNeedsProviderPin &&
897
+ daemon.running &&
898
+ daemon.pairedReady,
899
+ );
900
+
901
+ return {
902
+ platform,
903
+ profileName,
904
+ dshHome,
905
+ dshCommand,
906
+ ready,
907
+ acpPlugin,
908
+ models: {
909
+ source: sourceModel,
910
+ acp: acpModel,
911
+ mismatch: modelMismatch,
912
+ acpNeedsProviderPin,
913
+ },
914
+ customAgent,
915
+ daemon,
916
+ };
917
+ }
918
+
919
+ export async function runAgentDeckSetup({
920
+ profileName = 'web',
921
+ dshHome = join(homedir(), '.dsh'),
922
+ sourcePatchPath = null,
923
+ dataDir = getAgentDeckDataDir(),
924
+ syncModels = false,
925
+ platform = process.platform,
926
+ packageManager = null,
927
+ } = {}) {
928
+ const steps = [];
929
+ const dshCommand = resolveDshCommand({ platform });
930
+ if (!dshCommand) {
931
+ throw new Error(
932
+ 'Could not locate the `dsh` executable. Install DeepSeek Harness CLI or add `dsh` to your PATH.',
933
+ );
934
+ }
935
+
936
+ // Step 1: Ensure interactive ACP adapter is installed in the `acp` profile
937
+ const acpState = readAcpPluginState(dshHome);
938
+ if (acpState.installed) {
939
+ steps.push({
940
+ id: 'acp-plugin',
941
+ status: 'skipped',
942
+ detail: `${acpState.packageName}@${acpState.version}`,
943
+ });
944
+ } else {
945
+ const result = await runCommand(
946
+ dshCommand,
947
+ ['plugin', '--profile', 'acp', 'add', DEFAULT_ACP_PLUGIN],
948
+ {
949
+ env: { ...process.env, DSH_HOME: dshHome },
950
+ },
951
+ );
952
+ if (result.code !== 0) {
953
+ const detail = (result.stderr || result.stdout || '').trim().slice(-600);
954
+ throw new Error(
955
+ `Failed to install ${DEFAULT_ACP_PLUGIN} (exit ${result.code})${detail ? `: ${detail}` : ''}`,
956
+ );
957
+ }
958
+ steps.push({
959
+ id: 'acp-plugin',
960
+ status: 'installed',
961
+ detail: DEFAULT_ACP_PLUGIN,
962
+ });
963
+ }
964
+
965
+ // Step 2: Sync model/provider config into `acp/cordis.patch.yml`
966
+ const acpPatchPath = join(dshHome, 'profiles', 'acp', 'cordis.patch.yml');
967
+ const syncResult = syncAcpPatch({
968
+ sourcePatchPath,
969
+ acpPatchPath,
970
+ syncModels,
971
+ });
972
+ steps.push({
973
+ id: 'model-sync',
974
+ status: syncResult.changed ? 'updated' : 'unchanged',
975
+ detail: acpPatchPath,
976
+ });
977
+
978
+ // Step 3: Upsert `dsh` entry in AgentDeck's `custom_agents.json`
979
+ const customAgentsPath = join(dataDir, 'custom_agents.json');
980
+ const entry = upsertCustomAgent({ customAgentsPath, dshCommand });
981
+ steps.push({
982
+ id: 'custom-agents',
983
+ status: 'updated',
984
+ detail: `${entry.command} ${entry.args.join(' ')}`,
985
+ });
986
+
987
+ // Step 4: Install `agentdeckd` if not already installed or running
988
+ const daemonBefore = await readDaemonState(dataDir, { platform });
989
+ let daemonBin = daemonBefore.binaryPath;
990
+ if (daemonBefore.running) {
991
+ steps.push({
992
+ id: 'agentdeckd-install',
993
+ status: 'skipped',
994
+ detail: daemonBin || `running (PID ${daemonBefore.pid})`,
995
+ });
996
+ steps.push({
997
+ id: 'agentdeckd-autostart',
998
+ status: 'skipped',
999
+ detail: `PID ${daemonBefore.pid}`,
1000
+ });
1001
+ } else {
1002
+ if (!daemonBin) {
1003
+ const installRes = await installAgentDeckDaemon({
1004
+ dataDir,
1005
+ platform,
1006
+ packageManager,
1007
+ });
1008
+ daemonBin = installRes.binaryPath;
1009
+ steps.push({
1010
+ id: 'agentdeckd-install',
1011
+ status: installRes.installed ? 'installed' : 'skipped',
1012
+ detail: `${installRes.method}: ${daemonBin}`,
1013
+ });
1014
+ } else {
1015
+ steps.push({
1016
+ id: 'agentdeckd-install',
1017
+ status: 'skipped',
1018
+ detail: daemonBin,
1019
+ });
1020
+ }
1021
+
1022
+ // Step 5: Register autostart service & start `agentdeckd`
1023
+ const startRes = await runCommand(daemonBin, ['start'], {
1024
+ timeoutMs: 30_000,
1025
+ });
1026
+ if (startRes.code !== 0) {
1027
+ const detail = (startRes.stderr || startRes.stdout || '').trim().slice(-400);
1028
+ throw new Error(
1029
+ `agentdeckd start failed (exit ${startRes.code})${detail ? `: ${detail}` : ''}`,
1030
+ );
1031
+ }
1032
+ for (let i = 0; i < 10; i++) {
1033
+ const check = await readDaemonState(dataDir, { platform });
1034
+ if (check.running && check.pairedReady) break;
1035
+ await sleep(200);
1036
+ }
1037
+ steps.push({
1038
+ id: 'agentdeckd-autostart',
1039
+ status: 'started',
1040
+ detail: 'autostart enabled',
1041
+ });
1042
+ }
1043
+
1044
+ const status = await getAgentDeckStatus({
1045
+ profileName,
1046
+ dshHome,
1047
+ sourcePatchPath,
1048
+ dataDir,
1049
+ platform,
1050
+ });
1051
+
1052
+ return { ok: true, steps, status };
1053
+ }