dsh-plugin-agentdeck 0.2.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/README.md CHANGED
@@ -4,6 +4,8 @@ Zero-config mobile remote control plugin for [DeepSeek Harness (`dsh`)](https://
4
4
 
5
5
  Control DeepSeek Harness from your **iPhone or Android** over native ACP — end-to-end encrypted (`XChaCha20-Poly1305`), with push notifications, file & diff viewing, terminal output, and zero tunnel/VPN setup.
6
6
 
7
+ ![AgentDeck Remote Control for DeepSeek Harness](assets/screenshot-overview.png)
8
+
7
9
  ## Zero-Click Setup
8
10
 
9
11
  Install the plugin and open **Settings → AgentDeck** — everything is provisioned automatically in the background on startup:
@@ -15,7 +17,7 @@ Install the plugin and open **Settings → AgentDeck** — everything is provisi
15
17
 
16
18
  The Settings tab stays minimal — just your **scannable pairing QR code** plus the 3 controls you actually need:
17
19
 
18
- 1. **Remote Service & Autostart** (`Start` / `Restart` / `Stop`)
20
+ 1. **Remote Service & Autostart** (`Start` / `Restart` / `Stop`, plus current `agentdeckd` version and manual one-click `Update` when a newer release is available)
19
21
  2. **Prevent Automatic Sleep** (`Off` / `On Power` / `Active 1h` / `Always`, hot-reloads without restarting)
20
22
  3. **Mobile Default Model** (shows active model; syncs with your current profile in one click if different)
21
23
 
@@ -49,7 +51,7 @@ Open **Settings → Plugins**, install `dsh-plugin-agentdeck`, then open **Setti
49
51
 
50
52
  打开 DSH 的 **设置 → AgentDeck 手机远控** 即可直接扫码配对,界面仅保留最核心的 3 项开关:
51
53
 
52
- 1. **远程服务与开机自启**(开启 / 重启 / 停止)
54
+ 1. **远程服务与开机自启**(开启 / 重启 / 停止,显示当前 `agentdeckd` 版本,有新版时提供手动一键更新)
53
55
  2. **防自动休眠**(关闭 / 插电常亮 / 活跃 1 小时 / 始终常亮,热重载生效)
54
56
  3. **手机端默认模型**(与当前界面不同时一键同步)
55
57
 
package/lib/client.js CHANGED
@@ -46,7 +46,10 @@ window.__ModuleLoader__.load({
46
46
  btnStart: 'Start',
47
47
  btnStop: 'Stop',
48
48
  btnRestart: 'Restart',
49
+ btnUpdate: 'Update',
50
+ btnUpdating: 'Updating…',
49
51
  btnWorking: 'Working…',
52
+ updateAvailable: 'Update available:',
50
53
  awakeTitle: 'Prevent Automatic Sleep',
51
54
  awakeActive: 'Active',
52
55
  awakeInactive: 'Inactive',
@@ -92,7 +95,10 @@ window.__ModuleLoader__.load({
92
95
  btnStart: '开启',
93
96
  btnStop: '停止',
94
97
  btnRestart: '重启',
98
+ btnUpdate: '更新',
99
+ btnUpdating: '更新中…',
95
100
  btnWorking: '处理中…',
101
+ updateAvailable: '有新版本:',
96
102
  awakeTitle: '防自动休眠',
97
103
  awakeActive: '生效中',
98
104
  awakeInactive: '未激活',
@@ -305,6 +311,12 @@ window.__ModuleLoader__.load({
305
311
  background: rgba(127, 127, 127, 0.14);
306
312
  color: var(--dsw-alias-label-secondary, #6b7280);
307
313
  }
314
+ .adk-version {
315
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
316
+ font-size: 11.5px;
317
+ font-weight: 400;
318
+ color: var(--dsw-alias-label-tertiary, #6b7280);
319
+ }
308
320
  .adk-actions {
309
321
  display: flex;
310
322
  align-items: center;
@@ -455,8 +467,10 @@ window.__ModuleLoader__.load({
455
467
  const isZh = t('isZh') === '1';
456
468
 
457
469
  const [status, setStatus] = useState(null);
470
+ const [updateInfo, setUpdateInfo] = useState(null);
458
471
  const [error, setError] = useState(null);
459
472
  const [busy, setBusy] = useState(false);
473
+ const [upgrading, setUpgrading] = useState(false);
460
474
 
461
475
  const loadStatus = useCallback(async () => {
462
476
  try {
@@ -471,10 +485,30 @@ window.__ModuleLoader__.load({
471
485
  }
472
486
  }, []);
473
487
 
488
+ const checkUpdate = useCallback(async ({ force = false } = {}) => {
489
+ try {
490
+ const url = force
491
+ ? 'api/agentdeck/update-check?force=1'
492
+ : 'api/agentdeck/update-check';
493
+ const res = await fetch(url, { cache: 'no-store' });
494
+ if (!res.ok) return;
495
+ const data = await res.json();
496
+ if (data?.ok) setUpdateInfo(data);
497
+ } catch {
498
+ // Ignore offline / network errors during passive update check
499
+ }
500
+ }, []);
501
+
474
502
  useEffect(() => {
475
503
  loadStatus();
476
504
  }, [loadStatus]);
477
505
 
506
+ const daemonVersion = status?.daemon?.version || null;
507
+ useEffect(() => {
508
+ if (!daemonVersion) return;
509
+ checkUpdate();
510
+ }, [daemonVersion, checkUpdate]);
511
+
478
512
  // Automatically poll while first-time background provisioning is running
479
513
  const isProvisioning = status?.provisioning?.state === 'running';
480
514
  useEffect(() => {
@@ -499,13 +533,29 @@ window.__ModuleLoader__.load({
499
533
  if (!res.ok || !data?.ok) {
500
534
  throw new Error(data?.error || `HTTP ${res.status}`);
501
535
  }
536
+ return true;
502
537
  } catch (err) {
503
538
  setError(err instanceof Error ? err.message : String(err));
539
+ return false;
504
540
  } finally {
505
541
  setBusy(false);
506
542
  }
507
543
  }, []);
508
544
 
545
+ const handleUpgrade = useCallback(async () => {
546
+ setUpgrading(true);
547
+ try {
548
+ const ok = await postAction('api/agentdeck/daemon', {
549
+ action: 'upgrade',
550
+ });
551
+ if (ok) {
552
+ await checkUpdate({ force: true });
553
+ }
554
+ } finally {
555
+ setUpgrading(false);
556
+ }
557
+ }, [postAction, checkUpdate]);
558
+
509
559
  const awakeMode = status?.daemon?.awake?.mode || 'never';
510
560
  const awakeOptions = [
511
561
  { id: 'never', label: t('awakeNever'), hint: t('awakeHintNever') },
@@ -522,7 +572,15 @@ window.__ModuleLoader__.load({
522
572
  const acpModelText = formatModel(status?.models?.acp?.defaultModel);
523
573
  const sourceModelText = formatModel(status?.models?.source?.defaultModel);
524
574
  const provisionError = status?.provisioning?.error || null;
525
- const anyBusy = busy || isProvisioning;
575
+ const anyBusy = busy || upgrading || isProvisioning;
576
+ const latestVersion = updateInfo?.latestVersion || null;
577
+ const hasDaemonUpdate = Boolean(
578
+ updateInfo?.updateAvailable &&
579
+ latestVersion &&
580
+ daemonVersion &&
581
+ latestVersion !== daemonVersion,
582
+ );
583
+ const canAutoUpdate = Boolean(status?.daemon?.canUpdate);
526
584
 
527
585
  return h(
528
586
  'div',
@@ -712,6 +770,13 @@ window.__ModuleLoader__.load({
712
770
  ? t('statusRunning')
713
771
  : t('statusStopped'),
714
772
  ),
773
+ daemonVersion
774
+ ? h(
775
+ 'span',
776
+ { className: 'adk-version' },
777
+ `v${daemonVersion}`,
778
+ )
779
+ : null,
715
780
  ),
716
781
  h(
717
782
  'p',
@@ -719,11 +784,28 @@ window.__ModuleLoader__.load({
719
784
  status.daemon?.running
720
785
  ? t('serviceDescRunning')
721
786
  : t('serviceDescStopped'),
787
+ hasDaemonUpdate && !canAutoUpdate
788
+ ? ` · ${t('updateAvailable')} v${latestVersion}`
789
+ : null,
722
790
  ),
723
791
  ),
724
792
  h(
725
793
  'div',
726
794
  { className: 'adk-actions' },
795
+ hasDaemonUpdate && canAutoUpdate
796
+ ? h(
797
+ 'button',
798
+ {
799
+ type: 'button',
800
+ className: `adk-btn ${status.daemon?.running ? 'adk-btn-primary' : 'adk-btn-secondary'}`,
801
+ disabled: anyBusy,
802
+ onClick: handleUpgrade,
803
+ },
804
+ upgrading
805
+ ? t('btnUpdating')
806
+ : `${t('btnUpdate')} v${latestVersion}`,
807
+ )
808
+ : null,
727
809
  status.daemon?.running
728
810
  ? status.daemon?.binaryPath
729
811
  ? h(
@@ -740,7 +822,9 @@ window.__ModuleLoader__.load({
740
822
  action: 'restart',
741
823
  }),
742
824
  },
743
- busy ? t('btnWorking') : t('btnRestart'),
825
+ busy && !upgrading
826
+ ? t('btnWorking')
827
+ : t('btnRestart'),
744
828
  ),
745
829
  h(
746
830
  'button',
@@ -768,7 +852,7 @@ window.__ModuleLoader__.load({
768
852
  action: 'start',
769
853
  }),
770
854
  },
771
- busy ? t('btnWorking') : t('btnStart'),
855
+ busy && !upgrading ? t('btnWorking') : t('btnStart'),
772
856
  ),
773
857
  ),
774
858
  ),
package/lib/index.js CHANGED
@@ -2,17 +2,20 @@ import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import {
4
4
  AWAKE_MODES,
5
+ checkDaemonUpdate,
5
6
  controlAgentDeckDaemon,
6
7
  getAgentDeckStatus,
7
8
  runAgentDeckSetup,
8
9
  setAgentDeckAwake,
9
10
  syncAgentDeckModels,
11
+ upgradeAgentDeckDaemon,
10
12
  } from './setup.js';
11
13
 
12
14
  export const name = 'agentdeck';
13
15
  export const inject = ['webServer'];
14
16
 
15
17
  const STATUS_PATH = '/api/agentdeck/status';
18
+ const UPDATE_CHECK_PATH = '/api/agentdeck/update-check';
16
19
  const SETUP_PATH = '/api/agentdeck/setup';
17
20
  const DAEMON_PATH = '/api/agentdeck/daemon';
18
21
  const AWAKE_PATH = '/api/agentdeck/awake';
@@ -197,6 +200,33 @@ export function apply(ctx) {
197
200
  `agentdeck: GET ${STATUS_PATH}`,
198
201
  );
199
202
 
203
+ ctx.effect(
204
+ () =>
205
+ ctx.webServer.register({
206
+ kind: 'exact',
207
+ path: UPDATE_CHECK_PATH,
208
+ handler: async (req, res) => {
209
+ if (isRejected(req, res)) return;
210
+ if (req.method !== 'GET') {
211
+ sendMethodNotAllowed(res, 'GET');
212
+ return;
213
+ }
214
+ try {
215
+ const url = new URL(req.url || UPDATE_CHECK_PATH, 'http://localhost');
216
+ const force = url.searchParams.get('force') === '1';
217
+ const update = await checkDaemonUpdate({ force });
218
+ sendJson(res, 200, { ok: true, ...update });
219
+ } catch (err) {
220
+ sendJson(res, 500, {
221
+ ok: false,
222
+ error: err instanceof Error ? err.message : String(err),
223
+ });
224
+ }
225
+ },
226
+ }),
227
+ `agentdeck: GET ${UPDATE_CHECK_PATH}`,
228
+ );
229
+
200
230
  // Retry/repair endpoint if auto-provisioning failed or user wants to re-run
201
231
  ctx.effect(
202
232
  () =>
@@ -253,10 +283,10 @@ export function apply(ctx) {
253
283
  if (parsed === null) return;
254
284
 
255
285
  const action = parsed?.action;
256
- if (!['start', 'stop', 'restart'].includes(action)) {
286
+ if (!['start', 'stop', 'restart', 'upgrade'].includes(action)) {
257
287
  sendJson(res, 400, {
258
288
  ok: false,
259
- error: 'action must be "start", "stop", or "restart"',
289
+ error: 'action must be "start", "stop", "restart", or "upgrade"',
260
290
  });
261
291
  return;
262
292
  }
@@ -270,18 +300,35 @@ export function apply(ctx) {
270
300
  }
271
301
 
272
302
  const info = getProfileInfo(ctx);
273
- const task = controlAgentDeckDaemon({ ...info, action });
303
+ const task =
304
+ action === 'upgrade'
305
+ ? upgradeAgentDeckDaemon(info)
306
+ : controlAgentDeckDaemon({ ...info, action });
274
307
  opInFlight = task;
275
308
  try {
276
309
  const result = await task;
277
310
  sendJson(res, 200, {
278
311
  ok: true,
279
312
  status: { ...result.status, provisioning },
313
+ ...(action === 'upgrade'
314
+ ? {
315
+ previousVersion: result.previousVersion ?? null,
316
+ version: result.version ?? null,
317
+ method: result.method ?? null,
318
+ }
319
+ : {}),
280
320
  });
281
321
  } catch (err) {
322
+ let statusPayload;
323
+ try {
324
+ statusPayload = await buildStatusPayload();
325
+ } catch {
326
+ // Ignore secondary status failure
327
+ }
282
328
  sendJson(res, 500, {
283
329
  ok: false,
284
330
  error: err instanceof Error ? err.message : String(err),
331
+ ...(statusPayload ? { status: statusPayload } : {}),
285
332
  });
286
333
  } finally {
287
334
  if (opInFlight === task) opInFlight = null;
package/lib/setup.js CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  existsSync,
6
6
  mkdirSync,
7
7
  readFileSync,
8
+ realpathSync,
8
9
  chmodSync,
9
10
  renameSync,
10
11
  statSync,
@@ -244,11 +245,266 @@ function isPidAlive(pid) {
244
245
  }
245
246
  }
246
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
+
247
496
  export async function readDaemonState(
248
497
  dataDir,
249
498
  { platform = process.platform, env = process.env, home = homedir() } = {},
250
499
  ) {
251
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;
252
508
  const configPath = join(dataDir, 'daemon.json');
253
509
  const lockPath = join(dataDir, 'daemon.lock');
254
510
 
@@ -321,6 +577,9 @@ export async function readDaemonState(
321
577
  return {
322
578
  installed: Boolean(binaryPath) || running,
323
579
  binaryPath,
580
+ version,
581
+ installMethod,
582
+ canUpdate,
324
583
  running,
325
584
  pid: running ? pid : null,
326
585
  pairedReady: Boolean(relayId),
@@ -942,21 +1201,267 @@ export async function controlAgentDeckDaemon({
942
1201
  return { ok: true, action, status };
943
1202
  }
944
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
+
945
1448
  export async function getAgentDeckStatus({
946
1449
  profileName = 'web',
947
1450
  dshHome = join(homedir(), '.dsh'),
948
1451
  sourcePatchPath = null,
949
1452
  dataDir = getAgentDeckDataDir(),
950
1453
  platform = process.platform,
1454
+ env = process.env,
1455
+ home = homedir(),
951
1456
  } = {}) {
952
1457
  const acpPatchPath = join(dshHome, 'profiles', 'acp', 'cordis.patch.yml');
953
1458
  const customAgentsPath = join(dataDir, 'custom_agents.json');
954
- const dshCommand = resolveDshCommand({ platform });
1459
+ const dshCommand = resolveDshCommand({ platform, env, home });
955
1460
  const acpPlugin = readAcpPluginState(dshHome);
956
1461
  const sourceModel = extractModelSummary(sourcePatchPath);
957
1462
  const acpModel = extractModelSummary(acpPatchPath);
958
1463
  const customAgent = readCustomAgentState(customAgentsPath);
959
- const daemon = await readDaemonState(dataDir, { platform });
1464
+ const daemon = await readDaemonState(dataDir, { platform, env, home });
960
1465
 
961
1466
  const modelMismatch = Boolean(
962
1467
  sourceModel.defaultModel &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-agentdeck",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Zero-config AgentDeck mobile remote control plugin for DeepSeek Harness (dsh) — auto-installs ACP & agentdeckd with autostart, shows pairing QR & keep-awake controls in Settings",
5
5
  "license": "MIT",
6
6
  "author": "mantou132",