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.
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Local decisions (owner order 2026-11-01): the SDK decides a tool call from the policy bundle it already
3
+ * polls, in-process and in well under a millisecond, with the SAME answer `POST /runtime/check-tool-call`
4
+ * gives. No network here, no I/O, no timers: pure.
5
+ *
6
+ * The answer is the server's because the code is the server's:
7
+ * - the action-policy engine is a byte-identical copy (./policy/actionPolicyEngine.ts = backend
8
+ * modules/policies/action-policy-engine.ts = CLI actionPolicyEngine.ts; drift guard in
9
+ * backend action-policy-engine-sync.test.ts);
10
+ * - this file mirrors the gate's SDK glue in agent-security.service `checkToolCallPolicy`: the call's
11
+ * context (`actionContext`), the agent principal `agent:<name>` (sdk-agent-call.ts `sdkAgentPrincipal`),
12
+ * declared operations, the shield's environment and machine kind, "no human", "Require agent identity",
13
+ * and the decision mapping;
14
+ * - sdks/shared/policy-parity/vectors.json holds the server's own answers; tests/local-parity.test.js
15
+ * requires 100% equality.
16
+ *
17
+ * What the bundle cannot carry is never guessed: `route: 'server'` sends the call to check-tool-call instead
18
+ * (a policy that reads the agent's recorded history, a suspended shield, a server kill switch, and what an older
19
+ * backend does not send: the shield facts, or the built-in safety rules a command / file / web call needs). The
20
+ * built-in safety rules themselves run here (./localSafety.ts, guard twin ./policy/deterministicGuard.ts).
21
+ * A manager approval is decided here but filed by the server (the caller sends it there).
22
+ */
23
+ import { type EngineActionPolicy, type EngineCheckResult, type MachineKind } from './policy/actionPolicyEngine';
24
+ import { type ServedLocalSafety } from './localSafety';
25
+ /** The outcome words every SDK shares (sdks/shared/policy-parity/README.md). */
26
+ export type LocalOutcome = 'allow' | 'warn' | 'monitor' | 'ask_developer' | 'manager_approval' | 'block' | 'hard_block';
27
+ /** The bundle's `sdkGate` member (backend modules/policies/sdk-gate-bundle.ts). */
28
+ export interface SdkGateFacts {
29
+ environment: string | null;
30
+ machineKind: MachineKind;
31
+ requireAgentIdentity: boolean;
32
+ /** Server kill switch: `server` sends every call to check-tool-call (backend FCD_SDK_LOCAL_DECISIONS=off). */
33
+ decisions?: 'local' | 'server';
34
+ /** The built-in safety rules exactly as the gate applies them to SDK calls (absent: shaped calls go to the server). */
35
+ localSafety?: ServedLocalSafety;
36
+ }
37
+ /** What the local engine needs from `GET /api/cli/bundle?shieldId=…&agentRules=1`, prepared once per bundle. */
38
+ export interface LocalBundle {
39
+ mode: 'block' | 'monitor' | 'shadow';
40
+ /** The built-in safety rules stage this shield is served (`off` | `warn` | `enforce`); unknown = not off. */
41
+ localSafetyEnforcement?: string;
42
+ suspended: boolean;
43
+ policies: EngineActionPolicy[];
44
+ sdkGate?: SdkGateFacts;
45
+ /** Prepared facts about the policies (computed once, read on every call). */
46
+ facts: {
47
+ /** An enforcing policy reads the agent's recorded history (only the server has it). */
48
+ serverFacts: boolean;
49
+ /** A policy tests the call's environment. */
50
+ environmentRules: boolean;
51
+ /** A policy is written for some machine kinds only. */
52
+ kindTargeted: boolean;
53
+ };
54
+ }
55
+ export interface LocalCallInput {
56
+ toolName: string;
57
+ agentName?: string;
58
+ agentId?: string;
59
+ agentIdSource?: string;
60
+ operation?: string;
61
+ resourceType?: string;
62
+ environment?: string;
63
+ mcpServer?: string;
64
+ toolArgs?: Record<string, unknown>;
65
+ argsSummary?: Record<string, unknown>;
66
+ }
67
+ export interface LocalActionPolicy {
68
+ allowed: boolean;
69
+ verdict: 'allow' | 'block' | 'require_approval' | 'log';
70
+ policyId?: string;
71
+ policyName?: string;
72
+ resourceType?: string;
73
+ matchedRule?: string;
74
+ reason?: string;
75
+ approval?: EngineCheckResult['approval'];
76
+ monitorMatches?: EngineCheckResult['monitorMatches'];
77
+ }
78
+ export type LocalDecision = {
79
+ route: 'server';
80
+ why: string;
81
+ } | {
82
+ route: 'local';
83
+ outcome: Exclude<LocalOutcome, 'monitor'>;
84
+ allowed: boolean;
85
+ decision: 'allow' | 'block' | 'approval';
86
+ operation: string;
87
+ actionPolicy: LocalActionPolicy;
88
+ };
89
+ /**
90
+ * Prepare a bundle's `data` for local decisions; undefined when it has no usable mode. Policies arrive in the
91
+ * bundle's compact shape (`actionPolicies`), exactly what the engine evaluates on the server.
92
+ */
93
+ export declare function prepareLocalBundle(data: unknown): LocalBundle | undefined;
94
+ export type SdkToolShape = 'command' | 'file' | 'web';
95
+ export declare function sdkToolShape(toolName: string, toolArgs: Record<string, unknown> | undefined, mcpServer?: string): SdkToolShape | undefined;
96
+ /**
97
+ * Decide one Block-mode tool call from the bundle (Monitor never reaches here: it runs and records).
98
+ * `input` is the body the SDK would post (identity already merged).
99
+ */
100
+ export declare function decideLocally(bundle: LocalBundle, input: LocalCallInput): LocalDecision;
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareLocalBundle = prepareLocalBundle;
4
+ exports.sdkToolShape = sdkToolShape;
5
+ exports.decideLocally = decideLocally;
6
+ /**
7
+ * Local decisions (owner order 2026-11-01): the SDK decides a tool call from the policy bundle it already
8
+ * polls, in-process and in well under a millisecond, with the SAME answer `POST /runtime/check-tool-call`
9
+ * gives. No network here, no I/O, no timers: pure.
10
+ *
11
+ * The answer is the server's because the code is the server's:
12
+ * - the action-policy engine is a byte-identical copy (./policy/actionPolicyEngine.ts = backend
13
+ * modules/policies/action-policy-engine.ts = CLI actionPolicyEngine.ts; drift guard in
14
+ * backend action-policy-engine-sync.test.ts);
15
+ * - this file mirrors the gate's SDK glue in agent-security.service `checkToolCallPolicy`: the call's
16
+ * context (`actionContext`), the agent principal `agent:<name>` (sdk-agent-call.ts `sdkAgentPrincipal`),
17
+ * declared operations, the shield's environment and machine kind, "no human", "Require agent identity",
18
+ * and the decision mapping;
19
+ * - sdks/shared/policy-parity/vectors.json holds the server's own answers; tests/local-parity.test.js
20
+ * requires 100% equality.
21
+ *
22
+ * What the bundle cannot carry is never guessed: `route: 'server'` sends the call to check-tool-call instead
23
+ * (a policy that reads the agent's recorded history, a suspended shield, a server kill switch, and what an older
24
+ * backend does not send: the shield facts, or the built-in safety rules a command / file / web call needs). The
25
+ * built-in safety rules themselves run here (./localSafety.ts, guard twin ./policy/deterministicGuard.ts).
26
+ * A manager approval is decided here but filed by the server (the caller sends it there).
27
+ */
28
+ const actionPolicyEngine_1 = require("./policy/actionPolicyEngine");
29
+ const localSafety_1 = require("./localSafety");
30
+ const NAME_MAX = 160;
31
+ function normalizeName(value, fallback) {
32
+ return typeof value === 'string' && value.trim() ? value.trim().slice(0, NAME_MAX) : fallback;
33
+ }
34
+ function plainObject(value) {
35
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
36
+ }
37
+ // ── Bundle preparation ──────────────────────────────────────────────────────────────────────────────
38
+ /** Keep a policy only when it has the shape the engine reads (anything else is dropped, never trusted). */
39
+ function enginePolicy(raw) {
40
+ const policy = plainObject(raw);
41
+ if (!policy || typeof policy.id !== 'string' || !Array.isArray(policy.rules))
42
+ return undefined;
43
+ const rules = policy.rules.filter((rule) => {
44
+ const r = plainObject(rule);
45
+ return r && Array.isArray(r.operations) && typeof r.verdict === 'string';
46
+ });
47
+ return { ...policy, name: typeof policy.name === 'string' ? policy.name : policy.id, rules: rules };
48
+ }
49
+ function parseSdkGate(raw) {
50
+ const gate = plainObject(raw);
51
+ if (!gate || gate.v !== 1)
52
+ return undefined;
53
+ return {
54
+ environment: typeof gate.environment === 'string' && gate.environment.trim() ? gate.environment : null,
55
+ machineKind: (0, actionPolicyEngine_1.normalizeMachineKind)(typeof gate.machineKind === 'string' ? gate.machineKind : undefined),
56
+ requireAgentIdentity: gate.requireAgentIdentity === true,
57
+ decisions: gate.decisions === 'server' ? 'server' : 'local',
58
+ ...((0, localSafety_1.parseServedLocalSafety)(gate.localSafety) ? { localSafety: (0, localSafety_1.parseServedLocalSafety)(gate.localSafety) } : {}),
59
+ };
60
+ }
61
+ const ruleFields = (policy) => policy.rules.flatMap((rule) => (rule.constraints || []).map((c) => c && c.field));
62
+ /**
63
+ * Prepare a bundle's `data` for local decisions; undefined when it has no usable mode. Policies arrive in the
64
+ * bundle's compact shape (`actionPolicies`), exactly what the engine evaluates on the server.
65
+ */
66
+ function prepareLocalBundle(data) {
67
+ const body = plainObject(data);
68
+ if (!body)
69
+ return undefined;
70
+ const mode = body.mode;
71
+ if (mode !== 'block' && mode !== 'monitor' && mode !== 'shadow')
72
+ return undefined;
73
+ const policies = (Array.isArray(body.actionPolicies) ? body.actionPolicies : [])
74
+ .map(enginePolicy)
75
+ .filter((p) => Boolean(p));
76
+ const enforcing = policies.filter((p) => p.enabled !== false && p.stage !== 'monitor');
77
+ return {
78
+ mode,
79
+ localSafetyEnforcement: typeof body.localSafetyEnforcement === 'string' ? body.localSafetyEnforcement : undefined,
80
+ suspended: body.suspended === true,
81
+ policies,
82
+ sdkGate: parseSdkGate(body.sdkGate),
83
+ facts: {
84
+ serverFacts: enforcing.some((p) => p.needsServerFacts === true),
85
+ environmentRules: policies.some((p) => ruleFields(p).includes('environment')),
86
+ kindTargeted: policies.some((p) => Array.isArray(p.appliesTo?.machineKinds) && p.appliesTo.machineKinds.filter(Boolean).length > 0),
87
+ },
88
+ };
89
+ }
90
+ const COMMAND_NAME_WORDS = /\b(?:shell|bash|zsh|sh|command|commands|cmd|powershell|pwsh|terminal|exec|execute|subprocess|repl|interpreter)\b/;
91
+ const FILE_NAME_STRONG = /\b(?:filesystem|fs|glob)\b|\bapply patch\b|\b(?:read|write|edit|create|delete|remove|move|rename|copy|list|open|save|append) (?:text )?(?:file|files|dir|directory|directories|folder|folders)\b/;
92
+ const FILE_NAME_WORDS = /\b(?:file|files|path|paths|directory|directories|dir|folder|patch|notebook)\b/;
93
+ const WEB_NAME_STRONG = /\b(?:http|https|curl|wget|webhook|browse|browser|scrape|crawl)\b|\bfetch (?:url|uri|page|web|website|site|html)\b|\b(?:web|url) (?:fetch|request|get|post|browse)\b/;
94
+ const WEB_NAME_WORDS = /\b(?:fetch|url|uri|web|download|upload)\b/;
95
+ const COMMAND_ARG_KEYS = new Set(['command', 'cmd', 'script', 'shell', 'bash', 'powershell']);
96
+ const FILE_ARG_KEYS = new Set(['path', 'paths', 'file', 'files', 'filename', 'file_path', 'filepath', 'target_file', 'directory', 'dir', 'folder']);
97
+ const WEB_ARG_KEYS = new Set(['url', 'uri', 'href', 'endpoint', 'webhook', 'webhook_url', 'webhookurl']);
98
+ const PATH_VALUE = /^(?:(?:~|\.{1,2})?[\\/]|[a-z]:[\\/]|\.[a-z][\w-]*$|[\w.-]+[\\/][^\s]*|[\w-]+\.[a-z][a-z0-9]{0,7}$)/i;
99
+ function nameWords(toolName) {
100
+ return toolName.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_\-.:/]+/g, ' ').toLowerCase();
101
+ }
102
+ function textValue(value) {
103
+ if (typeof value === 'string')
104
+ return value.trim() !== '';
105
+ return Array.isArray(value) && value.some((item) => typeof item === 'string' && item.trim() !== '');
106
+ }
107
+ function webValue(value) {
108
+ const values = Array.isArray(value) ? value : [value];
109
+ return values.some((item) => typeof item === 'string' && /^(?:[a-z][a-z0-9+.-]*:\/\/|www\.)/i.test(item.trim()));
110
+ }
111
+ function pathValue(value) {
112
+ const values = Array.isArray(value) ? value : [value];
113
+ return values.some((item) => {
114
+ if (typeof item !== 'string')
115
+ return false;
116
+ const text = item.trim();
117
+ return text !== '' && text.length <= 4096 && !/\s/.test(text) && !/^[a-z][a-z0-9+.-]*:\/\//i.test(text) && PATH_VALUE.test(text);
118
+ });
119
+ }
120
+ function argEntries(toolArgs) {
121
+ const out = [];
122
+ for (const [key, value] of Object.entries(toolArgs || {}).slice(0, 200)) {
123
+ out.push([key.toLowerCase(), value]);
124
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
125
+ for (const [nestedKey, nested] of Object.entries(value).slice(0, 200))
126
+ out.push([nestedKey.toLowerCase(), nested]);
127
+ }
128
+ }
129
+ return out;
130
+ }
131
+ function sdkToolShape(toolName, toolArgs, mcpServer) {
132
+ const words = nameWords(`${mcpServer ? `${mcpServer} ` : ''}${toolName || ''}`);
133
+ const entries = argEntries(toolArgs && typeof toolArgs === 'object' ? toolArgs : {});
134
+ if (COMMAND_NAME_WORDS.test(words) || entries.some(([key, value]) => COMMAND_ARG_KEYS.has(key) && textValue(value)))
135
+ return 'command';
136
+ if (FILE_NAME_STRONG.test(words) || entries.some(([key, value]) => FILE_ARG_KEYS.has(key) && textValue(value))
137
+ || (FILE_NAME_WORDS.test(words) && entries.some(([, value]) => pathValue(value))))
138
+ return 'file';
139
+ if (WEB_NAME_STRONG.test(words) || entries.some(([key, value]) => WEB_ARG_KEYS.has(key) && webValue(value))
140
+ || (WEB_NAME_WORDS.test(words) && entries.some(([, value]) => webValue(value))))
141
+ return 'web';
142
+ return undefined;
143
+ }
144
+ // ── The decision ────────────────────────────────────────────────────────────────────────────────────
145
+ const AGENT_ID_SOURCES = new Set(['config', 'env', 'default']);
146
+ function outcomeOf(decision, policy, policies) {
147
+ if (decision === 'block') {
148
+ const hard = policy.policyId !== undefined && policies.some((p) => p.id === policy.policyId && p.enforcement === 'hard');
149
+ return hard ? 'hard_block' : 'block';
150
+ }
151
+ if (decision === 'approval')
152
+ return policy.approval?.scope === 'developer' ? 'ask_developer' : 'manager_approval';
153
+ return policy.verdict === 'log' ? 'warn' : 'allow';
154
+ }
155
+ /**
156
+ * Decide one Block-mode tool call from the bundle (Monitor never reaches here: it runs and records).
157
+ * `input` is the body the SDK would post (identity already merged).
158
+ */
159
+ function decideLocally(bundle, input) {
160
+ if (bundle.sdkGate?.decisions === 'server')
161
+ return { route: 'server', why: 'server_kill_switch' };
162
+ if (bundle.suspended)
163
+ return { route: 'server', why: 'shield_suspended' };
164
+ if (bundle.facts.serverFacts)
165
+ return { route: 'server', why: 'server_facts' };
166
+ const toolName = normalizeName(input.toolName, 'unknown-tool');
167
+ const agentName = normalizeName(input.agentName, 'unknown-agent');
168
+ const rawArgs = input.toolArgs ?? input.argsSummary;
169
+ const args = plainObject(rawArgs) ?? {};
170
+ const gate = bundle.sdkGate;
171
+ const agentIdSource = typeof input.agentIdSource === 'string' && AGENT_ID_SOURCES.has(input.agentIdSource) ? input.agentIdSource : undefined;
172
+ // Built-in safety rules (G-08): an SDK 2.1 call (the principal) shaped like a command, a file access or a web
173
+ // request is also checked by them, at the shield's stage, with the snapshot the bundle serves (`sdkGate.localSafety`,
174
+ // the gate's own value). An older backend serves none: such a call is the server's unless the rules are off.
175
+ const shape = agentIdSource ? sdkToolShape(toolName, args, input.mcpServer) : undefined;
176
+ const served = gate?.localSafety;
177
+ if (shape && !served && (bundle.localSafetyEnforcement ?? 'unknown') !== 'off') {
178
+ return { route: 'server', why: 'built_in_safety_rules' };
179
+ }
180
+ const derivedName = agentIdSource === 'default';
181
+ const identityMissing = !input.agentName || !String(input.agentName).trim() || agentName === 'unknown-agent' || derivedName;
182
+ if (!gate) {
183
+ // An older backend: the shield facts below are unknown, so a call they could change is the server's.
184
+ if (identityMissing)
185
+ return { route: 'server', why: 'agent_identity_unknown' };
186
+ if (bundle.facts.kindTargeted)
187
+ return { route: 'server', why: 'machine_kind_unknown' };
188
+ if (bundle.facts.environmentRules && !input.environment)
189
+ return { route: 'server', why: 'environment_unknown' };
190
+ }
191
+ // actionContext (agent-security.service): the engine's context of the call, plus who and what.
192
+ const inferred = (0, actionPolicyEngine_1.inferToolContext)(toolName, args);
193
+ const context = { ...inferred.context, agentName, toolName };
194
+ if (input.resourceType)
195
+ context.resourceType = input.resourceType;
196
+ if (input.mcpServer)
197
+ context.mcpServer = input.mcpServer;
198
+ if (input.environment)
199
+ context.environment = input.environment;
200
+ const operation = input.operation || inferred.operation;
201
+ // G-09: an SDK 2.1 call (agentIdSource) is the attributed principal `agent:<name>`.
202
+ if (agentIdSource)
203
+ context.developerName = `agent:${agentName}`;
204
+ const declaredOperations = (0, actionPolicyEngine_1.deriveToolOperations)(toolName, input.operation ? [input.operation] : []);
205
+ if (!context.environment && gate?.environment)
206
+ context.environment = gate.environment;
207
+ context.machineKind = gate?.machineKind ?? 'workstation';
208
+ // No human is at an SDK agent's keyboard: every block stops, an Ask goes to the organization.
209
+ context.humanPresent = 'false';
210
+ if (gate?.requireAgentIdentity && identityMissing) {
211
+ const reason = derivedName
212
+ ? `Tool call refused: the agent declared no identity (the SDK derived the name "${agentName}"). Set FCD_AGENT_ID or agentId in code — this shield requires agent identity.`
213
+ : 'Tool call refused: no agent identity provided. Set an agent name — this shield requires agent identity.';
214
+ return {
215
+ route: 'local', outcome: 'block', allowed: false, decision: 'block', operation,
216
+ actionPolicy: { allowed: false, verdict: 'block', reason, policyName: 'Require agent identity' },
217
+ };
218
+ }
219
+ const { skippedOrgPolicies: _skipped, ...result } = (0, actionPolicyEngine_1.evaluateActionPolicies)(bundle.policies, toolName, operation, context, declaredOperations);
220
+ void _skipped;
221
+ const policyResult = {
222
+ allowed: result.allowed,
223
+ verdict: result.verdict,
224
+ ...(result.policyId !== undefined ? { policyId: result.policyId } : {}),
225
+ ...(result.policyName !== undefined ? { policyName: result.policyName } : {}),
226
+ ...(result.resourceType !== undefined ? { resourceType: result.resourceType } : {}),
227
+ ...(result.matchedRule !== undefined ? { matchedRule: result.matchedRule } : {}),
228
+ ...(result.reason !== undefined ? { reason: result.reason } : {}),
229
+ ...(result.approval ? { approval: result.approval } : {}),
230
+ ...(result.monitorMatches?.length ? { monitorMatches: result.monitorMatches } : {}),
231
+ };
232
+ let actionPolicy = policyResult;
233
+ if (shape && served && served.stage !== 'off') {
234
+ let outcome;
235
+ try {
236
+ outcome = (0, localSafety_1.evaluateLocalSafety)({ toolName, toolArgs: args, ...(input.mcpServer ? { mcpServer: input.mcpServer } : {}) }, served);
237
+ }
238
+ catch (error) {
239
+ outcome = (0, localSafety_1.localSafetyFailure)(served.stage, error);
240
+ }
241
+ actionPolicy = (0, localSafety_1.withLocalSafety)(policyResult, outcome);
242
+ }
243
+ const decision = actionPolicy.verdict === 'block' ? 'block' : actionPolicy.verdict === 'require_approval' ? 'approval' : 'allow';
244
+ const allowed = actionPolicy.allowed && decision === 'allow';
245
+ return { route: 'local', outcome: outcomeOf(decision, actionPolicy, bundle.policies), allowed, decision, operation, actionPolicy };
246
+ }
@@ -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 Lambda extension's local decide server (`fcd-gate`, /opt/extensions): the shim asks it about each Bedrock tool
3
- // call over loopback instead of calling the FullCourtDefense API on every invocation.
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
- return (path, body, timeoutMs) => new Promise((resolve, reject) => {
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: false,
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,
@@ -0,0 +1,48 @@
1
+ import type { LocalActionPolicy } from './localDecision';
2
+ export declare const LOCAL_SAFETY_RULE_PREFIX = "local-safety:";
3
+ export type LocalSafetyStage = 'enforce' | 'warn' | 'off';
4
+ type ServedAction = 'block' | 'warn' | 'mask' | 'ask';
5
+ /** The served snapshot fields the guard and this glue read (the rest of the snapshot is passed through as is). */
6
+ export interface LocalSafetySnapshotView {
7
+ policyHash?: string;
8
+ categories?: Array<{
9
+ id: string;
10
+ items: Array<{
11
+ id: string;
12
+ label: string;
13
+ }>;
14
+ }>;
15
+ customBlocks?: Array<{
16
+ id: string;
17
+ pattern?: string;
18
+ action?: ServedAction;
19
+ categoryId?: string;
20
+ [key: string]: unknown;
21
+ }>;
22
+ disabledBuiltInItemIds?: string[];
23
+ itemActions?: Record<string, ServedAction>;
24
+ managerApprovalIds?: string[];
25
+ wouldActions?: Record<string, ServedAction>;
26
+ [key: string]: unknown;
27
+ }
28
+ /** `sdkGate.localSafety` from the bundle. */
29
+ export interface ServedLocalSafety {
30
+ stage: LocalSafetyStage;
31
+ snapshot: LocalSafetySnapshotView;
32
+ wouldManagerIds?: Set<string>;
33
+ }
34
+ export interface LocalSafetyOutcome {
35
+ check?: LocalActionPolicy;
36
+ wouldHave: NonNullable<LocalActionPolicy['monitorMatches']>;
37
+ ruleIds: string[];
38
+ }
39
+ export declare function parseServedLocalSafety(raw: unknown): ServedLocalSafety | undefined;
40
+ export declare function evaluateLocalSafety(call: {
41
+ toolName: string;
42
+ toolArgs: Record<string, unknown>;
43
+ mcpServer?: string;
44
+ }, input: ServedLocalSafety): LocalSafetyOutcome;
45
+ export declare function localSafetyFailure(stage: LocalSafetyStage, error: unknown): LocalSafetyOutcome;
46
+ /** The action-policy result with the built-in safety rules folded in (the gate's order; the strictest decides). */
47
+ export declare function withLocalSafety(actionPolicy: LocalActionPolicy, outcome: LocalSafetyOutcome): LocalActionPolicy;
48
+ export {};