@cirtium/acent-connect 1.2.5 → 1.3.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.
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdir, readFile, rm, stat, unlink } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { atomicJson, boundConfig, configDirectory, request } from "./acent-connect.mjs"
5
+ import { isCodexGeneratedPrompt } from "./codex-capture.mjs"
6
+
7
+ const guidance = "Acent Bridge: for feature work, bug fixes, or behavioral verification, call acent_bridge_settings before investigating or editing. If automatic delegation is enabled, check candidates early and start an independent task within the approved sharing scope. If no review can run, report the reason before finishing. Honor a user request to work directly."
8
+ const reminder = "Acent Bridge: this turn edited the project with automatic delegation enabled, and no candidate check or delegation was observed. Before finishing, check the Bridge settings and eligible candidates and arrange an independent check if applicable. For small styling or copy edits, a user opt-out, unavailable candidates, or pending sharing approval, finish directly and report the applicable reason."
9
+ const edits = /^(?:apply_patch|Edit|MultiEdit|Write|NotebookEdit|write_to_file|replace_file_content|multi_replace_file_content|str_replace|str_replace_editor)$/i
10
+ const bridgeTool = /^(?:(?:mcp__acent(?:_acent)?__|mcp_acent_acent_|MCP:)?acent_bridge_)(?:candidates|start|refine|request_approval)$/
11
+
12
+ export function isBridgeContinuation(payload) {
13
+ return ["UserPromptSubmit", "beforeSubmitPrompt"].includes(payload.hook_event_name) &&
14
+ payload.prompt === reminder
15
+ }
16
+
17
+ function observedTool(payload, tool, event) {
18
+ if (tool !== "Antigravity") {
19
+ if (event === "afterMCPExecution") {
20
+ return ["acent", "acent-acent", "acent_acent"].includes(payload.mcp_server_name)
21
+ ? payload.tool_name : undefined
22
+ }
23
+ return payload.tool_name
24
+ }
25
+ const { name, args } = payload.toolCall ?? {}
26
+ if (name === "call_mcp_tool" && args?.ServerName === "acent_acent") {
27
+ if (args.ToolName === "acent_workspace") return args.Arguments?.tool
28
+ return args.ToolName
29
+ }
30
+ if (name === "mcp_acent_acent_acent_workspace") return args?.tool
31
+ return name
32
+ }
33
+
34
+ function nativeContext(tool, event, payload) {
35
+ const model = payload.model ?? payload.model_name ?? payload.modelName
36
+ const modelKnown = typeof model === "string" && /^[\w][\w.:/-]{0,159}$/.test(model) &&
37
+ !/^(?:auto|default|unknown)$/i.test(model)
38
+ const context = modelKnown
39
+ ? guidance + " Use the host-reported model ID " + model + " as currentModel for independent review or diagnosis."
40
+ : guidance
41
+ if (tool === "Cursor") return { additional_context: context }
42
+ if (tool === "Antigravity") return { injectSteps: [{ ephemeralMessage: context }] }
43
+ return { hookSpecificOutput: { hookEventName: event, additionalContext: context } }
44
+ }
45
+
46
+ function nativeReminder(tool) {
47
+ if (tool === "Cursor") return { followup_message: reminder }
48
+ return { decision: tool === "Antigravity" ? "continue" : "block", reason: reminder }
49
+ }
50
+
51
+ async function automaticSetting(config, credentials) {
52
+ // The hook must not contend with capture for refresh-token rotation.
53
+ if (typeof credentials?.access_token !== "string" ||
54
+ !Number.isFinite(credentials.expiresAt) || credentials.expiresAt <= Date.now() + 30_000) return null
55
+ const settings = await request(config, "/api/external/bridge", {
56
+ headers: { Authorization: "Bearer " + credentials.access_token },
57
+ signal: AbortSignal.timeout(750),
58
+ }).catch(() => null)
59
+ return typeof settings?.automatic === "boolean" ? settings.automatic : null
60
+ }
61
+
62
+ export async function bridgeLifecycle({ tool, folder, session, payload, args, event }) {
63
+ if (process.env.ACENT_BRIDGE_WORKER === "1" || !folder || !session) return
64
+ const cursor = tool === "Cursor"
65
+ const antigravity = tool === "Antigravity"
66
+ const prompt = event === "UserPromptSubmit" || event === "beforeSubmitPrompt" ||
67
+ (event === "PreInvocation" && payload.invocationNum === 0)
68
+ const sessionStart = cursor && event === "sessionStart"
69
+ const stop = event === "Stop" || event === "stop"
70
+ const observed = event === "PostToolUse" || event === "postToolUse" || event === "afterMCPExecution"
71
+ const name = observed ? observedTool(payload, tool, event) ?? "" : ""
72
+ const attempted = bridgeTool.test(name)
73
+ const edited = event === "afterFileEdit" || edits.test(name)
74
+ if (!prompt && !sessionStart && !stop && !attempted && !edited) return
75
+
76
+ const config = await boundConfig(["flush", ...args, "--folder", folder])
77
+ if (config.general) return
78
+ const directory = configDirectory(config)
79
+ const credentialsPath = join(directory, "credentials.json")
80
+ if (!(await stat(credentialsPath).catch(() => null))?.isFile()) return
81
+ const stateDir = join(directory, "bridge-turns")
82
+ const key = createHash("sha256").update(JSON.stringify([
83
+ session, tool === "Codex" ? payload.turn_id ?? null : null,
84
+ ])).digest("hex")
85
+ const file = join(stateDir, key + ".json")
86
+ const editsFile = file + ".edited"
87
+ const attemptsFile = file + ".attempted"
88
+ const removeState = () => Promise.all([file, editsFile, attemptsFile].map(path => rm(path, { force: true })))
89
+ if (sessionStart) return nativeContext(tool, event, payload)
90
+
91
+ if (prompt) {
92
+ if (isBridgeContinuation(payload) || (tool === "Codex" && isCodexGeneratedPrompt(payload.prompt))) return
93
+ const credentials = await readFile(credentialsPath, "utf8").then(JSON.parse)
94
+ const automatic = await automaticSetting(config, credentials)
95
+ await mkdir(stateDir, { mode: 0o700, recursive: true })
96
+ await removeState()
97
+ if (automatic === true) await atomicJson(file, { at: Date.now() })
98
+ if (!cursor && automatic !== false) return nativeContext(tool, event, payload)
99
+ return
100
+ }
101
+
102
+ const state = await readFile(file, "utf8").then(JSON.parse).catch(() => null)
103
+ if (!state || Date.now() - state.at > 24 * 60 * 60 * 1000) {
104
+ if (stop && state) await removeState()
105
+ return
106
+ }
107
+ if (attempted || edited) {
108
+ await atomicJson(attempted ? attemptsFile : editsFile, true)
109
+ return
110
+ }
111
+ if (antigravity && !payload.fullyIdle) return
112
+ const [hasEdits, hasAttempt] = await Promise.all([editsFile, attemptsFile].map(path => stat(path).catch(() => null)))
113
+ // Only the first completion hook can claim the check for this turn.
114
+ if (!(await unlink(file).then(() => true).catch(() => false))) return
115
+ await Promise.all([editsFile, attemptsFile].map(path => rm(path, { force: true })))
116
+ if (payload.stop_hook_active || (cursor && (payload.status !== "completed" || payload.loop_count > 0)) ||
117
+ (antigravity && payload.terminationReason !== "model_stop")) return
118
+ if (hasEdits && !hasAttempt) return nativeReminder(tool)
119
+ }
@@ -389,7 +389,49 @@ async function codexInfo(run, cwd, includeQuota = false) {
389
389
  : { models, accountKey, windows }
390
390
  }
