ai-agentmanager 0.0.0-stage → 1.0.0
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +767 -2
- package/SECURITY.md +44 -0
- package/bin/agentmgr-hub.js +16 -0
- package/bin/agentmgr.js +4 -0
- package/docs/architecture.md +67 -0
- package/docs/distributed.md +147 -0
- package/docs/engines.md +177 -0
- package/docs/images/agents.jpg +0 -0
- package/docs/images/conflict-radar.jpg +0 -0
- package/docs/plugins.md +81 -0
- package/package.json +56 -4
- package/public/app.js +3083 -0
- package/public/hub/hub.css +230 -0
- package/public/hub/hub.js +766 -0
- package/public/hub/index.html +146 -0
- package/public/hub/term.js +147 -0
- package/public/index.html +342 -0
- package/public/share.html +34 -0
- package/public/share.js +41 -0
- package/public/style.css +541 -0
- package/public/touchscroll.js +73 -0
- package/public/transport.js +78 -0
- package/scripts/build-release.sh +58 -0
- package/scripts/fix-pty.js +15 -0
- package/src/backlog.js +413 -0
- package/src/brief.js +512 -0
- package/src/cli.js +1447 -0
- package/src/client.js +49 -0
- package/src/config.js +109 -0
- package/src/conflicts.js +105 -0
- package/src/engines/antigravity.js +296 -0
- package/src/engines/claude.js +98 -0
- package/src/engines/codex.js +331 -0
- package/src/engines/index.js +37 -0
- package/src/fleet.js +176 -0
- package/src/git.js +340 -0
- package/src/hub.js +857 -0
- package/src/hubactions.js +107 -0
- package/src/hubbacklog.js +373 -0
- package/src/hublink.js +437 -0
- package/src/inbox.js +94 -0
- package/src/judge.js +278 -0
- package/src/livebrowser.js +637 -0
- package/src/manager.js +2554 -0
- package/src/notify.js +284 -0
- package/src/plugins.js +119 -0
- package/src/preview.js +334 -0
- package/src/races.js +192 -0
- package/src/remote.js +284 -0
- package/src/server.js +759 -0
- package/src/service.js +150 -0
- package/src/sessions.js +160 -0
- package/src/store.js +104 -0
- package/src/stuck.js +160 -0
- package/src/tracker.js +311 -0
- package/src/trust.js +44 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { ensureHome, HOST, paths, PORT } from './config.js';
|
|
6
|
+
|
|
7
|
+
export const BASE = `http://${HOST}:${PORT}`;
|
|
8
|
+
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'agentmgr.js');
|
|
9
|
+
|
|
10
|
+
export async function api(method, route, body) {
|
|
11
|
+
const res = await fetch(`${BASE}/api${route}`, {
|
|
12
|
+
method,
|
|
13
|
+
headers: { 'content-type': 'application/json', 'x-agentmgr': '1' },
|
|
14
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
15
|
+
});
|
|
16
|
+
const data = await res.json().catch(() => ({}));
|
|
17
|
+
if (!res.ok) throw new Error(data.error || `${method} ${route} failed with HTTP ${res.status}`);
|
|
18
|
+
return data;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function isRunning() {
|
|
22
|
+
try {
|
|
23
|
+
await api('GET', '/health');
|
|
24
|
+
return true;
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Start the daemon in the background if it is not already listening. */
|
|
31
|
+
export async function ensureDaemon({ quiet = false } = {}) {
|
|
32
|
+
if (await isRunning()) return false;
|
|
33
|
+
ensureHome();
|
|
34
|
+
const log = fs.openSync(paths.log, 'a');
|
|
35
|
+
const child = spawn(process.execPath, [BIN, 'serve'], {
|
|
36
|
+
detached: true,
|
|
37
|
+
stdio: ['ignore', log, log],
|
|
38
|
+
env: process.env,
|
|
39
|
+
});
|
|
40
|
+
child.unref();
|
|
41
|
+
for (let i = 0; i < 50; i++) {
|
|
42
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
43
|
+
if (await isRunning()) {
|
|
44
|
+
if (!quiet) process.stderr.write(`agentmgr: started daemon at ${BASE} (log: ${paths.log})\n`);
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Daemon did not start; see ${paths.log}`);
|
|
49
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const HOME = process.env.AGENTMGR_HOME || path.join(os.homedir(), '.agentmanager');
|
|
6
|
+
export const HOST = '127.0.0.1';
|
|
7
|
+
export const PORT = Number(process.env.AGENTMGR_PORT || 4717);
|
|
8
|
+
|
|
9
|
+
export const paths = {
|
|
10
|
+
home: HOME,
|
|
11
|
+
state: path.join(HOME, 'state.json'),
|
|
12
|
+
config: path.join(HOME, 'config.json'),
|
|
13
|
+
log: path.join(HOME, 'daemon.log'),
|
|
14
|
+
pid: path.join(HOME, 'daemon.pid'),
|
|
15
|
+
workspaces: path.join(HOME, 'workspaces'),
|
|
16
|
+
repos: path.join(HOME, 'repos'),
|
|
17
|
+
// Shared working folder for general (no repo / folder) sessions.
|
|
18
|
+
general: path.join(HOME, 'general'),
|
|
19
|
+
// Holding folder for planning sessions that run while a repo is still cloning.
|
|
20
|
+
planning: path.join(HOME, 'planning'),
|
|
21
|
+
// Per-agent briefs (Problem / Solution / Diagram / Checks), kept outside any repo.
|
|
22
|
+
briefs: path.join(HOME, 'briefs'),
|
|
23
|
+
// Saved terminal output, restored into an agent's terminal after a daemon restart.
|
|
24
|
+
scrollback: path.join(HOME, 'scrollback'),
|
|
25
|
+
// Files attached from the UI (dropped or pasted into a terminal), per agent.
|
|
26
|
+
uploads: path.join(HOME, 'uploads'),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const DEFAULTS = {
|
|
30
|
+
// Binary used to launch agents. Override to test with a stub.
|
|
31
|
+
claudeBin: process.env.AGENTMGR_CLAUDE_BIN || 'claude',
|
|
32
|
+
// Extra args appended to every claude launch, e.g. ["--model", "opus"].
|
|
33
|
+
claudeArgs: [],
|
|
34
|
+
// Default --permission-mode for new agents ("default" passes nothing).
|
|
35
|
+
permissionMode: 'default',
|
|
36
|
+
// Extra regexes (strings) that identify bug keys in transcripts, e.g. ["\\bABC-\\d+\\b"].
|
|
37
|
+
bugPatterns: [],
|
|
38
|
+
// Terminal output kept in memory per agent so a re-opened terminal shows history.
|
|
39
|
+
scrollbackBytes: 1024 * 1024,
|
|
40
|
+
// How often (seconds) running agents get git / PR info refreshed.
|
|
41
|
+
gitRefreshSec: 15,
|
|
42
|
+
prRefreshSec: 120,
|
|
43
|
+
// On daemon start, resume agents that were running when it stopped (restart, crash, reboot).
|
|
44
|
+
autoResume: true,
|
|
45
|
+
// Partial clone for repo URLs: history now, file contents only when checked out.
|
|
46
|
+
// Much faster for big repos. Set to null for full clones.
|
|
47
|
+
cloneFilter: 'blob:none',
|
|
48
|
+
// Seconds between automatic flushes (scrollback, session IDs, usage, state) to disk.
|
|
49
|
+
flushSec: 30,
|
|
50
|
+
// Ask task agents to keep a brief (Problem / Solution / Diagram / Checks) for the UI.
|
|
51
|
+
brief: true,
|
|
52
|
+
// Backlog: items worked on at once per project (overridable per project), and overall.
|
|
53
|
+
backlogParallel: 2,
|
|
54
|
+
backlogMaxActive: 4,
|
|
55
|
+
// How many one-off Claude calls (documents, Explain, Insights) run at once; the rest queue.
|
|
56
|
+
summaryConcurrency: 2,
|
|
57
|
+
// Model for the Explain button's one-off summary (null = Claude's default).
|
|
58
|
+
explainModel: null,
|
|
59
|
+
// Tell agents to review and follow CLAUDE.md, skills, hooks and settings before working.
|
|
60
|
+
reviewConventions: true,
|
|
61
|
+
// Pre-accept Claude's "trust this folder" prompt for the folders agents run in.
|
|
62
|
+
trustAgentFolders: true,
|
|
63
|
+
// A planning session moves into the repo by itself once Claude has been idle this
|
|
64
|
+
// long and no terminal is attached; otherwise it waits for "Continue in repo".
|
|
65
|
+
handoffIdleSec: 5,
|
|
66
|
+
// The AI judge (stuck, idle screens, reviews); see JUDGE_DEFAULTS in judge.js for every field.
|
|
67
|
+
judge: { enabled: true },
|
|
68
|
+
// Shell used for the ancillary terminal in an agent's folder.
|
|
69
|
+
shell: process.env.SHELL || '/bin/zsh',
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export function ensureHome() {
|
|
73
|
+
for (const dir of [paths.home, paths.workspaces, paths.repos, paths.general, paths.planning, paths.briefs, paths.scrollback]) {
|
|
74
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function loadConfig() {
|
|
79
|
+
let user = {};
|
|
80
|
+
try {
|
|
81
|
+
user = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (err.code !== 'ENOENT') throw new Error(`Invalid ${paths.config}: ${err.message}`);
|
|
84
|
+
}
|
|
85
|
+
return { ...DEFAULTS, ...user };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Merges `patch` into config.json (top-level keys; objects are merged one level deep). */
|
|
89
|
+
export function saveConfig(patch) {
|
|
90
|
+
let user = {};
|
|
91
|
+
try {
|
|
92
|
+
user = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
|
|
93
|
+
} catch (err) {
|
|
94
|
+
if (err.code !== 'ENOENT') throw new Error(`Invalid ${paths.config}: ${err.message}`);
|
|
95
|
+
}
|
|
96
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
97
|
+
user[k] = v && typeof v === 'object' && !Array.isArray(v) && user[k] && typeof user[k] === 'object' ? { ...user[k], ...v } : v;
|
|
98
|
+
}
|
|
99
|
+
fs.mkdirSync(path.dirname(paths.config), { recursive: true });
|
|
100
|
+
fs.writeFileSync(paths.config, `${JSON.stringify(user, null, 2)}\n`);
|
|
101
|
+
return user;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function expandHome(p) {
|
|
105
|
+
if (!p) return p;
|
|
106
|
+
if (p === '~') return os.homedir();
|
|
107
|
+
if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2));
|
|
108
|
+
return p;
|
|
109
|
+
}
|
package/src/conflicts.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Conflict radar: agents working in the same repository that change the same files.
|
|
2
|
+
// Pure functions over each agent's change set (see git.changes), so it is cheap to
|
|
3
|
+
// recompute whenever any agent's changes move.
|
|
4
|
+
|
|
5
|
+
const SLACK = 3; // lines: edits this close together usually conflict when merged
|
|
6
|
+
|
|
7
|
+
/** Repository identity: agents sharing a clone (or a source folder) can step on each other. */
|
|
8
|
+
export function repoKey(agent) {
|
|
9
|
+
return agent.sourceDir || agent.repo || null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const overlaps = (a, b) => a.some(([s1, e1]) => b.some(([s2, e2]) => s1 <= e2 + SLACK && s2 <= e1 + SLACK));
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* entries: [{ agent, changes: { files }, baseSha }]. Returns Map agentId -> [conflict], where
|
|
16
|
+
* conflict = { file, severity: 'lines' | 'file', with: { id, name }, mergeFirst: id }.
|
|
17
|
+
* 'lines' means both edit the same region (likely merge conflict); 'file' only the same file.
|
|
18
|
+
*/
|
|
19
|
+
export function findConflicts(entries) {
|
|
20
|
+
const out = new Map();
|
|
21
|
+
const groups = new Map();
|
|
22
|
+
for (const e of entries) {
|
|
23
|
+
const key = repoKey(e.agent);
|
|
24
|
+
if (!key || !e.changes) continue;
|
|
25
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
26
|
+
groups.get(key).push(e);
|
|
27
|
+
}
|
|
28
|
+
for (const group of groups.values()) {
|
|
29
|
+
for (let i = 0; i < group.length; i++) {
|
|
30
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
31
|
+
const a = group[i];
|
|
32
|
+
const b = group[j];
|
|
33
|
+
if (related(a.agent, b.agent)) continue;
|
|
34
|
+
const shared = Object.keys(a.changes.files).filter((f) => b.changes.files[f]);
|
|
35
|
+
if (!shared.length) continue;
|
|
36
|
+
const first = mergeFirst(a, b, shared);
|
|
37
|
+
for (const file of shared) {
|
|
38
|
+
const fa = a.changes.files[file];
|
|
39
|
+
const fb = b.changes.files[file];
|
|
40
|
+
// Line numbers are only comparable when both branched from the same commit.
|
|
41
|
+
const severity = a.baseSha && a.baseSha === b.baseSha && overlaps(fa.ranges, fb.ranges) ? 'lines' : 'file';
|
|
42
|
+
push(out, a.agent.id, { file, severity, with: { id: b.agent.id, name: b.agent.name }, mergeFirst: first });
|
|
43
|
+
push(out, b.agent.id, { file, severity, with: { id: a.agent.id, name: a.agent.name }, mergeFirst: first });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
for (const list of out.values()) list.sort((x, y) => (x.severity === y.severity ? x.file.localeCompare(y.file) : x.severity === 'lines' ? -1 : 1));
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Attempts of one race, or a fork and its source, are meant to touch the same code. */
|
|
53
|
+
export function related(x, y) {
|
|
54
|
+
if (x.raceId && x.raceId === y.raceId) return true;
|
|
55
|
+
return x.forkOf?.agentId === y.id || y.forkOf?.agentId === x.id || (x.forkOf && x.forkOf.agentId === y.forkOf?.agentId);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function push(map, id, c) {
|
|
59
|
+
if (!map.has(id)) map.set(id, []);
|
|
60
|
+
map.get(id).push(c);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const prRank = (agent) => {
|
|
64
|
+
const states = Object.values(agent.prs ?? {}).map((p) => p.state);
|
|
65
|
+
return states.includes('MERGED') ? 0 : states.includes('OPEN') ? 1 : 2;
|
|
66
|
+
};
|
|
67
|
+
const churn = (e, files) => files.reduce((n, f) => n + (e.changes.files[f].added ?? 0) + (e.changes.files[f].removed ?? 0), 0);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Which of two agents should land first: one whose PR is merged or open goes first; otherwise
|
|
71
|
+
* the one with the smaller change in the shared files (cheaper for the other to rebase onto).
|
|
72
|
+
*/
|
|
73
|
+
export function mergeFirst(a, b, shared) {
|
|
74
|
+
const ra = prRank(a.agent);
|
|
75
|
+
const rb = prRank(b.agent);
|
|
76
|
+
if (ra !== rb) return ra < rb ? a.agent.id : b.agent.id;
|
|
77
|
+
return churn(a, shared) <= churn(b, shared) ? a.agent.id : b.agent.id;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Summary per agent for the UI: files grouped by the other agent. */
|
|
81
|
+
export function summarize(list = []) {
|
|
82
|
+
const byAgent = new Map();
|
|
83
|
+
for (const c of list) {
|
|
84
|
+
if (!byAgent.has(c.with.id)) byAgent.set(c.with.id, { agent: c.with, files: [], lines: 0, mergeFirst: c.mergeFirst });
|
|
85
|
+
const g = byAgent.get(c.with.id);
|
|
86
|
+
g.files.push({ file: c.file, severity: c.severity });
|
|
87
|
+
if (c.severity === 'lines') g.lines++;
|
|
88
|
+
}
|
|
89
|
+
return [...byAgent.values()];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The message an agent gets when told about an overlap (with the AI judge's reason and advice when it has them). */
|
|
93
|
+
export function conflictMessage(self, group) {
|
|
94
|
+
const files = group.files.map((f) => `${f.file}${f.severity === 'lines' ? ' (same lines)' : ''}`).join(', ');
|
|
95
|
+
const what = files ? `is changing the same files as you in this repository: ${files}.` : `is working on related code in this repository.`;
|
|
96
|
+
const order =
|
|
97
|
+
group.mergeFirst === self.id
|
|
98
|
+
? `Agent Manager suggests your change lands first; ${group.agent.name} will rebase onto it.`
|
|
99
|
+
: `Agent Manager suggests ${group.agent.name}'s change lands first: when it does, rebase onto it and resolve the overlap.`;
|
|
100
|
+
const ai = group.ai?.reason ? ` Why this matters: ${group.ai.reason}${group.ai.advice ? ` ${group.ai.advice}` : ''}` : '';
|
|
101
|
+
return (
|
|
102
|
+
`Heads-up from Agent Manager: another agent, ${group.agent.name}, ${what} ${order}${ai} ` +
|
|
103
|
+
`Keep your edits in those files focused, avoid unrelated reformatting there, and mention the overlap in your PR description.`
|
|
104
|
+
);
|
|
105
|
+
}
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// Google's Antigravity CLI (`agy`) as an agent engine (checked against agy 1.4.3; fixtures in
|
|
2
|
+
// test/fixtures/antigravity). It replaced Gemini CLI for personal Google accounts. Differences
|
|
3
|
+
// from Claude Code that shape this adapter:
|
|
4
|
+
// - agy picks its own conversation IDs; the manager adopts the one it creates. agy keeps
|
|
5
|
+
// the latest conversation per folder in cache/last_conversations.json.
|
|
6
|
+
// - Each conversation's log is brain/<id>/.system_generated/logs/transcript_full.jsonl:
|
|
7
|
+
// one record per step (USER_INPUT, PLANNER_RESPONSE with tool_calls and token counts,
|
|
8
|
+
// GENERIC with each tool's result).
|
|
9
|
+
// - No flag for extra instructions: they go in the first message of a new conversation.
|
|
10
|
+
// - Token counts but no cost figure.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { norm, tailOf } from '../stuck.js';
|
|
15
|
+
import { extractRefs } from '../tracker.js';
|
|
16
|
+
|
|
17
|
+
// ANTIGRAVITY_CLI_HOME is Agent Manager's own override (tests); agy itself always uses this folder.
|
|
18
|
+
const home = () => process.env.ANTIGRAVITY_CLI_HOME || path.join(os.homedir(), '.gemini', 'antigravity-cli');
|
|
19
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
20
|
+
const transcript = (id) => path.join(home(), 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
|
|
21
|
+
const real = (p) => {
|
|
22
|
+
try {
|
|
23
|
+
return fs.realpathSync(p);
|
|
24
|
+
} catch {
|
|
25
|
+
return path.resolve(p);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
const ANSI = /\x1b(\[[0-9;?<>=]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|[()][0-9A-B]|[=>78c])/g;
|
|
29
|
+
|
|
30
|
+
function readJson(file) {
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Read the complete lines added since the cursor's offset. */
|
|
39
|
+
function newRecords(file, cursor) {
|
|
40
|
+
let fd;
|
|
41
|
+
try {
|
|
42
|
+
fd = fs.openSync(file, 'r');
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const { size, mtime } = fs.fstatSync(fd);
|
|
48
|
+
cursor.lastActivity = mtime.toISOString();
|
|
49
|
+
if (size < cursor.offset) cursor.offset = 0;
|
|
50
|
+
if (size === cursor.offset) return [];
|
|
51
|
+
const buf = Buffer.alloc(size - cursor.offset);
|
|
52
|
+
fs.readSync(fd, buf, 0, buf.length, cursor.offset);
|
|
53
|
+
const lastNl = buf.lastIndexOf(0x0a);
|
|
54
|
+
if (lastNl < 0) return [];
|
|
55
|
+
cursor.offset += lastNl + 1;
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const line of buf.subarray(0, lastNl).toString('utf8').split('\n')) {
|
|
58
|
+
if (!line) continue;
|
|
59
|
+
try {
|
|
60
|
+
out.push(JSON.parse(line));
|
|
61
|
+
} catch {}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
} finally {
|
|
65
|
+
fs.closeSync(fd);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The user's words without agy's wrapper (<USER_REQUEST>, metadata, settings notes). */
|
|
70
|
+
const userText = (step) => {
|
|
71
|
+
const s = String(step.content ?? '');
|
|
72
|
+
return (/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(s)?.[1] ?? s).trim();
|
|
73
|
+
};
|
|
74
|
+
const calls = (step) => (Array.isArray(step.tool_calls) ? step.tool_calls : []);
|
|
75
|
+
const commandOf = (call) => String(call?.args?.CommandLine ?? call?.args?.command ?? '');
|
|
76
|
+
const fileOf = (call) => {
|
|
77
|
+
const a = call?.args ?? {};
|
|
78
|
+
return String(a.Path ?? a.TargetFile ?? a.AbsolutePath ?? a.path ?? '') || null;
|
|
79
|
+
};
|
|
80
|
+
const isEdit = (call) => Boolean(fileOf(call)) && /write|edit|replace|create|patch/i.test(String(call?.name ?? ''));
|
|
81
|
+
/** A tool result: "Command exited with code N.\n\nCommand output:\n...". */
|
|
82
|
+
const exitCode = (text) => {
|
|
83
|
+
const m = /Command exited with code (-?\d+)/.exec(text);
|
|
84
|
+
return m ? Number(m[1]) : null;
|
|
85
|
+
};
|
|
86
|
+
const outputOf = (text) => text.split(/\nCommand output:\n/)[1] ?? '';
|
|
87
|
+
|
|
88
|
+
/** agy's modes. Default asks before commands and file changes; the hub never starts the last one. */
|
|
89
|
+
const MODES = {
|
|
90
|
+
default: [],
|
|
91
|
+
acceptEdits: ['--mode', 'accept-edits'],
|
|
92
|
+
plan: ['--mode', 'plan'],
|
|
93
|
+
auto: ['--mode', 'auto'],
|
|
94
|
+
bypassPermissions: ['--dangerously-skip-permissions'],
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export default {
|
|
98
|
+
id: 'antigravity',
|
|
99
|
+
label: 'Antigravity',
|
|
100
|
+
supports: { chooseSessionId: false, cost: false, planHandoff: false, fork: false, oneShot: true },
|
|
101
|
+
permissionModes: Object.keys(MODES),
|
|
102
|
+
// Rules files it reads (agy also reads GEMINI.md), for the conventions note.
|
|
103
|
+
rulesFiles: ['AGENTS.md', 'GEMINI.md'],
|
|
104
|
+
|
|
105
|
+
bin: (config) => config.engines?.antigravity?.bin ?? 'agy',
|
|
106
|
+
extraArgs: (config) => [...(config.engines?.antigravity?.args ?? [])],
|
|
107
|
+
|
|
108
|
+
/** Full arguments for a launch. Instructions go in the first message; resume is --conversation. */
|
|
109
|
+
launchArgs({ extra = [], permissionMode, model, writableDir, instructions, sessionId, resume, prompt }) {
|
|
110
|
+
const opts = [...extra, ...(MODES[permissionMode] ?? MODES.default)];
|
|
111
|
+
if (model) opts.push('--model', model);
|
|
112
|
+
if (writableDir) opts.push('--add-dir', writableDir);
|
|
113
|
+
// "--flag=value" so a message starting with "-" isn't read as a flag.
|
|
114
|
+
if (resume) return ['--conversation', sessionId, ...opts, ...(prompt ? [`--prompt-interactive=${prompt}`] : [])];
|
|
115
|
+
const first = [instructions, prompt && (instructions ? `Your task:\n${prompt}` : prompt)].filter(Boolean).join('\n\n---\n\n');
|
|
116
|
+
return [...opts, ...(first ? [`--prompt-interactive=${first}`] : [])];
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
sessionFile: (cwd, sessionId) => transcript(UUID.test(String(sessionId)) ? sessionId : 'missing'),
|
|
120
|
+
hasSession: (cwd, sessionId) => UUID.test(String(sessionId)) && fs.existsSync(transcript(sessionId)),
|
|
121
|
+
subagentFiles: () => [],
|
|
122
|
+
|
|
123
|
+
/** The conversation agy started in this folder since a time; the manager adopts a new one. */
|
|
124
|
+
recentSessions(cwd, sinceMs) {
|
|
125
|
+
const want = real(cwd);
|
|
126
|
+
const map = readJson(path.join(home(), 'cache', 'last_conversations.json')) ?? {};
|
|
127
|
+
const out = [];
|
|
128
|
+
for (const [dir, id] of Object.entries(map)) {
|
|
129
|
+
if (!UUID.test(String(id)) || real(dir) !== want) continue;
|
|
130
|
+
let st;
|
|
131
|
+
try {
|
|
132
|
+
st = fs.statSync(transcript(id));
|
|
133
|
+
} catch {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (st.mtimeMs < sinceMs) continue;
|
|
137
|
+
out.push({ sessionId: id, file: transcript(id), mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs });
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
/** Usage (one entry per model step), PR and bug links from messages and command output. */
|
|
143
|
+
scan(file, cursor, bugPatterns = []) {
|
|
144
|
+
const result = { prs: [], bugs: [], title: null, lastPrompt: null, cost: null, lastActivity: null };
|
|
145
|
+
cursor.usage ??= new Map();
|
|
146
|
+
cursor.offset ??= 0;
|
|
147
|
+
const steps = newRecords(file, cursor);
|
|
148
|
+
result.lastActivity = cursor.lastActivity ?? null;
|
|
149
|
+
if (!steps) return result;
|
|
150
|
+
for (const step of steps) {
|
|
151
|
+
if (step.type === 'PLANNER_RESPONSE' && (step.input_tokens || step.output_tokens)) {
|
|
152
|
+
const cached = step.cache_read_tokens ?? 0;
|
|
153
|
+
// Gemini counts cached tokens inside the prompt tokens; Claude Code counts them apart.
|
|
154
|
+
cursor.usage.set(`s${step.step_index}`, {
|
|
155
|
+
input: Math.max(0, (step.input_tokens ?? 0) - cached),
|
|
156
|
+
output: step.output_tokens ?? 0,
|
|
157
|
+
cacheCreation: 0,
|
|
158
|
+
cacheRead: cached,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const text = step.type === 'USER_INPUT' ? userText(step) : String(step.content ?? '');
|
|
162
|
+
if (step.type === 'USER_INPUT' && step.source === 'USER_EXPLICIT' && text) result.lastPrompt = text.slice(0, 500);
|
|
163
|
+
if (step.type === 'SYSTEM_MESSAGE' || !text) continue;
|
|
164
|
+
const refs = extractRefs(text, bugPatterns);
|
|
165
|
+
result.prs.push(...refs.prs);
|
|
166
|
+
result.bugs.push(...refs.bugs);
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
/** Commands (with the result step that follows) and file writes, for stuck detection. */
|
|
172
|
+
activity(file, state) {
|
|
173
|
+
state.events ??= [];
|
|
174
|
+
state.offset ??= 0;
|
|
175
|
+
const steps = newRecords(file, state);
|
|
176
|
+
if (!steps) return state;
|
|
177
|
+
for (const step of steps) {
|
|
178
|
+
const t = Date.parse(step.created_at ?? '') || Date.now();
|
|
179
|
+
if (step.type === 'PLANNER_RESPONSE') {
|
|
180
|
+
for (const call of calls(step)) {
|
|
181
|
+
if (commandOf(call) && /command/i.test(String(call.name ?? ''))) {
|
|
182
|
+
state.pending = { t, cmd: norm(commandOf(call)).slice(0, 300) };
|
|
183
|
+
} else if (isEdit(call)) {
|
|
184
|
+
const a = call.args ?? {};
|
|
185
|
+
const before = a.TargetContent ?? a.OldString ?? '';
|
|
186
|
+
const after = a.ReplacementContent ?? a.NewString ?? a.Content ?? a.CodeContent ?? '';
|
|
187
|
+
state.events.push({ t, kind: 'edit', file: fileOf(call), edits: after || before ? [[norm(String(before)), norm(String(after))]] : [] });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
} else if (step.type === 'GENERIC' && state.pending) {
|
|
191
|
+
const text = String(step.content ?? '');
|
|
192
|
+
const code = exitCode(text);
|
|
193
|
+
if (code === null && !text.includes('Command output:')) continue;
|
|
194
|
+
const out = outputOf(text);
|
|
195
|
+
state.events.push({ ...state.pending, kind: 'cmd', failed: code !== null && code !== 0, result: tailOf(out), shown: out.replace(/\s+/g, ' ').trim().slice(-160) });
|
|
196
|
+
state.pending = null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (state.events.length > 400) state.events = state.events.slice(-400);
|
|
200
|
+
return state;
|
|
201
|
+
},
|
|
202
|
+
|
|
203
|
+
/** A readable digest of the conversation, for Explain and documents. */
|
|
204
|
+
digest(file, { maxChars = 24_000 } = {}) {
|
|
205
|
+
const events = [];
|
|
206
|
+
const edited = new Set();
|
|
207
|
+
let lastCmd = null;
|
|
208
|
+
for (const step of newRecords(file, { offset: 0 }) ?? []) {
|
|
209
|
+
if (step.type === 'USER_INPUT' && step.source === 'USER_EXPLICIT') events.push(`[user] ${userText(step).slice(0, 1200)}`);
|
|
210
|
+
else if (step.type === 'PLANNER_RESPONSE') {
|
|
211
|
+
if (step.content) events.push(`[agent] ${String(step.content).slice(0, 1800)}`);
|
|
212
|
+
for (const call of calls(step)) {
|
|
213
|
+
if (isEdit(call)) edited.add(fileOf(call)), events.push(`[action] edited ${fileOf(call)}`);
|
|
214
|
+
else if (commandOf(call)) lastCmd = events.push(`[action] ran \`${commandOf(call).slice(0, 200)}\``) - 1;
|
|
215
|
+
}
|
|
216
|
+
} else if (step.type === 'GENERIC' && lastCmd !== null) {
|
|
217
|
+
const code = exitCode(String(step.content ?? ''));
|
|
218
|
+
if (code) events[lastCmd] += ` (exit ${code})`;
|
|
219
|
+
lastCmd = null;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const head = events.find((e) => e.startsWith('[user]'));
|
|
223
|
+
const tail = [];
|
|
224
|
+
let used = head?.length ?? 0;
|
|
225
|
+
for (let i = events.length - 1; i >= 0 && events[i] !== head; i--) {
|
|
226
|
+
if (used + events[i].length > maxChars) {
|
|
227
|
+
tail.unshift('… (earlier events omitted) …');
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
tail.unshift(events[i]);
|
|
231
|
+
used += events[i].length + 1;
|
|
232
|
+
}
|
|
233
|
+
return { digest: [head, ...tail].filter(Boolean).join('\n'), events: events.length, edited: [...edited] };
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
copySession: () => false,
|
|
237
|
+
|
|
238
|
+
attention: [
|
|
239
|
+
[/Doyoutrustthecontentsofthisproject\?/i, 'Folder trust prompt'],
|
|
240
|
+
[/Runthiscommand\?/i, 'Permission prompt'],
|
|
241
|
+
// "Allow creation of this file?", "Allow access to this file?", ...: any Allow question with a menu.
|
|
242
|
+
[/Allow[a-z]{0,40}\?>?1\.Yes/i, 'Permission prompt'],
|
|
243
|
+
],
|
|
244
|
+
|
|
245
|
+
/** agy's menus: "Run this command? > 1. Yes, run command 2. ... 4. No, cancel ↑/↓ Navigate". */
|
|
246
|
+
promptChoices(screen) {
|
|
247
|
+
const text = String(screen ?? '')
|
|
248
|
+
.replace(/\x1b\[(\d*)C/g, ' ')
|
|
249
|
+
.replace(ANSI, ' ')
|
|
250
|
+
.replace(/\s+/g, ' ');
|
|
251
|
+
const cmdAt = text.lastIndexOf('Requesting permission for:');
|
|
252
|
+
const allowAt = [...text.matchAll(/Allow [a-z ]{0,50}\?(?= >? ?1\. )/g)].at(-1)?.index ?? -1;
|
|
253
|
+
const askAt = Math.max(text.lastIndexOf('Run this command?'), allowAt);
|
|
254
|
+
if (askAt < 0) return { question: '', choices: [] };
|
|
255
|
+
const tail = text.slice(askAt);
|
|
256
|
+
let question = (/^(.*?\?)/.exec(tail)?.[1] ?? '').trim();
|
|
257
|
+
if (question === 'Run this command?' && cmdAt >= 0 && cmdAt < askAt) question = `Run this command? ${text.slice(cmdAt + 26, askAt).trim()}`;
|
|
258
|
+
const choices = new Map();
|
|
259
|
+
for (const m of tail.matchAll(/(?:>\s*)?\b(\d)\.\s*(.+?)(?=\s+(?:>\s*)?\d\.\s|\s+↑\/↓|\s+esc to cancel|$)/g)) {
|
|
260
|
+
if (!choices.has(m[1])) choices.set(m[1], m[2].trim().slice(0, 100));
|
|
261
|
+
}
|
|
262
|
+
return { question: question.slice(0, 200), choices: [...choices.entries()].sort(([a], [b]) => a - b).map(([key, label]) => ({ key, label })) };
|
|
263
|
+
},
|
|
264
|
+
|
|
265
|
+
/** Add the folder to agy's trustedWorkspaces (what "Yes, I trust this folder" records). */
|
|
266
|
+
trust(dir) {
|
|
267
|
+
const file = path.join(home(), 'settings.json');
|
|
268
|
+
const want = real(dir);
|
|
269
|
+
let raw = '';
|
|
270
|
+
try {
|
|
271
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
272
|
+
} catch (err) {
|
|
273
|
+
if (err.code !== 'ENOENT') throw err;
|
|
274
|
+
}
|
|
275
|
+
const settings = raw ? JSON.parse(raw) : {};
|
|
276
|
+
const list = Array.isArray(settings.trustedWorkspaces) ? settings.trustedWorkspaces : [];
|
|
277
|
+
if (list.some((w) => typeof w === 'string' && (want === real(w) || want.startsWith(real(w) + path.sep)))) return false;
|
|
278
|
+
const backup = `${file}.agentmgr-backup`;
|
|
279
|
+
if (raw && !fs.existsSync(backup)) fs.writeFileSync(backup, raw, { mode: 0o600 });
|
|
280
|
+
settings.trustedWorkspaces = [...list, want];
|
|
281
|
+
fs.mkdirSync(home(), { recursive: true });
|
|
282
|
+
const tmp = `${file}.agentmgr-${process.pid}`;
|
|
283
|
+
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n', { mode: 0o600 });
|
|
284
|
+
fs.renameSync(tmp, file);
|
|
285
|
+
return true;
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* One-shot in print mode, in plan mode: print mode can't ask for permission, so commands
|
|
290
|
+
* and file changes are refused. The prompt is attached to the flag (agy doesn't read stdin).
|
|
291
|
+
*/
|
|
292
|
+
oneShotArgs: (config, { model, prompt = '' } = {}) => ['--mode', 'plan', ...(model ? ['--model', model] : []), '--print-timeout', '280s', `--print=${prompt}`],
|
|
293
|
+
oneShotStdin: false,
|
|
294
|
+
|
|
295
|
+
stripEnv: [],
|
|
296
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Claude Code as an agent engine: how to launch and resume it, where its sessions live,
|
|
2
|
+
// and how to read them. Other engines implement the same shape (see docs/engines.md).
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { promptChoices } from '../inbox.js';
|
|
6
|
+
import { scanActivity } from '../stuck.js';
|
|
7
|
+
import { recentSessionFiles, scanTranscript, sessionDigest, subagentTranscripts, transcriptPath } from '../tracker.js';
|
|
8
|
+
import { trustFolder } from '../trust.js';
|
|
9
|
+
|
|
10
|
+
export default {
|
|
11
|
+
id: 'claude',
|
|
12
|
+
label: 'Claude Code',
|
|
13
|
+
// What the UI may offer for this engine's agents.
|
|
14
|
+
supports: { chooseSessionId: true, cost: true, planHandoff: true, fork: true, oneShot: true },
|
|
15
|
+
permissionModes: ['default', 'acceptEdits', 'plan', 'auto', 'bypassPermissions'],
|
|
16
|
+
|
|
17
|
+
bin: (config) => config.engines?.claude?.bin ?? config.claudeBin ?? 'claude',
|
|
18
|
+
extraArgs: (config) => [...(config.engines?.claude?.args ?? config.claudeArgs ?? [])],
|
|
19
|
+
|
|
20
|
+
/** Options for every launch: permissions, model, a folder it may write to, extra instructions. */
|
|
21
|
+
optionArgs({ permissionMode, model, writableDir, instructions }) {
|
|
22
|
+
const args = [];
|
|
23
|
+
if (permissionMode && permissionMode !== 'default') args.push('--permission-mode', permissionMode);
|
|
24
|
+
if (model) args.push('--model', model);
|
|
25
|
+
if (writableDir) args.push('--add-dir', writableDir, '--allowedTools', `Write(/${writableDir}/**)`, `Edit(/${writableDir}/**)`);
|
|
26
|
+
if (instructions) args.push('--append-system-prompt', instructions);
|
|
27
|
+
return args;
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
/** Full arguments for a launch: options, then the session. */
|
|
31
|
+
launchArgs({ extra = [], permissionMode, model, writableDir, instructions, sessionId, resume, name, prompt }) {
|
|
32
|
+
return [...extra, ...this.optionArgs({ permissionMode, model, writableDir, instructions }), ...this.sessionArgs({ sessionId, resume, name, prompt })];
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
/** A new session under the ID we chose, or a resumed one; prompt is the first (or next) message. */
|
|
36
|
+
sessionArgs({ sessionId, resume, name, prompt }) {
|
|
37
|
+
const args = resume ? ['--resume', sessionId] : ['--session-id', sessionId, '--name', name];
|
|
38
|
+
if (prompt) args.push('--', prompt);
|
|
39
|
+
return args;
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
sessionFile: (cwd, sessionId) => transcriptPath(cwd, sessionId),
|
|
43
|
+
hasSession: (cwd, sessionId) => fs.existsSync(transcriptPath(cwd, sessionId)),
|
|
44
|
+
subagentFiles: (cwd, sessionId) => subagentTranscripts(cwd, sessionId),
|
|
45
|
+
/** Sessions started in this folder since a time (Claude may switch IDs mid-run, e.g. /clear). */
|
|
46
|
+
recentSessions: (cwd, sinceMs) => recentSessionFiles(cwd, sinceMs),
|
|
47
|
+
|
|
48
|
+
/** Incremental read of a session log: usage, cost, PR and bug links. */
|
|
49
|
+
scan: (file, cursor, bugPatterns) => scanTranscript(file, cursor, bugPatterns),
|
|
50
|
+
/** Tool calls and results, for stuck detection. */
|
|
51
|
+
activity: (file, state) => scanActivity(file, state),
|
|
52
|
+
/** A readable digest of the conversation, for Explain and documents. */
|
|
53
|
+
digest: (file) => sessionDigest(file),
|
|
54
|
+
|
|
55
|
+
/** Copy a session into another folder (planning handoff), optionally as a new session (fork). */
|
|
56
|
+
copySession({ fromCwd, toCwd, fromId, toId = fromId, bytes }) {
|
|
57
|
+
const from = transcriptPath(fromCwd, fromId);
|
|
58
|
+
const to = transcriptPath(toCwd, toId);
|
|
59
|
+
if (!fs.existsSync(from) || fs.existsSync(to)) return false;
|
|
60
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
61
|
+
if (toId === fromId && !bytes) {
|
|
62
|
+
fs.copyFileSync(from, to);
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
const raw = fs.readFileSync(from).subarray(0, bytes || undefined).toString('utf8');
|
|
66
|
+
const lines = raw.split('\n').filter(Boolean).map((line) => {
|
|
67
|
+
try {
|
|
68
|
+
const rec = JSON.parse(line);
|
|
69
|
+
if (rec.sessionId) rec.sessionId = toId;
|
|
70
|
+
if (rec.cwd === fromCwd) rec.cwd = toCwd;
|
|
71
|
+
return JSON.stringify(rec);
|
|
72
|
+
} catch {
|
|
73
|
+
return line;
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
fs.writeFileSync(to, `${lines.join('\n')}\n`);
|
|
77
|
+
return true;
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
/** Screens that need the user (whitespace removed before matching). */
|
|
81
|
+
attention: [
|
|
82
|
+
[/trustthisfolder/i, 'Folder trust prompt'],
|
|
83
|
+
[/Doyouwantto(proceed|make|create|allow|run|overwrite)/i, 'Permission prompt'],
|
|
84
|
+
],
|
|
85
|
+
promptChoices: (screen) => promptChoices(screen),
|
|
86
|
+
|
|
87
|
+
trust: (dir) => trustFolder(dir),
|
|
88
|
+
|
|
89
|
+
/** A one-shot, tool-less call; the prompt goes on stdin and the answer comes back as text. */
|
|
90
|
+
oneShotArgs: (config, { model } = {}) => {
|
|
91
|
+
const args = ['-p', '--tools', '', '--strict-mcp-config', '--no-session-persistence', '--output-format', 'text'];
|
|
92
|
+
if (model) args.push('--model', model);
|
|
93
|
+
return args;
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
/** Variables a nested Claude session would otherwise inherit from a parent one. */
|
|
97
|
+
stripEnv: ['CLAUDECODE', 'CLAUDE_CODE_CHILD_SESSION', 'CLAUDE_CODE_ENTRYPOINT'],
|
|
98
|
+
};
|