@phnx-labs/agents-cli 1.23.39 → 1.23.40

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 (84) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +7 -20
  3. package/dist/cli/command-registry.js +0 -2
  4. package/dist/commands/config.js +0 -4
  5. package/dist/commands/daemon.js +5 -5
  6. package/dist/commands/events.js +1 -1
  7. package/dist/commands/lead.js +4 -3
  8. package/dist/commands/setup.d.ts +1 -1
  9. package/dist/commands/setup.js +1 -9
  10. package/dist/commands/ssh.js +4 -5
  11. package/dist/lib/accounting/usage.d.ts +1 -1
  12. package/dist/lib/answer-router.d.ts +1 -1
  13. package/dist/lib/answer-router.js +16 -6
  14. package/dist/lib/channels/providers/session.js +13 -0
  15. package/dist/lib/channels/registry.d.ts +1 -1
  16. package/dist/lib/config-keys.d.ts +1 -1
  17. package/dist/lib/config-keys.js +1 -4
  18. package/dist/lib/daemon/daemon.js +1 -6
  19. package/dist/lib/daemon-services.d.ts +1 -1
  20. package/dist/lib/daemon-services.js +0 -5
  21. package/dist/lib/device-config.js +2 -11
  22. package/dist/lib/feed/answer.js +25 -1
  23. package/dist/lib/feed/attention.d.ts +8 -0
  24. package/dist/lib/feed/attention.js +39 -0
  25. package/dist/lib/feed/tab-delivery.d.ts +27 -0
  26. package/dist/lib/feed/tab-delivery.js +102 -0
  27. package/dist/lib/feed/watch.d.ts +3 -0
  28. package/dist/lib/feed/watch.js +63 -13
  29. package/dist/lib/hosts/passthrough.js +0 -1
  30. package/dist/lib/installations/migrate.d.ts +0 -1
  31. package/dist/lib/installations/migrate.js +0 -17
  32. package/dist/lib/lead/drafts.d.ts +11 -0
  33. package/dist/lib/lead/drafts.js +34 -0
  34. package/dist/lib/lead/host.d.ts +5 -0
  35. package/dist/lib/lead/host.js +52 -1
  36. package/dist/lib/lead/paths.js +1 -1
  37. package/dist/lib/lead/tools.d.ts +1 -0
  38. package/dist/lib/lead/tools.js +22 -0
  39. package/dist/lib/menubar/snapshot.d.ts +0 -6
  40. package/dist/lib/menubar/snapshot.js +0 -18
  41. package/dist/lib/session/active.d.ts +2 -1
  42. package/dist/lib/session/active.js +10 -6
  43. package/dist/lib/session/hook-sessions.d.ts +10 -0
  44. package/dist/lib/session/hook-sessions.js +22 -10
  45. package/dist/lib/session/inject-target.d.ts +1 -0
  46. package/dist/lib/session/inject-target.js +2 -1
  47. package/dist/lib/session/pid-registry.d.ts +1 -0
  48. package/dist/lib/session/remote/watch.d.ts +1 -0
  49. package/dist/lib/startup/command-registry.js +2 -1
  50. package/dist/lib/state.js +0 -1
  51. package/dist/lib/terminal/index.d.ts +1 -1
  52. package/dist/lib/terminal/index.js +1 -1
  53. package/dist/lib/terminal/inject.d.ts +0 -15
  54. package/dist/lib/terminal/inject.js +2 -16
  55. package/dist/lib/terminal/resolve.d.ts +2 -1
  56. package/dist/lib/terminal/resolve.js +13 -18
  57. package/dist/lib/types.d.ts +0 -3
  58. package/package.json +1 -1
  59. package/dist/commands/setup-watchdog.d.ts +0 -3
  60. package/dist/commands/setup-watchdog.js +0 -49
  61. package/dist/commands/watchdog.d.ts +0 -4
  62. package/dist/commands/watchdog.js +0 -361
  63. package/dist/lib/daemon/watchdog-service.d.ts +0 -10
  64. package/dist/lib/daemon/watchdog-service.js +0 -27
  65. package/dist/lib/session/presence.d.ts +0 -47
  66. package/dist/lib/session/presence.js +0 -100
  67. package/dist/lib/watchdog/history.d.ts +0 -20
  68. package/dist/lib/watchdog/history.js +0 -43
  69. package/dist/lib/watchdog/log.d.ts +0 -33
  70. package/dist/lib/watchdog/log.js +0 -117
  71. package/dist/lib/watchdog/read.d.ts +0 -8
  72. package/dist/lib/watchdog/read.js +0 -93
  73. package/dist/lib/watchdog/rotate.d.ts +0 -55
  74. package/dist/lib/watchdog/rotate.js +0 -220
  75. package/dist/lib/watchdog/runner.d.ts +0 -100
  76. package/dist/lib/watchdog/runner.js +0 -727
  77. package/dist/lib/watchdog/service.d.ts +0 -15
  78. package/dist/lib/watchdog/service.js +0 -36
  79. package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
  80. package/dist/lib/watchdog/watchdog-agent.js +0 -32
  81. package/dist/lib/watchdog/watchdog.d.ts +0 -43
  82. package/dist/lib/watchdog/watchdog.js +0 -116
  83. package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
  84. package/dist/lib/watchdog/watchdogTail.js +0 -116
