@phnx-labs/agents-cli 1.22.127 → 1.23.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +13 -16
  3. package/dist/bootstrap.js +4 -3
  4. package/dist/commands/browser.js +4 -19
  5. package/dist/commands/computer.d.ts +2 -6
  6. package/dist/commands/computer.js +12 -18
  7. package/dist/commands/logs.js +2 -6
  8. package/dist/commands/menubar.js +28 -1
  9. package/dist/commands/projects.js +103 -40
  10. package/dist/commands/sessions.d.ts +0 -11
  11. package/dist/commands/sessions.js +31 -364
  12. package/dist/index.js +10 -11
  13. package/dist/lib/browser-client.d.ts +0 -21
  14. package/dist/lib/browser-client.js +1 -44
  15. package/dist/lib/computer/record.d.ts +1 -0
  16. package/dist/lib/computer/record.js +2 -16
  17. package/dist/lib/config-keys.d.ts +2 -2
  18. package/dist/lib/config-keys.js +8 -2
  19. package/dist/lib/daemon/daemon.js +1 -8
  20. package/dist/lib/daemon/runner.js +3 -2
  21. package/dist/lib/daemon-services.d.ts +1 -1
  22. package/dist/lib/daemon-services.js +0 -5
  23. package/dist/lib/device-config.d.ts +1 -1
  24. package/dist/lib/device-config.js +48 -7
  25. package/dist/lib/feed/tool-activity.d.ts +22 -10
  26. package/dist/lib/feed/tool-activity.js +161 -32
  27. package/dist/lib/feed/tools.d.ts +55 -2
  28. package/dist/lib/feed/tools.js +22 -28
  29. package/dist/lib/feed/watch.js +4 -3
  30. package/dist/lib/github/open-prs.d.ts +41 -0
  31. package/dist/lib/github/open-prs.js +157 -0
  32. package/dist/lib/github/project-prs.d.ts +20 -1
  33. package/dist/lib/github/project-prs.js +8 -7
  34. package/dist/lib/helper-versions.js +1 -1
  35. package/dist/lib/menubar/install-menubar.d.ts +5 -7
  36. package/dist/lib/menubar/install-menubar.js +120 -29
  37. package/dist/lib/menubar/resolve-version.d.ts +1 -0
  38. package/dist/lib/menubar/resolve-version.js +4 -2
  39. package/dist/lib/menubar/snapshot.d.ts +2 -0
  40. package/dist/lib/menubar/snapshot.js +2 -0
  41. package/dist/lib/menubar/update-state.d.ts +15 -0
  42. package/dist/lib/menubar/update-state.js +36 -0
  43. package/dist/lib/owner-notify.d.ts +0 -12
  44. package/dist/lib/owner-notify.js +1 -10
  45. package/dist/lib/self-heal/checks/menubar-helper.js +1 -0
  46. package/dist/lib/session/cloud.d.ts +0 -1
  47. package/dist/lib/session/cloud.js +0 -5
  48. package/dist/lib/session/db.d.ts +0 -64
  49. package/dist/lib/session/db.js +0 -116
  50. package/dist/lib/session/remote/remote-list.d.ts +2 -36
  51. package/dist/lib/session/remote/remote-list.js +3 -320
  52. package/dist/lib/session/tool-index.d.ts +0 -62
  53. package/dist/lib/session/tool-index.js +1 -537
  54. package/dist/lib/sessions-client.d.ts +1 -0
  55. package/dist/lib/sessions-client.js +17 -1
  56. package/dist/lib/standalone-tools.js +2 -2
  57. package/dist/lib/testdata/owner-notify-api.d.ts +0 -13
  58. package/dist/lib/testdata/owner-notify-api.js +3 -23
  59. package/package.json +1 -1
  60. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  61. package/dist/commands/browser-sessions-picker.js +0 -136
  62. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  63. package/dist/commands/computer-sessions-picker.js +0 -90
  64. package/dist/commands/sessions-tail.d.ts +0 -13
  65. package/dist/commands/sessions-tail.js +0 -222
  66. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  67. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  68. package/dist/lib/browser/paths.d.ts +0 -9
  69. package/dist/lib/browser/paths.js +0 -31
  70. package/dist/lib/browser/record.d.ts +0 -4
  71. package/dist/lib/browser/record.js +0 -19
  72. package/dist/lib/browser/sessions-list.d.ts +0 -79
  73. package/dist/lib/browser/sessions-list.js +0 -415
  74. package/dist/lib/computer/sessions-list.d.ts +0 -78
  75. package/dist/lib/computer/sessions-list.js +0 -372
  76. package/dist/lib/daemon/owner-device-delivery-service.d.ts +0 -10
  77. package/dist/lib/daemon/owner-device-delivery-service.js +0 -28
@@ -95,7 +95,7 @@ export interface ProjectPrsOptions {
95
95
  }
