@phnx-labs/agents-cli 1.23.21 → 1.23.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/README.md +17 -0
  3. package/dist/bootstrap.js +5 -4
  4. package/dist/cli/command-registry.js +2 -0
  5. package/dist/commands/config.js +16 -0
  6. package/dist/commands/daemon.js +3 -3
  7. package/dist/commands/doctor.js +10 -19
  8. package/dist/commands/events.js +1 -14
  9. package/dist/commands/feed-watch.js +5 -2
  10. package/dist/commands/go.js +2 -2
  11. package/dist/commands/lead.d.ts +3 -0
  12. package/dist/commands/lead.js +280 -0
  13. package/dist/commands/projects.js +3 -2
  14. package/dist/commands/ps-roster.d.ts +2 -12
  15. package/dist/commands/ps-roster.js +5 -87
  16. package/dist/commands/ps.js +3 -1
  17. package/dist/commands/repo.js +12 -12
  18. package/dist/commands/resource-view.js +5 -5
  19. package/dist/commands/sessions-browser.js +2 -2
  20. package/dist/commands/sessions-watch.js +5 -2
  21. package/dist/commands/setup-secrets.d.ts +3 -4
  22. package/dist/commands/setup-secrets.js +15 -46
  23. package/dist/commands/setup-session-backup.js +1 -1
  24. package/dist/commands/ssh.d.ts +0 -4
  25. package/dist/commands/ssh.js +14 -81
  26. package/dist/commands/teams-picker.js +1 -12
  27. package/dist/commands/teams.js +1 -13
  28. package/dist/commands/view.d.ts +1 -40
  29. package/dist/commands/view.js +9 -330
  30. package/dist/commands/watchdog.js +4 -4
  31. package/dist/index.js +4 -0
  32. package/dist/lib/accounting/usage.d.ts +0 -1
  33. package/dist/lib/accounting/usage.js +1 -112
  34. package/dist/lib/accounts/add.js +1 -1
  35. package/dist/lib/accounts/migrate.js +1 -1
  36. package/dist/lib/auto-pull-worker.js +2 -16
  37. package/dist/lib/auto-pull.d.ts +1 -0
  38. package/dist/lib/auto-pull.js +27 -0
  39. package/dist/lib/browser-client.js +2 -11
  40. package/dist/lib/cloud/codex.js +3 -0
  41. package/dist/lib/commands.d.ts +0 -6
  42. package/dist/lib/commands.js +3 -116
  43. package/dist/lib/comms-render.d.ts +1 -7
  44. package/dist/lib/comms-render.js +0 -19
  45. package/dist/lib/computer-client.js +2 -11
  46. package/dist/lib/config-keys.d.ts +7 -3
  47. package/dist/lib/config-keys.js +15 -2
  48. package/dist/lib/crabbox/runtimes.d.ts +0 -14
  49. package/dist/lib/crabbox/runtimes.js +0 -80
  50. package/dist/lib/daemon/attention-notify-service.d.ts +51 -28
  51. package/dist/lib/daemon/attention-notify-service.js +219 -53
  52. package/dist/lib/daemon/daemon.js +1 -2
  53. package/dist/lib/daemon/feed-stream-service.js +2 -4
  54. package/dist/lib/device-config.d.ts +0 -5
  55. package/dist/lib/device-config.js +20 -27
  56. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  57. package/dist/lib/devices/doctor-findings.js +12 -1
  58. package/dist/lib/devices/fleet.d.ts +6 -0
  59. package/dist/lib/devices/fleet.js +15 -0
  60. package/dist/lib/devices/harness-inventory.d.ts +9 -0
  61. package/dist/lib/devices/harness-inventory.js +66 -0
  62. package/dist/lib/exec.js +1 -3
  63. package/dist/lib/feed/attention.d.ts +16 -1
  64. package/dist/lib/feed/attention.js +63 -1
  65. package/dist/lib/feed/feed.d.ts +1 -1
  66. package/dist/lib/feed/feed.js +12 -2
  67. package/dist/lib/feed/hub.d.ts +9 -0
  68. package/dist/lib/feed/hub.js +27 -1
  69. package/dist/lib/feed/notify-schedule.d.ts +16 -0
  70. package/dist/lib/feed/notify-schedule.js +62 -0
  71. package/dist/lib/feed/ticket-priority.d.ts +4 -0
  72. package/dist/lib/feed/ticket-priority.js +30 -0
  73. package/dist/lib/feed/watch.d.ts +1 -0
  74. package/dist/lib/feed/watch.js +27 -3
  75. package/dist/lib/feed-ranking.d.ts +1 -0
  76. package/dist/lib/feed-ranking.js +3 -1
  77. package/dist/lib/format.d.ts +0 -2
  78. package/dist/lib/format.js +0 -8
  79. package/dist/lib/helper-versions.js +1 -1
  80. package/dist/lib/hooks/cache.d.ts +1 -0
  81. package/dist/lib/hooks/cache.js +12 -1
  82. package/dist/lib/installations/duplicate-prune.d.ts +37 -0
  83. package/dist/lib/installations/duplicate-prune.js +85 -0
  84. package/dist/lib/installations/inventory-json.d.ts +20 -0
  85. package/dist/lib/installations/inventory-json.js +252 -0
  86. package/dist/lib/installations/shims.d.ts +0 -18
  87. package/dist/lib/installations/shims.js +1 -257
  88. package/dist/lib/lead/brief.d.ts +49 -0
  89. package/dist/lib/lead/brief.js +173 -0
  90. package/dist/lib/lead/client.d.ts +21 -0
  91. package/dist/lib/lead/client.js +167 -0
  92. package/dist/lib/lead/confirm.d.ts +22 -0
  93. package/dist/lib/lead/confirm.js +73 -0
  94. package/dist/lib/lead/events.d.ts +106 -0
  95. package/dist/lib/lead/events.js +188 -0
  96. package/dist/lib/lead/harness.d.ts +29 -0
  97. package/dist/lib/lead/harness.js +107 -0
  98. package/dist/lib/lead/host.d.ts +132 -0
  99. package/dist/lib/lead/host.js +675 -0
  100. package/dist/lib/lead/paths.d.ts +22 -0
  101. package/dist/lib/lead/paths.js +69 -0
  102. package/dist/lib/lead/refs.d.ts +17 -0
  103. package/dist/lib/lead/refs.js +75 -0
  104. package/dist/lib/lead/roster.d.ts +26 -0
  105. package/dist/lib/lead/roster.js +121 -0
  106. package/dist/lib/lead/shapes.d.ts +23 -0
  107. package/dist/lib/lead/shapes.js +95 -0
  108. package/dist/lib/lead/store.d.ts +46 -0
  109. package/dist/lib/lead/store.js +77 -0
  110. package/dist/lib/lead/tools.d.ts +18 -0
  111. package/dist/lib/lead/tools.js +106 -0
  112. package/dist/lib/lead/visibility.d.ts +16 -0
  113. package/dist/lib/lead/visibility.js +77 -0
  114. package/dist/lib/mailbox.d.ts +0 -18
  115. package/dist/lib/mailbox.js +0 -170
  116. package/dist/lib/menubar/notify-desktop.d.ts +5 -0
  117. package/dist/lib/menubar/notify-desktop.js +24 -0
  118. package/dist/lib/models.js +1 -19
  119. package/dist/lib/permissions.d.ts +0 -6
  120. package/dist/lib/permissions.js +0 -140
  121. package/dist/lib/platform/process.d.ts +1 -0
  122. package/dist/lib/platform/process.js +5 -0
  123. package/dist/lib/probe.js +13 -1
  124. package/dist/lib/project-status.js +4 -3
  125. package/dist/lib/projects.d.ts +9 -0
  126. package/dist/lib/projects.js +61 -3
  127. package/dist/lib/scheduling/routines.d.ts +1 -13
  128. package/dist/lib/scheduling/routines.js +1 -37
  129. package/dist/lib/secrets-cli.d.ts +3 -3
  130. package/dist/lib/secrets-cli.js +1 -1
  131. package/dist/lib/secrets-client.d.ts +4 -37
  132. package/dist/lib/secrets-client.js +19 -265
  133. package/dist/lib/session/active.d.ts +18 -8
  134. package/dist/lib/session/active.js +94 -18
  135. package/dist/lib/session/db.d.ts +0 -16
  136. package/dist/lib/session/db.js +1 -134
  137. package/dist/lib/session/detached.d.ts +0 -1
  138. package/dist/lib/session/detached.js +0 -18
  139. package/dist/lib/session/pending-work.d.ts +21 -0
  140. package/dist/lib/session/pending-work.js +284 -0
  141. package/dist/lib/session/remote/remote-list.d.ts +0 -3
  142. package/dist/lib/session/remote/remote-list.js +1 -23
  143. package/dist/lib/session/remote/watch.d.ts +5 -0
  144. package/dist/lib/session/remote/watch.js +19 -2
  145. package/dist/lib/session/session-cache.d.ts +1 -1
  146. package/dist/lib/session/session-cache.js +12 -5
  147. package/dist/lib/session/sync/provision.js +1 -2
  148. package/dist/lib/smart-launch.js +7 -2
  149. package/dist/lib/snapshot.js +3 -4
  150. package/dist/lib/ssh-exec.d.ts +0 -40
  151. package/dist/lib/ssh-exec.js +0 -108
  152. package/dist/lib/ssh-tunnel.d.ts +0 -6
  153. package/dist/lib/ssh-tunnel.js +0 -42
  154. package/dist/lib/standalone-tools.js +12 -1
  155. package/dist/lib/startup/command-registry.js +1 -1
  156. package/dist/lib/startup/spellcheck.d.ts +0 -1
  157. package/dist/lib/startup/spellcheck.js +1 -20
  158. package/dist/lib/state.d.ts +0 -6
  159. package/dist/lib/state.js +1 -14
  160. package/dist/lib/teams/delivery.d.ts +1 -0
  161. package/dist/lib/teams/delivery.js +13 -0
  162. package/dist/lib/types.d.ts +0 -37
  163. package/dist/lib/types.js +0 -9
  164. package/dist/lib/watchdog/log.d.ts +1 -1
  165. package/dist/lib/watchdog/log.js +6 -4
  166. package/package.json +2 -1
  167. package/dist/lib/artifact-actions.d.ts +0 -7
  168. package/dist/lib/artifact-actions.js +0 -39
  169. package/dist/lib/session/sync/managed-config.d.ts +0 -3
  170. package/dist/lib/session/sync/managed-config.js +0 -3
  171. package/dist/lib/session/sync/worker-template.d.ts +0 -1
  172. package/dist/lib/session/sync/worker-template.js +0 -807
  173. package/dist/lib/storage/selection.d.ts +0 -8
  174. package/dist/lib/storage/selection.js +0 -10
  175. package/dist/lib/watchdog/index.d.ts +0 -3
  176. package/dist/lib/watchdog/index.js +0 -3
