instar 0.9.13 → 0.9.14

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.
Files changed (40) hide show
  1. package/dist/commands/server.d.ts.map +1 -1
  2. package/dist/commands/server.js +16 -1
  3. package/dist/commands/server.js.map +1 -1
  4. package/dist/core/AdaptiveTrust.d.ts +180 -0
  5. package/dist/core/AdaptiveTrust.d.ts.map +1 -0
  6. package/dist/core/AdaptiveTrust.js +335 -0
  7. package/dist/core/AdaptiveTrust.js.map +1 -0
  8. package/dist/core/AutoUpdater.d.ts +10 -0
  9. package/dist/core/AutoUpdater.d.ts.map +1 -1
  10. package/dist/core/AutoUpdater.js +34 -0
  11. package/dist/core/AutoUpdater.js.map +1 -1
  12. package/dist/core/ExternalOperationGate.d.ts +204 -0
  13. package/dist/core/ExternalOperationGate.d.ts.map +1 -0
  14. package/dist/core/ExternalOperationGate.js +410 -0
  15. package/dist/core/ExternalOperationGate.js.map +1 -0
  16. package/dist/core/MessageSentinel.d.ts +116 -0
  17. package/dist/core/MessageSentinel.d.ts.map +1 -0
  18. package/dist/core/MessageSentinel.js +359 -0
  19. package/dist/core/MessageSentinel.js.map +1 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/lifeline/ServerSupervisor.d.ts +11 -0
  25. package/dist/lifeline/ServerSupervisor.d.ts.map +1 -1
  26. package/dist/lifeline/ServerSupervisor.js +57 -0
  27. package/dist/lifeline/ServerSupervisor.js.map +1 -1
  28. package/dist/lifeline/TelegramLifeline.d.ts.map +1 -1
  29. package/dist/lifeline/TelegramLifeline.js +1 -0
  30. package/dist/lifeline/TelegramLifeline.js.map +1 -1
  31. package/dist/server/AgentServer.d.ts +3 -0
  32. package/dist/server/AgentServer.d.ts.map +1 -1
  33. package/dist/server/AgentServer.js +3 -0
  34. package/dist/server/AgentServer.js.map +1 -1
  35. package/dist/server/routes.d.ts +6 -0
  36. package/dist/server/routes.d.ts.map +1 -1
  37. package/dist/server/routes.js +142 -0
  38. package/dist/server/routes.js.map +1 -1
  39. package/package.json +1 -1
  40. package/upgrades/0.9.14.md +23 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * External Operation Gate — LLM-supervised safety for external service operations.
