fullcourtdefense 2.2.0 → 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/README.md +15 -5
- package/dist/client.d.ts +32 -2
- package/dist/client.js +147 -13
- package/dist/localGate.d.ts +8 -0
- package/dist/localGate.js +41 -4
- package/dist/policy/actionPolicyEngine.d.ts +23 -2
- package/dist/policy/actionPolicyEngine.js +82 -3
- package/dist/policy/deterministicGuard.js +179 -1
- package/dist/recordQueue.d.ts +73 -18
- package/dist/recordQueue.js +218 -54
- package/dist/types.d.ts +10 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,13 +61,15 @@ await run(agent, 'Who is customer c-1?');
|
|
|
61
61
|
What happens on each call:
|
|
62
62
|
|
|
63
63
|
```
|
|
64
|
-
agent asks for tool -> protect() ->
|
|
65
|
-
(
|
|
66
|
-
|
|
64
|
+
agent asks for tool -> protect() -> decided in your process -> allow: run tool, record in the background
|
|
65
|
+
(your organisation's policy, -> block: throw, tool never runs
|
|
66
|
+
refreshed every 60 s) -> approval: throw (or wait, see below)
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
+
- **No request per tool call.** The SDK holds a copy of your policy and decides in well under a millisecond; FullCourtDefense being slow or unreachable does not delay a call. Only a call that needs a manager's approval contacts FullCourtDefense while it runs. Details: [Local decisions](#local-decisions-default-no-request-per-tool-call).
|
|
70
|
+
|
|
69
71
|
- **Identity:** every call carries the agent's name. Without `FCD_AGENT_ID` it is the service the process runs as (`OTEL_SERVICE_NAME`, Cloud Run `K_SERVICE`, `AWS_LAMBDA_FUNCTION_NAME`, Azure Container Apps / App Service), then the npm package (`npm start`), then the main script — and the call says it was derived (`agentIdSource: 'default'`).
|
|
70
|
-
- **A wrong key, an unknown shield
|
|
72
|
+
- **A wrong, expired or rotated key, or an unknown shield (HTTP 401 / 403 / 404), never stops your agent.** The SDK says so loudly once (`console.error`, and `onDegrade`), keeps deciding from the policies it already holds, and with none yet answers by `FCD_FAIL_MODE` (default `tiered`: the tool runs and is reported as "ran without a check" once a key works; `closed` stops it). On a Monitor shield the tool runs and the call is still reported, so FullCourtDefense raises a "wrong or missing shield key" alert. **A refused request (HTTP 400, and any other 4xx except 408 / 429) is not an outage:** the tool does not run and `FullCourtDefenseApiError` says what to fix. Only a real outage and a refused key are answered by `FCD_FAIL_MODE` (below).
|
|
71
73
|
- **Arguments too deep or too large to check** (nested deeper than 32 levels, more than 20,000 values, or not encodable as JSON) are never sent: on Block the call is stopped ("too large to check safely"), in Monitor it runs and the record says what was not sent. Never an outage, and they cannot trip the circuit breaker.
|
|
72
74
|
|
|
73
75
|
No text leaves your process by default. Text scanning (prompt injection in user input, poisoned tool output, RAG chunks) is a separate, opt-in capability — see [Text scanning (opt-in)](#text-scanning-opt-in).
|
|
@@ -133,6 +135,14 @@ FCD_MODE_AT_PROTECT monitor # the shield's mode, rewritten whe
|
|
|
133
135
|
|
|
134
136
|
---
|
|
135
137
|
|
|
138
|
+
## Upgrading to 2.3
|
|
139
|
+
|
|
140
|
+
| 2.2 | 2.3 |
|
|
141
|
+
|---|---|
|
|
142
|
+
| A wrong, expired or rotated shield key, or an unknown shield (HTTP 401 / 403 / 404), stopped every tool of a Block-mode agent with `FullCourtDefenseApiError` | **It never stops your agent.** The SDK says so once on `console.error` (and `onDegrade`), keeps deciding from the policies it holds, and with none answers by `FCD_FAIL_MODE` (default `tiered`: the tool runs and is reported once a key works). Set `FCD_FAIL_MODE=closed` to keep stopping. **Breaking** if your code catches `FullCourtDefenseApiError` with `status` 401 / 403 / 404 on a tool call: it is no longer thrown there (a 400 still is). |
|
|
143
|
+
| The first Block-mode call of a process waited up to 3 s for the first policies | Up to **1 s** (`FCD_COLD_START_WAIT_MS` / `coldStartWaitMs` to change it; `await fcd.ready()` at start-up waits once, outside any tool call). |
|
|
144
|
+
| A record sent again after a slow answer could be stored twice; records refused during a bad-key window were dropped in silence | Every record carries an id (one record per action); refused records are reported as a gap ("N actions were not recorded"). |
|
|
145
|
+
|
|
136
146
|
## Upgrading to 2.1
|
|
137
147
|
|
|
138
148
|
| 2.0 | 2.1 |
|
|
@@ -760,7 +770,7 @@ when the client is built and refreshes them every 60 s in the background; a tool
|
|
|
760
770
|
- The built-in safety rules (command, file and web tools) are decided locally too, with the rules FullCourtDefense
|
|
761
771
|
serves in the same bundle. Only a call that needs a **manager's approval** goes to FullCourtDefense while it runs, plus
|
|
762
772
|
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
|
|
773
|
+
- Cold start: a Block-mode call made in the first 1 s after the client was built waits for the first policies
|
|
764
774
|
(`coldStartWaitMs`, env `FCD_COLD_START_WAIT_MS`; `0` = never wait), so a short-lived agent's first call is checked.
|
|
765
775
|
After that, or if FullCourtDefense cannot be reached, a call with no policies runs, is recorded, and one warning says
|
|
766
776
|
so: the agent is never stalled. `await fcd.ready()` waits for the policies once at start-up instead.
|
package/dist/client.d.ts
CHANGED
|
@@ -82,8 +82,15 @@ export declare class FullCourtDefense {
|
|
|
82
82
|
ready(timeoutMs?: number): Promise<boolean>;
|
|
83
83
|
/** The bundle for a local decision, or undefined (none yet, or the backend serves no policies to decide from). */
|
|
84
84
|
private _localBundle;
|
|
85
|
-
/**
|
|
86
|
-
|
|
85
|
+
/**
|
|
86
|
+
* One batch of queued records (RecordQueue's sender): `POST /runtime/tool-calls` with the records and, when the queue dropped
|
|
87
|
+
* some, the gap. An older backend (404 / 405 with no runtime error code) has no such route: the records go one by one to
|
|
88
|
+
* `/runtime/tool-call` from then on, for the rest of the process. A record or two the backend could not write come back as
|
|
89
|
+
* `outage` (resent); a record it refused is dropped.
|
|
90
|
+
*/
|
|
91
|
+
private _sendRecordBatch;
|
|
92
|
+
/** The older route: one record per request, a few at a time; after the first outage the rest of the batch waits (resent later). */
|
|
93
|
+
private _sendRecordsOneByOne;
|
|
87
94
|
/** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
|
|
88
95
|
private _enqueueRecord;
|
|
89
96
|
/** Send the records an earlier process left in the local spool (once per shield per process, off the first tick). */
|
|
@@ -92,6 +99,21 @@ export declare class FullCourtDefense {
|
|
|
92
99
|
_takeUnsentForSpool(): SpooledRecord[];
|
|
93
100
|
/** @internal Send the calls spooled while the API was down and the queued records (called at `beforeExit`; the caller bounds the wait). */
|
|
94
101
|
_flushForExit(): Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* How the background record upload is doing (observability for the app and the load tests): records waiting, sent,
|
|
104
|
+
* refused, dropped because the upload could not keep up (`dropped`; `unreported` is the part no accepted upload has told
|
|
105
|
+
* FullCourtDefense about yet), gaps the backend took, requests made, and whether records go in batches or one by one (an older backend).
|
|
106
|
+
*/
|
|
107
|
+
recordStats(): {
|
|
108
|
+
queued: number;
|
|
109
|
+
sent: number;
|
|
110
|
+
refused: number;
|
|
111
|
+
dropped: number;
|
|
112
|
+
unreported: number;
|
|
113
|
+
gapsReported: number;
|
|
114
|
+
requests: number;
|
|
115
|
+
mode: 'batch' | 'single';
|
|
116
|
+
};
|
|
95
117
|
/** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
|
|
96
118
|
get identity(): Readonly<RuntimeIdentity>;
|
|
97
119
|
/** Effective feature flags. */
|
|
@@ -276,6 +298,14 @@ export declare class FullCourtDefense {
|
|
|
276
298
|
*/
|
|
277
299
|
private _degradeByFailMode;
|
|
278
300
|
checkContext(input: AgentContextSecurityInput): Promise<AgentSecurityApiResult<AgentContextSecurityResult>>;
|
|
301
|
+
/**
|
|
302
|
+
* The container's local gate (`gate-host`, started by the wrap): asked first when `FCD_LOCAL_GATE=on` (only the wrap writes
|
|
303
|
+
* it, once the gate listens). Created on first use; `NO_GATE` everywhere else, so no other path pays a connect.
|
|
304
|
+
*/
|
|
305
|
+
private localGateClient?;
|
|
306
|
+
private localGate;
|
|
307
|
+
/** What the gate said about a call it did not allow: the error the agent code receives (the gate wrote the record). */
|
|
308
|
+
private _localGateStop;
|
|
279
309
|
guardToolCall<T>(rawInput: AgentToolCallInput, action: () => Promise<T>, options?: GuardToolCallOptions): Promise<T>;
|
|
280
310
|
/**
|
|
281
311
|
* Run (or stop) a call decided locally, and write its ONE record afterwards in the background: a stopped call
|
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
|
-
/**
|
|
27
|
-
|
|
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;
|
|
@@ -206,6 +217,8 @@ const failedRecords = [];
|
|
|
206
217
|
/** Clients holding calls in memory (spooled while the API was down, or waiting for the first mode lookup). */
|
|
207
218
|
const liveClients = new Set();
|
|
208
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();
|
|
209
222
|
let exitHooksInstalled = false;
|
|
210
223
|
let exitFlushRunning = false;
|
|
211
224
|
function toSpooled(entry) {
|
|
@@ -331,7 +344,18 @@ class FullCourtDefense {
|
|
|
331
344
|
const coldStartRaw = config.coldStartWaitMs ?? Number(readEnv(COLD_START_WAIT_ENV_VARS) ?? DEFAULT_COLD_START_WAIT_MS);
|
|
332
345
|
const coldStartWaitMs = Number.isFinite(coldStartRaw) ? Math.max(0, Math.min(coldStartRaw, 10000)) : DEFAULT_COLD_START_WAIT_MS;
|
|
333
346
|
this.coldStartDeadline = Date.now() + coldStartWaitMs;
|
|
334
|
-
this.records = new recordQueue_1.RecordQueue((
|
|
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
|
+
});
|
|
335
359
|
this.breaker = config.circuitBreaker === false
|
|
336
360
|
? null
|
|
337
361
|
: (0, circuitBreaker_1.getCircuitBreaker)(`${this.config.apiUrl}|${this.config.shieldId}`, config.circuitBreaker || undefined);
|
|
@@ -408,20 +432,71 @@ class FullCourtDefense {
|
|
|
408
432
|
_localBundle() {
|
|
409
433
|
return modeCache.get(this._modeCacheKey())?.bundle;
|
|
410
434
|
}
|
|
411
|
-
/**
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
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
|
+
}
|
|
418
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);
|
|
419
463
|
if (status === undefined || status >= 500 || status === 408 || status === 429)
|
|
420
464
|
return 'outage';
|
|
421
465
|
return 'refused';
|
|
422
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
|
+
}
|
|
423
492
|
/** Queue a record for the background batches; kept across the end of the process (exit flush, local spool). */
|
|
424
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
|
+
}
|
|
425
500
|
this.records.push(body);
|
|
426
501
|
liveClients.add(this);
|
|
427
502
|
installExitHooks();
|
|
@@ -462,6 +537,10 @@ class FullCourtDefense {
|
|
|
462
537
|
at: entry.lastAt,
|
|
463
538
|
});
|
|
464
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 });
|
|
465
544
|
// Records of locally decided calls not sent yet: the next process with this shield sends them.
|
|
466
545
|
for (const item of this.records.drain()) {
|
|
467
546
|
out.push({ path: '/api/agent-security/runtime/tool-call', body: { ...item.body, shieldId: this.config.shieldId }, shieldId: this.config.shieldId, at: item.at });
|
|
@@ -472,6 +551,15 @@ class FullCourtDefense {
|
|
|
472
551
|
_flushForExit() {
|
|
473
552
|
return Promise.all([this._flushSkippedChecks(), this.records.flush()]).then(() => undefined);
|
|
474
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' };
|
|
562
|
+
}
|
|
475
563
|
/** Identity recorded on every runtime action (agentId / agentInstanceId / environment). */
|
|
476
564
|
get identity() {
|
|
477
565
|
return this._identity;
|
|
@@ -733,7 +821,9 @@ class FullCourtDefense {
|
|
|
733
821
|
modeCache.set(key, {
|
|
734
822
|
mode, rules: knownMode ? cached?.rules : undefined, fetchedAt: Date.now(), ttlMs: MODE_FAILURE_RETRY_MS,
|
|
735
823
|
confirmed: Boolean(knownMode), configError: fetched.configError,
|
|
736
|
-
//
|
|
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 } : {}),
|
|
737
827
|
});
|
|
738
828
|
return resolved(mode, Boolean(knownMode), fetched.configError);
|
|
739
829
|
}
|
|
@@ -766,7 +856,7 @@ class FullCourtDefense {
|
|
|
766
856
|
// A wrong key or an unknown shield is not an outage: say so once, loudly (O4: a Monitor agent's
|
|
767
857
|
// tools run and are reported, a Blocking agent's tools stop with the same explanation).
|
|
768
858
|
if (resp.status === 401 || resp.status === 403 || resp.status === 404) {
|
|
769
|
-
this._reportConfigurationError(resp.status, 'read the shield mode', undefined,
|
|
859
|
+
this._reportConfigurationError(resp.status, 'read the shield mode', undefined, REFUSED_KEY_OUTCOME);
|
|
770
860
|
return { configError: resp.status };
|
|
771
861
|
}
|
|
772
862
|
return null;
|
|
@@ -1339,6 +1429,7 @@ class FullCourtDefense {
|
|
|
1339
1429
|
this.breaker?.recordSuccess(Date.now() - startedAt);
|
|
1340
1430
|
if (this.skippedChecks.size > 0)
|
|
1341
1431
|
void this._flushSkippedChecks();
|
|
1432
|
+
this.records.resume(); // the API answers: queued records go now, not after the back-off
|
|
1342
1433
|
return result;
|
|
1343
1434
|
}
|
|
1344
1435
|
// The body could not be encoded (a value with a throwing toJSON): the call's own input, definite.
|
|
@@ -1350,6 +1441,13 @@ class FullCourtDefense {
|
|
|
1350
1441
|
// gets an explicit error (guardToolCall throws it; the tool does not run). An API that classifies
|
|
1351
1442
|
// its errors (G-04) may still call a 400 retryable (a server failure answered the way machines
|
|
1352
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
|
+
}
|
|
1353
1451
|
if ((0, errors_1.isDefiniteStatus)(result.status) && result.retryable !== true && result.category !== 'server') {
|
|
1354
1452
|
const error = this._reportConfigurationError(result.status, `check tool call "${input.toolName}"`, result.serverError, undefined, result.serverCode);
|
|
1355
1453
|
return {
|
|
@@ -1378,9 +1476,15 @@ class FullCourtDefense {
|
|
|
1378
1476
|
* warning says so. Never a request, never a wait.
|
|
1379
1477
|
*/
|
|
1380
1478
|
_decideLocal(input, mode) {
|
|
1381
|
-
if (this.decisionMode !== 'local'
|
|
1479
|
+
if (this.decisionMode !== 'local')
|
|
1382
1480
|
return undefined;
|
|
1383
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
|
+
}
|
|
1384
1488
|
if (!bundle) {
|
|
1385
1489
|
// A live answer came without policies (an older backend): the server decides, as before.
|
|
1386
1490
|
if (modeCache.get(this._modeCacheKey())?.confirmed)
|
|
@@ -1651,8 +1755,38 @@ class FullCourtDefense {
|
|
|
1651
1755
|
}
|
|
1652
1756
|
return result;
|
|
1653
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
|
+
}
|
|
1654
1780
|
async guardToolCall(rawInput, action, options = {}) {
|
|
1655
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
|
+
}
|
|
1656
1790
|
// Monitor mode: run the action immediately — no preflight wait, no approval
|
|
1657
1791
|
// gate. The tool call is recorded fire-and-forget for console visibility.
|
|
1658
1792
|
const mode = await this._resolveToolMode();
|
package/dist/localGate.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/localGate.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// The
|
|
3
|
-
// call
|
|
2
|
+
// The local decide server (`fcd-gate`): the shim asks it about each tool call over loopback instead of calling the
|
|
3
|
+
// FullCourtDefense API on every call. Two hosts run it: the Lambda extension (/opt/extensions/fcd-gate; Bedrock action
|
|
4
|
+
// groups, through `lambda.ts`) and a wrapped container (Cloud Run, ECS, Azure Container Apps: `workload-protect --local-gate
|
|
5
|
+
// true` starts `gate-host`, and `FullCourtDefense.guardToolCall` asks it). A container's gate is trusted only where
|
|
6
|
+
// `FCD_LOCAL_GATE=on` is set (see `localGateTrusted`): any process could listen on 18791, so a port that answers is never
|
|
7
|
+
// enough, and the only writer of that flag is the wrap, after the gate listens.
|
|
4
8
|
//
|
|
5
9
|
// POST 127.0.0.1:<FCD_GATE_PORT || 18791>/v1/tool-call -> { decision: 'allow' | 'block' | 'approval', message, ... }
|
|
6
10
|
// POST 127.0.0.1:<port>/v1/invocation-end { requestId } -> the work of this invocation is over: the extension
|
|
@@ -14,6 +18,8 @@
|
|
|
14
18
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
19
|
exports.NO_GATE = exports.LOCAL_END_TIMEOUT_MS = exports.LOCAL_DECIDE_TIMEOUT_MS = exports.LOCAL_GATE_DEFAULT_PORT = void 0;
|
|
16
20
|
exports.createLocalGate = createLocalGate;
|
|
21
|
+
exports.localGateTrusted = localGateTrusted;
|
|
22
|
+
exports.createTrustedLocalGate = createTrustedLocalGate;
|
|
17
23
|
/** The extension's default port; `FCD_GATE_PORT` overrides it (the extension reads the same variable). */
|
|
18
24
|
exports.LOCAL_GATE_DEFAULT_PORT = 18791;
|
|
19
25
|
/** Enforce may wait for the first bundle (the extension's cold wait is 3 s): the shim waits a little longer than that. */
|
|
@@ -22,14 +28,16 @@ exports.LOCAL_DECIDE_TIMEOUT_MS = 4500;
|
|
|
22
28
|
exports.LOCAL_END_TIMEOUT_MS = 300;
|
|
23
29
|
function loopbackPost(port) {
|
|
24
30
|
const http = require('http');
|
|
25
|
-
|
|
31
|
+
// One kept-alive connection pool: a call is one loopback round trip, not a connect each time.
|
|
32
|
+
const agent = new (require('http').Agent)({ keepAlive: true, maxSockets: 4 });
|
|
33
|
+
const once = (path, body, timeoutMs) => new Promise((resolve, reject) => {
|
|
26
34
|
let settled = false;
|
|
27
35
|
const finish = (fn) => { if (!settled) {
|
|
28
36
|
settled = true;
|
|
29
37
|
fn();
|
|
30
38
|
} };
|
|
31
39
|
const req = http.request({
|
|
32
|
-
host: '127.0.0.1', port, path, method: 'POST', agent:
|
|
40
|
+
host: '127.0.0.1', port, path, method: 'POST', agent: agent,
|
|
33
41
|
headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
|
|
34
42
|
}, (res) => {
|
|
35
43
|
let text = '';
|
|
@@ -42,6 +50,18 @@ function loopbackPost(port) {
|
|
|
42
50
|
req.setTimeout(timeoutMs, () => { finish(() => reject(new Error('timeout'))); req.destroy(); });
|
|
43
51
|
req.end(body);
|
|
44
52
|
});
|
|
53
|
+
// A kept-alive socket the server closed while idle is reset on first use: one more try on a fresh one.
|
|
54
|
+
return async (path, body, timeoutMs) => {
|
|
55
|
+
try {
|
|
56
|
+
return await once(path, body, timeoutMs);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const code = error?.code;
|
|
60
|
+
if (code === 'ECONNRESET' || code === 'EPIPE')
|
|
61
|
+
return once(path, body, timeoutMs);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
45
65
|
}
|
|
46
66
|
/** A refused connection means no listener: no extension in this environment. A timeout or a reset is a bad moment, not absence. */
|
|
47
67
|
function isRefused(error) {
|
|
@@ -106,6 +126,23 @@ function createLocalGate(env, post) {
|
|
|
106
126
|
};
|
|
107
127
|
return gate;
|
|
108
128
|
}
|
|
129
|
+
const ON = ['1', 'true', 'on', 'yes'];
|
|
130
|
+
const OFF = ['0', 'false', 'off', 'no'];
|
|
131
|
+
/**
|
|
132
|
+
* Whether the gate on 127.0.0.1 may be asked outside the Lambda shim, which knows its own extension. Trusted only where the
|
|
133
|
+
* operator or the wrap says so: `FCD_LOCAL_GATE` on (the wrap writes it once its gate listens) or an explicit `FCD_GATE_PORT`.
|
|
134
|
+
* `FCD_LOCAL_GATE=off` always wins. Elsewhere a local process could answer "allow", so it is never assumed.
|
|
135
|
+
*/
|
|
136
|
+
function localGateTrusted(env) {
|
|
137
|
+
const switchValue = (env.FCD_LOCAL_GATE || '').trim().toLowerCase();
|
|
138
|
+
if (OFF.includes(switchValue))
|
|
139
|
+
return false;
|
|
140
|
+
return ON.includes(switchValue) || Boolean((env.FCD_GATE_PORT || '').trim());
|
|
141
|
+
}
|
|
142
|
+
/** The loopback client for a host that is not the Lambda shim: none unless [`localGateTrusted`]. */
|
|
143
|
+
function createTrustedLocalGate(env, post) {
|
|
144
|
+
return localGateTrusted(env) ? createLocalGate(env, post) : exports.NO_GATE;
|
|
145
|
+
}
|
|
109
146
|
/** A gate that is never there: every call uses the shim's own path. */
|
|
110
147
|
exports.NO_GATE = {
|
|
111
148
|
present: false,
|
|
@@ -379,6 +379,20 @@ export declare function takeShellAstOperationComparison(): ShellAstOperationComp
|
|
|
379
379
|
* judged once per address as well, and the strictest outcome decides (judgeWebBatch).
|
|
380
380
|
*/
|
|
381
381
|
export declare function evaluateActionPolicies(policies: EngineActionPolicy[], toolName: string, operation: string, context?: Record<string, string>, declaredOperations?: string[]): EngineCheckResult;
|
|
382
|
+
/**
|
|
383
|
+
* Nested tool arguments as constraint fields (`args.customer.tier`, `args.items.0.sku`). A constraint field is a dotted
|
|
384
|
+
* path into the call's arguments: object keys and array indexes, joined by `.`. A path that is not there (a missing key, an
|
|
385
|
+
* index past the end, a value that is not a string / number / boolean) is a missing fact, exactly as a missing top-level
|
|
386
|
+
* field: no match. Limits, identical in every engine that decides tool calls (backend, Node SDK, Python SDK, Rust CLI;
|
|
387
|
+
* sdks/shared/policy-parity/nested-args.json): at most NESTED_ARGS_MAX_DEPTH segments after `args.`, array indexes below
|
|
388
|
+
* NESTED_ARGS_MAX_INDEX, NESTED_ARGS_MAX_LEAVES values per call, and a key containing `.` is not addressable.
|
|
389
|
+
* `validateArgsFieldPath` is the save-time check of the same rules.
|
|
390
|
+
*/
|
|
391
|
+
export declare const NESTED_ARGS_MAX_DEPTH = 6;
|
|
392
|
+
export declare const NESTED_ARGS_MAX_INDEX = 100;
|
|
393
|
+
export declare const NESTED_ARGS_MAX_LEAVES = 256;
|
|
394
|
+
/** Why a constraint field naming tool arguments cannot be evaluated by every engine, or undefined when it can. */
|
|
395
|
+
export declare function validateArgsFieldPath(field: string): string | undefined;
|
|
382
396
|
/**
|
|
383
397
|
* Infer operation and context from a tool call.
|
|
384
398
|
* Handles common patterns: SQL operations, file paths, HTTP methods, etc.
|
|
@@ -394,11 +408,18 @@ export declare function inferToolContext(toolName: string, args: Record<string,
|
|
|
394
408
|
* request catcher exists to capture whatever is sent to it). Deliberately absent:
|
|
395
409
|
* general cloud storage, code hosting and gists, which are everyday developer
|
|
396
410
|
* destinations and would turn the category into noise.
|
|
411
|
+
*
|
|
412
|
+
* Portions derived from DefenseClaw (Cisco, Apache-2.0), modified: the 2026-11 additions to the paste, file_drop,
|
|
413
|
+
* request_capture and tunnel lists and the anonymizer category follow DefenseClaw's sandbox egress blocklist
|
|
414
|
+
* categories (attribution: sdks/cli/THIRD_PARTY_NOTICES.txt). Left out on purpose: a company's own Tailscale names
|
|
415
|
+
* (ts.net), the ngrok and Dev Tunnels vendor sites and APIs. Rust twin: fcd-policy src/facts/urls.rs (pinned).
|
|
397
416
|
*/
|
|
398
|
-
export type DestinationCategory = 'paste' | 'file_drop' | 'request_capture' | 'tunnel' | 'messaging' | 'news';
|
|
417
|
+
export type DestinationCategory = 'paste' | 'file_drop' | 'request_capture' | 'tunnel' | 'anonymizer' | 'messaging' | 'news';
|
|
399
418
|
export declare const DESTINATION_CATEGORY_HOSTS: Readonly<Record<DestinationCategory, readonly string[]>>;
|
|
400
|
-
/** Categories whose purpose is to receive data from strangers: a first upload there is high risk. */
|
|
419
|
+
/** Categories whose purpose is to receive data from strangers, or to hide where it goes: a first upload there is high risk. */
|
|
401
420
|
export declare const HIGH_RISK_DESTINATION_CATEGORIES: ReadonlySet<DestinationCategory>;
|
|
421
|
+
/** Top-level names that resolve only through an anonymity network (Tor onion services, I2P, Tor exit notation). */
|
|
422
|
+
export declare const ANONYMITY_NETWORK_TLDS: readonly string[];
|
|
402
423
|
/** The listed host itself or any subdomain of it (`www.pastebin.com`, `x.m.pipedream.net`); never a look-alike (`notpastebin.com`). */
|
|
403
424
|
export declare function destinationCategory(host: string | undefined | null): DestinationCategory | undefined;
|
|
404
425
|
/** A host's category and whether that category exists to receive data from anyone — the shape the anomaly scorer takes. */
|