@unson/brainbase-mcp 0.50.29 → 0.50.30
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/contracts/brainbase-public-contract.v1.json +1 -0
- package/dist/antigravity-judgment-hook.d.ts +191 -0
- package/dist/antigravity-judgment-hook.js +2042 -0
- package/dist/claude-code-judgment-hook.d.ts +23 -0
- package/dist/claude-code-judgment-hook.js +8 -5
- package/dist/cli.js +273 -6
- package/dist/graph-retrieval.d.ts +4 -0
- package/dist/graph-retrieval.js +4 -0
- package/dist/judgment-event-adapter.d.ts +37 -2
- package/dist/judgment-event-adapter.js +88 -3
- package/dist/judgment-event-outbox.d.ts +9 -1
- package/dist/judgment-event-outbox.js +45 -8
- package/dist/judgment-execution-outcome.d.ts +2 -1
- package/dist/judgment-execution-outcome.js +2 -1
- package/dist/judgment-frame.d.ts +26 -4
- package/dist/judgment-frame.js +190 -15
- package/dist/judgment-host.d.ts +30 -0
- package/dist/judgment-host.js +170 -22
- package/dist/judgment-model-outcome.d.ts +29 -1
- package/dist/judgment-model-outcome.js +69 -1
- package/dist/judgment-offline-binary-audit.d.ts +360 -0
- package/dist/judgment-offline-binary-audit.js +555 -0
- package/dist/judgment-project-binding.d.ts +1 -1
- package/dist/judgment-project-binding.js +2 -1
- package/dist/judgment-reasoning-audit.d.ts +115 -0
- package/dist/judgment-reasoning-audit.js +623 -0
- package/dist/judgment-reasoning-gate-prompt.d.ts +42 -0
- package/dist/judgment-reasoning-gate-prompt.js +83 -0
- package/dist/judgment-runtime-resolution.d.ts +2 -2
- package/dist/judgment-runtime-resolution.js +2 -2
- package/dist/judgment-runtime-resolution.public.d.ts +2 -2
- package/dist/judgment-session-world-model.d.ts +163 -0
- package/dist/judgment-session-world-model.js +408 -0
- package/dist/organization-graph.js +9 -1
- package/dist/remote-judgment-hook-http.d.ts +36 -3
- package/dist/remote-judgment-hook-http.js +94 -15
- package/package.json +10 -2
|
@@ -0,0 +1,2042 @@
|
|
|
1
|
+
// Antigravity CLI adapter for a hosted Brainbase judgment Host.
|
|
2
|
+
//
|
|
3
|
+
// Antigravity runs this as a synchronous command hook (`brainbase judgment:antigravity-hook`)
|
|
4
|
+
// for PreInvocation, PreToolUse, PostToolUse, and Stop.
|
|
5
|
+
//
|
|
6
|
+
// Key protocol differences from Claude Code handled here:
|
|
7
|
+
// 1. PreInvocation fires before EVERY model call in a turn (including tool-call loops),
|
|
8
|
+
// and Reason Network may inject system USER_INPUT messages. Local turn state tracks
|
|
9
|
+
// `turn_active`, `turn_id`, `current_turn_user_step_index`, and `last_closed_user_step_index`
|
|
10
|
+
// so UserPromptSubmit is forwarded strictly once per user turn while rejecting delayed
|
|
11
|
+
// events from closed/older steps and draining turn-scoped pending messages safely.
|
|
12
|
+
// 2. Non-git workspaces (e.g. Orca bot homes) are supported when `project_code` is set
|
|
13
|
+
// and either `allow_non_git: true` or `cwd_prefixes` matches.
|
|
14
|
+
// 3. PostToolUse stdin omits `tool_response` and Stop stdin omits `last_assistant_message`.
|
|
15
|
+
// These are synthesized safely from `error` and bounded tail reads of `transcriptPath`.
|
|
16
|
+
// 4. Antigravity MCP tool names (`mcp_brainbase-unson_<tool>` / `call_mcp_tool`) are
|
|
17
|
+
// normalized to `mcp__brainbase__<tool>`.
|
|
18
|
+
// 5. Base URLs with path prefixes (e.g. `https://bb.unson.jp/runtime-mcp`) preserve their
|
|
19
|
+
// path when resolving `host/judgment/hook`.
|
|
20
|
+
// 6. Strict fail-open outputs with short HTTP timeouts:
|
|
21
|
+
// - PreInvocation: `{}` (or `{ injectSteps: [{ systemMessage: { systemMessage, metadata? } }], terminationBehavior: '' }`)
|
|
22
|
+
// - PreToolUse: `{ decision: 'allow' }` (or `{ decision: 'deny', reason }`)
|
|
23
|
+
// - PostToolUse: ALWAYS `{}` (any follow-up context is queued with `turn_id` for next PreInvocation)
|
|
24
|
+
// - Stop: ALWAYS `{ decision: '' }` (never `"continue"`)
|
|
25
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
26
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
27
|
+
import { accessSync, closeSync, constants as fsConstants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
28
|
+
import { homedir } from 'node:os';
|
|
29
|
+
import { delimiter, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
30
|
+
import { BrainbaseLoginError, getAccessTokenOfLogin } from './brainbase-login.js';
|
|
31
|
+
import { PRE_TOOL_USE_TOOLS, REGISTRATION_ID, bearerTransportSafe, canonicalFilePath, canonicalRepositoryIdentifier, digestSummary, forwardedStopPayload, hostCanMapRepository, resolveRepositoryScope, shellQuote, singleQuotedWords, } from './claude-code-judgment-hook.js';
|
|
32
|
+
export const ANTIGRAVITY_HOOK_CONFIG_SCHEMA = 'brainbase-antigravity-judgment-hook-v1';
|
|
33
|
+
export const ANTIGRAVITY_HOOK_COMMAND = 'judgment:antigravity-hook';
|
|
34
|
+
export const ANTIGRAVITY_HOOK_KEY = 'brainbase-judgment';
|
|
35
|
+
export const DEFAULT_ANTIGRAVITY_TIMEOUTS_MS = {
|
|
36
|
+
PreInvocation: 4_000,
|
|
37
|
+
PreToolUse: 2_500,
|
|
38
|
+
PostToolUse: 2_500,
|
|
39
|
+
Stop: 5_000,
|
|
40
|
+
};
|
|
41
|
+
const TURN_SCHEMA = 'brainbase-antigravity-judgment-turn-v1';
|
|
42
|
+
const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
|
|
43
|
+
const TRANSCRIPT_TAIL_MAX_BYTES = 256 * 1024;
|
|
44
|
+
const TRANSCRIPT_OPENAT_TIMEOUT_MS = 1_500;
|
|
45
|
+
const MAX_PENDING_MESSAGES = 8;
|
|
46
|
+
const DEFAULT_STALE_TURN_MS = 30 * 60 * 1000;
|
|
47
|
+
const MAX_CONFIG_TIMEOUT_MS = 60_000;
|
|
48
|
+
const TURN_STATE_LOCK_TIMEOUT_MS = 2_000;
|
|
49
|
+
const FLOCK_CONFLICT_EXIT_CODE = 75;
|
|
50
|
+
function sha256(text) {
|
|
51
|
+
return createHash('sha256').update(text).digest('hex');
|
|
52
|
+
}
|
|
53
|
+
function brainbaseHome(env) {
|
|
54
|
+
return join(env.HOME || homedir(), '.brainbase');
|
|
55
|
+
}
|
|
56
|
+
export function defaultAntigravityHookConfigPath(env = process.env) {
|
|
57
|
+
return env.BRAINBASE_ANTIGRAVITY_JUDGMENT_HOOK_CONFIG?.trim()
|
|
58
|
+
|| join(brainbaseHome(env), 'antigravity-judgment-hook.json');
|
|
59
|
+
}
|
|
60
|
+
export function defaultAntigravityHooksJsonPath(env = process.env) {
|
|
61
|
+
return join(env.HOME || homedir(), '.gemini', 'config', 'hooks.json');
|
|
62
|
+
}
|
|
63
|
+
/** Fail-open stdout contract per Antigravity lifecycle event. */
|
|
64
|
+
export function antigravityFailOpenOutput(eventName) {
|
|
65
|
+
if (eventName === 'Stop')
|
|
66
|
+
return { decision: '' };
|
|
67
|
+
if (eventName === 'PreToolUse')
|
|
68
|
+
return { decision: 'allow' };
|
|
69
|
+
return {};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Validates and normalizes a hosted MCP base URL while preserving its path
|
|
73
|
+
* prefix (e.g. `https://bb.unson.jp/runtime-mcp`).
|
|
74
|
+
*/
|
|
75
|
+
export function normalizeAntigravityHookBaseUrl(value) {
|
|
76
|
+
let url;
|
|
77
|
+
try {
|
|
78
|
+
url = new URL(value.trim());
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new BrainbaseLoginError('login_server_invalid', `Not a URL: ${value}`);
|
|
82
|
+
}
|
|
83
|
+
if (!bearerTransportSafe(url)) {
|
|
84
|
+
throw new BrainbaseLoginError('login_server_transport_unsafe', 'The server must use https (http is allowed only for localhost).');
|
|
85
|
+
}
|
|
86
|
+
if (url.username || url.password) {
|
|
87
|
+
throw new BrainbaseLoginError('login_server_invalid', 'The server URL must not contain a user name or password.');
|
|
88
|
+
}
|
|
89
|
+
if (url.search || url.hash) {
|
|
90
|
+
throw new BrainbaseLoginError('login_server_invalid', 'The hook base URL must not contain query parameters or a fragment.');
|
|
91
|
+
}
|
|
92
|
+
const cleanPath = url.pathname.replace(/\/+$/u, '');
|
|
93
|
+
return cleanPath ? `${url.origin}${cleanPath}` : url.origin;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Resolves the concrete judgment hook endpoint URL without dropping base URL
|
|
97
|
+
* path prefixes such as `/runtime-mcp`.
|
|
98
|
+
*/
|
|
99
|
+
export function resolveAntigravityHookEndpoint(config) {
|
|
100
|
+
if (typeof config.endpoint === 'string' && config.endpoint.trim()) {
|
|
101
|
+
let explicit;
|
|
102
|
+
try {
|
|
103
|
+
explicit = new URL(config.endpoint.trim());
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new Error('judgment_hook_endpoint_invalid');
|
|
107
|
+
}
|
|
108
|
+
if (!bearerTransportSafe(explicit) || explicit.username || explicit.password) {
|
|
109
|
+
throw new Error('judgment_hook_transport_unsafe');
|
|
110
|
+
}
|
|
111
|
+
return explicit;
|
|
112
|
+
}
|
|
113
|
+
let endpoint;
|
|
114
|
+
try {
|
|
115
|
+
const base = config.origin.trim();
|
|
116
|
+
const parsedBase = new URL(base);
|
|
117
|
+
if (parsedBase.username || parsedBase.password || parsedBase.search || parsedBase.hash) {
|
|
118
|
+
throw new Error('judgment_hook_endpoint_invalid');
|
|
119
|
+
}
|
|
120
|
+
const normalizedBase = base.endsWith('/') ? base : `${base}/`;
|
|
121
|
+
endpoint = new URL('host/judgment/hook', normalizedBase);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error instanceof Error && error.message === 'judgment_hook_endpoint_invalid')
|
|
125
|
+
throw error;
|
|
126
|
+
throw new Error('judgment_hook_endpoint_invalid');
|
|
127
|
+
}
|
|
128
|
+
if (!bearerTransportSafe(endpoint) || endpoint.username || endpoint.password) {
|
|
129
|
+
throw new Error('judgment_hook_transport_unsafe');
|
|
130
|
+
}
|
|
131
|
+
return endpoint;
|
|
132
|
+
}
|
|
133
|
+
function parseTimeouts(raw) {
|
|
134
|
+
if (raw === undefined)
|
|
135
|
+
return undefined;
|
|
136
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
137
|
+
return null;
|
|
138
|
+
const record = raw;
|
|
139
|
+
const result = {};
|
|
140
|
+
for (const key of ['PreInvocation', 'PreToolUse', 'PostToolUse', 'Stop']) {
|
|
141
|
+
if (record[key] === undefined)
|
|
142
|
+
continue;
|
|
143
|
+
const value = record[key];
|
|
144
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > MAX_CONFIG_TIMEOUT_MS) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
result[key] = Math.trunc(value);
|
|
148
|
+
}
|
|
149
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
150
|
+
}
|
|
151
|
+
export function readAntigravityHookConfig(path) {
|
|
152
|
+
let text;
|
|
153
|
+
try {
|
|
154
|
+
text = readFileSync(path, 'utf8');
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
return parseAntigravityHookConfig(text);
|
|
160
|
+
}
|
|
161
|
+
/** Parses an Antigravity hook config from JSON text, or null if unusable. */
|
|
162
|
+
export function parseAntigravityHookConfig(text) {
|
|
163
|
+
let parsed;
|
|
164
|
+
try {
|
|
165
|
+
parsed = JSON.parse(text);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const value = parsed;
|
|
171
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
172
|
+
return null;
|
|
173
|
+
if (value.schema_version !== ANTIGRAVITY_HOOK_CONFIG_SCHEMA)
|
|
174
|
+
return null;
|
|
175
|
+
if (typeof value.origin !== 'string' || !value.origin.trim())
|
|
176
|
+
return null;
|
|
177
|
+
if (typeof value.login_server !== 'string' || !value.login_server.trim())
|
|
178
|
+
return null;
|
|
179
|
+
if (value.endpoint !== undefined && (typeof value.endpoint !== 'string' || !value.endpoint.trim()))
|
|
180
|
+
return null;
|
|
181
|
+
if (value.allow_non_git !== undefined && typeof value.allow_non_git !== 'boolean')
|
|
182
|
+
return null;
|
|
183
|
+
let repositories;
|
|
184
|
+
if (value.repositories !== undefined) {
|
|
185
|
+
if (!Array.isArray(value.repositories))
|
|
186
|
+
return null;
|
|
187
|
+
repositories = [];
|
|
188
|
+
for (const entry of value.repositories) {
|
|
189
|
+
const normalized = typeof entry === 'string' ? canonicalRepositoryIdentifier(entry) : null;
|
|
190
|
+
if (!normalized)
|
|
191
|
+
return null;
|
|
192
|
+
repositories.push(normalized);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
let cwdPrefixes;
|
|
196
|
+
if (value.cwd_prefixes !== undefined) {
|
|
197
|
+
if (!Array.isArray(value.cwd_prefixes))
|
|
198
|
+
return null;
|
|
199
|
+
cwdPrefixes = [];
|
|
200
|
+
for (const entry of value.cwd_prefixes) {
|
|
201
|
+
if (typeof entry !== 'string' || !entry.trim())
|
|
202
|
+
return null;
|
|
203
|
+
cwdPrefixes.push(canonicalFilePath(entry.trim()));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const timeouts = parseTimeouts(value.timeouts_ms);
|
|
207
|
+
if (timeouts === null)
|
|
208
|
+
return null;
|
|
209
|
+
const registration = value.registration;
|
|
210
|
+
if (!registration || typeof registration.id !== 'string' || !REGISTRATION_ID.test(registration.id)
|
|
211
|
+
|| typeof registration.settings !== 'string' || !registration.settings) {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
schema_version: ANTIGRAVITY_HOOK_CONFIG_SCHEMA,
|
|
216
|
+
origin: value.origin.trim(),
|
|
217
|
+
...(value.endpoint ? { endpoint: value.endpoint.trim() } : {}),
|
|
218
|
+
login_server: value.login_server.trim(),
|
|
219
|
+
registration: { id: registration.id, settings: registration.settings },
|
|
220
|
+
...(typeof value.project_code === 'string' && value.project_code.trim()
|
|
221
|
+
? { project_code: value.project_code.trim() } : {}),
|
|
222
|
+
...(value.allow_non_git !== undefined ? { allow_non_git: value.allow_non_git } : {}),
|
|
223
|
+
...(cwdPrefixes !== undefined ? { cwd_prefixes: cwdPrefixes } : {}),
|
|
224
|
+
...(repositories !== undefined ? { repositories } : {}),
|
|
225
|
+
...(timeouts !== undefined ? { timeouts_ms: timeouts } : {}),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
export function isAntigravityHookConfigFile(path) {
|
|
229
|
+
try {
|
|
230
|
+
return isAntigravityHookConfigText(readFileSync(path, 'utf8'));
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
export function isAntigravityHookConfigText(text) {
|
|
237
|
+
try {
|
|
238
|
+
const parsed = JSON.parse(text);
|
|
239
|
+
return !!parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
240
|
+
&& parsed.schema_version === ANTIGRAVITY_HOOK_CONFIG_SCHEMA;
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// ---- Tool name normalization ----
|
|
247
|
+
/**
|
|
248
|
+
* Normalizes Antigravity MCP tool names to the canonical Brainbase Host format
|
|
249
|
+
* (`mcp__brainbase__<tool>`):
|
|
250
|
+
* - `mcp_brainbase_<tool>` or `mcp_brainbase-<suffix>_<tool>` -> `mcp__brainbase__<tool>`
|
|
251
|
+
* - `call_mcp_tool` with `ServerName` matching `^brainbase(?:-.+)?$` -> `mcp__brainbase__<ToolName>`
|
|
252
|
+
*/
|
|
253
|
+
export function normalizeAntigravityToolName(name, args) {
|
|
254
|
+
const trimmed = typeof name === 'string' ? name.trim() : '';
|
|
255
|
+
if (!trimmed)
|
|
256
|
+
return '';
|
|
257
|
+
if (trimmed.startsWith('mcp__brainbase__'))
|
|
258
|
+
return trimmed;
|
|
259
|
+
const eagerMatch = /^mcp_brainbase(?:-[a-z0-9-]+)?_(.+)$/u.exec(trimmed);
|
|
260
|
+
if (eagerMatch) {
|
|
261
|
+
return `mcp__brainbase__${eagerMatch[1]}`;
|
|
262
|
+
}
|
|
263
|
+
if (trimmed === 'call_mcp_tool' && args && typeof args === 'object' && !Array.isArray(args)) {
|
|
264
|
+
const record = args;
|
|
265
|
+
const serverName = typeof record.ServerName === 'string' ? record.ServerName.trim()
|
|
266
|
+
: typeof record.serverName === 'string' ? record.serverName.trim() : '';
|
|
267
|
+
const toolName = typeof record.ToolName === 'string' ? record.ToolName.trim()
|
|
268
|
+
: typeof record.toolName === 'string' ? record.toolName.trim() : '';
|
|
269
|
+
if (/^brainbase(?:-.+)?$/u.test(serverName) && toolName) {
|
|
270
|
+
return `mcp__brainbase__${toolName}`;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return trimmed;
|
|
274
|
+
}
|
|
275
|
+
function normalizedToolInput(rawName, normalizedName, args) {
|
|
276
|
+
if (rawName === 'call_mcp_tool' && normalizedName.startsWith('mcp__brainbase__')
|
|
277
|
+
&& args && typeof args === 'object' && !Array.isArray(args)) {
|
|
278
|
+
const record = args;
|
|
279
|
+
if ('Arguments' in record)
|
|
280
|
+
return record.Arguments;
|
|
281
|
+
if ('arguments' in record)
|
|
282
|
+
return record.arguments;
|
|
283
|
+
}
|
|
284
|
+
return args ?? {};
|
|
285
|
+
}
|
|
286
|
+
// ---- Scope resolution (git + non-git + cwd_prefixes) ----
|
|
287
|
+
function stripTrailingSeparator(pathValue) {
|
|
288
|
+
if (pathValue === sep || pathValue === '/')
|
|
289
|
+
return pathValue;
|
|
290
|
+
const trimmed = pathValue.replace(/[/\\]+$/u, '');
|
|
291
|
+
return trimmed || sep;
|
|
292
|
+
}
|
|
293
|
+
function matchesCwdPrefix(cwdCanonical, prefix) {
|
|
294
|
+
const canonicalPrefix = stripTrailingSeparator(canonicalFilePath(prefix));
|
|
295
|
+
const canonicalCwd = stripTrailingSeparator(cwdCanonical);
|
|
296
|
+
if (canonicalPrefix === sep || canonicalPrefix === '/') {
|
|
297
|
+
return canonicalCwd.startsWith(canonicalPrefix);
|
|
298
|
+
}
|
|
299
|
+
return canonicalCwd === canonicalPrefix || canonicalCwd.startsWith(`${canonicalPrefix}${sep}`);
|
|
300
|
+
}
|
|
301
|
+
function resolvePayloadCwd(payload) {
|
|
302
|
+
if (typeof payload.cwd === 'string' && payload.cwd.trim()) {
|
|
303
|
+
return canonicalFilePath(payload.cwd.trim());
|
|
304
|
+
}
|
|
305
|
+
if (Array.isArray(payload.workspacePaths)) {
|
|
306
|
+
const first = payload.workspacePaths.find((entry) => typeof entry === 'string' && entry.trim().length > 0);
|
|
307
|
+
if (first)
|
|
308
|
+
return canonicalFilePath(first.trim());
|
|
309
|
+
}
|
|
310
|
+
return canonicalFilePath(process.cwd());
|
|
311
|
+
}
|
|
312
|
+
function resolveAntigravityScope(payload, config, env) {
|
|
313
|
+
const cwd = resolvePayloadCwd(payload);
|
|
314
|
+
const gitScope = resolveRepositoryScope(cwd, env);
|
|
315
|
+
const matchedCwdPrefix = config.cwd_prefixes
|
|
316
|
+
? (config.cwd_prefixes.find((prefix) => matchesCwdPrefix(cwd, prefix)) ?? null)
|
|
317
|
+
: null;
|
|
318
|
+
return { ...gitScope, cwd, matchedCwdPrefix };
|
|
319
|
+
}
|
|
320
|
+
function isAuditedAntigravityScope(scope, config) {
|
|
321
|
+
if (config.cwd_prefixes !== undefined && scope.matchedCwdPrefix === null) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
if (scope.inGit) {
|
|
325
|
+
if (scope.unresolved)
|
|
326
|
+
return false;
|
|
327
|
+
if (scope.unidentified && !config.project_code)
|
|
328
|
+
return false;
|
|
329
|
+
if (!config.repositories)
|
|
330
|
+
return true;
|
|
331
|
+
return scope.repository !== null && config.repositories.includes(scope.repository);
|
|
332
|
+
}
|
|
333
|
+
// Non-git directory (e.g. Orca bot home): requires explicit project_code
|
|
334
|
+
// plus either allow_non_git: true or a matching cwd_prefixes entry.
|
|
335
|
+
if (!config.project_code)
|
|
336
|
+
return false;
|
|
337
|
+
return config.allow_non_git === true || scope.matchedCwdPrefix !== null;
|
|
338
|
+
}
|
|
339
|
+
function sameTurnScope(state, scope) {
|
|
340
|
+
if (state.matched_cwd_prefix !== scope.matchedCwdPrefix)
|
|
341
|
+
return false;
|
|
342
|
+
if (state.in_git) {
|
|
343
|
+
if (!scope.inGit)
|
|
344
|
+
return false;
|
|
345
|
+
if (typeof state.repository === 'string')
|
|
346
|
+
return state.repository === scope.repository;
|
|
347
|
+
return scope.repository === null && typeof state.checkout === 'string' && state.checkout === scope.checkout;
|
|
348
|
+
}
|
|
349
|
+
if (scope.inGit)
|
|
350
|
+
return false;
|
|
351
|
+
if (!state.non_git_scope_root)
|
|
352
|
+
return false;
|
|
353
|
+
return matchesCwdPrefix(scope.cwd, state.non_git_scope_root);
|
|
354
|
+
}
|
|
355
|
+
function resolvedEndpointString(config) {
|
|
356
|
+
try {
|
|
357
|
+
return resolveAntigravityHookEndpoint(config).toString();
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
function destinationOf(context) {
|
|
364
|
+
return JSON.stringify([
|
|
365
|
+
context.configPath,
|
|
366
|
+
resolvedEndpointString(context.config) ?? '',
|
|
367
|
+
context.config.login_server,
|
|
368
|
+
context.config.project_code ?? null,
|
|
369
|
+
context.config.allow_non_git === true,
|
|
370
|
+
context.config.cwd_prefixes ?? null,
|
|
371
|
+
context.config.repositories ?? null,
|
|
372
|
+
]);
|
|
373
|
+
}
|
|
374
|
+
function sameDestination(state, context) {
|
|
375
|
+
return state.destination === destinationOf(context);
|
|
376
|
+
}
|
|
377
|
+
function normalizeValidProjectCode(value) {
|
|
378
|
+
if (typeof value !== 'string')
|
|
379
|
+
return null;
|
|
380
|
+
return PROJECT_CODE_PATTERN.test(value) ? value : null;
|
|
381
|
+
}
|
|
382
|
+
function extractHostProjectCode(envelope, output) {
|
|
383
|
+
const specific = output.hookSpecificOutput
|
|
384
|
+
&& typeof output.hookSpecificOutput === 'object'
|
|
385
|
+
&& !Array.isArray(output.hookSpecificOutput)
|
|
386
|
+
? output.hookSpecificOutput
|
|
387
|
+
: null;
|
|
388
|
+
const binding = output.binding
|
|
389
|
+
&& typeof output.binding === 'object'
|
|
390
|
+
&& !Array.isArray(output.binding)
|
|
391
|
+
? output.binding
|
|
392
|
+
: null;
|
|
393
|
+
const candidates = [
|
|
394
|
+
envelope.project_code,
|
|
395
|
+
envelope.projectCode,
|
|
396
|
+
output.project_code,
|
|
397
|
+
output.projectCode,
|
|
398
|
+
specific?.project_code,
|
|
399
|
+
specific?.projectCode,
|
|
400
|
+
binding?.project_code,
|
|
401
|
+
binding?.projectCode,
|
|
402
|
+
].filter((value) => value !== undefined);
|
|
403
|
+
if (candidates.length === 0)
|
|
404
|
+
return { kind: 'missing' };
|
|
405
|
+
let resolved = null;
|
|
406
|
+
for (const raw of candidates) {
|
|
407
|
+
const valid = normalizeValidProjectCode(raw);
|
|
408
|
+
if (!valid)
|
|
409
|
+
return { kind: 'invalid' };
|
|
410
|
+
if (resolved !== null && resolved !== valid)
|
|
411
|
+
return { kind: 'invalid' };
|
|
412
|
+
resolved = valid;
|
|
413
|
+
}
|
|
414
|
+
return resolved ? { kind: 'valid', value: resolved } : { kind: 'missing' };
|
|
415
|
+
}
|
|
416
|
+
function resolveEffectiveProjectCode(envelope, output, configProjectCode) {
|
|
417
|
+
const hostResult = extractHostProjectCode(envelope, output);
|
|
418
|
+
if (hostResult.kind === 'invalid') {
|
|
419
|
+
return { ok: false, reason: 'invalid_host' };
|
|
420
|
+
}
|
|
421
|
+
const configValid = configProjectCode !== undefined ? normalizeValidProjectCode(configProjectCode) : null;
|
|
422
|
+
if (configProjectCode !== undefined && configValid === null) {
|
|
423
|
+
return { ok: false, reason: 'invalid_config' };
|
|
424
|
+
}
|
|
425
|
+
if (hostResult.kind === 'valid' && configValid !== null && hostResult.value !== configValid) {
|
|
426
|
+
return { ok: false, reason: 'mismatch' };
|
|
427
|
+
}
|
|
428
|
+
return { ok: true, value: hostResult.kind === 'valid' ? hostResult.value : configValid };
|
|
429
|
+
}
|
|
430
|
+
function derivePrincipalIdentity(obtained) {
|
|
431
|
+
const token = typeof obtained === 'string' ? obtained : obtained.token;
|
|
432
|
+
if (typeof token !== 'string' || !token.trim()) {
|
|
433
|
+
return { token: '', loginId: null };
|
|
434
|
+
}
|
|
435
|
+
const rawLoginId = typeof obtained === 'string' ? null : obtained.loginId;
|
|
436
|
+
if (typeof rawLoginId === 'string' && rawLoginId.trim()) {
|
|
437
|
+
return { token, loginId: `login:${rawLoginId.trim()}` };
|
|
438
|
+
}
|
|
439
|
+
return { token, loginId: `token-sha256:${sha256(token)}` };
|
|
440
|
+
}
|
|
441
|
+
function computeAuthFingerprint(context, nonGitScopeRoot, loginId, effectiveProjectCode) {
|
|
442
|
+
if (typeof loginId !== 'string' || !loginId)
|
|
443
|
+
return null;
|
|
444
|
+
const endpoint = resolvedEndpointString(context.config);
|
|
445
|
+
if (!endpoint)
|
|
446
|
+
return null;
|
|
447
|
+
if (!isAuditedAntigravityScope(context.scope, context.config)
|
|
448
|
+
|| !hostCanMapRepository(context.scope.repository, context.config)) {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
return sha256(JSON.stringify({
|
|
452
|
+
schema: TURN_SCHEMA,
|
|
453
|
+
config_path: context.configPath,
|
|
454
|
+
endpoint,
|
|
455
|
+
login_server: context.config.login_server,
|
|
456
|
+
project_code: context.config.project_code ?? null,
|
|
457
|
+
effective_project_code: effectiveProjectCode,
|
|
458
|
+
allow_non_git: context.config.allow_non_git === true,
|
|
459
|
+
cwd_prefixes: context.config.cwd_prefixes ?? null,
|
|
460
|
+
repositories: context.config.repositories ?? null,
|
|
461
|
+
in_git: context.scope.inGit,
|
|
462
|
+
repository: context.scope.repository,
|
|
463
|
+
checkout: context.scope.inGit ? context.scope.checkout : null,
|
|
464
|
+
matched_cwd_prefix: context.scope.matchedCwdPrefix,
|
|
465
|
+
non_git_scope_root: context.scope.inGit ? null : nonGitScopeRoot,
|
|
466
|
+
login: loginId,
|
|
467
|
+
}));
|
|
468
|
+
}
|
|
469
|
+
function isTurnStaticAuthorized(state, context) {
|
|
470
|
+
if (!state.turn_active || state.start_status !== 'started' || state.turn_generation <= 0) {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
if (typeof state.login !== 'string' || !state.login) {
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
if (typeof state.auth_fingerprint !== 'string' || !state.auth_fingerprint) {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
if (!isAuditedAntigravityScope(context.scope, context.config)
|
|
480
|
+
|| !hostCanMapRepository(context.scope.repository, context.config)) {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
if (!sameTurnScope(state, context.scope) || !sameDestination(state, context)) {
|
|
484
|
+
return false;
|
|
485
|
+
}
|
|
486
|
+
const expectedFingerprint = computeAuthFingerprint(context, state.non_git_scope_root, state.login, state.effective_project_code);
|
|
487
|
+
return expectedFingerprint !== null && expectedFingerprint === state.auth_fingerprint;
|
|
488
|
+
}
|
|
489
|
+
function canAuthorizePendingContext(state, context, currentLoginId) {
|
|
490
|
+
if (!isTurnStaticAuthorized(state, context))
|
|
491
|
+
return false;
|
|
492
|
+
if (typeof currentLoginId !== 'string' || !currentLoginId || state.login !== currentLoginId) {
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
// Pending context draining happens locally in PreInvocation without consulting the Host,
|
|
496
|
+
// so the caller MUST hold an authoritative explicit local project_code that matches the
|
|
497
|
+
// persisted effective_project_code. When config.project_code is absent (Host-assigned),
|
|
498
|
+
// we cannot verify locally whether Host assignment changed and MUST discard pending context.
|
|
499
|
+
const configuredProjectCode = normalizeValidProjectCode(context.config.project_code);
|
|
500
|
+
if (configuredProjectCode === null) {
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
const effectiveProjectCode = normalizeValidProjectCode(state.effective_project_code);
|
|
504
|
+
if (effectiveProjectCode === null || configuredProjectCode !== effectiveProjectCode) {
|
|
505
|
+
return false;
|
|
506
|
+
}
|
|
507
|
+
const expectedFingerprint = computeAuthFingerprint(context, state.non_git_scope_root, currentLoginId, configuredProjectCode);
|
|
508
|
+
return expectedFingerprint !== null && expectedFingerprint === state.auth_fingerprint;
|
|
509
|
+
}
|
|
510
|
+
async function resolveCurrentLoginId(context) {
|
|
511
|
+
try {
|
|
512
|
+
const obtained = await context.accessToken();
|
|
513
|
+
const { loginId } = derivePrincipalIdentity(obtained);
|
|
514
|
+
if (loginId === null)
|
|
515
|
+
return { ok: false };
|
|
516
|
+
return { ok: true, loginId };
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
return { ok: false };
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const ALLOWED_TRANSCRIPT_FILENAMES = new Set(['transcript.jsonl', 'transcript_full.jsonl']);
|
|
523
|
+
function isSafeConversationIdSegment(conversationId) {
|
|
524
|
+
return conversationId.length > 0
|
|
525
|
+
&& conversationId !== '.'
|
|
526
|
+
&& conversationId !== '..'
|
|
527
|
+
&& !conversationId.includes('/')
|
|
528
|
+
&& !conversationId.includes('\\')
|
|
529
|
+
&& !conversationId.includes('\0');
|
|
530
|
+
}
|
|
531
|
+
function defaultAntigravityTranscriptRoots(env) {
|
|
532
|
+
const configured = (env.BRAINBASE_ANTIGRAVITY_TRANSCRIPT_ROOTS ?? '')
|
|
533
|
+
.split(delimiter)
|
|
534
|
+
.map((entry) => entry.trim())
|
|
535
|
+
.filter(Boolean);
|
|
536
|
+
if (configured.length > 0)
|
|
537
|
+
return configured;
|
|
538
|
+
const home = env.HOME || homedir();
|
|
539
|
+
return [
|
|
540
|
+
join(home, '.gemini', 'antigravity-cli', 'brain'),
|
|
541
|
+
join(home, '.gemini', 'antigravity', 'brain'),
|
|
542
|
+
];
|
|
543
|
+
}
|
|
544
|
+
function canonicalTranscriptRoots(options) {
|
|
545
|
+
const rawRoots = options.allowedTranscriptRoots !== undefined
|
|
546
|
+
? [...options.allowedTranscriptRoots]
|
|
547
|
+
: defaultAntigravityTranscriptRoots(options.env ?? process.env);
|
|
548
|
+
const resolved = [];
|
|
549
|
+
for (const root of rawRoots) {
|
|
550
|
+
if (typeof root !== 'string' || !root.trim())
|
|
551
|
+
continue;
|
|
552
|
+
try {
|
|
553
|
+
resolved.push(realpathSync(root.trim()));
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
// Missing root cannot contain any authorized transcript file.
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return resolved;
|
|
560
|
+
}
|
|
561
|
+
function isStrictDescendantPath(canonicalRoot, candidatePath) {
|
|
562
|
+
if (!isAbsolute(canonicalRoot) || !isAbsolute(candidatePath))
|
|
563
|
+
return false;
|
|
564
|
+
const prefix = canonicalRoot === sep ? sep : `${canonicalRoot}${sep}`;
|
|
565
|
+
if (!candidatePath.startsWith(prefix))
|
|
566
|
+
return false;
|
|
567
|
+
const rel = relative(canonicalRoot, candidatePath);
|
|
568
|
+
if (!rel || rel === '.' || rel === '..' || isAbsolute(rel))
|
|
569
|
+
return false;
|
|
570
|
+
const segments = rel.split(sep);
|
|
571
|
+
return !segments.includes('..') && !segments.includes('.');
|
|
572
|
+
}
|
|
573
|
+
function matchesConversationTranscriptStructure(canonicalRoot, canonicalFile, conversationId) {
|
|
574
|
+
if (!isStrictDescendantPath(canonicalRoot, canonicalFile)) {
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
const rel = relative(canonicalRoot, canonicalFile);
|
|
578
|
+
const segments = rel.split(sep);
|
|
579
|
+
if (segments.length === 4
|
|
580
|
+
&& segments[0] === conversationId
|
|
581
|
+
&& segments[1] === '.system_generated'
|
|
582
|
+
&& segments[2] === 'logs'
|
|
583
|
+
&& ALLOWED_TRANSCRIPT_FILENAMES.has(segments[3])) {
|
|
584
|
+
return true;
|
|
585
|
+
}
|
|
586
|
+
if (segments.length === 5
|
|
587
|
+
&& segments[0] === 'brain'
|
|
588
|
+
&& segments[1] === conversationId
|
|
589
|
+
&& segments[2] === '.system_generated'
|
|
590
|
+
&& segments[3] === 'logs'
|
|
591
|
+
&& ALLOWED_TRANSCRIPT_FILENAMES.has(segments[4])) {
|
|
592
|
+
return true;
|
|
593
|
+
}
|
|
594
|
+
if (segments.length === 2
|
|
595
|
+
&& segments[0] === conversationId
|
|
596
|
+
&& ALLOWED_TRANSCRIPT_FILENAMES.has(segments[1])) {
|
|
597
|
+
return true;
|
|
598
|
+
}
|
|
599
|
+
if (segments.length === 1 && segments[0] === `${conversationId}.jsonl`) {
|
|
600
|
+
return true;
|
|
601
|
+
}
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
function isSafePathSegment(segment) {
|
|
605
|
+
return segment.length > 0
|
|
606
|
+
&& segment !== '.'
|
|
607
|
+
&& segment !== '..'
|
|
608
|
+
&& !segment.includes('/')
|
|
609
|
+
&& !segment.includes('\\')
|
|
610
|
+
&& !segment.includes('\0');
|
|
611
|
+
}
|
|
612
|
+
function verifyNoSymlinkPathUnderRoot(canonicalRoot, canonicalTarget) {
|
|
613
|
+
try {
|
|
614
|
+
const rootStat = lstatSync(canonicalRoot);
|
|
615
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory())
|
|
616
|
+
return { ok: false };
|
|
617
|
+
if (realpathSync(canonicalRoot) !== canonicalRoot)
|
|
618
|
+
return { ok: false };
|
|
619
|
+
if (!isStrictDescendantPath(canonicalRoot, canonicalTarget)) {
|
|
620
|
+
return { ok: false };
|
|
621
|
+
}
|
|
622
|
+
const rel = relative(canonicalRoot, canonicalTarget);
|
|
623
|
+
const segments = rel.split(sep);
|
|
624
|
+
if (segments.length === 0 || !segments.every(isSafePathSegment)) {
|
|
625
|
+
return { ok: false };
|
|
626
|
+
}
|
|
627
|
+
let current = canonicalRoot;
|
|
628
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
629
|
+
current = join(current, segments[i]);
|
|
630
|
+
const dirStat = lstatSync(current);
|
|
631
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
|
|
632
|
+
return { ok: false };
|
|
633
|
+
}
|
|
634
|
+
current = join(current, segments[segments.length - 1]);
|
|
635
|
+
const fileStat = lstatSync(current, { bigint: true });
|
|
636
|
+
if (fileStat.isSymbolicLink() || !fileStat.isFile())
|
|
637
|
+
return { ok: false };
|
|
638
|
+
return { ok: true, dev: fileStat.dev, ino: fileStat.ino };
|
|
639
|
+
}
|
|
640
|
+
catch {
|
|
641
|
+
return { ok: false };
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
function resolveAuthorizedTranscriptTarget(transcriptPath, options) {
|
|
645
|
+
if (typeof transcriptPath !== 'string' || !transcriptPath.trim() || transcriptPath.includes('\0')) {
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
const conversationId = options?.conversationId?.trim() ?? '';
|
|
649
|
+
if (!isSafeConversationIdSegment(conversationId))
|
|
650
|
+
return null;
|
|
651
|
+
const rawPath = transcriptPath.trim();
|
|
652
|
+
try {
|
|
653
|
+
// Reject symlinks, FIFOs, sockets, devices, and directories before resolving or opening.
|
|
654
|
+
if (!lstatSync(rawPath).isFile())
|
|
655
|
+
return null;
|
|
656
|
+
const canonicalPath = realpathSync(rawPath);
|
|
657
|
+
const roots = canonicalTranscriptRoots(options);
|
|
658
|
+
if (roots.length === 0)
|
|
659
|
+
return null;
|
|
660
|
+
const matchedRoot = roots.find((root) => (root !== sep
|
|
661
|
+
&& root !== '/'
|
|
662
|
+
&& matchesConversationTranscriptStructure(root, canonicalPath, conversationId)));
|
|
663
|
+
if (!matchedRoot)
|
|
664
|
+
return null;
|
|
665
|
+
if (!verifyNoSymlinkPathUnderRoot(matchedRoot, canonicalPath).ok)
|
|
666
|
+
return null;
|
|
667
|
+
const segments = relative(matchedRoot, canonicalPath).split(sep);
|
|
668
|
+
if (segments.length === 0 || !segments.every(isSafePathSegment))
|
|
669
|
+
return null;
|
|
670
|
+
return { canonicalRoot: matchedRoot, canonicalPath, segments };
|
|
671
|
+
}
|
|
672
|
+
catch {
|
|
673
|
+
return null;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function resolveAuthorizedTranscriptPath(transcriptPath, options) {
|
|
677
|
+
return resolveAuthorizedTranscriptTarget(transcriptPath, options)?.canonicalPath ?? null;
|
|
678
|
+
}
|
|
679
|
+
function buildPythonOpenatTailReader(faults) {
|
|
680
|
+
const forceOpenat2Errno = faults?.forceOpenat2Errno;
|
|
681
|
+
const renameAfterRead = faults?.renameAfterTailRead;
|
|
682
|
+
const lines = [
|
|
683
|
+
'import ctypes, errno, os, platform, stat, sys',
|
|
684
|
+
'def fail(): sys.exit(1)',
|
|
685
|
+
'if not sys.platform.startswith("linux"): fail()',
|
|
686
|
+
'if len(sys.argv) < 4: fail()',
|
|
687
|
+
'if not (hasattr(os, "O_NOFOLLOW") and hasattr(os, "O_DIRECTORY") and hasattr(os, "O_NONBLOCK") and (os.open in getattr(os, "supports_dir_fd", ()))): fail()',
|
|
688
|
+
'root = sys.argv[1]',
|
|
689
|
+
'try: max_bytes = int(sys.argv[2])',
|
|
690
|
+
'except ValueError: fail()',
|
|
691
|
+
'segments = sys.argv[3:]',
|
|
692
|
+
'if max_bytes <= 0 or not root or not os.path.isabs(root) or "\\x00" in root: fail()',
|
|
693
|
+
'root_parts = [p for p in root.split("/") if p]',
|
|
694
|
+
'if not root_parts or os.path.realpath(root) != root: fail()',
|
|
695
|
+
'if not segments: fail()',
|
|
696
|
+
'for seg in segments:',
|
|
697
|
+
' if not seg or seg in (".", "..") or "/" in seg or "\\\\" in seg or "\\x00" in seg: fail()',
|
|
698
|
+
'expected_exact_path = root.rstrip("/") + "/" + "/".join(segments)',
|
|
699
|
+
'def verify_fd_exact_path(fd, expected_path):',
|
|
700
|
+
' try:',
|
|
701
|
+
' actual = os.readlink(f"/proc/self/fd/{fd}")',
|
|
702
|
+
' except OSError:',
|
|
703
|
+
' fail()',
|
|
704
|
+
' if not actual or actual.endswith(" (deleted)") or actual != expected_path:',
|
|
705
|
+
' fail()',
|
|
706
|
+
'def openat2_beneath(root_fd, rel_bytes, flags):',
|
|
707
|
+
' arch = platform.machine().lower()',
|
|
708
|
+
' if arch not in ("x86_64", "amd64", "aarch64", "arm64", "i386", "i686", "armv7l", "armv6l", "riscv64", "s390x", "ppc64le", "ppc64", "loongarch64"):',
|
|
709
|
+
' fail()',
|
|
710
|
+
' class OpenHow(ctypes.Structure):',
|
|
711
|
+
' _fields_ = [("flags", ctypes.c_uint64), ("mode", ctypes.c_uint64), ("resolve", ctypes.c_uint64)]',
|
|
712
|
+
' try:',
|
|
713
|
+
' libc = ctypes.CDLL(None, use_errno=True)',
|
|
714
|
+
' syscall_fn = libc.syscall',
|
|
715
|
+
' syscall_fn.restype = ctypes.c_long',
|
|
716
|
+
' except (OSError, AttributeError):',
|
|
717
|
+
' fail()',
|
|
718
|
+
' RESOLVE_NO_SYMLINKS = 0x04',
|
|
719
|
+
' RESOLVE_BENEATH = 0x08',
|
|
720
|
+
' how = OpenHow(flags, 0, RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)',
|
|
721
|
+
' ctypes.set_errno(0)',
|
|
722
|
+
...(forceOpenat2Errno
|
|
723
|
+
? [
|
|
724
|
+
` ctypes.set_errno(errno.${forceOpenat2Errno})`,
|
|
725
|
+
' res = -1',
|
|
726
|
+
]
|
|
727
|
+
: [
|
|
728
|
+
' res = syscall_fn(ctypes.c_long(437), ctypes.c_int(root_fd), ctypes.c_char_p(rel_bytes), ctypes.byref(how), ctypes.c_size_t(ctypes.sizeof(how)))',
|
|
729
|
+
]),
|
|
730
|
+
' if res >= 0:',
|
|
731
|
+
' return int(res)',
|
|
732
|
+
' fail()',
|
|
733
|
+
'cloexec = getattr(os, "O_CLOEXEC", 0)',
|
|
734
|
+
'dir_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_NONBLOCK | cloexec',
|
|
735
|
+
'root_walk_flags = getattr(os, "O_PATH", os.O_RDONLY) | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_NONBLOCK | cloexec',
|
|
736
|
+
'file_flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | cloexec',
|
|
737
|
+
'cur_fd = -1',
|
|
738
|
+
'file_fd = -1',
|
|
739
|
+
'try:',
|
|
740
|
+
' cur_fd = os.open("/", root_walk_flags)',
|
|
741
|
+
' for idx, part in enumerate(root_parts):',
|
|
742
|
+
' flags = dir_flags if idx == len(root_parts) - 1 else root_walk_flags',
|
|
743
|
+
' next_fd = os.open(part, flags, dir_fd=cur_fd)',
|
|
744
|
+
' os.close(cur_fd)',
|
|
745
|
+
' cur_fd = next_fd',
|
|
746
|
+
' root_st = os.fstat(cur_fd)',
|
|
747
|
+
' if not stat.S_ISDIR(root_st.st_mode): fail()',
|
|
748
|
+
' verify_fd_exact_path(cur_fd, root)',
|
|
749
|
+
' if os.path.realpath(root) != root: fail()',
|
|
750
|
+
' root_lstat = os.lstat(root)',
|
|
751
|
+
' if root_lstat.st_dev != root_st.st_dev or root_lstat.st_ino != root_st.st_ino: fail()',
|
|
752
|
+
' rel_bytes = os.fsencode("/".join(segments))',
|
|
753
|
+
' file_fd = openat2_beneath(cur_fd, rel_bytes, file_flags)',
|
|
754
|
+
' verify_fd_exact_path(cur_fd, root)',
|
|
755
|
+
' os.close(cur_fd)',
|
|
756
|
+
' cur_fd = -1',
|
|
757
|
+
' st = os.fstat(file_fd)',
|
|
758
|
+
' if not stat.S_ISREG(st.st_mode): fail()',
|
|
759
|
+
' verify_fd_exact_path(file_fd, expected_exact_path)',
|
|
760
|
+
' size = st.st_size',
|
|
761
|
+
' if size <= 0: sys.exit(0)',
|
|
762
|
+
' read_size = min(size, max_bytes)',
|
|
763
|
+
' offset = size - read_size',
|
|
764
|
+
' chunks = []',
|
|
765
|
+
' remaining = read_size',
|
|
766
|
+
' pos = offset',
|
|
767
|
+
' has_pread = hasattr(os, "pread")',
|
|
768
|
+
' if not has_pread: os.lseek(file_fd, offset, os.SEEK_SET)',
|
|
769
|
+
' while remaining > 0:',
|
|
770
|
+
' chunk = os.pread(file_fd, remaining, pos) if has_pread else os.read(file_fd, remaining)',
|
|
771
|
+
' if not chunk: break',
|
|
772
|
+
' chunks.append(chunk)',
|
|
773
|
+
' n = len(chunk)',
|
|
774
|
+
' remaining -= n',
|
|
775
|
+
' pos += n',
|
|
776
|
+
...(renameAfterRead
|
|
777
|
+
? [` os.rename(${JSON.stringify(renameAfterRead.from)}, ${JSON.stringify(renameAfterRead.to)})`]
|
|
778
|
+
: []),
|
|
779
|
+
' verify_fd_exact_path(file_fd, expected_exact_path)',
|
|
780
|
+
' if not stat.S_ISREG(os.fstat(file_fd).st_mode): fail()',
|
|
781
|
+
' data = b"".join(chunks)',
|
|
782
|
+
' if offset > 0:',
|
|
783
|
+
' nl = data.find(b"\\n")',
|
|
784
|
+
' if nl < 0: sys.exit(0)',
|
|
785
|
+
' data = data[nl + 1:]',
|
|
786
|
+
' if data:',
|
|
787
|
+
' sys.stdout.buffer.write(data)',
|
|
788
|
+
' sys.stdout.buffer.flush()',
|
|
789
|
+
'except OSError:',
|
|
790
|
+
' fail()',
|
|
791
|
+
'finally:',
|
|
792
|
+
' if cur_fd >= 0:',
|
|
793
|
+
' try: os.close(cur_fd)',
|
|
794
|
+
' except OSError: pass',
|
|
795
|
+
' if file_fd >= 0:',
|
|
796
|
+
' try: os.close(file_fd)',
|
|
797
|
+
' except OSError: pass',
|
|
798
|
+
];
|
|
799
|
+
return lines.join('\n');
|
|
800
|
+
}
|
|
801
|
+
const PYTHON_OPENAT_TAIL_READER = buildPythonOpenatTailReader();
|
|
802
|
+
const DEFAULT_OPENAT_HELPER_CANDIDATES = [
|
|
803
|
+
'/usr/bin/python3',
|
|
804
|
+
'/usr/local/bin/python3',
|
|
805
|
+
'/bin/python3',
|
|
806
|
+
];
|
|
807
|
+
function isExecutableRegularFileAbsolute(candidate) {
|
|
808
|
+
if (!candidate || !isAbsolute(candidate) || candidate.includes('\0')) {
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
const resolved = realpathSync(candidate);
|
|
813
|
+
if (!isAbsolute(resolved) || !statSync(resolved).isFile()) {
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
accessSync(resolved, fsConstants.X_OK);
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
catch {
|
|
820
|
+
return false;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
function resolveOpenatHelperBinary(override, platform = process.platform, candidates = DEFAULT_OPENAT_HELPER_CANDIDATES) {
|
|
824
|
+
if (platform !== 'linux') {
|
|
825
|
+
return null;
|
|
826
|
+
}
|
|
827
|
+
if (override !== undefined) {
|
|
828
|
+
const trimmed = override.trim();
|
|
829
|
+
return isExecutableRegularFileAbsolute(trimmed) ? trimmed : null;
|
|
830
|
+
}
|
|
831
|
+
for (const candidate of candidates) {
|
|
832
|
+
if (isExecutableRegularFileAbsolute(candidate)) {
|
|
833
|
+
return candidate;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return null;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Reads up to `maxBytes` from the tail of a transcript file strictly via
|
|
840
|
+
* Linux 5.6+ kernel-enforced `openat2(RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)`
|
|
841
|
+
* plus mandatory `/proc/self/fd/{fd}` exact path verification before and after reading.
|
|
842
|
+
* Fails closed (`null`) immediately on non-Linux platforms, if `openat2` is unavailable
|
|
843
|
+
* or denied (`ENOSYS` / `EPERM` / any error), if fixed `python3` is missing, or if any
|
|
844
|
+
* kernel check rejects; NEVER falls back to staged `openat`, path-based `openSync`, or
|
|
845
|
+
* bare `PATH` lookups.
|
|
846
|
+
*/
|
|
847
|
+
function readTailViaKernelOpenat(canonicalRoot, segments, maxBytes, options) {
|
|
848
|
+
const effectivePlatform = options?.platform ?? process.platform;
|
|
849
|
+
if (effectivePlatform !== 'linux') {
|
|
850
|
+
return null;
|
|
851
|
+
}
|
|
852
|
+
if (!canonicalRoot || !isAbsolute(canonicalRoot) || canonicalRoot === '/' || canonicalRoot.includes('\0')) {
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
if (segments.length === 0 || !segments.every(isSafePathSegment)) {
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
const helperBin = resolveOpenatHelperBinary(options?.openatHelperBinary, effectivePlatform, options?.openatHelperCandidates);
|
|
859
|
+
if (!helperBin) {
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
const timeoutMs = options?.helperTimeoutMs ?? TRANSCRIPT_OPENAT_TIMEOUT_MS;
|
|
863
|
+
const helperScript = options?.openatTestFaults
|
|
864
|
+
? buildPythonOpenatTailReader(options.openatTestFaults)
|
|
865
|
+
: PYTHON_OPENAT_TAIL_READER;
|
|
866
|
+
try {
|
|
867
|
+
const result = spawnSync(helperBin, ['-I', '-c', helperScript, canonicalRoot, String(maxBytes), ...segments], {
|
|
868
|
+
encoding: 'buffer',
|
|
869
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
870
|
+
timeout: timeoutMs,
|
|
871
|
+
maxBuffer: maxBytes + 4096,
|
|
872
|
+
windowsHide: true,
|
|
873
|
+
});
|
|
874
|
+
if (result.error || result.signal !== null || result.status !== 0) {
|
|
875
|
+
return null;
|
|
876
|
+
}
|
|
877
|
+
if (!Buffer.isBuffer(result.stdout)) {
|
|
878
|
+
return null;
|
|
879
|
+
}
|
|
880
|
+
return result.stdout;
|
|
881
|
+
}
|
|
882
|
+
catch {
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
function readTranscriptTailEntries(transcriptPath, options, testHooks) {
|
|
887
|
+
const target = resolveAuthorizedTranscriptTarget(transcriptPath, options);
|
|
888
|
+
if (!target || !options)
|
|
889
|
+
return [];
|
|
890
|
+
try {
|
|
891
|
+
testHooks?.onBeforeOpen?.(target.canonicalPath);
|
|
892
|
+
const rawTail = readTailViaKernelOpenat(target.canonicalRoot, target.segments, TRANSCRIPT_TAIL_MAX_BYTES, {
|
|
893
|
+
openatHelperBinary: testHooks?.openatHelperBinary ?? options.openatHelperBinary,
|
|
894
|
+
openatHelperCandidates: testHooks?.openatHelperCandidates,
|
|
895
|
+
helperTimeoutMs: testHooks?.helperTimeoutMs,
|
|
896
|
+
platform: testHooks?.platform ?? options.platform,
|
|
897
|
+
openatTestFaults: testHooks?.openatTestFaults,
|
|
898
|
+
});
|
|
899
|
+
if (rawTail === null || rawTail.length === 0)
|
|
900
|
+
return [];
|
|
901
|
+
const text = rawTail.toString('utf8');
|
|
902
|
+
const entries = [];
|
|
903
|
+
for (const line of text.split(/\r?\n/u)) {
|
|
904
|
+
const trimmed = line.trim();
|
|
905
|
+
if (!trimmed)
|
|
906
|
+
continue;
|
|
907
|
+
try {
|
|
908
|
+
const parsed = JSON.parse(trimmed);
|
|
909
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
910
|
+
entries.push(parsed);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
catch {
|
|
914
|
+
// Ignore truncated or malformed lines.
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return entries;
|
|
918
|
+
}
|
|
919
|
+
catch {
|
|
920
|
+
return [];
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function stripUserRequestWrapper(text) {
|
|
924
|
+
const trimmed = text.trim();
|
|
925
|
+
const match = /^<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/u.exec(trimmed);
|
|
926
|
+
if (match)
|
|
927
|
+
return match[1].trim();
|
|
928
|
+
return trimmed;
|
|
929
|
+
}
|
|
930
|
+
const SYSTEM_INJECTED_PROMPT_PREFIXES = [
|
|
931
|
+
/^Reason Network:/iu,
|
|
932
|
+
/^<SYSTEM_MESSAGE>/iu,
|
|
933
|
+
];
|
|
934
|
+
/**
|
|
935
|
+
* Identifies system-injected USER_INPUT messages (e.g. Reason Network hooks)
|
|
936
|
+
* so they never masquerade as a fresh human prompt or trigger duplicate turns.
|
|
937
|
+
*/
|
|
938
|
+
export function isSystemInjectedUserInput(text, source) {
|
|
939
|
+
if (source === 'SYSTEM_SDK' || source === 'SYSTEM')
|
|
940
|
+
return true;
|
|
941
|
+
const unwrapped = stripUserRequestWrapper(text);
|
|
942
|
+
if (!unwrapped)
|
|
943
|
+
return true;
|
|
944
|
+
return SYSTEM_INJECTED_PROMPT_PREFIXES.some((pattern) => pattern.test(unwrapped));
|
|
945
|
+
}
|
|
946
|
+
export function extractLatestNonSystemUserInput(transcriptPath, options) {
|
|
947
|
+
const entries = readTranscriptTailEntries(transcriptPath, options);
|
|
948
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
949
|
+
const entry = entries[index];
|
|
950
|
+
if (entry.type !== 'USER_INPUT' || typeof entry.content !== 'string')
|
|
951
|
+
continue;
|
|
952
|
+
if (isSystemInjectedUserInput(entry.content, entry.source))
|
|
953
|
+
continue;
|
|
954
|
+
const content = stripUserRequestWrapper(entry.content);
|
|
955
|
+
if (!content)
|
|
956
|
+
continue;
|
|
957
|
+
const stepIndex = typeof entry.step_index === 'number' && Number.isSafeInteger(entry.step_index)
|
|
958
|
+
? entry.step_index
|
|
959
|
+
: null;
|
|
960
|
+
return { stepIndex, content };
|
|
961
|
+
}
|
|
962
|
+
return null;
|
|
963
|
+
}
|
|
964
|
+
export function extractLastAssistantMessage(transcriptPath, options) {
|
|
965
|
+
const entries = readTranscriptTailEntries(transcriptPath, options);
|
|
966
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
967
|
+
const entry = entries[index];
|
|
968
|
+
if (entry.type !== 'PLANNER_RESPONSE' || typeof entry.content !== 'string')
|
|
969
|
+
continue;
|
|
970
|
+
if (!entry.content.trim())
|
|
971
|
+
continue;
|
|
972
|
+
return entry.content;
|
|
973
|
+
}
|
|
974
|
+
return undefined;
|
|
975
|
+
}
|
|
976
|
+
function stripToolTimestampHeader(text) {
|
|
977
|
+
const lines = text.split(/\r?\n/u);
|
|
978
|
+
let index = 0;
|
|
979
|
+
while (index < lines.length && /^(?:Created At|Completed At):\s+/u.test(lines[index])) {
|
|
980
|
+
index += 1;
|
|
981
|
+
}
|
|
982
|
+
const body = lines.slice(index).join('\n').trim();
|
|
983
|
+
return body || text.trim();
|
|
984
|
+
}
|
|
985
|
+
export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
|
|
986
|
+
if (typeof stepIdx !== 'number' || !Number.isSafeInteger(stepIdx))
|
|
987
|
+
return null;
|
|
988
|
+
const entries = readTranscriptTailEntries(transcriptPath, options);
|
|
989
|
+
// Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
|
|
990
|
+
for (const targetStep of [stepIdx, stepIdx + 1]) {
|
|
991
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
992
|
+
const entry = entries[index];
|
|
993
|
+
if (entry.step_index !== targetStep)
|
|
994
|
+
continue;
|
|
995
|
+
if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
|
|
996
|
+
continue;
|
|
997
|
+
if (typeof entry.content !== 'string' || !entry.content.trim())
|
|
998
|
+
continue;
|
|
999
|
+
return stripToolTimestampHeader(entry.content);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return null;
|
|
1003
|
+
}
|
|
1004
|
+
// ---- Turn state persistence & exclusive lock ----
|
|
1005
|
+
function turnDirectory(env) {
|
|
1006
|
+
return env.BRAINBASE_ANTIGRAVITY_JUDGMENT_TURN_DIR
|
|
1007
|
+
|| join(brainbaseHome(env), 'var', 'antigravity-judgment-turns');
|
|
1008
|
+
}
|
|
1009
|
+
function turnKey(conversationId, configPath) {
|
|
1010
|
+
return sha256(`${conversationId}\n${configPath}`);
|
|
1011
|
+
}
|
|
1012
|
+
function statePath(env, key) {
|
|
1013
|
+
return join(turnDirectory(env), `${key}.json`);
|
|
1014
|
+
}
|
|
1015
|
+
function lockPathFor(env, key) {
|
|
1016
|
+
return `${statePath(env, key)}.lock`;
|
|
1017
|
+
}
|
|
1018
|
+
function resolveFlockBinary(override) {
|
|
1019
|
+
if (override !== undefined) {
|
|
1020
|
+
return override.trim() ? override : null;
|
|
1021
|
+
}
|
|
1022
|
+
if (process.platform === 'win32') {
|
|
1023
|
+
return null;
|
|
1024
|
+
}
|
|
1025
|
+
for (const candidate of ['/usr/bin/flock', '/bin/flock']) {
|
|
1026
|
+
try {
|
|
1027
|
+
accessSync(candidate, fsConstants.X_OK);
|
|
1028
|
+
return candidate;
|
|
1029
|
+
}
|
|
1030
|
+
catch { }
|
|
1031
|
+
}
|
|
1032
|
+
return 'flock';
|
|
1033
|
+
}
|
|
1034
|
+
function runFlockOnInheritedFd(flockBin, fd, remainingMs) {
|
|
1035
|
+
return new Promise((resolveOutcome) => {
|
|
1036
|
+
const args = remainingMs <= 0
|
|
1037
|
+
? ['-x', '-E', String(FLOCK_CONFLICT_EXIT_CODE), '-n', '3']
|
|
1038
|
+
: ['-x', '-E', String(FLOCK_CONFLICT_EXIT_CODE), '-w', Math.max(0.001, remainingMs / 1000).toFixed(3), '3'];
|
|
1039
|
+
let settled = false;
|
|
1040
|
+
const finish = (outcome) => {
|
|
1041
|
+
if (settled)
|
|
1042
|
+
return;
|
|
1043
|
+
settled = true;
|
|
1044
|
+
clearTimeout(watchdog);
|
|
1045
|
+
resolveOutcome(outcome);
|
|
1046
|
+
};
|
|
1047
|
+
const child = spawn(flockBin, args, {
|
|
1048
|
+
stdio: ['ignore', 'ignore', 'ignore', fd],
|
|
1049
|
+
windowsHide: true,
|
|
1050
|
+
});
|
|
1051
|
+
const watchdog = setTimeout(() => {
|
|
1052
|
+
try {
|
|
1053
|
+
child.kill('SIGKILL');
|
|
1054
|
+
}
|
|
1055
|
+
catch { }
|
|
1056
|
+
finish('timeout');
|
|
1057
|
+
}, Math.max(50, remainingMs) + 500);
|
|
1058
|
+
watchdog.unref();
|
|
1059
|
+
child.on('error', () => {
|
|
1060
|
+
finish('unavailable');
|
|
1061
|
+
});
|
|
1062
|
+
child.on('close', (code, signal) => {
|
|
1063
|
+
if (code === 0 && signal === null) {
|
|
1064
|
+
finish('acquired');
|
|
1065
|
+
}
|
|
1066
|
+
else if (code === FLOCK_CONFLICT_EXIT_CODE) {
|
|
1067
|
+
finish('timeout');
|
|
1068
|
+
}
|
|
1069
|
+
else {
|
|
1070
|
+
finish('unavailable');
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Acquires an OS kernel-managed `flock(2)` exclusive lock on the fixed lock file.
|
|
1077
|
+
*
|
|
1078
|
+
* The lock file is NEVER unlinked after creation: its inode stays fixed, and the
|
|
1079
|
+
* lock lives on the open file description held by `fd`. When the holder closes `fd`
|
|
1080
|
+
* (or crashes / is killed), the OS kernel releases the lock automatically without
|
|
1081
|
+
* any stale-lock unlink reaping.
|
|
1082
|
+
*/
|
|
1083
|
+
async function acquireOsFlockFd(lockPath, timeoutMs, flockBinaryOverride) {
|
|
1084
|
+
const flockBin = resolveFlockBinary(flockBinaryOverride);
|
|
1085
|
+
if (!flockBin) {
|
|
1086
|
+
throw new Error('antigravity_turn_state_lock_unavailable');
|
|
1087
|
+
}
|
|
1088
|
+
const openFlags = fsConstants.O_CREAT
|
|
1089
|
+
| fsConstants.O_RDWR
|
|
1090
|
+
| (fsConstants.O_NONBLOCK ?? 0)
|
|
1091
|
+
| (fsConstants.O_NOFOLLOW ?? 0);
|
|
1092
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
1093
|
+
for (;;) {
|
|
1094
|
+
let fd;
|
|
1095
|
+
try {
|
|
1096
|
+
fd = openSync(lockPath, openFlags, 0o600);
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
throw new Error('antigravity_turn_state_lock_unavailable');
|
|
1100
|
+
}
|
|
1101
|
+
let fdDev = 0n;
|
|
1102
|
+
let fdIno = 0n;
|
|
1103
|
+
try {
|
|
1104
|
+
const fdStat = fstatSync(fd, { bigint: true });
|
|
1105
|
+
if (!fdStat.isFile()) {
|
|
1106
|
+
closeSync(fd);
|
|
1107
|
+
throw new Error('antigravity_turn_state_lock_unavailable');
|
|
1108
|
+
}
|
|
1109
|
+
fdDev = fdStat.dev;
|
|
1110
|
+
fdIno = fdStat.ino;
|
|
1111
|
+
}
|
|
1112
|
+
catch (error) {
|
|
1113
|
+
try {
|
|
1114
|
+
closeSync(fd);
|
|
1115
|
+
}
|
|
1116
|
+
catch { }
|
|
1117
|
+
if (error instanceof Error && error.message === 'antigravity_turn_state_lock_unavailable') {
|
|
1118
|
+
throw error;
|
|
1119
|
+
}
|
|
1120
|
+
throw new Error('antigravity_turn_state_lock_unavailable');
|
|
1121
|
+
}
|
|
1122
|
+
const remainingMs = Math.max(0, deadline - Date.now());
|
|
1123
|
+
const outcome = await runFlockOnInheritedFd(flockBin, fd, remainingMs);
|
|
1124
|
+
if (outcome !== 'acquired') {
|
|
1125
|
+
try {
|
|
1126
|
+
closeSync(fd);
|
|
1127
|
+
}
|
|
1128
|
+
catch { }
|
|
1129
|
+
throw new Error(outcome === 'timeout'
|
|
1130
|
+
? 'antigravity_turn_state_lock_timeout'
|
|
1131
|
+
: 'antigravity_turn_state_lock_unavailable');
|
|
1132
|
+
}
|
|
1133
|
+
// Confirm the locked fd still corresponds to the current inode at `lockPath`
|
|
1134
|
+
// in case an external process unlinked or replaced the file before `flock` completed.
|
|
1135
|
+
try {
|
|
1136
|
+
const pathStat = lstatSync(lockPath, { bigint: true });
|
|
1137
|
+
if (pathStat.isFile() && pathStat.dev === fdDev && pathStat.ino === fdIno) {
|
|
1138
|
+
return fd;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
catch {
|
|
1142
|
+
// Fall through to close & retry if within deadline.
|
|
1143
|
+
}
|
|
1144
|
+
try {
|
|
1145
|
+
closeSync(fd);
|
|
1146
|
+
}
|
|
1147
|
+
catch { }
|
|
1148
|
+
if (Date.now() >= deadline) {
|
|
1149
|
+
throw new Error('antigravity_turn_state_lock_timeout');
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
async function withTurnStateLock(env, key, fn, options) {
|
|
1154
|
+
mkdirSync(turnDirectory(env), { recursive: true, mode: 0o700 });
|
|
1155
|
+
const lockPath = lockPathFor(env, key);
|
|
1156
|
+
const timeoutMs = options?.timeoutMs ?? TURN_STATE_LOCK_TIMEOUT_MS;
|
|
1157
|
+
const fd = await acquireOsFlockFd(lockPath, timeoutMs, options?.flockBinary);
|
|
1158
|
+
try {
|
|
1159
|
+
return await fn();
|
|
1160
|
+
}
|
|
1161
|
+
finally {
|
|
1162
|
+
// Release the OS kernel lock by closing the open file description; NEVER unlink `lockPath`.
|
|
1163
|
+
try {
|
|
1164
|
+
closeSync(fd);
|
|
1165
|
+
}
|
|
1166
|
+
catch { }
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
function parseOptionalStepIndex(value) {
|
|
1170
|
+
return typeof value === 'number' && Number.isSafeInteger(value) ? value : null;
|
|
1171
|
+
}
|
|
1172
|
+
function maxStepIndex(a, b) {
|
|
1173
|
+
if (a === null)
|
|
1174
|
+
return b;
|
|
1175
|
+
if (b === null)
|
|
1176
|
+
return a;
|
|
1177
|
+
return Math.max(a, b);
|
|
1178
|
+
}
|
|
1179
|
+
function readState(env, key) {
|
|
1180
|
+
try {
|
|
1181
|
+
const parsed = JSON.parse(readFileSync(statePath(env, key), 'utf8'));
|
|
1182
|
+
if (!parsed || parsed.schema_version !== TURN_SCHEMA || typeof parsed.turn_id !== 'string' || !parsed.turn_id) {
|
|
1183
|
+
return null;
|
|
1184
|
+
}
|
|
1185
|
+
const pending = Array.isArray(parsed.pending_messages)
|
|
1186
|
+
? parsed.pending_messages.filter((item) => (!!item && typeof item === 'object' && typeof item.turn_id === 'string'))
|
|
1187
|
+
: [];
|
|
1188
|
+
const generation = typeof parsed.turn_generation === 'number'
|
|
1189
|
+
&& Number.isSafeInteger(parsed.turn_generation) && parsed.turn_generation > 0
|
|
1190
|
+
? parsed.turn_generation
|
|
1191
|
+
: 0;
|
|
1192
|
+
const turnActive = parsed.turn_active === true;
|
|
1193
|
+
const lastOpened = parseOptionalStepIndex(parsed.last_opened_user_step_index);
|
|
1194
|
+
const isLegacyStepState = parsed.current_turn_user_step_index === undefined
|
|
1195
|
+
&& parsed.last_closed_user_step_index === undefined;
|
|
1196
|
+
const hasCurrentStepField = Object.prototype.hasOwnProperty.call(parsed, 'current_turn_user_step_index');
|
|
1197
|
+
const hasLastClosedField = Object.prototype.hasOwnProperty.call(parsed, 'last_closed_user_step_index');
|
|
1198
|
+
let currentTurnUserStepIndex = isLegacyStepState
|
|
1199
|
+
? null
|
|
1200
|
+
: (hasCurrentStepField ? parseOptionalStepIndex(parsed.current_turn_user_step_index) : null);
|
|
1201
|
+
let lastClosedUserStepIndex = isLegacyStepState
|
|
1202
|
+
? lastOpened
|
|
1203
|
+
: (hasLastClosedField ? parseOptionalStepIndex(parsed.last_closed_user_step_index) : lastOpened);
|
|
1204
|
+
if (!turnActive && currentTurnUserStepIndex !== null) {
|
|
1205
|
+
lastClosedUserStepIndex = maxStepIndex(lastClosedUserStepIndex, currentTurnUserStepIndex);
|
|
1206
|
+
currentTurnUserStepIndex = null;
|
|
1207
|
+
}
|
|
1208
|
+
return {
|
|
1209
|
+
schema_version: TURN_SCHEMA,
|
|
1210
|
+
turn_id: parsed.turn_id,
|
|
1211
|
+
turn_generation: generation,
|
|
1212
|
+
turn_active: turnActive,
|
|
1213
|
+
started_at: typeof parsed.started_at === 'string' ? parsed.started_at : new Date(0).toISOString(),
|
|
1214
|
+
current_turn_user_step_index: currentTurnUserStepIndex,
|
|
1215
|
+
last_closed_user_step_index: lastClosedUserStepIndex,
|
|
1216
|
+
last_opened_user_step_index: lastOpened,
|
|
1217
|
+
last_prompt_digest: typeof parsed.last_prompt_digest === 'string' ? parsed.last_prompt_digest : null,
|
|
1218
|
+
start_status: parsed.start_status === 'started' || parsed.start_status === 'out_of_scope'
|
|
1219
|
+
? parsed.start_status : 'failed',
|
|
1220
|
+
in_git: parsed.in_git === true,
|
|
1221
|
+
repository: typeof parsed.repository === 'string' ? parsed.repository : null,
|
|
1222
|
+
checkout: typeof parsed.checkout === 'string' ? parsed.checkout : null,
|
|
1223
|
+
non_git_scope_root: typeof parsed.non_git_scope_root === 'string' ? parsed.non_git_scope_root : null,
|
|
1224
|
+
matched_cwd_prefix: typeof parsed.matched_cwd_prefix === 'string' ? parsed.matched_cwd_prefix : null,
|
|
1225
|
+
destination: typeof parsed.destination === 'string' ? parsed.destination : '',
|
|
1226
|
+
login: typeof parsed.login === 'string' && parsed.login ? parsed.login : null,
|
|
1227
|
+
effective_project_code: normalizeValidProjectCode(parsed.effective_project_code),
|
|
1228
|
+
auth_fingerprint: typeof parsed.auth_fingerprint === 'string' && parsed.auth_fingerprint
|
|
1229
|
+
? parsed.auth_fingerprint : null,
|
|
1230
|
+
pending_messages: pending,
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
catch {
|
|
1234
|
+
return null;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
function writeState(env, key, state) {
|
|
1238
|
+
mkdirSync(turnDirectory(env), { recursive: true, mode: 0o700 });
|
|
1239
|
+
const target = statePath(env, key);
|
|
1240
|
+
const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
|
|
1241
|
+
try {
|
|
1242
|
+
writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
|
|
1243
|
+
renameSync(temporary, target);
|
|
1244
|
+
}
|
|
1245
|
+
catch (error) {
|
|
1246
|
+
try {
|
|
1247
|
+
unlinkSync(temporary);
|
|
1248
|
+
}
|
|
1249
|
+
catch { }
|
|
1250
|
+
throw error;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
// ---- Transport ----
|
|
1254
|
+
/** Namespaces session and turn IDs per registration, matching Claude Code isolation. */
|
|
1255
|
+
export function antigravityNamespacedId(id, config) {
|
|
1256
|
+
return `${id}.bb-${sha256(`brainbase-antigravity-registration\n${config.registration.id}`).slice(0, 16)}`;
|
|
1257
|
+
}
|
|
1258
|
+
function timeoutForEvent(config, antigravityEvent) {
|
|
1259
|
+
return config.timeouts_ms?.[antigravityEvent] ?? DEFAULT_ANTIGRAVITY_TIMEOUTS_MS[antigravityEvent];
|
|
1260
|
+
}
|
|
1261
|
+
function turnLogin(state) {
|
|
1262
|
+
return { expected: typeof state.login === 'string' && state.login ? state.login : '\u0000unrecorded' };
|
|
1263
|
+
}
|
|
1264
|
+
async function forward(payload, context, repository, login, antigravityEvent) {
|
|
1265
|
+
if (!hostCanMapRepository(repository, context.config))
|
|
1266
|
+
throw new Error('judgment_repository_unmappable');
|
|
1267
|
+
const endpoint = resolveAntigravityHookEndpoint(context.config);
|
|
1268
|
+
let token;
|
|
1269
|
+
let loginId;
|
|
1270
|
+
try {
|
|
1271
|
+
const obtained = await context.accessToken();
|
|
1272
|
+
const identity = derivePrincipalIdentity(obtained);
|
|
1273
|
+
token = identity.token;
|
|
1274
|
+
loginId = identity.loginId;
|
|
1275
|
+
}
|
|
1276
|
+
catch (error) {
|
|
1277
|
+
const code = error?.code;
|
|
1278
|
+
throw new Error(typeof code === 'string' && /^login_[a-z_]{1,60}$/u.test(code)
|
|
1279
|
+
? `judgment_hook_${code}` : 'judgment_hook_login_unavailable');
|
|
1280
|
+
}
|
|
1281
|
+
if (!token || loginId === null)
|
|
1282
|
+
throw new Error('judgment_hook_login_unavailable');
|
|
1283
|
+
if (login.expected !== undefined && login.expected !== loginId)
|
|
1284
|
+
throw new Error('judgment_turn_login_changed');
|
|
1285
|
+
login.used = loginId;
|
|
1286
|
+
const sent = {
|
|
1287
|
+
...payload,
|
|
1288
|
+
session_id: antigravityNamespacedId(String(payload.session_id), context.config),
|
|
1289
|
+
turn_id: antigravityNamespacedId(String(payload.turn_id), context.config),
|
|
1290
|
+
};
|
|
1291
|
+
let response;
|
|
1292
|
+
try {
|
|
1293
|
+
response = await context.fetch(endpoint, {
|
|
1294
|
+
method: 'POST',
|
|
1295
|
+
headers: {
|
|
1296
|
+
'content-type': 'application/json',
|
|
1297
|
+
authorization: `Bearer ${token}`,
|
|
1298
|
+
'x-brainbase-judgment-host': 'antigravity',
|
|
1299
|
+
...(context.config.project_code ? { 'x-brainbase-project-code': context.config.project_code } : {}),
|
|
1300
|
+
...(repository ? { 'x-brainbase-repository': repository } : {}),
|
|
1301
|
+
},
|
|
1302
|
+
body: JSON.stringify(sent),
|
|
1303
|
+
redirect: 'error',
|
|
1304
|
+
signal: AbortSignal.timeout(timeoutForEvent(context.config, antigravityEvent)),
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
catch (error) {
|
|
1308
|
+
throw new Error(error?.name === 'TimeoutError'
|
|
1309
|
+
? 'judgment_hook_timeout' : 'judgment_hook_unreachable');
|
|
1310
|
+
}
|
|
1311
|
+
const text = await response.text();
|
|
1312
|
+
let envelope;
|
|
1313
|
+
try {
|
|
1314
|
+
envelope = JSON.parse(text);
|
|
1315
|
+
}
|
|
1316
|
+
catch {
|
|
1317
|
+
envelope = null;
|
|
1318
|
+
}
|
|
1319
|
+
if (!response.ok) {
|
|
1320
|
+
const upstream = typeof envelope?.error === 'string' && /^[a-z0-9_]{1,80}$/u.test(envelope.error)
|
|
1321
|
+
? `_${envelope.error}` : '';
|
|
1322
|
+
throw new Error(`judgment_hook_http_${response.status}${upstream}`);
|
|
1323
|
+
}
|
|
1324
|
+
const output = envelope?.output;
|
|
1325
|
+
if (!envelope || envelope.schema_version !== '1' || envelope.accepted !== true
|
|
1326
|
+
|| envelope.hook_event_name !== payload.hook_event_name
|
|
1327
|
+
|| envelope.session_id !== sent.session_id || envelope.turn_id !== sent.turn_id
|
|
1328
|
+
|| !output || typeof output !== 'object' || Array.isArray(output)) {
|
|
1329
|
+
throw new Error('judgment_hook_response_invalid');
|
|
1330
|
+
}
|
|
1331
|
+
return { output: output, envelope };
|
|
1332
|
+
}
|
|
1333
|
+
// ---- Output conversion (Host -> Antigravity injectSteps) ----
|
|
1334
|
+
function extractHostMessages(output) {
|
|
1335
|
+
const systemMessage = typeof output.systemMessage === 'string' && output.systemMessage.trim()
|
|
1336
|
+
? output.systemMessage.trim()
|
|
1337
|
+
: undefined;
|
|
1338
|
+
const specific = output.hookSpecificOutput;
|
|
1339
|
+
const additionalContext = specific && typeof specific === 'object' && !Array.isArray(specific)
|
|
1340
|
+
&& typeof specific.additionalContext === 'string' && specific.additionalContext.trim()
|
|
1341
|
+
? specific.additionalContext.trim()
|
|
1342
|
+
: undefined;
|
|
1343
|
+
return { additionalContext, systemMessage };
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Formats a Brainbase judgment context as an Antigravity `injectSteps` entry.
|
|
1347
|
+
* Because `systemMessage` persists in Antigravity's conversation trajectory across turns,
|
|
1348
|
+
* the header binds it to the current `turn_id` and explicitly supersedes earlier turns.
|
|
1349
|
+
*/
|
|
1350
|
+
function buildSystemMessageStep(turnId, additionalContext, userMarkdown) {
|
|
1351
|
+
if (!additionalContext && !userMarkdown)
|
|
1352
|
+
return null;
|
|
1353
|
+
const guardHeader = [
|
|
1354
|
+
`[Brainbase Judgment Turn: ${turnId}]`,
|
|
1355
|
+
`※この判断契約・先頭監査行は当ターン(${turnId})のみ有効です。過去のターンに注入された旧ターンの判断契約・先頭監査行は上書きされ無効です。`,
|
|
1356
|
+
].join('\n');
|
|
1357
|
+
const modelText = additionalContext ? `${guardHeader}\n\n${additionalContext}` : '';
|
|
1358
|
+
return {
|
|
1359
|
+
systemMessage: {
|
|
1360
|
+
systemMessage: modelText,
|
|
1361
|
+
...(userMarkdown ? { metadata: { user_markdown: userMarkdown } } : {}),
|
|
1362
|
+
},
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
function preInvocationOutputFromSteps(steps) {
|
|
1366
|
+
if (steps.length === 0)
|
|
1367
|
+
return {};
|
|
1368
|
+
return {
|
|
1369
|
+
injectSteps: steps,
|
|
1370
|
+
terminationBehavior: '',
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
// ---- Event handlers ----
|
|
1374
|
+
function isStaleOrAlreadyClosedStep(state, currentUserStepIndex) {
|
|
1375
|
+
if (currentUserStepIndex === null) {
|
|
1376
|
+
return false;
|
|
1377
|
+
}
|
|
1378
|
+
if (state.last_closed_user_step_index !== null && currentUserStepIndex <= state.last_closed_user_step_index) {
|
|
1379
|
+
return true;
|
|
1380
|
+
}
|
|
1381
|
+
if (state.current_turn_user_step_index !== null) {
|
|
1382
|
+
if (currentUserStepIndex < state.current_turn_user_step_index) {
|
|
1383
|
+
return true;
|
|
1384
|
+
}
|
|
1385
|
+
if (!state.turn_active && currentUserStepIndex <= state.current_turn_user_step_index) {
|
|
1386
|
+
return true;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
return false;
|
|
1390
|
+
}
|
|
1391
|
+
function shouldRecoverNewTurn(state, currentUserStepIndex, promptDigest, invocationNum, nowMs, staleTurnMs) {
|
|
1392
|
+
// Always reject delayed past-step events (and duplicate closed-step events)
|
|
1393
|
+
// BEFORE checking `!state.turn_active`.
|
|
1394
|
+
if (isStaleOrAlreadyClosedStep(state, currentUserStepIndex)) {
|
|
1395
|
+
return false;
|
|
1396
|
+
}
|
|
1397
|
+
if (!state.turn_active)
|
|
1398
|
+
return true;
|
|
1399
|
+
if (currentUserStepIndex !== null && state.current_turn_user_step_index !== null) {
|
|
1400
|
+
if (currentUserStepIndex > state.current_turn_user_step_index) {
|
|
1401
|
+
return true;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
if (invocationNum === 1) {
|
|
1405
|
+
if (promptDigest !== null && state.last_prompt_digest !== null && promptDigest !== state.last_prompt_digest) {
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
const startedMs = Date.parse(state.started_at);
|
|
1409
|
+
if (Number.isFinite(startedMs) && (nowMs - startedMs) >= staleTurnMs) {
|
|
1410
|
+
return true;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
return false;
|
|
1414
|
+
}
|
|
1415
|
+
function transcriptOptionsFor(conversationId, context) {
|
|
1416
|
+
return {
|
|
1417
|
+
conversationId,
|
|
1418
|
+
env: context.env,
|
|
1419
|
+
...(context.allowedTranscriptRoots !== undefined
|
|
1420
|
+
? { allowedTranscriptRoots: context.allowedTranscriptRoots } : {}),
|
|
1421
|
+
...(context.transcriptOpenatBinary !== undefined
|
|
1422
|
+
? { openatHelperBinary: context.transcriptOpenatBinary } : {}),
|
|
1423
|
+
...(context.platform !== undefined
|
|
1424
|
+
? { platform: context.platform } : {}),
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
function matchesPendingEntry(entry, state, expectedProjectCode) {
|
|
1428
|
+
if (entry.turn_id !== state.turn_id)
|
|
1429
|
+
return false;
|
|
1430
|
+
if (entry.turn_generation !== state.turn_generation)
|
|
1431
|
+
return false;
|
|
1432
|
+
const effectiveProject = normalizeValidProjectCode(state.effective_project_code);
|
|
1433
|
+
if (effectiveProject === null || effectiveProject !== expectedProjectCode)
|
|
1434
|
+
return false;
|
|
1435
|
+
if (typeof entry.project_code !== 'string' || entry.project_code !== expectedProjectCode)
|
|
1436
|
+
return false;
|
|
1437
|
+
return true;
|
|
1438
|
+
}
|
|
1439
|
+
async function handlePreInvocation(payload, conversationId, context) {
|
|
1440
|
+
const key = turnKey(conversationId, context.configPath);
|
|
1441
|
+
const transcriptOpts = transcriptOptionsFor(conversationId, context);
|
|
1442
|
+
const authorizedTranscriptPath = resolveAuthorizedTranscriptPath(payload.transcriptPath, transcriptOpts);
|
|
1443
|
+
const transcriptUser = extractLatestNonSystemUserInput(payload.transcriptPath, transcriptOpts);
|
|
1444
|
+
const rawLastUserInput = typeof payload.lastUserInput === 'string' ? payload.lastUserInput : '';
|
|
1445
|
+
const prompt = rawLastUserInput && !isSystemInjectedUserInput(rawLastUserInput)
|
|
1446
|
+
? stripUserRequestWrapper(rawLastUserInput)
|
|
1447
|
+
: (transcriptUser?.content ?? null);
|
|
1448
|
+
const currentUserStepIndex = transcriptUser?.stepIndex ?? null;
|
|
1449
|
+
const promptDigest = prompt ? sha256(prompt) : null;
|
|
1450
|
+
const invocationNum = typeof payload.invocationNum === 'number' && Number.isSafeInteger(payload.invocationNum)
|
|
1451
|
+
? payload.invocationNum : null;
|
|
1452
|
+
const nonGitRoot = context.scope.inGit
|
|
1453
|
+
? null
|
|
1454
|
+
: (context.scope.matchedCwdPrefix ?? context.scope.cwd);
|
|
1455
|
+
const inScope = isAuditedAntigravityScope(context.scope, context.config)
|
|
1456
|
+
&& hostCanMapRepository(context.scope.repository, context.config);
|
|
1457
|
+
// Atomically decide whether to open a new turn or join the existing active turn
|
|
1458
|
+
// AND write the new turn state within a single OS-locked critical section.
|
|
1459
|
+
const decision = await withTurnStateLock(context.env, key, () => {
|
|
1460
|
+
const latest = readState(context.env, key);
|
|
1461
|
+
const nowMs = context.now();
|
|
1462
|
+
if (latest && isStaleOrAlreadyClosedStep(latest, currentUserStepIndex)) {
|
|
1463
|
+
return { kind: 'stale_step' };
|
|
1464
|
+
}
|
|
1465
|
+
if (latest && !shouldRecoverNewTurn(latest, currentUserStepIndex, promptDigest, invocationNum, nowMs, context.staleTurnMs)) {
|
|
1466
|
+
return { kind: 'existing_turn', state: latest };
|
|
1467
|
+
}
|
|
1468
|
+
if (!prompt) {
|
|
1469
|
+
if (latest && latest.pending_messages.length > 0) {
|
|
1470
|
+
writeState(context.env, key, {
|
|
1471
|
+
...latest,
|
|
1472
|
+
turn_active: false,
|
|
1473
|
+
current_turn_user_step_index: null,
|
|
1474
|
+
last_closed_user_step_index: maxStepIndex(latest.last_closed_user_step_index, latest.current_turn_user_step_index),
|
|
1475
|
+
pending_messages: [],
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
return { kind: 'no_prompt' };
|
|
1479
|
+
}
|
|
1480
|
+
const nextGeneration = (latest?.turn_generation ?? 0) + 1;
|
|
1481
|
+
const closingPreviousStep = latest
|
|
1482
|
+
&& latest.current_turn_user_step_index !== null
|
|
1483
|
+
&& (!latest.turn_active || latest.current_turn_user_step_index !== currentUserStepIndex)
|
|
1484
|
+
? latest.current_turn_user_step_index
|
|
1485
|
+
: null;
|
|
1486
|
+
const nextLastClosedUserStepIndex = maxStepIndex(latest?.last_closed_user_step_index ?? null, closingPreviousStep);
|
|
1487
|
+
const state = {
|
|
1488
|
+
schema_version: TURN_SCHEMA,
|
|
1489
|
+
turn_id: randomUUID(),
|
|
1490
|
+
turn_generation: nextGeneration,
|
|
1491
|
+
turn_active: true,
|
|
1492
|
+
started_at: new Date(nowMs).toISOString(),
|
|
1493
|
+
current_turn_user_step_index: currentUserStepIndex,
|
|
1494
|
+
last_closed_user_step_index: nextLastClosedUserStepIndex,
|
|
1495
|
+
last_opened_user_step_index: currentUserStepIndex,
|
|
1496
|
+
last_prompt_digest: promptDigest,
|
|
1497
|
+
start_status: inScope ? 'failed' : 'out_of_scope',
|
|
1498
|
+
in_git: context.scope.inGit,
|
|
1499
|
+
repository: context.scope.repository,
|
|
1500
|
+
checkout: context.scope.checkout,
|
|
1501
|
+
non_git_scope_root: nonGitRoot,
|
|
1502
|
+
matched_cwd_prefix: context.scope.matchedCwdPrefix,
|
|
1503
|
+
destination: destinationOf(context),
|
|
1504
|
+
login: null,
|
|
1505
|
+
effective_project_code: null,
|
|
1506
|
+
auth_fingerprint: null,
|
|
1507
|
+
pending_messages: [],
|
|
1508
|
+
};
|
|
1509
|
+
writeState(context.env, key, state);
|
|
1510
|
+
return { kind: 'opened_new_turn', state, inScope };
|
|
1511
|
+
}, context.turnLock);
|
|
1512
|
+
if (decision.kind === 'no_prompt' || decision.kind === 'stale_step') {
|
|
1513
|
+
return {};
|
|
1514
|
+
}
|
|
1515
|
+
if (decision.kind === 'existing_turn') {
|
|
1516
|
+
const previous = decision.state;
|
|
1517
|
+
// Same active turn (2nd+ PreInvocation in tool loop or duplicate):
|
|
1518
|
+
// NEVER fire a new UserPromptSubmit. Re-authorize started state, scope,
|
|
1519
|
+
// destination, explicit local project_code, and current login BEFORE draining or injecting.
|
|
1520
|
+
if (previous.pending_messages.length === 0) {
|
|
1521
|
+
return {};
|
|
1522
|
+
}
|
|
1523
|
+
const configuredProjectCode = normalizeValidProjectCode(context.config.project_code);
|
|
1524
|
+
const staticPendingEligible = configuredProjectCode !== null
|
|
1525
|
+
&& isTurnStaticAuthorized(previous, context)
|
|
1526
|
+
&& normalizeValidProjectCode(previous.effective_project_code) === configuredProjectCode
|
|
1527
|
+
&& typeof previous.login === 'string'
|
|
1528
|
+
&& previous.login.length > 0;
|
|
1529
|
+
if (!staticPendingEligible || configuredProjectCode === null) {
|
|
1530
|
+
try {
|
|
1531
|
+
await withTurnStateLock(context.env, key, () => {
|
|
1532
|
+
const latest = readState(context.env, key);
|
|
1533
|
+
if (latest && latest.turn_id === previous.turn_id
|
|
1534
|
+
&& latest.turn_generation === previous.turn_generation
|
|
1535
|
+
&& latest.pending_messages.length > 0) {
|
|
1536
|
+
writeState(context.env, key, { ...latest, pending_messages: [] });
|
|
1537
|
+
}
|
|
1538
|
+
}, context.turnLock);
|
|
1539
|
+
}
|
|
1540
|
+
catch { }
|
|
1541
|
+
return {};
|
|
1542
|
+
}
|
|
1543
|
+
const requiredProjectCode = configuredProjectCode;
|
|
1544
|
+
const currentLogin = await resolveCurrentLoginId(context);
|
|
1545
|
+
const currentLoginId = currentLogin.ok ? currentLogin.loginId : null;
|
|
1546
|
+
const preAuthorized = canAuthorizePendingContext(previous, context, currentLoginId);
|
|
1547
|
+
const drained = await withTurnStateLock(context.env, key, () => {
|
|
1548
|
+
const latest = readState(context.env, key);
|
|
1549
|
+
if (!latest || latest.turn_id !== previous.turn_id || latest.turn_generation !== previous.turn_generation) {
|
|
1550
|
+
return [];
|
|
1551
|
+
}
|
|
1552
|
+
if (!latest.turn_active) {
|
|
1553
|
+
return [];
|
|
1554
|
+
}
|
|
1555
|
+
const stillAuthorized = preAuthorized && canAuthorizePendingContext(latest, context, currentLoginId);
|
|
1556
|
+
if (!stillAuthorized) {
|
|
1557
|
+
if (latest.pending_messages.length > 0) {
|
|
1558
|
+
writeState(context.env, key, { ...latest, pending_messages: [] });
|
|
1559
|
+
}
|
|
1560
|
+
return [];
|
|
1561
|
+
}
|
|
1562
|
+
const matching = latest.pending_messages.filter((entry) => (matchesPendingEntry(entry, latest, requiredProjectCode)));
|
|
1563
|
+
if (latest.pending_messages.length > 0) {
|
|
1564
|
+
writeState(context.env, key, { ...latest, pending_messages: [] });
|
|
1565
|
+
}
|
|
1566
|
+
return matching;
|
|
1567
|
+
}, context.turnLock);
|
|
1568
|
+
const steps = [];
|
|
1569
|
+
for (const entry of drained) {
|
|
1570
|
+
const step = buildSystemMessageStep(previous.turn_id, entry.additional_context, entry.system_message);
|
|
1571
|
+
if (step)
|
|
1572
|
+
steps.push(step);
|
|
1573
|
+
}
|
|
1574
|
+
return preInvocationOutputFromSteps(steps);
|
|
1575
|
+
}
|
|
1576
|
+
const openedState = decision.state;
|
|
1577
|
+
if (!decision.inScope) {
|
|
1578
|
+
return {};
|
|
1579
|
+
}
|
|
1580
|
+
try {
|
|
1581
|
+
const login = {};
|
|
1582
|
+
const hostPayload = {
|
|
1583
|
+
hook_event_name: 'UserPromptSubmit',
|
|
1584
|
+
session_id: conversationId,
|
|
1585
|
+
turn_id: openedState.turn_id,
|
|
1586
|
+
prompt: prompt,
|
|
1587
|
+
cwd: context.scope.cwd,
|
|
1588
|
+
...(authorizedTranscriptPath ? { transcript_path: authorizedTranscriptPath } : {}),
|
|
1589
|
+
...(typeof payload.modelName === 'string' && payload.modelName
|
|
1590
|
+
? { model: payload.modelName } : {}),
|
|
1591
|
+
};
|
|
1592
|
+
const { output, envelope } = await forward(hostPayload, context, openedState.repository, login, 'PreInvocation');
|
|
1593
|
+
const loginId = login.used ?? null;
|
|
1594
|
+
const effectiveProjectResult = resolveEffectiveProjectCode(envelope, output, context.config.project_code);
|
|
1595
|
+
if (!effectiveProjectResult.ok) {
|
|
1596
|
+
// Explicit Host project_code mismatch or invalid project_code:
|
|
1597
|
+
// NEVER inject initial context, NEVER mark turn started, and prevent any pending injection.
|
|
1598
|
+
try {
|
|
1599
|
+
await withTurnStateLock(context.env, key, () => {
|
|
1600
|
+
const latest = readState(context.env, key);
|
|
1601
|
+
if (latest
|
|
1602
|
+
&& latest.turn_id === openedState.turn_id
|
|
1603
|
+
&& latest.turn_generation === openedState.turn_generation) {
|
|
1604
|
+
writeState(context.env, key, {
|
|
1605
|
+
...latest,
|
|
1606
|
+
start_status: 'failed',
|
|
1607
|
+
login: null,
|
|
1608
|
+
effective_project_code: null,
|
|
1609
|
+
auth_fingerprint: null,
|
|
1610
|
+
pending_messages: [],
|
|
1611
|
+
});
|
|
1612
|
+
}
|
|
1613
|
+
}, context.turnLock);
|
|
1614
|
+
}
|
|
1615
|
+
catch { }
|
|
1616
|
+
return {};
|
|
1617
|
+
}
|
|
1618
|
+
const effectiveProjectCode = effectiveProjectResult.value;
|
|
1619
|
+
const authFingerprint = computeAuthFingerprint(context, openedState.non_git_scope_root, loginId, effectiveProjectCode);
|
|
1620
|
+
let committed = false;
|
|
1621
|
+
try {
|
|
1622
|
+
committed = await withTurnStateLock(context.env, key, () => {
|
|
1623
|
+
const latest = readState(context.env, key);
|
|
1624
|
+
if (!latest
|
|
1625
|
+
|| latest.turn_active !== true
|
|
1626
|
+
|| latest.turn_id !== openedState.turn_id
|
|
1627
|
+
|| latest.turn_generation !== openedState.turn_generation) {
|
|
1628
|
+
return false;
|
|
1629
|
+
}
|
|
1630
|
+
writeState(context.env, key, {
|
|
1631
|
+
...latest,
|
|
1632
|
+
start_status: 'started',
|
|
1633
|
+
login: loginId,
|
|
1634
|
+
effective_project_code: effectiveProjectCode,
|
|
1635
|
+
auth_fingerprint: authFingerprint,
|
|
1636
|
+
});
|
|
1637
|
+
return true;
|
|
1638
|
+
}, context.turnLock);
|
|
1639
|
+
}
|
|
1640
|
+
catch {
|
|
1641
|
+
committed = false;
|
|
1642
|
+
}
|
|
1643
|
+
if (!committed) {
|
|
1644
|
+
// Turn was closed (e.g. by Stop) or superseded while awaiting HTTP:
|
|
1645
|
+
// never inject initial context for a finished or replaced turn.
|
|
1646
|
+
return {};
|
|
1647
|
+
}
|
|
1648
|
+
const { additionalContext, systemMessage } = extractHostMessages(output);
|
|
1649
|
+
const step = buildSystemMessageStep(openedState.turn_id, additionalContext, systemMessage);
|
|
1650
|
+
return step ? preInvocationOutputFromSteps([step]) : {};
|
|
1651
|
+
}
|
|
1652
|
+
catch {
|
|
1653
|
+
// Fail-open: keep turn_active=true with start_status='failed' so subsequent invocations
|
|
1654
|
+
// in the same turn do not retry or leak orphan events.
|
|
1655
|
+
return {};
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
async function handlePreToolUse(payload, conversationId, context) {
|
|
1659
|
+
const toolCall = payload.toolCall;
|
|
1660
|
+
const rawName = typeof toolCall?.name === 'string' ? toolCall.name : '';
|
|
1661
|
+
const normalizedName = normalizeAntigravityToolName(rawName, toolCall?.args);
|
|
1662
|
+
if (!PRE_TOOL_USE_TOOLS.has(normalizedName)) {
|
|
1663
|
+
return { decision: 'allow' };
|
|
1664
|
+
}
|
|
1665
|
+
const key = turnKey(conversationId, context.configPath);
|
|
1666
|
+
const state = await withTurnStateLock(context.env, key, () => readState(context.env, key), context.turnLock);
|
|
1667
|
+
if (!state || !isTurnStaticAuthorized(state, context)) {
|
|
1668
|
+
return { decision: 'allow' };
|
|
1669
|
+
}
|
|
1670
|
+
const transcriptOpts = transcriptOptionsFor(conversationId, context);
|
|
1671
|
+
const authorizedTranscriptPath = resolveAuthorizedTranscriptPath(payload.transcriptPath, transcriptOpts);
|
|
1672
|
+
const toolUseId = typeof toolCall?.id === 'string' && toolCall.id.trim()
|
|
1673
|
+
? toolCall.id.trim()
|
|
1674
|
+
: (typeof payload.stepIdx === 'number' ? `step-${payload.stepIdx}` : randomUUID());
|
|
1675
|
+
try {
|
|
1676
|
+
const { output } = await forward({
|
|
1677
|
+
hook_event_name: 'PreToolUse',
|
|
1678
|
+
session_id: conversationId,
|
|
1679
|
+
turn_id: state.turn_id,
|
|
1680
|
+
tool_name: normalizedName,
|
|
1681
|
+
tool_use_id: toolUseId,
|
|
1682
|
+
tool_input: normalizedToolInput(rawName, normalizedName, toolCall?.args),
|
|
1683
|
+
cwd: context.scope.cwd,
|
|
1684
|
+
...(authorizedTranscriptPath ? { transcript_path: authorizedTranscriptPath } : {}),
|
|
1685
|
+
...(typeof payload.modelName === 'string' && payload.modelName
|
|
1686
|
+
? { model: payload.modelName } : {}),
|
|
1687
|
+
}, context, state.repository, turnLogin(state), 'PreToolUse');
|
|
1688
|
+
const specific = output.hookSpecificOutput;
|
|
1689
|
+
if (specific && typeof specific === 'object' && !Array.isArray(specific)
|
|
1690
|
+
&& specific.permissionDecision === 'deny') {
|
|
1691
|
+
const reason = typeof specific.permissionDecisionReason === 'string' && specific.permissionDecisionReason
|
|
1692
|
+
? specific.permissionDecisionReason
|
|
1693
|
+
: undefined;
|
|
1694
|
+
return { decision: 'deny', ...(reason ? { reason } : {}) };
|
|
1695
|
+
}
|
|
1696
|
+
return { decision: 'allow' };
|
|
1697
|
+
}
|
|
1698
|
+
catch {
|
|
1699
|
+
return { decision: 'allow' };
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
async function handlePostToolUse(payload, conversationId, context) {
|
|
1703
|
+
const key = turnKey(conversationId, context.configPath);
|
|
1704
|
+
const state = await withTurnStateLock(context.env, key, () => readState(context.env, key), context.turnLock);
|
|
1705
|
+
if (!state || !isTurnStaticAuthorized(state, context)) {
|
|
1706
|
+
return {};
|
|
1707
|
+
}
|
|
1708
|
+
const startedTurnId = state.turn_id;
|
|
1709
|
+
const startedGeneration = state.turn_generation;
|
|
1710
|
+
const startedAuthFingerprint = state.auth_fingerprint;
|
|
1711
|
+
const toolCall = payload.toolCall;
|
|
1712
|
+
const rawName = typeof toolCall?.name === 'string' ? toolCall.name : '';
|
|
1713
|
+
const normalizedName = normalizeAntigravityToolName(rawName, toolCall?.args);
|
|
1714
|
+
if (!normalizedName)
|
|
1715
|
+
return {};
|
|
1716
|
+
const errorText = typeof payload.error === 'string' && payload.error.length > 0 ? payload.error : undefined;
|
|
1717
|
+
const hasError = errorText !== undefined;
|
|
1718
|
+
const hostEventName = hasError ? 'PostToolUseFailure' : 'PostToolUse';
|
|
1719
|
+
const toolUseId = typeof toolCall?.id === 'string' && toolCall.id.trim()
|
|
1720
|
+
? toolCall.id.trim()
|
|
1721
|
+
: (typeof payload.stepIdx === 'number' ? `step-${payload.stepIdx}` : randomUUID());
|
|
1722
|
+
const transcriptOpts = transcriptOptionsFor(conversationId, context);
|
|
1723
|
+
const authorizedTranscriptPath = resolveAuthorizedTranscriptPath(payload.transcriptPath, transcriptOpts);
|
|
1724
|
+
const isBrainbase = normalizedName.startsWith('mcp__brainbase__');
|
|
1725
|
+
let toolInput;
|
|
1726
|
+
let toolResponse;
|
|
1727
|
+
let errorField;
|
|
1728
|
+
if (isBrainbase) {
|
|
1729
|
+
toolInput = normalizedToolInput(rawName, normalizedName, toolCall?.args);
|
|
1730
|
+
const transcriptText = extractToolResultFromTranscript(payload.transcriptPath, payload.stepIdx, transcriptOpts);
|
|
1731
|
+
if (transcriptText !== null) {
|
|
1732
|
+
toolResponse = {
|
|
1733
|
+
content: [{ type: 'text', text: transcriptText }],
|
|
1734
|
+
isError: hasError,
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
else {
|
|
1738
|
+
toolResponse = {
|
|
1739
|
+
...digestSummary({ tool_use_id: toolUseId, tool_name: normalizedName, error: hasError ? errorText : null }),
|
|
1740
|
+
success: !hasError,
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
if (hasError)
|
|
1744
|
+
errorField = errorText;
|
|
1745
|
+
}
|
|
1746
|
+
else {
|
|
1747
|
+
toolInput = digestSummary(toolCall?.args ?? null);
|
|
1748
|
+
toolResponse = {
|
|
1749
|
+
...digestSummary(hasError ? { error: errorText } : { tool_use_id: toolUseId, ok: true }),
|
|
1750
|
+
success: !hasError,
|
|
1751
|
+
};
|
|
1752
|
+
if (hasError)
|
|
1753
|
+
errorField = digestSummary(errorText);
|
|
1754
|
+
}
|
|
1755
|
+
try {
|
|
1756
|
+
const { output, envelope } = await forward({
|
|
1757
|
+
hook_event_name: hostEventName,
|
|
1758
|
+
session_id: conversationId,
|
|
1759
|
+
turn_id: startedTurnId,
|
|
1760
|
+
tool_name: normalizedName,
|
|
1761
|
+
tool_use_id: toolUseId,
|
|
1762
|
+
tool_input: toolInput,
|
|
1763
|
+
tool_response: toolResponse,
|
|
1764
|
+
...(errorField !== undefined ? { error: errorField } : {}),
|
|
1765
|
+
cwd: context.scope.cwd,
|
|
1766
|
+
...(authorizedTranscriptPath ? { transcript_path: authorizedTranscriptPath } : {}),
|
|
1767
|
+
...(typeof payload.modelName === 'string' && payload.modelName
|
|
1768
|
+
? { model: payload.modelName } : {}),
|
|
1769
|
+
}, context, state.repository, turnLogin(state), 'PostToolUse');
|
|
1770
|
+
const { additionalContext, systemMessage } = extractHostMessages(output);
|
|
1771
|
+
const configuredProjectCode = normalizeValidProjectCode(context.config.project_code);
|
|
1772
|
+
const postProjectResult = resolveEffectiveProjectCode(envelope, output, context.config.project_code);
|
|
1773
|
+
if ((additionalContext || systemMessage)
|
|
1774
|
+
&& configuredProjectCode !== null
|
|
1775
|
+
&& postProjectResult.ok
|
|
1776
|
+
&& postProjectResult.value === configuredProjectCode) {
|
|
1777
|
+
try {
|
|
1778
|
+
await withTurnStateLock(context.env, key, () => {
|
|
1779
|
+
const latest = readState(context.env, key);
|
|
1780
|
+
if (!latest
|
|
1781
|
+
|| latest.turn_active !== true
|
|
1782
|
+
|| latest.turn_id !== startedTurnId
|
|
1783
|
+
|| latest.turn_generation !== startedGeneration
|
|
1784
|
+
|| latest.auth_fingerprint !== startedAuthFingerprint
|
|
1785
|
+
|| latest.effective_project_code !== configuredProjectCode
|
|
1786
|
+
|| !isTurnStaticAuthorized(latest, context)) {
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
const nextPending = [
|
|
1790
|
+
...latest.pending_messages.filter((entry) => matchesPendingEntry(entry, latest, configuredProjectCode)),
|
|
1791
|
+
{
|
|
1792
|
+
turn_id: latest.turn_id,
|
|
1793
|
+
turn_generation: latest.turn_generation,
|
|
1794
|
+
project_code: configuredProjectCode,
|
|
1795
|
+
...(additionalContext ? { additional_context: additionalContext } : {}),
|
|
1796
|
+
...(systemMessage ? { system_message: systemMessage } : {}),
|
|
1797
|
+
created_at: new Date(context.now()).toISOString(),
|
|
1798
|
+
},
|
|
1799
|
+
].slice(-MAX_PENDING_MESSAGES);
|
|
1800
|
+
writeState(context.env, key, { ...latest, pending_messages: nextPending });
|
|
1801
|
+
}, context.turnLock);
|
|
1802
|
+
}
|
|
1803
|
+
catch { }
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
catch {
|
|
1807
|
+
// Fail-open.
|
|
1808
|
+
}
|
|
1809
|
+
// Antigravity PostToolUse strictly expects `{}`.
|
|
1810
|
+
return {};
|
|
1811
|
+
}
|
|
1812
|
+
async function handleStop(payload, conversationId, context) {
|
|
1813
|
+
const key = turnKey(conversationId, context.configPath);
|
|
1814
|
+
const state = await withTurnStateLock(context.env, key, () => readState(context.env, key), context.turnLock);
|
|
1815
|
+
const terminationReason = typeof payload.terminationReason === 'string' ? payload.terminationReason : '';
|
|
1816
|
+
const clearTurn = async () => {
|
|
1817
|
+
if (!state)
|
|
1818
|
+
return;
|
|
1819
|
+
try {
|
|
1820
|
+
await withTurnStateLock(context.env, key, () => {
|
|
1821
|
+
const latest = readState(context.env, key);
|
|
1822
|
+
if (latest && latest.turn_id === state.turn_id && latest.turn_generation === state.turn_generation) {
|
|
1823
|
+
writeState(context.env, key, {
|
|
1824
|
+
...latest,
|
|
1825
|
+
turn_active: false,
|
|
1826
|
+
current_turn_user_step_index: null,
|
|
1827
|
+
last_closed_user_step_index: maxStepIndex(latest.last_closed_user_step_index, latest.current_turn_user_step_index),
|
|
1828
|
+
pending_messages: [],
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
}, context.turnLock);
|
|
1832
|
+
}
|
|
1833
|
+
catch { }
|
|
1834
|
+
};
|
|
1835
|
+
if (terminationReason !== 'NO_TOOL_CALL') {
|
|
1836
|
+
await clearTurn();
|
|
1837
|
+
return { decision: '' };
|
|
1838
|
+
}
|
|
1839
|
+
if (!state || !isTurnStaticAuthorized(state, context)) {
|
|
1840
|
+
await clearTurn();
|
|
1841
|
+
return { decision: '' };
|
|
1842
|
+
}
|
|
1843
|
+
const transcriptOpts = transcriptOptionsFor(conversationId, context);
|
|
1844
|
+
const authorizedTranscriptPath = resolveAuthorizedTranscriptPath(payload.transcriptPath, transcriptOpts);
|
|
1845
|
+
const lastAssistantMessage = extractLastAssistantMessage(payload.transcriptPath, transcriptOpts);
|
|
1846
|
+
try {
|
|
1847
|
+
const stopPayload = forwardedStopPayload({
|
|
1848
|
+
hook_event_name: 'Stop',
|
|
1849
|
+
session_id: conversationId,
|
|
1850
|
+
turn_id: state.turn_id,
|
|
1851
|
+
cwd: context.scope.cwd,
|
|
1852
|
+
...(authorizedTranscriptPath ? { transcript_path: authorizedTranscriptPath } : {}),
|
|
1853
|
+
...(typeof payload.modelName === 'string' && payload.modelName
|
|
1854
|
+
? { model: payload.modelName } : {}),
|
|
1855
|
+
...(lastAssistantMessage !== undefined ? { last_assistant_message: lastAssistantMessage } : {}),
|
|
1856
|
+
stop_hook_active: payload.continuationActive === true,
|
|
1857
|
+
});
|
|
1858
|
+
await forward(stopPayload, context, state.repository, turnLogin(state), 'Stop');
|
|
1859
|
+
}
|
|
1860
|
+
catch {
|
|
1861
|
+
// Fail-open.
|
|
1862
|
+
}
|
|
1863
|
+
finally {
|
|
1864
|
+
await clearTurn();
|
|
1865
|
+
}
|
|
1866
|
+
// Never return `"continue"` from Stop.
|
|
1867
|
+
return { decision: '' };
|
|
1868
|
+
}
|
|
1869
|
+
/** Handles one Antigravity lifecycle hook event. Never throws. */
|
|
1870
|
+
export async function handleAntigravityJudgmentHook(payload, options = {}) {
|
|
1871
|
+
const env = options.env ?? process.env;
|
|
1872
|
+
const eventName = payload?.hookEventName;
|
|
1873
|
+
try {
|
|
1874
|
+
if (env.BRAINBASE_ANTIGRAVITY_JUDGMENT_HOOK === 'disabled') {
|
|
1875
|
+
return antigravityFailOpenOutput(eventName);
|
|
1876
|
+
}
|
|
1877
|
+
const configPath = resolve(options.configPath ?? defaultAntigravityHookConfigPath(env));
|
|
1878
|
+
const config = readAntigravityHookConfig(configPath);
|
|
1879
|
+
if (!config)
|
|
1880
|
+
return antigravityFailOpenOutput(eventName);
|
|
1881
|
+
if (options.registrationId !== config.registration.id) {
|
|
1882
|
+
return antigravityFailOpenOutput(eventName);
|
|
1883
|
+
}
|
|
1884
|
+
const conversationId = typeof payload.conversationId === 'string' ? payload.conversationId.trim() : '';
|
|
1885
|
+
if (!conversationId)
|
|
1886
|
+
return antigravityFailOpenOutput(eventName);
|
|
1887
|
+
const context = {
|
|
1888
|
+
env,
|
|
1889
|
+
config,
|
|
1890
|
+
fetch: options.fetch ?? fetch,
|
|
1891
|
+
accessToken: options.accessToken ?? (async () => {
|
|
1892
|
+
const login = await getAccessTokenOfLogin({ fetch: options.fetch, ...options.credentials });
|
|
1893
|
+
if (login.serverUrl !== config.login_server) {
|
|
1894
|
+
throw Object.assign(new Error('login_origin_mismatch'), { code: 'login_origin_mismatch' });
|
|
1895
|
+
}
|
|
1896
|
+
return { token: login.token, loginId: login.loginId };
|
|
1897
|
+
}),
|
|
1898
|
+
scope: resolveAntigravityScope(payload, config, env),
|
|
1899
|
+
configPath,
|
|
1900
|
+
now: options.now ?? Date.now,
|
|
1901
|
+
staleTurnMs: options.staleTurnMs ?? DEFAULT_STALE_TURN_MS,
|
|
1902
|
+
...(options.allowedTranscriptRoots !== undefined
|
|
1903
|
+
? { allowedTranscriptRoots: options.allowedTranscriptRoots } : {}),
|
|
1904
|
+
...(options.turnLock !== undefined ? { turnLock: options.turnLock } : {}),
|
|
1905
|
+
...(options.transcriptOpenatBinary !== undefined
|
|
1906
|
+
? { transcriptOpenatBinary: options.transcriptOpenatBinary } : {}),
|
|
1907
|
+
...(options.platform !== undefined
|
|
1908
|
+
? { platform: options.platform } : {}),
|
|
1909
|
+
};
|
|
1910
|
+
if (eventName === 'PreInvocation')
|
|
1911
|
+
return await handlePreInvocation(payload, conversationId, context);
|
|
1912
|
+
if (eventName === 'PreToolUse')
|
|
1913
|
+
return await handlePreToolUse(payload, conversationId, context);
|
|
1914
|
+
if (eventName === 'PostToolUse')
|
|
1915
|
+
return await handlePostToolUse(payload, conversationId, context);
|
|
1916
|
+
if (eventName === 'Stop')
|
|
1917
|
+
return await handleStop(payload, conversationId, context);
|
|
1918
|
+
return antigravityFailOpenOutput(eventName);
|
|
1919
|
+
}
|
|
1920
|
+
catch {
|
|
1921
|
+
return antigravityFailOpenOutput(eventName);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
// ---- Registration in Antigravity hooks.json ----
|
|
1925
|
+
/** Builds the POSIX-quoted command registered in Antigravity `hooks.json`. */
|
|
1926
|
+
export function antigravityHookCommand(nodePath, cliPath, configPath, registrationId) {
|
|
1927
|
+
return [nodePath, cliPath, ANTIGRAVITY_HOOK_COMMAND, '--config', configPath, '--registration', registrationId]
|
|
1928
|
+
.map(shellQuote).join(' ');
|
|
1929
|
+
}
|
|
1930
|
+
export function installedAntigravityHookRegistration(hook) {
|
|
1931
|
+
const value = hook;
|
|
1932
|
+
if (!value || (value.type !== undefined && value.type !== 'command') || typeof value.command !== 'string') {
|
|
1933
|
+
return null;
|
|
1934
|
+
}
|
|
1935
|
+
const words = singleQuotedWords(value.command);
|
|
1936
|
+
if (!words || words.length !== 7 || words[2] !== ANTIGRAVITY_HOOK_COMMAND || words[3] !== '--config'
|
|
1937
|
+
|| words[5] !== '--registration' || !REGISTRATION_ID.test(words[6]) || !words[4]) {
|
|
1938
|
+
return null;
|
|
1939
|
+
}
|
|
1940
|
+
return { configPath: words[4], registrationId: words[6] };
|
|
1941
|
+
}
|
|
1942
|
+
function sameConfigFile(registered, configPath) {
|
|
1943
|
+
return registered === configPath || canonicalFilePath(registered) === canonicalFilePath(configPath);
|
|
1944
|
+
}
|
|
1945
|
+
function collectHookRegistrationsFromEntry(entry) {
|
|
1946
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
1947
|
+
return [];
|
|
1948
|
+
const spec = entry;
|
|
1949
|
+
const found = [];
|
|
1950
|
+
for (const flatEvent of ['SessionStart', 'PreInvocation', 'PostInvocation', 'Stop']) {
|
|
1951
|
+
const list = spec[flatEvent];
|
|
1952
|
+
if (!Array.isArray(list))
|
|
1953
|
+
continue;
|
|
1954
|
+
for (const handler of list) {
|
|
1955
|
+
const reg = installedAntigravityHookRegistration(handler);
|
|
1956
|
+
if (reg)
|
|
1957
|
+
found.push(reg);
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
for (const groupedEvent of ['PreToolUse', 'PostToolUse']) {
|
|
1961
|
+
const groups = spec[groupedEvent];
|
|
1962
|
+
if (!Array.isArray(groups))
|
|
1963
|
+
continue;
|
|
1964
|
+
for (const group of groups) {
|
|
1965
|
+
const inner = group?.hooks;
|
|
1966
|
+
if (!Array.isArray(inner))
|
|
1967
|
+
continue;
|
|
1968
|
+
for (const handler of inner) {
|
|
1969
|
+
const reg = installedAntigravityHookRegistration(handler);
|
|
1970
|
+
if (reg)
|
|
1971
|
+
found.push(reg);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
return found;
|
|
1976
|
+
}
|
|
1977
|
+
/** True when `hooksJson` contains a Brainbase Antigravity registration for `configPath`. */
|
|
1978
|
+
export function hasInstalledAntigravityHooks(hooksJson, configPath) {
|
|
1979
|
+
const entry = hooksJson[ANTIGRAVITY_HOOK_KEY];
|
|
1980
|
+
return collectHookRegistrationsFromEntry(entry).some((reg) => sameConfigFile(reg.configPath, configPath));
|
|
1981
|
+
}
|
|
1982
|
+
/** Generates the `"brainbase-judgment"` hook block for Antigravity `hooks.json`. */
|
|
1983
|
+
export function antigravityJudgmentHookEntry(command) {
|
|
1984
|
+
return {
|
|
1985
|
+
enabled: true,
|
|
1986
|
+
PreInvocation: [
|
|
1987
|
+
{ type: 'command', command, timeout: 6 },
|
|
1988
|
+
],
|
|
1989
|
+
PreToolUse: [
|
|
1990
|
+
{
|
|
1991
|
+
matcher: 'mcp_brainbase.*knowledge_lookup|call_mcp_tool',
|
|
1992
|
+
hooks: [{ type: 'command', command, timeout: 5 }],
|
|
1993
|
+
},
|
|
1994
|
+
],
|
|
1995
|
+
PostToolUse: [
|
|
1996
|
+
{
|
|
1997
|
+
matcher: '*',
|
|
1998
|
+
hooks: [{ type: 'command', command, timeout: 5 }],
|
|
1999
|
+
},
|
|
2000
|
+
],
|
|
2001
|
+
Stop: [
|
|
2002
|
+
{ type: 'command', command, timeout: 8 },
|
|
2003
|
+
],
|
|
2004
|
+
};
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Idempotently updates or removes only the `"brainbase-judgment"` top-level key
|
|
2008
|
+
* of Antigravity `hooks.json`, preserving every other hook entry untouched.
|
|
2009
|
+
*/
|
|
2010
|
+
export function registerAntigravityJudgmentHooks(hooksJson, options) {
|
|
2011
|
+
const { command, configPath, remove = false, removedIds } = options;
|
|
2012
|
+
const next = { ...hooksJson };
|
|
2013
|
+
const existing = collectHookRegistrationsFromEntry(hooksJson[ANTIGRAVITY_HOOK_KEY]);
|
|
2014
|
+
let matchedExisting = false;
|
|
2015
|
+
for (const reg of existing) {
|
|
2016
|
+
if (sameConfigFile(reg.configPath, configPath)) {
|
|
2017
|
+
matchedExisting = true;
|
|
2018
|
+
removedIds?.add(reg.registrationId);
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
if (remove) {
|
|
2022
|
+
if (matchedExisting) {
|
|
2023
|
+
delete next[ANTIGRAVITY_HOOK_KEY];
|
|
2024
|
+
}
|
|
2025
|
+
return next;
|
|
2026
|
+
}
|
|
2027
|
+
if (!command) {
|
|
2028
|
+
throw new Error('registerAntigravityJudgmentHooks requires command unless remove is true');
|
|
2029
|
+
}
|
|
2030
|
+
next[ANTIGRAVITY_HOOK_KEY] = antigravityJudgmentHookEntry(command);
|
|
2031
|
+
return next;
|
|
2032
|
+
}
|
|
2033
|
+
/** @internal Exposed strictly for deterministic concurrency and TOCTOU regression tests. */
|
|
2034
|
+
export const __antigravityHookTestInternals = {
|
|
2035
|
+
withTurnStateLock,
|
|
2036
|
+
readTranscriptTailEntries,
|
|
2037
|
+
resolveOpenatHelperBinary,
|
|
2038
|
+
PYTHON_OPENAT_TAIL_READER,
|
|
2039
|
+
turnKey,
|
|
2040
|
+
lockPathFor,
|
|
2041
|
+
statePath,
|
|
2042
|
+
};
|