pi-agy-acp 0.2.0 → 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 +26 -0
- package/README.md +4 -5
- package/docs/development.md +44 -12
- package/docs/reference.md +45 -35
- package/index.ts +19 -8
- package/package.json +1 -1
- package/src/acp-process.ts +48 -4
- package/src/catalog.ts +219 -51
- package/src/config.ts +1 -1
- package/src/conversation.ts +379 -35
- package/src/format.ts +76 -25
- package/src/host.ts +257 -20
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/pi-stream.ts +2 -2
- package/src/preflight.ts +356 -309
- package/src/quota.ts +202 -36
- package/src/runtime.ts +417 -139
- package/src/session-db.ts +670 -0
package/src/format.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { asEffort, type Effort, type QuotaDisplay } from './config.ts'
|
|
1
|
+
import { asEffort, EFFORTS, type Effort, type QuotaDisplay } from './config.ts'
|
|
2
2
|
import type {
|
|
3
3
|
AccountInfo,
|
|
4
4
|
QuotaSnapshot,
|
|
@@ -33,10 +33,28 @@ export interface QuotaModelRef {
|
|
|
33
33
|
const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
|
|
34
34
|
const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
|
|
35
35
|
const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
|
|
36
|
+
type EffortQualifier = Effort | 'extra-low'
|
|
37
|
+
|
|
38
|
+
// Keep longest qualifiers first (`extra[-_]low` before `low`) so compound suffixes match whole.
|
|
39
|
+
const EFFORT_QUALIFIER_PATTERN = [
|
|
40
|
+
'extra[-_]low',
|
|
41
|
+
...[...EFFORTS].sort((a, b) => b.length - a.length),
|
|
42
|
+
].join('|')
|
|
36
43
|
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
|
|
37
|
-
const ID_QUALIFIER_SUFFIX =
|
|
38
|
-
|
|
39
|
-
|
|
44
|
+
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
45
|
+
`[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
|
|
46
|
+
'i',
|
|
47
|
+
)
|
|
48
|
+
const GROUP_QUALIFIER_SUFFIX = new RegExp(
|
|
49
|
+
`\\s*\\((${EFFORT_QUALIFIER_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
|
|
50
|
+
'i',
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
function parseEffortQualifier(raw: string): EffortQualifier | undefined {
|
|
54
|
+
const normalized = raw.toLowerCase().replace(/_/g, '-')
|
|
55
|
+
if (normalized === 'extra-low') return 'extra-low'
|
|
56
|
+
return asEffort(normalized)
|
|
57
|
+
}
|
|
40
58
|
const SPECIFIER = /^\d+(?:\.\d+)*b?$/
|
|
41
59
|
const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
|
|
42
60
|
const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
|
|
@@ -69,7 +87,7 @@ interface ParsedPhrase {
|
|
|
69
87
|
readonly head: string | undefined
|
|
70
88
|
readonly words: readonly string[]
|
|
71
89
|
readonly specs: readonly string[]
|
|
72
|
-
readonly effort:
|
|
90
|
+
readonly effort: EffortQualifier | undefined
|
|
73
91
|
readonly thinking: boolean
|
|
74
92
|
readonly effortConflict: boolean
|
|
75
93
|
readonly tokenCount: number
|
|
@@ -78,7 +96,7 @@ interface ParsedPhrase {
|
|
|
78
96
|
|
|
79
97
|
function buildPhrase(
|
|
80
98
|
tokens: readonly string[],
|
|
81
|
-
effort?:
|
|
99
|
+
effort?: EffortQualifier,
|
|
82
100
|
thinking = false,
|
|
83
101
|
effortConflict = false,
|
|
84
102
|
): ParsedPhrase {
|
|
@@ -102,9 +120,21 @@ function buildPhrase(
|
|
|
102
120
|
|
|
103
121
|
function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
104
122
|
let text = raw.trim().replace(/[.!?]+$/, '')
|
|
105
|
-
let effort:
|
|
123
|
+
let effort: EffortQualifier | undefined
|
|
106
124
|
let thinking = false
|
|
107
125
|
let effortConflict = false
|
|
126
|
+
const applyQualifier = (rawQualifier: string) => {
|
|
127
|
+
const token = rawQualifier.toLowerCase()
|
|
128
|
+
if (token === 'thinking') {
|
|
129
|
+
thinking = true
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
const nextEffort = parseEffortQualifier(token)
|
|
133
|
+
if (nextEffort) {
|
|
134
|
+
if (effort && effort !== nextEffort) effortConflict = true
|
|
135
|
+
effort = nextEffort
|
|
136
|
+
}
|
|
137
|
+
}
|
|
108
138
|
while (text.length > 0) {
|
|
109
139
|
const withoutDate = text.replace(ID_DATE_SUFFIX, '')
|
|
110
140
|
if (withoutDate !== text) {
|
|
@@ -113,13 +143,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
113
143
|
}
|
|
114
144
|
const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
|
|
115
145
|
if (groupQual) {
|
|
116
|
-
|
|
117
|
-
if (nextEffort) {
|
|
118
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
119
|
-
effort = nextEffort
|
|
120
|
-
} else {
|
|
121
|
-
thinking = true
|
|
122
|
-
}
|
|
146
|
+
applyQualifier(groupQual[1]!)
|
|
123
147
|
text =
|
|
124
148
|
text.slice(0, groupQual.index) +
|
|
125
149
|
text.slice(groupQual.index + groupQual[0].length)
|
|
@@ -127,13 +151,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
127
151
|
}
|
|
128
152
|
const idQual = ID_QUALIFIER_SUFFIX.exec(text)
|
|
129
153
|
if (idQual) {
|
|
130
|
-
|
|
131
|
-
if (nextEffort) {
|
|
132
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
133
|
-
effort = nextEffort
|
|
134
|
-
} else {
|
|
135
|
-
thinking = true
|
|
136
|
-
}
|
|
154
|
+
applyQualifier((idQual[1] ?? idQual[2])!)
|
|
137
155
|
text = text.slice(0, idQual.index)
|
|
138
156
|
continue
|
|
139
157
|
}
|
|
@@ -365,6 +383,38 @@ export function formatQuotaStatus(
|
|
|
365
383
|
return `AGY ${Math.round(displayFraction(quota.fraction, display) * 100)}%`
|
|
366
384
|
}
|
|
367
385
|
|
|
386
|
+
const WINDOW_DURATION = /^(\d+)([mhdw])$/
|
|
387
|
+
const WINDOW_UNIT_SECONDS: Record<string, number> = {
|
|
388
|
+
m: 60,
|
|
389
|
+
h: 3600,
|
|
390
|
+
d: 86400,
|
|
391
|
+
w: 7 * 86400,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function windowSeconds(window: string): number | undefined {
|
|
395
|
+
const normalized = window.trim().toLowerCase()
|
|
396
|
+
if (normalized === 'weekly') return 7 * 86400
|
|
397
|
+
if (normalized === 'daily') return 86400
|
|
398
|
+
const match = WINDOW_DURATION.exec(normalized)
|
|
399
|
+
if (!match) return undefined
|
|
400
|
+
const count = Number(match[1])
|
|
401
|
+
const unit = WINDOW_UNIT_SECONDS[match[2]!]
|
|
402
|
+
return count > 0 && unit !== undefined ? count * unit : undefined
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function isUntouchedRollingReset(
|
|
406
|
+
bucket: QuotaBucket,
|
|
407
|
+
fraction: number | undefined,
|
|
408
|
+
now: number,
|
|
409
|
+
): boolean {
|
|
410
|
+
if (fraction === undefined || fraction < 1) return false
|
|
411
|
+
const resetMs = Date.parse(bucket.resetTime)
|
|
412
|
+
if (!Number.isFinite(resetMs)) return false
|
|
413
|
+
const windowSecs = windowSeconds(bucket.window)
|
|
414
|
+
if (windowSecs === undefined) return false
|
|
415
|
+
return Math.abs((resetMs - now) / 1000 - windowSecs) <= 60
|
|
416
|
+
}
|
|
417
|
+
|
|
368
418
|
function resetCountdown(resetTime: string, now: number): string {
|
|
369
419
|
const reset = Date.parse(resetTime)
|
|
370
420
|
if (!Number.isFinite(reset)) return 'reset time unavailable'
|
|
@@ -417,9 +467,10 @@ export function formatQuota(
|
|
|
417
467
|
bucket.id ||
|
|
418
468
|
'quota'
|
|
419
469
|
).padEnd(7)
|
|
420
|
-
const reset =
|
|
421
|
-
|
|
422
|
-
|
|
470
|
+
const reset =
|
|
471
|
+
bucket.resetTime && !isUntouchedRollingReset(bucket, fraction, now)
|
|
472
|
+
? ` · ${resetCountdown(bucket.resetTime, now)}`
|
|
473
|
+
: ''
|
|
423
474
|
lines.push(` ${label} [${bar}] ${percent.padStart(4)}${reset}`)
|
|
424
475
|
if (fraction !== undefined) {
|
|
425
476
|
if (fraction <= 0.05) level = 'error'
|
|
@@ -447,7 +498,7 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
|
|
|
447
498
|
` Home: ${status.home}`,
|
|
448
499
|
...(account ? [` Account: ${account}`] : []),
|
|
449
500
|
` Sessions: ${status.liveSessions} live · ${status.activeTurns} active turn(s)`,
|
|
450
|
-
` Context: ${status.contextWindow ? `${Math.round(status.contextWindow / 1024)}K tokens` : 'dynamic (unprobed)'} · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
|
|
501
|
+
` Context: ${status.contextWindow ? `${Math.round(status.contextWindow / 1024)}K tokens` : 'dynamic (unprobed)'} · default effort: ${status.defaultEffort}${status.efforts.length > 0 ? ` (${status.efforts.join(', ')})` : ''}`,
|
|
451
502
|
' Models:',
|
|
452
503
|
]
|
|
453
504
|
if (status.models.length === 0) lines.push(' No models available.')
|
package/src/host.ts
CHANGED
|
@@ -1,15 +1,145 @@
|
|
|
1
|
-
import { spawn,
|
|
1
|
+
import { spawn, type ChildProcess } from 'node:child_process'
|
|
2
2
|
import type { AcpSpawner } from './acp-process.ts'
|
|
3
|
-
import type { CommandRunner } from './preflight.ts'
|
|
3
|
+
import type { CommandOptions, CommandOutput, CommandRunner } from './preflight.ts'
|
|
4
|
+
|
|
5
|
+
const DEFAULT_MAX_STDOUT_BYTES = 8 * 1024 * 1024
|
|
6
|
+
const MAX_STDERR_TAIL_CHARS = 65_536
|
|
7
|
+
const EXIT_DRAIN_MS = 250
|
|
8
|
+
const SIGKILL_SETTLE_MS = 500
|
|
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
|
+
}
|
|
109
|
+
try {
|
|
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)
|
|
120
|
+
return
|
|
121
|
+
} catch {
|
|
122
|
+
// Fall back to signaling the direct child if process-group signaling fails.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
child.kill(signal)
|
|
127
|
+
} catch {
|
|
128
|
+
// Process already exited.
|
|
129
|
+
}
|
|
130
|
+
}
|
|
4
131
|
|
|
5
132
|
export const spawnAcp: AcpSpawner = (argv, cwd) => {
|
|
6
133
|
const child = spawn(argv[0]!, argv.slice(1), {
|
|
7
134
|
cwd,
|
|
135
|
+
env: buildAgyEnv(),
|
|
8
136
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
137
|
+
detached: process.platform !== 'win32',
|
|
9
138
|
})
|
|
10
139
|
let stderr = ''
|
|
11
|
-
child.stderr.
|
|
12
|
-
|
|
140
|
+
child.stderr.setEncoding('utf8')
|
|
141
|
+
child.stderr.on('data', (chunk: string) => {
|
|
142
|
+
stderr = (stderr + chunk).slice(-MAX_STDERR_TAIL_CHARS)
|
|
13
143
|
})
|
|
14
144
|
const exited = new Promise<{ code: number | null; signal: string | null }>(
|
|
15
145
|
(resolve) => {
|
|
@@ -24,30 +154,137 @@ export const spawnAcp: AcpSpawner = (argv, cwd) => {
|
|
|
24
154
|
stdin: child.stdin,
|
|
25
155
|
stdout: child.stdout,
|
|
26
156
|
exited,
|
|
27
|
-
stderrTail: () => stderr,
|
|
157
|
+
stderrTail: () => redactStderr(stderr),
|
|
28
158
|
terminate: () => {
|
|
29
|
-
child
|
|
159
|
+
terminateProcessTree(child, 'SIGTERM')
|
|
30
160
|
const timer = setTimeout(() => {
|
|
31
161
|
if (child.exitCode === null && child.signalCode === null)
|
|
32
|
-
child
|
|
162
|
+
terminateProcessTree(child, 'SIGKILL')
|
|
33
163
|
}, 5000)
|
|
34
164
|
timer.unref()
|
|
35
165
|
void exited.then(() => clearTimeout(timer))
|
|
36
166
|
},
|
|
37
167
|
}
|
|
38
168
|
}
|
|
39
|
-
|
|
169
|
+
|
|
170
|
+
export const runCommand: CommandRunner = (
|
|
171
|
+
argv: readonly string[],
|
|
172
|
+
timeout: number,
|
|
173
|
+
options?: CommandOptions,
|
|
174
|
+
): Promise<CommandOutput> =>
|
|
40
175
|
new Promise((resolve) => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
176
|
+
if (options?.signal?.aborted) {
|
|
177
|
+
resolve({
|
|
178
|
+
code: -1,
|
|
179
|
+
stdout: '',
|
|
180
|
+
stderr: 'command aborted',
|
|
181
|
+
abortedBy: 'signal',
|
|
182
|
+
})
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
const maxStdoutBytes = options?.maxStdoutBytes ?? DEFAULT_MAX_STDOUT_BYTES
|
|
186
|
+
const child = spawn(argv[0]!, argv.slice(1), {
|
|
187
|
+
env: buildAgyEnv(),
|
|
188
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
189
|
+
detached: process.platform !== 'win32',
|
|
190
|
+
})
|
|
191
|
+
const stdoutChunks: Buffer[] = []
|
|
192
|
+
let stdoutBytes = 0
|
|
193
|
+
let stderr = ''
|
|
194
|
+
let settled = false
|
|
195
|
+
let abortedBy: CommandOutput['abortedBy']
|
|
196
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
197
|
+
let settleTimer: ReturnType<typeof setTimeout> | undefined
|
|
198
|
+
let exitDrainTimer: ReturnType<typeof setTimeout> | undefined
|
|
199
|
+
|
|
200
|
+
const finish = (code: number | null, errorMessage?: string): void => {
|
|
201
|
+
if (settled) return
|
|
202
|
+
settled = true
|
|
203
|
+
clearTimeout(timeoutTimer)
|
|
204
|
+
if (killTimer !== undefined) clearTimeout(killTimer)
|
|
205
|
+
if (settleTimer !== undefined) clearTimeout(settleTimer)
|
|
206
|
+
if (exitDrainTimer !== undefined) clearTimeout(exitDrainTimer)
|
|
207
|
+
options?.signal?.removeEventListener('abort', onSignalAbort)
|
|
208
|
+
const stdout = Buffer.concat(stdoutChunks).toString('utf8')
|
|
209
|
+
let finalStderr = redactStderr(stderr || errorMessage || '')
|
|
210
|
+
if (abortedBy === 'timeout' && finalStderr.trim().length === 0) {
|
|
211
|
+
finalStderr = 'command timed out'
|
|
212
|
+
} else if (abortedBy === 'maxStdout' && finalStderr.trim().length === 0) {
|
|
213
|
+
finalStderr = `stdout exceeded ${maxStdoutBytes} bytes`
|
|
214
|
+
} else if (abortedBy === 'signal' && finalStderr.trim().length === 0) {
|
|
215
|
+
finalStderr = 'command aborted'
|
|
216
|
+
}
|
|
217
|
+
resolve({
|
|
218
|
+
code:
|
|
219
|
+
abortedBy !== undefined
|
|
220
|
+
? code !== null && code !== 0
|
|
221
|
+
? code
|
|
222
|
+
: -1
|
|
223
|
+
: (code ?? -1),
|
|
224
|
+
stdout,
|
|
225
|
+
stderr: finalStderr,
|
|
226
|
+
...(abortedBy !== undefined ? { abortedBy } : {}),
|
|
227
|
+
})
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const abort = (reason: NonNullable<CommandOutput['abortedBy']>): void => {
|
|
231
|
+
if (settled || abortedBy !== undefined) return
|
|
232
|
+
abortedBy = reason
|
|
233
|
+
child.stdout.destroy()
|
|
234
|
+
child.stderr.destroy()
|
|
235
|
+
terminateProcessTree(child, 'SIGTERM')
|
|
236
|
+
killTimer = setTimeout(() => {
|
|
237
|
+
if (settled) return
|
|
238
|
+
terminateProcessTree(child, 'SIGKILL')
|
|
239
|
+
settleTimer = setTimeout(() => {
|
|
240
|
+
finish(child.exitCode)
|
|
241
|
+
}, SIGKILL_SETTLE_MS)
|
|
242
|
+
settleTimer.unref()
|
|
243
|
+
}, 1000)
|
|
244
|
+
killTimer.unref()
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const onSignalAbort = (): void => abort('signal')
|
|
248
|
+
options?.signal?.addEventListener('abort', onSignalAbort, { once: true })
|
|
249
|
+
|
|
250
|
+
const timeoutTimer = setTimeout(() => abort('timeout'), timeout)
|
|
251
|
+
timeoutTimer.unref()
|
|
252
|
+
|
|
253
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
254
|
+
if (abortedBy !== undefined) return
|
|
255
|
+
stdoutBytes += chunk.length
|
|
256
|
+
if (stdoutBytes > maxStdoutBytes) {
|
|
257
|
+
abort('maxStdout')
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
stdoutChunks.push(chunk)
|
|
261
|
+
})
|
|
262
|
+
|
|
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)) {
|
|
268
|
+
abort('stderr')
|
|
269
|
+
}
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
child.once('error', (error) => {
|
|
273
|
+
finish(-1, error.message)
|
|
274
|
+
})
|
|
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
|
+
|
|
287
|
+
child.once('close', (code) => {
|
|
288
|
+
finish(code)
|
|
289
|
+
})
|
|
53
290
|
})
|
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
|
}
|
package/src/pi-stream.ts
CHANGED
|
@@ -142,8 +142,8 @@ export function streamPi(
|
|
|
142
142
|
low: 'low',
|
|
143
143
|
medium: 'medium',
|
|
144
144
|
high: 'high',
|
|
145
|
-
xhigh: '
|
|
146
|
-
max: '
|
|
145
|
+
xhigh: 'xhigh',
|
|
146
|
+
max: 'max',
|
|
147
147
|
}[options.reasoning ?? 'off'],
|
|
148
148
|
}
|
|
149
149
|
// onPayload may replace request content, but harness-owned routing/cancellation
|