@phnx-labs/agents-cli 1.22.127 → 1.23.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.
Files changed (119) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +15 -16
  3. package/dist/bootstrap.js +4 -3
  4. package/dist/commands/browser.js +4 -19
  5. package/dist/commands/cloud-transcripts.js +1 -2
  6. package/dist/commands/computer.d.ts +2 -6
  7. package/dist/commands/computer.js +12 -18
  8. package/dist/commands/daemon.js +70 -11
  9. package/dist/commands/exec.js +1 -1
  10. package/dist/commands/feed.js +1 -2
  11. package/dist/commands/focus.js +4 -1
  12. package/dist/commands/go.js +3 -2
  13. package/dist/commands/logs.js +3 -7
  14. package/dist/commands/menubar.js +55 -3
  15. package/dist/commands/projects.js +103 -40
  16. package/dist/commands/ps-roster.d.ts +0 -11
  17. package/dist/commands/ps-roster.js +3 -116
  18. package/dist/commands/ps.d.ts +10 -0
  19. package/dist/commands/ps.js +182 -1
  20. package/dist/commands/resume.js +1 -1
  21. package/dist/commands/sessions-browser.d.ts +0 -1
  22. package/dist/commands/sessions-browser.js +6 -23
  23. package/dist/commands/sessions-export.js +1 -1
  24. package/dist/commands/sessions-migrate.js +1 -1
  25. package/dist/commands/sessions-picker.d.ts +6 -32
  26. package/dist/commands/sessions-picker.js +81 -8
  27. package/dist/commands/sessions-render.js +1 -1
  28. package/dist/commands/sessions-resume.js +2 -2
  29. package/dist/commands/sessions-share.js +1 -1
  30. package/dist/commands/sessions-trace.js +1 -1
  31. package/dist/commands/sessions.d.ts +2 -176
  32. package/dist/commands/sessions.js +44 -1577
  33. package/dist/index.js +10 -11
  34. package/dist/lib/browser-client.d.ts +0 -21
  35. package/dist/lib/browser-client.js +1 -44
  36. package/dist/lib/computer/record.d.ts +1 -0
  37. package/dist/lib/computer/record.js +2 -16
  38. package/dist/lib/config-keys.d.ts +2 -2
  39. package/dist/lib/config-keys.js +8 -2
  40. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  41. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  42. package/dist/lib/daemon/attention-notify-service.js +8 -4
  43. package/dist/lib/daemon/daemon.d.ts +5 -1
  44. package/dist/lib/daemon/daemon.js +54 -14
  45. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  46. package/dist/lib/daemon/diagnostics.js +185 -0
  47. package/dist/lib/daemon/runner.js +3 -2
  48. package/dist/lib/daemon/service.d.ts +1 -1
  49. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  50. package/dist/lib/daemon/session-state-service.js +2 -2
  51. package/dist/lib/daemon/supervisor.d.ts +8 -0
  52. package/dist/lib/daemon/supervisor.js +47 -6
  53. package/dist/lib/daemon-services.d.ts +4 -1
  54. package/dist/lib/daemon-services.js +36 -5
  55. package/dist/lib/daemon-ticks.d.ts +3 -1
  56. package/dist/lib/daemon-ticks.js +18 -12
  57. package/dist/lib/device-config.d.ts +1 -1
  58. package/dist/lib/device-config.js +48 -7
  59. package/dist/lib/feed/tool-activity.d.ts +22 -10
  60. package/dist/lib/feed/tool-activity.js +168 -32
  61. package/dist/lib/feed/tools.d.ts +55 -2
  62. package/dist/lib/feed/tools.js +22 -28
  63. package/dist/lib/feed/watch.js +12 -8
  64. package/dist/lib/github/open-prs.d.ts +41 -0
  65. package/dist/lib/github/open-prs.js +157 -0
  66. package/dist/lib/github/project-prs.d.ts +20 -1
  67. package/dist/lib/github/project-prs.js +8 -7
  68. package/dist/lib/helper-versions.js +1 -1
  69. package/dist/lib/menubar/install-menubar.d.ts +23 -7
  70. package/dist/lib/menubar/install-menubar.js +179 -30
  71. package/dist/lib/menubar/resolve-version.d.ts +1 -0
  72. package/dist/lib/menubar/resolve-version.js +4 -2
  73. package/dist/lib/menubar/snapshot.d.ts +2 -0
  74. package/dist/lib/menubar/snapshot.js +2 -0
  75. package/dist/lib/menubar/update-state.d.ts +15 -0
  76. package/dist/lib/menubar/update-state.js +36 -0
  77. package/dist/lib/owner-notify.d.ts +0 -12
  78. package/dist/lib/owner-notify.js +1 -10
  79. package/dist/lib/self-heal/checks/menubar-helper.js +1 -0
  80. package/dist/lib/session/active.js +18 -14
  81. package/dist/lib/session/cloud.d.ts +0 -1
  82. package/dist/lib/session/cloud.js +0 -5
  83. package/dist/lib/session/db.d.ts +0 -64
  84. package/dist/lib/session/db.js +0 -116
  85. package/dist/lib/session/pid-registry.js +9 -6
  86. package/dist/lib/session/presentation.d.ts +107 -1
  87. package/dist/lib/session/presentation.js +543 -4
  88. package/dist/lib/session/remote/remote-list.d.ts +5 -36
  89. package/dist/lib/session/remote/remote-list.js +16 -320
  90. package/dist/lib/session/resume-command.d.ts +9 -0
  91. package/dist/lib/session/resume-command.js +107 -0
  92. package/dist/lib/session/selection.d.ts +102 -0
  93. package/dist/lib/session/selection.js +443 -0
  94. package/dist/lib/session/tool-index.d.ts +0 -62
  95. package/dist/lib/session/tool-index.js +1 -537
  96. package/dist/lib/sessions-client.d.ts +1 -0
  97. package/dist/lib/sessions-client.js +17 -1
  98. package/dist/lib/standalone-tools.js +2 -2
  99. package/dist/lib/testdata/owner-notify-api.d.ts +0 -13
  100. package/dist/lib/testdata/owner-notify-api.js +3 -23
  101. package/package.json +1 -1
  102. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  103. package/dist/commands/browser-sessions-picker.js +0 -136
  104. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  105. package/dist/commands/computer-sessions-picker.js +0 -90
  106. package/dist/commands/sessions-tail.d.ts +0 -13
  107. package/dist/commands/sessions-tail.js +0 -222
  108. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  109. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  110. package/dist/lib/browser/paths.d.ts +0 -9
  111. package/dist/lib/browser/paths.js +0 -31
  112. package/dist/lib/browser/record.d.ts +0 -4
  113. package/dist/lib/browser/record.js +0 -19
  114. package/dist/lib/browser/sessions-list.d.ts +0 -79
  115. package/dist/lib/browser/sessions-list.js +0 -415
  116. package/dist/lib/computer/sessions-list.d.ts +0 -78
  117. package/dist/lib/computer/sessions-list.js +0 -372
  118. package/dist/lib/daemon/owner-device-delivery-service.d.ts +0 -10
  119. package/dist/lib/daemon/owner-device-delivery-service.js +0 -28
