@phnx-labs/agents-cli 1.23.21 → 1.23.22

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 (176) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/README.md +17 -0
  3. package/dist/bootstrap.js +5 -4
  4. package/dist/cli/command-registry.js +2 -0
  5. package/dist/commands/config.js +16 -0
  6. package/dist/commands/daemon.js +3 -3
  7. package/dist/commands/doctor.js +10 -19
  8. package/dist/commands/events.js +1 -14
  9. package/dist/commands/feed-watch.js +5 -2
  10. package/dist/commands/go.js +2 -2
  11. package/dist/commands/lead.d.ts +3 -0
  12. package/dist/commands/lead.js +280 -0
  13. package/dist/commands/projects.js +3 -2
  14. package/dist/commands/ps-roster.d.ts +2 -12
  15. package/dist/commands/ps-roster.js +5 -87
  16. package/dist/commands/ps.js +3 -1
  17. package/dist/commands/repo.js +12 -12
  18. package/dist/commands/resource-view.js +5 -5
  19. package/dist/commands/sessions-browser.js +2 -2
  20. package/dist/commands/sessions-watch.js +5 -2
  21. package/dist/commands/setup-secrets.d.ts +3 -4
  22. package/dist/commands/setup-secrets.js +15 -46
  23. package/dist/commands/setup-session-backup.js +1 -1
  24. package/dist/commands/ssh.d.ts +0 -4
  25. package/dist/commands/ssh.js +14 -81
  26. package/dist/commands/teams-picker.js +1 -12
  27. package/dist/commands/teams.js +1 -13
  28. package/dist/commands/view.d.ts +1 -40
  29. package/dist/commands/view.js +9 -330
  30. package/dist/commands/watchdog.js +4 -4
  31. package/dist/index.js +4 -0
  32. package/dist/lib/accounting/usage.d.ts +0 -1
  33. package/dist/lib/accounting/usage.js +1 -112
  34. package/dist/lib/accounts/add.js +1 -1
  35. package/dist/lib/accounts/migrate.js +1 -1
  36. package/dist/lib/auto-pull-worker.js +2 -16
  37. package/dist/lib/auto-pull.d.ts +1 -0
  38. package/dist/lib/auto-pull.js +27 -0
  39. package/dist/lib/browser-client.js +2 -11
  40. package/dist/lib/cloud/codex.js +3 -0
  41. package/dist/lib/commands.d.ts +0 -6
  42. package/dist/lib/commands.js +3 -116
  43. package/dist/lib/comms-render.d.ts +1 -7
  44. package/dist/lib/comms-render.js +0 -19
  45. package/dist/lib/computer-client.js +2 -11
  46. package/dist/lib/config-keys.d.ts +7 -3
  47. package/dist/lib/config-keys.js +15 -2
  48. package/dist/lib/crabbox/runtimes.d.ts +0 -14
  49. package/dist/lib/crabbox/runtimes.js +0 -80
  50. package/dist/lib/daemon/attention-notify-service.d.ts +51 -28
  51. package/dist/lib/daemon/attention-notify-service.js +219 -53
  52. package/dist/lib/daemon/daemon.js +1 -2
  53. package/dist/lib/daemon/feed-stream-service.js +2 -4
  54. package/dist/lib/device-config.d.ts +0 -5
  55. package/dist/lib/device-config.js +20 -27
  56. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  57. package/dist/lib/devices/doctor-findings.js +12 -1
  58. package/dist/lib/devices/fleet.d.ts +6 -0
  59. package/dist/lib/devices/fleet.js +15 -0
  60. package/dist/lib/devices/harness-inventory.d.ts +9 -0
  61. package/dist/lib/devices/harness-inventory.js +66 -0
  62. package/dist/lib/exec.js +1 -3
  63. package/dist/lib/feed/attention.d.ts +16 -1
  64. package/dist/lib/feed/attention.js +63 -1
  65. package/dist/lib/feed/feed.d.ts +1 -1
  66. package/dist/lib/feed/feed.js +12 -2
  67. package/dist/lib/feed/hub.d.ts +9 -0
  68. package/dist/lib/feed/hub.js +27 -1
  69. package/dist/lib/feed/notify-schedule.d.ts +16 -0
  70. package/dist/lib/feed/notify-schedule.js +62 -0
  71. package/dist/lib/feed/ticket-priority.d.ts +4 -0
  72. package/dist/lib/feed/ticket-priority.js +30 -0
  73. package/dist/lib/feed/watch.d.ts +1 -0
  74. package/dist/lib/feed/watch.js +27 -3
  75. package/dist/lib/feed-ranking.d.ts +1 -0
  76. package/dist/lib/feed-ranking.js +3 -1
  77. package/dist/lib/format.d.ts +0 -2
  78. package/dist/lib/format.js +0 -8
  79. package/dist/lib/helper-versions.js +1 -1
  80. package/dist/lib/hooks/cache.d.ts +1 -0
  81. package/dist/lib/hooks/cache.js +12 -1
  82. package/dist/lib/installations/duplicate-prune.d.ts +37 -0
  83. package/dist/lib/installations/duplicate-prune.js +85 -0
  84. package/dist/lib/installations/inventory-json.d.ts +20 -0
  85. package/dist/lib/installations/inventory-json.js +252 -0
  86. package/dist/lib/installations/shims.d.ts +0 -18
  87. package/dist/lib/installations/shims.js +1 -257
  88. package/dist/lib/lead/brief.d.ts +49 -0
  89. package/dist/lib/lead/brief.js +173 -0
  90. package/dist/lib/lead/client.d.ts +21 -0
  91. package/dist/lib/lead/client.js +167 -0
  92. package/dist/lib/lead/confirm.d.ts +22 -0
  93. package/dist/lib/lead/confirm.js +73 -0
  94. package/dist/lib/lead/events.d.ts +106 -0
  95. package/dist/lib/lead/events.js +188 -0
  96. package/dist/lib/lead/harness.d.ts +29 -0
  97. package/dist/lib/lead/harness.js +107 -0
  98. package/dist/lib/lead/host.d.ts +132 -0
  99. package/dist/lib/lead/host.js +675 -0
  100. package/dist/lib/lead/paths.d.ts +22 -0
  101. package/dist/lib/lead/paths.js +69 -0
  102. package/dist/lib/lead/refs.d.ts +17 -0
  103. package/dist/lib/lead/refs.js +75 -0
  104. package/dist/lib/lead/roster.d.ts +26 -0
  105. package/dist/lib/lead/roster.js +121 -0
  106. package/dist/lib/lead/shapes.d.ts +23 -0
  107. package/dist/lib/lead/shapes.js +95 -0
  108. package/dist/lib/lead/store.d.ts +46 -0
  109. package/dist/lib/lead/store.js +77 -0
  110. package/dist/lib/lead/tools.d.ts +18 -0
  111. package/dist/lib/lead/tools.js +106 -0
  112. package/dist/lib/lead/visibility.d.ts +16 -0
  113. package/dist/lib/lead/visibility.js +77 -0
  114. package/dist/lib/mailbox.d.ts +0 -18
  115. package/dist/lib/mailbox.js +0 -170
  116. package/dist/lib/menubar/notify-desktop.d.ts +5 -0
  117. package/dist/lib/menubar/notify-desktop.js +24 -0
  118. package/dist/lib/models.js +1 -19
  119. package/dist/lib/permissions.d.ts +0 -6
  120. package/dist/lib/permissions.js +0 -140
  121. package/dist/lib/platform/process.d.ts +1 -0
  122. package/dist/lib/platform/process.js +5 -0
  123. package/dist/lib/probe.js +13 -1
  124. package/dist/lib/project-status.js +4 -3
  125. package/dist/lib/projects.d.ts +9 -0
  126. package/dist/lib/projects.js +61 -3
  127. package/dist/lib/scheduling/routines.d.ts +1 -13
  128. package/dist/lib/scheduling/routines.js +1 -37
  129. package/dist/lib/secrets-cli.d.ts +3 -3
  130. package/dist/lib/secrets-cli.js +1 -1
  131. package/dist/lib/secrets-client.d.ts +4 -37
  132. package/dist/lib/secrets-client.js +19 -265
  133. package/dist/lib/session/active.d.ts +18 -8
  134. package/dist/lib/session/active.js +94 -18
  135. package/dist/lib/session/db.d.ts +0 -16
  136. package/dist/lib/session/db.js +1 -134
  137. package/dist/lib/session/detached.d.ts +0 -1
  138. package/dist/lib/session/detached.js +0 -18
  139. package/dist/lib/session/pending-work.d.ts +21 -0
  140. package/dist/lib/session/pending-work.js +284 -0
  141. package/dist/lib/session/remote/remote-list.d.ts +0 -3
  142. package/dist/lib/session/remote/remote-list.js +1 -23
  143. package/dist/lib/session/remote/watch.d.ts +5 -0
  144. package/dist/lib/session/remote/watch.js +19 -2
  145. package/dist/lib/session/session-cache.d.ts +1 -1
  146. package/dist/lib/session/session-cache.js +12 -5
  147. package/dist/lib/session/sync/provision.js +1 -2
  148. package/dist/lib/smart-launch.js +7 -2
  149. package/dist/lib/snapshot.js +3 -4
  150. package/dist/lib/ssh-exec.d.ts +0 -40
  151. package/dist/lib/ssh-exec.js +0 -108
  152. package/dist/lib/ssh-tunnel.d.ts +0 -6
  153. package/dist/lib/ssh-tunnel.js +0 -42
  154. package/dist/lib/standalone-tools.js +12 -1
  155. package/dist/lib/startup/command-registry.js +1 -1
  156. package/dist/lib/startup/spellcheck.d.ts +0 -1
  157. package/dist/lib/startup/spellcheck.js +1 -20
  158. package/dist/lib/state.d.ts +0 -6
  159. package/dist/lib/state.js +1 -14
  160. package/dist/lib/teams/delivery.d.ts +1 -0
  161. package/dist/lib/teams/delivery.js +13 -0
  162. package/dist/lib/types.d.ts +0 -37
  163. package/dist/lib/types.js +0 -9
  164. package/dist/lib/watchdog/log.d.ts +1 -1
  165. package/dist/lib/watchdog/log.js +6 -4
  166. package/package.json +2 -1
  167. package/dist/lib/artifact-actions.d.ts +0 -7
  168. package/dist/lib/artifact-actions.js +0 -39
  169. package/dist/lib/session/sync/managed-config.d.ts +0 -3
  170. package/dist/lib/session/sync/managed-config.js +0 -3
  171. package/dist/lib/session/sync/worker-template.d.ts +0 -1
  172. package/dist/lib/session/sync/worker-template.js +0 -807
  173. package/dist/lib/storage/selection.d.ts +0 -8
  174. package/dist/lib/storage/selection.js +0 -10
  175. package/dist/lib/watchdog/index.d.ts +0 -3
  176. package/dist/lib/watchdog/index.js +0 -3
