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.
Files changed (46) hide show
  1. package/LICENSE.md +34 -0
  2. package/THIRD_PARTY_NOTICES.md +149 -0
  3. package/dist/agent-execution.js +103 -0
  4. package/dist/agent-process.js +70 -0
  5. package/dist/agent.js +2 -0
  6. package/dist/anchors.js +101 -0
  7. package/dist/applications.js +69 -0
  8. package/dist/apply-proposal.js +236 -0
  9. package/dist/bridge-health.js +57 -0
  10. package/dist/bridge.js +203 -0
  11. package/dist/change-proposals.js +51 -0
  12. package/dist/claude.js +277 -0
  13. package/dist/cli.js +278 -0
  14. package/dist/commands.js +80 -0
  15. package/dist/comment-file.js +41 -0
  16. package/dist/comment-host.js +96 -0
  17. package/dist/config.js +43 -0
  18. package/dist/converge.js +36 -0
  19. package/dist/exec.js +52 -0
  20. package/dist/follow-branch.js +70 -0
  21. package/dist/git.js +169 -0
  22. package/dist/hunks.js +558 -0
  23. package/dist/implementation-results.js +98 -0
  24. package/dist/implementation-runner.js +262 -0
  25. package/dist/queries/ecmascript.scm +35 -0
  26. package/dist/queries/javascript.scm +6 -0
  27. package/dist/queries/python.scm +10 -0
  28. package/dist/queries/typescript.scm +16 -0
  29. package/dist/relay.js +32 -0
  30. package/dist/runner.js +104 -0
  31. package/dist/sandbox.js +53 -0
  32. package/dist/session-state.js +36 -0
  33. package/dist/setup.js +328 -0
  34. package/dist/share-review.js +34 -0
  35. package/dist/shared.js +193 -0
  36. package/dist/skill/converge/SKILL.md +25 -0
  37. package/dist/skill/converge/converge.mjs +35 -0
  38. package/dist/skill-link.js +100 -0
  39. package/dist/worktree.js +231 -0
  40. package/grammars/SOURCES.json +22 -0
  41. package/grammars/tree-sitter-javascript.wasm +0 -0
  42. package/grammars/tree-sitter-python.wasm +0 -0
  43. package/grammars/tree-sitter-tsx.wasm +0 -0
  44. package/grammars/tree-sitter-typescript.wasm +0 -0
  45. package/package.json +45 -4
  46. package/README.md +0 -3
