pi-agy-acp 0.2.1 → 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/CHANGELOG.md +9 -0
- package/docs/development.md +15 -6
- package/docs/reference.md +15 -8
- package/index.ts +11 -2
- package/package.json +1 -1
- package/src/acp-process.ts +15 -1
- package/src/catalog.ts +29 -19
- package/src/conversation.ts +66 -16
- package/src/format.ts +68 -23
- package/src/host.ts +148 -13
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/preflight.ts +296 -371
- package/src/quota.ts +39 -20
- package/src/runtime.ts +305 -104
- package/src/session-db.ts +670 -0
package/src/host.ts
CHANGED
|
@@ -4,11 +4,119 @@ import type { CommandOptions, CommandOutput, CommandRunner } from './preflight.t
|
|
|
4
4
|
|
|
5
5
|
const DEFAULT_MAX_STDOUT_BYTES = 8 * 1024 * 1024
|
|
6
6
|
const MAX_STDERR_TAIL_CHARS = 65_536
|
|
7
|
+
const EXIT_DRAIN_MS = 250
|
|
8
|
+
const SIGKILL_SETTLE_MS = 500
|
|
7
9
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
const STRIPPED_AGY_ENV_KEYS = new Set([
|
|
11
|
+
'GEMINI_API_KEY',
|
|
12
|
+
'GOOGLE_API_KEY',
|
|
13
|
+
'GEMINI_HOME',
|
|
14
|
+
'ELECTRON_RUN_AS_NODE',
|
|
15
|
+
'CHROME_CRASHPAD_PIPE_NAME',
|
|
16
|
+
])
|
|
17
|
+
const STRIPPED_AGY_ENV_KEYS_LOWER = new Set(
|
|
18
|
+
[...STRIPPED_AGY_ENV_KEYS].map((key) => key.toLowerCase()),
|
|
19
|
+
)
|
|
20
|
+
const FORCED_AGY_ENV_KEYS_LOWER = new Set([
|
|
21
|
+
'agy_cli_disable_auto_update',
|
|
22
|
+
'pythonunbuffered',
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
/** Build a sanitized environment for spawning `agy` subprocesses. */
|
|
26
|
+
export function buildAgyEnv(
|
|
27
|
+
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
28
|
+
platform: NodeJS.Platform = process.platform,
|
|
29
|
+
): NodeJS.ProcessEnv {
|
|
30
|
+
const env: NodeJS.ProcessEnv = {}
|
|
31
|
+
const caseInsensitive = platform === 'win32'
|
|
32
|
+
for (const [key, value] of Object.entries(baseEnv)) {
|
|
33
|
+
if (value === undefined) continue
|
|
34
|
+
if (caseInsensitive) {
|
|
35
|
+
const lower = key.toLowerCase()
|
|
36
|
+
if (
|
|
37
|
+
STRIPPED_AGY_ENV_KEYS_LOWER.has(lower) ||
|
|
38
|
+
FORCED_AGY_ENV_KEYS_LOWER.has(lower)
|
|
39
|
+
)
|
|
40
|
+
continue
|
|
41
|
+
} else if (STRIPPED_AGY_ENV_KEYS.has(key)) {
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
env[key] = value
|
|
45
|
+
}
|
|
46
|
+
env.AGY_CLI_DISABLE_AUTO_UPDATE = '1'
|
|
47
|
+
env.PYTHONUNBUFFERED = '1'
|
|
48
|
+
return env
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Scrub bearer tokens, Google API/OAuth tokens, secret params, and Google OAuth URL queries from stderr. */
|
|
52
|
+
export function redactStderr(text: string): string {
|
|
53
|
+
return text
|
|
54
|
+
.replace(
|
|
55
|
+
/(https:\/\/accounts\.google\.com(?:\/[^\s"'?]*)?)\?[^\s"']+/gi,
|
|
56
|
+
'$1?[REDACTED]',
|
|
57
|
+
)
|
|
58
|
+
.replace(/\bBearer\s+[^\s"'`]+/gi, 'Bearer [REDACTED]')
|
|
59
|
+
.replace(/ya29\.[0-9A-Za-z._-]+/g, '[REDACTED]')
|
|
60
|
+
.replace(/AIza[0-9A-Za-z_-]{20,}/g, '[REDACTED]')
|
|
61
|
+
.replace(
|
|
62
|
+
/\b(access_token|refresh_token|id_token|client_secret|api_key|key)=[^&\s"']+/gi,
|
|
63
|
+
'$1=[REDACTED]',
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Optional boundary seams for deterministic process-tree termination tests. */
|
|
68
|
+
export interface TerminateProcessOptions {
|
|
69
|
+
platform?: NodeJS.Platform
|
|
70
|
+
spawnTaskkill?: (
|
|
71
|
+
command: string,
|
|
72
|
+
args: readonly string[],
|
|
73
|
+
options: { stdio: 'ignore'; windowsHide: true },
|
|
74
|
+
) => Pick<ChildProcess, 'unref' | 'once'>
|
|
75
|
+
killGroup?: (pid: number, signal: NodeJS.Signals) => void
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Terminate a spawned process and its process tree on Unix (`-pid`) and Windows (`taskkill /T /F /PID`). */
|
|
79
|
+
export function terminateProcessTree(
|
|
80
|
+
child: Pick<ChildProcess, 'pid' | 'kill'>,
|
|
81
|
+
signal: NodeJS.Signals,
|
|
82
|
+
options: TerminateProcessOptions = {},
|
|
83
|
+
): void {
|
|
84
|
+
const platform = options.platform ?? process.platform
|
|
85
|
+
if (platform === 'win32') {
|
|
86
|
+
if (child.pid !== undefined) {
|
|
87
|
+
try {
|
|
88
|
+
const spawnFn =
|
|
89
|
+
options.spawnTaskkill ??
|
|
90
|
+
((command, args, spawnOptions) =>
|
|
91
|
+
spawn(command, [...args], spawnOptions))
|
|
92
|
+
const killer = spawnFn('taskkill', ['/T', '/F', '/PID', String(child.pid)], {
|
|
93
|
+
stdio: 'ignore',
|
|
94
|
+
windowsHide: true,
|
|
95
|
+
})
|
|
96
|
+
killer.unref()
|
|
97
|
+
killer.once('error', () => {
|
|
98
|
+
try {
|
|
99
|
+
child.kill(signal)
|
|
100
|
+
} catch {
|
|
101
|
+
// Process already exited.
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
return
|
|
105
|
+
} catch {
|
|
106
|
+
// Fall back to signaling the direct child if spawning taskkill fails synchronously.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
10
109
|
try {
|
|
11
|
-
|
|
110
|
+
child.kill(signal)
|
|
111
|
+
} catch {
|
|
112
|
+
// Process already exited.
|
|
113
|
+
}
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
if (child.pid !== undefined) {
|
|
117
|
+
try {
|
|
118
|
+
const killFn = options.killGroup ?? process.kill
|
|
119
|
+
killFn(-child.pid, signal)
|
|
12
120
|
return
|
|
13
121
|
} catch {
|
|
14
122
|
// Fall back to signaling the direct child if process-group signaling fails.
|
|
@@ -24,11 +132,13 @@ function signalChild(child: ChildProcess, signal: NodeJS.Signals): void {
|
|
|
24
132
|
export const spawnAcp: AcpSpawner = (argv, cwd) => {
|
|
25
133
|
const child = spawn(argv[0]!, argv.slice(1), {
|
|
26
134
|
cwd,
|
|
135
|
+
env: buildAgyEnv(),
|
|
27
136
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
28
137
|
detached: process.platform !== 'win32',
|
|
29
138
|
})
|
|
30
139
|
let stderr = ''
|
|
31
|
-
child.stderr.
|
|
140
|
+
child.stderr.setEncoding('utf8')
|
|
141
|
+
child.stderr.on('data', (chunk: string) => {
|
|
32
142
|
stderr = (stderr + chunk).slice(-MAX_STDERR_TAIL_CHARS)
|
|
33
143
|
})
|
|
34
144
|
const exited = new Promise<{ code: number | null; signal: string | null }>(
|
|
@@ -44,12 +154,12 @@ export const spawnAcp: AcpSpawner = (argv, cwd) => {
|
|
|
44
154
|
stdin: child.stdin,
|
|
45
155
|
stdout: child.stdout,
|
|
46
156
|
exited,
|
|
47
|
-
stderrTail: () => stderr,
|
|
157
|
+
stderrTail: () => redactStderr(stderr),
|
|
48
158
|
terminate: () => {
|
|
49
|
-
|
|
159
|
+
terminateProcessTree(child, 'SIGTERM')
|
|
50
160
|
const timer = setTimeout(() => {
|
|
51
161
|
if (child.exitCode === null && child.signalCode === null)
|
|
52
|
-
|
|
162
|
+
terminateProcessTree(child, 'SIGKILL')
|
|
53
163
|
}, 5000)
|
|
54
164
|
timer.unref()
|
|
55
165
|
void exited.then(() => clearTimeout(timer))
|
|
@@ -74,6 +184,7 @@ export const runCommand: CommandRunner = (
|
|
|
74
184
|
}
|
|
75
185
|
const maxStdoutBytes = options?.maxStdoutBytes ?? DEFAULT_MAX_STDOUT_BYTES
|
|
76
186
|
const child = spawn(argv[0]!, argv.slice(1), {
|
|
187
|
+
env: buildAgyEnv(),
|
|
77
188
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
78
189
|
detached: process.platform !== 'win32',
|
|
79
190
|
})
|
|
@@ -83,15 +194,19 @@ export const runCommand: CommandRunner = (
|
|
|
83
194
|
let settled = false
|
|
84
195
|
let abortedBy: CommandOutput['abortedBy']
|
|
85
196
|
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
197
|
+
let settleTimer: ReturnType<typeof setTimeout> | undefined
|
|
198
|
+
let exitDrainTimer: ReturnType<typeof setTimeout> | undefined
|
|
86
199
|
|
|
87
200
|
const finish = (code: number | null, errorMessage?: string): void => {
|
|
88
201
|
if (settled) return
|
|
89
202
|
settled = true
|
|
90
203
|
clearTimeout(timeoutTimer)
|
|
91
204
|
if (killTimer !== undefined) clearTimeout(killTimer)
|
|
205
|
+
if (settleTimer !== undefined) clearTimeout(settleTimer)
|
|
206
|
+
if (exitDrainTimer !== undefined) clearTimeout(exitDrainTimer)
|
|
92
207
|
options?.signal?.removeEventListener('abort', onSignalAbort)
|
|
93
208
|
const stdout = Buffer.concat(stdoutChunks).toString('utf8')
|
|
94
|
-
let finalStderr = stderr || errorMessage || ''
|
|
209
|
+
let finalStderr = redactStderr(stderr || errorMessage || '')
|
|
95
210
|
if (abortedBy === 'timeout' && finalStderr.trim().length === 0) {
|
|
96
211
|
finalStderr = 'command timed out'
|
|
97
212
|
} else if (abortedBy === 'maxStdout' && finalStderr.trim().length === 0) {
|
|
@@ -115,9 +230,16 @@ export const runCommand: CommandRunner = (
|
|
|
115
230
|
const abort = (reason: NonNullable<CommandOutput['abortedBy']>): void => {
|
|
116
231
|
if (settled || abortedBy !== undefined) return
|
|
117
232
|
abortedBy = reason
|
|
118
|
-
|
|
233
|
+
child.stdout.destroy()
|
|
234
|
+
child.stderr.destroy()
|
|
235
|
+
terminateProcessTree(child, 'SIGTERM')
|
|
119
236
|
killTimer = setTimeout(() => {
|
|
120
|
-
if (
|
|
237
|
+
if (settled) return
|
|
238
|
+
terminateProcessTree(child, 'SIGKILL')
|
|
239
|
+
settleTimer = setTimeout(() => {
|
|
240
|
+
finish(child.exitCode)
|
|
241
|
+
}, SIGKILL_SETTLE_MS)
|
|
242
|
+
settleTimer.unref()
|
|
121
243
|
}, 1000)
|
|
122
244
|
killTimer.unref()
|
|
123
245
|
}
|
|
@@ -138,9 +260,11 @@ export const runCommand: CommandRunner = (
|
|
|
138
260
|
stdoutChunks.push(chunk)
|
|
139
261
|
})
|
|
140
262
|
|
|
141
|
-
child.stderr.
|
|
142
|
-
|
|
143
|
-
|
|
263
|
+
child.stderr.setEncoding('utf8')
|
|
264
|
+
child.stderr.on('data', (chunk: string) => {
|
|
265
|
+
const combined = stderr + chunk
|
|
266
|
+
stderr = combined.slice(-MAX_STDERR_TAIL_CHARS)
|
|
267
|
+
if (abortedBy === undefined && options?.abortOnStderr?.test(combined)) {
|
|
144
268
|
abort('stderr')
|
|
145
269
|
}
|
|
146
270
|
})
|
|
@@ -149,6 +273,17 @@ export const runCommand: CommandRunner = (
|
|
|
149
273
|
finish(-1, error.message)
|
|
150
274
|
})
|
|
151
275
|
|
|
276
|
+
child.once('exit', (code) => {
|
|
277
|
+
if (settled || exitDrainTimer !== undefined) return
|
|
278
|
+
// Prevent detached grandchildren inheriting stdio pipes from hanging runCommand indefinitely.
|
|
279
|
+
exitDrainTimer = setTimeout(() => {
|
|
280
|
+
child.stdout.destroy()
|
|
281
|
+
child.stderr.destroy()
|
|
282
|
+
finish(code)
|
|
283
|
+
}, EXIT_DRAIN_MS)
|
|
284
|
+
exitDrainTimer.unref()
|
|
285
|
+
})
|
|
286
|
+
|
|
152
287
|
child.once('close', (code) => {
|
|
153
288
|
finish(code)
|
|
154
289
|
})
|
package/src/jsonrpc.ts
CHANGED
|
@@ -63,6 +63,9 @@ export interface JsonRpcRequestOptions {
|
|
|
63
63
|
timeoutMs?: number | undefined
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
/** Maximum characters accepted for a single newline-delimited JSON-RPC frame (16 MiB). */
|
|
67
|
+
export const MAX_LINE_CHARS = 16 * 1024 * 1024
|
|
68
|
+
|
|
66
69
|
/** Bidirectional newline-delimited JSON-RPC 2.0 endpoint. */
|
|
67
70
|
export class JsonRpcPeer {
|
|
68
71
|
private nextId = 1
|
|
@@ -174,6 +177,7 @@ export class JsonRpcPeer {
|
|
|
174
177
|
close(error: Error): void {
|
|
175
178
|
if (this.closed !== undefined) return
|
|
176
179
|
this.closed = error
|
|
180
|
+
this.buffer = ''
|
|
177
181
|
for (const [id, pending] of this.pending) {
|
|
178
182
|
this.pending.delete(id)
|
|
179
183
|
pending.reject(
|
|
@@ -192,13 +196,43 @@ export class JsonRpcPeer {
|
|
|
192
196
|
}
|
|
193
197
|
|
|
194
198
|
private onData(chunk: string): void {
|
|
199
|
+
if (this.closed !== undefined) return
|
|
195
200
|
this.buffer += chunk
|
|
196
|
-
let
|
|
201
|
+
let start = 0
|
|
202
|
+
let newline = this.buffer.indexOf('\n', start)
|
|
197
203
|
while (newline >= 0) {
|
|
198
|
-
|
|
199
|
-
|
|
204
|
+
if (newline - start > MAX_LINE_CHARS) {
|
|
205
|
+
this.buffer = ''
|
|
206
|
+
this.handlers.onProtocolError?.(
|
|
207
|
+
`frame exceeded ${MAX_LINE_CHARS} character limit`,
|
|
208
|
+
)
|
|
209
|
+
this.close(new JsonRpcClosedError('ACP frame exceeded 16 MiB limit'))
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
const line = this.buffer.slice(start, newline).trim()
|
|
213
|
+
start = newline + 1
|
|
200
214
|
if (line.length > 0) this.onLine(line)
|
|
201
|
-
|
|
215
|
+
if (this.closed !== undefined) {
|
|
216
|
+
this.buffer = ''
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
newline = this.buffer.indexOf('\n', start)
|
|
220
|
+
}
|
|
221
|
+
if (this.buffer.length - start > MAX_LINE_CHARS) {
|
|
222
|
+
this.buffer = ''
|
|
223
|
+
this.handlers.onProtocolError?.(
|
|
224
|
+
`frame exceeded ${MAX_LINE_CHARS} character limit`,
|
|
225
|
+
)
|
|
226
|
+
this.close(new JsonRpcClosedError('ACP frame exceeded 16 MiB limit'))
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
if (start === this.buffer.length) {
|
|
230
|
+
this.buffer = ''
|
|
231
|
+
} else if (start > 0) {
|
|
232
|
+
// Flatten the remainder to detach V8's SlicedString backing buffer.
|
|
233
|
+
this.buffer = Buffer.from(this.buffer.slice(start), 'utf16le').toString(
|
|
234
|
+
'utf16le',
|
|
235
|
+
)
|
|
202
236
|
}
|
|
203
237
|
}
|
|
204
238
|
|
package/src/mcp-bridge.ts
CHANGED
|
@@ -52,6 +52,12 @@ export interface BridgeCallRequest {
|
|
|
52
52
|
arguments: Record<string, unknown>
|
|
53
53
|
/** Aborts when the agent disconnects or cancels the call. */
|
|
54
54
|
signal: AbortSignal
|
|
55
|
+
/**
|
|
56
|
+
* Synchronously finalize and write a tool result onto the open SSE stream
|
|
57
|
+
* without yielding a microtask. When the client has already disconnected,
|
|
58
|
+
* returns a cancelled error without invoking `finalize`.
|
|
59
|
+
*/
|
|
60
|
+
commit?: (finalize: () => BridgeToolResult) => BridgeToolResult
|
|
55
61
|
}
|
|
56
62
|
|
|
57
63
|
/** Owner-side routing of tool listings and calls. */
|
|
@@ -88,7 +94,7 @@ export interface McpBridgeOptions {
|
|
|
88
94
|
log?: (message: string) => void
|
|
89
95
|
}
|
|
90
96
|
|
|
91
|
-
const MAX_BODY_BYTES =
|
|
97
|
+
const MAX_BODY_BYTES = 8 * 1024 * 1024
|
|
92
98
|
|
|
93
99
|
const MCP_PROTOCOL_VERSION = '2025-06-18'
|
|
94
100
|
const CONVERSATION_META_KEY = 'antigravity.google/conversation_id'
|
|
@@ -391,6 +397,23 @@ export class McpBridge {
|
|
|
391
397
|
)
|
|
392
398
|
}
|
|
393
399
|
}, this.options.keepAliveMs)
|
|
400
|
+
keepAlive.unref()
|
|
401
|
+
|
|
402
|
+
let wroteResponse = false
|
|
403
|
+
const commit = (finalize: () => BridgeToolResult): BridgeToolResult => {
|
|
404
|
+
if (res.writableEnded || res.destroyed || controller.signal.aborted) {
|
|
405
|
+
return {
|
|
406
|
+
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
407
|
+
isError: true,
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const finalResult = finalize()
|
|
411
|
+
writeEvent(res, { jsonrpc: '2.0', id: request.id, result: finalResult })
|
|
412
|
+
settled = true
|
|
413
|
+
wroteResponse = true
|
|
414
|
+
res.end()
|
|
415
|
+
return finalResult
|
|
416
|
+
}
|
|
394
417
|
|
|
395
418
|
let result: BridgeToolResult
|
|
396
419
|
try {
|
|
@@ -400,6 +423,7 @@ export class McpBridge {
|
|
|
400
423
|
name,
|
|
401
424
|
arguments: args,
|
|
402
425
|
signal: controller.signal,
|
|
426
|
+
commit,
|
|
403
427
|
})
|
|
404
428
|
} catch (error) {
|
|
405
429
|
result = {
|
|
@@ -415,7 +439,7 @@ export class McpBridge {
|
|
|
415
439
|
settled = true
|
|
416
440
|
clearInterval(keepAlive)
|
|
417
441
|
}
|
|
418
|
-
if (!res.writableEnded && !res.destroyed) {
|
|
442
|
+
if (!wroteResponse && !res.writableEnded && !res.destroyed) {
|
|
419
443
|
writeEvent(res, { jsonrpc: '2.0', id: request.id, result })
|
|
420
444
|
res.end()
|
|
421
445
|
}
|