@cirtium/acent-connect 0.0.0-stage → 0.2.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/.agents/plugins/marketplace.json +10 -0
- package/.claude-plugin/marketplace.json +5 -0
- package/README.md +109 -2
- package/acent/.claude-plugin/plugin.json +7 -0
- package/acent/.codex-plugin/plugin.json +32 -0
- package/acent/.cursor-plugin/plugin.json +13 -0
- package/acent/README.md +35 -0
- package/acent/assets/logo-dark.svg +7 -0
- package/acent/assets/logo.svg +7 -0
- package/acent/hooks/claude.json +26 -0
- package/acent/hooks/codex.json +26 -0
- package/acent/hooks/cursor.json +15 -0
- package/acent/mcp-claude.json +12 -0
- package/acent/mcp-codex.json +11 -0
- package/acent/mcp-cursor.json +15 -0
- package/acent/scripts/acent-connect.mjs +440 -0
- package/acent/scripts/antigravity-capture.mjs +105 -0
- package/acent/scripts/antigravity-hook.mjs +26 -0
- package/acent/scripts/capture-attachments.mjs +112 -0
- package/acent/scripts/capture-images.mjs +106 -0
- package/acent/scripts/clarification.mjs +105 -0
- package/acent/scripts/codex-capture.mjs +38 -0
- package/acent/scripts/connection-context.mjs +76 -0
- package/acent/scripts/connection-result.mjs +30 -0
- package/acent/scripts/extract-attachment.swift +19 -0
- package/acent/scripts/hook.mjs +32 -0
- package/acent/scripts/mcp-proxy.mjs +258 -0
- package/acent/scripts/memory-instructions.mjs +14 -0
- package/acent/scripts/provide-diff.mjs +200 -0
- package/acent/skills/acent-connect/SKILL.md +14 -0
- package/acent/skills/acent-memory/SKILL.md +49 -0
- package/antigravity/README.md +25 -0
- package/antigravity/build.mjs +49 -0
- package/antigravity/mcp-local.example.json +12 -0
- package/antigravity/mcp.example.json +1 -0
- package/antigravity/plugin.json +15 -0
- package/package.json +19 -4
- package/scripts/acent.mjs +156 -0
- package/scripts/install-plugin.mjs +267 -0
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Local connection/capture adapter. No AI calls; credentials never go to stdout. */
|
|
3
|
+
import { captureCodexEvent } from "./codex-capture.mjs"
|
|
4
|
+
import { captureAntigravityEvent } from "./antigravity-capture.mjs"
|
|
5
|
+
import { attachFiles } from "./capture-attachments.mjs"
|
|
6
|
+
import { attachScreenshots } from "./capture-images.mjs"
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto"
|
|
8
|
+
import {
|
|
9
|
+
mkdir,
|
|
10
|
+
readFile,
|
|
11
|
+
writeFile,
|
|
12
|
+
rename,
|
|
13
|
+
readdir,
|
|
14
|
+
unlink,
|
|
15
|
+
stat,
|
|
16
|
+
rm,
|
|
17
|
+
} from "node:fs/promises"
|
|
18
|
+
import { homedir } from "node:os"
|
|
19
|
+
import { realpathSync } from "node:fs"
|
|
20
|
+
import { join, resolve } from "node:path"
|
|
21
|
+
import { spawn } from "node:child_process"
|
|
22
|
+
import { pathToFileURL } from "node:url"
|
|
23
|
+
const toolNames = ["Claude Code", "Codex", "Cursor", "Antigravity"]
|
|
24
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex")
|
|
25
|
+
const random = () => randomBytes(32).toString("base64url")
|
|
26
|
+
export function options(args) {
|
|
27
|
+
const result = {
|
|
28
|
+
command: args[0],
|
|
29
|
+
tool: "",
|
|
30
|
+
folder: process.cwd(),
|
|
31
|
+
server: "https://www.acent.cloud",
|
|
32
|
+
file: "",
|
|
33
|
+
}
|
|
34
|
+
for (let i = 1; i < args.length; i++) {
|
|
35
|
+
if (args[i] === "--general") { result.general = true; continue }
|
|
36
|
+
const key = args[i].replace(/^--/, "")
|
|
37
|
+
if (!["tool", "folder", "server", "file"].includes(key) || !args[i + 1])
|
|
38
|
+
throw new Error("Use --tool, --folder, --general, --server, or --file.")
|
|
39
|
+
result[key] = args[++i]
|
|
40
|
+
}
|
|
41
|
+
if (!toolNames.includes(result.tool))
|
|
42
|
+
throw new Error(`Choose --tool: ${toolNames.join(", ")}`)
|
|
43
|
+
const url = new URL(result.server)
|
|
44
|
+
if (
|
|
45
|
+
url.protocol !== "https:" &&
|
|
46
|
+
!(
|
|
47
|
+
url.protocol === "http:" &&
|
|
48
|
+
["localhost", "127.0.0.1"].includes(url.hostname)
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
throw new Error("Use HTTPS or local development HTTP.")
|
|
52
|
+
result.server = url.origin
|
|
53
|
+
result.folder = resolve(result.folder)
|
|
54
|
+
// macOS /var and /private/var (and symlinked repos) must share one binding.
|
|
55
|
+
try {
|
|
56
|
+
result.folder = realpathSync(result.folder)
|
|
57
|
+
} catch {
|
|
58
|
+
/* A missing folder has no active grant. */
|
|
59
|
+
}
|
|
60
|
+
if (result.general) {
|
|
61
|
+
result.contextFolder = args.includes("--folder") ? result.folder : ""
|
|
62
|
+
result.folder = ""
|
|
63
|
+
}
|
|
64
|
+
return result
|
|
65
|
+
}
|
|
66
|
+
export function configDirectory(config) {
|
|
67
|
+
return join(
|
|
68
|
+
process.env.ACENT_CONFIG_HOME || join(homedir(), ".config", "acent"),
|
|
69
|
+
hash(JSON.stringify([config.server, config.tool, config.folder]))
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
function bindingPath(config) {
|
|
73
|
+
return join(
|
|
74
|
+
process.env.ACENT_CONFIG_HOME || join(homedir(), ".config", "acent"),
|
|
75
|
+
"bindings",
|
|
76
|
+
`${hash(JSON.stringify([config.tool, config.contextFolder ?? config.folder]))}.json`
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
export async function boundConfig(args) {
|
|
80
|
+
const config = options(args)
|
|
81
|
+
const saved = await readFile(bindingPath(config), "utf8")
|
|
82
|
+
.then(JSON.parse).catch(() => null)
|
|
83
|
+
if (saved && (!args.includes("--server") || saved.server === config.server)) {
|
|
84
|
+
return { ...options([
|
|
85
|
+
...args,
|
|
86
|
+
...(!args.includes("--server") ? ["--server", saved.server] : []),
|
|
87
|
+
...(saved.general && !args.includes("--general") && config.command !== "connect"
|
|
88
|
+
? ["--general", "--folder", config.folder] : []),
|
|
89
|
+
]), bindingKnown: true }
|
|
90
|
+
}
|
|
91
|
+
return config
|
|
92
|
+
}
|
|
93
|
+
export async function accessToken(config, directory) {
|
|
94
|
+
// Credential updates use atomic rename, so readers see a complete snapshot.
|
|
95
|
+
const saved = await readCredentials(directory).catch((error) => {
|
|
96
|
+
if (error.code !== "ENOENT") throw error
|
|
97
|
+
})
|
|
98
|
+
if (hasFreshAccess(saved)) return saved.access_token
|
|
99
|
+
// Re-read under the shared lock before rotating a refresh token.
|
|
100
|
+
for (let attempt = 0; attempt < 200; attempt++) {
|
|
101
|
+
let access
|
|
102
|
+
if (
|
|
103
|
+
await lock(directory, async () => {
|
|
104
|
+
access = await token(config, directory)
|
|
105
|
+
})
|
|
106
|
+
)
|
|
107
|
+
return access
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
109
|
+
}
|
|
110
|
+
throw new Error("Acent is busy. Try again shortly.")
|
|
111
|
+
}
|
|
112
|
+
async function atomicJson(path, value) {
|
|
113
|
+
const temporary = `${path}.${random()}.tmp`
|
|
114
|
+
await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: "wx" })
|
|
115
|
+
await rename(temporary, path)
|
|
116
|
+
}
|
|
117
|
+
export async function request(config, path, init) {
|
|
118
|
+
const response = await fetch(`${config.server}${path}`, {
|
|
119
|
+
...init,
|
|
120
|
+
signal: AbortSignal.timeout(30_000),
|
|
121
|
+
})
|
|
122
|
+
const body = await response.json().catch(() => ({}))
|
|
123
|
+
if (!response.ok)
|
|
124
|
+
throw Object.assign(
|
|
125
|
+
new Error(body.error_description || body.error || "Acent request failed"),
|
|
126
|
+
{ status: response.status }
|
|
127
|
+
)
|
|
128
|
+
return body
|
|
129
|
+
}
|
|
130
|
+
function processIsAlive(pid) {
|
|
131
|
+
try {
|
|
132
|
+
process.kill(pid, 0)
|
|
133
|
+
return true
|
|
134
|
+
} catch (error) {
|
|
135
|
+
return error.code !== "ESRCH"
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async function acquireLock(directory) {
|
|
139
|
+
const file = join(directory, ".lock")
|
|
140
|
+
try {
|
|
141
|
+
await mkdir(file, { mode: 0o700 })
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error.code !== "EEXIST") throw error
|
|
144
|
+
const owner = await readFile(join(file, "owner.json"), "utf8")
|
|
145
|
+
.then(JSON.parse)
|
|
146
|
+
.catch(() => null)
|
|
147
|
+
if (
|
|
148
|
+
owner &&
|
|
149
|
+
Number.isInteger(owner.pid) &&
|
|
150
|
+
owner.pid > 0 &&
|
|
151
|
+
typeof owner.nonce === "string"
|
|
152
|
+
) {
|
|
153
|
+
if (processIsAlive(owner.pid)) return false
|
|
154
|
+
// Serialize recovery of this dead owner. Recheck identity before moving it;
|
|
155
|
+
// never remove a lock that a different process has acquired in the meantime.
|
|
156
|
+
const recovery = join(directory, `.recover-${hash(owner.nonce)}`)
|
|
157
|
+
try {
|
|
158
|
+
await mkdir(recovery, { mode: 0o700 })
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error.code === "EEXIST")
|
|
161
|
+
throw new Error(
|
|
162
|
+
"Acent lock recovery is already in progress. Pending events are preserved."
|
|
163
|
+
)
|
|
164
|
+
throw error
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const current = await readFile(join(file, "owner.json"), "utf8")
|
|
168
|
+
.then(JSON.parse)
|
|
169
|
+
.catch(() => null)
|
|
170
|
+
if (
|
|
171
|
+
current?.nonce === owner.nonce &&
|
|
172
|
+
current?.pid === owner.pid &&
|
|
173
|
+
!processIsAlive(current.pid)
|
|
174
|
+
) {
|
|
175
|
+
const abandoned = join(directory, `.abandoned-${random()}`)
|
|
176
|
+
await rename(file, abandoned)
|
|
177
|
+
await rm(abandoned, { recursive: true, force: true })
|
|
178
|
+
}
|
|
179
|
+
} finally {
|
|
180
|
+
await rm(recovery, { recursive: true, force: true })
|
|
181
|
+
}
|
|
182
|
+
return acquireLock(directory)
|
|
183
|
+
}
|
|
184
|
+
const info = await stat(file).catch(() => null)
|
|
185
|
+
if (!info) return acquireLock(directory)
|
|
186
|
+
if (Date.now() - info.mtimeMs > 5 * 60_000)
|
|
187
|
+
throw new Error(
|
|
188
|
+
`A stale capture lock exists at ${file}. Ensure no adapter is running before removing it.`
|
|
189
|
+
)
|
|
190
|
+
return false
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
await writeFile(
|
|
194
|
+
join(file, "owner.json"),
|
|
195
|
+
JSON.stringify({ pid: process.pid, nonce: random() }),
|
|
196
|
+
{ mode: 0o600, flag: "wx" }
|
|
197
|
+
)
|
|
198
|
+
} catch (error) {
|
|
199
|
+
await rm(file, { recursive: true, force: true })
|
|
200
|
+
throw error
|
|
201
|
+
}
|
|
202
|
+
return true
|
|
203
|
+
}
|
|
204
|
+
async function lock(directory, operation) {
|
|
205
|
+
const file = join(directory, ".lock")
|
|
206
|
+
// Concurrent hooks leave their queued events to the active drainer.
|
|
207
|
+
if (!(await acquireLock(directory))) return false
|
|
208
|
+
try {
|
|
209
|
+
await operation()
|
|
210
|
+
return true
|
|
211
|
+
} finally {
|
|
212
|
+
await rm(file, { recursive: true, force: true })
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async function readCredentials(directory) {
|
|
216
|
+
return JSON.parse(await readFile(join(directory, "credentials.json"), "utf8"))
|
|
217
|
+
}
|
|
218
|
+
function hasFreshAccess(saved) {
|
|
219
|
+
return saved?.expiresAt > Date.now() + 30_000
|
|
220
|
+
}
|
|
221
|
+
async function token(config, directory) {
|
|
222
|
+
const file = join(directory, "credentials.json")
|
|
223
|
+
const saved = await readCredentials(directory)
|
|
224
|
+
if (hasFreshAccess(saved)) return saved.access_token
|
|
225
|
+
const refreshed = await request(config, "/api/oauth/token", {
|
|
226
|
+
method: "POST",
|
|
227
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
228
|
+
body: new URLSearchParams({
|
|
229
|
+
grant_type: "refresh_token",
|
|
230
|
+
refresh_token: saved.refresh_token,
|
|
231
|
+
client_id: saved.client_id,
|
|
232
|
+
resource: `${config.server}/mcp`,
|
|
233
|
+
}),
|
|
234
|
+
})
|
|
235
|
+
await atomicJson(file, {
|
|
236
|
+
...refreshed,
|
|
237
|
+
client_id: saved.client_id,
|
|
238
|
+
expiresAt: Date.now() + refreshed.expires_in * 1000,
|
|
239
|
+
})
|
|
240
|
+
return refreshed.access_token
|
|
241
|
+
}
|
|
242
|
+
export async function drain(config, directory) {
|
|
243
|
+
return lock(directory, async () => {
|
|
244
|
+
const files = (await readdir(join(directory, "queue")))
|
|
245
|
+
.filter((file) => file.endsWith(".json"))
|
|
246
|
+
.sort()
|
|
247
|
+
if (!files.length) return
|
|
248
|
+
const access = await token(config, directory)
|
|
249
|
+
for (const file of files) {
|
|
250
|
+
const payload = JSON.parse(
|
|
251
|
+
await readFile(join(directory, "queue", file), "utf8")
|
|
252
|
+
)
|
|
253
|
+
try {
|
|
254
|
+
await request(config, "/api/external/collect", {
|
|
255
|
+
method: "POST",
|
|
256
|
+
headers: {
|
|
257
|
+
Authorization: `Bearer ${access}`,
|
|
258
|
+
"Content-Type": "application/json",
|
|
259
|
+
},
|
|
260
|
+
body: JSON.stringify({ source: config.tool, payload: await (async () => {
|
|
261
|
+
const attachments = await attachFiles(payload, config, access, request)
|
|
262
|
+
return attachments.enabled ? attachments.payload : await attachScreenshots(payload, config, access, request).catch(() => payload)
|
|
263
|
+
})() }),
|
|
264
|
+
})
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if (error.status === 401 || error.status === 403) {
|
|
267
|
+
const credentials = JSON.parse(
|
|
268
|
+
await readFile(join(directory, "credentials.json"), "utf8")
|
|
269
|
+
)
|
|
270
|
+
await atomicJson(join(directory, "credentials.json"), {
|
|
271
|
+
...credentials,
|
|
272
|
+
captureBlocked: true,
|
|
273
|
+
})
|
|
274
|
+
for (const queued of await readdir(join(directory, "queue")))
|
|
275
|
+
await unlink(join(directory, "queue", queued))
|
|
276
|
+
}
|
|
277
|
+
throw error
|
|
278
|
+
}
|
|
279
|
+
await unlink(join(directory, "queue", file))
|
|
280
|
+
}
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
function openBrowser(url) {
|
|
284
|
+
const command =
|
|
285
|
+
process.platform === "darwin"
|
|
286
|
+
? "open"
|
|
287
|
+
: process.platform === "win32"
|
|
288
|
+
? "explorer"
|
|
289
|
+
: "xdg-open"
|
|
290
|
+
const child = spawn(command, [url.toString()], { stdio: "ignore" })
|
|
291
|
+
child.on("error", () => {})
|
|
292
|
+
child.unref()
|
|
293
|
+
}
|
|
294
|
+
export async function connect(config, directory, open = openBrowser) {
|
|
295
|
+
const connectionDirectory = join(directory, "connection")
|
|
296
|
+
await mkdir(connectionDirectory, { recursive: true, mode: 0o700 })
|
|
297
|
+
const completed = await lock(connectionDirectory, async () => {
|
|
298
|
+
const verifier = random()
|
|
299
|
+
const started = await request(config, "/api/external/setup/start", {
|
|
300
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
301
|
+
body: JSON.stringify({ tool: config.tool, folder: config.folder, challenge: createHash("sha256").update(verifier).digest("base64url") }),
|
|
302
|
+
})
|
|
303
|
+
const url = new URL(started.authorization_url)
|
|
304
|
+
if (url.origin !== config.server || url.pathname !== "/oauth/authorize" || !url.searchParams.has("setup"))
|
|
305
|
+
throw new Error("Acent returned an invalid connection address.")
|
|
306
|
+
const expires = Math.min(Date.parse(started.expires_at), Date.now() + 15 * 60_000)
|
|
307
|
+
if (!Number.isFinite(expires) || expires <= Date.now() || !started.poll_token || !started.client_id)
|
|
308
|
+
throw new Error("Acent returned an invalid connection session.")
|
|
309
|
+
console.error(`Open this address to connect Acent:\n${url}`)
|
|
310
|
+
open(url)
|
|
311
|
+
const pollBody = JSON.stringify({ poll_token: started.poll_token, verifier })
|
|
312
|
+
while (Date.now() < expires) {
|
|
313
|
+
const tokens = await request(config, "/api/external/setup/token", {
|
|
314
|
+
method: "POST", headers: { "Content-Type": "application/json" }, body: pollBody,
|
|
315
|
+
})
|
|
316
|
+
if (tokens.status === "cancelled") throw new Error("Connection was cancelled.")
|
|
317
|
+
if (tokens.status === "issued") {
|
|
318
|
+
if (!tokens.access_token || !tokens.refresh_token) throw new Error("Connection response was incomplete. Request a new link.")
|
|
319
|
+
let saved = false
|
|
320
|
+
for (let attempt = 0; attempt < 200 && !saved; attempt++) {
|
|
321
|
+
saved = await lock(directory, () => atomicJson(join(directory, "credentials.json"), {
|
|
322
|
+
...tokens, client_id: started.client_id, expiresAt: Date.now() + tokens.expires_in * 1000,
|
|
323
|
+
}))
|
|
324
|
+
if (!saved) await new Promise(resolve => setTimeout(resolve, 100))
|
|
325
|
+
}
|
|
326
|
+
if (!saved) throw new Error("Acent is busy. Request a new connection after the current operation finishes.")
|
|
327
|
+
await mkdir(join(bindingPath(config), ".."), { recursive: true, mode: 0o700 })
|
|
328
|
+
const binding = { server: config.server, ...(config.general ? { general: true } : {}) }
|
|
329
|
+
await atomicJson(bindingPath(config), binding)
|
|
330
|
+
if (config.general && config.contextFolder)
|
|
331
|
+
await atomicJson(bindingPath({ ...config, contextFolder: "" }), binding)
|
|
332
|
+
await request(config, "/api/external/setup/complete", {
|
|
333
|
+
method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${tokens.access_token}` }, body: pollBody,
|
|
334
|
+
})
|
|
335
|
+
console.error(`✓ ${config.tool} connected to Acent.`)
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
if (tokens.status !== "pending") throw new Error("This connection session was already used. Request a new link.")
|
|
339
|
+
await new Promise(resolve => setTimeout(resolve, 2000))
|
|
340
|
+
}
|
|
341
|
+
throw new Error("Connection link expired. Request a new link from your tool.")
|
|
342
|
+
})
|
|
343
|
+
if (!completed) throw new Error("Another Acent connection is pending. Finish it or retry after it expires.")
|
|
344
|
+
}
|
|
345
|
+
export async function main(args = process.argv.slice(2), eventText) {
|
|
346
|
+
const config = await boundConfig(args),
|
|
347
|
+
directory = configDirectory(config)
|
|
348
|
+
await mkdir(join(directory, "queue"), { recursive: true, mode: 0o700 })
|
|
349
|
+
if (config.command === "connect") return connect(config, directory)
|
|
350
|
+
if (config.command === "collect") {
|
|
351
|
+
const credentials = await readFile(
|
|
352
|
+
join(directory, "credentials.json"),
|
|
353
|
+
"utf8"
|
|
354
|
+
)
|
|
355
|
+
.then(JSON.parse)
|
|
356
|
+
.catch(() => null)
|
|
357
|
+
if (
|
|
358
|
+
!credentials ||
|
|
359
|
+
credentials.captureBlocked ||
|
|
360
|
+
!credentials.scope?.split(" ").includes("conversation:write")
|
|
361
|
+
)
|
|
362
|
+
return
|
|
363
|
+
|
|
364
|
+
const content =
|
|
365
|
+
eventText ??
|
|
366
|
+
(config.file
|
|
367
|
+
? await readFile(config.file, "utf8")
|
|
368
|
+
: await new Promise((resolve, reject) => {
|
|
369
|
+
let text = ""
|
|
370
|
+
process.stdin.setEncoding("utf8")
|
|
371
|
+
process.stdin.on("data", (chunk) => {
|
|
372
|
+
text += chunk
|
|
373
|
+
if (Buffer.byteLength(text) > 2 * 1024 * 1024) {
|
|
374
|
+
process.stdin.destroy()
|
|
375
|
+
reject(new Error("Event exceeds 2 MiB."))
|
|
376
|
+
}
|
|
377
|
+
})
|
|
378
|
+
process.stdin.on("end", () => resolve(text))
|
|
379
|
+
process.stdin.on("error", reject)
|
|
380
|
+
}))
|
|
381
|
+
if (Buffer.byteLength(content) > 2 * 1024 * 1024)
|
|
382
|
+
throw new Error("Event exceeds 2 MiB.")
|
|
383
|
+
const payload = JSON.parse(content)
|
|
384
|
+
if (config.tool === "Codex" && !(await captureCodexEvent(payload, directory))) return
|
|
385
|
+
if (config.tool === "Antigravity" && !(await captureAntigravityEvent(payload, directory))) return
|
|
386
|
+
if (Buffer.byteLength(JSON.stringify(payload)) > 2 * 1024 * 1024)
|
|
387
|
+
throw new Error("Collected event exceeds 2 MiB.")
|
|
388
|
+
const files = await readdir(join(directory, "queue"))
|
|
389
|
+
if (files.length >= 500)
|
|
390
|
+
throw new Error(
|
|
391
|
+
"Capture queue is full. Reconnect or drain queued events before saving more."
|
|
392
|
+
)
|
|
393
|
+
const sizes = await Promise.all(
|
|
394
|
+
files.map((file) => stat(join(directory, "queue", file)))
|
|
395
|
+
)
|
|
396
|
+
if (
|
|
397
|
+
sizes.reduce((sum, file) => sum + file.size, 0) +
|
|
398
|
+
Buffer.byteLength(JSON.stringify(payload)) >
|
|
399
|
+
32 * 1024 * 1024
|
|
400
|
+
)
|
|
401
|
+
throw new Error(
|
|
402
|
+
"Capture queue exceeds 32 MiB. Drain it before saving more."
|
|
403
|
+
)
|
|
404
|
+
await atomicJson(
|
|
405
|
+
join(directory, "queue", `${Date.now()}-${random()}.json`),
|
|
406
|
+
payload
|
|
407
|
+
)
|
|
408
|
+
return drain(config, directory)
|
|
409
|
+
}
|
|
410
|
+
if (config.command === "flush") {
|
|
411
|
+
if (!(await drain(config, directory)))
|
|
412
|
+
throw new Error(
|
|
413
|
+
"Another Acent operation is running. Pending events are preserved; retry flush shortly."
|
|
414
|
+
)
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
if (config.command === "disconnect")
|
|
418
|
+
return lock(directory, async () => {
|
|
419
|
+
const file = join(directory, "credentials.json"),
|
|
420
|
+
saved = JSON.parse(await readFile(file, "utf8"))
|
|
421
|
+
await request(config, "/api/oauth/revoke", {
|
|
422
|
+
method: "POST",
|
|
423
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
424
|
+
body: new URLSearchParams({
|
|
425
|
+
token: saved.refresh_token,
|
|
426
|
+
client_id: saved.client_id,
|
|
427
|
+
}),
|
|
428
|
+
})
|
|
429
|
+
await unlink(file)
|
|
430
|
+
// Queued conversations are local private data. Explicit disconnect removes them.
|
|
431
|
+
for (const name of await readdir(join(directory, "queue")))
|
|
432
|
+
await unlink(join(directory, "queue", name))
|
|
433
|
+
})
|
|
434
|
+
throw new Error("Use connect, collect, flush, or disconnect.")
|
|
435
|
+
}
|
|
436
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
437
|
+
main().catch((error) => {
|
|
438
|
+
console.error(error.message)
|
|
439
|
+
process.exitCode = 1
|
|
440
|
+
})
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Contract verified against an IDE 2.6.0 transcript, 2026-11-10.
|
|
2
|
+
import { open, realpath, mkdir, readFile, writeFile, rename } from "node:fs/promises"
|
|
3
|
+
import { join, resolve } from "node:path"
|
|
4
|
+
import { homedir } from "node:os"
|
|
5
|
+
import { constants } from "node:fs"
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
7
|
+
|
|
8
|
+
export function userText(content) {
|
|
9
|
+
if (typeof content !== "string") return ""
|
|
10
|
+
if (!content.startsWith("<USER_REQUEST>\n")) return content.trim()
|
|
11
|
+
const end = content.lastIndexOf("\n</USER_REQUEST>")
|
|
12
|
+
return end < 0 ? "" : content.slice(15, end).trim()
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function transcriptMessages(rows, start) {
|
|
16
|
+
const messages = []
|
|
17
|
+
let user
|
|
18
|
+
for (const row of rows) {
|
|
19
|
+
if (!Number.isSafeInteger(row.step_index) || row.step_index < start) continue
|
|
20
|
+
if (row.type === "USER_INPUT") {
|
|
21
|
+
user = row.source === "USER_EXPLICIT" && row.status === "DONE"
|
|
22
|
+
? { role: "user", content: userText(row.content), turnId: `step:${row.step_index}` }
|
|
23
|
+
: undefined
|
|
24
|
+
} else if (row.type === "PLANNER_RESPONSE" && row.source === "MODEL" &&
|
|
25
|
+
row.status === "DONE" && typeof row.content === "string" && row.content.trim() && user?.content) {
|
|
26
|
+
if (!messages.includes(user)) messages.push(user)
|
|
27
|
+
messages.push({ role: "assistant", content: row.content.trim(), turnId: user.turnId })
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return messages
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Called only AFTER the shared adapter has checked conversation:write consent.
|
|
34
|
+
export async function captureAntigravityEvent(payload, directory, home = homedir()) {
|
|
35
|
+
if (payload.event === "user" || payload.event === "result") return true
|
|
36
|
+
if (!["PreInvocation", "PostInvocation", "Stop"].includes(payload.acent_hook)) return false
|
|
37
|
+
const id = payload.conversationId
|
|
38
|
+
if (typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new Error("Invalid Antigravity conversation ID.")
|
|
39
|
+
const supplied = payload.transcriptPath
|
|
40
|
+
if (typeof supplied !== "string") throw new Error("Antigravity hook did not supply a transcript path.")
|
|
41
|
+
const path = resolve(supplied.startsWith("~/") ? join(home, supplied.slice(2)) : supplied)
|
|
42
|
+
const allowed = ["antigravity", "antigravity-cli", "antigravity-ide"].flatMap(name =>
|
|
43
|
+
["transcript.jsonl", "transcript_full.jsonl"].map(file =>
|
|
44
|
+
join(home, ".gemini", name, "brain", id, ".system_generated/logs", file)))
|
|
45
|
+
const actual = await realpath(path).catch(error => {
|
|
46
|
+
if (error.code === "ENOENT" && payload.acent_hook === "PreInvocation") return path
|
|
47
|
+
throw error
|
|
48
|
+
})
|
|
49
|
+
if (!allowed.includes(path) || actual !== path)
|
|
50
|
+
throw new Error("Antigravity transcript path is outside this conversation.")
|
|
51
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(error => {
|
|
52
|
+
if (error.code === "ENOENT" && payload.acent_hook === "PreInvocation") return null
|
|
53
|
+
throw error
|
|
54
|
+
})
|
|
55
|
+
let raw = ""
|
|
56
|
+
try {
|
|
57
|
+
const info = file && await file.stat()
|
|
58
|
+
if (info) {
|
|
59
|
+
if (!info.isFile() || info.size > 16 * 1024 * 1024) throw new Error("Antigravity transcript exceeds 16 MiB.")
|
|
60
|
+
raw = await file.readFile("utf8")
|
|
61
|
+
}
|
|
62
|
+
} finally { await file?.close() }
|
|
63
|
+
const lines = raw.split("\n")
|
|
64
|
+
// Only complete JSONL records can be captured while the host is writing.
|
|
65
|
+
lines.pop()
|
|
66
|
+
const rows = lines.filter(Boolean).map(line => JSON.parse(line))
|
|
67
|
+
const root = join(directory, "antigravity-sessions")
|
|
68
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
69
|
+
const marker = join(root, createHash("sha256").update(path).digest("hex") + ".json")
|
|
70
|
+
if (payload.acent_hook === "PreInvocation") {
|
|
71
|
+
const last = rows.at(-1)
|
|
72
|
+
const latestUser = rows.findLast(row => row.type === "USER_INPUT")
|
|
73
|
+
const sameUser = latestUser?.source === "USER_EXPLICIT" && typeof payload.lastUserInput === "string" &&
|
|
74
|
+
userText(latestUser.content) === payload.lastUserInput.trim()
|
|
75
|
+
const start = sameUser ? latestUser.step_index : (last?.step_index ?? -1) + 1
|
|
76
|
+
const temporary = marker + "." + randomUUID()
|
|
77
|
+
await writeFile(temporary, JSON.stringify({ start }), { mode: 0o600, flag: "wx" })
|
|
78
|
+
await rename(temporary, marker)
|
|
79
|
+
const content = typeof payload.lastUserInput === "string" ? payload.lastUserInput.trim() : ""
|
|
80
|
+
if (!content) return false
|
|
81
|
+
delete payload.transcriptPath
|
|
82
|
+
delete payload.lastUserInput
|
|
83
|
+
if (sameUser) {
|
|
84
|
+
payload.event = "acent_transcript"
|
|
85
|
+
payload.messages = [{ role: "user", content, turnId: `step:${start}` }]
|
|
86
|
+
} else {
|
|
87
|
+
payload.event = "user"
|
|
88
|
+
payload.message = { content }
|
|
89
|
+
}
|
|
90
|
+
return true
|
|
91
|
+
}
|
|
92
|
+
if (payload.error || (payload.acent_hook === "Stop" && payload.terminationReason !== "NO_TOOL_CALL")) return false
|
|
93
|
+
const saved = await readFile(marker, "utf8").then(JSON.parse).catch(() => null)
|
|
94
|
+
if (!Number.isSafeInteger(saved?.start)) return false
|
|
95
|
+
const messages = transcriptMessages(rows, saved.start)
|
|
96
|
+
if (!messages.length) throw new Error("No complete supported Antigravity conversation turns found.")
|
|
97
|
+
// Never forward tool output, injected metadata, reasoning or file paths from the log.
|
|
98
|
+
delete payload.transcriptPath
|
|
99
|
+
delete payload.lastUserInput
|
|
100
|
+
payload.event = "acent_transcript"
|
|
101
|
+
const model = typeof payload.modelName === "string" ? payload.modelName.trim() : ""
|
|
102
|
+
payload.messages = messages.map(message => message.role === "assistant" && model
|
|
103
|
+
? { ...message, model } : message)
|
|
104
|
+
return true
|
|
105
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process"
|
|
3
|
+
import { fileURLToPath } from "node:url"
|
|
4
|
+
const started = Date.now()
|
|
5
|
+
try {
|
|
6
|
+
let raw = ""
|
|
7
|
+
for await (const chunk of process.stdin) {
|
|
8
|
+
raw += chunk
|
|
9
|
+
if (Buffer.byteLength(raw) > 2 * 1024 * 1024) throw new Error("Hook event exceeds 2 MiB.")
|
|
10
|
+
}
|
|
11
|
+
const payload = JSON.parse(raw)
|
|
12
|
+
payload.acent_hook = process.argv[2]
|
|
13
|
+
console.error("Acent capture timing: " + JSON.stringify({at:new Date().toISOString(),stage:"hook",event:payload.acent_hook,fullyIdle:payload.fullyIdle === true,terminationReason:payload.terminationReason,hasError:!!payload.error}))
|
|
14
|
+
if (!["PreInvocation", "PostInvocation", "Stop"].includes(payload.acent_hook)) throw new Error("Unknown Antigravity hook.")
|
|
15
|
+
await new Promise((resolve, reject) => {
|
|
16
|
+
const child = spawn(process.execPath, [fileURLToPath(new URL("./hook.mjs", import.meta.url)), "--tool", "Antigravity"],
|
|
17
|
+
{ stdio: ["pipe", "ignore", "inherit"] })
|
|
18
|
+
child.on("error", reject)
|
|
19
|
+
child.on("exit", code => code === 0 ? resolve() : reject(new Error("Acent capture failed.")))
|
|
20
|
+
child.stdin.on("error", reject)
|
|
21
|
+
child.stdin.end(JSON.stringify(payload))
|
|
22
|
+
})
|
|
23
|
+
console.error("Acent capture timing: " + JSON.stringify({at:new Date().toISOString(),stage:"finished",durationMs:Date.now()-started}))
|
|
24
|
+
} catch (error) { console.error(`Acent saving: ${error.message}`) }
|
|
25
|
+
// Hooks must emit a JSON object and must never force the agent to continue.
|
|
26
|
+
process.stdout.write("{}\n")
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { constants } from "node:fs"
|
|
2
|
+
import { open } from "node:fs/promises"
|
|
3
|
+
import { basename, isAbsolute } from "node:path"
|
|
4
|
+
import { createHash } from "node:crypto"
|
|
5
|
+
|
|
6
|
+
export const attachmentTool = {
|
|
7
|
+
name: "acent_save_attachments",
|
|
8
|
+
description: "Save originals of files the user directly attached to this conversation in the connected Acent project. Use when automatic attachment capture is unavailable. Requires Save attached files to be enabled. Only pass exact attachment paths supplied by the host/user; never infer paths, scan directories, or include files merely read by tools. Do not save generated outputs unless the user explicitly asks. Returns saved/unavailable/too_large/failed per file. Does not extract or analyze content. Files are searchable by name; this does not claim to attach them to a conversation when the host provides no conversation identifier.",
|
|
9
|
+
inputSchema: { type: "object", properties: {
|
|
10
|
+
paths: { type: "array", minItems: 1, maxItems: 20, items: { type: "string" } },
|
|
11
|
+
}, required: ["paths"], additionalProperties: false },
|
|
12
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Only host-provided user attachments. A path mentioned in ordinary prose or
|
|
16
|
+
// a tool call is deliberately not a capture candidate.
|
|
17
|
+
export function attachedPaths(payload, tool) {
|
|
18
|
+
if (tool === "Cursor" && payload.hook_event_name === "beforeSubmitPrompt")
|
|
19
|
+
return (Array.isArray(payload.attachments) ? payload.attachments : [])
|
|
20
|
+
.filter(item => item?.type === "file" && typeof item.file_path === "string")
|
|
21
|
+
.map(item => item.file_path)
|
|
22
|
+
if (tool === "Codex" && payload.hook_event_name === "UserPromptSubmit" && typeof payload.prompt === "string") {
|
|
23
|
+
const header = payload.prompt.trimStart().split(/^## My request:/m)[0]
|
|
24
|
+
if (!header.startsWith("# Files mentioned by the user:")) return []
|
|
25
|
+
return [...header.matchAll(/^## ([^\r\n]+): (\/[^\r\n]+)$/gm)]
|
|
26
|
+
.filter(([, name, path]) => basename(path.trim()) === name)
|
|
27
|
+
.map(([, , path]) => path.trim())
|
|
28
|
+
}
|
|
29
|
+
return []
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function saveAttachments(paths, config, access, request, upload = fetch) {
|
|
33
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > 20 ||
|
|
34
|
+
paths.some(path => typeof path !== "string" || !isAbsolute(path)))
|
|
35
|
+
throw new Error("Supply 1–20 absolute paths of user-attached files.")
|
|
36
|
+
const headers = { Authorization: "Bearer " + access }
|
|
37
|
+
const settings = await request(config, "/api/external/attachments", { headers })
|
|
38
|
+
if (!settings.enabled) return { enabled: false, files: [] }
|
|
39
|
+
const maxBytes = Math.min(50 * 1024 ** 2, settings.maxBytes)
|
|
40
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new Error("Attachment limit unavailable.")
|
|
41
|
+
const files = []
|
|
42
|
+
for (const path of new Set(paths)) {
|
|
43
|
+
const name = basename(path).slice(0, 255)
|
|
44
|
+
let size = 0, bytes
|
|
45
|
+
try {
|
|
46
|
+
// Resolve parents (e.g. macOS /var), but reject a symlink at the selected file.
|
|
47
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
48
|
+
try {
|
|
49
|
+
const info = await file.stat()
|
|
50
|
+
if (!info.isFile() || (process.getuid && info.uid !== process.getuid())) throw new Error("Not an owned regular file")
|
|
51
|
+
size = info.size
|
|
52
|
+
if (size > maxBytes) { files.push({ name, size, status: "too_large" }); continue }
|
|
53
|
+
// Bound the read even if the source grows while we are reading it.
|
|
54
|
+
bytes = Buffer.alloc(size)
|
|
55
|
+
let offset = 0
|
|
56
|
+
while (offset < size) {
|
|
57
|
+
const read = await file.read(bytes, offset, size - offset, offset)
|
|
58
|
+
if (!read.bytesRead) throw new Error("File changed")
|
|
59
|
+
offset += read.bytesRead
|
|
60
|
+
}
|
|
61
|
+
const after = await file.stat()
|
|
62
|
+
if (after.size !== size || after.mtimeMs !== info.mtimeMs) throw new Error("File changed")
|
|
63
|
+
} finally { await file.close() }
|
|
64
|
+
} catch {
|
|
65
|
+
files.push({ name, size, status: "unavailable" }); continue
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const id = createHash("sha256").update(bytes).digest("hex")
|
|
69
|
+
const metadata = { id, name, size }
|
|
70
|
+
const post = complete => request(config, "/api/external/attachments", {
|
|
71
|
+
method: "POST", headers: { ...headers, "Content-Type": "application/json" },
|
|
72
|
+
body: JSON.stringify({ ...metadata, ...(complete ? { complete: true } : {}) }),
|
|
73
|
+
})
|
|
74
|
+
let result = await post(false)
|
|
75
|
+
if (result.uploadUrl) {
|
|
76
|
+
const url = new URL(result.uploadUrl)
|
|
77
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname)))
|
|
78
|
+
throw new Error("Invalid upload URL")
|
|
79
|
+
// Never forward the Acent bearer token to Storage. Signed URL is path-scoped.
|
|
80
|
+
const response = await upload(url, {
|
|
81
|
+
method: "PUT", headers: { "Content-Type": "application/octet-stream", "x-upsert": "false" },
|
|
82
|
+
body: bytes, signal: AbortSignal.timeout(120_000),
|
|
83
|
+
})
|
|
84
|
+
if (!response.ok && response.status !== 409) {
|
|
85
|
+
const error = await response.json().catch(() => ({}))
|
|
86
|
+
if (String(error.statusCode) !== "409" && error.error !== "Duplicate") throw new Error("Upload failed")
|
|
87
|
+
}
|
|
88
|
+
result = await post(true)
|
|
89
|
+
}
|
|
90
|
+
if (result.id !== id || result.status !== "saved") throw new Error("Upload not confirmed")
|
|
91
|
+
files.push({ ...metadata, status: "saved" })
|
|
92
|
+
} catch { files.push({ name, size, status: "failed" }) }
|
|
93
|
+
}
|
|
94
|
+
return { enabled: true, files }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function attachFiles(payload, config, access, request) {
|
|
98
|
+
const paths = attachedPaths(payload, config.tool)
|
|
99
|
+
if (!paths.length) return { payload, enabled: false }
|
|
100
|
+
let result
|
|
101
|
+
try { result = await saveAttachments(paths.slice(0, 20), config, access, request) }
|
|
102
|
+
catch (error) {
|
|
103
|
+
// Retry service/auth failures through the normal queue; never silently claim success.
|
|
104
|
+
if ([400, 404].includes(error.status)) return { payload, enabled: false }
|
|
105
|
+
throw error
|
|
106
|
+
}
|
|
107
|
+
if (!result.enabled) return { payload, enabled: false }
|
|
108
|
+
const overflow = paths.slice(20).map(path => ({ name: basename(path).slice(0, 255), size: 0, status: "failed" }))
|
|
109
|
+
const markers = [...result.files, ...overflow.slice(0, 20)]
|
|
110
|
+
.map(file => `[acent-file:${encodeURIComponent(JSON.stringify(file))}]`).join("\n")
|
|
111
|
+
return { enabled: true, payload: { ...payload, prompt: payload.prompt + "\n" + markers } }
|
|
112
|
+
}
|