@@ -0,0 +1,236 @@
1
+ // Applying an approved Change Proposal on the requester's machine (docs/review-room.md, decision 32): the only code in
2
+ // Converge that changes a developer's branch. It runs in this bridge process, never in the agent's sandbox, and only
3
+ // for an application the relay handed this agent after its member asked (applications.ts).
4
+ //
5
+ // The strategy is a fast-forward to the proposal's own commit, the one everyone approved: no new commit is made, so the
6
+ // branch either is at that commit afterwards or is exactly where it was. Before anything is written it checks, on this
7
+ // machine, that this is the room's repository; that the kept result (refs/converge/<room>/<request>) is that commit,
8
+ // made on the expected base for this room and request; that the branch exists and is still at the base; and, when the
9
+ // branch is checked out here, that the checkout is clean, nothing is in progress, and no file on disk would be replaced.
10
+ //
11
+ // The only writes, and only after every check:
12
+ // - the branch is checked out in this checkout: `git merge --ff-only <commit>`. Git itself refuses to overwrite a
13
+ // change made since the check, and the branch is not switched.
14
+ // - it is not checked out anywhere: `git update-ref <branch> <commit> <base>`, which moves it only if it is still at
15
+ // the base. The checkout and whatever branch it is on are not touched.
16
+ // Both run with the developer's hooks off.
17
+ // A branch checked out in another worktree is refused. A branch that moved on is never rebased or merged: whether it
18
+ // would conflict is worked out with `git merge-tree`, which writes no file and no ref, and is reported. Nothing is
19
+ // pushed, fetched, stashed, reset or deleted.
20
+ import { lstat, realpath } from 'node:fs/promises';
21
+ import { devNull } from 'node:os';
22
+ import { basename, join } from 'node:path';
23
+ import { git, safeRemote } from './git.js';
24
+ import { resultRef } from './implementation-results.js';
25
+ /** apps/api applications.py MAX_REASON_CHARS. */
26
+ export const MAX_REASON_CHARS = 300;
27
+ /** Something on this machine that keeps the proposal from being applied; its message is what the requester reads. */
28
+ class Refused extends Error {
29
+ status;
30
+ constructor(status, message) {
31
+ super(message);
32
+ this.status = status;
33
+ }
34
+ }
35
+ const fail = (message) => { throw new Refused('failed', message); };
36
+ const short = (sha) => sha.slice(0, 7);
37
+ const FULL_SHA = /^([0-9a-f]{40}|[0-9a-f]{64})$/;
38
+ /** Operations git leaves a marker for while they are under way in a checkout. */
39
+ const IN_PROGRESS = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply', 'BISECT_LOG'];
40
+ /** No hook of the developer's runs while the branch moves (post-merge, reference-transaction): the write is only ours. */
41
+ const NO_HOOKS = ['-c', `core.hooksPath=${devNull}`];
42
+ /** Files named in a refusal; the rest are counted. */
43
+ const LISTED_PATHS = 3;
44
+ const commitOf = async (top, name) => (await git(top, ['rev-parse', '--verify', '--quiet', `${name}^{commit}`]).catch(() => '')).trim() || null;
45
+ const contains = (top, ancestor, descendant) => git(top, ['merge-base', '--is-ancestor', ancestor, descendant]).then(() => true, () => false);
46
+ const exists = (path) => lstat(path).then(() => true, () => false);
47
+ const listPaths = (paths) => paths.slice(0, LISTED_PATHS).join(', ') + (paths.length > LISTED_PATHS ? ` and ${paths.length - LISTED_PATHS} more` : '');
48
+ async function toplevel(repoDir) {
49
+ const top = (await git(repoDir, ['rev-parse', '--show-toplevel']).catch(() => '')).trim();
50
+ return top || fail(`${repoDir} is not a git repository, so the proposal cannot be applied here.`);
51
+ }
52
+ /** This must be the room's repository: its origin when the room knows it, else its name. */
53
+ async function checkRepository(top, target) {
54
+ const { repo, remote } = target.repository;
55
+ if (remote) {
56
+ const origin = (await git(top, ['remote', 'get-url', 'origin']).catch(() => '')).trim();
57
+ const local = origin ? safeRemote(origin) : null;
58
+ if (local !== remote)
59
+ fail(`This checkout's origin is ${local ?? 'not set'}, not the room's ${remote}: wrong repository.`);
60
+ return;
61
+ }
62
+ if (repo && basename(top) !== repo)
63
+ fail(`This checkout is ${basename(top)}, not the room's ${repo}: wrong repository.`);
64
+ }
65
+ /** The kept result must be the approved commit, made on the base, for this room and request. */
66
+ async function checkProposal(top, roomId, target) {
67
+ const name = `CP${target.num}`;
68
+ if (!FULL_SHA.test(target.commit) || !FULL_SHA.test(target.base_sha))
69
+ fail(`${name}'s commits are not full commit ids.`);
70
+ const ref = resultRef(roomId, target.request_id);
71
+ const kept = await commitOf(top, ref);
72
+ if (!kept)
73
+ fail(`${name}'s change is no longer in this repository (${ref} is missing), so it cannot be applied.`);
74
+ if (kept !== target.commit)
75
+ fail(`${ref} is at ${short(kept)}, not the approved ${short(target.commit)}.`);
76
+ const [, ...parents] = (await git(top, ['rev-list', '--parents', '-n', '1', target.commit])).trim().split(' ');
77
+ if (parents.length !== 1 || parents[0] !== target.base_sha)
78
+ fail(`${name}'s commit does not start from ${short(target.base_sha)}.`);
79
+ const trailer = async (key) => (await git(top, ['log', '-1', `--format=%(trailers:key=${key},valueonly)`, target.commit])).trim();
80
+ if (await trailer('Converge-Room') !== roomId || await trailer('Converge-Request') !== target.request_id) {
81
+ fail(`${short(target.commit)} was not made for this room's request, so it is not ${name}.`);
82
+ }
83
+ }
84
+ async function checkBranchName(top, branch) {
85
+ const ok = !branch.startsWith('-') && await git(top, ['check-ref-format', `refs/heads/${branch}`]).then(() => true, () => false);
86
+ if (!ok)
87
+ fail(`"${branch}" is not a branch name.`);
88
+ return `refs/heads/${branch}`;
89
+ }
90
+ /** The checkouts that have `branchRef` checked out, as real paths. */
91
+ async function checkedOutAt(top, branchRef) {
92
+ const listing = await git(top, ['worktree', 'list', '--porcelain', '-z']);
93
+ const places = [];
94
+ for (const entry of listing.split('\0\0')) {
95
+ const fields = entry.split('\0');
96
+ const path = fields.find((f) => f.startsWith('worktree '))?.slice('worktree '.length);
97
+ if (path && fields.includes(`branch ${branchRef}`))
98
+ places.push(await realpath(path).catch(() => path));
99
+ }
100
+ return places;
101
+ }
102
+ /** The branch moved on from the base: say whether the proposal would conflict with it, without touching anything. */
103
+ async function diverged(top, branch, head, target) {
104
+ const name = `CP${target.num}`;
105
+ const moved = `${branch} has moved on to ${short(head)} since ${name} was made from ${short(target.base_sha)}`;
106
+ const merged = await git(top, ['merge-tree', '--write-tree', '--name-only', '--no-messages', head, target.commit])
107
+ .then(() => null, (err) => (err.code === 1 ? String(err.stdout ?? '') : undefined));
108
+ if (merged === undefined)
109
+ return fail(`${moved}.`);
110
+ if (merged !== null) {
111
+ const files = merged.split('\n').slice(1).filter(Boolean);
112
+ throw new Refused('conflict', `${moved}, and ${name} conflicts with it in ${listPaths(files)}. Nothing was changed.`);
113
+ }
114
+ return fail(`${moved}. ${name} would not conflict, but it was approved on ${short(target.base_sha)}: ask your agent for a new proposal on ${branch}.`);
115
+ }
116
+ /** The checkout the branch is in must hold nothing the fast-forward could lose. */
117
+ /**
118
+ * The paths `git status --porcelain=v1 -z` lists. Each entry is "XY path"; a rename or copy is followed by one more
119
+ * entry, its original path, without the "XY " in front.
120
+ */
121
+ function statusPaths(output) {
122
+ const entries = output.split('\0').filter(Boolean);
123
+ const paths = [];
124
+ for (let i = 0; i < entries.length; i++) {
125
+ paths.push(entries[i].slice(3));
126
+ if (/^[RC]|^.[RC]/.test(entries[i]))
127
+ i++;
128
+ }
129
+ return paths;
130
+ }
131
+ /**
132
+ * What on disk stands where the proposal adds `path`: the path itself, or a folder on the way to it that is a file
133
+ * (git would delete an ignored one to make the folder).
134
+ */
135
+ async function standingIn(top, path) {
136
+ const parts = path.split('/');
137
+ for (let depth = 1; depth < parts.length; depth++) {
138
+ const folder = parts.slice(0, depth).join('/');
139
+ const found = await lstat(join(top, folder)).catch(() => null);
140
+ if (!found)
141
+ return null;
142
+ if (!found.isDirectory())
143
+ return folder;
144
+ }
145
+ return await exists(join(top, path)) ? path : null;
146
+ }
147
+ async function checkCheckout(top, branch, target) {
148
+ const changed = statusPaths(await git(top, ['status', '--porcelain=v1', '-z', '--untracked-files=no']));
149
+ if (changed.length) {
150
+ fail(`${branch} is checked out with uncommitted changes (${listPaths(changed)}). Commit or stash them, then apply again.`);
151
+ }
152
+ for (const marker of IN_PROGRESS) {
153
+ const path = (await git(top, ['rev-parse', '--git-path', marker])).trim();
154
+ if (await exists(join(top, path)) || await exists(path))
155
+ fail(`A git operation is in progress in this checkout (${marker}). Finish or abort it, then apply again.`);
156
+ }
157
+ // Untracked and ignored files are not in the status above, and git replaces ignored ones without asking.
158
+ const added = (await git(top, ['diff', '--name-only', '-z', '--no-renames', '--diff-filter=A', target.base_sha, target.commit]))
159
+ .split('\0').filter(Boolean);
160
+ const inTheWay = new Set();
161
+ for (const path of added) {
162
+ const standing = await standingIn(top, path);
163
+ if (standing)
164
+ inTheWay.add(standing);
165
+ }
166
+ if (inTheWay.size) {
167
+ throw new Refused('conflict', `CP${target.num} adds files where ${listPaths([...inTheWay])} already exist in this checkout. Move them, then apply again.`);
168
+ }
169
+ }
170
+ /** Verifies everything, then fast-forwards the branch to the proposal's commit. Never throws: refusals are outcomes. */
171
+ export async function applyProposal(repoDir, roomId, target) {
172
+ try {
173
+ const top = await toplevel(repoDir);
174
+ await checkRepository(top, target);
175
+ await checkProposal(top, roomId, target);
176
+ const branchRef = await checkBranchName(top, target.branch);
177
+ const head = await commitOf(top, branchRef);
178
+ if (!head)
179
+ fail(`There is no branch ${target.branch} in this repository.`);
180
+ // Already there (applied by hand, or an earlier attempt whose report was lost): nothing to do.
181
+ if (head === target.commit || await contains(top, target.commit, head))
182
+ return { status: 'applied', result_commit: target.commit };
183
+ if (head !== target.base_sha)
184
+ await diverged(top, target.branch, head, target);
185
+ const places = await checkedOutAt(top, branchRef);
186
+ const here = await realpath(top);
187
+ const elsewhere = places.filter((place) => place !== here);
188
+ if (elsewhere.length)
189
+ fail(`${target.branch} is checked out in another worktree (${elsewhere[0]}); apply it from there, or switch that worktree away.`);
190
+ if (places.length) {
191
+ await checkCheckout(top, target.branch, target);
192
+ await git(top, [...NO_HOOKS, 'merge', '--ff-only', '--no-stat', '--quiet', target.commit]);
193
+ }
194
+ else {
195
+ await git(top, [...NO_HOOKS, 'update-ref', '-m', `converge: apply CP${target.num}`, branchRef, target.commit, target.base_sha]);
196
+ }
197
+ const now = await commitOf(top, branchRef);
198
+ if (now !== target.commit)
199
+ fail(`${target.branch} is at ${short(now ?? 'nothing')} after applying, not ${short(target.commit)}: check it.`);
200
+ return { status: 'applied', result_commit: target.commit };
201
+ }
202
+ catch (err) {
203
+ if (err instanceof Refused)
204
+ return { status: err.status, reason: err.message.slice(0, MAX_REASON_CHARS) };
205
+ // Git refused the write itself (the branch or the checkout changed after the checks): it changed nothing.
206
+ const detail = String(err.stderr ?? err.message).trim().split('\n')[0];
207
+ return { status: 'failed', reason: `Git refused to apply it, and nothing was changed: ${detail}`.slice(0, MAX_REASON_CHARS) };
208
+ }
209
+ }
210
+ /**
211
+ * An application this bridge was working on when it stopped. It is never run again: the branch says what happened,
212
+ * and that is reported. Applying only ever moves the branch from the base to the commit, so a branch that does not
213
+ * contain the commit was not applied to, wherever it is; only one still at the base may hold a checkout that was being
214
+ * updated when it stopped.
215
+ */
216
+ export async function reconcileApplication(repoDir, target) {
217
+ const failed = (reason) => ({ status: 'failed', reason: reason.slice(0, MAX_REASON_CHARS) });
218
+ try {
219
+ const top = await toplevel(repoDir);
220
+ const head = await commitOf(top, `refs/heads/${target.branch}`);
221
+ if (head && (head === target.commit || await contains(top, target.commit, head)))
222
+ return { status: 'applied', result_commit: target.commit };
223
+ if (head !== target.base_sha) {
224
+ return failed(`Interrupted, and CP${target.num} was not applied: ${target.branch} is at ${head ? short(head) : 'nothing'}, not CP${target.num}'s base ${short(target.base_sha)}.`);
225
+ }
226
+ const here = await realpath(top);
227
+ const checkedOutHere = (await checkedOutAt(top, `refs/heads/${target.branch}`)).includes(here);
228
+ const changed = checkedOutHere && (await git(top, ['status', '--porcelain', '--untracked-files=no'])).trim();
229
+ return failed(changed
230
+ ? `Interrupted while applying CP${target.num}: ${target.branch} is still at ${short(head)}, but the checkout has uncommitted changes. Check \`git status\` before applying again.`
231
+ : `Interrupted before anything changed: ${target.branch} is still at ${short(head)}. Apply again when ready.`);
232
+ }
233
+ catch (err) {
234
+ return failed(`Interrupted while applying CP${target.num}, and the branch could not be checked: ${err.message}`);
235
+ }
236
+ }
@@ -0,0 +1,57 @@
1
+ // How a bridge describes itself and its connection problems (docs/review-room.md, decision 37). The relay shows the
2
+ // version and build to the room, so a bridge started before an update (an old detached process still holding the
3
+ // grant) is told apart from a current one; the descriptions turn a close code or a socket error into the one line a
4
+ // developer reading the agent's log can act on. Nothing here ever includes the agent's token: it travels only inside
5
+ // the `auth` frame and the Authorization header.
6
+ import { execFileSync } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ /**
9
+ * The bridge's protocol version, raised whenever a bridge needs to change for the room to work (apps/api
10
+ * bridge_status.py BRIDGE_VERSION). A bridge older than the relay's is outdated; bridges from before this existed
11
+ * send none and count as 0. 2: keeps a revision's result on its proposal's base (ClaimedRequest `base`).
12
+ */
13
+ export const BRIDGE_VERSION = 2;
14
+ /** A build as the relay accepts it (apps/api bridge_status.py BUILD_PATTERN): a short commit id or a version. */
15
+ export const BUILD_PATTERN = /^[A-Za-z0-9._-]{1,40}$/;
16
+ /** While connected, authorized requests are listed again this often, so a lost hint costs at most this long. */
17
+ export const RECONCILE_INTERVAL_MS = 60_000;
18
+ let build;
19
+ /** The commit of the bridge's own checkout, read once; null where that is not a git checkout. */
20
+ export function bridgeBuild() {
21
+ if (build !== undefined)
22
+ return build;
23
+ try {
24
+ const sha = execFileSync('git', ['rev-parse', '--short=12', 'HEAD'], {
25
+ cwd: fileURLToPath(new URL('.', import.meta.url)), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
26
+ }).trim();
27
+ build = BUILD_PATTERN.test(sha) ? sha : null;
28
+ }
29
+ catch {
30
+ build = null;
31
+ }
32
+ return build;
33
+ }
34
+ /** What the relay's close code means for someone reading the log; the permanent ones are bridge.ts PERMANENT_CLOSES. */
35
+ const CLOSE_MEANINGS = {
36
+ 1000: 'the relay closed the connection',
37
+ 1001: 'the relay is shutting down or restarting',
38
+ 1006: 'the connection dropped without a close (network loss, sleep, or the relay restarted)',
39
+ 1011: 'the relay hit an internal error',
40
+ 1012: 'the relay is restarting (a deploy)',
41
+ 1013: 'the relay is overloaded; try again later',
42
+ };
43
+ export function describeClose(code) {
44
+ return CLOSE_MEANINGS[code] ?? 'the connection closed';
45
+ }
46
+ /** A socket error as a cause and what to check; the error's own message when it is none of the known ones. */
47
+ export function describeConnectError(err) {
48
+ if (err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN')
49
+ return `cannot resolve the relay's address (DNS: ${err.code}); check the network or the relay URL`;
50
+ if (err.code === 'ECONNREFUSED')
51
+ return 'the relay refused the connection; it is not running at that address';
52
+ if (err.code === 'ECONNRESET' || err.code === 'ETIMEDOUT')
53
+ return `the network connection to the relay failed (${err.code})`;
54
+ if (/handshake has timed out/i.test(err.message))
55
+ return 'the relay did not answer the WebSocket handshake in time';
56
+ return err.message;
57
+ }
package/dist/bridge.js ADDED
@@ -0,0 +1,203 @@
1
+ import WebSocket from 'ws';
2
+ import { BRIDGE_VERSION, bridgeBuild, describeClose, describeConnectError, RECONCILE_INTERVAL_MS } from './bridge-health.js';
3
+ import { SharedStore } from './shared.js';
4
+ // Close codes from the relay that mean "do not reconnect".
5
+ const PERMANENT_CLOSES = {
6
+ 4401: 'agent authorization rejected',
7
+ 4403: 'agent authorization revoked (left the room)',
8
+ 4409: 'replaced by another bridge using the same authorization',
9
+ };
10
+ export const toWsUrl = (apiUrl) => apiUrl.replace(/^http/, 'ws').replace(/\/$/, '');
11
+ const MAX_RETRY_MS = 30_000;
12
+ const REQUEST_HINTS = ['authorized', 'cancelled'];
13
+ /**
14
+ * `heartbeatMs`: how often the relay must answer a ping. A connection that misses one is dropped and
15
+ * re-established, so a link that died silently (sleep, tunnel restart) does not leave the agent looking connected.
16
+ * Each ping goes with a `heartbeat` frame, which the relay records as the bridge's last-seen time.
17
+ * `instance`: this process's id, sent with the bridge's version and build so `/converge join` can tell it came online
18
+ * rather than an older process still holding the grant (cli.ts connect).
19
+ * `reconcileMs`: how often, while connected, the implementations are asked to look again for authorized requests,
20
+ * besides every connect and each hint: a hint lost with a dropped connection is not waited on until the next drop.
21
+ * `comments`: the owner's agent keeps the store in a file and matches it to new snapshots (comment-host.ts).
22
+ * `implementations`: the member's authorized requests, claimed and prepared apart from the agent's questions, which
23
+ * stay read-only (implementation-runner.ts).
24
+ * `applications`: approved proposals the member asked to apply, done by this process, never by the agent (applications.ts).
25
+ */
26
+ export function runBridge(opts) {
27
+ const { apiUrl, roomId, agentToken, adapter, heartbeatMs = 30_000, comments, implementations, applications, instance, reconcileMs = RECONCILE_INTERVAL_MS } = opts;
28
+ const hello = { version: BRIDGE_VERSION, build: bridgeBuild(), instance: instance ?? null };
29
+ // Kept across reconnects: if this is the room owner's bridge, it holds the room's comments and threads.
30
+ const shared = comments?.shared ?? new SharedStore();
31
+ const url = `${toWsUrl(apiUrl)}/ws/bridge/${encodeURIComponent(roomId)}`;
32
+ let busy = false;
33
+ let retryMs = 1000;
34
+ // Connection attempts since the last one the relay accepted, so the log says how long the relay has been away.
35
+ let failedAttempts = 0;
36
+ // Each job remembers the connection its prompt arrived on. The relay forgets a request when that connection
37
+ // closes, so output for it must never go out over a newer one.
38
+ const queue = [];
39
+ // The job the adapter is running, so a `stop` from the relay can end it.
40
+ let running = null;
41
+ const sendOn = (socket) => (event) => {
42
+ if (socket.readyState === WebSocket.OPEN)
43
+ socket.send(JSON.stringify(event));
44
+ };
45
+ // Serialized: one agent process per session at a time.
46
+ async function drain() {
47
+ if (busy)
48
+ return;
49
+ busy = true;
50
+ while (queue.length) {
51
+ const { job, socket } = queue.shift();
52
+ const send = sendOn(socket);
53
+ running = { id: job.id, controller: new AbortController() };
54
+ try {
55
+ await adapter.run(job, send, running.controller.signal);
56
+ }
57
+ catch (err) {
58
+ console.error(`${adapter.label} bridge failure:`, err);
59
+ send({ type: 'failure', id: job.id, content: 'Agent execution failed; check bridge terminal.' });
60
+ }
61
+ finally {
62
+ running = null;
63
+ }
64
+ }
65
+ busy = false;
66
+ }
67
+ return new Promise((stopped) => {
68
+ const connect = () => {
69
+ const socket = new WebSocket(url, { handshakeTimeout: heartbeatMs });
70
+ let alive = true;
71
+ const sendShared = () => {
72
+ if (socket.readyState === WebSocket.OPEN)
73
+ socket.send(JSON.stringify({ type: 'shared_state', state: shared.get() }));
74
+ };
75
+ let heartbeat;
76
+ let reconcile;
77
+ let missedHeartbeat = false;
78
+ socket.on('open', () => {
79
+ socket.send(JSON.stringify({ type: 'auth', token: agentToken, bridge: hello }));
80
+ heartbeat = setInterval(() => {
81
+ if (!alive) {
82
+ missedHeartbeat = true;
83
+ socket.terminate();
84
+ return;
85
+ }
86
+ alive = false;
87
+ socket.ping();
88
+ socket.send(JSON.stringify({ type: 'heartbeat' }));
89
+ }, heartbeatMs);
90
+ });
91
+ socket.on('pong', () => { alive = true; });
92
+ socket.on('message', (raw) => {
93
+ alive = true;
94
+ try {
95
+ const event = JSON.parse(raw.toString());
96
+ if (event.type === 'authenticated') {
97
+ retryMs = 1000;
98
+ failedAttempts = 0;
99
+ console.log(`${adapter.label} bridge connected to room ${roomId}${event.host === true ? ' (holds the room\'s comments)' : ''}` +
100
+ ` · bridge version ${BRIDGE_VERSION}${hello.build ? ` (${hello.build})` : ''}`);
101
+ if (event.outdated === true) {
102
+ console.error(`This bridge (version ${BRIDGE_VERSION}) is older than the relay expects (version ${event.bridge_version}). ` +
103
+ 'Update Converge, then restart the agent with "/converge join <room>"; its access is kept.');
104
+ }
105
+ // On every connect: the relay keeps the list only while this connection lasts.
106
+ void adapter.skills().then((skills) => {
107
+ if (socket.readyState === WebSocket.OPEN)
108
+ socket.send(JSON.stringify({ type: 'skills', skills }));
109
+ });
110
+ // Commits may have landed while this bridge was away: match the comments to what the room shows now.
111
+ if (event.host === true)
112
+ void comments?.refresh().then((moved) => { if (moved)
113
+ sendShared(); });
114
+ // Requests authorized or interrupted while this bridge was away: the relay sends no hint for those.
115
+ // Then again every `reconcileMs`, in case a hint is lost; the relay's claim keeps each request to one run.
116
+ void implementations?.discover();
117
+ clearInterval(reconcile);
118
+ if (implementations)
119
+ reconcile = setInterval(() => void implementations.discover(), reconcileMs);
120
+ // Applies asked for, or interrupted, while this bridge was away.
121
+ void applications?.discover();
122
+ return;
123
+ }
124
+ // Its requester asked for an unavailable Change Proposal again: look for every proposal still to share.
125
+ if (event.type === 'change_proposal_share') {
126
+ void implementations?.discover();
127
+ return;
128
+ }
129
+ // Its member asked to apply an approved proposal: claimed, checked again by the relay, then applied here.
130
+ if (event.type === 'change_proposal_apply') {
131
+ if (typeof event.id === 'string')
132
+ applications?.hint(event.id);
133
+ return;
134
+ }
135
+ if (event.type === 'implementation_request') {
136
+ if (typeof event.id === 'string' && REQUEST_HINTS.includes(event.status))
137
+ implementations?.hint(event.id, event.status);
138
+ return;
139
+ }
140
+ // The relay sends these only to the room's current host, which can change after this bridge connected
141
+ // (the owner's other bridge left), so answer whenever asked. Ops that change nothing get no answer.
142
+ if (event.type === 'shared_sync') {
143
+ sendShared();
144
+ return;
145
+ }
146
+ if (event.type === 'shared_op') {
147
+ if (shared.apply(event.op, event.actor)) {
148
+ sendShared();
149
+ comments?.save();
150
+ }
151
+ return;
152
+ }
153
+ if (event.type === 'review_updated') {
154
+ void comments?.refresh(event.review?.head_sha).then((moved) => { if (moved)
155
+ sendShared(); });
156
+ return;
157
+ }
158
+ // The member stopped a question (the relay checks it is theirs): one still waiting is dropped, the one
159
+ // running is ended and its adapter says so.
160
+ if (event.type === 'stop' && typeof event.id === 'string') {
161
+ const waiting = queue.findIndex((q) => q.job.id === event.id);
162
+ if (waiting >= 0)
163
+ sendOn(queue.splice(waiting, 1)[0].socket)({ type: 'stopped', id: event.id });
164
+ else if (running && running.id === event.id)
165
+ running.controller.abort();
166
+ return;
167
+ }
168
+ if (event.type !== 'prompt' || typeof event.id !== 'string' || typeof event.content !== 'string')
169
+ return;
170
+ if (queue.length >= 10) {
171
+ sendOn(socket)({ type: 'failure', id: event.id, content: 'Agent queue full.' });
172
+ return;
173
+ }
174
+ queue.push({ socket, job: { id: event.id, content: event.content, author: typeof event.author === 'string' ? event.author : undefined } });
175
+ void drain();
176
+ }
177
+ catch (err) {
178
+ console.error('Invalid relay event:', err);
179
+ }
180
+ });
181
+ socket.on('error', (err) => console.error(`Bridge connection error: ${describeConnectError(err)}`));
182
+ socket.on('close', (code, reason) => {
183
+ clearInterval(heartbeat);
184
+ clearInterval(reconcile);
185
+ // The relay fails in-flight requests on disconnect, so queued ones are stale.
186
+ queue.length = 0;
187
+ const permanent = PERMANENT_CLOSES[code];
188
+ if (permanent) {
189
+ console.log(`Bridge stopped: ${permanent}${reason.length ? ` (${reason})` : ''}`);
190
+ stopped(permanent);
191
+ return;
192
+ }
193
+ failedAttempts++;
194
+ const why = missedHeartbeat ? `the relay stopped answering pings for ${heartbeatMs / 1000}s` : describeClose(code);
195
+ console.log(`Bridge disconnected (${code}: ${why}${reason.length ? `, ${reason}` : ''}); ` +
196
+ `reconnecting in ${retryMs / 1000}s${failedAttempts > 1 ? ` (attempt ${failedAttempts})` : ''}`);
197
+ setTimeout(connect, retryMs);
198
+ retryMs = Math.min(retryMs * 2, MAX_RETRY_MS);
199
+ });
200
+ };
201
+ connect();
202
+ });
203
+ }
@@ -0,0 +1,51 @@
1
+ import { readResult } from './implementation-results.js';
2
+ import { api, RelayError } from './relay.js';
3
+ export const RESULT_GONE = "The change is no longer in the requester's repository, so its code can't be shown.";
4
+ export const RESULT_DIFFERS = "The change in the requester's repository is not the one this proposal recorded.";
5
+ const REFUSED = 'The relay did not accept the change as this proposal\'s: ';
6
+ /**
7
+ * Sends one proposal's code, or says why it cannot be. Returns false only when the relay could not be reached, so
8
+ * the next connect tries again; a refusal is final for this attempt and is reported as unavailable.
9
+ */
10
+ export async function shareProposal(room, proposal) {
11
+ const call = (path, init) => api(`/agent-grants/self/change-proposals/${encodeURIComponent(proposal.id)}${path}`, { ...init, token: room.agentToken, base: room.apiUrl });
12
+ const unavailable = (reason, retryable = false) => call('/unavailable', { method: 'POST', body: JSON.stringify({ reason: reason.slice(0, 200), retryable }) });
13
+ try {
14
+ const kept = await readResult(room.projectDir, room.roomId, proposal.request_id).catch(() => null);
15
+ if (!kept) {
16
+ // Still missing: the room already says so, and saying it again on every connect would only repeat it.
17
+ if (proposal.status !== 'unavailable')
18
+ await unavailable(RESULT_GONE, true);
19
+ return true;
20
+ }
21
+ if (kept.result.commit !== proposal.commit) {
22
+ await unavailable(RESULT_DIFFERS);
23
+ return true;
24
+ }
25
+ try {
26
+ await call('/snapshot', { method: 'PUT', body: JSON.stringify(kept.snapshot) });
27
+ }
28
+ catch (err) {
29
+ if (!(err instanceof RelayError) || err.status >= 500)
30
+ throw err;
31
+ // Already shared (409) needs nothing; anything else the relay refused is shown to the room as the reason.
32
+ if (err.status !== 409)
33
+ await unavailable(REFUSED + err.message);
34
+ }
35
+ console.log(`Shared CP${proposal.num} with the room`);
36
+ return true;
37
+ }
38
+ catch (err) {
39
+ if (err instanceof RelayError && err.status < 500)
40
+ return true;
41
+ console.error(`Could not share CP${proposal.num}; trying again on the next connect:`, err.message);
42
+ return false;
43
+ }
44
+ }
45
+ /** Every proposal of this agent still to share: what was missed while the bridge or relay was away, and what was
46
+ * missing before and may be here now. */
47
+ export async function shareWaiting(room) {
48
+ const { proposals } = await api('/agent-grants/self/change-proposals', { token: room.agentToken, base: room.apiUrl });
49
+ for (const proposal of proposals)
50
+ await shareProposal(room, proposal);
51
+ }