@cirtium/acent-connect 1.2.4 → 1.2.5

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.2.5",
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.2.5",
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.2.5",
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
  }
@@ -295,8 +295,8 @@ 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.",
@@ -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
  },
@@ -254,8 +254,10 @@ async function handleLine(line) {
254
254
  if (message.method === "tools/call" && localBridgeTools.includes(bridgeApprovalTool) &&
255
255
  message.params?.name === bridgeApprovalTool.name) {
256
256
  try {
257
+ const { context } = await detectConnectionContext(config, verifiedWorkspace)
258
+ const project = context.scope === "folder" ? { folder: context.folder } : undefined
257
259
  const value = await requestBridgeApproval(message.params.arguments, clientCapabilities, protocol,
258
- (params) => questions.request(params, message.id))
260
+ (params) => questions.request(params, message.id, { waitForUser: true }), project)
259
261
  reply({ ...content(JSON.stringify(value)), structuredContent: value })
260
262
  } catch (error) {
261
263
  reply(content(error.message, true))
@@ -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
 
@@ -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.2.5",
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.2.5",
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.")