@cirtium/acent-connect 1.3.0 → 1.3.3

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.
@@ -15,6 +15,7 @@ import { setTimeout as pause } from "node:timers/promises"
15
15
  import { lock } from "./acent-connect.mjs"
16
16
  import { bridgeChangeContributors } from "./bridge-capture.mjs"
17
17
  import { createBridgeFinalizer } from "./bridge-finalize.mjs"
18
+ import { checkProjectCodeReceipt, isProjectCodeReceipt } from "./bridge-project-permissions.mjs"
18
19
  import { createBridgeRetention } from "./bridge-retention.mjs"
19
20
  import { bridgeReviewResult } from "./bridge-review-result.mjs"
20
21
  import {
@@ -31,6 +32,7 @@ import {
31
32
  inspectBridgeChanges,
32
33
  mismatchedBridgePaths,
33
34
  pathsOverlap,
35
+ prepareBridgePatchRetry,
34
36
  projectSnapshot,
35
37
  projectFileVersions,
36
38
  withinPaths,
@@ -176,7 +178,7 @@ export const bridgeTools = [
176
178
  },
177
179
  dependsOn: idList,
178
180
  requestId: text(
179
- "Optional UUID reused for an exact retry of this request."
181
+ "Use the UUID returned by sharing approval. Reuse it for an exact retry."
180
182
  ),
181
183
  automatic: { type: "boolean" },
182
184
  },
@@ -201,10 +203,15 @@ export const bridgeTools = [
201
203
  ),
202
204
  toolSchema(
203
205
  "acent_bridge_integrate",
204
- "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.",
206
+ "Check completed patches or apply them after review. For overlap or changed source files, prepareRetry checks the patches in a private copy of the latest files and may return a new patch to review. It never applies the retry.",
205
207
  {
206
208
  ids: idList,
207
209
  apply: { type: "boolean" },
210
+ prepareRetry: {
211
+ type: "boolean",
212
+ description: "Prepare a new patch from the latest files. Use the returned retryId to read the patch and apply it separately after review.",
213
+ },
214
+ retryRevision: text("Revision returned by acent_bridge_status after reading a prepared retry. Required to apply that retry."),
208
215
  },
209
216
  ["ids"]
210
217
  ),
@@ -255,7 +262,7 @@ export const bridgeTools = [
255
262
  ],
256
263
  },
257
264
  id: text(
258
- "Stable UUID for this refinement, generated by the coordinating agent."
265
+ "Stable UUID for this refinement. Use the requestId returned by sharing approval when available."
259
266
  ),
260
267
  task: text("Original work and what to review."),
261
268
  acceptance: text("What the final code must do and how to verify it."),
