@phnx-labs/agents-cli 1.20.74 → 1.20.76

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 (199) hide show
  1. package/CHANGELOG.md +893 -0
  2. package/README.md +36 -10
  3. package/dist/bin/agents +0 -0
  4. package/dist/commands/apply.js +21 -3
  5. package/dist/commands/attach.d.ts +10 -0
  6. package/dist/commands/attach.js +41 -0
  7. package/dist/commands/computer.js +3 -3
  8. package/dist/commands/detach-core.d.ts +46 -0
  9. package/dist/commands/detach-core.js +61 -0
  10. package/dist/commands/detach.d.ts +5 -0
  11. package/dist/commands/detach.js +171 -0
  12. package/dist/commands/doctor.js +18 -0
  13. package/dist/commands/exec.js +31 -3
  14. package/dist/commands/feed.d.ts +7 -1
  15. package/dist/commands/feed.js +47 -4
  16. package/dist/commands/go.d.ts +9 -2
  17. package/dist/commands/go.js +16 -6
  18. package/dist/commands/harness.d.ts +14 -0
  19. package/dist/commands/harness.js +145 -0
  20. package/dist/commands/import.js +38 -8
  21. package/dist/commands/inspect.js +5 -2
  22. package/dist/commands/profiles.d.ts +20 -0
  23. package/dist/commands/profiles.js +68 -21
  24. package/dist/commands/repo.js +14 -0
  25. package/dist/commands/routines.js +15 -2
  26. package/dist/commands/secrets.js +44 -21
  27. package/dist/commands/sessions-browser.js +1 -1
  28. package/dist/commands/sessions-export.js +19 -5
  29. package/dist/commands/sessions-migrate.d.ts +29 -0
  30. package/dist/commands/sessions-migrate.js +596 -0
  31. package/dist/commands/sessions-picker.js +16 -1
  32. package/dist/commands/sessions.d.ts +36 -13
  33. package/dist/commands/sessions.js +210 -40
  34. package/dist/commands/setup-computer.js +2 -2
  35. package/dist/commands/ssh.js +71 -35
  36. package/dist/commands/status.js +10 -2
  37. package/dist/commands/versions.js +15 -6
  38. package/dist/commands/view.d.ts +5 -0
  39. package/dist/commands/view.js +24 -4
  40. package/dist/commands/watchdog.d.ts +7 -2
  41. package/dist/commands/watchdog.js +73 -57
  42. package/dist/index.js +58 -7
  43. package/dist/lib/activity.d.ts +14 -4
  44. package/dist/lib/activity.js +17 -5
  45. package/dist/lib/actor.d.ts +50 -0
  46. package/dist/lib/actor.js +166 -0
  47. package/dist/lib/agent-spec/provider.js +2 -1
  48. package/dist/lib/agent-spec/resolve.js +19 -5
  49. package/dist/lib/agent-spec/types.d.ts +9 -1
  50. package/dist/lib/agents.d.ts +21 -0
  51. package/dist/lib/agents.js +70 -6
  52. package/dist/lib/cloud/codex.d.ts +2 -0
  53. package/dist/lib/cloud/codex.js +14 -3
  54. package/dist/lib/cloud/session-index.d.ts +32 -0
  55. package/dist/lib/cloud/session-index.js +58 -0
  56. package/dist/lib/cloud/store.d.ts +7 -0
  57. package/dist/lib/cloud/store.js +25 -0
  58. package/dist/lib/config-transfer.js +4 -0
  59. package/dist/lib/daemon.js +18 -2
  60. package/dist/lib/devices/connect.d.ts +15 -1
  61. package/dist/lib/devices/connect.js +15 -1
  62. package/dist/lib/devices/fleet.d.ts +21 -0
  63. package/dist/lib/devices/fleet.js +26 -0
  64. package/dist/lib/devices/health-report.d.ts +38 -0
  65. package/dist/lib/devices/health-report.js +214 -0
  66. package/dist/lib/devices/health.js +4 -1
  67. package/dist/lib/devices/reachability.d.ts +31 -0
  68. package/dist/lib/devices/reachability.js +40 -0
  69. package/dist/lib/devices/registry.d.ts +33 -0
  70. package/dist/lib/devices/registry.js +37 -0
  71. package/dist/lib/devices/resolve-target.d.ts +15 -27
  72. package/dist/lib/devices/resolve-target.js +63 -102
  73. package/dist/lib/devices/sync.d.ts +18 -0
  74. package/dist/lib/devices/sync.js +23 -1
  75. package/dist/lib/devices/tailscale.d.ts +3 -0
  76. package/dist/lib/devices/tailscale.js +1 -0
  77. package/dist/lib/events.d.ts +1 -1
  78. package/dist/lib/exec.d.ts +66 -0
  79. package/dist/lib/exec.js +195 -6
  80. package/dist/lib/feed-post.d.ts +63 -0
  81. package/dist/lib/feed-post.js +204 -0
  82. package/dist/lib/fleet/apply.d.ts +32 -2
  83. package/dist/lib/fleet/apply.js +97 -10
  84. package/dist/lib/fleet/types.d.ts +11 -0
  85. package/dist/lib/fs-walk.d.ts +13 -0
  86. package/dist/lib/fs-walk.js +16 -7
  87. package/dist/lib/hooks.d.ts +1 -0
  88. package/dist/lib/hooks.js +156 -0
  89. package/dist/lib/hosts/dispatch.d.ts +7 -0
  90. package/dist/lib/hosts/dispatch.js +2 -0
  91. package/dist/lib/hosts/passthrough.js +2 -0
  92. package/dist/lib/hosts/reconnect.d.ts +78 -0
  93. package/dist/lib/hosts/reconnect.js +127 -0
  94. package/dist/lib/hosts/registry.d.ts +75 -14
  95. package/dist/lib/hosts/registry.js +205 -30
  96. package/dist/lib/hosts/remote-cmd.js +1 -0
  97. package/dist/lib/hosts/run-target.d.ts +13 -5
  98. package/dist/lib/hosts/run-target.js +26 -10
  99. package/dist/lib/hosts/session-index.d.ts +18 -1
  100. package/dist/lib/hosts/session-index.js +37 -2
  101. package/dist/lib/hosts/session-marker.d.ts +33 -0
  102. package/dist/lib/hosts/session-marker.js +51 -0
  103. package/dist/lib/hosts/tasks.d.ts +8 -4
  104. package/dist/lib/import.d.ts +2 -0
  105. package/dist/lib/import.js +35 -2
  106. package/dist/lib/menubar/install-menubar.d.ts +20 -0
  107. package/dist/lib/menubar/install-menubar.js +45 -1
  108. package/dist/lib/migrate.d.ts +16 -0
  109. package/dist/lib/migrate.js +36 -0
  110. package/dist/lib/models.d.ts +27 -0
  111. package/dist/lib/models.js +54 -1
  112. package/dist/lib/overdue.d.ts +7 -2
  113. package/dist/lib/overdue.js +18 -11
  114. package/dist/lib/picker.js +4 -1
  115. package/dist/lib/platform/process.d.ts +17 -0
  116. package/dist/lib/platform/process.js +70 -0
  117. package/dist/lib/profiles-presets.js +9 -7
  118. package/dist/lib/profiles.d.ts +31 -0
  119. package/dist/lib/profiles.js +70 -0
  120. package/dist/lib/pty-server.d.ts +2 -10
  121. package/dist/lib/pty-server.js +4 -38
  122. package/dist/lib/registry.d.ts +1 -1
  123. package/dist/lib/registry.js +48 -8
  124. package/dist/lib/rotate.d.ts +18 -0
  125. package/dist/lib/rotate.js +28 -0
  126. package/dist/lib/routines.d.ts +26 -0
  127. package/dist/lib/routines.js +19 -2
  128. package/dist/lib/runner.js +104 -7
  129. package/dist/lib/secrets/agent.d.ts +66 -1
  130. package/dist/lib/secrets/agent.js +154 -90
  131. package/dist/lib/secrets/bundles.d.ts +34 -0
  132. package/dist/lib/secrets/bundles.js +179 -19
  133. package/dist/lib/secrets/index.d.ts +15 -1
  134. package/dist/lib/secrets/index.js +21 -3
  135. package/dist/lib/secrets/rc-hygiene.d.ts +55 -0
  136. package/dist/lib/secrets/rc-hygiene.js +154 -0
  137. package/dist/lib/secrets/remote.d.ts +7 -4
  138. package/dist/lib/secrets/remote.js +7 -4
  139. package/dist/lib/secrets/sync-commands.d.ts +21 -0
  140. package/dist/lib/secrets/sync-commands.js +21 -0
  141. package/dist/lib/self-update.d.ts +23 -2
  142. package/dist/lib/self-update.js +86 -5
  143. package/dist/lib/session/active.d.ts +114 -7
  144. package/dist/lib/session/active.js +323 -52
  145. package/dist/lib/session/cloud.js +2 -1
  146. package/dist/lib/session/db.d.ts +48 -0
  147. package/dist/lib/session/db.js +238 -14
  148. package/dist/lib/session/detached.d.ts +30 -0
  149. package/dist/lib/session/detached.js +92 -0
  150. package/dist/lib/session/discover.d.ts +465 -2
  151. package/dist/lib/session/discover.js +1648 -468
  152. package/dist/lib/session/fork.js +2 -1
  153. package/dist/lib/session/hook-sessions.d.ts +43 -0
  154. package/dist/lib/session/hook-sessions.js +135 -0
  155. package/dist/lib/session/linear.d.ts +6 -0
  156. package/dist/lib/session/linear.js +55 -0
  157. package/dist/lib/session/migrate-targets.d.ts +65 -0
  158. package/dist/lib/session/migrate-targets.js +94 -0
  159. package/dist/lib/session/migrations.d.ts +37 -0
  160. package/dist/lib/session/migrations.js +60 -0
  161. package/dist/lib/session/parse.d.ts +18 -0
  162. package/dist/lib/session/parse.js +130 -30
  163. package/dist/lib/session/pid-registry.d.ts +34 -2
  164. package/dist/lib/session/pid-registry.js +49 -2
  165. package/dist/lib/session/render.d.ts +7 -2
  166. package/dist/lib/session/render.js +22 -10
  167. package/dist/lib/session/short-id.d.ts +17 -0
  168. package/dist/lib/session/short-id.js +20 -0
  169. package/dist/lib/session/state.js +6 -2
  170. package/dist/lib/shims.d.ts +1 -1
  171. package/dist/lib/shims.js +20 -6
  172. package/dist/lib/sqlite.d.ts +3 -2
  173. package/dist/lib/sqlite.js +27 -4
  174. package/dist/lib/staleness/detectors/commands.js +1 -1
  175. package/dist/lib/staleness/detectors/workflows.js +13 -2
  176. package/dist/lib/staleness/writers/commands.js +7 -7
  177. package/dist/lib/staleness/writers/workflows.d.ts +4 -2
  178. package/dist/lib/startup/command-registry.d.ts +1 -0
  179. package/dist/lib/startup/command-registry.js +3 -0
  180. package/dist/lib/state.d.ts +1 -1
  181. package/dist/lib/state.js +1 -32
  182. package/dist/lib/teams/agents.d.ts +19 -10
  183. package/dist/lib/teams/agents.js +40 -39
  184. package/dist/lib/types.d.ts +37 -2
  185. package/dist/lib/usage.d.ts +33 -1
  186. package/dist/lib/usage.js +172 -12
  187. package/dist/lib/versions.d.ts +9 -2
  188. package/dist/lib/versions.js +37 -8
  189. package/dist/lib/watchdog/log.d.ts +43 -0
  190. package/dist/lib/watchdog/log.js +69 -0
  191. package/dist/lib/watchdog/routine.d.ts +44 -0
  192. package/dist/lib/watchdog/routine.js +69 -0
  193. package/dist/lib/watchdog/runner.d.ts +51 -7
  194. package/dist/lib/watchdog/runner.js +239 -64
  195. package/dist/lib/watchdog/watchdog.d.ts +1 -1
  196. package/dist/lib/watchdog/watchdog.js +31 -16
  197. package/dist/lib/workflows.d.ts +16 -0
  198. package/dist/lib/workflows.js +110 -1
  199. package/package.json +1 -1