391
391
 
392
+ function antigravityQuota(report, now) {
393
+ const command = report?.command
394
+ if (report?.status !== "SUCCESS" || command?.name !== "usage" ||
395
+ !Array.isArray(command.data?.groups))
396
+ return []
397
+ return command.data.groups.flatMap((group) => {
398
+ const name = typeof group?.name === "string" ? group.name.trim().toLowerCase() : ""
399
+ const familyGroup = name === "gemini models" ? "gemini"
400
+ : name === "claude and gpt models" ? "claude_gpt" : undefined
401
+ if (!familyGroup || !Array.isArray(group.buckets)) return []
402
+ return group.buckets.flatMap((bucket) => {
403
+ const remaining = bucket?.remaining_fraction
404
+ const reset = typeof bucket?.reset_time === "string" ? Date.parse(bucket.reset_time) : NaN
405
+ if (bucket?.disabled || !Number.isFinite(remaining) || remaining < 0 || remaining > 1 ||
406
+ !/^[a-z0-9_-]{1,80}$/i.test(bucket?.id ?? "") ||
407
+ !["5h", "weekly"].includes(bucket.window) ||
408
+ (remaining === 0 && !(reset > now)) ||
409
+ (Number.isFinite(reset) && reset <= now && remaining < 1))
410
+ return []
411
+ return [{
412
+ bucket: bucket.id,
413
+ group: familyGroup,
414
+ window: bucket.window,
415
+ remainingPercent: remaining * 100,
416
+ ...(reset > now ? { resetsAt: reset } : {}),
417
+ }]
418
+ })
419
+ })
420
+ }
421
+
392
422
  export async function readBridgeQuota(tool, cwd, run = runProcess) {
423
+ if (tool === "Antigravity") {
424
+ const result = await runHost(tool, ["usage", "--json"], { cwd, timeout: 8000 }, run)
425
+ if (result.code !== 0 || result.failure) return
426
+ const checkedAt = Date.now()
427
+ try {
428
+ const windows = antigravityQuota(JSON.parse(result.stdout), checkedAt)
429
+ if (windows.length) return { checkedAt, windows }
430
+ } catch {
431
+ // Older versions and failed discovery leave the quota unknown.
432
+ }
433
+ return
434
+ }
393
435
  if (tool !== "Codex") return
394
436
  const { accountKey, windows } = await codexInfo(run, cwd, true)
395
437
  if (!accountKey || !windows?.length) return
@@ -489,6 +531,7 @@ export async function discoverBridgeTarget(
489
531
  modelCatalog: ids.length ? "available" : "unverified",
490
532
  ...(modelCatalogFailure ? { modelCatalogFailure } : {}),
491
533
  accountKey: codex?.accountKey,
534
+ ...(tool === "Antigravity" && ids.length ? { quotaReporting: "live" } : {}),
492
535
  }
493
536
  }
