@neuroverseos/governance 0.3.0 → 0.3.1

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 (105) hide show
  1. package/README.md +20 -0
  2. package/package.json +16 -3
  3. package/policies/content-moderation-rules.txt +8 -0
  4. package/policies/marketing-rules.txt +8 -0
  5. package/policies/science-research-rules.txt +11 -0
  6. package/policies/social-media-rules.txt +7 -0
  7. package/policies/strict-rules.txt +8 -0
  8. package/policies/trading-rules.txt +8 -0
  9. package/simulate.html +1899 -0
  10. package/dist/adapters/autoresearch.cjs +0 -196
  11. package/dist/adapters/autoresearch.d.cts +0 -103
  12. package/dist/adapters/autoresearch.d.ts +0 -103
  13. package/dist/adapters/autoresearch.js +0 -7
  14. package/dist/adapters/express.cjs +0 -1114
  15. package/dist/adapters/express.d.cts +0 -66
  16. package/dist/adapters/express.d.ts +0 -66
  17. package/dist/adapters/express.js +0 -12
  18. package/dist/adapters/index.cjs +0 -1669
  19. package/dist/adapters/index.d.cts +0 -6
  20. package/dist/adapters/index.d.ts +0 -6
  21. package/dist/adapters/index.js +0 -46
  22. package/dist/adapters/langchain.cjs +0 -1155
  23. package/dist/adapters/langchain.d.cts +0 -89
  24. package/dist/adapters/langchain.d.ts +0 -89
  25. package/dist/adapters/langchain.js +0 -16
  26. package/dist/adapters/openai.cjs +0 -1185
  27. package/dist/adapters/openai.d.cts +0 -99
  28. package/dist/adapters/openai.d.ts +0 -99
  29. package/dist/adapters/openai.js +0 -16
  30. package/dist/adapters/openclaw.cjs +0 -1177
  31. package/dist/adapters/openclaw.d.cts +0 -99
  32. package/dist/adapters/openclaw.d.ts +0 -99
  33. package/dist/adapters/openclaw.js +0 -16
  34. package/dist/bootstrap-GXVDZNF7.js +0 -114
  35. package/dist/build-P42YFKQV.js +0 -339
  36. package/dist/chunk-2NICNKOM.js +0 -100
  37. package/dist/chunk-2PQU3VAN.js +0 -131
  38. package/dist/chunk-4A7LISES.js +0 -324
  39. package/dist/chunk-4JRYGIO7.js +0 -727
  40. package/dist/chunk-4NGDRRQH.js +0 -10
  41. package/dist/chunk-4QXB6PEO.js +0 -232
  42. package/dist/chunk-6CZSKEY5.js +0 -164
  43. package/dist/chunk-7P3S7MAY.js +0 -1090
  44. package/dist/chunk-A5W4GNQO.js +0 -130
  45. package/dist/chunk-AKW5YVCE.js +0 -96
  46. package/dist/chunk-BUWWN2NX.js +0 -192
  47. package/dist/chunk-COT5XS4V.js +0 -109
  48. package/dist/chunk-ER62HNGF.js +0 -139
  49. package/dist/chunk-FYS2CBUW.js +0 -304
  50. package/dist/chunk-GR6DGCZ2.js +0 -340
  51. package/dist/chunk-I3RRAYK2.js +0 -11
  52. package/dist/chunk-JZPQGIKR.js +0 -79
  53. package/dist/chunk-MWDQ4MJB.js +0 -11
  54. package/dist/chunk-NF5POFCI.js +0 -622
  55. package/dist/chunk-OGL7QXZS.js +0 -608
  56. package/dist/chunk-OT6PXH54.js +0 -61
  57. package/dist/chunk-PDOZHZWL.js +0 -225
  58. package/dist/chunk-Q6O7ZLO2.js +0 -62
  59. package/dist/chunk-QPASI2BR.js +0 -187
  60. package/dist/chunk-T5EUJQE5.js +0 -172
  61. package/dist/chunk-XPDMYECO.js +0 -642
  62. package/dist/chunk-YZFATT7X.js +0 -9
  63. package/dist/cli/neuroverse.cjs +0 -11448
  64. package/dist/cli/neuroverse.d.cts +0 -1
  65. package/dist/cli/neuroverse.d.ts +0 -1
  66. package/dist/cli/neuroverse.js +0 -196
  67. package/dist/cli/plan.cjs +0 -1599
  68. package/dist/cli/plan.d.cts +0 -20
  69. package/dist/cli/plan.d.ts +0 -20
  70. package/dist/cli/plan.js +0 -361
  71. package/dist/cli/run.cjs +0 -1746
  72. package/dist/cli/run.d.cts +0 -20
  73. package/dist/cli/run.d.ts +0 -20
  74. package/dist/cli/run.js +0 -143
  75. package/dist/configure-ai-TK67ZWZL.js +0 -132
  76. package/dist/derive-TLIV4OOU.js +0 -152
  77. package/dist/doctor-XPDLEYXN.js +0 -171
  78. package/dist/explain-IDCRWMPX.js +0 -70
  79. package/dist/guard-RV65TT4L.js +0 -96
  80. package/dist/guard-contract-WZx__PmU.d.cts +0 -709
  81. package/dist/guard-contract-WZx__PmU.d.ts +0 -709
  82. package/dist/guard-engine-JLTUARGU.js +0 -10
  83. package/dist/impact-XPECYRLH.js +0 -59
  84. package/dist/improve-GPUBKTEA.js +0 -85
  85. package/dist/index.cjs +0 -6273
  86. package/dist/index.d.cts +0 -1616
  87. package/dist/index.d.ts +0 -1616
  88. package/dist/index.js +0 -379
  89. package/dist/infer-world-7GVZWFX4.js +0 -543
  90. package/dist/init-PKPIYHYE.js +0 -144
  91. package/dist/init-world-VWMQZQC7.js +0 -223
  92. package/dist/mcp-server-FPVSU32Z.js +0 -13
  93. package/dist/model-adapter-BB7G4MFI.js +0 -11
  94. package/dist/playground-E664U4T6.js +0 -550
  95. package/dist/redteam-Z7WREJ44.js +0 -357
  96. package/dist/session-EKTRSR7C.js +0 -14
  97. package/dist/simulate-VDOYQFRO.js +0 -108
  98. package/dist/test-OGXJK4QU.js +0 -217
  99. package/dist/trace-JVF67VR3.js +0 -166
  100. package/dist/validate-LLBWVPGV.js +0 -81
  101. package/dist/validate-engine-UIABSIHD.js +0 -7
  102. package/dist/world-LAXO6DOX.js +0 -378
  103. package/dist/world-loader-HMPTOEA2.js +0 -9
  104. package/dist/worlds/autoresearch.nv-world.md +0 -230
  105. package/dist/worlds/derivation-world.nv-world.md +0 -278
