@cirtium/acent-connect 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process"
2
2
  import { createHash } from "node:crypto"
3
3
  import { stat } from "node:fs/promises"
4
4
  import { homedir } from "node:os"
5
- import { join } from "node:path"
5
+ import { delimiter, isAbsolute, join } from "node:path"
6
6
  import { createInterface } from "node:readline"
7
7
  import { hostExecutableCandidates } from "./host-executables.mjs"
8
8
 
@@ -98,7 +98,12 @@ export function runProcess(
98
98
  stderr = (stderr + chunk).slice(-16384)
99
99
  })
100
100
  child.on("error", (error) => {
101
- failure = error.code === "ENOENT" ? "not_installed" : "failed"
101
+ failure =
102
+ error.code === "ENOENT"
103
+ ? "not_installed"
104
+ : ["EACCES", "EPERM"].includes(error.code)
105
+ ? "permission_denied"
106
+ : "failed"
102
107
  })
103
108
  if (onSpawn) {
104
109
  child.once("spawn", () => {
@@ -128,6 +133,11 @@ const commands = {
128
133
  Antigravity: "agy",
129
134
  }
130
135
 
136
+ export function bridgeExecutableCandidates(tool) {
137
+ if (!bridgeTargets.includes(tool)) throw new Error("Unknown Bridge tool.")
138
+ return hostExecutableCandidates(tool, commands[tool])
139
+ }
140
+
131
141
  export function bridgeGitEnvironment() {
132
142
  const env = { ...process.env }
133
143
  for (const key of Object.keys(env)) {
@@ -142,16 +152,41 @@ export function bridgeGitEnvironment() {
142
152
  }
143
153
 
144
154
  async function runHost(tool, args, options, run) {
145
- const command = commands[tool]
146
- let result = await run(command, args, options)
147
- if (result.failure !== "not_installed") return result
148
- for (const candidate of (await hostExecutableCandidates(tool, command)).slice(
149
- 1
150
- )) {
151
- result = await run(candidate, args, options)
152
- if (result.failure !== "not_installed") break
155
+ const candidates = await bridgeExecutableCandidates(tool)
156
+ const path = (options.env?.PATH ?? process.env.PATH ?? "")
157
+ .split(delimiter)
158
+ .filter(isAbsolute)
159
+ if (process.platform === "darwin")
160
+ path.push("/opt/homebrew/bin", "/usr/local/bin", "/opt/local/bin")
161
+ const executables =
162
+ run === runProcess && process.platform !== "win32"
163
+ ? candidates.flatMap((candidate) =>
164
+ isAbsolute(candidate)
165
+ ? [candidate]
166
+ : path.map((base) => join(base, candidate))
167
+ )
168
+ : candidates
169
+ const hostOptions =
170
+ run === runProcess && process.platform === "darwin"
171
+ ? {
172
+ ...options,
173
+ env: {
174
+ ...(options.env ?? process.env),
175
+ PATH: [...new Set(path)].join(delimiter),
176
+ },
177
+ }
178
+ : options
179
+ let failure = "not_installed"
180
+ for (const executable of new Set(executables)) {
181
+ const result = await run(executable, args, hostOptions)
182
+ if (result.failure === "not_installed") continue
183
+ if (result.failure === "permission_denied") {
184
+ failure = result.failure
185
+ continue
186
+ }
187
+ return { ...result, executable, env: hostOptions.env }
153
188
  }
154
- return result
189
+ return { failure }
155
190
  }
156
191
 
157
192
  async function claudeModelList(cwd, run) {
@@ -213,7 +248,7 @@ export async function bridgeAccountRevision(tool) {
213
248
  }
214
249
  }
215
250
 
216
- function modelRows(output) {
251
+ function modelRows(output, tabular = false) {
217
252
  return [
218
253
  ...new Set(
219
254
  output
@@ -223,7 +258,13 @@ function modelRows(output) {
223
258
  .replace(/\x1b\[[0-9;]*m/g, "")
224
259
  .trim()
225
260
  .replace(/^[›*•]\s*/, "")
226
- return clean.match(/^[\w][\w.:/-]*/)?.[0]
261
+ if (!tabular) return clean.match(/^[\w][\w.:/-]*/)?.[0]
262
+
263
+ // Antigravity prints a model ID and display name separated by a tab.
264
+ // Also accept bare model IDs from known families.
265
+ const row = clean.match(/^([\w][\w.:/-]*)\t+\S/)
266
+ if (row) return row[1]
267
+ if (/^[\w][\w.:/-]*$/.test(clean) && modelFamily(clean)) return clean
227
268
  })
228
269
  .filter((id) => id && /[-.:/]/.test(id) && !id.endsWith(":"))
229
270
  ),
@@ -355,7 +396,15 @@ export async function readBridgeQuota(tool, cwd, run = runProcess) {
355
396
  return { accountKey, checkedAt: Date.now(), windows }
356
397
  }
357
398
 
358
- export async function discoverBridgeTarget(tool, cwd, run = runProcess) {
399
+ const authenticationRequired =
400
+ /^\s*(?:(?:error|warning):\s*)?(?:you (?:are|are currently) )?(?:not (?:logged in|signed in|authenticated)|unauthenticated|authentication required|(?:login|sign[ -]in) required|please (?:log|sign) in)\b/im
401
+
402
+ export async function discoverBridgeTarget(
403
+ tool,
404
+ cwd,
405
+ run = runProcess,
406
+ onExecutable
407
+ ) {
359
408
  const statusArgs = {
360
409
  Codex: ["login", "status"],
361
410
  "Claude Code": ["auth", "status"],
@@ -364,26 +413,34 @@ export async function discoverBridgeTarget(tool, cwd, run = runProcess) {
364
413
  }[tool]
365
414
  const result = await runHost(tool, statusArgs, { cwd }, run)
366
415
  if (result.failure) return { tool, status: result.failure, models: [] }
367
- const diagnostics = result.stdout + "\n" + result.stderr
368
- if (
369
- /not (?:logged in|authenticated)|authentication required|login required/i.test(
370
- diagnostics
371
- )
372
- ) {
373
- return { tool, status: "login_required", models: [] }
374
- }
416
+ onExecutable?.(result.executable)
417
+ const runSelected = (_command, args, options) =>
418
+ run(result.executable, args, {
419
+ ...options,
420
+ ...(result.env ? { env: result.env } : {}),
421
+ })
422
+ const diagnostics = `${result.stdout}\n${result.stderr}`.replace(
423
+ /\x1b\[[0-9;]*m/g,
424
+ ""
425
+ )
375
426
  if (tool === "Claude Code") {
376
427
  let account
377
428
  try {
378
429
  account = JSON.parse(result.stdout)
379
430
  } catch {
380
- return { tool, status: "unavailable", models: [] }
431
+ return {
432
+ tool,
433
+ status: authenticationRequired.test(diagnostics)
434
+ ? "login_required"
435
+ : "unavailable",
436
+ models: [],
437
+ }
381
438
  }
382
- if (account.loggedIn === false)
439
+ if (account?.loggedIn === false)
383
440
  return { tool, status: "login_required", models: [] }
384
- if (!account.loggedIn || result.code !== 0)
441
+ if (account?.loggedIn !== true || result.code !== 0)
385
442
  return { tool, status: "unavailable", models: [] }
386
- const models = await claudeModelList(cwd, run)
443
+ const models = await claudeModelList(cwd, runSelected)
387
444
  return {
388
445
  tool,
389
446
  status: "ready",
@@ -395,24 +452,48 @@ export async function discoverBridgeTarget(tool, cwd, run = runProcess) {
395
452
  : undefined,
396
453
  }
397
454
  }
455
+ if (authenticationRequired.test(diagnostics)) {
456
+ return { tool, status: "login_required", models: [] }
457
+ }
398
458
  if (result.code !== 0) return { tool, status: "unavailable", models: [] }
399
- const codex = tool === "Codex" ? await codexInfo(run, cwd) : undefined
459
+ const codex = tool === "Codex" ? await codexInfo(runSelected, cwd) : undefined
460
+ const cursorModels =
461
+ tool === "Cursor" ? await runSelected(null, ["models"], { cwd }) : undefined
462
+ let modelCatalogFailure = cursorModels?.failure
463
+ if (cursorModels && !modelCatalogFailure) {
464
+ const diagnostics =
465
+ `${cursorModels.stdout}\n${cursorModels.stderr}`.replace(
466
+ /\x1b\[[0-9;]*m/g,
467
+ ""
468
+ )
469
+ if (authenticationRequired.test(diagnostics))
470
+ modelCatalogFailure = "login_required"
471
+ else if (cursorModels.code !== 0) modelCatalogFailure = "failed"
472
+ }
400
473
  const ids = codex
401
474
  ? codex.models
402
475
  : tool === "Antigravity"
403
- ? modelRows(result.stdout)
404
- : modelRows((await runHost(tool, ["models"], { cwd }, run)).stdout)
476
+ ? modelRows(result.stdout, true)
477
+ : !modelCatalogFailure
478
+ ? modelRows(cursorModels?.stdout ?? "")
479
+ : []
405
480
  return {
406
481
  tool,
407
- status: tool === "Antigravity" && !ids.length ? "unverified" : "ready",
482
+ status:
483
+ modelCatalogFailure === "login_required"
484
+ ? "login_required"
485
+ : tool === "Antigravity" && !ids.length
486
+ ? "unverified"
487
+ : "ready",
408
488
  models: ids.map((id) => ({ id, family: modelFamily(id) ?? null })),
409
489
  modelCatalog: ids.length ? "available" : "unverified",
490
+ ...(modelCatalogFailure ? { modelCatalogFailure } : {}),
410
491
  accountKey: codex?.accountKey,
411
492
  }
412
493
  }
413
494
 
414
495
  export async function executeBridgeTarget(
415
- { tool, model, readOnly, cwd, prompt, signal, onSpawn },
496
+ { tool, model, readOnly, managedWorkspace, cwd, prompt, signal, onSpawn },
416
497
  run = runProcess
417
498
  ) {
418
499
  const args = {
@@ -437,6 +518,7 @@ export async function executeBridgeTarget(
437
518
  Cursor: [
438
519
  "--output-format",
439
520
  "json",
521
+ ...(managedWorkspace ? ["--trust"] : []),
440
522
  ...(readOnly ? ["--mode=ask"] : []),
441
523
  ...(model ? ["--model", model] : []),
442
524
  "-p",
@@ -538,6 +620,8 @@ export async function executeBridgeTarget(
538
620
  payload.response ??
539
621
  (typeof payload.result === "string" ? payload.result : undefined)
540
622
  usage = payload.usage
623
+ const reportedModel = payload.model ?? event.model
624
+ if (typeof reportedModel === "string") actualModel = reportedModel
541
625
  if (
542
626
  event.is_error ||
543
627
  payload.is_error ||
@@ -553,7 +637,13 @@ export async function executeBridgeTarget(
553
637
  // A non-JSON response cannot verify that a delegated turn completed.
554
638
  }
555
639
  }
556
- const diagnostics = String(error ?? "") + "\n" + result.stderr
640
+ const diagnostics = [
641
+ error && (typeof error === "string" ? error : JSON.stringify(error)),
642
+ result.stderr,
643
+ result.code !== 0 ? result.stdout : "",
644
+ ]
645
+ .filter(Boolean)
646
+ .join("\n")
557
647
  let failure = result.failure
558
648
  if (!failure && (result.code !== 0 || error || typeof summary !== "string")) {
559
649
  if (
@@ -575,11 +665,13 @@ export async function executeBridgeTarget(
575
665
  )
576
666
  failure = "login_required"
577
667
  else if (
578
- /model.*(?:unavailable|not found|not supported|access denied)|unknown model/i.test(
668
+ /(?:model|variant).*(?:unavailable|not available|not enabled|not found|not supported|access denied)|unknown model|does not have access to (?:this |the )?model/i.test(
579
669
  diagnostics
580
670
  )
581
671
  )
582
672
  failure = "model_unavailable"
673
+ else if (/workspace trust required|untrusted workspace/i.test(diagnostics))
674
+ failure = "workspace_untrusted"
583
675
  else failure = "failed"
584
676
  }
585
677
  const tokens = Object.fromEntries(
@@ -595,9 +687,19 @@ export async function executeBridgeTarget(
595
687
  ],
596
688
  ].filter(([, value]) => Number.isSafeInteger(value) && value >= 0)
597
689
  )
690
+ let failureCode
691
+ if (failure === "failed" && Number.isInteger(result.code)) {
692
+ if (result.code !== 0) failureCode = "cli_exit_nonzero"
693
+ else if (!error && typeof summary !== "string")
694
+ failureCode = "invalid_cli_output"
695
+ }
598
696
  return {
599
697
  failure,
600
- summary: typeof summary === "string" ? summary.slice(0, 16000) : undefined,
698
+ ...(failureCode ? { failureCode } : {}),
699
+ summary:
700
+ !error && typeof summary === "string"
701
+ ? summary.slice(0, 16000)
702
+ : undefined,
601
703
  actualModel,
602
704
  rateLimitResetAt,
603
705
  ...(Object.keys(tokens).length ? { tokens } : {}),
@@ -36,6 +36,25 @@ export function workspacePath(path) {
36
36
  )
37
37
  }
38
38
 
39
+ export function delegateWorkspacePath(path) {
40
+ return (
41
+ workspacePath(path) &&
42
+ !path.split("/").some((part) =>
43
+ /^(?:\.(?:agents?|antigravity|claude|claude\.json|codex|cursor|cursorrules|gemini|vscode)|\.?mcp\.json)$/i.test(
44
+ part
45
+ )
46
+ )
47
+ )
48
+ }
49
+
50
+ export const withinPaths = (path, scopes) =>
51
+ scopes.some((scope) => path === scope || path.startsWith(scope + "/"))
52
+
53
+ export function delegateScopes({ paths = [], readPaths = [], dependencyPaths = [] }) {
54
+ const scopes = [...paths, ...readPaths]
55
+ return scopes.length ? scopes : dependencyPaths
56
+ }
57
+
39
58
  export function pathsOverlap(left, right) {
40
59
  if (process.platform === "darwin" || process.platform === "win32") {
41
60
  left = left.normalize("NFC").toLowerCase()
@@ -177,9 +196,7 @@ export async function bridgeReviewDiff(folder, scopes, from, to) {
177
196
  .then((value) => value.trim())
178
197
  .catch(() => null))
179
198
  const relevant = (path) =>
180
- workspacePath(path) &&
181
- (!scopes.length ||
182
- scopes.some((scope) => path === scope || path.startsWith(scope + "/")))
199
+ delegateWorkspacePath(path) && (!scopes.length || withinPaths(path, scopes))
183
200
  const untracked = !from
184
201
  ? (head
185
202
  ? (
@@ -244,13 +261,26 @@ export async function bridgeReviewDiff(folder, scopes, from, to) {
244
261
  .join("\n")
245
262
  }
246
263
 
247
- export async function projectSnapshot(folder, work, saveBaseline) {
264
+ export async function projectSnapshot(
265
+ folder,
266
+ work,
267
+ saveBaseline,
268
+ { scopes, trackSource = false } = {}
269
+ ) {
248
270
  const paths = await projectFiles(folder)
249
271
  const baseline = Object.create(null)
272
+ const sourceFiles = trackSource ? Object.create(null) : undefined
250
273
  let bytes = 0
251
274
  let fileCount = 0
252
275
  await mkdir(work, { recursive: true, mode: 0o700 })
253
276
  for (const path of paths) {
277
+ if (scopes && (!delegateWorkspacePath(path) || !withinPaths(path, scopes))) {
278
+ if (sourceFiles) {
279
+ const version = await fileVersion(folder, path)
280
+ if (version && version !== "unsupported") sourceFiles[path] = version
281
+ }
282
+ continue
283
+ }
254
284
  const source = join(folder, path)
255
285
  const canonical = await realpath(source).catch((error) => {
256
286
  if (error.code === "ENOENT" || error.code === "ENOTDIR") return null
@@ -271,9 +301,38 @@ export async function projectSnapshot(folder, work, saveBaseline) {
271
301
  await mkdir(dirname(destination), { recursive: true })
272
302
  await copyFile(source, destination, constants.COPYFILE_FICLONE)
273
303
  baseline[path] = await fileVersion(work, path)
304
+ if (sourceFiles) sourceFiles[path] = baseline[path]
274
305
  }
275
306
  await initBridgeGit(work)
276
- await saveBaseline(await checkpointBridgeWorkspace(work, { files: baseline }))
307
+ await saveBaseline({
308
+ ...(await checkpointBridgeWorkspace(work, { files: baseline })),
309
+ ...(scopes ? { scoped: true, scopes } : {}),
310
+ ...(sourceFiles ? { sourceFiles } : {}),
311
+ })
312
+ }
313
+
314
+ export async function checkDelegateWorkspace(work, scopes) {
315
+ const directory = await lstat(work).catch((error) => {
316
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null
317
+ throw error
318
+ })
319
+ if (!directory?.isDirectory()) return false
320
+ for (const path of await projectFiles(work, true)) {
321
+ const file = join(work, path)
322
+ const info = await lstat(file).catch((error) => {
323
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null
324
+ throw error
325
+ })
326
+ if (
327
+ info &&
328
+ (!info.isFile() ||
329
+ !delegateWorkspacePath(path) ||
330
+ (scopes && !withinPaths(path, scopes)) ||
331
+ (await realpath(file)) !== file)
332
+ )
333
+ return false
334
+ }
335
+ return true
277
336
  }
278
337
 
279
338
  async function initBridgeGit(work) {