@mycadet/cli 0.13.0-dev.202610231952.fa65022 → 0.13.0-dev.202610241003.f9cbe80

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.
Files changed (87) hide show
  1. package/node_modules/@mycadet/local-mode/src/__tests__/status.test.ts +0 -4
  2. package/node_modules/@mycadet/local-mode/src/index.ts +6 -2
  3. package/node_modules/@mycadet/local-mode/src/lockfile-contract.test.ts +0 -3
  4. package/node_modules/@mycadet/local-mode/src/lockfile-contract.ts +0 -2
  5. package/node_modules/@mycadet/local-mode/src/lockfile.test.ts +0 -31
  6. package/node_modules/@mycadet/local-mode/src/lockfile.ts +28 -48
  7. package/package.json +1 -1
  8. package/src/__tests__/app-command.test.ts +2 -2
  9. package/src/__tests__/assistant-client-cloud-auth.test.ts +2 -2
  10. package/src/__tests__/assistant-client-refresh.test.ts +2 -2
  11. package/src/__tests__/assistant-config.test.ts +28 -27
  12. package/src/__tests__/backup-ops.test.ts +4 -3
  13. package/src/__tests__/backup.test.ts +2 -2
  14. package/src/__tests__/client-tui-refresh.test.ts +3 -3
  15. package/src/__tests__/connect-import.test.ts +4 -52
  16. package/src/__tests__/debug.test.ts +1 -1
  17. package/src/__tests__/devices.test.ts +5 -6
  18. package/src/__tests__/gateway-token.test.ts +3 -3
  19. package/src/__tests__/helpers/lockfile-entry.ts +37 -0
  20. package/src/__tests__/host-teleport-docker.test.ts +2 -2
  21. package/src/__tests__/host-teleport.test.ts +15 -15
  22. package/src/__tests__/local-runtime-version.test.ts +4 -2
  23. package/src/__tests__/multi-local.test.ts +14 -25
  24. package/src/__tests__/nginx-ingress.test.ts +73 -5
  25. package/src/__tests__/orphan-detection.test.ts +13 -12
  26. package/src/__tests__/ps-cloud-status.test.ts +9 -9
  27. package/src/__tests__/restore.test.ts +32 -28
  28. package/src/__tests__/retire-local.test.ts +25 -29
  29. package/src/__tests__/retire.test.ts +33 -32
  30. package/src/__tests__/root-backup-docker.test.ts +2 -2
  31. package/src/__tests__/root-backup.test.ts +2 -3
  32. package/src/__tests__/root-restore-command.test.ts +2 -2
  33. package/src/__tests__/setup.test.ts +2 -5
  34. package/src/__tests__/signing-key-continuity.test.ts +2 -93
  35. package/src/__tests__/sleep.test.ts +13 -6
  36. package/src/__tests__/teleport-backup.test.ts +8 -2
  37. package/src/__tests__/teleport.test.ts +1 -1
  38. package/src/__tests__/tui-midsession-refresh.test.ts +4 -23
  39. package/src/__tests__/tunnel-stop.test.ts +2 -3
  40. package/src/__tests__/tunnel.test.ts +27 -16
  41. package/src/__tests__/uninstall.test.ts +31 -28
  42. package/src/__tests__/upgrade-local.test.ts +29 -15
  43. package/src/__tests__/upgrade-root-recovery.test.ts +2 -2
  44. package/src/__tests__/use.test.ts +16 -24
  45. package/src/__tests__/wake-error.test.ts +0 -1
  46. package/src/__tests__/wake.test.ts +22 -24
  47. package/src/commands/client.ts +5 -5
  48. package/src/commands/completions.test.ts +2 -2
  49. package/src/commands/debug.ts +13 -5
  50. package/src/commands/devices.ts +5 -5
  51. package/src/commands/gateway/token.ts +4 -4
  52. package/src/commands/hatch.ts +2 -2
  53. package/src/commands/login.ts +2 -2
  54. package/src/commands/logs.ts +4 -4
  55. package/src/commands/pair.ts +5 -5
  56. package/src/commands/ps.ts +23 -17
  57. package/src/commands/restore.ts +32 -20
  58. package/src/commands/retire.ts +6 -6
  59. package/src/commands/sleep.ts +117 -96
  60. package/src/commands/uninstall.ts +6 -4
  61. package/src/commands/upgrade.ts +200 -140
  62. package/src/commands/wake.ts +93 -93
  63. package/src/lib/__tests__/local-gateway-cli.test.ts +3 -3
  64. package/src/lib/__tests__/runtime-url.test.ts +1 -15
  65. package/src/lib/assistant-client.ts +5 -2
  66. package/src/lib/assistant-config.ts +43 -81
  67. package/src/lib/cloud-login.ts +12 -6
  68. package/src/lib/constants.ts +0 -1
  69. package/src/lib/docker.ts +11 -11
  70. package/src/lib/exec-apple-container.ts +2 -2
  71. package/src/lib/hatch-local.ts +12 -6
  72. package/src/lib/health-check.ts +123 -109
  73. package/src/lib/host-teleport.ts +31 -23
  74. package/src/lib/ingress-config.ts +2 -2
  75. package/src/lib/live-voice/connection.ts +2 -2
  76. package/src/lib/local.ts +76 -48
  77. package/src/lib/nginx-ingress.ts +41 -10
  78. package/src/lib/orphan-detection.ts +4 -3
  79. package/src/lib/retire-apple-container.ts +2 -2
  80. package/src/lib/retire-local.ts +11 -5
  81. package/src/lib/root-backup.ts +35 -21
  82. package/src/lib/runtime-url.ts +4 -4
  83. package/src/lib/ssh-apple-container.ts +2 -2
  84. package/src/lib/sync-cloud-assistants.ts +5 -5
  85. package/src/lib/teleport-backup.ts +15 -13
  86. package/src/lib/tunnel.ts +6 -6
  87. package/src/lib/upgrade-lifecycle.ts +36 -30