96
96
  export declare function rowToProjectPr(row: Record<string, unknown>): ProjectPr;
97
97
  export declare function listOpenPrs(repo: string, gh?: GhExec): Promise<ProjectPr[]>;
98
- export declare function fetchOnePr(repo: string, number: number, gh?: GhExec): Promise<ProjectPr>;
98
+ export declare function fetchOnePr(repo: string, number: number, gh?: GhExec, cache?: string): Promise<ProjectPr>;
99
99
  export declare function fetchReviewAndHead(repo: string, number: number, gh?: GhExec): Promise<{
100
100
  reviewDecision: string | null;
101
101
  headRefOid: string | null;
@@ -118,6 +118,11 @@ export declare function isPassingRollup(items: readonly RollupItem[]): boolean;
118
118
  export declare const PASSING_ROLLUP_TTL_MS: number;
119
119
  export declare const FAILING_ROLLUP_TTL_MS: number;
120
120
  export declare function isFinishedRollup(items: readonly RollupItem[]): boolean;
121
+ export interface CachedRollup {
122
+ items: RollupItem[];
123
+ readAt: number;
124
+ }
125
+ export declare const isCachedRollup: (v: unknown) => v is CachedRollup;
121
126
  export declare class KeyedCache<T> {
122
127
  private readonly file;
123
128
  private readonly sep;
@@ -129,6 +134,19 @@ export declare class KeyedCache<T> {
129
134
  prune(slug: string, listed: ReadonlySet<string>): void;
130
135
  save(): void;
131
136
  }
137
+ export declare class CiErrors {
138
+ message: string | null;
139
+ record(err: unknown): void;
140
+ }
141
+ export interface CiReader {
142
+ slug: string;
143
+ gh: GhExec;
144
+ rollups: KeyedCache<CachedRollup>;
145
+ errors: CiErrors;
146
+ nowMs: number;
147
+ reads: Map<string, Promise<CiSummary>>;
148
+ }
149
+ export declare function readCi(ci: CiReader, sha: string | null): Promise<CiSummary>;
132
150
  interface MergedCandidate {
133
151
  pr: MergedPr;
134
152
  headSha: string;
@@ -139,6 +157,7 @@ export declare function listRecentlyMerged(repo: string, sinceMs: number, gh?: G
139
157
  }>;
140
158
  export declare function resolveTargetSlugs(def: ProjectDef, repo: string | undefined, gh: GhExec): Promise<string[]>;
141
159
  export declare function scopeForFiles(files: readonly string[], own: readonly string[], others: readonly string[]): ProjectPrScope | null;
160
+ export declare function mapBounded<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>;
142
161
  export declare function fetchViewer(gh?: GhExec): Promise<string | null>;
143
162
  export declare function buildProjectPrs(def: ProjectDef, opts?: ProjectPrsOptions, gh?: GhExec, peers?: readonly ProjectDef[], ctx?: ProjectPrsContext): Promise<ProjectPrsEnvelope>;
144
163
  export declare const MERGE_METHODS: readonly ["rebase", "squash", "merge"];
@@ -61,8 +61,8 @@ export async function listOpenPrs(repo, gh = ghExec) {
61
61
  ]);
62
62
  return parseNdjson(out).map(rowToProjectPr);
63
63
  }
64
- export async function fetchOnePr(repo, number, gh = ghExec) {
65
- const out = await gh(['api', `repos/${repo}/pulls/${number}`, '--jq', PR_JQ]);
64
+ export async function fetchOnePr(repo, number, gh = ghExec, cache) {
65
+ const out = await gh(['api', `repos/${repo}/pulls/${number}`, ...(cache ? ['--cache', cache] : []), '--jq', PR_JQ]);
66
66
  const rows = parseNdjson(out);
67
67
  if (rows.length === 0)
68
68
  throw new Error(`no PR ${repo}#${number}`);
@@ -139,7 +139,7 @@ function rollupTtlMs(items) {
139
139
  }
140
140
  const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
141
141
  const isFileList = (v) => Array.isArray(v) && v.every((f) => typeof f === 'string');
142
- const isCachedRollup = (v) => isRecord(v) && typeof v.readAt === 'number' && Array.isArray(v.items) &&
142
+ export const isCachedRollup = (v) => isRecord(v) && typeof v.readAt === 'number' && Array.isArray(v.items) &&
143
143
  v.items.every((i) => isRecord(i) && typeof i.name === 'string');
144
144
  const isNpmRead = (v) => isRecord(v) && typeof v.readAt === 'number' && (v.version === null || typeof v.version === 'string') &&
145
145
  (v.error === null || typeof v.error === 'string');
@@ -192,7 +192,7 @@ export class KeyedCache {
192
192
  atomicWriteFileSync(this.file, JSON.stringify(this.entries));
193
193
  }
194
194
  }
195
- class CiErrors {
195
+ export class CiErrors {
196
196
  message = null;
197
197
  record(err) {
198
198
  const msg = ghFailure(err);
@@ -203,7 +203,7 @@ class CiErrors {
203
203
  function isRateLimited(message) {
204
204
  return isRateLimitError(message) || /API rate limit exceeded/i.test(message);
205
205
  }
206
- function readCi(ci, sha) {
206
+ export function readCi(ci, sha) {
207
207
  if (!sha)
208
208
  return Promise.resolve(NO_CI);
209
209
  let read = ci.reads.get(sha);
@@ -341,7 +341,7 @@ class PrFilesCache extends KeyedCache {
341
341
  return files;
342
342
  }
343
343
  }
344
- async function mapBounded(items, limit, fn) {
344
+ export async function mapBounded(items, limit, fn) {
345
345
  const results = new Array(items.length);
346
346
  let next = 0;
347
347
  const worker = async () => {
@@ -516,6 +516,7 @@ export async function defaultMergeMethod(repo, gh = ghExec) {
516
516
  throw new Error(`${repo} allows no merge method this token can see.`);
517
517
  return method;
518
518
  }
519
+ const NO_BRANCH_PROTECTION = /\(HTTP 404\)|Upgrade to GitHub Pro or make this repository public/;
519
520
  export async function readRepoMergeAbility(repo, gh = ghExec) {
520
521
  const settings = await readRepoMergeSettings(repo, gh);
521
522
  let adminBypass = false;
@@ -529,7 +530,7 @@ export async function readRepoMergeAbility(repo, gh = ghExec) {
529
530
  adminBypass = enforced !== 'true';
530
531
  }
531
532
  catch (err) {
532
- if (!/\(HTTP 404\)/.test(ghFailure(err)))
533
+ if (!NO_BRANCH_PROTECTION.test(ghFailure(err)))
533
534
  throw err;
534
535
  adminBypass = true;
535
536
  }
@@ -1,5 +1,5 @@
1
1
  export const HELPER_RELEASES = {
2
- menubar: { tagPrefix: 'menubar', floor: '1.15.9' },
2
+ menubar: { tagPrefix: 'menubar', floor: '1.15.19' },
3
3
  };
4
4
  export function helperTag(helper, version) {
5
5
  const release = HELPER_RELEASES[helper];
@@ -1,3 +1,4 @@
1
+ import { type MenubarUpdateState } from './update-state.js';
1
2
  export declare const MENUBAR_HELPER_EXECUTABLE_NAME = "AGI Menu";
2
3
  export declare function serviceLabel(): string;
3
4
  export declare const LOCAL_BUILD_LABEL = "local";
@@ -133,12 +134,7 @@ export interface PidStaleness {
133
134
  }
134
135
  export declare function isMenubarProcessStaleAgainstBundle(pidStartedAtMs: number, bundleMtimeMs: number): boolean;
135
136
  export declare function buildMenubarDoctorReport(): MenubarDoctorReport;
136
- interface MenubarUpdateResult {
137
- outcome: 'updated' | 'current' | 'skipped' | 'failed';
138
- installed: string | null;
139
- available: string;
140
- detail: string;
141
- }
137
+ export type MenubarUpdateResult = MenubarUpdateState;
142
138
  export declare function menubarUpdateSkipReason(opts: {
143
139
  darwin: boolean;
144
140
  disabledByUser: boolean;
@@ -147,8 +143,10 @@ export declare function menubarUpdateSkipReason(opts: {
147
143
  installed: MenubarStamp | null;
148
144
  }): string | null;
149
145
  export declare function menubarUpdateOutcome(installed: string, available: string): 'current' | 'updated';
146
+ export declare function getMenubarUpdateStatus(): MenubarUpdateResult;
150
147
  export declare function updateMenubarHelperIfNewer(opts?: {
151
148
  dryRun?: boolean;
152
- force?: boolean;
149
+ manual?: boolean;
150
+ deferRestart?: boolean;
153
151
  }): Promise<MenubarUpdateResult>;
154
152
  export {};
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from 'url';
2
- import { execFileSync, spawnSync } from 'child_process';
2
+ import { execFileSync, spawnSync, spawn } from 'child_process';
3
3
  import * as fs from 'fs';
4
4
  import * as os from 'os';
5
5
  import * as path from 'path';
@@ -10,6 +10,8 @@ import { copyAppBundle, withInstallLock } from '../app-bundle-install.js';
10
10
  import { compareVersions } from '../agent-spec/primitives.js';
11
11
  import { namespacedServiceLabel, serviceManifestHomeEnv, serviceManagerRegistrationAllowed } from '../service-manifest.js';
12
12
  import { downloadMenubarHelperApp, menubarHelperCacheDir } from './download-menubar.js';
13
+ import lockfile from 'proper-lockfile';
14
+ import { readUpdateState, saveUpdateState, updateStatePath, menubarAutoUpdateEnabled, menubarAutomaticUpdateDue, MENUBAR_AUTO_UPDATE_INTERVAL_MS } from './update-state.js';
13
15
  import { helperFloor } from '../helper-versions.js';
14
16
  import { cachedMenubarVersion, resolveMenubarVersion } from './resolve-version.js';
15
17
  const APP_BUNDLE_NAME = 'MenubarHelper.app';
@@ -373,6 +375,12 @@ export function menubarHelperPrefetchNeeded(opts) {
373
375
  return !opts.serviceInstalled || opts.stale;
374
376
  }
375
377
  export async function prefetchMenubarHelper() {
378
+ if (!menubarAutoUpdateEnabled())
379
+ return null;
380
+ if (menubarServiceInstalled()) {
381
+ await updateMenubarHelperIfNewer();
382
+ return null;
383
+ }
376
384
  const needed = menubarHelperPrefetchNeeded({
377
385
  darwin: onDarwin(),
378
386
  disabledByUser: menubarDisabledByUser(),
@@ -518,6 +526,16 @@ export function installMenubarLaunchAgentOnUpgrade() {
518
526
  return;
519
527
  if (menubarDisabledByUser())
520
528
  return;
529
+ if (menubarServiceInstalled() && fs.existsSync(installedExecutablePath()) && hasDeveloperIdSignature(installedAppPath())) {
530
+ if (menubarSetupNeedsRepoint() && mayHealMenubar(false, installedAppPath())) {
531
+ const stamp = readInstalledMenubarStamp();
532
+ if (stamp)
533
+ installAndStartService(installedExecutablePath(), stamp);
534
+ }
535
+ return;
536
+ }
537
+ if (!menubarAutoUpdateEnabled())
538
+ return;
521
539
  if (!sourceAppPath())
522
540
  return;
523
541
  if (!menubarServiceInstalled()) {
@@ -792,42 +810,115 @@ export function menubarUpdateSkipReason(opts) {
792
810
  export function menubarUpdateOutcome(installed, available) {
793
811
  return compareVersions(available, installed) > 0 ? 'updated' : 'current';
794
812
  }
813
+ export function getMenubarUpdateStatus() {
814
+ const saved = readUpdateState();
815
+ const autoUpdate = menubarAutoUpdateEnabled();
816
+ return {
817
+ outcome: saved.outcome ?? 'unknown', installed: stampVersionLabel(readInstalledMenubarStamp()),
818
+ available: saved.available ?? null, checkedAt: saved.checkedAt ?? null,
819
+ nextCheckAt: autoUpdate && saved.checkedAt ? new Date(Date.parse(saved.checkedAt) + MENUBAR_AUTO_UPDATE_INTERVAL_MS).toISOString() : null,
820
+ autoUpdate, detail: saved.detail ?? 'Not checked yet',
821
+ };
822
+ }
823
+ function handoffMenubarRestart(checkedAt) {
824
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `
825
+ import { execFileSync } from 'node:child_process';
826
+ import * as fs from 'node:fs';
827
+ const stateFile = ${JSON.stringify(updateStatePath())};
828
+ const fail = (detail) => {
829
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
830
+ if (state.checkedAt !== ${JSON.stringify(checkedAt)}) process.exit(1);
831
+ state.outcome = 'failed'; state.detail = detail;
832
+ const tmp = stateFile + '.' + process.pid + '.tmp';
833
+ fs.writeFileSync(tmp, JSON.stringify(state)); fs.renameSync(tmp, stateFile);
834
+ process.exit(1);
835
+ };
836
+ const deadline = Date.now() + 15000;
837
+ const timer = setInterval(() => {
838
+ try { process.kill(${process.pid}, 0); if (Date.now() < deadline) return; fail('AGI Menu installed, but its updater did not exit before the restart deadline'); }
839
+ catch {
840
+ clearInterval(timer);
841
+ try { execFileSync('launchctl', ['kickstart', '-k', ${JSON.stringify(`gui/${process.getuid?.() ?? 0}/${serviceLabel()}`)}], { timeout: 10000, stdio: 'ignore' }); }
842
+ catch (error) { fail('AGI Menu installed, but restart failed: ' + error.message); }
843
+ }
844
+ }, 100);
845
+ `], { detached: true, stdio: 'ignore' });
846
+ child.on('error', (error) => {
847
+ saveUpdateState({ ...getMenubarUpdateStatus(), outcome: 'failed', detail: `AGI Menu installed, but restart could not start: ${error.message}` });
848
+ });
849
+ child.unref();
850
+ }
795
851
  export async function updateMenubarHelperIfNewer(opts = {}) {
796
- const installedStamp = readInstalledMenubarStamp();
797
- const installed = stampVersionLabel(installedStamp);
798
- const skip = (detail, available = cachedMenubarVersion()) => ({ outcome: 'skipped', installed, available, detail });
852
+ const previous = getMenubarUpdateStatus();
853
+ const result = (outcome, detail, available = previous.available) => ({ ...previous, outcome, detail, available });
854
+ const registration = serviceManagerRegistrationAllowed();
855
+ if (!opts.dryRun && !registration.allowed)
856
+ return result('skipped', registration.reason);
799
857
  const reason = menubarUpdateSkipReason({
800
- darwin: onDarwin(),
801
- disabledByUser: menubarDisabledByUser(),
802
- serviceInstalled: menubarServiceInstalled(),
803
- shipped: Boolean(shippedAppPath()),
804
- installed: installedStamp,
858
+ darwin: onDarwin(), disabledByUser: menubarDisabledByUser(), serviceInstalled: menubarServiceInstalled(),
859
+ shipped: Boolean(shippedAppPath()), installed: readInstalledMenubarStamp(),
805
860
  });
806
861
  if (reason)
807
- return skip(reason);
808
- const release = installedStamp;
809
- const available = await resolveMenubarVersion({ force: opts.force });
810
- if (menubarUpdateOutcome(release.helperVersion, available) === 'current') {
811
- return { outcome: 'current', installed, available, detail: `AGI Menu ${installed} is the newest published build` };
812
- }
813
- if (opts.dryRun)
814
- return { outcome: 'updated', installed, available, detail: `would update AGI Menu ${installed} → ${available}` };
862
+ return result('skipped', reason);
863
+ if (!opts.manual && (!previous.autoUpdate || !menubarAutomaticUpdateDue(previous.checkedAt))) {
864
+ return result('skipped', previous.autoUpdate ? 'Next automatic check is not due' : 'Automatic updates are off');
865
+ }
866
+ fs.mkdirSync(path.dirname(updateStatePath()), { recursive: true });
867
+ let releaseLock;
868
+ try {
869
+ releaseLock = await lockfile.lock(updateStatePath(), { realpath: false, stale: 600000, retries: 0 });
870
+ }
871
+ catch (error) {
872
+ if (error.code === 'ELOCKED')
873
+ return result('skipped', 'An update check is already running');
874
+ throw error;
875
+ }
815
876
  try {
816
- const src = await downloadMenubarHelperApp(available);
817
- if (!mayHealMenubar(false, src))
818
- return skip(`another install owns the helper; it will update on its own cooldown`, available);
819
- const exec = ensureMenubarAppInstalled({ forceReinstall: true, sourceAppPath: src });
820
- if (!exec)
821
- return { outcome: 'failed', installed, available, detail: 'the verified bundle could not be installed' };
877
+ const current = getMenubarUpdateStatus();
878
+ if (!opts.manual && (!current.autoUpdate || !menubarAutomaticUpdateDue(current.checkedAt)))
879
+ return result('skipped', 'Automatic update check is not due');
880
+ previous.checkedAt = new Date().toISOString();
881
+ previous.nextCheckAt = previous.autoUpdate ? new Date(Date.now() + MENUBAR_AUTO_UPDATE_INTERVAL_MS).toISOString() : null;
882
+ saveUpdateState(result('unknown', 'Checking for AGI Menu updates'));
883
+ let available = previous.available;
822
884
  try {
885
+ available = await resolveMenubarVersion({ force: true, strict: true });
886
+ if (menubarUpdateOutcome(previous.installed, available) === 'current') {
887
+ const running = buildMenubarDoctorReport();
888
+ const needsRestart = !running.running || running.staleRunningProcess.some((p) => p.stale);
889
+ if (needsRestart && opts.dryRun)
890
+ return saveUpdateState(result('available', `AGI Menu ${previous.installed} is installed; restart needed to run it`, available));
891
+ if (needsRestart && opts.manual) {
892
+ const pending = saveUpdateState(result('updated', `AGI Menu ${previous.installed} is installed; restarting the older running app`, available));
893
+ handoffMenubarRestart(previous.checkedAt);
894
+ return pending;
895
+ }
896
+ return saveUpdateState(result('current', `AGI Menu ${previous.installed} is up to date`, available));
897
+ }
898
+ if (opts.dryRun)
899
+ return saveUpdateState(result('available', `AGI Menu ${available} is available`, available));
900
+ const src = await downloadMenubarHelperApp(available);
901
+ if (!opts.manual && !menubarAutoUpdateEnabled())
902
+ return saveUpdateState({ ...result('available', 'Automatic updates were turned off', available), autoUpdate: false, nextCheckAt: null });
903
+ if (!mayHealMenubar(false, src))
904
+ return saveUpdateState(result('skipped', 'Another install owns the helper', available));
905
+ const exec = ensureMenubarAppInstalled({ forceReinstall: true, sourceAppPath: src });
906
+ if (!exec)
907
+ return saveUpdateState(result('failed', 'The verified bundle could not be installed', available));
823
908
  fs.writeFileSync(installedVersionMarkerPath(), JSON.stringify(stampFor(src)));
909
+ stampMenubarHeal();
910
+ const updated = saveUpdateState({ ...result('updated', `AGI Menu updated to ${available}`, available), installed: available });
911
+ if (opts.deferRestart)
912
+ handoffMenubarRestart(previous.checkedAt);
913
+ else
914
+ execFileSync('launchctl', ['kickstart', '-k', `gui/${process.getuid?.() ?? 0}/${serviceLabel()}`], { timeout: 10000, stdio: 'ignore' });
915
+ return updated;
916
+ }
917
+ catch (error) {
918
+ return saveUpdateState({ ...result('failed', error.message, available), installed: stampVersionLabel(readInstalledMenubarStamp()) });
824
919
  }
825
- catch { }
826
- stampMenubarHeal();
827
- restartMenubarHelperAfterSwap(process.getuid?.() ?? 0, liveMenubarProcesses().own);
828
- return { outcome: 'updated', installed, available, detail: `AGI Menu ${installed} → ${available}` };
829
920
  }
830
- catch (e) {
831
- return { outcome: 'failed', installed, available, detail: e.message };
921
+ finally {
922
+ await releaseLock();
832
923
  }
833
924
  }
@@ -28,6 +28,7 @@ export declare function resolveMenubarVersion(opts?: {
28
28
  now?: number;
29
29
  ttlMs?: number;
30
30
  force?: boolean;
31
+ strict?: boolean;
31
32
  fetchImpl?: FetchLike;
32
33
  }): Promise<string>;
33
34
  export {};
@@ -6,7 +6,7 @@ import { helperFloor } from '../helper-versions.js';
6
6
  import { getCliVersion } from '../version.js';
7
7
  import { MENUBAR_HELPER_ASSET } from './download-menubar.js';
8
8
  const MENUBAR_RELEASES_API = 'https://api.github.com/repos/phnx-labs/agi-cli/releases?per_page=100';
9
- const MENUBAR_RESOLVE_TTL_MS = 24 * 60 * 60 * 1000;
9
+ const MENUBAR_RESOLVE_TTL_MS = 12 * 60 * 60 * 1000;
10
10
  const TAG = /^menubar\/v(\d+\.\d+\.\d+)$/;
11
11
  export function pickNewestMenubarVersion(candidates, floor) {
12
12
  let best = floor;
@@ -85,7 +85,9 @@ export async function resolveMenubarVersion(opts = {}) {
85
85
  writeMenubarResolveCache(file, { checkedAt: now, version });
86
86
  return version;
87
87
  }
88
- catch {
88
+ catch (error) {
89
+ if (opts.strict)
90
+ throw error;
89
91
  return cached && compareVersions(cached.version, floor) >= 0 ? cached.version : floor;
90
92
  }
91
93
  }
@@ -1,3 +1,4 @@
1
+ import { type MenubarUpdateResult } from './install-menubar.js';
1
2
  import { type GithubViewer } from '../github/viewer.js';
2
3
  import { type PhoenixSession } from '../identity/client.js';
3
4
  import type { DeviceStats } from '../devices/health.js';
@@ -39,6 +40,7 @@ interface MenubarSnapshot {
39
40
  version: 1;
40
41
  capturedAt: string;
41
42
  cliVersion: string;
43
+ menubarUpdate: MenubarUpdateResult;
42
44
  routines: Record<string, unknown>[];
43
45
  recentSessions: Record<string, unknown>[];
44
46
  activeSessions: Record<string, unknown>[];
@@ -1,3 +1,4 @@
1
+ import { getMenubarUpdateStatus } from './install-menubar.js';
1
2
  import * as fs from 'fs';
2
3
  import * as path from 'path';
3
4
  import { httpsUrl } from '../actor.js';
@@ -132,6 +133,7 @@ export async function computeMenubarSnapshot() {
132
133
  version: 1,
133
134
  capturedAt: new Date().toISOString(),
134
135
  cliVersion: getCliVersion(),
136
+ menubarUpdate: getMenubarUpdateStatus(),
135
137
  routines,
136
138
  recentSessions: JSON.parse(serializeSessionsJson(recent)),
137
139
  activeSessions: serializeActiveSessionsForJson(activeSessions),
@@ -0,0 +1,15 @@
1
+ export declare const MENUBAR_AUTO_UPDATE_INTERVAL_MS: number;
2
+ export declare const menubarAutoUpdateEnabled: () => boolean;
3
+ export declare const updateStatePath: () => string;
4
+ export interface MenubarUpdateState {
5
+ outcome: 'unknown' | 'available' | 'updated' | 'current' | 'skipped' | 'failed';
6
+ installed: string | null;
7
+ available: string | null;
8
+ checkedAt: string | null;
9
+ nextCheckAt: string | null;
10
+ autoUpdate: boolean;
11
+ detail: string;
12
+ }
13
+ export declare function readUpdateState(): Partial<MenubarUpdateState>;
14
+ export declare function saveUpdateState(status: MenubarUpdateState): MenubarUpdateState;
15
+ export declare function menubarAutomaticUpdateDue(checkedAt: string | null, now?: number): boolean;
@@ -0,0 +1,36 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { getRuntimeStateDir } from '../state.js';
4
+ import { getConfigValue } from '../device-config.js';
5
+ export const MENUBAR_AUTO_UPDATE_INTERVAL_MS = 12 * 60 * 60 * 1000;
6
+ export const menubarAutoUpdateEnabled = () => getConfigValue('menubar.autoUpdate').value !== false;
7
+ export const updateStatePath = () => path.join(getRuntimeStateDir(), 'menubar-update.json');
8
+ export function readUpdateState() {
9
+ try {
10
+ const state = JSON.parse(fs.readFileSync(updateStatePath(), 'utf8'));
11
+ if (!state || typeof state !== 'object')
12
+ return {};
13
+ if (state.checkedAt != null && (typeof state.checkedAt !== 'string' || !Number.isFinite(Date.parse(state.checkedAt))))
14
+ return {};
15
+ if (!['unknown', 'available', 'updated', 'current', 'skipped', 'failed'].includes(state.outcome))
16
+ return {};
17
+ if (state.available != null && (typeof state.available !== 'string' || !/^\d+\.\d+\.\d+$/.test(state.available)))
18
+ return {};
19
+ if (typeof state.detail !== 'string')
20
+ return {};
21
+ return state;
22
+ }
23
+ catch {
24
+ return {};
25
+ }
26
+ }
27
+ export function saveUpdateState(status) {
28
+ fs.mkdirSync(path.dirname(updateStatePath()), { recursive: true });
29
+ const tmp = `${updateStatePath()}.${process.pid}.tmp`;
30
+ fs.writeFileSync(tmp, JSON.stringify(status));
31
+ fs.renameSync(tmp, updateStatePath());
32
+ return status;
33
+ }
34
+ export function menubarAutomaticUpdateDue(checkedAt, now = Date.now()) {
35
+ return checkedAt === null || now - Date.parse(checkedAt) >= MENUBAR_AUTO_UPDATE_INTERVAL_MS;
36
+ }
@@ -24,13 +24,6 @@ export interface OwnerNotifyResult {
24
24
  }>;
25
25
  suppressed: null | 'duplicate' | 'quiet_hours';
26
26
  }
27
- export interface DeviceDelivery {
28
- id: string;
29
- channel: 'imessage';
30
- address: string;
31
- body: string;
32
- createdAt: string;
33
- }
34
27
  export interface OwnerPreferencesPatch {
35
28
  preferences?: Array<{
36
29
  event: OwnerEvent;
@@ -66,10 +59,5 @@ export declare function resolveOwnerCredential(): OwnerCredential | null;
66
59
  export declare const OWNER_DEDUP_PREFIX = "owner:";
67
60
  export declare function hasUsableDeviceToken(device: string, cacheDir?: string): boolean;
68
61
  export declare function postOwnerNotification(notification: OwnerNotification): Promise<OwnerNotifyResult>;
69
- export declare function claimDeviceDeliveries(device: string, limit?: number): Promise<DeviceDelivery[]>;
70
- export declare function reportDeviceDelivery(id: string, result: {
71
- ok: boolean;
72
- error?: string;
73
- }): Promise<void>;
74
62
  export declare function putOwnerPreferences(patch: OwnerPreferencesPatch): Promise<void>;
75
63
  export declare function describeOwnerResult(result: OwnerNotifyResult): string;
@@ -87,8 +87,6 @@ async function rushRequest(method, route, body) {
87
87
  }
88
88
  if (response.ok && credential.kind === 'device')
89
89
  fs.rmSync(rejectedTokenPath(getCacheDir()), { force: true });
90
- if (response.status === 204)
91
- return undefined;
92
90
  const text = await response.text();
93
91
  let payload = null;
94
92
  try {
@@ -118,13 +116,6 @@ export function postOwnerNotification(notification) {
118
116
  dedupKey: `${OWNER_DEDUP_PREFIX}${notification.dedupKey}`,
119
117
  });
120
118
  }
121
- export async function claimDeviceDeliveries(device, limit = 10) {
122
- const out = await rushRequest('POST', '/me/device-deliveries/claim', { device, limit });
123
- return out.deliveries;
124
- }
125
- export async function reportDeviceDelivery(id, result) {
126
- await rushRequest('POST', `/me/device-deliveries/${encodeURIComponent(id)}/result`, result);
127
- }
128
119
  export async function putOwnerPreferences(patch) {
129
120
  await rushRequest('PUT', '/me/preferences', patch);
130
121
  }
@@ -137,7 +128,7 @@ export function describeOwnerResult(result) {
137
128
  if (result.delivered.length)
138
129
  parts.push(`delivered ${result.delivered.join(', ')}`);
139
130
  if (result.queued.length)
140
- parts.push(`queued ${result.queued.join(', ')}`);
131
+ parts.push(`Rush is sending ${result.queued.join(', ')}`);
141
132
  for (const s of result.skipped)
142
133
  parts.push(`skipped ${s.channel} (${s.reason})`);
143
134
  return parts.join('; ') || 'no channel enabled for this event';
@@ -8,6 +8,7 @@ export const menubarHelperCheck = {
8
8
  const { updateMenubarHelperIfNewer } = await import('../../menubar/install-menubar.js');
9
9
  const r = await updateMenubarHelperIfNewer({ dryRun: ctx.dryRun });
10
10
  switch (r.outcome) {
11
+ case 'available':
11
12
  case 'updated': return resultOf([r.detail], []);
12
13
  case 'failed': return resultOf([], [`AGI Menu ${r.installed ?? '?'} → ${r.available}: ${r.detail}`]);
13
14
  default: return resultOf([], []);
@@ -3,4 +3,3 @@ export declare function discoverCloudSessions(options?: {
3
3
  limit?: number;
4
4
  }): Promise<SessionMeta[]>;
5
5
  export declare function ensureCloudSessionCached(executionId: string, destPath?: string): Promise<string>;
6
- export declare function isCloudSessionPath(filePath: string): boolean;
@@ -87,8 +87,3 @@ export async function ensureCloudSessionCached(executionId, destPath) {
87
87
  fs.writeFileSync(finalPath, body);
88
88
  return finalPath;
89
89
  }
90
- export function isCloudSessionPath(filePath) {
91
- const root = path.resolve(CLOUD_CACHE_DIR);
92
- const resolved = path.resolve(filePath);
93
- return resolved.startsWith(root + path.sep);
94
- }
@@ -356,68 +356,4 @@ export declare function reindexMovedSessionPaths(moves: ReadonlyArray<{
356
356
  }>): number;
357
357
  export declare function updateSessionFilePaths(oldPrefix: string, newPrefix: string): number;
358
358
  export declare function countSessionsWithFilePrefix(prefix: string): number;
359
- interface BrowserCaptureCounts {
360
- screenshot: number;
361
- pdf: number;
362
- recording: number;
363
- download: number;
364
- }
365
- interface BrowserSessionRecord {
366
- task: string;
367
- profile: string;
368
- sessionId?: string;
369
- launchId?: string;
370
- actor?: string;
371
- machine?: string;
372
- startedAt?: number;
373
- lastActivity?: number;
374
- counts?: Partial<BrowserCaptureCounts>;
375
- captureDir?: string;
376
- capturesRemote?: string;
377
- }
378
- interface ComputerSessionRecord {
379
- invocationId: string;
380
- sessionId?: string;
381
- launchId?: string;
382
- actor?: string;
383
- machine?: string;
384
- startedAt?: number;
385
- lastActivity?: number;
386
- actionCount?: number;
387
- taskPreview?: string;
388
- }
389
- export declare function recordBrowserSession(record: BrowserSessionRecord): void;
390
- export declare function recordComputerSession(record: ComputerSessionRecord): void;
391
- interface StoredBrowserSession extends Required<Pick<BrowserSessionRecord, 'task' | 'profile'>> {
392
- sessionId?: string;
393
- launchId?: string;
394
- actor?: string;
395
- machine: string;
396
- startedAt: number;
397
- lastActivity?: number;
398
- counts: BrowserCaptureCounts;
399
- captureDir?: string;
400
- capturesRemote?: string;
401
- }
402
- export declare function listBrowserSessionRecords(profile?: string, opts?: {
403
- limit?: number;
404
- deviceKeys?: boolean;
405
- }): StoredBrowserSession[];
406
- export declare function getBrowserSessionRecord(profile: string, task: string): StoredBrowserSession | null;
407
- interface StoredComputerSession {
408
- invocationId: string;
409
- sessionId?: string;
410
- launchId?: string;
411
- actor?: string;
412
- machine: string;
413
- startedAt: number;
414
- lastActivity?: number;
415
- actionCount: number;
416
- taskPreview?: string;
417
- }
418
- export declare function pruneToolSessions(maxAgeDays?: number): number;
419
- export declare function listComputerSessionRecords(opts?: {
420
- limit?: number;
421
- startedBeforeMs?: number;
422
- }): StoredComputerSession[];
423
359
  export {};