@poe-platform/safe-js 0.1.21 → 0.1.23

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.
@@ -27,7 +27,7 @@ import {
27
27
  validateMigrationSemantics,
28
28
  validateSnapshotData,
29
29
  validateSnapshotMigration
30
- } from "./chunk-B7H4ZL65.js";
30
+ } from "./chunk-MXUOEOBE.js";
31
31
 
32
32
  // packages/safe-js/src/migrate.ts
33
33
  import { createHash } from "node:crypto";
@@ -8245,4 +8245,4 @@ export {
8245
8245
  parseMcpConfig,
8246
8246
  makeMcpModule
8247
8247
  };
8248
- //# sourceMappingURL=chunk-GMDOPMVZ.js.map
8248
+ //# sourceMappingURL=chunk-X32RVLSM.js.map
@@ -22,7 +22,7 @@ import {
22
22
  resolveFsConfig,
23
23
  splitFrontmatter,
24
24
  withBrokenPipeGuard
25
- } from "./chunks/chunk-GMDOPMVZ.js";
25
+ } from "./chunks/chunk-X32RVLSM.js";
26
26
  import {
27
27
  Budget,
28
28
  SandboxError,
@@ -34,7 +34,7 @@ import {
34
34
  replaceErrorStack,
35
35
  restore,
36
36
  run
37
- } from "./chunks/chunk-B7H4ZL65.js";
37
+ } from "./chunks/chunk-MXUOEOBE.js";
38
38
  import "./chunks/chunk-4YIDX44G.js";
39
39
 
40
40
  // packages/safe-js/src/cli.ts
@@ -1,5 +1,8 @@
1
1
  export { lint, type Diagnostic, type Fix, type LintFixResult, type LintOptions } from "./lint.js";
2
2
  export { run } from "./run.js";
3
+ export { createRealm, type SafeJSRealm, type RealmOptions, type RealmResult, type RealmLimits } from "./realm.js";
4
+ export { defineExtension, type SafeJSExtension, type ExtensionDefinition, type ExtensionManifest, type ExtensionContext, type ExtensionExports, type CallbackOptions } from "./extensions.js";
5
+ export type { HostObject, HostObjectDefinition, GuestReference } from "./interp/host-capabilities.js";
3
6
  export { createReplayableRandom, type ReplayableRandom } from "./random.js";
4
7
  export type { RunClock, RunClockSnapshot, RunRandom } from "./run.js";
5
8
  export { Budget } from "./interp/budget.js";
@@ -1,13 +1,17 @@
1
1
  import {
2
2
  Budget,
3
+ createRealm,
3
4
  createReplayableRandom,
5
+ defineExtension,
4
6
  lint,
5
7
  run
6
- } from "./chunks/chunk-B7H4ZL65.js";
8
+ } from "./chunks/chunk-MXUOEOBE.js";
7
9
  import "./chunks/chunk-4YIDX44G.js";
8
10
  export {
9
11
  Budget,
12
+ createRealm,
10
13
  createReplayableRandom,
14
+ defineExtension,
11
15
  lint,
12
16
  run
13
17
  };
