@cirtium/acent-connect 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/acent/.claude-plugin/plugin.json +1 -1
- package/acent/.codex-plugin/plugin.json +1 -1
- package/acent/.cursor-plugin/plugin.json +1 -1
- package/acent/scripts/acent-connect.mjs +12 -3
- package/acent/scripts/bridge-checks.mjs +305 -0
- package/acent/scripts/bridge-finalize.mjs +233 -0
- package/acent/scripts/bridge-refinement.mjs +1073 -0
- package/acent/scripts/bridge-retention.mjs +168 -0
- package/acent/scripts/bridge-runners.mjs +605 -0
- package/acent/scripts/bridge-workspace.mjs +512 -0
- package/acent/scripts/bridge.mjs +1330 -0
- package/acent/scripts/capture-attachments.mjs +23 -8
- package/acent/scripts/host-executables.mjs +56 -0
- package/acent/scripts/mcp-proxy.mjs +70 -11
- package/acent/scripts/plugin-updates.mjs +184 -0
- package/acent/skills/acent-bridge/SKILL.md +18 -0
- package/acent/skills/acent-bridge/agents/openai.yaml +4 -0
- package/antigravity/plugin.json +1 -1
- package/package.json +1 -1
- package/scripts/install-plugin.mjs +2 -41
|
@@ -0,0 +1,1330 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
2
|
+
import {
|
|
3
|
+
mkdir,
|
|
4
|
+
readFile,
|
|
5
|
+
readdir,
|
|
6
|
+
realpath,
|
|
7
|
+
rename,
|
|
8
|
+
rm,
|
|
9
|
+
stat,
|
|
10
|
+
writeFile,
|
|
11
|
+
} from "node:fs/promises"
|
|
12
|
+
import { homedir } from "node:os"
|
|
13
|
+
import { dirname, join } from "node:path"
|
|
14
|
+
import { setTimeout as pause } from "node:timers/promises"
|
|
15
|
+
import { lock } from "./acent-connect.mjs"
|
|
16
|
+
import { createBridgeFinalizer } from "./bridge-finalize.mjs"
|
|
17
|
+
import { createBridgeRetention } from "./bridge-retention.mjs"
|
|
18
|
+
import {
|
|
19
|
+
createBridgeRefinement,
|
|
20
|
+
reviewFindings,
|
|
21
|
+
reviewFormat,
|
|
22
|
+
} from "./bridge-refinement.mjs"
|
|
23
|
+
import {
|
|
24
|
+
applyVersionedBridgePatch,
|
|
25
|
+
bridgeReviewDiff,
|
|
26
|
+
cloneBridgeSnapshot,
|
|
27
|
+
inspectBridgeChanges,
|
|
28
|
+
mismatchedBridgePaths,
|
|
29
|
+
pathsOverlap,
|
|
30
|
+
projectSnapshot,
|
|
31
|
+
workspacePath,
|
|
32
|
+
} from "./bridge-workspace.mjs"
|
|
33
|
+
import {
|
|
34
|
+
bridgeAccountRevision,
|
|
35
|
+
bridgeTargets,
|
|
36
|
+
discoverBridgeTarget,
|
|
37
|
+
executeBridgeTarget,
|
|
38
|
+
modelFamily,
|
|
39
|
+
readBridgeQuota,
|
|
40
|
+
} from "./bridge-runners.mjs"
|
|
41
|
+
|
|
42
|
+
const text = (description) => ({ type: "string", description })
|
|
43
|
+
const toolSchema = (name, description, properties, required = []) => ({
|
|
44
|
+
name,
|
|
45
|
+
description,
|
|
46
|
+
inputSchema: {
|
|
47
|
+
type: "object",
|
|
48
|
+
properties,
|
|
49
|
+
required,
|
|
50
|
+
additionalProperties: false,
|
|
51
|
+
},
|
|
52
|
+
})
|
|
53
|
+
const target = { type: "string", enum: bridgeTargets }
|
|
54
|
+
const kind = { type: "string", enum: ["review", "diagnose", "implement"] }
|
|
55
|
+
const idList = {
|
|
56
|
+
type: "array",
|
|
57
|
+
items: text("Bridge task ID"),
|
|
58
|
+
uniqueItems: true,
|
|
59
|
+
maxItems: 4,
|
|
60
|
+
}
|
|
61
|
+
const maxParallel = 4
|
|
62
|
+
const selection = {
|
|
63
|
+
type: "object",
|
|
64
|
+
properties: {
|
|
65
|
+
tool: target,
|
|
66
|
+
model: text("Verified model ID from the candidate list."),
|
|
67
|
+
},
|
|
68
|
+
required: ["tool", "model"],
|
|
69
|
+
additionalProperties: false,
|
|
70
|
+
}
|
|
71
|
+
const checks = {
|
|
72
|
+
type: "array",
|
|
73
|
+
description: "Optional observations supplied by legacy callers.",
|
|
74
|
+
maxItems: 12,
|
|
75
|
+
items: {
|
|
76
|
+
type: "object",
|
|
77
|
+
properties: {
|
|
78
|
+
name: text("Check or command actually run"),
|
|
79
|
+
outcome: { type: "string", enum: ["passed", "failed", "not_run"] },
|
|
80
|
+
evidence: text("Relevant result or reason it could not run."),
|
|
81
|
+
},
|
|
82
|
+
required: ["name", "outcome", "evidence"],
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
const commands = (minItems) => ({
|
|
87
|
+
type: "array",
|
|
88
|
+
minItems,
|
|
89
|
+
maxItems: 12,
|
|
90
|
+
items: {
|
|
91
|
+
type: "object",
|
|
92
|
+
properties: {
|
|
93
|
+
command: text("Executable authorized by the coordinating agent."),
|
|
94
|
+
args: { type: "array", items: text("Literal argument"), maxItems: 48 },
|
|
95
|
+
},
|
|
96
|
+
required: ["command", "args"],
|
|
97
|
+
additionalProperties: false,
|
|
98
|
+
},
|
|
99
|
+
})
|
|
100
|
+
const checkCommands = {
|
|
101
|
+
commands: commands(1),
|
|
102
|
+
setupCommands: {
|
|
103
|
+
...commands(0),
|
|
104
|
+
description:
|
|
105
|
+
"Optional dependency preparation for the private test copy. Defaults to a locked npm install when applicable. Use an empty array to skip setup.",
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
export const bridgeTools = [
|
|
109
|
+
toolSchema(
|
|
110
|
+
"acent_bridge_settings",
|
|
111
|
+
"Read the connected project's Bridge settings. Users change them in the project's Bridge dialog in Acent.",
|
|
112
|
+
{}
|
|
113
|
+
),
|
|
114
|
+
toolSchema(
|
|
115
|
+
"acent_bridge_candidates",
|
|
116
|
+
"List locally available tool and model combinations for a new Bridge task. For review or diagnosis, specify the verified model ID used for the original work. Omit a tool to consider all enabled tools.",
|
|
117
|
+
{
|
|
118
|
+
kind,
|
|
119
|
+
originModel: text("Actual model ID of the original work"),
|
|
120
|
+
tool: target,
|
|
121
|
+
automatic: {
|
|
122
|
+
type: "boolean",
|
|
123
|
+
description:
|
|
124
|
+
"True for delegation initiated by the agent without an explicit user delegation request.",
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
["kind"]
|
|
128
|
+
),
|
|
129
|
+
toolSchema(
|
|
130
|
+
"acent_bridge_start",
|
|
131
|
+
"Start one authorized task in a private project copy. Select a candidate from acent_bridge_candidates. The result includes a task ID for acent_bridge_status. Up to four tasks can run concurrently per working folder. Parallel writes require disjoint paths.",
|
|
132
|
+
{
|
|
133
|
+
kind,
|
|
134
|
+
originModel: text("Actual model ID of the original work"),
|
|
135
|
+
tool: target,
|
|
136
|
+
model: text(
|
|
137
|
+
"Model ID from the candidates list. Omit for the tool default."
|
|
138
|
+
),
|
|
139
|
+
task: text(
|
|
140
|
+
"Concrete task, relevant files, constraints, and what has already been tried."
|
|
141
|
+
),
|
|
142
|
+
acceptance: text("How to verify that the task is complete."),
|
|
143
|
+
context: text(
|
|
144
|
+
"Relevant decisions, code context, errors, and results from the coordinating agent."
|
|
145
|
+
),
|
|
146
|
+
paths: {
|
|
147
|
+
type: "array",
|
|
148
|
+
items: text("A relative file or directory the delegate may change."),
|
|
149
|
+
maxItems: 64,
|
|
150
|
+
},
|
|
151
|
+
dependsOn: idList,
|
|
152
|
+
requestId: text(
|
|
153
|
+
"Optional UUID reused for an exact retry of this request."
|
|
154
|
+
),
|
|
155
|
+
automatic: { type: "boolean" },
|
|
156
|
+
},
|
|
157
|
+
["kind", "tool", "task", "acceptance"]
|
|
158
|
+
),
|
|
159
|
+
toolSchema(
|
|
160
|
+
"acent_bridge_status",
|
|
161
|
+
"Read task progress, a context question, or the result and patch. Review the patch before applying it to the original project.",
|
|
162
|
+
{ id: text("Bridge task ID") },
|
|
163
|
+
["id"]
|
|
164
|
+
),
|
|
165
|
+
toolSchema(
|
|
166
|
+
"acent_bridge_activity",
|
|
167
|
+
"List recent Bridge tasks for this project with their current status and context questions.",
|
|
168
|
+
{}
|
|
169
|
+
),
|
|
170
|
+
toolSchema(
|
|
171
|
+
"acent_bridge_cancel",
|
|
172
|
+
"Cancel an active Bridge task when the user stops the work or it is no longer needed. Partial changes are preserved.",
|
|
173
|
+
{ id: text("Bridge task ID") },
|
|
174
|
+
["id"]
|
|
175
|
+
),
|
|
176
|
+
toolSchema(
|
|
177
|
+
"acent_bridge_integrate",
|
|
178
|
+
"Check completed patches together against the current folder, or apply them after review. By default this only checks for overlap and local changes. Apply only within the user's authorized editing scope, then run integration tests.",
|
|
179
|
+
{
|
|
180
|
+
ids: idList,
|
|
181
|
+
apply: { type: "boolean" },
|
|
182
|
+
},
|
|
183
|
+
["ids"]
|
|
184
|
+
),
|
|
185
|
+
toolSchema(
|
|
186
|
+
"acent_bridge_finalize",
|
|
187
|
+
"Verify independently reviewed, integrated work using actual commands in a private copy. Submit commands to start and omit them to poll. The full reviewed snapshot must still match.",
|
|
188
|
+
{
|
|
189
|
+
ids: idList,
|
|
190
|
+
reviewId: text("Completed independent review task ID."),
|
|
191
|
+
action: { type: "string", enum: ["cancel"] },
|
|
192
|
+
reviewOutcome: {
|
|
193
|
+
type: "string",
|
|
194
|
+
enum: ["cleared", "changes_requested"],
|
|
195
|
+
description:
|
|
196
|
+
"Use cleared only after assessing the independent review and resolving any blocking findings.",
|
|
197
|
+
},
|
|
198
|
+
checks,
|
|
199
|
+
...checkCommands,
|
|
200
|
+
},
|
|
201
|
+
["ids", "reviewId", "reviewOutcome"]
|
|
202
|
+
),
|
|
203
|
+
toolSchema(
|
|
204
|
+
"acent_bridge_continue",
|
|
205
|
+
"Resume the same task and work copy with an answer to its context question, or continue a failed/interrupted task using another eligible tool or model. Always pass through the original constraints; never report a partial patch as completed work.",
|
|
206
|
+
{
|
|
207
|
+
id: text("Bridge task ID"),
|
|
208
|
+
answer: text(
|
|
209
|
+
"Answer with the relevant decision, file location, or test output."
|
|
210
|
+
),
|
|
211
|
+
tool: target,
|
|
212
|
+
model: text("Model ID from the candidates list."),
|
|
213
|
+
},
|
|
214
|
+
["id"]
|
|
215
|
+
),
|
|
216
|
+
toolSchema(
|
|
217
|
+
"acent_bridge_refine",
|
|
218
|
+
"Review and repair in a private staging workspace. Replace an unavailable reviewer without discarding finished reviews. Run check commands against the reviewed candidate before it can be applied to the original project.",
|
|
219
|
+
{
|
|
220
|
+
action: {
|
|
221
|
+
type: "string",
|
|
222
|
+
enum: [
|
|
223
|
+
"start",
|
|
224
|
+
"status",
|
|
225
|
+
"replace_reviewer",
|
|
226
|
+
"apply",
|
|
227
|
+
"verify",
|
|
228
|
+
"cancel",
|
|
229
|
+
],
|
|
230
|
+
},
|
|
231
|
+
id: text(
|
|
232
|
+
"Stable UUID for this refinement, generated by the coordinating agent."
|
|
233
|
+
),
|
|
234
|
+
task: text("Original work and what to review."),
|
|
235
|
+
acceptance: text("What the final code must do and how to verify it."),
|
|
236
|
+
context: text("Relevant constraints, past decisions, and test context."),
|
|
237
|
+
originModel: text("Actual model ID of the original work."),
|
|
238
|
+
reviewers: { type: "array", minItems: 1, maxItems: 4, items: selection },
|
|
239
|
+
repair: selection,
|
|
240
|
+
paths: {
|
|
241
|
+
type: "array",
|
|
242
|
+
minItems: 1,
|
|
243
|
+
maxItems: 64,
|
|
244
|
+
items: text("Project-relative file or directory allowed for repairs."),
|
|
245
|
+
},
|
|
246
|
+
dependsOn: idList,
|
|
247
|
+
automatic: { type: "boolean" },
|
|
248
|
+
apply: {
|
|
249
|
+
type: "boolean",
|
|
250
|
+
description:
|
|
251
|
+
"At start, allow automatic application of scoped repairs when the user has authorized edits. Defaults to a patch checkpoint.",
|
|
252
|
+
},
|
|
253
|
+
reviewId: text("Failed or unavailable review task ID to replace."),
|
|
254
|
+
reviewer: selection,
|
|
255
|
+
checkRevision: text("Revision from needs_checks or patch_ready."),
|
|
256
|
+
...checkCommands,
|
|
257
|
+
},
|
|
258
|
+
["id"]
|
|
259
|
+
),
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
export const bridgeInstructions = [
|
|
263
|
+
"Use Acent Bridge when the user explicitly asks to delegate. For agent-initiated delegation, first check that acent_bridge_settings reports automatic=true, then pass automatic=true when listing candidates, starting a task, or starting refinement. Delegation is useful for independent review, difficult diagnoses, and implementation tasks with independent file scopes.",
|
|
264
|
+
"Get candidates for each new task and choose a tool and model that fit the work and the user's preference. Favor lower-usage options for routine work when verified quota is low and the user has not pinned a model. Start tasks with concrete acceptance criteria.",
|
|
265
|
+
"Check several jobs together with acent_bridge_activity while doing independent work. If a delegate requests context, answer from the conversation or ask the user if their judgment is needed, then continue. Use acent_bridge_integrate to check and apply completed diffs.",
|
|
266
|
+
"For substantive authorized edits with a defined write scope, use acent_bridge_refine to run independent review, repair and re-review. Select eligible models and set apply=true only within the user's authorized editing scope. Continue unrelated work while it runs.",
|
|
267
|
+
"At needs_checks, call verify with the current checkRevision and authorized test commands to run in the private staging workspace. For a pending verified patch, inspect and approve it with apply and checkRevision. Replace a failed reviewer with replace_reviewer and an eligible reviewer. Resolve context requests using acent_bridge_continue and then resume refinement status. For standalone review of integrated work, submit commands to acent_bridge_finalize and poll without commands until verification finishes. Use setupCommands if the private check copy needs project-specific preparation. Remain responsible for the final result.",
|
|
268
|
+
].join(" ")
|
|
269
|
+
|
|
270
|
+
const cacheDuration = 120_000
|
|
271
|
+
const leaseMaxAge = 20 * 60_000
|
|
272
|
+
const quotaMaxAge = 15 * 60_000
|
|
273
|
+
const xmlTag = /<acent-context>([\s\S]+?)<\/acent-context>\s*$/
|
|
274
|
+
const reviewOnly = (kind) => kind === "review" || kind === "diagnose"
|
|
275
|
+
const taskId = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
|
|
276
|
+
const isTaskId = (id) => typeof id === "string" && taskId.test(id)
|
|
277
|
+
function workerAlive(pid) {
|
|
278
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
279
|
+
try {
|
|
280
|
+
process.kill(pid, 0)
|
|
281
|
+
return true
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return error.code === "EPERM"
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async function readJson(path, fallback) {
|
|
288
|
+
try {
|
|
289
|
+
return JSON.parse(await readFile(path, "utf8"))
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error.code === "ENOENT") return fallback
|
|
292
|
+
throw error
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function writeJson(path, value) {
|
|
297
|
+
const temporary = path + "." + randomUUID()
|
|
298
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
|
299
|
+
try {
|
|
300
|
+
await writeFile(temporary, JSON.stringify(value), { mode: 0o600 })
|
|
301
|
+
await rename(temporary, path)
|
|
302
|
+
} finally {
|
|
303
|
+
await rm(temporary, { force: true })
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function withWorkspaceLock(directory, operation) {
|
|
308
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
309
|
+
const deadline = Date.now() + 2500
|
|
310
|
+
let value
|
|
311
|
+
while (Date.now() < deadline) {
|
|
312
|
+
if (
|
|
313
|
+
await lock(directory, async () => {
|
|
314
|
+
value = await operation()
|
|
315
|
+
})
|
|
316
|
+
)
|
|
317
|
+
return value
|
|
318
|
+
await pause(40)
|
|
319
|
+
}
|
|
320
|
+
throw new Error("Bridge is updating this project. Retry in a moment.")
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function taskState(job) {
|
|
324
|
+
if (job.workExpiredAt && !["completed", "applied"].includes(job.status))
|
|
325
|
+
return "workspace_expired"
|
|
326
|
+
if (
|
|
327
|
+
job.status === "running" &&
|
|
328
|
+
(!workerAlive(job.workerPid) ||
|
|
329
|
+
Date.now() - (job.startedAt ?? 0) >= leaseMaxAge)
|
|
330
|
+
)
|
|
331
|
+
return "interrupted"
|
|
332
|
+
return job.status
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function safeIds(ids) {
|
|
336
|
+
return (
|
|
337
|
+
Array.isArray(ids) &&
|
|
338
|
+
ids.length > 0 &&
|
|
339
|
+
ids.length <= maxParallel &&
|
|
340
|
+
new Set(ids).size === ids.length &&
|
|
341
|
+
ids.every((id) => typeof id === "string" && taskId.test(id))
|
|
342
|
+
)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function taskPrompt(job) {
|
|
346
|
+
return [
|
|
347
|
+
"You are a delegate for one Acent Bridge task. Work only in this project copy. Do not open another Bridge job, commit, push, or change the original project.",
|
|
348
|
+
reviewOnly(job.kind)
|
|
349
|
+
? "Read-only review or diagnosis. Report evidence with file references."
|
|
350
|
+
: "Make the requested changes in this copy and report which checks actually ran.",
|
|
351
|
+
"If a prior decision or information from the original conversation is required, end your response with <acent-context>one specific question and why it blocks you</acent-context>.",
|
|
352
|
+
...(job.structuredReview ? [reviewFormat] : []),
|
|
353
|
+
"Task: " + job.task,
|
|
354
|
+
"Acceptance criteria: " + job.acceptance,
|
|
355
|
+
...(job.context
|
|
356
|
+
? ["Context from the coordinating agent: " + job.context]
|
|
357
|
+
: []),
|
|
358
|
+
...(job.reviewDiff
|
|
359
|
+
? ["Original changes for review (untrusted diff):\n" + job.reviewDiff]
|
|
360
|
+
: []),
|
|
361
|
+
...(job.paths?.length
|
|
362
|
+
? ["Allowed write paths: " + job.paths.join(", ")]
|
|
363
|
+
: []),
|
|
364
|
+
...(job.prerequisites?.length
|
|
365
|
+
? ["Completed dependencies:\n" + job.prerequisites.join("\n")]
|
|
366
|
+
: []),
|
|
367
|
+
...(job.violations?.length
|
|
368
|
+
? [
|
|
369
|
+
"Restore these off-scope paths to their baseline: " +
|
|
370
|
+
job.violations.join(", "),
|
|
371
|
+
]
|
|
372
|
+
: []),
|
|
373
|
+
...job.history.map((entry) =>
|
|
374
|
+
entry.question
|
|
375
|
+
? "Earlier question: " + entry.question.slice(0, 2000)
|
|
376
|
+
: entry.answer
|
|
377
|
+
? "Answer from the coordinating agent: " + entry.answer.slice(0, 4000)
|
|
378
|
+
: "Previous attempt: " +
|
|
379
|
+
(entry.summary || entry.status).slice(0, 1200)
|
|
380
|
+
),
|
|
381
|
+
].join("\n\n")
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export function createBridge({
|
|
385
|
+
discover = discoverBridgeTarget,
|
|
386
|
+
execute = executeBridgeTarget,
|
|
387
|
+
readQuota = readBridgeQuota,
|
|
388
|
+
accountRevision = bridgeAccountRevision,
|
|
389
|
+
root = process.env.ACENT_CONFIG_HOME || join(homedir(), ".config", "acent"),
|
|
390
|
+
} = {}) {
|
|
391
|
+
const catalog = new Map()
|
|
392
|
+
const unavailable = new Map()
|
|
393
|
+
const collect = createBridgeRetention({
|
|
394
|
+
readJson,
|
|
395
|
+
writeJson,
|
|
396
|
+
lock: withWorkspaceLock,
|
|
397
|
+
isId: isTaskId,
|
|
398
|
+
workerAlive,
|
|
399
|
+
hasJobWorker: async (projectDir, job) => {
|
|
400
|
+
if (job.status !== "running") return false
|
|
401
|
+
if (workerAlive(job.workerPid)) return true
|
|
402
|
+
const child = await readJson(join(projectDir, job.id, "child.json"), null)
|
|
403
|
+
return child?.attempt === job.attempt && workerAlive(child?.pid)
|
|
404
|
+
},
|
|
405
|
+
})
|
|
406
|
+
const refine = createBridgeRefinement({
|
|
407
|
+
readJson,
|
|
408
|
+
writeJson,
|
|
409
|
+
lock: withWorkspaceLock,
|
|
410
|
+
isId: isTaskId,
|
|
411
|
+
targets: bridgeTargets,
|
|
412
|
+
jobState: taskState,
|
|
413
|
+
})
|
|
414
|
+
const finalize = createBridgeFinalizer({
|
|
415
|
+
readJson,
|
|
416
|
+
writeJson,
|
|
417
|
+
lock: withWorkspaceLock,
|
|
418
|
+
isId: isTaskId,
|
|
419
|
+
safeIds,
|
|
420
|
+
})
|
|
421
|
+
const modelKey = (folder, tool, model, accountKey) =>
|
|
422
|
+
JSON.stringify([folder, tool, model, accountKey ?? null])
|
|
423
|
+
|
|
424
|
+
function quotaPath(tool, accountKey) {
|
|
425
|
+
if (!/^[a-f0-9]{64}$/.test(accountKey ?? "")) return
|
|
426
|
+
return join(
|
|
427
|
+
root,
|
|
428
|
+
"bridge",
|
|
429
|
+
"usage",
|
|
430
|
+
createHash("sha256")
|
|
431
|
+
.update(JSON.stringify([tool, accountKey]))
|
|
432
|
+
.digest("hex") + ".json"
|
|
433
|
+
)
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function cachedQuota({ tool, accountKey }) {
|
|
437
|
+
const path = quotaPath(tool, accountKey)
|
|
438
|
+
if (!path) return { status: "unknown" }
|
|
439
|
+
const sample = await readJson(path, null).catch(() => null)
|
|
440
|
+
const now = Date.now()
|
|
441
|
+
if (
|
|
442
|
+
!Number.isFinite(sample?.checkedAt) ||
|
|
443
|
+
sample.checkedAt > now ||
|
|
444
|
+
now - sample.checkedAt >= quotaMaxAge ||
|
|
445
|
+
!Array.isArray(sample.windows)
|
|
446
|
+
)
|
|
447
|
+
return { status: "unknown" }
|
|
448
|
+
const windows = sample.windows.filter(
|
|
449
|
+
(window) =>
|
|
450
|
+
window && (window.resetsAt === undefined || window.resetsAt > now)
|
|
451
|
+
)
|
|
452
|
+
return windows.length
|
|
453
|
+
? { status: "reported", checkedAt: sample.checkedAt, windows }
|
|
454
|
+
: { status: "unknown" }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function getTarget(tool, folder) {
|
|
458
|
+
const key = JSON.stringify([folder, tool])
|
|
459
|
+
const revision = await accountRevision(tool)
|
|
460
|
+
const prior = catalog.get(key)
|
|
461
|
+
if (
|
|
462
|
+
prior &&
|
|
463
|
+
prior.revision === revision &&
|
|
464
|
+
Date.now() - prior.at < cacheDuration
|
|
465
|
+
)
|
|
466
|
+
return prior.result
|
|
467
|
+
const result = discover(tool, folder).catch(() => ({
|
|
468
|
+
tool,
|
|
469
|
+
status: "unavailable",
|
|
470
|
+
models: [],
|
|
471
|
+
}))
|
|
472
|
+
catalog.set(key, { at: Date.now(), revision, result })
|
|
473
|
+
return result
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function candidates(args, folder, settings) {
|
|
477
|
+
if (args.automatic && !settings.automatic)
|
|
478
|
+
return { status: "automatic_disabled", candidates: [] }
|
|
479
|
+
const originFamily = modelFamily(args.originModel)
|
|
480
|
+
if (reviewOnly(args.kind) && !originFamily)
|
|
481
|
+
return { status: "origin_model_unverified", candidates: [] }
|
|
482
|
+
const permittedTargets = args.automatic ? settings.targets : bridgeTargets
|
|
483
|
+
const targets = await Promise.all(
|
|
484
|
+
permittedTargets
|
|
485
|
+
.filter((tool) => !args.tool || tool === args.tool)
|
|
486
|
+
.map((tool) => getTarget(tool, folder))
|
|
487
|
+
)
|
|
488
|
+
const choices = targets.flatMap((item) =>
|
|
489
|
+
item.status !== "ready"
|
|
490
|
+
? []
|
|
491
|
+
: [{ id: null, family: item.defaultFamily ?? null }, ...item.models]
|
|
492
|
+
.filter(
|
|
493
|
+
(model) =>
|
|
494
|
+
!reviewOnly(args.kind) ||
|
|
495
|
+
(model.family && model.family !== originFamily)
|
|
496
|
+
)
|
|
497
|
+
.filter(
|
|
498
|
+
(model) =>
|
|
499
|
+
(unavailable.get(
|
|
500
|
+
modelKey(folder, item.tool, model.id, item.accountKey)
|
|
501
|
+
) ?? 0) <= Date.now()
|
|
502
|
+
)
|
|
503
|
+
.map((model) => ({
|
|
504
|
+
tool: item.tool,
|
|
505
|
+
model: model.id,
|
|
506
|
+
family: model.family,
|
|
507
|
+
}))
|
|
508
|
+
)
|
|
509
|
+
return {
|
|
510
|
+
status: choices.length ? "ready" : "no_candidate",
|
|
511
|
+
candidates: choices,
|
|
512
|
+
tools: await Promise.all(
|
|
513
|
+
targets.map(async (item) => ({
|
|
514
|
+
tool: item.tool,
|
|
515
|
+
status: item.status,
|
|
516
|
+
modelCatalog: item.modelCatalog,
|
|
517
|
+
remainingQuota:
|
|
518
|
+
item.status === "ready"
|
|
519
|
+
? await cachedQuota(item)
|
|
520
|
+
: { status: "unknown" },
|
|
521
|
+
}))
|
|
522
|
+
),
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async function leases(directory) {
|
|
527
|
+
const saved = await readJson(join(directory, "active.json"), [])
|
|
528
|
+
const current = []
|
|
529
|
+
for (const item of saved) {
|
|
530
|
+
if (Date.now() - item.startedAt >= leaseMaxAge) continue
|
|
531
|
+
const child = workerAlive(item.pid)
|
|
532
|
+
? null
|
|
533
|
+
: await readJson(join(item.projectDir, item.id, "child.json"), null)
|
|
534
|
+
if (
|
|
535
|
+
workerAlive(item.pid) ||
|
|
536
|
+
(child?.attempt === item.attempt && workerAlive(child.pid))
|
|
537
|
+
)
|
|
538
|
+
current.push(item)
|
|
539
|
+
}
|
|
540
|
+
return current
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function updateLease(directory, attempt, operation) {
|
|
544
|
+
await withWorkspaceLock(directory, async () => {
|
|
545
|
+
const current = await leases(directory)
|
|
546
|
+
await writeJson(
|
|
547
|
+
join(directory, "active.json"),
|
|
548
|
+
operation(current, attempt)
|
|
549
|
+
)
|
|
550
|
+
})
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
async function start(
|
|
554
|
+
job,
|
|
555
|
+
folder,
|
|
556
|
+
projectDir,
|
|
557
|
+
coordination,
|
|
558
|
+
prepare,
|
|
559
|
+
snapshot
|
|
560
|
+
) {
|
|
561
|
+
const jobDir = join(projectDir, job.id)
|
|
562
|
+
const record = join(jobDir, "job.json")
|
|
563
|
+
const baselineFile = join(jobDir, "baseline.json")
|
|
564
|
+
const work = join(jobDir, "work")
|
|
565
|
+
const attempt = randomUUID()
|
|
566
|
+
const admitted = await withWorkspaceLock(join(projectDir, "jobs"), () =>
|
|
567
|
+
withWorkspaceLock(coordination, async () => {
|
|
568
|
+
const previous = await readJson(record, null)
|
|
569
|
+
if (prepare && previous) {
|
|
570
|
+
if (previous.requestSignature !== job.requestSignature)
|
|
571
|
+
return { status: "request_conflict", id: job.id }
|
|
572
|
+
return {
|
|
573
|
+
id: job.id,
|
|
574
|
+
status: taskState(previous),
|
|
575
|
+
tool: previous.tool,
|
|
576
|
+
model: previous.model,
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (
|
|
580
|
+
!prepare &&
|
|
581
|
+
(!previous ||
|
|
582
|
+
previous.attempt !== job.attempt ||
|
|
583
|
+
["running", "completed", "applied", "workspace_expired"].includes(
|
|
584
|
+
taskState(previous)
|
|
585
|
+
))
|
|
586
|
+
) {
|
|
587
|
+
return {
|
|
588
|
+
id: job.id,
|
|
589
|
+
status: previous ? taskState(previous) : "not_found",
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (prepare && job.dependsOn?.length) {
|
|
593
|
+
const blocked = []
|
|
594
|
+
const prerequisites = []
|
|
595
|
+
for (const id of job.dependsOn) {
|
|
596
|
+
const dependency = await readJson(
|
|
597
|
+
join(projectDir, id, "job.json"),
|
|
598
|
+
null
|
|
599
|
+
)
|
|
600
|
+
const state = dependency ? taskState(dependency) : "not_found"
|
|
601
|
+
if (
|
|
602
|
+
!dependency ||
|
|
603
|
+
state !== (reviewOnly(dependency.kind) ? "completed" : "applied")
|
|
604
|
+
) {
|
|
605
|
+
blocked.push({ id, status: state })
|
|
606
|
+
} else {
|
|
607
|
+
const paths = (dependency.changes ?? [])
|
|
608
|
+
.map((change) => change.path)
|
|
609
|
+
.join(", ")
|
|
610
|
+
.slice(0, 1200)
|
|
611
|
+
const patch =
|
|
612
|
+
dependency.patchBytes && dependency.patchBytes <= 3500
|
|
613
|
+
? await readFile(
|
|
614
|
+
join(projectDir, id, "changes.patch"),
|
|
615
|
+
"utf8"
|
|
616
|
+
)
|
|
617
|
+
: ""
|
|
618
|
+
prerequisites.push(
|
|
619
|
+
[
|
|
620
|
+
dependency.task.slice(0, 600),
|
|
621
|
+
(dependency.summary || "").slice(0, 1200),
|
|
622
|
+
paths ? "Changed paths: " + paths : "",
|
|
623
|
+
patch,
|
|
624
|
+
]
|
|
625
|
+
.filter(Boolean)
|
|
626
|
+
.join("\n")
|
|
627
|
+
)
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
if (blocked.length)
|
|
631
|
+
return { status: "waiting_for_dependencies", dependencies: blocked }
|
|
632
|
+
job.prerequisites = prerequisites
|
|
633
|
+
}
|
|
634
|
+
const current = await leases(coordination)
|
|
635
|
+
if (
|
|
636
|
+
current.some(
|
|
637
|
+
(item) => item.id === job.id && item.projectDir === projectDir
|
|
638
|
+
)
|
|
639
|
+
)
|
|
640
|
+
return { status: "previous_worker_still_running", id: job.id }
|
|
641
|
+
if (current.length >= maxParallel)
|
|
642
|
+
return { status: "at_capacity", limit: maxParallel }
|
|
643
|
+
if (!reviewOnly(job.kind)) {
|
|
644
|
+
const overlap = current.filter(
|
|
645
|
+
(item) =>
|
|
646
|
+
item.writes &&
|
|
647
|
+
(!item.paths.length ||
|
|
648
|
+
!job.paths?.length ||
|
|
649
|
+
item.paths.some((left) =>
|
|
650
|
+
job.paths.some((right) => pathsOverlap(left, right))
|
|
651
|
+
))
|
|
652
|
+
)
|
|
653
|
+
if (overlap.length)
|
|
654
|
+
return {
|
|
655
|
+
status: "scope_conflict",
|
|
656
|
+
tasks: overlap
|
|
657
|
+
.filter((item) => item.projectDir === projectDir)
|
|
658
|
+
.map((item) => ({ id: item.id, paths: item.paths })),
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
const lease = {
|
|
662
|
+
attempt,
|
|
663
|
+
id: job.id,
|
|
664
|
+
projectDir,
|
|
665
|
+
pid: process.pid,
|
|
666
|
+
startedAt: Date.now(),
|
|
667
|
+
writes: !reviewOnly(job.kind),
|
|
668
|
+
paths: job.paths ?? [],
|
|
669
|
+
preparing: prepare,
|
|
670
|
+
}
|
|
671
|
+
Object.assign(job, {
|
|
672
|
+
status: "running",
|
|
673
|
+
phase: prepare ? "preparing" : "executing",
|
|
674
|
+
workerPid: process.pid,
|
|
675
|
+
attempt,
|
|
676
|
+
startedAt: lease.startedAt,
|
|
677
|
+
finishedAt: undefined,
|
|
678
|
+
lastRunTokens: undefined,
|
|
679
|
+
remainingQuota: undefined,
|
|
680
|
+
})
|
|
681
|
+
await writeJson(join(coordination, "active.json"), [...current, lease])
|
|
682
|
+
try {
|
|
683
|
+
await writeJson(record, job)
|
|
684
|
+
} catch (error) {
|
|
685
|
+
await writeJson(join(coordination, "active.json"), current)
|
|
686
|
+
throw error
|
|
687
|
+
}
|
|
688
|
+
return null
|
|
689
|
+
})
|
|
690
|
+
)
|
|
691
|
+
if (admitted) return admitted
|
|
692
|
+
|
|
693
|
+
const abort = new AbortController()
|
|
694
|
+
const cancelled = () =>
|
|
695
|
+
readJson(join(jobDir, "cancel.json"), null)
|
|
696
|
+
.then((value) => {
|
|
697
|
+
if (value?.attempt === attempt) abort.abort()
|
|
698
|
+
})
|
|
699
|
+
.catch(() => {})
|
|
700
|
+
const watcher = setInterval(() => void cancelled(), 500)
|
|
701
|
+
watcher.unref()
|
|
702
|
+
const task = (async () => {
|
|
703
|
+
try {
|
|
704
|
+
if (prepare) {
|
|
705
|
+
await cancelled()
|
|
706
|
+
if (abort.signal.aborted) throw abort.signal.reason
|
|
707
|
+
if (snapshot) {
|
|
708
|
+
await cloneBridgeSnapshot(snapshot.work, work)
|
|
709
|
+
await writeJson(baselineFile, snapshot.baseline)
|
|
710
|
+
} else {
|
|
711
|
+
if (reviewOnly(job.kind))
|
|
712
|
+
job.reviewDiff = await bridgeReviewDiff(folder, job.paths)
|
|
713
|
+
await projectSnapshot(folder, work, (baseline) =>
|
|
714
|
+
writeJson(baselineFile, baseline)
|
|
715
|
+
)
|
|
716
|
+
}
|
|
717
|
+
await updateLease(coordination, attempt, (entries, key) =>
|
|
718
|
+
entries.map((item) =>
|
|
719
|
+
item.attempt === key ? { ...item, preparing: false } : item
|
|
720
|
+
)
|
|
721
|
+
)
|
|
722
|
+
}
|
|
723
|
+
job.phase = "executing"
|
|
724
|
+
await writeJson(record, job)
|
|
725
|
+
const target = await getTarget(job.tool, folder)
|
|
726
|
+
await cancelled()
|
|
727
|
+
const result = abort.signal.aborted
|
|
728
|
+
? { failure: "cancelled" }
|
|
729
|
+
: await execute({
|
|
730
|
+
tool: job.tool,
|
|
731
|
+
model: job.model,
|
|
732
|
+
readOnly: reviewOnly(job.kind),
|
|
733
|
+
cwd: work,
|
|
734
|
+
prompt: taskPrompt(job),
|
|
735
|
+
signal: abort.signal,
|
|
736
|
+
onSpawn: (pid) =>
|
|
737
|
+
writeJson(join(jobDir, "child.json"), { attempt, pid }),
|
|
738
|
+
})
|
|
739
|
+
const question = result.failure
|
|
740
|
+
? undefined
|
|
741
|
+
: result.summary?.match(xmlTag)?.[1].trim()
|
|
742
|
+
job.violations = undefined
|
|
743
|
+
job.summary = result.summary
|
|
744
|
+
job.question = question
|
|
745
|
+
job.status = abort.signal.aborted
|
|
746
|
+
? "cancelled"
|
|
747
|
+
: (result.failure ?? (question ? "needs_context" : "completed"))
|
|
748
|
+
if (job.structuredReview && job.status === "completed") {
|
|
749
|
+
job.findings = reviewFindings(job.summary)
|
|
750
|
+
if (!job.findings) job.status = "invalid_review"
|
|
751
|
+
}
|
|
752
|
+
job.actualModel = result.actualModel
|
|
753
|
+
if (
|
|
754
|
+
reviewOnly(job.kind) &&
|
|
755
|
+
!result.failure &&
|
|
756
|
+
modelFamily(result.actualModel) === modelFamily(job.originModel) &&
|
|
757
|
+
modelFamily(result.actualModel)
|
|
758
|
+
)
|
|
759
|
+
job.status = "model_family_conflict"
|
|
760
|
+
job.lastRunTokens = result.tokens
|
|
761
|
+
job.remainingQuota = { status: "unknown" }
|
|
762
|
+
job.rateLimitResetAt = result.rateLimitResetAt
|
|
763
|
+
const baseline = await readJson(baselineFile, null)
|
|
764
|
+
if (baseline) {
|
|
765
|
+
const changes = await inspectBridgeChanges(work, baseline, job.paths)
|
|
766
|
+
if (
|
|
767
|
+
changes.violations.length ||
|
|
768
|
+
(reviewOnly(job.kind) && changes.changes.length)
|
|
769
|
+
) {
|
|
770
|
+
job.status = "out_of_scope"
|
|
771
|
+
job.violations = changes.violations.length
|
|
772
|
+
? changes.violations
|
|
773
|
+
: changes.changes.map((change) => change.path)
|
|
774
|
+
job.patchBytes = 0
|
|
775
|
+
job.changes = []
|
|
776
|
+
} else if (!reviewOnly(job.kind)) {
|
|
777
|
+
await writeFile(join(jobDir, "changes.patch"), changes.patch, {
|
|
778
|
+
mode: 0o600,
|
|
779
|
+
})
|
|
780
|
+
job.patchBytes = Buffer.byteLength(changes.patch)
|
|
781
|
+
job.changes = changes.changes
|
|
782
|
+
if (job.status === "completed" && !changes.patch)
|
|
783
|
+
job.status = "no_changes"
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
if (
|
|
787
|
+
[
|
|
788
|
+
"login_required",
|
|
789
|
+
"model_unavailable",
|
|
790
|
+
"not_installed",
|
|
791
|
+
"usage_limit",
|
|
792
|
+
].includes(job.status)
|
|
793
|
+
) {
|
|
794
|
+
catalog.delete(JSON.stringify([folder, job.tool]))
|
|
795
|
+
}
|
|
796
|
+
if (["model_unavailable", "usage_limit"].includes(job.status)) {
|
|
797
|
+
const key = modelKey(folder, job.tool, job.model, target.accountKey)
|
|
798
|
+
const until = Math.min(
|
|
799
|
+
Date.now() + 7 * 86400000,
|
|
800
|
+
Math.max(
|
|
801
|
+
Date.now() + cacheDuration,
|
|
802
|
+
target.accountKey ? (job.rateLimitResetAt ?? 0) : 0
|
|
803
|
+
)
|
|
804
|
+
)
|
|
805
|
+
unavailable.set(key, until)
|
|
806
|
+
setTimeout(() => {
|
|
807
|
+
if (unavailable.get(key) === until) unavailable.delete(key)
|
|
808
|
+
}, until - Date.now()).unref()
|
|
809
|
+
}
|
|
810
|
+
if (
|
|
811
|
+
target.accountKey &&
|
|
812
|
+
job.status !== "cancelled" &&
|
|
813
|
+
(!result.failure || result.failure === "usage_limit")
|
|
814
|
+
) {
|
|
815
|
+
const sample = await readQuota(job.tool, work).catch(() => undefined)
|
|
816
|
+
if (sample?.accountKey === target.accountKey) {
|
|
817
|
+
const path = quotaPath(job.tool, target.accountKey)
|
|
818
|
+
const { checkedAt, windows } = sample
|
|
819
|
+
job.remainingQuota = { status: "reported", checkedAt, windows }
|
|
820
|
+
if (path) {
|
|
821
|
+
const current = await readJson(path, null).catch(() => null)
|
|
822
|
+
if (!current || current.checkedAt <= checkedAt)
|
|
823
|
+
await writeJson(path, { checkedAt, windows }).catch(() => {})
|
|
824
|
+
}
|
|
825
|
+
} else if (sample) {
|
|
826
|
+
catalog.delete(JSON.stringify([folder, job.tool]))
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
} catch (error) {
|
|
830
|
+
await cancelled()
|
|
831
|
+
job.status = abort.signal.aborted ? "cancelled" : "failed"
|
|
832
|
+
job.summary = error.message
|
|
833
|
+
} finally {
|
|
834
|
+
clearInterval(watcher)
|
|
835
|
+
job.phase = undefined
|
|
836
|
+
job.finishedAt = Date.now()
|
|
837
|
+
await withWorkspaceLock(coordination, async () => {
|
|
838
|
+
await writeJson(record, job)
|
|
839
|
+
if (job.status === "completed") {
|
|
840
|
+
await rm(work, { recursive: true, force: true }).catch(() => {})
|
|
841
|
+
if (!reviewOnly(job.kind))
|
|
842
|
+
await rm(baselineFile, { force: true }).catch(() => {})
|
|
843
|
+
}
|
|
844
|
+
const entries = await leases(coordination)
|
|
845
|
+
await writeJson(
|
|
846
|
+
join(coordination, "active.json"),
|
|
847
|
+
entries.filter((item) => item.attempt !== attempt)
|
|
848
|
+
)
|
|
849
|
+
})
|
|
850
|
+
}
|
|
851
|
+
})()
|
|
852
|
+
task.catch(() => {})
|
|
853
|
+
return { id: job.id, status: "running", tool: job.tool, model: job.model }
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
async function integrate(folder, projectDir, coordination, ids, apply) {
|
|
857
|
+
if (!safeIds(ids) || (apply !== undefined && typeof apply !== "boolean"))
|
|
858
|
+
throw new Error("Select one to four completed Bridge task IDs.")
|
|
859
|
+
return withWorkspaceLock(coordination, async () => {
|
|
860
|
+
const receiptPath = join(
|
|
861
|
+
projectDir,
|
|
862
|
+
"integrations",
|
|
863
|
+
createHash("sha256")
|
|
864
|
+
.update(JSON.stringify([...ids].sort()))
|
|
865
|
+
.digest("hex") + ".json"
|
|
866
|
+
)
|
|
867
|
+
const receipt = await readJson(receiptPath, null)
|
|
868
|
+
const records = await Promise.all(
|
|
869
|
+
ids.map(async (id) => {
|
|
870
|
+
const directory = join(projectDir, id)
|
|
871
|
+
return {
|
|
872
|
+
id,
|
|
873
|
+
directory,
|
|
874
|
+
job: await readJson(join(directory, "job.json"), null),
|
|
875
|
+
}
|
|
876
|
+
})
|
|
877
|
+
)
|
|
878
|
+
const blocked = records.filter(
|
|
879
|
+
({ job }) =>
|
|
880
|
+
!job ||
|
|
881
|
+
reviewOnly(job.kind) ||
|
|
882
|
+
job.refinementId ||
|
|
883
|
+
!(
|
|
884
|
+
job.status === "completed" ||
|
|
885
|
+
(["applying", "applied"].includes(receipt?.status) &&
|
|
886
|
+
job.status === "applied")
|
|
887
|
+
)
|
|
888
|
+
)
|
|
889
|
+
if (blocked.length)
|
|
890
|
+
return {
|
|
891
|
+
status: "waiting_for_results",
|
|
892
|
+
tasks: blocked.map(({ id, job }) => ({
|
|
893
|
+
id,
|
|
894
|
+
status: job ? taskState(job) : "not_found",
|
|
895
|
+
})),
|
|
896
|
+
}
|
|
897
|
+
const changes = records.flatMap(({ id, job }) =>
|
|
898
|
+
(job.changes ?? []).map((change) => ({ ...change, id }))
|
|
899
|
+
)
|
|
900
|
+
const overlaps = changes
|
|
901
|
+
.filter((change, index) =>
|
|
902
|
+
changes
|
|
903
|
+
.slice(0, index)
|
|
904
|
+
.some(
|
|
905
|
+
(other) =>
|
|
906
|
+
other.id !== change.id && pathsOverlap(other.path, change.path)
|
|
907
|
+
)
|
|
908
|
+
)
|
|
909
|
+
.map((change) => change.path)
|
|
910
|
+
if (overlaps.length)
|
|
911
|
+
return { status: "patch_overlap", paths: [...new Set(overlaps)] }
|
|
912
|
+
const paths = changes.map((change) => change.path)
|
|
913
|
+
if (receipt?.status === "applied") {
|
|
914
|
+
const conflicts = await mismatchedBridgePaths(folder, changes)
|
|
915
|
+
return conflicts.length
|
|
916
|
+
? { status: "working_copy_changed", paths: conflicts }
|
|
917
|
+
: { status: "applied", ids, paths }
|
|
918
|
+
}
|
|
919
|
+
const markApplied = async () => {
|
|
920
|
+
const appliedAt = receipt?.appliedAt ?? Date.now()
|
|
921
|
+
for (const { directory, job } of records)
|
|
922
|
+
await writeJson(join(directory, "job.json"), {
|
|
923
|
+
...job,
|
|
924
|
+
status: "applied",
|
|
925
|
+
appliedAt,
|
|
926
|
+
})
|
|
927
|
+
await writeJson(receiptPath, { status: "applied", paths, appliedAt })
|
|
928
|
+
return {
|
|
929
|
+
status: "applied",
|
|
930
|
+
ids,
|
|
931
|
+
paths,
|
|
932
|
+
nextAction:
|
|
933
|
+
"Run the integrated checks and independently review substantive changes.",
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
if (
|
|
937
|
+
receipt?.status === "applying" &&
|
|
938
|
+
!(await mismatchedBridgePaths(folder, changes)).length
|
|
939
|
+
) {
|
|
940
|
+
return markApplied()
|
|
941
|
+
}
|
|
942
|
+
if (
|
|
943
|
+
receipt?.status === "applying" &&
|
|
944
|
+
records.some(({ job }) => job.status === "applied")
|
|
945
|
+
)
|
|
946
|
+
return { status: "working_copy_changed", paths }
|
|
947
|
+
const conflicts = await mismatchedBridgePaths(folder, changes, "before")
|
|
948
|
+
if (conflicts.length)
|
|
949
|
+
return { status: "working_copy_changed", paths: conflicts }
|
|
950
|
+
if (
|
|
951
|
+
await leases(coordination).then((entries) =>
|
|
952
|
+
entries.some((item) => item.preparing)
|
|
953
|
+
)
|
|
954
|
+
)
|
|
955
|
+
return { status: "snapshot_in_progress" }
|
|
956
|
+
|
|
957
|
+
const patches = await Promise.all(
|
|
958
|
+
records.map(({ directory, job }) =>
|
|
959
|
+
job.patchBytes
|
|
960
|
+
? readFile(join(directory, "changes.patch"), "utf8")
|
|
961
|
+
: ""
|
|
962
|
+
)
|
|
963
|
+
)
|
|
964
|
+
const patch = patches.filter(Boolean).join("\n")
|
|
965
|
+
const result = await applyVersionedBridgePatch(
|
|
966
|
+
folder,
|
|
967
|
+
{ patch, changes },
|
|
968
|
+
{
|
|
969
|
+
check: !apply,
|
|
970
|
+
previewRoot: join(projectDir, "previews"),
|
|
971
|
+
beforeApply: () =>
|
|
972
|
+
writeJson(receiptPath, { status: "applying", paths }),
|
|
973
|
+
}
|
|
974
|
+
)
|
|
975
|
+
if (result.status === "applied" && apply) return markApplied()
|
|
976
|
+
if (["applied", "ready_to_apply"].includes(result.status))
|
|
977
|
+
return { status: "ready_to_apply", ids, paths }
|
|
978
|
+
return { ...result, paths: result.paths ?? paths }
|
|
979
|
+
})
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
return async function call(name, args, selectedFolder, loadSettings) {
|
|
983
|
+
if (!selectedFolder)
|
|
984
|
+
throw new Error("Open a single project folder before using Bridge.")
|
|
985
|
+
const folder = await realpath(selectedFolder)
|
|
986
|
+
if (!(await stat(folder)).isDirectory())
|
|
987
|
+
throw new Error("Bridge needs a project directory.")
|
|
988
|
+
const settings = await loadSettings(folder)
|
|
989
|
+
if (
|
|
990
|
+
!/^[a-f0-9]{64}$/.test(settings?.projectKey ?? "") ||
|
|
991
|
+
typeof settings?.automatic !== "boolean" ||
|
|
992
|
+
!Array.isArray(settings.targets) ||
|
|
993
|
+
settings.targets.some((tool) => !bridgeTargets.includes(tool)) ||
|
|
994
|
+
new Set(settings.targets).size !== settings.targets.length ||
|
|
995
|
+
(settings.automatic && settings.targets.length === 0)
|
|
996
|
+
) {
|
|
997
|
+
throw new Error("Acent returned invalid project Bridge settings.")
|
|
998
|
+
}
|
|
999
|
+
const projectDir = join(
|
|
1000
|
+
root,
|
|
1001
|
+
"bridge",
|
|
1002
|
+
createHash("sha256")
|
|
1003
|
+
.update(JSON.stringify([settings.projectKey, folder]))
|
|
1004
|
+
.digest("hex")
|
|
1005
|
+
)
|
|
1006
|
+
const coordination = join(
|
|
1007
|
+
root,
|
|
1008
|
+
"bridge",
|
|
1009
|
+
"workspaces",
|
|
1010
|
+
createHash("sha256").update(folder).digest("hex")
|
|
1011
|
+
)
|
|
1012
|
+
await collect(join(root, "bridge"), projectDir)
|
|
1013
|
+
if (name === "acent_bridge_settings") {
|
|
1014
|
+
if (Object.keys(args).length)
|
|
1015
|
+
throw new Error("Change Bridge settings from the project in Acent.")
|
|
1016
|
+
if (settings.automatic)
|
|
1017
|
+
void Promise.all(
|
|
1018
|
+
settings.targets.map((tool) => getTarget(tool, folder))
|
|
1019
|
+
)
|
|
1020
|
+
return { automatic: settings.automatic, targets: settings.targets }
|
|
1021
|
+
}
|
|
1022
|
+
if (name === "acent_bridge_candidates" || name === "acent_bridge_start") {
|
|
1023
|
+
if (!["implement", "review", "diagnose"].includes(args.kind))
|
|
1024
|
+
throw new Error("Choose a valid Bridge task type.")
|
|
1025
|
+
}
|
|
1026
|
+
if (name === "acent_bridge_candidates")
|
|
1027
|
+
return candidates(args, folder, settings)
|
|
1028
|
+
if (name === "acent_bridge_refine")
|
|
1029
|
+
return refine(args, {
|
|
1030
|
+
folder,
|
|
1031
|
+
projectDir,
|
|
1032
|
+
settings,
|
|
1033
|
+
reloadSettings: () => loadSettings(folder),
|
|
1034
|
+
lockWorkspace: (operation) =>
|
|
1035
|
+
withWorkspaceLock(coordination, operation),
|
|
1036
|
+
getJob: (id) => readJson(join(projectDir, id, "job.json"), null),
|
|
1037
|
+
getBaseline: (id) =>
|
|
1038
|
+
readJson(join(projectDir, id, "baseline.json"), null),
|
|
1039
|
+
prepareStage: async (stageDir) => {
|
|
1040
|
+
const work = join(stageDir, "work")
|
|
1041
|
+
const baselineFile = join(stageDir, "baseline.json")
|
|
1042
|
+
let baseline = await readJson(baselineFile, null)
|
|
1043
|
+
if (!baseline) {
|
|
1044
|
+
await rm(stageDir, { recursive: true, force: true })
|
|
1045
|
+
try {
|
|
1046
|
+
await projectSnapshot(folder, work, (value) =>
|
|
1047
|
+
writeJson(baselineFile, value)
|
|
1048
|
+
)
|
|
1049
|
+
baseline = await readJson(baselineFile, null)
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
await rm(stageDir, { recursive: true, force: true })
|
|
1052
|
+
throw error
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return { work, baseline }
|
|
1056
|
+
},
|
|
1057
|
+
removeStage: (stageDir) =>
|
|
1058
|
+
rm(stageDir, { recursive: true, force: true }),
|
|
1059
|
+
launch: async (task, currentSettings, snapshot) => {
|
|
1060
|
+
const available = await candidates(task, folder, currentSettings)
|
|
1061
|
+
if (
|
|
1062
|
+
!available.candidates.some(
|
|
1063
|
+
({ tool, model }) => tool === task.tool && model === task.model
|
|
1064
|
+
)
|
|
1065
|
+
)
|
|
1066
|
+
return {
|
|
1067
|
+
status:
|
|
1068
|
+
available.status === "ready"
|
|
1069
|
+
? "selection_unavailable"
|
|
1070
|
+
: available.status,
|
|
1071
|
+
}
|
|
1072
|
+
const job = { ...task, history: [] }
|
|
1073
|
+
job.requestSignature = createHash("sha256")
|
|
1074
|
+
.update(JSON.stringify(job))
|
|
1075
|
+
.digest("hex")
|
|
1076
|
+
return start(
|
|
1077
|
+
job,
|
|
1078
|
+
folder,
|
|
1079
|
+
projectDir,
|
|
1080
|
+
coordination,
|
|
1081
|
+
true,
|
|
1082
|
+
snapshot && (await snapshot())
|
|
1083
|
+
)
|
|
1084
|
+
},
|
|
1085
|
+
readRepairPatch: (id) =>
|
|
1086
|
+
readFile(join(projectDir, id, "changes.patch"), "utf8"),
|
|
1087
|
+
select: (task, currentSettings) =>
|
|
1088
|
+
candidates(task, folder, currentSettings),
|
|
1089
|
+
preparingWorkspace: () =>
|
|
1090
|
+
leases(coordination).then((entries) =>
|
|
1091
|
+
entries.some(({ preparing }) => preparing)
|
|
1092
|
+
),
|
|
1093
|
+
cancelJob: async (id) => {
|
|
1094
|
+
const jobDir = join(projectDir, id)
|
|
1095
|
+
const job = await readJson(join(jobDir, "job.json"), null)
|
|
1096
|
+
if (job && taskState(job) === "running")
|
|
1097
|
+
await writeJson(join(jobDir, "cancel.json"), {
|
|
1098
|
+
attempt: job.attempt,
|
|
1099
|
+
})
|
|
1100
|
+
},
|
|
1101
|
+
})
|
|
1102
|
+
if (name === "acent_bridge_integrate")
|
|
1103
|
+
return integrate(folder, projectDir, coordination, args.ids, args.apply)
|
|
1104
|
+
if (name === "acent_bridge_finalize")
|
|
1105
|
+
return finalize(folder, projectDir, coordination, args)
|
|
1106
|
+
if (name === "acent_bridge_activity") {
|
|
1107
|
+
const entries = await readdir(projectDir).catch((error) => {
|
|
1108
|
+
if (error.code === "ENOENT") return []
|
|
1109
|
+
throw error
|
|
1110
|
+
})
|
|
1111
|
+
const records = await Promise.all(
|
|
1112
|
+
entries
|
|
1113
|
+
.filter((id) => taskId.test(id))
|
|
1114
|
+
.map((id) => readJson(join(projectDir, id, "job.json"), null))
|
|
1115
|
+
)
|
|
1116
|
+
return {
|
|
1117
|
+
limit: maxParallel,
|
|
1118
|
+
tasks: records
|
|
1119
|
+
.filter(Boolean)
|
|
1120
|
+
.sort((left, right) => (right.startedAt ?? 0) - (left.startedAt ?? 0))
|
|
1121
|
+
.slice(0, 24)
|
|
1122
|
+
.map((job) => ({
|
|
1123
|
+
id: job.id,
|
|
1124
|
+
kind: job.kind,
|
|
1125
|
+
task: job.task.slice(0, 200),
|
|
1126
|
+
tool: job.tool,
|
|
1127
|
+
model: job.model,
|
|
1128
|
+
status: taskState(job),
|
|
1129
|
+
phase: job.phase,
|
|
1130
|
+
paths: job.paths,
|
|
1131
|
+
question: job.question,
|
|
1132
|
+
})),
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (name === "acent_bridge_start") {
|
|
1136
|
+
if (
|
|
1137
|
+
![args.task, args.acceptance].every(
|
|
1138
|
+
(value) =>
|
|
1139
|
+
typeof value === "string" && value.trim() && value.length <= 12000
|
|
1140
|
+
)
|
|
1141
|
+
) {
|
|
1142
|
+
throw new Error(
|
|
1143
|
+
"Provide a task and acceptance criteria, up to 12,000 characters each."
|
|
1144
|
+
)
|
|
1145
|
+
}
|
|
1146
|
+
const paths = args.paths ?? []
|
|
1147
|
+
const dependsOn = args.dependsOn ?? []
|
|
1148
|
+
if (
|
|
1149
|
+
!Array.isArray(paths) ||
|
|
1150
|
+
paths.length > 64 ||
|
|
1151
|
+
!paths.every(workspacePath)
|
|
1152
|
+
)
|
|
1153
|
+
throw new Error(
|
|
1154
|
+
"Use relative project file or directory paths for the Bridge scope."
|
|
1155
|
+
)
|
|
1156
|
+
if (
|
|
1157
|
+
!Array.isArray(dependsOn) ||
|
|
1158
|
+
(dependsOn.length > 0 && !safeIds(dependsOn))
|
|
1159
|
+
)
|
|
1160
|
+
throw new Error("Use up to four distinct dependency task IDs.")
|
|
1161
|
+
if (
|
|
1162
|
+
args.requestId !== undefined &&
|
|
1163
|
+
(typeof args.requestId !== "string" || !taskId.test(args.requestId))
|
|
1164
|
+
)
|
|
1165
|
+
throw new Error("Use a UUID for the Bridge request ID.")
|
|
1166
|
+
if (
|
|
1167
|
+
args.context !== undefined &&
|
|
1168
|
+
(typeof args.context !== "string" || args.context.length > 12000)
|
|
1169
|
+
)
|
|
1170
|
+
throw new Error("Keep Bridge context under 12,000 characters.")
|
|
1171
|
+
const id = args.requestId ?? randomUUID()
|
|
1172
|
+
if (dependsOn.includes(id))
|
|
1173
|
+
throw new Error("A Bridge task cannot depend on itself.")
|
|
1174
|
+
const job = {
|
|
1175
|
+
id,
|
|
1176
|
+
kind: args.kind,
|
|
1177
|
+
originModel: args.originModel,
|
|
1178
|
+
tool: args.tool,
|
|
1179
|
+
model: args.model ?? null,
|
|
1180
|
+
task: args.task,
|
|
1181
|
+
acceptance: args.acceptance,
|
|
1182
|
+
context: args.context,
|
|
1183
|
+
paths: [...new Set(paths)].sort(),
|
|
1184
|
+
dependsOn,
|
|
1185
|
+
automatic: args.automatic === true,
|
|
1186
|
+
history: [],
|
|
1187
|
+
}
|
|
1188
|
+
job.requestSignature = createHash("sha256")
|
|
1189
|
+
.update(JSON.stringify(job))
|
|
1190
|
+
.digest("hex")
|
|
1191
|
+
if (args.requestId) {
|
|
1192
|
+
const existing = await readJson(
|
|
1193
|
+
join(projectDir, args.requestId, "job.json"),
|
|
1194
|
+
null
|
|
1195
|
+
)
|
|
1196
|
+
if (existing)
|
|
1197
|
+
return existing.requestSignature === job.requestSignature
|
|
1198
|
+
? {
|
|
1199
|
+
id,
|
|
1200
|
+
tool: existing.tool,
|
|
1201
|
+
model: existing.model,
|
|
1202
|
+
status: taskState(existing),
|
|
1203
|
+
}
|
|
1204
|
+
: { id, status: "request_conflict" }
|
|
1205
|
+
}
|
|
1206
|
+
const available = await candidates(args, folder, settings)
|
|
1207
|
+
if (
|
|
1208
|
+
!available.candidates.some(
|
|
1209
|
+
(candidate) =>
|
|
1210
|
+
candidate.tool === args.tool &&
|
|
1211
|
+
candidate.model === (args.model ?? null)
|
|
1212
|
+
)
|
|
1213
|
+
)
|
|
1214
|
+
return available.status === "ready"
|
|
1215
|
+
? { ...available, status: "selection_unavailable" }
|
|
1216
|
+
: available
|
|
1217
|
+
if (job.automatic && !reviewOnly(job.kind) && !paths.length)
|
|
1218
|
+
return { status: "write_scope_required" }
|
|
1219
|
+
return start(job, folder, projectDir, coordination, true)
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
if (typeof args.id !== "string" || !taskId.test(args.id))
|
|
1223
|
+
throw new Error("Provide a valid Bridge task ID.")
|
|
1224
|
+
const jobDir = join(projectDir, args.id)
|
|
1225
|
+
const record = join(jobDir, "job.json")
|
|
1226
|
+
const job = await readJson(record, null)
|
|
1227
|
+
if (!job) throw new Error("Bridge task not found for this project.")
|
|
1228
|
+
job.status = taskState(job)
|
|
1229
|
+
if (name === "acent_bridge_cancel") {
|
|
1230
|
+
if (job.status !== "running") return { id: job.id, status: job.status }
|
|
1231
|
+
await writeJson(join(jobDir, "cancel.json"), { attempt: job.attempt })
|
|
1232
|
+
return { id: job.id, status: "cancelling" }
|
|
1233
|
+
}
|
|
1234
|
+
if (job.status === "running")
|
|
1235
|
+
return {
|
|
1236
|
+
id: job.id,
|
|
1237
|
+
status: job.status,
|
|
1238
|
+
phase: job.phase,
|
|
1239
|
+
tool: job.tool,
|
|
1240
|
+
model: job.model,
|
|
1241
|
+
}
|
|
1242
|
+
if (name === "acent_bridge_status") {
|
|
1243
|
+
const {
|
|
1244
|
+
id,
|
|
1245
|
+
tool,
|
|
1246
|
+
model,
|
|
1247
|
+
actualModel,
|
|
1248
|
+
status,
|
|
1249
|
+
summary,
|
|
1250
|
+
findings,
|
|
1251
|
+
question,
|
|
1252
|
+
patchBytes,
|
|
1253
|
+
lastRunTokens,
|
|
1254
|
+
remainingQuota,
|
|
1255
|
+
rateLimitResetAt,
|
|
1256
|
+
violations,
|
|
1257
|
+
changes,
|
|
1258
|
+
} = job
|
|
1259
|
+
const patchPath = patchBytes ? join(jobDir, "changes.patch") : undefined
|
|
1260
|
+
const patch =
|
|
1261
|
+
patchPath && patchBytes <= 40000
|
|
1262
|
+
? await readFile(patchPath, "utf8")
|
|
1263
|
+
: undefined
|
|
1264
|
+
return {
|
|
1265
|
+
id,
|
|
1266
|
+
tool,
|
|
1267
|
+
model,
|
|
1268
|
+
actualModel,
|
|
1269
|
+
status,
|
|
1270
|
+
summary,
|
|
1271
|
+
findings,
|
|
1272
|
+
question,
|
|
1273
|
+
patch,
|
|
1274
|
+
patchPath,
|
|
1275
|
+
patchBytes,
|
|
1276
|
+
violations,
|
|
1277
|
+
changedPaths: changes?.map((change) => change.path),
|
|
1278
|
+
lastRunTokens,
|
|
1279
|
+
rateLimitResetAt,
|
|
1280
|
+
remainingQuota: remainingQuota ?? { status: "unknown" },
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
if (["completed", "applied"].includes(job.status))
|
|
1285
|
+
throw new Error("This Bridge task is already complete.")
|
|
1286
|
+
if (job.status === "workspace_expired")
|
|
1287
|
+
return { id: job.id, status: job.status }
|
|
1288
|
+
if (job.history.length >= 20)
|
|
1289
|
+
throw new Error("This Bridge task reached its context and retry limit.")
|
|
1290
|
+
if (
|
|
1291
|
+
job.status === "needs_context" &&
|
|
1292
|
+
(typeof args.answer !== "string" || !args.answer.trim())
|
|
1293
|
+
)
|
|
1294
|
+
throw new Error(
|
|
1295
|
+
"Reply to the delegate's context question before continuing."
|
|
1296
|
+
)
|
|
1297
|
+
if (
|
|
1298
|
+
args.answer !== undefined &&
|
|
1299
|
+
(typeof args.answer !== "string" || args.answer.length > 12000)
|
|
1300
|
+
)
|
|
1301
|
+
throw new Error("Keep the context answer under 12,000 characters.")
|
|
1302
|
+
const tool = args.tool ?? job.tool
|
|
1303
|
+
const model = args.tool || args.model ? (args.model ?? null) : job.model
|
|
1304
|
+
const available = await candidates({ ...job, tool }, folder, settings)
|
|
1305
|
+
if (
|
|
1306
|
+
!available.candidates.some(
|
|
1307
|
+
(candidate) => candidate.tool === tool && candidate.model === model
|
|
1308
|
+
)
|
|
1309
|
+
)
|
|
1310
|
+
return { ...available, status: "selection_unavailable" }
|
|
1311
|
+
const baseline = await readJson(join(jobDir, "baseline.json"), null)
|
|
1312
|
+
if (!baseline)
|
|
1313
|
+
throw new Error(
|
|
1314
|
+
"The project copy was not prepared. Start a new Bridge task."
|
|
1315
|
+
)
|
|
1316
|
+
job.history.push(
|
|
1317
|
+
job.question
|
|
1318
|
+
? { question: job.question }
|
|
1319
|
+
: { status: job.status, summary: job.summary }
|
|
1320
|
+
)
|
|
1321
|
+
if (args.answer) job.history.push({ answer: args.answer })
|
|
1322
|
+
return start(
|
|
1323
|
+
{ ...job, tool, model, question: undefined },
|
|
1324
|
+
folder,
|
|
1325
|
+
projectDir,
|
|
1326
|
+
coordination,
|
|
1327
|
+
false
|
|
1328
|
+
)
|
|
1329
|
+
}
|
|
1330
|
+
}
|