@cirtium/acent-connect 1.3.0 → 1.3.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "1.3.0",
3
+ "version": "1.3.3",
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.3.0",
3
+ "version": "1.3.3",
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.3.0",
3
+ "version": "1.3.3",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "author": {
6
6
  "name": "Cirtium"
@@ -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
- { status: response.status, code: body.error }
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_")) return
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
- if (!files.length) return
254
- const access = await token(config, directory)
255
- const headers = { Authorization: "Bearer " + access }
256
- const policy = await request(config, "/api/external/managed", { headers })
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
- // A code event can race its prompt upload. Retry it after queued prompts;
263
- // never let an early 409 permanently block the request behind it.
264
- for (const file of files) {
265
- const payload = JSON.parse(
266
- await readFile(join(queue, file), "utf8")
267
- )
268
- // An outbox entry belongs to the project approved at capture time.
269
- if (payload.acent_destination !== policy.destination) continue
270
- try {
271
- const filtered = capturePayload(payload, policy.code === true, policy.activity === true)
272
- if ((payload.acent_code_changes || payload.acent_activity) &&
273
- !filtered.acent_code_changes?.length && !filtered.acent_activity?.length) {
274
- await unlink(join(queue, file))
275
- continue
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
- await request(config, "/api/external/managed", {
278
- method: "POST", headers: { ...headers, "Content-Type": "application/json" },
279
- body: JSON.stringify({ id: hash(file), destination: policy.destination, at: Number(file.split("-")[0]), payload: filtered }),
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
- if (error.code === "destination_changed") continue
288
- if (error.code === "capture_disabled") {
289
- await unlink(join(queue, file))
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
- if (error.code === "invalid_token" || error.code === "insufficient_scope") {
293
- const credentials = JSON.parse(
294
- await readFile(join(directory, "credentials.json"), "utf8")
295
- )
296
- await atomicJson(join(directory, "credentials.json"), {
297
- ...credentials,
298
- captureBlocked: true,
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
- await rm(join(directory, "code-capture"), { recursive: true, force: true })
302
- for (const queued of await readdir(queue))
303
- await unlink(join(queue, queued))
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
- throw error
467
+ await unlink(join(queue, file))
306
468
  }
307
- await unlink(join(queue, file))
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 > 500) return "Capture queue is full."
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) > 32 * 1024 * 1024)
338
- return "Capture queue exceeds 32 MiB."
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
- await drain(config, directory)
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
- const content =
437
- eventText ??
438
- (config.file
439
- ? await readFile(config.file, "utf8")
440
- : await new Promise((resolve, reject) => {
441
- let text = ""
442
- process.stdin.setEncoding("utf8")
443
- process.stdin.on("data", (chunk) => {
444
- text += chunk
445
- if (Buffer.byteLength(text) > 2 * 1024 * 1024) {
446
- process.stdin.destroy()
447
- reject(new Error("Event exceeds 2 MiB."))
448
- }
449
- })
450
- process.stdin.on("end", () => resolve(text))
451
- process.stdin.on("error", reject)
452
- }))
453
- if (Buffer.byteLength(content) > 2 * 1024 * 1024)
454
- throw new Error("Event exceeds 2 MiB.")
455
- const captureDirectory = join(directory, "managed-capture", hash(credentials.client_id))
456
- const access = await accessToken(config, directory)
457
- const policy = await request(config, "/api/external/managed", { headers: { Authorization: "Bearer " + access } })
458
- if (!policy.enabled) return
459
- const code = policy.code === true
460
- const activity = policy.activity === true
461
- let payload = JSON.parse(content)
462
- const hook = payload.acent_hook || payload.hook_event_name
463
- const toolEvent = isToolActivityHook(hook)
464
- if ((toolEvent && !activity && !code) || (hook === "afterFileEdit" && !code)) return
465
- if (config.tool === "Codex" && !(await captureCodexEvent(payload, captureDirectory))) return
466
- if (config.tool === "Antigravity" && toolEvent) {
467
- if (code) await captureAntigravityEvent(payload, captureDirectory).catch(() => {
468
- payload.acent_request = null
469
- console.error("Acent request link unavailable.")
470
- })
471
- }
472
- const codeEvent = code && await captureCodeChanges(payload, config, captureDirectory)
473
- const activityEvent = activity && await captureActivity(payload, config, captureDirectory, code)
474
- const changes = code ? payload.acent_code_changes ?? [] : []
475
- const toolActivities = activity ? payload.acent_activity ?? [] : []
476
- if ((codeEvent || activityEvent || toolEvent) && !changes.length && !toolActivities.length) return
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
- if (codeEvent || activityEvent) {
487
- // Forward only bounded, redacted activity and validated edit records; never the raw host envelope.
488
- const minimal = {
489
- session_id: payload.session_id, conversation_id: payload.conversation_id,
490
- conversationId: payload.conversationId, turn_id: payload.turn_id,
491
- hook_event_name: payload.hook_event_name, acent_hook: payload.acent_hook,
492
- acent_code_changes: payload.acent_code_changes,
493
- acent_activity: payload.acent_activity,
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
- for (const key of Object.keys(payload)) delete payload[key]
496
- Object.assign(payload, minimal)
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
  }