@@ -8,41 +8,41 @@
8
8
  *
9
9
  * agents watchdog one tick, dry — prints what it WOULD nudge/skip and why
10
10
  * agents watchdog --nudge one tick, actually injects (explicit opt-in)
11
- * agents watchdog --watch daemon loop (poll every --interval)
11
+ * agents watchdog --watch manual poll loop (dry unless --nudge)
12
12
  * agents watchdog --json machine-readable tick output (for the menu-bar)
13
- * agents watchdog enable|disable flip the global auto-nudge sentinel (default OFF)
13
+ * agents watchdog enable|disable turn the always-on watchdog routine on/off
14
14
  * agents watchdog policy <id> <p> per-session policy: off | keep | handsoff
15
+ *
16
+ * The always-on watchdog is a daemon-fired ROUTINE, not a private sentinel + a
17
+ * hand-rolled loop: `enable` creates/enables a `watchdog` command routine
18
+ * (`agents watchdog --nudge` every couple of minutes) and reloads the daemon;
19
+ * `disable` pauses it. See ../lib/watchdog/routine.ts.
15
20
  */
16
21
  import chalk from 'chalk';
17
- import * as fs from 'fs';
18
22
  import * as path from 'path';
19
23
  import { setHelpSections } from '../lib/help.js';
20
24
  import { parseDuration } from '../lib/hooks/cache.js';
21
25
  import { getRuntimeStateDir } from '../lib/state.js';
26
+ import { setJobEnabled } from '../lib/routines.js';
27
+ import { ensureWatchdogRoutine, isWatchdogRoutineEnabled, watchdogRoutineExists, WATCHDOG_ROUTINE_NAME, WATCHDOG_ROUTINE_SCHEDULE, } from '../lib/watchdog/routine.js';
22
28
  import { runWatchdogTick, writePolicySentinel, DEFAULT_THRESHOLDS, } from '../lib/watchdog/runner.js';
23
29
  /** Default state dir the runner and these subcommands share. */
24
30
  function stateDir() {
25
31
  return path.join(getRuntimeStateDir(), 'watchdog');
26
32
  }