@@ -0,0 +1,44 @@
1
+ import type { HostObjectDefinition, HostObject } from "./interp/host-capabilities.js";
2
+ import type { ModuleRegistry } from "./modules/registry.js";
3
+ import type { CallerInjectedBinding } from "./interp/host-bridge.js";
4
+ export type CallbackOptions = {
5
+ thisValue?: unknown;
6
+ args?: readonly unknown[];
7
+ };
8
+ export type HostOperation = {
9
+ invoke(...args: readonly any[]): unknown;
10
+ }["invoke"];
11
+ export type ExtensionManifest = {
12
+ version: 1;
13
+ name: string;
14
+ capabilities?: readonly string[];
15
+ globals?: readonly string[];
16
+ modules?: Readonly<Record<string, readonly string[]>>;
17
+ };
18
+ export type ExtensionExports = {
19
+ globals?: Record<string, CallerInjectedBinding>;
20
+ modules?: ModuleRegistry;
21
+ };
22
+ export type ExtensionContext = {
23
+ readonly signal: AbortSignal;
24
+ onCleanup(cleanup: () => void | Promise<void>): void;
25
+ chargeWork(units?: number): void;
26
+ createHostObject(definition: HostObjectDefinition): HostObject;
27
+ invokeCallback(callback: unknown, options?: CallbackOptions): Promise<unknown>;
28
+ releaseCallback(callback: unknown): void;
29
+ retainGuestArguments<Operation extends HostOperation>(operation: Operation, from: number): Operation;
30
+ releaseGuestReference(reference: unknown): void;
31
+ nestedOperation<Operation extends HostOperation>(operation: Operation): Operation;
32
+ evaluateNested(source: string): Promise<void>;
33
+ };
34
+ export type ExtensionDefinition = {
35
+ manifest: ExtensionManifest;
36
+ setup(context: ExtensionContext): ExtensionExports;
37
+ };
38
+ export type SafeJSExtension = {
39
+ readonly manifest: Readonly<ExtensionManifest>;
40
+ };
41
+ export declare function readDataRecord(value: unknown, label: string): Record<string, unknown>;
42
+ export declare function readStringList(value: unknown, label: string): readonly string[];
43
+ export declare function defineExtension(definition: ExtensionDefinition): SafeJSExtension;
44
+ export declare function getExtensionSetup(extension: SafeJSExtension): ExtensionDefinition["setup"];
@@ -4,13 +4,16 @@ import { deepCopyFromSandbox as copyFromSandboxInternal, type SandboxPromise, ty
4
4
  export { parse } from "./parse.js";
5
5
  export declare const parseModule: (source: string, filename?: string) => Module;
6
6
  export declare const restore: <TSnapshot extends SafeJSSnapshot>(snapshot: TSnapshot, options: RestoreOptions) => TSnapshot;
7
- type PublicCopyOptions = Omit<NonNullable<Parameters<typeof copyFromSandboxInternal>[1]>, "compilation">;
7
+ type PublicCopyOptions = Omit<NonNullable<Parameters<typeof copyFromSandboxInternal>[1]>, "compilation" | "unwrapHostObject">;
8
8
  export declare const deepCopyFromSandbox: {
9
9
  (value: SandboxPromise, options?: PublicCopyOptions): Promise<unknown>;
10
10
  (value: SandboxValue, options?: PublicCopyOptions): unknown;
11
11
  };
12
12
  export { lint, type Diagnostic, type Fix, type LintFixResult, type LintOptions } from "./lint.js";
13
13
  export { run } from "./run.js";
14
+ export { createRealm, type SafeJSRealm, type RealmOptions, type RealmResult, type RealmLimits } from "./realm.js";
15
+ export { defineExtension, type SafeJSExtension, type ExtensionDefinition, type ExtensionManifest, type ExtensionContext, type ExtensionExports, type CallbackOptions } from "./extensions.js";
16
+ export type { HostObject, HostObjectDefinition, GuestReference } from "./interp/host-capabilities.js";
14
17
  export { createReplayableRandom, type ReplayableRandom } from "./random.js";
15
18
  export type { RunClock, RunClockSnapshot, RunRandom } from "./run.js";
16
19
  export { noopOtelSink } from "./observability/otel.js";
@@ -26,7 +26,7 @@ import {
26
26
  runWithSpawnUsageAccumulator,
27
27
  splitFrontmatter,
28
28
  supportsSpawnMode
29
- } from "./chunks/chunk-GMDOPMVZ.js";
29
+ } from "./chunks/chunk-X32RVLSM.js";
30
30
  import {
31
31
  Budget,
32
32
  FileSnapshotBackend,
@@ -34,11 +34,13 @@ import {
34
34
  HostOperationResumePolicyError,
35
35
  SandboxError,
36
36
  SnapshotValidationError,
37
+ createRealm,
37
38
  createReplayableRandom,
38
39
  createSeededRandom,
39
40
  declareHostOperation,
40
41
  deepCopyFromSandbox,
41
42
  deepCopyToSandbox,
43
+ defineExtension,
42
44
  dump,
43
45
  hasOwnErrorCode,
44
46
  lint,
@@ -48,7 +50,7 @@ import {
48
50
  registerPendingHostCallPolicy,
49
51
  restore,
50
52
  run
51
- } from "./chunks/chunk-B7H4ZL65.js";
53
+ } from "./chunks/chunk-MXUOEOBE.js";
52
54
  import "./chunks/chunk-4YIDX44G.js";
53
55
 
54
56
  // packages/safe-js/src/parse.ts
@@ -412,11 +414,13 @@ export {
412
414
  HostOperationResumePolicyError,
413
415
  SandboxError,
414
416
  SnapshotValidationError,
417
+ createRealm,
415
418
  createReplayableRandom,
416
419
  createSpawnUsageAccumulator,
417
420
  declareHostOperation,
418
421
  deepCopyFromSandbox2 as deepCopyFromSandbox,
419
422
  deepCopyToSandbox,
423
+ defineExtension,
420
424
  dump,
421
425
  extractBlock,
422
426
  findExportedConstInitializer,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/parse.ts", "../src/runner/run-harness.ts", "../src/loader/find-exported.ts", "../src/modules/time.ts", "../src/index.ts"],
4
- "sourcesContent": ["import { parse as parseInternal, type ParseResult as ParsedNode } from \"./parse/parser.js\";\n\nexport { DisallowedSyntaxError } from \"./parse/parser.js\";\nexport const parse: (source: string, filename?: string) => ParsedNode = parseInternal;\nexport type {\n ArrayPattern,\n ArrayExpression,\n ArrowFunctionExpression,\n AssignmentExpression,\n AssignmentPattern,\n AssignmentProperty,\n AwaitExpression,\n BinaryExpression,\n BlockStatement,\n BooleanLiteral,\n BreakStatement,\n CallExpression,\n CatchClause,\n ConditionalExpression,\n ContinueStatement,\n DoWhileStatement,\n EmptyStatement,\n Expression,\n ExpressionStatement,\n ExportDefaultDeclaration,\n ExportNamedDeclaration,\n ImportDeclaration,\n ImportDefaultSpecifier,\n ImportNamespaceSpecifier,\n ImportSpecifier,\n ForInStatement,\n ForOfStatement,\n ForStatement,\n FunctionDeclaration,\n FunctionExpression,\n Identifier,\n IfStatement,\n LogicalExpression,\n MemberExpression,\n MetaProperty,\n NewExpression,\n NullLiteral,\n NumericLiteral,\n ObjectExpression,\n ObjectPattern,\n ParseResult,\n PatternTarget,\n Property,\n RegexLiteral,\n RestElement,\n ReturnStatement,\n SequenceExpression,\n SourceSpan,\n SpreadElement,\n Statement,\n StringLiteral,\n SwitchCase,\n SwitchStatement,\n TaggedTemplateExpression,\n TemplateElement,\n TemplateLiteral,\n ThisExpression,\n ThrowStatement,\n TryStatement,\n UnaryExpression,\n UndefinedLiteral,\n UpdateExpression,\n UpdateTarget,\n VariableDeclaration,\n VariableDeclarationKind,\n VariableDeclarator,\n WhileStatement\n} from \"./parse/parser.js\";\n", "import { readFile, stat } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\n\nimport { supportsSpawnMode } from \"@poe-code/agent-spawn/configs\";\nimport { SPAWN_MODES, type SpawnMode } from \"@poe-code/agent-spawn/types\";\nimport { hasOwnErrorCode } from \"../error-codes.js\";\nimport { countLineBreaks, extractBlock, maskSource } from \"../loader/extract-block.js\";\nimport { splitFrontmatter } from \"../loader/frontmatter.js\";\nimport { lint, type Diagnostic } from \"../lint.js\";\nimport { createLintModulesFromRuntimeRegistry } from \"../lint/runtime-modules.js\";\nimport type { ModuleExports, ModuleRegistry } from \"../modules/registry.js\";\nimport type { OtelSink } from \"../observability/otel.js\";\nimport { parseModule } from \"../parse/parser.js\";\nimport { run, type RunOptions, type RunResult } from \"../run.js\";\nimport type { SnapshotBackend } from \"../snapshot/backend.js\";\n\ntype HarnessMeta = {\n filepath: string;\n kind: unknown;\n version: unknown;\n};\n\nexport type RunHarnessOptions = {\n budget?: RunOptions[\"budget\"];\n modulesFor: (frontmatter: Record<string, unknown>, meta: HarnessMeta) => ModuleRegistry;\n otelSink?: OtelSink;\n signal?: AbortSignal;\n snapshotBackend?: SnapshotBackend;\n snapshotIntervalMs?: number;\n snapshotPath?: string;\n};\n\nexport type RunHarnessExecutionErrorResult = {\n aborted?: true;\n error: unknown;\n ok: false;\n};\n\nexport type RunHarnessResult = RunResult | RunHarnessExecutionErrorResult;\n\nfunction getOwnEntry(record: Record<string, unknown>, key: string): unknown {\n return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;\n}\n\nfunction createHarnessMeta(filepath: string, frontmatter: Record<string, unknown>): HarnessMeta {\n return {\n filepath,\n kind: getOwnEntry(frontmatter, \"kind\"),\n version: getOwnEntry(frontmatter, \"version\")\n };\n}\n\nfunction assertFrontmatterAgentModes(frontmatter: Record<string, unknown>): void {\n const agents = getOwnEntry(frontmatter, \"agents\");\n if (typeof agents !== \"object\" || agents === null || Array.isArray(agents)) {\n return;\n }\n\n for (const [name, definition] of Object.entries(agents)) {\n if (typeof definition !== \"object\" || definition === null || Array.isArray(definition)) {\n continue;\n }\n\n const record = definition as Record<string, unknown>;\n const agent = getOwnEntry(record, \"agent\");\n const mode = getOwnEntry(record, \"mode\");\n if (typeof agent !== \"string\" || typeof mode !== \"string\") {\n continue;\n }\n\n // Malformed mode strings are reported by the agent module's own validation.\n if (!SPAWN_MODES.includes(mode as SpawnMode)) {\n continue;\n }\n\n if (!supportsSpawnMode(agent, mode as SpawnMode)) {\n throw new Error(`Harness agent \"${name}\": agent \"${agent}\" does not support mode \"${mode}\".`);\n }\n }\n}\n\nexport class LintError extends Error {\n readonly diagnostics: readonly Diagnostic[];\n\n constructor(diagnostics: readonly Diagnostic[]) {\n super(formatLintErrorMessage(diagnostics));\n this.name = \"LintError\";\n this.diagnostics = diagnostics;\n }\n}\n\nexport async function runHarness(\n filepath: string,\n options: RunHarnessOptions\n): Promise<RunHarnessResult> {\n const rawSource = await readHarnessFile(filepath);\n const { executableSource, frontmatter, isRawScript } = loadExecutableSource(filepath, rawSource);\n assertFrontmatterAgentModes(frontmatter);\n const meta = createHarnessMeta(filepath, frontmatter);\n const modules = excludeHarnessModule(options.modulesFor(frontmatter, meta), isRawScript);\n const diagnostics = lint(executableSource, {\n filename: filepath,\n modules: createLintModulesFromRuntimeRegistry(modules)\n });\n const lintErrors = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\n if (lintErrors.length > 0) {\n throw new LintError(lintErrors);\n }\n\n return runHarnessSource(executableSource, {\n budget: options.budget,\n entryPointArgs: hasDefaultExport(executableSource, filepath) ? [] : undefined,\n filename: filepath,\n modules,\n otelSink: options.otelSink,\n signal: options.signal,\n snapshotBackend: options.snapshotBackend,\n snapshotIntervalMs: options.snapshotIntervalMs,\n snapshotPath: options.snapshotPath\n });\n}\n\nexport async function runHarnessPair(\n filepath: string,\n options: RunHarnessOptions\n): Promise<RunHarnessResult> {\n const pair = resolveHarnessPair(filepath);\n const [rawMarkdown, rawScript] = await Promise.all([\n readHarnessFile(pair.markdownPath),\n readHarnessFile(pair.scriptPath)\n ]);\n const { frontmatter, body } = splitFrontmatter(stripByteOrderMark(rawMarkdown));\n assertFrontmatterAgentModes(frontmatter);\n const executableSource = stripByteOrderMark(rawScript);\n const meta = createHarnessMeta(pair.markdownPath, frontmatter);\n const modules = options.modulesFor(frontmatter, meta);\n const diagnostics = lint(executableSource, {\n allowedExportNames: [\"schema\"],\n defaultExport: {\n parameters: [\"frontmatter\"],\n required: true\n },\n filename: pair.scriptPath,\n frontmatterFields: Object.keys(frontmatter),\n modules: createLintModulesFromRuntimeRegistry(modules)\n });\n const lintErrors = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\n if (lintErrors.length > 0) {\n throw new LintError(lintErrors);\n }\n\n return runHarnessSource(executableSource, {\n budget: options.budget,\n entryPointArgs: [frontmatter],\n filename: pair.scriptPath,\n importMeta: {\n body,\n filepath: pair.markdownPath,\n kind: meta.kind,\n version: meta.version\n },\n modules,\n otelSink: options.otelSink,\n signal: options.signal,\n snapshotBackend: options.snapshotBackend,\n snapshotIntervalMs: options.snapshotIntervalMs,\n snapshotPath: options.snapshotPath\n });\n}\n\nasync function readHarnessFile(filepath: string): Promise<string> {\n try {\n const stats = await stat(filepath);\n if (!stats.isFile()) {\n throw new Error(`Harness path must point to a file: ${filepath}`);\n }\n\n return await readFile(filepath, \"utf8\");\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\") || hasOwnErrorCode(error, \"ENOTDIR\")) {\n throw new Error(`Harness file not found: ${filepath}`);\n }\n\n throw error;\n }\n}\n\nfunction loadExecutableSource(\n filepath: string,\n source: string\n): {\n executableSource: string;\n frontmatter: Record<string, unknown>;\n isRawScript: boolean;\n} {\n if (isRawScriptPath(filepath)) {\n const executableSource = stripByteOrderMark(source);\n if (executableSource.length === 0) {\n throw new Error(`No code block found in empty harness file: ${filepath}`);\n }\n\n return {\n executableSource,\n frontmatter: {},\n isRawScript: true\n };\n }\n\n const { frontmatter, body } = splitFrontmatter(source);\n if (source.length === 0 || body.trim().length === 0) {\n throw new Error(`No code block found in empty harness file: ${filepath}`);\n }\n\n const bodyStartOffset = source.length - body.length;\n const { source: executableBlock, startOffset } = extractBlock(\n body,\n countLineBreaks(source, 0, bodyStartOffset) + 1\n );\n return {\n executableSource:\n maskSource(source.slice(0, bodyStartOffset + startOffset)) + stripHashbang(executableBlock),\n frontmatter,\n isRawScript: false\n };\n}\n\nfunction resolveHarnessPair(filepath: string): { markdownPath: string; scriptPath: string } {\n const extension = extname(filepath);\n const basename = extension.length === 0 ? filepath : filepath.slice(0, -extension.length);\n\n if (isRawScriptExtension(extension)) {\n return {\n markdownPath: `${basename}.md`,\n scriptPath: filepath\n };\n }\n\n return {\n markdownPath: filepath,\n scriptPath: `${basename}.ajs`\n };\n}\n\nfunction isRawScriptPath(filepath: string): boolean {\n return isRawScriptExtension(extname(filepath));\n}\n\nfunction isRawScriptExtension(extension: string): boolean {\n return extension === \".safejs\" || extension === \".ajs\";\n}\n\nasync function runHarnessSource(\n executableSource: string,\n options: Parameters<typeof run>[1]\n): Promise<RunHarnessResult> {\n try {\n return await run(executableSource, options);\n } catch (error) {\n if (isSetupError(error)) {\n throw error;\n }\n\n return {\n ...(isAbortError(error) ? { aborted: true as const } : {}),\n error,\n ok: false\n };\n }\n}\n\nfunction isSetupError(error: unknown): boolean {\n return error instanceof Error && error.name === \"ParseError\";\n}\n\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof Error) {\n return error.name === \"AbortError\";\n }\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n Object.prototype.hasOwnProperty.call(error, \"name\") &&\n (error as { name?: unknown }).name === \"AbortError\"\n );\n}\n\nfunction hasDefaultExport(source: string, filename: string): boolean {\n return parseModule(source, filename).body.some(\n (statement) => statement.type === \"ExportDefaultDeclaration\"\n );\n}\n\nfunction excludeHarnessModule(modules: ModuleRegistry, isRawScript: boolean): ModuleRegistry {\n if (!isRawScript) {\n return modules;\n }\n\n if (modules instanceof Map) {\n const rawModules = new Map(modules);\n rawModules.delete(\"harness\");\n return rawModules;\n }\n\n const rawModules: Record<string, ModuleExports> = {};\n\n for (const [moduleName, moduleExports] of Object.entries(modules)) {\n if (moduleName !== \"harness\") {\n rawModules[moduleName] = moduleExports;\n }\n }\n\n return rawModules;\n}\n\nfunction stripByteOrderMark(source: string): string {\n return source.startsWith(\"\\uFEFF\") ? source.slice(1) : source;\n}\n\nfunction stripHashbang(source: string): string {\n if (!source.startsWith(\"#!\")) {\n return source;\n }\n\n let end = 2;\n while (end < source.length && source[end] !== \"\\n\" && source[end] !== \"\\r\") end += 1;\n return `${\" \".repeat(end)}${source.slice(end)}`;\n}\n\nfunction formatLintErrorMessage(diagnostics: readonly Diagnostic[]): string {\n if (diagnostics.length === 0) {\n return \"Script lint failed.\";\n }\n\n return diagnostics\n .map(\n (diagnostic) =>\n `${diagnostic.filename}:${diagnostic.line}:${diagnostic.column} ${diagnostic.code} ${diagnostic.message}`\n )\n .join(\"\\n\");\n}\n", "import type { Expression, Module } from \"../parse/parser.js\";\n\nexport function findExportedConstInitializer(module: Module, name: string): Expression | undefined {\n for (const statement of module.body) {\n if (statement.type === \"ExportDefaultDeclaration\") {\n if (name === \"default\") {\n return statement.declaration;\n }\n\n continue;\n }\n\n if (statement.type !== \"ExportNamedDeclaration\") {\n continue;\n }\n\n const declaration = statement.declaration;\n if (declaration.kind !== \"const\") {\n throw new Error(`Exported '${name}' must be declared with const.`);\n }\n\n if (declaration.declarations.length !== 1) {\n throw new Error(\"Exported const declarations must contain exactly one declarator.\");\n }\n\n const declarator = declaration.declarations[0]!;\n if (declarator.id.type !== \"Identifier\") {\n throw new Error(\"Destructured exported const bindings are not supported.\");\n }\n\n if (declarator.id.name !== name) {\n continue;\n }\n\n if (declarator.init === undefined) {\n throw new Error(`Exported const '${name}' must have an initializer.`);\n }\n\n return declarator.init;\n }\n\n return undefined;\n}\n", "import { webcrypto as crypto } from \"node:crypto\";\n\nimport { createSeededRandom } from \"../interp/globals/math.js\";\n\nexport type TimeModuleOptions = {\n now?: () => number;\n random?: () => number;\n seed?: number;\n signal?: AbortSignal;\n};\n\nexport function makeTimeModule(options: TimeModuleOptions = {}): {\n random: () => number;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n uuid: () => string;\n} {\n const hasDeterministicRandom = options.random !== undefined || options.seed !== undefined;\n const random =\n options.random ??\n (options.seed === undefined ? () => Math.random() : createSeededRandom(options.seed).next);\n const now = options.now ?? (() => Date.now());\n const signal = options.signal;\n\n async function sleep(ms: number): Promise<void> {\n assertSleepDelay(ms);\n\n return await new Promise<void>((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(createSleepAbortError());\n return;\n }\n\n const start = performance.now();\n let timeout = setTimeout(resolveSleep, ms);\n\n function cleanup(): void {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", rejectSleep);\n }\n\n function resolveSleep(): void {\n const remainingMs = ms - (performance.now() - start);\n if (remainingMs > 0) {\n timeout = setTimeout(resolveSleep, remainingMs);\n return;\n }\n\n cleanup();\n resolve();\n }\n\n function rejectSleep(): void {\n cleanup();\n reject(createSleepAbortError());\n }\n\n signal?.addEventListener(\"abort\", rejectSleep, { once: true });\n });\n }\n\n return {\n random,\n now,\n sleep,\n uuid: hasDeterministicRandom ? () => createRandomUuid(random) : () => crypto.randomUUID()\n };\n}\n\nfunction createRandomUuid(random: () => number): string {\n const bytes = Array.from({ length: 16 }, () => Math.floor(readRandomUnit(random()) * 256));\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = bytes.map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20)\n ].join(\"-\");\n}\n\nfunction readRandomUnit(value: number): number {\n if (Number.isFinite(value) && value >= 0 && value < 1) {\n return value;\n }\n\n throw new RangeError(\"time.uuid() random source must return a number in [0, 1).\");\n}\n\nfunction assertSleepDelay(ms: number): void {\n if (Number.isFinite(ms) && ms >= 0) {\n return;\n }\n\n throw new RangeError(\"time.sleep(ms) requires a non-negative finite millisecond delay.\");\n}\n\nfunction createSleepAbortError(): Error {\n return new Error(\"time.sleep aborted.\");\n}\n", "import { parseModule as parseModuleInternal, type Module } from \"./parse/parser.js\";\nimport { restore as restoreInternal, type SafeJSSnapshot, type RestoreOptions } from \"./restore.js\";\nimport {\n deepCopyFromSandbox as copyFromSandboxInternal,\n type SandboxPromise,\n type SandboxValue\n} from \"./interp/values.js\";\n\nexport { parse } from \"./parse.js\";\nexport const parseModule: (source: string, filename?: string) => Module = parseModuleInternal;\nexport const restore: <TSnapshot extends SafeJSSnapshot>(\n snapshot: TSnapshot,\n options: RestoreOptions\n) => TSnapshot = restoreInternal;\ntype PublicCopyOptions = Omit<\n NonNullable<Parameters<typeof copyFromSandboxInternal>[1]>,\n \"compilation\"\n>;\nexport const deepCopyFromSandbox: {\n (value: SandboxPromise, options?: PublicCopyOptions): Promise<unknown>;\n (value: SandboxValue, options?: PublicCopyOptions): unknown;\n} = copyFromSandboxInternal;\nexport { lint, type Diagnostic, type Fix, type LintFixResult, type LintOptions } from \"./lint.js\";\nexport { run } from \"./run.js\";\nexport { createReplayableRandom, type ReplayableRandom } from \"./random.js\";\nexport type { RunClock, RunClockSnapshot, RunRandom } from \"./run.js\";\nexport { noopOtelSink } from \"./observability/otel.js\";\nexport type { OtelSink, OtelSpan } from \"./observability/otel.js\";\nexport { FileSnapshotBackend } from \"./snapshot/backend.js\";\nexport type { Snapshot, SnapshotBackend } from \"./snapshot/backend.js\";\nexport { declareHostOperation } from \"./interp/host-bridge.js\";\nexport { HostCallResumabilityError } from \"./interp/host-call.js\";\nexport type {\n HostCallLifecycle,\n HostCallOutcome,\n HostCallRecord,\n HostCallResumeContext,\n HostCallResumeProof,\n HostCallResumeProvider,\n HostCallResumeRequest\n} from \"./interp/host-call.js\";\nexport {\n HostOperationResumePolicyError,\n registerPendingHostCallPolicy\n} from \"./snapshot/policy.js\";\nexport type {\n PendingHostCallPolicyMode,\n PendingHostCallPolicyRegistration\n} from \"./snapshot/policy.js\";\nexport { dump, type DumpOptions } from \"./dump.js\";\nexport { inspectSnapshotMigration, migrateSnapshot } from \"./migrate.js\";\nexport { migrateSnapshotFile, type SnapshotMigrationFileOptions } from \"./migration-file.js\";\nexport type {\n SnapshotMigration,\n SnapshotMigrationOptions,\n SnapshotMigrationReconciliation,\n SnapshotMigrationResolution\n} from \"./migrate.js\";\nexport { SnapshotValidationError } from \"./snapshot/validation.js\";\nexport type { SnapshotValidationCode } from \"./snapshot/validation.js\";\nexport { Budget, SandboxError } from \"./interp/budget.js\";\nexport type { BudgetName, BudgetOptions } from \"./interp/budget.js\";\nexport { formatInterpreterError, type InterpreterDiagnostic } from \"./error/format.js\";\nexport { deepCopyToSandbox } from \"./interp/values.js\";\nexport { runHarness, runHarnessPair } from \"./runner/run-harness.js\";\nexport { extractBlock } from \"./loader/extract-block.js\";\nexport { findExportedConstInitializer } from \"./loader/find-exported.js\";\nexport { splitFrontmatter } from \"./loader/frontmatter.js\";\nexport type { ExportDefaultDeclaration, ExportNamedDeclaration, MetaProperty } from \"./parse.js\";\nexport {\n AgentSpawnError,\n createSpawnUsageAccumulator,\n makeAgentModule,\n runWithSpawnUsageAccumulator\n} from \"./modules/agent.js\";\nexport type {\n AgentModuleDefinition,\n AgentModuleOptions,\n AgentModuleParallelCall,\n AgentModuleRetryOptions,\n AgentModuleSpawnOptions,\n AgentSpawnEvent,\n SpawnAgent,\n SpawnAgentInput,\n SpawnAgentResult,\n SpawnUsageAccumulator,\n SpawnUsageTotal\n} from \"./modules/agent.js\";\nexport { EnvAccessError, makeEnvModule, parseEnvConfig } from \"./modules/env.js\";\nexport type { EnvModule, EnvModuleOptions } from \"./modules/env.js\";\nexport { makeFailModule } from \"./modules/fail.js\";\nexport { makeFsModule } from \"./modules/fs.js\";\nexport { parseFsConfig, resolveFsConfig } from \"./modules/fs-config.js\";\nexport type { FsConfig, ResolveFsConfigOptions } from \"./modules/fs-config.js\";\nexport type {\n FsImplementation,\n FsModule,\n FsModuleOptions,\n SandboxDirent,\n SandboxStats\n} from \"./modules/fs.js\";\nexport { makeHarnessModule } from \"./modules/harness.js\";\nexport { makeLogModule } from \"./modules/log.js\";\nexport { makeMetricModule } from \"./modules/metric.js\";\nexport { makeMcpModule } from \"./modules/mcp.js\";\nexport { parseMcpConfig } from \"./modules/mcp-transport.js\";\nexport type { McpModuleOptions, McpServerConfig } from \"./modules/mcp-transport.js\";\nexport type { ManagedMcpClient, ManagedMcpModule, McpNamedServerHandle } from \"./modules/mcp.js\";\nexport { makeTimeModule } from \"./modules/time.js\";\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,SAA2D;;;ACHxE,SAAS,UAAU,YAAY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IAAI,MAAM,IAAI,EAAE;AAAA,IAChB,IAAI,MAAM,IAAI,EAAE;AAAA,IAChB,IAAI,MAAM,EAAE;AAAA,EACd,EAAE,KAAK,GAAG;AACZ;AAEA,SAAS,eAAe,OAAuB;AAC7C,MAAI,OAAO,SAAS,KAAK,KAAK,SAAS,KAAK,QAAQ,GAAG;AACrD,WAAO;AAAA,EACT;AAEA,QAAM,IAAI,WAAW,2DAA2D;AAClF;AAEA,SAAS,iBAAiB,IAAkB;AAC1C,MAAI,OAAO,SAAS,EAAE,KAAK,MAAM,GAAG;AAClC;AAAA,EACF;AAEA,QAAM,IAAI,WAAW,kEAAkE;AACzF;AAEA,SAAS,wBAA+B;AACtC,SAAO,IAAI,MAAM,qBAAqB;AACxC;;;AC7FO,IAAMC,eAA6D;AACnE,IAAMC,WAGI;AAKV,IAAMC,uBAGT;",
4
+ "sourcesContent": ["import { parse as parseInternal, type ParseResult as ParsedNode } from \"./parse/parser.js\";\n\nexport { DisallowedSyntaxError } from \"./parse/parser.js\";\nexport const parse: (source: string, filename?: string) => ParsedNode = parseInternal;\nexport type {\n ArrayPattern,\n ArrayExpression,\n ArrowFunctionExpression,\n AssignmentExpression,\n AssignmentPattern,\n AssignmentProperty,\n AwaitExpression,\n BinaryExpression,\n BlockStatement,\n BooleanLiteral,\n BreakStatement,\n CallExpression,\n CatchClause,\n ConditionalExpression,\n ContinueStatement,\n DoWhileStatement,\n EmptyStatement,\n Expression,\n ExpressionStatement,\n ExportDefaultDeclaration,\n ExportNamedDeclaration,\n ImportDeclaration,\n ImportDefaultSpecifier,\n ImportNamespaceSpecifier,\n ImportSpecifier,\n ForInStatement,\n ForOfStatement,\n ForStatement,\n FunctionDeclaration,\n FunctionExpression,\n Identifier,\n IfStatement,\n LogicalExpression,\n MemberExpression,\n MetaProperty,\n NewExpression,\n NullLiteral,\n NumericLiteral,\n ObjectExpression,\n ObjectPattern,\n ParseResult,\n PatternTarget,\n Property,\n RegexLiteral,\n RestElement,\n ReturnStatement,\n SequenceExpression,\n SourceSpan,\n SpreadElement,\n Statement,\n StringLiteral,\n SwitchCase,\n SwitchStatement,\n TaggedTemplateExpression,\n TemplateElement,\n TemplateLiteral,\n ThisExpression,\n ThrowStatement,\n TryStatement,\n UnaryExpression,\n UndefinedLiteral,\n UpdateExpression,\n UpdateTarget,\n VariableDeclaration,\n VariableDeclarationKind,\n VariableDeclarator,\n WhileStatement\n} from \"./parse/parser.js\";\n", "import { readFile, stat } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\n\nimport { supportsSpawnMode } from \"@poe-code/agent-spawn/configs\";\nimport { SPAWN_MODES, type SpawnMode } from \"@poe-code/agent-spawn/types\";\nimport { hasOwnErrorCode } from \"../error-codes.js\";\nimport { countLineBreaks, extractBlock, maskSource } from \"../loader/extract-block.js\";\nimport { splitFrontmatter } from \"../loader/frontmatter.js\";\nimport { lint, type Diagnostic } from \"../lint.js\";\nimport { createLintModulesFromRuntimeRegistry } from \"../lint/runtime-modules.js\";\nimport type { ModuleExports, ModuleRegistry } from \"../modules/registry.js\";\nimport type { OtelSink } from \"../observability/otel.js\";\nimport { parseModule } from \"../parse/parser.js\";\nimport { run, type RunOptions, type RunResult } from \"../run.js\";\nimport type { SnapshotBackend } from \"../snapshot/backend.js\";\n\ntype HarnessMeta = {\n filepath: string;\n kind: unknown;\n version: unknown;\n};\n\nexport type RunHarnessOptions = {\n budget?: RunOptions[\"budget\"];\n modulesFor: (frontmatter: Record<string, unknown>, meta: HarnessMeta) => ModuleRegistry;\n otelSink?: OtelSink;\n signal?: AbortSignal;\n snapshotBackend?: SnapshotBackend;\n snapshotIntervalMs?: number;\n snapshotPath?: string;\n};\n\nexport type RunHarnessExecutionErrorResult = {\n aborted?: true;\n error: unknown;\n ok: false;\n};\n\nexport type RunHarnessResult = RunResult | RunHarnessExecutionErrorResult;\n\nfunction getOwnEntry(record: Record<string, unknown>, key: string): unknown {\n return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;\n}\n\nfunction createHarnessMeta(filepath: string, frontmatter: Record<string, unknown>): HarnessMeta {\n return {\n filepath,\n kind: getOwnEntry(frontmatter, \"kind\"),\n version: getOwnEntry(frontmatter, \"version\")\n };\n}\n\nfunction assertFrontmatterAgentModes(frontmatter: Record<string, unknown>): void {\n const agents = getOwnEntry(frontmatter, \"agents\");\n if (typeof agents !== \"object\" || agents === null || Array.isArray(agents)) {\n return;\n }\n\n for (const [name, definition] of Object.entries(agents)) {\n if (typeof definition !== \"object\" || definition === null || Array.isArray(definition)) {\n continue;\n }\n\n const record = definition as Record<string, unknown>;\n const agent = getOwnEntry(record, \"agent\");\n const mode = getOwnEntry(record, \"mode\");\n if (typeof agent !== \"string\" || typeof mode !== \"string\") {\n continue;\n }\n\n // Malformed mode strings are reported by the agent module's own validation.\n if (!SPAWN_MODES.includes(mode as SpawnMode)) {\n continue;\n }\n\n if (!supportsSpawnMode(agent, mode as SpawnMode)) {\n throw new Error(`Harness agent \"${name}\": agent \"${agent}\" does not support mode \"${mode}\".`);\n }\n }\n}\n\nexport class LintError extends Error {\n readonly diagnostics: readonly Diagnostic[];\n\n constructor(diagnostics: readonly Diagnostic[]) {\n super(formatLintErrorMessage(diagnostics));\n this.name = \"LintError\";\n this.diagnostics = diagnostics;\n }\n}\n\nexport async function runHarness(\n filepath: string,\n options: RunHarnessOptions\n): Promise<RunHarnessResult> {\n const rawSource = await readHarnessFile(filepath);\n const { executableSource, frontmatter, isRawScript } = loadExecutableSource(filepath, rawSource);\n assertFrontmatterAgentModes(frontmatter);\n const meta = createHarnessMeta(filepath, frontmatter);\n const modules = excludeHarnessModule(options.modulesFor(frontmatter, meta), isRawScript);\n const diagnostics = lint(executableSource, {\n filename: filepath,\n modules: createLintModulesFromRuntimeRegistry(modules)\n });\n const lintErrors = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\n if (lintErrors.length > 0) {\n throw new LintError(lintErrors);\n }\n\n return runHarnessSource(executableSource, {\n budget: options.budget,\n entryPointArgs: hasDefaultExport(executableSource, filepath) ? [] : undefined,\n filename: filepath,\n modules,\n otelSink: options.otelSink,\n signal: options.signal,\n snapshotBackend: options.snapshotBackend,\n snapshotIntervalMs: options.snapshotIntervalMs,\n snapshotPath: options.snapshotPath\n });\n}\n\nexport async function runHarnessPair(\n filepath: string,\n options: RunHarnessOptions\n): Promise<RunHarnessResult> {\n const pair = resolveHarnessPair(filepath);\n const [rawMarkdown, rawScript] = await Promise.all([\n readHarnessFile(pair.markdownPath),\n readHarnessFile(pair.scriptPath)\n ]);\n const { frontmatter, body } = splitFrontmatter(stripByteOrderMark(rawMarkdown));\n assertFrontmatterAgentModes(frontmatter);\n const executableSource = stripByteOrderMark(rawScript);\n const meta = createHarnessMeta(pair.markdownPath, frontmatter);\n const modules = options.modulesFor(frontmatter, meta);\n const diagnostics = lint(executableSource, {\n allowedExportNames: [\"schema\"],\n defaultExport: {\n parameters: [\"frontmatter\"],\n required: true\n },\n filename: pair.scriptPath,\n frontmatterFields: Object.keys(frontmatter),\n modules: createLintModulesFromRuntimeRegistry(modules)\n });\n const lintErrors = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\n if (lintErrors.length > 0) {\n throw new LintError(lintErrors);\n }\n\n return runHarnessSource(executableSource, {\n budget: options.budget,\n entryPointArgs: [frontmatter],\n filename: pair.scriptPath,\n importMeta: {\n body,\n filepath: pair.markdownPath,\n kind: meta.kind,\n version: meta.version\n },\n modules,\n otelSink: options.otelSink,\n signal: options.signal,\n snapshotBackend: options.snapshotBackend,\n snapshotIntervalMs: options.snapshotIntervalMs,\n snapshotPath: options.snapshotPath\n });\n}\n\nasync function readHarnessFile(filepath: string): Promise<string> {\n try {\n const stats = await stat(filepath);\n if (!stats.isFile()) {\n throw new Error(`Harness path must point to a file: ${filepath}`);\n }\n\n return await readFile(filepath, \"utf8\");\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\") || hasOwnErrorCode(error, \"ENOTDIR\")) {\n throw new Error(`Harness file not found: ${filepath}`);\n }\n\n throw error;\n }\n}\n\nfunction loadExecutableSource(\n filepath: string,\n source: string\n): {\n executableSource: string;\n frontmatter: Record<string, unknown>;\n isRawScript: boolean;\n} {\n if (isRawScriptPath(filepath)) {\n const executableSource = stripByteOrderMark(source);\n if (executableSource.length === 0) {\n throw new Error(`No code block found in empty harness file: ${filepath}`);\n }\n\n return {\n executableSource,\n frontmatter: {},\n isRawScript: true\n };\n }\n\n const { frontmatter, body } = splitFrontmatter(source);\n if (source.length === 0 || body.trim().length === 0) {\n throw new Error(`No code block found in empty harness file: ${filepath}`);\n }\n\n const bodyStartOffset = source.length - body.length;\n const { source: executableBlock, startOffset } = extractBlock(\n body,\n countLineBreaks(source, 0, bodyStartOffset) + 1\n );\n return {\n executableSource:\n maskSource(source.slice(0, bodyStartOffset + startOffset)) + stripHashbang(executableBlock),\n frontmatter,\n isRawScript: false\n };\n}\n\nfunction resolveHarnessPair(filepath: string): { markdownPath: string; scriptPath: string } {\n const extension = extname(filepath);\n const basename = extension.length === 0 ? filepath : filepath.slice(0, -extension.length);\n\n if (isRawScriptExtension(extension)) {\n return {\n markdownPath: `${basename}.md`,\n scriptPath: filepath\n };\n }\n\n return {\n markdownPath: filepath,\n scriptPath: `${basename}.ajs`\n };\n}\n\nfunction isRawScriptPath(filepath: string): boolean {\n return isRawScriptExtension(extname(filepath));\n}\n\nfunction isRawScriptExtension(extension: string): boolean {\n return extension === \".safejs\" || extension === \".ajs\";\n}\n\nasync function runHarnessSource(\n executableSource: string,\n options: Parameters<typeof run>[1]\n): Promise<RunHarnessResult> {\n try {\n return await run(executableSource, options);\n } catch (error) {\n if (isSetupError(error)) {\n throw error;\n }\n\n return {\n ...(isAbortError(error) ? { aborted: true as const } : {}),\n error,\n ok: false\n };\n }\n}\n\nfunction isSetupError(error: unknown): boolean {\n return error instanceof Error && error.name === \"ParseError\";\n}\n\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof Error) {\n return error.name === \"AbortError\";\n }\n\n return (\n typeof error === \"object\" &&\n error !== null &&\n Object.prototype.hasOwnProperty.call(error, \"name\") &&\n (error as { name?: unknown }).name === \"AbortError\"\n );\n}\n\nfunction hasDefaultExport(source: string, filename: string): boolean {\n return parseModule(source, filename).body.some(\n (statement) => statement.type === \"ExportDefaultDeclaration\"\n );\n}\n\nfunction excludeHarnessModule(modules: ModuleRegistry, isRawScript: boolean): ModuleRegistry {\n if (!isRawScript) {\n return modules;\n }\n\n if (modules instanceof Map) {\n const rawModules = new Map(modules);\n rawModules.delete(\"harness\");\n return rawModules;\n }\n\n const rawModules: Record<string, ModuleExports> = {};\n\n for (const [moduleName, moduleExports] of Object.entries(modules)) {\n if (moduleName !== \"harness\") {\n rawModules[moduleName] = moduleExports;\n }\n }\n\n return rawModules;\n}\n\nfunction stripByteOrderMark(source: string): string {\n return source.startsWith(\"\\uFEFF\") ? source.slice(1) : source;\n}\n\nfunction stripHashbang(source: string): string {\n if (!source.startsWith(\"#!\")) {\n return source;\n }\n\n let end = 2;\n while (end < source.length && source[end] !== \"\\n\" && source[end] !== \"\\r\") end += 1;\n return `${\" \".repeat(end)}${source.slice(end)}`;\n}\n\nfunction formatLintErrorMessage(diagnostics: readonly Diagnostic[]): string {\n if (diagnostics.length === 0) {\n return \"Script lint failed.\";\n }\n\n return diagnostics\n .map(\n (diagnostic) =>\n `${diagnostic.filename}:${diagnostic.line}:${diagnostic.column} ${diagnostic.code} ${diagnostic.message}`\n )\n .join(\"\\n\");\n}\n", "import type { Expression, Module } from \"../parse/parser.js\";\n\nexport function findExportedConstInitializer(module: Module, name: string): Expression | undefined {\n for (const statement of module.body) {\n if (statement.type === \"ExportDefaultDeclaration\") {\n if (name === \"default\") {\n return statement.declaration;\n }\n\n continue;\n }\n\n if (statement.type !== \"ExportNamedDeclaration\") {\n continue;\n }\n\n const declaration = statement.declaration;\n if (declaration.kind !== \"const\") {\n throw new Error(`Exported '${name}' must be declared with const.`);\n }\n\n if (declaration.declarations.length !== 1) {\n throw new Error(\"Exported const declarations must contain exactly one declarator.\");\n }\n\n const declarator = declaration.declarations[0]!;\n if (declarator.id.type !== \"Identifier\") {\n throw new Error(\"Destructured exported const bindings are not supported.\");\n }\n\n if (declarator.id.name !== name) {\n continue;\n }\n\n if (declarator.init === undefined) {\n throw new Error(`Exported const '${name}' must have an initializer.`);\n }\n\n return declarator.init;\n }\n\n return undefined;\n}\n", "import { webcrypto as crypto } from \"node:crypto\";\n\nimport { createSeededRandom } from \"../interp/globals/math.js\";\n\nexport type TimeModuleOptions = {\n now?: () => number;\n random?: () => number;\n seed?: number;\n signal?: AbortSignal;\n};\n\nexport function makeTimeModule(options: TimeModuleOptions = {}): {\n random: () => number;\n now: () => number;\n sleep: (ms: number) => Promise<void>;\n uuid: () => string;\n} {\n const hasDeterministicRandom = options.random !== undefined || options.seed !== undefined;\n const random =\n options.random ??\n (options.seed === undefined ? () => Math.random() : createSeededRandom(options.seed).next);\n const now = options.now ?? (() => Date.now());\n const signal = options.signal;\n\n async function sleep(ms: number): Promise<void> {\n assertSleepDelay(ms);\n\n return await new Promise<void>((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(createSleepAbortError());\n return;\n }\n\n const start = performance.now();\n let timeout = setTimeout(resolveSleep, ms);\n\n function cleanup(): void {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", rejectSleep);\n }\n\n function resolveSleep(): void {\n const remainingMs = ms - (performance.now() - start);\n if (remainingMs > 0) {\n timeout = setTimeout(resolveSleep, remainingMs);\n return;\n }\n\n cleanup();\n resolve();\n }\n\n function rejectSleep(): void {\n cleanup();\n reject(createSleepAbortError());\n }\n\n signal?.addEventListener(\"abort\", rejectSleep, { once: true });\n });\n }\n\n return {\n random,\n now,\n sleep,\n uuid: hasDeterministicRandom ? () => createRandomUuid(random) : () => crypto.randomUUID()\n };\n}\n\nfunction createRandomUuid(random: () => number): string {\n const bytes = Array.from({ length: 16 }, () => Math.floor(readRandomUnit(random()) * 256));\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = bytes.map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20)\n ].join(\"-\");\n}\n\nfunction readRandomUnit(value: number): number {\n if (Number.isFinite(value) && value >= 0 && value < 1) {\n return value;\n }\n\n throw new RangeError(\"time.uuid() random source must return a number in [0, 1).\");\n}\n\nfunction assertSleepDelay(ms: number): void {\n if (Number.isFinite(ms) && ms >= 0) {\n return;\n }\n\n throw new RangeError(\"time.sleep(ms) requires a non-negative finite millisecond delay.\");\n}\n\nfunction createSleepAbortError(): Error {\n return new Error(\"time.sleep aborted.\");\n}\n", "import { parseModule as parseModuleInternal, type Module } from \"./parse/parser.js\";\nimport { restore as restoreInternal, type SafeJSSnapshot, type RestoreOptions } from \"./restore.js\";\nimport {\n deepCopyFromSandbox as copyFromSandboxInternal,\n type SandboxPromise,\n type SandboxValue\n} from \"./interp/values.js\";\n\nexport { parse } from \"./parse.js\";\nexport const parseModule: (source: string, filename?: string) => Module = parseModuleInternal;\nexport const restore: <TSnapshot extends SafeJSSnapshot>(\n snapshot: TSnapshot,\n options: RestoreOptions\n) => TSnapshot = restoreInternal;\ntype PublicCopyOptions = Omit<\n NonNullable<Parameters<typeof copyFromSandboxInternal>[1]>,\n \"compilation\" | \"unwrapHostObject\"\n>;\nexport const deepCopyFromSandbox: {\n (value: SandboxPromise, options?: PublicCopyOptions): Promise<unknown>;\n (value: SandboxValue, options?: PublicCopyOptions): unknown;\n} = copyFromSandboxInternal;\nexport { lint, type Diagnostic, type Fix, type LintFixResult, type LintOptions } from \"./lint.js\";\nexport { run } from \"./run.js\";\nexport { createRealm, type SafeJSRealm, type RealmOptions, type RealmResult, type RealmLimits } from \"./realm.js\";\nexport { defineExtension, type SafeJSExtension, type ExtensionDefinition, type ExtensionManifest, type ExtensionContext, type ExtensionExports, type CallbackOptions } from \"./extensions.js\";\nexport type { HostObject, HostObjectDefinition, GuestReference } from \"./interp/host-capabilities.js\";\nexport { createReplayableRandom, type ReplayableRandom } from \"./random.js\";\nexport type { RunClock, RunClockSnapshot, RunRandom } from \"./run.js\";\nexport { noopOtelSink } from \"./observability/otel.js\";\nexport type { OtelSink, OtelSpan } from \"./observability/otel.js\";\nexport { FileSnapshotBackend } from \"./snapshot/backend.js\";\nexport type { Snapshot, SnapshotBackend } from \"./snapshot/backend.js\";\nexport { declareHostOperation } from \"./interp/host-bridge.js\";\nexport { HostCallResumabilityError } from \"./interp/host-call.js\";\nexport type {\n HostCallLifecycle,\n HostCallOutcome,\n HostCallRecord,\n HostCallResumeContext,\n HostCallResumeProof,\n HostCallResumeProvider,\n HostCallResumeRequest\n} from \"./interp/host-call.js\";\nexport {\n HostOperationResumePolicyError,\n registerPendingHostCallPolicy\n} from \"./snapshot/policy.js\";\nexport type {\n PendingHostCallPolicyMode,\n PendingHostCallPolicyRegistration\n} from \"./snapshot/policy.js\";\nexport { dump, type DumpOptions } from \"./dump.js\";\nexport { inspectSnapshotMigration, migrateSnapshot } from \"./migrate.js\";\nexport { migrateSnapshotFile, type SnapshotMigrationFileOptions } from \"./migration-file.js\";\nexport type {\n SnapshotMigration,\n SnapshotMigrationOptions,\n SnapshotMigrationReconciliation,\n SnapshotMigrationResolution\n} from \"./migrate.js\";\nexport { SnapshotValidationError } from \"./snapshot/validation.js\";\nexport type { SnapshotValidationCode } from \"./snapshot/validation.js\";\nexport { Budget, SandboxError } from \"./interp/budget.js\";\nexport type { BudgetName, BudgetOptions } from \"./interp/budget.js\";\nexport { formatInterpreterError, type InterpreterDiagnostic } from \"./error/format.js\";\nexport { deepCopyToSandbox } from \"./interp/values.js\";\nexport { runHarness, runHarnessPair } from \"./runner/run-harness.js\";\nexport { extractBlock } from \"./loader/extract-block.js\";\nexport { findExportedConstInitializer } from \"./loader/find-exported.js\";\nexport { splitFrontmatter } from \"./loader/frontmatter.js\";\nexport type { ExportDefaultDeclaration, ExportNamedDeclaration, MetaProperty } from \"./parse.js\";\nexport {\n AgentSpawnError,\n createSpawnUsageAccumulator,\n makeAgentModule,\n runWithSpawnUsageAccumulator\n} from \"./modules/agent.js\";\nexport type {\n AgentModuleDefinition,\n AgentModuleOptions,\n AgentModuleParallelCall,\n AgentModuleRetryOptions,\n AgentModuleSpawnOptions,\n AgentSpawnEvent,\n SpawnAgent,\n SpawnAgentInput,\n SpawnAgentResult,\n SpawnUsageAccumulator,\n SpawnUsageTotal\n} from \"./modules/agent.js\";\nexport { EnvAccessError, makeEnvModule, parseEnvConfig } from \"./modules/env.js\";\nexport type { EnvModule, EnvModuleOptions } from \"./modules/env.js\";\nexport { makeFailModule } from \"./modules/fail.js\";\nexport { makeFsModule } from \"./modules/fs.js\";\nexport { parseFsConfig, resolveFsConfig } from \"./modules/fs-config.js\";\nexport type { FsConfig, ResolveFsConfigOptions } from \"./modules/fs-config.js\";\nexport type {\n FsImplementation,\n FsModule,\n FsModuleOptions,\n SandboxDirent,\n SandboxStats\n} from \"./modules/fs.js\";\nexport { makeHarnessModule } from \"./modules/harness.js\";\nexport { makeLogModule } from \"./modules/log.js\";\nexport { makeMetricModule } from \"./modules/metric.js\";\nexport { makeMcpModule } from \"./modules/mcp.js\";\nexport { parseMcpConfig } from \"./modules/mcp-transport.js\";\nexport type { McpModuleOptions, McpServerConfig } from \"./modules/mcp-transport.js\";\nexport type { ManagedMcpClient, ManagedMcpModule, McpNamedServerHandle } from \"./modules/mcp.js\";\nexport { makeTimeModule } from \"./modules/time.js\";\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,SAA2D;;;ACHxE,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AAuCxB,SAAS,YAAY,QAAiC,KAAsB;AAC1E,SAAO,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG,IAAI,OAAO,GAAG,IAAI;AAC3E;AAEA,SA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AuB;AAC7C,MAAI,OAAO,SAAS,KAAK,KAAK,SAAS,KAAK,QAAQ,GAAG;AACrD,WAAO;AAAA,EACT;AAEA,QAAM,IAAI,WAAW,2DAA2D;AAClF;AAEA,SAAS,iBAAiB,IAAkB;AAC1C,MAAI,OAAO,SAAS,EAAE,KAAK,MAAM,GAAG;AAClC;AAAA,EACF;AAEA,QAAM,IAAI,WAAW,kEAAkE;AACzF;AAEA,SAAS,wBAA+B;AACtC,SAAO,IAAI,MAAM,qBAAqB;AACxC;;;AC7FO,IAAMC,eAA6D;AACnE,IAAMC,WAGI;AAKV,IAAMC,uBAGT;",
6
6
  "names": ["parse", "rawModules", "parseModule", "restore", "deepCopyFromSandbox"]
7
7
  }
@@ -19,6 +19,7 @@ type ResumeBreakpoint = Omit<InterpreterYieldPoint, "snapshot">;
19
19
  export type AsyncInterpreterError = InterpreterError;
20
20
  export type AsyncEvaluationResult = EvaluationResult<AsyncInterpreterError>;
21
21
  export type AsyncEvaluationContext = {
22
+ assertActive?: () => void;
22
23
  compilation?: CompileScope;
23
24
  activeLoopIterations: Map<number, LoopIterationSnapshot>;
24
25
  budget: Budget;
@@ -6,7 +6,19 @@ import type { RunLifecycle } from "../snapshot/dump.js";
6
6
  type CallerInjectedFunction = {
7
7
  bivarianceHack(...args: readonly unknown[]): unknown;
8
8
  }["bivarianceHack"];
9
- type HostBridgeOptions = {
9
+ export type RealmBridge = {
10
+ readonly owner: object;
11
+ assertActive(): void;
12
+ wrapCallback(closure: SandboxClosure): (...args: readonly unknown[]) => Promise<unknown>;
13
+ invoke(operation: CallerInjectedFunction, call: () => unknown): unknown;
14
+ awaitResult(operation: CallerInjectedFunction): boolean;
15
+ captureArguments(operation: CallerInjectedFunction, args: readonly SandboxValue[], copy: (values: readonly SandboxValue[]) => unknown[]): {
16
+ args: unknown[];
17
+ rollback(): void;
18
+ };
19
+ };
20
+ export type HostBridgeOptions = {
21
+ realm?: RealmBridge;
10
22
  registerCapabilities?: boolean;
11
23
  capabilityPath?: readonly string[];
12
24
  budget: Budget;
@@ -26,4 +38,9 @@ export declare function declareHostOperation<TFunction extends CallerInjectedFun
26
38
  }): TFunction;
27
39
  export declare function readHostOperationPolicy(operation: CallerInjectedFunction): PendingHostCallPolicyMode | undefined;
28
40
  export declare function wrapCallerInjectedBindings(bindings: Record<string, CallerInjectedBinding>, options: HostBridgeOptions): Record<string, SandboxValue>;
41
+ export declare function copyHostValueToSandbox(value: unknown, stackFrames: readonly string[], options: HostBridgeOptions & {
42
+ errorData?: boolean;
43
+ }, state: {
44
+ seen: WeakMap<object, SandboxValue>;
45
+ }, path: string): SandboxValue;
29
46
  export {};
@@ -0,0 +1,50 @@
1
+ import { type HostOperation } from "../extensions.js";
2
+ import type { SandboxClosure, SandboxObject, SandboxValue } from "./values.js";
3
+ declare const hostObjectBrand: unique symbol;
4
+ declare const guestReferenceBrand: unique symbol;
5
+ declare const sandboxHostObjectBrand: unique symbol;
6
+ type SandboxHostObject = SandboxObject & {
7
+ readonly [sandboxHostObjectBrand]: true;
8
+ };
9
+ export type HostObject = Readonly<Record<string, never>> & {
10
+ readonly [hostObjectBrand]: true;
11
+ };
12
+ export type GuestReference = Readonly<Record<string, never>> & {
13
+ readonly [guestReferenceBrand]: true;
14
+ };
15
+ export type HostObjectDefinition = {
16
+ properties?: Record<string, {
17
+ get?: () => unknown;
18
+ set?: (value: unknown) => void;
19
+ }>;
20
+ methods?: Record<string, HostOperation>;
21
+ };
22
+ export type HostObjectController = {
23
+ owner: object;
24
+ assertActive(): void;
25
+ chargeWork(units?: number): void;
26
+ read(operation: () => unknown): SandboxValue;
27
+ write(operation: (value: unknown) => void, value: SandboxValue): void;
28
+ method(operation: HostOperation): SandboxClosure;
29
+ };
30
+ type GuestCallbackState = {
31
+ owner: object;
32
+ closure?: SandboxClosure;
33
+ assertActive(): void;
34
+ };
35
+ export declare function createGuestReference(root: [SandboxValue], owner: object, assertActive: () => void): GuestReference;
36
+ export declare function readGuestReference(reference: unknown, owner: object): SandboxValue;
37
+ export declare function revokeGuestReference(reference: GuestReference, owner: object): void;
38
+ export declare function createLiveHostObject(definition: HostObjectDefinition, controller: HostObjectController): HostObject;
39
+ export declare function isGuestHostObject(value: unknown): value is SandboxHostObject;
40
+ export declare function isLiveCapability(value: unknown): boolean;
41
+ export declare function importHostCapability(value: object, owner: object): SandboxValue;
42
+ export declare function exportHostCapability(value: object, owner: object): HostObject;
43
+ export declare function registerGuestCallback(callback: HostOperation, state: GuestCallbackState): void;
44
+ export declare function readGuestCallback(callback: unknown, owner: object): SandboxClosure;
45
+ export declare function revokeGuestCallback(callback: object, owner: object): void;
46
+ export declare function revokeHostObject(value: HostObject, owner: object): void;
47
+ export declare function getHostObjectMember(value: SandboxObject, key: string): SandboxValue;
48
+ export declare function setHostObjectMember(value: SandboxObject, key: string, entry: SandboxValue): void;
49
+ export declare function getHostObjectKeys(value: SandboxObject): string[];
50
+ export {};
@@ -1,3 +1,4 @@
1
+ import { SandboxJobQueue } from "./jobs.js";
1
2
  import type { ParseResult, SourceSpan } from "../parse.js";
2
3
  import { type AsyncEvaluationContext, type AsyncEvaluationResult, type InterpreterYieldPoint } from "./async.js";
3
4
  import type { GeneratorCompletion } from "./generator.js";
@@ -43,6 +44,9 @@ export type InterpreterResult = {
43
44
  stats: InterpreterStats;
44
45
  };
45
46
  export type InterpretOptions = {
47
+ assertActive?: () => void;
48
+ jobs?: SandboxJobQueue;
49
+ nested?: boolean;
46
50
  compilation?: CompileScope;
47
51
  compileOwner?: CompileOwner;
48
52
  captureReplayState?: () => unknown;
@@ -0,0 +1,20 @@
1
+ type ExecutionJob = {
2
+ queue: SandboxJobQueue;
3
+ ownsExecution: boolean;
4
+ prefixParent?: ExecutionJob;
5
+ };
6
+ export declare class SandboxJobQueue {
7
+ private running;
8
+ private readonly pending;
9
+ private readonly idle;
10
+ private generation;
11
+ acquire(job: ExecutionJob): Promise<void>;
12
+ release(job: ExecutionJob): void;
13
+ run<T>(task: () => T | Promise<T>): Promise<T>;
14
+ drain(): Promise<void>;
15
+ private advance;
16
+ }
17
+ export declare function runPromiseJob<T>(task: () => T | Promise<T>): Promise<T>;
18
+ export declare function runAsyncPrefix<T>(task: () => Promise<T>): Promise<T>;
19
+ export declare function suspendJob<T>(pending: Promise<T>): Promise<T>;
20
+ export {};
@@ -86,6 +86,7 @@ export type SandboxGenerator = {
86
86
  };
87
87
  type CopyFromSandboxOptions = {
88
88
  wrapClosure?: (value: SandboxClosure) => unknown;
89
+ unwrapHostObject?: (value: SandboxObject) => unknown;
89
90
  compilation?: CompileScope;
90
91
  };
91
92
  export declare function createSandboxClosure(input: {
@@ -1,6 +1,6 @@
1
1
  import type { Budget, CompileOwner } from "../interp/budget.js";
2
2
  import type { HostCallJournal } from "../interp/host-call.js";
3
- import { type CallerInjectedBinding } from "../interp/host-bridge.js";
3
+ import { type RealmBridge, type CallerInjectedBinding } from "../interp/host-bridge.js";
4
4
  import type { SandboxValue } from "../interp/values.js";
5
5
  import type { Module } from "../parse/parser.js";
6
6
  export type ModuleExports = ReadonlyMap<string, CallerInjectedBinding> | Record<string, CallerInjectedBinding>;
@@ -9,6 +9,8 @@ export declare function createUnknownModuleMessage(moduleName: string, moduleNam
9
9
  export declare function createUnknownExportMessage(moduleName: string, exportName: string, availableExports: readonly string[]): string;
10
10
  export declare function resolveModuleImports(module: Module, modules: ModuleRegistry | undefined, options: {
11
11
  budget: Budget;
12
+ realm?: RealmBridge;
13
+ wrappedModules?: Map<string, Record<string, SandboxValue>>;
12
14
  compileOwner?: CompileOwner;
13
15
  hostCalls?: HostCallJournal;
14
16
  signal?: AbortSignal;
@@ -0,0 +1,45 @@
1
+ import { Budget } from "./interp/budget.js";
2
+ import { type InterpreterResult } from "./interp/interpreter.js";
3
+ import { type CallerInjectedBinding } from "./interp/host-bridge.js";
4
+ import { type CallbackOptions, type SafeJSExtension } from "./extensions.js";
5
+ import { type ModuleRegistry } from "./modules/registry.js";
6
+ import type { ConsoleSink } from "./interp/globals/console-json.js";
7
+ import type { RunOptions, RunResult } from "./run.js";
8
+ export type RealmLimits = {
9
+ extensions?: number;
10
+ hostObjects?: number;
11
+ callbacks?: number;
12
+ guestReferences?: number;
13
+ cleanups?: number;
14
+ nestedEvaluations?: number;
15
+ };
16
+ export type RealmOptions = {
17
+ bindings?: Record<string, CallerInjectedBinding>;
18
+ modules?: ModuleRegistry;
19
+ extensions?: readonly SafeJSExtension[];
20
+ grants?: readonly string[];
21
+ budget?: Budget;
22
+ signal?: AbortSignal;
23
+ sink?: ConsoleSink;
24
+ randomSeed?: number;
25
+ limits?: RealmLimits;
26
+ };
27
+ export type RealmResult = (Omit<Extract<InterpreterResult, {
28
+ ok: true;
29
+ }>, "snapshot" | "returnValue"> & {
30
+ returnValue?: unknown;
31
+ }) | Omit<Extract<InterpreterResult, {
32
+ ok: false;
33
+ }>, "snapshot">;
34
+ export type SafeJSRealm = {
35
+ readonly extensions: readonly SafeJSExtension["manifest"][];
36
+ evaluate(source: string, options?: {
37
+ filename?: string;
38
+ }): Promise<RealmResult>;
39
+ invokeCallback(callback: unknown, options?: CallbackOptions): Promise<unknown>;
40
+ releaseCallback(callback: unknown): void;
41
+ releaseGuestReference(reference: unknown): void;
42
+ close(): Promise<void>;
43
+ };
44
+ export declare function createRealm(options?: RealmOptions): SafeJSRealm;
45
+ export declare function runWithExtensions(source: string, options: RunOptions): Promise<RunResult>;
@@ -1,10 +1,11 @@
1
+ import { type RealmOptions } from "./realm.js";
1
2
  import { type ErrorSourceSpan } from "./error/shape.js";
2
3
  import { type SourceSpan } from "./parse/parser.js";
3
4
  import { type SafeJSSnapshot } from "./restore.js";
4
5
  import { Budget } from "./interp/budget.js";
5
6
  import { type PromiseReplaySnapshot } from "./interp/promise-replay.js";
6
7
  import { type HostCallRecord, type HostCallReplay, type HostCallResumeProvider } from "./interp/host-call.js";
7
- import { type ConsoleSink } from "./interp/globals/console-json.js";
8
+ import type { ConsoleSink } from "./interp/globals/console-json.js";
8
9
  import { type CallerInjectedBinding } from "./interp/host-bridge.js";
9
10
  import { type InterpreterResult, type LoopIterationSnapshot } from "./interp/interpreter.js";
10
11
  import { type ModuleRegistry } from "./modules/registry.js";
@@ -12,6 +13,9 @@ import { type OtelSink } from "./observability/otel.js";
12
13
  import type { SnapshotBackend } from "./snapshot/backend.js";
13
14
  import { type ReplayData } from "./snapshot/replay-data.js";
14
15
  export type RunOptions = {
16
+ extensions?: RealmOptions["extensions"];
17
+ grants?: RealmOptions["grants"];
18
+ limits?: RealmOptions["limits"];
15
19
  bindings?: Record<string, CallerInjectedBinding>;
16
20
  budget?: Budget;
17
21
  clock?: RunClock;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@poe-platform/safe-js",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "Budgeted JavaScript interpreter with explicit host capabilities and resumable execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -58,7 +58,7 @@
58
58
  "access": "public"
59
59
  },
60
60
  "dependencies": {
61
- "@poe-platform/safe-fs": "0.1.21",
61
+ "@poe-platform/safe-fs": "0.1.23",
62
62
  "yaml": "^2.8.2",
63
63
  "jose": "^6.1.3",
64
64
  "@types/node": "^25.2.2"