@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
@@ -1,43 +1,37 @@
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 * as fs from 'fs';
27
13
  import * as path from 'path';
28
14
  import { atomicWriteFile } from '../fs-atomic.js';
29
15
  import { getFeedDir } from '../state.js';
30
- import { machineId } from '../machine-id.js';
16
+ import { machineId, normalizeHost } from '../machine-id.js';
17
+ import { getConfigValue } from '../device-config.js';
31
18
  import { getActiveSessions } from '../session/active.js';
19
+ import { mailboxIdForActiveSession } from '../mailbox-target.js';
20
+ import { gcMailbox } from '../mailbox-gc.js';
32
21
  import { blockIdForSession, readBlock, readResolution } from '../feed/feed.js';
33
22
  import { reconcileAttention, harnessOf } from '../feed/attention.js';
34
- import { notifyDesktop } from '../menubar/notify-desktop.js';
23
+ import { cachedTicketPriority } from '../feed/ticket-priority.js';
24
+ import { sharedFleetFeedHub } from '../feed/watch.js';
25
+ import { DEFAULT_NOTIFY_SCHEDULES, NOTIFY_LEVELS, NOTIFY_LEVEL_KEYS, formatWaited, parseNotifySchedule, } from '../feed/notify-schedule.js';
26
+ import { notifyDesktop, withdrawDesktop } from '../menubar/notify-desktop.js';
35
27
  import { BasePeriodicService } from './service.js';
36
28
  import { span, spanSync } from './diagnostics.js';
37
29
  const ATTENTION_NOTIFY_TICK_MS = 5_000;
38
30
  const ATTENTION_NOTIFY_DEADLINE_MS = 10_000;
39
31
  const LEDGER_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
40
- const LEDGER_PRUNE_EVERY_MS = 60 * 60 * 1000;
32
+ const HOURLY_MS = 60 * 60 * 1000;
33
+ const SETTINGS_TTL_MS = 30_000;
34
+ export const BANNER_HIDE_AFTER_MS = 10_000;
41
35
  const MAX_CHOICES = 6;
42
36
  const BODY_MAX = 200;