@@ -0,0 +1,69 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { getUserAgentsDir } from '../state.js';
4
+ import { ipcEndpoint } from '../platform/ipc.js';
5
+ import { isSafeProjectName } from '../projects.js';
6
+ const MAX_SOCKET_PATH = 100;
7
+ export function leadRoot() {
8
+ return path.join(getUserAgentsDir(), 'lead');
9
+ }
10
+ export function ensureLeadRoot() {
11
+ const root = leadRoot();
12
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
13
+ const ignore = path.join(root, '.gitignore');
14
+ if (!fs.existsSync(ignore))
15
+ fs.writeFileSync(ignore, '*\n');
16
+ return root;
17
+ }
18
+ export function assertLeadProject(project) {
19
+ if (!isSafeProjectName(project)) {
20
+ throw new Error(`Invalid project name '${project}'. Use the name from 'agents projects list'.`);
21
+ }
22
+ }
23
+ export function leadPaths(project) {
24
+ assertLeadProject(project);
25
+ const dir = path.join(leadRoot(), project);
26
+ const socket = path.join(dir, 'host.sock');
27
+ if (process.platform !== 'win32' && socket.length > MAX_SOCKET_PATH) {
28
+ throw new Error(`Lead socket path is ${socket.length} characters, over the ${MAX_SOCKET_PATH}-character unix socket limit: ${socket}`);
29
+ }
30
+ return {
31
+ dir,
32
+ session: path.join(dir, 'session.json'),
33
+ memory: path.join(dir, 'memory.md'),
34
+ history: path.join(dir, 'history.ndjson'),
35
+ host: path.join(dir, 'host.json'),
36
+ log: path.join(dir, 'host.log'),
37
+ out: path.join(dir, 'host.out'),
38
+ lock: path.join(dir, 'host.lock'),
39
+ settings: path.join(dir, 'lead-settings.json'),
40
+ bin: path.join(dir, 'bin'),
41
+ runs: path.join(dir, 'runs'),
42
+ socket,
43
+ endpoint: ipcEndpoint(socket),
44
+ };
45
+ }
46
+ export function ensureLeadDir(project) {
47
+ ensureLeadRoot();
48
+ const paths = leadPaths(project);
49
+ fs.mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
50
+ return paths;
51
+ }
52
+ export function confirmsDir() {
53
+ return path.join(leadRoot(), 'confirms');
54
+ }
55
+ export function listLeadProjects() {
56
+ let names;
57
+ try {
58
+ names = fs.readdirSync(leadRoot());
59
+ }
60
+ catch (err) {
61
+ if (err.code === 'ENOENT')
62
+ return [];
63
+ throw err;
64
+ }
65
+ return names
66
+ .filter((name) => name !== 'confirms' && isSafeProjectName(name))
67
+ .filter((name) => fs.statSync(path.join(leadRoot(), name)).isDirectory())
68
+ .sort();
69
+ }
@@ -0,0 +1,17 @@
1
+ import type { LeadRef } from './events.js';
2
+ import type { RosterRow } from './roster.js';
3
+ export interface RefContext {
4
+ ticketPrefixes: ReadonlySet<string>;
5
+ repo?: string;
6
+ knownPrs: ReadonlySet<number>;
7
+ sessions: RosterRow[];
8
+ }
9
+ export declare function extractRefs(text: string, ctx: RefContext): LeadRef[];
10
+ export interface TicketLookup {
11
+ cached(id: string): {
12
+ url?: string;
13
+ title?: string;
14
+ } | undefined;
15
+ urlFor(id: string): string | undefined;
16
+ }
17
+ export declare function enrichTickets(refs: LeadRef[], lookup: TicketLookup): LeadRef[];
@@ -0,0 +1,75 @@
1
+ import { linearIssueKeys } from '@phnx-labs/sessions-cli/reader';
2
+ const PR_URL_RE = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g;
3
+ const PR_NUM_RE = /(^|[^\w/&#])#(\d{1,6})\b/g;
4
+ const UUID_RE = /\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/g;
5
+ const SHORT_ID_RE = /\b[0-9a-f]{8}\b/g;
6
+ const MIN_TITLE_WORDS = 3;
7
+ function escapeRe(s) {
8
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
+ }
10
+ export function extractRefs(text, ctx) {
11
+ const refs = [];
12
+ const seen = new Set();
13
+ const add = (key, ref) => {
14
+ if (seen.has(key))
15
+ return;
16
+ seen.add(key);
17
+ refs.push(ref);
18
+ };
19
+ for (const id of linearIssueKeys(text)) {
20
+ if (ctx.ticketPrefixes.has(id.split('-')[0]))
21
+ add(`ticket:${id}`, { kind: 'ticket', id });
22
+ }
23
+ for (const m of text.matchAll(PR_URL_RE)) {
24
+ const number = Number(m[2]);
25
+ add(`pr:${m[1]}#${number}`, { kind: 'pr', repo: m[1], number, url: `https://github.com/${m[1]}/pull/${number}` });
26
+ }
27
+ if (ctx.repo) {
28
+ for (const m of text.matchAll(PR_NUM_RE)) {
29
+ const number = Number(m[2]);
30
+ if (!ctx.knownPrs.has(number))
31
+ continue;
32
+ add(`pr:${ctx.repo}#${number}`, { kind: 'pr', repo: ctx.repo, number, url: `https://github.com/${ctx.repo}/pull/${number}` });
33
+ }
34
+ }
35
+ const byId = new Map(ctx.sessions.map((s) => [s.id, s]));
36
+ const byShort = new Map();
37
+ for (const s of ctx.sessions) {
38
+ const short = s.id.slice(0, 8);
39
+ byShort.set(short, [...(byShort.get(short) ?? []), s]);
40
+ }
41
+ const sessionRef = (s) => ({ kind: 'session', id: s.id, title: s.title, host: s.host });
42
+ for (const m of text.matchAll(UUID_RE)) {
43
+ const s = byId.get(m[0]);
44
+ if (s)
45
+ add(`session:${s.id}`, sessionRef(s));
46
+ }
47
+ for (const m of text.matchAll(SHORT_ID_RE)) {
48
+ const hits = byShort.get(m[0]);
49
+ if (hits && hits.length === 1)
50
+ add(`session:${hits[0].id}`, sessionRef(hits[0]));
51
+ }
52
+ const titled = ctx.sessions
53
+ .filter((s) => s.title.trim().split(/\s+/).length >= MIN_TITLE_WORDS)
54
+ .sort((a, b) => b.title.length - a.title.length);
55
+ for (const s of titled) {
56
+ const re = new RegExp(`(^|[^\\w])${escapeRe(s.title)}(?=$|[^\\w])`);
57
+ if (re.test(text))
58
+ add(`session:${s.id}`, sessionRef(s));
59
+ }
60
+ return refs;
61
+ }
62
+ export function enrichTickets(refs, lookup) {
63
+ return refs.map((ref) => {
64
+ if (ref.kind !== 'ticket')
65
+ return ref;
66
+ const hit = lookup.cached(ref.id);
67
+ const url = hit?.url ?? lookup.urlFor(ref.id);
68
+ const out = { kind: 'ticket', id: ref.id };
69
+ if (url)
70
+ out.url = url;
71
+ if (hit?.title)
72
+ out.title = hit.title;
73
+ return out;
74
+ });
75
+ }
@@ -0,0 +1,26 @@
1
+ export interface RosterRow {
2
+ id: string;
3
+ title: string;
4
+ status: string;
5
+ host: string;
6
+ project?: string;
7
+ cwd?: string;
8
+ ticket?: string;
9
+ }
10
+ export type RosterSnapshot = Record<string, RosterRow>;
11
+ type Row = Record<string, unknown>;
12
+ export declare function rosterRowFromFeed(scope: string, agent: Row): RosterRow | null;
13
+ export declare class FeedRoster {
14
+ private readonly byScope;
15
+ private readonly scopesSeen;
16
+ private readonly waiters;
17
+ apply(envelope: Row): void;
18
+ get ready(): boolean;
19
+ whenReady(timeoutMs: number): Promise<boolean>;
20
+ snapshot(): RosterSnapshot;
21
+ private scopeRows;
22
+ }
23
+ export declare function filterProject(snapshot: RosterSnapshot, project: string, projectForCwd: (cwd: string | undefined) => string | undefined, exclude?: ReadonlySet<string>): RosterSnapshot;
24
+ export declare function formatRosterRow(row: RosterRow): string;
25
+ export declare function rosterDelta(prev: RosterSnapshot | null, cur: RosterSnapshot): string[];
26
+ export {};
@@ -0,0 +1,121 @@
1
+ import { sessionHeadline } from '../session/title.js';
2
+ function str(v) {
3
+ return typeof v === 'string' && v.length > 0 ? v : undefined;
4
+ }
5
+ export function rosterRowFromFeed(scope, agent) {
6
+ const id = str(agent.sessionId);
7
+ if (!id || agent.previous === true)
8
+ return null;
9
+ return {
10
+ id,
11
+ title: str(agent.title)
12
+ ?? sessionHeadline({ label: str(agent.label), generatedTitle: str(agent.generatedTitle), topic: str(agent.topic) })
13
+ ?? id.slice(0, 8),
14
+ status: str(agent.status) ?? 'unknown',
15
+ host: str(agent.machine) ?? scope,
16
+ project: str(agent.confirmedProject),
17
+ cwd: str(agent.cwd),
18
+ ticket: str(agent.ticketId),
19
+ };
20
+ }
21
+ export class FeedRoster {
22
+ byScope = new Map();
23
+ scopesSeen = new Set();
24
+ waiters = [];
25
+ apply(envelope) {
26
+ const scope = str(envelope.scope) ?? '';
27
+ switch (envelope.type) {
28
+ case 'reset': {
29
+ const rows = new Map();
30
+ for (const agent of envelope.agents ?? []) {
31
+ const row = rosterRowFromFeed(scope, agent);
32
+ if (row)
33
+ rows.set(String(agent.rowKey ?? row.id), row);
34
+ }
35
+ this.byScope.set(scope, rows);
36
+ this.scopesSeen.add(scope);
37
+ for (const wake of this.waiters.splice(0))
38
+ wake();
39
+ return;
40
+ }
41
+ case 'agent.upsert': {
42
+ const rows = this.scopeRows(scope);
43
+ const key = String(envelope.rowKey);
44
+ const row = rosterRowFromFeed(scope, envelope.agent ?? {});
45
+ if (row)
46
+ rows.set(key, row);
47
+ else
48
+ rows.delete(key);
49
+ return;
50
+ }
51
+ case 'agent.remove':
52
+ this.scopeRows(scope).delete(String(envelope.rowKey));
53
+ return;
54
+ default:
55
+ return;
56
+ }
57
+ }
58
+ get ready() {
59
+ return this.scopesSeen.size > 0;
60
+ }
61
+ whenReady(timeoutMs) {
62
+ if (this.ready)
63
+ return Promise.resolve(true);
64
+ return new Promise((resolve) => {
65
+ const timer = setTimeout(() => resolve(this.ready), timeoutMs);
66
+ timer.unref();
67
+ this.waiters.push(() => { clearTimeout(timer); resolve(true); });
68
+ });
69
+ }
70
+ snapshot() {
71
+ const out = {};
72
+ for (const rows of this.byScope.values()) {
73
+ for (const row of rows.values())
74
+ out[row.id] = row;
75
+ }
76
+ return out;
77
+ }
78
+ scopeRows(scope) {
79
+ let rows = this.byScope.get(scope);
80
+ if (!rows) {
81
+ rows = new Map();
82
+ this.byScope.set(scope, rows);
83
+ }
84
+ return rows;
85
+ }
86
+ }
87
+ export function filterProject(snapshot, project, projectForCwd, exclude = new Set()) {
88
+ const out = {};
89
+ for (const row of Object.values(snapshot)) {
90
+ if (exclude.has(row.id))
91
+ continue;
92
+ if ((projectForCwd(row.cwd) ?? row.project) === project)
93
+ out[row.id] = row;
94
+ }
95
+ return out;
96
+ }
97
+ export function formatRosterRow(row) {
98
+ const ticket = row.ticket ? ` ${row.ticket}` : '';
99
+ return `- ${row.id.slice(0, 8)} “${row.title}” ${row.status} on ${row.host}${ticket}`;
100
+ }
101
+ export function rosterDelta(prev, cur) {
102
+ if (!prev) {
103
+ const rows = Object.values(cur);
104
+ return rows.length === 0 ? ['No live sessions for this project.'] : rows.map(formatRosterRow);
105
+ }
106
+ const lines = [];
107
+ for (const row of Object.values(cur)) {
108
+ const before = prev[row.id];
109
+ if (!before)
110
+ lines.push(`+ started ${row.id.slice(0, 8)} “${row.title}” ${row.status} on ${row.host}`);
111
+ else if (before.status !== row.status)
112
+ lines.push(`~ ${row.id.slice(0, 8)} “${row.title}” ${before.status} → ${row.status}`);
113
+ else if (before.title !== row.title)
114
+ lines.push(`~ ${row.id.slice(0, 8)} renamed “${before.title}” → “${row.title}”`);
115
+ }
116
+ for (const row of Object.values(prev)) {
117
+ if (!cur[row.id])
118
+ lines.push(`- ended ${row.id.slice(0, 8)} “${row.title}” (was ${row.status} on ${row.host})`);
119
+ }
120
+ return lines;
121
+ }
@@ -0,0 +1,23 @@
1
+ import type { ProjectDef } from '../projects.js';
2
+ export declare const MAX_TASK_CHARS = 4000;
3
+ export declare const MAX_NOTE_CHARS = 500;
4
+ export declare const MAX_MEMORY_LINES = 60;
5
+ export declare const MAX_TASKS_LIMIT = 50;
6
+ export declare const LINEAR_STATUSES: readonly ["open", "todo", "progress", "backlog", "done"];
7
+ export declare class LeadToolError extends Error {
8
+ }
9
+ export declare function assertTicketId(id: string): string;
10
+ export declare function assertAgent(agent: string): string;
11
+ export declare function assertSessionId(id: string): string;
12
+ export declare function assertTask(text: string): string;
13
+ export declare const SEND_LABEL = "[Lead] ";
14
+ export declare function assertSendText(text: string): string;
15
+ export declare function linearProjectRef(def: ProjectDef): string;
16
+ export declare function dispatchPrompt(id: string, title: string): string;
17
+ export declare function runArgv(agent: string, prompt: string, project: string): string[];
18
+ export declare function linearPickupArgv(id: string, agent: string): string[];
19
+ export declare function sendArgv(sessionId: string, text: string): string[];
20
+ export declare function linearTasksArgv(def: ProjectDef, status: string, limit: number): string[];
21
+ export declare function linearViewArgv(id: string): string[];
22
+ export declare function linearCreateArgv(def: ProjectDef, title: string, description?: string): string[];
23
+ export declare function appendNote(memory: string, note: string): string;
@@ -0,0 +1,95 @@
1
+ import { isAgentId } from '../types.js';
2
+ export const MAX_TASK_CHARS = 4_000;
3
+ export const MAX_NOTE_CHARS = 500;
4
+ export const MAX_MEMORY_LINES = 60;
5
+ export const MAX_TASKS_LIMIT = 50;
6
+ export const LINEAR_STATUSES = ['open', 'todo', 'progress', 'backlog', 'done'];
7
+ const TICKET_RE = /^[A-Z][A-Z0-9]{1,9}-\d{1,6}$/;
8
+ const SESSION_RE = /^[0-9a-f][0-9a-f-]{7,35}$/;
9
+ export class LeadToolError extends Error {
10
+ }
11
+ export function assertTicketId(id) {
12
+ if (!TICKET_RE.test(id))
13
+ throw new LeadToolError(`'${id}' is not a ticket id (expected TEAM-123).`);
14
+ return id;
15
+ }
16
+ export function assertAgent(agent) {
17
+ if (!isAgentId(agent))
18
+ throw new LeadToolError(`'${agent}' is not a known agent.`);
19
+ return agent;
20
+ }
21
+ export function assertSessionId(id) {
22
+ if (!SESSION_RE.test(id))
23
+ throw new LeadToolError(`'${id}' is not a session id (a uuid or its first 8+ characters).`);
24
+ return id;
25
+ }
26
+ export function assertTask(text) {
27
+ const task = text.trim();
28
+ if (!task)
29
+ throw new LeadToolError('The task text is empty.');
30
+ if (task.length > MAX_TASK_CHARS)
31
+ throw new LeadToolError(`The task text is over ${MAX_TASK_CHARS} characters.`);
32
+ return task;
33
+ }
34
+ export const SEND_LABEL = '[Lead] ';
35
+ const SEND_LINE_BREAK = /[\r\n\u0085\u2028\u2029]/;
36
+ const SEND_CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
37
+ const SEND_SPECIAL_FIRST = /^[/!#]/;
38
+ export function assertSendText(text) {
39
+ if (SEND_LINE_BREAK.test(text))
40
+ throw new LeadToolError('A message to a session must be one line.');
41
+ const body = assertTask(text.replace(SEND_CONTROL, ''));
42
+ if (SEND_SPECIAL_FIRST.test(body)) {
43
+ throw new LeadToolError('Refusing a message that starts with /, ! or # (a slash command, shell escape or memory note in the session).');
44
+ }
45
+ return `${SEND_LABEL}${body}`;
46
+ }
47
+ export function linearProjectRef(def) {
48
+ const ref = def.linear?.projectId ?? def.linear?.name;
49
+ if (!ref)
50
+ throw new LeadToolError(`Project '${def.name}' has no Linear project.`);
51
+ return ref;
52
+ }
53
+ export function dispatchPrompt(id, title) {
54
+ return `Work on ${id}: ${title}`;
55
+ }
56
+ export function runArgv(agent, prompt, project) {
57
+ return ['run', assertAgent(agent), assertTask(prompt), '--headless', '-P', project, '--mode', 'edit'];
58
+ }
59
+ export function linearPickupArgv(id, agent) {
60
+ return ['update', assertTicketId(id), '--pickup', '--delegate', assertAgent(agent)];
61
+ }
62
+ export function sendArgv(sessionId, text) {
63
+ return ['send', '--channel', 'session', '--to', sessionId, '--text', assertSendText(text)];
64
+ }
65
+ export function linearTasksArgv(def, status, limit) {
66
+ if (!LINEAR_STATUSES.includes(status)) {
67
+ throw new LeadToolError(`--status must be one of ${LINEAR_STATUSES.join(', ')}.`);
68
+ }
69
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_TASKS_LIMIT) {
70
+ throw new LeadToolError(`--limit must be 1-${MAX_TASKS_LIMIT}.`);
71
+ }
72
+ return ['tasks', '--project', linearProjectRef(def), '--status', status, '--limit', String(limit), '--json'];
73
+ }
74
+ export function linearViewArgv(id) {
75
+ return ['tasks', assertTicketId(id), '--json'];
76
+ }
77
+ export function linearCreateArgv(def, title, description) {
78
+ const t = title.trim();
79
+ if (!t || t.length > 200)
80
+ throw new LeadToolError('--title must be 1-200 characters.');
81
+ const args = ['create', t, '--project', linearProjectRef(def)];
82
+ if (description !== undefined)
83
+ args.push('--description', assertTask(description));
84
+ return args;
85
+ }
86
+ export function appendNote(memory, note) {
87
+ const clean = note.replace(/\s+/g, ' ').trim();
88
+ if (!clean)
89
+ throw new LeadToolError('The note is empty.');
90
+ if (clean.length > MAX_NOTE_CHARS)
91
+ throw new LeadToolError(`A note is at most ${MAX_NOTE_CHARS} characters.`);
92
+ const lines = memory.split('\n').filter((l) => l.trim().length > 0);
93
+ lines.push(`- ${clean}`);
94
+ return `${lines.slice(-MAX_MEMORY_LINES).join('\n')}\n`;
95
+ }
@@ -0,0 +1,46 @@
1
+ import type { LeadEngine, LeadRef, LeadTiming } from './events.js';
2
+ import type { LeadPaths } from './paths.js';
3
+ import type { RosterSnapshot } from './roster.js';
4
+ export interface LeadSessionState {
5
+ sessionId: string;
6
+ model: string;
7
+ startedAtMs: number;
8
+ turns: number;
9
+ briefed: boolean;
10
+ brief: string[];
11
+ contextTokens?: number;
12
+ contextWindow?: number;
13
+ lastTurnAtMs?: number;
14
+ lastEngine?: LeadEngine;
15
+ rotatedFrom?: string;
16
+ roster?: RosterSnapshot;
17
+ }
18
+ export interface LeadHistoryTool {
19
+ label: string;
20
+ cmd: string;
21
+ state: 'ok' | 'fail' | 'run';
22
+ secs: number;
23
+ }
24
+ export interface LeadHistoryTurn {
25
+ turn: string;
26
+ at: string;
27
+ ask: string;
28
+ voice?: number;
29
+ text: string;
30
+ summary: string;
31
+ refs: LeadRef[];
32
+ tools?: LeadHistoryTool[];
33
+ session: string;
34
+ timing: LeadTiming;
35
+ }
36
+ export declare function readSessionState(paths: LeadPaths): LeadSessionState | null;
37
+ export declare function writeSessionState(paths: LeadPaths, state: LeadSessionState): void;
38
+ export declare function clearSessionState(paths: LeadPaths): void;
39
+ export declare function readMemory(paths: LeadPaths): string;
40
+ export declare function writeMemory(paths: LeadPaths, text: string): void;
41
+ export declare const HISTORY_MAX_BYTES: number;
42
+ export declare const LOG_MAX_BYTES: number;
43
+ export declare function rotateIfLarge(file: string, maxBytes: number): void;
44
+ export declare function appendHistory(paths: LeadPaths, turn: LeadHistoryTurn, maxBytes?: number): void;
45
+ export declare function appendLog(paths: LeadPaths, line: string, maxBytes?: number): void;
46
+ export declare function readHistory(paths: LeadPaths, limit?: number): LeadHistoryTurn[];
@@ -0,0 +1,77 @@
1
+ import * as fs from 'node:fs';
2
+ import { atomicWriteFileSync, atomicWriteJsonSync } from '../fs-atomic.js';
3
+ export function readSessionState(paths) {
4
+ try {
5
+ return JSON.parse(fs.readFileSync(paths.session, 'utf-8'));
6
+ }
7
+ catch (err) {
8
+ if (err.code === 'ENOENT')
9
+ return null;
10
+ throw err;
11
+ }
12
+ }
13
+ export function writeSessionState(paths, state) {
14
+ atomicWriteJsonSync(paths.session, state);
15
+ }
16
+ export function clearSessionState(paths) {
17
+ fs.rmSync(paths.session, { force: true });
18
+ }
19
+ export function readMemory(paths) {
20
+ try {
21
+ return fs.readFileSync(paths.memory, 'utf-8');
22
+ }
23
+ catch (err) {
24
+ if (err.code === 'ENOENT')
25
+ return '';
26
+ throw err;
27
+ }
28
+ }
29
+ export function writeMemory(paths, text) {
30
+ atomicWriteFileSync(paths.memory, text.endsWith('\n') ? text : `${text}\n`);
31
+ }
32
+ export const HISTORY_MAX_BYTES = 5 * 1024 * 1024;
33
+ export const LOG_MAX_BYTES = 2 * 1024 * 1024;
34
+ export function rotateIfLarge(file, maxBytes) {
35
+ let size;
36
+ try {
37
+ size = fs.statSync(file).size;
38
+ }
39
+ catch (err) {
40
+ if (err.code === 'ENOENT')
41
+ return;
42
+ throw err;
43
+ }
44
+ if (size >= maxBytes)
45
+ fs.renameSync(file, `${file}.1`);
46
+ }
47
+ export function appendHistory(paths, turn, maxBytes = HISTORY_MAX_BYTES) {
48
+ rotateIfLarge(paths.history, maxBytes);
49
+ fs.appendFileSync(paths.history, `${JSON.stringify(turn)}\n`);
50
+ }
51
+ export function appendLog(paths, line, maxBytes = LOG_MAX_BYTES) {
52
+ rotateIfLarge(paths.log, maxBytes);
53
+ fs.appendFileSync(paths.log, `${line}\n`);
54
+ }
55
+ export function readHistory(paths, limit) {
56
+ let raw;
57
+ try {
58
+ raw = fs.readFileSync(paths.history, 'utf-8');
59
+ }
60
+ catch (err) {
61
+ if (err.code === 'ENOENT')
62
+ return [];
63
+ throw err;
64
+ }
65
+ const turns = [];
66
+ for (const line of raw.split('\n')) {
67
+ if (!line.trim())
68
+ continue;
69
+ try {
70
+ turns.push(JSON.parse(line));
71
+ }
72
+ catch {
73
+ continue;
74
+ }
75
+ }
76
+ return limit === undefined ? turns : turns.slice(-limit);
77
+ }
@@ -0,0 +1,18 @@
1
+ import { type ProjectDef } from '../projects.js';
2
+ import { type LeadPaths } from './paths.js';
3
+ export * from './shapes.js';
4
+ export interface LeadToolContext {
5
+ project: string;
6
+ def: ProjectDef;
7
+ paths: LeadPaths;
8
+ }
9
+ export declare function leadToolContext(env?: NodeJS.ProcessEnv): LeadToolContext;
10
+ export declare function toolRoster(ctx: LeadToolContext, project?: string): Promise<string>;
11
+ export declare function toolDispatch(ctx: LeadToolContext, ticket: string, agent: string): Promise<string>;
12
+ export declare function toolStart(ctx: LeadToolContext, agent: string, task: string): Promise<string>;
13
+ export declare function toolSend(ctx: LeadToolContext, session: string, text: string): Promise<string>;
14
+ export declare function toolStop(ctx: LeadToolContext, session: string): Promise<string>;
15
+ export declare function toolLinearTasks(ctx: LeadToolContext, status: string, limit: number): Promise<string>;
16
+ export declare function toolLinearView(id: string): Promise<string>;
17
+ export declare function toolLinearCreate(ctx: LeadToolContext, title: string, description?: string): Promise<string>;
18
+ export declare function toolRemember(ctx: LeadToolContext, note: string): string;
@@ -0,0 +1,106 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { getCliLaunch } from '../cli-entry.js';
3
+ import { loadProjectDef } from '../projects.js';
4
+ import { atomicWriteFileSync } from '../fs-atomic.js';
5
+ import { connectHost, sendRequest } from './client.js';
6
+ import { LeadToolError, appendNote, assertAgent, assertSendText, assertSessionId, assertTask, assertTicketId, dispatchPrompt, linearCreateArgv, linearPickupArgv, linearTasksArgv, linearViewArgv, runArgv, sendArgv, } from './shapes.js';
7
+ import { ensureLeadDir } from './paths.js';
8
+ import { readMemory } from './store.js';
9
+ export * from './shapes.js';
10
+ const LINEAR_TIMEOUT_MS = 20_000;
11
+ export function leadToolContext(env = process.env) {
12
+ const project = env.AGENTS_LEAD_PROJECT;
13
+ if (!project)
14
+ throw new LeadToolError('agents lead tool runs only inside a Lead (AGENTS_LEAD_PROJECT is not set).');
15
+ const def = loadProjectDef(project);
16
+ if (!def)
17
+ throw new LeadToolError(`Unknown project '${project}'.`);
18
+ return { project, def, paths: ensureLeadDir(project) };
19
+ }
20
+ function runLinear(args) {
21
+ return new Promise((resolve, reject) => {
22
+ execFile('linear', args, { timeout: LINEAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
23
+ if (err)
24
+ reject(new LeadToolError(`linear ${args[0]} failed: ${String(stderr || err.message).trim().split('\n').pop()}`));
25
+ else
26
+ resolve(stdout);
27
+ });
28
+ });
29
+ }
30
+ async function hostRequest(project, req) {
31
+ const socket = await connectHost(project);
32
+ if (!socket)
33
+ throw new LeadToolError(`The Lead host for '${project}' is not running.`);
34
+ let reply = null;
35
+ await sendRequest(socket, req, (obj) => { reply = obj; });
36
+ if (!reply)
37
+ throw new LeadToolError('The Lead host closed without a reply.');
38
+ if (reply.type === 'error')
39
+ throw new LeadToolError(String(reply.message));
40
+ return reply;
41
+ }
42
+ async function spawnWorker(ctx, agent, prompt) {
43
+ const reply = await hostRequest(ctx.project, { op: 'spawn', agent, prompt });
44
+ return String(reply.log);
45
+ }
46
+ export async function toolRoster(ctx, project) {
47
+ const reply = await hostRequest(ctx.project, { op: 'roster', project: project ?? ctx.project });
48
+ return String(reply.text);
49
+ }
50
+ export async function toolDispatch(ctx, ticket, agent) {
51
+ assertTicketId(ticket);
52
+ assertAgent(agent);
53
+ const issue = JSON.parse(await runLinear(linearViewArgv(ticket)));
54
+ const prompt = dispatchPrompt(issue.identifier, issue.title);
55
+ runArgv(agent, prompt, ctx.project);
56
+ await runLinear(linearPickupArgv(issue.identifier, agent));
57
+ const log = await spawnWorker(ctx, agent, prompt);
58
+ return `Dispatched ${agent} on ${issue.identifier}: ${issue.title}. ${issue.identifier} is In Progress, delegated to ${agent}. Log: ${log}`;
59
+ }
60
+ export async function toolStart(ctx, agent, task) {
61
+ runArgv(agent, task, ctx.project);
62
+ const log = await spawnWorker(ctx, agent, task);
63
+ return `Started ${agent} on: ${assertTask(task).slice(0, 120)}. Log: ${log}`;
64
+ }
65
+ export async function toolSend(ctx, session, text) {
66
+ assertSessionId(session);
67
+ assertSendText(text);
68
+ const reply = await hostRequest(ctx.project, { op: 'resolve', session });
69
+ const id = String(reply.id);
70
+ const argv = sendArgv(id, text);
71
+ const launch = getCliLaunch(argv);
72
+ await new Promise((resolve, reject) => {
73
+ execFile(launch.command, launch.args, { timeout: 60_000 }, (err, _stdout, stderr) => {
74
+ if (err)
75
+ reject(new LeadToolError(`agents send failed: ${String(stderr || err.message).trim().split('\n').pop()}`));
76
+ else
77
+ resolve();
78
+ });
79
+ });
80
+ return `Sent to “${String(reply.title)}” (${id.slice(0, 8)}).`;
81
+ }
82
+ export async function toolStop(ctx, session) {
83
+ assertSessionId(session);
84
+ const reply = await hostRequest(ctx.project, { op: 'hold-stop', session });
85
+ return `Held for the owner's Confirm: ${String(reply.label)}. Nothing was stopped. Do not retry.`;
86
+ }
87
+ export async function toolLinearTasks(ctx, status, limit) {
88
+ const raw = JSON.parse(await runLinear(linearTasksArgv(ctx.def, status, limit)));
89
+ const issues = raw.issues ?? [];
90
+ if (issues.length === 0)
91
+ return `No ${status} tickets.`;
92
+ return issues.map((i) => `${i.identifier} ${i.title}${i.state?.name ? ` (${i.state.name})` : ''}`).join('\n');
93
+ }
94
+ export async function toolLinearView(id) {
95
+ const i = JSON.parse(await runLinear(linearViewArgv(id)));
96
+ const desc = (i.description ?? '').slice(0, 1_500);
97
+ return [`${i.identifier} ${i.title}${i.state?.name ? ` (${i.state.name})` : ''}`, desc].filter(Boolean).join('\n');
98
+ }
99
+ export async function toolLinearCreate(ctx, title, description) {
100
+ const out = await runLinear(linearCreateArgv(ctx.def, title, description));
101
+ return out.trim().split('\n').slice(-3).join('\n');
102
+ }
103
+ export function toolRemember(ctx, note) {
104
+ atomicWriteFileSync(ctx.paths.memory, appendNote(readMemory(ctx.paths), note));
105
+ return 'Noted.';
106
+ }