@@ -11,6 +11,33 @@ function fetchStateDir() {
11
11
  export function lockFilePath(alias, fetchDir) {
12
12
  return path.join(fetchDir ?? fetchStateDir(), `${alias}.lock`);
13
13
  }
14
+ export function tryAcquireSyncLock(alias, fetchDir) {
15
+ const lock = lockFilePath(alias, fetchDir);
16
+ const created = createLockExclusive(lock);
17
+ if (created !== 'exists')
18
+ return created;
19
+ return reclaimStaleLock(lock) && createLockExclusive(lock) === true;
20
+ }
21
+ function createLockExclusive(lock) {
22
+ try {
23
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' });
24
+ return true;
25
+ }
26
+ catch (err) {
27
+ return err.code === 'EEXIST' ? 'exists' : false;
28
+ }
29
+ }
30
+ function reclaimStaleLock(lock) {
31
+ try {
32
+ if (Date.now() - fs.statSync(lock).mtimeMs < SYNC_LOCK_TTL_MS)
33
+ return false;
34
+ fs.unlinkSync(lock);
35
+ return true;
36
+ }
37
+ catch (err) {
38
+ return err.code === 'ENOENT';
39
+ }
40
+ }
14
41
  export function statusFilePath(alias, fetchDir) {
15
42
  return path.join(fetchDir ?? fetchStateDir(), `${alias}.status.json`);
16
43
  }
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
2
2
  import { realpathSync, existsSync } from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { findInPath } from './agent-spec/agents.js';
5
+ import { childExitCode } from './platform/process.js';
5
6
  const INSTALL_HINT = 'npm i -g @phnx-labs/browser-cli';
6
7
  export const BROWSER_CONTEXT_FD = 3;
7
8
  export class BrowserClientError extends Error {
@@ -80,20 +81,10 @@ export async function runBrowser(opts) {
80
81
  child.on('error', (err) => {
81
82
  reject(new BrowserClientError('BROWSER_SPAWN_FAILED', `Could not run \`${bin}\`: ${err.message}`));
82
83
  });
83
- child.on('close', (code, signal) => {
84
- if (code == null)
85
- return resolve(signal ? 128 + (osSignalNumber(signal) ?? 0) : 1);
86
- resolve(code);
87
- });
84
+ child.on('close', (code, signal) => resolve(childExitCode(code, signal)));
88
85
  });
89
86
  return { exitCode, stdout };
90
87
  }