@@ -1,1185 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/adapters/openai.ts
31
- var openai_exports = {};
32
- __export(openai_exports, {
33
- GovernanceBlockedError: () => GovernanceBlockedError,
34
- GovernedToolExecutor: () => GovernedToolExecutor,
35
- createGovernedToolExecutor: () => createGovernedToolExecutor,
36
- createGovernedToolExecutorFromWorld: () => createGovernedToolExecutorFromWorld
37
- });
38
- module.exports = __toCommonJS(openai_exports);
39
-
40
- // src/engine/plan-engine.ts
41
- function keywordMatch(eventText, step) {
42
- const stepText = [
43
- step.label,
44
- step.description ?? "",
45
- ...step.tags ?? []
46
- ].join(" ").toLowerCase();
47
- const keywords = stepText.split(/\s+/).filter((w) => w.length > 3);
48
- if (keywords.length === 0) return false;
49
- const matched = keywords.filter((kw) => eventText.includes(kw));
50
- return matched.length >= Math.ceil(keywords.length * 0.5);
51
- }
52
- function tokenSimilarity(a, b) {
53
- const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
54
- const tokensB = new Set(b.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
55
- if (tokensA.size === 0 || tokensB.size === 0) return 0;
56
- let intersection = 0;
57
- for (const t of tokensA) {
58
- if (tokensB.has(t)) intersection++;
59
- }
60
- const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
61
- return union > 0 ? intersection / union : 0;
62
- }
63
- function findMatchingStep(eventText, event, steps) {
64
- const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
65
- if (pendingOrActive.length === 0) {
66
- return { matched: null, closest: null, closestScore: 0 };
67
- }
68
- for (const step of pendingOrActive) {
69
- if (keywordMatch(eventText, step)) {
70
- if (step.tools && event.tool && !step.tools.includes(event.tool)) {
71
- continue;
72
- }
73
- return { matched: step, closest: step, closestScore: 1 };
74
- }
75
- }
76
- const intentText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ");
77
- let bestStep = null;
78
- let bestScore = 0;
79
- for (const step of pendingOrActive) {
80
- const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
81
- const score = tokenSimilarity(intentText, stepText);
82
- if (score > bestScore) {
83
- bestScore = score;
84
- bestStep = step;
85
- }
86
- }
87
- const SIMILARITY_THRESHOLD = 0.35;
88
- if (bestScore >= SIMILARITY_THRESHOLD && bestStep) {
89
- if (bestStep.tools && event.tool && !bestStep.tools.includes(event.tool)) {
90
- return { matched: null, closest: bestStep, closestScore: bestScore };
91
- }
92
- return { matched: bestStep, closest: bestStep, closestScore: bestScore };
93
- }
94
- return { matched: null, closest: bestStep, closestScore: bestScore };
95
- }
96
- function isSequenceValid(step, plan) {
97
- if (!plan.sequential) return true;
98
- if (!step.requires || step.requires.length === 0) return true;
99
- return step.requires.every((reqId) => {
100
- const reqStep = plan.steps.find((s) => s.id === reqId);
101
- return reqStep?.status === "completed";
102
- });
103
- }
104
- function checkConstraints(event, eventText, constraints) {
105
- const checks = [];
106
- for (const constraint of constraints) {
107
- if (constraint.type === "approval") {
108
- if (constraint.trigger && eventText.includes(constraint.trigger.substring(0, 10).toLowerCase())) {
109
- checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
110
- return { violated: constraint, checks };
111
- }
112
- const keywords = constraint.description.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
113
- const relevant = keywords.some((kw) => eventText.includes(kw));
114
- if (relevant) {
115
- checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
116
- return { violated: constraint, checks };
117
- }
118
- checks.push({ constraintId: constraint.id, passed: true });
119
- continue;
120
- }
121
- if (constraint.type === "scope" && constraint.trigger) {
122
- const keywords = constraint.trigger.split(/\s+/).filter((w) => w.length > 3);
123
- const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
124
- checks.push({
125
- constraintId: constraint.id,
126
- passed: !violated,
127
- reason: violated ? constraint.description : void 0
128
- });
129
- if (violated) {
130
- return { violated: constraint, checks };
131
- }
132
- continue;
133
- }
134
- checks.push({ constraintId: constraint.id, passed: true });
135
- }
136
- return { violated: null, checks };
137
- }
138
- function getPlanProgress(plan) {
139
- const completed = plan.steps.filter((s) => s.status === "completed").length;
140
- const total = plan.steps.length;
141
- return {
142
- completed,
143
- total,
144
- percentage: total > 0 ? Math.round(completed / total * 100) : 0
145
- };
146
- }
147
- function advancePlan(plan, stepId, evidence) {
148
- const step = plan.steps.find((s) => s.id === stepId);
149
- if (!step) {
150
- return { success: false, reason: `Step "${stepId}" not found in plan.` };
151
- }
152
- if (step.status === "completed") {
153
- return { success: false, reason: `Step "${stepId}" is already completed.` };
154
- }
155
- const mode = plan.completion ?? "trust";
156
- if (mode === "verified" && step.verify) {
157
- if (!evidence) {
158
- return {
159
- success: false,
160
- reason: `Step "${step.label}" requires evidence (verify: ${step.verify}). Provide evidence to advance.`
161
- };
162
- }
163
- if (evidence.type !== step.verify) {
164
- return {
165
- success: false,
166
- reason: `Evidence type "${evidence.type}" does not match required verification "${step.verify}".`
167
- };
168
- }
169
- }
170
- const updatedPlan = {
171
- ...plan,
172
- steps: plan.steps.map(
173
- (s) => s.id === stepId ? { ...s, status: "completed" } : s
174
- )
175
- };
176
- return {
177
- success: true,
178
- plan: updatedPlan,
179
- evidence: evidence ?? void 0
180
- };
181
- }
182
- function evaluatePlan(event, plan) {
183
- const progress = getPlanProgress(plan);
184
- if (plan.expires_at) {
185
- const expiresAt = new Date(plan.expires_at).getTime();
186
- if (Date.now() > expiresAt) {
187
- return {
188
- allowed: true,
189
- status: "PLAN_COMPLETE",
190
- reason: "Plan has expired.",
191
- progress
192
- };
193
- }
194
- }
195
- if (progress.completed === progress.total) {
196
- return {
197
- allowed: true,
198
- status: "PLAN_COMPLETE",
199
- reason: "All plan steps are completed.",
200
- progress
201
- };
202
- }
203
- const eventText = [
204
- event.intent,
205
- event.tool ?? "",
206
- event.scope ?? ""
207
- ].join(" ").toLowerCase();
208
- const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
209
- if (!matched) {
210
- return {
211
- allowed: false,
212
- status: "OFF_PLAN",
213
- reason: "Action does not match any plan step.",
214
- closestStep: closest?.label,
215
- similarityScore: closestScore,
216
- progress
217
- };
218
- }
219
- if (!isSequenceValid(matched, plan)) {
220
- const pendingDeps = (matched.requires ?? []).filter((reqId) => plan.steps.find((s) => s.id === reqId)?.status !== "completed").join(", ");
221
- return {
222
- allowed: false,
223
- status: "OFF_PLAN",
224
- reason: `Step "${matched.label}" requires completion of: ${pendingDeps}`,
225
- matchedStep: matched.id,
226
- progress
227
- };
228
- }
229
- const { violated } = checkConstraints(event, eventText, plan.constraints);
230
- if (violated) {
231
- return {
232
- allowed: false,
233
- status: "CONSTRAINT_VIOLATED",
234
- reason: violated.description,
235
- matchedStep: matched.id,
236
- progress
237
- };
238
- }
239
- return {
240
- allowed: true,
241
- status: "ON_PLAN",
242
- reason: `Matches step: ${matched.label}`,
243
- matchedStep: matched.id,
244
- progress
245
- };
246
- }
247
- function buildPlanCheck(event, plan, verdict) {
248
- const eventText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ").toLowerCase();
249
- const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
250
- const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
251
- const progress = getPlanProgress(plan);
252
- return {
253
- planId: plan.plan_id,
254
- matched: !!matched,
255
- matchedStepId: matched?.id,
256
- matchedStepLabel: matched?.label,
257
- closestStepId: !matched ? closest?.id : void 0,
258
- closestStepLabel: !matched ? closest?.label : void 0,
259
- similarityScore: !matched ? closestScore : void 0,
260
- sequenceValid: matched ? isSequenceValid(matched, plan) : void 0,
261
- constraintsChecked: constraintChecks,
262
- progress: { completed: progress.completed, total: progress.total }
263
- };
264
- }
265
-
266
- // src/engine/guard-engine.ts
267
- var PROMPT_INJECTION_PATTERNS = [
268
- // Instruction override
269
- { pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
270
- { pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
271
- { pattern: /new\s+instructions?:/i, label: "new-instructions" },
272
- // Identity manipulation
273
- { pattern: /you\s+are\s+now/i, label: "identity-override" },
274
- { pattern: /new\s+persona/i, label: "new-persona" },
275
- { pattern: /act\s+as\s+if/i, label: "act-as-if" },
276
- { pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
277
- // Context reset
278
- { pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
279
- { pattern: /system\s*:\s*override/i, label: "system-override" },
280
- // Constraint bypass
281
- { pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
282
- { pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
283
- // Prompt extraction
284
- { pattern: /system\s+prompt/i, label: "system-prompt-probe" },
285
- { pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
286
- // Known jailbreak terms
287
- { pattern: /jailbreak/i, label: "jailbreak" },
288
- { pattern: /DAN\s+mode/i, label: "dan-mode" },
289
- { pattern: /developer\s+mode/i, label: "developer-mode" }
290
- ];
291
- var EXECUTION_CLAIM_PATTERNS = [
292
- { pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
293
- { pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
294
- { pattern: /The file has been/i, label: "claim-file-modified" },
295
- { pattern: /I've made the changes/i, label: "claim-made-changes" },
296
- { pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
297
- { pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
298
- { pattern: /Transaction complete/i, label: "claim-transaction" },
299
- { pattern: /Order placed/i, label: "claim-order" },
300
- { pattern: /Payment processed/i, label: "claim-payment" }
301
- ];
302
- var EXECUTION_INTENT_PATTERNS = [
303
- { pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
304
- { pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
305
- { pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
306
- { pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
307
- { pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
308
- { pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
309
- { pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
310
- { pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
311
- ];
312
- var SCOPE_ESCAPE_PATTERNS = [
313
- { pattern: /\.\.\//, label: "parent-traversal" },
314
- { pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
315
- { pattern: /~\//, label: "home-directory" },
316
- { pattern: /\/etc\//i, label: "system-config" },
317
- { pattern: /\/usr\//i, label: "system-binaries" },
318
- { pattern: /\/var\//i, label: "system-variable-data" }
319
- ];
320
- var NEUTRAL_MESSAGES = {
321
- "prompt-injection": "This input contains patterns that could alter agent behavior.",
322
- "scope-escape": "This action would affect resources outside the declared scope.",
323
- "execution-claim": "This response claims to have performed an action.",
324
- "execution-intent": "This input requests execution in a thinking-only environment.",
325
- "delete": "This action would remove files. Confirmation needed.",
326
- "write-external": "This action would write outside the project folder.",
327
- "network-mutate": "This action would send data to an external service.",
328
- "credential-access": "This action would access stored credentials."
329
- };
330
- function levelRequiresConfirmation(level, actionType) {
331
- if (level === "strict") return true;
332
- if (level === "standard") {
333
- return actionType === "delete" || actionType === "credential-access";
334
- }
335
- return false;
336
- }
337
- function isExternalScope(scope) {
338
- const internalPatterns = [
339
- /^\.?\/?src\//i,
340
- /^\.?\/?lib\//i,
341
- /^\.?\/?app\//i,
342
- /^\.?\/?components\//i,
343
- /^\.?\/?pages\//i,
344
- /^\.?\/?public\//i,
345
- /^\.?\/?assets\//i,
346
- /^\.\//
347
- ];
348
- return !internalPatterns.some((p) => p.test(scope));
349
- }
350
- function evaluateGuard(event, world, options = {}) {
351
- const startTime = performance.now();
352
- const level = options.level ?? "standard";
353
- const includeTrace = options.trace ?? false;
354
- const eventText = (event.intent + " " + (event.tool ?? "") + " " + (event.scope ?? "")).toLowerCase();
355
- const invariantChecks = [];
356
- const safetyChecks = [];
357
- let planCheckResult;
358
- const roleChecks = [];
359
- const guardChecks = [];
360
- const kernelRuleChecks = [];
361
- const levelChecks = [];
362
- let decidingLayer = "default-allow";
363
- let decidingId;
364
- const guardsMatched = [];
365
- const rulesMatched = [];
366
- checkInvariantCoverage(world, invariantChecks);
367
- if (options.sessionAllowlist) {
368
- const key = eventToAllowlistKey(event);
369
- if (options.sessionAllowlist.has(key)) {
370
- decidingLayer = "session-allowlist";
371
- decidingId = `allowlist:${key}`;
372
- return buildVerdict(
373
- "ALLOW",
374
- void 0,
375
- `allowlist:${key}`,
376
- void 0,
377
- world,
378
- level,
379
- invariantChecks,
380
- guardsMatched,
381
- rulesMatched,
382
- includeTrace ? buildTrace(
383
- invariantChecks,
384
- safetyChecks,
385
- planCheckResult,
386
- roleChecks,
387
- guardChecks,
388
- kernelRuleChecks,
389
- levelChecks,
390
- decidingLayer,
391
- decidingId,
392
- startTime
393
- ) : void 0
394
- );
395
- }
396
- }
397
- const safetyVerdict = checkSafety(event, eventText, safetyChecks);
398
- if (safetyVerdict) {
399
- decidingLayer = "safety";
400
- decidingId = safetyVerdict.ruleId;
401
- return buildVerdict(
402
- safetyVerdict.status,
403
- safetyVerdict.reason,
404
- safetyVerdict.ruleId,
405
- void 0,
406
- world,
407
- level,
408
- invariantChecks,
409
- guardsMatched,
410
- rulesMatched,
411
- includeTrace ? buildTrace(
412
- invariantChecks,
413
- safetyChecks,
414
- planCheckResult,
415
- roleChecks,
416
- guardChecks,
417
- kernelRuleChecks,
418
- levelChecks,
419
- decidingLayer,
420
- decidingId,
421
- startTime
422
- ) : void 0
423
- );
424
- }
425
- if (options.plan) {
426
- const planVerdict = evaluatePlan(event, options.plan);
427
- planCheckResult = buildPlanCheck(event, options.plan, planVerdict);
428
- if (!planVerdict.allowed && planVerdict.status !== "PLAN_COMPLETE") {
429
- decidingLayer = "plan-enforcement";
430
- decidingId = `plan-${options.plan.plan_id}`;
431
- const planStatus = planVerdict.status === "CONSTRAINT_VIOLATED" ? "PAUSE" : "BLOCK";
432
- let reason = planVerdict.reason ?? "Action blocked by plan.";
433
- if (planVerdict.status === "OFF_PLAN" && planVerdict.closestStep) {
434
- reason += ` Closest step: "${planVerdict.closestStep}" (similarity: ${(planVerdict.similarityScore ?? 0).toFixed(2)})`;
435
- }
436
- return buildVerdict(
437
- planStatus,
438
- reason,
439
- `plan-${options.plan.plan_id}`,
440
- void 0,
441
- world,
442
- level,
443
- invariantChecks,
444
- guardsMatched,
445
- rulesMatched,
446
- includeTrace ? buildTrace(
447
- invariantChecks,
448
- safetyChecks,
449
- planCheckResult,
450
- roleChecks,
451
- guardChecks,
452
- kernelRuleChecks,
453
- levelChecks,
454
- decidingLayer,
455
- decidingId,
456
- startTime
457
- ) : void 0
458
- );
459
- }
460
- }
461
- const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
462
- if (roleVerdict) {
463
- decidingLayer = "role";
464
- decidingId = roleVerdict.ruleId;
465
- return buildVerdict(
466
- roleVerdict.status,
467
- roleVerdict.reason,
468
- roleVerdict.ruleId,
469
- void 0,
470
- world,
471
- level,
472
- invariantChecks,
473
- guardsMatched,
474
- rulesMatched,
475
- includeTrace ? buildTrace(
476
- invariantChecks,
477
- safetyChecks,
478
- planCheckResult,
479
- roleChecks,
480
- guardChecks,
481
- kernelRuleChecks,
482
- levelChecks,
483
- decidingLayer,
484
- decidingId,
485
- startTime
486
- ) : void 0
487
- );
488
- }
489
- const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
490
- if (guardVerdict) {
491
- if (guardVerdict.status !== "ALLOW") {
492
- decidingLayer = "guard";
493
- decidingId = guardVerdict.ruleId;
494
- return buildVerdict(
495
- guardVerdict.status,
496
- guardVerdict.reason,
497
- guardVerdict.ruleId,
498
- void 0,
499
- world,
500
- level,
501
- invariantChecks,
502
- guardsMatched,
503
- rulesMatched,
504
- includeTrace ? buildTrace(
505
- invariantChecks,
506
- safetyChecks,
507
- planCheckResult,
508
- roleChecks,
509
- guardChecks,
510
- kernelRuleChecks,
511
- levelChecks,
512
- decidingLayer,
513
- decidingId,
514
- startTime
515
- ) : void 0
516
- );
517
- }
518
- }
519
- const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
520
- if (kernelVerdict) {
521
- decidingLayer = "kernel-rule";
522
- decidingId = kernelVerdict.ruleId;
523
- return buildVerdict(
524
- kernelVerdict.status,
525
- kernelVerdict.reason,
526
- kernelVerdict.ruleId,
527
- void 0,
528
- world,
529
- level,
530
- invariantChecks,
531
- guardsMatched,
532
- rulesMatched,
533
- includeTrace ? buildTrace(
534
- invariantChecks,
535
- safetyChecks,
536
- planCheckResult,
537
- roleChecks,
538
- guardChecks,
539
- kernelRuleChecks,
540
- levelChecks,
541
- decidingLayer,
542
- decidingId,
543
- startTime
544
- ) : void 0
545
- );
546
- }
547
- const levelVerdict = checkLevelConstraints(event, level, levelChecks);
548
- if (levelVerdict) {
549
- decidingLayer = "level-constraint";
550
- decidingId = levelVerdict.ruleId;
551
- return buildVerdict(
552
- levelVerdict.status,
553
- levelVerdict.reason,
554
- levelVerdict.ruleId,
555
- void 0,
556
- world,
557
- level,
558
- invariantChecks,
559
- guardsMatched,
560
- rulesMatched,
561
- includeTrace ? buildTrace(
562
- invariantChecks,
563
- safetyChecks,
564
- planCheckResult,
565
- roleChecks,
566
- guardChecks,
567
- kernelRuleChecks,
568
- levelChecks,
569
- decidingLayer,
570
- decidingId,
571
- startTime
572
- ) : void 0
573
- );
574
- }
575
- const warning = guardVerdict?.warning;
576
- return buildVerdict(
577
- "ALLOW",
578
- void 0,
579
- void 0,
580
- warning,
581
- world,
582
- level,
583
- invariantChecks,
584
- guardsMatched,
585
- rulesMatched,
586
- includeTrace ? buildTrace(
587
- invariantChecks,
588
- safetyChecks,
589
- planCheckResult,
590
- roleChecks,
591
- guardChecks,
592
- kernelRuleChecks,
593
- levelChecks,
594
- decidingLayer,
595
- decidingId,
596
- startTime
597
- ) : void 0
598
- );
599
- }
600
- function checkInvariantCoverage(world, checks) {
601
- const invariants = world.invariants ?? [];
602
- const guards = world.guards?.guards ?? [];
603
- for (const invariant of invariants) {
604
- const coveringGuard = guards.find(
605
- (g) => g.invariant_ref === invariant.id && g.immutable
606
- );
607
- checks.push({
608
- invariantId: invariant.id,
609
- label: invariant.label,
610
- hasGuardCoverage: !!coveringGuard,
611
- coveringGuardId: coveringGuard?.id
612
- });
613
- }
614
- }
615
- function checkSafety(event, eventText, checks) {
616
- const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
617
- for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
618
- const triggered = pattern.test(textToCheck);
619
- checks.push({
620
- checkType: "prompt-injection",
621
- triggered,
622
- matchedPattern: triggered ? label : void 0
623
- });
624
- if (triggered) {
625
- for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
626
- checks.push({
627
- checkType: "prompt-injection",
628
- triggered: remaining.pattern.test(textToCheck),
629
- matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
630
- });
631
- }
632
- return {
633
- status: "PAUSE",
634
- reason: NEUTRAL_MESSAGES["prompt-injection"],
635
- ruleId: `safety-injection-${label}`
636
- };
637
- }
638
- }
639
- const scopeToCheck = event.scope ?? event.intent;
640
- for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
641
- const triggered = pattern.test(scopeToCheck);
642
- checks.push({
643
- checkType: "scope-escape",
644
- triggered,
645
- matchedPattern: triggered ? label : void 0
646
- });
647
- if (triggered) {
648
- for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
649
- checks.push({
650
- checkType: "scope-escape",
651
- triggered: remaining.pattern.test(scopeToCheck),
652
- matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
653
- });
654
- }
655
- return {
656
- status: "PAUSE",
657
- reason: NEUTRAL_MESSAGES["scope-escape"],
658
- ruleId: `safety-scope-${label}`
659
- };
660
- }
661
- }
662
- if (event.direction === "output") {
663
- for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
664
- const triggered = pattern.test(textToCheck);
665
- checks.push({
666
- checkType: "execution-claim",
667
- triggered,
668
- matchedPattern: triggered ? label : void 0
669
- });
670
- if (triggered) {
671
- for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
672
- checks.push({
673
- checkType: "execution-claim",
674
- triggered: remaining.pattern.test(textToCheck),
675
- matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
676
- });
677
- }
678
- return {
679
- status: "PAUSE",
680
- reason: NEUTRAL_MESSAGES["execution-claim"],
681
- ruleId: `safety-execution-claim-${label}`
682
- };
683
- }
684
- }
685
- }
686
- if (event.direction === "input") {
687
- const intentTrimmed = event.intent.trim();
688
- for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
689
- const triggered = pattern.test(intentTrimmed);
690
- checks.push({
691
- checkType: "execution-intent",
692
- triggered,
693
- matchedPattern: triggered ? label : void 0
694
- });
695
- if (triggered) {
696
- for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
697
- checks.push({
698
- checkType: "execution-intent",
699
- triggered: remaining.pattern.test(intentTrimmed),
700
- matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
701
- });
702
- }
703
- return {
704
- status: "PAUSE",
705
- reason: NEUTRAL_MESSAGES["execution-intent"],
706
- ruleId: `safety-execution-intent-${label}`
707
- };
708
- }
709
- }
710
- }
711
- return null;
712
- }
713
- function checkRoleRules(event, eventText, world, checks) {
714
- if (!event.roleId || !world.roles) return null;
715
- const role = world.roles.roles.find((r) => r.id === event.roleId);
716
- if (!role) return null;
717
- if (role.requiresApproval) {
718
- checks.push({
719
- roleId: role.id,
720
- roleName: role.name,
721
- rule: "All actions require approval",
722
- ruleType: "requiresApproval",
723
- matched: true
724
- });
725
- return {
726
- status: "PAUSE",
727
- reason: `Role "${role.name}" requires approval for all actions.`,
728
- ruleId: `role-${role.id}-requires-approval`
729
- };
730
- }
731
- for (const rule of role.cannotDo) {
732
- const matched = matchesKeywords(eventText, rule);
733
- checks.push({
734
- roleId: role.id,
735
- roleName: role.name,
736
- rule,
737
- ruleType: "cannotDo",
738
- matched
739
- });
740
- if (matched) {
741
- return {
742
- status: "BLOCK",
743
- reason: `Role "${role.name}" cannot: ${rule}`,
744
- ruleId: `role-${role.id}-cannotdo`
745
- };
746
- }
747
- }
748
- for (const rule of role.canDo) {
749
- checks.push({
750
- roleId: role.id,
751
- roleName: role.name,
752
- rule,
753
- ruleType: "canDo",
754
- matched: matchesKeywords(eventText, rule)
755
- });
756
- }
757
- return null;
758
- }
759
- function checkGuards(event, eventText, world, checks, guardsMatched) {
760
- if (!world.guards) return null;
761
- const guardsConfig = world.guards;
762
- let warnResult = null;
763
- const compiledPatterns = /* @__PURE__ */ new Map();
764
- for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
765
- try {
766
- compiledPatterns.set(key, new RegExp(def.pattern, "i"));
767
- } catch {
768
- }
769
- }
770
- const eventTool = (event.tool ?? "").toLowerCase();
771
- for (const guard of guardsConfig.guards) {
772
- if (guard.appliesTo && guard.appliesTo.length > 0) {
773
- const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
774
- if (!normalizedAppliesTo.includes(eventTool)) {
775
- continue;
776
- }
777
- }
778
- const enabled = guard.immutable || guard.default_enabled !== false;
779
- const matchedPatterns = [];
780
- for (const patternKey of guard.intent_patterns) {
781
- const regex = compiledPatterns.get(patternKey);
782
- if (regex?.test(eventText)) {
783
- matchedPatterns.push(patternKey);
784
- }
785
- }
786
- const matched = matchedPatterns.length > 0 && enabled;
787
- let roleGated = false;
788
- if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
789
- roleGated = true;
790
- }
791
- checks.push({
792
- guardId: guard.id,
793
- label: guard.label,
794
- category: guard.category,
795
- enabled,
796
- matched: matched && !roleGated,
797
- enforcement: guard.enforcement,
798
- matchedPatterns,
799
- roleGated
800
- });
801
- if (!matched || roleGated) continue;
802
- guardsMatched.push(guard.id);
803
- const actionMode = guard.player_modes?.action ?? guard.enforcement;
804
- const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
805
- if (actionMode === "block") {
806
- return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
807
- }
808
- if (actionMode === "pause") {
809
- return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
810
- }
811
- if (actionMode === "warn" && !warnResult) {
812
- warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
813
- }
814
- }
815
- return warnResult;
816
- }
817
- function checkKernelRules(eventText, world, checks, rulesMatched) {
818
- if (!world.kernel) return null;
819
- const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
820
- const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
821
- for (const rule of forbidden) {
822
- let matched = false;
823
- let matchMethod = "none";
824
- if (rule.pattern) {
825
- try {
826
- matched = new RegExp(rule.pattern, "i").test(eventText);
827
- matchMethod = "pattern";
828
- } catch {
829
- }
830
- }
831
- if (!matched && rule.reason) {
832
- matched = matchesKeywords(eventText, rule.reason);
833
- if (matched) matchMethod = "keyword";
834
- }
835
- checks.push({
836
- ruleId: rule.id,
837
- text: rule.reason,
838
- category: "forbidden",
839
- matched,
840
- matchMethod
841
- });
842
- if (matched) {
843
- rulesMatched.push(rule.id);
844
- if (rule.action === "BLOCK") {
845
- return {
846
- status: "BLOCK",
847
- reason: rule.reason,
848
- ruleId: `kernel-${rule.id}`
849
- };
850
- }
851
- }
852
- }
853
- return null;
854
- }
855
- function checkLevelConstraints(event, level, checks) {
856
- if (level === "basic") return null;
857
- const intent = event.intent.toLowerCase();
858
- const tool = (event.tool ?? "").toLowerCase();
859
- const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
860
- const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
861
- checks.push({
862
- checkType: "delete",
863
- level,
864
- triggered: deleteTriggered,
865
- reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
866
- });
867
- if (deleteTriggered) {
868
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
869
- }
870
- const isExternal = event.scope ? isExternalScope(event.scope) : false;
871
- const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
872
- checks.push({
873
- checkType: "write-external",
874
- level,
875
- triggered: externalTriggered,
876
- reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
877
- });
878
- if (externalTriggered) {
879
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
880
- }
881
- const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
882
- const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
883
- checks.push({
884
- checkType: "network-mutate",
885
- level,
886
- triggered: networkTriggered,
887
- reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
888
- });
889
- if (networkTriggered) {
890
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
891
- }
892
- const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
893
- const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
894
- checks.push({
895
- checkType: "credential-access",
896
- level,
897
- triggered: credentialTriggered,
898
- reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
899
- });
900
- if (credentialTriggered) {
901
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
902
- }
903
- const irreversibleTriggered = !!event.irreversible && level !== "basic";
904
- checks.push({
905
- checkType: "irreversible",
906
- level,
907
- triggered: irreversibleTriggered,
908
- reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
909
- });
910
- if (irreversibleTriggered) {
911
- return {
912
- status: "PAUSE",
913
- reason: "This action is marked as irreversible.",
914
- ruleId: "level-irreversible-check"
915
- };
916
- }
917
- return null;
918
- }
919
- function matchesKeywords(eventText, ruleText) {
920
- const keywords = ruleText.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
921
- if (keywords.length === 0) return false;
922
- return keywords.every((kw) => eventText.includes(kw));
923
- }
924
- function eventToAllowlistKey(event) {
925
- return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
926
- }
927
- function buildTrace(invariantChecks, safetyChecks, planCheck, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
928
- const trace = {
929
- invariantChecks,
930
- safetyChecks,
931
- roleChecks,
932
- guardChecks,
933
- kernelRuleChecks,
934
- levelChecks,
935
- precedenceResolution: {
936
- decidingLayer,
937
- decidingId,
938
- strategy: "first-match-wins",
939
- chainOrder: [
940
- "invariant-coverage",
941
- "session-allowlist",
942
- "safety-injection",
943
- "safety-scope-escape",
944
- "safety-execution-claim",
945
- "safety-execution-intent",
946
- "plan-enforcement",
947
- "role-rules",
948
- "declarative-guards",
949
- "kernel-rules",
950
- "level-constraints",
951
- "default-allow"
952
- ]
953
- },
954
- durationMs: performance.now() - startTime
955
- };
956
- if (planCheck) {
957
- trace.planCheck = planCheck;
958
- }
959
- return trace;
960
- }
961
- function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace) {
962
- const evidence = {
963
- worldId: world.world.world_id,
964
- worldName: world.world.name,
965
- worldVersion: world.world.version,
966
- evaluatedAt: Date.now(),
967
- invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
968
- invariantsTotal: invariantChecks.length,
969
- guardsMatched,
970
- rulesMatched,
971
- enforcementLevel: level
972
- };
973
- const verdict = {
974
- status,
975
- evidence
976
- };
977
- if (reason) verdict.reason = reason;
978
- if (ruleId) verdict.ruleId = ruleId;
979
- if (warning) verdict.warning = warning;
980
- if (trace) verdict.trace = trace;
981
- return verdict;
982
- }
983
-
984
- // src/loader/world-loader.ts
985
- async function loadWorldFromDirectory(dirPath) {
986
- const { readFile } = await import("fs/promises");
987
- const { join } = await import("path");
988
- const { readdirSync } = await import("fs");
989
- async function readJson(filename) {
990
- try {
991
- const content = await readFile(join(dirPath, filename), "utf-8");
992
- return JSON.parse(content);
993
- } catch {
994
- return void 0;
995
- }
996
- }
997
- const worldJson = await readJson("world.json");
998
- if (!worldJson) {
999
- throw new Error(`Cannot read world.json in ${dirPath}`);
1000
- }
1001
- const invariantsJson = await readJson("invariants.json");
1002
- const assumptionsJson = await readJson("assumptions.json");
1003
- const stateSchemaJson = await readJson("state-schema.json");
1004
- const gatesJson = await readJson("gates.json");
1005
- const outcomesJson = await readJson("outcomes.json");
1006
- const guardsJson = await readJson("guards.json");
1007
- const rolesJson = await readJson("roles.json");
1008
- const kernelJson = await readJson("kernel.json");
1009
- const metadataJson = await readJson("metadata.json");
1010
- const rules = [];
1011
- try {
1012
- const rulesDir = join(dirPath, "rules");
1013
- const ruleFiles = readdirSync(rulesDir).filter((f) => f.endsWith(".json")).sort();
1014
- for (const file of ruleFiles) {
1015
- const content = await readFile(join(rulesDir, file), "utf-8");
1016
- rules.push(JSON.parse(content));
1017
- }
1018
- } catch {
1019
- }
1020
- return {
1021
- world: worldJson,
1022
- invariants: invariantsJson?.invariants ?? [],
1023
- assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
1024
- stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
1025
- rules,
1026
- gates: gatesJson ?? {
1027
- viability_classification: [],
1028
- structural_override: { description: "", enforcement: "mandatory" },
1029
- sustainability_threshold: 0,
1030
- collapse_visual: { background: "", text: "", border: "", label: "" }
1031
- },
1032
- outcomes: outcomesJson ?? {
1033
- computed_outcomes: [],
1034
- comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
1035
- },
1036
- guards: guardsJson,
1037
- roles: rolesJson,
1038
- kernel: kernelJson,
1039
- metadata: metadataJson ?? {
1040
- format_version: "1.0.0",
1041
- created_at: "",
1042
- last_modified: "",
1043
- authoring_method: "manual-authoring"
1044
- }
1045
- };
1046
- }
1047
- async function loadWorld(worldPath) {
1048
- const { stat } = await import("fs/promises");
1049
- const info = await stat(worldPath);
1050
- if (info.isDirectory()) {
1051
- return loadWorldFromDirectory(worldPath);
1052
- }
1053
- if (worldPath.endsWith(".nv-world.zip")) {
1054
- throw new Error(".nv-world.zip loading not yet implemented \u2014 use a world directory");
1055
- }
1056
- throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory or .nv-world.zip`);
1057
- }
1058
-
1059
- // src/adapters/openai.ts
1060
- var GovernanceBlockedError = class extends Error {
1061
- verdict;
1062
- toolCallId;
1063
- constructor(verdict, toolCallId) {
1064
- super(`[NeuroVerse] BLOCKED: ${verdict.reason ?? verdict.ruleId ?? "governance rule"}`);
1065
- this.name = "GovernanceBlockedError";
1066
- this.verdict = verdict;
1067
- this.toolCallId = toolCallId;
1068
- }
1069
- };
1070
- function defaultMapFunctionCall(name, args) {
1071
- return {
1072
- intent: name,
1073
- tool: name,
1074
- scope: typeof args.path === "string" ? args.path : typeof args.url === "string" ? args.url : void 0,
1075
- args,
1076
- direction: "input"
1077
- };
1078
- }
1079
- function defaultBlockMessage(verdict) {
1080
- return `Action blocked by governance policy: ${verdict.reason ?? "rule violation"}. Rule: ${verdict.ruleId ?? "unknown"}.`;
1081
- }
1082
- var GovernedToolExecutor = class {
1083
- world;
1084
- options;
1085
- engineOptions;
1086
- mapFn;
1087
- blockMsg;
1088
- activePlan;
1089
- constructor(world, options = {}) {
1090
- this.world = world;
1091
- this.options = options;
1092
- this.activePlan = options.plan;
1093
- this.engineOptions = {
1094
- trace: options.trace ?? false,
1095
- level: options.level,
1096
- plan: this.activePlan
1097
- };
1098
- this.mapFn = options.mapFunctionCall ?? defaultMapFunctionCall;
1099
- this.blockMsg = options.blockMessage ?? defaultBlockMessage;
1100
- }
1101
- /**
1102
- * Evaluate a single tool call against governance rules.
1103
- * Returns the verdict without executing the tool.
1104
- */
1105
- evaluate(toolCall) {
1106
- let args;
1107
- try {
1108
- args = JSON.parse(toolCall.function.arguments);
1109
- } catch {
1110
- args = { raw: toolCall.function.arguments };
1111
- }
1112
- const event = this.mapFn(toolCall.function.name, args);
1113
- this.engineOptions.plan = this.activePlan;
1114
- const verdict = evaluateGuard(event, this.world, this.engineOptions);
1115
- this.options.onEvaluate?.(verdict, event);
1116
- if (verdict.status === "ALLOW" && this.activePlan) {
1117
- const planVerdict = evaluatePlan(event, this.activePlan);
1118
- if (planVerdict.matchedStep) {
1119
- const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
1120
- if (advResult.success && advResult.plan) {
1121
- this.activePlan = advResult.plan;
1122
- this.engineOptions.plan = this.activePlan;
1123
- }
1124
- const progress = getPlanProgress(this.activePlan);
1125
- this.options.onPlanProgress?.(progress);
1126
- if (progress.completed === progress.total) {
1127
- this.options.onPlanComplete?.();
1128
- }
1129
- }
1130
- }
1131
- return verdict;
1132
- }
1133
- /**
1134
- * Execute a tool call with governance enforcement.
1135
- *
1136
- * If ALLOW: runs the tool and returns the result.
1137
- * If BLOCK: returns a blocked message (no execution).
1138
- * If PAUSE: throws — caller must handle approval flow.
1139
- *
1140
- * @param toolCall - The OpenAI tool call to evaluate
1141
- * @param runner - The actual tool execution function
1142
- * @returns A tool result message ready for the OpenAI API
1143
- */
1144
- async execute(toolCall, runner) {
1145
- const verdict = this.evaluate(toolCall);
1146
- if (verdict.status === "BLOCK") {
1147
- return {
1148
- tool_call_id: toolCall.id,
1149
- role: "tool",
1150
- content: this.blockMsg(verdict),
1151
- _verdict: verdict
1152
- };
1153
- }
1154
- if (verdict.status === "PAUSE") {
1155
- throw new GovernanceBlockedError(verdict, toolCall.id);
1156
- }
1157
- let args;
1158
- try {
1159
- args = JSON.parse(toolCall.function.arguments);
1160
- } catch {
1161
- args = { raw: toolCall.function.arguments };
1162
- }
1163
- const content = await runner(toolCall.function.name, args);
1164
- return {
1165
- tool_call_id: toolCall.id,
1166
- role: "tool",
1167
- content,
1168
- _verdict: verdict
1169
- };
1170
- }
1171
- };
1172
- async function createGovernedToolExecutor(worldPath, options) {
1173
- const world = await loadWorld(worldPath);
1174
- return new GovernedToolExecutor(world, options);
1175
- }
1176
- function createGovernedToolExecutorFromWorld(world, options) {
1177
- return new GovernedToolExecutor(world, options);
1178
- }
1179
- // Annotate the CommonJS export names for ESM import in node:
1180
- 0 && (module.exports = {
1181
- GovernanceBlockedError,
1182
- GovernedToolExecutor,
1183
- createGovernedToolExecutor,
1184
- createGovernedToolExecutorFromWorld
1185
- });