27
- /** Global auto-nudge sentinel — present = enabled. Default OFF (opt-in). */
28
- function enabledSentinelPath() {
29
- return path.join(stateDir(), 'enabled');
30
- }
31
- function isGloballyEnabled() {
32
- return fs.existsSync(enabledSentinelPath());
33
- }
34
- function setGloballyEnabled(on) {
35
- const p = enabledSentinelPath();
36
- if (on) {
37
- fs.mkdirSync(path.dirname(p), { recursive: true });
38
- fs.writeFileSync(p, 'enabled\n');
39
- }
40
- else {
41
- try {
42
- fs.rmSync(p);
43
- }
44
- catch { /* already off */ }
33
+ /**
34
+ * (Re)load the daemon so a just-changed routine takes effect without a restart.
35
+ * Best-effort: enabling starts the daemon if it is not running, then SIGHUPs it.
36
+ * Dynamic import keeps daemon.ts's heavy deps off the watchdog command's load path.
37
+ */
38
+ async function reloadDaemonForRoutine(startIfStopped) {
39
+ const { isDaemonRunning, ensureDaemonStarted, signalDaemonReload } = await import('../lib/daemon.js');
40
+ if (isDaemonRunning()) {
41
+ signalDaemonReload();
42
+ return;
45
43
  }
44
+ if (startIfStopped)
45
+ ensureDaemonStarted();
46
46
  }
47
47
  /** Parse a duration flag ("60s", "5m", "1h") to ms, or fall back to `fallbackMs`. */
48
48
  function durationMsOr(raw, fallbackMs) {
@@ -97,7 +97,7 @@ export function registerWatchdogCommand(program) {
97
97
  .command('watchdog')
98
98
  .description('Auto-nudge stalled agent terminals: detect stalls, resolve the exact split, inject "Continue." — no menu-bar needed.')
99
99
  .option('--nudge', 'Actually inject (default is a dry run that only reports what it would do)')
100
- .option('--watch', 'Daemon loop: run a tick every --interval until interrupted')
100
+ .option('--watch', 'Manual poll loop: run a tick every --interval (dry unless --nudge; the always-on path is `watchdog enable`)')
101
101
  .option('--interval <dur>', 'Poll interval in --watch mode (e.g. 30s, 1m)', '30s')
102
102
  .option('--stall <dur>', 'Idle time before a session counts as stalled', humanMs(DEFAULT_THRESHOLDS.stallMs))
103
103
  .option('--cooldown <dur>', 'Minimum time between nudges to the same session', humanMs(DEFAULT_THRESHOLDS.cooldownMs))
@@ -113,12 +113,11 @@ export function registerWatchdogCommand(program) {
113
113
  cooldownMs: durationMsOr(opts.cooldown, DEFAULT_THRESHOLDS.cooldownMs),
114
114
  dormantMs: durationMsOr(opts.dormant, DEFAULT_THRESHOLDS.dormantMs),
115
115
  };
116
- // Injection gate: --nudge is the explicit per-run opt-in; the global sentinel
117
- // enables the automatic daemon. Default OFF: bare `agents watchdog` is dry.
118
- // Re-read the sentinel every tick so a running `--watch` daemon reflects a
119
- // later `agents watchdog enable`/`disable` (or the Swift menu-bar toggle)
120
- // from another shell without a restart.
121
- const computeWillInject = () => opts.nudge === true || (opts.watch === true && isGloballyEnabled());
116
+ // Injection gate: --nudge is the explicit opt-in to actually inject. Bare
117
+ // `agents watchdog` (and `--watch` without `--nudge`) is dry. The always-on
118
+ // path is the daemon routine, which runs `agents watchdog --nudge` so the
119
+ // routine's enabled state IS the on/off switch, not a flag read here.
120
+ const computeWillInject = () => opts.nudge === true;
122
121
  const tickOnce = async (willInject) => runWatchdogTick({
123
122
  nudge: willInject,
124
123
  nudgeText: opts.text,
@@ -137,11 +136,11 @@ export function registerWatchdogCommand(program) {
137
136
  printTick(result, willInject);
138
137
  return;
139
138
  }
140
- // Daemon loop.
139
+ // Manual poll loop (for ad-hoc use; the always-on path is `enable`'s routine).
141
140
  const intervalMs = durationMsOr(opts.interval, 30_000);
142
141
  if (!computeWillInject() && !opts.json) {
143
- console.log(chalk.yellow(`watchdog --watch is DETECT-ONLY (global auto-nudge is ${isGloballyEnabled() ? 'on' : 'off'}). ` +
144
- `Pass --nudge or run 'agents watchdog enable' to inject.`));
142
+ console.log(chalk.yellow(`watchdog --watch is DETECT-ONLY. Pass --nudge to inject, ` +
143
+ `or run 'agents watchdog enable' for the always-on daemon routine.`));
145
144
  }
146
145
  // eslint-disable-next-line no-constant-condition
147
146
  while (true) {
@@ -163,50 +162,67 @@ export function registerWatchdogCommand(program) {
163
162
  # One tick, actually inject "Continue." into stalled+addressable splits
164
163
  agents watchdog --nudge
165
164
 
166
- # Watch loop every 30s, tighter stall threshold
167
- agents watchdog --watch --interval 30s --stall 60s --cooldown 5m
165
+ # Manual watch loop every 30s, tighter stall threshold (ad-hoc; dry unless --nudge)
166
+ agents watchdog --watch --nudge --interval 30s --stall 60s --cooldown 5m
168
167
 
169
168
  # Machine-readable for the menu-bar
170
169
  agents watchdog --json
171
170
 
172
- # Turn on the global auto-nudge (so --watch injects without --nudge)
171
+ # Turn on the ALWAYS-ON watchdog (a daemon-fired routine)
173
172
  agents watchdog enable
174
173
 
175
174
  # Leave one session detected-but-untouched
176
175
  agents watchdog policy <sessionId> handsoff
177
176
  `,
178
177
  notes: `
179
- Decision path (default, deterministic): a session is nudged only when its
180
- transcript tail shows it ANNOUNCED an action but no tool call followed
181
- (promise-without-toolcall) AND it is not waiting on the user. Completions and
182
- open questions are skipped.
178
+ Decision path: a cheap deterministic pre-filter resolves the obvious cases
179
+ (clearly complete -> skip; a clear promise-without-toolcall -> nudge) and
180
+ ESCALATES the judgment-heavy cases -- a session parked on a question, or an
181
+ ambiguous stall -- to a smart brain. The brain drives the agent to finish
182
+ end-to-end when it asked a needless / already-authorized question or paused
183
+ with work left, and leaves it for the human on genuine cases (credentials,
184
+ an irreversible or outward-facing action, a real ambiguous decision, or a
185
+ completed task). The brain is a customizable 'watchdog' workflow (drop a
186
+ WORKFLOW.md in project/user workflows/ to override the prompt + model);
187
+ absent one, the built-in prompt runs via 'agents run --mode plan'. Pass
188
+ --smart to force every stalled candidate through the brain.
183
189
 
184
- Safety gate: a nudge is delivered ONLY when the resolver can name the EXACT
185
- split the agent lives in (tmux / iTerm / IDE terminal). Un-addressable stalls
186
- (e.g. Ghostty with no tmux) are flagged for the menu-bar and SKIPPED never
187
- a guessed or frontmost target.
190
+ Delivery (answer-router): a running agent is steered via its mailbox; a
191
+ parked-on-question agent is answered into its EXACT split -- tmux / iTerm /
192
+ an IDE integrated terminal (VS Codium / Cursor / VS Code) -- or re-entered
193
+ via resume when headless. A parked agent with no addressable rail (e.g.
194
+ Ghostty with no tmux) is flagged for the menu-bar and SKIPPED -- never a
195
+ guessed or frontmost target.
188
196
 
189
- Policy: global auto-nudge defaults OFF (opt-in via 'enable' or --nudge).
190
- Per-session: off (ignore), keep (default), handsoff (detect + flag, never inject).
197
+ Always-on: 'agents watchdog enable' creates + enables a 'watchdog' command
198
+ routine ('${WATCHDOG_ROUTINE_SCHEDULE}' -> agents watchdog --nudge) and reloads the
199
+ daemon; 'disable' pauses it. Inspect it with 'agents routines list'. Defaults
200
+ OFF. Per-session policy: off (ignore), keep (default), handsoff (detect + flag).
191
201
 
192
202
  State (tray-readable): ${path.join('~/.agents/.cache/state/watchdog', '{nudges,flags,last-tick}.json')}
193
203
  `,
194
204
  });
195
- // --- global enable/disable/status -----------------------------------------
205
+ // --- always-on enable/disable/status (backed by the daemon routine) --------
196
206
  cmd.command('enable')
197
- .description('Turn ON global auto-nudge (so `agents watchdog --watch` injects without --nudge).')
198
- .action(() => {
199
- setGloballyEnabled(true);
200
- console.log(chalk.green('watchdog: global auto-nudge ENABLED'));
207
+ .description('Turn ON the always-on watchdog: create/enable the `watchdog` routine and (re)load the daemon.')
208
+ .action(async () => {
209
+ ensureWatchdogRoutine(true);
210
+ await reloadDaemonForRoutine(true);
211
+ console.log(chalk.green(`watchdog: ENABLED — routine '${WATCHDOG_ROUTINE_NAME}' fires ${WATCHDOG_ROUTINE_SCHEDULE} (agents watchdog --nudge)`));
201
212
  });
202
213
  cmd.command('disable')
203
- .description('Turn OFF global auto-nudge (back to detect-only unless --nudge is passed).')
204
- .action(() => {
205
- setGloballyEnabled(false);
206
- console.log(chalk.yellow('watchdog: global auto-nudge DISABLED'));
214
+ .description('Turn OFF the always-on watchdog (pause the `watchdog` routine).')
215
+ .action(async () => {
216
+ if (!watchdogRoutineExists()) {
217
+ console.log(chalk.dim('watchdog: already off (no routine)'));
218
+ return;
219
+ }
220
+ setJobEnabled(WATCHDOG_ROUTINE_NAME, false);
221
+ await reloadDaemonForRoutine(false);
222
+ console.log(chalk.yellow('watchdog: DISABLED (routine paused)'));
207
223
  });
208
224
  cmd.command('status')
209
- .description('Show whether global auto-nudge is on and where state is written.')
225
+ .description('Show whether the always-on watchdog routine is enabled and where state is written.')
210
226
  .option('--json', 'Emit status as JSON (for the menu-bar / scripts)')
211
227
  .action((_opts, command) => {
212
228
  // The parent `watchdog` command also declares --json and greedily parses it
@@ -214,12 +230,12 @@ export function registerWatchdogCommand(program) {
214
230
  // parent, not this subcommand. optsWithGlobals() merges both levels, so we
215
231
  // read it correctly regardless of which command commander bound it to.
216
232
  const json = command.optsWithGlobals().json === true;
217
- const on = isGloballyEnabled();
233
+ const on = isWatchdogRoutineEnabled();
218
234
  if (json) {
219
- console.log(JSON.stringify({ enabled: on, stateDir: stateDir() }));
235
+ console.log(JSON.stringify({ enabled: on, routine: WATCHDOG_ROUTINE_NAME, stateDir: stateDir() }));
220
236
  return;
221
237
  }
222
- console.log(`global auto-nudge: ${on ? chalk.green('ON') : chalk.dim('off')}`);
238
+ console.log(`always-on watchdog: ${on ? chalk.green('ON') : chalk.dim('off')} (routine '${WATCHDOG_ROUTINE_NAME}')`);
223
239
  console.log(`state dir: ${chalk.dim(stateDir())}`);
224
240
  });
225
241
  // --- per-session policy ----------------------------------------------------
package/dist/index.js CHANGED
@@ -26,11 +26,49 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
26
  const packageJsonPath = path.join(__dirname, '..', 'package.json');
27
27
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
28
28
  const VERSION = packageJson.version;
29
+ import { SYNC_GET_CMD, SYNC_PING_CMD, SYNC_LOCK_CMD } from './lib/secrets/sync-commands.js';
29
30
  if (process.argv[2] === '__vault-age-helper') {
30
31
  const { runVaultAgeHelperCli } = await import('./lib/secrets/vault-age-helper.js');
31
32
  await runVaultAgeHelperCli();
32
33
  process.exit(process.exitCode ?? 0);
33
34
  }
35
+ // Synchronous secrets-broker clients (src/lib/secrets/agent.ts). These are the
36
+ // hot read path: `readAndResolveBundleEnv` is synchronous all the way down, so
37
+ // it can't await a socket round-trip — it spawns one of these and reads the
38
+ // exit code (0 = hit/alive, 3 = miss/down).
39
+ //
40
+ // Intercepted HERE, before commander and before the startup STATEMENTS, for the
41
+ // same reason as __daemon-run and __vault-age-helper above. Everything below
42
+ // this point runs `checkForUpdates()` and `spawnDetachedSync()` on every
43
+ // non-help invocation — so registering these as ordinary hidden subcommands
44
+ // would fire an update check and fork a detached background sync on *every
45
+ // cache hit*, which is both a fork storm on the hot path and a source of stdout
46
+ // writes that could corrupt the JSON payload. Keep them above the line;
47
+ // agent.test.ts asserts this ordering so the block can't drift downward.
48
+ //
49
+ // The tokens are imported from the leaf module sync-commands.ts — the SAME
50
+ // bindings the clients spawn with, so this dispatch and those spawns cannot
51
+ // drift apart. It is a leaf precisely so binding them here is free: importing
52
+ // agent.js would pull the whole secrets graph into every invocation. Matching
53
+ // string literals were the earlier design; a text-scanning test could not
54
+ // reliably catch their divergence, and the divergence is silent — the CLI says
55
+ // "unknown command", the client reads that as "broker down", and every read
56
+ // falls back to a Touch ID prompt.
57
+ //
58
+ // "Before the startup statements", not "before all code": ESM hoists the
59
+ // imports below, so those module bodies evaluate first. They are side-effect
60
+ // free today (no top-level stdout write or spawn) — which is what makes this
61
+ // safe, and worth preserving.
62
+ if (process.argv[2] === SYNC_GET_CMD ||
63
+ process.argv[2] === SYNC_PING_CMD ||
64
+ process.argv[2] === SYNC_LOCK_CMD) {
65
+ const { runAgentGetSync, runAgentPingSync, runAgentLockSync } = await import('./lib/secrets/agent.js');
66
+ const name = process.argv[3] ?? '';
67
+ const code = process.argv[2] === SYNC_GET_CMD ? await runAgentGetSync(name)
68
+ : process.argv[2] === SYNC_PING_CMD ? await runAgentPingSync()
69
+ : await runAgentLockSync(name);
70
+ process.exit(code);
71
+ }
34
72
  import { NPM_PACKAGE_NAME, deriveGlobalPrefix, detectPackageManager, installPackageIntoPrefix, installPackageWithBun, verifyInstalledVersion, refreshAliasShims, downloadVerifiedTarball, } from './lib/self-update.js';
35
73
  // Detect dev/working-tree builds and default the noisy startup steps off.
36
74
  // Three cases trip this:
@@ -55,9 +93,10 @@ if (IS_DEV_BUILD) {
55
93
  // module on each invocation (which loaded the whole ~50-module tree before the
56
94
  // first byte of output), the registry maps a command name to a thunk that
57
95
  // imports only what that command needs. See src/lib/startup/command-registry.ts.
58
- import { COMMAND_LOADERS, LAZY_COMMAND_NAMES, loadView, loadInspect, loadResources, loadFeedback, loadCommands, loadHooks, loadSkills, loadRules, loadMemory, loadPermissions, loadMcp, loadCli, loadSubagents, loadPlugins, loadWorkflows, loadWorktree, loadVersions, loadImport, loadExport, loadPackages, loadRoutines, loadMonitors, loadRun, loadFork, loadDefaults, loadModels, loadPrune, loadTrash, loadRestore, loadDoctor, loadApply, loadCheck, loadStatus, loadProfiles, loadSecrets, loadLogin, loadWallet, loadHelper, loadMenubar, loadBeta, loadSync, loadLock, loadRefreshRules, loadDrive, loadFactory, loadUsage, loadCost, loadOutput, loadBudget, loadAlias, loadMine, loadPty, loadTmux, loadWatchdog, loadBrowser, loadComputer, loadHosts, loadLogs, loadEvents, loadAudit, loadWebhook, loadFunnel, loadSsh, loadPull, loadPush, loadRepo, loadSetup, loadUninstall, loadShare, loadSend, loadHq, loadFeed, loadActivity, loadMailboxes, } from './lib/startup/command-registry.js';
96
+ import { COMMAND_LOADERS, LAZY_COMMAND_NAMES, loadView, loadInspect, loadResources, loadFeedback, loadCommands, loadHooks, loadSkills, loadRules, loadMemory, loadPermissions, loadMcp, loadCli, loadSubagents, loadPlugins, loadWorkflows, loadWorktree, loadVersions, loadImport, loadExport, loadPackages, loadRoutines, loadMonitors, loadRun, loadFork, loadDefaults, loadModels, loadPrune, loadTrash, loadRestore, loadDoctor, loadApply, loadCheck, loadStatus, loadProfiles, loadHarness, loadSecrets, loadLogin, loadWallet, loadHelper, loadMenubar, loadBeta, loadSync, loadLock, loadRefreshRules, loadDrive, loadFactory, loadUsage, loadCost, loadOutput, loadBudget, loadAlias, loadMine, loadPty, loadTmux, loadWatchdog, loadBrowser, loadComputer, loadHosts, loadLogs, loadEvents, loadAudit, loadWebhook, loadFunnel, loadSsh, loadPull, loadPush, loadRepo, loadSetup, loadUninstall, loadShare, loadSend, loadHq, loadFeed, loadActivity, loadMailboxes, } from './lib/startup/command-registry.js';
59
97
  import { applyGlobalHelpConventions } from './lib/help.js';
60
98
  import { renderWhatsNew } from './lib/whats-new.js';
99
+ import { getCliLaunch } from './lib/cli-entry.js';
61
100
  import { emit, redactArgs } from './lib/events.js';
62
101
  // Transparent shim delegate: the generated Windows `.cmd` shims invoke
63
102
  // `agents __shim <agent>[@version] <raw args>`. Intercept here, before commander
@@ -294,7 +333,7 @@ async function showWhatsNew(fromVersion, toVersion) {
294
333
  const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
295
334
  import { getUpdateCheckPath, getMigratedSentinelPath, getUserAgentsDir, getRuntimeStateDir } from './lib/state.js';
296
335
  import { resolveBrandName, disabledCommandsForActiveBrand } from './lib/brand.js';
297
- import { readUpdateCache, saveUpdateCheck, dismissUpdateVersion, shouldPromptUpgrade, findAgentsCliInstalls, } from './lib/self-update.js';
336
+ import { readUpdateCache, saveUpdateCheck, dismissUpdateVersion, shouldPromptUpgrade, findAgentsCliInstalls, resolveRunningPackageRoot, } from './lib/self-update.js';
298
337
  const UPDATE_CHECK_FILE = getUpdateCheckPath();
299
338
  /**
300
339
  * Warn once when PATH resolves `agents` to a different agents-cli install
@@ -306,7 +345,16 @@ const UPDATE_CHECK_FILE = getUpdateCheckPath();
306
345
  */
307
346
  function maybeWarnMultiInstall() {
308
347
  const sentinel = path.join(getRuntimeStateDir(), 'multi-install-warned');
309
- const runningRoot = path.resolve(__dirname, '..');
348
+ let runningRoot;
349
+ try {
350
+ runningRoot = resolveRunningPackageRoot(__dirname);
351
+ }
352
+ catch {
353
+ // Without a real root for the running copy there is nothing to compare
354
+ // against, and a guess here is exactly what produced the phantom
355
+ // "/$bunfs" install. This warning is advisory — stay silent instead.
356
+ return;
357
+ }
310
358
  const byRoot = new Map();
311
359
  byRoot.set(runningRoot, { version: VERSION, note: 'running' });
312
360
  for (const install of findAgentsCliInstalls(process.env.PATH || '')) {
@@ -370,7 +418,7 @@ function printResolvedPackage(metadata) {
370
418
  console.log(chalk.gray(`Integrity: ${metadata.integrity}`));
371
419
  }
372
420
  async function installResolvedPackage(metadata) {
373
- const packageRoot = path.resolve(__dirname, '..');
421
+ const packageRoot = resolveRunningPackageRoot(__dirname);
374
422
  // Download the published tarball and prove its bytes match the registry
375
423
  // integrity BEFORE installing anything. A `name@version` spec would let the
376
424
  // package manager fetch and install whatever the registry serves with no
@@ -466,9 +514,11 @@ async function promptUpgrade(latestVersion) {
466
514
  console.log();
467
515
  // Re-exec the verified install's entrypoint and exit. PATH lookup of
468
516
  // `agents` could resolve a different copy (dev build, another prefix)
469
- // than the one that was just upgraded.
470
- const entrypoint = path.resolve(__dirname, '..', 'dist', 'index.js');
471
- const result = spawnSync(process.execPath, [entrypoint, ...process.argv.slice(2)], {
517
+ // than the one that was just upgraded. getCliLaunch resolves the JS-vs-
518
+ // standalone shape never hand-roll `[process.execPath, entrypoint]`,
519
+ // which hands the bun virtual entry to a compiled binary as a bogus arg.
520
+ const { command, args } = getCliLaunch(process.argv.slice(2));
521
+ const result = spawnSync(command, args, {
472
522
  stdio: 'inherit',
473
523
  shell: false,
474
524
  });
@@ -747,6 +797,7 @@ async function registerAllEagerCommands() {
747
797
  await reg(loadStatus);
748
798
  registerExecAliasCommand(program);
749
799
  await reg(loadProfiles);
800
+ await reg(loadHarness);
750
801
  await reg(loadSecrets);
751
802
  await reg(loadLogin);
752
803
  await reg(loadWallet);
@@ -1,6 +1,8 @@
1
1
  import type { EventRecord } from './events.js';
2
2
  /** Recognizable milestone events, ordered first in any activity lane. */
3
- export type MilestoneEvent = 'plan.created' | 'pr.opened' | 'pr.merged' | 'worktree.created' | 'worktree.removed' | 'commit.created' | 'pushed' | 'subagent.spawned' | 'artifact.created';
3
+ export type MilestoneEvent = 'plan.created' | 'pr.opened' | 'pr.merged' | 'worktree.created' | 'worktree.removed' | 'commit.created' | 'pushed' | 'subagent.spawned' | 'artifact.created'
4
+ /** Deliberate agent-authored progress post (`agents feed post`). */
5
+ | 'status.posted';
4
6
  /** Routine activity events, collapsed to counts by readers. */
5
7
  export type ActivityKind = 'file.edited';
6
8
  export type ActivityEventKind = MilestoneEvent | ActivityKind;
@@ -29,12 +31,20 @@ export interface ActivityEvent {
29
31
  cwd?: string;
30
32
  /** Agent that produced the event (claude, codex, ...). */
31
33
  agent?: string;
32
- /** Tool that triggered the event (Bash, Task, ExitPlanMode, ...). */
34
+ /** Tool that triggered the event (Bash, Task, ExitPlanMode, feed.post, ...). */
33
35
  tool?: string;
34
- /** One-line human summary (plan title, PR command, sub-agent role). */
36
+ /** One-line human summary (plan title, PR command, sub-agent role, status text). */
35
37
  detail?: string;
36
38
  /** Extracted URL when the event has one (e.g. the opened PR). */
37
39
  url?: string;
40
+ /** Auto-stamped process identity for deliberate posts (from pid registry / env). */
41
+ pid?: number;
42
+ /** Spawn-time join key (`AGENT_LAUNCH_ID`) when known. */
43
+ launchId?: string;
44
+ /** Factory terminal id when the launch inherited one. */
45
+ terminalId?: string;
46
+ /** `$TMUX_PANE` at launch when recorded. */
47
+ tmuxPane?: string;
38
48
  }
39
49
  /**
40
50
  * Append one event to a session's activity log. Primarily the Python hook
@@ -110,7 +120,7 @@ export declare function formatActivityLine(ev: ActivityEvent, opts?: {
110
120
  * Edit|MultiEdit) so read-only tools never pay the hook cost. Fail-open: any
111
121
  * error is swallowed so a logging hiccup never blocks a tool call.
112
122
  */
113
- export declare const ACTIVITY_LOG_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Append agent-activity events for `agents feed` / `agents activity`.\n\nBound to PreToolUse (ExitPlanMode, Task) and PostToolUse (Bash, Write, Edit,\nMultiEdit). One append-only file per session; read-only tools never trigger it\nbecause the manifest matcher excludes them.\n\nSub-agent gate: when the payload carries `agent_type`, this is a Task/Agent\nsub-agent -- skip so only the top-level agent logs its own activity.\n\nFail-open: ANY error is swallowed so a logging hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport re\nimport sys\nimport json\nimport shlex\nimport socket\nfrom datetime import datetime, timezone\n\nMAX_LOG_BYTES = 5 * 1024 * 1024 # cap a pathological session's log\nMILESTONE_EVENTS = {\n \"plan.created\", \"pr.opened\", \"pr.merged\", \"worktree.created\",\n \"worktree.removed\", \"commit.created\", \"pushed\", \"subagent.spawned\",\n \"artifact.created\",\n}\n\n# Deliverable file types + locations -- a Write here is a recognizable artifact\n# (an HTML plan, a PDF report, a rendered image), not a routine code edit.\nARTIFACT_EXTS = {\n \".html\", \".htm\", \".pdf\", \".png\", \".jpg\", \".jpeg\", \".gif\", \".svg\",\n \".webp\", \".mp4\", \".mov\", \".webm\", \".csv\", \".xlsx\", \".pptx\", \".docx\",\n}\nARTIFACT_DIR_HINTS = (\"/tmp/\", \"/downloads/\", \"/.agents/artifacts/\")\n\n\ndef is_artifact(file_path):\n low = (file_path or \"\").lower()\n if os.path.splitext(low)[1] in ARTIFACT_EXTS:\n return True\n return any(hint in low for hint in ARTIFACT_DIR_HINTS)\n\n\ndef first_line(text, limit=140):\n for raw in (text or \"\").splitlines():\n s = raw.strip().lstrip(\"#\").strip()\n if s:\n return s[:limit]\n return \"\"\n\n\ndef _subcommand(tokens, tool):\n \"\"\"First non-flag token after `tool`, i.e. its subcommand (skips -C <path>,\n -c <cfg>, and other leading flags). None if `tool` isn't the invoked command.\"\"\"\n try:\n i = tokens.index(tool) + 1\n except ValueError:\n return None, []\n while i < len(tokens):\n t = tokens[i]\n if t in (\"-C\", \"-c\", \"--git-dir\", \"--work-tree\"):\n i += 2 # flag that consumes the next token\n continue\n if t.startswith(\"-\"):\n i += 1\n continue\n return t, tokens[i + 1:]\n return None, []\n\n\ndef classify_bash(command):\n \"\"\"Return the milestone event for a git/gh command, else None. Tokenizes so a\n path like `git diff -- src/commit.ts` is not mistaken for a commit.\"\"\"\n try:\n tokens = shlex.split(command or \"\")\n except Exception:\n tokens = (command or \"\").split()\n\n verb, rest = _subcommand(tokens, \"git\")\n if verb == \"worktree\":\n sub = rest[0] if rest else \"\"\n if sub == \"add\":\n return \"worktree.created\"\n if sub == \"remove\":\n return \"worktree.removed\"\n elif verb == \"commit\":\n return \"commit.created\"\n elif verb == \"push\":\n return \"pushed\"\n\n verb, rest = _subcommand(tokens, \"gh\")\n if verb == \"pr\" and rest:\n if rest[0] == \"create\":\n return \"pr.opened\"\n if rest[0] == \"merge\":\n return \"pr.merged\"\n return None\n\n\ndef extract_url(tool_response):\n \"\"\"Pull the first https URL out of a Bash tool response (stdout).\"\"\"\n text = \"\"\n if isinstance(tool_response, dict):\n text = str(tool_response.get(\"stdout\") or tool_response.get(\"output\") or \"\")\n elif isinstance(tool_response, str):\n text = tool_response\n m = re.search(r\"https?://\\S+\", text)\n return m.group(0).rstrip(\").,\") if m else None\n\n\ndef build_event(payload, hook_event):\n tool_name = payload.get(\"tool_name\", \"\")\n tool_input = payload.get(\"tool_input\", {}) or {}\n tool_response = payload.get(\"tool_response\", {})\n\n event = None\n detail = None\n url = None\n\n if hook_event == \"PreToolUse\":\n if tool_name == \"ExitPlanMode\":\n event = \"plan.created\"\n detail = first_line(tool_input.get(\"plan\", \"\")) or \"plan presented\"\n elif tool_name == \"Task\":\n event = \"subagent.spawned\"\n role = tool_input.get(\"subagent_type\") or \"agent\"\n desc = tool_input.get(\"description\") or tool_input.get(\"prompt\") or \"\"\n detail = (role + \": \" + first_line(desc)).strip(\": \").strip()\n elif hook_event == \"PostToolUse\":\n if tool_name == \"Bash\":\n event = classify_bash(tool_input.get(\"command\", \"\"))\n if event:\n detail = first_line(tool_input.get(\"command\", \"\"))\n url = extract_url(tool_response)\n elif tool_name in (\"Write\", \"Edit\", \"MultiEdit\"):\n fp = tool_input.get(\"file_path\") or tool_input.get(\"path\") or \"\"\n # A freshly-written deliverable is a milestone; edits and code\n # writes stay routine and collapse to a count.\n if tool_name == \"Write\" and is_artifact(fp):\n event = \"artifact.created\"\n else:\n event = \"file.edited\"\n detail = os.path.basename(fp) if fp else tool_name\n\n if not event:\n return None, tool_name\n\n tier = \"milestone\" if event in MILESTONE_EVENTS else \"activity\"\n record = {\n \"v\": 1,\n \"ts\": datetime.now(timezone.utc).isoformat(),\n \"event\": event,\n \"tier\": tier,\n }\n if detail:\n record[\"detail\"] = detail\n if url:\n record[\"url\"] = url\n record[\"tool\"] = tool_name\n return record, tool_name\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n # Sub-agent gate -- only the top-level agent logs.\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n hook_event = payload.get(\"hook_event_name\", \"\")\n record, tool_name = build_event(payload, hook_event)\n if not record:\n return\n\n safe_session = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id) or \"unknown\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n activity_dir = os.path.join(home, \".agents\", \".history\", \"activity\")\n target = os.path.join(activity_dir, safe_session + \".jsonl\")\n\n # Identity (mirrors 10-feed-publish.py).\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", hostname.split(\".\")[0].strip().lower()) or \"unknown\"\n\n record[\"sessionId\"] = session_id\n record[\"mailboxId\"] = mailbox_id\n record[\"host\"] = host\n record[\"runtime\"] = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n if cwd:\n record[\"cwd\"] = cwd\n agent = os.environ.get(\"AGENTS_AGENT_NAME\") or \"claude\"\n record[\"agent\"] = agent\n\n try:\n os.makedirs(activity_dir, exist_ok=True)\n # Cap growth: once over the size limit, keep only milestones.\n if record[\"tier\"] != \"milestone\":\n try:\n if os.path.getsize(target) > MAX_LOG_BYTES:\n return\n except OSError:\n pass\n with open(target, \"a\") as f:\n f.write(json.dumps(record) + \"\\n\")\n except Exception:\n pass # fail open\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass # fail open\n";
123
+ export declare const ACTIVITY_LOG_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Append agent-activity events for `agents feed` / `agents activity`.\n\nBound to PreToolUse (ExitPlanMode, Task) and PostToolUse (Bash, Write, Edit,\nMultiEdit). One append-only file per session; read-only tools never trigger it\nbecause the manifest matcher excludes them.\n\nSub-agent gate: when the payload carries `agent_type`, this is a Task/Agent\nsub-agent -- skip so only the top-level agent logs its own activity.\n\nFail-open: ANY error is swallowed so a logging hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport re\nimport sys\nimport json\nimport shlex\nimport socket\nfrom datetime import datetime, timezone\n\nMAX_LOG_BYTES = 5 * 1024 * 1024 # cap a pathological session's log\nMILESTONE_EVENTS = {\n \"plan.created\", \"pr.opened\", \"pr.merged\", \"worktree.created\",\n \"worktree.removed\", \"commit.created\", \"pushed\", \"subagent.spawned\",\n \"artifact.created\", \"status.posted\",\n}\n\n# Deliverable file types + locations -- a Write here is a recognizable artifact\n# (an HTML plan, a PDF report, a rendered image), not a routine code edit.\nARTIFACT_EXTS = {\n \".html\", \".htm\", \".pdf\", \".png\", \".jpg\", \".jpeg\", \".gif\", \".svg\",\n \".webp\", \".mp4\", \".mov\", \".webm\", \".csv\", \".xlsx\", \".pptx\", \".docx\",\n}\nARTIFACT_DIR_HINTS = (\"/tmp/\", \"/downloads/\", \"/.agents/artifacts/\")\n\n\ndef is_artifact(file_path):\n low = (file_path or \"\").lower()\n if os.path.splitext(low)[1] in ARTIFACT_EXTS:\n return True\n return any(hint in low for hint in ARTIFACT_DIR_HINTS)\n\n\ndef first_line(text, limit=140):\n for raw in (text or \"\").splitlines():\n s = raw.strip().lstrip(\"#\").strip()\n if s:\n return s[:limit]\n return \"\"\n\n\ndef _subcommand(tokens, tool):\n \"\"\"First non-flag token after `tool`, i.e. its subcommand (skips -C <path>,\n -c <cfg>, and other leading flags). None if `tool` isn't the invoked command.\"\"\"\n try:\n i = tokens.index(tool) + 1\n except ValueError:\n return None, []\n while i < len(tokens):\n t = tokens[i]\n if t in (\"-C\", \"-c\", \"--git-dir\", \"--work-tree\"):\n i += 2 # flag that consumes the next token\n continue\n if t.startswith(\"-\"):\n i += 1\n continue\n return t, tokens[i + 1:]\n return None, []\n\n\ndef classify_bash(command):\n \"\"\"Return the milestone event for a git/gh command, else None. Tokenizes so a\n path like `git diff -- src/commit.ts` is not mistaken for a commit.\"\"\"\n try:\n tokens = shlex.split(command or \"\")\n except Exception:\n tokens = (command or \"\").split()\n\n verb, rest = _subcommand(tokens, \"git\")\n if verb == \"worktree\":\n sub = rest[0] if rest else \"\"\n if sub == \"add\":\n return \"worktree.created\"\n if sub == \"remove\":\n return \"worktree.removed\"\n elif verb == \"commit\":\n return \"commit.created\"\n elif verb == \"push\":\n return \"pushed\"\n\n verb, rest = _subcommand(tokens, \"gh\")\n if verb == \"pr\" and rest:\n if rest[0] == \"create\":\n return \"pr.opened\"\n if rest[0] == \"merge\":\n return \"pr.merged\"\n return None\n\n\ndef extract_url(tool_response):\n \"\"\"Pull the first https URL out of a Bash tool response (stdout).\"\"\"\n text = \"\"\n if isinstance(tool_response, dict):\n text = str(tool_response.get(\"stdout\") or tool_response.get(\"output\") or \"\")\n elif isinstance(tool_response, str):\n text = tool_response\n m = re.search(r\"https?://\\S+\", text)\n return m.group(0).rstrip(\").,\") if m else None\n\n\ndef build_event(payload, hook_event):\n tool_name = payload.get(\"tool_name\", \"\")\n tool_input = payload.get(\"tool_input\", {}) or {}\n tool_response = payload.get(\"tool_response\", {})\n\n event = None\n detail = None\n url = None\n\n if hook_event == \"PreToolUse\":\n if tool_name == \"ExitPlanMode\":\n event = \"plan.created\"\n detail = first_line(tool_input.get(\"plan\", \"\")) or \"plan presented\"\n elif tool_name == \"Task\":\n event = \"subagent.spawned\"\n role = tool_input.get(\"subagent_type\") or \"agent\"\n desc = tool_input.get(\"description\") or tool_input.get(\"prompt\") or \"\"\n detail = (role + \": \" + first_line(desc)).strip(\": \").strip()\n elif hook_event == \"PostToolUse\":\n if tool_name == \"Bash\":\n event = classify_bash(tool_input.get(\"command\", \"\"))\n if event:\n detail = first_line(tool_input.get(\"command\", \"\"))\n url = extract_url(tool_response)\n elif tool_name in (\"Write\", \"Edit\", \"MultiEdit\"):\n fp = tool_input.get(\"file_path\") or tool_input.get(\"path\") or \"\"\n # A freshly-written deliverable is a milestone; edits and code\n # writes stay routine and collapse to a count.\n if tool_name == \"Write\" and is_artifact(fp):\n event = \"artifact.created\"\n else:\n event = \"file.edited\"\n detail = os.path.basename(fp) if fp else tool_name\n\n if not event:\n return None, tool_name\n\n tier = \"milestone\" if event in MILESTONE_EVENTS else \"activity\"\n record = {\n \"v\": 1,\n \"ts\": datetime.now(timezone.utc).isoformat(),\n \"event\": event,\n \"tier\": tier,\n }\n if detail:\n record[\"detail\"] = detail\n if url:\n record[\"url\"] = url\n record[\"tool\"] = tool_name\n return record, tool_name\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n # Sub-agent gate -- only the top-level agent logs.\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n hook_event = payload.get(\"hook_event_name\", \"\")\n record, tool_name = build_event(payload, hook_event)\n if not record:\n return\n\n safe_session = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id) or \"unknown\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n activity_dir = os.path.join(home, \".agents\", \".history\", \"activity\")\n target = os.path.join(activity_dir, safe_session + \".jsonl\")\n\n # Identity (mirrors 10-feed-publish.py).\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", hostname.split(\".\")[0].strip().lower()) or \"unknown\"\n\n record[\"sessionId\"] = session_id\n record[\"mailboxId\"] = mailbox_id\n record[\"host\"] = host\n record[\"runtime\"] = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n if cwd:\n record[\"cwd\"] = cwd\n agent = os.environ.get(\"AGENTS_AGENT_NAME\") or \"claude\"\n record[\"agent\"] = agent\n\n try:\n os.makedirs(activity_dir, exist_ok=True)\n # Cap growth: once over the size limit, keep only milestones.\n if record[\"tier\"] != \"milestone\":\n try:\n if os.path.getsize(target) > MAX_LOG_BYTES:\n return\n except OSError:\n pass\n with open(target, \"a\") as f:\n f.write(json.dumps(record) + \"\\n\")\n except Exception:\n pass # fail open\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass # fail open\n";
114
124
  /** Hook manifest entries (agents.yaml shape) for the activity-log hook. */
115
125
  export declare const ACTIVITY_HOOK_DEFINITIONS: Record<string, Record<string, unknown>>;
116
126
  /**
@@ -34,6 +34,7 @@ export const MILESTONE_EVENTS = [
34
34
  'pushed',
35
35
  'subagent.spawned',
36
36
  'artifact.created',
37
+ 'status.posted',
37
38
  ];
38
39
  const MILESTONE_SET = new Set(MILESTONE_EVENTS);
39
40
  export function tierForEvent(event) {
@@ -82,6 +83,10 @@ function parseLine(line) {
82
83
  tool: parsed.tool,
83
84
  detail: parsed.detail,
84
85
  url: parsed.url,
86
+ pid: typeof parsed.pid === 'number' ? parsed.pid : undefined,
87
+ launchId: parsed.launchId,
88
+ terminalId: parsed.terminalId,
89
+ tmuxPane: parsed.tmuxPane,
85
90
  };
86
91
  }
87
92
  catch {
@@ -193,11 +198,11 @@ export function activityEventToRecord(ev) {
193
198
  hostname: ev.host,
194
199
  platform: process.platform,
195
200
  arch: process.arch,
196
- pid: 0,
201
+ pid: ev.pid ?? 0,
197
202
  ppid: 0,
198
203
  event: ev.event,
199
204
  level: 'info',
200
- caller: 'hook',
205
+ caller: ev.tool === 'feed.post' ? 'agent' : 'hook',
201
206
  session: ev.sessionId,
202
207
  osUser: ev.agent ?? 'agent',
203
208
  transport: 'local',
@@ -210,6 +215,9 @@ export function activityEventToRecord(ev) {
210
215
  detail: ev.detail,
211
216
  url: ev.url,
212
217
  tier: ev.tier,
218
+ ...(ev.launchId ? { launchId: ev.launchId } : {}),
219
+ ...(ev.terminalId ? { terminalId: ev.terminalId } : {}),
220
+ ...(ev.tmuxPane ? { tmuxPane: ev.tmuxPane } : {}),
213
221
  };
214
222
  }
215
223
  /** Read recent activity across sessions as unified {@link EventRecord}s. */
@@ -230,6 +238,7 @@ export const EVENT_STYLE = {
230
238
  'pushed': { glyph: '↥', color: chalk.yellow, label: 'pushed' },
231
239
  'subagent.spawned': { glyph: '⑂', color: chalk.magenta, label: 'sub-agent spawned' },
232
240
  'artifact.created': { glyph: '▤', color: chalk.cyan, label: 'artifact' },
241
+ 'status.posted': { glyph: '▸', color: chalk.white, label: 'status' },
233
242
  'file.edited': { glyph: '·', color: chalk.gray, label: 'file edited' },
234
243
  };
235
244
  export function styleForEvent(event) {
@@ -240,10 +249,13 @@ export function formatActivityLine(ev, opts = {}) {
240
249
  const s = styleForEvent(ev.event);
241
250
  const host = opts.showHost && ev.host && ev.host !== 'unknown' ? chalk.gray(`[${ev.host}] `) : '';
242
251
  const label = s.color(`${s.glyph} ${s.label}`);
243
- const detail = ev.detail ? ` ${truncate(ev.detail, 60)}` : '';
252
+ // Status posts are the message; allow a longer snippet than tool-derived detail.
253
+ const detailLimit = ev.event === 'status.posted' ? 100 : 60;
254
+ const detail = ev.detail ? ` ${truncate(ev.detail, detailLimit)}` : '';
244
255
  const url = ev.url ? chalk.gray(` ${ev.url}`) : '';
256
+ const agent = ev.event === 'status.posted' && ev.agent ? chalk.gray(` · ${ev.agent}`) : '';
245
257
  const when = chalk.gray(relTime(ev.ts).padStart(7));
246
- return ` ${when} ${host}${label}${detail}${url}`;
258
+ return ` ${when} ${host}${label}${detail}${agent}${url}`;
247
259
  }
248
260
  // ---------------------------------------------------------------------------
249
261
  // Hook installation
@@ -281,7 +293,7 @@ MAX_LOG_BYTES = 5 * 1024 * 1024 # cap a pathological session's log
281
293
  MILESTONE_EVENTS = {
282
294
  "plan.created", "pr.opened", "pr.merged", "worktree.created",
283
295
  "worktree.removed", "commit.created", "pushed", "subagent.spawned",
284
- "artifact.created",
296
+ "artifact.created", "status.posted",
285
297
  }
286
298
 
287
299
  # Deliverable file types + locations -- a Write here is a recognizable artifact
@@ -0,0 +1,50 @@
1
+ import type { ActorConfig } from './types.js';
2
+ export type ActorKind = 'human' | 'agent';
3
+ export interface ResolvedActor {
4
+ /**
5
+ * Stable id for the responsible entity: the tailnet login (usually an email)
6
+ * for a resolved human, or `UNRESOLVED@<host>` when it can't be determined.
7
+ */
8
+ id: string;
9
+ kind: ActorKind;
10
+ /** Human-readable name, for git author + display. */
11
+ name?: string;
12
+ /** Email, for git author + as a durable key. */
13
+ email?: string;
14
+ /** GitHub handle, when the actors map records one. */
15
+ github?: string;
16
+ }
17
+ /** Result of `tailscale whois --json <ip>` we care about. */
18
+ export interface WhoisIdentity {
19
+ login?: string;
20
+ displayName?: string;
21
+ }
22
+ /**
23
+ * Map a resolved tailnet identity (+ the actors map) to a ResolvedActor. Pure --
24
+ * the impure whois/config reads happen in computeActor -- so the enrich/override
25
+ * path is fully testable. No login (local, or an unnameable peer) yields the
26
+ * honest `UNRESOLVED@<host>`; a login without a config entry still credits git
27
+ * from the tailnet DisplayName + login email.
28
+ */
29
+ export declare function actorFromIdentity(who: WhoisIdentity | undefined, host: string, actors: Record<string, ActorConfig>): ResolvedActor;
30
+ /**
31
+ * Compute the actor for a given environment. Pure with respect to `env` (the
32
+ * only impurity is the `tailscale whois` / config read on the fresh-SSH path),
33
+ * so tests can drive every branch by passing an env explicitly.
34
+ */
35
+ export declare function computeActor(env?: NodeJS.ProcessEnv): ResolvedActor;
36
+ /**
37
+ * Resolve the actor for the current process, cached for the process lifetime
38
+ * (the SSH `whois` shell-out runs at most once).
39
+ */
40
+ export declare function resolveActor(): ResolvedActor;
41
+ /** Clear the per-process cache. For tests, and for env changes within a run. */
42
+ export declare function resetActorCache(): void;
43
+ /**
44
+ * The env an actor propagates to child processes. Always carries the actor id +
45
+ * kind (so children inherit and don't re-resolve). For a resolved human with a
46
+ * real name and email, it also carries `GIT_AUTHOR_*` / `GIT_COMMITTER_*` so the
47
+ * agent's own commits are credited to the person, not the shared account. An
48
+ * unresolved actor sets no git identity -- git keeps its ambient config.
49
+ */
50
+ export declare function actorEnv(actor: ResolvedActor): Record<string, string>;