@@ -10,10 +10,11 @@ import {
10
10
  findAssistantByName,
11
11
  formatAssistantLookupError,
12
12
  getActiveAssistant,
13
+ getLocalInstanceDir,
13
14
  loadAllAssistants,
14
15
  lookupAssistantByIdentifier,
15
- saveAssistantEntry,
16
- type AssistantEntry,
16
+ saveLockfileAssistant,
17
+ type LockfileAssistant,
17
18
  } from "../lib/assistant-config";
18
19
  import {
19
20
  captureImageRefs,
@@ -37,7 +38,7 @@ import {
37
38
  getCloudUrl,
38
39
  readCloudToken,
39
40
  } from "../lib/cloud-client";
40
- import { checkManagedHealth } from "../lib/health-check.js";
41
+ import { checkCloudHealth } from "../lib/health-check.js";
41
42
  import {
42
43
  evaluateUpgradePoll,
43
44
  resolveUpgradeTarget,
@@ -120,7 +121,9 @@ function parseArgs(): UpgradeArgs {
120
121
  console.log(`Usage: ${cliCommand()} upgrade [<name>] [options]`);
121
122
  console.log("");
122
123
  console.log("Upgrade an assistant to a newer version.");
123
- console.log("To roll back to a previous version, use `cadet restore` with a backup.");
124
+ console.log(
125
+ "To roll back to a previous version, use `cadet restore` with a backup.",
126
+ );
124
127
  console.log("");
125
128
  console.log("Arguments:");
126
129
  console.log(
@@ -224,7 +227,7 @@ function parseArgs(): UpgradeArgs {
224
227
  * 2. Active assistant set via `cadet use`
225
228
  * 3. Sole assistant (when exactly one exists)
226
229
  */
227
- function resolveTargetAssistant(nameArg: string | null): AssistantEntry {
230
+ function resolveTargetAssistant(nameArg: string | null): LockfileAssistant {
228
231
  if (nameArg) {
229
232
  const result = lookupAssistantByIdentifier(nameArg);
230
233
  if (result.status !== "found") {
@@ -259,10 +262,16 @@ function resolveTargetAssistant(nameArg: string | null): AssistantEntry {
259
262
  }
260
263
 
261
264
  async function upgradeDocker(
262
- entry: AssistantEntry,
265
+ entry: LockfileAssistant,
263
266
  version: string | null,
264
267
  force: boolean,
265
268
  ): Promise<void> {
269
+ const gatewayUrl = entry.runtimeUrl;
270
+ if (!gatewayUrl) {
271
+ throw new Error(
272
+ `Docker assistant '${entry.assistantId}' has no recorded gateway URL.`,
273
+ );
274
+ }
266
275
  const instanceName = entry.assistantId;
267
276
  const res = dockerResourceNames(instanceName);
268
277
 
@@ -279,7 +288,7 @@ async function upgradeDocker(
279
288
  } = {};
280
289
  try {
281
290
  const healthResp = await loopbackSafeFetch(
282
- `${entry.runtimeUrl}/healthz?include=migrations`,
291
+ `${gatewayUrl}/healthz?include=migrations`,
283
292
  {
284
293
  signal: AbortSignal.timeout(5000),
285
294
  },
@@ -350,7 +359,7 @@ async function upgradeDocker(
350
359
 
351
360
  // Record version transition start in workspace git history
352
361
  await commitWorkspaceViaGateway(
353
- entry.runtimeUrl,
362
+ gatewayUrl,
354
363
  entry.assistantId,
355
364
  buildUpgradeCommitMessage({
356
365
  action: "upgrade",
@@ -375,7 +384,7 @@ async function upgradeDocker(
375
384
  // isUpdateInProgress = true and starts displaying status messages.
376
385
  console.log("📢 Notifying connected clients...");
377
386
  await broadcastUpgradeEvent(
378
- entry.runtimeUrl,
387
+ gatewayUrl,
379
388
  entry.assistantId,
380
389
  buildStartingEvent(versionTag),
381
390
  );
@@ -383,7 +392,7 @@ async function upgradeDocker(
383
392
  await new Promise((r) => setTimeout(r, 500));
384
393
 
385
394
  await broadcastUpgradeEvent(
386
- entry.runtimeUrl,
395
+ gatewayUrl,
387
396
  entry.assistantId,
388
397
  buildProgressEvent(UPGRADE_PROGRESS.DOWNLOADING),
389
398
  );
@@ -402,7 +411,7 @@ async function upgradeDocker(
402
411
  const detail = pullErr instanceof Error ? pullErr.message : String(pullErr);
403
412
  console.error(`\n❌ Failed to pull Docker images: ${detail}`);
404
413
  await broadcastUpgradeEvent(
405
- entry.runtimeUrl,
414
+ gatewayUrl,
406
415
  entry.assistantId,
407
416
  buildCompleteEvent(currentVersion ?? "unknown", false),
408
417
  );
@@ -414,7 +423,7 @@ async function upgradeDocker(
414
423
  // Parse gateway port from entry's runtimeUrl, fall back to default
415
424
  let gatewayPort = GATEWAY_INTERNAL_PORT;
416
425
  try {
417
- const parsed = new URL(entry.runtimeUrl);
426
+ const parsed = new URL(gatewayUrl);
418
427
  const port = parseInt(parsed.port, 10);
419
428
  if (!isNaN(port)) {
420
429
  gatewayPort = port;
@@ -429,12 +438,12 @@ async function upgradeDocker(
429
438
 
430
439
  // Capture complete persistent roots before replacing any services.
431
440
  await broadcastUpgradeEvent(
432
- entry.runtimeUrl,
441
+ gatewayUrl,
433
442
  entry.assistantId,
434
443
  buildProgressEvent(UPGRADE_PROGRESS.BACKING_UP),
435
444
  );
436
445
  console.log("📦 Creating pre-upgrade backup...");
437
- const backupPath = await createBackup(entry.runtimeUrl, entry.assistantId, {
446
+ const backupPath = await createBackup(gatewayUrl, entry.assistantId, {
438
447
  prefix: `${entry.assistantId}-pre-upgrade`,
439
448
  description: `Pre-upgrade snapshot before ${currentVersion ?? "unknown"} → ${versionTag}`,
440
449
  });
@@ -449,7 +458,7 @@ async function upgradeDocker(
449
458
  }
450
459
 
451
460
  await broadcastUpgradeEvent(
452
- entry.runtimeUrl,
461
+ gatewayUrl,
453
462
  entry.assistantId,
454
463
  buildProgressEvent(UPGRADE_PROGRESS.INSTALLING),
455
464
  );
@@ -478,10 +487,10 @@ async function upgradeDocker(
478
487
  console.log("✅ Containers started\n");
479
488
 
480
489
  console.log("Waiting for assistant to become ready...");
481
- const ready = await waitForReady(entry.runtimeUrl);
490
+ const ready = await waitForReady(gatewayUrl);
482
491
  if (ready) {
483
492
  // Update lockfile with new service group topology
484
- const updatedEntry: AssistantEntry = {
493
+ const updatedEntry: LockfileAssistant = {
485
494
  ...entry,
486
495
  containerInfo: {
487
496
  assistantImage: imageTags.assistant,
@@ -490,20 +499,20 @@ async function upgradeDocker(
490
499
  assistantPort,
491
500
  },
492
501
  };
493
- saveAssistantEntry(updatedEntry);
502
+ saveLockfileAssistant(updatedEntry);
494
503
  // Refresh the host-served web bundle before clients reload on completion.
495
504
  await restoreContainerAppServer(updatedEntry);
496
505
 
497
506
  // Notify clients on the new service group that the upgrade succeeded.
498
507
  await broadcastUpgradeEvent(
499
- entry.runtimeUrl,
508
+ gatewayUrl,
500
509
  entry.assistantId,
501
510
  buildCompleteEvent(versionTag, true),
502
511
  );
503
512
 
504
513
  // Record successful upgrade in workspace git history
505
514
  await commitWorkspaceViaGateway(
506
- entry.runtimeUrl,
515
+ gatewayUrl,
507
516
  entry.assistantId,
508
517
  buildUpgradeCommitMessage({
509
518
  action: "upgrade",
@@ -532,7 +541,7 @@ async function upgradeDocker(
532
541
 
533
542
  if (previousImageRefs) {
534
543
  await broadcastUpgradeEvent(
535
- entry.runtimeUrl,
544
+ gatewayUrl,
536
545
  entry.assistantId,
537
546
  buildProgressEvent(UPGRADE_PROGRESS.REVERTING),
538
547
  );
@@ -546,12 +555,12 @@ async function upgradeDocker(
546
555
  ) {
547
556
  console.log("🔄 Reverting database changes...");
548
557
  await broadcastUpgradeEvent(
549
- entry.runtimeUrl,
558
+ gatewayUrl,
550
559
  entry.assistantId,
551
560
  buildProgressEvent(UPGRADE_PROGRESS.REVERTING_MIGRATIONS),
552
561
  );
553
562
  await rollbackMigrations(
554
- entry.runtimeUrl,
563
+ gatewayUrl,
555
564
  entry.assistantId,
556
565
  preMigrationState.dbVersion,
557
566
  preMigrationState.lastWorkspaceMigrationId,
@@ -577,11 +586,11 @@ async function upgradeDocker(
577
586
  (msg) => console.log(msg),
578
587
  );
579
588
 
580
- let rollbackReady = await waitForReady(entry.runtimeUrl);
589
+ let rollbackReady = await waitForReady(gatewayUrl);
581
590
  let restoredViaFailedState = false;
582
591
  if (!rollbackReady && backupPath) {
583
592
  const recovery = await attemptFailedStateRestore({
584
- runtimeUrl: entry.runtimeUrl,
593
+ runtimeUrl: gatewayUrl,
585
594
  assistantId: entry.assistantId,
586
595
  backupPath,
587
596
  backupLabel: "pre-upgrade",
@@ -615,14 +624,14 @@ async function upgradeDocker(
615
624
  );
616
625
  } else if (backupPath) {
617
626
  await broadcastUpgradeEvent(
618
- entry.runtimeUrl,
627
+ gatewayUrl,
619
628
  entry.assistantId,
620
629
  buildProgressEvent(UPGRADE_PROGRESS.RESTORING),
621
630
  );
622
631
  console.log(`📦 Restoring data from pre-upgrade backup...`);
623
632
  console.log(` Source: ${backupPath}`);
624
633
  const restored = await restoreBackup(
625
- entry.runtimeUrl,
634
+ gatewayUrl,
626
635
  entry.assistantId,
627
636
  backupPath,
628
637
  {},
@@ -630,7 +639,9 @@ async function upgradeDocker(
630
639
  if (restored) {
631
640
  console.log(" ✅ Data restored successfully\n");
632
641
  } else {
633
- throw new Error(`Root restore failed; rollback recovery is incomplete. Backup: ${backupPath}`);
642
+ throw new Error(
643
+ `Root restore failed; rollback recovery is incomplete. Backup: ${backupPath}`,
644
+ );
634
645
  }
635
646
  } else {
636
647
  console.log(
@@ -641,7 +652,7 @@ async function upgradeDocker(
641
652
  // Restore previous container info in lockfile after rollback.
642
653
  // The recorded image refs are the rollback record now (digests are
643
654
  // gone from the contract).
644
- const rolledBackEntry: AssistantEntry = {
655
+ const rolledBackEntry: LockfileAssistant = {
645
656
  ...entry,
646
657
  containerInfo: {
647
658
  assistantImage:
@@ -655,11 +666,11 @@ async function upgradeDocker(
655
666
  assistantPort,
656
667
  },
657
668
  };
658
- saveAssistantEntry(rolledBackEntry);
669
+ saveLockfileAssistant(rolledBackEntry);
659
670
 
660
671
  // Notify clients that the upgrade failed and rolled back.
661
672
  await broadcastUpgradeEvent(
662
- entry.runtimeUrl,
673
+ gatewayUrl,
663
674
  entry.assistantId,
664
675
  buildCompleteEvent(
665
676
  currentVersion ?? "unknown",
@@ -683,7 +694,7 @@ async function upgradeDocker(
683
694
  ` Check logs with: docker logs -f ${res.assistantContainer}`,
684
695
  );
685
696
  await broadcastUpgradeEvent(
686
- entry.runtimeUrl,
697
+ gatewayUrl,
687
698
  entry.assistantId,
688
699
  buildCompleteEvent(currentVersion ?? "unknown", false),
689
700
  );
@@ -703,7 +714,7 @@ async function upgradeDocker(
703
714
  ` Check logs with: docker logs -f ${res.assistantContainer}`,
704
715
  );
705
716
  await broadcastUpgradeEvent(
706
- entry.runtimeUrl,
717
+ gatewayUrl,
707
718
  entry.assistantId,
708
719
  buildCompleteEvent(currentVersion ?? "unknown", false),
709
720
  );
@@ -719,7 +730,7 @@ async function upgradeDocker(
719
730
  ` Check logs with: docker logs -f ${res.assistantContainer}`,
720
731
  );
721
732
  await broadcastUpgradeEvent(
722
- entry.runtimeUrl,
733
+ gatewayUrl,
723
734
  entry.assistantId,
724
735
  buildCompleteEvent(currentVersion ?? "unknown", false),
725
736
  );
@@ -749,7 +760,7 @@ export async function targetVersionFromCli(
749
760
  }
750
761
 
751
762
  async function ensureGuardianTokenAfterLocalUpgrade(
752
- entry: AssistantEntry,
763
+ entry: LockfileAssistant,
753
764
  gatewayPort: number,
754
765
  bootstrapSecret?: string,
755
766
  ): Promise<void> {
@@ -778,7 +789,7 @@ async function ensureGuardianTokenAfterLocalUpgrade(
778
789
  }
779
790
 
780
791
  async function upgradeLocal(
781
- entry: AssistantEntry,
792
+ entry: LockfileAssistant,
782
793
  version: string | null,
783
794
  force: boolean,
784
795
  ): Promise<void> {
@@ -789,15 +800,25 @@ async function upgradeLocal(
789
800
  process.exit(1);
790
801
  }
791
802
 
792
- const originalResources = { ...entry.resources };
793
- const signingKey = resolveExistingLocalSigningKey(entry.resources);
794
- if (entry.resources.signingKey !== signingKey) {
795
- entry.resources.signingKey = signingKey;
796
- saveAssistantEntry(entry);
803
+ const resources = entry.resources;
804
+
805
+ const gatewayUrl = entry.runtimeUrl;
806
+ if (!gatewayUrl) {
807
+ const msg = `Local assistant '${entry.assistantId}' is missing its gateway URL. Re-hatch to fix.`;
808
+ console.error(msg);
809
+ emitCliError("UNKNOWN", msg);
810
+ process.exit(1);
811
+ }
812
+
813
+ const originalResources = { ...resources };
814
+ const signingKey = resolveExistingLocalSigningKey(resources);
815
+ if (resources.signingKey !== signingKey) {
816
+ resources.signingKey = signingKey;
817
+ saveLockfileAssistant(entry);
797
818
  }
798
819
 
799
820
  const targetVersion = await targetVersionFromCli(version);
800
- const adminUrl = `http://127.0.0.1:${entry.resources.gatewayPort}`;
821
+ const adminUrl = `http://127.0.0.1:${resources.gatewayPort}`;
801
822
  const currentVersion = await fetchCurrentVersion(adminUrl);
802
823
 
803
824
  if (!currentVersion && targetVersion) {
@@ -878,7 +899,7 @@ async function upgradeLocal(
878
899
  }
879
900
 
880
901
  if (entryChanged) {
881
- saveAssistantEntry(entry);
902
+ saveLockfileAssistant(entry);
882
903
  }
883
904
 
884
905
  await broadcastUpgradeEvent(
@@ -890,20 +911,21 @@ async function upgradeLocal(
890
911
  console.log(
891
912
  "⬇️ Downloading local runtime packages (assistant, gateway, credential-executor)...",
892
913
  );
893
- const runtimeInstall = ensureLocalRuntime(entry.resources, targetVersion, {
914
+ const runtimeInstall = ensureLocalRuntime(resources, targetVersion, {
894
915
  force,
895
916
  });
896
- entry.resources = {
897
- ...entry.resources,
917
+ const upgradedResources = {
918
+ ...resources,
898
919
  runtimeVersion: runtimeInstall.version,
899
920
  runtimeInstallDir: runtimeInstall.installDir,
900
921
  };
901
- saveAssistantEntry(entry);
922
+ entry.resources = upgradedResources;
923
+ saveLockfileAssistant(entry);
902
924
  console.log(` Runtime installed: ${runtimeInstall.installDir}\n`);
903
925
 
904
926
  try {
905
927
  console.log("🛑 Stopping local assistant processes...");
906
- await stopLocalProcesses(entry.resources);
928
+ await stopLocalProcesses(upgradedResources);
907
929
  console.log("✅ Local assistant processes stopped\n");
908
930
 
909
931
  console.log("🚀 Starting upgraded local assistant...");
@@ -914,9 +936,9 @@ async function upgradeLocal(
914
936
  // topology starts its sibling processes together. startCes always
915
937
  // launches the CES sibling.
916
938
  await Promise.all([
917
- startCes(false, entry.resources),
918
- startLocalDaemon(false, entry.resources, { signingKey }),
919
- startGateway(false, entry.resources, { signingKey, bootstrapSecret }),
939
+ startCes(false, upgradedResources),
940
+ startLocalDaemon(false, upgradedResources, { signingKey }),
941
+ startGateway(false, upgradedResources, { signingKey, bootstrapSecret }),
920
942
  ]);
921
943
  } finally {
922
944
  if (previousAppVersion === undefined) {
@@ -927,15 +949,18 @@ async function upgradeLocal(
927
949
  }
928
950
  await ensureGuardianTokenAfterLocalUpgrade(
929
951
  entry,
930
- entry.resources.gatewayPort,
952
+ upgradedResources.gatewayPort,
931
953
  bootstrapSecret,
932
954
  );
933
955
  console.log("✅ Local assistant processes started\n");
934
956
 
935
- const workspaceDir = join(entry.resources.instanceDir, "workspace");
957
+ const workspaceDir = join(
958
+ getLocalInstanceDir(upgradedResources),
959
+ "workspace",
960
+ );
936
961
  await restoreAppServerAndAutoTunnel(
937
962
  entry.assistantId,
938
- entry.resources.gatewayPort,
963
+ upgradedResources.gatewayPort,
939
964
  workspaceDir,
940
965
  );
941
966
 
@@ -952,15 +977,34 @@ async function upgradeLocal(
952
977
  throw new Error(msg);
953
978
  }
954
979
  } catch (error) {
955
- console.error("Local upgrade failed; restoring the previous runtime and service roots...");
956
- await stopLocalProcesses(entry.resources);
980
+ console.error(
981
+ "Local upgrade failed; restoring the previous runtime and service roots...",
982
+ );
983
+ await stopLocalProcesses(upgradedResources);
957
984
  entry.resources = originalResources;
958
- saveAssistantEntry(entry);
985
+ saveLockfileAssistant(entry);
959
986
  if (backupPath) {
960
- const restored = await restoreBackup(adminUrl, entry.assistantId, backupPath, { resume: false });
961
- if (!restored) throw new Error(`Local recovery failed; services remain stopped. Backup: ${backupPath}`, { cause: error });
962
- await Promise.all([startCes(false, entry.resources), startLocalDaemon(false, entry.resources, { signingKey }), startGateway(false, entry.resources, { signingKey, bootstrapSecret })]);
963
- if (!await waitForReady(adminUrl)) throw new Error(`Previous local runtime did not recover. Backup: ${backupPath}`, { cause: error });
987
+ const restored = await restoreBackup(
988
+ adminUrl,
989
+ entry.assistantId,
990
+ backupPath,
991
+ { resume: false },
992
+ );
993
+ if (!restored)
994
+ throw new Error(
995
+ `Local recovery failed; services remain stopped. Backup: ${backupPath}`,
996
+ { cause: error },
997
+ );
998
+ await Promise.all([
999
+ startCes(false, originalResources),
1000
+ startLocalDaemon(false, originalResources, { signingKey }),
1001
+ startGateway(false, originalResources, { signingKey, bootstrapSecret }),
1002
+ ]);
1003
+ if (!(await waitForReady(adminUrl)))
1004
+ throw new Error(
1005
+ `Previous local runtime did not recover. Backup: ${backupPath}`,
1006
+ { cause: error },
1007
+ );
964
1008
  }
965
1009
  throw error;
966
1010
  }
@@ -1023,7 +1067,7 @@ function sleep(ms: number): Promise<void> {
1023
1067
  * the service group restarts).
1024
1068
  */
1025
1069
  async function waitForPlatformUpgrade(
1026
- entry: AssistantEntry,
1070
+ entry: LockfileAssistant,
1027
1071
  token: string,
1028
1072
  pollTarget: string | null,
1029
1073
  initialVersion: string | null,
@@ -1066,10 +1110,7 @@ async function waitForPlatformUpgrade(
1066
1110
  const finalVersion = observedVersion ?? pollTarget ?? "unknown";
1067
1111
  const healthDeadline = Date.now() + PLATFORM_HEALTH_CONFIRM_TIMEOUT_MS;
1068
1112
  while (Date.now() < healthDeadline) {
1069
- const health = await checkManagedHealth(
1070
- entry.runtimeUrl || getCloudUrl(),
1071
- entry.assistantId,
1072
- );
1113
+ const health = await checkCloudHealth(entry);
1073
1114
  if (health.status === "healthy") {
1074
1115
  console.log(`✅ Upgraded to ${finalVersion} — assistant is healthy.`);
1075
1116
  return;
@@ -1095,11 +1136,17 @@ async function waitForPlatformUpgrade(
1095
1136
  );
1096
1137
  }
1097
1138
 
1098
- async function upgradePlatform(
1099
- entry: AssistantEntry,
1139
+ async function upgradeCloud(
1140
+ entry: LockfileAssistant,
1100
1141
  version: string | null,
1101
1142
  wait: boolean,
1102
1143
  ): Promise<void> {
1144
+ const gatewayUrl = entry.runtimeUrl;
1145
+ if (!gatewayUrl) {
1146
+ throw new Error(
1147
+ `Cloud assistant '${entry.assistantId}' has no recorded gateway URL.`,
1148
+ );
1149
+ }
1103
1150
  console.log(
1104
1151
  `🔄 Upgrading cloud-hosted assistant '${entry.assistantId}'...\n`,
1105
1152
  );
@@ -1117,8 +1164,8 @@ async function upgradePlatform(
1117
1164
  // platform doesn't know about): resolve the target, detect no-ops and
1118
1165
  // downgrades before POSTing, and bail if an upgrade is already running.
1119
1166
  const [assistantDetail, health] = await Promise.all([
1120
- fetchAssistantDetail(token, entry.assistantId, entry.runtimeUrl),
1121
- checkManagedHealth(entry.runtimeUrl || getCloudUrl(), entry.assistantId),
1167
+ fetchAssistantDetail(token, entry.assistantId, gatewayUrl),
1168
+ checkCloudHealth(entry),
1122
1169
  ]);
1123
1170
  // Health probe first, DB-backed field as the sleeping-assistant fallback.
1124
1171
  const currentVersion =
@@ -1164,7 +1211,7 @@ async function upgradePlatform(
1164
1211
  const inProgress = await fetchUpgradeInProgress(
1165
1212
  token,
1166
1213
  entry.assistantId,
1167
- entry.runtimeUrl,
1214
+ gatewayUrl,
1168
1215
  );
1169
1216
  if (inProgress === true) {
1170
1217
  console.error(UPGRADE_IN_PROGRESS_MSG);
@@ -1176,9 +1223,9 @@ async function upgradePlatform(
1176
1223
  console.log(` ${currentVersion} → ${resolution.target}\n`);
1177
1224
  }
1178
1225
 
1179
- const headers = await authHeaders(token, entry.runtimeUrl);
1226
+ const headers = await authHeaders(token, gatewayUrl);
1180
1227
 
1181
- const url = `${entry.runtimeUrl || getCloudUrl()}/v1/assistants/${encodeURIComponent(entry.assistantId)}/upgrade/`;
1228
+ const url = `${gatewayUrl || getCloudUrl()}/v1/assistants/${encodeURIComponent(entry.assistantId)}/upgrade/`;
1182
1229
  const body: { version?: string } = {};
1183
1230
  if (version) {
1184
1231
  body.version = version;
@@ -1198,7 +1245,7 @@ async function upgradePlatform(
1198
1245
  emitCliError("AUTH_FAILED", "Authentication failed", text);
1199
1246
  try {
1200
1247
  await broadcastUpgradeEvent(
1201
- entry.runtimeUrl,
1248
+ gatewayUrl,
1202
1249
  entry.assistantId,
1203
1250
  buildCompleteEvent("unknown", false),
1204
1251
  );
@@ -1227,7 +1274,7 @@ async function upgradePlatform(
1227
1274
  );
1228
1275
  try {
1229
1276
  await broadcastUpgradeEvent(
1230
- entry.runtimeUrl,
1277
+ gatewayUrl,
1231
1278
  entry.assistantId,
1232
1279
  buildCompleteEvent("unknown", false),
1233
1280
  );
@@ -1277,35 +1324,41 @@ async function upgradePlatform(
1277
1324
  * prunes old backups, and outputs the backup path.
1278
1325
  */
1279
1326
  async function upgradePrepare(
1280
- entry: AssistantEntry,
1327
+ entry: LockfileAssistant,
1281
1328
  version: string | null,
1282
1329
  ): Promise<void> {
1330
+ const gatewayUrl = entry.runtimeUrl;
1331
+ if (!gatewayUrl) {
1332
+ throw new Error(
1333
+ `Assistant '${entry.assistantId}' has no recorded gateway URL.`,
1334
+ );
1335
+ }
1283
1336
  const targetVersion = version ?? "unknown";
1284
1337
  const currentVersion = "unknown";
1285
1338
 
1286
1339
  // 1. Broadcast "starting" so the UI shows the progress spinner
1287
1340
  await broadcastUpgradeEvent(
1288
- entry.runtimeUrl,
1341
+ gatewayUrl,
1289
1342
  entry.assistantId,
1290
1343
  buildStartingEvent(targetVersion, 30),
1291
1344
  );
1292
1345
 
1293
1346
  // 2. Workspace commit: record pre-update state
1294
1347
  await commitWorkspaceViaGateway(
1295
- entry.runtimeUrl,
1348
+ gatewayUrl,
1296
1349
  entry.assistantId,
1297
1350
  `[assistant-upgrade] Starting: ${currentVersion} → ${targetVersion}`,
1298
1351
  );
1299
1352
 
1300
1353
  // 3. Progress: saving backup
1301
1354
  await broadcastUpgradeEvent(
1302
- entry.runtimeUrl,
1355
+ gatewayUrl,
1303
1356
  entry.assistantId,
1304
1357
  buildProgressEvent("Saving a backup of your data…"),
1305
1358
  );
1306
1359
 
1307
1360
  // 4. Create backup
1308
- const backupPath = await createBackup(entry.runtimeUrl, entry.assistantId, {
1361
+ const backupPath = await createBackup(gatewayUrl, entry.assistantId, {
1309
1362
  prefix: `${entry.assistantId}-pre-upgrade`,
1310
1363
  description: `Pre-upgrade snapshot before ${currentVersion} → ${targetVersion}`,
1311
1364
  });
@@ -1322,7 +1375,7 @@ async function upgradePrepare(
1322
1375
 
1323
1376
  // 6. Progress: installing update
1324
1377
  await broadcastUpgradeEvent(
1325
- entry.runtimeUrl,
1378
+ gatewayUrl,
1326
1379
  entry.assistantId,
1327
1380
  buildProgressEvent(UPGRADE_PROGRESS.INSTALLING),
1328
1381
  );
@@ -1339,7 +1392,7 @@ async function upgradePrepare(
1339
1392
  * Broadcasts a "complete" SSE event and creates a workspace commit.
1340
1393
  */
1341
1394
  async function upgradeFinalize(
1342
- entry: AssistantEntry,
1395
+ entry: LockfileAssistant,
1343
1396
  version: string | null,
1344
1397
  ): Promise<void> {
1345
1398
  if (!version) {
@@ -1353,19 +1406,25 @@ async function upgradeFinalize(
1353
1406
  process.exit(1);
1354
1407
  }
1355
1408
 
1409
+ const gatewayUrl = entry.runtimeUrl;
1410
+ if (!gatewayUrl) {
1411
+ throw new Error(
1412
+ `Assistant '${entry.assistantId}' has no recorded gateway URL.`,
1413
+ );
1414
+ }
1356
1415
  const fromVersion = version;
1357
1416
  const currentVersion = cliPkg.version ? `v${cliPkg.version}` : "unknown";
1358
1417
 
1359
1418
  // 1. Broadcast "complete" so the UI clears the progress spinner
1360
1419
  await broadcastUpgradeEvent(
1361
- entry.runtimeUrl,
1420
+ gatewayUrl,
1362
1421
  entry.assistantId,
1363
1422
  buildCompleteEvent(currentVersion, true),
1364
1423
  );
1365
1424
 
1366
1425
  // 2. Workspace commit: record successful update
1367
1426
  await commitWorkspaceViaGateway(
1368
- entry.runtimeUrl,
1427
+ gatewayUrl,
1369
1428
  entry.assistantId,
1370
1429
  `[assistant-upgrade] Complete: ${fromVersion} → ${currentVersion}\n\nresult: success`,
1371
1430
  );
@@ -1453,70 +1512,71 @@ async function resolveLatestAndMaybeSelfUpdate(
1453
1512
 
1454
1513
  export const upgrade = Object.assign(
1455
1514
  async function upgrade(): Promise<void> {
1456
- const { name, version, latest, prepare, finalize, noWait, force } =
1457
- parseArgs();
1458
- const entry = resolveTargetAssistant(name);
1459
-
1460
- if (prepare) {
1461
- await upgradePrepare(entry, version);
1462
- return;
1463
- }
1515
+ const { name, version, latest, prepare, finalize, noWait, force } =
1516
+ parseArgs();
1517
+ const entry = resolveTargetAssistant(name);
1464
1518
 
1465
- if (finalize) {
1466
- await upgradeFinalize(entry, version);
1467
- return;
1468
- }
1469
-
1470
- // When --latest is passed, resolve the target from the cloud API and
1471
- // self-update the CLI if it's behind. The resolved version is then used
1472
- // as the explicit target for the rest of the upgrade flow.
1473
- let effectiveVersion = version;
1474
- const cloud = entry.cloud;
1475
- if (latest) {
1476
- effectiveVersion =
1477
- cloud === "local"
1478
- ? await resolveLatestStableTag()
1479
- : await resolveLatestAndMaybeSelfUpdate(name, {
1480
- noWait,
1481
- force,
1482
- });
1483
- }
1484
-
1485
- try {
1486
- if (cloud === "docker") {
1487
- await upgradeDocker(entry, effectiveVersion, force);
1519
+ if (prepare) {
1520
+ await upgradePrepare(entry, version);
1488
1521
  return;
1489
1522
  }
1490
1523
 
1491
- if (cloud === "local") {
1492
- await upgradeLocal(entry, effectiveVersion, force);
1524
+ if (finalize) {
1525
+ await upgradeFinalize(entry, version);
1493
1526
  return;
1494
1527
  }
1495
1528
 
1496
- if (isCloudHome(cloud)) {
1497
- await upgradePlatform(entry, effectiveVersion, !noWait);
1498
- return;
1529
+ // When --latest is passed, resolve the target from the cloud API and
1530
+ // self-update the CLI if it's behind. The resolved version is then used
1531
+ // as the explicit target for the rest of the upgrade flow.
1532
+ let effectiveVersion = version;
1533
+ const cloud = entry.cloud;
1534
+ if (latest) {
1535
+ effectiveVersion =
1536
+ cloud === "local"
1537
+ ? await resolveLatestStableTag()
1538
+ : await resolveLatestAndMaybeSelfUpdate(name, {
1539
+ noWait,
1540
+ force,
1541
+ });
1499
1542
  }
1500
- } catch (err) {
1501
- const detail = err instanceof Error ? err.message : String(err);
1502
- console.error(`\n❌ Upgrade failed: ${detail}`);
1503
- // Best-effort: notify connected clients that the upgrade failed.
1504
- // A `starting` event may have been sent inside upgradeDocker/upgradePlatform
1505
- // before the error was thrown, so we must close with `complete`.
1506
- await broadcastUpgradeEvent(
1507
- entry.runtimeUrl,
1508
- entry.assistantId,
1509
- buildCompleteEvent("unknown", false),
1510
- );
1511
- emitCliError(categorizeUpgradeError(err), "Upgrade failed", detail);
1512
- process.exit(1);
1513
- }
1514
1543
 
1515
- const msg = `Error: Upgrade is not supported for '${cloud}' assistants. Only 'local', 'docker', and 'cadet' assistants can be upgraded via the CLI.`;
1516
- console.error(msg);
1517
- emitCliError("UNSUPPORTED_TOPOLOGY", msg);
1518
- process.exit(1);
1519
- },
1544
+ try {
1545
+ if (cloud === "docker") {
1546
+ await upgradeDocker(entry, effectiveVersion, force);
1547
+ return;
1548
+ }
1549
+
1550
+ if (cloud === "local") {
1551
+ await upgradeLocal(entry, effectiveVersion, force);
1552
+ return;
1553
+ }
1554
+
1555
+ if (isCloudHome(cloud)) {
1556
+ await upgradeCloud(entry, effectiveVersion, !noWait);
1557
+ return;
1558
+ }
1559
+ } catch (err) {
1560
+ const detail = err instanceof Error ? err.message : String(err);
1561
+ console.error(`\n❌ Upgrade failed: ${detail}`);
1562
+ // Best-effort: notify connected clients that the upgrade failed.
1563
+ // A `starting` event may have been sent inside upgradeDocker/upgradeCloud
1564
+ // before the error was thrown, so we must close with `complete`.
1565
+ if (entry.runtimeUrl) {
1566
+ await broadcastUpgradeEvent(
1567
+ entry.runtimeUrl,
1568
+ entry.assistantId,
1569
+ buildCompleteEvent("unknown", false),
1570
+ );
1571
+ }
1572
+ emitCliError(categorizeUpgradeError(err), "Upgrade failed", detail);
1573
+ process.exit(1);
1574
+ }
1575
+
1576
+ const msg = `Error: Upgrade is not supported for '${cloud}' assistants. Only 'local', 'docker', and 'cadet' assistants can be upgraded via the CLI.`;
1577
+ console.error(msg);
1578
+ emitCliError("UNSUPPORTED_TOPOLOGY", msg);
1579
+ process.exit(1);
1580
+ },
1520
1581
  { description: "Upgrade an assistant to a newer version" },
1521
1582
  );
1522
-