@phnx-labs/agents-cli 1.23.21 → 1.23.23
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.
- package/CHANGELOG.md +115 -0
- package/README.md +17 -0
- package/dist/bootstrap.js +5 -4
- package/dist/cli/command-registry.js +2 -0
- package/dist/commands/config.js +16 -0
- package/dist/commands/daemon.js +3 -3
- package/dist/commands/doctor.js +10 -19
- package/dist/commands/events.js +1 -14
- package/dist/commands/feed-watch.js +5 -2
- package/dist/commands/go.js +2 -2
- package/dist/commands/lead.d.ts +3 -0
- package/dist/commands/lead.js +280 -0
- package/dist/commands/projects.js +3 -2
- package/dist/commands/ps-roster.d.ts +2 -12
- package/dist/commands/ps-roster.js +5 -87
- package/dist/commands/ps.js +3 -1
- package/dist/commands/repo.js +12 -12
- package/dist/commands/resource-view.js +5 -5
- package/dist/commands/sessions-browser.js +2 -2
- package/dist/commands/sessions-watch.js +5 -2
- package/dist/commands/setup-secrets.d.ts +3 -4
- package/dist/commands/setup-secrets.js +15 -46
- package/dist/commands/setup-session-backup.js +1 -1
- package/dist/commands/ssh.d.ts +0 -4
- package/dist/commands/ssh.js +14 -81
- package/dist/commands/teams-picker.js +1 -12
- package/dist/commands/teams.js +1 -13
- package/dist/commands/view.d.ts +1 -40
- package/dist/commands/view.js +9 -330
- package/dist/commands/watchdog.js +4 -4
- package/dist/index.js +4 -0
- package/dist/lib/accounting/usage.d.ts +0 -1
- package/dist/lib/accounting/usage.js +1 -112
- package/dist/lib/accounts/add.js +1 -1
- package/dist/lib/accounts/migrate.js +1 -1
- package/dist/lib/auto-pull-worker.js +2 -16
- package/dist/lib/auto-pull.d.ts +1 -0
- package/dist/lib/auto-pull.js +27 -0
- package/dist/lib/browser-client.js +2 -11
- package/dist/lib/cloud/codex.js +3 -0
- package/dist/lib/commands.d.ts +0 -6
- package/dist/lib/commands.js +3 -116
- package/dist/lib/comms-render.d.ts +1 -7
- package/dist/lib/comms-render.js +0 -19
- package/dist/lib/computer-client.js +2 -11
- package/dist/lib/config-keys.d.ts +7 -3
- package/dist/lib/config-keys.js +15 -2
- package/dist/lib/crabbox/runtimes.d.ts +0 -14
- package/dist/lib/crabbox/runtimes.js +0 -80
- package/dist/lib/daemon/attention-notify-service.d.ts +53 -28
- package/dist/lib/daemon/attention-notify-service.js +232 -53
- package/dist/lib/daemon/daemon.js +1 -2
- package/dist/lib/daemon/feed-stream-service.js +2 -4
- package/dist/lib/device-config.d.ts +0 -5
- package/dist/lib/device-config.js +20 -27
- package/dist/lib/devices/doctor-findings.d.ts +2 -1
- package/dist/lib/devices/doctor-findings.js +12 -1
- package/dist/lib/devices/fleet.d.ts +6 -0
- package/dist/lib/devices/fleet.js +15 -0
- package/dist/lib/devices/harness-inventory.d.ts +9 -0
- package/dist/lib/devices/harness-inventory.js +66 -0
- package/dist/lib/exec.js +1 -3
- package/dist/lib/feed/attention.d.ts +16 -1
- package/dist/lib/feed/attention.js +63 -1
- package/dist/lib/feed/feed.d.ts +1 -1
- package/dist/lib/feed/feed.js +12 -2
- package/dist/lib/feed/hub.d.ts +9 -0
- package/dist/lib/feed/hub.js +27 -1
- package/dist/lib/feed/notify-schedule.d.ts +16 -0
- package/dist/lib/feed/notify-schedule.js +62 -0
- package/dist/lib/feed/ticket-priority.d.ts +4 -0
- package/dist/lib/feed/ticket-priority.js +30 -0
- package/dist/lib/feed/watch.d.ts +1 -0
- package/dist/lib/feed/watch.js +27 -3
- package/dist/lib/feed-ranking.d.ts +1 -0
- package/dist/lib/feed-ranking.js +3 -1
- package/dist/lib/format.d.ts +0 -2
- package/dist/lib/format.js +0 -8
- package/dist/lib/helper-versions.js +1 -1
- package/dist/lib/hooks/cache.d.ts +1 -0
- package/dist/lib/hooks/cache.js +12 -1
- package/dist/lib/installations/duplicate-prune.d.ts +37 -0
- package/dist/lib/installations/duplicate-prune.js +85 -0
- package/dist/lib/installations/inventory-json.d.ts +20 -0
- package/dist/lib/installations/inventory-json.js +252 -0
- package/dist/lib/installations/shims.d.ts +0 -18
- package/dist/lib/installations/shims.js +1 -257
- package/dist/lib/lead/brief.d.ts +49 -0
- package/dist/lib/lead/brief.js +173 -0
- package/dist/lib/lead/client.d.ts +21 -0
- package/dist/lib/lead/client.js +167 -0
- package/dist/lib/lead/confirm.d.ts +22 -0
- package/dist/lib/lead/confirm.js +73 -0
- package/dist/lib/lead/events.d.ts +106 -0
- package/dist/lib/lead/events.js +188 -0
- package/dist/lib/lead/harness.d.ts +29 -0
- package/dist/lib/lead/harness.js +107 -0
- package/dist/lib/lead/host.d.ts +132 -0
- package/dist/lib/lead/host.js +675 -0
- package/dist/lib/lead/paths.d.ts +22 -0
- package/dist/lib/lead/paths.js +69 -0
- package/dist/lib/lead/refs.d.ts +17 -0
- package/dist/lib/lead/refs.js +75 -0
- package/dist/lib/lead/roster.d.ts +26 -0
- package/dist/lib/lead/roster.js +121 -0
- package/dist/lib/lead/shapes.d.ts +23 -0
- package/dist/lib/lead/shapes.js +95 -0
- package/dist/lib/lead/store.d.ts +46 -0
- package/dist/lib/lead/store.js +77 -0
- package/dist/lib/lead/tools.d.ts +18 -0
- package/dist/lib/lead/tools.js +106 -0
- package/dist/lib/lead/visibility.d.ts +16 -0
- package/dist/lib/lead/visibility.js +77 -0
- package/dist/lib/mailbox.d.ts +0 -18
- package/dist/lib/mailbox.js +0 -170
- package/dist/lib/menubar/notify-desktop.d.ts +5 -0
- package/dist/lib/menubar/notify-desktop.js +24 -0
- package/dist/lib/models.js +1 -19
- package/dist/lib/permissions.d.ts +0 -6
- package/dist/lib/permissions.js +0 -140
- package/dist/lib/platform/process.d.ts +1 -0
- package/dist/lib/platform/process.js +5 -0
- package/dist/lib/probe.js +13 -1
- package/dist/lib/project-status.js +4 -3
- package/dist/lib/projects.d.ts +9 -0
- package/dist/lib/projects.js +61 -3
- package/dist/lib/scheduling/routines.d.ts +1 -13
- package/dist/lib/scheduling/routines.js +1 -37
- package/dist/lib/secrets-cli.d.ts +3 -3
- package/dist/lib/secrets-cli.js +1 -1
- package/dist/lib/secrets-client.d.ts +4 -37
- package/dist/lib/secrets-client.js +19 -265
- package/dist/lib/session/active.d.ts +18 -8
- package/dist/lib/session/active.js +94 -18
- package/dist/lib/session/db.d.ts +0 -16
- package/dist/lib/session/db.js +1 -134
- package/dist/lib/session/detached.d.ts +0 -1
- package/dist/lib/session/detached.js +0 -18
- package/dist/lib/session/pending-work.d.ts +21 -0
- package/dist/lib/session/pending-work.js +284 -0
- package/dist/lib/session/remote/remote-list.d.ts +0 -3
- package/dist/lib/session/remote/remote-list.js +1 -23
- package/dist/lib/session/remote/watch.d.ts +5 -0
- package/dist/lib/session/remote/watch.js +19 -2
- package/dist/lib/session/session-cache.d.ts +1 -1
- package/dist/lib/session/session-cache.js +12 -5
- package/dist/lib/session/sync/provision.js +1 -2
- package/dist/lib/smart-launch.js +7 -2
- package/dist/lib/snapshot.js +3 -4
- package/dist/lib/ssh-exec.d.ts +0 -40
- package/dist/lib/ssh-exec.js +0 -108
- package/dist/lib/ssh-tunnel.d.ts +0 -6
- package/dist/lib/ssh-tunnel.js +0 -42
- package/dist/lib/standalone-tools.js +12 -1
- package/dist/lib/startup/command-registry.js +1 -1
- package/dist/lib/startup/spellcheck.d.ts +0 -1
- package/dist/lib/startup/spellcheck.js +1 -20
- package/dist/lib/state.d.ts +0 -6
- package/dist/lib/state.js +1 -14
- package/dist/lib/teams/delivery.d.ts +1 -0
- package/dist/lib/teams/delivery.js +13 -0
- package/dist/lib/types.d.ts +0 -37
- package/dist/lib/types.js +0 -9
- package/dist/lib/watchdog/log.d.ts +1 -1
- package/dist/lib/watchdog/log.js +6 -4
- package/package.json +2 -1
- package/dist/lib/artifact-actions.d.ts +0 -7
- package/dist/lib/artifact-actions.js +0 -39
- package/dist/lib/session/sync/managed-config.d.ts +0 -3
- package/dist/lib/session/sync/managed-config.js +0 -3
- package/dist/lib/session/sync/worker-template.d.ts +0 -1
- package/dist/lib/session/sync/worker-template.js +0 -807
- package/dist/lib/storage/selection.d.ts +0 -8
- package/dist/lib/storage/selection.js +0 -10
- package/dist/lib/watchdog/index.d.ts +0 -3
- package/dist/lib/watchdog/index.js +0 -3
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as net from 'node:net';
|
|
3
|
+
import * as readline from 'node:readline';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { getCliLaunch } from '../cli-entry.js';
|
|
7
|
+
import { loadProjectDef } from '../projects.js';
|
|
8
|
+
import { ensureLeadDir, leadPaths } from './paths.js';
|
|
9
|
+
import { LeadHost, readHostRecord } from './host.js';
|
|
10
|
+
import { agentsCliLaunch, cliVersion, leadModel } from './harness.js';
|
|
11
|
+
import { claimConfirm } from './confirm.js';
|
|
12
|
+
import { summarize } from './events.js';
|
|
13
|
+
import { appendHistory, appendLog } from './store.js';
|
|
14
|
+
export const HOST_START_TIMEOUT_MS = 15_000;
|
|
15
|
+
const HOST_POLL_MS = 100;
|
|
16
|
+
export function requireProjectDef(project) {
|
|
17
|
+
const def = loadProjectDef(project);
|
|
18
|
+
if (!def)
|
|
19
|
+
throw new Error(`Unknown project '${project}'. Run 'agents projects list' for the names.`);
|
|
20
|
+
return def;
|
|
21
|
+
}
|
|
22
|
+
function connect(paths) {
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
const socket = net.connect(paths.endpoint);
|
|
25
|
+
socket.once('connect', () => resolve(socket));
|
|
26
|
+
socket.once('error', () => resolve(null));
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export async function connectHost(project) {
|
|
30
|
+
return connect(leadPaths(project));
|
|
31
|
+
}
|
|
32
|
+
async function waitForExit(pid, timeoutMs) {
|
|
33
|
+
const deadline = Date.now() + timeoutMs;
|
|
34
|
+
while (Date.now() < deadline) {
|
|
35
|
+
try {
|
|
36
|
+
process.kill(pid, 0);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
await new Promise((r) => setTimeout(r, HOST_POLL_MS));
|
|
42
|
+
}
|
|
43
|
+
throw new Error(`The old Lead host (pid ${pid}) did not exit within ${timeoutMs / 1000}s.`);
|
|
44
|
+
}
|
|
45
|
+
export function hostNeedsRestart(record, want) {
|
|
46
|
+
return record === null || record.version !== want.version || record.model !== want.model;
|
|
47
|
+
}
|
|
48
|
+
export async function ensureHost(project, want = { version: cliVersion(), model: leadModel() }) {
|
|
49
|
+
const paths = ensureLeadDir(project);
|
|
50
|
+
const existing = await connect(paths);
|
|
51
|
+
if (existing) {
|
|
52
|
+
const record = readHostRecord(paths);
|
|
53
|
+
if (!hostNeedsRestart(record, want))
|
|
54
|
+
return existing;
|
|
55
|
+
await sendRequest(existing, { op: 'stop' }, () => { });
|
|
56
|
+
if (record)
|
|
57
|
+
await waitForExit(record.pid, HOST_START_TIMEOUT_MS);
|
|
58
|
+
}
|
|
59
|
+
const launch = getCliLaunch(['__lead-host', project]);
|
|
60
|
+
const outFd = fs.openSync(paths.out, 'a');
|
|
61
|
+
const child = spawn(launch.command, launch.args, { detached: true, stdio: ['ignore', outFd, outFd] });
|
|
62
|
+
fs.closeSync(outFd);
|
|
63
|
+
let exited = null;
|
|
64
|
+
child.once('exit', (code) => { exited = code ?? -1; });
|
|
65
|
+
child.unref();
|
|
66
|
+
const deadline = Date.now() + HOST_START_TIMEOUT_MS;
|
|
67
|
+
while (Date.now() < deadline) {
|
|
68
|
+
const socket = await connect(paths);
|
|
69
|
+
if (socket)
|
|
70
|
+
return socket;
|
|
71
|
+
if (exited !== null) {
|
|
72
|
+
const raced = await connect(paths);
|
|
73
|
+
if (raced)
|
|
74
|
+
return raced;
|
|
75
|
+
throw new Error(`The Lead host for '${project}' exited with code ${exited} before listening; see ${paths.log} and ${paths.out}`);
|
|
76
|
+
}
|
|
77
|
+
await new Promise((r) => setTimeout(r, HOST_POLL_MS));
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`The Lead host for '${project}' did not start listening within ${HOST_START_TIMEOUT_MS / 1000}s; see ${paths.log}`);
|
|
80
|
+
}
|
|
81
|
+
export async function sendRequest(socket, req, onLine) {
|
|
82
|
+
socket.write(`${JSON.stringify(req)}\n`);
|
|
83
|
+
const rl = readline.createInterface({ input: socket });
|
|
84
|
+
await new Promise((resolve, reject) => {
|
|
85
|
+
rl.on('line', (line) => {
|
|
86
|
+
if (!line.trim())
|
|
87
|
+
return;
|
|
88
|
+
onLine(JSON.parse(line));
|
|
89
|
+
});
|
|
90
|
+
socket.once('error', reject);
|
|
91
|
+
rl.once('close', () => resolve());
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
export async function runLeadHost(project) {
|
|
95
|
+
const def = requireProjectDef(project);
|
|
96
|
+
const paths = ensureLeadDir(project);
|
|
97
|
+
const log = (line) => appendLog(paths, line);
|
|
98
|
+
const host = new LeadHost({
|
|
99
|
+
project,
|
|
100
|
+
def,
|
|
101
|
+
paths,
|
|
102
|
+
model: leadModel(),
|
|
103
|
+
version: cliVersion(),
|
|
104
|
+
harness: agentsCliLaunch,
|
|
105
|
+
feed: agentsCliLaunch(['feed', 'watch', '--json']),
|
|
106
|
+
log,
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
await host.start();
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
log(`host start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
const stop = () => { void host.shutdown(); };
|
|
116
|
+
process.on('SIGTERM', stop);
|
|
117
|
+
process.on('SIGINT', stop);
|
|
118
|
+
process.on('SIGHUP', () => { });
|
|
119
|
+
await host.closed;
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
export async function runConfirm(token, emit, launch = agentsCliLaunch) {
|
|
123
|
+
const record = claimConfirm(token);
|
|
124
|
+
const paths = ensureLeadDir(record.project);
|
|
125
|
+
const turn = `t_${randomBytes(6).toString('hex')}`;
|
|
126
|
+
const startedAt = Date.now();
|
|
127
|
+
const args = ['ps', 'stop', record.sessionId];
|
|
128
|
+
const cmd = `agents ${args.join(' ')}`;
|
|
129
|
+
const toolId = `confirm_${record.token}`;
|
|
130
|
+
emit({ type: 'tool', id: toolId, label: 'agents ps stop', cmd, state: 'run' });
|
|
131
|
+
const l = launch(args);
|
|
132
|
+
const { code, output } = await new Promise((resolve) => {
|
|
133
|
+
const child = spawn(l.command, l.args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
134
|
+
let output = '';
|
|
135
|
+
child.stdout.on('data', (d) => { output += d.toString(); });
|
|
136
|
+
child.stderr.on('data', (d) => { output += d.toString(); });
|
|
137
|
+
child.on('error', (err) => resolve({ code: -1, output: err.message }));
|
|
138
|
+
child.on('exit', (c) => resolve({ code: c ?? -1, output }));
|
|
139
|
+
});
|
|
140
|
+
const secs = Math.round((Date.now() - startedAt) / 10) / 100;
|
|
141
|
+
const ok = code === 0;
|
|
142
|
+
emit({ type: 'tool', id: toolId, label: 'agents ps stop', state: ok ? 'ok' : 'fail', secs });
|
|
143
|
+
const title = record.label.replace(/^Stop\s+/, '');
|
|
144
|
+
const text = ok
|
|
145
|
+
? `Stopped ${title}.`
|
|
146
|
+
: `Could not stop ${title}: ${output.trim().split('\n').pop() ?? `exit ${code}`}`;
|
|
147
|
+
if (!ok) {
|
|
148
|
+
emit({ type: 'error', message: text });
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
const refs = [{ kind: 'session', id: record.sessionId, title: title.replace(/^“|”$/g, '') }];
|
|
152
|
+
const timing = { boot: 0, model: 0, tools: secs };
|
|
153
|
+
const summary = summarize(text);
|
|
154
|
+
emit({ type: 'done', turn, text, summary, refs, timing });
|
|
155
|
+
appendHistory(paths, {
|
|
156
|
+
turn,
|
|
157
|
+
at: new Date(startedAt).toISOString(),
|
|
158
|
+
ask: `confirm ${record.token}: ${record.label}`,
|
|
159
|
+
text,
|
|
160
|
+
summary,
|
|
161
|
+
refs,
|
|
162
|
+
tools: [{ label: 'agents ps stop', cmd, state: 'ok', secs }],
|
|
163
|
+
session: record.sessionId,
|
|
164
|
+
timing,
|
|
165
|
+
});
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare const CONFIRM_TTL_MS: number;
|
|
2
|
+
export interface ConfirmRecord {
|
|
3
|
+
token: string;
|
|
4
|
+
project: string;
|
|
5
|
+
action: 'stop';
|
|
6
|
+
sessionId: string;
|
|
7
|
+
label: string;
|
|
8
|
+
createdAtMs: number;
|
|
9
|
+
expiresAtMs: number;
|
|
10
|
+
}
|
|
11
|
+
export declare class ConfirmError extends Error {
|
|
12
|
+
readonly reason: 'invalid' | 'unknown' | 'expired';
|
|
13
|
+
constructor(message: string, reason: 'invalid' | 'unknown' | 'expired');
|
|
14
|
+
}
|
|
15
|
+
export declare function mintConfirm(input: {
|
|
16
|
+
project: string;
|
|
17
|
+
action: 'stop';
|
|
18
|
+
sessionId: string;
|
|
19
|
+
label: string;
|
|
20
|
+
}, nowMs?: number): ConfirmRecord;
|
|
21
|
+
export declare function claimConfirm(token: string, nowMs?: number): ConfirmRecord;
|
|
22
|
+
export declare function sweepExpiredConfirms(nowMs?: number): number;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { atomicWriteJsonSync } from '../fs-atomic.js';
|
|
5
|
+
import { confirmsDir, ensureLeadRoot } from './paths.js';
|
|
6
|
+
export const CONFIRM_TTL_MS = 10 * 60 * 1000;
|
|
7
|
+
const TOKEN_RE = /^c_[0-9a-f]{16}$/;
|
|
8
|
+
export class ConfirmError extends Error {
|
|
9
|
+
reason;
|
|
10
|
+
constructor(message, reason) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.reason = reason;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function tokenPath(token) {
|
|
16
|
+
return path.join(confirmsDir(), `${token}.json`);
|
|
17
|
+
}
|
|
18
|
+
export function mintConfirm(input, nowMs = Date.now()) {
|
|
19
|
+
ensureLeadRoot();
|
|
20
|
+
fs.mkdirSync(confirmsDir(), { recursive: true, mode: 0o700 });
|
|
21
|
+
const record = {
|
|
22
|
+
token: `c_${randomBytes(8).toString('hex')}`,
|
|
23
|
+
...input,
|
|
24
|
+
createdAtMs: nowMs,
|
|
25
|
+
expiresAtMs: nowMs + CONFIRM_TTL_MS,
|
|
26
|
+
};
|
|
27
|
+
atomicWriteJsonSync(tokenPath(record.token), record);
|
|
28
|
+
return record;
|
|
29
|
+
}
|
|
30
|
+
export function claimConfirm(token, nowMs = Date.now()) {
|
|
31
|
+
if (!TOKEN_RE.test(token))
|
|
32
|
+
throw new ConfirmError(`'${token}' is not a confirm token (expected c_ and 16 hex characters).`, 'invalid');
|
|
33
|
+
const file = tokenPath(token);
|
|
34
|
+
const claimed = `${file}.claimed-${process.pid}`;
|
|
35
|
+
try {
|
|
36
|
+
fs.renameSync(file, claimed);
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
if (err.code === 'ENOENT') {
|
|
40
|
+
throw new ConfirmError(`Confirm token ${token} is unknown or was already used.`, 'unknown');
|
|
41
|
+
}
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
const record = JSON.parse(fs.readFileSync(claimed, 'utf-8'));
|
|
45
|
+
fs.unlinkSync(claimed);
|
|
46
|
+
if (nowMs > record.expiresAtMs) {
|
|
47
|
+
throw new ConfirmError(`Confirm token ${token} expired ${Math.round((nowMs - record.expiresAtMs) / 1000)}s ago; ask the Lead again.`, 'expired');
|
|
48
|
+
}
|
|
49
|
+
return record;
|
|
50
|
+
}
|
|
51
|
+
export function sweepExpiredConfirms(nowMs = Date.now()) {
|
|
52
|
+
let names;
|
|
53
|
+
try {
|
|
54
|
+
names = fs.readdirSync(confirmsDir());
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
if (err.code === 'ENOENT')
|
|
58
|
+
return 0;
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
let removed = 0;
|
|
62
|
+
for (const name of names) {
|
|
63
|
+
if (!name.endsWith('.json'))
|
|
64
|
+
continue;
|
|
65
|
+
const file = path.join(confirmsDir(), name);
|
|
66
|
+
const record = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
67
|
+
if (nowMs > record.expiresAtMs) {
|
|
68
|
+
fs.rmSync(file, { force: true });
|
|
69
|
+
removed++;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return removed;
|
|
73
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
export type LeadEngine = 'warm' | 'cold';
|
|
2
|
+
export type LeadStatusState = 'booting' | 'thinking' | 'tool' | 'answering';
|
|
3
|
+
export interface LeadTicketRef {
|
|
4
|
+
kind: 'ticket';
|
|
5
|
+
id: string;
|
|
6
|
+
url?: string;
|
|
7
|
+
title?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface LeadPrRef {
|
|
10
|
+
kind: 'pr';
|
|
11
|
+
repo: string;
|
|
12
|
+
number: number;
|
|
13
|
+
url: string;
|
|
14
|
+
}
|
|
15
|
+
export interface LeadSessionRef {
|
|
16
|
+
kind: 'session';
|
|
17
|
+
id: string;
|
|
18
|
+
title: string;
|
|
19
|
+
host?: string;
|
|
20
|
+
}
|
|
21
|
+
export type LeadRef = LeadTicketRef | LeadPrRef | LeadSessionRef;
|
|
22
|
+
export interface LeadTiming {
|
|
23
|
+
boot: number;
|
|
24
|
+
model: number;
|
|
25
|
+
tools: number;
|
|
26
|
+
}
|
|
27
|
+
export type LeadEvent = {
|
|
28
|
+
type: 'turn';
|
|
29
|
+
turn: string;
|
|
30
|
+
project: string;
|
|
31
|
+
session: string;
|
|
32
|
+
engine: LeadEngine;
|
|
33
|
+
} | {
|
|
34
|
+
type: 'status';
|
|
35
|
+
state: LeadStatusState;
|
|
36
|
+
} | {
|
|
37
|
+
type: 'tool';
|
|
38
|
+
id: string;
|
|
39
|
+
label: string;
|
|
40
|
+
cmd: string;
|
|
41
|
+
state: 'run';
|
|
42
|
+
} | {
|
|
43
|
+
type: 'tool';
|
|
44
|
+
id: string;
|
|
45
|
+
label: string;
|
|
46
|
+
state: 'ok' | 'fail';
|
|
47
|
+
secs: number;
|
|
48
|
+
} | {
|
|
49
|
+
type: 'text';
|
|
50
|
+
delta: string;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'confirm';
|
|
53
|
+
token: string;
|
|
54
|
+
action: 'stop';
|
|
55
|
+
sessionId: string;
|
|
56
|
+
label: string;
|
|
57
|
+
} | {
|
|
58
|
+
type: 'done';
|
|
59
|
+
turn: string;
|
|
60
|
+
text: string;
|
|
61
|
+
summary: string;
|
|
62
|
+
refs: LeadRef[];
|
|
63
|
+
timing: LeadTiming;
|
|
64
|
+
} | {
|
|
65
|
+
type: 'error';
|
|
66
|
+
message: string;
|
|
67
|
+
};
|
|
68
|
+
export interface ContextUsage {
|
|
69
|
+
tokens: number;
|
|
70
|
+
window: number;
|
|
71
|
+
}
|
|
72
|
+
export interface TurnResult {
|
|
73
|
+
text: string;
|
|
74
|
+
isError: boolean;
|
|
75
|
+
usage: ContextUsage | null;
|
|
76
|
+
sessionId?: string;
|
|
77
|
+
}
|
|
78
|
+
export type ParsedItem = {
|
|
79
|
+
kind: 'event';
|
|
80
|
+
event: LeadEvent;
|
|
81
|
+
} | {
|
|
82
|
+
kind: 'init';
|
|
83
|
+
sessionId: string;
|
|
84
|
+
} | {
|
|
85
|
+
kind: 'result';
|
|
86
|
+
result: TurnResult;
|
|
87
|
+
};
|
|
88
|
+
export declare const ROTATE_AT_FRACTION = 0.6;
|
|
89
|
+
export declare function toolLabel(command: string): string;
|
|
90
|
+
export declare function isHeldCommand(command: string): boolean;
|
|
91
|
+
export declare function contextUsageFromResult(result: Record<string, unknown>): ContextUsage | null;
|
|
92
|
+
export declare function shouldRotate(usage: ContextUsage | null, threshold?: number): boolean;
|
|
93
|
+
export declare function summarize(text: string, max?: number): string;
|
|
94
|
+
export declare class LeadTurnParser {
|
|
95
|
+
private status;
|
|
96
|
+
private readonly tools;
|
|
97
|
+
private readonly held;
|
|
98
|
+
private readonly spans;
|
|
99
|
+
private streamedText;
|
|
100
|
+
feed(msg: Record<string, unknown>, nowMs: number): ParsedItem[];
|
|
101
|
+
toolSeconds(): number;
|
|
102
|
+
private setStatus;
|
|
103
|
+
private onStreamEvent;
|
|
104
|
+
private onAssistant;
|
|
105
|
+
private onUser;
|
|
106
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
export const ROTATE_AT_FRACTION = 0.6;
|
|
2
|
+
const LEAD_TOOL_RE = /^\s*agents\s+lead\s+tool\s+([a-z]+)/;
|
|
3
|
+
const HELD_TOOLS = new Set(['stop']);
|
|
4
|
+
export function toolLabel(command) {
|
|
5
|
+
const lead = LEAD_TOOL_RE.exec(command);
|
|
6
|
+
if (lead)
|
|
7
|
+
return lead[1];
|
|
8
|
+
const words = command.trim().split(/\s+/);
|
|
9
|
+
return words[0] || 'Bash';
|
|
10
|
+
}
|
|
11
|
+
export function isHeldCommand(command) {
|
|
12
|
+
const lead = LEAD_TOOL_RE.exec(command);
|
|
13
|
+
return lead !== null && HELD_TOOLS.has(lead[1]);
|
|
14
|
+
}
|
|
15
|
+
function round2(n) {
|
|
16
|
+
return Math.round(n * 100) / 100;
|
|
17
|
+
}
|
|
18
|
+
function mergedSeconds(spans) {
|
|
19
|
+
const sorted = [...spans].sort((a, b) => a[0] - b[0]);
|
|
20
|
+
let total = 0;
|
|
21
|
+
let curStart = -1;
|
|
22
|
+
let curEnd = -1;
|
|
23
|
+
for (const [s, e] of sorted) {
|
|
24
|
+
if (s > curEnd) {
|
|
25
|
+
if (curEnd > curStart)
|
|
26
|
+
total += curEnd - curStart;
|
|
27
|
+
curStart = s;
|
|
28
|
+
curEnd = e;
|
|
29
|
+
}
|
|
30
|
+
else if (e > curEnd) {
|
|
31
|
+
curEnd = e;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (curEnd > curStart)
|
|
35
|
+
total += curEnd - curStart;
|
|
36
|
+
return total / 1000;
|
|
37
|
+
}
|
|
38
|
+
function usageTokens(u) {
|
|
39
|
+
const n = (k) => (typeof u[k] === 'number' ? u[k] : 0);
|
|
40
|
+
return n('input_tokens') + n('cache_creation_input_tokens') + n('cache_read_input_tokens') + n('output_tokens');
|
|
41
|
+
}
|
|
42
|
+
export function contextUsageFromResult(result) {
|
|
43
|
+
const usage = result.usage;
|
|
44
|
+
const modelUsage = result.modelUsage;
|
|
45
|
+
if (!usage || !modelUsage)
|
|
46
|
+
return null;
|
|
47
|
+
const windows = Object.values(modelUsage).map((m) => m.contextWindow).filter((w) => typeof w === 'number' && w > 0);
|
|
48
|
+
if (windows.length === 0)
|
|
49
|
+
return null;
|
|
50
|
+
const iterations = Array.isArray(usage.iterations) ? usage.iterations : [];
|
|
51
|
+
const last = iterations.length > 0 ? iterations[iterations.length - 1] : usage;
|
|
52
|
+
return { tokens: usageTokens(last), window: Math.max(...windows) };
|
|
53
|
+
}
|
|
54
|
+
export function shouldRotate(usage, threshold = ROTATE_AT_FRACTION) {
|
|
55
|
+
if (!usage)
|
|
56
|
+
return false;
|
|
57
|
+
return usage.tokens / usage.window >= threshold;
|
|
58
|
+
}
|
|
59
|
+
export function summarize(text, max = 80) {
|
|
60
|
+
const plain = text
|
|
61
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
62
|
+
.replace(/`([^`]*)`/g, '$1')
|
|
63
|
+
.replace(/\*\*([^*]*)\*\*/g, '$1')
|
|
64
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
65
|
+
.split('\n')
|
|
66
|
+
.map((line) => line.replace(/^\s*(?:[-*+]|\d+\.|#+)\s+/, '').trim())
|
|
67
|
+
.filter(Boolean)
|
|
68
|
+
.join(' ')
|
|
69
|
+
.replace(/\s+/g, ' ')
|
|
70
|
+
.trim();
|
|
71
|
+
const match = /^.*?[.!?](?=\s|$)/.exec(plain);
|
|
72
|
+
const sentence = (match ? match[0] : plain).trim();
|
|
73
|
+
if (sentence.length <= max)
|
|
74
|
+
return sentence;
|
|
75
|
+
const cut = sentence.slice(0, max - 1);
|
|
76
|
+
const space = cut.lastIndexOf(' ');
|
|
77
|
+
return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, '')}…`;
|
|
78
|
+
}
|
|
79
|
+
export class LeadTurnParser {
|
|
80
|
+
status = null;
|
|
81
|
+
tools = new Map();
|
|
82
|
+
held = new Set();
|
|
83
|
+
spans = [];
|
|
84
|
+
streamedText = false;
|
|
85
|
+
feed(msg, nowMs) {
|
|
86
|
+
const out = [];
|
|
87
|
+
const type = msg.type;
|
|
88
|
+
if (type === 'system' && msg.subtype === 'init' && typeof msg.session_id === 'string') {
|
|
89
|
+
out.push({ kind: 'init', sessionId: msg.session_id });
|
|
90
|
+
}
|
|
91
|
+
else if (type === 'stream_event') {
|
|
92
|
+
this.onStreamEvent(msg.event, out);
|
|
93
|
+
}
|
|
94
|
+
else if (type === 'assistant') {
|
|
95
|
+
this.onAssistant(msg, nowMs, out);
|
|
96
|
+
}
|
|
97
|
+
else if (type === 'user') {
|
|
98
|
+
this.onUser(msg, nowMs, out);
|
|
99
|
+
}
|
|
100
|
+
else if (type === 'result') {
|
|
101
|
+
out.push({
|
|
102
|
+
kind: 'result',
|
|
103
|
+
result: {
|
|
104
|
+
text: typeof msg.result === 'string' ? msg.result : '',
|
|
105
|
+
isError: msg.is_error === true || (typeof msg.subtype === 'string' && msg.subtype !== 'success'),
|
|
106
|
+
usage: contextUsageFromResult(msg),
|
|
107
|
+
sessionId: typeof msg.session_id === 'string' ? msg.session_id : undefined,
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
toolSeconds() {
|
|
114
|
+
return round2(mergedSeconds(this.spans));
|
|
115
|
+
}
|
|
116
|
+
setStatus(state, out) {
|
|
117
|
+
if (this.status === state)
|
|
118
|
+
return;
|
|
119
|
+
this.status = state;
|
|
120
|
+
out.push({ kind: 'event', event: { type: 'status', state } });
|
|
121
|
+
}
|
|
122
|
+
onStreamEvent(event, out) {
|
|
123
|
+
if (!event)
|
|
124
|
+
return;
|
|
125
|
+
if (event.type === 'message_start') {
|
|
126
|
+
this.setStatus('thinking', out);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (event.type === 'content_block_delta') {
|
|
130
|
+
const delta = event.delta;
|
|
131
|
+
if (delta?.type === 'text_delta' && typeof delta.text === 'string' && delta.text.length > 0) {
|
|
132
|
+
this.setStatus('answering', out);
|
|
133
|
+
this.streamedText = true;
|
|
134
|
+
out.push({ kind: 'event', event: { type: 'text', delta: delta.text } });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
onAssistant(msg, nowMs, out) {
|
|
139
|
+
const content = msg.message?.content;
|
|
140
|
+
if (!Array.isArray(content))
|
|
141
|
+
return;
|
|
142
|
+
for (const block of content) {
|
|
143
|
+
if (block.type === 'text' && typeof block.text === 'string' && block.text.length > 0 && !this.streamedText) {
|
|
144
|
+
this.setStatus('answering', out);
|
|
145
|
+
out.push({ kind: 'event', event: { type: 'text', delta: block.text } });
|
|
146
|
+
}
|
|
147
|
+
else if (block.type === 'tool_use' && typeof block.id === 'string') {
|
|
148
|
+
const input = (block.input ?? {});
|
|
149
|
+
const cmd = typeof input.command === 'string' ? input.command : String(block.name ?? 'tool');
|
|
150
|
+
if (block.name === 'Bash' && isHeldCommand(cmd)) {
|
|
151
|
+
this.held.add(block.id);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const label = block.name === 'Bash' ? toolLabel(cmd) : String(block.name ?? 'tool');
|
|
155
|
+
this.tools.set(block.id, { label, startMs: nowMs });
|
|
156
|
+
this.setStatus('tool', out);
|
|
157
|
+
out.push({ kind: 'event', event: { type: 'tool', id: block.id, label, cmd, state: 'run' } });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
this.streamedText = false;
|
|
161
|
+
}
|
|
162
|
+
onUser(msg, nowMs, out) {
|
|
163
|
+
const content = msg.message?.content;
|
|
164
|
+
if (!Array.isArray(content))
|
|
165
|
+
return;
|
|
166
|
+
for (const block of content) {
|
|
167
|
+
if (block.type !== 'tool_result' || typeof block.tool_use_id !== 'string')
|
|
168
|
+
continue;
|
|
169
|
+
if (this.held.has(block.tool_use_id))
|
|
170
|
+
continue;
|
|
171
|
+
const span = this.tools.get(block.tool_use_id);
|
|
172
|
+
if (!span)
|
|
173
|
+
continue;
|
|
174
|
+
this.tools.delete(block.tool_use_id);
|
|
175
|
+
this.spans.push([span.startMs, nowMs]);
|
|
176
|
+
out.push({
|
|
177
|
+
kind: 'event',
|
|
178
|
+
event: {
|
|
179
|
+
type: 'tool',
|
|
180
|
+
id: block.tool_use_id,
|
|
181
|
+
label: span.label,
|
|
182
|
+
state: block.is_error === true ? 'fail' : 'ok',
|
|
183
|
+
secs: round2((nowMs - span.startMs) / 1000),
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { LeadPaths } from './paths.js';
|
|
2
|
+
export declare const LEAD_TOOL_NAMES: readonly ["roster", "dispatch", "start", "send", "stop", "linear", "remember"];
|
|
3
|
+
export type LeadToolName = typeof LEAD_TOOL_NAMES[number];
|
|
4
|
+
export declare const LEAD_ALLOWED_TOOLS: readonly string[];
|
|
5
|
+
export declare const LEAD_DENIED_TOOLS: readonly ["Edit", "Write", "MultiEdit", "NotebookEdit", "Read", "Glob", "Grep", "WebFetch", "WebSearch"];
|
|
6
|
+
export declare const LEAD_EFFORT = "low";
|
|
7
|
+
export declare const LEAD_ENV_PASSTHROUGH: readonly ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "TMPDIR", "XDG_RUNTIME_DIR", "TERM"];
|
|
8
|
+
export interface Launch {
|
|
9
|
+
command: string;
|
|
10
|
+
args: string[];
|
|
11
|
+
}
|
|
12
|
+
export type LeadSessionStart = {
|
|
13
|
+
mode: 'fresh';
|
|
14
|
+
sessionId: string;
|
|
15
|
+
} | {
|
|
16
|
+
mode: 'resume';
|
|
17
|
+
sessionId: string;
|
|
18
|
+
};
|
|
19
|
+
export declare function leadModel(): string;
|
|
20
|
+
export declare function cliVersion(): string;
|
|
21
|
+
export declare function leadSettings(): Record<string, unknown>;
|
|
22
|
+
export declare function writeLeadSettings(paths: LeadPaths): string;
|
|
23
|
+
export declare function writeAgentsShim(paths: LeadPaths, launch?: Launch): string;
|
|
24
|
+
export declare function leadChildEnv(project: string, paths: LeadPaths, source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
25
|
+
export declare const WORKER_ENV_PASSTHROUGH: readonly ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "TMPDIR", "XDG_RUNTIME_DIR", "TERM", "SSH_AUTH_SOCK", "GH_TOKEN", "GITHUB_TOKEN", "LINEAR_API_KEY", "DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "COLORTERM", "EDITOR", "VISUAL"];
|
|
26
|
+
export declare function curatedClientEnv(source?: NodeJS.ProcessEnv): Record<string, string>;
|
|
27
|
+
export declare function workerEnv(hostEnv: NodeJS.ProcessEnv, clientEnv: Record<string, string>, leadRootDir: string): NodeJS.ProcessEnv;
|
|
28
|
+
export declare function leadRunArgs(project: string, model: string, start: LeadSessionStart, paths: LeadPaths): string[];
|
|
29
|
+
export declare function agentsCliLaunch(args: string[]): Launch;
|