43
37
  const BANNER_KINDS = {
@@ -79,32 +73,150 @@ export function buildAttentionNotification(item, session) {
79
73
  n.choices = choices;
80
74
  return n;
81
75
  }
76
+ export function notifyScope(interactiveHost, self) {
77
+ if (!interactiveHost?.trim())
78
+ return 'local';
79
+ return normalizeHost(interactiveHost) === normalizeHost(self) ? 'fleet' : 'none';
80
+ }
81
+ export function readAttentionNotifySettings() {
82
+ const schedules = {};
83
+ for (const level of NOTIFY_LEVELS) {
84
+ const stored = getConfigValue(NOTIFY_LEVEL_KEYS[level]).value;
85
+ const parsed = parseNotifySchedule(Array.isArray(stored) ? stored.map(String) : DEFAULT_NOTIFY_SCHEDULES[level]);
86
+ // A hand-edited agents.yaml can hold what `config set` refuses; the level then keeps its default.
87
+ schedules[level] = typeof parsed === 'string' ? parseNotifySchedule(DEFAULT_NOTIFY_SCHEDULES[level]) : parsed;
88
+ }
89
+ const host = getConfigValue('interactive.host').value;
90
+ return { interactiveHost: typeof host === 'string' ? host : undefined, schedules };
91
+ }
92
+ export function dueStage(schedule, openedMs, nowMs) {
93
+ if (schedule.sidebar)
94
+ return -1;
95
+ let stage = -1;
96
+ schedule.atMs.forEach((at, i) => { if (openedMs + at <= nowMs)
97
+ stage = i; });
98
+ return stage;
99
+ }
82
100
  export class AttentionNotifyService extends BasePeriodicService {
83
101
  id = 'attention-notify';
84
102
  intervalMs = ATTENTION_NOTIFY_TICK_MS;
85
103
  deadlineMs = ATTENTION_NOTIFY_DEADLINE_MS;
86
104
  getSessions;
87
105
  notify;
106
+ withdraw;
107
+ fleetHubOf;
108
+ readSettings;
109
+ self;
110
+ gc;
88
111
  feedRoot;
89
112
  ledgerDir;
90
113
  now;
91
- lastPruneMs = 0;
114
+ lastHourlyMs = 0;
115
+ settingsCache;
116
+ banners = null;
117
+ fleetHub = null;
118
+ detachFleet = null;
92
119
  constructor(opts = {}) {
93
120
  super();
94
121
  this.getSessions = opts.getSessions ?? (() => getActiveSessions());
95
122
  this.notify = opts.notify ?? notifyDesktop;
123
+ this.withdraw = opts.withdraw ?? withdrawDesktop;
124
+ this.fleetHubOf = opts.fleetHub ?? sharedFleetFeedHub;
125
+ this.readSettings = opts.settings ?? readAttentionNotifySettings;
126
+ this.self = opts.self ?? machineId;
96
127
  this.feedRoot = opts.feedRoot;
128
+ this.gc = opts.gc ?? ((ids) => { gcMailbox(ids, { feedRoot: this.feedRoot }); });
97
129
  this.ledgerDir = opts.ledgerDir ?? path.join(opts.feedRoot ?? getFeedDir(), 'notified');
98
130
  this.now = opts.now ?? Date.now;
99
131
  }
100
132
  async onStart(_ctx) {
101
133
  }
102
134
  async onStop() {
135
+ this.releaseFleet();
103
136
  }
104
137
  async onTick(ctx) {
105
- const sessions = await span('attention.sessions', () => this.getSessions(), () => ({}));
106
- const host = machineId();
138
+ const nowMs = this.now();
139
+ const settings = this.settings(nowMs);
140
+ const scope = notifyScope(settings.interactiveHost, this.self());
141
+ if (scope !== 'fleet')
142
+ this.releaseFleet();
143
+ const local = scope === 'local' ? await this.localAsks(nowMs) : undefined;
144
+ const { asks, scopes } = local
145
+ ? { asks: local.asks, scopes: null }
146
+ : scope === 'fleet'
147
+ ? this.fleetAsks()
148
+ : { asks: [], scopes: null };
149
+ const banners = await this.loadBanners();
150
+ const toWithdraw = [];
151
+ const seen = new Set();
107
152
  let posted = 0;
153
+ for (const { item, session } of asks) {
154
+ if (!BANNER_KINDS[item.kind])
155
+ continue;
156
+ seen.add(item.key);
157
+ const level = item.urgency ?? 'normal';
158
+ const schedule = settings.schedules[level];
159
+ if (schedule.sidebar)
160
+ continue;
161
+ const opened = Date.parse(item.openedAt);
162
+ const openedMs = Number.isFinite(opened) ? opened : nowMs;
163
+ const stage = dueStage(schedule, openedMs, nowMs);
164
+ if (stage < 0 || await this.stageSent(item.key, stage, banners))
165
+ continue;
166
+ const notification = buildAttentionNotification(item, session);
167
+ if (!notification)
168
+ continue;
169
+ notification.level = level;
170
+ if (schedule.sound)
171
+ notification.sound = true;
172
+ if (stage > 0) {
173
+ notification.reminder = stage;
174
+ notification.subtitle = [notification.subtitle, `Still waiting · ${formatWaited(nowMs - openedMs)}`].filter(Boolean).join(' · ');
175
+ }
176
+ this.notify(notification);
177
+ await this.recordStage(banners, {
178
+ key: item.key,
179
+ postedAt: new Date(nowMs).toISOString(),
180
+ level,
181
+ stage,
182
+ bannerUp: true,
183
+ ...(schedule.stay ? {} : { hideAt: nowMs + BANNER_HIDE_AFTER_MS }),
184
+ });
185
+ posted += 1;
186
+ ctx.log('INFO', `attention-notify: posted ${level} ${item.kind} banner for ${item.key}${stage ? ` (reminder ${stage})` : ''}`, { event: 'attention.posted', kind: item.kind, key: item.key, level, reminder: stage });
187
+ }
188
+ for (const state of banners.values()) {
189
+ const resolved = !seen.has(state.key) && (scopes === null || scopes.has(state.key.split('/')[0]));
190
+ if (resolved) {
191
+ if (state.bannerUp)
192
+ toWithdraw.push(state.key);
193
+ banners.delete(state.key);
194
+ await this.writeState({ ...state, bannerUp: false, resolvedAt: new Date(nowMs).toISOString() });
195
+ }
196
+ else if (state.bannerUp && state.hideAt !== undefined && nowMs >= state.hideAt) {
197
+ toWithdraw.push(state.key);
198
+ state.bannerUp = false;
199
+ delete state.hideAt;
200
+ await this.writeState(state);
201
+ }
202
+ }
203
+ if (toWithdraw.length) {
204
+ this.withdraw(toWithdraw);
205
+ ctx.log('INFO', `attention-notify: withdrew ${toWithdraw.length} banner(s)`, { event: 'attention.withdrawn', keys: toWithdraw });
206
+ }
207
+ await this.hourly(ctx, nowMs, local?.sessions);
208
+ ctx.log('DEBUG', `attention-notify: ${asks.length} ask(s) in ${scope} scope, ${posted} banner(s) posted`, { event: 'attention.tick', scope, asks: asks.length, posted });
209
+ }
210
+ settings(nowMs) {
211
+ if (!this.settingsCache || nowMs - this.settingsCache.at >= SETTINGS_TTL_MS || nowMs < this.settingsCache.at) {
212
+ this.settingsCache = { at: nowMs, value: this.readSettings() };
213
+ }
214
+ return this.settingsCache.value;
215
+ }
216
+ async localAsks(nowMs) {
217
+ const sessions = await span('attention.sessions', () => this.getSessions(), () => ({}));
218
+ const host = normalizeHost(this.self());
219
+ const asks = [];
108
220
  for (const session of sessions) {
109
221
  if (!session.sessionId)
110
222
  continue;
@@ -114,44 +226,98 @@ export class AttentionNotifyService extends BasePeriodicService {
114
226
  block: readBlock(blockId, this.feedRoot),
115
227
  session: projected,
116
228
  resolution: readResolution(blockId, this.feedRoot),
117
- nowMs: this.now(),
229
+ ticketPriority: (ticketId) => cachedTicketPriority(ticketId, nowMs),
230
+ nowMs,
118
231
  }));
119
- if (!item || !BANNER_KINDS[item.kind])
120
- continue;
121
- if (await this.hasNotified(item.key))
122
- continue;
123
- const notification = buildAttentionNotification(item, projected);
124
- if (!notification)
125
- continue;
126
- this.notify(notification);
127
- await this.markNotified(item.key);
128
- posted += 1;
129
- ctx.log('INFO', `attention-notify: posted ${item.kind} banner for ${item.key}`, { event: 'attention.posted', kind: item.kind, key: item.key });
232
+ if (item)
233
+ asks.push({ item, session: projected });
234
+ }
235
+ return { asks, sessions };
236
+ }
237
+ fleetAsks() {
238
+ const hub = this.fleetHubOf();
239
+ // The feed-stream service closes the shared hub when it stops; re-attach rather than read a dead stream.
240
+ if (this.fleetHub !== hub || !this.detachFleet || !hub.active) {
241
+ this.releaseFleet();
242
+ this.fleetHub = hub;
243
+ this.detachFleet = hub.subscribe(() => { });
130
244
  }
131
- await this.pruneLedger();
132
- ctx.log('DEBUG', `attention-notify: ${sessions.length} session(s) reconciled, ${posted} banner(s) posted`, { event: 'attention.tick', sessions: sessions.length, posted });
245
+ const asks = hub.state.attention().map(({ item, agent }) => ({
246
+ item: item.urgency ? item : { ...item, urgency: 'normal' },
247
+ session: agent ?? {},
248
+ }));
249
+ return { asks, scopes: hub.state.reportingScopes };
133
250
  }
