fullcourtdefense 2.2.0 → 2.3.1

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/client.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FullCourtDefense = exports.TextScanDisabledError = exports._clearCircuitBreakers = void 0;
4
4
  exports._clearShieldModeCache = _clearShieldModeCache;
5
+ const crypto_1 = require("crypto");
5
6
  const circuitBreaker_1 = require("./circuitBreaker");
6
7
  Object.defineProperty(exports, "_clearCircuitBreakers", { enumerable: true, get: function () { return circuitBreaker_1._clearCircuitBreakers; } });
7
8
  const protect_1 = require("./protect");
@@ -13,6 +14,7 @@ const recordSpool_1 = require("./recordSpool");
13
14
  const argsBounds_1 = require("./argsBounds");
14
15
  const localDecision_1 = require("./localDecision");
15
16
  const recordQueue_1 = require("./recordQueue");
17
+ const localGate_1 = require("./localGate");
16
18
  const DEFAULT_API_URL = 'https://api.fullcourtdefense.ai';
17
19
  const SHIELD_ID_ENV_VARS = ['FCD_SHIELD_ID', 'FULLCOURTDEFENSE_SHIELD_ID', 'AGENTGUARD_SHIELD_ID'];
18
20
  const SHIELD_KEY_ENV_VARS = ['FCD_SHIELD_KEY', 'FULLCOURTDEFENSE_SHIELD_KEY', 'AGENTGUARD_SHIELD_KEY'];
