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.
@@ -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
+ }
@@ -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 {};
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOCAL_SAFETY_RULE_PREFIX = void 0;
4
+ exports.parseServedLocalSafety = parseServedLocalSafety;
5
+ exports.evaluateLocalSafety = evaluateLocalSafety;
6
+ exports.localSafetyFailure = localSafetyFailure;
7
+ exports.withLocalSafety = withLocalSafety;
8
+ /**
9
+ * The built-in safety rules (Local Safety) on an SDK tool call, decided in-process: the twin of the gate's G-08 glue
10
+ * (backend modules/policies/sdk-agent-call.ts `evaluateSdkLocalSafety`, `withSdkLocalSafety`, `sdkLocalSafetyFailure`;
11
+ * local-safety-approval.ts `managerApprovalRuleIds`, `localSafetyManagerApproval`, `localSafetyApprovalCheck`).
12
+ * The guard itself is the byte-identical copy (./policy/deterministicGuard.ts = backend deterministic-guard.ts), and
13
+ * the snapshot is the one the gate uses, served in the bundle (`sdkGate.localSafety`, backend
14
+ * services/sdk-local-safety-served.ts). sdks/shared/policy-parity/vectors.json pins every answer.
15
+ */
16
+ const actionPolicyEngine_1 = require("./policy/actionPolicyEngine");
17
+ const deterministicGuard_1 = require("./policy/deterministicGuard");
18
+ exports.LOCAL_SAFETY_RULE_PREFIX = 'local-safety:';
19
+ const NO_FINDING = Object.freeze({ wouldHave: [], ruleIds: [] });
20
+ function parseServedLocalSafety(raw) {
21
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
22
+ return undefined;
23
+ const value = raw;
24
+ if (value.stage !== 'enforce' && value.stage !== 'warn' && value.stage !== 'off')
25
+ return undefined;
26
+ if (!value.snapshot || typeof value.snapshot !== 'object' || Array.isArray(value.snapshot))
27
+ return undefined;
28
+ const snapshot = value.snapshot;
29
+ if (!Array.isArray(snapshot.categories) || !Array.isArray(snapshot.customBlocks) || !Array.isArray(snapshot.disabledBuiltInItemIds))
30
+ return undefined;
31
+ return {
32
+ stage: value.stage,
33
+ snapshot,
34
+ ...(Array.isArray(value.wouldManagerIds) ? { wouldManagerIds: new Set(value.wouldManagerIds.filter((id) => typeof id === 'string')) } : {}),
35
+ };
36
+ }
37
+ // ── local-safety-approval.ts twin ──
38
+ function managerApprovalRuleIds(snapshot) {
39
+ const listed = new Set(snapshot.managerApprovalIds || []);
40
+ const ids = new Set();
41
+ if (listed.size === 0)
42
+ return ids;
43
+ const disabled = new Set(snapshot.disabledBuiltInItemIds || []);
44
+ for (const [id, action] of Object.entries(snapshot.itemActions || {})) {
45
+ if (action === 'ask' && listed.has(id) && !disabled.has(id))
46
+ ids.add(id);
47
+ }
48
+ for (const block of snapshot.customBlocks || []) {
49
+ if (block.action === 'ask' && listed.has(block.id))
50
+ ids.add(block.id);
51
+ }
52
+ return ids;
53
+ }
54
+ function localSafetyManagerApproval(snapshot, ref) {
55
+ if (!managerApprovalRuleIds(snapshot).has(ref))
56
+ return undefined;
57
+ const custom = (snapshot.customBlocks || []).find((block) => block.id === ref);
58
+ if (custom)
59
+ return { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${custom.id}`, policyName: `Command contains “${custom.pattern}”`, itemId: custom.id };
60
+ for (const category of snapshot.categories || []) {
61
+ const item = category.items.find((entry) => entry.id === ref);
62
+ if (item)
63
+ return { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${item.id}`, policyName: item.label, itemId: item.id };
64
+ }
65
+ return undefined;
66
+ }
67
+ function localSafetyApprovalCheck(rule) {
68
+ return {
69
+ allowed: false,
70
+ verdict: 'require_approval',
71
+ policyId: rule.policyId,
72
+ policyName: rule.policyName,
73
+ resourceType: 'custom',
74
+ matchedRule: rule.itemId,
75
+ reason: `Shell-command rule "${rule.policyName}" needs a manager's OK before this runs`,
76
+ approval: { ...actionPolicyEngine_1.DEFAULT_ACTION_POLICY_APPROVAL, scope: 'org' },
77
+ };
78
+ }
79
+ // ── sdk-agent-call.ts twin ──
80
+ function ruleRef(snapshot, finding) {
81
+ const itemId = finding.itemId;
82
+ if (finding.source === 'custom') {
83
+ const block = (snapshot.customBlocks || []).find((entry) => entry.id === itemId);
84
+ return { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${itemId}`, policyName: block?.pattern ? `Contains “${block.pattern}”` : 'Custom safety rule', itemId };
85
+ }
86
+ for (const category of snapshot.categories || []) {
87
+ const item = category.items.find((entry) => entry.id === itemId);
88
+ if (item)
89
+ return { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${item.id}`, policyName: item.label, itemId };
90
+ }
91
+ return { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${itemId}`, policyName: 'Built-in safety rule', itemId };
92
+ }
93
+ function stripStop(text) {
94
+ return String(text || '').trim().replace(/[.\s]+$/, '');
95
+ }
96
+ function blockCheck(rule, reason) {
97
+ return { allowed: false, verdict: 'block', policyId: rule.policyId, policyName: rule.policyName, resourceType: 'custom', matchedRule: rule.itemId, reason };
98
+ }
99
+ function warnCheck(rule, reason) {
100
+ return { allowed: true, verdict: 'log', policyId: rule.policyId, policyName: rule.policyName, resourceType: 'custom', matchedRule: rule.itemId, reason };
101
+ }
102
+ function wouldMatch(snapshot, finding, wouldManagerIds) {
103
+ const would = snapshot.wouldActions?.[finding.itemId];
104
+ if (!would || would === 'warn')
105
+ return undefined;
106
+ const rule = ruleRef(snapshot, finding);
107
+ const verdict = would === 'ask' && wouldManagerIds?.has(finding.itemId) ? 'require_approval' : 'block';
108
+ return { policyId: rule.policyId, policyName: rule.policyName, verdict, matchedRule: rule.itemId };
109
+ }
110
+ function evaluateLocalSafety(call, input) {
111
+ if (input.stage === 'off')
112
+ return NO_FINDING;
113
+ const { snapshot } = input;
114
+ const enforce = input.stage === 'enforce';
115
+ const mcpServerName = call.mcpServer && call.mcpServer.trim() ? call.mcpServer.trim() : undefined;
116
+ const oversize = (0, deterministicGuard_1.oversizedAction)(call.toolName, call.toolArgs, mcpServerName ? { mcpServerName } : undefined);
117
+ if (oversize) {
118
+ const words = (0, deterministicGuard_1.oversizeWording)(oversize, 'tool call');
119
+ const rule = { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}${words.ruleId}`, policyName: 'Too large to check safely', itemId: words.ruleId };
120
+ if (enforce)
121
+ return { check: blockCheck(rule, words.blockedRecord), wouldHave: [], ruleIds: [words.ruleId] };
122
+ return {
123
+ check: warnCheck(rule, words.monitorRecord),
124
+ wouldHave: snapshot.wouldActions ? [{ policyId: rule.policyId, policyName: rule.policyName, verdict: 'block', matchedRule: rule.itemId }] : [],
125
+ ruleIds: [words.ruleId],
126
+ };
127
+ }
128
+ const options = {
129
+ disabledBuiltInItemIds: snapshot.disabledBuiltInItemIds,
130
+ itemActions: snapshot.itemActions,
131
+ snapshotPresent: true,
132
+ customBlocks: snapshot.customBlocks,
133
+ policyHash: snapshot.policyHash,
134
+ ...(mcpServerName ? { mcpServerName } : {}),
135
+ // As on the server: no filesystem reads, no decoys.
136
+ inspectScripts: false,
137
+ };
138
+ const outcome = (0, deterministicGuard_1.resolveDeterministicOutcome)((opts) => (0, deterministicGuard_1.scanDeterministicToolCall)(call.toolName, call.toolArgs, opts), options);
139
+ const ruleIds = [
140
+ ...(outcome.blockingFinding ? [outcome.blockingFinding.ruleId] : []),
141
+ ...(outcome.askFindings || []).map((finding) => finding.ruleId),
142
+ ...outcome.warnings.map((finding) => finding.ruleId),
143
+ ];
144
+ if (!enforce) {
145
+ const findings = [
146
+ ...(outcome.blockingFinding ? [outcome.blockingFinding] : []),
147
+ ...(outcome.askFindings || []),
148
+ ...outcome.warnings,
149
+ ];
150
+ if (findings.length === 0)
151
+ return NO_FINDING;
152
+ const rule = ruleRef(snapshot, findings[0]);
153
+ return {
154
+ check: warnCheck(rule, `Built-in safety rule "${rule.policyName}" (warn only here): ${stripStop(findings[0].reason)}`),
155
+ wouldHave: findings.map((finding) => wouldMatch(snapshot, finding, input.wouldManagerIds)).filter((match) => Boolean(match)),
156
+ ruleIds,
157
+ };
158
+ }
159
+ if (outcome.blockingFinding) {
160
+ const finding = outcome.blockingFinding;
161
+ const rule = ruleRef(snapshot, finding);
162
+ const masked = (finding.action || 'block') === 'mask';
163
+ return {
164
+ check: blockCheck(rule, `Built-in safety rule "${rule.policyName}": ${stripStop(finding.reason)}${masked ? ' (set to Mask, which cannot rewrite a tool call, so it stops it)' : ''}`),
165
+ wouldHave: [],
166
+ ruleIds,
167
+ };
168
+ }
169
+ if (outcome.askFinding) {
170
+ const managerIds = managerApprovalRuleIds(snapshot);
171
+ const managerFinding = (outcome.askFindings || []).find((finding) => managerIds.has(finding.itemId));
172
+ const manager = managerFinding ? localSafetyManagerApproval(snapshot, managerFinding.itemId) : undefined;
173
+ if (manager) {
174
+ const check = localSafetyApprovalCheck(manager);
175
+ return { check: { ...check, reason: `Built-in safety rule "${manager.policyName}" needs a manager's OK before this runs` }, wouldHave: [], ruleIds };
176
+ }
177
+ const finding = (outcome.askFindings || [])[0] || outcome.askFinding;
178
+ const rule = ruleRef(snapshot, finding);
179
+ return {
180
+ check: blockCheck(rule, `Built-in safety rule "${rule.policyName}" asks the developer; an AI agent with the SDK in its code has nobody to answer, so it is stopped: ${stripStop(finding.reason)}`),
181
+ wouldHave: [],
182
+ ruleIds,
183
+ };
184
+ }
185
+ if (outcome.warnings.length === 0)
186
+ return NO_FINDING;
187
+ const first = outcome.warnings[0];
188
+ const rule = ruleRef(snapshot, first);
189
+ return { check: warnCheck(rule, `Built-in safety rule "${rule.policyName}" (warn only): ${stripStop(first.reason)}`), wouldHave: [], ruleIds };
190
+ }
191
+ function localSafetyFailure(stage, error) {
192
+ if (stage === 'off')
193
+ return NO_FINDING;
194
+ const message = error instanceof Error ? error.message : String(error);
195
+ const rule = { policyId: `${exports.LOCAL_SAFETY_RULE_PREFIX}check-failed`, policyName: 'Built-in safety rules could not run', itemId: 'check-failed' };
196
+ const reason = `The built-in safety rules could not check this tool call (${message.slice(0, 160)})`;
197
+ return stage === 'enforce'
198
+ ? { check: blockCheck(rule, `${reason}; it is stopped`), wouldHave: [], ruleIds: [rule.itemId] }
199
+ : { check: warnCheck(rule, `${reason}; recorded only (the rules only warn here)`), wouldHave: [], ruleIds: [rule.itemId] };
200
+ }
201
+ /** The action-policy result with the built-in safety rules folded in (the gate's order; the strictest decides). */
202
+ function withLocalSafety(actionPolicy, outcome) {
203
+ const monitorMatches = [...outcome.wouldHave, ...(actionPolicy.monitorMatches || [])];
204
+ const withMonitor = (result) => {
205
+ const rest = { ...result };
206
+ delete rest.monitorMatches;
207
+ return monitorMatches.length > 0 ? { ...rest, monitorMatches } : rest;
208
+ };
209
+ const check = outcome.check;
210
+ if (!check)
211
+ return outcome.wouldHave.length > 0 ? withMonitor(actionPolicy) : actionPolicy;
212
+ if (check.verdict === 'block')
213
+ return withMonitor(check);
214
+ if (check.verdict === 'require_approval') {
215
+ const policyHolds = actionPolicy.verdict === 'block'
216
+ || (actionPolicy.verdict === 'require_approval' && actionPolicy.approval?.scope !== 'developer');
217
+ return withMonitor(policyHolds ? actionPolicy : check);
218
+ }
219
+ return withMonitor(actionPolicy.verdict === 'allow' ? check : actionPolicy);
220
+ }