dsh-plugin-agentdeck 0.1.0 → 0.2.1

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 CHANGED
@@ -5,7 +5,11 @@ import {
5
5
  existsSync,
6
6
  mkdirSync,
7
7
  readFileSync,
8
+ realpathSync,
9
+ chmodSync,
8
10
  renameSync,
11
+ statSync,
12
+ unlinkSync,
9
13
  writeFileSync,
10
14
  } from 'node:fs';
11
15
  import { arch, homedir } from 'node:os';
@@ -21,6 +25,7 @@ export const ACP_PLUGIN_PACKAGES = [
21
25
  '@cnctem/dsh-acp',
22
26
  ];
23
27
  export const DEFAULT_ACP_PLUGIN = '@openma/deepseek-harness-acp@latest';
28
+ export const AWAKE_MODES = ['never', 'plugged', 'active', 'always'];
24
29
 
25
30
  const BUILTIN_DEEPSEEK_PROVIDERS = new Set([
26
31
  'deepseek-official',
@@ -112,14 +117,17 @@ export function findExecutable(
112
117
  ? [`${name}.exe`, `${name}.cmd`, `${name}.bat`, name]
113
118
  : [name];
114
119
  const pathDirs = (env.PATH || '').split(delimiter).filter(Boolean);
120
+ const nodeBinDir = dirname(process.execPath);
115
121
  const fallbackDirs =
116
122
  platform === 'win32'
117
123
  ? [
124
+ nodeBinDir,
118
125
  join(home, 'scoop', 'shims'),
119
126
  join(env.APPDATA || join(home, 'AppData', 'Roaming'), 'npm'),
120
127
  join(home, '.cargo', 'bin'),
121
128
  ]
122
129
  : [
130
+ nodeBinDir,
123
131
  join(home, '.local', 'bin'),
124
132
  '/opt/homebrew/bin',
125
133
  '/usr/local/bin',
@@ -158,8 +166,9 @@ export function findAgentDeckDaemon({
158
166
  platform = process.platform,
159
167
  env = process.env,
160
168
  home = homedir(),
169
+ extraDirs = [],
161
170
  } = {}) {
162
- const onPath = findExecutable('agentdeckd', { platform, env, home });
171
+ const onPath = findExecutable('agentdeckd', { platform, env, home, extraDirs });
163
172
  if (onPath) return onPath;
164
173
 
165
174
  const cliDir = join(dataDir, 'cli');
@@ -236,11 +245,266 @@ function isPidAlive(pid) {
236
245
  }
237
246
  }
238
247
 
248
+ const AUTO_UPDATABLE_METHODS = new Set([
249
+ 'local',
250
+ 'homebrew',
251
+ 'npm-global',
252
+ 'pnpm-global',
253
+ 'scoop',
254
+ ]);
255
+ const LATEST_VERSION_CACHE_TTL_MS = 10 * 60 * 1000;
256
+ const NPM_LATEST_URL = 'https://registry.npmjs.org/agentdeckd/latest';
257
+ const GITHUB_LATEST_URL =
258
+ 'https://api.github.com/repos/mantou132/AgentDeck/releases/latest';
259
+
260
+ const daemonVersionCache = new Map();
261
+ let latestVersionCache = { version: null, fetchedAt: 0 };
262
+
263
+ export function clearDaemonVersionCaches() {
264
+ daemonVersionCache.clear();
265
+ latestVersionCache = { version: null, fetchedAt: 0 };
266
+ }
267
+
268
+ export function parseSemver(raw) {
269
+ if (typeof raw !== 'string') return null;
270
+ const match = raw.match(/\bv?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?\b/);
271
+ if (!match) return null;
272
+ const major = Number.parseInt(match[1], 10);
273
+ const minor = Number.parseInt(match[2], 10);
274
+ const patch = Number.parseInt(match[3], 10);
275
+ const prerelease = match[4] || null;
276
+ return {
277
+ version: `${major}.${minor}.${patch}${prerelease ? `-${prerelease}` : ''}`,
278
+ major,
279
+ minor,
280
+ patch,
281
+ prerelease,
282
+ };
283
+ }
284
+
285
+ export function compareSemver(aRaw, bRaw) {
286
+ const a = typeof aRaw === 'string' ? parseSemver(aRaw) : aRaw;
287
+ const b = typeof bRaw === 'string' ? parseSemver(bRaw) : bRaw;
288
+ if (!a || !b) return 0;
289
+ if (a.major !== b.major) return a.major > b.major ? 1 : -1;
290
+ if (a.minor !== b.minor) return a.minor > b.minor ? 1 : -1;
291
+ if (a.patch !== b.patch) return a.patch > b.patch ? 1 : -1;
292
+ if (!a.prerelease && !b.prerelease) return 0;
293
+ if (!a.prerelease) return 1;
294
+ if (!b.prerelease) return -1;
295
+ const aParts = a.prerelease.split('.');
296
+ const bParts = b.prerelease.split('.');
297
+ const len = Math.max(aParts.length, bParts.length);
298
+ for (let i = 0; i < len; i++) {
299
+ const ap = aParts[i];
300
+ const bp = bParts[i];
301
+ if (ap === undefined) return -1;
302
+ if (bp === undefined) return 1;
303
+ if (ap === bp) continue;
304
+ const aNum = /^\d+$/.test(ap);
305
+ const bNum = /^\d+$/.test(bp);
306
+ if (aNum && bNum) return Number(ap) > Number(bp) ? 1 : -1;
307
+ if (aNum !== bNum) return aNum ? -1 : 1;
308
+ return ap > bp ? 1 : -1;
309
+ }
310
+ return 0;
311
+ }
312
+
313
+ function normalizePathForMatch(p, platform = process.platform) {
314
+ const normalized = String(p || '').replace(/\\/g, '/');
315
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
316
+ }
317
+
318
+ export function detectDaemonInstallMethod(
319
+ binaryPath,
320
+ {
321
+ dataDir = getAgentDeckDataDir(),
322
+ platform = process.platform,
323
+ home = homedir(),
324
+ } = {},
325
+ ) {
326
+ if (!binaryPath) return 'none';
327
+ let resolvedPath = binaryPath;
328
+ try {
329
+ resolvedPath = realpathSync(binaryPath);
330
+ } catch {
331
+ // Keep original path if symlink resolution fails
332
+ }
333
+
334
+ const binNorm = normalizePathForMatch(binaryPath, platform);
335
+ const realNorm = normalizePathForMatch(resolvedPath, platform);
336
+ const cliDirNorm = normalizePathForMatch(join(dataDir, 'cli'), platform).replace(
337
+ /\/+$/,
338
+ '',
339
+ );
340
+
341
+ if (
342
+ binNorm.startsWith(`${cliDirNorm}/`) ||
343
+ realNorm.startsWith(`${cliDirNorm}/`)
344
+ ) {
345
+ return 'local';
346
+ }
347
+
348
+ const brewPattern = /(?:^|\/)(?:cellar\/agentdeckd|homebrew|linuxbrew)\//i;
349
+ if (brewPattern.test(realNorm) || brewPattern.test(binNorm)) {
350
+ return 'homebrew';
351
+ }
352
+
353
+ if (
354
+ platform === 'win32' &&
355
+ (/\/scoop\//i.test(binNorm) || /\/scoop\//i.test(realNorm))
356
+ ) {
357
+ return 'scoop';
358
+ }
359
+
360
+ const cargoBinNorm = normalizePathForMatch(
361
+ join(home, '.cargo', 'bin'),
362
+ platform,
363
+ ).replace(/\/+$/, '');
364
+ if (
365
+ binNorm.startsWith(`${cargoBinNorm}/`) ||
366
+ realNorm.startsWith(`${cargoBinNorm}/`)
367
+ ) {
368
+ return 'cargo';
369
+ }
370
+
371
+ if (/\/pnpm\//i.test(binNorm) || /\/pnpm\//i.test(realNorm)) {
372
+ return 'pnpm-global';
373
+ }
374
+
375
+ if (
376
+ realNorm.includes('/node_modules/') ||
377
+ binNorm.includes('/node_modules/') ||
378
+ existsSync(join(dirname(binaryPath), 'node_modules', 'agentdeckd'))
379
+ ) {
380
+ return 'npm-global';
381
+ }
382
+
383
+ return 'unknown';
384
+ }
385
+
386
+ export async function readDaemonVersion(binaryPath) {
387
+ if (!binaryPath) return null;
388
+ let cacheKey = binaryPath;
389
+ let mtimeMs = 0;
390
+ try {
391
+ const real = realpathSync(binaryPath);
392
+ cacheKey = real;
393
+ mtimeMs = statSync(real).mtimeMs;
394
+ } catch {
395
+ try {
396
+ mtimeMs = statSync(binaryPath).mtimeMs;
397
+ } catch {
398
+ return null;
399
+ }
400
+ }
401
+
402
+ const cached = daemonVersionCache.get(cacheKey);
403
+ if (cached && cached.mtimeMs === mtimeMs) {
404
+ return cached.version;
405
+ }
406
+
407
+ try {
408
+ const res = await runCommand(binaryPath, ['--version'], { timeoutMs: 5_000 });
409
+ const parsed = parseSemver(`${res.stdout}\n${res.stderr}`);
410
+ const version = parsed ? parsed.version : null;
411
+ daemonVersionCache.set(cacheKey, { mtimeMs, version });
412
+ return version;
413
+ } catch {
414
+ return null;
415
+ }
416
+ }
417
+
418
+ export async function fetchLatestDaemonVersion({
419
+ force = false,
420
+ fetchImpl = globalThis.fetch,
421
+ timeoutMs = 5_000,
422
+ } = {}) {
423
+ const now = Date.now();
424
+ if (
425
+ !force &&
426
+ latestVersionCache.version &&
427
+ now - latestVersionCache.fetchedAt < LATEST_VERSION_CACHE_TTL_MS
428
+ ) {
429
+ return latestVersionCache.version;
430
+ }
431
+ if (typeof fetchImpl !== 'function') return latestVersionCache.version;
432
+
433
+ const tryJsonUrl = async (url, extractor) => {
434
+ const controller = new AbortController();
435
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
436
+ try {
437
+ const res = await fetchImpl(url, {
438
+ signal: controller.signal,
439
+ headers: { accept: 'application/json' },
440
+ });
441
+ if (!res.ok) return null;
442
+ const data = await res.json();
443
+ const parsed = parseSemver(extractor(data));
444
+ return parsed ? parsed.version : null;
445
+ } catch {
446
+ return null;
447
+ } finally {
448
+ clearTimeout(timer);
449
+ }
450
+ };
451
+
452
+ let version = await tryJsonUrl(NPM_LATEST_URL, (d) => d?.version);
453
+ if (!version) {
454
+ version = await tryJsonUrl(GITHUB_LATEST_URL, (d) => d?.tag_name);
455
+ }
456
+
457
+ if (version) {
458
+ latestVersionCache = { version, fetchedAt: now };
459
+ }
460
+ return version;
461
+ }
462
+
463
+ export async function checkDaemonUpdate({
464
+ dataDir = getAgentDeckDataDir(),
465
+ platform = process.platform,
466
+ env = process.env,
467
+ home = homedir(),
468
+ force = false,
469
+ fetchImpl = globalThis.fetch,
470
+ } = {}) {
471
+ const binaryPath = findAgentDeckDaemon({ dataDir, platform, env, home });
472
+ const installMethod = detectDaemonInstallMethod(binaryPath, {
473
+ dataDir,
474
+ platform,
475
+ home,
476
+ });
477
+ const canUpdate = AUTO_UPDATABLE_METHODS.has(installMethod);
478
+ const [currentVersion, latestVersion] = await Promise.all([
479
+ readDaemonVersion(binaryPath),
480
+ fetchLatestDaemonVersion({ force, fetchImpl }),
481
+ ]);
482
+ const updateAvailable = Boolean(
483
+ currentVersion &&
484
+ latestVersion &&
485
+ compareSemver(latestVersion, currentVersion) > 0,
486
+ );
487
+ return {
488
+ currentVersion,
489
+ latestVersion,
490
+ updateAvailable,
491
+ installMethod,
492
+ canUpdate,
493
+ };
494
+ }
495
+
239
496
  export async function readDaemonState(
240
497
  dataDir,
241
498
  { platform = process.platform, env = process.env, home = homedir() } = {},
242
499
  ) {
243
500
  const binaryPath = findAgentDeckDaemon({ dataDir, platform, env, home });
501
+ const installMethod = detectDaemonInstallMethod(binaryPath, {
502
+ dataDir,
503
+ platform,
504
+ home,
505
+ });
506
+ const canUpdate = AUTO_UPDATABLE_METHODS.has(installMethod);
507
+ const version = binaryPath ? await readDaemonVersion(binaryPath) : null;
244
508
  const configPath = join(dataDir, 'daemon.json');
245
509
  const lockPath = join(dataDir, 'daemon.lock');
246
510
 
@@ -261,6 +525,7 @@ export async function readDaemonState(
261
525
  let relayId = null;
262
526
  let relayUrl = DEFAULT_RELAY_URL;
263
527
  let hasCustomRelay = false;
528
+ let awakeMode = 'never';
264
529
  if (existsSync(configPath)) {
265
530
  try {
266
531
  const raw = JSON.parse(readFileSync(configPath, 'utf8'));
@@ -275,11 +540,29 @@ export async function readDaemonState(
275
540
  relayUrl = raw.relay_url.trim();
276
541
  hasCustomRelay = relayUrl !== DEFAULT_RELAY_URL;
277
542
  }
543
+ if (typeof raw?.awake === 'string' && AWAKE_MODES.includes(raw.awake)) {
544
+ awakeMode = raw.awake;
545
+ }
278
546
  } catch {
279
547
  // Ignore corrupt daemon.json
280
548
  }
281
549
  }
282
550
 
551
+ const awakeStatusPath = join(dataDir, 'awake_status.json');
552
+ let awakeActive = false;
553
+ let awakeError = null;
554
+ if (running && existsSync(awakeStatusPath)) {
555
+ try {
556
+ const st = JSON.parse(readFileSync(awakeStatusPath, 'utf8'));
557
+ if (st?.pid === pid && st?.mode === awakeMode) {
558
+ awakeActive = Boolean(st.on);
559
+ awakeError = typeof st.error === 'string' ? st.error : null;
560
+ }
561
+ } catch {
562
+ // Ignore unreadable awake_status.json
563
+ }
564
+ }
565
+
283
566
  let qrSvg = null;
284
567
  let maskedPairingId = null;
285
568
  if (relayId) {
@@ -294,6 +577,9 @@ export async function readDaemonState(
294
577
  return {
295
578
  installed: Boolean(binaryPath) || running,
296
579
  binaryPath,
580
+ version,
581
+ installMethod,
582
+ canUpdate,
297
583
  running,
298
584
  pid: running ? pid : null,
299
585
  pairedReady: Boolean(relayId),
@@ -301,6 +587,11 @@ export async function readDaemonState(
301
587
  relayUrl,
302
588
  hasCustomRelay,
303
589
  qrSvg,
590
+ awake: {
591
+ mode: awakeMode,
592
+ active: awakeActive,
593
+ error: awakeError,
594
+ },
304
595
  };
305
596
  }
306
597
 
@@ -429,11 +720,38 @@ export function extractModelSummary(patchPath) {
429
720
  }
430
721
  }
431
722
 
432
- function writeFileAtomic(filePath, content) {
723
+ function writeFileAtomic(filePath, content, { mode } = {}) {
433
724
  mkdirSync(dirname(filePath), { recursive: true });
725
+ let targetMode = mode;
726
+ if (targetMode === undefined && existsSync(filePath)) {
727
+ try {
728
+ targetMode = statSync(filePath).mode & 0o777;
729
+ } catch {
730
+ // Fall back to default umask
731
+ }
732
+ }
434
733
  const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
435
- writeFileSync(tmpPath, content, 'utf8');
436
- renameSync(tmpPath, filePath);
734
+ try {
735
+ writeFileSync(tmpPath, content, {
736
+ encoding: 'utf8',
737
+ ...(targetMode !== undefined ? { mode: targetMode } : {}),
738
+ });
739
+ if (targetMode !== undefined && process.platform !== 'win32') {
740
+ try {
741
+ chmodSync(tmpPath, targetMode);
742
+ } catch {
743
+ // Ignore chmod failure on unsupported filesystems
744
+ }
745
+ }
746
+ renameSync(tmpPath, filePath);
747
+ } catch (err) {
748
+ try {
749
+ unlinkSync(tmpPath);
750
+ } catch {
751
+ // Ignore cleanup failure
752
+ }
753
+ throw err;
754
+ }
437
755
  }
438
756
 
439
757
  /**
@@ -603,11 +921,14 @@ function runCommand(
603
921
  { cwd, env = process.env, timeoutMs = 180_000 } = {},
604
922
  ) {
605
923
  return new Promise((resolvePromise, reject) => {
924
+ const needsWindowsShell =
925
+ process.platform === 'win32' && /\.(cmd|bat)$/i.test(command);
606
926
  const child = spawn(command, args, {
607
927
  cwd,
608
928
  env,
609
929
  stdio: ['ignore', 'pipe', 'pipe'],
610
930
  windowsHide: true,
931
+ shell: needsWindowsShell,
611
932
  });
612
933
  let stdout = '';
613
934
  let stderr = '';
@@ -699,7 +1020,26 @@ export async function installAgentDeckDaemon({
699
1020
  { env, timeoutMs: 180_000 },
700
1021
  );
701
1022
  if (res.code === 0) {
702
- const bin = findAgentDeckDaemon({ dataDir, platform, env, home });
1023
+ const npmExtraDirs = [dirname(npmBin)];
1024
+ try {
1025
+ const prefixRes = await runCommand(npmBin, ['prefix', '-g'], {
1026
+ env,
1027
+ timeoutMs: 15_000,
1028
+ });
1029
+ const prefix = prefixRes.code === 0 ? prefixRes.stdout.trim() : '';
1030
+ if (prefix) {
1031
+ npmExtraDirs.push(platform === 'win32' ? prefix : join(prefix, 'bin'));
1032
+ }
1033
+ } catch {
1034
+ // Ignore prefix lookup failure
1035
+ }
1036
+ const bin = findAgentDeckDaemon({
1037
+ dataDir,
1038
+ platform,
1039
+ env,
1040
+ home,
1041
+ extraDirs: npmExtraDirs,
1042
+ });
703
1043
  if (bin) return { installed: true, method: 'npm-global', binaryPath: bin };
704
1044
  }
705
1045
  errors.push(
@@ -861,21 +1201,267 @@ export async function controlAgentDeckDaemon({
861
1201
  return { ok: true, action, status };
862
1202
  }
863
1203
 
1204
+ /**
1205
+ * Upgrade the local `agentdeckd` installation using the package manager that
1206
+ * installed it, following AgentDeck's stop -> upgrade -> start workflow.
1207
+ * Never runs automatically on startup — only triggered explicitly by the user.
1208
+ */
1209
+ export async function upgradeAgentDeckDaemon({
1210
+ profileName = 'web',
1211
+ dshHome = join(homedir(), '.dsh'),
1212
+ sourcePatchPath = null,
1213
+ dataDir = getAgentDeckDataDir(),
1214
+ platform = process.platform,
1215
+ env = process.env,
1216
+ home = homedir(),
1217
+ packageManager = null,
1218
+ runCommandImpl = runCommand,
1219
+ } = {}) {
1220
+ const daemonBefore = await readDaemonState(dataDir, { platform, env, home });
1221
+ let binaryPath = daemonBefore.binaryPath;
1222
+ if (!binaryPath) {
1223
+ const installed = await installAgentDeckDaemon({
1224
+ dataDir,
1225
+ platform,
1226
+ env,
1227
+ home,
1228
+ packageManager,
1229
+ });
1230
+ clearDaemonVersionCaches();
1231
+ const status = await getAgentDeckStatus({
1232
+ profileName,
1233
+ dshHome,
1234
+ sourcePatchPath,
1235
+ dataDir,
1236
+ platform,
1237
+ env,
1238
+ home,
1239
+ });
1240
+ return {
1241
+ ok: true,
1242
+ method: installed.method,
1243
+ previousVersion: null,
1244
+ version: status.daemon.version,
1245
+ status,
1246
+ };
1247
+ }
1248
+
1249
+ const method = daemonBefore.installMethod;
1250
+ if (!AUTO_UPDATABLE_METHODS.has(method)) {
1251
+ throw new Error(
1252
+ `Cannot auto-update agentdeckd installed at ${binaryPath} (${method}). Please update it manually.`,
1253
+ );
1254
+ }
1255
+
1256
+ const wasRunning = daemonBefore.running;
1257
+ const previousVersion = daemonBefore.version;
1258
+
1259
+ const waitForRunningState = async (expectRunning, attempts = 15) => {
1260
+ for (let i = 0; i < attempts; i++) {
1261
+ const check = await readDaemonState(dataDir, { platform, env, home });
1262
+ if (check.running === expectRunning) break;
1263
+ await sleep(200);
1264
+ }
1265
+ };
1266
+
1267
+ if (wasRunning) {
1268
+ const stopRes = await runCommandImpl(binaryPath, ['stop'], {
1269
+ env,
1270
+ timeoutMs: 30_000,
1271
+ });
1272
+ if (stopRes.code !== 0) {
1273
+ const detail = (stopRes.stderr || stopRes.stdout || '').trim().slice(-400);
1274
+ throw new Error(
1275
+ `agentdeckd stop failed before upgrade (exit ${stopRes.code})${detail ? `: ${detail}` : ''}`,
1276
+ );
1277
+ }
1278
+ await waitForRunningState(false);
1279
+ }
1280
+
1281
+ const runUpgradeCommand = async () => {
1282
+ if (method === 'local') {
1283
+ const cliDir = join(dataDir, 'cli');
1284
+ mkdirSync(cliDir, { recursive: true });
1285
+ if (packageManager?.command) {
1286
+ const res = await runCommandImpl(
1287
+ packageManager.command,
1288
+ [...(packageManager.args || []), 'add', 'agentdeckd@latest'],
1289
+ {
1290
+ cwd: cliDir,
1291
+ env: { ...env, ...(packageManager.env || {}) },
1292
+ timeoutMs: 180_000,
1293
+ },
1294
+ );
1295
+ if (res.code === 0) return;
1296
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1297
+ throw new Error(
1298
+ `Failed to upgrade agentdeckd via bundled package manager (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1299
+ );
1300
+ }
1301
+ const npmBin = findExecutable('npm', { platform, env, home });
1302
+ if (!npmBin) {
1303
+ throw new Error('Could not find npm to upgrade local agentdeckd.');
1304
+ }
1305
+ const res = await runCommandImpl(
1306
+ npmBin,
1307
+ ['install', '--prefix', cliDir, 'agentdeckd@latest', '--include=optional'],
1308
+ { env, timeoutMs: 180_000 },
1309
+ );
1310
+ if (res.code !== 0) {
1311
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1312
+ throw new Error(
1313
+ `Failed to upgrade local agentdeckd via npm (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1314
+ );
1315
+ }
1316
+ return;
1317
+ }
1318
+
1319
+ if (method === 'homebrew') {
1320
+ const brewBin = findExecutable('brew', { platform, env, home });
1321
+ if (!brewBin) {
1322
+ throw new Error('Could not find Homebrew (`brew`) to upgrade agentdeckd.');
1323
+ }
1324
+ const brewEnv = { ...env, HOMEBREW_NO_ENV_HINTS: '1' };
1325
+ delete brewEnv.HOMEBREW_NO_AUTO_UPDATE;
1326
+ const res = await runCommandImpl(
1327
+ brewBin,
1328
+ ['upgrade', 'mantou132/tap/agentdeckd'],
1329
+ { env: brewEnv, timeoutMs: 240_000 },
1330
+ );
1331
+ if (res.code !== 0) {
1332
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1333
+ throw new Error(
1334
+ `brew upgrade failed (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1335
+ );
1336
+ }
1337
+ return;
1338
+ }
1339
+
1340
+ if (method === 'pnpm-global') {
1341
+ const pnpmBin = findExecutable('pnpm', { platform, env, home });
1342
+ if (pnpmBin) {
1343
+ const res = await runCommandImpl(
1344
+ pnpmBin,
1345
+ ['add', '-g', 'agentdeckd@latest'],
1346
+ { env, timeoutMs: 180_000 },
1347
+ );
1348
+ if (res.code !== 0) {
1349
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1350
+ throw new Error(
1351
+ `pnpm global upgrade failed (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1352
+ );
1353
+ }
1354
+ return;
1355
+ }
1356
+ }
1357
+
1358
+ if (method === 'npm-global' || method === 'pnpm-global') {
1359
+ const npmBin = findExecutable('npm', { platform, env, home });
1360
+ if (!npmBin) {
1361
+ throw new Error('Could not find npm to upgrade global agentdeckd.');
1362
+ }
1363
+ const res = await runCommandImpl(
1364
+ npmBin,
1365
+ ['install', '-g', 'agentdeckd@latest', '--include=optional'],
1366
+ { env, timeoutMs: 180_000 },
1367
+ );
1368
+ if (res.code !== 0) {
1369
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1370
+ throw new Error(
1371
+ `npm global upgrade failed (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1372
+ );
1373
+ }
1374
+ return;
1375
+ }
1376
+
1377
+ if (method === 'scoop') {
1378
+ const scoopBin = findExecutable('scoop', { platform, env, home });
1379
+ if (!scoopBin) {
1380
+ throw new Error('Could not find Scoop to upgrade agentdeckd.');
1381
+ }
1382
+ const res = await runCommandImpl(scoopBin, ['update', 'agentdeckd'], {
1383
+ env,
1384
+ timeoutMs: 180_000,
1385
+ });
1386
+ if (res.code !== 0) {
1387
+ const detail = (res.stderr || res.stdout || '').trim().slice(-400);
1388
+ throw new Error(
1389
+ `scoop update failed (exit ${res.code})${detail ? `: ${detail}` : ''}`,
1390
+ );
1391
+ }
1392
+ }
1393
+ };
1394
+
1395
+ try {
1396
+ await runUpgradeCommand();
1397
+ } catch (err) {
1398
+ if (wasRunning) {
1399
+ try {
1400
+ const fallbackBin =
1401
+ findAgentDeckDaemon({ dataDir, platform, env, home }) || binaryPath;
1402
+ await runCommandImpl(fallbackBin, ['start'], { env, timeoutMs: 30_000 });
1403
+ } catch {
1404
+ // Best-effort restart of previous daemon on upgrade failure
1405
+ }
1406
+ }
1407
+ throw err;
1408
+ }
1409
+
1410
+ clearDaemonVersionCaches();
1411
+ const nextBinaryPath =
1412
+ findAgentDeckDaemon({ dataDir, platform, env, home }) || binaryPath;
1413
+
1414
+ if (wasRunning) {
1415
+ const startRes = await runCommandImpl(nextBinaryPath, ['start'], {
1416
+ env,
1417
+ timeoutMs: 30_000,
1418
+ });
1419
+ if (startRes.code !== 0) {
1420
+ const detail = (startRes.stderr || startRes.stdout || '').trim().slice(-400);
1421
+ throw new Error(
1422
+ `agentdeckd start failed after upgrade (exit ${startRes.code})${detail ? `: ${detail}` : ''}`,
1423
+ );
1424
+ }
1425
+ await waitForRunningState(true, 10);
1426
+ }
1427
+
1428
+ const status = await getAgentDeckStatus({
1429
+ profileName,
1430
+ dshHome,
1431
+ sourcePatchPath,
1432
+ dataDir,
1433
+ platform,
1434
+ env,
1435
+ home,
1436
+ });
1437
+
1438
+ return {
1439
+ ok: true,
1440
+ action: 'upgrade',
1441
+ method,
1442
+ previousVersion,
1443
+ version: status.daemon.version,
1444
+ status,
1445
+ };
1446
+ }
1447
+
864
1448
  export async function getAgentDeckStatus({
865
1449
  profileName = 'web',
866
1450
  dshHome = join(homedir(), '.dsh'),
867
1451
  sourcePatchPath = null,
868
1452
  dataDir = getAgentDeckDataDir(),
869
1453
  platform = process.platform,
1454
+ env = process.env,
1455
+ home = homedir(),
870
1456
  } = {}) {
871
1457
  const acpPatchPath = join(dshHome, 'profiles', 'acp', 'cordis.patch.yml');
872
1458
  const customAgentsPath = join(dataDir, 'custom_agents.json');
873
- const dshCommand = resolveDshCommand({ platform });
1459
+ const dshCommand = resolveDshCommand({ platform, env, home });
874
1460
  const acpPlugin = readAcpPluginState(dshHome);
875
1461
  const sourceModel = extractModelSummary(sourcePatchPath);
876
1462
  const acpModel = extractModelSummary(acpPatchPath);
877
1463
  const customAgent = readCustomAgentState(customAgentsPath);
878
- const daemon = await readDaemonState(dataDir, { platform });
1464
+ const daemon = await readDaemonState(dataDir, { platform, env, home });
879
1465
 
880
1466
  const modelMismatch = Boolean(
881
1467
  sourceModel.defaultModel &&
@@ -922,6 +1508,7 @@ export async function runAgentDeckSetup({
922
1508
  sourcePatchPath = null,
923
1509
  dataDir = getAgentDeckDataDir(),
924
1510
  syncModels = false,
1511
+ startDaemon = true,
925
1512
  platform = process.platform,
926
1513
  packageManager = null,
927
1514
  } = {}) {
@@ -1020,6 +1607,13 @@ export async function runAgentDeckSetup({
1020
1607
  }
1021
1608
 
1022
1609
  // Step 5: Register autostart service & start `agentdeckd`
1610
+ if (!startDaemon) {
1611
+ steps.push({
1612
+ id: 'agentdeckd-autostart',
1613
+ status: 'skipped',
1614
+ detail: 'stopped by user',
1615
+ });
1616
+ } else {
1023
1617
  const startRes = await runCommand(daemonBin, ['start'], {
1024
1618
  timeoutMs: 30_000,
1025
1619
  });
@@ -1039,6 +1633,7 @@ export async function runAgentDeckSetup({
1039
1633
  status: 'started',
1040
1634
  detail: 'autostart enabled',
1041
1635
  });
1636
+ }
1042
1637
  }
1043
1638
 
1044
1639
  const status = await getAgentDeckStatus({
@@ -1051,3 +1646,83 @@ export async function runAgentDeckSetup({
1051
1646
 
1052
1647
  return { ok: true, steps, status };
1053
1648
  }
1649
+
1650
+ /**
1651
+ * Update `daemon.json` `awake` mode atomically (preserving `relay_id`, `relay_url`,
1652
+ * and `features`). A running `agentdeckd` automatically hot-reloads this setting.
1653
+ */
1654
+ export async function setAgentDeckAwake({
1655
+ mode,
1656
+ profileName = 'web',
1657
+ dshHome = join(homedir(), '.dsh'),
1658
+ sourcePatchPath = null,
1659
+ dataDir = getAgentDeckDataDir(),
1660
+ platform = process.platform,
1661
+ } = {}) {
1662
+ if (!AWAKE_MODES.includes(mode)) {
1663
+ throw new Error(`Invalid awake mode "${mode}". Expected one of: ${AWAKE_MODES.join(', ')}`);
1664
+ }
1665
+
1666
+ const configPath = join(dataDir, 'daemon.json');
1667
+ let config = {};
1668
+ if (existsSync(configPath)) {
1669
+ try {
1670
+ const parsed = JSON.parse(readFileSync(configPath, 'utf8'));
1671
+ if (parsed && typeof parsed === 'object') config = parsed;
1672
+ } catch {
1673
+ throw new Error(`Invalid daemon config at ${configPath}`);
1674
+ }
1675
+ }
1676
+ config.awake = mode;
1677
+ writeFileAtomic(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
1678
+
1679
+ // If daemon is running, wait briefly for awake_status.json to reflect the new mode
1680
+ const awakeStatusPath = join(dataDir, 'awake_status.json');
1681
+ const lockPath = join(dataDir, 'daemon.lock');
1682
+ let runningPid = null;
1683
+ if (existsSync(lockPath)) {
1684
+ const p = Number.parseInt(readFileSync(lockPath, 'utf8').trim(), 10);
1685
+ if (isPidAlive(p)) runningPid = p;
1686
+ }
1687
+ if (runningPid) {
1688
+ for (let i = 0; i < 12; i++) {
1689
+ if (existsSync(awakeStatusPath)) {
1690
+ try {
1691
+ const st = JSON.parse(readFileSync(awakeStatusPath, 'utf8'));
1692
+ if (st?.pid === runningPid && st?.mode === mode) break;
1693
+ } catch {
1694
+ // Ignore transient read
1695
+ }
1696
+ }
1697
+ await sleep(100);
1698
+ }
1699
+ }
1700
+
1701
+ const status = await getAgentDeckStatus({
1702
+ profileName,
1703
+ dshHome,
1704
+ sourcePatchPath,
1705
+ dataDir,
1706
+ platform,
1707
+ });
1708
+ return { ok: true, mode, status };
1709
+ }
1710
+
1711
+ export async function syncAgentDeckModels({
1712
+ profileName = 'web',
1713
+ dshHome = join(homedir(), '.dsh'),
1714
+ sourcePatchPath = null,
1715
+ dataDir = getAgentDeckDataDir(),
1716
+ platform = process.platform,
1717
+ } = {}) {
1718
+ const acpPatchPath = join(dshHome, 'profiles', 'acp', 'cordis.patch.yml');
1719
+ syncAcpPatch({ sourcePatchPath, acpPatchPath, syncModels: true });
1720
+ const status = await getAgentDeckStatus({
1721
+ profileName,
1722
+ dshHome,
1723
+ sourcePatchPath,
1724
+ dataDir,
1725
+ platform,
1726
+ });
1727
+ return { ok: true, status };
1728
+ }