@brunobracaioli/aibrain 0.1.0-beta.1 → 0.3.0-beta.13

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/dist/mcp.mjs CHANGED
@@ -3,6 +3,9 @@ import { createHash, randomUUID } from 'node:crypto';
3
3
  const MAX_BODY = 256 * 1024;
4
4
  const MAX_SESSION_ID = 256;
5
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;
6
9
  const MAX_ENDPOINT_LENGTH = 2_048;
7
10
  const SUPPORTED_PROTOCOL_VERSIONS = new Set([
8
11
  '2024-11-05',
@@ -147,11 +150,12 @@ async function responseObject(response) {
147
150
  * @param {JsonObject} body
148
151
  * @param {string | undefined} sessionId
149
152
  * @param {string | undefined} protocolVersion
153
+ * @param {number} [timeoutMs]
150
154
  * @returns {Promise<CallResult>}
151
155
  */
152
- async function call(url, token, body, sessionId, protocolVersion) {
156
+ async function call(url, token, body, sessionId, protocolVersion, timeoutMs = TIMEOUT_MS) {
153
157
  const controller = new AbortController();
154
- const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
158
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
155
159
  const expectedId = Object.hasOwn(body, 'id') ? body.id : undefined;
156
160
  try {
157
161
  const response = await fetch(url, {
@@ -216,6 +220,324 @@ async function call(url, token, body, sessionId, protocolVersion) {
216
220
  }
217
221
  }
218
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
+
219
541
  /** @param {unknown} value @returns {boolean} */
220
542
  function validTimestamp(value) {
221
543
  return typeof value === 'string' && Number.isFinite(Date.parse(value));
@@ -243,7 +565,7 @@ function structuredErrorCode(result) {
243
565
  }
244
566
 
245
567
  /** @param {string} endpoint @param {string} token @returns {Promise<{ok:true, providerBatches:0, providerModel:null}>} */
246
- export async function providerFreeProbe(endpoint, token) {
568
+ async function providerFreeProbeV1(endpoint, token) {
247
569
  const url = endpointUrl(endpoint).toString();
248
570
  if (typeof token !== 'string' || token.trim() === '') throw new Error('mcp_auth_denied');
249
571
  const initialized = await call(
@@ -256,7 +578,7 @@ export async function providerFreeProbe(endpoint, token) {
256
578
  params: {
257
579
  protocolVersion: '2025-03-26',
258
580
  capabilities: {},
259
- clientInfo: { name: 'aibrain', version: '0.1.0-beta.1' },
581
+ clientInfo: { name: 'aibrain', version: '0.3.0-beta.9' },
260
582
  },
261
583
  },
262
584
  undefined,
@@ -310,7 +632,7 @@ export async function providerFreeProbe(endpoint, token) {
310
632
  arguments: {
311
633
  schema_version: 1,
312
634
  client: 'codex_app_server',
313
- client_version: '0.162.0',
635
+ client_version: '0.3.0-beta.9',
314
636
  session_ref: sessionRef,
315
637
  revision,
316
638
  observed_at: new Date().toISOString(),
@@ -388,3 +710,253 @@ export async function providerFreeProbe(endpoint, token) {
388
710
  throw new Error(structuredErrorCode(result) ?? 'mcp_paid_pilot_probe_denied');
389
711
  return { ok: true, providerBatches: 0, providerModel: null };
390
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
+ }