fullcourtdefense 2.1.2 → 2.3.0

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");
@@ -11,6 +12,9 @@ const identity_1 = require("./identity");
11
12
  const errors_1 = require("./errors");
12
13
  const recordSpool_1 = require("./recordSpool");
13
14
  const argsBounds_1 = require("./argsBounds");
15
+ const localDecision_1 = require("./localDecision");
16
+ const recordQueue_1 = require("./recordQueue");
17
+ const localGate_1 = require("./localGate");
14
18
  const DEFAULT_API_URL = 'https://api.fullcourtdefense.ai';
15
19
  const SHIELD_ID_ENV_VARS = ['FCD_SHIELD_ID', 'FULLCOURTDEFENSE_SHIELD_ID', 'AGENTGUARD_SHIELD_ID'];
16
20
  const SHIELD_KEY_ENV_VARS = ['FCD_SHIELD_KEY', 'FULLCOURTDEFENSE_SHIELD_KEY', 'AGENTGUARD_SHIELD_KEY'];
@@ -19,6 +23,23 @@ const API_KEY_ENV_VARS = ['FCD_API_KEY', 'FULLCOURTDEFENSE_API_KEY', 'BOTGUARD_A
19
23
  const AGENT_INSTANCE_ID_ENV_VARS = ['FCD_AGENT_INSTANCE_ID', 'FULLCOURTDEFENSE_AGENT_INSTANCE_ID'];
20
24
  const ENVIRONMENT_ENV_VARS = ['FCD_ENVIRONMENT', 'FULLCOURTDEFENSE_ENVIRONMENT', 'NODE_ENV'];
21
25
  const TEXT_SCAN_ENV_VARS = ['FCD_TEXT_SCAN', 'FULLCOURTDEFENSE_TEXT_SCAN'];
26
+ const DECISION_MODE_ENV_VARS = ['FCD_DECISION_MODE', 'FULLCOURTDEFENSE_DECISION_MODE'];
27
+ const COLD_START_WAIT_ENV_VARS = ['FCD_COLD_START_WAIT_MS', 'FULLCOURTDEFENSE_COLD_START_WAIT_MS'];
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.';
39
+ function parseDecisionMode(raw) {
40
+ const value = (raw || '').trim().toLowerCase();
41
+ return value === 'local' || value === 'server' ? value : undefined;
42
+ }
22
43
  function readEnv(names) {
23
44
  const env = globalThis.process?.env;
24
45
  if (!env)
@@ -147,11 +168,19 @@ const MODE_FETCH_TIMEOUT_MS = 1500;
147
168
  // After a failed mode lookup, don't retry for this window — avoids adding the
148
169
  // lookup timeout to every call while the backend is down.
149
170
  const MODE_FAILURE_RETRY_MS = 5000;
171
+ /** How often local decisions refresh the bundle in the background (never on a tool call's path). */
172
+ const BUNDLE_REFRESH_MS = 60000;
173
+ /** A background bundle fetch may take longer than a hot-path lookup: nothing waits for it. */
174
+ const BUNDLE_FETCH_TIMEOUT_MS = 5000;
175
+ const bundleRefreshTimers = new Map();
150
176
  const modeCache = new Map();
151
177
  /** Test hook — clears the module-level shield mode cache. */
152
178
  function _clearShieldModeCache() {
153
179
  modeCache.clear();
154
180
  replayedShields.clear();
181
+ for (const timer of bundleRefreshTimers.values())
182
+ clearInterval(timer);
183
+ bundleRefreshTimers.clear();
155
184
  }
156
185
  // Built-in high-risk operations/tools that fail CLOSED when the backend is
157
186
  // unreachable in block mode. Irreversible/high-impact actions must never
@@ -188,6 +217,8 @@ const failedRecords = [];
188
217
  /** Clients holding calls in memory (spooled while the API was down, or waiting for the first mode lookup). */
189
218
  const liveClients = new Set();
190
219
  const replayedShields = new Set();
220
+ /** 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. */
221
+ const singleRecordApis = new Set();
191
222
  let exitHooksInstalled = false;
192
223
  let exitFlushRunning = false;
193
224
  function toSpooled(entry) {
@@ -278,6 +309,10 @@ class FullCourtDefense {
278
309
  this.reportedConfigErrors = new Set();
279
310
  /** O4: a Monitor call ran with a refused key or shield and stderr said so (once, without onDegrade). */
280
311
  this.warnedMonitorConfigError = false;
312
+ /** One warning when a Block-mode call ran before any policy bundle was available. */
313
+ this.warnedNoBundle = false;
314
+ /** guardToolCall's calls: the local decision's record is handed back here and written after the tool ran. */
315
+ this.deferredLocalRecords = new WeakMap();
281
316
  const shieldId = config.shieldId ?? readEnv(SHIELD_ID_ENV_VARS);
282
317
  validateShieldId(shieldId);
283
318
  this.config = {
@@ -305,6 +340,22 @@ class FullCourtDefense {
305
340
  this.failMode = config.failMode ?? (0, failMode_1.parseFailMode)(readEnv(failMode_1.FAIL_MODE_ENV_VARS)) ?? 'tiered';
306
341
  this.modeAtProtect = config.modeAtProtect ?? (0, failMode_1.parseModeAtProtect)(readEnv(failMode_1.MODE_AT_PROTECT_ENV_VARS));
307
342
  this.onDegrade = config.onDegrade;
343
+ this.decisionMode = config.decisionMode ?? parseDecisionMode(readEnv(DECISION_MODE_ENV_VARS)) ?? 'local';
344
+ const coldStartRaw = config.coldStartWaitMs ?? Number(readEnv(COLD_START_WAIT_ENV_VARS) ?? DEFAULT_COLD_START_WAIT_MS);
345
+ const coldStartWaitMs = Number.isFinite(coldStartRaw) ? Math.max(0, Math.min(coldStartRaw, 10000)) : DEFAULT_COLD_START_WAIT_MS;
346
+ this.coldStartDeadline = Date.now() + coldStartWaitMs;
347
+ this.records = new recordQueue_1.RecordQueue((bodies, gap) => this._sendRecordBatch(bodies, gap), {
348
+ // Records dropped because the upload could not keep up: the app hears it (once per 30 s), the next upload reports it.
349
+ onDrop: (info) => this.emitDegrade({
350
+ call: 'recordUpload',
351
+ 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)`,
352
+ breakerState: this.breakerState(),
353
+ failedClosed: false,
354
+ droppedRecords: info.dropped,
355
+ droppedFrom: info.from,
356
+ droppedTo: info.to,
357
+ }),
358
+ });
308
359
  this.breaker = config.circuitBreaker === false
309
360
  ? null
310
361
  : (0, circuitBreaker_1.getCircuitBreaker)(`${this.config.apiUrl}|${this.config.shieldId}`, config.circuitBreaker || undefined);
@@ -324,8 +375,132 @@ class FullCourtDefense {
324
375
  }
325
376
  });
326
377
  }
378
+ if (this.decisionMode === 'local')
379
+ this._startBundleRefresh();
327
380
  this._replaySpooledRecords();
328
381
  }
382
+ /**
383
+ * Local decisions: refresh the bundle every BUNDLE_REFRESH_MS in the background (stale-while-revalidate), one
384
+ * timer per shield, never keeping the process alive. A call never waits for it; a failed refresh keeps the
385
+ * last bundle (the policies a live answer gave) and the next tick tries again.
386
+ */
387
+ _startBundleRefresh() {
388
+ const key = this._modeCacheKey();
389
+ if (bundleRefreshTimers.has(key) || typeof setInterval !== 'function')
390
+ return;
391
+ const timer = setInterval(() => {
392
+ try {
393
+ const cached = modeCache.get(key);
394
+ if (cached?.inflight || typeof fetch !== 'function')
395
+ return;
396
+ const refresh = this._fetchShieldMode();
397
+ if (cached)
398
+ cached.inflight = refresh;
399
+ void refresh.then((fetched) => { this._applyFetchedMode(key, modeCache.get(key), fetched); }, () => { this._applyFetchedMode(key, modeCache.get(key), null); });
400
+ }
401
+ catch {
402
+ // never reaches the agent
403
+ }
404
+ }, BUNDLE_REFRESH_MS);
405
+ timer.unref?.();
406
+ bundleRefreshTimers.set(key, timer);
407
+ }
408
+ /**
409
+ * Wait (at most `timeoutMs`, default 3 s) for the shield's mode and policies, at START-UP, outside any tool call.
410
+ * Local decisions never wait inside a call: a call made before the first bundle arrives runs and is reported. An
411
+ * agent that must have its first call checked awaits this once after building the client (a Lambda handler during
412
+ * its init). Resolves true when the policies are here, false when FullCourtDefense did not answer in time. Never throws.
413
+ */
414
+ async ready(timeoutMs = 3000) {
415
+ try {
416
+ if (this.config.monitorMode === 'off' && this.decisionMode !== 'local')
417
+ return true;
418
+ const key = this._modeCacheKey();
419
+ const cached = modeCache.get(key);
420
+ if (cached && cached.fetchedAt > 0 && cached.confirmed)
421
+ return true;
422
+ if (typeof fetch !== 'function')
423
+ return false;
424
+ await settleWithin(this._firstLookup(key), timeoutMs);
425
+ return Boolean(modeCache.get(key)?.confirmed);
426
+ }
427
+ catch {
428
+ return false;
429
+ }
430
+ }
431
+ /** The bundle for a local decision, or undefined (none yet, or the backend serves no policies to decide from). */
432
+ _localBundle() {
433
+ return modeCache.get(this._modeCacheKey())?.bundle;
434
+ }
435
+ /**
436
+ * One batch of queued records (RecordQueue's sender): `POST /runtime/tool-calls` with the records and, when the queue dropped
437
+ * some, the gap. An older backend (404 / 405 with no runtime error code) has no such route: the records go one by one to
438
+ * `/runtime/tool-call` from then on, for the rest of the process. A record or two the backend could not write come back as
439
+ * `outage` (resent); a record it refused is dropped.
440
+ */
441
+ async _sendRecordBatch(bodies, gap) {
442
+ if (singleRecordApis.has(this.config.apiUrl))
443
+ return this._sendRecordsOneByOne(bodies);
444
+ 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));
445
+ if (result.success) {
446
+ const data = result.data ?? {};
447
+ const refused = new Set(Array.isArray(data.refused) ? data.refused : []);
448
+ const failed = new Set(Array.isArray(data.failed) ? data.failed : []);
449
+ return {
450
+ results: bodies.map((_, at) => (failed.has(at) ? 'outage' : refused.has(at) ? 'refused' : 'sent')),
451
+ gapAccepted: gap ? data.gapRecorded === true : undefined,
452
+ };
453
+ }
454
+ const status = typeof result.status === 'number' ? result.status : undefined;
455
+ // A route this backend does not have (no runtime error code on the answer): remembered, so this costs one request per process.
456
+ if ((status === 404 || status === 405) && !result.serverCode) {
457
+ singleRecordApis.add(this.config.apiUrl);
458
+ return this._sendRecordsOneByOne(bodies);
459
+ }
460
+ // One record that cannot be encoded, or a request too large: the single route says which record is the problem.
461
+ if (result.localEncodingError || status === 413)
462
+ return this._sendRecordsOneByOne(bodies);
463
+ if (status === undefined || status >= 500 || status === 408 || status === 429)
464
+ return 'outage';
465
+ return 'refused';
466
+ }
467
+ /** The older route: one record per request, a few at a time; after the first outage the rest of the batch waits (resent later). */
468
+ async _sendRecordsOneByOne(bodies) {
469
+ const results = new Array(bodies.length).fill('outage');
470
+ let next = 0;
471
+ let down = false;
472
+ const worker = async () => {
473
+ while (next < bodies.length && !down) {
474
+ const at = next++;
475
+ const result = await this._postAgentSecurity('/api/agent-security/runtime/tool-call', bodies[at], 'inflight');
476
+ if (result.success)
477
+ results[at] = 'sent';
478
+ else if (result.localEncodingError)
479
+ results[at] = 'refused';
480
+ else {
481
+ const status = typeof result.status === 'number' ? result.status : undefined;
482
+ if (status === undefined || status >= 500 || status === 408 || status === 429)
483
+ down = true;
484
+ else
485
+ results[at] = 'refused';
486
+ }
487
+ }
488
+ };
489
+ await Promise.all(Array.from({ length: Math.min(8, bodies.length) }, worker));
490
+ return { results, gapAccepted: false };
491
+ }
492
+ /** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
493
+ _enqueueRecord(body) {
494
+ // Every record has an id the backend keys on (runtime/tool-call-identity.ts): the provider's tool-call id, else one
495
+ // 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
496
+ // the first time holds ONE record, not one per attempt.
497
+ if (typeof body.toolCallId !== 'string' || !body.toolCallId) {
498
+ body = { ...body, toolCallId: `fcd-${(0, crypto_1.randomUUID)()}`, decisionSource: 'sdk' };
499
+ }
500
+ this.records.push(body);
501
+ liveClients.add(this);
502
+ installExitHooks();
503
+ }
329
504
  /** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
330
505
  _replaySpooledRecords() {
331
506
  const shieldId = this.config.shieldId;
@@ -362,11 +537,28 @@ class FullCourtDefense {
362
537
  at: entry.lastAt,
363
538
  });
364
539
  }
540
+ // Records dropped and not reported yet: the next process with this shield reports the gap.
541
+ const gap = this.records.takeGap();
542
+ if (gap)
543
+ out.push({ path: '/api/agent-security/runtime/tool-calls', body: { records: [], gap, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: gap.to });
544
+ // Records of locally decided calls not sent yet: the next process with this shield sends them.
545
+ for (const item of this.records.drain()) {
546
+ out.push({ path: '/api/agent-security/runtime/tool-call', body: { ...item.body, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: item.at });
547
+ }
365
548
  return out;
366
549
  }
367
- /** @internal Send the calls spooled while the API was down (called at `beforeExit`; the caller bounds the wait). */
550
+ /** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
368
551
  _flushForExit() {
369
- return this._flushSkippedChecks();
552
+ return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
553
+ }
554
+ /**
555
+ * How the background record upload is doing (observability for the app and the load tests): records waiting, sent,
556
+ * refused, dropped because the upload could not keep up (`dropped`; `unreported` is the part no accepted upload has told
557
+ * FullCourtDefense about yet), gaps the backend took, requests made, and whether records go in batches or one by one (an older backend).
558
+ */
559
+ recordStats() {
560
+ const q = this.records;
561
+ 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' };
370
562
  }
371
563
  /** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
372
564
  get identity() {
@@ -402,6 +594,10 @@ class FullCourtDefense {
402
594
  agentIdSource: input.agentIdSource ?? (callAgentId || callAgentName ? 'config' : this._identity.agentIdSource),
403
595
  agentInstanceId: input.agentInstanceId ?? this._identity.agentInstanceId,
404
596
  environment: input.environment ?? this._identity.environment,
597
+ ...(input.toolCallId && !input.attemptId ? { attemptId: input.toolCallId } : {}),
598
+ // Mixed SDK + local AI gateway: one action = one record by (agent, toolCallId), so a call with the provider's
599
+ // tool-call id says who sent it. `source` stays runtime_sdk (the backend reads an SDK agent from it).
600
+ ...(input.toolCallId ? { decisionSource: 'sdk' } : {}),
405
601
  };
406
602
  }
407
603
  // ── protect(): actions-first, one call ──
@@ -501,7 +697,27 @@ class FullCourtDefense {
501
697
  * A refused key or shield (HTTP 401 / 403 / 404) is not "unknown": it keeps its own rule.
502
698
  */
503
699
  async _resolveToolMode() {
504
- const mode = await this._resolveMode(this._mayRunBeforeModeKnown());
700
+ // Local decisions never wait for the network once the first bundle is here (owner order 2026-11-01). Without
701
+ // one, a call runs and its record follows the answer (allow + record + one warning, never stall), except for the
702
+ // bounded cold-start wait below.
703
+ let mode = await this._resolveMode(this._mayRunBeforeModeKnown() || this.decisionMode === 'local');
704
+ // Cold start (local decisions): while the first bundle is on its way, a call on a shield not recorded as Monitor
705
+ // waits for it, at most until the deadline set when the client was built. Never after: one bounded wait per
706
+ // process at most, and a hanging FullCourtDefense costs only the calls made in that first window.
707
+ if (mode.pending && this.decisionMode === 'local' && !this._mayRunBeforeModeKnown()) {
708
+ const left = this.coldStartDeadline - Date.now();
709
+ if (left > 0) {
710
+ let timer;
711
+ const settled = await Promise.race([
712
+ mode.pending.then((value) => value, () => undefined),
713
+ new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), left); }),
714
+ ]);
715
+ if (timer !== undefined)
716
+ clearTimeout(timer);
717
+ if (settled)
718
+ mode = { effective: settled.effective, confirmed: settled.confirmed, ...(settled.configError ? { configError: settled.configError } : {}) };
719
+ }
720
+ }
505
721
  if (mode.pending)
506
722
  return { ...mode, pending: mode.pending.then((settled) => this._adjustToolMode(settled)) };
507
723
  return this._adjustToolMode(mode);
@@ -584,10 +800,14 @@ class FullCourtDefense {
584
800
  if (cached)
585
801
  cached.inflight = undefined;
586
802
  if (fetched && 'mode' in fetched) {
587
- modeCache.set(key, { mode: fetched.mode, rules: fetched.rules, fetchedAt: Date.now(), ttlMs: MODE_CACHE_TTL_MS, confirmed: true });
588
- // The API answers again: send what was decided without a check meanwhile (the alert).
803
+ modeCache.set(key, {
804
+ mode: fetched.mode, rules: fetched.rules, fetchedAt: Date.now(), ttlMs: MODE_CACHE_TTL_MS, confirmed: true,
805
+ ...(fetched.bundle ? { bundle: fetched.bundle } : {}),
806
+ });
807
+ // The API answers again: send what was decided without a check meanwhile (the alert), and the queued records.
589
808
  if (this.skippedChecks.size > 0)
590
809
  void this._flushSkippedChecks();
810
+ this.records.resume();
591
811
  return resolved(fetched.mode, true);
592
812
  }
593
813
  if (fetched && 'configError' in fetched) {
@@ -601,6 +821,9 @@ class FullCourtDefense {
601
821
  modeCache.set(key, {
602
822
  mode, rules: knownMode ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS,
603
823
  confirmed: Boolean(knownMode), configError: fetched.configError,
824
+ // Owner decision 2026-11-15: a refused key never stops the agent. The policies a live answer gave earlier keep
825
+ // deciding (stale-while-error, like an outage); with none, the fail mode answers (_decideLocal).
826
+ ...(knownMode && cached?.bundle ? { bundle: cached.bundle } : {}),
604
827
  });
605
828
  return resolved(mode, Boolean(knownMode), fetched.configError);
606
829
  }
@@ -613,7 +836,11 @@ class FullCourtDefense {
613
836
  // a Monitor call is reported once the API answers, a Block call is spooled as before.
614
837
  const known = Boolean(cached && cached.confirmed && cached.fetchedAt > 0);
615
838
  const lastKnown = known && cached ? cached.mode : (this.modeAtProtect ?? 'block');
616
- modeCache.set(key, { mode: lastKnown, rules: known ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS, confirmed: known });
839
+ // Local decisions keep deciding from the last bundle a live answer gave (stale-while-error).
840
+ modeCache.set(key, {
841
+ mode: lastKnown, rules: known ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS, confirmed: known,
842
+ ...(known && cached?.bundle ? { bundle: cached.bundle } : {}),
843
+ });
617
844
  return resolved(lastKnown, known);
618
845
  }
619
846
  async _fetchShieldMode() {
@@ -622,21 +849,25 @@ class FullCourtDefense {
622
849
  const resp = await fetch(url, {
623
850
  method: 'GET',
624
851
  headers: this.config.shieldKey ? { 'x-shield-key': this.config.shieldKey } : {},
625
- signal: AbortSignal.timeout(MODE_FETCH_TIMEOUT_MS),
852
+ // Local decisions never wait for this request, so it may take longer than a lookup a call waits for.
853
+ signal: AbortSignal.timeout(this.decisionMode === 'local' ? BUNDLE_FETCH_TIMEOUT_MS : MODE_FETCH_TIMEOUT_MS),
626
854
  });
627
855
  if (!resp.ok) {
628
856
  // A wrong key or an unknown shield is not an outage: say so once, loudly (O4: a Monitor agent's
629
857
  // tools run and are reported, a Blocking agent's tools stop with the same explanation).
630
858
  if (resp.status === 401 || resp.status === 403 || resp.status === 404) {
631
- 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.');
859
+ this._reportConfigurationError(resp.status, 'read the shield mode', undefined, REFUSED_KEY_OUTCOME);
632
860
  return { configError: resp.status };
633
861
  }
634
862
  return null;
635
863
  }
636
864
  const data = await resp.json().catch(() => null);
637
865
  const mode = data?.data?.mode;
638
- if (mode === 'monitor' || mode === 'block' || mode === 'shadow')
639
- return { mode, rules: (0, failMode_1.sanitizeFailsafeRules)(data?.data?.agentFailsafeRules) };
866
+ if (mode === 'monitor' || mode === 'block' || mode === 'shadow') {
867
+ // A bundle without `actionPolicies` (a backend that serves none to an SDK) cannot decide locally: the server does.
868
+ const bundle = this.decisionMode === 'local' && Array.isArray(data?.data?.actionPolicies) ? (0, localDecision_1.prepareLocalBundle)(data?.data) : undefined;
869
+ return { mode, rules: (0, failMode_1.sanitizeFailsafeRules)(data?.data?.agentFailsafeRules), ...(bundle ? { bundle } : {}) };
870
+ }
640
871
  return null;
641
872
  }
642
873
  catch {
@@ -1145,6 +1376,19 @@ class FullCourtDefense {
1145
1376
  const argsProblem = (0, argsBounds_1.toolCallArgsProblem)(input);
1146
1377
  if (argsProblem)
1147
1378
  return this._argsProblemVerdict(input, argsProblem);
1379
+ // Local decisions (owner order 2026-11-01): from the bundle, in this process, no request. A manager approval
1380
+ // and a call the bundle cannot decide continue to the server check below.
1381
+ const local = this._decideLocal(input, mode);
1382
+ if (local) {
1383
+ if (local.record) {
1384
+ // guardToolCall writes ONE record after the tool ran (decision + how it ended); a direct check writes it now.
1385
+ if (this.deferredLocalRecords.has(rawInput))
1386
+ this.deferredLocalRecords.set(rawInput, local.record);
1387
+ else
1388
+ this._enqueueRecord(local.record);
1389
+ }
1390
+ return local.result;
1391
+ }
1148
1392
  const degrade = (reason) => {
1149
1393
  if (this.failMode)
1150
1394
  return this._degradeByFailMode(input, reason, this.failMode);
@@ -1185,6 +1429,7 @@ class FullCourtDefense {
1185
1429
  this.breaker?.recordSuccess(Date.now() - startedAt);
1186
1430
  if (this.skippedChecks.size > 0)
1187
1431
  void this._flushSkippedChecks();
1432
+ this.records.resume(); // the API answers: queued records go now, not after the back-off
1188
1433
  return result;
1189
1434
  }
1190
1435
  // The body could not be encoded (a value with a throwing toJSON): the call's own input, definite.
@@ -1196,6 +1441,13 @@ class FullCourtDefense {
1196
1441
  // gets an explicit error (guardToolCall throws it; the tool does not run). An API that classifies
1197
1442
  // its errors (G-04) may still call a 400 retryable (a server failure answered the way machines
1198
1443
  // expect): that one is an outage.
1444
+ if (isRefusedKeyStatus(result.status) && result.retryable !== true && result.category !== 'server') {
1445
+ // Owner decision 2026-11-15: a refused shield key or shield (401 / 403 / 404) is OUR side not working for this
1446
+ // agent, whatever the cause; it never stops the customer's tool. Said loudly once, then the fail mode answers
1447
+ // (tiered: the tool runs and is reported as "ran without a check" once a key works). No breaker failure.
1448
+ this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, REFUSED_KEY_OUTCOME, result.serverCode);
1449
+ return this._degradeByFailMode(input, `shield key or shield refused (HTTP ${result.status})`, this.failMode ?? 'tiered');
1450
+ }
1199
1451
  if ((0, errors_1.isDefiniteStatus)(result.status) && result.retryable !== true && result.category !== 'server') {
1200
1452
  const error = this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, undefined, result.serverCode);
1201
1453
  return {
@@ -1216,6 +1468,77 @@ class FullCourtDefense {
1216
1468
  }
1217
1469
  return result;
1218
1470
  }
1471
+ /**
1472
+ * A Block-mode call decided in this process from the bundle, or undefined when the server decides it (server
1473
+ * decision mode, a manager approval, a call the bundle cannot decide, a backend that serves no policies, a
1474
+ * refused key). With no bundle at all (FullCourtDefense never reached since this agent started), the call is
1475
+ * answered by the fail mode at once: it runs (only a never-allowed rule stops one), it is recorded, and one
1476
+ * warning says so. Never a request, never a wait.
1477
+ */
1478
+ _decideLocal(input, mode) {
1479
+ if (this.decisionMode !== 'local')
1480
+ return undefined;
1481
+ const bundle = this._localBundle();
1482
+ if (!bundle && mode.configError) {
1483
+ // The shield key or the shield is refused (401 / 403 / 404) and no policies were ever read: said loudly once,
1484
+ // and the fail mode answers (the tool runs unless FCD_FAIL_MODE=closed). Never a request, never a stop of ours.
1485
+ this._reportConfigurationError(mode.configError, 'read the shield policies', undefined, REFUSED_KEY_OUTCOME);
1486
+ return { result: this._degradeByFailMode(input, `shield key or shield refused (HTTP ${mode.configError})`, this.failMode ?? 'tiered') };
1487
+ }
1488
+ if (!bundle) {
1489
+ // A live answer came without policies (an older backend): the server decides, as before.
1490
+ if (modeCache.get(this._modeCacheKey())?.confirmed)
1491
+ return undefined;
1492
+ if (!this.warnedNoBundle) {
1493
+ this.warnedNoBundle = true;
1494
+ console.warn('[FullCourtDefense] No policy bundle yet (FullCourtDefense not reached since this agent started): tool calls run under the fail mode and are recorded; local decisions start with the first bundle.');
1495
+ }
1496
+ return { result: this._degradeByFailMode(input, 'no policy bundle yet', this.failMode ?? 'tiered') };
1497
+ }
1498
+ const decided = (0, localDecision_1.decideLocally)(bundle, input);
1499
+ if (decided.route === 'server' || decided.decision === 'approval')
1500
+ return undefined;
1501
+ const data = {
1502
+ allowed: decided.allowed,
1503
+ decision: decided.decision,
1504
+ operation: decided.operation,
1505
+ actionPolicy: decided.actionPolicy,
1506
+ analysis: 'sync',
1507
+ decidedBy: 'local',
1508
+ outcome: decided.outcome,
1509
+ };
1510
+ return { result: { success: true, data }, record: this._localRecordBody(input, data) };
1511
+ }
1512
+ /**
1513
+ * The record of a locally decided call, for the existing record endpoint (`POST /runtime/tool-call`): what was
1514
+ * decided and by which rule, the arguments as their summary (the server minimizes them as for every SDK record),
1515
+ * the provider's tool-call id (one action = one record when a local AI gateway also saw it), and how the tool
1516
+ * ended when it ran.
1517
+ */
1518
+ _localRecordBody(input, data, ended) {
1519
+ const { toolArgs, failClosed: _failClosed, ...rest } = input;
1520
+ void _failClosed;
1521
+ const policy = data.actionPolicy || {};
1522
+ const why = policy.reason || (data.decision === 'block' ? 'Blocked by policy' : 'No policy stops this call');
1523
+ const ran = ended ? (ended.outcome === 'failed' ? ` The tool ran and raised ${ended.errorType ?? 'an error'}.` : ' The tool ran.') : '';
1524
+ return {
1525
+ ...rest,
1526
+ argsSummary: input.argsSummary || toolArgs,
1527
+ operation: data.operation,
1528
+ decision: data.decision === 'block' ? 'block' : 'allow',
1529
+ reason: `${data.outcome === 'warn' ? 'Warn only: ' : ''}${why} (decided in the agent's process from the shield's policies).${ran}`.slice(0, 1000),
1530
+ ...(policy.policyId ? { policyId: policy.policyId } : {}),
1531
+ ...(policy.policyName ? { policyName: policy.policyName } : {}),
1532
+ ...(policy.matchedRule ? { matchedRule: policy.matchedRule } : {}),
1533
+ ...(policy.monitorMatches?.length ? { monitorMatches: policy.monitorMatches } : {}),
1534
+ decisionSource: 'sdk',
1535
+ decidedBy: 'sdk_local',
1536
+ ...(data.outcome ? { localOutcome: data.outcome } : {}),
1537
+ ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
1538
+ ...(ended ? { toolOutcome: ended.outcome, ...(ended.errorType ? { errorType: ended.errorType } : {}) } : {}),
1539
+ occurredAt: new Date().toISOString(),
1540
+ };
1541
+ }
1219
1542
  /**
1220
1543
  * The record of a call that runs in Monitor (it never waits for it):
1221
1544
  * - the API refused the key or shield (O4): the call runs; its report goes to the API anyway, where
@@ -1267,6 +1590,18 @@ class FullCourtDefense {
1267
1590
  _sendMonitorRecord(input) {
1268
1591
  const problem = (0, argsBounds_1.toolCallArgsProblem)(input);
1269
1592
  const { toolArgs, ...rest } = input;
1593
+ if (this.decisionMode === 'local') {
1594
+ // Local decisions: the Monitor record joins the background batches (the server still evaluates its would-have).
1595
+ this._enqueueRecord({
1596
+ ...rest,
1597
+ decision: input.decision || 'allow',
1598
+ reason: input.reason || 'monitor_mode_async',
1599
+ argsSummary: problem ? (0, argsBounds_1.toolArgsProblemSummary)(problem) : (input.argsSummary || toolArgs),
1600
+ decisionSource: 'sdk',
1601
+ ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
1602
+ });
1603
+ return Promise.resolve();
1604
+ }
1270
1605
  return this.recordToolCall({
1271
1606
  ...rest,
1272
1607
  decision: input.decision || 'allow',
@@ -1420,8 +1755,38 @@ class FullCourtDefense {
1420
1755
  }
1421
1756
  return result;
1422
1757
  }
1758
+ localGate() {
1759
+ return (this.localGateClient ?? (this.localGateClient = typeof process !== 'undefined' ? (0, localGate_1.createTrustedLocalGate)(process.env) : localGate_1.NO_GATE));
1760
+ }
1761
+ /** What the gate said about a call it did not allow: the error the agent code receives (the gate wrote the record). */
1762
+ async _localGateStop(input, answer, action, options) {
1763
+ const approval = answer.decision === 'approval';
1764
+ const reason = (answer.message || '').trim()
1765
+ || (approval ? `"${input.toolName}" needs a manager's approval and was sent to one.` : `Tool call blocked`);
1766
+ const hint = approval && answer.request && !reason.includes(answer.request) ? ` (request ${answer.request})` : '';
1767
+ if (approval && answer.request && options.approvalMode === 'wait') {
1768
+ await this._waitForApproval(answer.request, options);
1769
+ return action();
1770
+ }
1771
+ const message = `FullCourtDefense blocked tool call "${input.toolName}": ${reason}${hint}`;
1772
+ throw options.onBlocked
1773
+ ? options.onBlocked(message)
1774
+ : new errors_1.ToolCallBlocked(message, {
1775
+ toolName: input.toolName, decision: approval ? 'approval' : 'block', reason, outcome: approval ? 'approval' : 'block',
1776
+ code: approval ? 'FCD_APPROVAL_REQUIRED' : 'FCD_BLOCKED',
1777
+ ...(answer.ruleId ? { rule: { id: answer.ruleId } } : {}), approvalActionId: answer.request, degraded: false,
1778
+ });
1779
+ }
1423
1780
  async guardToolCall(rawInput, action, options = {}) {
1424
1781
  const input = this.withIdentity(rawInput);
1782
+ // A wrapped container's own gate decides first, from the signed bundle it holds (no request on the call; Monitor is one
1783
+ // local acknowledgement and never blocks). It writes the record. null: absent or unavailable, the paths below decide.
1784
+ const local = this.localGate();
1785
+ if (local !== localGate_1.NO_GATE) {
1786
+ const answer = await local.decide({ toolName: input.toolName, toolArgs: (input.toolArgs || {}), sessionId: input.sessionId, framework: input.framework });
1787
+ if (answer)
1788
+ return answer.decision === 'allow' ? action() : this._localGateStop(input, answer, action, options);
1789
+ }
1425
1790
  // Monitor mode: run the action immediately — no preflight wait, no approval
1426
1791
  // gate. The tool call is recorded fire-and-forget for console visibility.
1427
1792
  const mode = await this._resolveToolMode();
@@ -1442,10 +1807,24 @@ class FullCourtDefense {
1442
1807
  finally {
1443
1808
  // Short-lived hosts (Lambda) freeze when the handler returns: the record, and a report of
1444
1809
  // calls spooled while the API was down (started when the mode lookup answered), finish first.
1445
- await settleWithin(Promise.all([recording, this.skippedFlush]), RECORD_FLUSH_MAX_MS);
1810
+ await settleWithin(Promise.all([recording, this.skippedFlush, this.records.flush()]), RECORD_FLUSH_MAX_MS);
1446
1811
  }
1447
1812
  }
1448
- const preflight = await this.checkToolCall(input);
1813
+ // A local decision's record is written once, after the tool ran (decision + how it ended).
1814
+ this.deferredLocalRecords.set(input, null);
1815
+ let preflight;
1816
+ try {
1817
+ preflight = await this.checkToolCall(input);
1818
+ }
1819
+ catch (error) {
1820
+ this.deferredLocalRecords.delete(input);
1821
+ throw error;
1822
+ }
1823
+ const localRecord = this.deferredLocalRecords.get(input) ?? undefined;
1824
+ this.deferredLocalRecords.delete(input);
1825
+ if (localRecord && preflight.data?.decidedBy === 'local') {
1826
+ return this._runLocallyDecided(input, preflight.data, action, options);
1827
+ }
1449
1828
  if (!preflight.success) {
1450
1829
  // `code` is set only when checkToolCall classified the answer as definite (a 4xx, not an outage).
1451
1830
  if (preflight.code && (0, errors_1.isDefiniteStatus)(preflight.status)) {
@@ -1532,6 +1911,40 @@ class FullCourtDefense {
1532
1911
  await settleWithin(this.skippedFlush, RECORD_FLUSH_MAX_MS);
1533
1912
  return result;
1534
1913
  }
1914
+ /**
1915
+ * Run (or stop) a call decided locally, and write its ONE record afterwards in the background: a stopped call
1916
+ * at once, an allowed call with how it ended (`executed`, or `failed` with the error's type name only).
1917
+ */
1918
+ async _runLocallyDecided(input, data, action, options) {
1919
+ const finish = async (record) => {
1920
+ this._enqueueRecord(record);
1921
+ // Short-lived hosts (Lambda) freeze when the handler returns: the record goes first, capped.
1922
+ if (options.awaitRecord)
1923
+ await settleWithin(this.records.flush(), RECORD_FLUSH_MAX_MS);
1924
+ };
1925
+ if (!data.allowed) {
1926
+ await finish(this._localRecordBody(input, data));
1927
+ const policy = data.actionPolicy;
1928
+ const reason = policy?.reason || `Tool call ${data.decision}`;
1929
+ const message = `FullCourtDefense blocked tool call "${input.toolName}": ${reason}`;
1930
+ const rule = policy && (policy.matchedRule || policy.policyId || policy.policyName)
1931
+ ? { ...(policy.matchedRule || policy.policyId ? { id: String(policy.matchedRule || policy.policyId) } : {}), ...(policy.policyName ? { name: String(policy.policyName) } : {}) }
1932
+ : undefined;
1933
+ throw options.onBlocked
1934
+ ? options.onBlocked(message)
1935
+ : new errors_1.ToolCallBlocked(message, { toolName: input.toolName, decision: data.decision, reason, outcome: 'block', code: 'FCD_BLOCKED', rule, degraded: false });
1936
+ }
1937
+ let result;
1938
+ try {
1939
+ result = await action();
1940
+ }
1941
+ catch (error) {
1942
+ await finish(this._localRecordBody(input, data, { outcome: 'failed', errorType: errorTypeName(error) }));
1943
+ throw error;
1944
+ }
1945
+ await finish(this._localRecordBody(input, data, { outcome: 'executed' }));
1946
+ return result;
1947
+ }
1535
1948
  /**
1536
1949
  * How an allowed call ended. When the check returned the gate record's `actionId` (backends with
1537
1950
  * the G-11 outcome report), the outcome goes ON that record: no second record, and a failure