@cirtium/acent-connect 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/acent/.claude-plugin/plugin.json +1 -1
- package/acent/.codex-plugin/plugin.json +1 -1
- package/acent/.cursor-plugin/plugin.json +1 -1
- package/acent/hooks/cursor.json +15 -0
- package/acent/scripts/acent-connect.mjs +334 -117
- package/acent/scripts/antigravity-hook.mjs +12 -0
- package/acent/scripts/bridge-lifecycle.mjs +119 -0
- package/acent/scripts/bridge.mjs +8 -2
- package/acent/scripts/capture-diagnostics.mjs +67 -0
- package/acent/scripts/capture-policy.mjs +9 -0
- package/acent/scripts/codex-capture.mjs +5 -1
- package/acent/scripts/hook.mjs +20 -5
- package/acent/scripts/mcp-proxy.mjs +9 -0
- package/acent/skills/acent-bridge/SKILL.md +1 -0
- package/antigravity/plugin.json +1 -1
- package/package.json +1 -1
- package/scripts/acent.mjs +3 -3
package/acent/hooks/cursor.json
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
3
|
"hooks": {
|
|
4
|
+
"sessionStart": [
|
|
5
|
+
{
|
|
6
|
+
"command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/hook.mjs\" --tool Cursor --bridge-event sessionStart"
|
|
7
|
+
}
|
|
8
|
+
],
|
|
9
|
+
"stop": [
|
|
10
|
+
{
|
|
11
|
+
"command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/hook.mjs\" --tool Cursor --bridge-event stop"
|
|
12
|
+
}
|
|
13
|
+
],
|
|
14
|
+
"afterMCPExecution": [
|
|
15
|
+
{
|
|
16
|
+
"command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/hook.mjs\" --tool Cursor --bridge-event afterMCPExecution"
|
|
17
|
+
}
|
|
18
|
+
],
|
|
4
19
|
"beforeSubmitPrompt": [
|
|
5
20
|
{
|
|
6
21
|
"command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/hook.mjs\" --tool Cursor"
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { capturePayload, isToolActivityHook } from "./capture-policy.mjs"
|
|
3
|
+
import { captureDiagnosticDirectory, recordCaptureDiagnostic } from "./capture-diagnostics.mjs"
|
|
3
4
|
import { captureActivity } from "./capture-activity.mjs"
|
|
4
5
|
import { attachFiles } from "./capture-attachments.mjs"
|
|
5
6
|
/** Local connection/capture adapter. No AI calls; credentials never go to stdout. */
|
|
@@ -25,6 +26,11 @@ import { pathToFileURL } from "node:url"
|
|
|
25
26
|
const toolNames = ["Claude Code", "Codex", "Cursor", "Antigravity"]
|
|
26
27
|
const hash = (value) => createHash("sha256").update(value).digest("hex")
|
|
27
28
|
const random = () => randomBytes(32).toString("base64url")
|
|
29
|
+
const maxQueuedEvents = 500
|
|
30
|
+
const maxQueuedBytes = 32 * 1024 * 1024
|
|
31
|
+
const conversationReserveEvents = 64
|
|
32
|
+
const conversationReserveBytes = 4 * 1024 * 1024
|
|
33
|
+
const maxConsecutiveServerErrors = 3
|
|
28
34
|
export function options(args) {
|
|
29
35
|
const result = {
|
|
30
36
|
command: args[0],
|
|
@@ -119,13 +125,19 @@ export async function atomicJson(path, value) {
|
|
|
119
125
|
export async function request(config, path, init) {
|
|
120
126
|
const response = await fetch(`${config.server}${path}`, {
|
|
121
127
|
...init,
|
|
122
|
-
signal: AbortSignal.timeout(30_000),
|
|
128
|
+
signal: init?.signal ?? AbortSignal.timeout(30_000),
|
|
123
129
|
})
|
|
124
130
|
const body = await response.json().catch(() => ({}))
|
|
125
131
|
if (!response.ok)
|
|
126
132
|
throw Object.assign(
|
|
127
133
|
new Error(body.error_description || body.error || "Acent request failed"),
|
|
128
|
-
{
|
|
134
|
+
{
|
|
135
|
+
status: response.status,
|
|
136
|
+
code: body.error,
|
|
137
|
+
requestId: response.headers.get("x-acent-capture-id") ?? response.headers.get("x-vercel-id"),
|
|
138
|
+
serverStage: response.headers.get("x-acent-capture-stage"),
|
|
139
|
+
serverReason: response.headers.get("x-acent-capture-reason"),
|
|
140
|
+
}
|
|
129
141
|
)
|
|
130
142
|
return body
|
|
131
143
|
}
|
|
@@ -217,6 +229,31 @@ export async function lock(directory, operation) {
|
|
|
217
229
|
async function readCredentials(directory) {
|
|
218
230
|
return JSON.parse(await readFile(join(directory, "credentials.json"), "utf8"))
|
|
219
231
|
}
|
|
232
|
+
function captureStatusPath(directory, clientId) {
|
|
233
|
+
return join(directory, "managed-capture-status-" + hash(clientId) + ".json")
|
|
234
|
+
}
|
|
235
|
+
async function captureStatus(directory) {
|
|
236
|
+
const grant = await readCredentials(directory).catch(error => {
|
|
237
|
+
if (error.code !== "ENOENT") throw error
|
|
238
|
+
})
|
|
239
|
+
if (!grant?.scope?.split(" ").includes("conversation:write") ||
|
|
240
|
+
!grant.client_id || grant.client_id.startsWith("ac_private_client_"))
|
|
241
|
+
return { connected: false }
|
|
242
|
+
const queue = join(directory, "managed-queue", hash(grant.client_id))
|
|
243
|
+
const files = await readdir(queue).catch(error => {
|
|
244
|
+
if (error.code !== "ENOENT") throw error
|
|
245
|
+
return []
|
|
246
|
+
})
|
|
247
|
+
const status = await readFile(captureStatusPath(directory, grant.client_id), "utf8")
|
|
248
|
+
.then(JSON.parse).catch(() => ({}))
|
|
249
|
+
return {
|
|
250
|
+
connected: true,
|
|
251
|
+
blocked: grant.captureBlocked === true,
|
|
252
|
+
pending: files.filter(file => file.endsWith(".json")).length,
|
|
253
|
+
lastStoredAt: status.lastStoredAt ?? null,
|
|
254
|
+
lastError: status.lastError ?? null,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
220
257
|
function hasFreshAccess(saved) {
|
|
221
258
|
return saved?.expiresAt > Date.now() + 30_000
|
|
222
259
|
}
|
|
@@ -242,69 +279,199 @@ async function token(config, directory) {
|
|
|
242
279
|
})
|
|
243
280
|
return refreshed.access_token
|
|
244
281
|
}
|
|
282
|
+
|
|
283
|
+
function deliveryFailure(file, error) {
|
|
284
|
+
const rejected = ["prompt_pending", "invalid_packet", "invalid_capture", "invalid_session"]
|
|
285
|
+
const code = rejected.includes(error.code) ? error.code
|
|
286
|
+
: error.status >= 500 ? "server_error"
|
|
287
|
+
: error.status === 429 ? "rate_limited"
|
|
288
|
+
: error.status ? null
|
|
289
|
+
: ["TimeoutError", "AbortError"].includes(error.name) ? "timeout" : "network_error"
|
|
290
|
+
if (!code) return null
|
|
291
|
+
return {
|
|
292
|
+
packetId: hash(file), at: new Date().toISOString(), code,
|
|
293
|
+
requestId: /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(error.requestId ?? "")
|
|
294
|
+
? error.requestId : null,
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function reportCaptureDelivery(config, headers, policy, queue, status) {
|
|
299
|
+
if (!policy.deliveryReporting || (!status.deliveryFailures?.length && !status.deliveryPending)) return
|
|
300
|
+
const files = (await readdir(queue).catch(error => {
|
|
301
|
+
if (error.code === "ENOENT") return []
|
|
302
|
+
throw error
|
|
303
|
+
})).filter(file => /^\d{13}-.*\.json$/.test(file)).sort()
|
|
304
|
+
const response = await request(config, "/api/external/managed", {
|
|
305
|
+
method: "PATCH",
|
|
306
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
307
|
+
signal: AbortSignal.timeout(1_500),
|
|
308
|
+
body: JSON.stringify({
|
|
309
|
+
destination: policy.destination,
|
|
310
|
+
failures: status.deliveryFailures ?? [],
|
|
311
|
+
pending: files.length,
|
|
312
|
+
oldestPendingAt: files.length ? new Date(Number(files[0].split("-")[0])).toISOString() : null,
|
|
313
|
+
lastStoredAt: status.lastStoredAt ?? null,
|
|
314
|
+
}),
|
|
315
|
+
})
|
|
316
|
+
if (response.recorded === true) {
|
|
317
|
+
status.deliveryFailures = []
|
|
318
|
+
status.deliveryPending = files.length > 0
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function retainDeliveryFailure(status, file, error) {
|
|
323
|
+
const failure = deliveryFailure(file, error)
|
|
324
|
+
if (!failure) return
|
|
325
|
+
status.deliveryFailures = [failure, ...(status.deliveryFailures ?? []).filter(
|
|
326
|
+
item => item.packetId !== failure.packetId
|
|
327
|
+
)].slice(0, 32)
|
|
328
|
+
}
|
|
329
|
+
|
|
245
330
|
export async function drain(config, directory) {
|
|
246
331
|
return lock(directory, async () => {
|
|
247
332
|
const grant = await readCredentials(directory)
|
|
248
|
-
if (!grant.client_id || grant.client_id.startsWith("ac_private_client_")
|
|
333
|
+
if (!grant.client_id || grant.client_id.startsWith("ac_private_client_") ||
|
|
334
|
+
grant.captureBlocked || !grant.scope?.split(" ").includes("conversation:write")) return
|
|
249
335
|
const queue = join(directory, "managed-queue", hash(grant.client_id))
|
|
250
336
|
const files = (await readdir(queue).catch(error => { if (error.code === "ENOENT") return []; throw error }))
|
|
251
337
|
.filter((file) => file.endsWith(".json"))
|
|
252
338
|
.sort()
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
339
|
+
const statusPath = captureStatusPath(directory, grant.client_id)
|
|
340
|
+
const status = await readFile(statusPath, "utf8").then(JSON.parse).catch(() => ({}))
|
|
341
|
+
if (!files.length && !status.deliveryFailures?.length && !status.deliveryPending) return
|
|
342
|
+
let stage = "authorization"
|
|
343
|
+
let headers, policy
|
|
344
|
+
try {
|
|
345
|
+
const access = await token(config, directory)
|
|
346
|
+
headers = { Authorization: "Bearer " + access }
|
|
347
|
+
stage = "policy"
|
|
348
|
+
policy = await request(config, "/api/external/managed", { headers })
|
|
349
|
+
} catch (error) {
|
|
350
|
+
await recordCaptureDiagnostic(directory, grant.client_id, stage, error)
|
|
351
|
+
if (files.length) {
|
|
352
|
+
const packet = await readFile(join(queue, files[0]), "utf8").then(JSON.parse).catch(() => null)
|
|
353
|
+
if (packet?.acent_destination && (!status.deliveryDestination || status.deliveryDestination === packet.acent_destination)) {
|
|
354
|
+
status.deliveryDestination = packet.acent_destination
|
|
355
|
+
retainDeliveryFailure(status, files[0], error)
|
|
356
|
+
await atomicJson(statusPath, status).catch(() => {})
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
throw error
|
|
360
|
+
}
|
|
257
361
|
if (!policy.enabled) {
|
|
258
362
|
for (const file of files) await unlink(join(queue, file))
|
|
259
363
|
return
|
|
260
364
|
}
|
|
365
|
+
if (status.deliveryDestination !== policy.destination) {
|
|
366
|
+
status.deliveryDestination = policy.destination
|
|
367
|
+
status.deliveryFailures = []
|
|
368
|
+
status.deliveryPending = false
|
|
369
|
+
}
|
|
370
|
+
async function recordStatus(error) {
|
|
371
|
+
status.lastError = error
|
|
372
|
+
await atomicJson(statusPath, status).catch(() => {})
|
|
373
|
+
}
|
|
261
374
|
const deferred = new Set()
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
)
|
|
268
|
-
|
|
269
|
-
if (
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
375
|
+
let serverErrors = 0
|
|
376
|
+
let retryableError
|
|
377
|
+
let pendingError = null
|
|
378
|
+
const seenErrors = new Set()
|
|
379
|
+
async function recordUploadError(stage, error, file) {
|
|
380
|
+
if (file && policy.deliveryReporting) retainDeliveryFailure(status, file, error)
|
|
381
|
+
const signature = JSON.stringify([stage, error.code, error.status, error.serverStage, error.serverReason])
|
|
382
|
+
if (seenErrors.has(signature)) return
|
|
383
|
+
seenErrors.add(signature)
|
|
384
|
+
await recordCaptureDiagnostic(directory, grant.client_id, stage, error)
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
// Dependent records may arrive before their prompt. Give queued prompts
|
|
388
|
+
// one chance to unblock them, then leave unresolved records for a later drain.
|
|
389
|
+
for (const file of files) {
|
|
390
|
+
let payload
|
|
391
|
+
try {
|
|
392
|
+
payload = JSON.parse(await readFile(join(queue, file), "utf8"))
|
|
393
|
+
} catch (error) {
|
|
394
|
+
if (error.code === "ENOENT") continue
|
|
395
|
+
if (!(error instanceof SyntaxError)) throw error
|
|
276
396
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
})
|
|
281
|
-
} catch (error) {
|
|
282
|
-
if (error.status === 409 && error.code === "prompt_pending" && !deferred.has(file)) {
|
|
283
|
-
deferred.add(file)
|
|
284
|
-
files.push(file)
|
|
397
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
398
|
+
pendingError = "invalid_packet"
|
|
399
|
+
await recordUploadError("queue", { code: pendingError }, file)
|
|
285
400
|
continue
|
|
286
401
|
}
|
|
287
|
-
|
|
288
|
-
if (
|
|
289
|
-
|
|
402
|
+
// An outbox entry belongs to the project approved at capture time.
|
|
403
|
+
if (payload.acent_destination !== policy.destination) {
|
|
404
|
+
pendingError = "destination_changed"
|
|
405
|
+
await recordUploadError("policy", { code: pendingError })
|
|
290
406
|
continue
|
|
291
407
|
}
|
|
292
|
-
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
408
|
+
try {
|
|
409
|
+
const filtered = capturePayload(payload, policy.code === true, policy.activity === true)
|
|
410
|
+
if ((payload.acent_code_changes || payload.acent_activity) &&
|
|
411
|
+
!filtered.acent_code_changes?.length && !filtered.acent_activity?.length) {
|
|
412
|
+
await unlink(join(queue, file))
|
|
413
|
+
continue
|
|
414
|
+
}
|
|
415
|
+
const response = await request(config, "/api/external/managed", {
|
|
416
|
+
method: "POST", headers: { ...headers, "Content-Type": "application/json" },
|
|
417
|
+
body: JSON.stringify({ id: hash(file), destination: policy.destination, at: Number(file.split("-")[0]), payload: filtered }),
|
|
299
418
|
})
|
|
419
|
+
if (response.stored === true) status.lastStoredAt = new Date().toISOString()
|
|
420
|
+
serverErrors = 0
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (error.status === 409 && error.code === "prompt_pending") {
|
|
423
|
+
if (!deferred.has(file)) {
|
|
424
|
+
deferred.add(file)
|
|
425
|
+
files.push(file)
|
|
426
|
+
} else {
|
|
427
|
+
pendingError = "prompt_pending"
|
|
428
|
+
await recordUploadError("upload", error, file)
|
|
429
|
+
}
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
if (error.code !== "capture_disabled") await recordUploadError("upload", error, file)
|
|
433
|
+
if (error.status === 400 && ["invalid_packet", "invalid_capture", "invalid_session"].includes(error.code)) {
|
|
434
|
+
// Keep the rejected packet for recovery without blocking other turns.
|
|
435
|
+
pendingError = error.code
|
|
436
|
+
continue
|
|
437
|
+
}
|
|
438
|
+
if (error.status === 503 && ++serverErrors < maxConsecutiveServerErrors) {
|
|
439
|
+
pendingError = "server_error"
|
|
440
|
+
retryableError ??= error
|
|
441
|
+
continue
|
|
442
|
+
}
|
|
443
|
+
if (error.code === "destination_changed") continue
|
|
444
|
+
if (error.code === "capture_disabled") {
|
|
445
|
+
await unlink(join(queue, file))
|
|
446
|
+
continue
|
|
447
|
+
}
|
|
448
|
+
if (error.code === "invalid_token" || error.code === "insufficient_scope") {
|
|
449
|
+
const credentials = JSON.parse(
|
|
450
|
+
await readFile(join(directory, "credentials.json"), "utf8")
|
|
451
|
+
)
|
|
452
|
+
await atomicJson(join(directory, "credentials.json"), {
|
|
453
|
+
...credentials,
|
|
454
|
+
captureBlocked: true,
|
|
455
|
+
})
|
|
300
456
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
457
|
+
await rm(join(directory, "code-capture"), { recursive: true, force: true })
|
|
458
|
+
for (const queued of await readdir(queue))
|
|
459
|
+
await unlink(join(queue, queued))
|
|
460
|
+
}
|
|
461
|
+
await recordStatus(
|
|
462
|
+
typeof error.code === "string" && /^[a-z_]{1,60}$/.test(error.code)
|
|
463
|
+
? error.code : error.status ? "request_failed" : "network_error"
|
|
464
|
+
)
|
|
465
|
+
throw error
|
|
304
466
|
}
|
|
305
|
-
|
|
467
|
+
await unlink(join(queue, file))
|
|
306
468
|
}
|
|
307
|
-
await
|
|
469
|
+
await recordStatus(pendingError)
|
|
470
|
+
if (retryableError) throw retryableError
|
|
471
|
+
} finally {
|
|
472
|
+
// Retain a bounded report until the server acknowledges it. Delivery is independent of capture.
|
|
473
|
+
await reportCaptureDelivery(config, headers, policy, queue, status).catch(() => {})
|
|
474
|
+
await atomicJson(statusPath, status).catch(() => {})
|
|
308
475
|
}
|
|
309
476
|
})
|
|
310
477
|
}
|
|
@@ -322,25 +489,42 @@ export async function queueManagedCapture(config, directory, policy, events, at
|
|
|
322
489
|
}))
|
|
323
490
|
const eventBytes = packets.reduce((sum, event) => {
|
|
324
491
|
const bytes = Buffer.byteLength(JSON.stringify(event))
|
|
325
|
-
if (bytes > 2 * 1024 * 1024) throw new Error("Collected event exceeds 2 MiB.")
|
|
492
|
+
if (bytes > 2 * 1024 * 1024) throw Object.assign(new Error("Collected event exceeds 2 MiB."), { code: "payload_too_large" })
|
|
326
493
|
return sum + bytes
|
|
327
494
|
}, 0)
|
|
495
|
+
const evidenceOnly = packets.every(event =>
|
|
496
|
+
event.acent_code_changes?.length || event.acent_activity?.length
|
|
497
|
+
)
|
|
498
|
+
const eventLimit = maxQueuedEvents - (evidenceOnly ? conversationReserveEvents : 0)
|
|
499
|
+
const byteLimit = maxQueuedBytes - (evidenceOnly ? conversationReserveBytes : 0)
|
|
328
500
|
async function capacityError() {
|
|
329
501
|
const files = (await readdir(queue)).filter(file => file.endsWith(".json"))
|
|
330
|
-
if (files.length + packets.length >
|
|
502
|
+
if (files.length + packets.length > eventLimit) return "Capture queue is full."
|
|
331
503
|
const sizes = await Promise.all(files.map(file =>
|
|
332
504
|
stat(join(queue, file)).catch(error => {
|
|
333
505
|
if (error.code === "ENOENT") return { size: 0 }
|
|
334
506
|
throw error
|
|
335
507
|
})
|
|
336
508
|
))
|
|
337
|
-
if (sizes.reduce((sum, file) => sum + file.size, eventBytes) >
|
|
338
|
-
return "Capture queue
|
|
509
|
+
if (sizes.reduce((sum, file) => sum + file.size, eventBytes) > byteLimit)
|
|
510
|
+
return "Capture queue storage limit reached."
|
|
339
511
|
}
|
|
340
512
|
if (await capacityError()) {
|
|
341
|
-
|
|
513
|
+
let drainError
|
|
514
|
+
try {
|
|
515
|
+
await drain(config, directory)
|
|
516
|
+
} catch (error) {
|
|
517
|
+
drainError = error
|
|
518
|
+
}
|
|
342
519
|
const error = await capacityError()
|
|
343
|
-
if (error) throw new Error(error + " Retry after pending events are sent.")
|
|
520
|
+
if (error) throw drainError ?? Object.assign(new Error(error + " Retry after pending events are sent."), { code: "queue_full" })
|
|
521
|
+
// A partial flush can make room even when one packet still has a server error.
|
|
522
|
+
if (drainError && drainError.status !== 503) throw drainError
|
|
523
|
+
const access = await accessToken(config, directory)
|
|
524
|
+
const updated = await request(config, "/api/external/managed", {
|
|
525
|
+
headers: { Authorization: "Bearer " + access },
|
|
526
|
+
})
|
|
527
|
+
if (!updated.enabled || updated.destination !== policy.destination) return
|
|
344
528
|
}
|
|
345
529
|
for (const packet of packets) {
|
|
346
530
|
const bridgeId = packet.hook_event_name === "AcentBridge"
|
|
@@ -417,6 +601,10 @@ export async function connect(config, directory, open = openBrowser) {
|
|
|
417
601
|
export async function main(args = process.argv.slice(2), eventText) {
|
|
418
602
|
const config = await boundConfig(args),
|
|
419
603
|
directory = configDirectory(config)
|
|
604
|
+
if (config.command === "status") {
|
|
605
|
+
console.log(JSON.stringify(await captureStatus(directory), null, 2))
|
|
606
|
+
return
|
|
607
|
+
}
|
|
420
608
|
await mkdir(join(directory, "queue"), { recursive: true, mode: 0o700 })
|
|
421
609
|
if (config.command === "connect") return connect(config, directory)
|
|
422
610
|
if (config.command === "collect") {
|
|
@@ -433,75 +621,88 @@ export async function main(args = process.argv.slice(2), eventText) {
|
|
|
433
621
|
)
|
|
434
622
|
return
|
|
435
623
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
if (config.tool === "Antigravity" && !codeEvent && !activityEvent && !(await captureAntigravityEvent(payload, captureDirectory))) return
|
|
478
|
-
if (policy.attachments === true && !codeEvent && !activityEvent && !toolEvent) {
|
|
479
|
-
try {
|
|
480
|
-
payload = (await attachFiles(payload, config, access, request, policy.destination)).payload
|
|
481
|
-
} catch {
|
|
482
|
-
// Keep conversation capture available if file storage is temporarily down.
|
|
483
|
-
console.error("Acent could not save the attached files.")
|
|
624
|
+
let stage = "hook"
|
|
625
|
+
try {
|
|
626
|
+
const content =
|
|
627
|
+
eventText ??
|
|
628
|
+
(config.file
|
|
629
|
+
? await readFile(config.file, "utf8")
|
|
630
|
+
: await new Promise((resolve, reject) => {
|
|
631
|
+
let text = ""
|
|
632
|
+
process.stdin.setEncoding("utf8")
|
|
633
|
+
process.stdin.on("data", (chunk) => {
|
|
634
|
+
text += chunk
|
|
635
|
+
if (Buffer.byteLength(text) > 2 * 1024 * 1024) {
|
|
636
|
+
process.stdin.destroy()
|
|
637
|
+
reject(new Error("Event exceeds 2 MiB."))
|
|
638
|
+
}
|
|
639
|
+
})
|
|
640
|
+
process.stdin.on("end", () => resolve(text))
|
|
641
|
+
process.stdin.on("error", reject)
|
|
642
|
+
}))
|
|
643
|
+
if (Buffer.byteLength(content) > 2 * 1024 * 1024)
|
|
644
|
+
throw Object.assign(new Error("Event exceeds 2 MiB."), { code: "payload_too_large" })
|
|
645
|
+
const captureDirectory = join(directory, "managed-capture", hash(credentials.client_id))
|
|
646
|
+
stage = "authorization"
|
|
647
|
+
const access = await accessToken(config, directory)
|
|
648
|
+
stage = "policy"
|
|
649
|
+
const policy = await request(config, "/api/external/managed", { headers: { Authorization: "Bearer " + access } })
|
|
650
|
+
if (!policy.enabled) return
|
|
651
|
+
const code = policy.code === true
|
|
652
|
+
const activity = policy.activity === true
|
|
653
|
+
stage = "hook"
|
|
654
|
+
let payload = JSON.parse(content)
|
|
655
|
+
stage = "prepare"
|
|
656
|
+
const hook = payload.acent_hook || payload.hook_event_name
|
|
657
|
+
const toolEvent = isToolActivityHook(hook)
|
|
658
|
+
if ((toolEvent && !activity && !code) || (hook === "afterFileEdit" && !code)) return
|
|
659
|
+
if (config.tool === "Codex" && !(await captureCodexEvent(payload, captureDirectory))) return
|
|
660
|
+
if (config.tool === "Antigravity" && toolEvent) {
|
|
661
|
+
if (code) await captureAntigravityEvent(payload, captureDirectory).catch(() => {
|
|
662
|
+
payload.acent_request = null
|
|
663
|
+
console.error("Acent request link unavailable.")
|
|
664
|
+
})
|
|
484
665
|
}
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
const
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
666
|
+
const codeEvent = code && await captureCodeChanges(payload, config, captureDirectory)
|
|
667
|
+
const activityEvent = activity && await captureActivity(payload, config, captureDirectory, code)
|
|
668
|
+
const changes = code ? payload.acent_code_changes ?? [] : []
|
|
669
|
+
const toolActivities = activity ? payload.acent_activity ?? [] : []
|
|
670
|
+
if ((codeEvent || activityEvent || toolEvent) && !changes.length && !toolActivities.length) return
|
|
671
|
+
if (config.tool === "Antigravity" && !codeEvent && !activityEvent && !(await captureAntigravityEvent(payload, captureDirectory))) return
|
|
672
|
+
if (policy.attachments === true && !codeEvent && !activityEvent && !toolEvent) {
|
|
673
|
+
try {
|
|
674
|
+
payload = (await attachFiles(payload, config, access, request, policy.destination)).payload
|
|
675
|
+
} catch (error) {
|
|
676
|
+
await recordCaptureDiagnostic(directory, credentials.client_id, "attachments", error, { missed: true })
|
|
677
|
+
// Keep conversation capture available if file storage is temporarily down.
|
|
678
|
+
console.error("Acent could not save the attached files.")
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (codeEvent || activityEvent) {
|
|
682
|
+
// Forward only bounded, redacted activity and validated edit records; never the raw host envelope.
|
|
683
|
+
const minimal = {
|
|
684
|
+
session_id: payload.session_id, conversation_id: payload.conversation_id,
|
|
685
|
+
conversationId: payload.conversationId, turn_id: payload.turn_id,
|
|
686
|
+
hook_event_name: payload.hook_event_name, acent_hook: payload.acent_hook,
|
|
687
|
+
acent_code_changes: payload.acent_code_changes,
|
|
688
|
+
acent_activity: payload.acent_activity,
|
|
689
|
+
}
|
|
690
|
+
for (const key of Object.keys(payload)) delete payload[key]
|
|
691
|
+
Object.assign(payload, minimal)
|
|
494
692
|
}
|
|
495
|
-
|
|
496
|
-
|
|
693
|
+
const events = codeEvent || activityEvent
|
|
694
|
+
? [
|
|
695
|
+
...changes.map(change => ({ ...payload, acent_activity: undefined, acent_code_changes: [change] })),
|
|
696
|
+
...toolActivities.map(record => ({ ...payload, acent_code_changes: undefined, acent_activity: [record] })),
|
|
697
|
+
]
|
|
698
|
+
: [payload]
|
|
699
|
+
stage = "queue"
|
|
700
|
+
await queueManagedCapture(config, directory, policy, events)
|
|
701
|
+
} catch (error) {
|
|
702
|
+
const reason = stage === "hook" && error instanceof SyntaxError ? { code: "invalid_hook" } : error
|
|
703
|
+
await recordCaptureDiagnostic(directory, credentials.client_id, stage, reason, { missed: true })
|
|
704
|
+
throw error
|
|
497
705
|
}
|
|
498
|
-
const events = codeEvent || activityEvent
|
|
499
|
-
? [
|
|
500
|
-
...changes.map(change => ({ ...payload, acent_activity: undefined, acent_code_changes: [change] })),
|
|
501
|
-
...toolActivities.map(record => ({ ...payload, acent_code_changes: undefined, acent_activity: [record] })),
|
|
502
|
-
]
|
|
503
|
-
: [payload]
|
|
504
|
-
await queueManagedCapture(config, directory, policy, events)
|
|
505
706
|
return drain(config, directory)
|
|
506
707
|
}
|
|
507
708
|
if (config.command === "flush") {
|
|
@@ -524,6 +725,10 @@ export async function main(args = process.argv.slice(2), eventText) {
|
|
|
524
725
|
}),
|
|
525
726
|
})
|
|
526
727
|
await unlink(file)
|
|
728
|
+
if (saved.client_id) {
|
|
729
|
+
await rm(captureStatusPath(directory, saved.client_id), { force: true })
|
|
730
|
+
await rm(captureDiagnosticDirectory(directory, saved.client_id), { recursive: true, force: true })
|
|
731
|
+
}
|
|
527
732
|
await rm(join(directory, "managed-capture"), {recursive:true, force:true})
|
|
528
733
|
await rm(join(directory, "managed-queue"), {recursive:true, force:true})
|
|
529
734
|
await rm(join(directory, "paired-capture"), {recursive:true, force:true})
|
|
@@ -533,7 +738,19 @@ export async function main(args = process.argv.slice(2), eventText) {
|
|
|
533
738
|
for (const name of await readdir(join(directory, "queue")))
|
|
534
739
|
await unlink(join(directory, "queue", name))
|
|
535
740
|
})
|
|
536
|
-
throw new Error("Use connect, collect, flush, or disconnect.")
|
|
741
|
+
throw new Error("Use connect, collect, flush, status, or disconnect.")
|
|
742
|
+
}
|
|
743
|
+
export async function recordBoundHookFailure(args, code) {
|
|
744
|
+
try {
|
|
745
|
+
const config = await boundConfig(["collect", ...args])
|
|
746
|
+
const directory = configDirectory(config)
|
|
747
|
+
const grant = await readCredentials(directory)
|
|
748
|
+
if (grant.client_id && !grant.client_id.startsWith("ac_private_client_") &&
|
|
749
|
+
!grant.captureBlocked && grant.scope?.split(" ").includes("conversation:write"))
|
|
750
|
+
await recordCaptureDiagnostic(directory, grant.client_id, "hook", { code }, { missed: true })
|
|
751
|
+
} catch {
|
|
752
|
+
// A hook with no usable grant has no private connection diagnostics to update.
|
|
753
|
+
}
|
|
537
754
|
}
|
|
538
755
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
539
756
|
main().catch((error) => {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process"
|
|
3
3
|
import { fileURLToPath } from "node:url"
|
|
4
|
+
import { isAbsolute } from "node:path"
|
|
4
5
|
import { recordWorkspaceCall, workspaceInstructions } from "./antigravity-workspace.mjs"
|
|
6
|
+
import { bridgeLifecycle } from "./bridge-lifecycle.mjs"
|
|
5
7
|
const started = Date.now()
|
|
6
8
|
const event = process.argv[2]
|
|
7
9
|
let output = event === "PreToolUse" ? { decision: "allow" } : {}
|
|
@@ -15,6 +17,16 @@ try {
|
|
|
15
17
|
payload.acent_hook = event
|
|
16
18
|
if (!["PreInvocation", "PostInvocation", "Stop", "PreToolUse", "PostToolUse"].includes(payload.acent_hook)) throw new Error("Unknown Antigravity hook.")
|
|
17
19
|
if (event === "PreInvocation") output = workspaceInstructions(payload)
|
|
20
|
+
const folder = Array.isArray(payload.workspacePaths) && payload.workspacePaths.length === 1
|
|
21
|
+
? payload.workspacePaths[0] : undefined
|
|
22
|
+
if (typeof folder === "string" && isAbsolute(folder) && typeof payload.conversationId === "string") {
|
|
23
|
+
const bridgeOutput = await bridgeLifecycle({
|
|
24
|
+
tool: "Antigravity", args: ["--tool", "Antigravity"], folder,
|
|
25
|
+
session: payload.conversationId, payload, event,
|
|
26
|
+
}).catch(() => undefined)
|
|
27
|
+
if (bridgeOutput?.injectSteps) output.injectSteps = [...(output.injectSteps ?? []), ...bridgeOutput.injectSteps]
|
|
28
|
+
else if (bridgeOutput) output = bridgeOutput
|
|
29
|
+
}
|
|
18
30
|
if (event === "PreToolUse") {
|
|
19
31
|
await recordWorkspaceCall(payload).catch(() => console.error("Acent could not verify this workspace call."))
|
|
20
32
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { mkdir, readFile, rm, stat, unlink } from "node:fs/promises"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { atomicJson, boundConfig, configDirectory, request } from "./acent-connect.mjs"
|
|
5
|
+
import { isCodexGeneratedPrompt } from "./codex-capture.mjs"
|
|
6
|
+
|
|
7
|
+
const guidance = "Acent Bridge: for feature work, bug fixes, or behavioral verification, call acent_bridge_settings before investigating or editing. If automatic delegation is enabled, check candidates early and start an independent task within the approved sharing scope. If no review can run, report the reason before finishing. Honor a user request to work directly."
|
|
8
|
+
const reminder = "Acent Bridge: this turn edited the project with automatic delegation enabled, and no candidate check or delegation was observed. Before finishing, check the Bridge settings and eligible candidates and arrange an independent check if applicable. For small styling or copy edits, a user opt-out, unavailable candidates, or pending sharing approval, finish directly and report the applicable reason."
|
|
9
|
+
const edits = /^(?:apply_patch|Edit|MultiEdit|Write|NotebookEdit|write_to_file|replace_file_content|multi_replace_file_content|str_replace|str_replace_editor)$/i
|
|
10
|
+
const bridgeTool = /^(?:(?:mcp__acent(?:_acent)?__|mcp_acent_acent_|MCP:)?acent_bridge_)(?:candidates|start|refine|request_approval)$/
|
|
11
|
+
|
|
12
|
+
export function isBridgeContinuation(payload) {
|
|
13
|
+
return ["UserPromptSubmit", "beforeSubmitPrompt"].includes(payload.hook_event_name) &&
|
|
14
|
+
payload.prompt === reminder
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function observedTool(payload, tool, event) {
|
|
18
|
+
if (tool !== "Antigravity") {
|
|
19
|
+
if (event === "afterMCPExecution") {
|
|
20
|
+
return ["acent", "acent-acent", "acent_acent"].includes(payload.mcp_server_name)
|
|
21
|
+
? payload.tool_name : undefined
|
|
22
|
+
}
|
|
23
|
+
return payload.tool_name
|
|
24
|
+
}
|
|
25
|
+
const { name, args } = payload.toolCall ?? {}
|
|
26
|
+
if (name === "call_mcp_tool" && args?.ServerName === "acent_acent") {
|
|
27
|
+
if (args.ToolName === "acent_workspace") return args.Arguments?.tool
|
|
28
|
+
return args.ToolName
|
|
29
|
+
}
|
|
30
|
+
if (name === "mcp_acent_acent_acent_workspace") return args?.tool
|
|
31
|
+
return name
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function nativeContext(tool, event, payload) {
|
|
35
|
+
const model = payload.model ?? payload.model_name ?? payload.modelName
|
|
36
|
+
const modelKnown = typeof model === "string" && /^[\w][\w.:/-]{0,159}$/.test(model) &&
|
|
37
|
+
!/^(?:auto|default|unknown)$/i.test(model)
|
|
38
|
+
const context = modelKnown
|
|
39
|
+
? guidance + " Use the host-reported model ID " + model + " as currentModel for independent review or diagnosis."
|
|
40
|
+
: guidance
|
|
41
|
+
if (tool === "Cursor") return { additional_context: context }
|
|
42
|
+
if (tool === "Antigravity") return { injectSteps: [{ ephemeralMessage: context }] }
|
|
43
|
+
return { hookSpecificOutput: { hookEventName: event, additionalContext: context } }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function nativeReminder(tool) {
|
|
47
|
+
if (tool === "Cursor") return { followup_message: reminder }
|
|
48
|
+
return { decision: tool === "Antigravity" ? "continue" : "block", reason: reminder }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function automaticSetting(config, credentials) {
|
|
52
|
+
// The hook must not contend with capture for refresh-token rotation.
|
|
53
|
+
if (typeof credentials?.access_token !== "string" ||
|
|
54
|
+
!Number.isFinite(credentials.expiresAt) || credentials.expiresAt <= Date.now() + 30_000) return null
|
|
55
|
+
const settings = await request(config, "/api/external/bridge", {
|
|
56
|
+
headers: { Authorization: "Bearer " + credentials.access_token },
|
|
57
|
+
signal: AbortSignal.timeout(750),
|
|
58
|
+
}).catch(() => null)
|
|
59
|
+
return typeof settings?.automatic === "boolean" ? settings.automatic : null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function bridgeLifecycle({ tool, folder, session, payload, args, event }) {
|
|
63
|
+
if (process.env.ACENT_BRIDGE_WORKER === "1" || !folder || !session) return
|
|
64
|
+
const cursor = tool === "Cursor"
|
|
65
|
+
const antigravity = tool === "Antigravity"
|
|
66
|
+
const prompt = event === "UserPromptSubmit" || event === "beforeSubmitPrompt" ||
|
|
67
|
+
(event === "PreInvocation" && payload.invocationNum === 0)
|
|
68
|
+
const sessionStart = cursor && event === "sessionStart"
|
|
69
|
+
const stop = event === "Stop" || event === "stop"
|
|
70
|
+
const observed = event === "PostToolUse" || event === "postToolUse" || event === "afterMCPExecution"
|
|
71
|
+
const name = observed ? observedTool(payload, tool, event) ?? "" : ""
|
|
72
|
+
const attempted = bridgeTool.test(name)
|
|
73
|
+
const edited = event === "afterFileEdit" || edits.test(name)
|
|
74
|
+
if (!prompt && !sessionStart && !stop && !attempted && !edited) return
|
|
75
|
+
|
|
76
|
+
const config = await boundConfig(["flush", ...args, "--folder", folder])
|
|
77
|
+
if (config.general) return
|
|
78
|
+
const directory = configDirectory(config)
|
|
79
|
+
const credentialsPath = join(directory, "credentials.json")
|
|
80
|
+
if (!(await stat(credentialsPath).catch(() => null))?.isFile()) return
|
|
81
|
+
const stateDir = join(directory, "bridge-turns")
|
|
82
|
+
const key = createHash("sha256").update(JSON.stringify([
|
|
83
|
+
session, tool === "Codex" ? payload.turn_id ?? null : null,
|
|
84
|
+
])).digest("hex")
|
|
85
|
+
const file = join(stateDir, key + ".json")
|
|
86
|
+
const editsFile = file + ".edited"
|
|
87
|
+
const attemptsFile = file + ".attempted"
|
|
88
|
+
const removeState = () => Promise.all([file, editsFile, attemptsFile].map(path => rm(path, { force: true })))
|
|
89
|
+
if (sessionStart) return nativeContext(tool, event, payload)
|
|
90
|
+
|
|
91
|
+
if (prompt) {
|
|
92
|
+
if (isBridgeContinuation(payload) || (tool === "Codex" && isCodexGeneratedPrompt(payload.prompt))) return
|
|
93
|
+
const credentials = await readFile(credentialsPath, "utf8").then(JSON.parse)
|
|
94
|
+
const automatic = await automaticSetting(config, credentials)
|
|
95
|
+
await mkdir(stateDir, { mode: 0o700, recursive: true })
|
|
96
|
+
await removeState()
|
|
97
|
+
if (automatic === true) await atomicJson(file, { at: Date.now() })
|
|
98
|
+
if (!cursor && automatic !== false) return nativeContext(tool, event, payload)
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const state = await readFile(file, "utf8").then(JSON.parse).catch(() => null)
|
|
103
|
+
if (!state || Date.now() - state.at > 24 * 60 * 60 * 1000) {
|
|
104
|
+
if (stop && state) await removeState()
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (attempted || edited) {
|
|
108
|
+
await atomicJson(attempted ? attemptsFile : editsFile, true)
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
if (antigravity && !payload.fullyIdle) return
|
|
112
|
+
const [hasEdits, hasAttempt] = await Promise.all([editsFile, attemptsFile].map(path => stat(path).catch(() => null)))
|
|
113
|
+
// Only the first completion hook can claim the check for this turn.
|
|
114
|
+
if (!(await unlink(file).then(() => true).catch(() => false))) return
|
|
115
|
+
await Promise.all([editsFile, attemptsFile].map(path => rm(path, { force: true })))
|
|
116
|
+
if (payload.stop_hook_active || (cursor && (payload.status !== "completed" || payload.loop_count > 0)) ||
|
|
117
|
+
(antigravity && payload.terminationReason !== "model_stop")) return
|
|
118
|
+
if (hasEdits && !hasAttempt) return nativeReminder(tool)
|
|
119
|
+
}
|
package/acent/scripts/bridge.mjs
CHANGED
|
@@ -302,6 +302,7 @@ export const bridgeInstructions = [
|
|
|
302
302
|
"Handle straightforward copy or styling edits and dependent steps directly. Start additional automatic tasks only when each has a distinct, useful result. Keep one writer responsible for each shared contract, state machine, or business rule, even if the files are disjoint. Resolve shared design decisions before starting parallel implementation. If one task needs an earlier result, pass dependsOn or finish the prerequisite first. Use read-only review or diagnosis for independent work when writes need one owner.",
|
|
303
303
|
"Keep authorized production actions such as deploys, database migrations, and live payments or refunds with the coordinating agent. Use Bridge for independent review of the plan and verification of the result.",
|
|
304
304
|
"If automatic delegation is disabled, continue the task directly. If automatic delegation is enabled but no suitable candidate is available, continue work you can verify and state the specific reason the independent work did not run. Report only the reviews and checks that actually completed.",
|
|
305
|
+
"Before finishing eligible work, confirm the independent check ran or state why it could not run. If the host issues a completion reminder, handle it once and finish normally. Bridge workers do not start another delegation.",
|
|
305
306
|
"Get candidates for each task. Honor the user's selected model. For automatic selection, choose a model that fits the work and preserves review independence. Check any reported quota and avoid candidates with exhausted included quota for automatic selection, unless the user has approved that usage. Among similarly suitable candidates, prefer Grok in Cursor and Gemini in Antigravity. An external model such as Claude in Cursor may be selected when it better fits the task or when the preferred family is unavailable, within the user's usage and spending settings. Unknown quota does not indicate availability or exhaustion. Pass the selected model ID explicitly and start with concrete acceptance criteria.",
|
|
306
307
|
"For review, diagnosis, or refinement, use the host-reported current turn model as currentModel. Supply originModel only when the user is revisiting earlier work and its model is known. If earlier model metadata is missing, proceed with currentModel. In Codex, the Bridge tool hook can report the current model after a call. If Bridge returns origin_model_unverified and the hook reports a model, retry with that currentModel. Pass the same model inputs when starting the selected review. Never guess a model ID.",
|
|
307
308
|
"Before starting a task or refinement, gather the decisions, constraints, and evidence that affect the delegated work. Reuse current evidence and use Acent Decisions or Recall first if missing project history could change the work. Pass the relevant facts and any unresolved constraints in context on the initial request. For self-contained work, include the current facts the delegate needs.",
|
|
@@ -1346,6 +1347,11 @@ export function createBridge({
|
|
|
1346
1347
|
}
|
|
1347
1348
|
|
|
1348
1349
|
return async function call(name, args, selectedFolder, loadSettings) {
|
|
1350
|
+
const worker = process.env.ACENT_BRIDGE_WORKER === "1"
|
|
1351
|
+
if (worker && (name === "acent_bridge_start" ||
|
|
1352
|
+
(name === "acent_bridge_refine" && args.action === "start"))) {
|
|
1353
|
+
throw new Error("A Bridge worker cannot start another delegation.")
|
|
1354
|
+
}
|
|
1349
1355
|
if (!selectedFolder)
|
|
1350
1356
|
throw new Error("Open a single project folder before using Bridge.")
|
|
1351
1357
|
const folder = await realpath(selectedFolder)
|
|
@@ -1380,11 +1386,11 @@ export function createBridge({
|
|
|
1380
1386
|
if (name === "acent_bridge_settings") {
|
|
1381
1387
|
if (Object.keys(args).length)
|
|
1382
1388
|
throw new Error("Change Bridge settings from the project in Acent.")
|
|
1383
|
-
if (settings.automatic)
|
|
1389
|
+
if (settings.automatic && !worker)
|
|
1384
1390
|
void Promise.all(
|
|
1385
1391
|
settings.targets.map((tool) => getTarget(tool, folder))
|
|
1386
1392
|
)
|
|
1387
|
-
return { automatic: settings.automatic, targets: settings.targets }
|
|
1393
|
+
return { automatic: settings.automatic && !worker, targets: settings.targets }
|
|
1388
1394
|
}
|
|
1389
1395
|
if (name === "acent_bridge_candidates" || name === "acent_bridge_start") {
|
|
1390
1396
|
if (!["implement", "review", "diagnose"].includes(args.kind))
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
2
|
+
import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
|
|
5
|
+
const filename = /^[a-f0-9]{64}\.json$/
|
|
6
|
+
const requestId = /^(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?:[a-z0-9]+::){1,3}[a-z0-9]+-\d{6,}-[a-f0-9]+)$/i
|
|
7
|
+
const stages = new Set(["authorization", "policy", "hook", "prepare", "attachments", "queue", "upload"])
|
|
8
|
+
const knownCodes = new Set([
|
|
9
|
+
"invalid_token", "invalid_grant", "insufficient_scope", "capture_disabled",
|
|
10
|
+
"destination_changed", "prompt_pending", "invalid_packet", "invalid_capture",
|
|
11
|
+
"invalid_session", "capacity_exceeded", "subscription_required", "server_error",
|
|
12
|
+
"queue_full", "payload_too_large", "invalid_hook", "hook_timeout", "missing_session",
|
|
13
|
+
"lock_busy", "EACCES", "EPERM", "ENOSPC", "EROFS", "ENOENT", "EIO",
|
|
14
|
+
"ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT",
|
|
15
|
+
"UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET",
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
export function captureDiagnosticDirectory(directory, clientId) {
|
|
19
|
+
const key = createHash("sha256").update(clientId).digest("hex")
|
|
20
|
+
return join(directory, "managed-capture-diagnostics", key)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function recordCaptureDiagnostic(directory, clientId, stage, error, { missed = false } = {}) {
|
|
24
|
+
if (!stages.has(stage)) return
|
|
25
|
+
try {
|
|
26
|
+
const root = captureDiagnosticDirectory(directory, clientId)
|
|
27
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
28
|
+
const candidate = error?.code ?? error?.cause?.code
|
|
29
|
+
const code = knownCodes.has(candidate) ? candidate
|
|
30
|
+
: error?.name === "TimeoutError" || error?.name === "AbortError" ? "timeout"
|
|
31
|
+
: error?.status ? "http_error" : "unknown"
|
|
32
|
+
const entry = { timestamp: new Date().toISOString(), stage, code }
|
|
33
|
+
if (missed) entry.missed = true
|
|
34
|
+
if (Number.isInteger(error?.status) && error.status >= 100 && error.status <= 599)
|
|
35
|
+
entry.status = error.status
|
|
36
|
+
if (typeof error?.requestId === "string" && error.requestId.length <= 100 && requestId.test(error.requestId))
|
|
37
|
+
entry.requestId = error.requestId
|
|
38
|
+
if (["authorization", "validate", "turn_policy", "encryption", "save_evidence", "save_conversation"].includes(error?.serverStage))
|
|
39
|
+
entry.serverStage = error.serverStage
|
|
40
|
+
if (["conflict", "constraint", "permission", "database", "unknown"].includes(error?.serverReason))
|
|
41
|
+
entry.serverReason = error.serverReason
|
|
42
|
+
// Keep the latest occurrence of each failure, with bounded local retention.
|
|
43
|
+
const signature = createHash("sha256").update(JSON.stringify([
|
|
44
|
+
stage, code, entry.status, entry.serverStage, entry.serverReason, missed,
|
|
45
|
+
])).digest("hex")
|
|
46
|
+
const file = join(root, signature + ".json")
|
|
47
|
+
const temp = join(root, signature + "." + randomUUID() + ".tmp")
|
|
48
|
+
try {
|
|
49
|
+
await writeFile(temp, JSON.stringify(entry), { mode: 0o600, flag: "wx" })
|
|
50
|
+
await rename(temp, file)
|
|
51
|
+
} finally {
|
|
52
|
+
await rm(temp, { force: true })
|
|
53
|
+
}
|
|
54
|
+
const files = (await readdir(root, { withFileTypes: true }))
|
|
55
|
+
.filter(item => item.isFile() && filename.test(item.name))
|
|
56
|
+
if (files.length > 96) {
|
|
57
|
+
const entries = await Promise.all(files.map(async item => {
|
|
58
|
+
const name = join(root, item.name)
|
|
59
|
+
return { name, at: (await stat(name).catch(() => null))?.mtimeMs ?? 0 }
|
|
60
|
+
}))
|
|
61
|
+
entries.sort((a, b) => b.at - a.at)
|
|
62
|
+
await Promise.all(entries.slice(96).map(item => rm(item.name, { force: true })))
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
// Diagnostics must not stop capture when the local disk is unavailable.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -81,6 +81,15 @@ export function capturePayload(event, code, activity) {
|
|
|
81
81
|
changeIds: [],
|
|
82
82
|
}
|
|
83
83
|
)
|
|
84
|
+
// Bridge can report multiple statuses or batches for one operation. Link
|
|
85
|
+
// edits by their explicit change IDs and give each activity its own call ID.
|
|
86
|
+
if (event.hook_event_name === "AcentBridge" && result.acent_activity) {
|
|
87
|
+
result.acent_activity = result.acent_activity.map((item) => {
|
|
88
|
+
if (typeof item?.callId !== "string" || !/^bridge:[a-f0-9-]{36}:[a-z_]+$/.test(item.callId) ||
|
|
89
|
+
typeof item.id !== "string" || !/^[a-f0-9]{64}$/.test(item.id)) return item
|
|
90
|
+
return { ...item, callId: item.callId + ":" + item.id }
|
|
91
|
+
})
|
|
92
|
+
}
|
|
84
93
|
if (code && Array.isArray(event.acent_code_changes))
|
|
85
94
|
result.acent_code_changes = event.acent_code_changes
|
|
86
95
|
if (code && Array.isArray(event.acent_activities))
|
|
@@ -7,6 +7,10 @@ import { join } from "node:path"
|
|
|
7
7
|
const generatedHeader =
|
|
8
8
|
/^This is an app-generated request\b[^\n]{0,500}The user did not write this message\.(?:\s|$)/i
|
|
9
9
|
|
|
10
|
+
export function isCodexGeneratedPrompt(prompt) {
|
|
11
|
+
return typeof prompt === "string" && generatedHeader.test(prompt.trimStart())
|
|
12
|
+
}
|
|
13
|
+
|
|
10
14
|
export async function captureCodexEvent(payload, directory) {
|
|
11
15
|
const session = payload.session_id
|
|
12
16
|
if (typeof session !== "string" || !session) return false
|
|
@@ -22,7 +26,7 @@ export async function captureCodexEvent(payload, directory) {
|
|
|
22
26
|
if (
|
|
23
27
|
typeof prompt !== "string" ||
|
|
24
28
|
!prompt.trim() ||
|
|
25
|
-
|
|
29
|
+
isCodexGeneratedPrompt(prompt)
|
|
26
30
|
) {
|
|
27
31
|
await rm(marker, { force: true })
|
|
28
32
|
return false
|
package/acent/scripts/hook.mjs
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { isAbsolute } from "node:path"
|
|
3
|
-
import { main } from "./acent-connect.mjs"
|
|
3
|
+
import { main, recordBoundHookFailure } from "./acent-connect.mjs"
|
|
4
|
+
import { bridgeLifecycle, isBridgeContinuation } from "./bridge-lifecycle.mjs"
|
|
4
5
|
// Use the documented hook cwd, never a plugin cache folder or another binding.
|
|
6
|
+
const args = process.argv.slice(2)
|
|
7
|
+
const bridgeEventIndex = args.indexOf("--bridge-event")
|
|
8
|
+
const bridgeEvent = bridgeEventIndex === -1 ? undefined : args.splice(bridgeEventIndex, 2)[1]
|
|
5
9
|
let text = ""
|
|
6
10
|
try {
|
|
7
11
|
for await (const chunk of process.stdin) {
|
|
@@ -10,6 +14,8 @@ try {
|
|
|
10
14
|
throw new Error("Hook event exceeds 2 MiB")
|
|
11
15
|
}
|
|
12
16
|
const payload = JSON.parse(text)
|
|
17
|
+
// A host may dispatch the completion reminder as a new prompt event.
|
|
18
|
+
if (isBridgeContinuation(payload)) process.exit(0)
|
|
13
19
|
const cursor = process.argv.includes("Cursor")
|
|
14
20
|
const antigravity = process.argv.includes("Antigravity")
|
|
15
21
|
const roots = cursor ? payload.workspace_roots : antigravity ? payload.workspacePaths : undefined
|
|
@@ -20,11 +26,20 @@ try {
|
|
|
20
26
|
: payload.cwd
|
|
21
27
|
if (folder != null && folder !== "" && (typeof folder !== "string" || !isAbsolute(folder)))
|
|
22
28
|
throw new Error("Hook has an invalid working folder")
|
|
23
|
-
const session = payload.session_id
|
|
24
|
-
|
|
29
|
+
const session = [payload.session_id, payload.conversation_id, payload.conversationId]
|
|
30
|
+
.find(value => typeof value === "string" && value.trim())
|
|
31
|
+
if (!session) {
|
|
32
|
+
if (folder && !bridgeEvent) await recordBoundHookFailure([...args, "--folder", folder], "missing_session")
|
|
25
33
|
throw new Error("Hook is missing a conversation identifier")
|
|
34
|
+
}
|
|
35
|
+
if (!antigravity) {
|
|
36
|
+
const event = bridgeEvent ?? payload.hook_event_name
|
|
37
|
+
const tool = args[args.indexOf("--tool") + 1]
|
|
38
|
+
const bridgeOutput = await bridgeLifecycle({ tool, folder, session, payload, args, event }).catch(() => undefined)
|
|
39
|
+
if (bridgeOutput) process.stdout.write(JSON.stringify(bridgeOutput) + "\n")
|
|
40
|
+
}
|
|
26
41
|
// The host delivers this context to the turn that made the Bridge call.
|
|
27
|
-
if (process.argv.includes("Codex") &&
|
|
42
|
+
if (process.env.ACENT_BRIDGE_WORKER !== "1" && process.argv.includes("Codex") &&
|
|
28
43
|
payload.hook_event_name === "PostToolUse" &&
|
|
29
44
|
/^mcp__acent__acent_bridge_[a-z_]+$/.test(payload.tool_name ?? "") &&
|
|
30
45
|
typeof payload.model === "string" && /^[\w][\w.:/-]{0,159}$/.test(payload.model) &&
|
|
@@ -34,7 +49,7 @@ try {
|
|
|
34
49
|
additionalContext: `Codex reports ${payload.model} as the coordinating model for this turn. Use this ID as currentModel for Bridge review, diagnosis, and refinement in this turn. If candidate selection could not verify a reference model, retry with this currentModel. Use it for this turn's direct-work row in the Acent Bridge report.`,
|
|
35
50
|
} }) + "\n")
|
|
36
51
|
}
|
|
37
|
-
await main(["collect", ...
|
|
52
|
+
if (!bridgeEvent) await main(["collect", ...args,
|
|
38
53
|
...(folder ? ["--folder", folder] : ["--general"])], text)
|
|
39
54
|
|
|
40
55
|
} catch (error) {
|
|
@@ -479,11 +479,20 @@ async function handleLine(line) {
|
|
|
479
479
|
|
|
480
480
|
// Keep reading while a tool waits for an elicitation response on this same pipe.
|
|
481
481
|
const active = new Set()
|
|
482
|
+
// Retry previously approved queued captures while the host connection is open.
|
|
483
|
+
// The shared drain lock and the current server policy still govern every upload.
|
|
484
|
+
const captureRetry = process.env.ACENT_BRIDGE_WORKER === "1" ? null : setInterval(() => {
|
|
485
|
+
const config = activeConfig
|
|
486
|
+
if (!config.bindingKnown) return
|
|
487
|
+
void drain(config, configDirectory(config)).catch(() => {})
|
|
488
|
+
}, 120_000)
|
|
489
|
+
captureRetry?.unref()
|
|
482
490
|
for await (const line of lines) {
|
|
483
491
|
const task = handleLine(line)
|
|
484
492
|
active.add(task)
|
|
485
493
|
void task.finally(() => active.delete(task))
|
|
486
494
|
}
|
|
495
|
+
if (captureRetry) clearInterval(captureRetry)
|
|
487
496
|
rootRequests.close()
|
|
488
497
|
questions.close()
|
|
489
498
|
await Promise.allSettled(active)
|
|
@@ -15,6 +15,7 @@ Use the Acent Bridge MCP tools in a session with one local project folder open.
|
|
|
15
15
|
- Keep straightforward copy or styling edits and dependent steps with the coordinating agent. Start additional automatic tasks only when each has a distinct, useful result. Give each shared contract, state machine, or business rule one writer, even when it spans separate files. Finish a prerequisite first or use `dependsOn` when later work needs its result. Use read-only review or diagnosis for independent work when writes need one owner.
|
|
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
|
+
- Before finishing eligible work, confirm that the independent check ran or explain why it could not run. If the host issues a completion reminder, handle this once and finish normally. Bridge worker sessions carry out the assigned task without starting another delegation.
|
|
18
19
|
- 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
20
|
- 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
21
|
- 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.
|
package/antigravity/plugin.json
CHANGED
|
@@ -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.3.
|
|
5
|
+
"version": "1.3.2",
|
|
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
package/scripts/acent.mjs
CHANGED
|
@@ -71,7 +71,7 @@ export async function main(
|
|
|
71
71
|
if (args.includes("--help") || args[0] === "help") {
|
|
72
72
|
console.log(
|
|
73
73
|
[
|
|
74
|
-
"Usage\n\n acent [connect|install|update|disconnect|flush]\n [--tool codex|claude|cursor|antigravity] [--folder PATH]",
|
|
74
|
+
"Usage\n\n acent [connect|install|update|disconnect|flush|status]\n [--tool codex|claude|cursor|antigravity] [--folder PATH]",
|
|
75
75
|
"Install\n\n acent install\n acent install --all\n\n Install for one tool, or prepare all four supported tools with --all.\n After installation, follow the printed steps and ask your agent: Connect Acent.",
|
|
76
76
|
"Connect\n\n acent connect\n\n Run in your project folder. Running acent without a command also starts connection.",
|
|
77
77
|
"Update\n\n acent update\n acent update --all\n\n Update one tool, or all plugins installed by this CLI.\n Existing project connections are kept.",
|
|
@@ -83,9 +83,9 @@ export async function main(
|
|
|
83
83
|
const command =
|
|
84
84
|
!args.length || args[0].startsWith("--") ? "connect" : args.shift()
|
|
85
85
|
if (
|
|
86
|
-
!["connect", "install", "update", "disconnect", "flush"].includes(command)
|
|
86
|
+
!["connect", "install", "update", "disconnect", "flush", "status"].includes(command)
|
|
87
87
|
)
|
|
88
|
-
throw new Error("Use connect, install, update, disconnect, or
|
|
88
|
+
throw new Error("Use connect, install, update, disconnect, flush, or status")
|
|
89
89
|
const settings = {}
|
|
90
90
|
let all = false
|
|
91
91
|
for (let i = 0; i < args.length; i++) {
|