fullcourtdefense 2.1.2 → 2.2.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/README.md +21 -0
- package/dist/anthropic.js +2 -0
- package/dist/client.d.ts +50 -1
- package/dist/client.js +290 -11
- package/dist/localDecision.d.ts +100 -0
- package/dist/localDecision.js +246 -0
- package/dist/localSafety.d.ts +48 -0
- package/dist/localSafety.js +220 -0
- package/dist/policy/acorn.js +6365 -0
- package/dist/policy/actionPolicyEngine.d.ts +427 -0
- package/dist/policy/actionPolicyEngine.js +6481 -0
- package/dist/policy/detectionData.d.ts +21 -0
- package/dist/policy/detectionData.js +71 -0
- package/dist/policy/detectorRuntime.d.ts +27 -0
- package/dist/policy/detectorRuntime.js +58 -0
- package/dist/policy/deterministicGuard.d.ts +406 -0
- package/dist/policy/deterministicGuard.js +6651 -0
- package/dist/protect.d.ts +6 -0
- package/dist/protect.js +18 -0
- package/dist/recordQueue.d.ts +53 -0
- package/dist/recordQueue.js +132 -0
- package/dist/types.d.ts +47 -0
- package/package.json +16 -10
package/README.md
CHANGED
|
@@ -748,6 +748,27 @@ the console:
|
|
|
748
748
|
The mode is cached for 60s, so flipping monitor → block in the console takes
|
|
749
749
|
effect within a minute without redeploying your agent.
|
|
750
750
|
|
|
751
|
+
### Local decisions (default): no request per tool call
|
|
752
|
+
|
|
753
|
+
With `decisionMode: 'local'` (the default; env `FCD_DECISION_MODE`) a Block-mode tool call is decided **in your process**
|
|
754
|
+
from the shield's policies, with the same policy engine and the same answer the API gives. The SDK fetches the policies
|
|
755
|
+
when the client is built and refreshes them every 60 s in the background; a tool call never waits for that.
|
|
756
|
+
|
|
757
|
+
- The call's record (what was decided, which rule, how the tool ended, the provider's tool-call id) is sent afterwards,
|
|
758
|
+
in background batches. If FullCourtDefense is down the records wait in memory (bounded) and are sent once it is back;
|
|
759
|
+
at exit they are flushed briefly or kept in the local spool for the next run.
|
|
760
|
+
- The built-in safety rules (command, file and web tools) are decided locally too, with the rules FullCourtDefense
|
|
761
|
+
serves in the same bundle. Only a call that needs a **manager's approval** goes to FullCourtDefense while it runs, plus
|
|
762
|
+
the rare call the bundle cannot decide: a policy that reads the agent's recorded history, a suspended shield.
|
|
763
|
+
- Cold start: a Block-mode call made in the first 1.5 s after the client was built waits for the first policies
|
|
764
|
+
(`coldStartWaitMs`, env `FCD_COLD_START_WAIT_MS`; `0` = never wait), so a short-lived agent's first call is checked.
|
|
765
|
+
After that, or if FullCourtDefense cannot be reached, a call with no policies runs, is recorded, and one warning says
|
|
766
|
+
so: the agent is never stalled. `await fcd.ready()` waits for the policies once at start-up instead.
|
|
767
|
+
- `decisionMode: 'server'` (or `FCD_DECISION_MODE=server`) restores a check request per call. FullCourtDefense can also
|
|
768
|
+
switch local decisions off for every agent from the server.
|
|
769
|
+
- Pass the model's tool-call id as `toolCallId` (`protect()` and `anthropicToolResults()` do it for Vercel AI, LangChain
|
|
770
|
+
and Anthropic): when a local AI gateway also sees the same call, one action stays one record.
|
|
771
|
+
|
|
751
772
|
### Tiered by default in Enforce, never blocking in Monitor
|
|
752
773
|
|
|
753
774
|
A tool call is answered quickly in every case: allow, or a typed refusal. Nothing waits for a manager inside the call
|
package/dist/anthropic.js
CHANGED
|
@@ -42,6 +42,8 @@ async function anthropicToolResults(fcd, content, handlers, options = {}) {
|
|
|
42
42
|
toolName: block.name,
|
|
43
43
|
toolArgs: input,
|
|
44
44
|
framework: 'anthropic',
|
|
45
|
+
// The tool_use id: one action = one record when a local AI gateway also saw this call.
|
|
46
|
+
...(typeof block.id === 'string' && block.id ? { toolCallId: block.id } : {}),
|
|
45
47
|
agentName: options.agentName,
|
|
46
48
|
sessionId: options.sessionId,
|
|
47
49
|
operation: options.operation,
|
package/dist/client.d.ts
CHANGED
|
@@ -52,16 +52,45 @@ export declare class FullCourtDefense {
|
|
|
52
52
|
/** O4: a Monitor call ran with a refused key or shield and stderr said so (once, without onDegrade). */
|
|
53
53
|
private warnedMonitorConfigError;
|
|
54
54
|
private onDegrade?;
|
|
55
|
+
/** Where Block-mode calls are decided (`local` = from the bundle, in this process). */
|
|
56
|
+
private readonly decisionMode;
|
|
57
|
+
/** Local decisions: until this time (ms epoch) a Block-mode call may wait for the first bundle; never after. */
|
|
58
|
+
private readonly coldStartDeadline;
|
|
59
|
+
/** Records of locally decided calls (and Monitor records in local mode), sent in background batches. */
|
|
60
|
+
private readonly records;
|
|
61
|
+
/** One warning when a Block-mode call ran before any policy bundle was available. */
|
|
62
|
+
private warnedNoBundle;
|
|
63
|
+
/** guardToolCall's calls: the local decision's record is handed back here and written after the tool ran. */
|
|
64
|
+
private readonly deferredLocalRecords;
|
|
55
65
|
private breaker;
|
|
56
66
|
private readonly _identity;
|
|
57
67
|
private readonly _features;
|
|
58
68
|
chat: ChatNamespace;
|
|
59
69
|
constructor(config?: FullCourtDefenseConfig);
|
|
70
|
+
/**
|
|
71
|
+
* Local decisions: refresh the bundle every BUNDLE_REFRESH_MS in the background (stale-while-revalidate), one
|
|
72
|
+
* timer per shield, never keeping the process alive. A call never waits for it; a failed refresh keeps the
|
|
73
|
+
* last bundle (the policies a live answer gave) and the next tick tries again.
|
|
74
|
+
*/
|
|
75
|
+
private _startBundleRefresh;
|
|
76
|
+
/**
|
|
77
|
+
* Wait (at most `timeoutMs`, default 3 s) for the shield's mode and policies, at START-UP, outside any tool call.
|
|
78
|
+
* Local decisions never wait inside a call: a call made before the first bundle arrives runs and is reported. An
|
|
79
|
+
* agent that must have its first call checked awaits this once after building the client (a Lambda handler during
|
|
80
|
+
* its init). Resolves true when the policies are here, false when FullCourtDefense did not answer in time. Never throws.
|
|
81
|
+
*/
|
|
82
|
+
ready(timeoutMs?: number): Promise<boolean>;
|
|
83
|
+
/** The bundle for a local decision, or undefined (none yet, or the backend serves no policies to decide from). */
|
|
84
|
+
private _localBundle;
|
|
85
|
+
/** One queued record to the record endpoint (RecordQueue's sender). */
|
|
86
|
+
private _sendQueuedRecord;
|
|
87
|
+
/** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
|
|
88
|
+
private _enqueueRecord;
|
|
60
89
|
/** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
|
|
61
90
|
private _replaySpooledRecords;
|
|
62
91
|
/** @internal Calls held in memory, as request bodies for the local spool (called at exit). */
|
|
63
92
|
_takeUnsentForSpool(): SpooledRecord[];
|
|
64
|
-
/** @internal Send the calls spooled while the API was down (called at `beforeExit`; the caller bounds the wait). */
|
|
93
|
+
/** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
|
|
65
94
|
_flushForExit(): Promise<void>;
|
|
66
95
|
/** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
|
|
67
96
|
get identity(): Readonly<RuntimeIdentity>;
|
|
@@ -199,6 +228,21 @@ export declare class FullCourtDefense {
|
|
|
199
228
|
registerAgent(input: AgentRegistrationInput): Promise<AgentSecurityApiResult>;
|
|
200
229
|
recordToolCall(rawInput: AgentToolCallInput): Promise<AgentSecurityApiResult>;
|
|
201
230
|
checkToolCall(rawInput: AgentToolCallInput): Promise<AgentSecurityApiResult<AgentToolCallCheckResult>>;
|
|
231
|
+
/**
|
|
232
|
+
* A Block-mode call decided in this process from the bundle, or undefined when the server decides it (server
|
|
233
|
+
* decision mode, a manager approval, a call the bundle cannot decide, a backend that serves no policies, a
|
|
234
|
+
* refused key). With no bundle at all (FullCourtDefense never reached since this agent started), the call is
|
|
235
|
+
* answered by the fail mode at once: it runs (only a never-allowed rule stops one), it is recorded, and one
|
|
236
|
+
* warning says so. Never a request, never a wait.
|
|
237
|
+
*/
|
|
238
|
+
private _decideLocal;
|
|
239
|
+
/**
|
|
240
|
+
* The record of a locally decided call, for the existing record endpoint (`POST /runtime/tool-call`): what was
|
|
241
|
+
* decided and by which rule, the arguments as their summary (the server minimizes them as for every SDK record),
|
|
242
|
+
* the provider's tool-call id (one action = one record when a local AI gateway also saw it), and how the tool
|
|
243
|
+
* ended when it ran.
|
|
244
|
+
*/
|
|
245
|
+
private _localRecordBody;
|
|
202
246
|
/**
|
|
203
247
|
* The record of a call that runs in Monitor (it never waits for it):
|
|
204
248
|
* - the API refused the key or shield (O4): the call runs; its report goes to the API anyway, where
|
|
@@ -233,6 +277,11 @@ export declare class FullCourtDefense {
|
|
|
233
277
|
private _degradeByFailMode;
|
|
234
278
|
checkContext(input: AgentContextSecurityInput): Promise<AgentSecurityApiResult<AgentContextSecurityResult>>;
|
|
235
279
|
guardToolCall<T>(rawInput: AgentToolCallInput, action: () => Promise<T>, options?: GuardToolCallOptions): Promise<T>;
|
|
280
|
+
/**
|
|
281
|
+
* Run (or stop) a call decided locally, and write its ONE record afterwards in the background: a stopped call
|
|
282
|
+
* at once, an allowed call with how it ended (`executed`, or `failed` with the error's type name only).
|
|
283
|
+
*/
|
|
284
|
+
private _runLocallyDecided;
|
|
236
285
|
/**
|
|
237
286
|
* How an allowed call ended. When the check returned the gate record's `actionId` (backends with
|
|
238
287
|
* the G-11 outcome report), the outcome goes ON that record: no second record, and a failure
|
package/dist/client.js
CHANGED
|
@@ -11,6 +11,8 @@ const identity_1 = require("./identity");
|
|
|
11
11
|
const errors_1 = require("./errors");
|
|
12
12
|
const recordSpool_1 = require("./recordSpool");
|
|
13
13
|
const argsBounds_1 = require("./argsBounds");
|
|
14
|
+
const localDecision_1 = require("./localDecision");
|
|
15
|
+
const recordQueue_1 = require("./recordQueue");
|
|
14
16
|
const DEFAULT_API_URL = 'https://api.fullcourtdefense.ai';
|
|
15
17
|
const SHIELD_ID_ENV_VARS = ['FCD_SHIELD_ID', 'FULLCOURTDEFENSE_SHIELD_ID', 'AGENTGUARD_SHIELD_ID'];
|
|
16
18
|
const SHIELD_KEY_ENV_VARS = ['FCD_SHIELD_KEY', 'FULLCOURTDEFENSE_SHIELD_KEY', 'AGENTGUARD_SHIELD_KEY'];
|
|
@@ -19,6 +21,14 @@ const API_KEY_ENV_VARS = ['FCD_API_KEY', 'FULLCOURTDEFENSE_API_KEY', 'BOTGUARD_A
|
|
|
19
21
|
const AGENT_INSTANCE_ID_ENV_VARS = ['FCD_AGENT_INSTANCE_ID', 'FULLCOURTDEFENSE_AGENT_INSTANCE_ID'];
|
|
20
22
|
const ENVIRONMENT_ENV_VARS = ['FCD_ENVIRONMENT', 'FULLCOURTDEFENSE_ENVIRONMENT', 'NODE_ENV'];
|
|
21
23
|
const TEXT_SCAN_ENV_VARS = ['FCD_TEXT_SCAN', 'FULLCOURTDEFENSE_TEXT_SCAN'];
|
|
24
|
+
const DECISION_MODE_ENV_VARS = ['FCD_DECISION_MODE', 'FULLCOURTDEFENSE_DECISION_MODE'];
|
|
25
|
+
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
|
+
function parseDecisionMode(raw) {
|
|
29
|
+
const value = (raw || '').trim().toLowerCase();
|
|
30
|
+
return value === 'local' || value === 'server' ? value : undefined;
|
|
31
|
+
}
|
|
22
32
|
function readEnv(names) {
|
|
23
33
|
const env = globalThis.process?.env;
|
|
24
34
|
if (!env)
|
|
@@ -147,11 +157,19 @@ const MODE_FETCH_TIMEOUT_MS = 1500;
|
|
|
147
157
|
// After a failed mode lookup, don't retry for this window — avoids adding the
|
|
148
158
|
// lookup timeout to every call while the backend is down.
|
|
149
159
|
const MODE_FAILURE_RETRY_MS = 5000;
|
|
160
|
+
/** How often local decisions refresh the bundle in the background (never on a tool call's path). */
|
|
161
|
+
const BUNDLE_REFRESH_MS = 60000;
|
|
162
|
+
/** A background bundle fetch may take longer than a hot-path lookup: nothing waits for it. */
|
|
163
|
+
const BUNDLE_FETCH_TIMEOUT_MS = 5000;
|
|
164
|
+
const bundleRefreshTimers = new Map();
|
|
150
165
|
const modeCache = new Map();
|
|
151
166
|
/** Test hook — clears the module-level shield mode cache. */
|
|
152
167
|
function _clearShieldModeCache() {
|
|
153
168
|
modeCache.clear();
|
|
154
169
|
replayedShields.clear();
|
|
170
|
+
for (const timer of bundleRefreshTimers.values())
|
|
171
|
+
clearInterval(timer);
|
|
172
|
+
bundleRefreshTimers.clear();
|
|
155
173
|
}
|
|
156
174
|
// Built-in high-risk operations/tools that fail CLOSED when the backend is
|
|
157
175
|
// unreachable in block mode. Irreversible/high-impact actions must never
|
|
@@ -278,6 +296,10 @@ class FullCourtDefense {
|
|
|
278
296
|
this.reportedConfigErrors = new Set();
|
|
279
297
|
/** O4: a Monitor call ran with a refused key or shield and stderr said so (once, without onDegrade). */
|
|
280
298
|
this.warnedMonitorConfigError = false;
|
|
299
|
+
/** One warning when a Block-mode call ran before any policy bundle was available. */
|
|
300
|
+
this.warnedNoBundle = false;
|
|
301
|
+
/** guardToolCall's calls: the local decision's record is handed back here and written after the tool ran. */
|
|
302
|
+
this.deferredLocalRecords = new WeakMap();
|
|
281
303
|
const shieldId = config.shieldId ?? readEnv(SHIELD_ID_ENV_VARS);
|
|
282
304
|
validateShieldId(shieldId);
|
|
283
305
|
this.config = {
|
|
@@ -305,6 +327,11 @@ class FullCourtDefense {
|
|
|
305
327
|
this.failMode = config.failMode ?? (0, failMode_1.parseFailMode)(readEnv(failMode_1.FAIL_MODE_ENV_VARS)) ?? 'tiered';
|
|
306
328
|
this.modeAtProtect = config.modeAtProtect ?? (0, failMode_1.parseModeAtProtect)(readEnv(failMode_1.MODE_AT_PROTECT_ENV_VARS));
|
|
307
329
|
this.onDegrade = config.onDegrade;
|
|
330
|
+
this.decisionMode = config.decisionMode ?? parseDecisionMode(readEnv(DECISION_MODE_ENV_VARS)) ?? 'local';
|
|
331
|
+
const coldStartRaw = config.coldStartWaitMs ?? Number(readEnv(COLD_START_WAIT_ENV_VARS) ?? DEFAULT_COLD_START_WAIT_MS);
|
|
332
|
+
const coldStartWaitMs = Number.isFinite(coldStartRaw) ? Math.max(0, Math.min(coldStartRaw, 10000)) : DEFAULT_COLD_START_WAIT_MS;
|
|
333
|
+
this.coldStartDeadline = Date.now() + coldStartWaitMs;
|
|
334
|
+
this.records = new recordQueue_1.RecordQueue((body) => this._sendQueuedRecord(body));
|
|
308
335
|
this.breaker = config.circuitBreaker === false
|
|
309
336
|
? null
|
|
310
337
|
: (0, circuitBreaker_1.getCircuitBreaker)(`${this.config.apiUrl}|${this.config.shieldId}`, config.circuitBreaker || undefined);
|
|
@@ -324,8 +351,81 @@ class FullCourtDefense {
|
|
|
324
351
|
}
|
|
325
352
|
});
|
|
326
353
|
}
|
|
354
|
+
if (this.decisionMode === 'local')
|
|
355
|
+
this._startBundleRefresh();
|
|
327
356
|
this._replaySpooledRecords();
|
|
328
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* Local decisions: refresh the bundle every BUNDLE_REFRESH_MS in the background (stale-while-revalidate), one
|
|
360
|
+
* timer per shield, never keeping the process alive. A call never waits for it; a failed refresh keeps the
|
|
361
|
+
* last bundle (the policies a live answer gave) and the next tick tries again.
|
|
362
|
+
*/
|
|
363
|
+
_startBundleRefresh() {
|
|
364
|
+
const key = this._modeCacheKey();
|
|
365
|
+
if (bundleRefreshTimers.has(key) || typeof setInterval !== 'function')
|
|
366
|
+
return;
|
|
367
|
+
const timer = setInterval(() => {
|
|
368
|
+
try {
|
|
369
|
+
const cached = modeCache.get(key);
|
|
370
|
+
if (cached?.inflight || typeof fetch !== 'function')
|
|
371
|
+
return;
|
|
372
|
+
const refresh = this._fetchShieldMode();
|
|
373
|
+
if (cached)
|
|
374
|
+
cached.inflight = refresh;
|
|
375
|
+
void refresh.then((fetched) => { this._applyFetchedMode(key, modeCache.get(key), fetched); }, () => { this._applyFetchedMode(key, modeCache.get(key), null); });
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
// never reaches the agent
|
|
379
|
+
}
|
|
380
|
+
}, BUNDLE_REFRESH_MS);
|
|
381
|
+
timer.unref?.();
|
|
382
|
+
bundleRefreshTimers.set(key, timer);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Wait (at most `timeoutMs`, default 3 s) for the shield's mode and policies, at START-UP, outside any tool call.
|
|
386
|
+
* Local decisions never wait inside a call: a call made before the first bundle arrives runs and is reported. An
|
|
387
|
+
* agent that must have its first call checked awaits this once after building the client (a Lambda handler during
|
|
388
|
+
* its init). Resolves true when the policies are here, false when FullCourtDefense did not answer in time. Never throws.
|
|
389
|
+
*/
|
|
390
|
+
async ready(timeoutMs = 3000) {
|
|
391
|
+
try {
|
|
392
|
+
if (this.config.monitorMode === 'off' && this.decisionMode !== 'local')
|
|
393
|
+
return true;
|
|
394
|
+
const key = this._modeCacheKey();
|
|
395
|
+
const cached = modeCache.get(key);
|
|
396
|
+
if (cached && cached.fetchedAt > 0 && cached.confirmed)
|
|
397
|
+
return true;
|
|
398
|
+
if (typeof fetch !== 'function')
|
|
399
|
+
return false;
|
|
400
|
+
await settleWithin(this._firstLookup(key), timeoutMs);
|
|
401
|
+
return Boolean(modeCache.get(key)?.confirmed);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/** The bundle for a local decision, or undefined (none yet, or the backend serves no policies to decide from). */
|
|
408
|
+
_localBundle() {
|
|
409
|
+
return modeCache.get(this._modeCacheKey())?.bundle;
|
|
410
|
+
}
|
|
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';
|
|
418
|
+
const status = typeof result.status === 'number' ? result.status : undefined;
|
|
419
|
+
if (status === undefined || status >= 500 || status === 408 || status === 429)
|
|
420
|
+
return 'outage';
|
|
421
|
+
return 'refused';
|
|
422
|
+
}
|
|
423
|
+
/** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
|
|
424
|
+
_enqueueRecord(body) {
|
|
425
|
+
this.records.push(body);
|
|
426
|
+
liveClients.add(this);
|
|
427
|
+
installExitHooks();
|
|
428
|
+
}
|
|
329
429
|
/** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
|
|
330
430
|
_replaySpooledRecords() {
|
|
331
431
|
const shieldId = this.config.shieldId;
|
|
@@ -362,11 +462,15 @@ class FullCourtDefense {
|
|
|
362
462
|
at: entry.lastAt,
|
|
363
463
|
});
|
|
364
464
|
}
|
|
465
|
+
// Records of locally decided calls not sent yet: the next process with this shield sends them.
|
|
466
|
+
for (const item of this.records.drain()) {
|
|
467
|
+
out.push({ path: '/api/agent-security/runtime/tool-call', body: { ...item.body, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: item.at });
|
|
468
|
+
}
|
|
365
469
|
return out;
|
|
366
470
|
}
|
|
367
|
-
/** @internal Send the calls spooled while the API was down (called at `beforeExit`; the caller bounds the wait). */
|
|
471
|
+
/** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
|
|
368
472
|
_flushForExit() {
|
|
369
|
-
return this._flushSkippedChecks();
|
|
473
|
+
return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
|
|
370
474
|
}
|
|
371
475
|
/** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
|
|
372
476
|
get identity() {
|
|
@@ -402,6 +506,10 @@ class FullCourtDefense {
|
|
|
402
506
|
agentIdSource: input.agentIdSource ?? (callAgentId || callAgentName ? 'config' : this._identity.agentIdSource),
|
|
403
507
|
agentInstanceId: input.agentInstanceId ?? this._identity.agentInstanceId,
|
|
404
508
|
environment: input.environment ?? this._identity.environment,
|
|
509
|
+
...(input.toolCallId && !input.attemptId ? { attemptId: input.toolCallId } : {}),
|
|
510
|
+
// Mixed SDK + local AI gateway: one action = one record by (agent, toolCallId), so a call with the provider's
|
|
511
|
+
// tool-call id says who sent it. `source` stays runtime_sdk (the backend reads an SDK agent from it).
|
|
512
|
+
...(input.toolCallId ? { decisionSource: 'sdk' } : {}),
|
|
405
513
|
};
|
|
406
514
|
}
|
|
407
515
|
// ── protect(): actions-first, one call ──
|
|
@@ -501,7 +609,27 @@ class FullCourtDefense {
|
|
|
501
609
|
* A refused key or shield (HTTP 401 / 403 / 404) is not "unknown": it keeps its own rule.
|
|
502
610
|
*/
|
|
503
611
|
async _resolveToolMode() {
|
|
504
|
-
|
|
612
|
+
// Local decisions never wait for the network once the first bundle is here (owner order 2026-11-01). Without
|
|
613
|
+
// one, a call runs and its record follows the answer (allow + record + one warning, never stall), except for the
|
|
614
|
+
// bounded cold-start wait below.
|
|
615
|
+
let mode = await this._resolveMode(this._mayRunBeforeModeKnown() || this.decisionMode === 'local');
|
|
616
|
+
// Cold start (local decisions): while the first bundle is on its way, a call on a shield not recorded as Monitor
|
|
617
|
+
// waits for it, at most until the deadline set when the client was built. Never after: one bounded wait per
|
|
618
|
+
// process at most, and a hanging FullCourtDefense costs only the calls made in that first window.
|
|
619
|
+
if (mode.pending && this.decisionMode === 'local' && !this._mayRunBeforeModeKnown()) {
|
|
620
|
+
const left = this.coldStartDeadline - Date.now();
|
|
621
|
+
if (left > 0) {
|
|
622
|
+
let timer;
|
|
623
|
+
const settled = await Promise.race([
|
|
624
|
+
mode.pending.then((value) => value, () => undefined),
|
|
625
|
+
new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), left); }),
|
|
626
|
+
]);
|
|
627
|
+
if (timer !== undefined)
|
|
628
|
+
clearTimeout(timer);
|
|
629
|
+
if (settled)
|
|
630
|
+
mode = { effective: settled.effective, confirmed: settled.confirmed, ...(settled.configError ? { configError: settled.configError } : {}) };
|
|
631
|
+
}
|
|
632
|
+
}
|
|
505
633
|
if (mode.pending)
|
|
506
634
|
return { ...mode, pending: mode.pending.then((settled) => this._adjustToolMode(settled)) };
|
|
507
635
|
return this._adjustToolMode(mode);
|
|
@@ -584,10 +712,14 @@ class FullCourtDefense {
|
|
|
584
712
|
if (cached)
|
|
585
713
|
cached.inflight = undefined;
|
|
586
714
|
if (fetched && 'mode' in fetched) {
|
|
587
|
-
modeCache.set(key, {
|
|
588
|
-
|
|
715
|
+
modeCache.set(key, {
|
|
716
|
+
mode: fetched.mode, rules: fetched.rules, fetchedAt: Date.now(), ttlMs: MODE_CACHE_TTL_MS, confirmed: true,
|
|
717
|
+
...(fetched.bundle ? { bundle: fetched.bundle } : {}),
|
|
718
|
+
});
|
|
719
|
+
// The API answers again: send what was decided without a check meanwhile (the alert), and the queued records.
|
|
589
720
|
if (this.skippedChecks.size > 0)
|
|
590
721
|
void this._flushSkippedChecks();
|
|
722
|
+
this.records.resume();
|
|
591
723
|
return resolved(fetched.mode, true);
|
|
592
724
|
}
|
|
593
725
|
if (fetched && 'configError' in fetched) {
|
|
@@ -601,6 +733,7 @@ class FullCourtDefense {
|
|
|
601
733
|
modeCache.set(key, {
|
|
602
734
|
mode, rules: knownMode ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS,
|
|
603
735
|
confirmed: Boolean(knownMode), configError: fetched.configError,
|
|
736
|
+
// A refused key decides nothing locally: Block calls go to the server, which answers the same refusal.
|
|
604
737
|
});
|
|
605
738
|
return resolved(mode, Boolean(knownMode), fetched.configError);
|
|
606
739
|
}
|
|
@@ -613,7 +746,11 @@ class FullCourtDefense {
|
|
|
613
746
|
// a Monitor call is reported once the API answers, a Block call is spooled as before.
|
|
614
747
|
const known = Boolean(cached && cached.confirmed && cached.fetchedAt > 0);
|
|
615
748
|
const lastKnown = known && cached ? cached.mode : (this.modeAtProtect ?? 'block');
|
|
616
|
-
|
|
749
|
+
// Local decisions keep deciding from the last bundle a live answer gave (stale-while-error).
|
|
750
|
+
modeCache.set(key, {
|
|
751
|
+
mode: lastKnown, rules: known ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS, confirmed: known,
|
|
752
|
+
...(known && cached?.bundle ? { bundle: cached.bundle } : {}),
|
|
753
|
+
});
|
|
617
754
|
return resolved(lastKnown, known);
|
|
618
755
|
}
|
|
619
756
|
async _fetchShieldMode() {
|
|
@@ -622,7 +759,8 @@ class FullCourtDefense {
|
|
|
622
759
|
const resp = await fetch(url, {
|
|
623
760
|
method: 'GET',
|
|
624
761
|
headers: this.config.shieldKey ? { 'x-shield-key': this.config.shieldKey } : {},
|
|
625
|
-
|
|
762
|
+
// Local decisions never wait for this request, so it may take longer than a lookup a call waits for.
|
|
763
|
+
signal: AbortSignal.timeout(this.decisionMode === 'local' ? BUNDLE_FETCH_TIMEOUT_MS : MODE_FETCH_TIMEOUT_MS),
|
|
626
764
|
});
|
|
627
765
|
if (!resp.ok) {
|
|
628
766
|
// A wrong key or an unknown shield is not an outage: say so once, loudly (O4: a Monitor agent's
|
|
@@ -635,8 +773,11 @@ class FullCourtDefense {
|
|
|
635
773
|
}
|
|
636
774
|
const data = await resp.json().catch(() => null);
|
|
637
775
|
const mode = data?.data?.mode;
|
|
638
|
-
if (mode === 'monitor' || mode === 'block' || mode === 'shadow')
|
|
639
|
-
|
|
776
|
+
if (mode === 'monitor' || mode === 'block' || mode === 'shadow') {
|
|
777
|
+
// A bundle without `actionPolicies` (a backend that serves none to an SDK) cannot decide locally: the server does.
|
|
778
|
+
const bundle = this.decisionMode === 'local' && Array.isArray(data?.data?.actionPolicies) ? (0, localDecision_1.prepareLocalBundle)(data?.data) : undefined;
|
|
779
|
+
return { mode, rules: (0, failMode_1.sanitizeFailsafeRules)(data?.data?.agentFailsafeRules), ...(bundle ? { bundle } : {}) };
|
|
780
|
+
}
|
|
640
781
|
return null;
|
|
641
782
|
}
|
|
642
783
|
catch {
|
|
@@ -1145,6 +1286,19 @@ class FullCourtDefense {
|
|
|
1145
1286
|
const argsProblem = (0, argsBounds_1.toolCallArgsProblem)(input);
|
|
1146
1287
|
if (argsProblem)
|
|
1147
1288
|
return this._argsProblemVerdict(input, argsProblem);
|
|
1289
|
+
// Local decisions (owner order 2026-11-01): from the bundle, in this process, no request. A manager approval
|
|
1290
|
+
// and a call the bundle cannot decide continue to the server check below.
|
|
1291
|
+
const local = this._decideLocal(input, mode);
|
|
1292
|
+
if (local) {
|
|
1293
|
+
if (local.record) {
|
|
1294
|
+
// guardToolCall writes ONE record after the tool ran (decision + how it ended); a direct check writes it now.
|
|
1295
|
+
if (this.deferredLocalRecords.has(rawInput))
|
|
1296
|
+
this.deferredLocalRecords.set(rawInput, local.record);
|
|
1297
|
+
else
|
|
1298
|
+
this._enqueueRecord(local.record);
|
|
1299
|
+
}
|
|
1300
|
+
return local.result;
|
|
1301
|
+
}
|
|
1148
1302
|
const degrade = (reason) => {
|
|
1149
1303
|
if (this.failMode)
|
|
1150
1304
|
return this._degradeByFailMode(input, reason, this.failMode);
|
|
@@ -1216,6 +1370,71 @@ class FullCourtDefense {
|
|
|
1216
1370
|
}
|
|
1217
1371
|
return result;
|
|
1218
1372
|
}
|
|
1373
|
+
/**
|
|
1374
|
+
* A Block-mode call decided in this process from the bundle, or undefined when the server decides it (server
|
|
1375
|
+
* decision mode, a manager approval, a call the bundle cannot decide, a backend that serves no policies, a
|
|
1376
|
+
* refused key). With no bundle at all (FullCourtDefense never reached since this agent started), the call is
|
|
1377
|
+
* answered by the fail mode at once: it runs (only a never-allowed rule stops one), it is recorded, and one
|
|
1378
|
+
* warning says so. Never a request, never a wait.
|
|
1379
|
+
*/
|
|
1380
|
+
_decideLocal(input, mode) {
|
|
1381
|
+
if (this.decisionMode !== 'local' || mode.configError)
|
|
1382
|
+
return undefined;
|
|
1383
|
+
const bundle = this._localBundle();
|
|
1384
|
+
if (!bundle) {
|
|
1385
|
+
// A live answer came without policies (an older backend): the server decides, as before.
|
|
1386
|
+
if (modeCache.get(this._modeCacheKey())?.confirmed)
|
|
1387
|
+
return undefined;
|
|
1388
|
+
if (!this.warnedNoBundle) {
|
|
1389
|
+
this.warnedNoBundle = true;
|
|
1390
|
+
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.');
|
|
1391
|
+
}
|
|
1392
|
+
return { result: this._degradeByFailMode(input, 'no policy bundle yet', this.failMode ?? 'tiered') };
|
|
1393
|
+
}
|
|
1394
|
+
const decided = (0, localDecision_1.decideLocally)(bundle, input);
|
|
1395
|
+
if (decided.route === 'server' || decided.decision === 'approval')
|
|
1396
|
+
return undefined;
|
|
1397
|
+
const data = {
|
|
1398
|
+
allowed: decided.allowed,
|
|
1399
|
+
decision: decided.decision,
|
|
1400
|
+
operation: decided.operation,
|
|
1401
|
+
actionPolicy: decided.actionPolicy,
|
|
1402
|
+
analysis: 'sync',
|
|
1403
|
+
decidedBy: 'local',
|
|
1404
|
+
outcome: decided.outcome,
|
|
1405
|
+
};
|
|
1406
|
+
return { result: { success: true, data }, record: this._localRecordBody(input, data) };
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* The record of a locally decided call, for the existing record endpoint (`POST /runtime/tool-call`): what was
|
|
1410
|
+
* decided and by which rule, the arguments as their summary (the server minimizes them as for every SDK record),
|
|
1411
|
+
* the provider's tool-call id (one action = one record when a local AI gateway also saw it), and how the tool
|
|
1412
|
+
* ended when it ran.
|
|
1413
|
+
*/
|
|
1414
|
+
_localRecordBody(input, data, ended) {
|
|
1415
|
+
const { toolArgs, failClosed: _failClosed, ...rest } = input;
|
|
1416
|
+
void _failClosed;
|
|
1417
|
+
const policy = data.actionPolicy || {};
|
|
1418
|
+
const why = policy.reason || (data.decision === 'block' ? 'Blocked by policy' : 'No policy stops this call');
|
|
1419
|
+
const ran = ended ? (ended.outcome === 'failed' ? ` The tool ran and raised ${ended.errorType ?? 'an error'}.` : ' The tool ran.') : '';
|
|
1420
|
+
return {
|
|
1421
|
+
...rest,
|
|
1422
|
+
argsSummary: input.argsSummary || toolArgs,
|
|
1423
|
+
operation: data.operation,
|
|
1424
|
+
decision: data.decision === 'block' ? 'block' : 'allow',
|
|
1425
|
+
reason: `${data.outcome === 'warn' ? 'Warn only: ' : ''}${why} (decided in the agent's process from the shield's policies).${ran}`.slice(0, 1000),
|
|
1426
|
+
...(policy.policyId ? { policyId: policy.policyId } : {}),
|
|
1427
|
+
...(policy.policyName ? { policyName: policy.policyName } : {}),
|
|
1428
|
+
...(policy.matchedRule ? { matchedRule: policy.matchedRule } : {}),
|
|
1429
|
+
...(policy.monitorMatches?.length ? { monitorMatches: policy.monitorMatches } : {}),
|
|
1430
|
+
decisionSource: 'sdk',
|
|
1431
|
+
decidedBy: 'sdk_local',
|
|
1432
|
+
...(data.outcome ? { localOutcome: data.outcome } : {}),
|
|
1433
|
+
...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
|
|
1434
|
+
...(ended ? { toolOutcome: ended.outcome, ...(ended.errorType ? { errorType: ended.errorType } : {}) } : {}),
|
|
1435
|
+
occurredAt: new Date().toISOString(),
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1219
1438
|
/**
|
|
1220
1439
|
* The record of a call that runs in Monitor (it never waits for it):
|
|
1221
1440
|
* - the API refused the key or shield (O4): the call runs; its report goes to the API anyway, where
|
|
@@ -1267,6 +1486,18 @@ class FullCourtDefense {
|
|
|
1267
1486
|
_sendMonitorRecord(input) {
|
|
1268
1487
|
const problem = (0, argsBounds_1.toolCallArgsProblem)(input);
|
|
1269
1488
|
const { toolArgs, ...rest } = input;
|
|
1489
|
+
if (this.decisionMode === 'local') {
|
|
1490
|
+
// Local decisions: the Monitor record joins the background batches (the server still evaluates its would-have).
|
|
1491
|
+
this._enqueueRecord({
|
|
1492
|
+
...rest,
|
|
1493
|
+
decision: input.decision || 'allow',
|
|
1494
|
+
reason: input.reason || 'monitor_mode_async',
|
|
1495
|
+
argsSummary: problem ? (0, argsBounds_1.toolArgsProblemSummary)(problem) : (input.argsSummary || toolArgs),
|
|
1496
|
+
decisionSource: 'sdk',
|
|
1497
|
+
...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
|
|
1498
|
+
});
|
|
1499
|
+
return Promise.resolve();
|
|
1500
|
+
}
|
|
1270
1501
|
return this.recordToolCall({
|
|
1271
1502
|
...rest,
|
|
1272
1503
|
decision: input.decision || 'allow',
|
|
@@ -1442,10 +1673,24 @@ class FullCourtDefense {
|
|
|
1442
1673
|
finally {
|
|
1443
1674
|
// Short-lived hosts (Lambda) freeze when the handler returns: the record, and a report of
|
|
1444
1675
|
// 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);
|
|
1676
|
+
await settleWithin(Promise.all([recording, this.skippedFlush, this.records.flush()]), RECORD_FLUSH_MAX_MS);
|
|
1446
1677
|
}
|
|
1447
1678
|
}
|
|
1448
|
-
|
|
1679
|
+
// A local decision's record is written once, after the tool ran (decision + how it ended).
|
|
1680
|
+
this.deferredLocalRecords.set(input, null);
|
|
1681
|
+
let preflight;
|
|
1682
|
+
try {
|
|
1683
|
+
preflight = await this.checkToolCall(input);
|
|
1684
|
+
}
|
|
1685
|
+
catch (error) {
|
|
1686
|
+
this.deferredLocalRecords.delete(input);
|
|
1687
|
+
throw error;
|
|
1688
|
+
}
|
|
1689
|
+
const localRecord = this.deferredLocalRecords.get(input) ?? undefined;
|
|
1690
|
+
this.deferredLocalRecords.delete(input);
|
|
1691
|
+
if (localRecord && preflight.data?.decidedBy === 'local') {
|
|
1692
|
+
return this._runLocallyDecided(input, preflight.data, action, options);
|
|
1693
|
+
}
|
|
1449
1694
|
if (!preflight.success) {
|
|
1450
1695
|
// `code` is set only when checkToolCall classified the answer as definite (a 4xx, not an outage).
|
|
1451
1696
|
if (preflight.code && (0, errors_1.isDefiniteStatus)(preflight.status)) {
|
|
@@ -1532,6 +1777,40 @@ class FullCourtDefense {
|
|
|
1532
1777
|
await settleWithin(this.skippedFlush, RECORD_FLUSH_MAX_MS);
|
|
1533
1778
|
return result;
|
|
1534
1779
|
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Run (or stop) a call decided locally, and write its ONE record afterwards in the background: a stopped call
|
|
1782
|
+
* at once, an allowed call with how it ended (`executed`, or `failed` with the error's type name only).
|
|
1783
|
+
*/
|
|
1784
|
+
async _runLocallyDecided(input, data, action, options) {
|
|
1785
|
+
const finish = async (record) => {
|
|
1786
|
+
this._enqueueRecord(record);
|
|
1787
|
+
// Short-lived hosts (Lambda) freeze when the handler returns: the record goes first, capped.
|
|
1788
|
+
if (options.awaitRecord)
|
|
1789
|
+
await settleWithin(this.records.flush(), RECORD_FLUSH_MAX_MS);
|
|
1790
|
+
};
|
|
1791
|
+
if (!data.allowed) {
|
|
1792
|
+
await finish(this._localRecordBody(input, data));
|
|
1793
|
+
const policy = data.actionPolicy;
|
|
1794
|
+
const reason = policy?.reason || `Tool call ${data.decision}`;
|
|
1795
|
+
const message = `FullCourtDefense blocked tool call "${input.toolName}": ${reason}`;
|
|
1796
|
+
const rule = policy && (policy.matchedRule || policy.policyId || policy.policyName)
|
|
1797
|
+
? { ...(policy.matchedRule || policy.policyId ? { id: String(policy.matchedRule || policy.policyId) } : {}), ...(policy.policyName ? { name: String(policy.policyName) } : {}) }
|
|
1798
|
+
: undefined;
|
|
1799
|
+
throw options.onBlocked
|
|
1800
|
+
? options.onBlocked(message)
|
|
1801
|
+
: new errors_1.ToolCallBlocked(message, { toolName: input.toolName, decision: data.decision, reason, outcome: 'block', code: 'FCD_BLOCKED', rule, degraded: false });
|
|
1802
|
+
}
|
|
1803
|
+
let result;
|
|
1804
|
+
try {
|
|
1805
|
+
result = await action();
|
|
1806
|
+
}
|
|
1807
|
+
catch (error) {
|
|
1808
|
+
await finish(this._localRecordBody(input, data, { outcome: 'failed', errorType: errorTypeName(error) }));
|
|
1809
|
+
throw error;
|
|
1810
|
+
}
|
|
1811
|
+
await finish(this._localRecordBody(input, data, { outcome: 'executed' }));
|
|
1812
|
+
return result;
|
|
1813
|
+
}
|
|
1535
1814
|
/**
|
|
1536
1815
|
* How an allowed call ended. When the check returned the gate record's `actionId` (backends with
|
|
1537
1816
|
* the G-11 outcome report), the outcome goes ON that record: no second record, and a failure
|