@@ -151,6 +151,42 @@ function attentionFromBlock(block, session, nowMs) {
151
151
  };
152
152
  return { item, generation };
153
153
  }
154
+ export function currentTurnVerdict(session) {
155
+ const v = session.turnVerdict;
156
+ if (!v || session.activity === 'working')
157
+ return undefined;
158
+ if (session.lastEventMs != null && session.lastEventMs > v.atMs)
159
+ return undefined;
160
+ return v;
161
+ }
162
+ function attentionFromTurnVerdict(session) {
163
+ const v = currentTurnVerdict(session);
164
+ if (!v || (v.kind !== 'asks' && v.kind !== 'not_done'))
165
+ return undefined;
166
+ const question = v.kind === 'asks'
167
+ ? { text: v.quote || 'The agent is waiting for your answer.', ...(v.choices.length ? { options: v.choices.map((label) => ({ label })) } : {}) }
168
+ : { text: v.quote || 'The agent stopped before finishing.', header: 'Not done' };
169
+ const host = session.host ?? 'unknown';
170
+ const sessionId = session.sessionId ?? '';
171
+ const generation = `v${v.atMs}`;
172
+ const item = {
173
+ key: attentionKey(host, sessionId, generation),
174
+ sessionId,
175
+ mailboxId: sessionId,
176
+ host,
177
+ project: session.project ?? undefined,
178
+ kind: 'question',
179
+ source: 'lifecycle',
180
+ state: 'open',
181
+ openedAt: new Date(v.atMs).toISOString(),
182
+ question,
183
+ choices: questionChoices(question),
184
+ replyCapability: replyCapabilityForSession(session),
185
+ fingerprint: attentionFingerprint('question', question),
186
+ sourceCursor: { lastActivityMs: v.atMs },
187
+ };
188
+ return { item, generation };
189
+ }
154
190
  function attentionFromSession(session, nowMs) {
155
191
  if (session.activity !== 'waiting_input')
156
192
  return undefined;
@@ -160,6 +196,8 @@ function attentionFromSession(session, nowMs) {
160
196
  const kind = reason === 'plan_review' ? 'plan_review' : reason === 'permission' ? 'unverified' : 'question';
161
197
  const sq = session.question;
162
198
  const structural = kind === 'plan_review' || (kind === 'question' && (sq?.options?.length ?? 0) > 0);
199
+ if (!structural && kind === 'question' && currentTurnVerdict(session))
200
+ return undefined;
163
201
  const source = structural ? 'lifecycle' : 'heuristic';
164
202
  const question = sq ? structuredToBlockQuestion(sq) : undefined;
165
203
  const host = session.host ?? 'unknown';
@@ -295,6 +333,7 @@ export function reconcileAttention(input) {
295
333
  : undefined;
296
334
  const candidate = fromBlock ??
297
335
  attentionFromSession(input.session, input.nowMs) ??
336
+ attentionFromTurnVerdict(input.session) ??
298
337
  attentionFromPullRequest(input.session, input.nowMs, input.pullRequest);
299
338
  if (!candidate)
300
339
  return undefined;
@@ -0,0 +1,27 @@
1
+ export interface TabDelivery {
2
+ id: string;
3
+ sessionId: string;
4
+ text: string;
5
+ enter: boolean;
6
+ at: string;
7
+ }
8
+ export declare const TAB_DELIVERY_TTL_MS = 15000;
9
+ export declare function tabDeliveryDir(root?: string): string;
10
+ export declare function readTabDelivery(sessionId: string, root?: string, nowMs?: number): TabDelivery | undefined;
11
+ export type TabDeliveryResult = {
12
+ delivered: true;
13
+ id: string;
14
+ } | {
15
+ delivered: false;
16
+ id: string;
17
+ reason: string;
18
+ touched: boolean;
19
+ };
20
+ export declare function deliverToTab(input: {
21
+ sessionId: string;
22
+ text: string;
23
+ enter?: boolean;
24
+ transcript?: string;
25
+ root?: string;
26
+ timeoutMs?: number;
27
+ }): Promise<TabDeliveryResult>;
@@ -0,0 +1,102 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getFeedDir } from '../state.js';
4
+ export const TAB_DELIVERY_TTL_MS = 15_000;
5
+ const POLL_MS = 250;
6
+ function deliveryDir(root) {
7
+ return path.join(root ?? getFeedDir(), 'deliveries');
8
+ }
9
+ function deliveryPath(sessionId, root) {
10
+ return path.join(deliveryDir(root), `${sessionId.replace(/[^A-Za-z0-9._-]/g, '-')}.json`);
11
+ }
12
+ export function tabDeliveryDir(root) {
13
+ return deliveryDir(root);
14
+ }
15
+ export function readTabDelivery(sessionId, root, nowMs = Date.now()) {
16
+ try {
17
+ const d = JSON.parse(fs.readFileSync(deliveryPath(sessionId, root), 'utf8'));
18
+ if (!d || d.sessionId !== sessionId || typeof d.text !== 'string')
19
+ return undefined;
20
+ return nowMs - Date.parse(d.at) <= TAB_DELIVERY_TTL_MS ? d : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function removeTabDelivery(d, root) {
27
+ const current = readTabDelivery(d.sessionId, root, Number.NEGATIVE_INFINITY);
28
+ if (current && current.id !== d.id)
29
+ return;
30
+ try {
31
+ fs.unlinkSync(deliveryPath(d.sessionId, root));
32
+ }
33
+ catch { }
34
+ }
35
+ function sizeOf(file) {
36
+ if (!file)
37
+ return 0;
38
+ try {
39
+ return fs.statSync(file).size;
40
+ }
41
+ catch {
42
+ return 0;
43
+ }
44
+ }
45
+ function appendedSince(file, from) {
46
+ const fd = fs.openSync(file, 'r');
47
+ try {
48
+ const size = fs.fstatSync(fd).size;
49
+ if (size <= from)
50
+ return '';
51
+ const buf = Buffer.alloc(size - from);
52
+ fs.readSync(fd, buf, 0, buf.length, from);
53
+ return buf.toString('utf8');
54
+ }
55
+ finally {
56
+ fs.closeSync(fd);
57
+ }
58
+ }
59
+ function received(appended, text) {
60
+ if (!appended)
61
+ return false;
62
+ const probe = Array.from(text.trim()).slice(0, 60).join('');
63
+ if (probe.length <= 1)
64
+ return appended.includes('"tool_result"');
65
+ return appended.includes(JSON.stringify(probe).slice(1, -1));
66
+ }
67
+ export async function deliverToTab(input) {
68
+ if (!input.transcript) {
69
+ return { delivered: false, id: '', touched: false, reason: 'This session has no transcript to confirm a delivery, so nothing was sent.' };
70
+ }
71
+ const at = new Date();
72
+ const delivery = {
73
+ id: `tab-${input.sessionId.slice(0, 8)}-${at.getTime()}`,
74
+ sessionId: input.sessionId,
75
+ text: input.text,
76
+ enter: input.enter !== false,
77
+ at: at.toISOString(),
78
+ };
79
+ const from = sizeOf(input.transcript);
80
+ fs.mkdirSync(deliveryDir(input.root), { recursive: true, mode: 0o700 });
81
+ const file = deliveryPath(input.sessionId, input.root);
82
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify(delivery), { mode: 0o600 });
83
+ fs.renameSync(`${file}.tmp`, file);
84
+ const deadline = at.getTime() + Math.min(input.timeoutMs ?? TAB_DELIVERY_TTL_MS, TAB_DELIVERY_TTL_MS);
85
+ try {
86
+ while (Date.now() < deadline) {
87
+ if (input.transcript && received(appendedSince(input.transcript, from), input.text)) {
88
+ return { delivered: true, id: delivery.id };
89
+ }
90
+ await new Promise((r) => setTimeout(r, POLL_MS));
91
+ }
92
+ return {
93
+ delivered: false,
94
+ id: delivery.id,
95
+ touched: sizeOf(input.transcript) > from,
96
+ reason: `No editor window holding this session's tab typed it within ${Math.round(TAB_DELIVERY_TTL_MS / 1000)} seconds.`,
97
+ };
98
+ }
99
+ finally {
100
+ removeTabDelivery(delivery, input.root);
101
+ }
102
+ }
@@ -15,6 +15,9 @@ export declare class FeedSessionProjection {
15
15
  private readonly setupByScope;
16
16
  constructor(state?: FeedWatchState);
17
17
  apply(event: FeedWatchEnvelope): FeedWatchEnvelope[];
18
+ redraft(): FeedWatchEnvelope[];
19
+ private currentAttention;
20
+ private upsertChanged;
18
21
  }
19
22
  export declare function projectSessionEnvelope(event: SessionWatchEnvelope, state: FeedWatchState, gh?: GhExec, tools?: ToolRow[], setup?: ToolSetupRow[]): Promise<FeedWatchEnvelope[]>;
20
23
  interface WatchLocalFeedOptions {
@@ -14,6 +14,8 @@ import { watchLocalSessions, withCanonicalProject } from '../session/watch.js';
14
14
  import { readBlock, readResolution, blockIdForSession } from './feed.js';
15
15
  import { reconcileAttention } from './attention.js';
16
16
  import { cachedTicketPriority } from './ticket-priority.js';
17
+ import { readTabDelivery, tabDeliveryDir } from './tab-delivery.js';
18
+ import { leadDraftsDir, readLeadDraft } from '../lead/drafts.js';
17
19
  import { ActivityStream } from './activity-stream.js';
18
20
  import { watchToolActivity } from './tool-activity.js';
19
21
  import { FeedWatchState } from './envelope.js';
@@ -81,13 +83,7 @@ export class FeedSessionProjection {
81
83
  return [this.state.emit(payload)];
82
84
  }
83
85
  const projected = sessionEvent ? this.sessions.apply(sessionEvent) : [];
84
- const next = new Map();
85
- for (const [observer, items] of this.observations)
86
- for (const [rowKey, item] of items) {
87
- const row = this.sessions.rowForObservation(observer, rowKey);
88
- if (row && !row.previous && row.sourceDevice === observer)
89
- next.set(item.key, { scope: observer, item });
90
- }
86
+ const next = this.currentAttention();
91
87
  const result = [];
92
88
  const resetScopes = new Set();
93
89
  for (const rowEvent of projected) {
@@ -109,13 +105,51 @@ export class FeedSessionProjection {
109
105
  if (!next.has(key) && !resetScopes.has(previous.scope))
110
106
  result.push(this.state.emit({ type: 'attention.remove', scope: previous.scope, rowKey: key }));
111
107
  }
108
+ this.upsertChanged(next, resetScopes, result);
109
+ return result;
110
+ }
111
+ redraft() {
112
+ const result = [];
113
+ this.upsertChanged(this.currentAttention(), new Set(), result);
114
+ return result;
115
+ }
116
+ currentAttention() {
117
+ const next = new Map();
118
+ for (const [observer, items] of this.observations)
119
+ for (const [rowKey, item] of items) {
120
+ const row = this.sessions.rowForObservation(observer, rowKey);
121
+ if (row && !row.previous && row.sourceDevice === observer)
122
+ next.set(item.key, { scope: observer, item: withLeadDraft(item) });
123
+ }
124
+ return next;
125
+ }
126
+ upsertChanged(next, resetScopes, result) {
112
127
  for (const [key, value] of next) {
113
128
  if (!resetScopes.has(value.scope) && JSON.stringify(this.projectedAttention.get(key)) !== JSON.stringify(value)) {
114
129
  result.push(this.state.emit({ type: 'attention.upsert', scope: value.scope, rowKey: key, attention: value.item }));
115
130
  }
116
131
  }
117
132
  this.projectedAttention = next;
118
- return result;
133
+ }
134
+ }
135
+ function withLeadDraft(item) {
136
+ const draft = item.state === 'open' ? readLeadDraft(item.key) : undefined;
137
+ if (draft)
138
+ return { ...item, draft: { label: draft.label, at: draft.at, ...(draft.text ? { text: draft.text } : {}), ...(draft.choiceId ? { choiceId: draft.choiceId } : {}) } };
139
+ if (!item.draft)
140
+ return item;
141
+ const { draft: _gone, ...rest } = item;
142
+ return rest;
143
+ }
144
+ function watchLeadDrafts(onChange) {
145
+ try {
146
+ fs.mkdirSync(leadDraftsDir(), { recursive: true, mode: 0o700 });
147
+ const watcher = fs.watch(leadDraftsDir(), () => onChange());
148
+ watcher.on('error', () => watcher.close());
149
+ return () => watcher.close();
150
+ }
151
+ catch {
152
+ return () => { };
119
153
  }
120
154
  }
121
155
  function isLive(agent) {
@@ -140,9 +174,18 @@ function attentionFor(agent, pullRequest) {
140
174
  ticketPriority: (ticketId) => cachedTicketPriority(ticketId, Date.now()),
141
175
  });
142
176
  }
177
+ function withDelivery(agent) {
178
+ const delivery = isLive(agent) && agent.sessionId ? readTabDelivery(agent.sessionId) : undefined;
179
+ if (delivery)
180
+ return { ...agent, delivery };
181
+ if (!agent.delivery)
182
+ return agent;
183
+ const { delivery: _gone, ...rest } = agent;
184
+ return rest;
185
+ }
143
186
  async function projectAgent(agent, gh) {
144
187
  const pullRequest = await pullRequestFor(agent, gh);
145
- return { agent: withPullRequestStatus(agent, pullRequest), attention: attentionFor(agent, pullRequest) };
188
+ return { agent: withDelivery(withPullRequestStatus(agent, pullRequest)), attention: attentionFor(agent, pullRequest) };
146
189
  }
147
190
  export async function projectSessionEnvelope(event, state, gh, tools = [], setup = []) {
148
191
  if (event.type === 'reset') {
@@ -171,7 +214,7 @@ export async function projectSessionEnvelope(event, state, gh, tools = [], setup
171
214
  function watchAttentionStores(onChange) {
172
215
  const feedDir = getFeedDir();
173
216
  const watchers = [];
174
- for (const dir of [feedDir, path.join(feedDir, 'resolutions')]) {
217
+ for (const dir of [feedDir, path.join(feedDir, 'resolutions'), tabDeliveryDir()]) {
175
218
  try {
176
219
  fs.mkdirSync(dir, { recursive: true });
177
220
  const watcher = fs.watch(dir, () => onChange());
@@ -205,9 +248,11 @@ export async function watchLocalFeed(options) {
205
248
  const reconcileRows = async () => {
206
249
  for (const [rowKey, raw] of agents) {
207
250
  const { agent, attention: item } = await projectAgent(raw, options.gh);
208
- const nextPr = agent.pr ? JSON.stringify(agent.pr) : '';
209
- if (agent.pr && prStatus.get(rowKey) !== nextPr) {
210
- prStatus.set(rowKey, nextPr);
251
+ const nextProjected = agent.pr || agent.delivery || prStatus.has(rowKey)
252
+ ? JSON.stringify({ pr: agent.pr, delivery: agent.delivery })
253
+ : '';
254
+ if (nextProjected && prStatus.get(rowKey) !== nextProjected) {
255
+ prStatus.set(rowKey, nextProjected);
211
256
  options.emit(state.emit({ type: 'agent.upsert', scope: options.scope, rowKey, agent }));
212
257
  }
213
258
  const next = item ? JSON.stringify(item) : '';
@@ -377,6 +422,11 @@ export async function watchFleetFeed(options) {
377
422
  }, () => ({ type: event.type, scope: 'scope' in event ? event.scope : undefined }));
378
423
  };
379
424
  const local = subscribeSharedLocalFeed({ signal: options.signal, emit: forward });
425
+ const stopDrafts = watchLeadDrafts(() => {
426
+ for (const projected of projection.redraft())
427
+ options.emit(projected);
428
+ });
429
+ options.signal.addEventListener('abort', stopDrafts, { once: true });
380
430
  let devices;
381
431
  try {
382
432
  devices = await loadDevices();
@@ -56,7 +56,6 @@ export const REMOTE_PASSTHROUGH = {
56
56
  worktree: {},
57
57
  events: {},
58
58
  feedback: {},
59
- watchdog: {},
60
59
  factory: {},
61
60
  };
62
61
  export const OWN_HOST_COMMANDS = new Set([
@@ -6,7 +6,6 @@ export declare function foldBrowserSessionsIntoProfiles(browserDir?: string): vo
6
6
  export declare function repairSelfReferentialBinShims(versionsRoot?: string, shimsDir?: string, historyDir?: string): void;
7
7
  export declare function migrateMachineLocalBrowserProfileOutOfCentral(userDir?: string, machine?: string): void;
8
8
  export declare function migrateExtrasExtrasToAgentsExtras(historyDir?: string): void;
9
- export declare function migrateWatchdogSentinelToConfig(sentinelPath?: string, enable?: (value: boolean) => void): void;
10
9
  export declare function migrateMenubarSentinelToConfig(sentinelPath?: string, disable?: () => void): void;
11
10
  export declare function migrateCliDirToClis(agentsDirs: string[]): void;
12
11
  export declare const LEGACY_HUMANS_FILE = "humans.yaml";
@@ -1439,22 +1439,6 @@ export function migrateExtrasExtrasToAgentsExtras(historyDir = HISTORY_DIR) {
1439
1439
  console.error(`Renamed extras-extras → agents-extras (dirs: ${renamedDirs}, known_marketplaces: ${rewroteKnown}, settings: ${rewroteSettings})`);
1440
1440
  }
1441
1441
  }
1442
- export function migrateWatchdogSentinelToConfig(sentinelPath = path.join(CACHE_DIR, 'state', 'watchdog', 'enabled'), enable = (value) => setConfigValue('watchdog.enabled', value)) {
1443
- if (!fs.existsSync(sentinelPath))
1444
- return;
1445
- try {
1446
- enable(true);
1447
- }
1448
- catch (err) {
1449
- console.error(`watchdog sentinel migration: could not set watchdog.enabled (${err.message}); leaving the sentinel for a later retry`);
1450
- return;
1451
- }
1452
- try {
1453
- fs.rmSync(sentinelPath);
1454
- }
1455
- catch { }
1456
- console.error('Migrated watchdog: legacy enable sentinel → watchdog.enabled config (kept enabled)');
1457
- }
1458
1442
  export function migrateMenubarSentinelToConfig(sentinelPath = path.join(CACHE_DIR, 'state', 'menubar.disabled'), disable = () => setConfigValue('menubar.enabled', false)) {
1459
1443
  if (!fs.existsSync(sentinelPath))
1460
1444
  return;
@@ -1766,7 +1750,6 @@ export async function runMigration() {
1766
1750
  dropDeadSystemArtifacts();
1767
1751
  warnSystemOrphans();
1768
1752
  migrateExtrasExtrasToAgentsExtras();
1769
- migrateWatchdogSentinelToConfig();
1770
1753
  migrateMenubarSentinelToConfig();
1771
1754
  removeHomeCompiledProjectRules();
1772
1755
  repairAgentConfigSymlinks();
@@ -0,0 +1,11 @@
1
+ export interface LeadDraft {
2
+ key: string;
3
+ text?: string;
4
+ choiceId?: string;
5
+ label: string;
6
+ project: string;
7
+ at: string;
8
+ }
9
+ export declare function leadDraftsDir(): string;
10
+ export declare function writeLeadDraft(draft: LeadDraft): void;
11
+ export declare function readLeadDraft(key: string): LeadDraft | undefined;
@@ -0,0 +1,34 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { atomicWriteJsonSync } from '../fs-atomic.js';
5
+ import { leadRoot } from './paths.js';
6
+ const DRAFT_TTL_MS = 24 * 60 * 60_000;
7
+ export function leadDraftsDir() {
8
+ return path.join(leadRoot(), 'drafts');
9
+ }
10
+ function draftPath(key) {
11
+ return path.join(leadDraftsDir(), `${createHash('sha256').update(key).digest('hex').slice(0, 20)}.json`);
12
+ }
13
+ export function writeLeadDraft(draft) {
14
+ fs.mkdirSync(leadDraftsDir(), { recursive: true, mode: 0o700 });
15
+ atomicWriteJsonSync(draftPath(draft.key), draft);
16
+ const cutoff = Date.now() - DRAFT_TTL_MS;
17
+ for (const name of fs.readdirSync(leadDraftsDir())) {
18
+ const file = path.join(leadDraftsDir(), name);
19
+ try {
20
+ if (fs.statSync(file).mtimeMs < cutoff)
21
+ fs.unlinkSync(file);
22
+ }
23
+ catch { }
24
+ }
25
+ }
26
+ export function readLeadDraft(key) {
27
+ try {
28
+ const d = JSON.parse(fs.readFileSync(draftPath(key), 'utf8'));
29
+ return d && d.key === key && typeof d.label === 'string' ? d : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
@@ -105,6 +105,9 @@ export declare class LeadHost {
105
105
  private readonly ticketPrefixes;
106
106
  private rotatedFrom;
107
107
  private resolveClosed;
108
+ private readonly draftedAsks;
109
+ private draftBatch;
110
+ private draftTimer;
108
111
  readonly closed: Promise<void>;
109
112
  constructor(opts: LeadHostOptions);
110
113
  private log;
@@ -122,6 +125,7 @@ export declare class LeadHost {
122
125
  private resolveReply;
123
126
  private holdStop;
124
127
  private hold;
128
+ private noteNewAsks;
125
129
  private openAsk;
126
130
  private attentionReply;
127
131
  private attentionItem;
@@ -137,3 +141,4 @@ export declare class LeadHost {
137
141
  private stopChild;
138
142
  shutdown(): Promise<void>;
139
143
  }
144
+ export declare function draftTurnText(asks: string[]): string;
@@ -10,6 +10,7 @@ import { listProjectDefsCached, projectNameForCwd, resolveDefinedProjectPath } f
10
10
  import { LeadTurnParser, shouldRotate, summarize, } from './events.js';
11
11
  import { extractRefs, enrichTickets } from './refs.js';
12
12
  import { mintConfirm, sweepExpiredConfirms } from './confirm.js';
13
+ import { writeLeadDraft } from './drafts.js';
13
14
  import { FeedRoster, filterProject, formatAttention, formatRosterRow, rosterDelta, } from './roster.js';
14
15
  import { LEAD_RULES_ID, agentsMdDigest, briefSummary, buildBrief, composeTurnMessage, fetchOpenTickets, fetchRecentPrs, fleetLine, linearTeamKey, projectRepo, } from './brief.js';
15
16
  import { appendHistory, clearSessionState, readMemory, readSessionState, writeMemory, writeSessionState, } from './store.js';
@@ -22,6 +23,7 @@ export const CONFIRM_SWEEP_MS = 5 * 60 * 1000;
22
23
  const CHILD_STOP_GRACE_MS = 5_000;
23
24
  const FEED_BACKOFF_MIN_MS = 2_000;
24
25
  const FEED_BACKOFF_MAX_MS = 60_000;
26
+ const DRAFT_BATCH_MS = 20_000;
25
27
  const STDERR_TAIL_CHARS = 4_000;
26
28
  const RESUME_MISSING_RE = /No session matching|No conversation found/i;
27
29
  export const MEMORY_PROMPT = 'Your context is about to be rotated. Write the memory your successor Lead needs, as a short Markdown list (at most 25 lines): ' +
@@ -131,6 +133,9 @@ export class LeadHost {
131
133
  ticketPrefixes = new Set();
132
134
  rotatedFrom;
133
135
  resolveClosed;
136
+ draftedAsks = new Set();
137
+ draftBatch = [];
138
+ draftTimer = null;
134
139
  closed = new Promise((resolve) => { this.resolveClosed = resolve; });
135
140
  constructor(opts) {
136
141
  this.opts = opts;
@@ -217,6 +222,7 @@ export class LeadHost {
217
222
  }
218
223
  this.feedBackoffMs = FEED_BACKOFF_MIN_MS;
219
224
  this.roster.apply(envelope);
225
+ this.noteNewAsks();
220
226
  });
221
227
  feed.stderr.on('data', (d) => this.log(`feed stderr: ${d.toString().trim().slice(0, 300)}`));
222
228
  feed.on('exit', (code, signal) => {
@@ -314,7 +320,7 @@ export class LeadHost {
314
320
  const row = this.findRow(session, Object.values(this.projectRoster()));
315
321
  if (!row)
316
322
  throw new Error(`No live session '${session}' in ${this.opts.project}; check the roster tool.`);
317
- return { type: 'session', id: row.id, title: row.title };
323
+ return { type: 'session', id: row.id, title: row.title, host: row.host };
318
324
  }
319
325
  holdStop(session) {
320
326
  const row = this.findRow(session, this.liveRows());
@@ -333,6 +339,13 @@ export class LeadHost {
333
339
  throw new Error(`The ask ${held.argv[2]} is no longer open; check the attention tool.`);
334
340
  }
335
341
  const record = mintConfirm(held);
342
+ if (held.action === 'answer') {
343
+ const [, , key, flag, value] = held.argv;
344
+ writeLeadDraft({
345
+ key, label: held.detail ?? value, project: this.opts.project, at: new Date().toISOString(),
346
+ ...(flag === '--choice' ? { choiceId: value } : { text: value }),
347
+ });
348
+ }
336
349
  this.active?.emit({
337
350
  type: 'confirm',
338
351
  token: record.token,
@@ -344,6 +357,33 @@ export class LeadHost {
344
357
  this.log(`held ${record.action} (${record.label}) as ${record.token}`);
345
358
  return { type: 'held', token: record.token, label: record.label };
346
359
  }
360
+ noteNewAsks() {
361
+ if (!this.roster.ready || this.stopping)
362
+ return;
363
+ const mine = this.projectRoster();
364
+ for (const ask of this.roster.openAttention()) {
365
+ if (this.draftedAsks.has(ask.key) || !mine[ask.sessionId])
366
+ continue;
367
+ this.draftedAsks.add(ask.key);
368
+ this.draftBatch.push(ask);
369
+ }
370
+ if (this.draftBatch.length === 0 || this.draftTimer)
371
+ return;
372
+ this.draftTimer = setTimeout(() => {
373
+ this.draftTimer = null;
374
+ const open = this.draftBatch.filter((a) => this.openAsk(a.key));
375
+ this.draftBatch = [];
376
+ if (open.length === 0)
377
+ return;
378
+ const rows = this.roster.snapshot();
379
+ void this.enqueue(draftTurnText(open.map((a) => formatAttention(a, rows[a.sessionId]))), undefined, (e) => {
380
+ if (e.type === 'error')
381
+ this.log(`draft turn failed: ${e.message}`);
382
+ });
383
+ }, DRAFT_BATCH_MS);
384
+ this.draftTimer.unref?.();
385
+ this.timers.push(this.draftTimer);
386
+ }
347
387
  openAsk(key) {
348
388
  return this.roster.openAttention().find((a) => a.key === key);
349
389
  }
@@ -701,3 +741,14 @@ export class LeadHost {
701
741
  this.resolveClosed();
702
742
  }
703
743
  }
744
+ export function draftTurnText(asks) {
745
+ return [
746
+ '[New asks] These agents in this project stopped and are waiting on the owner. For each one, draft the reply the owner would most likely send, from the goals, the project rules, your memory and what the agent said (`agents lead tool roster --session <id>` shows its last turns when you need more).',
747
+ '- Draft with `agents lead tool answer --key <key> --text "<one line>"` (or `--choice <id>`). It is shown on that agent\'s card for the owner to send; nothing is delivered until they do.',
748
+ '- An agent that stopped before finishing ("Not done") gets the specific next step, never a bare "continue".',
749
+ '- Draft nothing when the decision is the owner\'s: spending or cancelling money, publishing or releasing, deleting, credentials, or a taste call you cannot infer. Say why in one line instead.',
750
+ '- Do not use send, start, dispatch or stop for these.',
751
+ '',
752
+ ...asks,
753
+ ].join('\n');
754
+ }
@@ -63,7 +63,7 @@ export function listLeadProjects() {
63
63
  throw err;
64
64
  }
65
65
  return names
66
- .filter((name) => name !== 'confirms' && isSafeProjectName(name))
66
+ .filter((name) => name !== 'confirms' && name !== 'drafts' && isSafeProjectName(name))
67
67
  .filter((name) => fs.statSync(path.join(leadRoot(), name)).isDirectory())
68
68
  .sort();
69
69
  }
@@ -9,6 +9,7 @@ export interface LeadToolContext {
9
9
  }
10
10
  export declare function leadToolContext(env?: NodeJS.ProcessEnv): LeadToolContext;
11
11
  export declare function toolRoster(ctx: LeadToolContext, project?: string): Promise<string>;
12
+ export declare function toolRosterSession(ctx: LeadToolContext, session: string): Promise<string>;
12
13
  export declare function toolAttention(ctx: LeadToolContext): Promise<string>;
13
14
  interface LinearIssue {
14
15
  identifier: string;
@@ -6,6 +6,9 @@ import { ago } from './roster.js';
6
6
  import { LeadToolError, answerArgv, appendNote, assertAgent, assertPrNumber, assertRepo, assertSessionId, assertTask, assertTicketId, dispatchPrompt, linearCreateArgv, linearPickupArgv, linearTasksArgv, linearViewArgv, prArgv, prFailureArgv, prReadArgv, prsListArgv, runArgv, sendArgv, } from './shapes.js';
7
7
  import { ensureLeadDir } from './paths.js';
8
8
  import { readMemory } from './store.js';
9
+ import { execFile } from 'node:child_process';
10
+ import { invocation, resolveSessionsBin } from '../sessions-client.js';
11
+ import { machineId, normalizeHost } from '../machine-id.js';
9
12
  export * from './shapes.js';
10
13
  export function leadToolContext(env = process.env) {
11
14
  const project = env.AGENTS_LEAD_PROJECT;
@@ -36,6 +39,25 @@ export async function toolRoster(ctx, project) {
36
39
  const reply = await hostRequest(ctx.project, { op: 'roster', project: project ?? ctx.project });
37
40
  return String(reply.text);
38
41
  }
42
+ const SESSION_TURNS_CHARS = 12_000;
43
+ export async function toolRosterSession(ctx, session) {
44
+ assertSessionId(session);
45
+ const reply = await hostRequest(ctx.project, { op: 'resolve', session });
46
+ const id = String(reply.id);
47
+ const host = String(reply.host ?? '');
48
+ const remote = host && normalizeHost(host) !== machineId() ? ['-H', host] : [];
49
+ const { command, prefix } = invocation(resolveSessionsBin());
50
+ const text = await new Promise((resolve, reject) => {
51
+ execFile(command, [...prefix, id, '--include', 'user,assistant', '--last', '2', '--markdown', ...remote], { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
52
+ if (err)
53
+ reject(new LeadToolError(`sessions ${id.slice(0, 8)} failed: ${(stderr || err.message).trim().slice(0, 300)}`));
54
+ else
55
+ resolve(stdout);
56
+ });
57
+ });
58
+ const body = text.length > SESSION_TURNS_CHARS ? `…${text.slice(-SESSION_TURNS_CHARS)}` : text;
59
+ return `Last two turns of “${String(reply.title)}” (${id.slice(0, 8)}):\n${body}`;
60
+ }
39
61
  export async function toolAttention(ctx) {
40
62
  const reply = await hostRequest(ctx.project, { op: 'attention' });
41
63
  return String(reply.text);
@@ -2,7 +2,6 @@ import { type MenubarUpdateResult } from './install-menubar.js';
2
2
  import { type GithubViewer } from '../github/viewer.js';
3
3
  import { type PhoenixSession } from '../identity/client.js';
4
4
  import type { DeviceStats } from '../devices/health.js';
5
- import type { WatchdogTickResult } from '../watchdog/runner.js';
6
5
  interface MenubarDevice {
7
6
  name: string;
8
7
  platform: string;
@@ -47,14 +46,9 @@ interface MenubarSnapshot {
47
46
  me: MenubarMe | null;
48
47
  menuPreferences: Record<string, unknown>;
49
48
  menuListPreferences: Record<string, string[]>;
50
- watchdog: {
51
- enabled: boolean;
52
- lastTick: Pick<WatchdogTickResult, 'didNudge' | 'counts'> | null;
53
- };
54
49
  }
55
50
  export declare function buildMenuPreferences(): Record<string, unknown>;
56
51
  export declare function buildMenuListPreferences(): Record<string, string[]>;
57
52
  export declare function projectDeviceStats(row: DeviceStats | undefined): MenubarDeviceStats | null;
58
- export declare function readLastWatchdogTick(stateDir?: string): WatchdogTickResult | null;
59
53
  export declare function computeMenubarSnapshot(): Promise<MenubarSnapshot>;
60
54
  export {};