@@ -23,8 +25,17 @@ const ENVIRONMENT_ENV_VARS = ['FCD_ENVIRONMENT', 'FULLCOURTDEFENSE_ENVIRONMENT',
23
25
  const TEXT_SCAN_ENV_VARS = ['FCD_TEXT_SCAN', 'FULLCOURTDEFENSE_TEXT_SCAN'];
24
26
  const DECISION_MODE_ENV_VARS = ['FCD_DECISION_MODE', 'FULLCOURTDEFENSE_DECISION_MODE'];
25
27
  const COLD_START_WAIT_ENV_VARS = ['FCD_COLD_START_WAIT_MS', 'FULLCOURTDEFENSE_COLD_START_WAIT_MS'];
26
- /** Local decisions: the longest a call waits for the first bundle, measured from the client's construction. */
27
- const DEFAULT_COLD_START_WAIT_MS = 1500;
28
+ /**
29
+ * Local decisions: the longest a call waits for the first bundle, measured from the client's construction. 1 s, the ceiling of
30
+ * the machine hook (owner decision 2026-11-15; it was 3 s). A serverless agent whose first policies arrive later sets
31
+ * FCD_COLD_START_WAIT_MS, or awaits `ready()` at start-up.
32
+ */
33
+ const DEFAULT_COLD_START_WAIT_MS = 1000;
34
+ /** The API refused this agent's shield key or shield: wrong / expired / rotated key (401), not allowed (403), unknown shield (404). */
35
+ function isRefusedKeyStatus(status) {
36
+ return status === 401 || status === 403 || status === 404;
37
+ }
38
+ const REFUSED_KEY_OUTCOME = 'Tool calls of this agent are NOT checked until this is fixed: they run under the fail mode (FCD_FAIL_MODE) and are reported once a key works.';
28
39
  function parseDecisionMode(raw) {
29
40
  const value = (raw || '').trim().toLowerCase();
30
41
  return value === 'local' || value === 'server' ? value : undefined;
@@ -199,13 +210,29 @@ async function settleWithin(work, ms) {
199
210
  if (cap !== undefined)
200
211
  clearTimeout(cap);
201
212
  }
202
- const EXIT_FLUSH_MAX_MS = 1500;
213
+ /** The end of the process SENDS its last records for at most this long (owner 2026-11-21: the SDK sends the data). */
214
+ const EXIT_FLUSH_MAX_MS = 4000;
215
+ /** Requests at once at the end of the process. */
216
+ const EXIT_SENDERS = 8;
217
+ /** The one direct gap report at the end of the process (after the send window). */
218
+ const EXIT_GAP_TIMEOUT_MS = 1000;
219
+ const RECORD_PATH = '/api/agent-security/runtime/tool-call';
220
+ /** Spooled records an earlier process left that this process queued and has not confirmed yet: shield -> gap id -> count. */
221
+ const replayedGaps = new Map();
222
+ /**
223
+ * Aborted once the end of the process has kept and reported what was left: the SDK's own requests still open would
224
+ * otherwise keep the process alive until their timeouts (seen on the lab VM: 7-10 s). Their records are already kept.
225
+ */
226
+ const exitAbort = new AbortController();
227
+ let exitKept = false;
203
228
  const FAILED_RECORDS_MAX = 200;
204
229
  const pendingRecords = new Set();
205
230
  const failedRecords = [];
206
231
  /** Clients holding calls in memory (spooled while the API was down, or waiting for the first mode lookup). */
207
232
  const liveClients = new Set();
208
233
  const replayedShields = new Set();
234
+ /** API origins that answered the batch record route with "no such route" (an older backend): their records go one by one for the rest of the process. */
235
+ const singleRecordApis = new Set();
209
236
  let exitHooksInstalled = false;
210
237
  let exitFlushRunning = false;
211
238
  function toSpooled(entry) {
@@ -216,8 +243,16 @@ function toSpooled(entry) {
216
243
  return undefined;
217
244
  }
218
245
  }
219
- /** Write everything still unsent to the local spool (synchronous: it runs at `exit`). */
220
- function persistLeftovers() {
246
+ /** How many tool-call records a spooled request carries (a single record, or the records of a batch that was on the wire). */
247
+ function recordsIn(record) {
248
+ if (record.path === RECORD_PATH)
249
+ return 'actionId' in record.body && 'outcome' in record.body ? 0 : 1;
250
+ if (record.path === recordSpool_1.GAP_PATH && Array.isArray(record.body.records))
251
+ return record.body.records.length;
252
+ return 0;
253
+ }
254
+ /** Everything still unsent, records tagged with their shield's exit gap; and per shield the one gap report to send. */
255
+ function collectLeftovers() {
221
256
  const records = [];
222
257
  const keep = (entry) => {
223
258
  const record = toSpooled(entry);
@@ -230,11 +265,63 @@ function persistLeftovers() {
230
265
  for (const entry of failedRecords)
231
266
  keep(entry);
232
267
  failedRecords.length = 0;
233
- for (const client of liveClients)
268
+ const clients = new Map();
269
+ for (const client of liveClients) {
270
+ clients.set(client._shieldIdForExit(), client);
234
271
  records.push(...client._takeUnsentForSpool());
272
+ }
235
273
  liveClients.clear();
236
- (0, recordSpool_1.writeSpool)(records);
274
+ const counts = new Map();
275
+ const gapIds = new Map();
276
+ const at = new Date().toISOString();
277
+ for (const record of records) {
278
+ const n = recordsIn(record);
279
+ if (n === 0)
280
+ continue;
281
+ if (!gapIds.has(record.shieldId))
282
+ gapIds.set(record.shieldId, `gap-exit-${(0, crypto_1.randomUUID)()}`);
283
+ record.gapId = gapIds.get(record.shieldId);
284
+ counts.set(record.shieldId, (counts.get(record.shieldId) ?? 0) + n);
285
+ }
286
+ const reports = [];
287
+ for (const shieldId of new Set([...counts.keys(), ...replayedGaps.keys()])) {
288
+ const body = { records: [] };
289
+ const n = counts.get(shieldId) ?? 0;
290
+ if (n > 0)
291
+ body.gap = { dropped: n, from: at, to: at, id: gapIds.get(shieldId), pending: true };
292
+ const held = replayedGaps.get(shieldId);
293
+ if (held && held.size > 0)
294
+ body.resolveGaps = Array.from(held, ([id, count]) => ({ id, count })).slice(0, 20);
295
+ reports.push({ shieldId, client: clients.get(shieldId), body, at });
296
+ }
297
+ replayedGaps.clear();
298
+ return { records, reports };
299
+ }
300
+ /** Write everything still unsent to the local spool, with its gap report (synchronous: it runs at `exit`, which cannot send). */
301
+ function persistLeftovers() {
302
+ const { records, reports } = collectLeftovers();
303
+ (0, recordSpool_1.writeSpool)([...records, ...reports.filter((r) => r.body.gap).map((r) => ({ path: recordSpool_1.GAP_PATH, body: { ...r.body, shieldId: r.shieldId }, shieldId: r.shieldId, at: r.at }))]);
304
+ }
305
+ /** Spool what is left, then send each shield's gap report directly (the console shows it even if this disk is gone). */
306
+ async function keepAndReport() {
307
+ const { records, reports } = collectLeftovers();
308
+ const kept = (0, recordSpool_1.writeSpool)(records);
309
+ const unsent = [];
310
+ await Promise.all(reports.map(async (report) => {
311
+ const gap = report.body.gap;
312
+ if (gap && kept < records.length)
313
+ gap.pending = false;
314
+ const ok = report.client ? await report.client._postExitReport(report.body, EXIT_GAP_TIMEOUT_MS) : false;
315
+ if (!ok && gap)
316
+ unsent.push({ path: recordSpool_1.GAP_PATH, body: { ...report.body, shieldId: report.shieldId }, shieldId: report.shieldId, at: report.at });
317
+ }));
318
+ (0, recordSpool_1.writeSpool)(unsent);
237
319
  }
320
+ /**
321
+ * The end of the process (owner 2026-11-21: the SDK sends the data, nothing to configure): SEND every unsent record in
322
+ * parallel batches for at most EXIT_FLUSH_MAX_MS; keep what is still left on this machine; report it to the server at once
323
+ * (one gap per shield, `pending` when it was kept; the next start clears it as it delivers the records).
324
+ */
238
325
  async function flushAtExit() {
239
326
  if (exitFlushRunning)
240
327
  return;
@@ -250,7 +337,14 @@ async function flushAtExit() {
250
337
  await settleWithin(Promise.all(work), EXIT_FLUSH_MAX_MS);
251
338
  }
252
339
  finally {
253
- persistLeftovers();
340
+ try {
341
+ await settleWithin(keepAndReport(), EXIT_GAP_TIMEOUT_MS + 500);
342
+ }
343
+ catch {
344
+ persistLeftovers();
345
+ }
346
+ exitKept = true;
347
+ exitAbort.abort();
254
348
  exitFlushRunning = false;
255
349
  }
256
350
  }
@@ -267,12 +361,15 @@ function installExitHooks() {
267
361
  for (const signal of ['SIGINT', 'SIGTERM']) {
268
362
  const handler = () => {
269
363
  // Another handler of the host shuts down its own way (and `exit` still runs); when ours is the only
270
- // one, the signal would have ended the process: keep the records, then end it the same way.
364
+ // one, the signal would have ended the process: send the records (bounded), then end it the same way.
271
365
  if (proc.listenerCount(signal) > 1)
272
366
  return;
273
- persistLeftovers();
274
- proc.removeListener(signal, handler);
275
- proc.kill(proc.pid, signal);
367
+ const end = () => {
368
+ persistLeftovers();
369
+ proc.removeListener(signal, handler);
370
+ proc.kill(proc.pid, signal);
371
+ };
372
+ void flushAtExit().then(end, end);
276
373
  };
277
374
  proc.on(signal, handler);
278
375
  }
@@ -282,6 +379,8 @@ function installExitHooks() {
282
379
  }
283
380
  }
284
381
  function keepFailed(entry) {
382
+ if (exitKept)
383
+ return; // already kept by the end of the process (an aborted request)
285
384
  if (failedRecords.length >= FAILED_RECORDS_MAX)
286
385
  failedRecords.shift();
287
386
  failedRecords.push(entry);
@@ -331,7 +430,18 @@ class FullCourtDefense {
331
430
  const coldStartRaw = config.coldStartWaitMs ?? Number(readEnv(COLD_START_WAIT_ENV_VARS) ?? DEFAULT_COLD_START_WAIT_MS);
332
431
  const coldStartWaitMs = Number.isFinite(coldStartRaw) ? Math.max(0, Math.min(coldStartRaw, 10000)) : DEFAULT_COLD_START_WAIT_MS;
333
432
  this.coldStartDeadline = Date.now() + coldStartWaitMs;
334
- this.records = new recordQueue_1.RecordQueue((body) => this._sendQueuedRecord(body));
433
+ this.records = new recordQueue_1.RecordQueue((bodies, gap) => this._sendRecordBatch(bodies, gap), {
434
+ // Records dropped because the upload could not keep up: the app hears it (once per 30 s), the next upload reports it.
435
+ onDrop: (info) => this.emitDegrade({
436
+ call: 'recordUpload',
437
+ reason: `records_dropped: ${info.dropped} tool-call ${info.dropped === 1 ? 'record was' : 'records were'} not uploaded between ${info.from} and ${info.to} (the app made more calls than could be uploaded)`,
438
+ breakerState: this.breakerState(),
439
+ failedClosed: false,
440
+ droppedRecords: info.dropped,
441
+ droppedFrom: info.from,
442
+ droppedTo: info.to,
443
+ }),
444
+ });
335
445
  this.breaker = config.circuitBreaker === false
336
446
  ? null
337
447
  : (0, circuitBreaker_1.getCircuitBreaker)(`${this.config.apiUrl}|${this.config.shieldId}`, config.circuitBreaker || undefined);
@@ -408,20 +518,75 @@ class FullCourtDefense {
408
518
  _localBundle() {
409
519
  return modeCache.get(this._modeCacheKey())?.bundle;
410
520
  }
411
- /** One queued record to the record endpoint (RecordQueue's sender). */
412
- async _sendQueuedRecord(body) {
413
- const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-call', body, 'inflight');
414
- if (result.success)
415
- return 'sent';
416
- if (result.localEncodingError)
417
- return 'refused';
521
+ /**
522
+ * One batch of queued records (RecordQueue's sender): `POST /runtime/tool-calls` with the records and, when the queue dropped
523
+ * some, the gap. An older backend (404 / 405 with no runtime error code) has no such route: the records go one by one to
524
+ * `/runtime/tool-call` from then on, for the rest of the process. A record or two the backend could not write come back as
525
+ * `outage` (resent); a record it refused is dropped.
526
+ */
527
+ async _sendRecordBatch(bodies, gap) {
528
+ if (singleRecordApis.has(this.config.apiUrl))
529
+ return this._sendRecordsOneByOne(bodies);
530
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-calls', { agentName: this._identity.agentId, records: bodies, ...(gap ? { gap } : {}) }, 'inflight', Math.max(this.config.scanTimeoutMs, 8000));
531
+ if (result.success) {
532
+ const data = result.data ?? {};
533
+ const refused = new Set(Array.isArray(data.refused) ? data.refused : []);
534
+ const failed = new Set(Array.isArray(data.failed) ? data.failed : []);
535
+ return {
536
+ results: bodies.map((_, at) => (failed.has(at) ? 'outage' : refused.has(at) ? 'refused' : 'sent')),
537
+ gapAccepted: gap ? data.gapRecorded === true : undefined,
538
+ };
539
+ }
418
540
  const status = typeof result.status === 'number' ? result.status : undefined;
541
+ // A route this backend does not have (no runtime error code on the answer): remembered, so this costs one request per process.
542
+ if ((status === 404 || status === 405) && !result.serverCode) {
543
+ singleRecordApis.add(this.config.apiUrl);
544
+ return this._sendRecordsOneByOne(bodies);
545
+ }
546
+ // One record that cannot be encoded, or a request too large: the single route says which record is the problem.
547
+ if (result.localEncodingError || status === 413)
548
+ return this._sendRecordsOneByOne(bodies);
419
549
  if (status === undefined || status >= 500 || status === 408 || status === 429)
420
550
  return 'outage';
421
551
  return 'refused';
422
552
  }
553
+ /** The older route: one record per request, a few at a time; after the first outage the rest of the batch waits (resent later). */
554
+ async _sendRecordsOneByOne(bodies) {
555
+ const results = new Array(bodies.length).fill('outage');
556
+ let next = 0;
557
+ let down = false;
558
+ const worker = async () => {
559
+ while (next < bodies.length && !down) {
560
+ const at = next++;
561
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-call', bodies[at], 'inflight');
562
+ if (result.success)
563
+ results[at] = 'sent';
564
+ else if (result.localEncodingError)
565
+ results[at] = 'refused';
566
+ else {
567
+ const status = typeof result.status === 'number' ? result.status : undefined;
568
+ if (status === undefined || status >= 500 || status === 408 || status === 429)
569
+ down = true;
570
+ else
571
+ results[at] = 'refused';
572
+ }
573
+ }
574
+ };
575
+ await Promise.all(Array.from({ length: Math.min(8, bodies.length) }, worker));
576
+ return { results, gapAccepted: false };
577
+ }
423
578
  /** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
424
579
  _enqueueRecord(body) {
580
+ // Every record has an id the backend keys on (runtime/tool-call-identity.ts): the provider's tool-call id, else one
581
+ // made here. A record is sent again when the API did not answer in time; with the id, a slow API that did store it
582
+ // the first time holds ONE record, not one per attempt.
583
+ if (typeof body.toolCallId !== 'string' || !body.toolCallId) {
584
+ body = { ...body, toolCallId: `fcd-${(0, crypto_1.randomUUID)()}`, decisionSource: 'sdk' };
585
+ }
586
+ // The record's OWN id, made once and kept on every resend (batches, spool): the server stores a record once by it,
587
+ // never by the provider's tool-call id, which scripted models and some providers repeat (sdk-albtech-e2e 2026-11-22).
588
+ if (typeof body.recordId !== 'string' || !body.recordId)
589
+ body = { ...body, recordId: `r${(0, crypto_1.randomUUID)().replace(/-/g, '')}` };
425
590
  this.records.push(body);
426
591
  liveClients.add(this);
427
592
  installExitHooks();
@@ -434,14 +599,61 @@ class FullCourtDefense {
434
599
  replayedShields.add(shieldId);
435
600
  setTimeout(() => {
436
601
  try {
437
- for (const record of (0, recordSpool_1.claimSpooled)(shieldId))
438
- void this._postAgentSecurity(record.path, record.body, 'full');
602
+ const spooled = (0, recordSpool_1.claimSpooled)(shieldId);
603
+ // Gap reports first (one request each), then the records through the batched queue (#4087), then clear the gaps.
604
+ const queued = spooled.filter((r) => r.path === RECORD_PATH && !('actionId' in r.body && 'outcome' in r.body));
605
+ for (const record of spooled)
606
+ if (!queued.includes(record))
607
+ void this._postAgentSecurity(record.path, record.body, 'full');
608
+ const gaps = new Map();
609
+ for (const record of queued) {
610
+ if (record.gapId)
611
+ gaps.set(record.gapId, (gaps.get(record.gapId) ?? 0) + 1);
612
+ const { shieldId: _drop, ...body } = record.body;
613
+ this._enqueueRecord(body);
614
+ }
615
+ for (const record of spooled) {
616
+ if (record.path === recordSpool_1.GAP_PATH && record.gapId && Array.isArray(record.body.records))
617
+ gaps.set(record.gapId, (gaps.get(record.gapId) ?? 0) + record.body.records.length);
618
+ }
619
+ if (gaps.size > 0) {
620
+ const held = replayedGaps.get(shieldId) ?? new Map();
621
+ for (const [id, n] of gaps)
622
+ held.set(id, (held.get(id) ?? 0) + n);
623
+ replayedGaps.set(shieldId, held);
624
+ this._resolveReplayedGaps(gaps);
625
+ }
439
626
  }
440
627
  catch {
441
628
  // never reaches the agent
442
629
  }
443
630
  }, 0);
444
631
  }
632
+ /** Once the replayed records left the queue, clear the pending gaps an earlier process reported for them. */
633
+ _resolveReplayedGaps(gaps) {
634
+ const shieldId = this.config.shieldId;
635
+ const started = Date.now();
636
+ const tick = () => {
637
+ if (exitFlushRunning)
638
+ return; // the end of the process clears them in its own report
639
+ if (this.records.size > 0 && Date.now() - started < 600000) {
640
+ const t = setTimeout(tick, 500);
641
+ t.unref?.();
642
+ return;
643
+ }
644
+ if (this.records.size > 0)
645
+ return;
646
+ void this._postAgentSecurity(recordSpool_1.GAP_PATH, { records: [], resolveGaps: Array.from(gaps, ([id, count]) => ({ id, count })).slice(0, 20) }).then((result) => {
647
+ if (!result.success)
648
+ return;
649
+ const held = replayedGaps.get(shieldId);
650
+ for (const id of gaps.keys())
651
+ held?.delete(id);
652
+ });
653
+ };
654
+ const t = setTimeout(tick, 500);
655
+ t.unref?.();
656
+ }
445
657
  /** @internal Calls held in memory, as request bodies for the local spool (called at exit). */
446
658
  _takeUnsentForSpool() {
447
659
  for (const item of this.awaitingMode) {
@@ -462,6 +674,10 @@ class FullCourtDefense {
462
674
  at: entry.lastAt,
463
675
  });
464
676
  }
677
+ // Records dropped and not reported yet: the next process with this shield reports the gap.
678
+ const gap = this.records.takeGap();
679
+ if (gap)
680
+ out.push({ path: '/api/agent-security/runtime/tool-calls', body: { records: [], gap, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: gap.to });
465
681
  // Records of locally decided calls not sent yet: the next process with this shield sends them.
466
682
  for (const item of this.records.drain()) {
467
683
  out.push({ path: '/api/agent-security/runtime/tool-call', body: { ...item.body, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: item.at });
@@ -470,7 +686,26 @@ class FullCourtDefense {
470
686
  }
471
687
  /** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
472
688
  _flushForExit() {
473
- return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
689
+ this.records.boost(EXIT_SENDERS);
690
+ return Promise.all([this._flushSkippedChecks(), this.records.flush(EXIT_FLUSH_MAX_MS, EXIT_FLUSH_MAX_MS)]).then(() => undefined);
691
+ }
692
+ /** @internal This client's shield (the end of the process groups leftovers by shield). */
693
+ _shieldIdForExit() {
694
+ return this.config.shieldId;
695
+ }
696
+ /** @internal The one direct gap report at the end of the process; true when the server took it. */
697
+ async _postExitReport(body, timeoutMs) {
698
+ const result = await this._postAgentSecurity(recordSpool_1.GAP_PATH, { agentName: this._identity.agentId, ...body }, undefined, timeoutMs);
699
+ return result.success === true;
700
+ }
701
+ /**
702
+ * How the background record upload is doing (observability for the app and the load tests): records waiting, sent,
703
+ * refused, dropped because the upload could not keep up (`dropped`; `unreported` is the part no accepted upload has told
704
+ * FullCourtDefense about yet), gaps the backend took, requests made, and whether records go in batches or one by one (an older backend).
705
+ */
706
+ recordStats() {
707
+ const q = this.records;
708
+ return { queued: q.size, sent: q.sent, refused: q.refused, dropped: q.lost, unreported: q.unreportedLoss, gapsReported: q.gapsReported, requests: q.requests, mode: singleRecordApis.has(this.config.apiUrl) ? 'single' : 'batch' };
474
709
  }
475
710
  /** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
476
711
  get identity() {
@@ -733,7 +968,9 @@ class FullCourtDefense {
733
968
  modeCache.set(key, {
734
969
  mode, rules: knownMode ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS,
735
970
  confirmed: Boolean(knownMode), configError: fetched.configError,
736
- // A refused key decides nothing locally: Block calls go to the server, which answers the same refusal.
971
+ // Owner decision 2026-11-15: a refused key never stops the agent. The policies a live answer gave earlier keep
972
+ // deciding (stale-while-error, like an outage); with none, the fail mode answers (_decideLocal).
973
+ ...(knownMode && cached?.bundle ? { bundle: cached.bundle } : {}),
737
974
  });
738
975
  return resolved(mode, Boolean(knownMode), fetched.configError);
739
976
  }
@@ -766,7 +1003,7 @@ class FullCourtDefense {
766
1003
  // A wrong key or an unknown shield is not an outage: say so once, loudly (O4: a Monitor agent's
767
1004
  // tools run and are reported, a Blocking agent's tools stop with the same explanation).
768
1005
  if (resp.status === 401 || resp.status === 403 || resp.status === 404) {
769
- this._reportConfigurationError(resp.status, 'read the shield mode', undefined, 'Tool calls of this agent are not checked until this is fixed: on a Monitor shield they run and are reported, on a Blocking shield they stop.');
1006
+ this._reportConfigurationError(resp.status, 'read the shield mode', undefined, REFUSED_KEY_OUTCOME);
770
1007
  return { configError: resp.status };
771
1008
  }
772
1009
  return null;
@@ -1260,7 +1497,8 @@ class FullCourtDefense {
1260
1497
  return this._postAgentSecurity('/api/agent-security/runtime/register-agent', input);
1261
1498
  }
1262
1499
  async recordToolCall(rawInput) {
1263
- return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(rawInput), 'full');
1500
+ const withId = rawInput.recordId ? rawInput : { ...rawInput, recordId: `r${(0, crypto_1.randomUUID)().replace(/-/g, '')}` };
1501
+ return this._postAgentSecurity('/api/agent-security/runtime/tool-call', this.withIdentity(withId), 'full');
1264
1502
  }
1265
1503
  async checkToolCall(rawInput) {
1266
1504
  const input = this.withIdentity(rawInput);
@@ -1339,6 +1577,7 @@ class FullCourtDefense {
1339
1577
  this.breaker?.recordSuccess(Date.now() - startedAt);
1340
1578
  if (this.skippedChecks.size > 0)
1341
1579
  void this._flushSkippedChecks();
1580
+ this.records.resume(); // the API answers: queued records go now, not after the back-off
1342
1581
  return result;
1343
1582
  }
1344
1583
  // The body could not be encoded (a value with a throwing toJSON): the call's own input, definite.
@@ -1350,6 +1589,13 @@ class FullCourtDefense {
1350
1589
  // gets an explicit error (guardToolCall throws it; the tool does not run). An API that classifies
1351
1590
  // its errors (G-04) may still call a 400 retryable (a server failure answered the way machines
1352
1591
  // expect): that one is an outage.
1592
+ if (isRefusedKeyStatus(result.status) && result.retryable !== true && result.category !== 'server') {
1593
+ // Owner decision 2026-11-15: a refused shield key or shield (401 / 403 / 404) is OUR side not working for this
1594
+ // agent, whatever the cause; it never stops the customer's tool. Said loudly once, then the fail mode answers
1595
+ // (tiered: the tool runs and is reported as "ran without a check" once a key works). No breaker failure.
1596
+ this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, REFUSED_KEY_OUTCOME, result.serverCode);
1597
+ return this._degradeByFailMode(input, `shield key or shield refused (HTTP ${result.status})`, this.failMode ?? 'tiered');
1598
+ }
1353
1599
  if ((0, errors_1.isDefiniteStatus)(result.status) && result.retryable !== true && result.category !== 'server') {
1354
1600
  const error = this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, undefined, result.serverCode);
1355
1601
  return {
@@ -1378,9 +1624,15 @@ class FullCourtDefense {
1378
1624
  * warning says so. Never a request, never a wait.
1379
1625
  */
1380
1626
  _decideLocal(input, mode) {
1381
- if (this.decisionMode !== 'local' || mode.configError)
1627
+ if (this.decisionMode !== 'local')
1382
1628
  return undefined;
1383
1629
  const bundle = this._localBundle();
1630
+ if (!bundle && mode.configError) {
1631
+ // The shield key or the shield is refused (401 / 403 / 404) and no policies were ever read: said loudly once,
1632
+ // and the fail mode answers (the tool runs unless FCD_FAIL_MODE=closed). Never a request, never a stop of ours.
1633
+ this._reportConfigurationError(mode.configError, 'read the shield policies', undefined, REFUSED_KEY_OUTCOME);
1634
+ return { result: this._degradeByFailMode(input, `shield key or shield refused (HTTP ${mode.configError})`, this.failMode ?? 'tiered') };
1635
+ }
1384
1636
  if (!bundle) {
1385
1637
  // A live answer came without policies (an older backend): the server decides, as before.
1386
1638
  if (modeCache.get(this._modeCacheKey())?.confirmed)
@@ -1651,8 +1903,38 @@ class FullCourtDefense {
1651
1903
  }
1652
1904
  return result;
1653
1905
  }
1906
+ localGate() {
1907
+ return (this.localGateClient ?? (this.localGateClient = typeof process !== 'undefined' ? (0, localGate_1.createTrustedLocalGate)(process.env) : localGate_1.NO_GATE));
1908
+ }
1909
+ /** What the gate said about a call it did not allow: the error the agent code receives (the gate wrote the record). */
1910
+ async _localGateStop(input, answer, action, options) {
1911
+ const approval = answer.decision === 'approval';
1912
+ const reason = (answer.message || '').trim()
1913
+ || (approval ? `"${input.toolName}" needs a manager's approval and was sent to one.` : `Tool call blocked`);
1914
+ const hint = approval && answer.request && !reason.includes(answer.request) ? ` (request ${answer.request})` : '';
1915
+ if (approval && answer.request && options.approvalMode === 'wait') {
1916
+ await this._waitForApproval(answer.request, options);
1917
+ return action();
1918
+ }
1919
+ const message = `FullCourtDefense blocked tool call "${input.toolName}": ${reason}${hint}`;
1920
+ throw options.onBlocked
1921
+ ? options.onBlocked(message)
1922
+ : new errors_1.ToolCallBlocked(message, {
1923
+ toolName: input.toolName, decision: approval ? 'approval' : 'block', reason, outcome: approval ? 'approval' : 'block',
1924
+ code: approval ? 'FCD_APPROVAL_REQUIRED' : 'FCD_BLOCKED',
1925
+ ...(answer.ruleId ? { rule: { id: answer.ruleId } } : {}), approvalActionId: answer.request, degraded: false,
1926
+ });
1927
+ }
1654
1928
  async guardToolCall(rawInput, action, options = {}) {
1655
1929
  const input = this.withIdentity(rawInput);
1930
+ // A wrapped container's own gate decides first, from the signed bundle it holds (no request on the call; Monitor is one
1931
+ // local acknowledgement and never blocks). It writes the record. null: absent or unavailable, the paths below decide.
1932
+ const local = this.localGate();
1933
+ if (local !== localGate_1.NO_GATE) {
1934
+ const answer = await local.decide({ toolName: input.toolName, toolArgs: (input.toolArgs || {}), sessionId: input.sessionId, framework: input.framework });
1935
+ if (answer)
1936
+ return answer.decision === 'allow' ? action() : this._localGateStop(input, answer, action, options);
1937
+ }
1656
1938
  // Monitor mode: run the action immediately — no preflight wait, no approval
1657
1939
  // gate. The tool call is recorded fire-and-forget for console visibility.
1658
1940
  const mode = await this._resolveToolMode();
@@ -1917,7 +2199,7 @@ class FullCourtDefense {
1917
2199
  return this._postEncoded(path, encoded.json, timeoutMs);
1918
2200
  // A record: tracked while on the wire so the end of the process can wait for it briefly or spool it.
1919
2201
  const entry = { path, json: encoded.json, shieldId: this.config.shieldId, at: new Date().toISOString() };
1920
- const sending = this._postEncoded(path, encoded.json);
2202
+ const sending = this._postEncoded(path, encoded.json, timeoutMs);
1921
2203
  entry.done = sending;
1922
2204
  pendingRecords.add(entry);
1923
2205
  installExitHooks();
@@ -1925,8 +2207,19 @@ class FullCourtDefense {
1925
2207
  if (pendingRecords.delete(entry) && durable === 'full' && !result.success) {
1926
2208
  const noAnswer = typeof result.error === 'string' && result.error.startsWith('fcd_unavailable');
1927
2209
  const status = typeof result.status === 'number' ? result.status : undefined;
1928
- if (noAnswer || (status !== undefined && (status >= 500 || status === 408 || status === 429)))
1929
- keepFailed(entry);
2210
+ if (noAnswer || (status !== undefined && (status >= 500 || status === 408 || status === 429))) {
2211
+ // A record the server could not take goes to the batched queue, which sends it again with back-off while the process
2212
+ // runs (and keeps it at exit). Before, it waited for the next start (CI 2026-11-22: a burst lost records).
2213
+ const record = input;
2214
+ if (path === RECORD_PATH && !(record.actionId && record.outcome)) {
2215
+ const { shieldId: _drop, ...body } = record;
2216
+ void _drop;
2217
+ this._enqueueRecord(body);
2218
+ }
2219
+ else {
2220
+ keepFailed(entry);
2221
+ }
2222
+ }
1930
2223
  }
1931
2224
  return result;
1932
2225
  }
@@ -1937,12 +2230,23 @@ class FullCourtDefense {
1937
2230
  // when FullCourtDefense cannot be reached only once the agent itself reports it.
1938
2231
  if (this.failMode && this.failMode !== 'open')
1939
2232
  headers[failMode_1.FAIL_MODE_HEADER] = this.failMode;
1940
- const resp = await fetch(`${this.config.apiUrl}${path}`, {
1941
- method: 'POST',
1942
- headers,
1943
- body: json,
1944
- signal: AbortSignal.timeout(timeoutMs ?? this.config.scanTimeoutMs),
1945
- });
2233
+ // The request's own timeout, or the end of the process (exitAbort), whichever comes first (Node 18 has no AbortSignal.any).
2234
+ const controller = new AbortController();
2235
+ const limit = setTimeout(() => controller.abort(), timeoutMs ?? this.config.scanTimeoutMs);
2236
+ limit.unref?.();
2237
+ const onExit = () => controller.abort();
2238
+ if (exitAbort.signal.aborted)
2239
+ controller.abort();
2240
+ else
2241
+ exitAbort.signal.addEventListener('abort', onExit, { once: true });
2242
+ let resp;
2243
+ try {
2244
+ resp = await fetch(`${this.config.apiUrl}${path}`, { method: 'POST', headers, body: json, signal: controller.signal });
2245
+ }
2246
+ finally {
2247
+ clearTimeout(limit);
2248
+ exitAbort.signal.removeEventListener('abort', onExit);
2249
+ }
1946
2250
  const data = await resp.json().catch(() => ({}));
1947
2251
  if (!resp.ok) {
1948
2252
  // The runtime API's error body: { error, message?, code, category, retryable } (G-04).
@@ -39,6 +39,14 @@ type Post = (path: string, body: string, timeoutMs: number) => Promise<Reply>;
39
39
  * listener: asking again on every invocation would only add a failed connect to each call).
40
40
  */
41
41
  export declare function createLocalGate(env: Env, post?: Post): LocalGate;
42
+ /**
43
+ * Whether the gate on 127.0.0.1 may be asked outside the Lambda shim, which knows its own extension. Trusted only where the
44
+ * operator or the wrap says so: `FCD_LOCAL_GATE` on (the wrap writes it once its gate listens) or an explicit `FCD_GATE_PORT`.
45
+ * `FCD_LOCAL_GATE=off` always wins. Elsewhere a local process could answer "allow", so it is never assumed.
46
+ */
47
+ export declare function localGateTrusted(env: Env): boolean;
48
+ /** The loopback client for a host that is not the Lambda shim: none unless [`localGateTrusted`]. */
49
+ export declare function createTrustedLocalGate(env: Env, post?: Post): LocalGate;
42
50
  /** A gate that is never there: every call uses the shim's own path. */
43
51
  export declare const NO_GATE: LocalGate;
44
52
  export {};