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
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { shareProposal, shareWaiting } from './change-proposals.js';
|
|
2
|
+
import { discardResult, keptResults, readResult } from './implementation-results.js';
|
|
3
|
+
import { api, RelayError } from './relay.js';
|
|
4
|
+
import { createWorktree, removeWorktree, sweepWorktrees, WorktreeError } from './worktree.js';
|
|
5
|
+
/** ImplementationRequest.reason's column (apps/api implementations.py MAX_REASON_CHARS). */
|
|
6
|
+
export const MAX_REASON_CHARS = 200;
|
|
7
|
+
/** One run at a time: a request is a whole agent session, and each has its own worktree on disk. */
|
|
8
|
+
export const MAX_CONCURRENT_RUNS = 1;
|
|
9
|
+
/** Why a run's signal aborted: the member cancelled it, or this bridge is stopping (shutdown, access revoked). */
|
|
10
|
+
export const CANCELLED = 'cancelled';
|
|
11
|
+
export const STOPPING = 'stopping';
|
|
12
|
+
/** Progress lines are sent at most this often; the latest one waiting is sent when the interval ends. */
|
|
13
|
+
export const PROGRESS_INTERVAL_MS = 1_500;
|
|
14
|
+
export const INTERRUPTED = 'Your agent stopped while working on this request (its bridge restarted or lost the relay); nothing was changed. Prepare it again.';
|
|
15
|
+
/** The claim may have landed but its answer did not arrive; nothing ran. */
|
|
16
|
+
export const CLAIM_LOST = 'Your agent lost its connection to the relay while starting this request; nothing ran. Prepare it again.';
|
|
17
|
+
export const EXECUTE_FAILED = 'Your agent failed while working on this request; nothing was changed in your checkout.';
|
|
18
|
+
/** A run stopped before it finished; after a member's cancel the relay refuses it and the request stays cancelled. */
|
|
19
|
+
const STOPPED = { status: 'failed', reason: INTERRUPTED };
|
|
20
|
+
const PREPARE_FAILED = 'Your agent could not prepare an isolated copy of the code for this request.';
|
|
21
|
+
/** EXECUTE_FAILED with the error's first line, so the member sees what broke; the agent's log has the rest. */
|
|
22
|
+
export function failedBecause(err) {
|
|
23
|
+
const first = err instanceof Error ? err.message.split('\n')[0].trim() : '';
|
|
24
|
+
return (first ? `${EXECUTE_FAILED} ${first}` : EXECUTE_FAILED).slice(0, MAX_REASON_CHARS);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Where a running request is (apps/api implementation_runs.py RUN_STAGES, web/lib/implementation.ts RunStage). The
|
|
28
|
+
* relay records `preparing_worktree` with the claim; the bridge reports the rest.
|
|
29
|
+
*/
|
|
30
|
+
export const RUN_STAGES = ['preparing_worktree', 'implementing', 'publishing'];
|
|
31
|
+
/**
|
|
32
|
+
* A request in one of these final statuses never completed, so its kept result stands for nothing (apps/api
|
|
33
|
+
* implementations.py TRANSITIONS). Any other answer, or none, keeps the result.
|
|
34
|
+
*/
|
|
35
|
+
const ENDED_OTHERWISE = ['failed', 'cancelled'];
|
|
36
|
+
export function openImplementations(opts) {
|
|
37
|
+
const { room, execute, maxConcurrent = MAX_CONCURRENT_RUNS } = opts;
|
|
38
|
+
const active = new Map();
|
|
39
|
+
const waiting = [];
|
|
40
|
+
let stopped = false;
|
|
41
|
+
// The discovery under way, and whether another was asked for meanwhile (it runs once this one ends).
|
|
42
|
+
let discovering;
|
|
43
|
+
let discoverAgain = false;
|
|
44
|
+
const call = (path, init = {}) => api(`/agent-grants/self/implementation-requests${path}`, { ...init, token: room.agentToken, base: room.apiUrl });
|
|
45
|
+
/**
|
|
46
|
+
* Tells the relay how the run ended. A refusal (409: cancelled, or no longer running; 403: revoked) is final: it is
|
|
47
|
+
* the relay's state that counts. Unreachable: the next connect settles it.
|
|
48
|
+
*/
|
|
49
|
+
async function finish(id, outcome) {
|
|
50
|
+
const body = outcome.status === 'completed'
|
|
51
|
+
? { status: outcome.status, result: outcome.result }
|
|
52
|
+
: { status: outcome.status, reason: outcome.reason?.slice(0, MAX_REASON_CHARS) };
|
|
53
|
+
try {
|
|
54
|
+
const heard = await call(`/${encodeURIComponent(id)}/finish`, { method: 'POST', body: JSON.stringify(body) });
|
|
55
|
+
// The relay made the room's Change Proposal of it: its code is shared from here (change-proposals.ts).
|
|
56
|
+
if (outcome.status === 'completed' && heard?.change_proposal) {
|
|
57
|
+
await shareProposal(room, { ...heard.change_proposal, request_id: id, commit: outcome.result.commit });
|
|
58
|
+
}
|
|
59
|
+
return 'accepted';
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
if (err instanceof RelayError && err.status < 500)
|
|
63
|
+
return 'refused';
|
|
64
|
+
console.error(`Could not report request ${id} (${outcome.status}); it is settled on the next connect:`, err.message);
|
|
65
|
+
return 'unreachable';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Reports the outcome. A completion the relay refuses takes its kept result with it only once the relay confirms
|
|
70
|
+
* the request ended without completing; if it completed (an earlier report landed) its proposal needs that commit,
|
|
71
|
+
* and if the relay cannot say, the next discovery settles it.
|
|
72
|
+
*/
|
|
73
|
+
async function settle(id, outcome) {
|
|
74
|
+
if (await finish(id, outcome) !== 'refused' || outcome.status !== 'completed')
|
|
75
|
+
return;
|
|
76
|
+
if (await endedOtherwise(id)) {
|
|
77
|
+
await discard(outcome.result);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
console.log(`Kept the result of request ${id}: the relay did not confirm it ended otherwise; it is checked again on the next look.`);
|
|
81
|
+
}
|
|
82
|
+
/** Whether the relay explicitly says the request ended without completing. An error, or any other status, is no. */
|
|
83
|
+
async function endedOtherwise(id) {
|
|
84
|
+
const known = await call(`/${encodeURIComponent(id)}/status`).catch(() => undefined);
|
|
85
|
+
return typeof known?.status === 'string' && ENDED_OTHERWISE.includes(known.status);
|
|
86
|
+
}
|
|
87
|
+
/** Best effort, like progress: the request's status is what counts, and the room falls back to "working". */
|
|
88
|
+
function reportStage(id, stage) {
|
|
89
|
+
void call(`/${encodeURIComponent(id)}/progress`, { method: 'POST', body: JSON.stringify({ stage }) }).catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
async function discard(result) {
|
|
92
|
+
await discardResult(room.projectDir, result.ref, result.commit).catch((err) => console.error(`Could not remove ${result.ref}; it is removed on the next connect:`, err.message));
|
|
93
|
+
}
|
|
94
|
+
/** Best effort, throttled: a lost line costs nothing, and the request's status is what counts. */
|
|
95
|
+
function progressFor(id) {
|
|
96
|
+
let last = 0;
|
|
97
|
+
let pending;
|
|
98
|
+
let timer;
|
|
99
|
+
const send = (text) => {
|
|
100
|
+
last = Date.now();
|
|
101
|
+
void call(`/${encodeURIComponent(id)}/progress`, { method: 'POST', body: JSON.stringify({ text }) }).catch(() => { });
|
|
102
|
+
};
|
|
103
|
+
return (text) => {
|
|
104
|
+
const wait = last + PROGRESS_INTERVAL_MS - Date.now();
|
|
105
|
+
if (wait <= 0) {
|
|
106
|
+
send(text);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
pending = text;
|
|
110
|
+
timer ??= setTimeout(() => { timer = undefined; if (pending)
|
|
111
|
+
send(pending); pending = undefined; }, wait);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async function work(claimed, signal) {
|
|
115
|
+
let worktree;
|
|
116
|
+
try {
|
|
117
|
+
worktree = await createWorktree({ repoDir: room.projectDir, roomId: room.roomId, requestId: claimed.id, commit: claimed.commit });
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
console.error(`Could not prepare a worktree for request ${claimed.id}:`, err.message);
|
|
121
|
+
return { status: 'failed', reason: err instanceof WorktreeError ? err.message : PREPARE_FAILED };
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
console.log(`Request ${claimed.id}: worktree at ${claimed.commit.slice(0, 7)} in ${worktree}`);
|
|
125
|
+
if (signal.aborted)
|
|
126
|
+
return STOPPED;
|
|
127
|
+
reportStage(claimed.id, 'implementing');
|
|
128
|
+
const outcome = await execute(claimed, worktree, signal, progressFor(claimed.id)).catch((err) => {
|
|
129
|
+
console.error(`Request ${claimed.id} failed:`, err);
|
|
130
|
+
return { status: 'failed', reason: failedBecause(err) };
|
|
131
|
+
});
|
|
132
|
+
if (!signal.aborted)
|
|
133
|
+
return outcome;
|
|
134
|
+
// Stopped while the changes were being kept. A shutdown does not undo a run that completed; a cancel does.
|
|
135
|
+
if (outcome.status === 'completed' && signal.reason === STOPPING)
|
|
136
|
+
return outcome;
|
|
137
|
+
if (outcome.status === 'completed')
|
|
138
|
+
await discard(outcome.result);
|
|
139
|
+
return STOPPED;
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await removeWorktree(room.projectDir, room.roomId, claimed.id).catch((err) => console.error(`Could not remove ${worktree}; it is swept on the next connect:`, err.message));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function run(id, abort) {
|
|
146
|
+
let claimed;
|
|
147
|
+
try {
|
|
148
|
+
claimed = await call(`/${encodeURIComponent(id)}/claim`, { method: 'POST' });
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
// Refused: cancelled, sent back for authorizing (the relay tells the member why), already claimed, or access
|
|
152
|
+
// revoked. Nothing of ours started; the relay's reason is logged for whoever reads the agent's log.
|
|
153
|
+
if (err instanceof RelayError && err.status < 500) {
|
|
154
|
+
console.log(`Request ${id} was not claimed: ${err.message}`);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
// The claim may have landed with its answer lost: end it now rather than leave it running with no one on it.
|
|
158
|
+
// If this report is lost too, the next discovery (at most RECONCILE_INTERVAL_MS away) settles it.
|
|
159
|
+
console.error(`Could not claim request ${id}; reporting it as not started:`, err.message);
|
|
160
|
+
await finish(id, { status: 'failed', reason: CLAIM_LOST });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// Stopped while the claim was in flight (cancelled, or this bridge is stopping): the claim was accepted, so it is
|
|
164
|
+
// settled now rather than left running, and no worktree is made.
|
|
165
|
+
if (abort.signal.aborted) {
|
|
166
|
+
await finish(id, STOPPED);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const outcome = await work(claimed, abort.signal);
|
|
170
|
+
if (outcome.status === 'completed')
|
|
171
|
+
reportStage(id, 'publishing');
|
|
172
|
+
await settle(id, outcome);
|
|
173
|
+
}
|
|
174
|
+
function start(id) {
|
|
175
|
+
if (stopped || active.has(id) || waiting.includes(id))
|
|
176
|
+
return;
|
|
177
|
+
waiting.push(id);
|
|
178
|
+
next();
|
|
179
|
+
}
|
|
180
|
+
function next() {
|
|
181
|
+
while (!stopped && active.size < maxConcurrent && waiting.length) {
|
|
182
|
+
const id = waiting.shift();
|
|
183
|
+
const abort = new AbortController();
|
|
184
|
+
const done = run(id, abort)
|
|
185
|
+
.catch((err) => console.error(`Request ${id}:`, err))
|
|
186
|
+
.finally(() => { active.delete(id); next(); });
|
|
187
|
+
active.set(id, { abort, done });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** A request left running by an earlier process: completed if its result was kept before it stopped. */
|
|
191
|
+
async function settleInterrupted(id) {
|
|
192
|
+
const kept = await readResult(room.projectDir, room.roomId, id).catch(() => null);
|
|
193
|
+
await settle(id, kept ? { status: 'completed', result: kept.result } : STOPPED);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Results kept for requests the relay no longer runs, from a run whose report never arrived. Removed when the
|
|
197
|
+
* relay says the request ended otherwise; kept when it completed, or when the request is not this agent's (another
|
|
198
|
+
* member's agent in the same repository) or the relay cannot say.
|
|
199
|
+
*/
|
|
200
|
+
async function removeOrphans(listed) {
|
|
201
|
+
for (const kept of await keptResults(room.projectDir, room.roomId)) {
|
|
202
|
+
if (active.has(kept.requestId) || listed.has(kept.requestId))
|
|
203
|
+
continue;
|
|
204
|
+
if (await endedOtherwise(kept.requestId))
|
|
205
|
+
await discardResult(room.projectDir, kept.ref, kept.commit);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** One look at the relay's list: claim what is authorized, settle what was interrupted, clean up the rest. */
|
|
209
|
+
async function discoverOnce() {
|
|
210
|
+
try {
|
|
211
|
+
const { requests } = await call('');
|
|
212
|
+
for (const request of requests) {
|
|
213
|
+
if (request.status === 'authorized')
|
|
214
|
+
start(request.id);
|
|
215
|
+
else if (request.status === 'running' && !active.has(request.id))
|
|
216
|
+
await settleInterrupted(request.id);
|
|
217
|
+
}
|
|
218
|
+
await removeOrphans(new Set(requests.map((request) => request.id)));
|
|
219
|
+
await shareWaiting(room);
|
|
220
|
+
await sweepWorktrees(room.projectDir, room.roomId, active);
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
console.error('Could not check for implementation requests; trying again shortly:', err.message);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
discover() {
|
|
228
|
+
if (stopped)
|
|
229
|
+
return Promise.resolve();
|
|
230
|
+
// One at a time: two overlapping looks could both settle the same interrupted request.
|
|
231
|
+
if (discovering) {
|
|
232
|
+
discoverAgain = true;
|
|
233
|
+
return discovering;
|
|
234
|
+
}
|
|
235
|
+
discovering = (async () => {
|
|
236
|
+
do {
|
|
237
|
+
discoverAgain = false;
|
|
238
|
+
await discoverOnce();
|
|
239
|
+
} while (discoverAgain && !stopped);
|
|
240
|
+
})().finally(() => { discovering = undefined; });
|
|
241
|
+
return discovering;
|
|
242
|
+
},
|
|
243
|
+
hint(id, status) {
|
|
244
|
+
if (status === 'authorized') {
|
|
245
|
+
start(id);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const queued = waiting.indexOf(id);
|
|
249
|
+
if (queued >= 0)
|
|
250
|
+
waiting.splice(queued, 1);
|
|
251
|
+
active.get(id)?.abort.abort(CANCELLED);
|
|
252
|
+
},
|
|
253
|
+
async stop() {
|
|
254
|
+
stopped = true;
|
|
255
|
+
waiting.length = 0;
|
|
256
|
+
const running = [...active.values()];
|
|
257
|
+
for (const { abort } of running)
|
|
258
|
+
abort.abort(STOPPING);
|
|
259
|
+
await Promise.all(running.map(({ done }) => done));
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
; Definitions the hunk splitter files changed lines under, shared by JavaScript, TypeScript and TSX.
|
|
2
|
+
; Only node types present in all three grammars belong here; grammar-specific ones go in javascript.scm or
|
|
3
|
+
; typescript.scm. Capture the definition node as @function, @method or @class, and its name as @name.
|
|
4
|
+
; Imports are captured as @import so changed import lines form their own hunk.
|
|
5
|
+
|
|
6
|
+
(function_declaration name: (identifier) @name) @function
|
|
7
|
+
(generator_function_declaration name: (identifier) @name) @function
|
|
8
|
+
(method_definition name: (_) @name) @method
|
|
9
|
+
(class_declaration name: (_) @name) @class
|
|
10
|
+
(class name: (_) @name) @class
|
|
11
|
+
|
|
12
|
+
; const f = () => {} / const f = function () {}
|
|
13
|
+
(variable_declarator
|
|
14
|
+
name: (identifier) @name
|
|
15
|
+
value: [(arrow_function) (function_expression) (generator_function)]) @function
|
|
16
|
+
|
|
17
|
+
; { key() {} } is a method_definition (above); { key: () => {} } is a pair
|
|
18
|
+
(pair
|
|
19
|
+
key: (_) @name
|
|
20
|
+
value: [(arrow_function) (function_expression) (generator_function)]) @function
|
|
21
|
+
|
|
22
|
+
; module.exports.f = function () {} / exports.f = () => {}
|
|
23
|
+
(assignment_expression
|
|
24
|
+
left: (member_expression property: (property_identifier) @name)
|
|
25
|
+
right: [(arrow_function) (function_expression) (generator_function)]) @function
|
|
26
|
+
|
|
27
|
+
; A top-level call with a title and a callback is reviewed as its own unit, named after the title:
|
|
28
|
+
; test('joins a room', () => {}), describe('Room', …), app.get('/users', (req, res) => {}).
|
|
29
|
+
(expression_statement
|
|
30
|
+
(call_expression
|
|
31
|
+
function: [(identifier) (member_expression)] @callee
|
|
32
|
+
arguments: (arguments . (string) @name [(arrow_function) (function_expression)]))) @call
|
|
33
|
+
|
|
34
|
+
(import_statement) @import
|
|
35
|
+
(export_statement source: (_)) @import
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
; Definitions the hunk splitter files changed lines under (Python).
|
|
2
|
+
; A function inside a class is reported as a method by the splitter. Decorators are included in the
|
|
3
|
+
; definition's range by the splitter (it widens a definition to its decorated_definition parent).
|
|
4
|
+
|
|
5
|
+
(function_definition name: (identifier) @name) @function
|
|
6
|
+
(class_definition name: (identifier) @name) @class
|
|
7
|
+
|
|
8
|
+
(import_statement) @import
|
|
9
|
+
(import_from_statement) @import
|
|
10
|
+
(future_import_statement) @import
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
; TypeScript-only definitions, loaded together with ecmascript.scm for .ts and .tsx files.
|
|
2
|
+
; Interfaces, type aliases, enums and namespaces are reported as @class (class-like containers).
|
|
3
|
+
|
|
4
|
+
(abstract_class_declaration name: (_) @name) @class
|
|
5
|
+
(interface_declaration name: (_) @name) @class
|
|
6
|
+
(type_alias_declaration name: (_) @name) @class
|
|
7
|
+
(enum_declaration name: (_) @name) @class
|
|
8
|
+
(internal_module name: (_) @name) @class
|
|
9
|
+
(function_signature name: (_) @name) @function
|
|
10
|
+
(method_signature name: (_) @name) @method
|
|
11
|
+
(abstract_method_signature name: (_) @name) @method
|
|
12
|
+
|
|
13
|
+
; class A { private handle = () => {} }
|
|
14
|
+
(public_field_definition
|
|
15
|
+
name: (_) @name
|
|
16
|
+
value: [(arrow_function) (function_expression) (generator_function)]) @method
|
package/dist/relay.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// The relay's HTTP API as the bridge calls it: JSON in and out, the agent's token as a bearer, and the relay's own
|
|
2
|
+
// error message (its "detail") as the error, so a /converge command can show the developer why it failed.
|
|
3
|
+
/** The hosted relay the published package talks to (web lib/api.ts PRODUCTION_API_URL, see Known duplication). */
|
|
4
|
+
export const PRODUCTION_RELAY = 'https://converge-xvta.onrender.com';
|
|
5
|
+
/** The relay a contributor runs from this repository (scripts/dev-session.sh, web lib/api.ts DEFAULT_API_URL). */
|
|
6
|
+
export const LOCAL_RELAY = 'http://127.0.0.1:8000';
|
|
7
|
+
/**
|
|
8
|
+
* Where a new room or a connect code goes when neither `join --relay` nor AGENT_REVIEW_API_URL says otherwise. The
|
|
9
|
+
* installed package (compiled, so this module is .js) uses the hosted relay; a checkout run through tsx (.ts) uses the
|
|
10
|
+
* local one, so a contributor's /converge review never creates a room on the hosted relay by accident (decision 40).
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_RELAY = import.meta.url.endsWith('.ts') ? LOCAL_RELAY : PRODUCTION_RELAY;
|
|
13
|
+
/** The owner's member role, as `rooms.py` sets it and the relay reports it on grants and actors (see Known duplication). */
|
|
14
|
+
export const OWNER_ROLE = 'owner';
|
|
15
|
+
/** The relay answered with an error; `status` tells a refusal (4xx) from a failure worth retrying (5xx). */
|
|
16
|
+
export class RelayError extends Error {
|
|
17
|
+
status;
|
|
18
|
+
constructor(message, status) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function api(path, init) {
|
|
24
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
25
|
+
if (init.token)
|
|
26
|
+
headers.Authorization = `Bearer ${init.token}`;
|
|
27
|
+
const response = await fetch(`${init.base.replace(/\/$/, '')}${path}`, { ...init, headers });
|
|
28
|
+
const body = await response.json().catch(() => ({}));
|
|
29
|
+
if (!response.ok)
|
|
30
|
+
throw new RelayError(body.detail ?? `${response.status} ${response.statusText}`, response.status);
|
|
31
|
+
return body;
|
|
32
|
+
}
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
/** Seconds of silence before a run is abandoned; streaming output keeps resetting it. */
|
|
4
|
+
export function idleTimeoutMs(env = process.env) {
|
|
5
|
+
const seconds = Number(env.AGENT_REVIEW_IDLE_TIMEOUT);
|
|
6
|
+
return (Number.isFinite(seconds) && seconds > 0 ? seconds : 120) * 1000;
|
|
7
|
+
}
|
|
8
|
+
const live = new Set();
|
|
9
|
+
let cleanupInstalled = false;
|
|
10
|
+
function installCleanup() {
|
|
11
|
+
if (cleanupInstalled)
|
|
12
|
+
return;
|
|
13
|
+
cleanupInstalled = true;
|
|
14
|
+
// Agent processes run in their own process group on POSIX (see runProcess), so Ctrl+C would not reach them.
|
|
15
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
16
|
+
process.on(signal, () => { for (const child of live)
|
|
17
|
+
terminate(child); process.exit(130); });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Ends the process and everything it started (MCP servers, helpers), not just the top-level one. */
|
|
21
|
+
export function terminate(child) {
|
|
22
|
+
if (child.exitCode !== null || child.signalCode !== null || child.pid === undefined)
|
|
23
|
+
return;
|
|
24
|
+
if (process.platform === 'win32') {
|
|
25
|
+
execFile('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true }, () => { child.kill(); });
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const group = -child.pid;
|
|
29
|
+
try {
|
|
30
|
+
process.kill(group, 'SIGTERM');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
child.kill('SIGTERM');
|
|
34
|
+
}
|
|
35
|
+
setTimeout(() => { try {
|
|
36
|
+
process.kill(group, 'SIGKILL');
|
|
37
|
+
}
|
|
38
|
+
catch { /* already gone */ } }, 5_000).unref();
|
|
39
|
+
}
|
|
40
|
+
/** Runs one headless agent invocation to completion, delivering stdout line by line. */
|
|
41
|
+
export async function runProcess(cmd, opts) {
|
|
42
|
+
installCleanup();
|
|
43
|
+
const child = spawn(cmd.command, [...cmd.prefix, ...opts.args], {
|
|
44
|
+
cwd: opts.cwd, env: opts.env,
|
|
45
|
+
stdio: [opts.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
|
|
46
|
+
windowsHide: true, // a detached bridge has no console; Windows would otherwise open one per run
|
|
47
|
+
detached: process.platform !== 'win32', // own process group, so terminate() can take helpers with it
|
|
48
|
+
});
|
|
49
|
+
live.add(child);
|
|
50
|
+
if (opts.stdin !== undefined) {
|
|
51
|
+
child.stdin.on('error', () => { });
|
|
52
|
+
child.stdin.end(opts.stdin);
|
|
53
|
+
}
|
|
54
|
+
let stderr = '';
|
|
55
|
+
let stopped;
|
|
56
|
+
const stop = (reason) => { stopped ??= reason; terminate(child); };
|
|
57
|
+
let idle;
|
|
58
|
+
const touch = () => {
|
|
59
|
+
clearTimeout(idle);
|
|
60
|
+
idle = setTimeout(() => stop('idle'), opts.idleMs);
|
|
61
|
+
};
|
|
62
|
+
touch();
|
|
63
|
+
const deadline = opts.deadlineMs ? setTimeout(() => stop('deadline'), opts.deadlineMs) : undefined;
|
|
64
|
+
const onAbort = () => stop('aborted');
|
|
65
|
+
if (opts.signal?.aborted)
|
|
66
|
+
onAbort();
|
|
67
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
68
|
+
let outputBytes = 0;
|
|
69
|
+
// Ending a process is not instant (on Windows it takes a taskkill), so lines printed after the caller said stop
|
|
70
|
+
// are dropped rather than delivered to a caller that has moved on.
|
|
71
|
+
let stopping = false;
|
|
72
|
+
createInterface({ input: child.stdout }).on('line', (line) => {
|
|
73
|
+
if (stopping)
|
|
74
|
+
return;
|
|
75
|
+
touch();
|
|
76
|
+
outputBytes += Buffer.byteLength(line) + 1;
|
|
77
|
+
if (opts.maxOutputBytes && outputBytes > opts.maxOutputBytes) {
|
|
78
|
+
stopping = true;
|
|
79
|
+
stop('output');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (opts.onLine(line) === true) {
|
|
83
|
+
stopping = true;
|
|
84
|
+
terminate(child);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
child.stderr.on('data', (data) => { touch(); if (stderr.length < 4096)
|
|
88
|
+
stderr += data.toString().slice(0, 2048); });
|
|
89
|
+
const exitCode = await new Promise((done) => {
|
|
90
|
+
child.on('error', (err) => { stderr += err.message; done(-1); });
|
|
91
|
+
child.on('close', (code) => done(code ?? -1));
|
|
92
|
+
});
|
|
93
|
+
clearTimeout(idle);
|
|
94
|
+
clearTimeout(deadline);
|
|
95
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
96
|
+
live.delete(child);
|
|
97
|
+
return { exitCode, timedOut: stopped === 'idle', stderr, stopped };
|
|
98
|
+
}
|
|
99
|
+
/** Runs `<cmd> <args>` briefly (e.g. `--version`) and returns trimmed stdout, or throws with the reason. */
|
|
100
|
+
export function probe(cmd, args, env, timeoutMs = 20_000) {
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
execFile(cmd.command, [...cmd.prefix, ...args], { env, timeout: timeoutMs, windowsHide: true }, (err, stdout, stderr) => err ? reject(new Error(stderr.trim() || err.message)) : resolve(stdout.trim()));
|
|
103
|
+
});
|
|
104
|
+
}
|
package/dist/sandbox.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The operating-system boundary around a write-capable agent run (docs/review-room.md, decision 17). Claude Code's own
|
|
2
|
+
// restricted mode keeps its file tools in the worktree, but that is the agent's process policing itself; this is the
|
|
3
|
+
// kernel doing it, whatever the process tries. Writes are refused everywhere except the run's worktree, its own
|
|
4
|
+
// temporary folder and the devices a process needs; reads are refused for credentials, Converge's own config (agent
|
|
5
|
+
// tokens) and the developer's checkout apart from its git folder. Everything else, including the network, is left as
|
|
6
|
+
// it is: the agent needs its model API and its own install.
|
|
7
|
+
//
|
|
8
|
+
// Only macOS (Seatbelt, `sandbox-exec`) is supported for now. Elsewhere `osSandbox` returns null and the run is
|
|
9
|
+
// refused, rather than run without a boundary.
|
|
10
|
+
import { realpath } from 'node:fs/promises';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { runnable } from './exec.js';
|
|
13
|
+
const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
|
|
14
|
+
/** Under the home folder: credentials an agent never needs to implement a change. Hidden whether or not they exist. */
|
|
15
|
+
export const CREDENTIALS = ['.ssh', '.aws', '.gnupg', '.netrc', '.git-credentials', '.npmrc', '.pypirc', '.docker',
|
|
16
|
+
'.kube', '.azure', '.config/gh', '.config/gcloud'];
|
|
17
|
+
const real = (path) => realpath(path).catch(() => path);
|
|
18
|
+
/** The boundary for one run in `worktree` of the repository at `repoDir`. */
|
|
19
|
+
export async function boundaryFor(opts) {
|
|
20
|
+
const repo = await real(opts.repoDir);
|
|
21
|
+
return {
|
|
22
|
+
writable: [await real(opts.worktree), await real(opts.tempDir)],
|
|
23
|
+
unreadable: [repo, await real(opts.configDir), ...await Promise.all(CREDENTIALS.map((path) => real(join(opts.home, path))))],
|
|
24
|
+
readable: [await real(opts.worktree), join(repo, '.git')],
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** A path as a Seatbelt string. Anything that could end the string or the rule is refused, not escaped. */
|
|
28
|
+
function literal(path) {
|
|
29
|
+
if (!path.startsWith('/') || /["\\\0-\x1f]/.test(path))
|
|
30
|
+
throw new Error(`Cannot sandbox the path ${JSON.stringify(path)}`);
|
|
31
|
+
return `"${path}"`;
|
|
32
|
+
}
|
|
33
|
+
/** Later rules win in Seatbelt: allow all, then refuse writes, then allow the writable, then refuse and allow reads. */
|
|
34
|
+
export function seatbeltProfile(boundary) {
|
|
35
|
+
const subpaths = (paths) => paths.map((path) => `(subpath ${literal(path)})`).join(' ');
|
|
36
|
+
return [
|
|
37
|
+
'(version 1)',
|
|
38
|
+
'(allow default)',
|
|
39
|
+
'(deny file-write*)',
|
|
40
|
+
`(allow file-write* ${subpaths(boundary.writable)} (literal "/dev/null") (literal "/dev/tty") (regex #"^/dev/fd/"))`,
|
|
41
|
+
`(deny file-read* ${subpaths(boundary.unreadable)})`,
|
|
42
|
+
`(allow file-read* ${subpaths(boundary.readable)})`,
|
|
43
|
+
].join('\n');
|
|
44
|
+
}
|
|
45
|
+
/** Whether this platform has a sandbox to run an implementation in; without one, requests fail with NO_SANDBOX. */
|
|
46
|
+
export const hasOsSandbox = (platform = process.platform) => platform === 'darwin' && runnable(SANDBOX_EXEC);
|
|
47
|
+
/** The sandbox for `boundary` on this platform, or null when there is none to enforce it. */
|
|
48
|
+
export function osSandbox(boundary, platform = process.platform) {
|
|
49
|
+
if (!hasOsSandbox(platform))
|
|
50
|
+
return null;
|
|
51
|
+
const profile = seatbeltProfile(boundary);
|
|
52
|
+
return { name: 'macOS sandbox', wrap: (cmd) => ({ command: SANDBOX_EXEC, prefix: ['-p', profile, cmd.command, ...cmd.prefix] }) };
|
|
53
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { readFile, writeFile, rename } from 'node:fs/promises';
|
|
2
|
+
export const sessionKey = (room, projectDir) => `${room}::${projectDir}`;
|
|
3
|
+
export function parseState(raw) {
|
|
4
|
+
const state = JSON.parse(raw);
|
|
5
|
+
const sessions = {};
|
|
6
|
+
if (state && typeof state.sessions === 'object') {
|
|
7
|
+
for (const [key, value] of Object.entries(state.sessions))
|
|
8
|
+
if (typeof value === 'string')
|
|
9
|
+
sessions[key] = value;
|
|
10
|
+
}
|
|
11
|
+
else if (typeof state?.room === 'string' && typeof state?.projectDir === 'string' && typeof state?.sessionId === 'string') {
|
|
12
|
+
sessions[sessionKey(state.room, state.projectDir)] = state.sessionId; // legacy single-session format
|
|
13
|
+
}
|
|
14
|
+
return { sessions };
|
|
15
|
+
}
|
|
16
|
+
export async function loadSessionId(path, room, projectDir) {
|
|
17
|
+
try {
|
|
18
|
+
return parseState(await readFile(path, 'utf8')).sessions[sessionKey(room, projectDir)];
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
if (err?.code !== 'ENOENT')
|
|
22
|
+
console.warn('Ignoring unreadable session state:', err.message);
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export async function saveSessionId(path, room, projectDir, sessionId) {
|
|
27
|
+
let state = { sessions: {} };
|
|
28
|
+
try {
|
|
29
|
+
state = parseState(await readFile(path, 'utf8'));
|
|
30
|
+
}
|
|
31
|
+
catch { /* start fresh */ }
|
|
32
|
+
state.sessions[sessionKey(room, projectDir)] = sessionId;
|
|
33
|
+
const temp = `${path}.tmp`;
|
|
34
|
+
await writeFile(temp, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
35
|
+
await rename(temp, path);
|
|
36
|
+
}
|