@neuroverseos/governance 0.3.1 → 0.3.3

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 (132) hide show
  1. package/.well-known/ai-plugin.json +34 -9
  2. package/AGENTS.md +72 -24
  3. package/README.md +343 -248
  4. package/dist/adapters/autoresearch.cjs +1345 -0
  5. package/dist/adapters/autoresearch.d.cts +111 -0
  6. package/dist/adapters/autoresearch.d.ts +111 -0
  7. package/dist/adapters/autoresearch.js +12 -0
  8. package/dist/adapters/deep-agents.cjs +1528 -0
  9. package/dist/adapters/deep-agents.d.cts +181 -0
  10. package/dist/adapters/deep-agents.d.ts +181 -0
  11. package/dist/adapters/deep-agents.js +17 -0
  12. package/dist/adapters/express.cjs +1253 -0
  13. package/dist/adapters/express.d.cts +66 -0
  14. package/dist/adapters/express.d.ts +66 -0
  15. package/dist/adapters/express.js +12 -0
  16. package/dist/adapters/index.cjs +2112 -0
  17. package/dist/adapters/index.d.cts +8 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +68 -0
  20. package/dist/adapters/langchain.cjs +1315 -0
  21. package/dist/adapters/langchain.d.cts +89 -0
  22. package/dist/adapters/langchain.d.ts +89 -0
  23. package/dist/adapters/langchain.js +17 -0
  24. package/dist/adapters/openai.cjs +1345 -0
  25. package/dist/adapters/openai.d.cts +99 -0
  26. package/dist/adapters/openai.d.ts +99 -0
  27. package/dist/adapters/openai.js +17 -0
  28. package/dist/adapters/openclaw.cjs +1337 -0
  29. package/dist/adapters/openclaw.d.cts +99 -0
  30. package/dist/adapters/openclaw.d.ts +99 -0
  31. package/dist/adapters/openclaw.js +17 -0
  32. package/dist/add-ROOZLU62.js +314 -0
  33. package/dist/behavioral-MJO34S6Q.js +118 -0
  34. package/dist/bootstrap-CQRZVOXK.js +116 -0
  35. package/dist/bootstrap-emitter-Q7UIJZ2O.js +7 -0
  36. package/dist/bootstrap-parser-EEF36XDU.js +7 -0
  37. package/dist/browser.global.js +941 -0
  38. package/dist/build-QKOBBC23.js +341 -0
  39. package/dist/chunk-3WQLXYTP.js +91 -0
  40. package/dist/chunk-4FLICVVA.js +119 -0
  41. package/dist/chunk-4NGDRRQH.js +10 -0
  42. package/dist/chunk-5TPFNWRU.js +215 -0
  43. package/dist/chunk-5U2MQO5P.js +57 -0
  44. package/dist/chunk-6CZSKEY5.js +164 -0
  45. package/dist/chunk-6S5CFQXY.js +624 -0
  46. package/dist/chunk-7P3S7MAY.js +1090 -0
  47. package/dist/chunk-A5W4GNQO.js +130 -0
  48. package/dist/chunk-A7GKPPU7.js +226 -0
  49. package/dist/chunk-AKW5YVCE.js +96 -0
  50. package/dist/chunk-B6OXJLJ5.js +622 -0
  51. package/dist/chunk-BNKJPUPQ.js +113 -0
  52. package/dist/chunk-BQZMOEML.js +43 -0
  53. package/dist/chunk-CNSO6XW5.js +207 -0
  54. package/dist/chunk-CTZHONLA.js +135 -0
  55. package/dist/chunk-D2UCV5AK.js +326 -0
  56. package/dist/chunk-EMQDLDAF.js +458 -0
  57. package/dist/chunk-F66BVUYB.js +340 -0
  58. package/dist/chunk-G7DJ6VOD.js +101 -0
  59. package/dist/chunk-I3RRAYK2.js +11 -0
  60. package/dist/chunk-IS4WUH6Y.js +363 -0
  61. package/dist/chunk-MH7BT4VH.js +15 -0
  62. package/dist/chunk-O5ABKEA7.js +304 -0
  63. package/dist/chunk-OT6PXH54.js +61 -0
  64. package/dist/chunk-PVTQQS3Y.js +186 -0
  65. package/dist/chunk-Q6O7ZLO2.js +62 -0
  66. package/dist/chunk-QLPTHTVB.js +253 -0
  67. package/dist/chunk-QWGCMQQD.js +16 -0
  68. package/dist/chunk-QXBFT7NI.js +201 -0
  69. package/dist/chunk-TG6SEF24.js +246 -0
  70. package/dist/chunk-U6U7EJZL.js +177 -0
  71. package/dist/chunk-W7LLXRGY.js +830 -0
  72. package/dist/chunk-ZJTDUCC2.js +194 -0
  73. package/dist/chunk-ZWI3NIXK.js +314 -0
  74. package/dist/cli/neuroverse.cjs +14191 -0
  75. package/dist/cli/neuroverse.d.cts +1 -0
  76. package/dist/cli/neuroverse.d.ts +1 -0
  77. package/dist/cli/neuroverse.js +227 -0
  78. package/dist/cli/plan.cjs +2439 -0
  79. package/dist/cli/plan.d.cts +20 -0
  80. package/dist/cli/plan.d.ts +20 -0
  81. package/dist/cli/plan.js +353 -0
  82. package/dist/cli/run.cjs +2001 -0
  83. package/dist/cli/run.d.cts +20 -0
  84. package/dist/cli/run.d.ts +20 -0
  85. package/dist/cli/run.js +143 -0
  86. package/dist/configure-ai-6TZ3MCSI.js +132 -0
  87. package/dist/decision-flow-M63D47LO.js +61 -0
  88. package/dist/demo-G43RLCPK.js +469 -0
  89. package/dist/derive-FJZVIPUZ.js +153 -0
  90. package/dist/doctor-6BC6X2VO.js +173 -0
  91. package/dist/equity-penalties-SG5IZQ7I.js +244 -0
  92. package/dist/explain-RHBU2GBR.js +51 -0
  93. package/dist/guard-AJCCGZMF.js +92 -0
  94. package/dist/guard-contract-DqFcTScd.d.cts +821 -0
  95. package/dist/guard-contract-DqFcTScd.d.ts +821 -0
  96. package/dist/guard-engine-PNR6MHCM.js +10 -0
  97. package/dist/impact-3XVDSCBU.js +59 -0
  98. package/dist/improve-TQP4ECSY.js +66 -0
  99. package/dist/index.cjs +7591 -0
  100. package/dist/index.d.cts +2195 -0
  101. package/dist/index.d.ts +2195 -0
  102. package/dist/index.js +472 -0
  103. package/dist/infer-world-IFXCACJ5.js +543 -0
  104. package/dist/init-FYPV4SST.js +144 -0
  105. package/dist/init-world-TI7ARHBT.js +223 -0
  106. package/dist/mcp-server-5Y3ZM7TV.js +13 -0
  107. package/dist/model-adapter-VXEKB4LS.js +11 -0
  108. package/dist/playground-VZBNPPBO.js +560 -0
  109. package/dist/redteam-MZPZD3EF.js +357 -0
  110. package/dist/session-JYOARW54.js +15 -0
  111. package/dist/shared-7RLUHNMU.js +16 -0
  112. package/dist/shared-B8dvUUD8.d.cts +60 -0
  113. package/dist/shared-Dr5Wiay8.d.ts +60 -0
  114. package/dist/simulate-LJXYBC6M.js +83 -0
  115. package/dist/test-BOOR4A5F.js +217 -0
  116. package/dist/trace-PKV4KX56.js +166 -0
  117. package/dist/validate-RALX7CZS.js +81 -0
  118. package/dist/validate-engine-7ZXFVGF2.js +7 -0
  119. package/dist/viz/assets/index-B8SaeJZZ.js +23 -0
  120. package/dist/viz/index.html +23 -0
  121. package/dist/world-BIP4GZBZ.js +376 -0
  122. package/dist/world-loader-Y6HMQH2D.js +13 -0
  123. package/dist/worlds/autoresearch.nv-world.md +230 -0
  124. package/dist/worlds/coding-agent.nv-world.md +211 -0
  125. package/dist/worlds/derivation-world.nv-world.md +278 -0
  126. package/dist/worlds/research-agent.nv-world.md +169 -0
  127. package/dist/worlds/social-media.nv-world.md +198 -0
  128. package/dist/worlds/trading-agent.nv-world.md +218 -0
  129. package/examples/social-media-sim/bridge.py +209 -0
  130. package/examples/social-media-sim/simulation.py +927 -0
  131. package/package.json +16 -3
  132. package/simulate.html +4 -336
