@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,130 +0,0 @@
1
- // src/runtime/model-adapter.ts
2
- var DEFAULT_SYSTEM_PROMPT = `You are an AI assistant operating under NeuroVerse governance.
3
- All your tool calls are evaluated against governance rules before execution.
4
- If an action is blocked, you will be told why. Adjust your approach accordingly.
5
- Do not attempt to bypass governance rules.`;
6
- var ModelAdapter = class {
7
- config;
8
- messages;
9
- tools;
10
- constructor(config, tools = []) {
11
- this.config = config;
12
- this.tools = tools;
13
- this.messages = [];
14
- const systemPrompt = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
15
- this.messages.push({ role: "system", content: systemPrompt });
16
- }
17
- /**
18
- * Send a user message and get the model's response.
19
- */
20
- async chat(userMessage) {
21
- this.messages.push({ role: "user", content: userMessage });
22
- return this.complete();
23
- }
24
- /**
25
- * Send a tool result back to the model and get the next response.
26
- */
27
- async sendToolResult(toolCallId, result) {
28
- this.messages.push({
29
- role: "tool",
30
- content: result,
31
- tool_call_id: toolCallId
32
- });
33
- return this.complete();
34
- }
35
- /**
36
- * Send a governance block message as a tool result.
37
- */
38
- async sendBlockedResult(toolCallId, reason) {
39
- return this.sendToolResult(
40
- toolCallId,
41
- `[GOVERNANCE BLOCKED] ${reason}. Please adjust your approach.`
42
- );
43
- }
44
- /**
45
- * Call the model API and parse the response.
46
- */
47
- async complete() {
48
- const url = `${this.config.baseUrl}/chat/completions`;
49
- const body = {
50
- model: this.config.model,
51
- messages: this.messages,
52
- max_tokens: this.config.maxTokens ?? 4096
53
- };
54
- if (this.tools.length > 0) {
55
- body.tools = this.tools;
56
- }
57
- const response = await fetch(url, {
58
- method: "POST",
59
- headers: {
60
- "Content-Type": "application/json",
61
- "Authorization": `Bearer ${this.config.apiKey}`
62
- },
63
- body: JSON.stringify(body)
64
- });
65
- if (!response.ok) {
66
- const text = await response.text();
67
- throw new Error(`Model API error ${response.status}: ${text}`);
68
- }
69
- const data = await response.json();
70
- const choice = data.choices?.[0];
71
- if (!choice) {
72
- throw new Error("Model returned no choices");
73
- }
74
- const message = choice.message;
75
- this.messages.push(message);
76
- return {
77
- content: message.content ?? null,
78
- toolCalls: message.tool_calls ?? [],
79
- finishReason: choice.finish_reason ?? "stop"
80
- };
81
- }
82
- /** Get current message count (for context tracking). */
83
- get messageCount() {
84
- return this.messages.length;
85
- }
86
- };
87
- var PROVIDERS = {
88
- openai: {
89
- baseUrl: "https://api.openai.com/v1",
90
- defaultModel: "gpt-4o",
91
- envVar: "OPENAI_API_KEY"
92
- },
93
- anthropic: {
94
- baseUrl: "https://api.anthropic.com/v1",
95
- defaultModel: "claude-sonnet-4-20250514",
96
- envVar: "ANTHROPIC_API_KEY"
97
- },
98
- ollama: {
99
- baseUrl: "http://localhost:11434/v1",
100
- defaultModel: "llama3",
101
- envVar: ""
102
- }
103
- };
104
- function resolveProvider(provider, overrides) {
105
- const preset = PROVIDERS[provider];
106
- if (!preset) {
107
- throw new Error(
108
- `Unknown provider: "${provider}". Available: ${Object.keys(PROVIDERS).join(", ")}`
109
- );
110
- }
111
- const apiKey = overrides?.apiKey ?? (preset.envVar ? process.env[preset.envVar] : "") ?? "";
112
- if (!apiKey && preset.envVar) {
113
- throw new Error(
114
- `Missing API key. Set ${preset.envVar} or pass --api-key.`
115
- );
116
- }
117
- return {
118
- baseUrl: overrides?.baseUrl ?? preset.baseUrl,
119
- apiKey,
120
- model: overrides?.model ?? preset.defaultModel,
121
- systemPrompt: overrides?.systemPrompt,
122
- maxTokens: overrides?.maxTokens
123
- };
124
- }
125
-
126
- export {
127
- ModelAdapter,
128
- PROVIDERS,
129
- resolveProvider
130
- };
@@ -1,96 +0,0 @@
1
- // src/loader/world-resolver.ts
2
- import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync } from "fs";
3
- import { join, resolve, isAbsolute } from "path";
4
- var WORLDS_DIR = ".neuroverse/worlds";
5
- var ACTIVE_WORLD_FILE = ".neuroverse/active_world";
6
- function listWorlds(cwd = process.cwd()) {
7
- const worldsDir = join(cwd, WORLDS_DIR);
8
- if (!existsSync(worldsDir)) return [];
9
- const activeName = getActiveWorldName(cwd);
10
- const entries = readdirSync(worldsDir);
11
- return entries.filter((name) => {
12
- const worldJson = join(worldsDir, name, "world.json");
13
- return existsSync(worldJson);
14
- }).map((name) => ({
15
- name,
16
- path: join(worldsDir, name),
17
- active: name === activeName
18
- })).sort((a, b) => a.name.localeCompare(b.name));
19
- }
20
- function getActiveWorldName(cwd = process.cwd()) {
21
- const filePath = join(cwd, ACTIVE_WORLD_FILE);
22
- try {
23
- return readFileSync(filePath, "utf-8").trim() || void 0;
24
- } catch {
25
- return void 0;
26
- }
27
- }
28
- function setActiveWorld(name, cwd = process.cwd()) {
29
- const worldsDir = join(cwd, WORLDS_DIR);
30
- const worldPath = join(worldsDir, name, "world.json");
31
- if (!existsSync(worldPath)) {
32
- const available = listWorlds(cwd);
33
- const names = available.map((w) => w.name).join(", ");
34
- throw new Error(
35
- `World "${name}" not found in ${WORLDS_DIR}/
36
- ` + (names ? `Available: ${names}` : "No worlds found. Run `neuroverse build` first.")
37
- );
38
- }
39
- const dir = join(cwd, ".neuroverse");
40
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
41
- writeFileSync(join(cwd, ACTIVE_WORLD_FILE), name + "\n", "utf-8");
42
- }
43
- function resolveWorldPath(explicit, cwd = process.cwd()) {
44
- if (explicit) {
45
- return resolveNameOrPath(explicit, cwd);
46
- }
47
- const envWorld = process.env.NEUROVERSE_WORLD;
48
- if (envWorld) {
49
- return resolveNameOrPath(envWorld, cwd);
50
- }
51
- const activeName = getActiveWorldName(cwd);
52
- if (activeName) {
53
- return resolveNameOrPath(activeName, cwd);
54
- }
55
- const worlds = listWorlds(cwd);
56
- if (worlds.length === 1) {
57
- return resolve(worlds[0].path);
58
- }
59
- return void 0;
60
- }
61
- function describeActiveWorld(explicit, cwd = process.cwd()) {
62
- if (explicit) {
63
- return { name: explicit, source: "--world flag" };
64
- }
65
- const envWorld = process.env.NEUROVERSE_WORLD;
66
- if (envWorld) {
67
- return { name: envWorld, source: "NEUROVERSE_WORLD env var" };
68
- }
69
- const activeName = getActiveWorldName(cwd);
70
- if (activeName) {
71
- return { name: activeName, source: ".neuroverse/active_world" };
72
- }
73
- const worlds = listWorlds(cwd);
74
- if (worlds.length === 1) {
75
- return { name: worlds[0].name, source: "auto-detected (only world)" };
76
- }
77
- return void 0;
78
- }
79
- function resolveNameOrPath(ref, cwd) {
80
- if (ref.includes("/") || ref.includes("\\") || ref.startsWith(".") || isAbsolute(ref)) {
81
- return resolve(cwd, ref);
82
- }
83
- const namedPath = join(cwd, WORLDS_DIR, ref);
84
- if (existsSync(join(namedPath, "world.json"))) {
85
- return resolve(namedPath);
86
- }
87
- return resolve(cwd, ref);
88
- }
89
-
90
- export {
91
- listWorlds,
92
- getActiveWorldName,
93
- setActiveWorld,
94
- resolveWorldPath,
95
- describeActiveWorld
96
- };
@@ -1,192 +0,0 @@
1
- // src/engine/explain-engine.ts
2
- function detectTensions(rules) {
3
- const increases = /* @__PURE__ */ new Map();
4
- const decreases = /* @__PURE__ */ new Map();
5
- for (const rule of rules) {
6
- const allEffects = collectAllEffects(rule);
7
- for (const effect of allEffects) {
8
- const target = effect.target;
9
- const isIncrease = effect.operation === "add" || effect.operation === "multiply" && typeof effect.value === "number" && effect.value > 1;
10
- const isDecrease = effect.operation === "subtract" || effect.operation === "multiply" && typeof effect.value === "number" && effect.value < 1;
11
- if (isIncrease) {
12
- if (!increases.has(target)) increases.set(target, []);
13
- increases.get(target).push(rule.label);
14
- }
15
- if (isDecrease) {
16
- if (!decreases.has(target)) decreases.set(target, []);
17
- decreases.get(target).push(rule.label);
18
- }
19
- }
20
- }
21
- const tensions = [];
22
- for (const [variable, incRules] of increases) {
23
- const decRules = decreases.get(variable);
24
- if (decRules && decRules.length > 0) {
25
- tensions.push({
26
- variable,
27
- increasedBy: incRules,
28
- decreasedBy: decRules
29
- });
30
- }
31
- }
32
- return tensions;
33
- }
34
- function collectAllEffects(rule) {
35
- const effects = [...rule.effects ?? []];
36
- for (const ce of rule.effects_conditional ?? []) {
37
- effects.push(...ce.effects);
38
- }
39
- return effects;
40
- }
41
- function explainWorld(world) {
42
- const dynamics = [...world.rules].sort((a, b) => a.order - b.order).map((rule) => {
43
- const allEffects = collectAllEffects(rule);
44
- return {
45
- ruleId: rule.id,
46
- label: rule.label,
47
- severity: rule.severity,
48
- triggerDescription: rule.causal_translation?.trigger_text ?? describeTriggers(rule),
49
- effectDescription: rule.causal_translation?.effect_text ?? describeEffects(allEffects),
50
- targets: [...new Set(allEffects.map((e) => e.target))]
51
- };
52
- });
53
- const stateVariables = Object.entries(world.stateSchema.variables ?? {}).map(
54
- ([name, v]) => ({
55
- name,
56
- label: v.label || name,
57
- type: v.type,
58
- defaultValue: v.default,
59
- range: v.type === "number" && v.min !== void 0 && v.max !== void 0 ? `${v.min}\u2013${v.max}` : v.type === "enum" && v.options ? v.options.join(", ") : void 0
60
- })
61
- );
62
- const invariants = world.invariants.map((inv) => ({
63
- id: inv.id,
64
- label: inv.label,
65
- enforcement: inv.enforcement
66
- }));
67
- const gates = (world.gates.viability_classification ?? []).map((g) => ({
68
- status: g.status,
69
- field: g.field,
70
- threshold: `${g.operator} ${g.value}`
71
- }));
72
- const tensions = detectTensions(world.rules);
73
- const outcomes = (world.outcomes.computed_outcomes ?? []).map((o) => ({
74
- id: o.id,
75
- label: o.label,
76
- type: o.type,
77
- primary: o.primary ?? false
78
- }));
79
- const stats = {
80
- invariants: world.invariants.length,
81
- stateVariables: Object.keys(world.stateSchema.variables ?? {}).length,
82
- rules: world.rules.length,
83
- gates: (world.gates.viability_classification ?? []).length,
84
- outcomes: (world.outcomes.computed_outcomes ?? []).length,
85
- assumptions: Object.keys(world.assumptions.profiles ?? {}).length
86
- };
87
- return {
88
- worldName: world.world.name,
89
- worldId: world.world.world_id,
90
- thesis: world.world.thesis,
91
- dynamics,
92
- stateVariables,
93
- invariants,
94
- gates,
95
- tensions,
96
- outcomes,
97
- stats
98
- };
99
- }
100
- function describeTriggers(rule) {
101
- if (!rule.triggers || rule.triggers.length === 0) return "Always active";
102
- return rule.triggers.map((t) => `${t.field} ${t.operator} ${t.value}`).join(" AND ");
103
- }
104
- function describeEffects(effects) {
105
- if (effects.length === 0) return "No direct effects";
106
- return effects.map((e) => {
107
- switch (e.operation) {
108
- case "multiply":
109
- return `${e.target} scaled by ${e.value}`;
110
- case "add":
111
- return `${e.target} increased by ${e.value}`;
112
- case "subtract":
113
- return `${e.target} decreased by ${e.value}`;
114
- case "set":
115
- return `${e.target} set to ${e.value}`;
116
- case "set_boolean":
117
- return `${e.target} set to ${e.value}`;
118
- default:
119
- return `${e.target} ${e.operation} ${e.value}`;
120
- }
121
- }).join("; ");
122
- }
123
- function renderExplainText(output) {
124
- const lines = [];
125
- lines.push(`WORLD: ${output.worldName}`);
126
- lines.push(`ID: ${output.worldId}`);
127
- lines.push("");
128
- if (output.thesis) {
129
- lines.push("THESIS");
130
- lines.push(` ${output.thesis}`);
131
- lines.push("");
132
- }
133
- lines.push("STRUCTURE");
134
- lines.push(` ${output.stats.invariants} invariants, ${output.stats.stateVariables} state variables, ${output.stats.rules} rules`);
135
- lines.push(` ${output.stats.gates} viability gates, ${output.stats.outcomes} outcomes, ${output.stats.assumptions} assumption profiles`);
136
- lines.push("");
137
- if (output.dynamics.length > 0) {
138
- lines.push("KEY DYNAMICS");
139
- for (const d of output.dynamics) {
140
- const severity = d.severity === "structural" ? "[structural]" : d.severity === "advantage" ? "[advantage]" : "[degradation]";
141
- lines.push(` ${d.label} ${severity}`);
142
- lines.push(` When: ${d.triggerDescription}`);
143
- lines.push(` Then: ${d.effectDescription}`);
144
- }
145
- lines.push("");
146
- }
147
- if (output.tensions.length > 0) {
148
- lines.push("DRAMATIC TENSIONS");
149
- for (const t of output.tensions) {
150
- lines.push(` ${t.variable}:`);
151
- lines.push(` Increased by: ${t.increasedBy.join(", ")}`);
152
- lines.push(` Decreased by: ${t.decreasedBy.join(", ")}`);
153
- }
154
- lines.push("");
155
- }
156
- if (output.stateVariables.length > 0) {
157
- lines.push("STATE VARIABLES");
158
- for (const v of output.stateVariables) {
159
- const range = v.range ? ` (${v.range})` : "";
160
- lines.push(` ${v.label}: ${v.type}, default ${v.defaultValue}${range}`);
161
- }
162
- lines.push("");
163
- }
164
- if (output.invariants.length > 0) {
165
- lines.push("INVARIANTS (cannot change)");
166
- for (const inv of output.invariants) {
167
- lines.push(` ${inv.label} [${inv.enforcement}]`);
168
- }
169
- lines.push("");
170
- }
171
- if (output.gates.length > 0) {
172
- lines.push("VIABILITY GATES");
173
- for (const g of output.gates) {
174
- lines.push(` ${g.status}: ${g.field} ${g.threshold}`);
175
- }
176
- lines.push("");
177
- }
178
- if (output.outcomes.length > 0) {
179
- lines.push("OUTCOMES");
180
- for (const o of output.outcomes) {
181
- const primary = o.primary ? " [primary]" : "";
182
- lines.push(` ${o.label} (${o.type})${primary}`);
183
- }
184
- lines.push("");
185
- }
186
- return lines.join("\n");
187
- }
188
-
189
- export {
190
- explainWorld,
191
- renderExplainText
192
- };
@@ -1,109 +0,0 @@
1
- import {
2
- evaluateGuard
3
- } from "./chunk-4JRYGIO7.js";
4
- import {
5
- advancePlan,
6
- evaluatePlan,
7
- getPlanProgress
8
- } from "./chunk-4QXB6PEO.js";
9
- import {
10
- loadWorld
11
- } from "./chunk-JZPQGIKR.js";
12
-
13
- // src/adapters/langchain.ts
14
- var GovernanceBlockedError = class extends Error {
15
- verdict;
16
- event;
17
- constructor(verdict, event) {
18
- super(`[NeuroVerse] BLOCKED: ${verdict.reason ?? verdict.ruleId ?? "governance rule"}`);
19
- this.name = "GovernanceBlockedError";
20
- this.verdict = verdict;
21
- this.event = event;
22
- }
23
- };
24
- function defaultMapToolCall(toolName, toolInput) {
25
- return {
26
- intent: toolName,
27
- tool: toolName,
28
- scope: typeof toolInput.path === "string" ? toolInput.path : typeof toolInput.url === "string" ? toolInput.url : void 0,
29
- args: toolInput,
30
- direction: "input"
31
- };
32
- }
33
- var NeuroVerseCallbackHandler = class {
34
- name = "NeuroVerseGovernance";
35
- world;
36
- options;
37
- engineOptions;
38
- mapToolCall;
39
- activePlan;
40
- constructor(world, options = {}) {
41
- this.world = world;
42
- this.options = options;
43
- this.activePlan = options.plan;
44
- this.engineOptions = {
45
- trace: options.trace ?? false,
46
- level: options.level,
47
- plan: this.activePlan
48
- };
49
- this.mapToolCall = options.mapToolCall ?? defaultMapToolCall;
50
- }
51
- /**
52
- * Called before a tool is executed.
53
- * Evaluates the tool call against the governance world.
54
- *
55
- * @throws GovernanceBlockedError if the action is BLOCKED
56
- * @throws GovernanceBlockedError if the action is PAUSED and onPause returns false
57
- */
58
- async handleToolStart(tool, input) {
59
- let parsedInput;
60
- try {
61
- parsedInput = typeof input === "string" ? JSON.parse(input) : input;
62
- } catch {
63
- parsedInput = { raw: input };
64
- }
65
- const event = this.mapToolCall(tool.name, parsedInput);
66
- this.engineOptions.plan = this.activePlan;
67
- const verdict = evaluateGuard(event, this.world, this.engineOptions);
68
- this.options.onEvaluate?.(verdict, event);
69
- if (verdict.status === "BLOCK") {
70
- this.options.onBlock?.(verdict, event);
71
- throw new GovernanceBlockedError(verdict, event);
72
- }
73
- if (verdict.status === "PAUSE") {
74
- const approved = await this.options.onPause?.(verdict, event);
75
- if (!approved) {
76
- throw new GovernanceBlockedError(verdict, event);
77
- }
78
- }
79
- if (verdict.status === "ALLOW" && this.activePlan) {
80
- const planVerdict = evaluatePlan(event, this.activePlan);
81
- if (planVerdict.matchedStep) {
82
- const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
83
- if (advResult.success && advResult.plan) {
84
- this.activePlan = advResult.plan;
85
- this.engineOptions.plan = this.activePlan;
86
- }
87
- const progress = getPlanProgress(this.activePlan);
88
- this.options.onPlanProgress?.(progress);
89
- if (progress.completed === progress.total) {
90
- this.options.onPlanComplete?.();
91
- }
92
- }
93
- }
94
- }
95
- };
96
- async function createNeuroVerseCallbackHandler(worldPath, options) {
97
- const world = await loadWorld(worldPath);
98
- return new NeuroVerseCallbackHandler(world, options);
99
- }
100
- function createNeuroVerseCallbackHandlerFromWorld(world, options) {
101
- return new NeuroVerseCallbackHandler(world, options);
102
- }
103
-
104
- export {
105
- GovernanceBlockedError,
106
- NeuroVerseCallbackHandler,
107
- createNeuroVerseCallbackHandler,
108
- createNeuroVerseCallbackHandlerFromWorld
109
- };
@@ -1,139 +0,0 @@
1
- import {
2
- evaluateGuard
3
- } from "./chunk-4JRYGIO7.js";
4
- import {
5
- advancePlan,
6
- evaluatePlan,
7
- getPlanProgress
8
- } from "./chunk-4QXB6PEO.js";
9
- import {
10
- loadWorld
11
- } from "./chunk-JZPQGIKR.js";
12
-
13
- // src/adapters/openai.ts
14
- var GovernanceBlockedError = class extends Error {
15
- verdict;
16
- toolCallId;
17
- constructor(verdict, toolCallId) {
18
- super(`[NeuroVerse] BLOCKED: ${verdict.reason ?? verdict.ruleId ?? "governance rule"}`);
19
- this.name = "GovernanceBlockedError";
20
- this.verdict = verdict;
21
- this.toolCallId = toolCallId;
22
- }
23
- };
24
- function defaultMapFunctionCall(name, args) {
25
- return {
26
- intent: name,
27
- tool: name,
28
- scope: typeof args.path === "string" ? args.path : typeof args.url === "string" ? args.url : void 0,
29
- args,
30
- direction: "input"
31
- };
32
- }
33
- function defaultBlockMessage(verdict) {
34
- return `Action blocked by governance policy: ${verdict.reason ?? "rule violation"}. Rule: ${verdict.ruleId ?? "unknown"}.`;
35
- }
36
- var GovernedToolExecutor = class {
37
- world;
38
- options;
39
- engineOptions;
40
- mapFn;
41
- blockMsg;
42
- activePlan;
43
- constructor(world, options = {}) {
44
- this.world = world;
45
- this.options = options;
46
- this.activePlan = options.plan;
47
- this.engineOptions = {
48
- trace: options.trace ?? false,
49
- level: options.level,
50
- plan: this.activePlan
51
- };
52
- this.mapFn = options.mapFunctionCall ?? defaultMapFunctionCall;
53
- this.blockMsg = options.blockMessage ?? defaultBlockMessage;
54
- }
55
- /**
56
- * Evaluate a single tool call against governance rules.
57
- * Returns the verdict without executing the tool.
58
- */
59
- evaluate(toolCall) {
60
- let args;
61
- try {
62
- args = JSON.parse(toolCall.function.arguments);
63
- } catch {
64
- args = { raw: toolCall.function.arguments };
65
- }
66
- const event = this.mapFn(toolCall.function.name, args);
67
- this.engineOptions.plan = this.activePlan;
68
- const verdict = evaluateGuard(event, this.world, this.engineOptions);
69
- this.options.onEvaluate?.(verdict, event);
70
- if (verdict.status === "ALLOW" && this.activePlan) {
71
- const planVerdict = evaluatePlan(event, this.activePlan);
72
- if (planVerdict.matchedStep) {
73
- const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
74
- if (advResult.success && advResult.plan) {
75
- this.activePlan = advResult.plan;
76
- this.engineOptions.plan = this.activePlan;
77
- }
78
- const progress = getPlanProgress(this.activePlan);
79
- this.options.onPlanProgress?.(progress);
80
- if (progress.completed === progress.total) {
81
- this.options.onPlanComplete?.();
82
- }
83
- }
84
- }
85
- return verdict;
86
- }
87
- /**
88
- * Execute a tool call with governance enforcement.
89
- *
90
- * If ALLOW: runs the tool and returns the result.
91
- * If BLOCK: returns a blocked message (no execution).
92
- * If PAUSE: throws — caller must handle approval flow.
93
- *
94
- * @param toolCall - The OpenAI tool call to evaluate
95
- * @param runner - The actual tool execution function
96
- * @returns A tool result message ready for the OpenAI API
97
- */
98
- async execute(toolCall, runner) {
99
- const verdict = this.evaluate(toolCall);
100
- if (verdict.status === "BLOCK") {
101
- return {
102
- tool_call_id: toolCall.id,
103
- role: "tool",
104
- content: this.blockMsg(verdict),
105
- _verdict: verdict
106
- };
107
- }
108
- if (verdict.status === "PAUSE") {
109
- throw new GovernanceBlockedError(verdict, toolCall.id);
110
- }
111
- let args;
112
- try {
113
- args = JSON.parse(toolCall.function.arguments);
114
- } catch {
115
- args = { raw: toolCall.function.arguments };
116
- }
117
- const content = await runner(toolCall.function.name, args);
118
- return {
119
- tool_call_id: toolCall.id,
120
- role: "tool",
121
- content,
122
- _verdict: verdict
123
- };
124
- }
125
- };
126
- async function createGovernedToolExecutor(worldPath, options) {
127
- const world = await loadWorld(worldPath);
128
- return new GovernedToolExecutor(world, options);
129
- }
130
- function createGovernedToolExecutorFromWorld(world, options) {
131
- return new GovernedToolExecutor(world, options);
132
- }
133
-
134
- export {
135
- GovernanceBlockedError,
136
- GovernedToolExecutor,
137
- createGovernedToolExecutor,
138
- createGovernedToolExecutorFromWorld
139
- };