@firefunc-agent/runner 0.9.0 → 0.9.3
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/README.md +90 -28
- package/dist/activity.d.ts +4 -1
- package/dist/activity.js +94 -8
- package/dist/api.d.ts +24 -0
- package/dist/api.js +74 -5
- package/dist/brief.d.ts +5 -0
- package/dist/brief.js +21 -0
- package/dist/build-info.json +2 -2
- package/dist/cli.js +10 -2
- package/dist/config.d.ts +2 -0
- package/dist/cut.d.ts +45 -0
- package/dist/cut.js +105 -0
- package/dist/daemon.d.ts +16 -0
- package/dist/daemon.js +156 -35
- package/dist/declined.d.ts +11 -0
- package/dist/declined.js +27 -0
- package/dist/engines/claude.js +129 -1
- package/dist/engines/types.d.ts +10 -0
- package/dist/exec.d.ts +3 -0
- package/dist/exec.js +48 -5
- package/dist/firefunc/agents.js +59 -7
- package/dist/firefunc/client.d.ts +1 -0
- package/dist/firefunc/client.js +3 -0
- package/dist/firefunc/configure.d.ts +6 -0
- package/dist/firefunc/configure.js +409 -0
- package/dist/firefunc/main.js +45 -7
- package/dist/firefunc/output.js +4 -1
- package/dist/firefunc/version.js +2 -17
- package/dist/held.d.ts +18 -0
- package/dist/held.js +95 -0
- package/dist/job.d.ts +3 -0
- package/dist/job.js +437 -76
- package/dist/keep-local.d.ts +6 -1
- package/dist/keep-local.js +171 -4
- package/dist/limit.d.ts +30 -0
- package/dist/limit.js +258 -0
- package/dist/locks.d.ts +14 -0
- package/dist/locks.js +164 -0
- package/dist/mcp-proxy.d.ts +21 -0
- package/dist/mcp-proxy.js +180 -0
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +31 -2
- package/dist/orphans.d.ts +40 -0
- package/dist/orphans.js +235 -0
- package/dist/pool.d.ts +7 -0
- package/dist/pool.js +57 -9
- package/dist/pr-title.d.ts +11 -0
- package/dist/pr-title.js +63 -0
- package/dist/recover.d.ts +10 -0
- package/dist/recover.js +104 -0
- package/dist/session-stream.d.ts +8 -1
- package/dist/session-stream.js +9 -1
- package/dist/skills.d.ts +11 -0
- package/dist/skills.js +164 -0
- package/dist/stopped.d.ts +3 -0
- package/dist/stopped.js +10 -0
- package/dist/usage.d.ts +49 -0
- package/dist/usage.js +389 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +17 -0
- package/dist/worktrees.d.ts +15 -0
- package/dist/worktrees.js +96 -0
- package/package.json +1 -1
- package/skill/firefunc/SKILL.md +57 -8
package/dist/cut.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { RunUsage } from './usage.js';
|
|
2
|
+
import type { WrittenSkills } from './skills.js';
|
|
3
|
+
export type CutSession = {
|
|
4
|
+
workItemId: string;
|
|
5
|
+
runId: string;
|
|
6
|
+
engine: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
repo: string | null;
|
|
9
|
+
branch: string;
|
|
10
|
+
base: string;
|
|
11
|
+
worktree: string;
|
|
12
|
+
repoPath: string | null;
|
|
13
|
+
readHead?: string;
|
|
14
|
+
resetsAt: string | null;
|
|
15
|
+
cutAt: string;
|
|
16
|
+
keepUntil: string;
|
|
17
|
+
promptHash: string;
|
|
18
|
+
review: boolean;
|
|
19
|
+
toolsOnly: boolean;
|
|
20
|
+
continuesBranch: boolean;
|
|
21
|
+
usage?: RunUsage;
|
|
22
|
+
writtenSkills?: WrittenSkills;
|
|
23
|
+
};
|
|
24
|
+
export declare function cutDir(runnerDir: string): string;
|
|
25
|
+
export declare function promptHash(prompt: string): string;
|
|
26
|
+
export declare function keepUntil(resetsAt: string | null, cutAt: number): string;
|
|
27
|
+
export declare function saveCut(runnerDir: string, cut: CutSession): boolean;
|
|
28
|
+
export declare function listCuts(runnerDir: string): CutSession[];
|
|
29
|
+
export declare function dropCut(runnerDir: string, workItemId: string): void;
|
|
30
|
+
export type CutKey = {
|
|
31
|
+
workItemId: string;
|
|
32
|
+
engine: string;
|
|
33
|
+
repo: string | null;
|
|
34
|
+
branch: string;
|
|
35
|
+
review: boolean;
|
|
36
|
+
toolsOnly: boolean;
|
|
37
|
+
};
|
|
38
|
+
export declare function cutFor(runnerDir: string, key: CutKey, now?: number): {
|
|
39
|
+
resume: CutSession;
|
|
40
|
+
} | {
|
|
41
|
+
discard: CutSession;
|
|
42
|
+
} | null;
|
|
43
|
+
export declare function expiredCuts(runnerDir: string, now?: number): CutSession[];
|
|
44
|
+
export declare function keptWorktrees(runnerDir: string): Set<string>;
|
|
45
|
+
export declare function resumeAfterResetBrief(prompt: string, briefChanged: boolean): string;
|
package/dist/cut.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
const DAY = 86_400_000;
|
|
5
|
+
const ITEM_ID = /^[A-Za-z0-9][A-Za-z0-9-]{3,79}$/;
|
|
6
|
+
export function cutDir(runnerDir) {
|
|
7
|
+
return join(runnerDir, 'cut');
|
|
8
|
+
}
|
|
9
|
+
function fileFor(runnerDir, workItemId) {
|
|
10
|
+
return typeof workItemId === 'string' && ITEM_ID.test(workItemId)
|
|
11
|
+
? join(cutDir(runnerDir), `${workItemId}.json`)
|
|
12
|
+
: null;
|
|
13
|
+
}
|
|
14
|
+
export function promptHash(prompt) {
|
|
15
|
+
return createHash('sha256').update(prompt).digest('hex').slice(0, 32);
|
|
16
|
+
}
|
|
17
|
+
export function keepUntil(resetsAt, cutAt) {
|
|
18
|
+
const reset = resetsAt ? Date.parse(resetsAt) : Number.NaN;
|
|
19
|
+
const from = Number.isFinite(reset) ? Math.max(reset, cutAt) : cutAt;
|
|
20
|
+
return new Date(Math.min(from + DAY, cutAt + 8 * DAY)).toISOString();
|
|
21
|
+
}
|
|
22
|
+
export function saveCut(runnerDir, cut) {
|
|
23
|
+
const file = fileFor(runnerDir, cut.workItemId);
|
|
24
|
+
if (!file)
|
|
25
|
+
return false;
|
|
26
|
+
try {
|
|
27
|
+
mkdirSync(cutDir(runnerDir), { recursive: true, mode: 0o700 });
|
|
28
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
29
|
+
writeFileSync(tmp, `${JSON.stringify(cut, null, 2)}\n`, { mode: 0o600 });
|
|
30
|
+
renameSync(tmp, file);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function listCuts(runnerDir) {
|
|
38
|
+
const dir = cutDir(runnerDir);
|
|
39
|
+
if (!existsSync(dir))
|
|
40
|
+
return [];
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const name of readdirSync(dir)) {
|
|
43
|
+
if (!name.endsWith('.json'))
|
|
44
|
+
continue;
|
|
45
|
+
try {
|
|
46
|
+
const rec = JSON.parse(readFileSync(join(dir, name), 'utf8'));
|
|
47
|
+
if (rec &&
|
|
48
|
+
typeof rec.workItemId === 'string' &&
|
|
49
|
+
typeof rec.sessionId === 'string' &&
|
|
50
|
+
typeof rec.worktree === 'string' &&
|
|
51
|
+
typeof rec.keepUntil === 'string') {
|
|
52
|
+
out.push(rec);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
export function dropCut(runnerDir, workItemId) {
|
|
61
|
+
const file = fileFor(runnerDir, workItemId);
|
|
62
|
+
if (!file)
|
|
63
|
+
return;
|
|
64
|
+
try {
|
|
65
|
+
unlinkSync(file);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export function cutFor(runnerDir, key, now = Date.now()) {
|
|
71
|
+
const file = fileFor(runnerDir, key.workItemId);
|
|
72
|
+
if (!file || !existsSync(file))
|
|
73
|
+
return null;
|
|
74
|
+
const cut = listCuts(runnerDir).find((c) => c.workItemId === key.workItemId);
|
|
75
|
+
if (!cut)
|
|
76
|
+
return null;
|
|
77
|
+
const matches = cut.engine === key.engine &&
|
|
78
|
+
(cut.repo ?? null) === (key.repo ?? null) &&
|
|
79
|
+
cut.branch === key.branch &&
|
|
80
|
+
cut.review === key.review &&
|
|
81
|
+
cut.toolsOnly === key.toolsOnly;
|
|
82
|
+
if (!matches || Date.parse(cut.keepUntil) <= now || !existsSync(cut.worktree)) {
|
|
83
|
+
return { discard: cut };
|
|
84
|
+
}
|
|
85
|
+
const reset = cut.resetsAt ? Date.parse(cut.resetsAt) : Number.NaN;
|
|
86
|
+
if (Number.isFinite(reset) && reset > now)
|
|
87
|
+
return null;
|
|
88
|
+
return { resume: cut };
|
|
89
|
+
}
|
|
90
|
+
export function expiredCuts(runnerDir, now = Date.now()) {
|
|
91
|
+
return listCuts(runnerDir).filter((c) => Date.parse(c.keepUntil) <= now);
|
|
92
|
+
}
|
|
93
|
+
export function keptWorktrees(runnerDir) {
|
|
94
|
+
return new Set(listCuts(runnerDir).map((c) => c.worktree));
|
|
95
|
+
}
|
|
96
|
+
export function resumeAfterResetBrief(prompt, briefChanged) {
|
|
97
|
+
return ("Your session on this task was stopped by the plan's usage limit, which has now reset. " +
|
|
98
|
+
'The worktree still holds everything you did — check `git status` and `git diff`, then ' +
|
|
99
|
+
'continue from where you stopped and finish the task.' +
|
|
100
|
+
(briefChanged
|
|
101
|
+
? ' FireFunc sent this run a brief that differs from the one you started with; it follows, and where the two differ, follow this one.\n\n' +
|
|
102
|
+
prompt
|
|
103
|
+
: ''));
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=cut.js.map
|
package/dist/daemon.d.ts
CHANGED
|
@@ -1,2 +1,18 @@
|
|
|
1
|
+
import { type EngineLimitReport } from './api.js';
|
|
1
2
|
import type { RunnerConfig } from './config.js';
|
|
3
|
+
export type ClaimState = {
|
|
4
|
+
holding: Iterable<string>;
|
|
5
|
+
pending: Iterable<string>;
|
|
6
|
+
lostRuns?: string[];
|
|
7
|
+
limits?: EngineLimitReport[];
|
|
8
|
+
heartbeat?: boolean;
|
|
9
|
+
draining?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function claimState(s: ClaimState): {
|
|
12
|
+
heldRuns: string[];
|
|
13
|
+
lostRuns?: string[];
|
|
14
|
+
limits?: EngineLimitReport[];
|
|
15
|
+
heartbeat?: true;
|
|
16
|
+
draining?: true;
|
|
17
|
+
};
|
|
2
18
|
export declare function startDaemon(cfg: RunnerConfig): Promise<void>;
|
package/dist/daemon.js
CHANGED
|
@@ -1,33 +1,38 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync, rmSync } from 'node:fs';
|
|
2
|
+
import { flushPendingResults, listPendingResults } from './pending.js';
|
|
2
3
|
import { runnerDir } from './config.js';
|
|
3
|
-
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { hostname, platform } from 'node:os';
|
|
5
|
-
import { dirname, join } from 'node:path';
|
|
6
|
-
import { fileURLToPath } from 'node:url';
|
|
7
5
|
import { RunnerApi } from './api.js';
|
|
8
6
|
import { availableEngines, getAdapter, supportedEngines } from './engines/index.js';
|
|
9
7
|
import { runJob, resolveRepoPath } from './job.js';
|
|
10
8
|
import { createSessionViewer } from './viewer.js';
|
|
11
9
|
import { runJobPool } from './pool.js';
|
|
12
10
|
import { machineLogins } from './machine-logins.js';
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
return '0.0.0';
|
|
25
|
-
})();
|
|
11
|
+
import { RUNNER_VERSION } from './version.js';
|
|
12
|
+
import { LimitGate } from './limit.js';
|
|
13
|
+
import { heldByLiveProcesses, liveWorktrees, recordHeld, releaseHeld } from './held.js';
|
|
14
|
+
import { recoverPreviousProcess } from './recover.js';
|
|
15
|
+
import { dropCut, expiredCuts, keptWorktrees } from './cut.js';
|
|
16
|
+
import { removeRunnerWorktree, sweepLeftoverWorktrees } from './worktrees.js';
|
|
17
|
+
import { signalEngineGroups } from './orphans.js';
|
|
26
18
|
function log(msg) {
|
|
27
19
|
console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
|
|
28
20
|
}
|
|
21
|
+
export function claimState(s) {
|
|
22
|
+
const held = [...new Set([...s.holding, ...s.pending])].sort();
|
|
23
|
+
return {
|
|
24
|
+
heldRuns: held,
|
|
25
|
+
...(s.lostRuns?.length ? { lostRuns: s.lostRuns } : {}),
|
|
26
|
+
...(s.limits?.length ? { limits: s.limits } : {}),
|
|
27
|
+
...(s.heartbeat ? { heartbeat: true } : {}),
|
|
28
|
+
...(s.draining ? { draining: true } : {}),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const SERVICE_GRACE_MS = 10_000;
|
|
29
32
|
export async function startDaemon(cfg) {
|
|
30
33
|
const api = new RunnerApi(cfg.apiUrl, cfg.token);
|
|
34
|
+
const rdir = runnerDir();
|
|
35
|
+
const machine = cfg.name ?? hostname();
|
|
31
36
|
const viewerPort = cfg.viewerEnabled === false ? null : (cfg.viewerPort ?? 8787);
|
|
32
37
|
const declaredEngines = availableEngines(cfg);
|
|
33
38
|
const skipped = supportedEngines().filter((e) => !declaredEngines.includes(e));
|
|
@@ -41,7 +46,7 @@ export async function startDaemon(cfg) {
|
|
|
41
46
|
log(`engines not installed (skipped): ${skipped.join(', ')} — install the CLI to enable them`);
|
|
42
47
|
}
|
|
43
48
|
const meta = {
|
|
44
|
-
version:
|
|
49
|
+
version: RUNNER_VERSION,
|
|
45
50
|
hostname: hostname(),
|
|
46
51
|
platform: platform(),
|
|
47
52
|
viewerPort,
|
|
@@ -78,14 +83,49 @@ export async function startDaemon(cfg) {
|
|
|
78
83
|
onListen: (u) => log(`live session viewer → ${u} (local only — watch Claude work in a browser)`),
|
|
79
84
|
onError: (m) => log(`${m} — set "viewerPort" or pass --no-viewer`),
|
|
80
85
|
});
|
|
86
|
+
const holding = new Set();
|
|
87
|
+
const pendingIds = () => {
|
|
88
|
+
try {
|
|
89
|
+
return listPendingResults(rdir).map((p) => p.runId);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
let forced = false;
|
|
96
|
+
const forceStop = (why) => {
|
|
97
|
+
if (forced)
|
|
98
|
+
return;
|
|
99
|
+
forced = true;
|
|
100
|
+
const n = signalEngineGroups('SIGTERM');
|
|
101
|
+
if (n > 0)
|
|
102
|
+
log(`${why} — stopping ${n} engine session(s) now; each run reports how it ended`);
|
|
103
|
+
setTimeout(() => signalEngineGroups('SIGKILL'), 3_000).unref();
|
|
104
|
+
};
|
|
105
|
+
const underService = process.env.FIREFUNC_RUNNER_SERVICE === '1';
|
|
81
106
|
const stop = (sig) => {
|
|
82
|
-
if (stopping)
|
|
107
|
+
if (stopping) {
|
|
108
|
+
forceStop(`${sig} received again`);
|
|
83
109
|
return;
|
|
110
|
+
}
|
|
84
111
|
stopping = true;
|
|
85
|
-
|
|
112
|
+
if (underService && sig === 'SIGTERM') {
|
|
113
|
+
setTimeout(() => forceStop('the service is stopping'), SERVICE_GRACE_MS).unref();
|
|
114
|
+
}
|
|
115
|
+
if (holding.size === 0) {
|
|
116
|
+
log(`${sig} received — stopping.`);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
log(`${sig} received — finishing ${holding.size} in-flight job(s) before exiting, claiming nothing new` +
|
|
120
|
+
(underService
|
|
121
|
+
? ` (the service manager stops this process soon, so their engines are stopped in ${SERVICE_GRACE_MS / 1000}s)`
|
|
122
|
+
: ' — press Ctrl-C again to stop them now'));
|
|
86
123
|
};
|
|
87
124
|
process.on('SIGINT', () => stop('SIGINT'));
|
|
88
125
|
process.on('SIGTERM', () => stop('SIGTERM'));
|
|
126
|
+
process.on('exit', () => {
|
|
127
|
+
signalEngineGroups('SIGKILL');
|
|
128
|
+
});
|
|
89
129
|
let serverMax = 1;
|
|
90
130
|
const refreshConfig = async () => {
|
|
91
131
|
const c = await api.config();
|
|
@@ -124,7 +164,7 @@ export async function startDaemon(cfg) {
|
|
|
124
164
|
refreshLogins();
|
|
125
165
|
const loginTimer = setInterval(refreshLogins, 5 * 60_000);
|
|
126
166
|
const effectiveMax = () => Math.max(1, Math.floor(cfg.maxParallel ?? serverMax));
|
|
127
|
-
log(`connected to ${cfg.apiUrl} as "${
|
|
167
|
+
log(`connected to ${cfg.apiUrl} as "${machine}" — watching for work` +
|
|
128
168
|
(effectiveMax() > 1 ? ` (up to ${effectiveMax()} parallel sessions).` : '.'));
|
|
129
169
|
try {
|
|
130
170
|
const routed = await api.repos();
|
|
@@ -141,6 +181,77 @@ export async function startDaemon(cfg) {
|
|
|
141
181
|
}
|
|
142
182
|
catch {
|
|
143
183
|
}
|
|
184
|
+
let lostRuns = await recoverPreviousProcess({ runnerDir: rdir, api, machine, log }).catch(() => []);
|
|
185
|
+
const dropExpiredCuts = async () => {
|
|
186
|
+
for (const cut of expiredCuts(rdir)) {
|
|
187
|
+
log(`the session a plan limit cut for work item ${cut.workItemId} was not resumed in time — removing its worktree`);
|
|
188
|
+
if (cut.repoPath && existsSync(cut.repoPath)) {
|
|
189
|
+
await removeRunnerWorktree(cut.repoPath, cut.worktree, log).catch(() => { });
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
try {
|
|
193
|
+
rmSync(cut.worktree, { recursive: true, force: true });
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
dropCut(rdir, cut.workItemId);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
await dropExpiredCuts().catch(() => { });
|
|
202
|
+
let lastCutSweep = Date.now();
|
|
203
|
+
try {
|
|
204
|
+
const checkouts = Object.values(cfg.repos ?? {}).filter((p) => existsSync(p));
|
|
205
|
+
const removed = await sweepLeftoverWorktrees(checkouts, {
|
|
206
|
+
live: liveWorktrees(rdir),
|
|
207
|
+
keep: keptWorktrees(rdir),
|
|
208
|
+
log,
|
|
209
|
+
});
|
|
210
|
+
if (removed > 0)
|
|
211
|
+
log(`removed ${removed} leftover worktree(s)`);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
}
|
|
215
|
+
const gate = new LimitGate(LimitGate.fileIn(rdir));
|
|
216
|
+
const limitReports = () => gate.active().map((l) => ({ engine: l.engine, kind: 'plan', resetsAt: l.resetsAt }));
|
|
217
|
+
let wasPaused = false;
|
|
218
|
+
const paused = () => {
|
|
219
|
+
const engines = meta.engines.length > 0 ? meta.engines : ['claude_code'];
|
|
220
|
+
const spent = engines.map((e) => gate.isLimited(e));
|
|
221
|
+
const now = spent.every((l) => l !== null);
|
|
222
|
+
if (now && !wasPaused) {
|
|
223
|
+
const until = spent
|
|
224
|
+
.map((l) => l.until)
|
|
225
|
+
.sort()
|
|
226
|
+
.at(-1);
|
|
227
|
+
log(`the plan's usage limit is spent on every engine here — claiming no work until ${until}`);
|
|
228
|
+
}
|
|
229
|
+
else if (!now && wasPaused) {
|
|
230
|
+
log("the plan's usage limit has reset — claiming work again");
|
|
231
|
+
}
|
|
232
|
+
wasPaused = now;
|
|
233
|
+
return now;
|
|
234
|
+
};
|
|
235
|
+
const claimBody = (extra = {}) => ({
|
|
236
|
+
...meta,
|
|
237
|
+
maxParallel: effectiveMax(),
|
|
238
|
+
budget: budgets,
|
|
239
|
+
mcpLogins: logins.map((l) => ({
|
|
240
|
+
server: l.server,
|
|
241
|
+
state: l.state,
|
|
242
|
+
via: l.via,
|
|
243
|
+
accountLabel: l.accountLabel,
|
|
244
|
+
expiresAt: l.expiresAt,
|
|
245
|
+
...(l.detail ? { detail: l.detail } : {}),
|
|
246
|
+
})),
|
|
247
|
+
...claimState({
|
|
248
|
+
holding: [...holding, ...heldByLiveProcesses(rdir)],
|
|
249
|
+
pending: pendingIds(),
|
|
250
|
+
lostRuns,
|
|
251
|
+
limits: limitReports(),
|
|
252
|
+
...extra,
|
|
253
|
+
}),
|
|
254
|
+
});
|
|
144
255
|
const portBase = cfg.devServerBasePort ?? 3100;
|
|
145
256
|
const usedPorts = new Set();
|
|
146
257
|
const takePort = () => {
|
|
@@ -155,27 +266,33 @@ export async function startDaemon(cfg) {
|
|
|
155
266
|
return undefined;
|
|
156
267
|
};
|
|
157
268
|
let backoffMs = 2_000;
|
|
269
|
+
let heartbeatIgnored = false;
|
|
158
270
|
await runJobPool({
|
|
159
271
|
maxParallel: effectiveMax,
|
|
160
272
|
stopping: () => stopping,
|
|
273
|
+
paused,
|
|
274
|
+
heartbeat: async ({ draining, paused: waitingOutLimit }) => {
|
|
275
|
+
if (waitingOutLimit && heartbeatIgnored)
|
|
276
|
+
return null;
|
|
277
|
+
const job = await api.claim(claimBody({ heartbeat: true, draining })).catch(() => null);
|
|
278
|
+
if (job) {
|
|
279
|
+
heartbeatIgnored = true;
|
|
280
|
+
log(`FireFunc handed ${job.runId} to a heartbeat — running it`);
|
|
281
|
+
}
|
|
282
|
+
return job;
|
|
283
|
+
},
|
|
161
284
|
claim: async () => {
|
|
162
|
-
const flushed = await flushPendingResults(
|
|
285
|
+
const flushed = await flushPendingResults(rdir, api, log).catch(() => null);
|
|
163
286
|
if (flushed && (flushed.delivered || flushed.refused)) {
|
|
164
287
|
log(`pending results: ${flushed.delivered} delivered, ${flushed.refused} refused, ${flushed.kept} kept`);
|
|
165
288
|
}
|
|
166
289
|
rescanEngines();
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
via: l.via,
|
|
174
|
-
accountLabel: l.accountLabel,
|
|
175
|
-
expiresAt: l.expiresAt,
|
|
176
|
-
...(l.detail ? { detail: l.detail } : {}),
|
|
177
|
-
})),
|
|
178
|
-
});
|
|
290
|
+
if (Date.now() - lastCutSweep > 10 * 60_000) {
|
|
291
|
+
lastCutSweep = Date.now();
|
|
292
|
+
await dropExpiredCuts().catch(() => { });
|
|
293
|
+
}
|
|
294
|
+
const job = await api.claim(claimBody());
|
|
295
|
+
lostRuns = [];
|
|
179
296
|
backoffMs = 2_000;
|
|
180
297
|
return job;
|
|
181
298
|
},
|
|
@@ -192,6 +309,8 @@ export async function startDaemon(cfg) {
|
|
|
192
309
|
return 'retry';
|
|
193
310
|
},
|
|
194
311
|
onStart: (job, inFlight) => {
|
|
312
|
+
holding.add(job.runId);
|
|
313
|
+
recordHeld(rdir, job.runId);
|
|
195
314
|
log(`[${inFlight}/${effectiveMax()}] claimed ${job.runId} — ${job.title ?? job.externalId ?? 'a bug'} (${job.repo ?? '?'})`);
|
|
196
315
|
if (viewer?.url)
|
|
197
316
|
log(` watch live → ${viewer.url}/s/${job.runId}`);
|
|
@@ -199,7 +318,7 @@ export async function startDaemon(cfg) {
|
|
|
199
318
|
run: async (job) => {
|
|
200
319
|
const devServerPort = takePort();
|
|
201
320
|
try {
|
|
202
|
-
await runJob(job, cfg, api, viewer, { devServerPort });
|
|
321
|
+
await runJob(job, cfg, api, viewer, { devServerPort, limits: gate });
|
|
203
322
|
}
|
|
204
323
|
catch (e) {
|
|
205
324
|
log(`job ${job.runId} errored: ${e.message}`);
|
|
@@ -207,6 +326,8 @@ export async function startDaemon(cfg) {
|
|
|
207
326
|
finally {
|
|
208
327
|
if (devServerPort != null)
|
|
209
328
|
usedPorts.delete(devServerPort);
|
|
329
|
+
holding.delete(job.runId);
|
|
330
|
+
releaseHeld(rdir, job.runId);
|
|
210
331
|
log(`done ${job.runId}`);
|
|
211
332
|
}
|
|
212
333
|
},
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface EngineEnding {
|
|
2
|
+
error: string | null;
|
|
3
|
+
refusal: boolean;
|
|
4
|
+
}
|
|
5
|
+
export declare function hasRefusalShape(text: string): boolean;
|
|
6
|
+
export declare function endedOnRefusal(input: {
|
|
7
|
+
ending: EngineEnding | undefined;
|
|
8
|
+
summary: string;
|
|
9
|
+
stderr: string;
|
|
10
|
+
}): boolean;
|
|
11
|
+
export declare function modelDeclinedSentence(engineName: string): string;
|
package/dist/declined.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const REFUSAL_SHAPE = /\bapi error\b[^\n]*?(?:\bsafeguards?\s+(?:have\s+)?flagged\b|\b(?:violat\w*|against)\s+(?:our|the|anthropic[’']s)\s+usage\s+polic|anthropic\.com\/legal\/aup)/i;
|
|
2
|
+
const API_ERROR_LINE = /^\s*(?:error:\s*)?api error\b/i;
|
|
3
|
+
export function hasRefusalShape(text) {
|
|
4
|
+
return REFUSAL_SHAPE.test(text);
|
|
5
|
+
}
|
|
6
|
+
function isRefusalLine(line) {
|
|
7
|
+
return API_ERROR_LINE.test(line) && hasRefusalShape(line);
|
|
8
|
+
}
|
|
9
|
+
export function endedOnRefusal(input) {
|
|
10
|
+
const { ending } = input;
|
|
11
|
+
if (ending) {
|
|
12
|
+
if (ending.error === null)
|
|
13
|
+
return false;
|
|
14
|
+
return ending.refusal || hasRefusalShape(ending.error);
|
|
15
|
+
}
|
|
16
|
+
const firstLine = input.summary.trim().split('\n', 1)[0] ?? '';
|
|
17
|
+
if (isRefusalLine(firstLine))
|
|
18
|
+
return true;
|
|
19
|
+
return input.stderr
|
|
20
|
+
.slice(-4000)
|
|
21
|
+
.split('\n')
|
|
22
|
+
.some((line) => isRefusalLine(line));
|
|
23
|
+
}
|
|
24
|
+
export function modelDeclinedSentence(engineName) {
|
|
25
|
+
return `The model's safety system declined this task — ${engineName} ended the session on a usage-policy refusal, so nothing it did was kept.`;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=declined.js.map
|
package/dist/engines/claude.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { makeStreamJsonParser } from '../session-stream.js';
|
|
2
2
|
import { readClaudeBudget } from './claude-budget.js';
|
|
3
|
+
import { readClaudeUsage } from '../usage.js';
|
|
3
4
|
import { mcpFromContext } from '../mcp.js';
|
|
5
|
+
import { readClaudeLimit } from '../limit.js';
|
|
6
|
+
import { commandName } from '../keep-local.js';
|
|
4
7
|
function claudeSummary(streamJson) {
|
|
5
8
|
const lines = streamJson.trim().split('\n');
|
|
6
9
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
@@ -24,10 +27,111 @@ function claudeSummary(streamJson) {
|
|
|
24
27
|
}
|
|
25
28
|
return '';
|
|
26
29
|
}
|
|
30
|
+
function claudeEnding(streamJson) {
|
|
31
|
+
const lines = streamJson.trim().split('\n');
|
|
32
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
33
|
+
let ev;
|
|
34
|
+
try {
|
|
35
|
+
ev = JSON.parse(lines[i]);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (!ev || typeof ev !== 'object' || ev.type !== 'result')
|
|
41
|
+
continue;
|
|
42
|
+
const refusal = ev.stop_reason === 'refusal';
|
|
43
|
+
if (ev.is_error !== true && !refusal)
|
|
44
|
+
return { error: null, refusal: false };
|
|
45
|
+
return { error: typeof ev.result === 'string' ? ev.result : '', refusal };
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{7,79}$/;
|
|
50
|
+
function claudeSessionId(streamJson) {
|
|
51
|
+
let id = null;
|
|
52
|
+
for (const line of streamJson.split('\n')) {
|
|
53
|
+
const t = line.trim();
|
|
54
|
+
if (!t.startsWith('{') || !t.includes('"session_id"'))
|
|
55
|
+
continue;
|
|
56
|
+
if (!t.includes('"subtype":"init"') && !t.includes('"type":"result"'))
|
|
57
|
+
continue;
|
|
58
|
+
try {
|
|
59
|
+
const ev = JSON.parse(t);
|
|
60
|
+
if (typeof ev.session_id === 'string' && SESSION_ID.test(ev.session_id))
|
|
61
|
+
id = ev.session_id;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return id;
|
|
67
|
+
}
|
|
68
|
+
const TASK_ENDED = new Set(['completed', 'failed', 'killed', 'stopped', 'cancelled', 'error']);
|
|
69
|
+
function claudeOpenCommands(streamJson) {
|
|
70
|
+
const open = new Map();
|
|
71
|
+
const commands = new Map();
|
|
72
|
+
let atClose = [];
|
|
73
|
+
for (const line of streamJson.split('\n')) {
|
|
74
|
+
const t = line.trim();
|
|
75
|
+
if (!t.startsWith('{'))
|
|
76
|
+
continue;
|
|
77
|
+
if (t.includes('"type":"assistant"')) {
|
|
78
|
+
if (!t.includes('"name":"Bash"'))
|
|
79
|
+
continue;
|
|
80
|
+
try {
|
|
81
|
+
const ev = JSON.parse(t);
|
|
82
|
+
for (const c of ev.message?.content ?? []) {
|
|
83
|
+
if (c.type === 'tool_use' &&
|
|
84
|
+
c.name === 'Bash' &&
|
|
85
|
+
c.id &&
|
|
86
|
+
typeof c.input?.command === 'string') {
|
|
87
|
+
commands.set(c.id, c.input.command);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (t.includes('"type":"result"')) {
|
|
96
|
+
atClose = [...open.values()];
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (!t.includes('"type":"system"') || !t.includes('"task_id"'))
|
|
100
|
+
continue;
|
|
101
|
+
let ev;
|
|
102
|
+
try {
|
|
103
|
+
ev = JSON.parse(t);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (typeof ev.task_id !== 'string')
|
|
109
|
+
continue;
|
|
110
|
+
if (ev.subtype === 'task_started') {
|
|
111
|
+
if (ev.task_type === 'local_bash') {
|
|
112
|
+
open.set(ev.task_id, typeof ev.tool_use_id === 'string' ? ev.tool_use_id : null);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
else if (ev.subtype === 'task_updated') {
|
|
116
|
+
if (typeof ev.patch?.status === 'string' && TASK_ENDED.has(ev.patch.status)) {
|
|
117
|
+
open.delete(ev.task_id);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else if (ev.subtype === 'task_notification') {
|
|
121
|
+
if (typeof ev.status === 'string' && TASK_ENDED.has(ev.status))
|
|
122
|
+
open.delete(ev.task_id);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return atClose.map((id) => {
|
|
126
|
+
const command = id ? commands.get(id) : undefined;
|
|
127
|
+
return command ? commandName(command) : 'a command';
|
|
128
|
+
});
|
|
129
|
+
}
|
|
27
130
|
export const claudeAdapter = {
|
|
28
131
|
id: 'claude_code',
|
|
29
132
|
displayName: 'Claude Code',
|
|
30
133
|
branchPrefix: 'claude',
|
|
134
|
+
resumesSessions: true,
|
|
31
135
|
bin(cfg) {
|
|
32
136
|
return cfg.claudeBin ?? 'claude';
|
|
33
137
|
},
|
|
@@ -39,9 +143,13 @@ export const claudeAdapter = {
|
|
|
39
143
|
'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
|
|
40
144
|
const mcp = mcpFromContext(ctx, 'claude');
|
|
41
145
|
const tools = mcp?.toolNames.length ? `${baseTools} ${mcp.toolNames.join(' ')}` : baseTools;
|
|
146
|
+
const resume = ctx.resumeSessionId && SESSION_ID.test(ctx.resumeSessionId)
|
|
147
|
+
? ['--resume', ctx.resumeSessionId]
|
|
148
|
+
: [];
|
|
42
149
|
const args = [
|
|
43
150
|
'-p',
|
|
44
151
|
...(ctx.isWin ? [] : [ctx.prompt]),
|
|
152
|
+
...resume,
|
|
45
153
|
'--output-format',
|
|
46
154
|
'stream-json',
|
|
47
155
|
'--verbose',
|
|
@@ -92,13 +200,16 @@ export const claudeAdapter = {
|
|
|
92
200
|
process.stdout.write(` │ ${short(ev.text)}\n`);
|
|
93
201
|
else if (ev.kind === 'tool')
|
|
94
202
|
process.stdout.write(` │ ⚒ ${ev.name}${ev.arg ? ` ${short(ev.arg, 90)}` : ''}\n`);
|
|
95
|
-
else
|
|
203
|
+
else if (ev.kind === 'result')
|
|
96
204
|
process.stdout.write(` └ ${short(ev.text, 240)}\n`);
|
|
97
205
|
});
|
|
98
206
|
},
|
|
99
207
|
summarize(stdout) {
|
|
100
208
|
return claudeSummary(stdout);
|
|
101
209
|
},
|
|
210
|
+
ending(stdout) {
|
|
211
|
+
return claudeEnding(stdout);
|
|
212
|
+
},
|
|
102
213
|
authFailureHint(text) {
|
|
103
214
|
const t = text.toLowerCase();
|
|
104
215
|
if (t.includes('credit balance is too low')) {
|
|
@@ -126,5 +237,22 @@ export const claudeAdapter = {
|
|
|
126
237
|
readBudget(cfg) {
|
|
127
238
|
return readClaudeBudget(cfg);
|
|
128
239
|
},
|
|
240
|
+
meter(stdout) {
|
|
241
|
+
return readClaudeUsage(stdout);
|
|
242
|
+
},
|
|
243
|
+
planLimit(stdout, now) {
|
|
244
|
+
return readClaudeLimit(stdout, now);
|
|
245
|
+
},
|
|
246
|
+
sessionId(stdout) {
|
|
247
|
+
return claudeSessionId(stdout);
|
|
248
|
+
},
|
|
249
|
+
openCommandsAtEnd(stdout) {
|
|
250
|
+
try {
|
|
251
|
+
return claudeOpenCommands(stdout);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return [];
|
|
255
|
+
}
|
|
256
|
+
},
|
|
129
257
|
};
|
|
130
258
|
//# sourceMappingURL=claude.js.map
|
package/dist/engines/types.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { RunnerConfig } from '../config.js';
|
|
2
|
+
import type { RunUsage } from '../usage.js';
|
|
3
|
+
import type { EngineEnding } from '../declined.js';
|
|
4
|
+
import type { PlanLimit } from '../limit.js';
|
|
2
5
|
export type EngineId = 'claude_code' | 'codex_cli' | 'gemini_cli' | 'cursor_cli' | 'antigravity' | 'copilot_cli';
|
|
3
6
|
export type InvocationContext = {
|
|
4
7
|
prompt: string;
|
|
@@ -14,6 +17,7 @@ export type InvocationContext = {
|
|
|
14
17
|
isWin: boolean;
|
|
15
18
|
runEnv: NodeJS.ProcessEnv;
|
|
16
19
|
cfg: RunnerConfig;
|
|
20
|
+
resumeSessionId?: string;
|
|
17
21
|
};
|
|
18
22
|
export type Invocation = {
|
|
19
23
|
bin: string;
|
|
@@ -44,5 +48,11 @@ export interface AgentAdapter {
|
|
|
44
48
|
summarize(stdout: string): string;
|
|
45
49
|
authFailureHint(text: string): string | null;
|
|
46
50
|
rateLimitHint(text: string): string | null;
|
|
51
|
+
ending?(stdout: string): EngineEnding | undefined;
|
|
52
|
+
meter?(stdout: string): RunUsage | null;
|
|
53
|
+
planLimit?(stdout: string, now: Date): PlanLimit | null;
|
|
54
|
+
sessionId?(stdout: string): string | null;
|
|
55
|
+
openCommandsAtEnd?(stdout: string): string[];
|
|
56
|
+
readonly resumesSessions?: boolean;
|
|
47
57
|
readBudget?(cfg: RunnerConfig): Promise<EngineBudgetReport | null>;
|
|
48
58
|
}
|