@cirtium/acent-connect 1.0.1 → 1.1.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.
@@ -0,0 +1,605 @@
1
+ import { spawn } from "node:child_process"
2
+ import { createHash } from "node:crypto"
3
+ import { stat } from "node:fs/promises"
4
+ import { homedir } from "node:os"
5
+ import { join } from "node:path"
6
+ import { createInterface } from "node:readline"
7
+ import { hostExecutableCandidates } from "./host-executables.mjs"
8
+
9
+ export const bridgeTargets = ["Codex", "Claude Code", "Cursor", "Antigravity"]
10
+
11
+ export function modelFamily(model) {
12
+ const value = model?.toLowerCase() ?? ""
13
+ if (/^(?:openai[/:])?(?:gpt[- ]|o[134](?:[- ]|$))/.test(value)) return "gpt"
14
+ if (
15
+ /^(?:anthropic[/:])?(?:claude[- ]|sonnet(?:-|$)|opus(?:-|$)|haiku(?:-|$)|fable(?:-|$)|mythos(?:-|$))/.test(
16
+ value
17
+ )
18
+ )
19
+ return "claude"
20
+ if (/^(?:google[/:])?gemini[- ]/.test(value)) return "gemini"
21
+ if (/^(?:(?:xai|spacexai)[/:])?grok(?:[- ]|$)/.test(value)) return "grok"
22
+ }
23
+
24
+ export function runProcess(
25
+ command,
26
+ args,
27
+ {
28
+ cwd,
29
+ env,
30
+ timeout = 8000,
31
+ maxBytes = 1024 * 1024,
32
+ onLine,
33
+ initialize,
34
+ input,
35
+ signal,
36
+ onSpawn,
37
+ processGroup = false,
38
+ } = {}
39
+ ) {
40
+ return new Promise((resolve) => {
41
+ const detached = processGroup && process.platform !== "win32"
42
+ const child = spawn(command, args, {
43
+ cwd,
44
+ env,
45
+ detached,
46
+ stdio: ["pipe", "pipe", "pipe"],
47
+ windowsHide: true,
48
+ })
49
+ const kill = (type) => {
50
+ if (detached && child.pid) {
51
+ try {
52
+ process.kill(-child.pid, type)
53
+ } catch (error) {
54
+ if (error.code !== "ESRCH") child.kill(type)
55
+ }
56
+ } else child.kill(type)
57
+ }
58
+ let stdout = ""
59
+ let stderr = ""
60
+ let failure
61
+ let killTimer
62
+ let registering = Promise.resolve()
63
+ let closed = false
64
+ const stop = (reason) => {
65
+ if (failure) return
66
+ failure = reason
67
+ kill("SIGTERM")
68
+ killTimer = setTimeout(() => kill("SIGKILL"), 1500)
69
+ killTimer.unref()
70
+ }
71
+ const timer = setTimeout(() => stop("timed_out"), timeout)
72
+ const abort = () => stop("cancelled")
73
+ signal?.addEventListener("abort", abort, { once: true })
74
+ if (signal?.aborted) abort()
75
+ if (onLine) {
76
+ createInterface({ input: child.stdout }).on("line", (line) => {
77
+ let event
78
+ try {
79
+ event = JSON.parse(line)
80
+ } catch {
81
+ return
82
+ }
83
+ onLine(event, (message) => {
84
+ if (message === null) child.stdin.end()
85
+ else child.stdin.write(JSON.stringify(message) + "\n")
86
+ })
87
+ })
88
+ child.stdin.write(JSON.stringify(initialize) + "\n")
89
+ } else {
90
+ child.stdin.end(input)
91
+ }
92
+ child.stdin.on("error", () => {})
93
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
94
+ if (stdout.length + chunk.length > maxBytes) stop("output_limit")
95
+ else stdout += chunk
96
+ })
97
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
98
+ stderr = (stderr + chunk).slice(-16384)
99
+ })
100
+ child.on("error", (error) => {
101
+ failure = error.code === "ENOENT" ? "not_installed" : "failed"
102
+ })
103
+ if (onSpawn) {
104
+ child.once("spawn", () => {
105
+ registering = Promise.resolve()
106
+ .then(() => onSpawn(child.pid))
107
+ .catch(() => {
108
+ if (closed) failure ??= "failed"
109
+ else stop("failed")
110
+ })
111
+ })
112
+ }
113
+ child.on("close", async (code) => {
114
+ closed = true
115
+ clearTimeout(timer)
116
+ clearTimeout(killTimer)
117
+ signal?.removeEventListener("abort", abort)
118
+ await registering
119
+ resolve({ code, stdout, stderr, failure })
120
+ })
121
+ })
122
+ }
123
+
124
+ const commands = {
125
+ Codex: "codex",
126
+ "Claude Code": "claude",
127
+ Cursor: "agent",
128
+ Antigravity: "agy",
129
+ }
130
+
131
+ export function bridgeGitEnvironment() {
132
+ const env = { ...process.env }
133
+ for (const key of Object.keys(env)) {
134
+ if (
135
+ /^GIT_(?:DIR|WORK_TREE|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|PREFIX|CONFIG(?:$|_COUNT|_KEY_|_VALUE_|_PARAMETERS))/.test(
136
+ key
137
+ )
138
+ )
139
+ delete env[key]
140
+ }
141
+ return env
142
+ }
143
+
144
+ 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
153
+ }
154
+ return result
155
+ }
156
+
157
+ async function claudeModelList(cwd, run) {
158
+ let models = []
159
+ const result = await runHost(
160
+ "Claude Code",
161
+ [
162
+ "--print",
163
+ "--input-format",
164
+ "stream-json",
165
+ "--output-format",
166
+ "stream-json",
167
+ "--verbose",
168
+ ],
169
+ {
170
+ cwd,
171
+ timeout: 3500,
172
+ env: { ...bridgeGitEnvironment(), ACENT_BRIDGE_WORKER: "1" },
173
+ initialize: {
174
+ type: "control_request",
175
+ request_id: "acent-models",
176
+ request: { subtype: "initialize" },
177
+ },
178
+ onLine(event, send) {
179
+ if (
180
+ event.type !== "control_response" ||
181
+ event.response?.request_id !== "acent-models"
182
+ )
183
+ return
184
+ const reported = event.response?.response?.models
185
+ if (Array.isArray(reported))
186
+ models = reported.flatMap((item) =>
187
+ typeof item?.value === "string" &&
188
+ /^[a-z0-9][a-z0-9._:/-]{0,127}$/i.test(item.value) &&
189
+ item.value !== "default"
190
+ ? [{ id: item.value, family: modelFamily(item.value) ?? null }]
191
+ : []
192
+ )
193
+ send(null)
194
+ },
195
+ },
196
+ run
197
+ )
198
+ return result.code === 0 && !result.failure ? models : []
199
+ }
200
+
201
+ export async function bridgeAccountRevision(tool) {
202
+ if (tool !== "Codex") return
203
+ try {
204
+ // A file-backed sign-in change invalidates the catalog without reading credentials.
205
+ const path = join(
206
+ process.env.CODEX_HOME || join(homedir(), ".codex"),
207
+ "auth.json"
208
+ )
209
+ const file = await stat(path)
210
+ return JSON.stringify([path, file.ino, file.mtimeMs, file.size])
211
+ } catch {
212
+ return undefined
213
+ }
214
+ }
215
+
216
+ function modelRows(output) {
217
+ return [
218
+ ...new Set(
219
+ output
220
+ .split("\n")
221
+ .map((line) => {
222
+ const clean = line
223
+ .replace(/\x1b\[[0-9;]*m/g, "")
224
+ .trim()
225
+ .replace(/^[›*•]\s*/, "")
226
+ return clean.match(/^[\w][\w.:/-]*/)?.[0]
227
+ })
228
+ .filter((id) => id && /[-.:/]/.test(id) && !id.endsWith(":"))
229
+ ),
230
+ ]
231
+ }
232
+
233
+ function codexAccountKey(result) {
234
+ const account = result?.account
235
+ if (
236
+ result?.requiresOpenaiAuth !== true ||
237
+ account?.type !== "chatgpt" ||
238
+ typeof account.email !== "string" ||
239
+ !account.email.trim() ||
240
+ !["free", "go", "plus", "prolite", "pro"].includes(account.planType)
241
+ )
242
+ return
243
+ // The protocol exposes email and plan, but no workspace ID for shared plans.
244
+ return createHash("sha256")
245
+ .update(
246
+ JSON.stringify([account.email.trim().toLowerCase(), account.planType])
247
+ )
248
+ .digest("hex")
249
+ }
250
+
251
+ function codexQuota(result) {
252
+ const limits = result?.rateLimitsByLimitId
253
+ const entries =
254
+ limits && Object.keys(limits).length
255
+ ? Object.entries(limits)
256
+ : result?.rateLimits
257
+ ? [[result.rateLimits.limitId ?? "codex", result.rateLimits]]
258
+ : []
259
+ return entries.flatMap(([id, bucket]) =>
260
+ ["primary", "secondary"].flatMap((window) => {
261
+ const value = bucket?.[window]
262
+ if (
263
+ !Number.isFinite(value?.usedPercent) ||
264
+ value.usedPercent < 0 ||
265
+ value.usedPercent > 100
266
+ )
267
+ return []
268
+ return [
269
+ {
270
+ bucket: id,
271
+ window,
272
+ remainingPercent: 100 - value.usedPercent,
273
+ ...(Number.isFinite(value.windowDurationMins)
274
+ ? { durationMinutes: value.windowDurationMins }
275
+ : {}),
276
+ ...(Number.isFinite(value.resetsAt)
277
+ ? { resetsAt: value.resetsAt * 1000 }
278
+ : {}),
279
+ },
280
+ ]
281
+ })
282
+ )
283
+ }
284
+
285
+ async function codexInfo(run, cwd, includeQuota = false) {
286
+ const models = []
287
+ let cursor
288
+ let accountKey
289
+ let windows = []
290
+ let modelsDone = includeQuota
291
+ let accountDone = false
292
+ let quotaDone = !includeQuota
293
+ const result = await runHost(
294
+ "Codex",
295
+ ["app-server"],
296
+ {
297
+ cwd,
298
+ timeout: includeQuota ? 3500 : 8000,
299
+ onLine(event, send) {
300
+ if (event.id === 1) {
301
+ send({ method: "initialized" })
302
+ send({
303
+ id: 3,
304
+ method: "account/read",
305
+ params: { refreshToken: false },
306
+ })
307
+ if (!includeQuota)
308
+ send({ id: 2, method: "model/list", params: { limit: 100 } })
309
+ }
310
+ if (event.id === 2) {
311
+ for (const model of event.result?.data ?? [])
312
+ if (model.model) models.push(model.model)
313
+ const next = event.result?.nextCursor
314
+ if (next && next !== cursor) {
315
+ cursor = next
316
+ send({
317
+ id: 2,
318
+ method: "model/list",
319
+ params: { limit: 100, cursor },
320
+ })
321
+ } else {
322
+ modelsDone = true
323
+ }
324
+ }
325
+ if (event.id === 3) {
326
+ accountKey = codexAccountKey(event.result)
327
+ accountDone = true
328
+ if (includeQuota && accountKey)
329
+ send({ id: 4, method: "account/rateLimits/read" })
330
+ else quotaDone = true
331
+ }
332
+ if (event.id === 4) {
333
+ windows = codexQuota(event.result)
334
+ quotaDone = true
335
+ }
336
+ if (modelsDone && accountDone && quotaDone) send(null)
337
+ },
338
+ initialize: {
339
+ id: 1,
340
+ method: "initialize",
341
+ params: { clientInfo: { name: "acent", version: "1.0" } },
342
+ },
343
+ },
344
+ run
345
+ )
346
+ return result.failure || result.code !== 0
347
+ ? { models: [] }
348
+ : { models, accountKey, windows }
349
+ }
350
+
351
+ export async function readBridgeQuota(tool, cwd, run = runProcess) {
352
+ if (tool !== "Codex") return
353
+ const { accountKey, windows } = await codexInfo(run, cwd, true)
354
+ if (!accountKey || !windows?.length) return
355
+ return { accountKey, checkedAt: Date.now(), windows }
356
+ }
357
+
358
+ export async function discoverBridgeTarget(tool, cwd, run = runProcess) {
359
+ const statusArgs = {
360
+ Codex: ["login", "status"],
361
+ "Claude Code": ["auth", "status"],
362
+ Cursor: ["status"],
363
+ Antigravity: ["models"],
364
+ }[tool]
365
+ const result = await runHost(tool, statusArgs, { cwd }, run)
366
+ 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
+ }
375
+ if (tool === "Claude Code") {
376
+ let account
377
+ try {
378
+ account = JSON.parse(result.stdout)
379
+ } catch {
380
+ return { tool, status: "unavailable", models: [] }
381
+ }
382
+ if (account.loggedIn === false)
383
+ return { tool, status: "login_required", models: [] }
384
+ if (!account.loggedIn || result.code !== 0)
385
+ return { tool, status: "unavailable", models: [] }
386
+ const models = await claudeModelList(cwd, run)
387
+ return {
388
+ tool,
389
+ status: "ready",
390
+ models,
391
+ modelCatalog: models.length ? "available" : "unverified",
392
+ defaultFamily:
393
+ account.authMethod === "claude.ai" && !process.env.ANTHROPIC_BASE_URL
394
+ ? "claude"
395
+ : undefined,
396
+ }
397
+ }
398
+ if (result.code !== 0) return { tool, status: "unavailable", models: [] }
399
+ const codex = tool === "Codex" ? await codexInfo(run, cwd) : undefined
400
+ const ids = codex
401
+ ? codex.models
402
+ : tool === "Antigravity"
403
+ ? modelRows(result.stdout)
404
+ : modelRows((await runHost(tool, ["models"], { cwd }, run)).stdout)
405
+ return {
406
+ tool,
407
+ status: tool === "Antigravity" && !ids.length ? "unverified" : "ready",
408
+ models: ids.map((id) => ({ id, family: modelFamily(id) ?? null })),
409
+ modelCatalog: ids.length ? "available" : "unverified",
410
+ accountKey: codex?.accountKey,
411
+ }
412
+ }
413
+
414
+ export async function executeBridgeTarget(
415
+ { tool, model, readOnly, cwd, prompt, signal, onSpawn },
416
+ run = runProcess
417
+ ) {
418
+ const args = {
419
+ Codex: [
420
+ "exec",
421
+ "--json",
422
+ "--sandbox",
423
+ readOnly ? "read-only" : "workspace-write",
424
+ ...(model ? ["-m", model] : []),
425
+ "--",
426
+ "-",
427
+ ],
428
+ "Claude Code": [
429
+ "-p",
430
+ "--output-format",
431
+ "stream-json",
432
+ "--verbose",
433
+ "--permission-mode",
434
+ readOnly ? "plan" : "acceptEdits",
435
+ ...(model ? ["--model", model] : []),
436
+ ],
437
+ Cursor: [
438
+ "--output-format",
439
+ "json",
440
+ ...(readOnly ? ["--mode=ask"] : []),
441
+ ...(model ? ["--model", model] : []),
442
+ "-p",
443
+ prompt,
444
+ ],
445
+ Antigravity: [
446
+ "--output-format",
447
+ "stream-json",
448
+ "--mode",
449
+ readOnly ? "plan" : "accept-edits",
450
+ ...(model ? ["--model", model] : []),
451
+ "-p",
452
+ prompt,
453
+ ],
454
+ }[tool]
455
+ const result = await runHost(
456
+ tool,
457
+ args,
458
+ {
459
+ cwd,
460
+ signal,
461
+ onSpawn,
462
+ processGroup: true,
463
+ env: { ...bridgeGitEnvironment(), ACENT_BRIDGE_WORKER: "1" },
464
+ input: tool === "Codex" || tool === "Claude Code" ? prompt : undefined,
465
+ timeout: 10 * 60 * 1000,
466
+ maxBytes: 8 * 1024 * 1024,
467
+ },
468
+ run
469
+ )
470
+ let summary
471
+ let error
472
+ let usage
473
+ let actualModel
474
+ let rateLimitResetAt
475
+ if (tool === "Codex" || tool === "Claude Code") {
476
+ const events = result.stdout.split("\n").flatMap((line) => {
477
+ try {
478
+ return [JSON.parse(line)]
479
+ } catch {
480
+ return []
481
+ }
482
+ })
483
+ if (tool === "Codex") {
484
+ const turn = events.findLast((event) => event.type === "turn.completed")
485
+ summary = events.findLast((event) => event.item?.type === "agent_message")
486
+ ?.item.text
487
+ error = events.findLast((event) => event.type === "turn.failed")?.error
488
+ ?.message
489
+ if (!turn && !error) error = "Codex did not report a completed turn."
490
+ usage = turn?.usage
491
+ } else {
492
+ const terminal = events.findLast((event) => event.type === "result")
493
+ summary = terminal?.result
494
+ usage = terminal?.usage
495
+ actualModel = events.findLast(
496
+ (event) =>
497
+ event.type === "assistant" && typeof event.message?.model === "string"
498
+ )?.message.model
499
+ const limit = events.findLast(
500
+ (event) =>
501
+ event.type === "rate_limit_event" &&
502
+ event.rate_limit_info?.status === "rejected"
503
+ )?.rate_limit_info
504
+ if (limit) {
505
+ error = "Usage limit reached"
506
+ if (Number.isFinite(limit.resetsAt))
507
+ rateLimitResetAt = limit.resetsAt * 1000
508
+ } else if (
509
+ !terminal ||
510
+ terminal.is_error ||
511
+ terminal.subtype !== "success"
512
+ ) {
513
+ error =
514
+ terminal?.errors?.join("\n") ||
515
+ summary ||
516
+ "Claude Code did not report a completed turn."
517
+ }
518
+ }
519
+ } else {
520
+ try {
521
+ const event =
522
+ tool === "Antigravity"
523
+ ? result.stdout
524
+ .split("\n")
525
+ .flatMap((line) => {
526
+ try {
527
+ return [JSON.parse(line)]
528
+ } catch {
529
+ return []
530
+ }
531
+ })
532
+ .findLast((item) => item.event === "result")
533
+ : JSON.parse(result.stdout)
534
+ if (!event) throw new Error("Missing final CLI result")
535
+ const payload =
536
+ typeof event.result === "object" && event.result ? event.result : event
537
+ summary =
538
+ payload.response ??
539
+ (typeof payload.result === "string" ? payload.result : undefined)
540
+ usage = payload.usage
541
+ if (
542
+ event.is_error ||
543
+ payload.is_error ||
544
+ /^(error|failed)$/i.test(payload.status ?? "")
545
+ ) {
546
+ error =
547
+ payload.error ||
548
+ summary ||
549
+ payload.status ||
550
+ "Agent returned an error."
551
+ }
552
+ } catch {
553
+ // A non-JSON response cannot verify that a delegated turn completed.
554
+ }
555
+ }
556
+ const diagnostics = String(error ?? "") + "\n" + result.stderr
557
+ let failure = result.failure
558
+ if (!failure && (result.code !== 0 || error || typeof summary !== "string")) {
559
+ if (
560
+ /context (?:window|length|limit)|prompt is too long|token limit exceeded/i.test(
561
+ diagnostics
562
+ )
563
+ )
564
+ failure = "context_limit"
565
+ else if (
566
+ /rate.limit|quota|usage limit|insufficient credits|resource.exhausted|429/i.test(
567
+ diagnostics
568
+ )
569
+ )
570
+ failure = "usage_limit"
571
+ else if (
572
+ /not (?:logged in|authenticated)|authentication required|login required|401/i.test(
573
+ diagnostics
574
+ )
575
+ )
576
+ failure = "login_required"
577
+ else if (
578
+ /model.*(?:unavailable|not found|not supported|access denied)|unknown model/i.test(
579
+ diagnostics
580
+ )
581
+ )
582
+ failure = "model_unavailable"
583
+ else failure = "failed"
584
+ }
585
+ const tokens = Object.fromEntries(
586
+ [
587
+ ["input", usage?.input_tokens ?? usage?.inputTokens],
588
+ ["output", usage?.output_tokens ?? usage?.outputTokens],
589
+ [
590
+ "cachedInput",
591
+ usage?.cached_input_tokens ??
592
+ usage?.cache_read_input_tokens ??
593
+ usage?.cache_read_tokens ??
594
+ usage?.cachedInputTokens,
595
+ ],
596
+ ].filter(([, value]) => Number.isSafeInteger(value) && value >= 0)
597
+ )
598
+ return {
599
+ failure,
600
+ summary: typeof summary === "string" ? summary.slice(0, 16000) : undefined,
601
+ actualModel,
602
+ rateLimitResetAt,
603
+ ...(Object.keys(tokens).length ? { tokens } : {}),
604
+ }
605
+ }