@@ -0,0 +1,157 @@
1
+ import { ghExec, canonicalizeRepo, projectRepoSlugs } from './pr-mergeable.js';
2
+ import { CiErrors, KeyedCache, enrichPr, fetchOnePr, fetchViewer, ghFailure, isCachedRollup, mapBounded, readCi, readRepoMergeAbility, rowToProjectPr, } from './project-prs.js';
3
+ import { getCacheDir } from '../state.js';
4
+ const NEEDS_ME_RANK = { review: 0, failing: 1, conflicts: 2 };
5
+ export const SEARCH_RESULT_CAP = 1000;
6
+ const SEARCH_JQ = '.items[] | {number, title, url: .html_url, isDraft: (.draft // false), ' +
7
+ 'state: (.state // "" | ascii_upcase), createdAt: (.created_at // ""), updatedAt: (.updated_at // ""), ' +
8
+ 'login: (.user.login // ""), avatarUrl: (.user.avatar_url // ""), ' +
9
+ 'slug: (.repository_url // "" | sub("^.*/repos/"; ""))}';
10
+ function parseNdjson(out) {
11
+ return out.split('\n').map((l) => l.trim()).filter(Boolean).map((l) => JSON.parse(l));
12
+ }
13
+ async function searchOpenPrs(qualifier, gh) {
14
+ const q = encodeURIComponent(`is:pr is:open archived:false ${qualifier}`);
15
+ const out = await gh([
16
+ 'api', `search/issues?q=${q}&sort=updated&order=desc&per_page=100`, '--paginate', '--cache', '60s', '--jq', SEARCH_JQ,
17
+ ]);
18
+ return parseNdjson(out).map((row) => ({ slug: String(row.slug ?? ''), pr: rowToProjectPr(row) }));
19
+ }
20
+ export async function listViewerOwners(viewer, gh = ghExec) {
21
+ const orgs = (await gh(['api', 'user/orgs', '--paginate', '--cache', '1h', '--jq', '.[].login']))
22
+ .split('\n').map((l) => l.trim()).filter(Boolean);
23
+ return [...new Set([...(viewer ? [viewer] : []), ...orgs.sort((a, b) => a.localeCompare(b))])];
24
+ }
25
+ export function needsMeFor(pr, viewer, reviewRequested) {
26
+ if (reviewRequested)
27
+ return 'review';
28
+ if (!viewer || pr.author.login.toLowerCase() !== viewer.toLowerCase())
29
+ return null;
30
+ if (pr.ciState === 'FAILURE' || pr.ciState === 'ERROR')
31
+ return 'failing';
32
+ if (pr.mergeableState === 'dirty')
33
+ return 'conflicts';
34
+ return null;
35
+ }
36
+ const needsRank = (pr) => (pr.needsMe === null ? 3 : NEEDS_ME_RANK[pr.needsMe]);
37
+ export function compareOpenPrs(a, b) {
38
+ return needsRank(a) - needsRank(b) || b.updatedAt.localeCompare(a.updatedAt);
39
+ }
40
+ function compareRepos(a, b) {
41
+ const best = (r) => Math.min(3, ...r.pullRequests.map(needsRank));
42
+ return best(a) - best(b) || a.slug.localeCompare(b.slug);
43
+ }
44
+ export const OWNER_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
45
+ async function projectsBySlug(defs, gh) {
46
+ const out = new Map();
47
+ await Promise.all(defs.map(async (def) => {
48
+ const slugs = await Promise.all(projectRepoSlugs([def]).map((s) => canonicalizeRepo(s, gh)));
49
+ for (const slug of new Set(slugs.map((s) => s.toLowerCase()))) {
50
+ out.set(slug, [...(out.get(slug) ?? []), def.name]);
51
+ }
52
+ }));
53
+ for (const names of out.values())
54
+ names.sort((a, b) => a.localeCompare(b));
55
+ return out;
56
+ }
57
+ function withNeeds(pr, viewer, reviewRequested) {
58
+ return { ...pr, reviewRequested, needsMe: needsMeFor(pr, viewer, reviewRequested) };
59
+ }
60
+ export async function buildOpenPrs(defs, opts = {}, gh = ghExec) {
61
+ const viewer = await fetchViewer(gh);
62
+ const projectMap = projectsBySlug(defs, gh);
63
+ if (opts.repo !== undefined && opts.number !== undefined) {
64
+ const slug = await canonicalizeRepo(opts.repo, gh);
65
+ const [{ pr, reviewError }, merge, requested] = await Promise.all([
66
+ fetchOnePr(slug, opts.number, gh).then((pr) => enrichPr(slug, pr, gh)),
67
+ readRepoMergeAbility(slug, gh).then((m) => ({ merge: m, error: null }), (err) => ({ merge: null, error: ghFailure(err) })),
68
+ gh(['api', `repos/${slug}/pulls/${opts.number}/requested_reviewers`, '--jq', '.users[].login'])
69
+ .then((out) => ({ logins: out.split('\n').map((l) => l.trim().toLowerCase()).filter(Boolean), error: null }), (err) => ({ logins: [], error: ghFailure(err) })),
70
+ ]);
71
+ const reviewRequested = viewer !== null && requested.logins.includes(viewer.toLowerCase());
72
+ return {
73
+ viewer,
74
+ owners: [],
75
+ reviewRequestedError: requested.error,
76
+ repositories: [{
77
+ slug,
78
+ projects: (await projectMap).get(slug.toLowerCase()) ?? [],
79
+ merge: merge.merge,
80
+ pullRequests: [withNeeds(pr, viewer, reviewRequested)],
81
+ ciError: [reviewError, merge.error].filter(Boolean).join('; ') || null,
82
+ }],
83
+ partial: false,
84
+ };
85
+ }
86
+ const bad = opts.owners?.find((o) => !OWNER_LOGIN.test(o));
87
+ if (bad !== undefined)
88
+ throw new Error(`--org expects a GitHub org or account login, got "${bad}".`);
89
+ const ownerLogins = opts.owners?.length ? [...new Set(opts.owners)] : await listViewerOwners(viewer, gh);
90
+ const ownerSet = new Set(ownerLogins.map((o) => o.toLowerCase()));
91
+ const [ownerReads, requestedRead] = await Promise.all([
92
+ Promise.all(ownerLogins.map(async (login) => {
93
+ try {
94
+ const rows = await searchOpenPrs(`user:${login}`, gh);
95
+ return { owner: { login, open: rows.length, truncated: rows.length >= SEARCH_RESULT_CAP, error: null }, rows };
96
+ }
97
+ catch (err) {
98
+ return { owner: { login, open: 0, truncated: false, error: ghFailure(err) }, rows: [] };
99
+ }
100
+ })),
101
+ searchOpenPrs('review-requested:@me', gh).then((rows) => ({ rows, error: null }), (err) => ({ rows: [], error: ghFailure(err) })),
102
+ ]);
103
+ const key = (slug, n) => `${slug.toLowerCase()}#${n}`;
104
+ const requestedRows = opts.owners?.length
105
+ ? requestedRead.rows.filter((r) => ownerSet.has(r.slug.split('/')[0].toLowerCase()))
106
+ : requestedRead.rows;
107
+ const requested = new Set(requestedRows.map((r) => key(r.slug, r.pr.number)));
108
+ const bySlug = new Map();
109
+ for (const { slug, pr } of [...ownerReads.flatMap((r) => r.rows), ...requestedRows]) {
110
+ if (!slug)
111
+ continue;
112
+ const prs = bySlug.get(slug) ?? new Map();
113
+ prs.set(pr.number, pr);
114
+ bySlug.set(slug, prs);
115
+ }
116
+ const cacheDir = opts.cacheDir ?? getCacheDir();
117
+ const rollups = new KeyedCache(cacheDir, 'project-pr-ci.json', '@', isCachedRollup);
118
+ const nowMs = opts.nowMs ?? Date.now();
119
+ const projects = await projectMap;
120
+ const readers = new Map();
121
+ for (const slug of bySlug.keys())
122
+ readers.set(slug, { slug, gh, rollups, errors: new CiErrors(), nowMs, reads: new Map() });
123
+ const merges = new Map([...bySlug.keys()].map((slug) => [slug, readRepoMergeAbility(slug, gh).catch((err) => {
124
+ readers.get(slug).errors.record(err);
125
+ return null;
126
+ })]));
127
+ const listed = [...bySlug].flatMap(([slug, prs]) => [...prs.values()].map((pr) => ({ slug, pr })));
128
+ const read = await mapBounded(listed, 8, async ({ slug, pr: row }) => {
129
+ const ci = readers.get(slug);
130
+ let pr = row;
131
+ try {
132
+ pr = await fetchOnePr(slug, row.number, gh, '60s');
133
+ }
134
+ catch (err) {
135
+ ci.errors.record(err);
136
+ }
137
+ const ciSummary = await readCi(ci, pr.headSha || null);
138
+ return { slug, pr: withNeeds({ ...pr, ...ciSummary }, viewer, requested.has(key(slug, pr.number))) };
139
+ });
140
+ const repositories = await Promise.all([...bySlug.keys()].map(async (slug) => ({
141
+ slug,
142
+ projects: projects.get(slug.toLowerCase()) ?? [],
143
+ merge: await merges.get(slug),
144
+ pullRequests: read.filter((r) => r.slug === slug).map((r) => r.pr).sort(compareOpenPrs),
145
+ ciError: readers.get(slug).errors.message,
146
+ })));
147
+ repositories.sort(compareRepos);
148
+ rollups.save();
149
+ const owners = ownerReads.map((r) => r.owner);
150
+ return {
151
+ viewer,
152
+ owners,
153
+ reviewRequestedError: requestedRead.error,
154
+ repositories,
155
+ partial: owners.some((o) => o.error !== null) || requestedRead.error !== null,
156
+ };
157
+ }
@@ -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.20' },
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";
@@ -28,6 +29,23 @@ export declare function restartMenubarLaunchAgent(uid: number, plist: string, ex
28
29
  export declare function restartMenubarHelperAfterSwap(uid: number, ownProcesses: readonly MenubarProcess[], exec?: (cmd: string, args: readonly string[], opts: {
29
30
  stdio: ['ignore', 'ignore', 'ignore'];
30
31
  }) => Buffer, kill?: (pid: number) => void): void;
32
+ export interface MenubarRestartResult {
33
+ outcome: 'restarted' | 'failed';
34
+ previousPids: number[];
35
+ pids: number[];
36
+ detail: string;
37
+ }
38
+ export declare const MENUBAR_RESTART_DEADLINE_MS = 15000;
39
+ export interface MenubarRestartDeps {
40
+ ownPids: () => number[];
41
+ kickstart: (target: string) => Promise<{
42
+ code: number | null;
43
+ stderr: string;
44
+ }>;
45
+ sleep: (ms: number) => Promise<void>;
46
+ deadlineMs: number;
47
+ }
48
+ export declare function restartMenubarHelper(deps?: MenubarRestartDeps): Promise<MenubarRestartResult>;
31
49
  export declare function enableMenubarService(opts?: {
32
50
  clearOptOut?: boolean;
33
51
  }): Promise<boolean>;
@@ -57,6 +75,7 @@ export declare function menubarPlistNeedsRepoint(opts: {
57
75
  plistNodeExists: boolean;
58
76
  activeEntry: string | null;
59
77
  activeNode: string | null;
78
+ plistRelaunchesCleanExit: boolean;
60
79
  }): boolean;
61
80
  export declare function disableMenubarService(): void;
62
81
  export declare function mayInstallMenubarHelper(opts: {
@@ -133,12 +152,7 @@ export interface PidStaleness {
133
152
  }
134
153
  export declare function isMenubarProcessStaleAgainstBundle(pidStartedAtMs: number, bundleMtimeMs: number): boolean;
135
154
  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
- }
155
+ export type MenubarUpdateResult = MenubarUpdateState;
142
156
  export declare function menubarUpdateSkipReason(opts: {
143
157
  darwin: boolean;
144
158
  disabledByUser: boolean;
@@ -147,8 +161,10 @@ export declare function menubarUpdateSkipReason(opts: {
147
161
  installed: MenubarStamp | null;
148
162
  }): string | null;
149
163
  export declare function menubarUpdateOutcome(installed: string, available: string): 'current' | 'updated';
164
+ export declare function getMenubarUpdateStatus(): MenubarUpdateResult;
150
165
  export declare function updateMenubarHelperIfNewer(opts?: {
151
166
  dryRun?: boolean;
152
- force?: boolean;
167
+ manual?: boolean;
168
+ deferRestart?: boolean;
153
169
  }): Promise<MenubarUpdateResult>;
154
170
  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';
@@ -211,7 +213,10 @@ export function generateServicePlist(execPath) {
211
213
  <key>RunAtLoad</key>
212
214
  <true/>
213
215
  <key>KeepAlive</key>
214
- <true/>
216
+ <dict>
217
+ <key>SuccessfulExit</key>
218
+ <false/>
219
+ </dict>
215
220
  <key>ThrottleInterval</key>
216
221
  <integer>${MENUBAR_THROTTLE_SECONDS}</integer>
217
222
  <key>ProcessType</key>
@@ -263,6 +268,50 @@ export function restartMenubarHelperAfterSwap(uid, ownProcesses, exec = execFile
263
268
  kill(p.pid);
264
269
  }
265
270
  }
271
+ export const MENUBAR_RESTART_DEADLINE_MS = 15_000;
272
+ function kickstartDetached(target) {
273
+ return new Promise((resolve) => {
274
+ const child = spawn('launchctl', ['kickstart', '-k', target], { detached: true, stdio: ['ignore', 'ignore', 'pipe'] });
275
+ let stderr = '';
276
+ child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
277
+ const timer = setTimeout(() => { stderr = `${stderr}timed out after 10 s`; child.kill('SIGKILL'); }, 10_000);
278
+ child.on('error', (error) => { clearTimeout(timer); resolve({ code: null, stderr: error.message }); });
279
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, stderr: stderr.trim() }); });
280
+ });
281
+ }
282
+ const defaultRestartDeps = {
283
+ ownPids: () => liveMenubarProcesses().own.map((p) => p.pid),
284
+ kickstart: kickstartDetached,
285
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
286
+ deadlineMs: MENUBAR_RESTART_DEADLINE_MS,
287
+ };
288
+ export async function restartMenubarHelper(deps = defaultRestartDeps) {
289
+ const failed = (detail, previousPids = [], pids = []) => ({ outcome: 'failed', previousPids, pids, detail });
290
+ if (!onDarwin())
291
+ return failed('AGI Menu is macOS only');
292
+ if (menubarDisabledByUser() || !menubarServiceInstalled()) {
293
+ return failed('AGI Menu is turned off; `agents menubar setup` turns it on');
294
+ }
295
+ const registration = serviceManagerRegistrationAllowed();
296
+ if (!registration.allowed)
297
+ return failed(registration.reason);
298
+ const previousPids = deps.ownPids();
299
+ const target = `gui/${process.getuid?.() ?? 0}/${serviceLabel()}`;
300
+ const kick = await deps.kickstart(target);
301
+ if (kick.code !== 0) {
302
+ return failed(`launchctl kickstart -k ${target} failed${kick.stderr ? `: ${kick.stderr}` : ''}`, previousPids, deps.ownPids());
303
+ }
304
+ const deadline = Date.now() + deps.deadlineMs;
305
+ let pids = deps.ownPids();
306
+ while (!(pids.length === 1 && !previousPids.includes(pids[0]))) {
307
+ if (Date.now() >= deadline) {
308
+ return failed(`AGI Menu did not come back as one new process within ${Math.round(deps.deadlineMs / 1000)} s; \`agents menubar setup\` repairs it`, previousPids, pids);
309
+ }
310
+ await deps.sleep(200);
311
+ pids = deps.ownPids();
312
+ }
313
+ return { outcome: 'restarted', previousPids, pids, detail: `AGI Menu restarted (pid ${pids[0]})` };
314
+ }
266
315
  function startMenubarServiceFromSource(opts = {}) {
267
316
  if (!onDarwin())
268
317
  return false;
@@ -373,6 +422,12 @@ export function menubarHelperPrefetchNeeded(opts) {
373
422
  return !opts.serviceInstalled || opts.stale;
374
423
  }
375
424
  export async function prefetchMenubarHelper() {
425
+ if (!menubarAutoUpdateEnabled())
426
+ return null;
427
+ if (menubarServiceInstalled()) {
428
+ await updateMenubarHelperIfNewer();
429
+ return null;
430
+ }
376
431
  const needed = menubarHelperPrefetchNeeded({
377
432
  darwin: onDarwin(),
378
433
  disabledByUser: menubarDisabledByUser(),
@@ -392,6 +447,8 @@ export function menubarPlistNeedsRepoint(opts) {
392
447
  return false;
393
448
  if (opts.plistEntry !== opts.activeEntry)
394
449
  return true;
450
+ if (opts.plistRelaunchesCleanExit)
451
+ return true;
395
452
  if (opts.activeNode && (!opts.plistNode || !opts.plistNodeExists))
396
453
  return true;
397
454
  return false;
@@ -414,8 +471,17 @@ function menubarSetupNeedsRepoint() {
414
471
  plistNodeExists: Boolean(plistNode) && fs.existsSync(plistNode),
415
472
  activeEntry: resolveCliEntry(),
416
473
  activeNode: process.execPath,
474
+ plistRelaunchesCleanExit: plistRelaunchesCleanExit(),
417
475
  });
418
476
  }
477
+ function plistRelaunchesCleanExit() {
478
+ try {
479
+ return /<key>KeepAlive<\/key>\s*<true\/>/.test(fs.readFileSync(servicePlistPath(), 'utf-8'));
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
419
485
  export function disableMenubarService() {
420
486
  if (!onDarwin())
421
487
  return;
@@ -518,6 +584,16 @@ export function installMenubarLaunchAgentOnUpgrade() {
518
584
  return;
519
585
  if (menubarDisabledByUser())
520
586
  return;
587
+ if (menubarServiceInstalled() && fs.existsSync(installedExecutablePath()) && hasDeveloperIdSignature(installedAppPath())) {
588
+ if (menubarSetupNeedsRepoint() && mayHealMenubar(false, installedAppPath())) {
589
+ const stamp = readInstalledMenubarStamp();
590
+ if (stamp)
591
+ installAndStartService(installedExecutablePath(), stamp);
592
+ }
593
+ return;
594
+ }
595
+ if (!menubarAutoUpdateEnabled())
596
+ return;
521
597
  if (!sourceAppPath())
522
598
  return;
523
599
  if (!menubarServiceInstalled()) {
@@ -792,42 +868,115 @@ export function menubarUpdateSkipReason(opts) {
792
868
  export function menubarUpdateOutcome(installed, available) {
793
869
  return compareVersions(available, installed) > 0 ? 'updated' : 'current';
794
870
  }
871
+ export function getMenubarUpdateStatus() {
872
+ const saved = readUpdateState();
873
+ const autoUpdate = menubarAutoUpdateEnabled();
874
+ return {
875
+ outcome: saved.outcome ?? 'unknown', installed: stampVersionLabel(readInstalledMenubarStamp()),
876
+ available: saved.available ?? null, checkedAt: saved.checkedAt ?? null,
877
+ nextCheckAt: autoUpdate && saved.checkedAt ? new Date(Date.parse(saved.checkedAt) + MENUBAR_AUTO_UPDATE_INTERVAL_MS).toISOString() : null,
878
+ autoUpdate, detail: saved.detail ?? 'Not checked yet',
879
+ };
880
+ }
881
+ function handoffMenubarRestart(checkedAt) {
882
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `
883
+ import { execFileSync } from 'node:child_process';
884
+ import * as fs from 'node:fs';
885
+ const stateFile = ${JSON.stringify(updateStatePath())};
886
+ const fail = (detail) => {
887
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
888
+ if (state.checkedAt !== ${JSON.stringify(checkedAt)}) process.exit(1);
889
+ state.outcome = 'failed'; state.detail = detail;
890
+ const tmp = stateFile + '.' + process.pid + '.tmp';
891
+ fs.writeFileSync(tmp, JSON.stringify(state)); fs.renameSync(tmp, stateFile);
892
+ process.exit(1);
893
+ };
894
+ const deadline = Date.now() + 15000;
895
+ const timer = setInterval(() => {
896
+ 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'); }
897
+ catch {
898
+ clearInterval(timer);
899
+ try { execFileSync('launchctl', ['kickstart', '-k', ${JSON.stringify(`gui/${process.getuid?.() ?? 0}/${serviceLabel()}`)}], { timeout: 10000, stdio: 'ignore' }); }
900
+ catch (error) { fail('AGI Menu installed, but restart failed: ' + error.message); }
901
+ }
902
+ }, 100);
903
+ `], { detached: true, stdio: 'ignore' });
904
+ child.on('error', (error) => {
905
+ saveUpdateState({ ...getMenubarUpdateStatus(), outcome: 'failed', detail: `AGI Menu installed, but restart could not start: ${error.message}` });
906
+ });
907
+ child.unref();
908
+ }
795
909
  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 });
910
+ const previous = getMenubarUpdateStatus();
911
+ const result = (outcome, detail, available = previous.available) => ({ ...previous, outcome, detail, available });
912
+ const registration = serviceManagerRegistrationAllowed();
913
+ if (!opts.dryRun && !registration.allowed)
914
+ return result('skipped', registration.reason);
799
915
  const reason = menubarUpdateSkipReason({
800
- darwin: onDarwin(),
801
- disabledByUser: menubarDisabledByUser(),
802
- serviceInstalled: menubarServiceInstalled(),
803
- shipped: Boolean(shippedAppPath()),
804
- installed: installedStamp,
916
+ darwin: onDarwin(), disabledByUser: menubarDisabledByUser(), serviceInstalled: menubarServiceInstalled(),
917
+ shipped: Boolean(shippedAppPath()), installed: readInstalledMenubarStamp(),
805
918
  });
806
919
  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}` };
920
+ return result('skipped', reason);
921
+ if (!opts.manual && (!previous.autoUpdate || !menubarAutomaticUpdateDue(previous.checkedAt))) {
922
+ return result('skipped', previous.autoUpdate ? 'Next automatic check is not due' : 'Automatic updates are off');
923
+ }
924
+ fs.mkdirSync(path.dirname(updateStatePath()), { recursive: true });
925
+ let releaseLock;
926
+ try {
927
+ releaseLock = await lockfile.lock(updateStatePath(), { realpath: false, stale: 600000, retries: 0 });
928
+ }
929
+ catch (error) {
930
+ if (error.code === 'ELOCKED')
931
+ return result('skipped', 'An update check is already running');
932
+ throw error;
933
+ }
815
934
  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' };
935
+ const current = getMenubarUpdateStatus();
936
+ if (!opts.manual && (!current.autoUpdate || !menubarAutomaticUpdateDue(current.checkedAt)))
937
+ return result('skipped', 'Automatic update check is not due');
938
+ previous.checkedAt = new Date().toISOString();
939
+ previous.nextCheckAt = previous.autoUpdate ? new Date(Date.now() + MENUBAR_AUTO_UPDATE_INTERVAL_MS).toISOString() : null;
940
+ saveUpdateState(result('unknown', 'Checking for AGI Menu updates'));
941
+ let available = previous.available;
822
942
  try {
943
+ available = await resolveMenubarVersion({ force: true, strict: true });
944
+ if (menubarUpdateOutcome(previous.installed, available) === 'current') {
945
+ const running = buildMenubarDoctorReport();
946
+ const needsRestart = !running.running || running.staleRunningProcess.some((p) => p.stale);
947
+ if (needsRestart && opts.dryRun)
948
+ return saveUpdateState(result('available', `AGI Menu ${previous.installed} is installed; restart needed to run it`, available));
949
+ if (needsRestart && opts.manual) {
950
+ const pending = saveUpdateState(result('updated', `AGI Menu ${previous.installed} is installed; restarting the older running app`, available));
951
+ handoffMenubarRestart(previous.checkedAt);
952
+ return pending;
953
+ }
954
+ return saveUpdateState(result('current', `AGI Menu ${previous.installed} is up to date`, available));
955
+ }
956
+ if (opts.dryRun)
957
+ return saveUpdateState(result('available', `AGI Menu ${available} is available`, available));
958
+ const src = await downloadMenubarHelperApp(available);
959
+ if (!opts.manual && !menubarAutoUpdateEnabled())
960
+ return saveUpdateState({ ...result('available', 'Automatic updates were turned off', available), autoUpdate: false, nextCheckAt: null });
961
+ if (!mayHealMenubar(false, src))
962
+ return saveUpdateState(result('skipped', 'Another install owns the helper', available));
963
+ const exec = ensureMenubarAppInstalled({ forceReinstall: true, sourceAppPath: src });
964
+ if (!exec)
965
+ return saveUpdateState(result('failed', 'The verified bundle could not be installed', available));
823
966
  fs.writeFileSync(installedVersionMarkerPath(), JSON.stringify(stampFor(src)));
967
+ stampMenubarHeal();
968
+ const updated = saveUpdateState({ ...result('updated', `AGI Menu updated to ${available}`, available), installed: available });
969
+ if (opts.deferRestart)
970
+ handoffMenubarRestart(previous.checkedAt);
971
+ else
972
+ execFileSync('launchctl', ['kickstart', '-k', `gui/${process.getuid?.() ?? 0}/${serviceLabel()}`], { timeout: 10000, stdio: 'ignore' });
973
+ return updated;
974
+ }
975
+ catch (error) {
976
+ return saveUpdateState({ ...result('failed', error.message, available), installed: stampVersionLabel(readInstalledMenubarStamp()) });
824
977
  }
825
- catch { }
826
- stampMenubarHeal();
827
- restartMenubarHelperAfterSwap(process.getuid?.() ?? 0, liveMenubarProcesses().own);
828
- return { outcome: 'updated', installed, available, detail: `AGI Menu ${installed} → ${available}` };
829
978
  }
830
- catch (e) {
831
- return { outcome: 'failed', installed, available, detail: e.message };
979
+ finally {
980
+ await releaseLock();
832
981
  }
833
982
  }
@@ -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>[];