494
537
 
@@ -130,7 +130,7 @@ export const bridgeTools = [
130
130
  ),
131
131
  toolSchema(
132
132
  "acent_bridge_candidates",
133
- "List locally available tool and model combinations for a new Bridge task. Review and diagnosis use the current model by default, or a verified model from the earlier work when supplied. Omit a tool to consider all enabled tools.",
133
+ "List available tool and model combinations for a new Bridge task. For similarly suitable candidates, prefer Grok in Cursor and Gemini in Antigravity, marked preferredForTool. Review and diagnosis exclude the current model family or the family verified for earlier work. Omit a tool to consider all enabled tools.",
134
134
  {
135
135
  kind,
136
136
  ...reviewModelInputs,
@@ -151,7 +151,7 @@ export const bridgeTools = [
151
151
  ...reviewModelInputs,
152
152
  tool: target,
153
153
  model: text(
154
- "Model ID from the candidates list. Omit for the tool default."
154
+ "Use a concrete model ID from the candidates list. If omitted, Cursor prefers eligible Grok and Antigravity prefers eligible Gemini. If Gemini included quota is exhausted, Antigravity can select an eligible external model with confirmed included quota. Other tools use their eligible default."
155
155
  ),
156
156
  task: text(
157
157
  "Concrete task, relevant files, constraints, and what has already been tried."
@@ -302,7 +302,8 @@ export const bridgeInstructions = [
302
302
  "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
303
  "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
304
  "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.",
305
- "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.",
305
+ "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.",
306
+ "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
307
  "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
308
  "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
309
  "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.",
@@ -315,6 +316,38 @@ export const bridgeInstructions = [
315
316
  "Put application status, pending checks, and blockers in the table or the evidence above the conclusion. End the entire final answer, after the table and any evidence, with exactly one standalone sentence summarizing the overall outcome and the delegate's most useful observed contribution. If delegation could not run, state the blocker in that sentence. Place nothing after it.",
316
317
  ].join(" ")
317
318
 
319
+ const preferredModelFamilies = new Map([
320
+ ["Cursor", "grok"],
321
+ ["Antigravity", "gemini"],
322
+ ])
323
+
324
+ function selectBridgeModel(candidates, tool, requested) {
325
+ const available = candidates.filter((candidate) => candidate.tool === tool)
326
+ if (requested !== undefined)
327
+ return available.find((candidate) => candidate.model === requested)
328
+ if (!preferredModelFamilies.has(tool))
329
+ return available.find((candidate) => candidate.model === null)
330
+ const preferred = available.find((candidate) =>
331
+ candidate.preferredForTool && candidate.includedQuota !== "exhausted"
332
+ )
333
+ if (preferred) return preferred
334
+ if (tool === "Antigravity" && available.some((candidate) =>
335
+ candidate.preferredForTool && candidate.includedQuota === "exhausted"
336
+ ))
337
+ return available.find((candidate) =>
338
+ !candidate.preferredForTool && candidate.includedQuota === "available"
339
+ )
340
+ }
341
+
342
+ function antigravityModelQuota(family, quota) {
343
+ const group = family === "gemini" ? "gemini"
344
+ : family === "claude" || family === "gpt" ? "claude_gpt" : undefined
345
+ if (!group || quota.status !== "reported") return "unknown"
346
+ const windows = quota.windows.filter((window) => window.group === group)
347
+ if (windows.some((window) => window.remainingPercent === 0)) return "exhausted"
348
+ return windows.length ? "available" : "unknown"
349
+ }
350
+
318
351
  const cacheDuration = 120_000
319
352
  const failedDiscoveryCacheDuration = 5_000
320
353
  const leaseMaxAge = 20 * 60_000
@@ -588,7 +621,7 @@ export function createBridge({
588
621
  return result
589
622
  }
590
623
 
591
- async function candidates(args, folder, settings) {
624
+ async function candidates(args, folder, settings, { keepToolDefault = false, liveQuota = true } = {}) {
592
625
  if (args.automatic && !settings.automatic)
593
626
  return { status: "automatic_disabled", candidates: [] }
594
627
  const reference = reviewOnly(args.kind) ? reviewModelReference(args) : undefined
@@ -607,46 +640,52 @@ export function createBridge({
607
640
  (settings.targets.includes(tool) || args.tool === tool)
608
641
  )
609
642
  .map(({ tool }) => tool)
610
- const choices = targets.flatMap((item) =>
611
- item.status !== "ready"
612
- ? []
643
+ const quotas = await Promise.all(targets.map(async (item) => {
644
+ if (item.status !== "ready") return { status: "unknown" }
645
+ if (item.quotaReporting !== "live") return cachedQuota(item)
646
+ if (!liveQuota) return { status: "unknown" }
647
+ // The Antigravity command does not expose an account ID. Use a fresh snapshot
648
+ // for this selection and avoid sharing quota across signed-in accounts.
649
+ const sample = await readQuota(item.tool, folder).catch(() => undefined)
650
+ return sample?.windows?.length
651
+ ? { status: "reported", checkedAt: sample.checkedAt, windows: sample.windows }
652
+ : { status: "unknown" }
653
+ }))
654
+ const choices = targets.flatMap((item, index) => {
655
+ if (item.status !== "ready") return []
656
+ const preferredFamily = preferredModelFamilies.get(item.tool)
657
+ const models = preferredFamily && !keepToolDefault
658
+ ? item.models
613
659
  : [{ id: null, family: item.defaultFamily ?? null }, ...item.models]
614
- .filter(
615
- (model) =>
616
- !reference ||
617
- (model.family && model.family !== reference.family)
618
- )
619
- .filter(
620
- (model) =>
621
- (unavailable.get(
622
- modelKey(folder, item.tool, model.id, item.accountKey)
623
- ) ?? 0) <= Date.now()
624
- )
625
- .map((model) => ({
626
- tool: item.tool,
627
- model: model.id,
628
- family: model.family,
629
- }))
630
- )
660
+ return models
661
+ .filter((model) => !reference || (model.family && model.family !== reference.family))
662
+ .filter((model) =>
663
+ (unavailable.get(modelKey(folder, item.tool, model.id, item.accountKey)) ?? 0) <= Date.now()
664
+ )
665
+ .map((model) => ({
666
+ tool: item.tool,
667
+ model: model.id,
668
+ family: model.family,
669
+ ...(preferredFamily && model.family === preferredFamily ? { preferredForTool: true } : {}),
670
+ ...(item.tool === "Antigravity" ? { includedQuota: antigravityModelQuota(model.family, quotas[index]) } : {}),
671
+ }))
672
+ .sort((a, b) =>
673
+ Number(a.includedQuota === "exhausted") - Number(b.includedQuota === "exhausted") ||
674
+ Number(b.preferredForTool ?? false) - Number(a.preferredForTool ?? false)
675
+ )
676
+ })
631
677
  return {
632
678
  status: choices.length ? "ready" : "no_candidate",
633
679
  candidates: choices,
634
680
  ...(reference ? { referenceModel: reference.model, referenceModelSource: reference.source } : {}),
635
681
  ...(loginRequiredTools.length ? { loginRequiredTools } : {}),
636
- tools: await Promise.all(
637
- targets.map(async (item) => ({
638
- tool: item.tool,
639
- status: item.status,
640
- modelCatalog: item.modelCatalog,
641
- ...(item.modelCatalogFailure
642
- ? { modelCatalogFailure: item.modelCatalogFailure }
643
- : {}),
644
- remainingQuota:
645
- item.status === "ready"
646
- ? await cachedQuota(item)
647
- : { status: "unknown" },
648
- }))
649
- ),
682
+ tools: targets.map((item, index) => ({
683
+ tool: item.tool,
684
+ status: item.status,
685
+ modelCatalog: item.modelCatalog,
686
+ ...(item.modelCatalogFailure ? { modelCatalogFailure: item.modelCatalogFailure } : {}),
687
+ remainingQuota: quotas[index],
688
+ })),
650
689
  }
651
690
  }
652
691
 
@@ -741,9 +780,13 @@ export function createBridge({
741
780
  if (settings?.projectKey !== projectKey) return false
742
781
  let pending = false
743
782
  for (const job of queued) {
744
- const available = await candidates({ ...job, tool: job.tool }, folder, settings)
745
- if (!available.candidates.some(({ tool, model }) =>
746
- tool === job.tool && model === job.model
783
+ const available = await candidates({ ...job, tool: job.tool }, folder, settings, {
784
+ keepToolDefault: job.model === null,
785
+ liveQuota: job.modelSelectedAutomatically === true,
786
+ })
787
+ if (!available.candidates.some(({ tool, model, includedQuota }) =>
788
+ tool === job.tool && model === job.model &&
789
+ !(job.modelSelectedAutomatically && includedQuota === "exhausted")
747
790
  )) {
748
791
  const status = available.loginRequiredTools?.includes(job.tool)
749
792
  ? "login_required"
@@ -1304,6 +1347,11 @@ export function createBridge({
1304
1347
  }
1305
1348
 
1306
1349
  return async function call(name, args, selectedFolder, loadSettings) {
1350
+ const worker = process.env.ACENT_BRIDGE_WORKER === "1"
1351
+ if (worker && (name === "acent_bridge_start" ||
1352
+ (name === "acent_bridge_refine" && args.action === "start"))) {
1353
+ throw new Error("A Bridge worker cannot start another delegation.")
1354
+ }
1307
1355
  if (!selectedFolder)
1308
1356
  throw new Error("Open a single project folder before using Bridge.")
1309
1357
  const folder = await realpath(selectedFolder)
@@ -1338,11 +1386,11 @@ export function createBridge({
1338
1386
  if (name === "acent_bridge_settings") {
1339
1387
  if (Object.keys(args).length)
1340
1388
  throw new Error("Change Bridge settings from the project in Acent.")
1341
- if (settings.automatic)
1389
+ if (settings.automatic && !worker)
1342
1390
  void Promise.all(
1343
1391
  settings.targets.map((tool) => getTarget(tool, folder))
1344
1392
  )
1345
- return { automatic: settings.automatic, targets: settings.targets }
1393
+ return { automatic: settings.automatic && !worker, targets: settings.targets }
1346
1394
  }
1347
1395
  if (name === "acent_bridge_candidates" || name === "acent_bridge_start") {
1348
1396
  if (!["implement", "review", "diagnose"].includes(args.kind))
@@ -1387,7 +1435,7 @@ export function createBridge({
1387
1435
  removeStage: (stageDir) =>
1388
1436
  rm(stageDir, { recursive: true, force: true }),
1389
1437
  launch: async (task, currentSettings, snapshot) => {
1390
- const available = await candidates(task, folder, currentSettings)
1438
+ const available = await candidates(task, folder, currentSettings, { liveQuota: false })
1391
1439
  if (available.loginRequiredTools?.includes(task.tool))
1392
1440
  return { status: "login_required" }
1393
1441
  if (
@@ -1553,17 +1601,15 @@ export function createBridge({
1553
1601
  }
1554
1602
  : { id, status: "request_conflict" }
1555
1603
  }
1556
- const available = await candidates(args, folder, settings)
1557
- if (
1558
- !available.candidates.some(
1559
- (candidate) =>
1560
- candidate.tool === args.tool &&
1561
- candidate.model === (args.model ?? null)
1562
- )
1563
- )
1604
+ const available = await candidates(args, folder, settings, { liveQuota: args.model == null })
1605
+ const selection = selectBridgeModel(available.candidates, args.tool, args.model ?? undefined)
1606
+ if (!selection)
1564
1607
  return available.status === "ready"
1565
1608
  ? { ...available, status: "selection_unavailable" }
1566
1609
  : available
1610
+ job.model = selection.model
1611
+ if (args.model == null && preferredModelFamilies.has(args.tool))
1612
+ job.modelSelectedAutomatically = true
1567
1613
  if (!reviewOnly(job.kind) && !paths.length)
1568
1614
  return { status: "write_scope_required" }
1569
1615
  const result = await start(
@@ -1656,13 +1702,13 @@ export function createBridge({
1656
1702
  )
1657
1703
  throw new Error("Keep the context answer under 12,000 characters.")
1658
1704
  const tool = args.tool ?? job.tool
1659
- const model = args.tool || args.model ? (args.model ?? null) : job.model
1660
- const available = await candidates({ ...job, tool }, folder, settings)
1661
- if (
1662
- !available.candidates.some(
1663
- (candidate) => candidate.tool === tool && candidate.model === model
1664
- )
1665
- )
1705
+ const requested = args.model ?? (args.tool ? undefined : job.model)
1706
+ const available = await candidates({ ...job, tool }, folder, settings, {
1707
+ keepToolDefault: requested === null,
1708
+ liveQuota: requested === undefined || (!args.tool && !args.model && job.modelSelectedAutomatically === true),
1709
+ })
1710
+ const selection = selectBridgeModel(available.candidates, tool, requested)
1711
+ if (!selection || (!args.tool && !args.model && job.modelSelectedAutomatically && selection.includedQuota === "exhausted"))
1666
1712
  return { ...available, status: "selection_unavailable" }
1667
1713
  const baseline = await readJson(join(jobDir, "baseline.json"), null)
1668
1714
  if (!baseline)
@@ -1676,7 +1722,15 @@ export function createBridge({
1676
1722
  )
1677
1723
  if (args.answer) job.history.push({ answer: args.answer })
1678
1724
  return start(
1679
- { ...job, tool, model, question: undefined },
1725
+ {
1726
+ ...job,
1727
+ tool,
1728
+ model: selection.model,
1729
+ modelSelectedAutomatically: args.tool || args.model
1730
+ ? requested === undefined && preferredModelFamilies.has(tool)
1731
+ : job.modelSelectedAutomatically,
1732
+ question: undefined,
1733
+ },
1680
1734
  folder,
1681
1735
  projectDir,
1682
1736
  coordination,
@@ -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
@@ -0,0 +1,81 @@
1
+ import { supportsForm } from "./clarification.mjs"
2
+
3
+ export const decisionConflictInstructions =
4
+ "Before the first code write in a connected project, check existing evidence for decisions relevant to the requested behavior. If needed, use one focused get_decision_context lookup for that project. Reuse the result during the task and check again only if the intended behavior materially changes. Only consider explicit user decisions that still apply. If the request can be fulfilled within the decision, proceed within it. If a proposed edit clearly conflicts and proceeding requires a choice, call acent_resolve_decision_conflict before writing the edit or dependent work. Explain the decision, its source and reason, and the specific planned change in the user's language. Honor the selected result. If native input is unavailable, present the same options in chat once and wait for an explicit reply. On interruption, keep the conflicting change paused until the user returns and chooses. A one-time exception covers only that planned change. Ambiguous or unverified conflicts can be surfaced as notes. Current explicit user instructions remain authoritative."
5
+
6
+ const outcomes = ["keep_decision", "proceed_once", "cancel"]
7
+ const fields = {
8
+ decision: { type: "string", maxLength: 600 },
9
+ reason: { type: "string", maxLength: 600 },
10
+ source: { type: "string", maxLength: 400 },
11
+ proposedChange: { type: "string", maxLength: 600 },
12
+ }
13
+
14
+ export const decisionConflictTool = {
15
+ name: "acent_resolve_decision_conflict",
16
+ title: "Resolve an Acent decision conflict",
17
+ description: "Pause before a proposed code change that clearly conflicts with a verified, still-current user decision. Show the decision, reason, source and intended change, then wait for the user's choice. This tool returns a choice to the agent.",
18
+ inputSchema: {
19
+ type: "object",
20
+ properties: {
21
+ ...fields,
22
+ labels: {
23
+ type: "object",
24
+ properties: Object.fromEntries(outcomes.map(outcome => [outcome, { type: "string", maxLength: 80 }])),
25
+ required: outcomes,
26
+ additionalProperties: false,
27
+ description: "Translate Keep existing decision, Proceed with this change only, and Cancel to the user's language.",
28
+ },
29
+ },
30
+ required: [...Object.keys(fields), "labels"],
31
+ additionalProperties: false,
32
+ },
33
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
34
+ }
35
+
36
+ function validText(value, maxLength) {
37
+ return typeof value === "string" && Boolean(value.trim()) && value.length <= maxLength
38
+ }
39
+
40
+ export async function resolveDecisionConflict(input, capabilities, protocol, request) {
41
+ const { decision, reason, source, proposedChange, labels } = input ?? {}
42
+ if (
43
+ Object.entries(fields).some(([key, field]) => !validText(input?.[key], field.maxLength)) ||
44
+ !outcomes.every(key => validText(labels?.[key], 80) && !/[\r\n]/u.test(labels[key])) ||
45
+ new Set(outcomes.map(key => labels[key])).size !== outcomes.length
46
+ ) throw new Error("Provide a verified decision, its reason and source, the proposed change, and three distinct choice labels.")
47
+
48
+ const message = [proposedChange, decision, reason, source].join("\n\n")
49
+ const choices = outcomes.map(outcome => labels[outcome])
50
+ const fallback = {
51
+ status: "needs_user_input",
52
+ question: message,
53
+ choices,
54
+ nextAction: "Show the decision conflict and options in the current chat and ask once whether to proceed. Wait for the user before the conflicting write or dependent work.",
55
+ }
56
+ if (!supportsForm(capabilities, protocol)) return fallback
57
+
58
+ let result
59
+ try {
60
+ result = await request({
61
+ ...(protocol === "2025-06-18" ? {} : { mode: "form" }),
62
+ message,
63
+ requestedSchema: {
64
+ type: "object",
65
+ properties: { choice: { type: "string", enum: choices } },
66
+ required: ["choice"],
67
+ },
68
+ })
69
+ } catch {
70
+ return fallback
71
+ }
72
+ if (result?.action === "cancel" || result?.action === "decline") {
73
+ return { status: "cancel" }
74
+ }
75
+ if (result?.action === "interrupted") return { status: "interrupted" }
76
+ if (result?.action === "accept") {
77
+ const outcome = outcomes.find(key => labels[key] === result.content?.choice)
78
+ if (outcome) return { status: outcome }
79
+ }
80
+ return fallback
81
+ }