91
- function osSignalNumber(signal) {
92
- const table = {
93
- SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGPIPE: 13, SIGTERM: 15,
94
- };
95
- return table[signal];
96
- }
97
88
  export function _resetBrowserClientForTest() {
98
89
  cachedBin = undefined;
99
90
  }
@@ -31,6 +31,9 @@ function runCodex(args, env) {
31
31
  let stderr = '';
32
32
  proc.stdout.on('data', (d) => { stdout += d.toString(); });
33
33
  proc.stderr.on('data', (d) => { stderr += d.toString(); });
34
+ proc.on('error', (err) => {
35
+ resolve({ stdout, stderr: `could not run ${bin}: ${err.message}`, code: 127 });
36
+ });
34
37
  proc.on('close', (code) => {
35
38
  resolve({ stdout, stderr, code: code ?? 1 });
36
39
  });
@@ -51,12 +51,6 @@ export interface VersionCommandDiff {
51
51
  }
52
52
  export declare function listPluginCommandNames(): Set<string>;
53
53
  export declare function diffVersionCommands(agent: AgentId, version: string): VersionCommandDiff;
54
- export declare function installCommandToVersion(agent: AgentId, version: string, commandName: string, method?: 'symlink' | 'copy'): {
55
- success: boolean;
56
- error?: string;
57
- skipped?: boolean;
58
- skipReason?: string;
59
- };
60
54
  export declare function removeCommandFromVersion(agent: AgentId, version: string, commandName: string): {
61
55
  success: boolean;
62
56
  error?: string;
@@ -8,11 +8,11 @@ import { capableAgents, isCapable, supports } from './capabilities.js';
8
8
  import { isDirectoryDoc } from './resources.js';
9
9
  import { normalizeAliases } from './resource-aliases.js';
10
10
  import { markdownToToml } from './convert.js';
11
- import { getCommandsDir, getUserCommandsDir, getEnabledExtraRepos, getProjectAgentsDir, getSkillsDir, getTrashCommandsDir } from './state.js';
11
+ import { getCommandsDir, getUserCommandsDir, getProjectAgentsDir, getTrashCommandsDir } from './state.js';
12
12
  import { getEffectiveHome, getVersionHomePath, listInstalledVersions } from './installations/versions.js';
13
13
  import { discoverPlugins } from './plugins/plugins.js';
14
- import { commandSkillMatches, installCommandSkillToVersion, listCommandSkillsInVersion, removeCommandSkillFromVersion, shouldAlsoInstallCommandAsSkill, shouldInstallCommandAsSkill, } from './command-skills.js';
15
- import { installGooseCommandToVersion, listGooseCommandsInVersion, gooseCommandMatches, removeGooseCommandFromVersion, } from './goose-commands.js';
14
+ import { commandSkillMatches, listCommandSkillsInVersion, removeCommandSkillFromVersion, shouldAlsoInstallCommandAsSkill, shouldInstallCommandAsSkill, } from './command-skills.js';
15
+ import { listGooseCommandsInVersion, gooseCommandMatches, removeGooseCommandFromVersion, } from './goose-commands.js';
16
16
  function parseAgentsField(raw) {
17
17
  if (raw == null)
18
18
  return undefined;
@@ -45,23 +45,6 @@ export function commandAppliesTo(agent, version, metadata) {
45
45
  }
46
46
  return { ok: true };
47
47
  }
48
- function explainCommandSkip(agent, version, commandName, result) {
49
- if (result.ok)
50
- return '';
51
- const tag = `${agent}@${version}`;
52
- switch (result.reason) {
53
- case 'unsupported':
54
- return `${tag}: /${commandName} not supported for this agent version`;
55
- case 'agent_excluded':
56
- return `${tag}: /${commandName} excluded by command frontmatter agents list`;
57
- case 'too_old':
58
- return `${tag}: /${commandName} requires ${result.need}`;
59
- case 'too_new':
60
- return `${tag}: /${commandName} requires ${result.need}`;
61
- default:
62
- return `${tag}: /${commandName} skipped`;
63
- }
64
- }
65
48
  export function parseCommandMetadata(filePath) {
66
49
  if (!fs.existsSync(filePath)) {
67
50
  return null;
@@ -264,57 +247,6 @@ export function diffVersionCommands(agent, version) {
264
247
  orphans: orphans.sort(),
265
248
  };
266
249
  }
267
- export function installCommandToVersion(agent, version, commandName, method = 'copy') {
268
- const sourcePath = path.join(getCommandsDir(), `${commandName}.md`);
269
- if (!fs.existsSync(sourcePath)) {
270
- return { success: false, error: `Command '${commandName}' not found in central` };
271
- }
272
- const metadata = parseCommandMetadata(sourcePath);
273
- const gate = commandAppliesTo(agent, version, metadata);
274
- if (!gate.ok) {
275
- return { success: true, skipped: true, skipReason: explainCommandSkip(agent, version, commandName, gate) };
276
- }
277
- const versionHome = getVersionHomePath(agent, version);
278
- const agentDir = path.join(versionHome, agentConfigDirName(agent));
279
- if (shouldInstallCommandAsSkill(agent, version)) {
280
- return installCommandSkillToVersion(agentDir, commandName, sourcePath, [
281
- getSkillsDir(),
282
- ...getEnabledExtraRepos().map((repo) => path.join(repo.dir, 'skills')),
283
- ]);
284
- }
285
- if (shouldAlsoInstallCommandAsSkill(agent, version)) {
286
- const installed = installCommandSkillToVersion(agentDir, commandName, sourcePath, [getSkillsDir(), ...getEnabledExtraRepos().map((repo) => path.join(repo.dir, 'skills'))]);
287
- if (!installed.success)
288
- return installed;
289
- }
290
- if (agent === 'goose') {
291
- return installGooseCommandToVersion(versionHome, commandName, sourcePath);
292
- }
293
- const agentConfig = AGENTS[agent];
294
- const commandsDir = getVersionCommandsDir(agent, version);
295
- fs.mkdirSync(commandsDir, { recursive: true });
296
- const ext = agentConfig.format === 'toml' ? '.toml' : '.md';
297
- const targetPath = path.join(commandsDir, `${commandName}${ext}`);
298
- try {
299
- if (fs.existsSync(targetPath) || fs.lstatSync(targetPath, { throwIfNoEntry: false })) {
300
- fs.unlinkSync(targetPath);
301
- }
302
- if (agentConfig.format === 'toml') {
303
- const sourceContent = fs.readFileSync(sourcePath, 'utf-8');
304
- fs.writeFileSync(targetPath, markdownToToml(commandName, sourceContent), 'utf-8');
305
- }
306
- else if (method === 'symlink') {
307
- fs.symlinkSync(sourcePath, targetPath);
308
- }
309
- else {
310
- fs.copyFileSync(sourcePath, targetPath);
311
- }
312
- }
313
- catch (err) {
314
- return { success: false, error: err.message };
315
- }
316
- return { success: true };
317
- }
318
250
  export function removeCommandFromVersion(agent, version, commandName) {
319
251
  const versionHome = getVersionHomePath(agent, version);
320
252
  const agentDir = path.join(versionHome, agentConfigDirName(agent));
@@ -373,54 +305,9 @@ export function uninstallCommand(agentId, commandName) {
373
305
  }
374
306
  return false;
375
307
  }
376
- function listInstalledCommands(agentId) {
377
- const agent = AGENTS[agentId];
378
- const home = getEffectiveHome(agentId);
379
- const commandsDir = path.join(home, agentConfigDirName(agentId), agent.commandsSubdir);
380
- if (!fs.existsSync(commandsDir)) {
381
- return [];
382
- }
383
- const ext = agent.format === 'toml' ? '.toml' : '.md';
384
- return fs
385
- .readdirSync(commandsDir)
386
- .filter((f) => f.endsWith(ext))
387
- .map((f) => f.replace(ext, ''));
388
- }
389
- function commandExists(agentId, commandName) {
390
- const agent = AGENTS[agentId];
391
- const home = getEffectiveHome(agentId);
392
- const commandsDir = path.join(home, agentConfigDirName(agentId), agent.commandsSubdir);
393
- const ext = agent.format === 'toml' ? '.toml' : '.md';
394
- const targetPath = path.join(commandsDir, `${commandName}${ext}`);
395
- return fs.existsSync(targetPath);
396
- }
397
308
  function normalizeContent(content) {
398
309
  return content.replace(/\r\n/g, '\n').trim();
399
310
  }
400
- function commandContentMatches(agentId, commandName, sourcePath) {
401
- const agent = AGENTS[agentId];
402
- const home = getEffectiveHome(agentId);
403
- const commandsDir = path.join(home, agentConfigDirName(agentId), agent.commandsSubdir);
404
- const ext = agent.format === 'toml' ? '.toml' : '.md';
405
- const installedPath = path.join(commandsDir, `${commandName}${ext}`);
406
- if (!fs.existsSync(installedPath) || !fs.existsSync(sourcePath)) {
407
- return false;
408
- }
409
- try {
410
- const installedContent = fs.readFileSync(installedPath, 'utf-8');
411
- const sourceContent = fs.readFileSync(sourcePath, 'utf-8');
412
- const sourceIsMarkdown = sourcePath.endsWith('.md');
413
- const needsConversion = agent.format === 'toml' && sourceIsMarkdown;
414
- if (needsConversion) {
415
- const convertedSource = markdownToToml(commandName, sourceContent);
416
- return normalizeContent(installedContent) === normalizeContent(convertedSource);
417
- }
418
- return normalizeContent(installedContent) === normalizeContent(sourceContent);
419
- }
420
- catch {
421
- return false;
422
- }
423
- }
424
311
  function getProjectCommandsDirs(agentId, cwd = process.cwd()) {
425
312
  const agent = AGENTS[agentId];
426
313
  const dirs = [];
@@ -1,5 +1,3 @@
1
- import type { CommsMsg } from './mailbox.js';
2
- export type { CommsMsg } from './mailbox.js';
3
1
  export declare const GLYPH: {
4
2
  readonly live: "●";
5
3
  readonly idle: "○";
@@ -18,8 +16,4 @@ export declare function masthead(o: {
18
16
  right?: string;
19
17
  stats?: string[];
20
18
  }): string;
21
- export declare function aggregate(boxes: {
22
- id: string;
23
- label: string;
24
- messages: import('./mailbox.js').StoredMessage[];
25
- }[]): CommsMsg[];
19
+ export {};
@@ -22,22 +22,3 @@ export function masthead(o) {
22
22
  const gap = Math.max(1, terminalWidth() - stringWidth(left) - stringWidth(right));
23
23
  return `${left}${' '.repeat(gap)}${right}`;
24
24
  }
25
- export function aggregate(boxes) {
26
- return boxes
27
- .flatMap((box) => {
28
- const toLabel = box.label || box.id.slice(0, 8);
29
- return box.messages.map((message) => ({
30
- from: message.from || 'operator',
31
- to: message.to,
32
- toLabel,
33
- ts: message.ts,
34
- text: message.text,
35
- state: message.state,
36
- box: box.id,
37
- }));
38
- })
39
- .sort((a, b) => compareText(b.ts, a.ts));
40
- }
41
- function compareText(a, b) {
42
- return a < b ? -1 : a > b ? 1 : 0;
43
- }
@@ -6,6 +6,7 @@ import { spawn } from 'node:child_process';
6
6
  import { realpathSync, existsSync } from 'node:fs';
7
7
  import * as path from 'node:path';
8
8
  import { findInPath } from './agent-spec/agents.js';
9
+ import { childExitCode } from './platform/process.js';
9
10
  import { buildComputerContext } from './computer/context.js';
10
11
  const INSTALL_HINT = 'npm i -g @phnx-labs/computer-cli';
11
12
  export const COMPUTER_CONTEXT_FD = 3;
@@ -87,20 +88,10 @@ async function forwardToComputer(opts) {
87
88
  child.on('error', (err) => {
88
89
  reject(new ComputerClientError('COMPUTER_SPAWN_FAILED', `Could not run \`${bin}\`: ${err.message}`));
89
90
  });
90
- child.on('close', (code, signal) => {
91
- if (code == null)
92
- return resolve(signal ? 128 + (osSignalNumber(signal) ?? 0) : 1);
93
- resolve(code);
94
- });
91
+ child.on('close', (code, signal) => resolve(childExitCode(code, signal)));
95
92
  });
96
93
  return { exitCode, stdout };
97
94
  }
98
- function osSignalNumber(signal) {
99
- const table = {
100
- SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGPIPE: 13, SIGTERM: 15,
101
- };
102
- return table[signal];
103
- }
104
95
  export async function installComputerHelperMacLocal() {
105
96
  const { exitCode } = await forwardToComputer({ argv: ['setup'] });
106
97
  if (exitCode !== 0)
@@ -1,7 +1,7 @@
1
1
  import type { AgentId } from './types.js';
2
2
  import { type ModelTier } from './model-tiers.js';
3
- export type ConfigScope = 'run' | 'interactive' | 'auto' | 'browser' | 'project' | 'device' | 'summarizer' | 'updates' | 'menubar';
4
- export declare const MENUBAR_MENU_PROPERTIES: readonly ["defaultProject", "todoProject", "workingRowsShown", "showPreviews", "projectPriorityFilter", "hideCompletedMilestones", "bannerWhenNeedsYou", "includeOtherDeviceRequests", "groupBy", "thenBy", "projectScope", "projectSort", "ticketSort", "showPullRequests", "sessionUpdates", "showBrowserSessions", "showComputerSessions", "deviceSort", "headlessAgent", "headlessFallbackAgent", "headlessPlacement", "pinnedProjects", "tabOrder", "hiddenTabs", "groupTicketsByMilestone", "ticketGroup", "prGroupOpen", "prGroupMerged", "homeGoals", "homeSections", "sessionFilter", "artifactApps", "githubHidden", "githubDrafts", "githubBots"];
3
+ export type ConfigScope = 'run' | 'interactive' | 'auto' | 'browser' | 'project' | 'device' | 'summarizer' | 'updates' | 'menubar' | 'lead';
4
+ export declare const MENUBAR_MENU_PROPERTIES: readonly ["defaultProject", "todoProject", "workingRowsShown", "showPreviews", "projectPriorityFilter", "hideCompletedMilestones", "bannerWhenNeedsYou", "includeOtherDeviceRequests", "groupBy", "thenBy", "projectScope", "projectSort", "ticketSort", "showPullRequests", "sessionUpdates", "showBrowserSessions", "showComputerSessions", "deviceSort", "headlessAgent", "headlessFallbackAgent", "headlessPlacement", "pinnedProjects", "tabOrder", "hiddenTabs", "groupTicketsByMilestone", "ticketGroup", "prGroupOpen", "prGroupMerged", "homeGoals", "homeSections", "sessionFilter", "artifactApps", "githubHidden", "githubDrafts", "githubBots", "notifyUrgent", "notifyHigh", "notifyNormal", "notifyLow"];
5
5
  export declare const MENUBAR_STATUSBAR_PROPERTIES: readonly ["goalCountdown"];
6
6
  export type MenubarSection = 'menu' | 'statusbar';
7
7
  export declare const MENUBAR_CONFIG_KEYS: readonly string[];
@@ -38,6 +38,10 @@ export interface ParsedSummarizerConfigKey {
38
38
  scope: 'summarizer';
39
39
  property: 'enabled' | 'baseUrl' | 'model';
40
40
  }
41
+ export interface ParsedLeadConfigKey {
42
+ scope: 'lead';
43
+ property: 'model';
44
+ }
41
45
  export interface ParsedUpdatesConfigKey {
42
46
  scope: 'updates';
43
47
  property: 'auto';
@@ -48,7 +52,7 @@ export interface ParsedMenubarConfigKey {
48
52
  section?: MenubarSection;
49
53
  property: string;
50
54
  }
51
- export type ParsedConfigKey = ParsedRunConfigKey | ParsedInteractiveConfigKey | ParsedAutoConfigKey | ParsedBrowserConfigKey | ParsedProjectConfigKey | ParsedDeviceConfigKey | ParsedSummarizerConfigKey | ParsedUpdatesConfigKey | ParsedMenubarConfigKey;
55
+ export type ParsedConfigKey = ParsedRunConfigKey | ParsedInteractiveConfigKey | ParsedAutoConfigKey | ParsedBrowserConfigKey | ParsedProjectConfigKey | ParsedDeviceConfigKey | ParsedSummarizerConfigKey | ParsedUpdatesConfigKey | ParsedMenubarConfigKey | ParsedLeadConfigKey;
52
56
  export type DeviceConfigProperty = 'role' | 'max-agents' | 'scheduler' | 'daemon' | 'watchdog' | 'tmux' | 'browser.remote-control' | 'browser.task-idle-minutes' | 'notes' | 'browser.profile' | 'browser.viewer' | 'formFactor';
53
57
  export declare function formatAgentVersion(agent: AgentId, version: string): string;
54
58
  export declare function parseConfigKey(key: string): ParsedConfigKey;
@@ -37,6 +37,10 @@ export const MENUBAR_MENU_PROPERTIES = [
37
37
  'githubHidden',
38
38
  'githubDrafts',
39
39
  'githubBots',
40
+ 'notifyUrgent',
41
+ 'notifyHigh',
42
+ 'notifyNormal',
43
+ 'notifyLow',
40
44
  ];
41
45
  export const MENUBAR_STATUSBAR_PROPERTIES = ['goalCountdown'];
42
46
  export const MENUBAR_CONFIG_KEYS = [
@@ -110,6 +114,8 @@ export function parseConfigKey(key) {
110
114
  if (summarizerMatch) {
111
115
  return { scope: 'summarizer', property: summarizerMatch[1] };
112
116
  }
117
+ if (raw === 'lead.model')
118
+ return { scope: 'lead', property: 'model' };
113
119
  if (raw === 'menubar.enabled')
114
120
  return { scope: 'menubar', property: 'enabled' };
115
121
  if (raw === 'menubar.autoUpdate')
@@ -158,6 +164,9 @@ export function parseConfigKey(key) {
158
164
  if (raw.startsWith('summarizer.')) {
159
165
  throw new Error(`Invalid summarizer config key '${key}'. Use summarizer.enabled, summarizer.baseUrl, or summarizer.model.`);
160
166
  }
167
+ if (raw.startsWith('lead.')) {
168
+ throw new Error(`Invalid lead config key '${key}'. Use lead.model.`);
169
+ }
161
170
  if (raw.startsWith('updates.')) {
162
171
  throw new Error(`Invalid updates config key '${key}'. Use updates.auto or updates.<agent>.auto.`);
163
172
  }
@@ -167,7 +176,7 @@ export function parseConfigKey(key) {
167
176
  if (raw.startsWith('devices.')) {
168
177
  throw new Error(`Invalid device config key '${key}'. Expected devices.<name>.<${DEVICE_CONFIG_PROPERTIES.join('|')}>.`);
169
178
  }
170
- throw new Error(`Unknown config scope in '${key}'. Use one of: run, interactive, auto, browser, project, devices, summarizer, updates, menubar.`);
179
+ throw new Error(`Unknown config scope in '${key}'. Use one of: run, interactive, auto, browser, project, devices, summarizer, updates, menubar, lead.`);
171
180
  }
172
181
  export function formatConfigKey(parsed) {
173
182
  switch (parsed.scope) {
@@ -194,6 +203,8 @@ export function formatConfigKey(parsed) {
194
203
  return parsed.agent ? `updates.${parsed.agent}.auto` : 'updates.auto';
195
204
  case 'menubar':
196
205
  return parsed.section ? `menubar.${parsed.section}.${parsed.property}` : `menubar.${parsed.property}`;
206
+ case 'lead':
207
+ return 'lead.model';
197
208
  }
198
209
  }
199
210
  export function listKnownConfigKeys() {
@@ -202,7 +213,7 @@ export function listKnownConfigKeys() {
202
213
  for (const tier of MODEL_TIERS) {
203
214
  keys.push(`run.<agent@version>.tier.${tier}`);
204
215
  }
205
- keys.push('interactive.host', 'auto.pool', 'browser.profile', 'browser.viewer', 'browser.device', 'project.root', 'summarizer.enabled', 'summarizer.baseUrl', 'summarizer.model', 'updates.auto', 'updates.<agent>.auto');
216
+ keys.push('interactive.host', 'auto.pool', 'browser.profile', 'browser.viewer', 'browser.device', 'project.root', 'summarizer.enabled', 'summarizer.baseUrl', 'summarizer.model', 'updates.auto', 'updates.<agent>.auto', 'lead.model');
206
217
  keys.push(...MENUBAR_CONFIG_KEYS);
207
218
  for (const prop of DEVICE_CONFIG_PROPERTIES) {
208
219
  keys.push(`devices.<name>.${prop}`);
@@ -271,6 +282,8 @@ export function configKeyStorageHint(parsed) {
271
282
  return parsed.agent
272
283
  ? `config.updatesAgentAuto.${parsed.agent} (central agents.yaml; syncs fleet-wide)`
273
284
  : 'config.updatesAuto (central agents.yaml; syncs fleet-wide)';
285
+ case 'lead':
286
+ return 'config.leadModel (central agents.yaml; syncs fleet-wide)';
274
287
  case 'menubar':
275
288
  if (parsed.property === 'enabled')
276
289
  return 'devices/<self>/agents.yaml config.menubarEnabled';
@@ -16,24 +16,10 @@ export interface DetectedRuntime {
16
16
  credPath: string | null;
17
17
  }
18
18
  export declare function detectSignedInRuntimes(): Promise<DetectedRuntime[]>;
19
- export declare function pickRuntimes(detected: DetectedRuntime[], prompt?: (choices: {
20
- name: string;
21
- value: AgentId;
22
- checked: boolean;
23
- disabled: boolean | string;
24
- }[]) => Promise<AgentId[]>): Promise<AgentId[]>;
25
19
  export declare function inferLeaseRuntime(agentName: string, detected: DetectedRuntime[]): AgentId | null;
26
20
  export declare function profileNeedsBaseRuntimeCredentials(agent: AgentId, env: Record<string, string>, authEnvVar?: string): boolean;
27
21
  export declare function buildHomeFileWriteScript(remote: string, contents: string): string;
28
22
  export declare const CLAUDE_TOKEN_REMOTE = ".claude/.credentials.json";
29
- export declare function resolveClaudeCredentialsBlob(opts?: {
30
- preferEmail?: string | null;
31
- readItem?: (service: string) => string;
32
- service?: (home?: string) => string;
33
- listVersions?: () => string[];
34
- versionHome?: (version: string) => string;
35
- accountEmail?: (home: string) => Promise<string | null>;
36
- }): Promise<string | null>;
37
23
  export declare function refusedNativeOAuthRuntimes(picked: AgentId[], detected: DetectedRuntime[], extras?: {
38
24
  claudeCredentialsJson?: string | null;
39
25
  }): AgentId[];
@@ -2,9 +2,6 @@ import * as os from 'os';
2
2
  import * as path from 'path';
3
3
  import * as fs from 'fs';
4
4
  import { getAccountInfo } from '../agents.js';
5
- import { getKeychainTokenSync } from '../secrets-client.js';
6
- import { getClaudeKeychainService } from '../accounting/usage.js';
7
- import { listInstalledVersions, getVersionHomePath } from '../installations/versions.js';
8
5
  export const LEASE_RUNTIMES = [
9
6
  { id: 'claude', label: 'Claude Code', localCandidates: ['.claude/.claude.json', '.claude.json'], remote: '.claude.json' },
10
7
  { id: 'codex', label: 'Codex CLI', localCandidates: ['.codex/auth.json'], remote: '.codex/auth.json' },
@@ -69,18 +66,6 @@ export async function detectSignedInRuntimes() {
69
66
  }
70
67
  return out;
71
68
  }
72
- export async function pickRuntimes(detected, prompt) {
73
- const choices = detected.map((d) => ({
74
- name: `${d.label}${d.email ? ` (${d.email})` : d.signedIn ? ' (signed in)' : ''}`,
75
- value: d.id,
76
- checked: d.signedIn && !!d.credPath,
77
- disabled: d.credPath ? false : 'no local credential — sign in first',
78
- }));
79
- if (prompt)
80
- return prompt(choices);
81
- const { checkbox } = await import('@inquirer/prompts');
82
- return checkbox({ message: 'Provision which runtime(s) on the leased box?', choices });
83
- }
84
69
  export function inferLeaseRuntime(agentName, detected) {
85
70
  const signedIn = detected.filter((d) => d.signedIn && d.credPath);
86
71
  if (LEASE_RUNTIMES.some((c) => c.id === agentName)) {
@@ -118,71 +103,6 @@ export function buildHomeFileWriteScript(remote, contents) {
118
103
  `chmod 600 "$HOME/${remote}"`);
119
104
  }
120
105
  export const CLAUDE_TOKEN_REMOTE = '.claude/.credentials.json';
121
- function isClaudeCredentialsBlob(s) {
122
- try {
123
- const p = JSON.parse(s);
124
- return typeof p?.claudeAiOauth?.accessToken === 'string';
125
- }
126
- catch {
127
- return false;
128
- }
129
- }
130
- export async function resolveClaudeCredentialsBlob(opts) {
131
- const readItem = opts?.readItem ?? getKeychainTokenSync;
132
- const service = opts?.service ?? getClaudeKeychainService;
133
- const listVersions = opts?.listVersions ?? (() => listInstalledVersions('claude'));
134
- const versionHome = opts?.versionHome ?? ((v) => getVersionHomePath('claude', v));
135
- const accountEmail = opts?.accountEmail ?? (async (home) => (await getAccountInfo('claude', home)).email);
136
- const tryRead = (svc) => {
137
- try {
138
- const raw = readItem(svc).trim();
139
- return isClaudeCredentialsBlob(raw) ? raw : null;
140
- }
141
- catch {
142
- return null;
143
- }
144
- };
145
- if (process.platform === 'darwin') {
146
- const bare = tryRead(service(undefined));
147
- if (bare) {
148
- if (!opts?.preferEmail)
149
- return bare;
150
- const realHome = process.env.AGENTS_REAL_HOME || os.homedir();
151
- const bareEmail = await accountEmail(realHome).catch(() => null);
152
- if (bareEmail === opts.preferEmail)
153
- return bare;
154
- }
155
- let homes;
156
- try {
157
- homes = listVersions().map(versionHome);
158
- }
159
- catch {
160
- homes = [];
161
- }
162
- if (opts?.preferEmail) {
163
- const scored = await Promise.all(homes.map(async (home) => ({ home, match: (await accountEmail(home).catch(() => null)) === opts.preferEmail })));
164
- homes = [...scored.filter((s) => s.match), ...scored.filter((s) => !s.match)].map((s) => s.home);
165
- }
166
- for (const home of homes) {
167
- const hit = tryRead(service(home));
168
- if (hit)
169
- return hit;
170
- }
171
- return null;
172
- }
173
- const home = process.env.AGENTS_REAL_HOME || os.homedir();
174
- const credsPath = path.join(home, '.claude', '.credentials.json');
175
- try {
176
- if (fs.existsSync(credsPath)) {
177
- const raw = fs.readFileSync(credsPath, 'utf-8').trim();
178
- if (raw && isClaudeCredentialsBlob(raw))
179
- return raw;
180
- }
181
- }
182
- catch {
183
- }
184
- return null;
185
- }
186
106
  export function refusedNativeOAuthRuntimes(picked, detected, extras) {
187
107
  const byId = new Map(detected.map((d) => [d.id, d]));
188
108
  return picked.filter((id) => {
@@ -1,37 +1,44 @@
1
1
  /**
2
- * Attention desktop banners as a supervised periodic service (PHNX-4004).
3
- *
4
- * Each tick reconciles this host's live sessions into attention items through
5
- * the CLI-owned reconciler (feed/attention.ts — never re-deriving detection) and
6
- * posts ONE actionable desktop banner per attention key not yet notified. The
7
- * banner carries the category, the attention key, the session id, and the
8
- * answerable choices, so the macOS companion can offer Approve / Approve for
9
- * session / Deny (permission), the options plus a typed reply (question),
10
- * Approve / Send back (plan review), or Open terminal (a stall/failure, or a
11
- * request the CLI could not verify is still pending), and route the answer back
12
- * through `agents feed answer <key> --choice <id>`. The kind — and so the button
13
- * set — is the reconciler's verdict from explicit harness evidence; an idle
14
- * reminder never reaches here as a permission (PHNX-3999).
15
- *
16
- * Idempotency is a filesystem ledger, not memory: one sidecar file per notified
17
- * key under `~/.agents/.history/feed/notified/`, so a daemon restart never
18
- * re-posts a banner already sent — the ledger is the truth. It is pruned with
19
- * the feed's 14-day retention rule.
20
- *
21
- * Reader-independent: unlike the session-state publisher this does NOT gate on a
22
- * live `sessions watch` reader — an attention banner must fire whether or not
23
- * anyone is watching the stream. `done` banners are deliberately NOT produced
24
- * here; they ride the run process's own exit (`run-notify.ts`).
2
+ * Attention desktop banners (PHNX-4004, PHNX-4369). Each tick takes the open asks
3
+ * from the CLI-owned reconciler (feed/attention.ts) and drives each banner along
4
+ * its urgency level's schedule (`menubar.menu.notify*`): first banner, reminders
5
+ * (same identifier, so they replace it), withdraw on resolve, and withdraw ~10 s
6
+ * after posting when the level has no `stay` (macOS alert style is app-wide).
7
+ * `interactive.host` unset: this host's asks; this machine: every host's, from
8
+ * the shared fleet collector; another machine: none. The ledger under
9
+ * `feed/notified/` (`<key>`, `<key>#r<n>`) makes a restart re-send nothing.
10
+ * `done` banners ride the run process's exit (`run-notify.ts`), not this service.
25
11
  */
26
12
  import { type ActiveSession } from '../session/active.js';
27
- import { type AttentionItem } from '../feed/attention.js';
13
+ import { type AttentionItem, type AttentionUrgency } from '../feed/attention.js';
14
+ import type { FeedHub } from '../feed/hub.js';
15
+ import { type NotifySchedule } from '../feed/notify-schedule.js';
28
16
  import { type DesktopNotification } from '../menubar/notify-desktop.js';
29
17
  import { BasePeriodicService, type DaemonContext } from './service.js';
30
18
  import type { DaemonServiceId } from '../daemon-services.js';
31
- export declare function buildAttentionNotification(item: AttentionItem, session: ActiveSession): DesktopNotification | undefined;
19
+ export declare const BANNER_HIDE_AFTER_MS = 10000;
20
+ type BannerSession = Partial<Pick<ActiveSession, 'label' | 'title' | 'harness' | 'kind'>>;
21
+ export interface AttentionAsk {
22
+ item: AttentionItem;
23
+ session: BannerSession;
24
+ }
25
+ export type NotifyScope = 'local' | 'fleet' | 'none';
26
+ export interface AttentionNotifySettings {
27
+ interactiveHost?: string;
28
+ schedules: Record<AttentionUrgency, NotifySchedule>;
29
+ }
30
+ export declare function buildAttentionNotification(item: AttentionItem, session: BannerSession): DesktopNotification | undefined;
31
+ export declare function notifyScope(interactiveHost: string | undefined, self: string): NotifyScope;
32
+ export declare function readAttentionNotifySettings(): AttentionNotifySettings;
33
+ export declare function dueStage(schedule: NotifySchedule, openedMs: number, nowMs: number): number;
32
34
  interface AttentionNotifyServiceOptions {
33
35
  getSessions?: () => Promise<ActiveSession[]>;
34
36
  notify?: (n: DesktopNotification) => void;
37
+ withdraw?: (keys: string[]) => void;
38
+ fleetHub?: () => FeedHub;
39
+ settings?: () => AttentionNotifySettings;
40
+ self?: () => string;
41
+ gc?: (activeBoxIds: Set<string>) => void;
35
42
  feedRoot?: string;
36
43
  ledgerDir?: string;
37
44
  now?: () => number;
@@ -42,17 +49,33 @@ export declare class AttentionNotifyService extends BasePeriodicService {
42
49
  readonly deadlineMs = 10000;
43
50
  private readonly getSessions;
44
51
  private readonly notify;
52
+ private readonly withdraw;
53
+ private readonly fleetHubOf;
54
+ private readonly readSettings;
55
+ private readonly self;
56
+ private readonly gc;
45
57
  private readonly feedRoot?;
46
58
  private readonly ledgerDir;
47
59
  private readonly now;
48
- private lastPruneMs;
60
+ private lastHourlyMs;
61
+ private settingsCache?;
62
+ private banners;
63
+ private fleetHub;
64
+ private detachFleet;
49
65
  constructor(opts?: AttentionNotifyServiceOptions);
50
66
  protected onStart(_ctx: DaemonContext): Promise<void>;
51
67
  protected onStop(): Promise<void>;
52
68
  protected onTick(ctx: DaemonContext): Promise<void>;
69
+ private settings;
70
+ private localAsks;
71
+ private fleetAsks;
72
+ private releaseFleet;
53
73
  private ledgerPath;
54
- private hasNotified;
55
- private markNotified;
74
+ private loadBanners;
75
+ private stageSent;
76
+ private recordStage;
77
+ private writeState;
78
+ private hourly;
56
79
  private pruneLedger;
57
80
  }
58
81
  export {};