@aisac/cli 0.0.0-stage → 0.4.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +166 -2
  2. package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
  3. package/dist/assets/claude/hooks/context-compaction.ts +6930 -0
  4. package/dist/assets/claude/hooks/hooks.json +3 -0
  5. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
  6. package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
  7. package/dist/assets/claude/hooks/provider-window.js +263 -0
  8. package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
  9. package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
  10. package/dist/assets/codex-context-compaction.mjs +4689 -0
  11. package/dist/assets/context-selection-fitting.mjs +194 -0
  12. package/dist/assets/context-state-fitting.mjs +324 -0
  13. package/dist/assets/context-telemetry-reporter.mjs +305 -0
  14. package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
  15. package/dist/claude-checkpoint.mjs +1338 -0
  16. package/dist/claude-compatibility.mjs +506 -0
  17. package/dist/claude-observation.mjs +1338 -0
  18. package/dist/cli.mjs +771 -0
  19. package/dist/codex-compatibility.mjs +481 -0
  20. package/dist/codex-diagnostics.mjs +447 -0
  21. package/dist/codex-permissions.mjs +590 -0
  22. package/dist/codex-protocol-fingerprint.json +131 -0
  23. package/dist/context-telemetry.mjs +257 -0
  24. package/dist/engineering-pack-public-key.json +10 -0
  25. package/dist/engineering-pack.mjs +722 -0
  26. package/dist/engineering.mjs +194 -0
  27. package/dist/launch.mjs +690 -0
  28. package/dist/mcp.mjs +962 -0
  29. package/dist/monitor.mjs +133 -0
  30. package/dist/package.json +5 -0
  31. package/dist/platform.mjs +126 -0
  32. package/dist/policy.mjs +218 -0
  33. package/dist/state.mjs +408 -0
  34. package/dist/telemetry-report.mjs +133 -0
  35. package/package.json +24 -4