3
+ *
4
+ * Born from the OpenClaw email deletion incident (2026-02-25): An agent deleted
5
+ * 200+ emails autonomously, ignoring repeated "stop" commands, because nothing
6
+ * distinguished safe operations (read email) from destructive ones (delete 200 emails).
7
+ *
8
+ * Design principle: Structure > Willpower. A memory.md rule saying "don't delete
9
+ * emails without approval" degrades as context grows. A gate that physically
10
+ * intercepts the operation and evaluates risk does not.
11
+ *
12
+ * Three layers:
13
+ * 1. Static classification — operation type × reversibility × scope → risk level
14
+ * 2. Config permissions — per-service allow/block lists (structural floor)
15
+ * 3. LLM evaluation — for medium+ risk, a haiku-tier model evaluates proportionality
16
+ *
17
+ * Integrates with AdaptiveTrust for organic permission evolution.
18
+ */
19
+ import type { IntelligenceProvider } from './types.js';
20
+ export type OperationMutability = 'read' | 'write' | 'modify' | 'delete';
21
+ export type OperationReversibility = 'reversible' | 'partially-reversible' | 'irreversible';
22
+ export type OperationScope = 'single' | 'batch' | 'bulk';
23
+ export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
24
+ export type GateAction = 'proceed' | 'show-plan' | 'suggest-alternative' | 'block';
25
+ export type TrustLevel = 'blocked' | 'approve-always' | 'approve-first' | 'log' | 'autonomous';
26
+ export type TrustSource = 'default' | 'config' | 'user-explicit' | 'earned' | 'revoked';
27
+ export type AutonomyBehavior = 'proceed' | 'log' | 'approve' | 'block';
28
+ export interface OperationClassification {
29
+ /** What the operation does */
30
+ mutability: OperationMutability;
31
+ /** Whether it can be undone */
32
+ reversibility: OperationReversibility;
33
+ /** How many items affected */
34
+ scope: OperationScope;
35
+ /** Computed risk level */
36
+ riskLevel: RiskLevel;
37
+ /** External service name */
38
+ service: string;
39
+ /** Human-readable description */
40
+ description: string;
41
+ /** Number of items affected (if known) */
42
+ itemCount?: number;
43
+ }
44
+ export interface GateDecision {
45
+ /** What the gate recommends */
46
+ action: GateAction;
47
+ /** Why this decision was made */
48
+ reason: string;
49
+ /** The operation classification that led to this decision */
50
+ classification: OperationClassification;
51
+ /** If show-plan: what to present to user */
52
+ plan?: string;
53
+ /** If suggest-alternative: safer approach */
54
+ alternative?: string;
55
+ /** If batch/bulk: checkpoint config */
56
+ checkpoint?: CheckpointConfig;
57
+ /** Whether LLM was consulted */
58
+ llmEvaluated: boolean;
59
+ /** Timestamp */
60
+ evaluatedAt: string;
61
+ }
62
+ export interface CheckpointConfig {
63
+ /** Pause after this many items */
64
+ afterCount: number;
65
+ /** Total items expected */
66
+ totalExpected: number;
67
+ /** Items completed so far */
68
+ completedSoFar: number;
69
+ }
70
+ export interface ServicePermissions {
71
+ /** Operations the agent CAN perform */
72
+ permissions: OperationMutability[];
73
+ /** Operations that are HARD BLOCKED (no override, no trust escalation) */
74
+ blocked?: OperationMutability[];
75
+ /** Maximum batch size before requiring checkpoint */
76
+ batchLimit?: number;
77
+ /** Operations that always require approval regardless of trust */
78
+ requireApproval?: OperationMutability[];
79
+ }
80
+ export interface ExternalOperationGateConfig {
81
+ /** State directory for operation logs and trust data */
82
+ stateDir: string;
83
+ /** Intelligence provider for LLM evaluation (haiku-tier recommended) */
84
+ intelligence?: IntelligenceProvider;
85
+ /** Per-service permissions */
86
+ services?: Record<string, ServicePermissions>;
87
+ /** Services that are fully blocked */
88
+ blockedServices?: string[];
89
+ /** Services that are read-only */
90
+ readOnlyServices?: string[];
91
+ /** Batch checkpoint configuration */
92
+ batchCheckpoint?: {
93
+ /** Items before first checkpoint (default: 5) */
94
+ batchThreshold: number;
95
+ /** Items considered "bulk" (default: 20) */
96
+ bulkThreshold: number;
97
+ /** Checkpoint interval for bulk operations (default: 10) */
98
+ checkpointEvery: number;
99
+ };
100
+ /** Autonomy gradient — default behavior per risk level */
101
+ autonomyDefaults?: Record<RiskLevel, AutonomyBehavior>;
102
+ }
103
+ export interface OperationLogEntry {
104
+ /** ISO timestamp */
105
+ timestamp: string;
106
+ /** The operation that was evaluated */
107
+ classification: OperationClassification;
108
+ /** The gate's decision */
109
+ decision: GateAction;
110
+ /** Whether the user approved (if approval was requested) */
111
+ userApproved?: boolean;
112
+ /** Whether the operation completed successfully */
113
+ succeeded?: boolean;
114
+ }
115
+ /** Autonomy profiles for the three standard levels */
116
+ export declare const AUTONOMY_PROFILES: Record<string, Record<RiskLevel, AutonomyBehavior>>;
117
+ /**
118
+ * Compute risk level from operation dimensions.
119
+ *
120
+ * The matrix follows the principle: irreversible + bulk = critical,
121
+ * read operations are always low, and risk escalates with scope.
122
+ */
123
+ export declare function computeRiskLevel(mutability: OperationMutability, reversibility: OperationReversibility, scope: OperationScope): RiskLevel;
124
+ /**
125
+ * Determine scope from item count.
126
+ */
127
+ export declare function scopeFromCount(count: number, config?: {
128
+ batchThreshold?: number;
129
+ bulkThreshold?: number;
130
+ }): OperationScope;
131
+ export declare class ExternalOperationGate {
132
+ private config;
133
+ private logPath;
134
+ constructor(config: ExternalOperationGateConfig);
135
+ /**
136
+ * Classify an external operation into its risk dimensions.
137
+ */
138
+ classify(params: {
139
+ service: string;
140
+ mutability: OperationMutability;
141
+ reversibility: OperationReversibility;
142
+ description: string;
143
+ itemCount?: number;
144
+ }): OperationClassification;
145
+ /**
146
+ * Evaluate an operation through the full gate pipeline.
147
+ *
148
+ * Pipeline:
149
+ * 1. Check if service is fully blocked → block
150
+ * 2. Check if service is read-only and operation mutates → block
151
+ * 3. Check per-service permission config → block if operation type blocked
152
+ * 4. Classify operation risk
153
+ * 5. Check autonomy gradient for this risk level
154
+ * 6. For medium+ risk with intelligence provider, consult LLM
155
+ * 7. Check batch limits and add checkpoint if needed
156
+ * 8. Return final decision
157
+ */
158
+ evaluate(params: {
159
+ service: string;
160
+ mutability: OperationMutability;
161
+ reversibility: OperationReversibility;
162
+ description: string;
163
+ itemCount?: number;
164
+ /** The user's original request (for LLM proportionality check) */
165
+ userRequest?: string;
166
+ }): Promise<GateDecision>;
167
+ /**
168
+ * Consult LLM for proportionality evaluation.
169
+ *
170
+ * IMPORTANT: The LLM never sees the content being operated on.
171
+ * This prevents prompt injection via email body, calendar event, etc.
172
+ * The LLM only sees: what operation, what scope, what the user asked for.
173
+ */
174
+ private consultLLM;
175
+ /**
176
+ * Build a human-readable plan for the user.
177
+ */
178
+ private buildPlan;
179
+ /**
180
+ * Log an operation evaluation to the JSONL log.
181
+ */
182
+ private logOperation;
183
+ /**
184
+ * Read recent operation log entries.
185
+ */
186
+ getOperationLog(limit?: number): OperationLogEntry[];
187
+ /**
188
+ * Get the effective service permissions (config + defaults).
189
+ */
190
+ getServicePermissions(service: string): ServicePermissions | null;
191
+ /**
192
+ * Get the current autonomy profile.
193
+ */
194
+ getAutonomyProfile(): Record<RiskLevel, AutonomyBehavior>;
195
+ /**
196
+ * Update autonomy defaults (used by AdaptiveTrust when trust changes).
197
+ */
198
+ updateAutonomyDefaults(defaults: Record<RiskLevel, AutonomyBehavior>): void;
199
+ /**
200
+ * Update service permissions at runtime.
201
+ */
202
+ updateServicePermissions(service: string, permissions: ServicePermissions): void;
203
+ }
204
+ //# sourceMappingURL=ExternalOperationGate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExternalOperationGate.d.ts","sourceRoot":"","sources":["../../src/core/ExternalOperationGate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAIvD,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC;AACzE,MAAM,MAAM,sBAAsB,GAAG,YAAY,GAAG,sBAAsB,GAAG,cAAc,CAAC;AAC5F,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,CAAC;AACzD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;OAEG;IACH,eAAe,CAAC,KAAK,SAAK,GAAG,iBAAiB,EAAE;IAgBhD;;OAEG;IACH,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,kBAAkB,GAAG,IAAI;IAYjE;;OAEG;IACH,kBAAkB,IAAI,MAAM,CAAC,SAAS,EAAE,gBAAgB,CAAC;IAIzD;;OAEG;IACH,sBAAsB,CAAC,QAAQ,EAAE,MAAM,CAAC,SAAS,EAAE,gBAAgB,CAAC,GAAG,IAAI;IAI3E;;OAEG;IACH,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,kBAAkB,GAAG,IAAI;CAMjF"}
@@ -0,0 +1,410 @@
1
+ /**
2
+ * External Operation Gate — LLM-supervised safety for external service operations.
3
+ *
4
+ * Born from the OpenClaw email deletion incident (2026-02-25): An agent deleted
5
+ * 200+ emails autonomously, ignoring repeated "stop" commands, because nothing
6
+ * distinguished safe operations (read email) from destructive ones (delete 200 emails).
7
+ *
8
+ * Design principle: Structure > Willpower. A memory.md rule saying "don't delete
9
+ * emails without approval" degrades as context grows. A gate that physically
10
+ * intercepts the operation and evaluates risk does not.
11
+ *
12
+ * Three layers:
13
+ * 1. Static classification — operation type × reversibility × scope → risk level
14
+ * 2. Config permissions — per-service allow/block lists (structural floor)
15
+ * 3. LLM evaluation — for medium+ risk, a haiku-tier model evaluates proportionality
16
+ *
17
+ * Integrates with AdaptiveTrust for organic permission evolution.
18
+ */
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ // ── Constants ────────────────────────────────────────────────────────
22
+ /** Default autonomy behaviors per risk level (collaborative profile) */
23
+ const DEFAULT_AUTONOMY = {
24
+ low: 'proceed',
25
+ medium: 'log',
26
+ high: 'approve',
27
+ critical: 'approve',
28
+ };
29
+ /** Autonomy profiles for the three standard levels */
30
+ export const AUTONOMY_PROFILES = {
31
+ supervised: { low: 'log', medium: 'approve', high: 'approve', critical: 'block' },
32
+ collaborative: { low: 'proceed', medium: 'log', high: 'approve', critical: 'approve' },
33
+ autonomous: { low: 'proceed', medium: 'proceed', high: 'log', critical: 'approve' },
34
+ };
35
+ const DEFAULT_BATCH_CONFIG = {
36
+ batchThreshold: 5,
37
+ bulkThreshold: 20,
38
+ checkpointEvery: 10,
39
+ };
40
+ // ── Risk Matrix ──────────────────────────────────────────────────────
41
+ /**
42
+ * Compute risk level from operation dimensions.
43
+ *
44
+ * The matrix follows the principle: irreversible + bulk = critical,
45
+ * read operations are always low, and risk escalates with scope.
46
+ */
47
+ export function computeRiskLevel(mutability, reversibility, scope) {
48
+ // Reads are always low risk
49
+ if (mutability === 'read')
50
+ return 'low';
51
+ // Bulk irreversible = always critical
52
+ if (scope === 'bulk' && reversibility === 'irreversible')
53
+ return 'critical';
54
+ // Bulk deletes = critical regardless of reversibility
55
+ if (scope === 'bulk' && mutability === 'delete')
56
+ return 'critical';
57
+ // Any irreversible bulk = critical
58
+ if (scope === 'bulk')
59
+ return 'critical';
60
+ // Batch deletes = high
61
+ if (scope === 'batch' && mutability === 'delete')
62
+ return 'high';
63
+ // Batch irreversible = high
64
+ if (scope === 'batch' && reversibility === 'irreversible')
65
+ return 'high';
66
+ // Single deletes = medium-to-high based on reversibility
67
+ if (mutability === 'delete' && reversibility === 'irreversible')
68
+ return 'high';
69
+ if (mutability === 'delete')
70
+ return 'medium';
71
+ // Single irreversible writes/modifies = medium
72
+ if (reversibility === 'irreversible')
73
+ return 'medium';
74
+ // Batch reversible writes/modifies = medium
75
+ if (scope === 'batch')
76
+ return 'medium';
77
+ // Single reversible writes/modifies = low
78
+ return 'low';
79
+ }
80
+ /**
81
+ * Determine scope from item count.
82
+ */
83
+ export function scopeFromCount(count, config) {
84
+ const batch = config?.batchThreshold ?? DEFAULT_BATCH_CONFIG.batchThreshold;
85
+ const bulk = config?.bulkThreshold ?? DEFAULT_BATCH_CONFIG.bulkThreshold;
86
+ if (count <= 1)
87
+ return 'single';
88
+ if (count <= bulk)
89
+ return 'batch';
90
+ return 'bulk';
91
+ }
92
+ // ── Gate Implementation ──────────────────────────────────────────────
93
+ export class ExternalOperationGate {
94
+ config;
95
+ logPath;
96
+ constructor(config) {
97
+ this.config = config;
98
+ this.logPath = path.join(config.stateDir, 'state', 'operation-log.jsonl');
99
+ }
100
+ /**
101
+ * Classify an external operation into its risk dimensions.
102
+ */
103
+ classify(params) {
104
+ const scope = scopeFromCount(params.itemCount ?? 1, this.config.batchCheckpoint);
105
+ const riskLevel = computeRiskLevel(params.mutability, params.reversibility, scope);
106
+ return {
107
+ mutability: params.mutability,
108
+ reversibility: params.reversibility,
109
+ scope,
110
+ riskLevel,
111
+ service: params.service,
112
+ description: params.description,
113
+ itemCount: params.itemCount,
114
+ };
115
+ }
116
+ /**
117
+ * Evaluate an operation through the full gate pipeline.
118
+ *
119
+ * Pipeline:
120
+ * 1. Check if service is fully blocked → block
121
+ * 2. Check if service is read-only and operation mutates → block
122
+ * 3. Check per-service permission config → block if operation type blocked
123
+ * 4. Classify operation risk
124
+ * 5. Check autonomy gradient for this risk level
125
+ * 6. For medium+ risk with intelligence provider, consult LLM
126
+ * 7. Check batch limits and add checkpoint if needed
127
+ * 8. Return final decision
128
+ */
129
+ async evaluate(params) {
130
+ const now = new Date().toISOString();
131
+ // Step 1: Check if service is fully blocked
132
+ if (this.config.blockedServices?.includes(params.service)) {
133
+ const classification = this.classify(params);
134
+ return {
135
+ action: 'block',
136
+ reason: `Service "${params.service}" is fully blocked by configuration.`,
137
+ classification,
138
+ llmEvaluated: false,
139
+ evaluatedAt: now,
140
+ };
141
+ }
142
+ // Step 2: Check if service is read-only
143
+ if (this.config.readOnlyServices?.includes(params.service) && params.mutability !== 'read') {
144
+ const classification = this.classify(params);
145
+ return {
146
+ action: 'block',
147
+ reason: `Service "${params.service}" is configured as read-only. ${params.mutability} operations are not allowed.`,
148
+ classification,
149
+ llmEvaluated: false,
150
+ evaluatedAt: now,
151
+ };
152
+ }
153
+ // Step 3: Check per-service permissions
154
+ const serviceConfig = this.config.services?.[params.service];
155
+ if (serviceConfig) {
156
+ // Check blocked operations
157
+ if (serviceConfig.blocked?.includes(params.mutability)) {
158
+ const classification = this.classify(params);
159
+ return {
160
+ action: 'block',
161
+ reason: `"${params.mutability}" operations are blocked for service "${params.service}" by configuration.`,
162
+ classification,
163
+ llmEvaluated: false,
164
+ evaluatedAt: now,
165
+ };
166
+ }
167
+ // Check if operation is in allowed permissions
168
+ if (serviceConfig.permissions.length > 0 && !serviceConfig.permissions.includes(params.mutability)) {
169
+ const classification = this.classify(params);
170
+ return {
171
+ action: 'block',
172
+ reason: `"${params.mutability}" is not in the allowed permissions for "${params.service}". Allowed: ${serviceConfig.permissions.join(', ')}.`,
173
+ classification,
174
+ llmEvaluated: false,
175
+ evaluatedAt: now,
176
+ };
177
+ }
178
+ }
179
+ // Step 4: Classify
180
+ const classification = this.classify(params);
181
+ // Step 5: Check autonomy gradient
182
+ const autonomyDefaults = this.config.autonomyDefaults ?? DEFAULT_AUTONOMY;
183
+ let behavior = autonomyDefaults[classification.riskLevel];
184
+ // Per-service requireApproval override
185
+ if (serviceConfig?.requireApproval?.includes(params.mutability)) {
186
+ if (behavior === 'proceed' || behavior === 'log') {
187
+ behavior = 'approve';
188
+ }
189
+ }
190
+ // Step 6: LLM evaluation for medium+ risk (if available)
191
+ let llmEvaluated = false;
192
+ let llmSuggestion = null;
193
+ if (this.config.intelligence &&
194
+ classification.riskLevel !== 'low' &&
195
+ behavior !== 'block') {
196
+ llmSuggestion = await this.consultLLM(classification, params.userRequest);
197
+ llmEvaluated = true;
198
+ // LLM can escalate (make stricter) but not relax past the config floor
199
+ if (llmSuggestion === 'block' || llmSuggestion === 'show-plan') {
200
+ if (behavior === 'proceed' || behavior === 'log') {
201
+ behavior = 'approve'; // LLM escalated
202
+ }
203
+ }
204
+ }
205
+ // Step 7: Map autonomy behavior to gate action
206
+ let action;
207
+ let reason;
208
+ switch (behavior) {
209
+ case 'proceed':
210
+ action = 'proceed';
211
+ reason = `Risk level "${classification.riskLevel}" allows proceeding under current autonomy settings.`;
212
+ break;
213
+ case 'log':
214
+ action = 'proceed';
215
+ reason = `Risk level "${classification.riskLevel}" allows proceeding with logging under current autonomy settings.`;
216
+ break;
217
+ case 'approve':
218
+ action = 'show-plan';
219
+ reason = `Risk level "${classification.riskLevel}" requires approval under current autonomy settings.`;
220
+ break;
221
+ case 'block':
222
+ action = 'block';
223
+ reason = `Risk level "${classification.riskLevel}" is blocked under current autonomy settings.`;
224
+ break;
225
+ }
226
+ // Override with LLM suggestion if it provided an alternative
227
+ if (llmSuggestion === 'suggest-alternative') {
228
+ action = 'suggest-alternative';
229
+ reason = 'LLM evaluation suggests a safer alternative approach.';
230
+ }
231
+ // Step 8: Add checkpoint for batch/bulk operations
232
+ let checkpoint;
233
+ if (classification.scope !== 'single' && action !== 'block') {
234
+ const batchConfig = this.config.batchCheckpoint ?? DEFAULT_BATCH_CONFIG;
235
+ const itemCount = params.itemCount ?? 0;
236
+ if (classification.scope === 'batch') {
237
+ checkpoint = {
238
+ afterCount: batchConfig.batchThreshold,
239
+ totalExpected: itemCount,
240
+ completedSoFar: 0,
241
+ };
242
+ }
243
+ else if (classification.scope === 'bulk') {
244
+ checkpoint = {
245
+ afterCount: batchConfig.checkpointEvery,
246
+ totalExpected: itemCount,
247
+ completedSoFar: 0,
248
+ };
249
+ // Bulk operations always require plan even if autonomy says proceed
250
+ if (action === 'proceed') {
251
+ action = 'show-plan';
252
+ reason = `Bulk operations (${itemCount} items) always require a plan before proceeding.`;
253
+ }
254
+ }
255
+ }
256
+ // Build plan text for show-plan actions
257
+ let plan;
258
+ if (action === 'show-plan') {
259
+ plan = this.buildPlan(classification, checkpoint);
260
+ }
261
+ const decision = {
262
+ action,
263
+ reason,
264
+ classification,
265
+ plan,
266
+ checkpoint,
267
+ llmEvaluated,
268
+ evaluatedAt: now,
269
+ };
270
+ // Log the evaluation
271
+ this.logOperation({
272
+ timestamp: now,
273
+ classification,
274
+ decision: action,
275
+ });
276
+ return decision;
277
+ }
278
+ /**
279
+ * Consult LLM for proportionality evaluation.
280
+ *
281
+ * IMPORTANT: The LLM never sees the content being operated on.
282
+ * This prevents prompt injection via email body, calendar event, etc.
283
+ * The LLM only sees: what operation, what scope, what the user asked for.
284
+ */
285
+ async consultLLM(classification, userRequest) {
286
+ if (!this.config.intelligence)
287
+ return 'proceed';
288
+ const prompt = [
289
+ 'You are a safety evaluator for an AI agent\'s external service operations.',
290
+ 'Evaluate whether this operation is proportional and appropriate.',
291
+ '',
292
+ `Service: ${classification.service}`,
293
+ `Operation: ${classification.mutability} (${classification.description})`,
294
+ `Reversibility: ${classification.reversibility}`,
295
+ `Scope: ${classification.scope}${classification.itemCount ? ` (${classification.itemCount} items)` : ''}`,
296
+ `Risk level: ${classification.riskLevel}`,
297
+ '',
298
+ userRequest ? `User's original request: "${userRequest}"` : 'No user request context available.',
299
+ '',
300
+ 'Questions:',
301
+ '1. Does this operation match what the user likely intended?',
302
+ '2. Is the scope proportional to the request?',
303
+ '3. Is there a less destructive way to achieve the same goal?',
304
+ '',
305
+ 'Respond with exactly one word: proceed, show-plan, suggest-alternative, or block.',
306
+ ].join('\n');
307
+ try {
308
+ const response = await this.config.intelligence.evaluate(prompt, {
309
+ maxTokens: 10,
310
+ temperature: 0,
311
+ });
312
+ const cleaned = response.trim().toLowerCase();
313
+ if (['proceed', 'show-plan', 'suggest-alternative', 'block'].includes(cleaned)) {
314
+ return cleaned;
315
+ }
316
+ // If LLM response is unparseable, default to cautious
317
+ return 'show-plan';
318
+ }
319
+ catch {
320
+ // If LLM fails, don't block — fall back to programmatic decision
321
+ return 'proceed';
322
+ }
323
+ }
324
+ /**
325
+ * Build a human-readable plan for the user.
326
+ */
327
+ buildPlan(classification, checkpoint) {
328
+ const lines = [];
329
+ lines.push(`I'd like to ${classification.mutability} on ${classification.service}: ${classification.description}`);
330
+ lines.push('');
331
+ lines.push(`Risk: ${classification.riskLevel} (${classification.reversibility}, ${classification.scope})`);
332
+ if (classification.itemCount) {
333
+ lines.push(`Items affected: ${classification.itemCount}`);
334
+ }
335
+ if (checkpoint) {
336
+ lines.push('');
337
+ lines.push(`I'll check in after every ${checkpoint.afterCount} items with a progress report.`);
338
+ }
339
+ lines.push('');
340
+ lines.push('Approve to proceed, or tell me to adjust the approach.');
341
+ return lines.join('\n');
342
+ }
343
+ /**
344
+ * Log an operation evaluation to the JSONL log.
345
+ */
346
+ logOperation(entry) {
347
+ try {
348
+ const dir = path.dirname(this.logPath);
349
+ if (!fs.existsSync(dir)) {
350
+ fs.mkdirSync(dir, { recursive: true });
351
+ }
352
+ fs.appendFileSync(this.logPath, JSON.stringify(entry) + '\n');
353
+ }
354
+ catch {
355
+ // Logging should never break the gate
356
+ }
357
+ }
358
+ /**
359
+ * Read recent operation log entries.
360
+ */
361
+ getOperationLog(limit = 50) {
362
+ if (!fs.existsSync(this.logPath))
363
+ return [];
364
+ try {
365
+ const lines = fs.readFileSync(this.logPath, 'utf-8')
366
+ .split('\n')
367
+ .filter(Boolean);
368
+ return lines
369
+ .slice(-limit)
370
+ .map(line => JSON.parse(line));
371
+ }
372
+ catch {
373
+ return [];
374
+ }
375
+ }
376
+ /**
377
+ * Get the effective service permissions (config + defaults).
378
+ */
379
+ getServicePermissions(service) {
380
+ if (this.config.blockedServices?.includes(service)) {
381
+ return { permissions: [], blocked: ['read', 'write', 'modify', 'delete'] };
382
+ }
383
+ if (this.config.readOnlyServices?.includes(service)) {
384
+ return { permissions: ['read'], blocked: ['write', 'modify', 'delete'] };
385
+ }
386
+ return this.config.services?.[service] ?? null;
387
+ }
388
+ /**
389
+ * Get the current autonomy profile.
390
+ */
391
+ getAutonomyProfile() {
392
+ return this.config.autonomyDefaults ?? DEFAULT_AUTONOMY;
393
+ }
394
+ /**
395
+ * Update autonomy defaults (used by AdaptiveTrust when trust changes).
396
+ */
397
+ updateAutonomyDefaults(defaults) {
398
+ this.config.autonomyDefaults = defaults;
399
+ }
400
+ /**
401
+ * Update service permissions at runtime.
402
+ */
403
+ updateServicePermissions(service, permissions) {
404
+ if (!this.config.services) {
405
+ this.config.services = {};
406
+ }
407
+ this.config.services[service] = permissions;
408
+ }
409
+ }
410
+ //# sourceMappingURL=ExternalOperationGate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExternalOperationGate.js","sourceRoot":"","sources":["../../src/core/ExternalOperationGate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AA2G7B,wEAAwE;AAExE,wEAAwE;AACxE,MAAM,gBAAgB,GAAwC;IAC5D,GAAG,EAAE,SAAS;IACd,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,SAAS;IACf,QAAQ,EAAE,SAAS;CACpB,CAAC;AAEF,sDAAsD;AACtD,MAAM,CAAC,MAAM,iBAAiB,GAAwD;IACpF,UAAU,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;IACjF,aAAa,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE;IACtF,UAAU,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE;CACpF,CAAC;AAEF,MAAM,oBAAoB,GAAG;IAC3B,cAAc,EAAE,CAAC;IACjB,aAAa,EAAE,EAAE;IACjB,eAAe,EAAE,EAAE;CACpB,CAAC;AAEF,wEAAwE;AAExE;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAC9B,UAA+B,EAC/B,aAAqC,EACrC,KAAqB;IAErB,4BAA4B;IAC5B,IAAI,UAAU,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IAExC,sCAAsC;IACtC,IAAI,KAAK,KA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