@phnx-labs/agents-cli 1.22.121 → 1.22.123

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 (247) hide show
  1. package/CHANGELOG.md +316 -0
  2. package/README.md +53 -53
  3. package/dist/bootstrap.js +22 -17
  4. package/dist/cli/command-registry.d.ts +0 -1
  5. package/dist/cli/command-registry.js +2 -12
  6. package/dist/commands/auth.js +13 -4
  7. package/dist/commands/browser.js +3 -4
  8. package/dist/commands/cloud-transcripts.d.ts +7 -0
  9. package/dist/commands/cloud-transcripts.js +100 -0
  10. package/dist/commands/cloud.js +5 -0
  11. package/dist/commands/computer.d.ts +0 -12
  12. package/dist/commands/computer.js +14 -124
  13. package/dist/commands/config.js +5 -4
  14. package/dist/commands/daemon-index.d.ts +2 -0
  15. package/dist/commands/daemon-index.js +44 -0
  16. package/dist/commands/daemon.js +13 -8
  17. package/dist/commands/doctor.js +3 -4
  18. package/dist/commands/exec.d.ts +5 -0
  19. package/dist/commands/exec.js +35 -7
  20. package/dist/commands/feed-watch.js +12 -0
  21. package/dist/commands/feed.d.ts +1 -1
  22. package/dist/commands/feed.js +7 -4
  23. package/dist/commands/insights.js +3 -1
  24. package/dist/commands/inspect.js +1 -1
  25. package/dist/commands/logs.js +2 -1
  26. package/dist/commands/mailboxes.js +1 -1
  27. package/dist/commands/models.js +1 -1
  28. package/dist/commands/projects.js +3 -3
  29. package/dist/commands/prune.js +6 -28
  30. package/dist/commands/ps-roster.d.ts +0 -1
  31. package/dist/commands/ps-roster.js +2 -21
  32. package/dist/commands/ps.js +13 -1
  33. package/dist/commands/recordings.d.ts +2 -0
  34. package/dist/commands/recordings.js +117 -0
  35. package/dist/commands/routines.js +1 -1
  36. package/dist/commands/secrets-passthrough.js +3 -3
  37. package/dist/commands/send.js +33 -20
  38. package/dist/commands/sessions-backfill.d.ts +1 -0
  39. package/dist/commands/sessions-backfill.js +48 -13
  40. package/dist/commands/sessions-migrate.d.ts +1 -1
  41. package/dist/commands/sessions-migrate.js +11 -10
  42. package/dist/commands/sessions-optimize.d.ts +1 -0
  43. package/dist/commands/sessions-optimize.js +7 -4
  44. package/dist/commands/sessions-resume.js +8 -1
  45. package/dist/commands/sessions-stats.d.ts +2 -0
  46. package/dist/commands/sessions-stats.js +24 -7
  47. package/dist/commands/sessions.d.ts +5 -11
  48. package/dist/commands/sessions.js +8 -236
  49. package/dist/commands/setup-computer.js +1 -2
  50. package/dist/commands/setup-mine.js +0 -1
  51. package/dist/commands/setup.js +1 -1
  52. package/dist/commands/sync.js +101 -1
  53. package/dist/commands/teams.js +2 -2
  54. package/dist/commands/testdata/feed-hub.js +11 -0
  55. package/dist/commands/trash.d.ts +0 -1
  56. package/dist/commands/trash.js +74 -10
  57. package/dist/lib/accounting/usage-sync.js +7 -0
  58. package/dist/lib/agent-modes.d.ts +1 -1
  59. package/dist/lib/agent-modes.js +11 -5
  60. package/dist/lib/auth-mint.d.ts +4 -0
  61. package/dist/lib/auth-mint.js +6 -4
  62. package/dist/lib/browser/native-history.test-fixture.d.ts +12 -0
  63. package/dist/lib/browser/native-history.test-fixture.js +43 -0
  64. package/dist/lib/browser/paths.d.ts +5 -0
  65. package/dist/lib/browser/paths.js +7 -1
  66. package/dist/lib/browser/sessions-list.d.ts +28 -1
  67. package/dist/lib/browser/sessions-list.js +137 -25
  68. package/dist/lib/channels/providers/rush.d.ts +2 -1
  69. package/dist/lib/channels/providers/rush.js +2 -2
  70. package/dist/lib/channels/providers/session.d.ts +1 -0
  71. package/dist/lib/channels/providers/session.js +23 -12
  72. package/dist/lib/channels/registry.d.ts +9 -2
  73. package/dist/lib/channels/send.d.ts +5 -10
  74. package/dist/lib/channels/send.js +88 -50
  75. package/dist/lib/cloud/rush.d.ts +6 -0
  76. package/dist/lib/cloud/rush.js +18 -3
  77. package/dist/lib/computer-client.d.ts +19 -0
  78. package/dist/lib/computer-client.js +104 -0
  79. package/dist/lib/config-keys.d.ts +5 -1
  80. package/dist/lib/config-keys.js +14 -11
  81. package/dist/lib/daemon/auth-sync-service.js +13 -0
  82. package/dist/lib/daemon/daemon.js +20 -23
  83. package/dist/lib/daemon/owner-device-delivery-service.d.ts +10 -0
  84. package/dist/lib/daemon/owner-device-delivery-service.js +28 -0
  85. package/dist/lib/daemon-services.d.ts +2 -1
  86. package/dist/lib/daemon-services.js +17 -10
  87. package/dist/lib/daemon-webhooks.d.ts +1 -1
  88. package/dist/lib/daemon-webhooks.js +1 -1
  89. package/dist/lib/device-config.d.ts +4 -1
  90. package/dist/lib/device-config.js +58 -8
  91. package/dist/lib/devices/doctor-findings.d.ts +2 -3
  92. package/dist/lib/devices/doctor-findings.js +10 -19
  93. package/dist/lib/event-provenance.d.ts +1 -0
  94. package/dist/lib/event-provenance.js +2 -0
  95. package/dist/lib/exec.d.ts +1 -0
  96. package/dist/lib/exec.js +20 -15
  97. package/dist/lib/feed/pr-status.d.ts +5 -1
  98. package/dist/lib/feed/pr-status.js +44 -3
  99. package/dist/lib/feed/tool-activity.js +9 -6
  100. package/dist/lib/feed/tools.d.ts +4 -1
  101. package/dist/lib/feed/tools.js +8 -11
  102. package/dist/lib/feed-broadcast.d.ts +5 -3
  103. package/dist/lib/feed-broadcast.js +47 -36
  104. package/dist/lib/fleet-shared-state.d.ts +5 -0
  105. package/dist/lib/fleet-shared-state.js +8 -0
  106. package/dist/lib/github/project-prs.d.ts +4 -1
  107. package/dist/lib/github/project-prs.js +20 -7
  108. package/dist/lib/help.d.ts +1 -0
  109. package/dist/lib/help.js +8 -0
  110. package/dist/lib/helper-versions.js +1 -1
  111. package/dist/lib/hosts/passthrough.js +5 -9
  112. package/dist/lib/hosts/remote-cmd.d.ts +2 -7
  113. package/dist/lib/hosts/remote-cmd.js +14 -22
  114. package/dist/lib/hosts/routing-flag.d.ts +22 -0
  115. package/dist/lib/hosts/routing-flag.js +127 -14
  116. package/dist/lib/identity/index.d.ts +22 -0
  117. package/dist/lib/identity/index.js +3 -0
  118. package/dist/lib/installations/migrate.d.ts +7 -0
  119. package/dist/lib/installations/migrate.js +99 -88
  120. package/dist/lib/installations/versions.js +2 -2
  121. package/dist/lib/launch-identity.d.ts +6 -1
  122. package/dist/lib/launch-identity.js +12 -2
  123. package/dist/lib/menubar/install-menubar.d.ts +1 -0
  124. package/dist/lib/menubar/install-menubar.js +8 -5
  125. package/dist/lib/menubar/snapshot.js +2 -3
  126. package/dist/lib/notify.d.ts +7 -14
  127. package/dist/lib/notify.js +29 -75
  128. package/dist/lib/owner-message.d.ts +4 -6
  129. package/dist/lib/owner-message.js +12 -11
  130. package/dist/lib/owner-notify-tokens.d.ts +49 -0
  131. package/dist/lib/owner-notify-tokens.js +214 -0
  132. package/dist/lib/owner-notify.d.ts +75 -0
  133. package/dist/lib/owner-notify.js +144 -0
  134. package/dist/lib/plugins/plugins.d.ts +7 -1
  135. package/dist/lib/plugins/plugins.js +26 -5
  136. package/dist/lib/pr-land-detach.js +2 -2
  137. package/dist/lib/recordings/config.d.ts +11 -0
  138. package/dist/lib/recordings/config.js +54 -0
  139. package/dist/lib/recordings/identity.d.ts +12 -0
  140. package/dist/lib/recordings/identity.js +57 -0
  141. package/dist/lib/recordings/ledger.d.ts +16 -0
  142. package/dist/lib/recordings/ledger.js +141 -0
  143. package/dist/lib/recordings/model.d.ts +29 -0
  144. package/dist/lib/recordings/model.js +28 -0
  145. package/dist/lib/recordings/pipeline.d.ts +44 -0
  146. package/dist/lib/recordings/pipeline.js +272 -0
  147. package/dist/lib/recordings/process.d.ts +17 -0
  148. package/dist/lib/recordings/process.js +94 -0
  149. package/dist/lib/recordings/service.d.ts +15 -0
  150. package/dist/lib/recordings/service.js +45 -0
  151. package/dist/lib/recordings/settle.d.ts +21 -0
  152. package/dist/lib/recordings/settle.js +92 -0
  153. package/dist/lib/recordings/transcode.d.ts +13 -0
  154. package/dist/lib/recordings/transcode.js +44 -0
  155. package/dist/lib/refresh.js +4 -1
  156. package/dist/lib/reminders.d.ts +0 -1
  157. package/dist/lib/reminders.js +1 -1
  158. package/dist/lib/reserved-stores.d.ts +3 -0
  159. package/dist/lib/reserved-stores.js +13 -0
  160. package/dist/lib/routine-notify-owner.d.ts +3 -23
  161. package/dist/lib/routine-notify-owner.js +26 -107
  162. package/dist/lib/rush-api.d.ts +1 -0
  163. package/dist/lib/rush-api.js +1 -0
  164. package/dist/lib/scheduling/routines.d.ts +1 -1
  165. package/dist/lib/scheduling/routines.js +1 -1
  166. package/dist/lib/session/active.d.ts +18 -2
  167. package/dist/lib/session/active.js +47 -37
  168. package/dist/lib/session/cloud.js +18 -45
  169. package/dist/lib/session/db.d.ts +3 -1
  170. package/dist/lib/session/db.js +64 -32
  171. package/dist/lib/session/glance-files.d.ts +4 -3
  172. package/dist/lib/session/glance-files.js +31 -0
  173. package/dist/lib/session/inject-target.js +12 -2
  174. package/dist/lib/session/pid-registry.d.ts +2 -0
  175. package/dist/lib/session/pid-registry.js +6 -2
  176. package/dist/lib/session/presentation.d.ts +21 -0
  177. package/dist/lib/session/presentation.js +198 -0
  178. package/dist/lib/session/projection.js +9 -2
  179. package/dist/lib/sqlite.d.ts +3 -1
  180. package/dist/lib/sqlite.js +7 -3
  181. package/dist/lib/staleness/index.js +12 -0
  182. package/dist/lib/staleness/types.d.ts +5 -0
  183. package/dist/lib/standalone-tools.js +1 -1
  184. package/dist/lib/startup/command-registry.js +10 -5
  185. package/dist/lib/state.d.ts +2 -5
  186. package/dist/lib/state.js +3 -11
  187. package/dist/lib/sync-delete.d.ts +21 -0
  188. package/dist/lib/sync-delete.js +113 -0
  189. package/dist/lib/terminal/inject.js +1 -1
  190. package/dist/lib/testdata/owner-notify-api.d.ts +36 -0
  191. package/dist/lib/testdata/owner-notify-api.js +102 -0
  192. package/dist/lib/trash.d.ts +14 -0
  193. package/dist/lib/trash.js +75 -0
  194. package/dist/lib/types.d.ts +0 -34
  195. package/package.json +1 -3
  196. package/dist/commands/feedback.d.ts +0 -2
  197. package/dist/commands/feedback.js +0 -68
  198. package/dist/commands/humans.d.ts +0 -2
  199. package/dist/commands/humans.js +0 -83
  200. package/dist/commands/modes.d.ts +0 -2
  201. package/dist/commands/modes.js +0 -134
  202. package/dist/commands/monitors.d.ts +0 -2
  203. package/dist/commands/monitors.js +0 -1070
  204. package/dist/commands/reminders.d.ts +0 -2
  205. package/dist/commands/reminders.js +0 -49
  206. package/dist/lib/channels/owner-forward.d.ts +0 -25
  207. package/dist/lib/channels/owner-forward.js +0 -78
  208. package/dist/lib/channels/owner-sink.d.ts +0 -10
  209. package/dist/lib/channels/owner-sink.js +0 -26
  210. package/dist/lib/daemon/monitor-engine-service.d.ts +0 -13
  211. package/dist/lib/daemon/monitor-engine-service.js +0 -25
  212. package/dist/lib/humans.d.ts +0 -12
  213. package/dist/lib/humans.js +0 -64
  214. package/dist/lib/monitors/config.d.ts +0 -77
  215. package/dist/lib/monitors/config.js +0 -405
  216. package/dist/lib/monitors/dispatch.d.ts +0 -10
  217. package/dist/lib/monitors/dispatch.js +0 -72
  218. package/dist/lib/monitors/engine.d.ts +0 -45
  219. package/dist/lib/monitors/engine.js +0 -243
  220. package/dist/lib/monitors/fingerprint.d.ts +0 -3
  221. package/dist/lib/monitors/fingerprint.js +0 -43
  222. package/dist/lib/monitors/pid-watch.d.ts +0 -4
  223. package/dist/lib/monitors/pid-watch.js +0 -14
  224. package/dist/lib/monitors/remote.d.ts +0 -31
  225. package/dist/lib/monitors/remote.js +0 -63
  226. package/dist/lib/monitors/sources/command.d.ts +0 -4
  227. package/dist/lib/monitors/sources/command.js +0 -20
  228. package/dist/lib/monitors/sources/device.d.ts +0 -3
  229. package/dist/lib/monitors/sources/device.js +0 -31
  230. package/dist/lib/monitors/sources/failure.d.ts +0 -5
  231. package/dist/lib/monitors/sources/failure.js +0 -25
  232. package/dist/lib/monitors/sources/file.d.ts +0 -4
  233. package/dist/lib/monitors/sources/file.js +0 -46
  234. package/dist/lib/monitors/sources/http.d.ts +0 -3
  235. package/dist/lib/monitors/sources/http.js +0 -25
  236. package/dist/lib/monitors/sources/index.d.ts +0 -5
  237. package/dist/lib/monitors/sources/index.js +0 -22
  238. package/dist/lib/monitors/sources/poll.d.ts +0 -1
  239. package/dist/lib/monitors/sources/poll.js +0 -1
  240. package/dist/lib/monitors/sources/types.d.ts +0 -9
  241. package/dist/lib/monitors/sources/webhook.d.ts +0 -3
  242. package/dist/lib/monitors/sources/webhook.js +0 -3
  243. package/dist/lib/monitors/sources/ws.d.ts +0 -4
  244. package/dist/lib/monitors/sources/ws.js +0 -35
  245. package/dist/lib/monitors/state.d.ts +0 -51
  246. package/dist/lib/monitors/state.js +0 -221
  247. /package/dist/{lib/monitors/sources/types.js → commands/testdata/feed-hub.d.ts} +0 -0
