@cirtium/acent-connect 0.3.2 → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acent",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
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": "0.3.2",
3
+ "version": "0.4.0",
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": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
5
5
  "author": {
6
6
  "name": "Cirtium"
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createPairing, encryptCapture, privateGrant } from "./encrypted-capture.mjs"
2
3
  import { captureActivity } from "./capture-activity.mjs"
3
4
  /** Local connection/capture adapter. No AI calls; credentials never go to stdout. */
4
5
  import { captureCodeChanges } from "./capture-code-changes.mjs"
@@ -235,6 +236,7 @@ async function token(config, directory) {
235
236
  }),
236
237
  })
237
238
  await atomicJson(file, {
239
+ ...saved,
238
240
  ...refreshed,
239
241
  client_id: saved.client_id,
240
242
  expiresAt: Date.now() + refreshed.expires_in * 1000,
@@ -243,7 +245,10 @@ async function token(config, directory) {
243
245
  }
244
246
  export async function drain(config, directory) {
245
247
  return lock(directory, async () => {
246
- const files = (await readdir(join(directory, "queue")))
248
+ const grant = await readCredentials(directory)
249
+ const encrypted = privateGrant(grant.client_id)
250
+ const queue = encrypted ? join(directory, "private-queue", hash(grant.client_id)) : join(directory, "queue")
251
+ const files = (await readdir(queue).catch(error => { if (error.code === "ENOENT") return []; throw error }))
247
252
  .filter((file) => file.endsWith(".json"))
248
253
  .sort()
249
254
  if (!files.length) return
@@ -253,10 +258,15 @@ export async function drain(config, directory) {
253
258
  // never let an early 409 permanently block the request behind it.
254
259
  for (const file of files) {
255
260
  const payload = JSON.parse(
256
- await readFile(join(directory, "queue", file), "utf8")
261
+ await readFile(join(queue, file), "utf8")
257
262
  )
258
263
  try {
259
- await request(config, "/api/external/collect", {
264
+ if (encrypted) {
265
+ await request(config, "/api/external/encrypted", {
266
+ method: "POST", headers: { Authorization: "Bearer " + access, "Content-Type": "application/json" },
267
+ body: JSON.stringify(payload),
268
+ })
269
+ } else await request(config, "/api/external/collect", {
260
270
  method: "POST",
261
271
  headers: {
262
272
  Authorization: `Bearer ${access}`,
@@ -281,13 +291,14 @@ export async function drain(config, directory) {
281
291
  ...credentials,
282
292
  captureBlocked: true,
283
293
  })
294
+ if (encrypted) await rm(join(directory, "paired-capture", hash(grant.client_id)), {recursive:true, force:true})
284
295
  await rm(join(directory, "code-capture"), { recursive: true, force: true })
285
- for (const queued of await readdir(join(directory, "queue")))
286
- await unlink(join(directory, "queue", queued))
296
+ for (const queued of await readdir(queue))
297
+ await unlink(join(queue, queued))
287
298
  }
288
299
  throw error
289
300
  }
290
- await unlink(join(directory, "queue", file))
301
+ await unlink(join(queue, file))
291
302
  }
292
303
  })
293
304
  }
@@ -307,17 +318,20 @@ export async function connect(config, directory, open = openBrowser) {
307
318
  await mkdir(connectionDirectory, { recursive: true, mode: 0o700 })
308
319
  const completed = await lock(connectionDirectory, async () => {
309
320
  const verifier = random()
321
+ const pairing = await createPairing()
310
322
  const started = await request(config, "/api/external/setup/start", {
311
323
  method: "POST", headers: { "Content-Type": "application/json" },
312
- body: JSON.stringify({ tool: config.tool, folder: config.folder, challenge: createHash("sha256").update(verifier).digest("base64url") }),
324
+ body: JSON.stringify({ tool: config.tool, folder: config.folder, encrypted: true, challenge: createHash("sha256").update(verifier).digest("base64url") }),
313
325
  })
314
326
  const url = new URL(started.authorization_url)
315
327
  if (url.origin !== config.server || url.pathname !== "/oauth/authorize" || !url.searchParams.has("setup"))
316
328
  throw new Error("Acent returned an invalid connection address.")
329
+ url.searchParams.set("device", pairing.publicKey)
330
+ url.hash = new URLSearchParams({ pairing: pairing.proof }).toString()
317
331
  const expires = Math.min(Date.parse(started.expires_at), Date.now() + 15 * 60_000)
318
332
  if (!Number.isFinite(expires) || expires <= Date.now() || !started.poll_token || !started.client_id)
319
333
  throw new Error("Acent returned an invalid connection session.")
320
- console.error(`Open this address to connect Acent:\n${url}`)
334
+ if (open === openBrowser) console.error(`Open this address to connect Acent:\n${url}`)
321
335
  open(url)
322
336
  const pollBody = JSON.stringify({ poll_token: started.poll_token, verifier })
323
337
  while (Date.now() < expires) {
@@ -327,10 +341,17 @@ export async function connect(config, directory, open = openBrowser) {
327
341
  if (tokens.status === "cancelled") throw new Error("Connection was cancelled.")
328
342
  if (tokens.status === "issued") {
329
343
  if (!tokens.access_token || !tokens.refresh_token) throw new Error("Connection response was incomplete. Request a new link.")
344
+ if (!privateGrant(started.client_id)) throw new Error("Server does not support encrypted capture.")
345
+ let captureKey, project
346
+ if (tokens.scope?.split(" ").includes("conversation:write")) {
347
+ const wrapped = await request(config, "/api/external/encrypted", { headers: { Authorization: "Bearer " + tokens.access_token } })
348
+ project = wrapped.project
349
+ captureKey = pairing.unwrap(wrapped.wrapped)
350
+ }
330
351
  let saved = false
331
352
  for (let attempt = 0; attempt < 200 && !saved; attempt++) {
332
353
  saved = await lock(directory, () => atomicJson(join(directory, "credentials.json"), {
333
- ...tokens, client_id: started.client_id, expiresAt: Date.now() + tokens.expires_in * 1000,
354
+ ...tokens, captureKey, project, client_id: started.client_id, expiresAt: Date.now() + tokens.expires_in * 1000,
334
355
  }))
335
356
  if (!saved) await new Promise(resolve => setTimeout(resolve, 100))
336
357
  }
@@ -391,19 +412,20 @@ export async function main(args = process.argv.slice(2), eventText) {
391
412
  }))
392
413
  if (Buffer.byteLength(content) > 2 * 1024 * 1024)
393
414
  throw new Error("Event exceeds 2 MiB.")
415
+ const captureDirectory = privateGrant(credentials.client_id) ? join(directory, "paired-capture", hash(credentials.client_id)) : directory
394
416
  const payload = JSON.parse(content)
395
- if (config.tool === "Codex" && !(await captureCodexEvent(payload, directory))) return
417
+ if (config.tool === "Codex" && !(await captureCodexEvent(payload, captureDirectory))) return
396
418
  const toolEvent = ["PreToolUse", "PostToolUse", "PostToolUseFailure"].includes(payload.acent_hook || payload.hook_event_name)
397
419
  if (config.tool === "Antigravity" && toolEvent) {
398
- await captureAntigravityEvent(payload, directory).catch(error => {
420
+ await captureAntigravityEvent(payload, captureDirectory).catch(error => {
399
421
  payload.acent_request = null
400
422
  console.error(`Acent request link unavailable: ${error.message}`)
401
423
  })
402
424
  }
403
- const codeEvent = await captureCodeChanges(payload, config, directory)
404
- const activityEvent = await captureActivity(payload, config, directory)
425
+ const codeEvent = await captureCodeChanges(payload, config, captureDirectory)
426
+ const activityEvent = await captureActivity(payload, config, captureDirectory)
405
427
  if ((codeEvent || activityEvent) && !payload.acent_code_changes?.length && !payload.acent_activity?.length) return
406
- if (config.tool === "Antigravity" && !codeEvent && !activityEvent && !(await captureAntigravityEvent(payload, directory))) return
428
+ if (config.tool === "Antigravity" && !codeEvent && !activityEvent && !(await captureAntigravityEvent(payload, captureDirectory))) return
407
429
  if (codeEvent || activityEvent) {
408
430
  // Forward only bounded, redacted activity and validated edit records; never the raw host envelope.
409
431
  const minimal = {
@@ -424,24 +446,30 @@ export async function main(args = process.argv.slice(2), eventText) {
424
446
  : [payload]
425
447
  if (events.some(event => Buffer.byteLength(JSON.stringify(event)) > 2 * 1024 * 1024))
426
448
  throw new Error("Collected event exceeds 2 MiB.")
427
- const files = await readdir(join(directory, "queue"))
428
- if (files.length + events.length > 500)
429
- throw new Error(
430
- "Capture queue is full. Reconnect or drain queued events before saving more."
431
- )
432
- const sizes = await Promise.all(
433
- files.map((file) => stat(join(directory, "queue", file)))
434
- )
435
- if (
436
- sizes.reduce((sum, file) => sum + file.size, 0) +
437
- events.reduce((sum, event) => sum + Buffer.byteLength(JSON.stringify(event)), 0) >
438
- 32 * 1024 * 1024
439
- )
440
- throw new Error(
441
- "Capture queue exceeds 32 MiB. Drain it before saving more."
442
- )
443
- for (const event of events) await atomicJson(
444
- join(directory, "queue", `${Date.now()}-${random()}.json`), event
449
+ const encrypted = privateGrant(credentials.client_id)
450
+ const queue = encrypted ? join(directory, "private-queue", hash(credentials.client_id)) : join(directory, "queue")
451
+ await mkdir(queue, { recursive: true, mode: 0o700 })
452
+ const packets = encrypted ? events.map(event => encryptCapture(event, credentials, config.tool)) : events
453
+ const eventBytes = packets.reduce((sum, event) => sum + Buffer.byteLength(JSON.stringify(event)), 0)
454
+ async function capacityError() {
455
+ const files = (await readdir(queue)).filter(file => file.endsWith(".json"))
456
+ if (files.length + events.length > 500) return "Capture queue is full."
457
+ const sizes = await Promise.all(files.map(file =>
458
+ stat(join(queue, file)).catch(error => {
459
+ if (error.code === "ENOENT") return { size: 0 }
460
+ throw error
461
+ })
462
+ ))
463
+ if (sizes.reduce((sum, file) => sum + file.size, eventBytes) > 32 * 1024 * 1024)
464
+ return "Capture queue exceeds 32 MiB."
465
+ }
466
+ if (await capacityError()) {
467
+ await drain(config, directory)
468
+ const error = await capacityError()
469
+ if (error) throw new Error(error + " Retry after pending events are sent.")
470
+ }
471
+ for (const event of packets) await atomicJson(
472
+ join(queue, `${Date.now()}-${random()}.json`), event
445
473
  )
446
474
  return drain(config, directory)
447
475
  }
@@ -465,6 +493,8 @@ export async function main(args = process.argv.slice(2), eventText) {
465
493
  }),
466
494
  })
467
495
  await unlink(file)
496
+ await rm(join(directory, "paired-capture"), {recursive:true, force:true})
497
+ await rm(join(directory, "private-queue"), { recursive: true, force: true })
468
498
  await rm(join(directory, "code-capture"), { recursive: true, force: true })
469
499
  // Queued conversations are local private data. Explicit disconnect removes them.
470
500
  for (const name of await readdir(join(directory, "queue")))
@@ -0,0 +1,170 @@
1
+ import {
2
+ createCipheriv,
3
+ createHash,
4
+ generateKeyPair,
5
+ privateDecrypt,
6
+ randomBytes,
7
+ timingSafeEqual,
8
+ } from "node:crypto"
9
+ import { promisify } from "node:util"
10
+
11
+ export async function createPairing() {
12
+ const pair = await promisify(generateKeyPair)("rsa", { modulusLength: 3072 })
13
+ const challenge = randomBytes(32)
14
+ return {
15
+ proof: challenge.toString("base64url"),
16
+ publicKey: pair.publicKey
17
+ .export({ type: "spki", format: "der" })
18
+ .toString("base64url"),
19
+ unwrap(ciphertext) {
20
+ const key = privateDecrypt(
21
+ { key: pair.privateKey, oaepHash: "sha256" },
22
+ Buffer.from(ciphertext, "base64")
23
+ )
24
+ if (key.length !== 64 || !timingSafeEqual(key.subarray(0, 32), challenge))
25
+ throw new Error("Device pairing failed verification.")
26
+ return key.subarray(32).toString("base64")
27
+ },
28
+ }
29
+ }
30
+
31
+ // Encode only host fields consumed by the conversation and activity readers.
32
+ const fields = [
33
+ "session_id",
34
+ "conversation_id",
35
+ "conversationId",
36
+ "turn_id",
37
+ "prompt_id",
38
+ "generation_id",
39
+ "acent_turn_id",
40
+ "model",
41
+ "modelName",
42
+ "hook_event_name",
43
+ "event",
44
+ "messages",
45
+ "prompt",
46
+ "last_assistant_message",
47
+ "text",
48
+ "message",
49
+ "response",
50
+ "num_turns",
51
+ "result",
52
+ "acent_activity",
53
+ "acent_code_changes",
54
+ "acent_activities",
55
+ ]
56
+
57
+ export function encryptCapture(event, credentials, source) {
58
+ const key = Buffer.from(credentials.captureKey ?? "", "base64")
59
+ if (key.length !== 32)
60
+ throw new Error("Encrypted capture requires a paired key.")
61
+ const payload = Object.fromEntries(
62
+ fields
63
+ .filter((field) => field in event)
64
+ .map((field) => [field, event[field]])
65
+ )
66
+ const iv = randomBytes(12)
67
+ const cipher = createCipheriv("aes-256-gcm", key, iv)
68
+ cipher.setAAD(Buffer.from("acent:external:v1:" + credentials.client_id))
69
+ const body = Buffer.from(JSON.stringify({ source, project: credentials.project, at: Date.now(), payload }))
70
+ const sealed = Buffer.concat([
71
+ iv,
72
+ cipher.update(body),
73
+ cipher.final(),
74
+ cipher.getAuthTag(),
75
+ ])
76
+ return {
77
+ id: createHash("sha256").update(sealed).digest("hex"),
78
+ ciphertext: sealed.toString("base64"),
79
+ }
80
+ }
81
+
82
+ export const privateGrant = (id) =>
83
+ typeof id === "string" && id.startsWith("ac_private_client_")
84
+
85
+ export const encryptedReadTool = {
86
+ name: "read_encrypted_sessions",
87
+ description:
88
+ "Search encrypted events for this connection locally. Returns short, untrusted excerpts and nextOffset for another page. Pass a returned id and textOffset to read that event in bounded pages. Plaintext results are shared with this agent.",
89
+ inputSchema: {
90
+ type: "object",
91
+ properties: {
92
+ query: { type: "string", maxLength: 200 },
93
+ offset: { type: "integer", minimum: 0 },
94
+ id: { type: "string", pattern: "^[0-9a-f]{64}$" },
95
+ textOffset: { type: "integer", minimum: 0 },
96
+ },
97
+ additionalProperties: false,
98
+ },
99
+ annotations: { readOnlyHint: true },
100
+ }
101
+
102
+ export async function readEncryptedRecords(
103
+ config,
104
+ grant,
105
+ access,
106
+ args,
107
+ request
108
+ ) {
109
+ const params = new URLSearchParams({
110
+ records: "1",
111
+ offset: String(args.offset ?? 0),
112
+ })
113
+ if (args.id && !/^[a-f0-9]{64}$/.test(args.id))
114
+ throw new Error("Invalid record ID.")
115
+ const offset = args.textOffset ?? 0
116
+ if (
117
+ !Number.isSafeInteger(offset) ||
118
+ offset < 0 ||
119
+ (args.query && typeof args.query !== "string")
120
+ )
121
+ throw new Error("Invalid search.")
122
+ const init = { headers: { Authorization: "Bearer " + access } }
123
+ const page = args.id
124
+ ? { records: [args.id], nextOffset: null }
125
+ : await request(config, "/api/external/encrypted?" + params, init)
126
+ const key = await crypto.subtle.importKey(
127
+ "raw",
128
+ Buffer.from(grant.captureKey, "base64"),
129
+ "AES-GCM",
130
+ false,
131
+ ["decrypt"]
132
+ )
133
+ const records = []
134
+ for (const id of page.records) {
135
+ if (!/^[a-f0-9]{64}$/.test(id)) throw new Error("Invalid record ID.")
136
+ const record = await request(
137
+ config,
138
+ "/api/external/encrypted?records=1&id=" + id,
139
+ init
140
+ )
141
+ const bytes = Buffer.from(record.ciphertext, "base64")
142
+ if (createHash("sha256").update(bytes).digest("hex") !== id)
143
+ throw new Error("Encrypted record mismatch.")
144
+ const clear = await crypto.subtle.decrypt(
145
+ {
146
+ name: "AES-GCM",
147
+ iv: bytes.subarray(0, 12),
148
+ additionalData: Buffer.from("acent:external:v1:" + grant.client_id),
149
+ },
150
+ key,
151
+ bytes.subarray(12)
152
+ )
153
+ const payload = JSON.parse(new TextDecoder().decode(clear))
154
+ const text = JSON.stringify(
155
+ payload.kind === "summary" ? payload.result : payload.payload
156
+ )
157
+ const match = args.id
158
+ ? offset
159
+ : text.toLowerCase().indexOf((args.query ?? "").toLowerCase())
160
+ if (match < 0) continue
161
+ const end = match + (args.id ? 6000 : 300)
162
+ records.push({
163
+ id,
164
+ source: payload.source,
165
+ text: text.slice(match, end),
166
+ nextTextOffset: end < text.length ? end : null,
167
+ })
168
+ }
169
+ return { records, nextOffset: page.nextOffset }
170
+ }
@@ -1,4 +1,6 @@
1
1
  #!/usr/bin/env node
2
+ import { encryptedReadTool, readEncryptedRecords, privateGrant } from "./encrypted-capture.mjs"
3
+ import { readFile } from "node:fs/promises"
2
4
  import { connectionGuidance } from "./host-guidance.mjs"
3
5
  // Folder-scoped MCP with setup available even before the first authorization.
4
6
  import { clarificationInstructions, clarificationTool, clarify, createQuestionChannel } from "./clarification.mjs"
@@ -230,6 +232,13 @@ async function handleLine(line) {
230
232
  }
231
233
  return
232
234
  }
235
+ if (message.method === "tools/call" && message.params?.name === encryptedReadTool.name) {
236
+ const grant = JSON.parse(await readFile(directory + "/credentials.json", "utf8"))
237
+ if (!privateGrant(grant.client_id)) throw new Error("Encrypted connection required.")
238
+ const value = await readEncryptedRecords(config, grant, access, message.params.arguments ?? {}, request)
239
+ reply(content(JSON.stringify(value)))
240
+ return
241
+ }
233
242
  if (message.method === "tools/call" && message.params?.name === attachmentTool.name) {
234
243
  try {
235
244
  const value = await saveAttachments(message.params.arguments?.paths, config, access, request)
@@ -247,8 +256,13 @@ async function handleLine(line) {
247
256
  }
248
257
  if (response.status === 202 || response.status === 204) return
249
258
  const result = await response.json()
250
- if (message.method === "tools/list" && result.result?.tools)
251
- result.result.tools = [...result.result.tools.filter((tool) => tool.name !== clarificationTool.name), setupTool, clarificationTool, attachmentTool]
259
+ if (message.method === "tools/list" && result.result?.tools) {
260
+ const grant = JSON.parse(await readFile(directory + "/credentials.json", "utf8"))
261
+ const localTools = privateGrant(grant.client_id)
262
+ ? (grant.captureKey && grant.scope?.split(" ").includes("original:read") ? [encryptedReadTool] : [])
263
+ : [attachmentTool]
264
+ result.result.tools = [...result.result.tools.filter((tool) => tool.name !== clarificationTool.name), setupTool, clarificationTool, ...localTools]
265
+ }
252
266
  write(result)
253
267
  } catch (error) {
254
268
  console.error(`Acent: ${error.message}`)
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
3
  "name": "acent",
4
4
  "displayName": "Acent",
5
- "version": "0.3.2",
5
+ "version": "0.4.0",
6
6
  "description": "Recall past work, trace code changes, revisit decisions, and resume tasks with Acent.",
7
7
  "author": {
8
8
  "name": "Cirtium"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cirtium/acent-connect",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Install and connect the shared Acent coding-tool plugin",
6
6
  "repository": {