@cirtium/acent-connect 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.2.4",
3
+ "version": "1.3.0",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "mcpServers": "./mcp-claude.json",
6
6
  "hooks": "./hooks/claude.json"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.2.4",
3
+ "version": "1.3.0",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "skills": "./skills/",
6
6
  "mcpServers": "./mcp-codex.json",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.2.4",
3
+ "version": "1.3.0",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "author": {
6
6
  "name": "Cirtium"
@@ -1,3 +1,7 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"
3
+ import { homedir } from "node:os"
4
+ import { join } from "node:path"
1
5
  import { bridgeTargets } from "./bridge-runners.mjs"
2
6
  import { supportsForm } from "./clarification.mjs"
3
7
 
@@ -8,7 +12,7 @@ const choices = ["Allow once", "Continue locally"]
8
12
 
9
13
  export const bridgeApprovalTool = {
10
14
  name: "acent_bridge_request_approval",
11
- description: "Ask for one-time permission before a Bridge handoff that needs user approval. Pass only the external agent names, file paths or names of data categories, and a brief purpose. Never include file contents, diffs, secrets, or raw logs. This tool only asks the user and does not launch a delegate or override host policy.",
15
+ description: "Ask for scoped permission before a Bridge handoff that needs user approval. Pass only the external agent names, file paths or names of data categories, and a brief purpose. Never include file contents, diffs, secrets, or raw logs. This tool only asks the user and does not launch a delegate or override host policy.",
12
16
  inputSchema: {
13
17
  type: "object",
14
18
  properties: {
@@ -19,7 +23,7 @@ export const bridgeApprovalTool = {
19
23
  required: ["targets", "scope", "purpose"],
20
24
  additionalProperties: false,
21
25
  },
22
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
26
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
23
27
  }
24
28
 
25
29
  function validList(value, maxItems, validItem) {
@@ -32,7 +36,7 @@ function validLabel(value, limit) {
32
36
  value.length <= limit && !/[\r\n]/u.test(value)
33
37
  }
34
38
 
35
- export async function requestBridgeApproval(input, capabilities, protocol, request) {
39
+ export async function requestBridgeApproval(input, capabilities, protocol, request, project) {
36
40
  const { targets, scope, purpose } = input ?? {}
37
41
  if (
38
42
  !validList(targets, bridgeTargets.length, (target) => bridgeTargets.includes(target)) ||
@@ -43,6 +47,18 @@ export async function requestBridgeApproval(input, capabilities, protocol, reque
43
47
  throw new Error("Provide the Bridge destinations, data scope, and purpose using brief labels only.")
44
48
  }
45
49
 
50
+ // Match only this project, exact destinations, and exact scope and purpose labels.
51
+ const choicesForProject = project ? ["Allow once", "Always allow this scope", "Continue locally"] : choices
52
+ const store = project ? await approvalStore(project, { targets, scope, purpose }) : undefined
53
+ const saved = await store?.readGrant()
54
+ const pending = await store?.readPending()
55
+ const requestId = pending?.requestId ?? randomUUID()
56
+ const proceed = status => ({
57
+ status, targets, scope, purpose, requestId,
58
+ nextAction: "Submit only the approved handoff through the normal Bridge tool. Use requestId when starting the task so retries cannot start duplicates. Honor any host approval requirements.",
59
+ })
60
+ if (saved?.status === "approved_always") return { ...proceed("approved_always"), requestId: randomUUID() }
61
+
46
62
  const question = [
47
63
  "Allow Acent Bridge to share the following with the selected coding agents?",
48
64
  `Destinations: ${targets.join(", ")}`,
@@ -53,45 +69,78 @@ export async function requestBridgeApproval(input, capabilities, protocol, reque
53
69
  const fallback = {
54
70
  status: "needs_user_input",
55
71
  question,
56
- choices,
72
+ choices: choicesForProject.filter(choice => choice !== "Always allow this scope"),
73
+ requestId,
57
74
  nextAction: "Ask the user in their language using the host's approval flow when available, or ask in the current chat if the host permits it. Wait for explicit approval of this exact scope. A chat answer does not override a host denial.",
58
75
  }
59
76
  if (!supportsForm(capabilities, protocol)) return fallback
60
- const unavailable = {
61
- status: "approval_unavailable",
62
- nextAction: "Continue locally. The host did not provide an approval. Do not retry this handoff through a different path.",
63
- }
77
+ await store?.write({ status: "pending", requestId })
78
+ const unavailable = reason => ({
79
+ status: "approval_unavailable", reason, requestId,
80
+ nextAction: "The handoff is still unapproved. On explicit user request, reopen the same approval with the same destinations, scope and purpose. Honor host policy.",
81
+ })
64
82
 
65
83
  let result
66
84
  try {
67
85
  result = await request({
68
- ...(protocol === "2025-11-25" ? { mode: "form" } : {}),
86
+ ...(protocol !== "2025-06-18" ? { mode: "form" } : {}),
69
87
  message: question,
70
88
  requestedSchema: {
71
89
  type: "object",
72
90
  properties: {
73
- decision: { type: "string", title: "Bridge permission", enum: choices },
91
+ decision: { type: "string", title: "Bridge permission", enum: choicesForProject },
74
92
  },
75
93
  required: ["decision"],
76
94
  },
77
95
  })
78
- } catch {
79
- return unavailable
96
+ } catch (error) {
97
+ return unavailable(error.code === "QUESTION_TIMEOUT" ? "response_timeout" : "host_error")
80
98
  }
81
99
 
82
- if (result?.action === "cancel") return { status: "cancelled" }
83
- if (result?.action === "decline") return { status: "declined" }
84
- if (result?.action === "accept") {
85
- if (result.content?.decision === "Continue locally") return { status: "declined" }
86
- if (result.content?.decision === "Allow once") {
87
- return {
88
- status: "approved_once",
89
- targets,
90
- scope,
91
- purpose,
92
- nextAction: "Submit only the approved handoff through the normal Bridge tool and follow all host approval requirements. If the host blocks it, do not retry through a different path.",
100
+ const decision = result?.action === "accept" ? result.content?.decision : result?.action
101
+ if (decision === "interrupted") return unavailable("host_disconnected")
102
+ if (decision === "cancel" || decision === "decline" || decision === "Continue locally") {
103
+ await store?.clearPending(requestId)
104
+ return { status: decision === "cancel" ? "cancelled" : "declined" }
105
+ }
106
+ if (decision === "Allow once") {
107
+ await store?.clearPending(requestId)
108
+ return proceed("approved_once")
109
+ }
110
+ if (decision === "Always allow this scope" && store) {
111
+ await store.write({ status: "approved_always", requestId })
112
+ await store.clearPending(requestId)
113
+ return proceed("approved_always")
114
+ }
115
+ return unavailable("invalid_response")
116
+ }
117
+
118
+ async function approvalStore({ folder, directory = join(homedir(), ".local", "share", "acent", "bridge-approvals") }, { targets, scope, purpose }) {
119
+ const project = await realpath(folder)
120
+ const key = createHash("sha256").update(JSON.stringify([project, [...targets].sort(), [...scope].sort(), purpose])).digest("hex")
121
+ const grant = join(directory, key + ".grant.json")
122
+ const pending = join(directory, key + ".pending.json")
123
+ const read = path => readFile(path, "utf8").then(JSON.parse).catch(error => {
124
+ if (error.code === "ENOENT") return undefined
125
+ throw error
126
+ })
127
+ return {
128
+ readGrant: () => read(grant),
129
+ readPending: () => read(pending),
130
+ async clearPending(requestId) {
131
+ const current = await read(pending)
132
+ if (current?.requestId === requestId) await rm(pending, { force: true })
133
+ },
134
+ async write(value) {
135
+ await mkdir(directory, { recursive: true, mode: 0o700 })
136
+ const path = value.status === "approved_always" ? grant : pending
137
+ const temp = path + "." + randomUUID()
138
+ try {
139
+ await writeFile(temp, JSON.stringify(value), { flag: "wx", mode: 0o600 })
140
+ await rename(temp, path)
141
+ } finally {
142
+ await rm(temp, { force: true })
93
143
  }
94
- }
144
+ },
95
145
  }
96
- return unavailable
97
146
  }
@@ -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."
@@ -295,14 +295,14 @@ export const bridgeTools = [
295
295
  ]
296
296
 
297
297
  export const bridgeInstructions = [
298
- "Automatic Bridge settings select eligible tools; they do not grant permission to share sensitive data. If a handoff requires approval and the user has not already authorized the exact destinations, data scope, and purpose, call acent_bridge_request_approval before submitting any work. Pass only agent names, file paths or data category labels, and a brief purpose, never source contents, diffs, secrets, or logs. Include every destination and all data the delegate will be able to read, including diffs, task context, and read paths when applicable. For a refinement, include reviewers and the repair agent, and ask again when a replacement, continuation, or scope change introduces new data sharing.",
299
- "Use approved_once only for the described handoff. If the form is unsupported and the result is needs_user_input, use the host's approval flow, or ask once in the current chat if permitted, in the user's language. Wait for an explicit answer. On decline, cancellation, or unavailable approval, keep working locally. Submit approved work through the normal Bridge tool and respect host approval decisions. Never use this question or another route to bypass a blocked tool call.",
298
+ "A direct request identifying the destination and what to share authorizes that scope. Automatic Bridge settings only select tools. Before sharing additional data, call acent_bridge_request_approval with destination names, exact paths or category labels, and the purpose. Include diffs, context and read paths in the scope without sending their contents to the approval tool. On an approved result, continue the handoff with the returned request ID where supported. After interruption, reopen the same approval only when the user asks to resume. Follow the host's approval policy.",
299
+ "Use approved_once or approved_always only for the described handoff. If the form is unsupported and the result is needs_user_input, use the host's approval flow, or ask once in the current chat if permitted, in the user's language. Wait for an explicit answer. On decline, cancellation, or unavailable approval, keep working locally. Submit approved work through the normal Bridge tool and respect host approval decisions. Never use this question or another route to bypass a blocked tool call.",
300
300
  "Use Acent Bridge when the user explicitly asks to delegate. For feature work or a bug fix that needs investigation or behavioral verification, identify one focused task that could run alongside your work as soon as the goal and likely scope are clear. Check acent_bridge_settings at that point, even for a single-file change. If the project reports automatic=true and a suitable candidate is available, start the independent task before detailed investigation or implementation, and continue the main work in parallel. Pass automatic=true when listing candidates, starting a task, or starting refinement. Honor any user instruction to keep the work in the current agent.",
301
301
  "Prefer one concrete read-only task when the implementation scope is still forming, such as tracing a caller, identifying a specific regression case, or checking test coverage. Give the delegate a distinct question with a verifiable result. Check settings if a trigger first becomes clear later and reassess when a reviewable patch is ready. Other automatic triggers are independent implementation with verifiable outcomes and disjoint write scopes, substantive changes to payments, authorization, privacy, or durable data, and difficult failures where the cause remains unclear or a fix repeatedly fails.",
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
+ "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
306
  "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
307
  "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
308
  "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 +315,38 @@ export const bridgeInstructions = [
315
315
  "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
316
  ].join(" ")
317
317
 
318
+ const preferredModelFamilies = new Map([
319
+ ["Cursor", "grok"],
320
+ ["Antigravity", "gemini"],
321
+ ])
322
+
323
+ function selectBridgeModel(candidates, tool, requested) {
324
+ const available = candidates.filter((candidate) => candidate.tool === tool)
325
+ if (requested !== undefined)
326
+ return available.find((candidate) => candidate.model === requested)
327
+ if (!preferredModelFamilies.has(tool))
328
+ return available.find((candidate) => candidate.model === null)
329
+ const preferred = available.find((candidate) =>
330
+ candidate.preferredForTool && candidate.includedQuota !== "exhausted"
331
+ )
332
+ if (preferred) return preferred
333
+ if (tool === "Antigravity" && available.some((candidate) =>
334
+ candidate.preferredForTool && candidate.includedQuota === "exhausted"
335
+ ))
336
+ return available.find((candidate) =>
337
+ !candidate.preferredForTool && candidate.includedQuota === "available"
338
+ )
339
+ }
340
+
341
+ function antigravityModelQuota(family, quota) {
342
+ const group = family === "gemini" ? "gemini"
343
+ : family === "claude" || family === "gpt" ? "claude_gpt" : undefined
344
+ if (!group || quota.status !== "reported") return "unknown"
345
+ const windows = quota.windows.filter((window) => window.group === group)
346
+ if (windows.some((window) => window.remainingPercent === 0)) return "exhausted"
347
+ return windows.length ? "available" : "unknown"
348
+ }
349
+
318
350
  const cacheDuration = 120_000
319
351
  const failedDiscoveryCacheDuration = 5_000
320
352
  const leaseMaxAge = 20 * 60_000
@@ -588,7 +620,7 @@ export function createBridge({
588
620
  return result
589
621
  }
590
622
 
591
- async function candidates(args, folder, settings) {
623
+ async function candidates(args, folder, settings, { keepToolDefault = false, liveQuota = true } = {}) {
592
624
  if (args.automatic && !settings.automatic)
593
625
  return { status: "automatic_disabled", candidates: [] }
594
626
  const reference = reviewOnly(args.kind) ? reviewModelReference(args) : undefined
@@ -607,46 +639,52 @@ export function createBridge({
607
639
  (settings.targets.includes(tool) || args.tool === tool)
608
640
  )
609
641
  .map(({ tool }) => tool)
610
- const choices = targets.flatMap((item) =>
611
- item.status !== "ready"
612
- ? []
642
+ const quotas = await Promise.all(targets.map(async (item) => {
643
+ if (item.status !== "ready") return { status: "unknown" }
644
+ if (item.quotaReporting !== "live") return cachedQuota(item)
645
+ if (!liveQuota) return { status: "unknown" }
646
+ // The Antigravity command does not expose an account ID. Use a fresh snapshot
647
+ // for this selection and avoid sharing quota across signed-in accounts.
648
+ const sample = await readQuota(item.tool, folder).catch(() => undefined)
649
+ return sample?.windows?.length
650
+ ? { status: "reported", checkedAt: sample.checkedAt, windows: sample.windows }
651
+ : { status: "unknown" }
652
+ }))
653
+ const choices = targets.flatMap((item, index) => {
654
+ if (item.status !== "ready") return []
655
+ const preferredFamily = preferredModelFamilies.get(item.tool)
656
+ const models = preferredFamily && !keepToolDefault
657
+ ? item.models
613
658
  : [{ 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
- )
659
+ return models
660
+ .filter((model) => !reference || (model.family && model.family !== reference.family))
661
+ .filter((model) =>
662
+ (unavailable.get(modelKey(folder, item.tool, model.id, item.accountKey)) ?? 0) <= Date.now()
663
+ )
664
+ .map((model) => ({
665
+ tool: item.tool,
666
+ model: model.id,
667
+ family: model.family,
668
+ ...(preferredFamily && model.family === preferredFamily ? { preferredForTool: true } : {}),
669
+ ...(item.tool === "Antigravity" ? { includedQuota: antigravityModelQuota(model.family, quotas[index]) } : {}),
670
+ }))
671
+ .sort((a, b) =>
672
+ Number(a.includedQuota === "exhausted") - Number(b.includedQuota === "exhausted") ||
673
+ Number(b.preferredForTool ?? false) - Number(a.preferredForTool ?? false)
674
+ )
675
+ })
631
676
  return {
632
677
  status: choices.length ? "ready" : "no_candidate",
633
678
  candidates: choices,
634
679
  ...(reference ? { referenceModel: reference.model, referenceModelSource: reference.source } : {}),
635
680
  ...(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
- ),
681
+ tools: targets.map((item, index) => ({
682
+ tool: item.tool,
683
+ status: item.status,
684
+ modelCatalog: item.modelCatalog,
685
+ ...(item.modelCatalogFailure ? { modelCatalogFailure: item.modelCatalogFailure } : {}),
686
+ remainingQuota: quotas[index],
687
+ })),
650
688
  }
651
689
  }
652
690
 
@@ -741,9 +779,13 @@ export function createBridge({
741
779
  if (settings?.projectKey !== projectKey) return false
742
780
  let pending = false
743
781
  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
782
+ const available = await candidates({ ...job, tool: job.tool }, folder, settings, {
783
+ keepToolDefault: job.model === null,
784
+ liveQuota: job.modelSelectedAutomatically === true,
785
+ })
786
+ if (!available.candidates.some(({ tool, model, includedQuota }) =>
787
+ tool === job.tool && model === job.model &&
788
+ !(job.modelSelectedAutomatically && includedQuota === "exhausted")
747
789
  )) {
748
790
  const status = available.loginRequiredTools?.includes(job.tool)
749
791
  ? "login_required"
@@ -1387,7 +1429,7 @@ export function createBridge({
1387
1429
  removeStage: (stageDir) =>
1388
1430
  rm(stageDir, { recursive: true, force: true }),
1389
1431
  launch: async (task, currentSettings, snapshot) => {
1390
- const available = await candidates(task, folder, currentSettings)
1432
+ const available = await candidates(task, folder, currentSettings, { liveQuota: false })
1391
1433
  if (available.loginRequiredTools?.includes(task.tool))
1392
1434
  return { status: "login_required" }
1393
1435
  if (
@@ -1553,17 +1595,15 @@ export function createBridge({
1553
1595
  }
1554
1596
  : { id, status: "request_conflict" }
1555
1597
  }
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
- )
1598
+ const available = await candidates(args, folder, settings, { liveQuota: args.model == null })
1599
+ const selection = selectBridgeModel(available.candidates, args.tool, args.model ?? undefined)
1600
+ if (!selection)
1564
1601
  return available.status === "ready"
1565
1602
  ? { ...available, status: "selection_unavailable" }
1566
1603
  : available
1604
+ job.model = selection.model
1605
+ if (args.model == null && preferredModelFamilies.has(args.tool))
1606
+ job.modelSelectedAutomatically = true
1567
1607
  if (!reviewOnly(job.kind) && !paths.length)
1568
1608
  return { status: "write_scope_required" }
1569
1609
  const result = await start(
@@ -1656,13 +1696,13 @@ export function createBridge({
1656
1696
  )
1657
1697
  throw new Error("Keep the context answer under 12,000 characters.")
1658
1698
  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
- )
1699
+ const requested = args.model ?? (args.tool ? undefined : job.model)
1700
+ const available = await candidates({ ...job, tool }, folder, settings, {
1701
+ keepToolDefault: requested === null,
1702
+ liveQuota: requested === undefined || (!args.tool && !args.model && job.modelSelectedAutomatically === true),
1703
+ })
1704
+ const selection = selectBridgeModel(available.candidates, tool, requested)
1705
+ if (!selection || (!args.tool && !args.model && job.modelSelectedAutomatically && selection.includedQuota === "exhausted"))
1666
1706
  return { ...available, status: "selection_unavailable" }
1667
1707
  const baseline = await readJson(join(jobDir, "baseline.json"), null)
1668
1708
  if (!baseline)
@@ -1676,7 +1716,15 @@ export function createBridge({
1676
1716
  )
1677
1717
  if (args.answer) job.history.push({ answer: args.answer })
1678
1718
  return start(
1679
- { ...job, tool, model, question: undefined },
1719
+ {
1720
+ ...job,
1721
+ tool,
1722
+ model: selection.model,
1723
+ modelSelectedAutomatically: args.tool || args.model
1724
+ ? requested === undefined && preferredModelFamilies.has(tool)
1725
+ : job.modelSelectedAutomatically,
1726
+ question: undefined,
1727
+ },
1680
1728
  folder,
1681
1729
  projectDir,
1682
1730
  coordination,
@@ -33,7 +33,7 @@ export function chatClarification(input, reason = "native_input_unavailable") {
33
33
 
34
34
  export function supportsForm(capabilities, protocol) {
35
35
  const elicitation = capabilities?.elicitation
36
- return ["2025-06-18", "2025-11-25"].includes(protocol) &&
36
+ return ["2025-06-18", "2025-11-25", "2026-07-28"].includes(protocol) &&
37
37
  !!elicitation && typeof elicitation === "object" &&
38
38
  (Object.keys(elicitation).length === 0 || !!elicitation.form)
39
39
  }
@@ -43,7 +43,7 @@ export async function clarify(input, capabilities, protocol, request) {
43
43
  if (!supportsForm(capabilities, protocol)) return chatClarification(input)
44
44
  try {
45
45
  const result = await request({
46
- ...(protocol === "2025-11-25" ? { mode: "form" } : {}),
46
+ ...(protocol !== "2025-06-18" ? { mode: "form" } : {}),
47
47
  message: `${input.question}\n${input.choices.map((choice, index) => `${index + 1}. ${choice}`).join("\n")}\nYou can also describe another task in your answer.`,
48
48
  requestedSchema: {
49
49
  type: "object",
@@ -66,14 +66,14 @@ export function createQuestionChannel(write, timeoutMs = 120000) {
66
66
  let sequence = 0
67
67
  const pending = new Map()
68
68
  return {
69
- request(params, relatedRequestId) {
69
+ request(params, relatedRequestId, { waitForUser = false } = {}) {
70
70
  const id = `acent-question-${++sequence}`
71
71
  return new Promise((resolve, reject) => {
72
- const timer = setTimeout(() => {
72
+ const timer = waitForUser ? undefined : setTimeout(() => {
73
73
  pending.delete(id)
74
- reject(new Error("Question timed out"))
74
+ reject(Object.assign(new Error("Question timed out"), { code: "QUESTION_TIMEOUT" }))
75
75
  }, timeoutMs)
76
- pending.set(id, { resolve, reject, timer, relatedRequestId })
76
+ pending.set(id, { resolve, reject, timer, relatedRequestId, waitForUser })
77
77
  write({ jsonrpc: "2.0", id, method: "elicitation/create", params })
78
78
  })
79
79
  },
@@ -82,7 +82,7 @@ export function createQuestionChannel(write, timeoutMs = 120000) {
82
82
  const entry = pending.get(message.id)
83
83
  pending.delete(message.id)
84
84
  clearTimeout(entry.timer)
85
- if (message.error) entry.reject(new Error("Host declined the request"))
85
+ if (message.error) entry.reject(new Error("Host could not complete the question"))
86
86
  else entry.resolve(message.result)
87
87
  return true
88
88
  },
@@ -91,13 +91,13 @@ export function createQuestionChannel(write, timeoutMs = 120000) {
91
91
  if (entry.relatedRequestId !== requestId) continue
92
92
  clearTimeout(entry.timer)
93
93
  pending.delete(id)
94
- entry.resolve({ action: "cancel" })
94
+ entry.resolve({ action: entry.waitForUser ? "interrupted" : "cancel" })
95
95
  }
96
96
  },
97
97
  close() {
98
98
  for (const entry of pending.values()) {
99
99
  clearTimeout(entry.timer)
100
- entry.resolve({ action: "cancel" })
100
+ entry.resolve({ action: entry.waitForUser ? "interrupted" : "cancel" })
101
101
  }
102
102
  pending.clear()
103
103
  },
@@ -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
+ }
@@ -6,6 +6,7 @@ import { connectionGuidance } from "./host-guidance.mjs"
6
6
  import { clarificationInstructions, clarificationTool, clarify, createQuestionChannel } from "./clarification.mjs"
7
7
  import { connectionContext, createRootsChannel, projectFolder } from "./connection-context.mjs"
8
8
  import { memoryInstructions } from "./memory-instructions.mjs"
9
+ import { decisionConflictInstructions, decisionConflictTool, resolveDecisionConflict } from "./decision-conflict.mjs"
9
10
  import { attachmentTool, saveAttachments } from "./capture-attachments.mjs"
10
11
  import { bridgeInstructions, bridgeTools, createBridge } from "./bridge.mjs"
11
12
  import { bridgeApprovalTool, requestBridgeApproval } from "./bridge-approval.mjs"
@@ -225,6 +226,7 @@ async function handleLine(line) {
225
226
  serverInfo: { name: "acent", version: installation?.version ?? "0.2.0" },
226
227
  instructions:
227
228
  "Use acent_connect to connect Acent when setup is needed; its default scope is auto. If it returns needs_user_input, ask its question once in the user’s language and wait for their answer. Show its authorization link to the user. After approval, refresh tools/list and continue the original request. Never approve on the user's behalf. " + memoryInstructions + "\n\n" + clarificationInstructions +
229
+ "\n\n" + decisionConflictInstructions +
228
230
  (localBridgeTools.length ? "\n\n" + bridgeInstructions : "") +
229
231
  (pluginUpdates ? "\n\n" + pluginUpdateInstructions : ""),
230
232
  })
@@ -254,8 +256,10 @@ async function handleLine(line) {
254
256
  if (message.method === "tools/call" && localBridgeTools.includes(bridgeApprovalTool) &&
255
257
  message.params?.name === bridgeApprovalTool.name) {
256
258
  try {
259
+ const { context } = await detectConnectionContext(config, verifiedWorkspace)
260
+ const project = context.scope === "folder" ? { folder: context.folder } : undefined
257
261
  const value = await requestBridgeApproval(message.params.arguments, clientCapabilities, protocol,
258
- (params) => questions.request(params, message.id))
262
+ (params) => questions.request(params, message.id, { waitForUser: true }), project)
259
263
  reply({ ...content(JSON.stringify(value)), structuredContent: value })
260
264
  } catch (error) {
261
265
  reply(content(error.message, true))
@@ -398,6 +402,16 @@ async function handleLine(line) {
398
402
  }
399
403
  throw error
400
404
  }
405
+ if (message.method === "tools/call" && message.params?.name === decisionConflictTool.name) {
406
+ try {
407
+ const value = await resolveDecisionConflict(message.params.arguments, clientCapabilities, protocol,
408
+ (params) => questions.request(params, message.id, { waitForUser: true }))
409
+ reply({ ...content(JSON.stringify(value)), structuredContent: value })
410
+ } catch (error) {
411
+ reply(content(error.message, true))
412
+ }
413
+ return
414
+ }
401
415
  if (message.method === "tools/call" && message.params?.name === clarificationTool.name) {
402
416
  try {
403
417
  const value = await clarify(message.params.arguments, clientCapabilities, protocol,
@@ -437,7 +451,7 @@ async function handleLine(line) {
437
451
  const localTools = privateGrant(grant.client_id)
438
452
  ? (grant.captureKey && grant.scope?.split(" ").includes("original:read") ? [encryptedReadTool] : [])
439
453
  : grant.scope?.split(" ").includes("conversation:write") ? [attachmentTool] : []
440
- result.result.tools = [...result.result.tools.filter((tool) => tool.name !== clarificationTool.name), setupTool, clarificationTool, ...localTools, ...localBridgeTools, ...workspaceTools]
454
+ result.result.tools = [...result.result.tools.filter((tool) => tool.name !== clarificationTool.name), setupTool, clarificationTool, decisionConflictTool, ...localTools, ...localBridgeTools, ...workspaceTools]
441
455
  }
442
456
  if (message.method === "tools/call" && result.result)
443
457
  result.result = await withPluginUpdate(result.result)
@@ -1,6 +1,7 @@
1
1
  // Shared by the HTTP server and the packaged stdio proxy. The proxy handles
2
2
  // initialize locally, so upstream server instructions do not reach its host.
3
3
  export const memoryInstructions = [
4
+ "When get_recent_work, get_handoff or search_evidence returns attachments, match them to the relevant conversation by sourceId even if the user did not mention files. When reporting past work, include relevant filenames and their returned download links. When continuing work, read attachments that the prior request or decision relied on, using readWith when provided. Download links may require the user's Acent web session. For a relevant source in attachmentSourcesUnavailable, try search_attachments if the file matters. Describe file contents only after a successful read or inspection.",
4
5
  "Acent has five named skills: Acent Recall finds past context; Acent Trace explains saved code edits; Acent Decisions retrieves choices and reasons; Acent Resume continues saved work; Acent Connect manages connection setup. Recognize these names in user requests and use the relevant exposed tools. These are workflows within the Acent plugin, not separate connections. Automatic capture remains controlled by saving consent.",
5
6
  "Use connected Acent as the first source for missing project history when it could change the answer or next action, including within the same conversation or after context compaction. Search before asking the user to restate that history, even without an explicit mention of Acent. For example, if the user says 'do it like last time' or '저번처럼 해줘' and the earlier approach is unclear, search using the task, feature, or error they mention. Also retrieve for resumed work, unexplained past decisions or constraints, conflicting records, and recurring failures where earlier attempts could affect the next step. Skip retrieval when the current context and files already answer the question. Reuse evidence already read and search again when the task changes, a reference is stale, or later corrections may matter.",
6
7
  "When looking for conversations saved by this plugin connection, use read_saved_sessions when available. For an earlier device-encrypted connection use read_encrypted_sessions when available. Follow the returned pagination to continue a search.",
@@ -16,7 +16,7 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
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
18
  - 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
- - Use a reported quota snapshot as a tiebreaker among suitable candidates. When a quota is low, favor a lower-usage option if it still fits the task and the user has not pinned a model. Quota windows are provider-specific, and tokens from the last run cannot establish remaining quota.
19
+ - 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
20
  - 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.
21
21
  - Start with `acent_bridge_start`. Use `paths` for the files to review or the files an implementation may edit. Use `readPaths` for additional context the delegate may read. Specify how to verify completion in `acceptance`. The folder shares four baseline slots across implementation, review, and diagnosis and expands up to eight as needed. Ready tasks submitted after all eight slots fill are queued and start as slots open. Track their existing IDs. Pass `dependsOn` when a task needs the result of earlier work. Review and diagnosis run in read-only mode.
22
22
  - 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.
@@ -28,8 +28,8 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
28
28
 
29
29
  ## Approval before sharing data
30
30
 
31
- - Automatic delegation selects eligible tools. 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 only after explicit approval of that handoff. 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.
31
+ - 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.
33
33
 
34
34
  ## Review when only the coordinator can access a source
35
35
 
@@ -18,6 +18,8 @@ Read relevant returned references to recover the last user request, completed or
18
18
 
19
19
  When a past command, test, build, or migration result matters, check the returned `activities` for the selected conversation and relevant turn. Use `read_activity` with its `source_id` as `sourceId` and its `id`. Read only the sections you need, such as `output` to verify the result. If you need more records, use `search_activities` with the selected `sourceId`. An unknown status or missing output leaves the outcome unconfirmed.
20
20
 
21
+ Check returned `attachments` for the selected `sourceId`. When reporting past work, include relevant file names and download links. When resuming, read files the original task relied on, using the attachment's `readWith` reference for extracted text when available. If that source appears in `attachmentSourcesUnavailable`, retry with `search_attachments` when the file matters. Report what was actually accessible.
22
+
21
23
  Conversation candidates are not verified task lists. Distinguish message time, collection time and archive storage time. Do not assume the newest conversation is unfinished, or that a reported successful change still exists. Compare the selected evidence with current files and repository state before proceeding.
22
24
 
23
25
  If several tasks fit or the next step is materially ambiguous after a focused search, ask one question with evidence-based choices in the current chat. Use `request_clarification` when available, otherwise the host's question mechanism. Wait for the answer before dependent work; never answer on the user's behalf or retry a cancelled question.
@@ -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.2.4",
5
+ "version": "1.3.0",
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.2.4",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Install and connect the shared Acent coding-tool plugin",
6
6
  "repository": {
package/scripts/acent.mjs CHANGED
@@ -3,6 +3,7 @@ import { installationGuidance } from "../acent/scripts/host-guidance.mjs"
3
3
  import { pathToFileURL } from "node:url"
4
4
  import { realpathSync } from "node:fs"
5
5
  import { stat } from "node:fs/promises"
6
+ import { offerBridgePermission } from "./bridge-permissions.mjs"
6
7
  import { chooseTool } from "./choose-tool.mjs"
7
8
  import { main as adapter, options } from "../acent/scripts/acent-connect.mjs"
8
9
  import {
@@ -25,6 +26,13 @@ async function applyPlugin(tool, command, settings, folder, execute, dependencie
25
26
  const action = command === "update" ? "files and settings updated" : "files and settings prepared"
26
27
  console.error(`\nAcent ${installed.version} ${action} for ${tool}.\n`)
27
28
  console.error(installationGuidance(tool) + "\n")
29
+ if (command === "install" || command === "update") {
30
+ try {
31
+ await (dependencies.offerPermission || offerBridgePermission)(tool)
32
+ } catch (error) {
33
+ console.error(`Bridge permission for ${tool} was not updated: ${error.message}`)
34
+ }
35
+ }
28
36
  return true
29
37
  }
30
38
 
@@ -0,0 +1,68 @@
1
+ import { homedir } from "node:os"
2
+ import { join } from "node:path"
3
+ import { createInterface } from "node:readline/promises"
4
+ import { editSettings } from "./local-registration.mjs"
5
+
6
+ const bridgeTool = "acent_bridge_start"
7
+
8
+ function addRule(object, key, rule) {
9
+ const list = object[key] ?? []
10
+ if (!Array.isArray(list)) throw new Error(`Invalid ${key} permission list`)
11
+ if (list.includes(rule)) return false
12
+ object[key] = [...list, rule]
13
+ return true
14
+ }
15
+
16
+ export async function offerBridgePermission(tool, {
17
+ home = homedir(),
18
+ input = process.stdin,
19
+ output = process.stderr,
20
+ ask,
21
+ } = {}) {
22
+ if (!ask && !input.isTTY) return
23
+ const codex = tool === "Codex"
24
+ const claude = tool === "Claude Code"
25
+ const cursor = tool === "Cursor"
26
+ const path = codex
27
+ ? join(home === homedir() && process.env.CODEX_HOME || join(home, ".codex"), "config.toml")
28
+ : claude
29
+ ? join(home === homedir() && process.env.CLAUDE_CONFIG_DIR || join(home, ".claude"), "settings.json")
30
+ : cursor
31
+ ? join(home, ".cursor", "permissions.json")
32
+ : join(home, ".gemini", "antigravity-cli", "settings.json")
33
+ const change = data => {
34
+ if (codex) {
35
+ const plugin = (data.plugins ??= {})["acent@acent"] ??= {}
36
+ const server = (plugin.mcp_servers ??= {}).acent ??= {}
37
+ const entry = (server.tools ??= {})[bridgeTool] ??= {}
38
+ // Honor an explicit existing host policy.
39
+ if (entry.approval_mode !== undefined) return false
40
+ entry.approval_mode = "approve"
41
+ return true
42
+ }
43
+ if (cursor) return addRule(data, "mcpAllowlist", `acent:${bridgeTool}`)
44
+ return addRule(data.permissions ??= {}, "allow", claude
45
+ ? `mcp__plugin_acent_acent__${bridgeTool}`
46
+ : `mcp(acent/${bridgeTool})`)
47
+ }
48
+ const select = ask ?? (async question => {
49
+ const prompt = createInterface({ input, output })
50
+ try {
51
+ return /^y(?:es)?$/iu.test((await prompt.question(question)).trim())
52
+ } finally {
53
+ prompt.close()
54
+ }
55
+ })
56
+ const decisionPath = join(home, ".local", "share", "acent", "bridge-host-permissions.json")
57
+ await editSettings(decisionPath, false, async decisions => {
58
+ if (decisions[tool] !== undefined) return false
59
+ await editSettings(path, codex, async data => {
60
+ if (!change(data)) return false
61
+ const host = tool === "Antigravity" ? "Antigravity CLI" : tool
62
+ const allowed = await select(`Always allow Acent Bridge to start in ${host} across projects? [y/N] `)
63
+ decisions[tool] = allowed ? "allowed" : "skipped"
64
+ return allowed
65
+ })
66
+ return decisions[tool] !== undefined
67
+ })
68
+ }
@@ -10,14 +10,7 @@ export async function registerLocal(tool, root, home) {
10
10
  const path = tool === "Codex"
11
11
  ? join(home === homedir() && process.env.CODEX_HOME || join(home, ".codex"), "config.toml")
12
12
  : join(home === homedir() && process.env.CLAUDE_CONFIG_DIR || join(home, ".claude"), "settings.json")
13
- await mkdir(dirname(path), { recursive: true })
14
- const lock = `${path}.acent-lock`
15
- await mkdir(lock).catch(() => { throw new Error(`Settings are busy: ${path}. Retry after the other installer finishes.`) })
16
- const temp = join(lock, "settings.json")
17
- try {
18
- const raw = await readFile(path, "utf8").catch(error => { if (error.code === "ENOENT") return null; throw error })
19
- const data = raw === null ? {} : (tool === "Codex" ? parse(raw) : JSON.parse(raw))
20
- if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(`Invalid settings: ${path}`)
13
+ await editSettings(path, tool === "Codex", data => {
21
14
  if (tool === "Codex") {
22
15
  for (const key of ["marketplaces", "plugins"]) {
23
16
  if (data[key] !== undefined && (!data[key] || typeof data[key] !== "object" || Array.isArray(data[key]))) throw new Error(`Invalid ${key}`)
@@ -38,7 +31,20 @@ export async function registerLocal(tool, root, home) {
38
31
  // Preserve an explicit user decision to disable the plugin.
39
32
  data.enabledPlugins["acent@acent"] ??= true
40
33
  }
41
- await writeFile(temp, (tool === "Codex" ? stringify(data) : JSON.stringify(data, null, 2) + "\n"), { mode: 0o600 })
34
+ })
35
+ }
36
+
37
+ export async function editSettings(path, toml, edit) {
38
+ await mkdir(dirname(path), { recursive: true })
39
+ const lock = `${path}.acent-lock`
40
+ await mkdir(lock).catch(() => { throw new Error(`Settings are busy: ${path}. Retry after the other installer finishes.`) })
41
+ const temp = join(lock, "settings.json")
42
+ try {
43
+ const raw = await readFile(path, "utf8").catch(error => { if (error.code === "ENOENT") return null; throw error })
44
+ const data = raw === null ? {} : (toml ? parse(raw) : JSON.parse(raw))
45
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(`Invalid settings: ${path}`)
46
+ if (await edit(data) === false) return
47
+ await writeFile(temp, (toml ? stringify(data) : JSON.stringify(data, null, 2) + "\n"), { mode: 0o600 })
42
48
  // Detect concurrent edits by the app before replacing its settings.
43
49
  const current = await readFile(path, "utf8").catch(error => { if (error.code === "ENOENT") return null; throw error })
44
50
  if (current !== raw) throw new Error("Settings changed during installation; retry. Existing settings preserved.")