package/dist/mcp.mjs ADDED
@@ -0,0 +1,962 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+
3
+ const MAX_BODY = 256 * 1024;
4
+ const MAX_SESSION_ID = 256;
5
+ const TIMEOUT_MS = 10_000;
6
+ const MAX_BUDGET_SNAPSHOT_AGE_MS = 15_000;
7
+ const MAX_RETRY_AFTER_MS = 3_600_000;
8
+ const SAFE_IDENTIFIER = /^[A-Za-z0-9._:-]{1,128}$/u;
9
+ const MAX_ENDPOINT_LENGTH = 2_048;
10
+ const SUPPORTED_PROTOCOL_VERSIONS = new Set([
11
+ '2024-11-05',
12
+ '2025-03-26',
13
+ '2025-06-18',
14
+ '2025-11-25',
15
+ ]);
16
+
17
+ /** @typedef {Record<string, unknown>} JsonObject */
18
+ /** @typedef {{ response: Response, parsed: JsonObject | null, sessionId: string | undefined }} CallResult */
19
+
20
+ /** @param {unknown} value @returns {value is JsonObject} */
21
+ function isObject(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ /** @param {JsonObject} value @param {string[]} keys */
26
+ function hasOnlyKeys(value, keys) {
27
+ return Object.keys(value).every((key) => keys.includes(key));
28
+ }
29
+
30
+ /** @param {unknown} value @returns {string} */
31
+ function safeErrorCode(value) {
32
+ return value instanceof Error && /^mcp_[a-z0-9_]+$/u.test(value.message)
33
+ ? value.message
34
+ : 'mcp_network_error';
35
+ }
36
+
37
+ /** @param {unknown} value @returns {string} */
38
+ function canonicalJson(value) {
39
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
40
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
41
+ /** @type {JsonObject} */
42
+ const object = /** @type {JsonObject} */ (value);
43
+ return `{${Object.keys(object)
44
+ .sort()
45
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`)
46
+ .join(',')}}`;
47
+ }
48
+
49
+ /** @param {JsonObject} value */
50
+ function hashJson(value) {
51
+ return createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex');
52
+ }
53
+
54
+ /** @param {string} endpoint */
55
+ function endpointUrl(endpoint) {
56
+ let url;
57
+ try {
58
+ url = new URL(endpoint);
59
+ } catch {
60
+ throw new Error('endpoint_invalid');
61
+ }
62
+ if (endpoint.length > MAX_ENDPOINT_LENGTH) throw new Error('endpoint_too_long');
63
+ if (
64
+ url.protocol !== 'https:' &&
65
+ !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(url.hostname))
66
+ )
67
+ throw new Error('endpoint_must_use_https');
68
+ if (url.username || url.password || url.hash || url.search)
69
+ throw new Error('endpoint_credentials_query_or_fragment_rejected');
70
+ return url;
71
+ }
72
+
73
+ /** @param {string} text */
74
+ function parseJson(text) {
75
+ if (text.trim() === '') return null;
76
+ let value;
77
+ try {
78
+ value = JSON.parse(text);
79
+ } catch {
80
+ throw new Error('mcp_response_malformed');
81
+ }
82
+ if (!isObject(value)) throw new Error('mcp_response_invalid_shape');
83
+ return value;
84
+ }
85
+
86
+ /** @param {string} text @returns {JsonObject[]} */
87
+ function parseEventStream(text) {
88
+ /** @type {JsonObject[]} */
89
+ const events = [];
90
+ /** @type {string[]} */
91
+ let data = [];
92
+ const flush = () => {
93
+ if (data.length > 0) {
94
+ const event = data.join('\n');
95
+ if (event !== '' && event !== '[DONE]') {
96
+ const parsed = parseJson(event);
97
+ if (parsed !== null) events.push(parsed);
98
+ }
99
+ }
100
+ data = [];
101
+ };
102
+ for (const line of text.split(/\r?\n/u)) {
103
+ if (line === '') flush();
104
+ else if (line.startsWith('data:')) data.push(line.slice(5).trimStart());
105
+ }
106
+ flush();
107
+ return events.filter((event) => event !== null);
108
+ }
109
+
110
+ /** @param {Response} response @returns {Promise<JsonObject | JsonObject[] | null>} */
111
+ async function responseObject(response) {
112
+ if (response.status === 202 || response.status === 204 || response.body === null) return null;
113
+ const reader = response.body.getReader();
114
+ const chunks = [];
115
+ let total = 0;
116
+ try {
117
+ while (true) {
118
+ const part = await reader.read();
119
+ if (part.done) break;
120
+ total += part.value.byteLength;
121
+ if (total > MAX_BODY) {
122
+ await reader.cancel();
123
+ throw new Error('mcp_response_too_large');
124
+ }
125
+ chunks.push(part.value);
126
+ }
127
+ } catch (error) {
128
+ await reader.cancel().catch(() => undefined);
129
+ throw error;
130
+ }
131
+ const bytes = new Uint8Array(total);
132
+ let offset = 0;
133
+ for (const chunk of chunks) {
134
+ bytes.set(chunk, offset);
135
+ offset += chunk.byteLength;
136
+ }
137
+ let text;
138
+ try {
139
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
140
+ } catch {
141
+ throw new Error('mcp_response_invalid_utf8');
142
+ }
143
+ const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
144
+ return contentType.includes('text/event-stream') ? parseEventStream(text) : parseJson(text);
145
+ }
146
+
147
+ /**
148
+ * @param {string} url
149
+ * @param {string} token
150
+ * @param {JsonObject} body
151
+ * @param {string | undefined} sessionId
152
+ * @param {string | undefined} protocolVersion
153
+ * @param {number} [timeoutMs]
154
+ * @returns {Promise<CallResult>}
155
+ */
156
+ async function call(url, token, body, sessionId, protocolVersion, timeoutMs = TIMEOUT_MS) {
157
+ const controller = new AbortController();
158
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
159
+ const expectedId = Object.hasOwn(body, 'id') ? body.id : undefined;
160
+ try {
161
+ const response = await fetch(url, {
162
+ method: 'POST',
163
+ redirect: 'error',
164
+ signal: controller.signal,
165
+ headers: {
166
+ Authorization: `Bearer ${token}`,
167
+ 'Content-Type': 'application/json',
168
+ Accept: 'application/json, text/event-stream',
169
+ ...(sessionId ? { 'MCP-Session-Id': sessionId } : {}),
170
+ ...(protocolVersion ? { 'MCP-Protocol-Version': protocolVersion } : {}),
171
+ },
172
+ body: JSON.stringify(body),
173
+ });
174
+ if (!response.ok && response.body !== null) await response.body.cancel().catch(() => undefined);
175
+ let parsed =
176
+ response.ok || response.status === 202 || response.status === 204
177
+ ? await responseObject(response)
178
+ : null;
179
+ /** @type {JsonObject | null} */
180
+ let parsedObject = Array.isArray(parsed) ? null : parsed;
181
+ if (Array.isArray(parsed)) {
182
+ parsedObject =
183
+ expectedId === undefined
184
+ ? null
185
+ : (parsed.find((item) => Object.hasOwn(item, 'id') && Object.is(item.id, expectedId)) ??
186
+ null);
187
+ }
188
+ if (expectedId !== undefined && response.ok) {
189
+ if (
190
+ !parsedObject ||
191
+ parsedObject.jsonrpc !== '2.0' ||
192
+ !Object.hasOwn(parsedObject, 'id') ||
193
+ !Object.is(parsedObject.id, expectedId)
194
+ )
195
+ throw new Error('mcp_response_id_mismatch');
196
+ }
197
+ const headerSession = response.headers.get('mcp-session-id');
198
+ if (
199
+ headerSession !== null &&
200
+ (headerSession.length === 0 ||
201
+ headerSession.length > MAX_SESSION_ID ||
202
+ /[\r\n]/u.test(headerSession))
203
+ )
204
+ throw new Error('mcp_session_id_invalid');
205
+ if (sessionId !== undefined && headerSession !== null && headerSession !== sessionId)
206
+ throw new Error('mcp_session_id_changed');
207
+ const nextSession = headerSession ?? sessionId;
208
+ return {
209
+ response,
210
+ parsed: parsedObject,
211
+ sessionId: nextSession === '' ? sessionId : nextSession,
212
+ };
213
+ } catch (error) {
214
+ if (error instanceof Error && error.name === 'AbortError')
215
+ throw new Error('mcp_request_timeout');
216
+ if (error instanceof Error && /^mcp_[a-z0-9_]+$/u.test(error.message)) throw error;
217
+ throw new Error(safeErrorCode(error));
218
+ } finally {
219
+ clearTimeout(timer);
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Send one already validated, content-free telemetry report over the existing
225
+ * authenticated MCP transport. The tool name and all protocol fields are
226
+ * fixed here; callers cannot select a server or tool.
227
+ *
228
+ * @param {string} endpoint
229
+ * @param {string} token
230
+ * @param {JsonObject} report
231
+ * @param {number} [deadlineMs]
232
+ * @returns {Promise<{accepted:true, duplicate:boolean}>}
233
+ */
234
+ export async function reportContextTelemetry(endpoint, token, report, deadlineMs = 8_000) {
235
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0 || deadlineMs > 8_000)
236
+ throw new Error('mcp_deadline_invalid');
237
+ const url = endpointUrl(endpoint).toString();
238
+ if (typeof token !== 'string' || token.trim() === '') throw new Error('mcp_auth_denied');
239
+ const deadline = Date.now() + deadlineMs;
240
+ const remaining = () => {
241
+ const value = deadline - Date.now();
242
+ if (value <= 0) throw new Error('mcp_request_timeout');
243
+ return Math.min(TIMEOUT_MS, value);
244
+ };
245
+ const initialized = await call(
246
+ url,
247
+ token,
248
+ {
249
+ jsonrpc: '2.0',
250
+ id: randomUUID(),
251
+ method: 'initialize',
252
+ params: {
253
+ protocolVersion: '2025-03-26',
254
+ capabilities: {},
255
+ clientInfo: { name: 'aibrain-telemetry-report', version: '0.3.0-beta.9' },
256
+ },
257
+ },
258
+ undefined,
259
+ undefined,
260
+ remaining(),
261
+ );
262
+ const initializeResult = initialized.parsed?.result;
263
+ if (
264
+ !initialized.response.ok ||
265
+ initialized.parsed?.error ||
266
+ !isObject(initializeResult) ||
267
+ typeof initializeResult.protocolVersion !== 'string' ||
268
+ !SUPPORTED_PROTOCOL_VERSIONS.has(initializeResult.protocolVersion)
269
+ )
270
+ throw new Error(responseError(initialized.response, 'mcp_initialize_denied'));
271
+ const protocolVersion = initializeResult.protocolVersion;
272
+ const initializedNotification = await call(
273
+ url,
274
+ token,
275
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
276
+ initialized.sessionId,
277
+ protocolVersion,
278
+ remaining(),
279
+ );
280
+ if (
281
+ !initializedNotification.response.ok &&
282
+ ![202, 204].includes(initializedNotification.response.status)
283
+ )
284
+ throw new Error(responseError(initializedNotification.response, 'mcp_initialize_denied'));
285
+ const reportResponse = await call(
286
+ url,
287
+ token,
288
+ {
289
+ jsonrpc: '2.0',
290
+ id: randomUUID(),
291
+ method: 'tools/call',
292
+ params: { name: 'brain_context_report', arguments: report },
293
+ },
294
+ initialized.sessionId,
295
+ protocolVersion,
296
+ remaining(),
297
+ );
298
+ const result = reportResponse.parsed?.result;
299
+ if (!reportResponse.response.ok || reportResponse.parsed?.error || !isObject(result))
300
+ throw new Error(responseError(reportResponse.response, 'mcp_report_rejected'));
301
+ if (result.isError === true)
302
+ throw new Error(structuredErrorCode(result) ?? 'mcp_report_rejected');
303
+ const structured = isObject(result.structuredContent) ? result.structuredContent : result;
304
+ if (
305
+ !isObject(structured) ||
306
+ structured.accepted !== true ||
307
+ typeof structured.duplicate !== 'boolean'
308
+ )
309
+ throw new Error('mcp_report_rejected');
310
+ return { accepted: true, duplicate: structured.duplicate };
311
+ }
312
+
313
+ /**
314
+ * Ask the fixed v2 selection tool for a shadow decision. The caller supplies
315
+ * only the already-redacted projection; this function owns the destination,
316
+ * MCP lifecycle and response binding.
317
+ * @param {string} endpoint
318
+ * @param {string} token
319
+ * @param {JsonObject} request
320
+ * @param {number} [deadlineMs]
321
+ * @returns {Promise<JsonObject>}
322
+ */
323
+ export async function selectContextShadow(endpoint, token, request, deadlineMs = 15_000) {
324
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0 || deadlineMs > 15_000)
325
+ throw new Error('mcp_deadline_invalid');
326
+ const url = endpointUrl(endpoint).toString();
327
+ if (typeof token !== 'string' || token.trim() === '') throw new Error('mcp_auth_denied');
328
+ const projection = isObject(request.projection) ? request.projection : null;
329
+ const options = isObject(request.options) ? request.options : null;
330
+ if (projection === null || options === null) throw new Error('mcp_shadow_request_invalid');
331
+ const deadline = Date.now() + deadlineMs;
332
+ const remaining = () => {
333
+ const value = deadline - Date.now();
334
+ if (value <= 0) throw new Error('mcp_request_timeout');
335
+ return Math.min(TIMEOUT_MS, value);
336
+ };
337
+ const initialized = await call(
338
+ url,
339
+ token,
340
+ {
341
+ jsonrpc: '2.0',
342
+ id: randomUUID(),
343
+ method: 'initialize',
344
+ params: {
345
+ protocolVersion: '2025-03-26',
346
+ capabilities: {},
347
+ clientInfo: { name: 'aibrain-claude-shadow', version: '0.3.0-beta.9' },
348
+ },
349
+ },
350
+ undefined,
351
+ undefined,
352
+ remaining(),
353
+ );
354
+ const initializeResult = initialized.parsed?.result;
355
+ if (
356
+ !initialized.response.ok ||
357
+ initialized.parsed?.error ||
358
+ !isObject(initializeResult) ||
359
+ typeof initializeResult.protocolVersion !== 'string' ||
360
+ !SUPPORTED_PROTOCOL_VERSIONS.has(initializeResult.protocolVersion)
361
+ )
362
+ throw new Error(responseError(initialized.response, 'mcp_initialize_denied'));
363
+ const protocolVersion = initializeResult.protocolVersion;
364
+ const initializedNotification = await call(
365
+ url,
366
+ token,
367
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
368
+ initialized.sessionId,
369
+ protocolVersion,
370
+ remaining(),
371
+ );
372
+ if (
373
+ !initializedNotification.response.ok &&
374
+ ![202, 204].includes(initializedNotification.response.status)
375
+ )
376
+ throw new Error(responseError(initializedNotification.response, 'mcp_initialize_denied'));
377
+ const response = await call(
378
+ url,
379
+ token,
380
+ {
381
+ jsonrpc: '2.0',
382
+ id: randomUUID(),
383
+ method: 'tools/call',
384
+ params: { name: 'brain_context_select', arguments: request },
385
+ },
386
+ initialized.sessionId,
387
+ protocolVersion,
388
+ remaining(),
389
+ );
390
+ const result = response.parsed?.result;
391
+ if (!response.response.ok || response.parsed?.error || !isObject(result))
392
+ throw new Error(responseError(response.response, 'mcp_shadow_rejected'));
393
+ if (result.isError === true)
394
+ throw new Error(structuredErrorCode(result) ?? 'mcp_shadow_rejected');
395
+ const structured = isObject(result.structuredContent) ? result.structuredContent : result;
396
+ if (!isObject(structured)) throw new Error('mcp_shadow_rejected');
397
+ return structured;
398
+ }
399
+
400
+ /**
401
+ * Read the provider-free shared capacity snapshot. The snapshot is advisory;
402
+ * atomic admission remains authoritative and this helper never retries or
403
+ * reserves capacity.
404
+ * @param {string} endpoint
405
+ * @param {string} token
406
+ * @param {number} [deadlineMs]
407
+ * @returns {Promise<JsonObject>}
408
+ */
409
+ export async function readContextBudget(endpoint, token, deadlineMs = 8_000) {
410
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0 || deadlineMs > 8_000)
411
+ throw new Error('mcp_deadline_invalid');
412
+ const url = endpointUrl(endpoint).toString();
413
+ if (typeof token !== 'string' || token.trim() === '') throw new Error('mcp_auth_denied');
414
+ const fetchedAt = Date.now();
415
+ const deadline = Date.now() + deadlineMs;
416
+ const remaining = () => {
417
+ const value = deadline - Date.now();
418
+ if (value <= 0) throw new Error('mcp_request_timeout');
419
+ return Math.min(TIMEOUT_MS, value);
420
+ };
421
+ const initialized = await call(
422
+ url,
423
+ token,
424
+ {
425
+ jsonrpc: '2.0',
426
+ id: randomUUID(),
427
+ method: 'initialize',
428
+ params: {
429
+ protocolVersion: '2025-03-26',
430
+ capabilities: {},
431
+ clientInfo: { name: 'aibrain-context-budget', version: '0.3.0-beta.9' },
432
+ },
433
+ },
434
+ undefined,
435
+ undefined,
436
+ remaining(),
437
+ );
438
+ const initializeResult = initialized.parsed?.result;
439
+ if (
440
+ !initialized.response.ok ||
441
+ initialized.parsed?.error ||
442
+ !isObject(initializeResult) ||
443
+ typeof initializeResult.protocolVersion !== 'string' ||
444
+ !SUPPORTED_PROTOCOL_VERSIONS.has(initializeResult.protocolVersion)
445
+ )
446
+ throw new Error(responseError(initialized.response, 'mcp_initialize_denied'));
447
+ const protocolVersion = initializeResult.protocolVersion;
448
+ const initializedNotification = await call(
449
+ url,
450
+ token,
451
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
452
+ initialized.sessionId,
453
+ protocolVersion,
454
+ remaining(),
455
+ );
456
+ if (
457
+ !initializedNotification.response.ok &&
458
+ ![202, 204].includes(initializedNotification.response.status)
459
+ )
460
+ throw new Error(responseError(initializedNotification.response, 'mcp_initialize_denied'));
461
+ const response = await call(
462
+ url,
463
+ token,
464
+ {
465
+ jsonrpc: '2.0',
466
+ id: randomUUID(),
467
+ method: 'tools/call',
468
+ params: { name: 'brain_context_budget', arguments: { schema_version: 1 } },
469
+ },
470
+ initialized.sessionId,
471
+ protocolVersion,
472
+ remaining(),
473
+ );
474
+ const result = response.parsed?.result;
475
+ if (!response.response.ok || response.parsed?.error || !isObject(result))
476
+ throw new Error(responseError(response.response, 'mcp_budget_unavailable'));
477
+ if (result.isError === true) throw new Error(structuredErrorCode(result) ?? 'mcp_budget_denied');
478
+ const structured = isObject(result.structuredContent) ? result.structuredContent : result;
479
+ if (!isObject(structured)) throw new Error('mcp_budget_unavailable');
480
+ const numericFields = [
481
+ structured.available_requests,
482
+ structured.available_tokens,
483
+ structured.output_token_allowance,
484
+ structured.max_batches_per_operation,
485
+ structured.retry_after_ms,
486
+ structured.provider_batches,
487
+ ];
488
+ const numericFieldsValid = numericFields.every(
489
+ (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0,
490
+ );
491
+ const maxBatches = structured.max_batches_per_operation;
492
+ const retryAfter = structured.retry_after_ms;
493
+ const serverTime = Date.parse(String(structured.server_time));
494
+ const expiresAt = Date.parse(String(structured.expires_at));
495
+ const windowEnd = Date.parse(String(structured.window_end));
496
+ const localElapsed = Date.now() - fetchedAt;
497
+ const allowed = new Set([
498
+ 'schema_version',
499
+ 'server_time',
500
+ 'expires_at',
501
+ 'window_end',
502
+ 'available_requests',
503
+ 'available_tokens',
504
+ 'output_token_allowance',
505
+ 'max_batches_per_operation',
506
+ 'account_in_flight',
507
+ 'retry_after_ms',
508
+ 'provider_batches',
509
+ 'provider_model',
510
+ 'correlation_id',
511
+ ]);
512
+ if (
513
+ Object.keys(structured).some((key) => !allowed.has(key)) ||
514
+ structured.schema_version !== 1 ||
515
+ !validTimestamp(structured.server_time) ||
516
+ !validTimestamp(structured.expires_at) ||
517
+ !validTimestamp(structured.window_end) ||
518
+ !Number.isFinite(serverTime) ||
519
+ !Number.isFinite(expiresAt) ||
520
+ !Number.isFinite(windowEnd) ||
521
+ localElapsed < 0 ||
522
+ localElapsed > MAX_BUDGET_SNAPSHOT_AGE_MS ||
523
+ expiresAt <= serverTime ||
524
+ expiresAt - serverTime > MAX_BUDGET_SNAPSHOT_AGE_MS ||
525
+ expiresAt > windowEnd ||
526
+ !numericFieldsValid ||
527
+ typeof maxBatches !== 'number' ||
528
+ maxBatches > 4 ||
529
+ typeof retryAfter !== 'number' ||
530
+ retryAfter > MAX_RETRY_AFTER_MS ||
531
+ typeof structured.account_in_flight !== 'boolean' ||
532
+ (structured.provider_model !== null &&
533
+ (typeof structured.provider_model !== 'string' || structured.provider_model.length > 128)) ||
534
+ typeof structured.correlation_id !== 'string' ||
535
+ !SAFE_IDENTIFIER.test(structured.correlation_id)
536
+ )
537
+ throw new Error('mcp_budget_response_invalid');
538
+ return structured;
539
+ }
540
+
541
+ /** @param {unknown} value @returns {boolean} */
542
+ function validTimestamp(value) {
543
+ return typeof value === 'string' && Number.isFinite(Date.parse(value));
544
+ }
545
+
546
+ /** @param {Response} response @param {string} fallback */
547
+ function responseError(response, fallback) {
548
+ if (response.status === 401 || response.status === 403) return 'mcp_auth_denied';
549
+ if (response.status === 404 || response.status === 405) return 'mcp_tool_unavailable';
550
+ return fallback;
551
+ }
552
+
553
+ /** @param {JsonObject | null} result @returns {string | undefined} */
554
+ function structuredErrorCode(result) {
555
+ if (!result || result.isError !== true || !Array.isArray(result.content)) return undefined;
556
+ const text = result.content.find((item) => isObject(item) && typeof item.text === 'string')?.text;
557
+ const prefix =
558
+ typeof text === 'string'
559
+ ? /^(FEATURE_DISABLED|TOOL_UNAVAILABLE|PAID_PLAN_REQUIRED)(?::|$)/u.exec(text)?.[1]
560
+ : undefined;
561
+ if (prefix === 'FEATURE_DISABLED') return 'mcp_feature_disabled';
562
+ if (prefix === 'TOOL_UNAVAILABLE') return 'mcp_tool_unavailable';
563
+ if (prefix === 'PAID_PLAN_REQUIRED') return 'mcp_paid_plan_required';
564
+ return undefined;
565
+ }
566
+
567
+ /** @param {string} endpoint @param {string} token @returns {Promise<{ok:true, providerBatches:0, providerModel:null}>} */
568
+ async function providerFreeProbeV1(endpoint, token) {
569
+ const url = endpointUrl(endpoint).toString();
570
+ if (typeof token !== 'string' || token.trim() === '') throw new Error('mcp_auth_denied');
571
+ const initialized = await call(
572
+ url,
573
+ token,
574
+ {
575
+ jsonrpc: '2.0',
576
+ id: 1,
577
+ method: 'initialize',
578
+ params: {
579
+ protocolVersion: '2025-03-26',
580
+ capabilities: {},
581
+ clientInfo: { name: 'aibrain', version: '0.3.0-beta.9' },
582
+ },
583
+ },
584
+ undefined,
585
+ undefined,
586
+ );
587
+ const initializeResult =
588
+ initialized.parsed && isObject(initialized.parsed.result) ? initialized.parsed.result : null;
589
+ if (
590
+ !initialized.response.ok ||
591
+ initialized.parsed?.error ||
592
+ !initializeResult ||
593
+ typeof initializeResult.protocolVersion !== 'string' ||
594
+ !SUPPORTED_PROTOCOL_VERSIONS.has(initializeResult.protocolVersion) ||
595
+ !isObject(initializeResult.capabilities) ||
596
+ !isObject(initializeResult.serverInfo) ||
597
+ typeof initializeResult.serverInfo.name !== 'string' ||
598
+ initializeResult.serverInfo.name.length === 0 ||
599
+ initializeResult.serverInfo.name.length > 128 ||
600
+ typeof initializeResult.serverInfo.version !== 'string' ||
601
+ initializeResult.serverInfo.version.length === 0 ||
602
+ initializeResult.serverInfo.version.length > 128
603
+ )
604
+ throw new Error(responseError(initialized.response, 'mcp_initialize_denied'));
605
+ const protocolVersion = initializeResult.protocolVersion;
606
+ const initializedNotification = await call(
607
+ url,
608
+ token,
609
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
610
+ initialized.sessionId,
611
+ protocolVersion,
612
+ );
613
+ if (
614
+ !initializedNotification.response.ok &&
615
+ initializedNotification.response.status !== 202 &&
616
+ initializedNotification.response.status !== 204
617
+ )
618
+ throw new Error(responseError(initializedNotification.response, 'mcp_initialize_denied'));
619
+ const requestId = randomUUID();
620
+ const sessionRef = 'aibrain-setup-probe';
621
+ const revision = 'a'.repeat(64);
622
+ const projection = { goal: 'provider-free setup probe', items: [] };
623
+ const selection = await call(
624
+ url,
625
+ token,
626
+ {
627
+ jsonrpc: '2.0',
628
+ id: 2,
629
+ method: 'tools/call',
630
+ params: {
631
+ name: 'brain_context_select',
632
+ arguments: {
633
+ schema_version: 1,
634
+ client: 'codex_app_server',
635
+ client_version: '0.3.0-beta.9',
636
+ session_ref: sessionRef,
637
+ revision,
638
+ observed_at: new Date().toISOString(),
639
+ request_id: requestId,
640
+ policy_version: 'context-recovery-v1',
641
+ projection,
642
+ },
643
+ },
644
+ },
645
+ initialized.sessionId,
646
+ protocolVersion,
647
+ );
648
+ const rawResult = selection.parsed?.result;
649
+ const result = isObject(rawResult) ? rawResult : null;
650
+ const structured = result && isObject(result.structuredContent) ? result.structuredContent : null;
651
+ const stats = structured && isObject(structured.stats) ? structured.stats : null;
652
+ const validNoop =
653
+ structured !== null &&
654
+ hasOnlyKeys(structured, [
655
+ 'schema_version',
656
+ 'status',
657
+ 'applied',
658
+ 'persisted',
659
+ 'request_id',
660
+ 'correlation_id',
661
+ 'session_ref',
662
+ 'revision',
663
+ 'projection_hash',
664
+ 'policy_version',
665
+ 'provider_model',
666
+ 'created_at',
667
+ 'expires_at',
668
+ 'decisions',
669
+ 'stats',
670
+ ]) &&
671
+ hasOnlyKeys(stats ?? {}, [
672
+ 'selected_count',
673
+ 'protected_count',
674
+ 'eligible_count',
675
+ 'batch_count',
676
+ 'provider_input_tokens',
677
+ 'provider_output_tokens',
678
+ ]) &&
679
+ structured.schema_version === 1 &&
680
+ structured.status === 'noop' &&
681
+ structured.applied === false &&
682
+ structured.persisted === false &&
683
+ structured.request_id === requestId &&
684
+ structured.session_ref === sessionRef &&
685
+ structured.revision === revision &&
686
+ structured.policy_version === 'context-recovery-v1' &&
687
+ typeof structured.correlation_id === 'string' &&
688
+ structured.correlation_id.length > 0 &&
689
+ typeof structured.projection_hash === 'string' &&
690
+ structured.projection_hash === hashJson(projection) &&
691
+ validTimestamp(structured.created_at) &&
692
+ validTimestamp(structured.expires_at) &&
693
+ structured.provider_model === null &&
694
+ Array.isArray(structured.decisions) &&
695
+ structured.decisions.length === 0 &&
696
+ stats?.selected_count === 0 &&
697
+ stats?.protected_count === 0 &&
698
+ stats?.eligible_count === 0 &&
699
+ stats?.batch_count === 0 &&
700
+ stats?.provider_input_tokens === null &&
701
+ stats?.provider_output_tokens === null;
702
+ if (!selection.response.ok || selection.parsed?.error || !validNoop)
703
+ throw new Error(
704
+ responseError(
705
+ selection.response,
706
+ structuredErrorCode(result) ?? 'mcp_paid_pilot_probe_denied',
707
+ ),
708
+ );
709
+ if (result?.isError === true)
710
+ throw new Error(structuredErrorCode(result) ?? 'mcp_paid_pilot_probe_denied');
711
+ return { ok: true, providerBatches: 0, providerModel: null };
712
+ }
713
+
714
+ /** @param {string} endpoint @param {string} token @param {import('./policy.mjs').ContextPolicy} policy @param {string} clients */
715
+ export async function providerFreeProbeV2(endpoint, token, policy, clients) {
716
+ const url = endpointUrl(endpoint).toString();
717
+ const initialized = await call(
718
+ url,
719
+ token,
720
+ {
721
+ jsonrpc: '2.0',
722
+ id: 1,
723
+ method: 'initialize',
724
+ params: {
725
+ protocolVersion: '2025-03-26',
726
+ capabilities: {},
727
+ clientInfo: { name: 'aibrain', version: '0.3.0-beta.9' },
728
+ },
729
+ },
730
+ undefined,
731
+ undefined,
732
+ );
733
+ const initializeResult = initialized.parsed?.result;
734
+ if (
735
+ !initialized.response.ok ||
736
+ initialized.parsed?.error ||
737
+ !isObject(initializeResult) ||
738
+ typeof initializeResult.protocolVersion !== 'string' ||
739
+ !SUPPORTED_PROTOCOL_VERSIONS.has(initializeResult.protocolVersion) ||
740
+ !isObject(initializeResult.capabilities) ||
741
+ !isObject(initializeResult.serverInfo) ||
742
+ typeof initializeResult.serverInfo.name !== 'string' ||
743
+ initializeResult.serverInfo.name.length === 0 ||
744
+ initializeResult.serverInfo.name.length > 128 ||
745
+ typeof initializeResult.serverInfo.version !== 'string' ||
746
+ initializeResult.serverInfo.version.length === 0 ||
747
+ initializeResult.serverInfo.version.length > 128
748
+ )
749
+ throw new Error(responseError(initialized.response, 'mcp_v2_unsupported'));
750
+ const protocolVersion = initializeResult.protocolVersion;
751
+ const initializedNotification = await call(
752
+ url,
753
+ token,
754
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
755
+ initialized.sessionId,
756
+ protocolVersion,
757
+ );
758
+ if (
759
+ !initializedNotification.response.ok &&
760
+ ![202, 204].includes(initializedNotification.response.status)
761
+ )
762
+ throw new Error(responseError(initializedNotification.response, 'mcp_v2_unsupported'));
763
+ const revision = 'a'.repeat(64);
764
+ const sessionRef = 'aibrain-setup-probe-v2';
765
+ const now = new Date().toISOString();
766
+ const compactOptions = {
767
+ keep_threshold: policy.keepThreshold,
768
+ preserve_recent_messages: policy.preserveRecentMessages,
769
+ min_reduction_ratio: policy.minReductionRatio,
770
+ truncate_head_chars: policy.truncateHeadChars,
771
+ max_state_tokens: policy.maxStateTokens,
772
+ max_request_tokens: policy.maxRequestTokens,
773
+ tool_policy: policy.toolPolicy,
774
+ };
775
+ const selectionOptions = {
776
+ keep_threshold: policy.keepThreshold,
777
+ preserve_recent_items: policy.preserveRecentMessages,
778
+ max_state_tokens: policy.maxStateTokens,
779
+ max_request_tokens: policy.maxRequestTokens,
780
+ };
781
+ /** @param {JsonObject | null} structured @param {string} expectedPolicy @param {string} expectedOptionsHash @param {string} expectedProjectionHash @param {string} expectedRequestId @param {boolean} selection */
782
+ const validateNoop = (
783
+ structured,
784
+ expectedPolicy,
785
+ expectedOptionsHash,
786
+ expectedProjectionHash,
787
+ expectedRequestId,
788
+ selection,
789
+ ) => {
790
+ const stats = structured && isObject(structured.stats) ? structured.stats : null;
791
+ const expectedKeys = selection
792
+ ? [
793
+ 'schema_version',
794
+ 'status',
795
+ 'applied',
796
+ 'persisted',
797
+ 'request_id',
798
+ 'correlation_id',
799
+ 'session_ref',
800
+ 'revision',
801
+ 'projection_hash',
802
+ 'options_hash',
803
+ 'policy_version',
804
+ 'provider_model',
805
+ 'created_at',
806
+ 'expires_at',
807
+ 'decisions',
808
+ 'fitting',
809
+ 'stats',
810
+ ]
811
+ : [
812
+ 'schema_version',
813
+ 'status',
814
+ 'applied',
815
+ 'request_id',
816
+ 'correlation_id',
817
+ 'session_ref',
818
+ 'revision',
819
+ 'projection_hash',
820
+ 'options_hash',
821
+ 'policy_version',
822
+ 'provider_model',
823
+ 'created_at',
824
+ 'expires_at',
825
+ 'decisions',
826
+ 'fitting',
827
+ 'stats',
828
+ ];
829
+ const statKeys = selection
830
+ ? [
831
+ 'selected_count',
832
+ 'protected_count',
833
+ 'eligible_count',
834
+ 'batch_count',
835
+ 'provider_input_tokens',
836
+ 'provider_output_tokens',
837
+ ]
838
+ : [
839
+ 'eligible_count',
840
+ 'protected_count',
841
+ 'kept_count',
842
+ 'truncated_count',
843
+ 'dropped_count',
844
+ 'batch_count',
845
+ 'provider_input_tokens',
846
+ 'provider_output_tokens',
847
+ 'estimated_state_tokens',
848
+ 'estimated_request_tokens',
849
+ 'estimated_reduction',
850
+ ];
851
+ const zeroStats = selection
852
+ ? stats?.selected_count === 0 &&
853
+ stats?.protected_count === 0 &&
854
+ stats?.eligible_count === 0 &&
855
+ stats?.batch_count === 0 &&
856
+ stats?.provider_input_tokens === null &&
857
+ stats?.provider_output_tokens === null
858
+ : stats?.eligible_count === 0 &&
859
+ stats?.protected_count === 0 &&
860
+ stats?.kept_count === 0 &&
861
+ stats?.truncated_count === 0 &&
862
+ stats?.dropped_count === 0 &&
863
+ stats?.batch_count === 0 &&
864
+ stats?.provider_input_tokens === null &&
865
+ stats?.provider_output_tokens === null;
866
+ return (
867
+ structured !== null &&
868
+ hasOnlyKeys(structured, expectedKeys) &&
869
+ hasOnlyKeys(stats ?? {}, statKeys) &&
870
+ structured.schema_version === 2 &&
871
+ structured.status === 'noop' &&
872
+ structured.applied === false &&
873
+ (selection ? structured.persisted === false : true) &&
874
+ structured.request_id === expectedRequestId &&
875
+ structured.session_ref === sessionRef &&
876
+ structured.revision === revision &&
877
+ structured.policy_version === expectedPolicy &&
878
+ typeof structured.correlation_id === 'string' &&
879
+ structured.correlation_id.length > 0 &&
880
+ validTimestamp(structured.created_at) &&
881
+ validTimestamp(structured.expires_at) &&
882
+ structured.projection_hash === expectedProjectionHash &&
883
+ structured.options_hash === expectedOptionsHash &&
884
+ structured.provider_model === null &&
885
+ Array.isArray(structured.decisions) &&
886
+ structured.decisions.length === 0 &&
887
+ structured.fitting === null &&
888
+ zeroStats
889
+ );
890
+ };
891
+ /** @param {number} id @param {string} name @param {JsonObject} argumentsValue */
892
+ const callTool = async (id, name, argumentsValue) => {
893
+ const response = await call(
894
+ url,
895
+ token,
896
+ { jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: argumentsValue } },
897
+ initialized.sessionId,
898
+ protocolVersion,
899
+ );
900
+ const result =
901
+ response.parsed && isObject(response.parsed.result) ? response.parsed.result : null;
902
+ const structured =
903
+ result && isObject(result) && isObject(result.structuredContent)
904
+ ? result.structuredContent
905
+ : null;
906
+ const policyVersion =
907
+ typeof argumentsValue.policy_version === 'string' ? argumentsValue.policy_version : '';
908
+ const options = isObject(argumentsValue.options) ? argumentsValue.options : null;
909
+ const projection = isObject(argumentsValue.projection) ? argumentsValue.projection : null;
910
+ if (
911
+ !response.response.ok ||
912
+ response.parsed?.error ||
913
+ result?.isError === true ||
914
+ options === null ||
915
+ projection === null ||
916
+ typeof argumentsValue.request_id !== 'string' ||
917
+ !validateNoop(
918
+ structured,
919
+ policyVersion,
920
+ hashJson(options),
921
+ hashJson(projection),
922
+ argumentsValue.request_id,
923
+ name === 'brain_context_select',
924
+ )
925
+ )
926
+ throw new Error(responseError(response.response, 'mcp_v2_unsupported'));
927
+ };
928
+ await callTool(2, 'brain_context_select', {
929
+ schema_version: 2,
930
+ client: clients === 'claude' ? 'claude_code' : 'codex_app_server',
931
+ client_version: '0.3.0-beta.9',
932
+ session_ref: sessionRef,
933
+ revision,
934
+ observed_at: now,
935
+ request_id: randomUUID(),
936
+ policy_version: 'context-recovery-v2',
937
+ projection: { goal: '', items: [] },
938
+ options: selectionOptions,
939
+ });
940
+ if (clients === 'claude' || clients === 'both')
941
+ await callTool(3, 'brain_context_compact', {
942
+ schema_version: 2,
943
+ client: 'claude_code',
944
+ client_version: '0.3.0-beta.9',
945
+ session_ref: sessionRef,
946
+ revision,
947
+ observed_at: now,
948
+ request_id: randomUUID(),
949
+ projection_version: 1,
950
+ policy_version: 'context-v2',
951
+ projection: { goal: '', messages: [], pairs: [], protected_item_count: 0 },
952
+ options: compactOptions,
953
+ });
954
+ return { ok: true, providerBatches: 0, providerModel: null, protocol: 'v2' };
955
+ }
956
+
957
+ /** @param {string} endpoint @param {string} token @param {import('./policy.mjs').ContextPolicy} [policy] @param {string} [clients] */
958
+ export async function providerFreeProbe(endpoint, token, policy, clients) {
959
+ return policy === undefined
960
+ ? providerFreeProbeV1(endpoint, token)
961
+ : providerFreeProbeV2(endpoint, token, policy, clients ?? 'both');
962
+ }