@@ -1,9 +1,4 @@
1
- import { readMeta } from './state.js';
2
- import { getOwnerNotifyDestinationsFromHumans } from './humans.js';
3
- import { registerBuiltinProviders } from './channels/providers/index.js';
4
- import { lookupTransport } from './channels/resolve.js';
5
- import { forwardOwnerNotifyToPeer } from './channels/owner-forward.js';
6
- import { sinkMessageFormat } from './sink-format.js';
1
+ import { describeOwnerResult, postOwnerNotification, resolveOwnerCredential, OwnerNotSignedInError, } from './owner-notify.js';
7
2
  export function formatUrgentBlockMessage(block) {
8
3
  const q = block.questions[0];
9
4
  const header = q?.header ? `[${q.header}] ` : '';
@@ -29,78 +24,28 @@ export function buildOpenClawNotifyArgs(text, opts) {
29
24
  text,
30
25
  ];
31
26
  }
32
- export async function sendToOwner(text, options = {}) {
33
- const meta = options.meta ?? readMeta();
34
- const canonical = getOwnerNotifyDestinationsFromHumans();
35
- const legacy = meta.notify?.owner ? [meta.notify.owner] : [];
36
- const configured = canonical.length > 0 ? canonical : legacy;
37
- const destinations = options.target
38
- ? [{ channel: options.channel ?? configured[0]?.channel, to: options.target }]
39
- : options.channel
40
- ? [configured.find((dest) => dest.channel === options.channel) ?? {
41
- channel: options.channel,
42
- to: configured[0]?.to,
43
- }]
44
- : configured;
45
- const addressable = destinations.filter((dest) => Boolean(dest.channel && dest.to));
46
- if (addressable.length === 0) {
27
+ export async function sendToOwner(notification, options = {}) {
28
+ try {
29
+ if (options.dryRun) {
30
+ if (!resolveOwnerCredential())
31
+ throw new OwnerNotSignedInError();
32
+ return { ok: true, channel: 'owner', id: notification.dedupKey, body: notification.body };
33
+ }
34
+ const result = await postOwnerNotification(notification);
35
+ const partial = result.skipped.length > 0 && result.delivered.length + result.queued.length > 0;
36
+ const reachedNobody = result.suppressed === null && result.delivered.length + result.queued.length === 0;
47
37
  return {
48
- ok: false,
49
- channel: options.channel ?? 'unknown',
50
- id: options.target ?? '',
51
- error: 'No addressable owner channel configured in humans.yaml or legacy notify.owner',
38
+ ok: !reachedNobody,
39
+ channel: 'owner',
40
+ id: result.dispatchId ?? notification.dedupKey,
41
+ body: notification.body,
42
+ msgId: describeOwnerResult(result),
43
+ ...(partial || reachedNobody ? { error: describeOwnerResult(result) } : {}),
52
44
  };
53
45
  }
54
- registerBuiltinProviders();
55
- const deliveries = [];
56
- for (const { channel, to: target } of addressable) {
57
- const { provider, providerName, error } = lookupTransport(channel, meta);
58
- const body = options.composeForFormat
59
- ? options.composeForFormat(sinkMessageFormat(providerName))
60
- : text;
61
- let result;
62
- try {
63
- result = provider
64
- ? await provider.send(body, {
65
- target,
66
- ownerScoped: options.target === undefined,
67
- dryRun: options.dryRun,
68
- thread: options.thread,
69
- attachments: options.attachments,
70
- from: options.from,
71
- })
72
- : { ok: false, channel, id: target, error };
73
- }
74
- catch (err) {
75
- result = { ok: false, channel, id: target, error: err.message };
76
- }
77
- if (!result.ok && !options.dryRun && options.target === undefined) {
78
- if (options.attachments?.length) {
79
- result = {
80
- ...result,
81
- error: `${result.error ?? 'local delivery failed'}; owner attachments cannot be forwarded to another device`,
82
- };
83
- }
84
- else {
85
- result = await forwardOwnerNotifyToPeer(body, channel, target, meta, {
86
- envelope: { thread: options.thread, from: options.from },
87
- }) ?? result;
88
- }
89
- }
90
- deliveries.push({ ...result, body });
46
+ catch (err) {
47
+ return { ok: false, channel: 'owner', id: notification.dedupKey, error: err.message };
91
48
  }
92
- if (deliveries.length === 1)
93
- return deliveries[0];
94
- const failures = deliveries.filter((result) => !result.ok);
95
- return {
96
- ok: deliveries.some((result) => result.ok),
97
- channel: 'owner',
98
- id: deliveries.map((result) => `${result.channel}:${result.id}`).join(','),
99
- ...(failures.length > 0
100
- ? { error: failures.map((result) => `${result.channel}: ${result.error ?? 'failed'}`).join('; ') }
101
- : {}),
102
- deliveries,
103
- };
104
49
  }
105
50
  export async function notifyUrgentBlock(block, options = {}) {
106
51
  if (block.notifiedAt) {
@@ -109,6 +54,15 @@ export async function notifyUrgentBlock(block, options = {}) {
109
54
  if (options.dryRun) {
110
55
  return { ok: true, skipped: true };
111
56
  }
112
- const result = await sendToOwner(formatUrgentBlockMessage(block), options);
57
+ const q = block.questions[0];
58
+ const result = await sendToOwner({
59
+ event: 'needs_you',
60
+ title: q?.header?.trim() || 'Agent needs input',
61
+ body: formatUrgentBlockMessage(block),
62
+ sessionId: block.sessionId,
63
+ ...(block.ticket ? { ticket: block.ticket } : {}),
64
+ dedupKey: `block:${block.blockId}`,
65
+ source: { device: block.host },
66
+ });
113
67
  return result.ok ? { ok: true } : { ok: false, error: result.error };
114
68
  }
@@ -1,9 +1,7 @@
1
- import type { SinkMessageFormat } from './sink-format.js';
1
+ import type { OwnerNotification } from './owner-notify.js';
2
2
  interface OwnerMessageOptions {
3
- title?: string;
4
- sessionId?: string;
5
- format?: SinkMessageFormat;
3
+ agent?: string;
4
+ url?: string;
6
5
  }
7
- export declare function composeOwnerMessage(rawText: string, opts?: OwnerMessageOptions): string;
8
- export declare function ownerMessageComposer(rawText: string, opts?: OwnerMessageOptions): (format: SinkMessageFormat) => string;
6
+ export declare function ownerMessageNotification(rawText: string, opts?: OwnerMessageOptions): OwnerNotification;
9
7
  export {};
@@ -1,25 +1,26 @@
1
- import { composeBroadcastMessage } from './feed-broadcast.js';
1
+ import { randomUUID } from 'crypto';
2
+ import { ownerNotificationFromContext } from './feed-broadcast.js';
2
3
  import { resolvePostIdentity } from './feed-post.js';
3
4
  import { getSessionById, resolveFullSessionId } from './session/db.js';
4
5
  import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
5
- function ownerMessageContext(rawText, opts = {}) {
6
- const identity = resolvePostIdentity({ sessionId: opts.sessionId });
6
+ function ownerMessageContext(rawText, opts) {
7
+ const identity = resolvePostIdentity({});
7
8
  const session = resolveFullSessionId(identity?.sessionId);
8
9
  const ticket = session ? getSessionById(session)?.ticketId : undefined;
10
+ const agent = opts.agent ?? identity?.agent;
9
11
  return {
10
- ...(opts.title?.trim() ? { title: opts.title.trim() } : {}),
11
12
  text: rawText,
12
13
  level: 'important',
13
14
  ...(ticket ? { ticket, ticketUrl: linearIssueUrl(ticket) } : {}),
14
- ...(identity?.agent ? { agent: identity.agent } : {}),
15
+ ...(agent ? { agent } : {}),
15
16
  ...(identity?.host ? { host: identity.host } : {}),
16
17
  ...(session ? { session } : {}),
18
+ ...(opts.url ? { links: [opts.url] } : {}),
17
19
  };
18
20
  }
19
- export function composeOwnerMessage(rawText, opts = {}) {
20
- return composeBroadcastMessage(ownerMessageContext(rawText, opts), opts.format ?? 'plain');
21
- }
22
- export function ownerMessageComposer(rawText, opts = {}) {
23
- const ctx = ownerMessageContext(rawText, opts);
24
- return (format) => composeBroadcastMessage(ctx, format);
21
+ export function ownerMessageNotification(rawText, opts = {}) {
22
+ const notification = ownerNotificationFromContext(ownerMessageContext(rawText, opts), 'message', `send:${randomUUID()}`);
23
+ if (!notification)
24
+ throw new Error('Message is empty.');
25
+ return notification;
25
26
  }
@@ -0,0 +1,49 @@
1
+ import type { PushBundleResult } from './secrets-types.js';
2
+ import { type DeviceProfile } from './devices/registry.js';
3
+ import { selfConfiguredDeviceRole } from './device-config.js';
4
+ export declare const OWNER_NOTIFY_PEER_FRESH_MS: number;
5
+ type Role = ReturnType<typeof selfConfiguredDeviceRole>;
6
+ export declare function publishOwnerNotifyState(opts?: {
7
+ device?: string;
8
+ userAgentsDir?: string;
9
+ }): Promise<{
10
+ signedIn: boolean;
11
+ deviceToken: boolean;
12
+ changed: boolean;
13
+ }>;
14
+ export declare function electOwnerNotifyMinter(signedInHeaded: readonly string[]): string | null;
15
+ interface OwnerNotifySyncResult {
16
+ minter: string | null;
17
+ minted: string[];
18
+ pushed: string[];
19
+ revoked: string[];
20
+ skipped: Array<{
21
+ device: string;
22
+ reason: string;
23
+ }>;
24
+ errors: Array<{
25
+ device: string;
26
+ message: string;
27
+ }>;
28
+ }
29
+ interface OwnerNotifySyncDeps {
30
+ localName?: string;
31
+ userAgentsDir?: string;
32
+ cacheDir?: string;
33
+ listDevices?: () => DeviceProfile[];
34
+ selfRole?: () => Role;
35
+ peerRole?: (name: string) => Role;
36
+ isPinned?: (name: string) => boolean;
37
+ push?: (bundle: string, host: string) => Promise<PushBundleResult>;
38
+ sshTarget?: (device: DeviceProfile) => string;
39
+ now?: () => number;
40
+ }
41
+ export declare function syncOwnerNotifyTokens(deps?: OwnerNotifySyncDeps): Promise<OwnerNotifySyncResult>;
42
+ export declare function revokeMintedOwnerNotifyTokens(cacheDir?: string): Promise<{
43
+ revoked: string[];
44
+ errors: Array<{
45
+ device: string;
46
+ message: string;
47
+ }>;
48
+ }>;
49
+ export {};
@@ -0,0 +1,214 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { deleteBundleSync, deleteKeychainTokenSync, pushBundleToHostAsync, secretsKeychainItem } from './secrets-client.js';
4
+ import { readReservedCredential } from './claude-account-token.js';
5
+ import { writeReservedStoreItem } from './auth-mint.js';
6
+ import { OWNER_NOTIFY_TOKEN_KEY, canHoldOwnerNotifyToken, ownerNotifyStoreName } from './reserved-stores.js';
7
+ import { PhoenixApiError, readSession } from './identity/client.js';
8
+ import { listApiTokens, mintDeviceToken, revokeApiToken } from './identity/index.js';
9
+ import { isDialableDevice, loadDevicesSync } from './devices/registry.js';
10
+ import { sshTargetFor } from './devices/connect.js';
11
+ import { isDevicePinned, isHostPinned, managedKnownHostsPath } from './devices/known-hosts.js';
12
+ import { machineId, normalizeHost } from './machine-id.js';
13
+ import { configuredDeviceRole, isHeadedDeviceRole, selfConfiguredDeviceRole } from './device-config.js';
14
+ import { readFleetSharedDeviceStates, updateFleetSharedDeviceStateAsync } from './fleet-shared-state.js';
15
+ import { getCacheDir, getUserAgentsDir } from './state.js';
16
+ import { atomicWriteFileSync } from './fs-atomic.js';
17
+ import { hasUsableDeviceToken } from './owner-notify.js';
18
+ import { USAGE_SYNC_INTERVAL_MS } from './accounting/usage-sync.js';
19
+ const OWNER_NOTIFY_PUSH_DEADLINE_MS = 20_000;
20
+ export const OWNER_NOTIFY_PEER_FRESH_MS = 3 * USAGE_SYNC_INTERVAL_MS;
21
+ export async function publishOwnerNotifyState(opts = {}) {
22
+ const device = opts.device ?? machineId();
23
+ const signedIn = Boolean(readSession()?.access_token);
24
+ const deviceToken = hasUsableDeviceToken(device);
25
+ const write = await updateFleetSharedDeviceStateAsync(device, { ownerNotify: { signedIn, deviceToken } }, opts.userAgentsDir ?? getUserAgentsDir());
26
+ return { signedIn, deviceToken, changed: write.changed };
27
+ }
28
+ export function electOwnerNotifyMinter(signedInHeaded) {
29
+ return [...signedInHeaded].sort((a, b) => normalizeHost(a).localeCompare(normalizeHost(b)))[0] ?? null;
30
+ }
31
+ function memoPath(root) {
32
+ return path.join(root, 'owner-notify-minted.json');
33
+ }
34
+ function readMemo(root) {
35
+ try {
36
+ const parsed = JSON.parse(fs.readFileSync(memoPath(root), 'utf-8'));
37
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
38
+ return Object.fromEntries(Object.entries(parsed)
39
+ .filter((e) => typeof e[1]?.id === 'string'));
40
+ }
41
+ }
42
+ catch { }
43
+ return {};
44
+ }
45
+ function writeMemo(root, memo) {
46
+ fs.mkdirSync(root, { recursive: true });
47
+ atomicWriteFileSync(memoPath(root), `${JSON.stringify(memo, null, 2)}\n`, { encoding: 'utf-8', mode: 0o600 });
48
+ }
49
+ export async function syncOwnerNotifyTokens(deps = {}) {
50
+ const result = { minter: null, minted: [], pushed: [], revoked: [], skipped: [], errors: [] };
51
+ const localName = deps.localName ?? machineId();
52
+ const localNorm = normalizeHost(localName);
53
+ const selfRole = (deps.selfRole ?? selfConfiguredDeviceRole)();
54
+ if (!isHeadedDeviceRole(selfRole) || !readSession()?.access_token)
55
+ return result;
56
+ const devices = (deps.listDevices ?? (() => Object.values(loadDevicesSync())))()
57
+ .filter((d) => normalizeHost(d.name) !== localNorm);
58
+ const roles = new Map(devices.map((d) => {
59
+ try {
60
+ return [d.name, (deps.peerRole ?? configuredDeviceRole)(d.name)];
61
+ }
62
+ catch {
63
+ return [d.name, undefined];
64
+ }
65
+ }));
66
+ const peerRole = (name) => roles.get(name);
67
+ const read = readFleetSharedDeviceStates(deps.userAgentsDir ?? getUserAgentsDir());
68
+ result.errors.push(...read.errors);
69
+ const stateByDevice = new Map(read.states.map((s) => [normalizeHost(s.device), s]));
70
+ const now = (deps.now ?? Date.now)();
71
+ const signedInHeaded = [localName, ...devices
72
+ .filter((d) => {
73
+ const state = stateByDevice.get(normalizeHost(d.name));
74
+ return isHeadedDeviceRole(peerRole(d.name))
75
+ && state?.ownerNotify?.signedIn === true
76
+ && state.receivedAt !== undefined
77
+ && now - state.receivedAt <= OWNER_NOTIFY_PEER_FRESH_MS;
78
+ })
79
+ .map((d) => d.name)];
80
+ result.minter = electOwnerNotifyMinter(signedInHeaded);
81
+ const workers = devices.filter((d) => peerRole(d.name) === 'worker');
82
+ const cacheDir = deps.cacheDir ?? getCacheDir();
83
+ const memo = readMemo(cacheDir);
84
+ if (devices.length === 0 || [...roles.values()].some((r) => r === undefined)) {
85
+ result.skipped.push({ device: localName, reason: 'stale-token revocation needs a device registry with every role readable' });
86
+ }
87
+ else {
88
+ const workerNames = new Set(workers.map((w) => normalizeHost(w.name)));
89
+ for (const [name, minted] of Object.entries(memo).filter(([n]) => !workerNames.has(n))) {
90
+ try {
91
+ await revokeOwnerNotifyToken(name, minted.id, memo);
92
+ result.revoked.push(name);
93
+ }
94
+ catch (err) {
95
+ result.errors.push({ device: name, message: `revoke token of a device that is no longer a worker: ${err.message}` });
96
+ }
97
+ }
98
+ if (result.revoked.length > 0)
99
+ writeMemo(cacheDir, memo);
100
+ }
101
+ if (normalizeHost(result.minter ?? '') !== localNorm) {
102
+ for (const d of workers)
103
+ result.skipped.push({ device: d.name, reason: `${result.minter} mints owner-notify tokens` });
104
+ return result;
105
+ }
106
+ const pinned = deps.isPinned ?? ((name) => isHostPinned(name, managedKnownHostsPath()));
107
+ const push = deps.push ?? ((bundle, host) => pushBundleToHostAsync(bundle, host, {
108
+ remoteBackend: 'file', operation: 'owner-notify-sync', agentOnly: true, timeoutMs: OWNER_NOTIFY_PUSH_DEADLINE_MS,
109
+ }));
110
+ const sshTarget = deps.sshTarget ?? sshTargetFor;
111
+ let tokens;
112
+ try {
113
+ tokens = (await listApiTokens()).filter((t) => t.kind === 'device' && t.device !== null && t.scopes.includes('notify'));
114
+ }
115
+ catch (err) {
116
+ result.errors.push({ device: localName, message: `list device tokens: ${err.message}` });
117
+ return result;
118
+ }
119
+ for (const worker of workers) {
120
+ const name = normalizeHost(worker.name);
121
+ const store = ownerNotifyStoreName(name);
122
+ const peer = stateByDevice.get(name);
123
+ const peerState = peer?.ownerNotify;
124
+ if (!peerState) {
125
+ result.skipped.push({ device: worker.name, reason: 'no owner-notify state from this peer yet' });
126
+ continue;
127
+ }
128
+ if (!isDialableDevice(worker)) {
129
+ result.skipped.push({ device: worker.name, reason: 'unreachable' });
130
+ continue;
131
+ }
132
+ if (!isDevicePinned(worker, pinned)) {
133
+ result.skipped.push({ device: worker.name, reason: `host key not pinned; run \`agents ssh ${worker.name}\` once` });
134
+ continue;
135
+ }
136
+ if (peerState.deviceToken) {
137
+ result.skipped.push({ device: worker.name, reason: 'token present' });
138
+ continue;
139
+ }
140
+ let onServer = tokens.find((t) => normalizeHost(t.device) === name);
141
+ const held = memo[name];
142
+ try {
143
+ const holdsLive = onServer !== undefined && held?.id === onServer.id
144
+ && readReservedCredential(store, OWNER_NOTIFY_TOKEN_KEY) !== null;
145
+ if (holdsLive && held.pushedAt !== undefined && (peer?.receivedAt ?? 0) <= held.pushedAt) {
146
+ result.skipped.push({ device: worker.name, reason: 'waiting for the worker to report the pushed token' });
147
+ continue;
148
+ }
149
+ if (onServer && !(holdsLive && held.pushedAt === undefined)) {
150
+ await revokeApiToken(onServer.id);
151
+ onServer = undefined;
152
+ }
153
+ if (!onServer) {
154
+ const minted = await mintDeviceToken(name, ['notify']);
155
+ try {
156
+ writeReservedStoreItem(store, OWNER_NOTIFY_TOKEN_KEY, minted.token, `Owner-notify device token for ${name} (scope notify); pushed only to that worker by the daemon.`);
157
+ }
158
+ catch (err) {
159
+ await revokeApiToken(minted.id);
160
+ throw err;
161
+ }
162
+ memo[name] = { id: minted.id };
163
+ writeMemo(cacheDir, memo);
164
+ result.minted.push(worker.name);
165
+ }
166
+ const out = await push(store, sshTarget(worker));
167
+ if (out.ok) {
168
+ memo[name] = { ...memo[name], pushedAt: now };
169
+ writeMemo(cacheDir, memo);
170
+ result.pushed.push(worker.name);
171
+ }
172
+ else {
173
+ result.errors.push({ device: worker.name, message: out.message });
174
+ }
175
+ }
176
+ catch (err) {
177
+ result.errors.push({ device: worker.name, message: err.message });
178
+ }
179
+ }
180
+ return result;
181
+ }
182
+ async function revokeOwnerNotifyToken(name, id, memo) {
183
+ try {
184
+ await revokeApiToken(id);
185
+ }
186
+ catch (err) {
187
+ if (!(err instanceof PhoenixApiError && err.status === 404))
188
+ throw err;
189
+ }
190
+ if (memo[name]?.id === id) {
191
+ delete memo[name];
192
+ if (canHoldOwnerNotifyToken(name)) {
193
+ const store = ownerNotifyStoreName(name);
194
+ deleteKeychainTokenSync(secretsKeychainItem(store, OWNER_NOTIFY_TOKEN_KEY));
195
+ deleteBundleSync(store);
196
+ }
197
+ }
198
+ }
199
+ export async function revokeMintedOwnerNotifyTokens(cacheDir = getCacheDir()) {
200
+ const out = { revoked: [], errors: [] };
201
+ const memo = readMemo(cacheDir);
202
+ for (const [name, { id }] of Object.entries(memo)) {
203
+ try {
204
+ await revokeOwnerNotifyToken(name, id, memo);
205
+ out.revoked.push(name);
206
+ }
207
+ catch (err) {
208
+ out.errors.push({ device: name, message: err.message });
209
+ }
210
+ }
211
+ if (Object.keys(memo).length > 0 || out.revoked.length > 0)
212
+ writeMemo(cacheDir, memo);
213
+ return out;
214
+ }
@@ -0,0 +1,75 @@
1
+ export declare const OWNER_EVENTS: readonly ["needs_you", "completed", "failed", "spend_threshold", "message"];
2
+ export type OwnerEvent = (typeof OWNER_EVENTS)[number];
3
+ export type OwnerChannel = 'email' | 'slack' | 'imessage';
4
+ export interface OwnerNotification {
5
+ event: OwnerEvent;
6
+ title: string;
7
+ body: string;
8
+ url?: string;
9
+ sessionId?: string;
10
+ ticket?: string;
11
+ dedupKey: string;
12
+ source?: {
13
+ device?: string;
14
+ agent?: string;
15
+ };
16
+ }
17
+ export interface OwnerNotifyResult {
18
+ dispatchId: string | null;
19
+ delivered: OwnerChannel[];
20
+ queued: OwnerChannel[];
21
+ skipped: Array<{
22
+ channel: OwnerChannel;
23
+ reason: string;
24
+ }>;
25
+ suppressed: null | 'duplicate' | 'quiet_hours';
26
+ }
27
+ export interface DeviceDelivery {
28
+ id: string;
29
+ channel: 'imessage';
30
+ address: string;
31
+ body: string;
32
+ createdAt: string;
33
+ }
34
+ export interface OwnerPreferencesPatch {
35
+ preferences?: Array<{
36
+ event: OwnerEvent;
37
+ channel: OwnerChannel;
38
+ enabled: boolean;
39
+ }>;
40
+ settings?: {
41
+ timezone?: string;
42
+ quietStart?: string | null;
43
+ quietEnd?: string | null;
44
+ };
45
+ destinations?: {
46
+ imessage?: {
47
+ address: string;
48
+ } | null;
49
+ };
50
+ }
51
+ export declare class OwnerNotSignedInError extends Error {
52
+ readonly code = "OWNER_NOT_SIGNED_IN";
53
+ constructor();
54
+ }
55
+ export declare class OwnerNotifyApiError extends Error {
56
+ readonly status: number;
57
+ readonly code?: string | undefined;
58
+ constructor(message: string, status: number, code?: string | undefined);
59
+ }
60
+ export interface OwnerCredential {
61
+ kind: 'session' | 'device';
62
+ token: string;
63
+ }
64
+ export declare function selfDeviceName(): string;
65
+ export declare function resolveOwnerCredential(): OwnerCredential | null;
66
+ export declare const OWNER_DEDUP_PREFIX = "owner:";
67
+ export declare function hasUsableDeviceToken(device: string, cacheDir?: string): boolean;
68
+ export declare function postOwnerNotification(notification: OwnerNotification): Promise<OwnerNotifyResult>;
69
+ export declare function claimDeviceDeliveries(device: string, limit?: number): Promise<DeviceDelivery[]>;
70
+ export declare function reportDeviceDelivery(id: string, result: {
71
+ ok: boolean;
72
+ error?: string;
73
+ }): Promise<void>;
74
+ export declare function putOwnerPreferences(patch: OwnerPreferencesPatch): Promise<void>;
75
+ export declare function describeOwnerResult(result: OwnerNotifyResult): string;
@@ -0,0 +1,144 @@
1
+ import { createHash } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { readSession } from './identity/client.js';
5
+ import { readReservedCredential } from './claude-account-token.js';
6
+ import { machineId, normalizeHost } from './machine-id.js';
7
+ import { OWNER_NOTIFY_TOKEN_KEY, canHoldOwnerNotifyToken, ownerNotifyStoreName } from './reserved-stores.js';
8
+ import { RUSH_API_BASE } from './rush-api.js';
9
+ import { getCacheDir } from './state.js';
10
+ export const OWNER_EVENTS = ['needs_you', 'completed', 'failed', 'spend_threshold', 'message'];
11
+ export class OwnerNotSignedInError extends Error {
12
+ code = 'OWNER_NOT_SIGNED_IN';
13
+ constructor() {
14
+ super("This box cannot reach the owner: no Phoenix session and no device token. Run 'agents auth login' (a worker receives its device token from a signed-in personal device).");
15
+ this.name = 'OwnerNotSignedInError';
16
+ }
17
+ }
18
+ export class OwnerNotifyApiError extends Error {
19
+ status;
20
+ code;
21
+ constructor(message, status, code) {
22
+ super(message);
23
+ this.status = status;
24
+ this.code = code;
25
+ this.name = 'OwnerNotifyApiError';
26
+ }
27
+ }
28
+ export function selfDeviceName() {
29
+ return normalizeHost(machineId());
30
+ }
31
+ export function resolveOwnerCredential() {
32
+ const session = readSession()?.access_token?.trim();
33
+ if (session)
34
+ return { kind: 'session', token: session };
35
+ const self = selfDeviceName();
36
+ if (!canHoldOwnerNotifyToken(self))
37
+ return null;
38
+ const device = readReservedCredential(ownerNotifyStoreName(self), OWNER_NOTIFY_TOKEN_KEY);
39
+ return device ? { kind: 'device', token: device } : null;
40
+ }
41
+ export const OWNER_DEDUP_PREFIX = 'owner:';
42
+ function rejectedTokenPath(cacheDir) {
43
+ return path.join(cacheDir, 'owner-notify-rejected.json');
44
+ }
45
+ function tokenFingerprint(token) {
46
+ return createHash('sha256').update(token).digest('hex');
47
+ }
48
+ function markDeviceTokenRejected(token, cacheDir = getCacheDir()) {
49
+ fs.mkdirSync(cacheDir, { recursive: true });
50
+ fs.writeFileSync(rejectedTokenPath(cacheDir), `${JSON.stringify({ sha256: tokenFingerprint(token), at: new Date().toISOString() })}\n`, { mode: 0o600 });
51
+ }
52
+ function isDeviceTokenRejected(token, cacheDir) {
53
+ try {
54
+ const parsed = JSON.parse(fs.readFileSync(rejectedTokenPath(cacheDir), 'utf-8'));
55
+ return parsed.sha256 === tokenFingerprint(token);
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ export function hasUsableDeviceToken(device, cacheDir = getCacheDir()) {
62
+ const self = normalizeHost(device);
63
+ if (!canHoldOwnerNotifyToken(self))
64
+ return false;
65
+ const token = readReservedCredential(ownerNotifyStoreName(self), OWNER_NOTIFY_TOKEN_KEY);
66
+ return token !== null && !isDeviceTokenRejected(token, cacheDir);
67
+ }
68
+ function requireOwnerCredential() {
69
+ const credential = resolveOwnerCredential();
70
+ if (!credential)
71
+ throw new OwnerNotSignedInError();
72
+ return credential;
73
+ }
74
+ async function rushRequest(method, route, body) {
75
+ const credential = requireOwnerCredential();
76
+ let response;
77
+ try {
78
+ response = await fetch(`${RUSH_API_BASE}${route}`, {
79
+ method,
80
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${credential.token}` },
81
+ body: JSON.stringify(body),
82
+ signal: AbortSignal.timeout(15_000),
83
+ });
84
+ }
85
+ catch (err) {
86
+ throw new OwnerNotifyApiError(`Could not reach ${RUSH_API_BASE} (${err.message}).`, 0);
87
+ }
88
+ if (response.ok && credential.kind === 'device')
89
+ fs.rmSync(rejectedTokenPath(getCacheDir()), { force: true });
90
+ if (response.status === 204)
91
+ return undefined;
92
+ const text = await response.text();
93
+ let payload = null;
94
+ try {
95
+ payload = text ? JSON.parse(text) : null;
96
+ }
97
+ catch {
98
+ payload = null;
99
+ }
100
+ if (!response.ok) {
101
+ const fields = payload && typeof payload === 'object' ? payload : {};
102
+ const detail = typeof fields.error === 'string' ? fields.error : `${response.status} ${response.statusText}`;
103
+ const code = typeof fields.code === 'string' ? fields.code : undefined;
104
+ if (response.status === 401 && credential.kind === 'device')
105
+ markDeviceTokenRejected(credential.token);
106
+ const hint = response.status === 401
107
+ ? (credential.kind === 'session'
108
+ ? " Run 'agents auth login'."
109
+ : ' The device token was rejected; a signed-in personal device re-mints it on its next auth-sync tick.')
110
+ : '';
111
+ throw new OwnerNotifyApiError(`rush/api ${route}: ${detail}.${hint}`, response.status, code);
112
+ }
113
+ return payload;
114
+ }
115
+ export function postOwnerNotification(notification) {
116
+ return rushRequest('POST', '/me/notifications', {
117
+ ...notification,
118
+ dedupKey: `${OWNER_DEDUP_PREFIX}${notification.dedupKey}`,
119
+ });
120
+ }
121
+ export async function claimDeviceDeliveries(device, limit = 10) {
122
+ const out = await rushRequest('POST', '/me/device-deliveries/claim', { device, limit });
123
+ return out.deliveries;
124
+ }
125
+ export async function reportDeviceDelivery(id, result) {
126
+ await rushRequest('POST', `/me/device-deliveries/${encodeURIComponent(id)}/result`, result);
127
+ }
128
+ export async function putOwnerPreferences(patch) {
129
+ await rushRequest('PUT', '/me/preferences', patch);
130
+ }
131
+ export function describeOwnerResult(result) {
132
+ if (result.suppressed === 'duplicate')
133
+ return 'suppressed: already sent';
134
+ if (result.suppressed === 'quiet_hours')
135
+ return 'suppressed: quiet hours';
136
+ const parts = [];
137
+ if (result.delivered.length)
138
+ parts.push(`delivered ${result.delivered.join(', ')}`);
139
+ if (result.queued.length)
140
+ parts.push(`queued ${result.queued.join(', ')}`);
141
+ for (const s of result.skipped)
142
+ parts.push(`skipped ${s.channel} (${s.reason})`);
143
+ return parts.join('; ') || 'no channel enabled for this event';
144
+ }