@hmharness/cognitive 0.23.12 → 0.23.13

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.
package/dist/index.d.ts CHANGED
@@ -15,6 +15,8 @@ export * from './world-model.js';
15
15
  export * from './goal.js';
16
16
  export * from './exploration.js';
17
17
  export * from './rlm.js';
18
+ export { runSandboxedEval } from './rlm-sandbox.js';
19
+ export type { SandboxResult, SandboxOptions } from './rlm-sandbox.js';
18
20
  export * from './memory.js';
19
21
  export * from './skill-compiler.js';
20
22
  export * from './continual.js';
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ export * from "./world-model.js";
15
15
  export * from "./goal.js";
16
16
  export * from "./exploration.js";
17
17
  export * from "./rlm.js";
18
+ export { runSandboxedEval } from "./rlm-sandbox.js";
18
19
  export * from "./memory.js";
19
20
  export * from "./skill-compiler.js";
20
21
  export * from "./continual.js";
@@ -0,0 +1,21 @@
1
+ export interface SandboxResult {
2
+ ok: boolean;
3
+ value?: unknown;
4
+ error?: {
5
+ code: string;
6
+ message: string;
7
+ };
8
+ durationMs: number;
9
+ terminated: boolean;
10
+ }
11
+ export interface SandboxOptions {
12
+ /** hard per-eval wall; the worker is terminated past it (default 15s) */
13
+ timeoutMs?: number;
14
+ /** worker heap caps (defaults below) */
15
+ maxOldGenerationSizeMb?: number;
16
+ maxYoungGenerationSizeMb?: number;
17
+ }
18
+ /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
19
+ * are coarse-grained (composing workspace variables), so per-eval spawn
20
+ * overhead (~10-30ms) is acceptable for real isolation each time. */
21
+ export declare function runSandboxedEval(code: string, vars: Record<string, unknown>, meta: Record<string, unknown>, opts?: SandboxOptions): Promise<SandboxResult>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @hmharness/cognitive - RLM sandbox (review P0-1 / RLM-001..004, 2026-10-03)
3
+ *
4
+ * RLM eval code used to run through `new Function` in the MAIN process:
5
+ * full authority (globals, dynamic import, process), only budget-counted.
6
+ * This module moves eval into a worker_threads Worker with real walls:
7
+ *
8
+ * - crash containment: a throwing/OOM-ing eval cannot take the host down
9
+ * - termination: infinite loops are killed at the timeout (terminate())
10
+ * - secret isolation: the worker is created with `env: {}` — API keys in
11
+ * the host environment are NEVER inherited (RLM-002 security rule)
12
+ * - memory ceiling: resourceLimits cap the worker heap
13
+ * - shadowed surface: process/require are undefined inside the eval scope
14
+ *
15
+ * HONEST limits (documented, not hidden): a worker is a containment boundary,
16
+ * NOT a cryptographic sandbox — determined code may still reach Node
17
+ * internals. The walls above are real against the failure modes that
18
+ * actually happen (bugs, loops, leaks, secret inheritance); malicious
19
+ * capability escalation is the Capability OS layer's job, not this one.
20
+ */
21
+ import { Worker } from 'node:worker_threads';
22
+ /** The worker bootstrap source. Runs as CommonJS, receives {code, vars, meta}
23
+ * through workerData (structured-cloned at spawn), executes the code as an
24
+ * async function body with a frozen ctx, and posts the result back.
25
+ * Shadows the dangerous globals at function-constructor scope so casual
26
+ * access fails loudly. */
27
+ const WORKER_SOURCE = `
28
+ const { parentPort, workerData } = require('node:worker_threads');
29
+ (async () => {
30
+ const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
+ try {
32
+ const process = undefined, require = undefined;
33
+ const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
+ const value = await fn(ctx, undefined, undefined);
35
+ parentPort.postMessage({ ok: true, value });
36
+ } catch (err) {
37
+ parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
+ }
39
+ })();
40
+ `;
41
+ /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
42
+ * are coarse-grained (composing workspace variables), so per-eval spawn
43
+ * overhead (~10-30ms) is acceptable for real isolation each time. */
44
+ export function runSandboxedEval(code, vars, meta, opts = {}) {
45
+ const started = Date.now();
46
+ const timeoutMs = opts.timeoutMs ?? 15_000;
47
+ return new Promise((resolve) => {
48
+ let settled = false;
49
+ let worker;
50
+ try {
51
+ worker = new Worker(WORKER_SOURCE, {
52
+ eval: true,
53
+ workerData: { code, vars, meta }, // structured-cloned at spawn — no message race
54
+ env: {}, // secrets never inherit (RLM-002)
55
+ stdout: true,
56
+ stderr: true,
57
+ resourceLimits: {
58
+ maxOldGenerationSizeMb: opts.maxOldGenerationSizeMb ?? 256,
59
+ maxYoungGenerationSizeMb: opts.maxYoungGenerationSizeMb ?? 64,
60
+ },
61
+ });
62
+ }
63
+ catch (err) {
64
+ resolve({ ok: false, error: { code: 'E_SANDBOX_SPAWN', message: String(err).slice(0, 200) }, durationMs: Date.now() - started, terminated: false });
65
+ return;
66
+ }
67
+ const finish = (r) => {
68
+ if (settled)
69
+ return;
70
+ settled = true;
71
+ clearTimeout(timer);
72
+ worker.terminate().catch(() => undefined);
73
+ resolve(r);
74
+ };
75
+ const timer = setTimeout(() => {
76
+ finish({ ok: false, error: { code: 'E_SANDBOX_TIMEOUT', message: `eval exceeded ${timeoutMs}ms and was terminated` }, durationMs: Date.now() - started, terminated: true });
77
+ }, timeoutMs);
78
+ worker.on('message', (m) => {
79
+ finish({ ok: m.ok, value: m.value, error: m.error, durationMs: Date.now() - started, terminated: false });
80
+ });
81
+ worker.on('error', (err) => {
82
+ finish({ ok: false, error: { code: 'E_SANDBOX_CRASH', message: String(err.message || err).slice(0, 200) }, durationMs: Date.now() - started, terminated: false });
83
+ });
84
+ worker.on('exit', (code) => {
85
+ if (!settled) {
86
+ finish({ ok: false, error: { code: 'E_SANDBOX_EXIT', message: `worker exited early (code ${code})` }, durationMs: Date.now() - started, terminated: false });
87
+ }
88
+ });
89
+ });
90
+ }
package/dist/rlm.d.ts CHANGED
@@ -71,8 +71,10 @@ export declare class RLMRuntime {
71
71
  set(name: string, value: RLMValue): void;
72
72
  get(name: string): RLMValue;
73
73
  names(): string[];
74
- /** RLM-003. Recursive call: eval code can spawn nested evals and read
75
- * other variables, but through THIS runtime so accounting holds. */
74
+ /** RLM-003 / review P0-1. Eval runs in a SANDBOXED WORKER per call: crash
75
+ * containment, timeout termination, secret-free env, memory caps (see
76
+ * rlm-sandbox.ts). Budget checks stay in the host; ctx is frozen inside
77
+ * the worker so governance state (meta) cannot be mutated from eval. */
76
78
  eval(code: string, ctx?: Partial<RLMContext>): Promise<RLMResult>;
77
79
  /** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
78
80
  checkpoint(label?: string): RLMCheckpoint;
package/dist/rlm.js CHANGED
@@ -3,13 +3,15 @@
3
3
  *
4
4
  * A programmable cognitive workbench: context, memory snippets, environment
5
5
  * state, predictions, subagent handles and validators are ADDRESSABLE
6
- * VARIABLES the (host) program composes. `eval` runs host-supplied code
7
- * against those variables — the runtime provides isolation walls, resource
8
- * accounting, checkpoints and forks; it does NOT allow hidden unsafe
9
- * self-modification: eval code can only touch workspace variables, never
10
- * the runtime's own governance state (RLM-008).
6
+ * VARIABLES the (host) program composes. Eval code runs in a SANDBOXED
7
+ * WORKER (rlm-sandbox.ts, review P0-1 2026-10-03): crash containment,
8
+ * timeout termination, secret-free env, memory caps. The runtime provides
9
+ * budget accounting, checkpoints and forks; it does NOT allow hidden
10
+ * unsafe self-modification: eval code can only touch workspace variables,
11
+ * never the runtime's own governance state (RLM-008).
11
12
  */
12
13
  import { stableHash } from "./protocol.js";
14
+ import { runSandboxedEval } from "./rlm-sandbox.js";
13
15
  export class RLMRuntime {
14
16
  budget;
15
17
  host;
@@ -46,8 +48,10 @@ export class RLMRuntime {
46
48
  names() {
47
49
  return Object.keys(this.vars);
48
50
  }
49
- /** RLM-003. Recursive call: eval code can spawn nested evals and read
50
- * other variables, but through THIS runtime so accounting holds. */
51
+ /** RLM-003 / review P0-1. Eval runs in a SANDBOXED WORKER per call: crash
52
+ * containment, timeout termination, secret-free env, memory caps (see
53
+ * rlm-sandbox.ts). Budget checks stay in the host; ctx is frozen inside
54
+ * the worker so governance state (meta) cannot be mutated from eval. */
51
55
  async eval(code, ctx) {
52
56
  const started = Date.now();
53
57
  const budget = this.materializeBudget();
@@ -58,24 +62,20 @@ export class RLMRuntime {
58
62
  return { ok: false, error: { code: 'E_BUDGET_WALL', message: `wall-clock budget exhausted (${budget.maxWallMs}ms)` }, durationMs: 0, budget };
59
63
  }
60
64
  this._evals += 1;
61
- const meta = Object.freeze({ evalsUsed: this._evals, subagentsUsed: this.subagents.length, checkpointCount: this.checkpoints.length });
62
- const sandbox = Object.freeze({ vars: this.vars, meta, ...ctx });
63
- try {
64
- const fn = new Function('ctx', `"use strict";\n${code}`);
65
- const value = fn(sandbox);
66
- const resolved = value instanceof Promise ? await value : value;
67
- this.log.push(`eval ok (${Date.now() - started}ms)`);
68
- return { ok: true, value: resolved, durationMs: Date.now() - started, budget: this.materializeBudget() };
69
- }
70
- catch (err) {
71
- this.log.push(`eval fail: ${String(err).slice(0, 120)}`);
72
- return {
73
- ok: false,
74
- error: { code: 'E_EVAL', message: err instanceof Error ? err.message : String(err) },
75
- durationMs: Date.now() - started,
76
- budget: this.materializeBudget(),
77
- };
65
+ const meta = { evalsUsed: this._evals, subagentsUsed: this.subagents.length, checkpointCount: this.checkpoints.length };
66
+ const merged = ctx?.vars ? { ...ctx.vars } : { ...this.vars };
67
+ const r = await runSandboxedEval(code, merged, meta, { timeoutMs: Math.min(15_000, Math.max(1_000, budget.maxWallMs - budget.used.wallMs)) });
68
+ if (r.ok) {
69
+ this.log.push(`eval ok (${r.durationMs}ms)`);
70
+ return { ok: true, value: r.value, durationMs: Date.now() - started, budget: this.materializeBudget() };
78
71
  }
72
+ this.log.push(`eval fail: ${r.error?.code} ${String(r.error?.message).slice(0, 80)}`);
73
+ return {
74
+ ok: false,
75
+ error: r.error ?? { code: 'E_EVAL', message: 'unknown sandbox failure' },
76
+ durationMs: Date.now() - started,
77
+ budget: this.materializeBudget(),
78
+ };
79
79
  }
80
80
  /** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
81
81
  checkpoint(label) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.23.12",
3
+ "version": "0.23.13",
4
4
  "description": "hmharness Cognitive OS core: Environment protocol, World Model, Goal system, Exploration, RLM runtime, five-layer memory, Skill Compiler, Continual Learning control plane, Evolution 2.0 governance, Multi-Agent topology, Transfer lab and GeneralBench schema. Cognitive strategy layer per the HMH Cognitive OS blueprint (2026-09).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,6 +26,6 @@
26
26
  "node": ">=22"
27
27
  },
28
28
  "dependencies": {
29
- "@hmharness/kernel": "0.23.12"
29
+ "@hmharness/kernel": "0.23.13"
30
30
  }
31
31
  }