convergedev 0.0.0-stage → 0.1.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.md +34 -0
- package/THIRD_PARTY_NOTICES.md +149 -0
- package/dist/agent-execution.js +103 -0
- package/dist/agent-process.js +70 -0
- package/dist/agent.js +2 -0
- package/dist/anchors.js +101 -0
- package/dist/applications.js +69 -0
- package/dist/apply-proposal.js +236 -0
- package/dist/bridge-health.js +57 -0
- package/dist/bridge.js +203 -0
- package/dist/change-proposals.js +51 -0
- package/dist/claude.js +277 -0
- package/dist/cli.js +278 -0
- package/dist/commands.js +80 -0
- package/dist/comment-file.js +41 -0
- package/dist/comment-host.js +96 -0
- package/dist/config.js +43 -0
- package/dist/converge.js +36 -0
- package/dist/exec.js +52 -0
- package/dist/follow-branch.js +70 -0
- package/dist/git.js +169 -0
- package/dist/hunks.js +558 -0
- package/dist/implementation-results.js +98 -0
- package/dist/implementation-runner.js +262 -0
- package/dist/queries/ecmascript.scm +35 -0
- package/dist/queries/javascript.scm +6 -0
- package/dist/queries/python.scm +10 -0
- package/dist/queries/typescript.scm +16 -0
- package/dist/relay.js +32 -0
- package/dist/runner.js +104 -0
- package/dist/sandbox.js +53 -0
- package/dist/session-state.js +36 -0
- package/dist/setup.js +328 -0
- package/dist/share-review.js +34 -0
- package/dist/shared.js +193 -0
- package/dist/skill/converge/SKILL.md +25 -0
- package/dist/skill/converge/converge.mjs +35 -0
- package/dist/skill-link.js +100 -0
- package/dist/worktree.js +231 -0
- package/grammars/SOURCES.json +22 -0
- package/grammars/tree-sitter-javascript.wasm +0 -0
- package/grammars/tree-sitter-python.wasm +0 -0
- package/grammars/tree-sitter-tsx.wasm +0 -0
- package/grammars/tree-sitter-typescript.wasm +0 -0
- package/package.json +45 -4
- package/README.md +0 -3
package/dist/claude.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { SKILL_LIMITS } from './agent.js';
|
|
2
|
+
import { describeCommand, findExecutable } from './exec.js';
|
|
3
|
+
import { idleTimeoutMs, probe, runProcess } from './runner.js';
|
|
4
|
+
import { loadSessionId, saveSessionId } from './session-state.js';
|
|
5
|
+
export const OVERRIDE_ENV = 'AGENT_REVIEW_CLAUDE';
|
|
6
|
+
/** Claude Code's official installation guide, named wherever it is missing (here, and `converge` and its doctor). */
|
|
7
|
+
export const CLAUDE_SETUP_DOCS = 'https://code.claude.com/docs/en/setup';
|
|
8
|
+
const LOOKUP = {
|
|
9
|
+
name: 'claude',
|
|
10
|
+
npmPackage: '@anthropic-ai/claude-code',
|
|
11
|
+
shimTargets: ['bin/claude.exe', 'cli.js'], // native binary (2.1.x+), then the older node entry point
|
|
12
|
+
extraDirs: ['~/.local/bin', '~/AppData/Roaming/npm', '/opt/homebrew/bin', '/usr/local/bin'],
|
|
13
|
+
};
|
|
14
|
+
/** The claude executable: AGENT_REVIEW_CLAUDE if set, else the one on PATH or in the usual install folders. */
|
|
15
|
+
export const findClaude = () => findExecutable({ ...LOOKUP, override: process.env[OVERRIDE_ENV] });
|
|
16
|
+
/**
|
|
17
|
+
* Environment for the claude process. CLAUDECODE is set by an enclosing Claude Code session (e.g. the
|
|
18
|
+
* /converge skill); the CLI refuses to start "nested" with it, but this child is an independent headless session.
|
|
19
|
+
*/
|
|
20
|
+
function childEnv() {
|
|
21
|
+
const { CLAUDECODE: _nested, ...env } = process.env;
|
|
22
|
+
return env;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The only variables a write-capable run gets (docs/review-room.md, decision 17): what Claude Code needs to start, find
|
|
26
|
+
* its config, authenticate with Anthropic (an API key, an auth token or an OAuth token; on macOS the login is in the
|
|
27
|
+
* keychain) and reach the API through a proxy, and nothing else. Exact names, never prefixes: an enclosing Claude Code
|
|
28
|
+
* session exports its own CLAUDE_CODE_* internals, a messaging token among them. Cloud credentials (so Bedrock and
|
|
29
|
+
* Vertex too), GitHub and npm tokens, SSH_AUTH_SOCK and Converge's own variables stay out. Ask keeps the whole
|
|
30
|
+
* environment (`childEnv`): it is read-only and runs as the developer always has.
|
|
31
|
+
*/
|
|
32
|
+
export const IMPLEMENTATION_ENV = [
|
|
33
|
+
'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'TZ',
|
|
34
|
+
'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME',
|
|
35
|
+
'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_CUSTOM_HEADERS', 'ANTHROPIC_MODEL',
|
|
36
|
+
'ANTHROPIC_SMALL_FAST_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
37
|
+
'CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CONFIG_DIR',
|
|
38
|
+
'HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR',
|
|
39
|
+
'DISABLE_TELEMETRY', 'DISABLE_ERROR_REPORTING', 'DISABLE_AUTOUPDATER', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
|
|
40
|
+
];
|
|
41
|
+
/** The environment of a write-capable run: `IMPLEMENTATION_ENV` from `source`, and the run's own temporary folder. */
|
|
42
|
+
export function implementationEnv(source, tempDir) {
|
|
43
|
+
const env = {};
|
|
44
|
+
for (const name of IMPLEMENTATION_ENV)
|
|
45
|
+
if (source[name] !== undefined)
|
|
46
|
+
env[name] = source[name];
|
|
47
|
+
return { ...env, TMPDIR: tempDir, TMP: tempDir, TEMP: tempDir };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Claude Code's own setup and scheduling skills, and this tool's: nothing a reviewer starts a question with, and they
|
|
51
|
+
* cannot do their job in a headless read-only run.
|
|
52
|
+
*/
|
|
53
|
+
const NOT_FOR_THE_ROOM = new Set(['converge', 'update-config', 'fewer-permission-prompts', 'doctor', 'loop', 'schedule']);
|
|
54
|
+
/**
|
|
55
|
+
* The skills listed in the `system`/`init` line Claude Code prints first, within the relay's limits; undefined for
|
|
56
|
+
* any other line. An init line without a list (an older CLI) gives an empty one, so the caller can stop there.
|
|
57
|
+
*/
|
|
58
|
+
export function parseSkills(line) {
|
|
59
|
+
let item;
|
|
60
|
+
try {
|
|
61
|
+
item = JSON.parse(line);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
if (item?.type !== 'system' || item.subtype !== 'init')
|
|
67
|
+
return undefined;
|
|
68
|
+
if (!Array.isArray(item.skills))
|
|
69
|
+
return [];
|
|
70
|
+
return item.skills
|
|
71
|
+
.filter((name) => typeof name === 'string' && name.length <= SKILL_LIMITS.nameChars && !NOT_FOR_THE_ROOM.has(name))
|
|
72
|
+
.slice(0, SKILL_LIMITS.count);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* An implementation run may edit files in its worktree and nothing else, enforced twice (docs/review-room.md, decision
|
|
76
|
+
* 17). Claude Code's restricted mode confines its file tools to the working directory, removes the tools that run
|
|
77
|
+
* code, refuses edits to settings, git and tool-configuration files, and ignores the developer's settings files, so
|
|
78
|
+
* an allow rule there cannot widen it; acceptEdits approves the edits that remain. The tools below are refused as
|
|
79
|
+
* well (WebSearch is not code-running), and no MCP server starts (--strict-mcp-config with none given). Around the
|
|
80
|
+
* process, the operating system refuses writes outside the worktree whatever the agent does (sandbox.ts).
|
|
81
|
+
*/
|
|
82
|
+
export const IMPLEMENTATION_REFUSED_TOOLS = ['Bash', 'PowerShell', 'WebFetch', 'WebSearch'];
|
|
83
|
+
/** A tool the agent used, as a progress line: "Editing src/cart.ts". Only the tool and file, never its input. */
|
|
84
|
+
export function describeTool(name, input) {
|
|
85
|
+
const file = typeof input?.file_path === 'string' ? input.file_path : undefined;
|
|
86
|
+
const verb = { Edit: 'Editing', MultiEdit: 'Editing', Write: 'Writing', Read: 'Reading', NotebookEdit: 'Editing' }[name];
|
|
87
|
+
return verb && file ? `${verb} ${file}` : `Using ${name}`;
|
|
88
|
+
}
|
|
89
|
+
/** What one line of `--output-format stream-json` means to the bridge; everything else is ignored. */
|
|
90
|
+
export function parseLine(line) {
|
|
91
|
+
let item;
|
|
92
|
+
try {
|
|
93
|
+
item = JSON.parse(line);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return undefined;
|
|
97
|
+
} // non-JSON CLI chatter
|
|
98
|
+
if (item?.type === 'stream_event' && item.event?.type === 'content_block_delta' &&
|
|
99
|
+
item.event.delta?.type === 'text_delta' && typeof item.event.delta.text === 'string') {
|
|
100
|
+
return { type: 'text', text: item.event.delta.text };
|
|
101
|
+
}
|
|
102
|
+
if (item?.type === 'assistant' && Array.isArray(item.message?.content)) {
|
|
103
|
+
const use = item.message.content.find((block) => block?.type === 'tool_use' && typeof block.name === 'string');
|
|
104
|
+
if (use)
|
|
105
|
+
return { type: 'tool', name: use.name, input: use.input };
|
|
106
|
+
}
|
|
107
|
+
if (item?.type === 'result') {
|
|
108
|
+
if (item.is_error)
|
|
109
|
+
return { type: 'result', error: typeof item.result === 'string' && item.result ? item.result : 'Claude reported an error' };
|
|
110
|
+
return { type: 'result', text: typeof item.result === 'string' ? item.result : undefined };
|
|
111
|
+
}
|
|
112
|
+
if (item?.type === 'system' && typeof item.session_id === 'string')
|
|
113
|
+
return { type: 'session', id: item.session_id };
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
export class ClaudeCodeAdapter {
|
|
117
|
+
cmd;
|
|
118
|
+
room;
|
|
119
|
+
projectDir;
|
|
120
|
+
statePath;
|
|
121
|
+
context;
|
|
122
|
+
provider = 'claude_code';
|
|
123
|
+
label = 'Claude Code';
|
|
124
|
+
sessionId;
|
|
125
|
+
listedSkills;
|
|
126
|
+
constructor(cmd, room, projectDir, statePath, context) {
|
|
127
|
+
this.cmd = cmd;
|
|
128
|
+
this.room = room;
|
|
129
|
+
this.projectDir = projectDir;
|
|
130
|
+
this.statePath = statePath;
|
|
131
|
+
this.context = context;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Resolves and smoke-tests the CLI up front, so a missing or broken install fails the connect with the cause in
|
|
135
|
+
* the bridge output rather than failing every prompt in the room. `context` supplies room/review instructions,
|
|
136
|
+
* appended to Claude's system prompt on every run.
|
|
137
|
+
*/
|
|
138
|
+
static async create(room, projectDir, statePath, context) {
|
|
139
|
+
const override = process.env[OVERRIDE_ENV];
|
|
140
|
+
const cmd = findClaude();
|
|
141
|
+
if (!cmd) {
|
|
142
|
+
throw new Error(`Claude Code CLI not found ${override ? `at ${OVERRIDE_ENV}=${override}` : 'on PATH'}. ` +
|
|
143
|
+
`Install it (${CLAUDE_SETUP_DOCS}) or set ${OVERRIDE_ENV} to the claude executable.`);
|
|
144
|
+
}
|
|
145
|
+
const version = await probe(cmd, ['--version'], childEnv())
|
|
146
|
+
.then((out) => out.replace(/\s*\(Claude Code\)$/, ''))
|
|
147
|
+
.catch((err) => { throw new Error(`${describeCommand(cmd)} --version failed: ${err.message}`); });
|
|
148
|
+
console.log(`Using Claude Code ${version} (${describeCommand(cmd)})`);
|
|
149
|
+
const adapter = new ClaudeCodeAdapter(cmd, room, projectDir, statePath, context);
|
|
150
|
+
adapter.sessionId = await loadSessionId(statePath, room, projectDir);
|
|
151
|
+
if (adapter.sessionId)
|
|
152
|
+
console.log(`Resuming saved Claude session ${adapter.sessionId}`);
|
|
153
|
+
return adapter;
|
|
154
|
+
}
|
|
155
|
+
async run(job, send, signal) {
|
|
156
|
+
console.log(`[${new Date().toISOString()}] Received prompt ${job.id}: ${job.content}`);
|
|
157
|
+
// A skill runs only when its /name starts the prompt, so a slash command goes unprefixed. Only the member who owns
|
|
158
|
+
// this agent can ask it (docs/review-room.md), so the name adds little there.
|
|
159
|
+
const prompt = job.author && !job.content.startsWith('/') ? `[${job.author}] ${job.content}` : job.content;
|
|
160
|
+
// The prompt goes to stdin: no shell quoting and no command-line length limit.
|
|
161
|
+
const args = ['-p', '--permission-mode', 'plan', '--max-turns', '5',
|
|
162
|
+
'--output-format', 'stream-json', '--verbose', '--include-partial-messages'];
|
|
163
|
+
if (this.sessionId)
|
|
164
|
+
args.push('--resume', this.sessionId);
|
|
165
|
+
const systemContext = await this.context?.().catch((err) => { console.warn('Room context unavailable:', err.message); return undefined; });
|
|
166
|
+
if (systemContext)
|
|
167
|
+
args.push('--append-system-prompt', systemContext);
|
|
168
|
+
let fullText = '';
|
|
169
|
+
let streamed = false;
|
|
170
|
+
let nextSessionId;
|
|
171
|
+
let resultError;
|
|
172
|
+
const idleMs = idleTimeoutMs();
|
|
173
|
+
const { exitCode, timedOut, stderr, stopped } = await runProcess(this.cmd, {
|
|
174
|
+
args, stdin: prompt, cwd: this.projectDir, env: childEnv(), idleMs, signal,
|
|
175
|
+
onLine: (line) => {
|
|
176
|
+
const event = parseLine(line);
|
|
177
|
+
if (!event)
|
|
178
|
+
return;
|
|
179
|
+
if (event.type === 'text') {
|
|
180
|
+
fullText += event.text;
|
|
181
|
+
streamed = true;
|
|
182
|
+
send({ type: 'delta', id: job.id, content: event.text });
|
|
183
|
+
}
|
|
184
|
+
else if (event.type === 'session') {
|
|
185
|
+
nextSessionId = event.id; // stored only after a successful run, below
|
|
186
|
+
}
|
|
187
|
+
else if (event.type === 'result') {
|
|
188
|
+
if (event.error)
|
|
189
|
+
resultError = event.error;
|
|
190
|
+
if (!streamed && event.text)
|
|
191
|
+
fullText = event.text;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
// Stopped by the member: the session is left as it was, since this answer never finished.
|
|
196
|
+
if (stopped === 'aborted') {
|
|
197
|
+
send({ type: 'stopped', id: job.id });
|
|
198
|
+
console.log(`Stopped prompt ${job.id}`);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (exitCode !== 0 || resultError) {
|
|
202
|
+
const reason = timedOut
|
|
203
|
+
? `Claude produced no output for ${idleMs / 1000}s and was stopped. Check that \`claude -p\` works in ${this.projectDir}; ` +
|
|
204
|
+
'AGENT_REVIEW_IDLE_TIMEOUT (seconds) raises the limit.'
|
|
205
|
+
: `Claude exited (${exitCode}): ${stderr.slice(0, 500)}`;
|
|
206
|
+
send({ type: 'failure', id: job.id, content: resultError || reason });
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (nextSessionId && nextSessionId !== this.sessionId) {
|
|
210
|
+
this.sessionId = nextSessionId;
|
|
211
|
+
await saveSessionId(this.statePath, this.room, this.projectDir, nextSessionId);
|
|
212
|
+
}
|
|
213
|
+
send({ type: 'result', id: job.id, content: fullText.trim() || '(Claude returned no text)' });
|
|
214
|
+
console.log(`Completed prompt ${job.id} · session ${this.sessionId ?? 'unknown'}`);
|
|
215
|
+
}
|
|
216
|
+
async implement(task) {
|
|
217
|
+
// A fresh session that is not saved: the member's Ask session stays read-only and keeps its own history.
|
|
218
|
+
const args = ['-p', '--no-session-persistence', '--restricted', '--permission-mode', 'acceptEdits',
|
|
219
|
+
'--disallowedTools', ...IMPLEMENTATION_REFUSED_TOOLS, '--strict-mcp-config',
|
|
220
|
+
'--max-turns', String(task.limits.turns), '--output-format', 'stream-json', '--verbose',
|
|
221
|
+
'--append-system-prompt', task.rules];
|
|
222
|
+
let summary = '';
|
|
223
|
+
let resultError;
|
|
224
|
+
const idleMs = idleTimeoutMs();
|
|
225
|
+
// Temporary files go to the run's own folder: the sandbox refuses every other place to write.
|
|
226
|
+
const env = implementationEnv(process.env, task.tempDir);
|
|
227
|
+
const { exitCode, stopped, stderr } = await runProcess(task.sandbox.wrap(this.cmd), {
|
|
228
|
+
args, stdin: task.prompt, cwd: task.cwd, env, idleMs, signal: task.signal,
|
|
229
|
+
deadlineMs: task.limits.deadlineMs, maxOutputBytes: task.limits.maxOutputBytes,
|
|
230
|
+
onLine: (line) => {
|
|
231
|
+
const event = parseLine(line);
|
|
232
|
+
if (event?.type === 'tool')
|
|
233
|
+
task.onProgress(describeTool(event.name, event.input));
|
|
234
|
+
if (event?.type === 'result') {
|
|
235
|
+
if (event.error)
|
|
236
|
+
resultError = event.error;
|
|
237
|
+
else
|
|
238
|
+
summary = event.text ?? '';
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
if (stopped) {
|
|
243
|
+
const reasons = {
|
|
244
|
+
aborted: 'Stopped.',
|
|
245
|
+
deadline: `Your agent ran for over ${Math.round(task.limits.deadlineMs / 60_000)} minutes and was stopped.`,
|
|
246
|
+
idle: `Your agent produced no output for ${idleMs / 1000}s and was stopped.`,
|
|
247
|
+
output: 'Your agent produced too much output and was stopped.',
|
|
248
|
+
};
|
|
249
|
+
return { ok: false, reason: reasons[stopped], stopped };
|
|
250
|
+
}
|
|
251
|
+
if (exitCode !== 0 || resultError)
|
|
252
|
+
return { ok: false, reason: resultError || `Claude exited (${exitCode}): ${stderr.slice(0, 300)}` };
|
|
253
|
+
return { ok: true, summary: summary.trim() };
|
|
254
|
+
}
|
|
255
|
+
/** Listed once per bridge: Claude Code reads skills when it starts, so one added later shows after a restart. */
|
|
256
|
+
skills() {
|
|
257
|
+
this.listedSkills ??= this.listSkills();
|
|
258
|
+
return this.listedSkills;
|
|
259
|
+
}
|
|
260
|
+
async listSkills() {
|
|
261
|
+
let skills = [];
|
|
262
|
+
// The init line comes first, so the run stops there rather than answering the placeholder prompt.
|
|
263
|
+
// --no-session-persistence keeps this run out of the developer's /resume list.
|
|
264
|
+
const { timedOut } = await runProcess(this.cmd, {
|
|
265
|
+
args: ['-p', '--no-session-persistence', '--permission-mode', 'plan', '--output-format', 'stream-json', '--verbose'],
|
|
266
|
+
stdin: 'List your skills.', cwd: this.projectDir, env: childEnv(), idleMs: idleTimeoutMs(),
|
|
267
|
+
onLine: (line) => {
|
|
268
|
+
const found = parseSkills(line);
|
|
269
|
+
if (found)
|
|
270
|
+
skills = found;
|
|
271
|
+
return found !== undefined;
|
|
272
|
+
},
|
|
273
|
+
});
|
|
274
|
+
console.log(timedOut ? 'Could not list Claude Code skills: no output' : `Offering ${skills.length} skills in the room`);
|
|
275
|
+
return skills;
|
|
276
|
+
}
|
|
277
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// The engine behind /converge: runs one command of the grammar in commands.ts against this repository and the relay.
|
|
2
|
+
// It is internal. A developer reaches it only through their coding agent's slash command, whose launcher passes the
|
|
3
|
+
// arguments through (integrations/claude-code/skills/converge); the package's own `converge` command (converge.ts) only
|
|
4
|
+
// sets up and checks, and no bin or npm script starts this engine.
|
|
5
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { mkdirSync, openSync, readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { userInfo } from 'node:os';
|
|
9
|
+
import { dirname, extname, resolve } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { parseCommand, USAGE, UsageError } from './commands.js';
|
|
12
|
+
import { loadConfig, logPath, parseRoomRef, saveConfig, saveRoom } from './config.js';
|
|
13
|
+
import { collectRepository, collectReview, describeReview, GitReviewError } from './git.js';
|
|
14
|
+
import { describeHunks } from './hunks.js';
|
|
15
|
+
import { api as relayApi, DEFAULT_RELAY } from './relay.js';
|
|
16
|
+
import { shareReview } from './share-review.js';
|
|
17
|
+
// The relay a new room or a connect code goes to (join --relay, or AGENT_REVIEW_API_URL). A stored room always talks
|
|
18
|
+
// to the relay that issued its token: the token is never sent anywhere else, because a pasted command naming another
|
|
19
|
+
// relay would hand it to whoever runs that relay. Moving a room means a new connect code from it.
|
|
20
|
+
let relayOverride = process.env.AGENT_REVIEW_API_URL?.replace(/\/$/, '');
|
|
21
|
+
const relay = () => relayOverride ?? DEFAULT_RELAY;
|
|
22
|
+
// Default workspace: the git repository containing the current directory, so any subdirectory works. Hidden like
|
|
23
|
+
// git() in git.ts: when Claude Code starts the CLI there may be no console, and Windows would open one for git.
|
|
24
|
+
function repoRoot(dir) {
|
|
25
|
+
try {
|
|
26
|
+
return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }).trim();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return dir;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const projectDir = resolve(process.env.PROJECT_DIR ?? repoRoot(process.cwd()));
|
|
33
|
+
// The room's agent, beside this file: agent-process.ts from a checkout (run through tsx, which execArgv carries on), or
|
|
34
|
+
// agent-process.js in the installed package.
|
|
35
|
+
const agentProcess = fileURLToPath(new URL(`./agent-process${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
|
|
36
|
+
/** A development room's task description; the API refuses longer ones (apps/api/rooms.py MAX_TASK_CHARS). */
|
|
37
|
+
const MAX_TASK_CHARS = 10_000;
|
|
38
|
+
const api = (path, init = {}) => relayApi(path, { ...init, base: init.base ?? relay() });
|
|
39
|
+
/**
|
|
40
|
+
* Starts the room's agent in the background and returns once the relay reports this new process online. An older
|
|
41
|
+
* process still holding the grant is replaced by the relay when the new one connects (it stops on 4409), so the
|
|
42
|
+
* restart keeps the room's access and never needs a new code.
|
|
43
|
+
*/
|
|
44
|
+
async function connect(room) {
|
|
45
|
+
mkdirSync(dirname(logPath(room.roomId)), { recursive: true, mode: 0o700 });
|
|
46
|
+
const log = openSync(logPath(room.roomId), 'a', 0o600);
|
|
47
|
+
const instance = randomUUID();
|
|
48
|
+
const child = spawn(process.execPath, [...process.execArgv, agentProcess, room.roomId, instance], {
|
|
49
|
+
detached: true, stdio: ['ignore', log, log],
|
|
50
|
+
});
|
|
51
|
+
child.unref();
|
|
52
|
+
let exited = null;
|
|
53
|
+
child.on('exit', (code) => { exited = code ?? -1; });
|
|
54
|
+
// Wait until the relay reports this process online, so the developer gets a definite result. An agent that dies on
|
|
55
|
+
// startup, or an earlier one that is still online, must not be mistaken for it. A relay from before bridges sent an
|
|
56
|
+
// instance reports none, and then online is all there is to go on.
|
|
57
|
+
for (let i = 0; i < 20 && exited === null; i++) {
|
|
58
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
59
|
+
if (exited !== null)
|
|
60
|
+
break;
|
|
61
|
+
const s = await api('/agent-grants/self', { token: room.agentToken, base: room.apiUrl }).catch(() => undefined);
|
|
62
|
+
if (s?.online && (s.bridge === undefined || s.bridge.instance === instance)) {
|
|
63
|
+
console.log(`Agent connected (background pid ${child.pid}, workspace ${room.projectDir}).\n` +
|
|
64
|
+
'Run "/converge status" to check it and "/converge leave" to disconnect it and revoke its access.');
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const tail = readFileSync(logPath(room.roomId), 'utf8').trim().split('\n').slice(-15).join('\n');
|
|
69
|
+
const what = exited !== null ? `The agent exited (${exited}) before coming online` : 'The agent did not come online within 10s';
|
|
70
|
+
throw new Error(`${what}. Last log lines (${logPath(room.roomId)}):\n${tail}`);
|
|
71
|
+
}
|
|
72
|
+
function printShared({ snapshot, dirty }) {
|
|
73
|
+
console.log(`Sharing committed changes: ${describeReview(snapshot)}`);
|
|
74
|
+
console.log(snapshot.hunks.length ? ` Split into ${describeHunks(snapshot.hunks)}`
|
|
75
|
+
: ' Could not split the diff into hunks; the room shows it file by file.');
|
|
76
|
+
if (snapshot.diff_truncated)
|
|
77
|
+
console.log(' Diff is large; the room shows a truncated diff (the agent still sees all of it).');
|
|
78
|
+
if (dirty)
|
|
79
|
+
console.log(' Note: you have uncommitted changes; they are not shared. Commit them and run "/converge update" to include them.');
|
|
80
|
+
}
|
|
81
|
+
async function snapshotFor(dir, base, required) {
|
|
82
|
+
try {
|
|
83
|
+
const collected = await collectReview(dir, base);
|
|
84
|
+
printShared(collected);
|
|
85
|
+
return collected.snapshot;
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
if (!required && err instanceof GitReviewError && err.kind === 'not-a-repo') {
|
|
89
|
+
console.log(`${dir} is not a git repository; creating a room without a change snapshot.`);
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
throw err;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function requireProjectDir() {
|
|
96
|
+
if (!statSync(projectDir, { throwIfNoEntry: false })?.isDirectory()) {
|
|
97
|
+
throw new Error(`PROJECT_DIR ${projectDir} is not a directory. Set it to the repository your agent should ` +
|
|
98
|
+
'work in, or run the command from inside that repository without PROJECT_DIR.');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function pickStoredRoom(ref) {
|
|
102
|
+
const { rooms } = await loadConfig();
|
|
103
|
+
if (ref) {
|
|
104
|
+
const room = rooms[parseRoomRef(ref)];
|
|
105
|
+
if (!room)
|
|
106
|
+
throw new Error('This agent is not connected to that room.');
|
|
107
|
+
return room;
|
|
108
|
+
}
|
|
109
|
+
const all = Object.values(rooms);
|
|
110
|
+
if (all.length === 1)
|
|
111
|
+
return all[0];
|
|
112
|
+
if (!all.length)
|
|
113
|
+
throw new Error('This agent is not connected to any rooms.');
|
|
114
|
+
throw new Error(`Specify a room:\n${all.map((r) => ` ${r.roomId} ${r.title}`).join('\n')}`);
|
|
115
|
+
}
|
|
116
|
+
/** A development room: the task, plus where the repository stands now. Nothing in it is changed or shared. */
|
|
117
|
+
async function build({ task, title, owner }) {
|
|
118
|
+
requireProjectDir();
|
|
119
|
+
if (task.length > MAX_TASK_CHARS)
|
|
120
|
+
throw new Error(`The task description is over ${MAX_TASK_CHARS} characters; shorten it.`);
|
|
121
|
+
const { repository, dirty } = await collectRepository(projectDir);
|
|
122
|
+
console.log(`Starting a development session at ${repository.branch} ${repository.base_sha.slice(0, 7)} in ${repository.repo}.`);
|
|
123
|
+
if (dirty)
|
|
124
|
+
console.log(' Note: you have uncommitted changes; they stay on your machine and are not shared.');
|
|
125
|
+
const created = await api('/rooms', { method: 'POST', body: JSON.stringify({
|
|
126
|
+
title: title ?? `${repository.repo}: ${task.split('\n')[0]}`.slice(0, 200),
|
|
127
|
+
owner_name: owner ?? userInfo().username, provider: 'claude_code', kind: 'development', task, repository,
|
|
128
|
+
}) });
|
|
129
|
+
await announce(created, undefined);
|
|
130
|
+
}
|
|
131
|
+
/** A review room for the commits on this branch, or a plain room outside a git repository. */
|
|
132
|
+
async function review({ title, owner, base }) {
|
|
133
|
+
requireProjectDir();
|
|
134
|
+
const snapshot = await snapshotFor(projectDir, base, Boolean(base));
|
|
135
|
+
const created = await api('/rooms', { method: 'POST', body: JSON.stringify({
|
|
136
|
+
title: title ?? (snapshot ? `${snapshot.repo}: ${snapshot.branch}` : 'Review room'),
|
|
137
|
+
owner_name: owner ?? userInfo().username, provider: 'claude_code', review: snapshot,
|
|
138
|
+
}) });
|
|
139
|
+
await announce(created, snapshot?.base_ref);
|
|
140
|
+
}
|
|
141
|
+
/** Remembers a room this CLI just created, prints its links and connects its agent. */
|
|
142
|
+
async function announce(created, baseRef) {
|
|
143
|
+
const room = { roomId: created.room_id, title: created.title, roomUrl: created.room_url, apiUrl: relay(),
|
|
144
|
+
grantId: created.grant_id, agentToken: created.agent_token, projectDir, baseRef };
|
|
145
|
+
await saveRoom(room);
|
|
146
|
+
console.log(`\nRoom created: ${created.title}\n Room URL (share with reviewers after inviting them): ${created.room_url}\n` +
|
|
147
|
+
` Your owner link (keep private, open it in your browser): ${created.owner_link}\n`);
|
|
148
|
+
await connect(room);
|
|
149
|
+
}
|
|
150
|
+
async function join({ room: ref, code }) {
|
|
151
|
+
const roomId = parseRoomRef(ref);
|
|
152
|
+
requireProjectDir(); // before a connect code is spent
|
|
153
|
+
if (code) {
|
|
154
|
+
const grant = await api('/agent-grants/exchange', { method: 'POST', body: JSON.stringify({ code }) });
|
|
155
|
+
if (grant.room_id !== roomId)
|
|
156
|
+
throw new Error('That connect code belongs to a different room.');
|
|
157
|
+
// A re-join keeps what this machine already knew about the room (an owner's review base).
|
|
158
|
+
const known = (await loadConfig()).rooms[roomId];
|
|
159
|
+
await saveRoom({ ...known, roomId, title: grant.title, roomUrl: grant.room_url, apiUrl: relay(), grantId: grant.grant_id,
|
|
160
|
+
agentToken: grant.agent_token, projectDir });
|
|
161
|
+
}
|
|
162
|
+
const stored = (await loadConfig()).rooms[roomId];
|
|
163
|
+
if (!stored) {
|
|
164
|
+
throw new Error('This agent is not authorized for that room yet. Open the room in your browser, choose ' +
|
|
165
|
+
'"Connect Claude Code", and run the /converge join command it shows.');
|
|
166
|
+
}
|
|
167
|
+
if (relayOverride && relayOverride !== stored.apiUrl) {
|
|
168
|
+
throw new Error(`This agent's access to ${stored.title} was issued by ${stored.apiUrl}, and is never sent to another ` +
|
|
169
|
+
`relay. To connect it through ${relayOverride}, open the room there, choose "Connect Claude Code", and run the ` +
|
|
170
|
+
'/converge join command it shows: it carries a new code for that relay.');
|
|
171
|
+
}
|
|
172
|
+
const room = { ...stored, projectDir };
|
|
173
|
+
if (stored.projectDir !== projectDir)
|
|
174
|
+
await saveRoom(room);
|
|
175
|
+
await connect(room);
|
|
176
|
+
}
|
|
177
|
+
async function update({ room: ref, base }) {
|
|
178
|
+
const room = await pickStoredRoom(ref);
|
|
179
|
+
const shared = await shareReview(room, { base });
|
|
180
|
+
printShared(shared);
|
|
181
|
+
console.log(`Updated ${room.title}. Everyone in the room now sees ${shared.snapshot.head_sha.slice(0, 7)}.`);
|
|
182
|
+
}
|
|
183
|
+
async function status(ref) {
|
|
184
|
+
const { rooms } = await loadConfig();
|
|
185
|
+
const targets = ref ? [await pickStoredRoom(ref)] : Object.values(rooms);
|
|
186
|
+
if (!targets.length)
|
|
187
|
+
console.log('Not connected to any rooms.');
|
|
188
|
+
for (const room of targets) {
|
|
189
|
+
try {
|
|
190
|
+
const s = await fetch(`${room.apiUrl}/agent-grants/self`, { headers: { Authorization: `Bearer ${room.agentToken}` } })
|
|
191
|
+
.then(async (r) => r.ok ? r.json() : Promise.reject(new Error((await r.json().catch(() => ({}))).detail ?? r.statusText)));
|
|
192
|
+
const task = s.kind === 'development' && s.repository ? `\n task: ${s.task.split('\n')[0]}\n started from: ` +
|
|
193
|
+
`${s.repository.branch} ${s.repository.base_sha.slice(0, 7)}` : '';
|
|
194
|
+
const reviewing = s.review ? `\n reviewing: ${s.review.branch} vs ${s.review.base_ref} · ${s.review.commit_count} commit(s) · ` +
|
|
195
|
+
`${s.review.base_sha.slice(0, 7)}..${s.review.head_sha.slice(0, 7)}` : '';
|
|
196
|
+
console.log(`${s.title} (${room.roomId})\n ${s.room_url}${task}${reviewing}\n access: ${s.status} · bridge: ${describeBridge(s)}` +
|
|
197
|
+
` · humans online: ${s.humans_online}${await describeRequests(room)}\n workspace: ${room.projectDir}\n log: ${logPath(room.roomId)}`);
|
|
198
|
+
if (s.bridge?.outdated) {
|
|
199
|
+
console.log(` The connected bridge is outdated (version ${s.bridge.version}; the relay expects ${s.bridge.expected}). ` +
|
|
200
|
+
`Update Converge, then run "/converge join ${room.roomId}" to restart it; its access is kept.`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
console.log(`${room.title} (${room.roomId})\n unavailable: ${err.message}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** "online · version 1 (3f2a…)" or "offline · last seen 12 min ago": what the relay knows of this grant's bridge. */
|
|
209
|
+
function describeBridge(s) {
|
|
210
|
+
if (!s.bridge)
|
|
211
|
+
return s.online ? 'online' : 'offline';
|
|
212
|
+
const { version, build, last_seen_at } = s.bridge;
|
|
213
|
+
if (s.online)
|
|
214
|
+
return `online · version ${version}${build ? ` (${build})` : ''}`;
|
|
215
|
+
return last_seen_at ? `offline · last seen ${ago(last_seen_at)}` : 'offline · never connected';
|
|
216
|
+
}
|
|
217
|
+
function ago(iso) {
|
|
218
|
+
const minutes = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60_000));
|
|
219
|
+
return minutes < 1 ? 'just now' : minutes < 120 ? `${minutes} min ago` : `${Math.round(minutes / 60)} h ago`;
|
|
220
|
+
}
|
|
221
|
+
/** The requests waiting on this agent, so a request stuck in Authorized shows up here too. */
|
|
222
|
+
async function describeRequests(room) {
|
|
223
|
+
const listed = await api('/agent-grants/self/implementation-requests', { token: room.agentToken, base: room.apiUrl })
|
|
224
|
+
.catch(() => undefined);
|
|
225
|
+
if (!listed?.requests.length)
|
|
226
|
+
return '';
|
|
227
|
+
const authorized = listed.requests.filter((r) => r.status === 'authorized');
|
|
228
|
+
const running = listed.requests.length - authorized.length;
|
|
229
|
+
const oldest = authorized[0]?.updated_at ? ` (oldest authorized ${ago(authorized[0].updated_at)})` : '';
|
|
230
|
+
return `\n implementation requests: ${authorized.length} authorized, ${running} running${oldest}`;
|
|
231
|
+
}
|
|
232
|
+
async function leave(ref) {
|
|
233
|
+
const room = await pickStoredRoom(ref);
|
|
234
|
+
const response = await fetch(`${room.apiUrl}/agent-grants/self`, { method: 'DELETE', headers: { Authorization: `Bearer ${room.agentToken}` } })
|
|
235
|
+
.catch((err) => {
|
|
236
|
+
throw new Error(`Could not reach the relay at ${room.apiUrl} (${err.cause?.message ?? err.message}); access was not ` +
|
|
237
|
+
'revoked. If the relay moved, connect to the room there with a new code (its "Connect Claude Code"), then leave again.');
|
|
238
|
+
});
|
|
239
|
+
// 401: the relay no longer knows this authorization, so there is nothing left to revoke.
|
|
240
|
+
if (!response.ok && response.status !== 401) {
|
|
241
|
+
throw new Error(`The relay did not revoke access (${response.status} ${response.statusText}); try again.`);
|
|
242
|
+
}
|
|
243
|
+
const config = await loadConfig();
|
|
244
|
+
delete config.rooms[room.roomId];
|
|
245
|
+
await saveConfig(config);
|
|
246
|
+
console.log(`Left ${room.title}. This agent can no longer connect to it.`);
|
|
247
|
+
// Kept on purpose: a room opened on this branch again starts from them. Said here so the owner can delete them.
|
|
248
|
+
if (room.commentsFile)
|
|
249
|
+
console.log(`The room's comments are kept in ${room.commentsFile}; a room opened on this branch again brings them back.`);
|
|
250
|
+
}
|
|
251
|
+
async function run(command) {
|
|
252
|
+
if (command.name === 'review')
|
|
253
|
+
return review(command);
|
|
254
|
+
if (command.name === 'build')
|
|
255
|
+
return build(command);
|
|
256
|
+
if (command.name === 'join') {
|
|
257
|
+
if (command.relay)
|
|
258
|
+
relayOverride = command.relay.replace(/\/$/, '');
|
|
259
|
+
return join(command);
|
|
260
|
+
}
|
|
261
|
+
if (command.name === 'update')
|
|
262
|
+
return update(command);
|
|
263
|
+
if (command.name === 'status')
|
|
264
|
+
return status(command.room);
|
|
265
|
+
if (command.name === 'leave')
|
|
266
|
+
return leave(command.room);
|
|
267
|
+
console.log(USAGE);
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
await run(parseCommand(process.argv.slice(2)));
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
if (err instanceof UsageError)
|
|
274
|
+
console.error(`${err.message}\n\n${USAGE}`);
|
|
275
|
+
else
|
|
276
|
+
console.error(`Error: ${err.message}`);
|
|
277
|
+
process.exitCode = 1;
|
|
278
|
+
}
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The /converge commands, the bridge's only public interface. Each coding agent's slash command (for Claude Code,
|
|
2
|
+
// integrations/claude-code/skills/converge) passes its arguments here unchanged, so this grammar, not the skill, decides
|
|
3
|
+
// what a developer can do. Rooms are created only by `review` and `build`; there is deliberately no command that
|
|
4
|
+
// creates a room any other way, and none that proposes changes: Change Proposals will come from implementation requests
|
|
5
|
+
// made inside a room (docs/review-room.md, decision 12).
|
|
6
|
+
import { parseArgs } from 'node:util';
|
|
7
|
+
export const USAGE = `Usage: /converge <command>
|
|
8
|
+
|
|
9
|
+
review [--title <t>] [--name <n>] [--base <ref>]
|
|
10
|
+
Create a review room for the commits on this branch and connect your agent to it
|
|
11
|
+
build <task description> [--title <t>] [--name <n>]
|
|
12
|
+
Create a development room for a task, starting at the commit checked out now (no changes needed)
|
|
13
|
+
join <room-url> [--code <connect-code>] [--relay <url>]
|
|
14
|
+
Connect your agent to a room you belong to (the room's "Connect Claude Code" shows the command)
|
|
15
|
+
update [<room>] [--base <ref>]
|
|
16
|
+
Share newly committed changes with a room you own
|
|
17
|
+
status [<room>] Show your rooms and whether your agent is connected
|
|
18
|
+
leave [<room>] Disconnect your agent and revoke its access to a room
|
|
19
|
+
|
|
20
|
+
review shares the committed changes since the branch left --base (default: origin's default branch, main or
|
|
21
|
+
master); uncommitted changes are never shared. build shares the task and the repository's name, branch and origin,
|
|
22
|
+
and pins the current commit as the room's base; neither changes your working tree or branches. join --relay names
|
|
23
|
+
the relay a new connect code is exchanged at; a room you have joined always stays on the relay that let you in.`;
|
|
24
|
+
export class UsageError extends Error {
|
|
25
|
+
}
|
|
26
|
+
const OPTIONS = {
|
|
27
|
+
review: { title: { type: 'string' }, name: { type: 'string' }, base: { type: 'string' } },
|
|
28
|
+
build: { title: { type: 'string' }, name: { type: 'string' } },
|
|
29
|
+
join: { code: { type: 'string' }, relay: { type: 'string' } },
|
|
30
|
+
update: { base: { type: 'string' } },
|
|
31
|
+
status: {},
|
|
32
|
+
leave: {},
|
|
33
|
+
};
|
|
34
|
+
/** The command a developer typed after /converge. Anything outside the grammar is a UsageError, never a guess. */
|
|
35
|
+
export function parseCommand(args) {
|
|
36
|
+
const [name, ...rest] = args;
|
|
37
|
+
if (name === undefined || name === 'help' || name === '--help' || name === '-h')
|
|
38
|
+
return { name: 'help' };
|
|
39
|
+
if (!Object.hasOwn(OPTIONS, name))
|
|
40
|
+
throw new UsageError(`Unknown command "${name}".`);
|
|
41
|
+
let parsed;
|
|
42
|
+
try {
|
|
43
|
+
parsed = parseArgs({ args: rest, options: OPTIONS[name], allowPositionals: true, strict: true });
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
throw new UsageError(err.message);
|
|
47
|
+
}
|
|
48
|
+
const values = parsed.values;
|
|
49
|
+
const { positionals } = parsed;
|
|
50
|
+
const atMostOne = () => {
|
|
51
|
+
if (positionals.length > 1)
|
|
52
|
+
throw new UsageError(`${name} takes at most one room, got: ${positionals.join(' ')}`);
|
|
53
|
+
return positionals[0];
|
|
54
|
+
};
|
|
55
|
+
switch (name) {
|
|
56
|
+
case 'review':
|
|
57
|
+
if (positionals.length)
|
|
58
|
+
throw new UsageError(`review takes no arguments, got: ${positionals.join(' ')}. For a task, use build.`);
|
|
59
|
+
return { name: 'review', title: values.title, owner: values.name, base: values.base };
|
|
60
|
+
case 'build': {
|
|
61
|
+
// The task may be quoted or not: `/converge build Add a discount field` reads the same as the quoted form.
|
|
62
|
+
const task = positionals.join(' ').trim();
|
|
63
|
+
if (!task)
|
|
64
|
+
throw new UsageError('build needs a description of the task, e.g. /converge build "Add a discount code field to checkout"');
|
|
65
|
+
return { name: 'build', task, title: values.title, owner: values.name };
|
|
66
|
+
}
|
|
67
|
+
case 'join': {
|
|
68
|
+
const room = atMostOne();
|
|
69
|
+
if (!room)
|
|
70
|
+
throw new UsageError('join needs the room URL.');
|
|
71
|
+
return { name: 'join', room, code: values.code, relay: values.relay };
|
|
72
|
+
}
|
|
73
|
+
case 'update':
|
|
74
|
+
return { name: 'update', room: atMostOne(), base: values.base };
|
|
75
|
+
case 'status':
|
|
76
|
+
return { name: 'status', room: atMostOne() };
|
|
77
|
+
case 'leave':
|
|
78
|
+
return { name: 'leave', room: atMostOne() };
|
|
79
|
+
}
|
|
80
|
+
}
|