@@ -0,0 +1,2001 @@
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 __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/runtime/model-adapter.ts
34
+ var model_adapter_exports = {};
35
+ __export(model_adapter_exports, {
36
+ ModelAdapter: () => ModelAdapter,
37
+ PROVIDERS: () => PROVIDERS,
38
+ resolveProvider: () => resolveProvider
39
+ });
40
+ function resolveProvider(provider, overrides) {
41
+ const preset = PROVIDERS[provider];
42
+ if (!preset) {
43
+ throw new Error(
44
+ `Unknown provider: "${provider}". Available: ${Object.keys(PROVIDERS).join(", ")}`
45
+ );
46
+ }
47
+ const apiKey = overrides?.apiKey ?? (preset.envVar ? process.env[preset.envVar] : "") ?? "";
48
+ if (!apiKey && preset.envVar) {
49
+ throw new Error(
50
+ `Missing API key. Set ${preset.envVar} or pass --api-key.`
51
+ );
52
+ }
53
+ return {
54
+ baseUrl: overrides?.baseUrl ?? preset.baseUrl,
55
+ apiKey,
56
+ model: overrides?.model ?? preset.defaultModel,
57
+ systemPrompt: overrides?.systemPrompt,
58
+ maxTokens: overrides?.maxTokens
59
+ };
60
+ }
61
+ var DEFAULT_SYSTEM_PROMPT, ModelAdapter, PROVIDERS;
62
+ var init_model_adapter = __esm({
63
+ "src/runtime/model-adapter.ts"() {
64
+ "use strict";
65
+ DEFAULT_SYSTEM_PROMPT = `You are an AI assistant operating under NeuroVerse governance.
66
+ All your tool calls are evaluated against governance rules before execution.
67
+ If an action is blocked, you will be told why. Adjust your approach accordingly.
68
+ Do not attempt to bypass governance rules.`;
69
+ ModelAdapter = class {
70
+ config;
71
+ messages;
72
+ tools;
73
+ constructor(config, tools = []) {
74
+ this.config = config;
75
+ this.tools = tools;
76
+ this.messages = [];
77
+ const systemPrompt = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
78
+ this.messages.push({ role: "system", content: systemPrompt });
79
+ }
80
+ /**
81
+ * Send a user message and get the model's response.
82
+ */
83
+ async chat(userMessage) {
84
+ this.messages.push({ role: "user", content: userMessage });
85
+ return this.complete();
86
+ }
87
+ /**
88
+ * Send a tool result back to the model and get the next response.
89
+ */
90
+ async sendToolResult(toolCallId, result) {
91
+ this.messages.push({
92
+ role: "tool",
93
+ content: result,
94
+ tool_call_id: toolCallId
95
+ });
96
+ return this.complete();
97
+ }
98
+ /**
99
+ * Send a governance block message as a tool result.
100
+ */
101
+ async sendBlockedResult(toolCallId, reason) {
102
+ return this.sendToolResult(
103
+ toolCallId,
104
+ `[GOVERNANCE BLOCKED] ${reason}. Please adjust your approach.`
105
+ );
106
+ }
107
+ /**
108
+ * Call the model API and parse the response.
109
+ */
110
+ async complete() {
111
+ const url = `${this.config.baseUrl}/chat/completions`;
112
+ const body = {
113
+ model: this.config.model,
114
+ messages: this.messages,
115
+ max_tokens: this.config.maxTokens ?? 4096
116
+ };
117
+ if (this.tools.length > 0) {
118
+ body.tools = this.tools;
119
+ }
120
+ const response = await fetch(url, {
121
+ method: "POST",
122
+ headers: {
123
+ "Content-Type": "application/json",
124
+ "Authorization": `Bearer ${this.config.apiKey}`
125
+ },
126
+ body: JSON.stringify(body)
127
+ });
128
+ if (!response.ok) {
129
+ const text = await response.text();
130
+ throw new Error(`Model API error ${response.status}: ${text}`);
131
+ }
132
+ const data = await response.json();
133
+ const choice = data.choices?.[0];
134
+ if (!choice) {
135
+ throw new Error("Model returned no choices");
136
+ }
137
+ const message = choice.message;
138
+ this.messages.push(message);
139
+ return {
140
+ content: message.content ?? null,
141
+ toolCalls: message.tool_calls ?? [],
142
+ finishReason: choice.finish_reason ?? "stop"
143
+ };
144
+ }
145
+ /** Get current message count (for context tracking). */
146
+ get messageCount() {
147
+ return this.messages.length;
148
+ }
149
+ };
150
+ PROVIDERS = {
151
+ openai: {
152
+ baseUrl: "https://api.openai.com/v1",
153
+ defaultModel: "gpt-4o",
154
+ envVar: "OPENAI_API_KEY"
155
+ },
156
+ anthropic: {
157
+ baseUrl: "https://api.anthropic.com/v1",
158
+ defaultModel: "claude-sonnet-4-20250514",
159
+ envVar: "ANTHROPIC_API_KEY"
160
+ },
161
+ ollama: {
162
+ baseUrl: "http://localhost:11434/v1",
163
+ defaultModel: "llama3",
164
+ envVar: ""
165
+ }
166
+ };
167
+ }
168
+ });
169
+
170
+ // src/engine/text-utils.ts
171
+ function normalizeEventText(event) {
172
+ return [
173
+ event.intent,
174
+ event.tool ?? "",
175
+ event.scope ?? ""
176
+ ].join(" ").toLowerCase();
177
+ }
178
+ function extractKeywords(text, minLength = 3) {
179
+ return text.toLowerCase().split(/\s+/).filter((w) => w.length > minLength);
180
+ }
181
+ function matchesAllKeywords(eventText, ruleText) {
182
+ const keywords = extractKeywords(ruleText);
183
+ if (keywords.length === 0) return false;
184
+ return keywords.every((kw) => eventText.includes(kw));
185
+ }
186
+ function matchesKeywordThreshold(eventText, ruleText, threshold = 0.5) {
187
+ const keywords = extractKeywords(ruleText);
188
+ if (keywords.length === 0) return false;
189
+ const matched = keywords.filter((kw) => eventText.includes(kw));
190
+ return matched.length >= Math.ceil(keywords.length * threshold);
191
+ }
192
+ function tokenSimilarity(a, b) {
193
+ const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
194
+ const tokensB = new Set(b.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
195
+ if (tokensA.size === 0 || tokensB.size === 0) return 0;
196
+ let intersection = 0;
197
+ for (const t of tokensA) {
198
+ if (tokensB.has(t)) intersection++;
199
+ }
200
+ const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
201
+ return union > 0 ? intersection / union : 0;
202
+ }
203
+ var init_text_utils = __esm({
204
+ "src/engine/text-utils.ts"() {
205
+ "use strict";
206
+ }
207
+ });
208
+
209
+ // src/engine/plan-engine.ts
210
+ function keywordMatch(eventText, step) {
211
+ const stepText = [
212
+ step.label,
213
+ step.description ?? "",
214
+ ...step.tags ?? []
215
+ ].join(" ");
216
+ return matchesKeywordThreshold(eventText, stepText, 0.5);
217
+ }
218
+ function tokenSimilarity2(a, b) {
219
+ return tokenSimilarity(a, b);
220
+ }
221
+ function findMatchingStep(eventText, event, steps) {
222
+ const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
223
+ if (pendingOrActive.length === 0) {
224
+ return { matched: null, closest: null, closestScore: 0 };
225
+ }
226
+ for (const step of pendingOrActive) {
227
+ if (keywordMatch(eventText, step)) {
228
+ if (step.tools && event.tool && !step.tools.includes(event.tool)) {
229
+ continue;
230
+ }
231
+ return { matched: step, closest: step, closestScore: 1 };
232
+ }
233
+ }
234
+ const intentText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ");
235
+ let bestStep = null;
236
+ let bestScore = 0;
237
+ for (const step of pendingOrActive) {
238
+ const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
239
+ const score = tokenSimilarity2(intentText, stepText);
240
+ if (score > bestScore) {
241
+ bestScore = score;
242
+ bestStep = step;
243
+ }
244
+ }
245
+ const SIMILARITY_THRESHOLD = 0.35;
246
+ if (bestScore >= SIMILARITY_THRESHOLD && bestStep) {
247
+ if (bestStep.tools && event.tool && !bestStep.tools.includes(event.tool)) {
248
+ return { matched: null, closest: bestStep, closestScore: bestScore };
249
+ }
250
+ return { matched: bestStep, closest: bestStep, closestScore: bestScore };
251
+ }
252
+ return { matched: null, closest: bestStep, closestScore: bestScore };
253
+ }
254
+ function isSequenceValid(step, plan) {
255
+ if (!plan.sequential) return true;
256
+ if (!step.requires || step.requires.length === 0) return true;
257
+ return step.requires.every((reqId) => {
258
+ const reqStep = plan.steps.find((s) => s.id === reqId);
259
+ return reqStep?.status === "completed";
260
+ });
261
+ }
262
+ function checkConstraints(event, eventText, constraints) {
263
+ const checks = [];
264
+ for (const constraint of constraints) {
265
+ if (constraint.type === "approval") {
266
+ if (constraint.trigger && eventText.includes(constraint.trigger.substring(0, 10).toLowerCase())) {
267
+ checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
268
+ return { violated: constraint, checks };
269
+ }
270
+ const keywords = constraint.description.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
271
+ const relevant = keywords.some((kw) => eventText.includes(kw));
272
+ if (relevant) {
273
+ checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
274
+ return { violated: constraint, checks };
275
+ }
276
+ checks.push({ constraintId: constraint.id, passed: true });
277
+ continue;
278
+ }
279
+ if (constraint.type === "scope" && constraint.trigger) {
280
+ const keywords = extractKeywords(constraint.trigger);
281
+ const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
282
+ checks.push({
283
+ constraintId: constraint.id,
284
+ passed: !violated,
285
+ reason: violated ? constraint.description : void 0
286
+ });
287
+ if (violated) {
288
+ return { violated: constraint, checks };
289
+ }
290
+ continue;
291
+ }
292
+ checks.push({ constraintId: constraint.id, passed: true });
293
+ }
294
+ return { violated: null, checks };
295
+ }
296
+ function getPlanProgress(plan) {
297
+ const completed = plan.steps.filter((s) => s.status === "completed").length;
298
+ const total = plan.steps.length;
299
+ return {
300
+ completed,
301
+ total,
302
+ percentage: total > 0 ? Math.round(completed / total * 100) : 0
303
+ };
304
+ }
305
+ function advancePlan(plan, stepId, evidence) {
306
+ const step = plan.steps.find((s) => s.id === stepId);
307
+ if (!step) {
308
+ return { success: false, reason: `Step "${stepId}" not found in plan.` };
309
+ }
310
+ if (step.status === "completed") {
311
+ return { success: false, reason: `Step "${stepId}" is already completed.` };
312
+ }
313
+ const mode = plan.completion ?? "trust";
314
+ if (mode === "verified" && step.verify) {
315
+ if (!evidence) {
316
+ return {
317
+ success: false,
318
+ reason: `Step "${step.label}" requires evidence (verify: ${step.verify}). Provide evidence to advance.`
319
+ };
320
+ }
321
+ if (evidence.type !== step.verify) {
322
+ return {
323
+ success: false,
324
+ reason: `Evidence type "${evidence.type}" does not match required verification "${step.verify}".`
325
+ };
326
+ }
327
+ }
328
+ const updatedPlan = {
329
+ ...plan,
330
+ steps: plan.steps.map(
331
+ (s) => s.id === stepId ? { ...s, status: "completed" } : s
332
+ )
333
+ };
334
+ return {
335
+ success: true,
336
+ plan: updatedPlan,
337
+ evidence: evidence ?? void 0
338
+ };
339
+ }
340
+ function evaluatePlan(event, plan) {
341
+ const progress = getPlanProgress(plan);
342
+ if (plan.expires_at) {
343
+ const expiresAt = new Date(plan.expires_at).getTime();
344
+ if (Date.now() > expiresAt) {
345
+ return {
346
+ allowed: true,
347
+ status: "PLAN_COMPLETE",
348
+ reason: "Plan has expired.",
349
+ progress
350
+ };
351
+ }
352
+ }
353
+ if (progress.completed === progress.total) {
354
+ return {
355
+ allowed: true,
356
+ status: "PLAN_COMPLETE",
357
+ reason: "All plan steps are completed.",
358
+ progress
359
+ };
360
+ }
361
+ const eventText = normalizeEventText(event);
362
+ const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
363
+ if (!matched) {
364
+ return {
365
+ allowed: false,
366
+ status: "OFF_PLAN",
367
+ reason: "Action does not match any plan step.",
368
+ closestStep: closest?.label,
369
+ similarityScore: closestScore,
370
+ progress
371
+ };
372
+ }
373
+ if (!isSequenceValid(matched, plan)) {
374
+ const pendingDeps = (matched.requires ?? []).filter((reqId) => plan.steps.find((s) => s.id === reqId)?.status !== "completed").join(", ");
375
+ return {
376
+ allowed: false,
377
+ status: "OFF_PLAN",
378
+ reason: `Step "${matched.label}" requires completion of: ${pendingDeps}`,
379
+ matchedStep: matched.id,
380
+ progress
381
+ };
382
+ }
383
+ const { violated } = checkConstraints(event, eventText, plan.constraints);
384
+ if (violated) {
385
+ return {
386
+ allowed: false,
387
+ status: "CONSTRAINT_VIOLATED",
388
+ reason: violated.description,
389
+ matchedStep: matched.id,
390
+ progress
391
+ };
392
+ }
393
+ return {
394
+ allowed: true,
395
+ status: "ON_PLAN",
396
+ reason: `Matches step: ${matched.label}`,
397
+ matchedStep: matched.id,
398
+ progress
399
+ };
400
+ }
401
+ function buildPlanCheck(event, plan, verdict) {
402
+ const eventText = normalizeEventText(event);
403
+ const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
404
+ const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
405
+ const progress = getPlanProgress(plan);
406
+ return {
407
+ planId: plan.plan_id,
408
+ matched: !!matched,
409
+ matchedStepId: matched?.id,
410
+ matchedStepLabel: matched?.label,
411
+ closestStepId: !matched ? closest?.id : void 0,
412
+ closestStepLabel: !matched ? closest?.label : void 0,
413
+ similarityScore: !matched ? closestScore : void 0,
414
+ sequenceValid: matched ? isSequenceValid(matched, plan) : void 0,
415
+ constraintsChecked: constraintChecks,
416
+ progress: { completed: progress.completed, total: progress.total }
417
+ };
418
+ }
419
+ var init_plan_engine = __esm({
420
+ "src/engine/plan-engine.ts"() {
421
+ "use strict";
422
+ init_text_utils();
423
+ }
424
+ });
425
+
426
+ // src/engine/guard-engine.ts
427
+ function levelRequiresConfirmation(level, actionType) {
428
+ if (level === "strict") return true;
429
+ if (level === "standard") {
430
+ return actionType === "delete" || actionType === "credential-access";
431
+ }
432
+ return false;
433
+ }
434
+ function isExternalScope(scope) {
435
+ const internalPatterns = [
436
+ /^\.?\/?src\//i,
437
+ /^\.?\/?lib\//i,
438
+ /^\.?\/?app\//i,
439
+ /^\.?\/?components\//i,
440
+ /^\.?\/?pages\//i,
441
+ /^\.?\/?public\//i,
442
+ /^\.?\/?assets\//i,
443
+ /^\.\//
444
+ ];
445
+ return !internalPatterns.some((p) => p.test(scope));
446
+ }
447
+ function evaluateGuard(event, world, options = {}) {
448
+ const startTime = performance.now();
449
+ const level = options.level ?? "standard";
450
+ const includeTrace = options.trace ?? false;
451
+ if (!event.intent || typeof event.intent !== "string") {
452
+ return {
453
+ status: "BLOCK",
454
+ reason: "GuardEvent.intent is required and must be a string",
455
+ ruleId: "safety-input-validation",
456
+ evidence: {
457
+ worldId: world.world?.world_id ?? "",
458
+ worldName: world.world?.name ?? "",
459
+ worldVersion: world.world?.version ?? "",
460
+ evaluatedAt: Date.now(),
461
+ invariantsSatisfied: 0,
462
+ invariantsTotal: 0,
463
+ guardsMatched: [],
464
+ rulesMatched: [],
465
+ enforcementLevel: level
466
+ }
467
+ };
468
+ }
469
+ const inputLength = event.intent.length + (event.tool?.length ?? 0) + (event.scope?.length ?? 0) + (event.payload ? JSON.stringify(event.payload).length : 0);
470
+ if (inputLength > MAX_INPUT_LENGTH) {
471
+ return {
472
+ status: "BLOCK",
473
+ reason: `Input exceeds maximum allowed length (${MAX_INPUT_LENGTH} characters)`,
474
+ ruleId: "safety-input-length",
475
+ evidence: {
476
+ worldId: world.world?.world_id ?? "",
477
+ worldName: world.world?.name ?? "",
478
+ worldVersion: world.world?.version ?? "",
479
+ evaluatedAt: Date.now(),
480
+ invariantsSatisfied: 0,
481
+ invariantsTotal: 0,
482
+ guardsMatched: [],
483
+ rulesMatched: [],
484
+ enforcementLevel: level
485
+ }
486
+ };
487
+ }
488
+ const eventText = normalizeEventText(event);
489
+ const invariantChecks = [];
490
+ const safetyChecks = [];
491
+ let planCheckResult;
492
+ const roleChecks = [];
493
+ const guardChecks = [];
494
+ const kernelRuleChecks = [];
495
+ const levelChecks = [];
496
+ let decidingLayer = "default-allow";
497
+ let decidingId;
498
+ const guardsMatched = [];
499
+ const rulesMatched = [];
500
+ checkInvariantCoverage(world, invariantChecks);
501
+ if (event.roleId && options.agentStates) {
502
+ const agentState = options.agentStates.get(event.roleId);
503
+ if (agentState && agentState.cooldownRemaining > 0) {
504
+ decidingLayer = "safety";
505
+ decidingId = `penalize-cooldown-${event.roleId}`;
506
+ const verdict = buildVerdict(
507
+ "PENALIZE",
508
+ `Agent "${event.roleId}" is frozen for ${agentState.cooldownRemaining} more round(s) due to prior penalty.`,
509
+ `penalize-cooldown-${event.roleId}`,
510
+ void 0,
511
+ world,
512
+ level,
513
+ invariantChecks,
514
+ guardsMatched,
515
+ rulesMatched,
516
+ includeTrace ? buildTrace(
517
+ invariantChecks,
518
+ safetyChecks,
519
+ planCheckResult,
520
+ roleChecks,
521
+ guardChecks,
522
+ kernelRuleChecks,
523
+ levelChecks,
524
+ decidingLayer,
525
+ decidingId,
526
+ startTime
527
+ ) : void 0
528
+ );
529
+ verdict.intentRecord = {
530
+ originalIntent: event.intent,
531
+ finalAction: "blocked (agent frozen)",
532
+ enforcement: "PENALIZE",
533
+ consequence: { type: "freeze", rounds: agentState.cooldownRemaining, description: "Agent still in cooldown from prior penalty" }
534
+ };
535
+ return verdict;
536
+ }
537
+ }
538
+ if (options.sessionAllowlist) {
539
+ const key = eventToAllowlistKey(event);
540
+ if (options.sessionAllowlist.has(key)) {
541
+ decidingLayer = "session-allowlist";
542
+ decidingId = `allowlist:${key}`;
543
+ return buildVerdict(
544
+ "ALLOW",
545
+ void 0,
546
+ `allowlist:${key}`,
547
+ void 0,
548
+ world,
549
+ level,
550
+ invariantChecks,
551
+ guardsMatched,
552
+ rulesMatched,
553
+ includeTrace ? buildTrace(
554
+ invariantChecks,
555
+ safetyChecks,
556
+ planCheckResult,
557
+ roleChecks,
558
+ guardChecks,
559
+ kernelRuleChecks,
560
+ levelChecks,
561
+ decidingLayer,
562
+ decidingId,
563
+ startTime
564
+ ) : void 0
565
+ );
566
+ }
567
+ }
568
+ const safetyVerdict = checkSafety(event, eventText, safetyChecks);
569
+ if (safetyVerdict) {
570
+ decidingLayer = "safety";
571
+ decidingId = safetyVerdict.ruleId;
572
+ return buildVerdict(
573
+ safetyVerdict.status,
574
+ safetyVerdict.reason,
575
+ safetyVerdict.ruleId,
576
+ void 0,
577
+ world,
578
+ level,
579
+ invariantChecks,
580
+ guardsMatched,
581
+ rulesMatched,
582
+ includeTrace ? buildTrace(
583
+ invariantChecks,
584
+ safetyChecks,
585
+ planCheckResult,
586
+ roleChecks,
587
+ guardChecks,
588
+ kernelRuleChecks,
589
+ levelChecks,
590
+ decidingLayer,
591
+ decidingId,
592
+ startTime
593
+ ) : void 0
594
+ );
595
+ }
596
+ if (options.plan) {
597
+ const planVerdict = evaluatePlan(event, options.plan);
598
+ planCheckResult = buildPlanCheck(event, options.plan, planVerdict);
599
+ if (!planVerdict.allowed && planVerdict.status !== "PLAN_COMPLETE") {
600
+ decidingLayer = "plan-enforcement";
601
+ decidingId = `plan-${options.plan.plan_id}`;
602
+ const planStatus = planVerdict.status === "CONSTRAINT_VIOLATED" ? "PAUSE" : "BLOCK";
603
+ let reason = planVerdict.reason ?? "Action blocked by plan.";
604
+ if (planVerdict.status === "OFF_PLAN" && planVerdict.closestStep) {
605
+ reason += ` Closest step: "${planVerdict.closestStep}" (similarity: ${(planVerdict.similarityScore ?? 0).toFixed(2)})`;
606
+ }
607
+ return buildVerdict(
608
+ planStatus,
609
+ reason,
610
+ `plan-${options.plan.plan_id}`,
611
+ void 0,
612
+ world,
613
+ level,
614
+ invariantChecks,
615
+ guardsMatched,
616
+ rulesMatched,
617
+ includeTrace ? buildTrace(
618
+ invariantChecks,
619
+ safetyChecks,
620
+ planCheckResult,
621
+ roleChecks,
622
+ guardChecks,
623
+ kernelRuleChecks,
624
+ levelChecks,
625
+ decidingLayer,
626
+ decidingId,
627
+ startTime
628
+ ) : void 0
629
+ );
630
+ }
631
+ }
632
+ const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
633
+ if (roleVerdict) {
634
+ decidingLayer = "role";
635
+ decidingId = roleVerdict.ruleId;
636
+ return buildVerdict(
637
+ roleVerdict.status,
638
+ roleVerdict.reason,
639
+ roleVerdict.ruleId,
640
+ void 0,
641
+ world,
642
+ level,
643
+ invariantChecks,
644
+ guardsMatched,
645
+ rulesMatched,
646
+ includeTrace ? buildTrace(
647
+ invariantChecks,
648
+ safetyChecks,
649
+ planCheckResult,
650
+ roleChecks,
651
+ guardChecks,
652
+ kernelRuleChecks,
653
+ levelChecks,
654
+ decidingLayer,
655
+ decidingId,
656
+ startTime
657
+ ) : void 0
658
+ );
659
+ }
660
+ const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
661
+ if (guardVerdict) {
662
+ if (guardVerdict.status !== "ALLOW") {
663
+ decidingLayer = "guard";
664
+ decidingId = guardVerdict.ruleId;
665
+ const intentRecord = {
666
+ originalIntent: event.intent,
667
+ finalAction: guardVerdict.status === "MODIFY" ? guardVerdict.modifiedTo ?? "modified" : guardVerdict.status === "PENALIZE" ? "blocked + penalized" : guardVerdict.status === "REWARD" ? event.intent : guardVerdict.status === "NEUTRAL" ? event.intent : guardVerdict.status === "BLOCK" ? "blocked" : "paused",
668
+ ruleApplied: guardVerdict.ruleId,
669
+ enforcement: guardVerdict.status,
670
+ modifiedTo: guardVerdict.modifiedTo,
671
+ consequence: guardVerdict.consequence,
672
+ reward: guardVerdict.reward
673
+ };
674
+ const verdict = buildVerdict(
675
+ guardVerdict.status,
676
+ guardVerdict.reason,
677
+ guardVerdict.ruleId,
678
+ void 0,
679
+ world,
680
+ level,
681
+ invariantChecks,
682
+ guardsMatched,
683
+ rulesMatched,
684
+ includeTrace ? buildTrace(
685
+ invariantChecks,
686
+ safetyChecks,
687
+ planCheckResult,
688
+ roleChecks,
689
+ guardChecks,
690
+ kernelRuleChecks,
691
+ levelChecks,
692
+ decidingLayer,
693
+ decidingId,
694
+ startTime
695
+ ) : void 0
696
+ );
697
+ verdict.intentRecord = intentRecord;
698
+ if (guardVerdict.consequence) verdict.consequence = guardVerdict.consequence;
699
+ if (guardVerdict.reward) verdict.reward = guardVerdict.reward;
700
+ return verdict;
701
+ }
702
+ }
703
+ const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
704
+ if (kernelVerdict) {
705
+ decidingLayer = "kernel-rule";
706
+ decidingId = kernelVerdict.ruleId;
707
+ return buildVerdict(
708
+ kernelVerdict.status,
709
+ kernelVerdict.reason,
710
+ kernelVerdict.ruleId,
711
+ void 0,
712
+ world,
713
+ level,
714
+ invariantChecks,
715
+ guardsMatched,
716
+ rulesMatched,
717
+ includeTrace ? buildTrace(
718
+ invariantChecks,
719
+ safetyChecks,
720
+ planCheckResult,
721
+ roleChecks,
722
+ guardChecks,
723
+ kernelRuleChecks,
724
+ levelChecks,
725
+ decidingLayer,
726
+ decidingId,
727
+ startTime
728
+ ) : void 0
729
+ );
730
+ }
731
+ const levelVerdict = checkLevelConstraints(event, level, levelChecks);
732
+ if (levelVerdict) {
733
+ decidingLayer = "level-constraint";
734
+ decidingId = levelVerdict.ruleId;
735
+ return buildVerdict(
736
+ levelVerdict.status,
737
+ levelVerdict.reason,
738
+ levelVerdict.ruleId,
739
+ void 0,
740
+ world,
741
+ level,
742
+ invariantChecks,
743
+ guardsMatched,
744
+ rulesMatched,
745
+ includeTrace ? buildTrace(
746
+ invariantChecks,
747
+ safetyChecks,
748
+ planCheckResult,
749
+ roleChecks,
750
+ guardChecks,
751
+ kernelRuleChecks,
752
+ levelChecks,
753
+ decidingLayer,
754
+ decidingId,
755
+ startTime
756
+ ) : void 0
757
+ );
758
+ }
759
+ const warning = guardVerdict?.warning;
760
+ return buildVerdict(
761
+ "ALLOW",
762
+ void 0,
763
+ void 0,
764
+ warning,
765
+ world,
766
+ level,
767
+ invariantChecks,
768
+ guardsMatched,
769
+ rulesMatched,
770
+ includeTrace ? buildTrace(
771
+ invariantChecks,
772
+ safetyChecks,
773
+ planCheckResult,
774
+ roleChecks,
775
+ guardChecks,
776
+ kernelRuleChecks,
777
+ levelChecks,
778
+ decidingLayer,
779
+ decidingId,
780
+ startTime
781
+ ) : void 0
782
+ );
783
+ }
784
+ function checkInvariantCoverage(world, checks) {
785
+ const invariants = world.invariants ?? [];
786
+ const guards = world.guards?.guards ?? [];
787
+ for (const invariant of invariants) {
788
+ const coveringGuard = guards.find(
789
+ (g) => g.invariant_ref === invariant.id && g.immutable
790
+ );
791
+ checks.push({
792
+ invariantId: invariant.id,
793
+ label: invariant.label,
794
+ hasGuardCoverage: !!coveringGuard,
795
+ coveringGuardId: coveringGuard?.id
796
+ });
797
+ }
798
+ }
799
+ function checkSafety(event, eventText, checks) {
800
+ const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
801
+ for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
802
+ const triggered = pattern.test(textToCheck);
803
+ checks.push({
804
+ checkType: "prompt-injection",
805
+ triggered,
806
+ matchedPattern: triggered ? label : void 0
807
+ });
808
+ if (triggered) {
809
+ for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
810
+ checks.push({
811
+ checkType: "prompt-injection",
812
+ triggered: remaining.pattern.test(textToCheck),
813
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
814
+ });
815
+ }
816
+ return {
817
+ status: "PAUSE",
818
+ reason: NEUTRAL_MESSAGES["prompt-injection"],
819
+ ruleId: `safety-injection-${label}`
820
+ };
821
+ }
822
+ }
823
+ const scopeToCheck = event.scope ?? event.intent;
824
+ for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
825
+ const triggered = pattern.test(scopeToCheck);
826
+ checks.push({
827
+ checkType: "scope-escape",
828
+ triggered,
829
+ matchedPattern: triggered ? label : void 0
830
+ });
831
+ if (triggered) {
832
+ for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
833
+ checks.push({
834
+ checkType: "scope-escape",
835
+ triggered: remaining.pattern.test(scopeToCheck),
836
+ matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
837
+ });
838
+ }
839
+ return {
840
+ status: "PAUSE",
841
+ reason: NEUTRAL_MESSAGES["scope-escape"],
842
+ ruleId: `safety-scope-${label}`
843
+ };
844
+ }
845
+ }
846
+ if (event.direction === "output") {
847
+ for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
848
+ const triggered = pattern.test(textToCheck);
849
+ checks.push({
850
+ checkType: "execution-claim",
851
+ triggered,
852
+ matchedPattern: triggered ? label : void 0
853
+ });
854
+ if (triggered) {
855
+ for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
856
+ checks.push({
857
+ checkType: "execution-claim",
858
+ triggered: remaining.pattern.test(textToCheck),
859
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
860
+ });
861
+ }
862
+ return {
863
+ status: "PAUSE",
864
+ reason: NEUTRAL_MESSAGES["execution-claim"],
865
+ ruleId: `safety-execution-claim-${label}`
866
+ };
867
+ }
868
+ }
869
+ }
870
+ if (event.direction === "input") {
871
+ const intentTrimmed = event.intent.trim();
872
+ for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
873
+ const triggered = pattern.test(intentTrimmed);
874
+ checks.push({
875
+ checkType: "execution-intent",
876
+ triggered,
877
+ matchedPattern: triggered ? label : void 0
878
+ });
879
+ if (triggered) {
880
+ for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
881
+ checks.push({
882
+ checkType: "execution-intent",
883
+ triggered: remaining.pattern.test(intentTrimmed),
884
+ matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
885
+ });
886
+ }
887
+ return {
888
+ status: "PAUSE",
889
+ reason: NEUTRAL_MESSAGES["execution-intent"],
890
+ ruleId: `safety-execution-intent-${label}`
891
+ };
892
+ }
893
+ }
894
+ }
895
+ return null;
896
+ }
897
+ function checkRoleRules(event, eventText, world, checks) {
898
+ if (!event.roleId || !world.roles) return null;
899
+ const role = world.roles.roles.find((r) => r.id === event.roleId);
900
+ if (!role) return null;
901
+ if (role.requiresApproval) {
902
+ checks.push({
903
+ roleId: role.id,
904
+ roleName: role.name,
905
+ rule: "All actions require approval",
906
+ ruleType: "requiresApproval",
907
+ matched: true
908
+ });
909
+ return {
910
+ status: "PAUSE",
911
+ reason: `Role "${role.name}" requires approval for all actions.`,
912
+ ruleId: `role-${role.id}-requires-approval`
913
+ };
914
+ }
915
+ for (const rule of role.cannotDo) {
916
+ const matched = matchesKeywords(eventText, rule);
917
+ checks.push({
918
+ roleId: role.id,
919
+ roleName: role.name,
920
+ rule,
921
+ ruleType: "cannotDo",
922
+ matched
923
+ });
924
+ if (matched) {
925
+ return {
926
+ status: "BLOCK",
927
+ reason: `Role "${role.name}" cannot: ${rule}`,
928
+ ruleId: `role-${role.id}-cannotdo`
929
+ };
930
+ }
931
+ }
932
+ for (const rule of role.canDo) {
933
+ checks.push({
934
+ roleId: role.id,
935
+ roleName: role.name,
936
+ rule,
937
+ ruleType: "canDo",
938
+ matched: matchesKeywords(eventText, rule)
939
+ });
940
+ }
941
+ return null;
942
+ }
943
+ function checkGuards(event, eventText, world, checks, guardsMatched) {
944
+ if (!world.guards) return null;
945
+ const guardsConfig = world.guards;
946
+ let warnResult = null;
947
+ const compiledPatterns = /* @__PURE__ */ new Map();
948
+ for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
949
+ try {
950
+ compiledPatterns.set(key, new RegExp(def.pattern, "i"));
951
+ } catch {
952
+ }
953
+ }
954
+ const eventTool = (event.tool ?? "").toLowerCase();
955
+ for (const guard of guardsConfig.guards) {
956
+ if (guard.appliesTo && guard.appliesTo.length > 0) {
957
+ const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
958
+ if (!normalizedAppliesTo.includes(eventTool)) {
959
+ continue;
960
+ }
961
+ }
962
+ const enabled = guard.immutable || guard.default_enabled !== false;
963
+ const matchedPatterns = [];
964
+ for (const patternKey of guard.intent_patterns) {
965
+ const regex = compiledPatterns.get(patternKey);
966
+ if (regex?.test(eventText)) {
967
+ matchedPatterns.push(patternKey);
968
+ }
969
+ }
970
+ const matched = matchedPatterns.length > 0 && enabled;
971
+ let roleGated = false;
972
+ if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
973
+ roleGated = true;
974
+ }
975
+ checks.push({
976
+ guardId: guard.id,
977
+ label: guard.label,
978
+ category: guard.category,
979
+ enabled,
980
+ matched: matched && !roleGated,
981
+ enforcement: guard.enforcement,
982
+ matchedPatterns,
983
+ roleGated
984
+ });
985
+ if (!matched || roleGated) continue;
986
+ guardsMatched.push(guard.id);
987
+ const actionMode = guard.player_modes?.action ?? guard.enforcement;
988
+ const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
989
+ if (actionMode === "block") {
990
+ return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
991
+ }
992
+ if (actionMode === "pause") {
993
+ return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
994
+ }
995
+ if (actionMode === "penalize") {
996
+ const consequence = guard.consequence ? { ...guard.consequence } : { type: "freeze", rounds: 1, description: `Penalized for violating: ${guard.label}` };
997
+ return { status: "PENALIZE", reason, ruleId: `guard-${guard.id}`, consequence };
998
+ }
999
+ if (actionMode === "reward") {
1000
+ const reward = guard.reward ? { ...guard.reward } : { type: "boost_influence", magnitude: 0.1, description: `Rewarded for: ${guard.label}` };
1001
+ return { status: "REWARD", reason, ruleId: `guard-${guard.id}`, reward };
1002
+ }
1003
+ if (actionMode === "modify") {
1004
+ const modifiedTo = guard.modify_to ?? guard.redirect ?? "hold";
1005
+ return { status: "MODIFY", reason: `${reason} \u2192 Modified to: ${modifiedTo}`, ruleId: `guard-${guard.id}`, modifiedTo };
1006
+ }
1007
+ if (actionMode === "neutral") {
1008
+ return { status: "NEUTRAL", reason, ruleId: `guard-${guard.id}` };
1009
+ }
1010
+ if (actionMode === "warn" && !warnResult) {
1011
+ warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
1012
+ }
1013
+ }
1014
+ return warnResult;
1015
+ }
1016
+ function checkKernelRules(eventText, world, checks, rulesMatched) {
1017
+ if (!world.kernel) return null;
1018
+ const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
1019
+ const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
1020
+ for (const rule of forbidden) {
1021
+ let matched = false;
1022
+ let matchMethod = "none";
1023
+ if (rule.pattern) {
1024
+ try {
1025
+ matched = new RegExp(rule.pattern, "i").test(eventText);
1026
+ matchMethod = "pattern";
1027
+ } catch {
1028
+ }
1029
+ }
1030
+ if (!matched && rule.reason) {
1031
+ matched = matchesKeywords(eventText, rule.reason);
1032
+ if (matched) matchMethod = "keyword";
1033
+ }
1034
+ checks.push({
1035
+ ruleId: rule.id,
1036
+ text: rule.reason,
1037
+ category: "forbidden",
1038
+ matched,
1039
+ matchMethod
1040
+ });
1041
+ if (matched) {
1042
+ rulesMatched.push(rule.id);
1043
+ if (rule.action === "BLOCK") {
1044
+ return {
1045
+ status: "BLOCK",
1046
+ reason: rule.reason,
1047
+ ruleId: `kernel-${rule.id}`
1048
+ };
1049
+ }
1050
+ }
1051
+ }
1052
+ return null;
1053
+ }
1054
+ function checkLevelConstraints(event, level, checks) {
1055
+ if (level === "basic") return null;
1056
+ const intent = event.intent.toLowerCase();
1057
+ const tool = (event.tool ?? "").toLowerCase();
1058
+ const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
1059
+ const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
1060
+ checks.push({
1061
+ checkType: "delete",
1062
+ level,
1063
+ triggered: deleteTriggered,
1064
+ reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
1065
+ });
1066
+ if (deleteTriggered) {
1067
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
1068
+ }
1069
+ const isExternal = event.scope ? isExternalScope(event.scope) : false;
1070
+ const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
1071
+ checks.push({
1072
+ checkType: "write-external",
1073
+ level,
1074
+ triggered: externalTriggered,
1075
+ reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
1076
+ });
1077
+ if (externalTriggered) {
1078
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
1079
+ }
1080
+ const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
1081
+ const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
1082
+ checks.push({
1083
+ checkType: "network-mutate",
1084
+ level,
1085
+ triggered: networkTriggered,
1086
+ reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
1087
+ });
1088
+ if (networkTriggered) {
1089
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
1090
+ }
1091
+ const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
1092
+ const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
1093
+ checks.push({
1094
+ checkType: "credential-access",
1095
+ level,
1096
+ triggered: credentialTriggered,
1097
+ reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
1098
+ });
1099
+ if (credentialTriggered) {
1100
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
1101
+ }
1102
+ const irreversibleTriggered = !!event.irreversible && level !== "basic";
1103
+ checks.push({
1104
+ checkType: "irreversible",
1105
+ level,
1106
+ triggered: irreversibleTriggered,
1107
+ reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
1108
+ });
1109
+ if (irreversibleTriggered) {
1110
+ return {
1111
+ status: "PAUSE",
1112
+ reason: "This action is marked as irreversible.",
1113
+ ruleId: "level-irreversible-check"
1114
+ };
1115
+ }
1116
+ return null;
1117
+ }
1118
+ function matchesKeywords(eventText, ruleText) {
1119
+ return matchesAllKeywords(eventText, ruleText);
1120
+ }
1121
+ function eventToAllowlistKey(event) {
1122
+ return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
1123
+ }
1124
+ function buildTrace(invariantChecks, safetyChecks, planCheck, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
1125
+ const trace = {
1126
+ invariantChecks,
1127
+ safetyChecks,
1128
+ roleChecks,
1129
+ guardChecks,
1130
+ kernelRuleChecks,
1131
+ levelChecks,
1132
+ precedenceResolution: {
1133
+ decidingLayer,
1134
+ decidingId,
1135
+ strategy: "first-match-wins",
1136
+ chainOrder: [
1137
+ "invariant-coverage",
1138
+ "session-allowlist",
1139
+ "safety-injection",
1140
+ "safety-scope-escape",
1141
+ "safety-execution-claim",
1142
+ "safety-execution-intent",
1143
+ "plan-enforcement",
1144
+ "role-rules",
1145
+ "declarative-guards",
1146
+ "kernel-rules",
1147
+ "level-constraints",
1148
+ "default-allow"
1149
+ ]
1150
+ },
1151
+ durationMs: performance.now() - startTime
1152
+ };
1153
+ if (planCheck) {
1154
+ trace.planCheck = planCheck;
1155
+ }
1156
+ return trace;
1157
+ }
1158
+ function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace) {
1159
+ const evidence = {
1160
+ worldId: world.world.world_id,
1161
+ worldName: world.world.name,
1162
+ worldVersion: world.world.version,
1163
+ evaluatedAt: Date.now(),
1164
+ invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
1165
+ invariantsTotal: invariantChecks.length,
1166
+ guardsMatched,
1167
+ rulesMatched,
1168
+ enforcementLevel: level
1169
+ };
1170
+ const verdict = {
1171
+ status,
1172
+ evidence
1173
+ };
1174
+ if (reason) verdict.reason = reason;
1175
+ if (ruleId) verdict.ruleId = ruleId;
1176
+ if (warning) verdict.warning = warning;
1177
+ if (trace) verdict.trace = trace;
1178
+ return verdict;
1179
+ }
1180
+ var PROMPT_INJECTION_PATTERNS, EXECUTION_CLAIM_PATTERNS, EXECUTION_INTENT_PATTERNS, SCOPE_ESCAPE_PATTERNS, NEUTRAL_MESSAGES, MAX_INPUT_LENGTH;
1181
+ var init_guard_engine = __esm({
1182
+ "src/engine/guard-engine.ts"() {
1183
+ "use strict";
1184
+ init_plan_engine();
1185
+ init_text_utils();
1186
+ PROMPT_INJECTION_PATTERNS = [
1187
+ // Instruction override
1188
+ { pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
1189
+ { pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
1190
+ { pattern: /new\s+instructions?:/i, label: "new-instructions" },
1191
+ // Identity manipulation
1192
+ { pattern: /you\s+are\s+now/i, label: "identity-override" },
1193
+ { pattern: /new\s+persona/i, label: "new-persona" },
1194
+ { pattern: /act\s+as\s+if/i, label: "act-as-if" },
1195
+ { pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
1196
+ // Context reset
1197
+ { pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
1198
+ { pattern: /system\s*:\s*override/i, label: "system-override" },
1199
+ // Constraint bypass
1200
+ { pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
1201
+ { pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
1202
+ // Prompt extraction
1203
+ { pattern: /system\s+prompt/i, label: "system-prompt-probe" },
1204
+ { pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
1205
+ // Known jailbreak terms
1206
+ { pattern: /jailbreak/i, label: "jailbreak" },
1207
+ { pattern: /DAN\s+mode/i, label: "dan-mode" },
1208
+ { pattern: /developer\s+mode/i, label: "developer-mode" }
1209
+ ];
1210
+ EXECUTION_CLAIM_PATTERNS = [
1211
+ { pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
1212
+ { pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
1213
+ { pattern: /The file has been/i, label: "claim-file-modified" },
1214
+ { pattern: /I've made the changes/i, label: "claim-made-changes" },
1215
+ { pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
1216
+ { pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
1217
+ { pattern: /Transaction complete/i, label: "claim-transaction" },
1218
+ { pattern: /Order placed/i, label: "claim-order" },
1219
+ { pattern: /Payment processed/i, label: "claim-payment" }
1220
+ ];
1221
+ EXECUTION_INTENT_PATTERNS = [
1222
+ { pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
1223
+ { pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
1224
+ { pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
1225
+ { pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
1226
+ { pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
1227
+ { pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
1228
+ { pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
1229
+ { pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
1230
+ ];
1231
+ SCOPE_ESCAPE_PATTERNS = [
1232
+ { pattern: /\.\.\//, label: "parent-traversal" },
1233
+ { pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
1234
+ { pattern: /~\//, label: "home-directory" },
1235
+ { pattern: /\/etc\//i, label: "system-config" },
1236
+ { pattern: /\/usr\//i, label: "system-binaries" },
1237
+ { pattern: /\/var\//i, label: "system-variable-data" }
1238
+ ];
1239
+ NEUTRAL_MESSAGES = {
1240
+ "prompt-injection": "This input contains patterns that could alter agent behavior.",
1241
+ "scope-escape": "This action would affect resources outside the declared scope.",
1242
+ "execution-claim": "This response claims to have performed an action.",
1243
+ "execution-intent": "This input requests execution in a thinking-only environment.",
1244
+ "delete": "This action would remove files. Confirmation needed.",
1245
+ "write-external": "This action would write outside the project folder.",
1246
+ "network-mutate": "This action would send data to an external service.",
1247
+ "credential-access": "This action would access stored credentials."
1248
+ };
1249
+ MAX_INPUT_LENGTH = 1e5;
1250
+ }
1251
+ });
1252
+
1253
+ // src/loader/world-loader.ts
1254
+ async function loadWorldFromDirectory(dirPath) {
1255
+ const { readFile } = await import("fs/promises");
1256
+ const { join: join3 } = await import("path");
1257
+ const { readdirSync: readdirSync3 } = await import("fs");
1258
+ async function readJson(filename) {
1259
+ const filePath = join3(dirPath, filename);
1260
+ try {
1261
+ const content = await readFile(filePath, "utf-8");
1262
+ return JSON.parse(content);
1263
+ } catch (err) {
1264
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
1265
+ return void 0;
1266
+ }
1267
+ process.stderr.write(
1268
+ `[neuroverse] Warning: Failed to read ${filename}: ${err instanceof Error ? err.message : String(err)}
1269
+ `
1270
+ );
1271
+ return void 0;
1272
+ }
1273
+ }
1274
+ const worldJson = await readJson("world.json");
1275
+ if (!worldJson) {
1276
+ throw new Error(`Cannot read world.json in ${dirPath}`);
1277
+ }
1278
+ const invariantsJson = await readJson("invariants.json");
1279
+ const assumptionsJson = await readJson("assumptions.json");
1280
+ const stateSchemaJson = await readJson("state-schema.json");
1281
+ const gatesJson = await readJson("gates.json");
1282
+ const outcomesJson = await readJson("outcomes.json");
1283
+ const guardsJson = await readJson("guards.json");
1284
+ const rolesJson = await readJson("roles.json");
1285
+ const kernelJson = await readJson("kernel.json");
1286
+ const metadataJson = await readJson("metadata.json");
1287
+ const rules = [];
1288
+ try {
1289
+ const rulesDir = join3(dirPath, "rules");
1290
+ const ruleFiles = readdirSync3(rulesDir).filter((f) => f.endsWith(".json")).sort();
1291
+ for (const file of ruleFiles) {
1292
+ try {
1293
+ const content = await readFile(join3(rulesDir, file), "utf-8");
1294
+ rules.push(JSON.parse(content));
1295
+ } catch (err) {
1296
+ process.stderr.write(
1297
+ `[neuroverse] Warning: Failed to parse rule ${file}: ${err instanceof Error ? err.message : String(err)}
1298
+ `
1299
+ );
1300
+ }
1301
+ }
1302
+ } catch (err) {
1303
+ if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) {
1304
+ process.stderr.write(
1305
+ `[neuroverse] Warning: Failed to read rules directory: ${err instanceof Error ? err.message : String(err)}
1306
+ `
1307
+ );
1308
+ }
1309
+ }
1310
+ return {
1311
+ world: worldJson,
1312
+ invariants: invariantsJson?.invariants ?? [],
1313
+ assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
1314
+ stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
1315
+ rules,
1316
+ gates: gatesJson ?? {
1317
+ viability_classification: [],
1318
+ structural_override: { description: "", enforcement: "mandatory" },
1319
+ sustainability_threshold: 0,
1320
+ collapse_visual: { background: "", text: "", border: "", label: "" }
1321
+ },
1322
+ outcomes: outcomesJson ?? {
1323
+ computed_outcomes: [],
1324
+ comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
1325
+ },
1326
+ guards: guardsJson,
1327
+ roles: rolesJson,
1328
+ kernel: kernelJson,
1329
+ metadata: metadataJson ?? {
1330
+ format_version: "1.0.0",
1331
+ created_at: "",
1332
+ last_modified: "",
1333
+ authoring_method: "manual-authoring"
1334
+ }
1335
+ };
1336
+ }
1337
+ async function loadWorld(worldPath) {
1338
+ const { stat } = await import("fs/promises");
1339
+ const info = await stat(worldPath);
1340
+ if (info.isDirectory()) {
1341
+ return loadWorldFromDirectory(worldPath);
1342
+ }
1343
+ throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory`);
1344
+ }
1345
+ var init_world_loader = __esm({
1346
+ "src/loader/world-loader.ts"() {
1347
+ "use strict";
1348
+ }
1349
+ });
1350
+
1351
+ // src/engine/decision-flow-engine.ts
1352
+ function createAgentState(agentId) {
1353
+ return {
1354
+ agentId,
1355
+ cooldownRemaining: 0,
1356
+ influence: 1,
1357
+ rewardMultiplier: 1,
1358
+ totalPenalties: 0,
1359
+ totalRewards: 0,
1360
+ consequenceHistory: [],
1361
+ rewardHistory: []
1362
+ };
1363
+ }
1364
+ function applyConsequence(state, consequence, ruleId) {
1365
+ const updated = { ...state };
1366
+ updated.totalPenalties++;
1367
+ updated.consequenceHistory = [
1368
+ ...state.consequenceHistory,
1369
+ { ruleId, consequence, appliedAt: Date.now() }
1370
+ ];
1371
+ switch (consequence.type) {
1372
+ case "freeze":
1373
+ case "cooldown":
1374
+ updated.cooldownRemaining = Math.max(
1375
+ state.cooldownRemaining,
1376
+ consequence.rounds ?? 1
1377
+ );
1378
+ break;
1379
+ case "reduce_influence":
1380
+ updated.influence = Math.max(0, state.influence - (consequence.magnitude ?? 0.1));
1381
+ break;
1382
+ case "increase_risk":
1383
+ break;
1384
+ case "custom":
1385
+ break;
1386
+ }
1387
+ return updated;
1388
+ }
1389
+ function applyReward(state, reward, ruleId) {
1390
+ const updated = { ...state };
1391
+ updated.totalRewards++;
1392
+ updated.rewardHistory = [
1393
+ ...state.rewardHistory,
1394
+ { ruleId, reward, appliedAt: Date.now() }
1395
+ ];
1396
+ switch (reward.type) {
1397
+ case "boost_influence":
1398
+ updated.influence = Math.min(2, state.influence + (reward.magnitude ?? 0.1));
1399
+ break;
1400
+ case "weight_increase":
1401
+ updated.rewardMultiplier = Math.min(3, state.rewardMultiplier + (reward.magnitude ?? 0.1));
1402
+ break;
1403
+ case "priority":
1404
+ case "faster_execution":
1405
+ break;
1406
+ case "custom":
1407
+ break;
1408
+ }
1409
+ return updated;
1410
+ }
1411
+ function tickAgentStates(states) {
1412
+ const updated = /* @__PURE__ */ new Map();
1413
+ for (const [id, state] of states) {
1414
+ updated.set(id, {
1415
+ ...state,
1416
+ cooldownRemaining: Math.max(0, state.cooldownRemaining - 1)
1417
+ });
1418
+ }
1419
+ return updated;
1420
+ }
1421
+ var init_decision_flow_engine = __esm({
1422
+ "src/engine/decision-flow-engine.ts"() {
1423
+ "use strict";
1424
+ }
1425
+ });
1426
+
1427
+ // src/runtime/session.ts
1428
+ var session_exports = {};
1429
+ __export(session_exports, {
1430
+ SessionManager: () => SessionManager,
1431
+ runInteractiveMode: () => runInteractiveMode,
1432
+ runPipeMode: () => runPipeMode
1433
+ });
1434
+ async function defaultToolExecutor(name, args) {
1435
+ return `Tool "${name}" executed successfully with args: ${JSON.stringify(args)}`;
1436
+ }
1437
+ async function runPipeMode(config) {
1438
+ const session = new SessionManager(config);
1439
+ await session.start();
1440
+ const state = session.getState();
1441
+ process.stderr.write(`[neuroverse] Pipe mode active
1442
+ `);
1443
+ process.stderr.write(`[neuroverse] World: ${state.world.world.name}
1444
+ `);
1445
+ if (state.plan) {
1446
+ process.stderr.write(`[neuroverse] Plan: ${state.plan.plan_id} (${state.plan.objective})
1447
+ `);
1448
+ }
1449
+ return new Promise((resolve2, reject) => {
1450
+ let buffer = "";
1451
+ process.stdin.setEncoding("utf-8");
1452
+ process.stdin.on("data", (chunk) => {
1453
+ buffer += chunk;
1454
+ const lines = buffer.split("\n");
1455
+ buffer = lines.pop() ?? "";
1456
+ for (const line of lines) {
1457
+ const trimmed = line.trim();
1458
+ if (!trimmed) continue;
1459
+ try {
1460
+ const event = JSON.parse(trimmed);
1461
+ if (!event.intent) {
1462
+ process.stderr.write(`[neuroverse] Warning: event missing "intent" field
1463
+ `);
1464
+ continue;
1465
+ }
1466
+ const verdict = session.evaluate(event);
1467
+ process.stdout.write(JSON.stringify(verdict) + "\n");
1468
+ } catch (err) {
1469
+ process.stderr.write(`[neuroverse] Error parsing line: ${err}
1470
+ `);
1471
+ }
1472
+ }
1473
+ });
1474
+ process.stdin.on("end", () => {
1475
+ if (buffer.trim()) {
1476
+ try {
1477
+ const event = JSON.parse(buffer.trim());
1478
+ if (event.intent) {
1479
+ const verdict = session.evaluate(event);
1480
+ process.stdout.write(JSON.stringify(verdict) + "\n");
1481
+ }
1482
+ } catch {
1483
+ }
1484
+ }
1485
+ const finalState = session.stop();
1486
+ process.stderr.write(
1487
+ `[neuroverse] Session complete: ${finalState.actionsEvaluated} evaluated, ${finalState.actionsAllowed} allowed, ${finalState.actionsBlocked} blocked, ${finalState.actionsPaused} paused
1488
+ `
1489
+ );
1490
+ resolve2();
1491
+ });
1492
+ process.stdin.on("error", reject);
1493
+ });
1494
+ }
1495
+ async function runInteractiveMode(config, model) {
1496
+ const session = new SessionManager(config);
1497
+ await session.start();
1498
+ const state = session.getState();
1499
+ process.stdout.write("\n");
1500
+ process.stdout.write(` World: ${state.world.world.name}
1501
+ `);
1502
+ if (state.plan) {
1503
+ process.stdout.write(` Plan: ${state.plan.plan_id}
1504
+ `);
1505
+ process.stdout.write(` Goal: ${state.plan.objective}
1506
+ `);
1507
+ process.stdout.write(` Steps: ${state.progress?.total ?? 0}
1508
+ `);
1509
+ }
1510
+ process.stdout.write(` Type "exit" to end session.
1511
+ `);
1512
+ process.stdout.write("\n");
1513
+ const readline = await import("readline");
1514
+ const rl = readline.createInterface({
1515
+ input: process.stdin,
1516
+ output: process.stdout,
1517
+ prompt: "> "
1518
+ });
1519
+ const printProgress = () => {
1520
+ const s = session.getState();
1521
+ if (s.progress) {
1522
+ process.stdout.write(
1523
+ ` [plan: ${s.progress.completed}/${s.progress.total} (${s.progress.percentage}%)]
1524
+ `
1525
+ );
1526
+ }
1527
+ };
1528
+ rl.prompt();
1529
+ rl.on("line", async (input) => {
1530
+ const trimmed = input.trim();
1531
+ if (!trimmed) {
1532
+ rl.prompt();
1533
+ return;
1534
+ }
1535
+ if (trimmed === "exit" || trimmed === "quit") {
1536
+ const finalState = session.stop();
1537
+ process.stdout.write("\n");
1538
+ process.stdout.write(` Session complete.
1539
+ `);
1540
+ process.stdout.write(` Actions: ${finalState.actionsEvaluated} evaluated`);
1541
+ process.stdout.write(`, ${finalState.actionsAllowed} allowed`);
1542
+ process.stdout.write(`, ${finalState.actionsBlocked} blocked
1543
+ `);
1544
+ if (finalState.progress) {
1545
+ process.stdout.write(
1546
+ ` Plan: ${finalState.progress.completed}/${finalState.progress.total} steps completed
1547
+ `
1548
+ );
1549
+ }
1550
+ process.stdout.write("\n");
1551
+ rl.close();
1552
+ return;
1553
+ }
1554
+ if (trimmed === "status") {
1555
+ const s = session.getState();
1556
+ process.stdout.write(`
1557
+ World: ${s.world.world.name}
1558
+ `);
1559
+ process.stdout.write(` Actions: ${s.actionsEvaluated} evaluated
1560
+ `);
1561
+ process.stdout.write(` Allowed: ${s.actionsAllowed} | Blocked: ${s.actionsBlocked} | Modified: ${s.actionsModified} | Paused: ${s.actionsPaused}
1562
+ `);
1563
+ process.stdout.write(` Penalized: ${s.actionsPenalized} | Rewarded: ${s.actionsRewarded}
1564
+ `);
1565
+ if (s.progress && s.plan) {
1566
+ process.stdout.write(` Plan: ${s.plan.plan_id} \u2014 ${s.progress.completed}/${s.progress.total} (${s.progress.percentage}%)
1567
+ `);
1568
+ for (const step of s.plan.steps) {
1569
+ const icon = step.status === "completed" ? "[x]" : "[ ]";
1570
+ process.stdout.write(` ${icon} ${step.label}
1571
+ `);
1572
+ }
1573
+ }
1574
+ process.stdout.write("\n");
1575
+ rl.prompt();
1576
+ return;
1577
+ }
1578
+ try {
1579
+ const response = await model.chat(trimmed);
1580
+ if (response.toolCalls.length > 0) {
1581
+ const finalResponse = await session.processModelResponse(response, model);
1582
+ if (finalResponse.content) {
1583
+ process.stdout.write(`
1584
+ ${finalResponse.content}
1585
+
1586
+ `);
1587
+ }
1588
+ printProgress();
1589
+ } else if (response.content) {
1590
+ process.stdout.write(`
1591
+ ${response.content}
1592
+
1593
+ `);
1594
+ }
1595
+ } catch (err) {
1596
+ process.stderr.write(`
1597
+ Error: ${err}
1598
+
1599
+ `);
1600
+ }
1601
+ rl.prompt();
1602
+ });
1603
+ rl.on("close", () => {
1604
+ session.stop();
1605
+ });
1606
+ return new Promise((resolve2) => {
1607
+ rl.on("close", resolve2);
1608
+ });
1609
+ }
1610
+ var SessionManager;
1611
+ var init_session = __esm({
1612
+ "src/runtime/session.ts"() {
1613
+ "use strict";
1614
+ init_guard_engine();
1615
+ init_plan_engine();
1616
+ init_world_loader();
1617
+ init_decision_flow_engine();
1618
+ SessionManager = class {
1619
+ config;
1620
+ state;
1621
+ engineOptions;
1622
+ executor;
1623
+ constructor(config) {
1624
+ this.config = config;
1625
+ this.executor = config.toolExecutor ?? defaultToolExecutor;
1626
+ this.engineOptions = {
1627
+ trace: config.trace ?? false,
1628
+ level: config.level,
1629
+ plan: config.plan
1630
+ };
1631
+ this.state = {
1632
+ active: false,
1633
+ world: config.world,
1634
+ plan: config.plan,
1635
+ progress: config.plan ? getPlanProgress(config.plan) : void 0,
1636
+ actionsEvaluated: 0,
1637
+ actionsAllowed: 0,
1638
+ actionsBlocked: 0,
1639
+ actionsPaused: 0,
1640
+ actionsModified: 0,
1641
+ actionsPenalized: 0,
1642
+ actionsRewarded: 0,
1643
+ agentStates: /* @__PURE__ */ new Map()
1644
+ };
1645
+ }
1646
+ /**
1647
+ * Initialize the session — load world from disk if needed.
1648
+ */
1649
+ async start() {
1650
+ if (this.config.worldPath && !this.config.world) {
1651
+ this.state.world = await loadWorld(this.config.worldPath);
1652
+ }
1653
+ if (!this.state.world) {
1654
+ throw new Error("No world provided. Use --world or pass a world definition.");
1655
+ }
1656
+ this.state.active = true;
1657
+ return this.getState();
1658
+ }
1659
+ /**
1660
+ * Evaluate a single event against governance.
1661
+ * Returns the verdict without executing anything.
1662
+ */
1663
+ evaluate(event) {
1664
+ this.engineOptions.plan = this.state.plan;
1665
+ this.engineOptions.agentStates = this.state.agentStates;
1666
+ const verdict = evaluateGuard(event, this.state.world, this.engineOptions);
1667
+ this.state.actionsEvaluated++;
1668
+ if (verdict.status === "ALLOW") this.state.actionsAllowed++;
1669
+ if (verdict.status === "BLOCK") this.state.actionsBlocked++;
1670
+ if (verdict.status === "PAUSE") this.state.actionsPaused++;
1671
+ if (verdict.status === "MODIFY") this.state.actionsModified++;
1672
+ if (verdict.status === "PENALIZE") this.state.actionsPenalized++;
1673
+ if (verdict.status === "REWARD") this.state.actionsRewarded++;
1674
+ if (event.roleId) {
1675
+ let agentState = this.state.agentStates.get(event.roleId) ?? createAgentState(event.roleId);
1676
+ if (verdict.status === "PENALIZE" && verdict.consequence) {
1677
+ agentState = applyConsequence(agentState, verdict.consequence, verdict.ruleId ?? "unknown");
1678
+ }
1679
+ if (verdict.status === "REWARD" && verdict.reward) {
1680
+ agentState = applyReward(agentState, verdict.reward, verdict.ruleId ?? "unknown");
1681
+ }
1682
+ this.state.agentStates.set(event.roleId, agentState);
1683
+ }
1684
+ this.config.onVerdict?.(verdict, event);
1685
+ return verdict;
1686
+ }
1687
+ /**
1688
+ * Advance all agent states by one round.
1689
+ * Call this at the end of each simulation round to decrement cooldowns.
1690
+ */
1691
+ tickRound() {
1692
+ this.state.agentStates = tickAgentStates(this.state.agentStates);
1693
+ }
1694
+ /**
1695
+ * Get the behavior state for a specific agent.
1696
+ */
1697
+ getAgentState(agentId) {
1698
+ return this.state.agentStates.get(agentId);
1699
+ }
1700
+ /**
1701
+ * Evaluate and execute a tool call.
1702
+ * Returns the execution result or block reason.
1703
+ */
1704
+ async executeToolCall(toolCall) {
1705
+ let args;
1706
+ try {
1707
+ args = JSON.parse(toolCall.function.arguments);
1708
+ } catch {
1709
+ args = { raw: toolCall.function.arguments };
1710
+ }
1711
+ const event = {
1712
+ intent: toolCall.function.name,
1713
+ tool: toolCall.function.name,
1714
+ args,
1715
+ direction: "input"
1716
+ };
1717
+ const verdict = this.evaluate(event);
1718
+ if (verdict.status === "BLOCK" || verdict.status === "PENALIZE") {
1719
+ return { allowed: false, verdict };
1720
+ }
1721
+ if (verdict.status === "PAUSE") {
1722
+ return { allowed: false, verdict };
1723
+ }
1724
+ const result = await this.executor(toolCall.function.name, args);
1725
+ this.config.onToolResult?.(toolCall.function.name, result);
1726
+ if (this.state.plan) {
1727
+ const planVerdict = evaluatePlan(event, this.state.plan);
1728
+ if (planVerdict.matchedStep) {
1729
+ const advResult = advancePlan(this.state.plan, planVerdict.matchedStep);
1730
+ if (advResult.success && advResult.plan) {
1731
+ this.state.plan = advResult.plan;
1732
+ this.engineOptions.plan = this.state.plan;
1733
+ }
1734
+ this.state.progress = getPlanProgress(this.state.plan);
1735
+ this.config.onPlanProgress?.(this.state.progress);
1736
+ if (this.state.progress.completed === this.state.progress.total) {
1737
+ this.config.onPlanComplete?.();
1738
+ }
1739
+ }
1740
+ }
1741
+ return { allowed: true, verdict, result };
1742
+ }
1743
+ /**
1744
+ * Process a model response — evaluate and execute all tool calls.
1745
+ * Returns results for each tool call.
1746
+ */
1747
+ async processModelResponse(response, model) {
1748
+ if (response.toolCalls.length === 0) {
1749
+ return response;
1750
+ }
1751
+ for (const toolCall of response.toolCalls) {
1752
+ const { allowed, verdict, result } = await this.executeToolCall(toolCall);
1753
+ if (allowed && result) {
1754
+ const nextResponse = await model.sendToolResult(toolCall.id, result);
1755
+ if (nextResponse.toolCalls.length > 0) {
1756
+ return this.processModelResponse(nextResponse, model);
1757
+ }
1758
+ return nextResponse;
1759
+ } else {
1760
+ const reason = verdict.reason ?? "Action blocked by governance.";
1761
+ const nextResponse = await model.sendBlockedResult(toolCall.id, reason);
1762
+ if (nextResponse.toolCalls.length > 0) {
1763
+ return this.processModelResponse(nextResponse, model);
1764
+ }
1765
+ return nextResponse;
1766
+ }
1767
+ }
1768
+ return response;
1769
+ }
1770
+ /** Get current session state. */
1771
+ getState() {
1772
+ return { ...this.state };
1773
+ }
1774
+ /** Stop the session. */
1775
+ stop() {
1776
+ this.state.active = false;
1777
+ return this.getState();
1778
+ }
1779
+ };
1780
+ }
1781
+ });
1782
+
1783
+ // src/cli/run.ts
1784
+ var run_exports = {};
1785
+ __export(run_exports, {
1786
+ main: () => main
1787
+ });
1788
+ module.exports = __toCommonJS(run_exports);
1789
+ var import_fs2 = require("fs");
1790
+ var import_path2 = require("path");
1791
+
1792
+ // src/loader/world-resolver.ts
1793
+ var import_fs = require("fs");
1794
+ var import_path = require("path");
1795
+ var WORLDS_DIR = ".neuroverse/worlds";
1796
+ var ACTIVE_WORLD_FILE = ".neuroverse/active_world";
1797
+ function listWorlds(cwd = process.cwd()) {
1798
+ const worldsDir = (0, import_path.join)(cwd, WORLDS_DIR);
1799
+ if (!(0, import_fs.existsSync)(worldsDir)) return [];
1800
+ const activeName = getActiveWorldName(cwd);
1801
+ const entries = (0, import_fs.readdirSync)(worldsDir);
1802
+ return entries.filter((name) => {
1803
+ const worldJson = (0, import_path.join)(worldsDir, name, "world.json");
1804
+ return (0, import_fs.existsSync)(worldJson);
1805
+ }).map((name) => ({
1806
+ name,
1807
+ path: (0, import_path.join)(worldsDir, name),
1808
+ active: name === activeName
1809
+ })).sort((a, b) => a.name.localeCompare(b.name));
1810
+ }
1811
+ function getActiveWorldName(cwd = process.cwd()) {
1812
+ const filePath = (0, import_path.join)(cwd, ACTIVE_WORLD_FILE);
1813
+ try {
1814
+ return (0, import_fs.readFileSync)(filePath, "utf-8").trim() || void 0;
1815
+ } catch {
1816
+ return void 0;
1817
+ }
1818
+ }
1819
+ function resolveWorldPath(explicit, cwd = process.cwd()) {
1820
+ if (explicit) {
1821
+ return resolveNameOrPath(explicit, cwd);
1822
+ }
1823
+ const envWorld = process.env.NEUROVERSE_WORLD;
1824
+ if (envWorld) {
1825
+ return resolveNameOrPath(envWorld, cwd);
1826
+ }
1827
+ const activeName = getActiveWorldName(cwd);
1828
+ if (activeName) {
1829
+ return resolveNameOrPath(activeName, cwd);
1830
+ }
1831
+ const worlds = listWorlds(cwd);
1832
+ if (worlds.length === 1) {
1833
+ return (0, import_path.resolve)(worlds[0].path);
1834
+ }
1835
+ return void 0;
1836
+ }
1837
+ function describeActiveWorld(explicit, cwd = process.cwd()) {
1838
+ if (explicit) {
1839
+ return { name: explicit, source: "--world flag" };
1840
+ }
1841
+ const envWorld = process.env.NEUROVERSE_WORLD;
1842
+ if (envWorld) {
1843
+ return { name: envWorld, source: "NEUROVERSE_WORLD env var" };
1844
+ }
1845
+ const activeName = getActiveWorldName(cwd);
1846
+ if (activeName) {
1847
+ return { name: activeName, source: ".neuroverse/active_world" };
1848
+ }
1849
+ const worlds = listWorlds(cwd);
1850
+ if (worlds.length === 1) {
1851
+ return { name: worlds[0].name, source: "auto-detected (only world)" };
1852
+ }
1853
+ return void 0;
1854
+ }
1855
+ function resolveNameOrPath(ref, cwd) {
1856
+ if (ref.includes("/") || ref.includes("\\") || ref.startsWith(".") || (0, import_path.isAbsolute)(ref)) {
1857
+ return (0, import_path.resolve)(cwd, ref);
1858
+ }
1859
+ const namedPath = (0, import_path.join)(cwd, WORLDS_DIR, ref);
1860
+ if ((0, import_fs.existsSync)((0, import_path.join)(namedPath, "world.json"))) {
1861
+ return (0, import_path.resolve)(namedPath);
1862
+ }
1863
+ return (0, import_path.resolve)(cwd, ref);
1864
+ }
1865
+
1866
+ // src/cli/run.ts
1867
+ function parseArg(args, flag) {
1868
+ const idx = args.indexOf(flag);
1869
+ return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : void 0;
1870
+ }
1871
+ function hasFlag(args, flag) {
1872
+ return args.includes(flag);
1873
+ }
1874
+ function autoDetectPlan() {
1875
+ const nvDir = ".neuroverse/plans";
1876
+ if (!(0, import_fs2.existsSync)(nvDir)) return void 0;
1877
+ const entries = (0, import_fs2.readdirSync)(nvDir).filter((e) => e.endsWith(".json"));
1878
+ if (entries.length === 1) {
1879
+ try {
1880
+ return JSON.parse((0, import_fs2.readFileSync)((0, import_path2.join)(nvDir, entries[0]), "utf-8"));
1881
+ } catch {
1882
+ return void 0;
1883
+ }
1884
+ }
1885
+ return void 0;
1886
+ }
1887
+ function loadPlan(path) {
1888
+ return JSON.parse((0, import_fs2.readFileSync)(path, "utf-8"));
1889
+ }
1890
+ var RUN_USAGE = `
1891
+ neuroverse run \u2014 Governed runtime for AI agents.
1892
+
1893
+ Modes:
1894
+ --pipe JSON lines in \u2192 verdicts out (default if stdin is piped)
1895
+ --interactive Chat session with model + governance
1896
+
1897
+ Options:
1898
+ --world <path> Path to world directory
1899
+ --plan <path> Path to plan.json
1900
+ --level <level> Enforcement level (basic|standard|strict)
1901
+ --trace Include evaluation trace in verdicts
1902
+ --provider <name> Model provider (openai|anthropic|ollama)
1903
+ --model <name> Model name override
1904
+ --api-key <key> API key (or set via env var)
1905
+
1906
+ Usage:
1907
+ # Pipe mode \u2014 works with any agent
1908
+ my_agent | neuroverse run --world ./world/ --plan plan.json
1909
+
1910
+ # Interactive mode \u2014 governed chat session
1911
+ neuroverse run --interactive --world ./world/ --provider openai
1912
+
1913
+ # Auto-detect world and plan
1914
+ neuroverse run
1915
+ `.trim();
1916
+ async function main(args) {
1917
+ if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1918
+ process.stdout.write(RUN_USAGE + "\n");
1919
+ process.exit(0);
1920
+ return;
1921
+ }
1922
+ const worldPath = resolveWorldPath(parseArg(args, "--world"));
1923
+ if (!worldPath) {
1924
+ process.stderr.write(
1925
+ "Error: No world found.\nUse --world <path>, set NEUROVERSE_WORLD, or run `neuroverse world use <name>`\n"
1926
+ );
1927
+ process.exit(1);
1928
+ return;
1929
+ }
1930
+ const explicitWorld = parseArg(args, "--world");
1931
+ const worldInfo = describeActiveWorld(explicitWorld);
1932
+ if (worldInfo) {
1933
+ process.stderr.write(`Using world: ${worldInfo.name}
1934
+ `);
1935
+ }
1936
+ const planPath = parseArg(args, "--plan");
1937
+ const plan = planPath ? loadPlan(planPath) : autoDetectPlan();
1938
+ const level = parseArg(args, "--level");
1939
+ const trace = hasFlag(args, "--trace");
1940
+ const isPipeMode = hasFlag(args, "--pipe") || !process.stdin.isTTY;
1941
+ const isInteractive = hasFlag(args, "--interactive");
1942
+ if (isInteractive) {
1943
+ const providerName = parseArg(args, "--provider");
1944
+ if (!providerName) {
1945
+ process.stderr.write(
1946
+ "Error: Interactive mode requires --provider (openai|anthropic|ollama)\n"
1947
+ );
1948
+ process.exit(1);
1949
+ return;
1950
+ }
1951
+ const { resolveProvider: resolveProvider2, ModelAdapter: ModelAdapter2 } = await Promise.resolve().then(() => (init_model_adapter(), model_adapter_exports));
1952
+ const { runInteractiveMode: runInteractiveMode2 } = await Promise.resolve().then(() => (init_session(), session_exports));
1953
+ const modelConfig = resolveProvider2(providerName, {
1954
+ model: parseArg(args, "--model"),
1955
+ apiKey: parseArg(args, "--api-key")
1956
+ });
1957
+ const model = new ModelAdapter2(modelConfig);
1958
+ await runInteractiveMode2(
1959
+ {
1960
+ worldPath,
1961
+ plan,
1962
+ level,
1963
+ trace,
1964
+ onVerdict: (verdict, event) => {
1965
+ if (verdict.status !== "ALLOW") {
1966
+ process.stderr.write(
1967
+ ` [${verdict.status}] ${event.intent} \u2014 ${verdict.reason ?? verdict.ruleId ?? "governance rule"}
1968
+ `
1969
+ );
1970
+ }
1971
+ },
1972
+ onPlanProgress: (progress) => {
1973
+ process.stderr.write(
1974
+ ` [plan] ${progress.completed}/${progress.total} (${progress.percentage}%)
1975
+ `
1976
+ );
1977
+ },
1978
+ onPlanComplete: () => {
1979
+ process.stderr.write(` [plan] Complete!
1980
+ `);
1981
+ }
1982
+ },
1983
+ model
1984
+ );
1985
+ } else if (isPipeMode) {
1986
+ const { runPipeMode: runPipeMode2 } = await Promise.resolve().then(() => (init_session(), session_exports));
1987
+ await runPipeMode2({
1988
+ worldPath,
1989
+ plan,
1990
+ level,
1991
+ trace
1992
+ });
1993
+ } else {
1994
+ process.stdout.write(RUN_USAGE + "\n");
1995
+ process.exit(0);
1996
+ }
1997
+ }
1998
+ // Annotate the CommonJS export names for ESM import in node:
1999
+ 0 && (module.exports = {
2000
+ main
2001
+ });