134
- ledgerPath(key) {
135
- return path.join(this.ledgerDir, encodeURIComponent(key));
251
+ releaseFleet() {
252
+ this.detachFleet?.();
253
+ this.detachFleet = null;
254
+ this.fleetHub = null;
255
+ }
256
+ ledgerPath(key, stage = 0) {
257
+ return path.join(this.ledgerDir, encodeURIComponent(stage ? `${key}#r${stage}` : key));
258
+ }
259
+ async loadBanners() {
260
+ if (this.banners)
261
+ return this.banners;
262
+ const banners = new Map();
263
+ let names = [];
264
+ try {
265
+ names = await fs.promises.readdir(this.ledgerDir);
266
+ }
267
+ catch {
268
+ }
269
+ for (const name of names) {
270
+ if (name.includes('%23r'))
271
+ continue;
272
+ try {
273
+ const state = JSON.parse(await fs.promises.readFile(path.join(this.ledgerDir, name), 'utf-8'));
274
+ if (state.key && state.level && typeof state.stage === 'number' && !state.resolvedAt)
275
+ banners.set(state.key, state);
276
+ }
277
+ catch {
278
+ }
279
+ }
280
+ this.banners = banners;
281
+ return banners;
136
282
  }
137
- async hasNotified(key) {
283
+ async stageSent(key, stage, banners) {
284
+ const known = banners.get(key);
285
+ if (known && known.stage >= stage)
286
+ return true;
138
287
  try {
139
- await fs.promises.stat(this.ledgerPath(key));
288
+ await fs.promises.stat(this.ledgerPath(key, stage));
140
289
  return true;
141
290
  }
142
291
  catch {
143
292
  return false;
144
293
  }
145
294
  }
146
- async markNotified(key) {
295
+ async recordStage(banners, state) {
296
+ banners.set(state.key, state);
297
+ await this.writeState(state);
298
+ for (let reminder = 1; reminder <= state.stage; reminder += 1) {
299
+ await atomicWriteFile(this.ledgerPath(state.key, reminder), JSON.stringify({ key: state.key, reminder, postedAt: state.postedAt }), 'utf-8');
300
+ }
301
+ }
302
+ async writeState(state) {
147
303
  await fs.promises.mkdir(this.ledgerDir, { recursive: true });
148
- await atomicWriteFile(this.ledgerPath(key), JSON.stringify({ key, postedAt: new Date(this.now()).toISOString() }), 'utf-8');
304
+ await atomicWriteFile(this.ledgerPath(state.key), JSON.stringify(state), 'utf-8');
149
305
  }
150
- async pruneLedger() {
151
- const nowMs = this.now();
152
- if (nowMs - this.lastPruneMs < LEDGER_PRUNE_EVERY_MS)
306
+ async hourly(ctx, nowMs, fetched) {
307
+ if (nowMs - this.lastHourlyMs < HOURLY_MS)
153
308
  return;
154
- this.lastPruneMs = nowMs;
309
+ this.lastHourlyMs = nowMs;
310
+ await this.pruneLedger(nowMs);
311
+ try {
312
+ const sessions = fetched ?? await this.getSessions();
313
+ const active = new Set(sessions.map(mailboxIdForActiveSession).filter((id) => !!id));
314
+ spanSync('attention.gc', () => this.gc(active));
315
+ }
316
+ catch (err) {
317
+ ctx.log('WARN', `attention-notify: mailbox gc skipped: ${err.message}`, { event: 'attention.gc.failed' });
318
+ }
319
+ }
320
+ async pruneLedger(nowMs) {
155
321
  let names;
156
322
  try {
157
323
  names = await fs.promises.readdir(this.ledgerDir);
@@ -1259,8 +1259,7 @@ function waitForPid(timeoutMs) {
1259
1259
  const pid = readDaemonPid();
1260
1260
  if (pid)
1261
1261
  return pid;
1262
- const waitUntil = Date.now() + 200;
1263
- while (Date.now() < waitUntil) { }
1262
+ sleepSync(200);
1264
1263
  }
1265
1264
  return readDaemonPid();
1266
1265
  }
@@ -1,13 +1,11 @@
1
1
  import { BaseDaemonService } from './service.js';
2
- import { FeedHub } from '../feed/hub.js';
3
2
  import { FeedHubServer } from '../feed/hub-server.js';
4
- import { sharedLocalFeedHub, watchFleetFeed } from '../feed/watch.js';
3
+ import { sharedFleetFeedHub, sharedLocalFeedHub } from '../feed/watch.js';
5
4
  export class FeedStreamService extends BaseDaemonService {
6
5
  id = 'feed-stream';
7
6
  server = null;
8
7
  async onStart(ctx) {
9
- const fleet = new FeedHub({ watch: watchFleetFeed });
10
- this.server = new FeedHubServer(fleet, undefined, sharedLocalFeedHub());
8
+ this.server = new FeedHubServer(sharedFleetFeedHub(), undefined, sharedLocalFeedHub());
11
9
  await this.server.start();
12
10
  ctx.log('INFO', 'Feed stream hub listening (fan-out starts on first reader)');
13
11
  }
@@ -50,10 +50,6 @@ export declare function configuredDeviceRole(name: string): ConfiguredDeviceRole
50
50
  export declare function selfConfiguredDeviceRole(): ConfiguredDeviceRole | undefined;
51
51
  export declare function isHeadedDeviceRole(role: ConfiguredDeviceRole | undefined): boolean;
52
52
  export declare function setConfiguredDeviceRole(name: string, role: ConfiguredDeviceRole | undefined): void;
53
- export declare function devicesPinningBrowserProfile(profile: string): Array<{
54
- device: string;
55
- key: 'browser.profile' | 'browser.viewer';
56
- }>;
57
53
  export declare function listConfiguredDeviceRoles(roster?: string[]): Record<string, ConfiguredDeviceRole>;
58
54
  export declare function autoPoolMode(): AutoPoolMode;
59
55
  export interface AutoLaunchPreference {
@@ -70,6 +66,5 @@ export declare function assertSchedulerEnabled(): void;
70
66
  export declare function isTmuxEnabled(): boolean;
71
67
  export declare function isDaemonEnabled(): boolean;
72
68
  export declare function assertDaemonEnabled(): void;
73
- export declare function resolveBrowserTaskIdleMs(): Promise<number | null>;
74
69
  export declare function readMaxConcurrentCaps(devices: string[]): Record<string, number>;
75
70
  export {};
@@ -8,6 +8,7 @@ import { machineId } from './machine-id.js';
8
8
  import { assertValidDeviceName, assertRegistrableDeviceName } from './devices/registry.js';
9
9
  import { migrateDeviceConfigStores } from './devices/config-migration.js';
10
10
  import { isAgentId } from './types.js';
11
+ import { DEFAULT_NOTIFY_SCHEDULES, NOTIFY_LEVELS, NOTIFY_LEVEL_KEYS, notifyScheduleDescription, validateNotifySchedule } from './feed/notify-schedule.js';
11
12
  const DEVICE_PLATFORMS = ['windows', 'linux', 'macos', 'unknown'];
12
13
  const SSH_AUTH_METHODS = ['key', 'password'];
13
14
  const DEVICE_ROLES = ['worker', 'personal', 'desktop'];
@@ -86,6 +87,16 @@ export const CONFIG_KEYS = [
86
87
  type: 'string',
87
88
  description: 'Model the summarizer requests from summarizer.baseUrl, e.g. qwen2.5:3b. Overridden per-process by AGENTS_SUMMARIZER_MODEL.',
88
89
  },
90
+ {
91
+ name: 'lead.model',
92
+ yamlKey: 'leadModel',
93
+ scope: 'user',
94
+ type: 'string',
95
+ defaultValue: 'sonnet',
96
+ description: 'Model the per-project Lead (`agents lead ask`) runs on, passed to `agents run claude --model`. A tier ' +
97
+ '(cheap|default|best|ultra) or a model id. Read when a Lead session starts; a running Lead keeps its model ' +
98
+ 'until `agents lead stop` or the next context rotation.',
99
+ },
89
100
  {
90
101
  name: 'updates.auto',
91
102
  yamlKey: 'updatesAuto',
@@ -611,6 +622,15 @@ export const CONFIG_KEYS = [
611
622
  return null;
612
623
  },
613
624
  },
625
+ ...NOTIFY_LEVELS.map((level) => ({
626
+ name: NOTIFY_LEVEL_KEYS[level],
627
+ yamlKey: `menubarMenuNotify${level[0].toUpperCase()}${level.slice(1)}`,
628
+ scope: 'user',
629
+ type: 'string-list',
630
+ defaultValue: [...DEFAULT_NOTIFY_SCHEDULES[level]],
631
+ description: notifyScheduleDescription(level),
632
+ validate: validateNotifySchedule(NOTIFY_LEVEL_KEYS[level]),
633
+ })),
614
634
  {
615
635
  name: 'menubar.menu.githubHidden',
616
636
  yamlKey: 'menubarMenuGithubHidden',
@@ -1090,29 +1110,6 @@ export function setConfiguredDeviceRole(name, role) {
1090
1110
  else
1091
1111
  setConfigValue('role', role, { device: name });
1092
1112
  }
1093
- export function devicesPinningBrowserProfile(profile) {
1094
- ensureDeviceConfigMigrated();
1095
- const hits = [];
1096
- const devicesRoot = path.join(getUserAgentsDir(), 'devices');
1097
- let names = [];
1098
- try {
1099
- names = fs
1100
- .readdirSync(devicesRoot, { withFileTypes: true })
1101
- .filter((e) => e.isDirectory())
1102
- .map((e) => e.name);
1103
- }
1104
- catch {
1105
- return hits;
1106
- }
1107
- for (const name of names.sort()) {
1108
- const cfg = readDeviceDocConfig(name);
1109
- if (cfg.defaultBrowserProfile === profile)
1110
- hits.push({ device: name, key: 'browser.profile' });
1111
- if (cfg.browserViewer === profile)
1112
- hits.push({ device: name, key: 'browser.viewer' });
1113
- }
1114
- return hits;
1115
- }
1116
1113
  export function listConfiguredDeviceRoles(roster) {
1117
1114
  ensureDeviceConfigMigrated();
1118
1115
  const out = {};
@@ -1212,10 +1209,6 @@ export function assertDaemonEnabled() {
1212
1209
  throw new Error(`The daemon is disabled on this device (daemon.enabled=false in ~/.agents/devices/${machineId()}/agents.yaml). ` +
1213
1210
  `Re-enable with: agents daemon enable`);
1214
1211
  }
1215
- export async function resolveBrowserTaskIdleMs() {
1216
- const minutes = (await getConfigValueAsync('browser.task-idle-minutes')).value ?? 30;
1217
- return minutes === 0 ? null : minutes * 60_000;
1218
- }
1219
1212
  export function readMaxConcurrentCaps(devices) {
1220
1213
  const caps = {};
1221
1214
  for (const device of devices) {
@@ -10,7 +10,7 @@ import type { FetchStatusMarker } from '../auto-pull.js';
10
10
  import { type VersionResourceReport } from '../doctor-diff.js';
11
11
  import type { FleetDivergence, FleetHookRuntimeState, FleetVersionSignIn } from './fleet-divergence.js';
12
12
  export type FindingSeverity = 'critical' | 'warning';
13
- export declare const ALL_FINDING_KINDS: readonly ["logged-out", "logout-unprovable", "missing-hook", "missing-plugin", "unwired-hook", "hook-runtime-broken", "hook-runtime-visibility-unavailable", "cli-missing", "missing-resource", "content-drift", "never-synced", "stale", "repo-behind", "repo-drift", "fleet-resource-gap", "host-cli-missing", "host-cli-invalid", "version-skew", "orphan", "duplicate-hook", "duplicate-hook-drift", "rc-secret-export", "env-secret-export", "auth-bundle-wrong-backend", "exec-policy", "ssh-key-enrollment", "stale-cli", "binary-shadow", "owner-not-signed-in", "leaked-daemon", "menubar"];
13
+ export declare const ALL_FINDING_KINDS: readonly ["logged-out", "logout-unprovable", "missing-hook", "missing-plugin", "unwired-hook", "hook-runtime-broken", "hook-runtime-visibility-unavailable", "cli-missing", "missing-resource", "content-drift", "never-synced", "stale", "repo-behind", "repo-drift", "fleet-resource-gap", "host-cli-missing", "host-cli-invalid", "version-skew", "orphan", "duplicate-hook", "duplicate-hook-drift", "rc-secret-export", "env-secret-export", "auth-bundle-wrong-backend", "secrets-engine-incompatible", "exec-policy", "ssh-key-enrollment", "stale-cli", "binary-shadow", "owner-not-signed-in", "leaked-daemon", "menubar"];
14
14
  export declare const FINDING_SEVERITY: Record<FindingKind, FindingSeverity>;
15
15
  export type FindingKind = typeof ALL_FINDING_KINDS[number];
16
16
  export interface DoctorFinding {
@@ -47,6 +47,7 @@ export interface LocalFindingInputs {
47
47
  rcSecrets?: RcSecretFinding[];
48
48
  masterPassphraseInEnv?: boolean;
49
49
  authBundleWrongBackend?: boolean;
50
+ secretsEngineIncompatible?: boolean;
50
51
  execPolicy?: {
51
52
  platform: NodeJS.Platform;
52
53
  policy: string | null;
@@ -19,7 +19,7 @@
19
19
  * CRITICAL — logged-out (provable) · missing-hook · missing-plugin ·
20
20
  * unwired-hook (a hook on disk that settings.json never fires) ·
21
21
  * hook-runtime-broken (a wired hook's generated shim wrapper is
22
- * missing or unusable) · cli-missing · ssh-key-enrollment ·
22
+ * missing or unusable) · cli-missing · ssh-key-enrollment · secrets-engine-incompatible ·
23
23
  * owner-not-signed-in (no Phoenix session or worker device
24
24
  * token, so this box cannot reach the owner).
25
25
  * WARNING — logout-unprovable (hedged) · missing-resource · content-drift ·
@@ -93,6 +93,7 @@ export const ALL_FINDING_KINDS = [
93
93
  'rc-secret-export',
94
94
  'env-secret-export',
95
95
  'auth-bundle-wrong-backend',
96
+ 'secrets-engine-incompatible',
96
97
  'exec-policy',
97
98
  'ssh-key-enrollment',
98
99
  'stale-cli',
@@ -109,6 +110,7 @@ export const FINDING_SEVERITY = {
109
110
  'hook-runtime-broken': 'critical',
110
111
  'cli-missing': 'critical',
111
112
  'owner-not-signed-in': 'critical',
113
+ 'secrets-engine-incompatible': 'critical',
112
114
  'logout-unprovable': 'warning',
113
115
  'hook-runtime-visibility-unavailable': 'warning',
114
116
  'missing-resource': 'warning',
@@ -208,6 +210,8 @@ export function remediationFor(finding) {
208
210
  return 'unset at the source, then restart every process that inherited it (shells, editor, tmux, agents daemon)';
209
211
  case 'auth-bundle-wrong-backend':
210
212
  return 'secrets delete auth --yes && secrets create auth --backend file';
213
+ case 'secrets-engine-incompatible':
214
+ return 'agents setup tools --tool secrets';
211
215
  case 'exec-policy':
212
216
  return 'Set-ExecutionPolicy -Scope CurrentUser RemoteSigned';
213
217
  case 'ssh-key-enrollment':
@@ -390,6 +394,13 @@ export function buildLocalFindings(input) {
390
394
  const authFinding = authBundleWrongBackendFinding(device, input.authBundleWrongBackend ?? false);
391
395
  if (authFinding)
392
396
  out.push(authFinding);
397
+ if (input.secretsEngineIncompatible) {
398
+ out.push(finding({
399
+ severity: FINDING_SEVERITY['secrets-engine-incompatible'], kind: 'secrets-engine-incompatible', device,
400
+ message: 'the `secrets` engine on PATH (or SECRETS_BIN) predates the 0.4.0 contract this agents-cli needs, '
401
+ + 'so every secrets read fails with ENGINE_INCOMPATIBLE',
402
+ }));
403
+ }
393
404
  const policyFinding = execPolicyFinding(device, input.execPolicy);
394
405
  if (policyFinding)
395
406
  out.push(policyFinding);
@@ -48,8 +48,14 @@ interface RunFleetOptions {
48
48
  localRunner?: typeof runLocalCommand;
49
49
  }
50
50
  export declare function runFleet(targets: FleetTarget[], cmd: string[], opts?: RunFleetOptions): FleetRunResult[];
51
+ export interface FleetStatusTarget extends FanOutDeviceTarget {
52
+ platform?: string;
53
+ dialTarget: string;
54
+ extraSshArgs?: string[];
55
+ }
51
56
  interface FanOutDeviceOptions {
52
57
  perDeviceTimeoutMs?: number;
53
58
  }
54
59
  export declare function fanOutDevices<T, Target extends FanOutDeviceTarget = FanOutDeviceTarget>(targets: Target[], probe: (target: Target) => Promise<T>, opts?: FanOutDeviceOptions): Promise<FanOutDeviceResult<T>[]>;
60
+ export declare function raceFleetPingDeadline<T, Target extends FanOutDeviceTarget>(fanOut: Promise<FanOutDeviceResult<T>[]>, remoteTargets: Target[], overallTimeoutMs: number): Promise<FanOutDeviceResult<T>[]>;
55
61
  export {};
@@ -159,3 +159,18 @@ export async function fanOutDevices(targets, probe, opts = {}) {
159
159
  }
160
160
  }));
161
161
  }
162
+ export async function raceFleetPingDeadline(fanOut, remoteTargets, overallTimeoutMs) {
163
+ const overallDeadline = new Promise((_, reject) => setTimeout(() => reject(new Error('fleet ping overall deadline exceeded')), overallTimeoutMs));
164
+ try {
165
+ return await Promise.race([fanOut, overallDeadline]);
166
+ }
167
+ catch (err) {
168
+ const errMsg = err instanceof Error ? err.message : String(err);
169
+ return remoteTargets.map((t) => ({
170
+ name: t.name,
171
+ status: t.skip ? 'skipped' : 'failed',
172
+ reason: t.skip,
173
+ error: t.skip ? undefined : errMsg,
174
+ }));
175
+ }
176
+ }
@@ -56,6 +56,15 @@ export declare function collectLocalHarnessInventory(opts?: {
56
56
  agents?: readonly AgentId[];
57
57
  refresh?: boolean;
58
58
  }): Promise<HarnessRow[]>;
59
+ export interface FleetHarnessQuery {
60
+ agents?: AgentId[];
61
+ devices?: string[];
62
+ refresh?: boolean;
63
+ spinner?: (text: string) => {
64
+ stop(): void;
65
+ };
66
+ }
67
+ export declare function collectFleetHarnesses(opts: FleetHarnessQuery): Promise<HostHarnessResult[]>;
59
68
  export declare function groupByAccount(rows: HarnessRow[]): AccountGroup[];
60
69
  export declare function formatQuota(quota: QuotaSummary): string;
61
70
  export declare function renderHarnessMatrix(results: HostHarnessResult[]): string[];