@@ -302,12 +309,14 @@ export const bridgeInstructions = [
302
309
  "Handle straightforward copy or styling edits and dependent steps directly. Start additional automatic tasks only when each has a distinct, useful result. Keep one writer responsible for each shared contract, state machine, or business rule, even if the files are disjoint. Resolve shared design decisions before starting parallel implementation. If one task needs an earlier result, pass dependsOn or finish the prerequisite first. Use read-only review or diagnosis for independent work when writes need one owner.",
303
310
  "Keep authorized production actions such as deploys, database migrations, and live payments or refunds with the coordinating agent. Use Bridge for independent review of the plan and verification of the result.",
304
311
  "If automatic delegation is disabled, continue the task directly. If automatic delegation is enabled but no suitable candidate is available, continue work you can verify and state the specific reason the independent work did not run. Report only the reviews and checks that actually completed.",
312
+ "Before finishing eligible work, confirm the independent check ran or state why it could not run. If the host issues a completion reminder, handle it once and finish normally. Bridge workers do not start another delegation.",
305
313
  "Get candidates for each task. Honor the user's selected model. For automatic selection, choose a model that fits the work and preserves review independence. Check any reported quota and avoid candidates with exhausted included quota for automatic selection, unless the user has approved that usage. Among similarly suitable candidates, prefer Grok in Cursor and Gemini in Antigravity. An external model such as Claude in Cursor may be selected when it better fits the task or when the preferred family is unavailable, within the user's usage and spending settings. Unknown quota does not indicate availability or exhaustion. Pass the selected model ID explicitly and start with concrete acceptance criteria.",
306
314
  "For review, diagnosis, or refinement, use the host-reported current turn model as currentModel. Supply originModel only when the user is revisiting earlier work and its model is known. If earlier model metadata is missing, proceed with currentModel. In Codex, the Bridge tool hook can report the current model after a call. If Bridge returns origin_model_unverified and the hook reports a model, retry with that currentModel. Pass the same model inputs when starting the selected review. Never guess a model ID.",
307
315
  "Before starting a task or refinement, gather the decisions, constraints, and evidence that affect the delegated work. Reuse current evidence and use Acent Decisions or Recall first if missing project history could change the work. Pass the relevant facts and any unresolved constraints in context on the initial request. For self-contained work, include the current facts the delegate needs.",
308
316
  "In the final answer after using Bridge, name any enabled or explicitly requested tools that could not participate because CLI authentication was required, even if other tools completed the work. Use loginRequiredTools from candidate selection and login_required from task or refinement status as evidence. If the tool later succeeds in the same request, report its final outcome instead. Do not infer sign-out from missing models or an unavailable tool. Point users to Set up in Acent Bridge when they need to sign in.",
309
317
  "Bridge runs four tasks per project folder as a baseline and expands to eight as needed; extra ready tasks queue and start as slots open. Track queued jobs using their existing IDs. 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.",
310
318
  "Use acent_bridge_integrate to check and apply completed diffs. For substantive changes implemented in parallel, review the integrated result and run end-to-end checks while eligible independent reviewers look at the same integrated candidate. Give multiple reviewers complementary priorities, such as concurrency, interface behavior, or regressions. Keep the reviewed files stable while reviews and checks run. Apply findings and re-review and rerun affected checks if the candidate changes.",
319
+ "For an integration conflict, use prepareRetry on the original task IDs when offered. Inspect the returned retryId with acent_bridge_status, then pass its retryRevision to apply that patch alone. If a source patch conflicts with the latest files, reconcile the changes in one scoped task instead of forcing the old patch.",
311
320
  "For substantive authorized edits with a defined write scope, use acent_bridge_refine to run independent review, repair and re-review. Pass applied task IDs in dependsOn. Choose eligible model families and optionally set each reviewer's focus to a distinct priority. Set apply=true only within the user's authorized editing scope.",
312
321
  "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.",
313
322
  "Include an Acent Bridge section in the first final answer after any Bridge run or requested independent review, including when a requested review could not run. Start with a bold Acent Bridge label and the observed status in the user's language. Follow it immediately with a Markdown table showing the agent or check and its execution model, the work it performed and its scope, the outcome, and the findings or evidence. Include the table even when only one delegate participated or its execution model is unknown. Name the coordinator and delegate separately for the checks each performed. For delegates, use actualModel as the host-reported model. For the coordinator, use the host's model metadata for that turn when available. When the execution model is unavailable, label any requested model as requested and mark the execution model unconfirmed. Keep model families separate from model names.",
@@ -823,6 +832,7 @@ export function createBridge({
823
832
  queueMode
824
833
  ) {
825
834
  const jobDir = join(projectDir, job.id)
835
+ const exactScopes = isProjectCodeReceipt(job.refinementId ?? job.id)
826
836
  const record = join(jobDir, "job.json")
827
837
  const baselineFile = join(jobDir, "baseline.json")
828
838
  const work = join(jobDir, "work")
@@ -860,6 +870,9 @@ export function createBridge({
860
870
  const prerequisites = []
861
871
  const dependencyPaths = new Set()
862
872
  const requestedScopes = delegateScopes(job)
873
+ const visible = (path) => exactScopes
874
+ ? requestedScopes.includes(path)
875
+ : withinPaths(path, requestedScopes)
863
876
  for (const id of job.dependsOn) {
864
877
  const dependency = await readJson(
865
878
  join(projectDir, id, "job.json"),
@@ -878,7 +891,7 @@ export function createBridge({
878
891
  const visiblePaths = changedPaths.filter(
879
892
  (path) =>
880
893
  delegateWorkspacePath(path) &&
881
- (!requestedScopes.length || withinPaths(path, requestedScopes))
894
+ (!requestedScopes.length || visible(path))
882
895
  )
883
896
  for (const path of visiblePaths) dependencyPaths.add(path)
884
897
  const paths = visiblePaths.join(", ").slice(0, 1200)
@@ -887,7 +900,7 @@ export function createBridge({
887
900
  !requestedScopes.length ||
888
901
  (earlierScopes.length > 0 &&
889
902
  earlierScopes.every((path) =>
890
- withinPaths(path, requestedScopes)
903
+ visible(path)
891
904
  ))
892
905
  const patch =
893
906
  visiblePaths.length === changedPaths.length &&
@@ -1007,7 +1020,7 @@ export function createBridge({
1007
1020
  if (abort.signal.aborted) throw abort.signal.reason
1008
1021
  const scopes = delegateScopes(job)
1009
1022
  if (!snapshot && reviewOnly(job.kind) && scopes.length)
1010
- job.reviewDiff = await bridgeReviewDiff(folder, scopes)
1023
+ job.reviewDiff = await bridgeReviewDiff(folder, scopes, undefined, undefined, { exactScopes })
1011
1024
  await projectSnapshot(
1012
1025
  snapshot?.work ?? folder,
1013
1026
  work,
@@ -1018,6 +1031,7 @@ export function createBridge({
1018
1031
  }),
1019
1032
  {
1020
1033
  scopes,
1034
+ exactScopes,
1021
1035
  trackSource:
1022
1036
  !snapshot && reviewOnly(job.kind) && Boolean(job.dependsOn?.length),
1023
1037
  }
@@ -1036,7 +1050,8 @@ export function createBridge({
1036
1050
  !prepare &&
1037
1051
  !(await checkDelegateWorkspace(
1038
1052
  work,
1039
- baseline.scopes ?? delegateScopes(job)
1053
+ baseline.scopes ?? delegateScopes(job),
1054
+ { exactScopes }
1040
1055
  ))
1041
1056
  const target = invalidWorkspace ? {} : await getTarget(job.tool, folder)
1042
1057
  const beforeAttempt = !prepare && !invalidWorkspace && !reviewOnly(job.kind)
@@ -1208,9 +1223,58 @@ export function createBridge({
1208
1223
  return { id: job.id, status: "running", tool: job.tool, model: job.model }
1209
1224
  }
1210
1225
 
1211
- async function integrate(folder, projectDir, coordination, ids, apply, captureEvidence) {
1212
- if (!safeIds(ids) || (apply !== undefined && typeof apply !== "boolean"))
1226
+ async function saveIntegrationRetry(folder, projectDir, records, patches) {
1227
+ const prepared = await prepareBridgePatchRetry(folder, records.map(({ id, job }, index) => ({
1228
+ id, changes: job.changes ?? [], patch: patches[index],
1229
+ })), join(projectDir, "previews"))
1230
+ if (prepared.status !== "prepared") {
1231
+ return prepared.status === "manual_review_required"
1232
+ ? { ...prepared, nextAction: "Review the source patches and current files together. Resolve the conflict in one new task before applying." }
1233
+ : prepared
1234
+ }
1235
+
1236
+ const sourceTaskIds = records.map(({ id }) => id)
1237
+ const digest = createHash("sha256").update(JSON.stringify([
1238
+ sourceTaskIds, prepared.versions, prepared.patch,
1239
+ ])).digest("hex")
1240
+ const retryId = `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`
1241
+ const directory = join(projectDir, retryId)
1242
+ const record = join(directory, "job.json")
1243
+ const paths = prepared.changes.map(({ path }) => path)
1244
+ if (!(await readJson(record, null))) {
1245
+ const contributors = records.map(({ job }) =>
1246
+ job.changeContributors ?? bridgeChangeContributors(job, job.changes ?? [])
1247
+ )
1248
+ await mkdir(directory, { recursive: true, mode: 0o700 })
1249
+ await writeFile(join(directory, "changes.patch"), prepared.patch, { mode: 0o600 })
1250
+ await writeJson(record, {
1251
+ id: retryId,
1252
+ kind: "implement",
1253
+ status: "completed",
1254
+ task: "Prepare integration retry from the latest files",
1255
+ summary: "Prepared a new patch for review. The original working copy was not modified.",
1256
+ paths,
1257
+ sourceTaskIds,
1258
+ retryRevision: randomUUID(),
1259
+ retryGuards: prepared.versions.filter(({ path }) => !paths.includes(path)),
1260
+ changes: prepared.changes,
1261
+ changeContributors: Object.fromEntries(paths.map((path) => [path,
1262
+ contributors.flatMap((byPath) => byPath[path] ?? []).slice(-8),
1263
+ ])),
1264
+ patchBytes: Buffer.byteLength(prepared.patch),
1265
+ history: [],
1266
+ finishedAt: Date.now(),
1267
+ })
1268
+ }
1269
+ return { status: "retry_prepared", retryId, sourceTaskIds, paths,
1270
+ nextAction: "Review the patch with acent_bridge_status, then apply only the retryId with its retryRevision if approved." }
1271
+ }
1272
+
1273
+ async function integrateOnce(folder, projectDir, coordination, { ids, apply, prepareRetry, retryRevision }, captureEvidence) {
1274
+ if (!safeIds(ids) || (apply !== undefined && typeof apply !== "boolean") ||
1275
+ (prepareRetry !== undefined && typeof prepareRetry !== "boolean"))
1213
1276
  throw new Error("Select one to eight completed Bridge task IDs.")
1277
+ if (apply && prepareRetry) throw new Error("Prepare and review the retry before applying it.")
1214
1278
  return withWorkspaceLock(coordination, async () => {
1215
1279
  const receiptPath = join(
1216
1280
  projectDir,
@@ -1249,9 +1313,19 @@ export function createBridge({
1249
1313
  status: job ? taskState(job) : "not_found",
1250
1314
  })),
1251
1315
  }
1316
+ const preparedRetry = records.find(({ job }) => job.sourceTaskIds)?.job
1317
+ if (preparedRetry && ids.length > 1)
1318
+ return { status: "retry_requires_separate_apply", retryId: preparedRetry.id }
1319
+ if (preparedRetry && apply && retryRevision !== preparedRetry.retryRevision)
1320
+ return { status: "retry_review_required", retryId: preparedRetry.id }
1252
1321
  const changes = records.flatMap(({ id, job }) =>
1253
1322
  (job.changes ?? []).map((change) => ({ ...change, id }))
1254
1323
  )
1324
+ const guards = records.flatMap(({ job }) => job.retryGuards ?? [])
1325
+ const guardConflicts = await mismatchedBridgePaths(folder, guards, "before")
1326
+ if (guardConflicts.length)
1327
+ return { status: "working_copy_changed", paths: guardConflicts,
1328
+ sourceTaskIds: preparedRetry?.sourceTaskIds }
1255
1329
  const overlaps = changes
1256
1330
  .filter((change, index) =>
1257
1331
  changes
@@ -1262,8 +1336,6 @@ export function createBridge({
1262
1336
  )
1263
1337
  )
1264
1338
  .map((change) => change.path)
1265
- if (overlaps.length)
1266
- return { status: "patch_overlap", paths: [...new Set(overlaps)] }
1267
1339
  const paths = changes.map((change) => change.path)
1268
1340
  const captureApplied = async (at) => {
1269
1341
  if (!captureEvidence) return
@@ -1311,15 +1383,23 @@ export function createBridge({
1311
1383
  )
1312
1384
  return { status: "working_copy_changed", paths }
1313
1385
  const conflicts = await mismatchedBridgePaths(folder, changes, "before")
1314
- if (conflicts.length)
1315
- return { status: "working_copy_changed", paths: conflicts }
1316
- if (
1317
- await leases(coordination).then((entries) =>
1318
- entries.some((item) => item.preparing)
1319
- )
1320
- )
1321
- return { status: "snapshot_in_progress" }
1322
-
1386
+ const retryable = receipt?.status !== "applying" && !preparedRetry
1387
+ const needsRetry = overlaps.length || conflicts.length
1388
+ if (needsRetry && (!prepareRetry || !retryable)) {
1389
+ return {
1390
+ status: overlaps.length ? "patch_overlap" : "working_copy_changed",
1391
+ paths: [...new Set(overlaps.length ? overlaps : conflicts)],
1392
+ ...(retryable && { nextAction: "Prepare a patch from the latest files with prepareRetry: true." }),
1393
+ ...(preparedRetry && { sourceTaskIds: preparedRetry.sourceTaskIds,
1394
+ nextAction: "Prepare another patch from the latest files using the original task IDs." }),
1395
+ }
1396
+ }
1397
+ const active = await leases(coordination)
1398
+ if (active.some(({ preparing }) => preparing)) return { status: "snapshot_in_progress" }
1399
+ const busy = [...paths, ...guards.map(({ path }) => path)].filter((path) => active.some((item) =>
1400
+ item.writes && (!item.paths.length || item.paths.some((scope) => pathsOverlap(scope, path)))
1401
+ ))
1402
+ if (busy.length) return { status: "scope_busy", paths: [...new Set(busy)] }
1323
1403
  const patches = await Promise.all(
1324
1404
  records.map(({ directory, job }) =>
1325
1405
  job.patchBytes
@@ -1327,12 +1407,15 @@ export function createBridge({
1327
1407
  : ""
1328
1408
  )
1329
1409
  )
1410
+ if (prepareRetry && needsRetry)
1411
+ return saveIntegrationRetry(folder, projectDir, records, patches)
1330
1412
  const patch = patches.filter(Boolean).join("\n")
1331
1413
  const result = await applyVersionedBridgePatch(
1332
1414
  folder,
1333
1415
  { patch, changes },
1334
1416
  {
1335
1417
  check: !apply,
1418
+ guards,
1336
1419
  previewRoot: join(projectDir, "previews"),
1337
1420
  beforeApply: () =>
1338
1421
  writeJson(receiptPath, { status: "applying", paths }),
@@ -1345,12 +1428,27 @@ export function createBridge({
1345
1428
  })
1346
1429
  }
1347
1430
 
1431
+ async function integrate(folder, projectDir, coordination, args, captureEvidence) {
1432
+ for (let retries = 0; ; retries++) {
1433
+ const result = await integrateOnce(folder, projectDir, coordination, args, captureEvidence)
1434
+ if (retries === 3 || !["snapshot_in_progress", "scope_busy"].includes(result.status))
1435
+ return result
1436
+ await pause(250 * (retries + 1))
1437
+ }
1438
+ }
1439
+
1348
1440
  return async function call(name, args, selectedFolder, loadSettings) {
1441
+ const worker = process.env.ACENT_BRIDGE_WORKER === "1"
1442
+ if (worker && (name === "acent_bridge_start" ||
1443
+ (name === "acent_bridge_refine" && args.action === "start"))) {
1444
+ throw new Error("A Bridge worker cannot start another delegation.")
1445
+ }
1349
1446
  if (!selectedFolder)
1350
1447
  throw new Error("Open a single project folder before using Bridge.")
1351
1448
  const folder = await realpath(selectedFolder)
1352
1449
  if (!(await stat(folder)).isDirectory())
1353
1450
  throw new Error("Bridge needs a project directory.")
1451
+ await checkProjectCodeReceipt(name, args, folder)
1354
1452
  const settings = await loadSettings(folder)
1355
1453
  if (
1356
1454
  !/^[a-f0-9]{64}$/.test(settings?.projectKey ?? "") ||
@@ -1380,11 +1478,11 @@ export function createBridge({
1380
1478
  if (name === "acent_bridge_settings") {
1381
1479
  if (Object.keys(args).length)
1382
1480
  throw new Error("Change Bridge settings from the project in Acent.")
1383
- if (settings.automatic)
1481
+ if (settings.automatic && !worker)
1384
1482
  void Promise.all(
1385
1483
  settings.targets.map((tool) => getTarget(tool, folder))
1386
1484
  )
1387
- return { automatic: settings.automatic, targets: settings.targets }
1485
+ return { automatic: settings.automatic && !worker, targets: settings.targets }
1388
1486
  }
1389
1487
  if (name === "acent_bridge_candidates" || name === "acent_bridge_start") {
1390
1488
  if (!["implement", "review", "diagnose"].includes(args.kind))
@@ -1473,7 +1571,7 @@ export function createBridge({
1473
1571
  })
1474
1572
  }
1475
1573
  if (name === "acent_bridge_integrate")
1476
- return integrate(folder, projectDir, coordination, args.ids, args.apply, settings.captureEvidence)
1574
+ return integrate(folder, projectDir, coordination, args, settings.captureEvidence)
1477
1575
  if (name === "acent_bridge_finalize") {
1478
1576
  const result = await finalize(folder, projectDir, coordination, args)
1479
1577
  if (settings.captureEvidence && result.checkedAt)
@@ -1643,6 +1741,8 @@ export function createBridge({
1643
1741
  findings,
1644
1742
  question,
1645
1743
  patchBytes,
1744
+ sourceTaskIds,
1745
+ retryRevision,
1646
1746
  lastRunTokens,
1647
1747
  lastRunErrorCode,
1648
1748
  remainingQuota,
@@ -1668,6 +1768,8 @@ export function createBridge({
1668
1768
  patch,
1669
1769
  patchPath,
1670
1770
  patchBytes,
1771
+ sourceTaskIds,
1772
+ retryRevision,
1671
1773
  violations,
1672
1774
  changedPaths: changes?.map((change) => change.path),
1673
1775
  lastRunTokens,
@@ -0,0 +1,67 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+
5
+ const filename = /^[a-f0-9]{64}\.json$/
6
+ const requestId = /^(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?:[a-z0-9]+::){1,3}[a-z0-9]+-\d{6,}-[a-f0-9]+)$/i
7
+ const stages = new Set(["authorization", "policy", "hook", "prepare", "attachments", "queue", "upload"])
8
+ const knownCodes = new Set([
9
+ "invalid_token", "invalid_grant", "insufficient_scope", "capture_disabled",
10
+ "destination_changed", "prompt_pending", "invalid_packet", "invalid_capture",
11
+ "invalid_session", "capacity_exceeded", "subscription_required", "server_error",
12
+ "queue_full", "payload_too_large", "invalid_hook", "hook_timeout", "missing_session",
13
+ "lock_busy", "EACCES", "EPERM", "ENOSPC", "EROFS", "ENOENT", "EIO",
14
+ "ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT",
15
+ "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET",
16
+ ])
17
+
18
+ export function captureDiagnosticDirectory(directory, clientId) {
19
+ const key = createHash("sha256").update(clientId).digest("hex")
20
+ return join(directory, "managed-capture-diagnostics", key)
21
+ }
22
+
23
+ export async function recordCaptureDiagnostic(directory, clientId, stage, error, { missed = false } = {}) {
24
+ if (!stages.has(stage)) return
25
+ try {
26
+ const root = captureDiagnosticDirectory(directory, clientId)
27
+ await mkdir(root, { recursive: true, mode: 0o700 })
28
+ const candidate = error?.code ?? error?.cause?.code
29
+ const code = knownCodes.has(candidate) ? candidate
30
+ : error?.name === "TimeoutError" || error?.name === "AbortError" ? "timeout"
31
+ : error?.status ? "http_error" : "unknown"
32
+ const entry = { timestamp: new Date().toISOString(), stage, code }
33
+ if (missed) entry.missed = true
34
+ if (Number.isInteger(error?.status) && error.status >= 100 && error.status <= 599)
35
+ entry.status = error.status
36
+ if (typeof error?.requestId === "string" && error.requestId.length <= 100 && requestId.test(error.requestId))
37
+ entry.requestId = error.requestId
38
+ if (["authorization", "validate", "turn_policy", "encryption", "save_evidence", "save_conversation"].includes(error?.serverStage))
39
+ entry.serverStage = error.serverStage
40
+ if (["conflict", "constraint", "permission", "database", "unknown"].includes(error?.serverReason))
41
+ entry.serverReason = error.serverReason
42
+ // Keep the latest occurrence of each failure, with bounded local retention.
43
+ const signature = createHash("sha256").update(JSON.stringify([
44
+ stage, code, entry.status, entry.serverStage, entry.serverReason, missed,
45
+ ])).digest("hex")
46
+ const file = join(root, signature + ".json")
47
+ const temp = join(root, signature + "." + randomUUID() + ".tmp")
48
+ try {
49
+ await writeFile(temp, JSON.stringify(entry), { mode: 0o600, flag: "wx" })
50
+ await rename(temp, file)
51
+ } finally {
52
+ await rm(temp, { force: true })
53
+ }
54
+ const files = (await readdir(root, { withFileTypes: true }))
55
+ .filter(item => item.isFile() && filename.test(item.name))
56
+ if (files.length > 96) {
57
+ const entries = await Promise.all(files.map(async item => {
58
+ const name = join(root, item.name)
59
+ return { name, at: (await stat(name).catch(() => null))?.mtimeMs ?? 0 }
60
+ }))
61
+ entries.sort((a, b) => b.at - a.at)
62
+ await Promise.all(entries.slice(96).map(item => rm(item.name, { force: true })))
63
+ }
64
+ } catch {
65
+ // Diagnostics must not stop capture when the local disk is unavailable.
66
+ }
67
+ }
@@ -81,6 +81,15 @@ export function capturePayload(event, code, activity) {
81
81
  changeIds: [],
82
82
  }
83
83
  )
84
+ // Bridge can report multiple statuses or batches for one operation. Link
85
+ // edits by their explicit change IDs and give each activity its own call ID.
86
+ if (event.hook_event_name === "AcentBridge" && result.acent_activity) {
87
+ result.acent_activity = result.acent_activity.map((item) => {
88
+ if (typeof item?.callId !== "string" || !/^bridge:[a-f0-9-]{36}:[a-z_]+$/.test(item.callId) ||
89
+ typeof item.id !== "string" || !/^[a-f0-9]{64}$/.test(item.id)) return item
90
+ return { ...item, callId: item.callId + ":" + item.id }
91
+ })
92
+ }
84
93
  if (code && Array.isArray(event.acent_code_changes))
85
94
  result.acent_code_changes = event.acent_code_changes
86
95
  if (code && Array.isArray(event.acent_activities))
@@ -7,6 +7,10 @@ import { join } from "node:path"
7
7
  const generatedHeader =
8
8
  /^This is an app-generated request\b[^\n]{0,500}The user did not write this message\.(?:\s|$)/i
9
9
 
10
+ export function isCodexGeneratedPrompt(prompt) {
11
+ return typeof prompt === "string" && generatedHeader.test(prompt.trimStart())
12
+ }
13
+
10
14
  export async function captureCodexEvent(payload, directory) {
11
15
  const session = payload.session_id
12
16
  if (typeof session !== "string" || !session) return false
@@ -22,7 +26,7 @@ export async function captureCodexEvent(payload, directory) {
22
26
  if (
23
27
  typeof prompt !== "string" ||
24
28
  !prompt.trim() ||
25
- generatedHeader.test(prompt.trimStart())
29
+ isCodexGeneratedPrompt(prompt)
26
30
  ) {
27
31
  await rm(marker, { force: true })
28
32
  return false
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { isAbsolute } from "node:path"
3
- import { main } from "./acent-connect.mjs"
3
+ import { main, recordBoundHookFailure } from "./acent-connect.mjs"
4
+ import { bridgeLifecycle, isBridgeContinuation } from "./bridge-lifecycle.mjs"
4
5
  // Use the documented hook cwd, never a plugin cache folder or another binding.
6
+ const args = process.argv.slice(2)
7
+ const bridgeEventIndex = args.indexOf("--bridge-event")
8
+ const bridgeEvent = bridgeEventIndex === -1 ? undefined : args.splice(bridgeEventIndex, 2)[1]
5
9
  let text = ""
6
10
  try {
7
11
  for await (const chunk of process.stdin) {
@@ -10,6 +14,8 @@ try {
10
14
  throw new Error("Hook event exceeds 2 MiB")
11
15
  }
12
16
  const payload = JSON.parse(text)
17
+ // A host may dispatch the completion reminder as a new prompt event.
18
+ if (isBridgeContinuation(payload)) process.exit(0)
13
19
  const cursor = process.argv.includes("Cursor")
14
20
  const antigravity = process.argv.includes("Antigravity")
15
21
  const roots = cursor ? payload.workspace_roots : antigravity ? payload.workspacePaths : undefined
@@ -20,11 +26,20 @@ try {
20
26
  : payload.cwd
21
27
  if (folder != null && folder !== "" && (typeof folder !== "string" || !isAbsolute(folder)))
22
28
  throw new Error("Hook has an invalid working folder")
23
- const session = payload.session_id || payload.conversation_id || payload.conversationId
24
- if (typeof session !== "string" || !session.trim())
29
+ const session = [payload.session_id, payload.conversation_id, payload.conversationId]
30
+ .find(value => typeof value === "string" && value.trim())
31
+ if (!session) {
32
+ if (folder && !bridgeEvent) await recordBoundHookFailure([...args, "--folder", folder], "missing_session")
25
33
  throw new Error("Hook is missing a conversation identifier")
34
+ }
35
+ if (!antigravity) {
36
+ const event = bridgeEvent ?? payload.hook_event_name
37
+ const tool = args[args.indexOf("--tool") + 1]
38
+ const bridgeOutput = await bridgeLifecycle({ tool, folder, session, payload, args, event }).catch(() => undefined)
39
+ if (bridgeOutput) process.stdout.write(JSON.stringify(bridgeOutput) + "\n")
40
+ }
26
41
  // The host delivers this context to the turn that made the Bridge call.
27
- if (process.argv.includes("Codex") &&
42
+ if (process.env.ACENT_BRIDGE_WORKER !== "1" && process.argv.includes("Codex") &&
28
43
  payload.hook_event_name === "PostToolUse" &&
29
44
  /^mcp__acent__acent_bridge_[a-z_]+$/.test(payload.tool_name ?? "") &&
30
45
  typeof payload.model === "string" && /^[\w][\w.:/-]{0,159}$/.test(payload.model) &&
@@ -34,7 +49,7 @@ try {
34
49
  additionalContext: `Codex reports ${payload.model} as the coordinating model for this turn. Use this ID as currentModel for Bridge review, diagnosis, and refinement in this turn. If candidate selection could not verify a reference model, retry with this currentModel. Use it for this turn's direct-work row in the Acent Bridge report.`,
35
50
  } }) + "\n")
36
51
  }
37
- await main(["collect", ...process.argv.slice(2),
52
+ if (!bridgeEvent) await main(["collect", ...args,
38
53
  ...(folder ? ["--folder", folder] : ["--general"])], text)
39
54
 
40
55
  } catch (error) {
@@ -479,11 +479,20 @@ async function handleLine(line) {
479
479
 
480
480
  // Keep reading while a tool waits for an elicitation response on this same pipe.
481
481
  const active = new Set()
482
+ // Retry previously approved queued captures while the host connection is open.
483
+ // The shared drain lock and the current server policy still govern every upload.
484
+ const captureRetry = process.env.ACENT_BRIDGE_WORKER === "1" ? null : setInterval(() => {
485
+ const config = activeConfig
486
+ if (!config.bindingKnown) return
487
+ void drain(config, configDirectory(config)).catch(() => {})
488
+ }, 120_000)
489
+ captureRetry?.unref()
482
490
  for await (const line of lines) {
483
491
  const task = handleLine(line)
484
492
  active.add(task)
485
493
  void task.finally(() => active.delete(task))
486
494
  }
495
+ if (captureRetry) clearInterval(captureRetry)
487
496
  rootRequests.close()
488
497
  questions.close()
489
498
  await Promise.allSettled(active)
@@ -15,6 +15,7 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
15
15
  - Keep straightforward copy or styling edits and dependent steps with the coordinating agent. Start additional automatic tasks only when each has a distinct, useful result. Give each shared contract, state machine, or business rule one writer, even when it spans separate files. Finish a prerequisite first or use `dependsOn` when later work needs its result. Use read-only review or diagnosis for independent work when writes need one owner.
16
16
  - Keep authorized production actions with the coordinating agent, including deployments, database migrations, and live payments or refunds. Bridge can review the plan or verify the outcome independently.
17
17
  - If automatic delegation is disabled, continue directly. If it is enabled and no suitable candidate is available, continue the work you can verify and report why independent work did not run.
18
+ - Before finishing eligible work, confirm that the independent check ran or explain why it could not run. If the host issues a completion reminder, handle this once and finish normally. Bridge worker sessions carry out the assigned task without starting another delegation.
18
19
  - Classify the work as `implement`, `review`, or `diagnose`. Call `acent_bridge_candidates` and select a returned tool and model that fit the task and the user's preference. For review, diagnosis, and refinement, pass the host-reported model for this turn as `currentModel`. Supply `originModel` when reviewing earlier work whose originating model is known. Bridge uses the earlier model when supplied and recognized, otherwise it checks independence against the current model. In Codex, if candidate selection returns `origin_model_unverified` and the Bridge hook reports the current model, retry with that ID. Pass the same model inputs to start the selected work. Report when no eligible candidate is available.
19
20
  - Honor a user-specified model. For automatic selection, choose for task fit and review independence first and check any reported quota. Among similarly suitable candidates, prefer Grok in Cursor and Gemini in Antigravity, marked `preferredForTool`. Use another eligible model such as Claude in Cursor when it fits the task better or when the preferred family is unavailable, within the user's usage and spending settings. Pass the selected model ID explicitly. Treat missing or expired quota data as unknown. In Antigravity, skip candidates marked `includedQuota: exhausted` for automatic selection unless the user has authorized overage use.
20
21
  - Before starting any task or refinement, gather the active decisions, constraints, and prior findings that affect the delegated scope. Use evidence already available. If missing project history could change the work, use [Acent Decisions](../acent-decisions/SKILL.md) for prior choices or [Acent Recall](../acent-recall/SKILL.md) for earlier requirements and attempts. Put the relevant facts, decision rationale where it affects the task, and unresolved points in `context` on the first call. For self-contained work, pass the current facts the delegate needs.
@@ -22,6 +23,7 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
22
23
  - Check multiple jobs together with `acent_bridge_activity`, or use `acent_bridge_status` for a patch or a full answer. While jobs run, continue independent work and avoid tight polling. If a delegate requests context, answer with the relevant evidence using `acent_bridge_continue`. Ask the user if their judgment is needed. Resume interrupted work from its existing copy or use `acent_bridge_cancel` to stop work that is no longer needed.
23
24
  - In the final answer, name any enabled or explicitly requested tool that could not participate because its CLI required authentication. Use `loginRequiredTools` from candidate selection or `login_required` from task or refinement status. Include the tool even if others completed the work, and use its final result if it later succeeded. Point the user to **Set up** in Acent Bridge. Report model catalog failures and other unavailable states with their own reasons.
24
25
  - Use `acent_bridge_integrate` to check completed patches together. Review them before applying. Start independent review after integration so all reviewers examine the same candidate, including the interfaces between changes. For substantive changes you are authorized to edit, start `acent_bridge_refine` with a UUID, the original task and constraints, the scoped files, a repair model, and one or more reviewers from distinct model families outside the original and repair families. Pass applied task IDs in `dependsOn`. For complex integrations, give eligible reviewers complementary priorities with `focus`, such as concurrency, cross-component behavior, or regressions. Review the integrated changes and run the coordinator's checks while Bridge reviewers work. Keep the reviewed files stable until the reports return. If fixes change the candidate, re-review and rerun the affected checks on the updated changes. For a read-only request, use the standalone review instead.
26
+ - Bridge briefly rechecks a busy workspace during integration. If the files changed or patches overlap, use `prepareRetry: true` on the original task IDs when offered, then read the returned `retryId` with `acent_bridge_status`. After review, apply that retry on its own with the returned `retryRevision`. If preparation reports `manual_review_required`, reconcile the current file and source patches in one scoped task.
25
27
  - Refinement supplies the original scoped Git diff and the cumulative repair diff to reviewers. It gathers independent findings and re-reviews repairs in a private staging workspace. Keep working on unrelated files while it runs. Check its status when results are needed. If a worker requests context, answer with `acent_bridge_continue` and then check refinement status. If a reviewer cannot run, call `replace_reviewer` with that review ID and an eligible replacement model. Completed reviews in that round stay in place.
26
28
  - At `needs_checks`, call the refinement's `verify` action with the current `checkRevision` and the authorized test executables and arguments. Bridge runs them in a private copy of the reviewed candidate. For a standalone review of integrated edits, submit `commands` to `acent_bridge_finalize` and poll without them. Both flows prepare dependencies in the private test copy. Bridge can install locked npm dependencies automatically, and `setupCommands` can supply the project's own preparation steps. Report verification after `verified`. If project files captured in the verification snapshot change, begin from the latest changes.
27
29
  - Use `apply: true` to apply scoped repairs after the stage passes review and tests. Otherwise inspect the verified patch and call `apply` with the current `checkRevision`. If the user stops verification or refinement, call its `cancel` action and confirm the final state. If promotion has already started, check what was applied. If findings remain after three repairs or require files outside the approved scope, report the blocker.
@@ -29,7 +31,8 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
29
31
  ## Approval before sharing data
30
32
 
31
33
  - Automatic delegation selects eligible tools. A direct request authorizes its stated destination and data. When a handoff needs additional data-sharing approval, call `acent_bridge_request_approval` before submitting it. Show all destination agents, the exact file or data scope, and the purpose using labels only. Include any context, diffs, and extra read access in the scope description without including their contents. Check again before a replacement or continuation that would share new data.
32
- - Proceed through the normal Bridge tool after explicit approval or a saved exact-scope approval. For a new task use the approval result’s requestId when calling acent_bridge_start. After an interrupted approval, reopen the same scope only when the user asks to resume. On `needs_user_input`, use the host's approval flow or ask once in the current chat if the host permits it. On decline, cancellation, or unavailable approval, continue locally. Follow all host approval requirements and never use the Bridge question to override or route around a host denial.
34
+ - Proceed through the normal Bridge tool after approval. Interactive Acent CLI install or update can save project code permission. Pass individual project-relative file paths to `acent_bridge_request_approval` to use that permission. When the result has `permissionScope: "project_code"`, use exactly those files across `paths` and `readPaths`. Keep any inline context within that project code scope. Request explicit approval for additional data, including raw logs and conversation content.
35
+ - Request approval once for destinations sharing the same scope and purpose. For a separate task per destination, set `requestId` to its `requestIdsByTarget` value. For a single task use `requestId`, and for refinement pass it as `id`. Keep the same purpose label for related handoffs with the same purpose. After an interrupted approval, reopen the same scope only when the user asks to resume. On `needs_user_input`, use the host's approval flow or ask once in the current chat if the host permits it. On decline, cancellation, or unavailable approval, continue locally. Follow all host approval requirements and never use the Bridge question to override or route around a host denial.
33
36
 
34
37
  ## Review when only the coordinator can access a source
35
38
 
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
3
  "name": "acent",
4
4
  "displayName": "Acent",
5
- "version": "1.3.0",
5
+ "version": "1.3.3",
6
6
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
7
7
  "author": {
8
8
  "name": "Cirtium"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cirtium/acent-connect",
3
- "version": "1.3.0",
3
+ "version": "1.3.3",
4
4
  "type": "module",
5
5
  "description": "Install and connect the shared Acent coding-tool plugin",
6
6
  "repository": {