poe-code 13.0.3 → 13.0.5

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 (57) hide show
  1. package/dist/index.js +14421 -13628
  2. package/dist/index.js.map +4 -4
  3. package/dist/metafile.json +1 -1
  4. package/package.json +1 -1
  5. package/packages/safe-js/dist/chunks/{chunk-73LWNNUG.js → chunk-BI5UBZ7A.js} +14508 -13744
  6. package/packages/safe-js/dist/chunks/chunk-BI5UBZ7A.js.map +7 -0
  7. package/packages/safe-js/dist/chunks/{chunk-QCJ7UAMC.js → chunk-FH5X7CUS.js} +2 -2
  8. package/packages/safe-js/dist/cli.js +2 -2
  9. package/packages/safe-js/dist/core.js +1 -1
  10. package/packages/safe-js/dist/index.d.ts +11 -3
  11. package/packages/safe-js/dist/index.js +14 -6
  12. package/packages/safe-js/dist/index.js.map +4 -4
  13. package/packages/safe-js/dist/interp/async.d.ts +2 -0
  14. package/packages/safe-js/dist/interp/async.js +31 -15
  15. package/packages/safe-js/dist/interp/budget.d.ts +29 -0
  16. package/packages/safe-js/dist/interp/budget.js +143 -0
  17. package/packages/safe-js/dist/interp/globals/console-json.d.ts +2 -1
  18. package/packages/safe-js/dist/interp/globals/console-json.js +24 -6
  19. package/packages/safe-js/dist/interp/globals/regex.d.ts +2 -1
  20. package/packages/safe-js/dist/interp/globals/regex.js +24 -3
  21. package/packages/safe-js/dist/interp/host-bridge.d.ts +2 -1
  22. package/packages/safe-js/dist/interp/host-bridge.js +98 -55
  23. package/packages/safe-js/dist/interp/host-call.d.ts +3 -2
  24. package/packages/safe-js/dist/interp/host-call.js +91 -52
  25. package/packages/safe-js/dist/interp/interpreter.d.ts +4 -1
  26. package/packages/safe-js/dist/interp/interpreter.js +115 -79
  27. package/packages/safe-js/dist/interp/methods/string.d.ts +2 -1
  28. package/packages/safe-js/dist/interp/methods/string.js +111 -100
  29. package/packages/safe-js/dist/interp/regex/compile-guard.d.ts +33 -0
  30. package/packages/safe-js/dist/interp/regex/compile-guard.js +179 -0
  31. package/packages/safe-js/dist/interp/regex/parse.d.ts +2 -1
  32. package/packages/safe-js/dist/interp/regex/parse.js +87 -16
  33. package/packages/safe-js/dist/interp/values.d.ts +7 -2
  34. package/packages/safe-js/dist/interp/values.js +95 -9
  35. package/packages/safe-js/dist/modules/registry.d.ts +2 -1
  36. package/packages/safe-js/dist/modules/registry.js +1 -0
  37. package/packages/safe-js/dist/parse/hash.d.ts +2 -1
  38. package/packages/safe-js/dist/parse/hash.js +7 -4
  39. package/packages/safe-js/dist/parse/parser.d.ts +5 -3
  40. package/packages/safe-js/dist/parse/parser.js +53 -27
  41. package/packages/safe-js/dist/parse/tokenizer.d.ts +2 -0
  42. package/packages/safe-js/dist/parse/tokenizer.js +48 -26
  43. package/packages/safe-js/dist/parse.d.ts +3 -1
  44. package/packages/safe-js/dist/parse.js +3 -1
  45. package/packages/safe-js/dist/restore.d.ts +2 -1
  46. package/packages/safe-js/dist/restore.js +3 -3
  47. package/packages/safe-js/dist/run.js +289 -263
  48. package/packages/safe-js/dist/snapshot/migration.d.ts +3 -2
  49. package/packages/safe-js/dist/snapshot/migration.js +12 -5
  50. package/packages/safe-js/dist/snapshot/replay-data.d.ts +2 -1
  51. package/packages/safe-js/dist/snapshot/replay-data.js +172 -162
  52. package/packages/safe-js/dist/snapshot/replay-inputs.d.ts +2 -1
  53. package/packages/safe-js/dist/snapshot/replay-inputs.js +18 -11
  54. package/packages/safe-js/dist/snapshot/restore.d.ts +2 -2
  55. package/packages/safe-js/dist/snapshot/restore.js +142 -113
  56. package/packages/safe-js/dist/chunks/chunk-73LWNNUG.js.map +0 -7
  57. /package/packages/safe-js/dist/chunks/{chunk-QCJ7UAMC.js.map → chunk-FH5X7CUS.js.map} +0 -0
@@ -27,7 +27,7 @@ import {
27
27
  validateMigrationSemantics,
28
28
  validateSnapshotData,
29
29
  validateSnapshotMigration
30
- } from "./chunk-73LWNNUG.js";
30
+ } from "./chunk-BI5UBZ7A.js";
31
31
  import {
32
32
  createFileSystem,
33
33
  createNodeFileSystemAdapterRegistry,
@@ -8183,4 +8183,4 @@ export {
8183
8183
  parseMcpConfig,
8184
8184
  makeMcpModule
8185
8185
  };
8186
- //# sourceMappingURL=chunk-QCJ7UAMC.js.map
8186
+ //# sourceMappingURL=chunk-FH5X7CUS.js.map
@@ -22,7 +22,7 @@ import {
22
22
  resolveFsConfig,
23
23
  splitFrontmatter,
24
24
  withBrokenPipeGuard
25
- } from "./chunks/chunk-QCJ7UAMC.js";
25
+ } from "./chunks/chunk-FH5X7CUS.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-73LWNNUG.js";
37
+ } from "./chunks/chunk-BI5UBZ7A.js";
38
38
  import "./chunks/chunk-ZRX5HT5L.js";
39
39
  import "./chunks/chunk-WVN5MMDR.js";
40
40
  import "./chunks/chunk-4YIDX44G.js";
@@ -3,7 +3,7 @@ import {
3
3
  createReplayableRandom,
4
4
  lint,
5
5
  run
6
- } from "./chunks/chunk-73LWNNUG.js";
6
+ } from "./chunks/chunk-BI5UBZ7A.js";
7
7
  import "./chunks/chunk-4YIDX44G.js";
8
8
  export {
9
9
  Budget,
@@ -1,5 +1,14 @@
1
+ import { type Module } from "./parse/parser.js";
2
+ import { type SafeJSSnapshot, type RestoreOptions } from "./restore.js";
3
+ import { deepCopyFromSandbox as copyFromSandboxInternal, type SandboxPromise, type SandboxValue } from "./interp/values.js";
1
4
  export { parse } from "./parse.js";
2
- export { parseModule } from "./parse/parser.js";
5
+ export declare const parseModule: (source: string, filename?: string) => Module;
6
+ export declare const restore: <TSnapshot extends SafeJSSnapshot>(snapshot: TSnapshot, options: RestoreOptions) => TSnapshot;
7
+ type PublicCopyOptions = Omit<NonNullable<Parameters<typeof copyFromSandboxInternal>[1]>, "compilation">;
8
+ export declare const deepCopyFromSandbox: {
9
+ (value: SandboxPromise, options?: PublicCopyOptions): Promise<unknown>;
10
+ (value: SandboxValue, options?: PublicCopyOptions): unknown;
11
+ };
3
12
  export { lint, type Diagnostic, type Fix, type LintFixResult, type LintOptions } from "./lint.js";
4
13
  export { run } from "./run.js";
5
14
  export { createReplayableRandom, type ReplayableRandom } from "./random.js";
@@ -14,7 +23,6 @@ export type { HostCallLifecycle, HostCallOutcome, HostCallRecord, HostCallResume
14
23
  export { HostOperationResumePolicyError, registerPendingHostCallPolicy } from "./snapshot/policy.js";
15
24
  export type { PendingHostCallPolicyMode, PendingHostCallPolicyRegistration } from "./snapshot/policy.js";
16
25
  export { dump, type DumpOptions } from "./dump.js";
17
- export { restore } from "./restore.js";
18
26
  export { inspectSnapshotMigration, migrateSnapshot } from "./migrate.js";
19
27
  export { migrateSnapshotFile, type SnapshotMigrationFileOptions } from "./migration-file.js";
20
28
  export type { SnapshotMigration, SnapshotMigrationOptions, SnapshotMigrationReconciliation, SnapshotMigrationResolution } from "./migrate.js";
@@ -23,7 +31,7 @@ export type { SnapshotValidationCode } from "./snapshot/validation.js";
23
31
  export { Budget, SandboxError } from "./interp/budget.js";
24
32
  export type { BudgetName, BudgetOptions } from "./interp/budget.js";
25
33
  export { formatInterpreterError, type InterpreterDiagnostic } from "./error/format.js";
26
- export { deepCopyFromSandbox, deepCopyToSandbox } from "./interp/values.js";
34
+ export { deepCopyToSandbox } from "./interp/values.js";
27
35
  export { runHarness, runHarnessPair } from "./runner/run-harness.js";
28
36
  export { extractBlock } from "./loader/extract-block.js";
29
37
  export { findExportedConstInitializer } from "./loader/find-exported.js";
@@ -29,7 +29,7 @@ import {
29
29
  runWithSpawnUsageAccumulator,
30
30
  splitFrontmatter,
31
31
  supportsSpawnMode
32
- } from "./chunks/chunk-QCJ7UAMC.js";
32
+ } from "./chunks/chunk-FH5X7CUS.js";
33
33
  import {
34
34
  Budget,
35
35
  FileSnapshotBackend,
@@ -51,11 +51,14 @@ import {
51
51
  registerPendingHostCallPolicy,
52
52
  restore,
53
53
  run
54
- } from "./chunks/chunk-73LWNNUG.js";
54
+ } from "./chunks/chunk-BI5UBZ7A.js";
55
55
  import "./chunks/chunk-ZRX5HT5L.js";
56
56
  import "./chunks/chunk-WVN5MMDR.js";
57
57
  import "./chunks/chunk-4YIDX44G.js";
58
58
 
59
+ // packages/safe-js/src/parse.ts
60
+ var parse2 = parse;
61
+
59
62
  // packages/safe-js/src/runner/run-harness.ts
60
63
  import { readFile, stat } from "node:fs/promises";
61
64
  import { extname } from "node:path";
@@ -726,6 +729,11 @@ function assertSleepDelay(ms) {
726
729
  function createSleepAbortError() {
727
730
  return new Error("time.sleep aborted.");
728
731
  }
732
+
733
+ // packages/safe-js/src/index.ts
734
+ var parseModule2 = parseModule;
735
+ var restore2 = restore;
736
+ var deepCopyFromSandbox2 = deepCopyFromSandbox;
729
737
  export {
730
738
  AgentSpawnError,
731
739
  Budget,
@@ -738,7 +746,7 @@ export {
738
746
  createReplayableRandom,
739
747
  createSpawnUsageAccumulator,
740
748
  declareHostOperation,
741
- deepCopyFromSandbox,
749
+ deepCopyFromSandbox2 as deepCopyFromSandbox,
742
750
  deepCopyToSandbox,
743
751
  dump,
744
752
  extractBlock,
@@ -759,14 +767,14 @@ export {
759
767
  migrateSnapshot,
760
768
  migrateSnapshotFile,
761
769
  noopOtelSink,
762
- parse,
770
+ parse2 as parse,
763
771
  parseEnvConfig,
764
772
  parseFsConfig,
765
773
  parseMcpConfig,
766
- parseModule,
774
+ parseModule2 as parseModule,
767
775
  registerPendingHostCallPolicy,
768
776
  resolveFsConfig,
769
- restore,
777
+ restore2 as restore,
770
778
  run,
771
779
  runHarness,
772
780
  runHarnessPair,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/runner/run-harness.ts", "../src/loader/find-exported.ts", "../src/modules/git.ts", "../src/modules/time.ts"],
4
- "sourcesContent": ["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 { execFile } from \"node:child_process\";\nimport { mkdir, readlink, realpath, rm, stat } from \"node:fs/promises\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { containsPath, isSamePath, resolveCanonicalPath } from \"./canonical-path.js\";\n\nexport type GitSavepoint = {\n head: string;\n stashRef?: string;\n};\n\nexport type GitCommitOptions = {\n message: string;\n files?: string[];\n};\n\nexport type GitWorktree = {\n path: string;\n branch: string;\n};\n\nexport type GitWorktreeCreateOptions = {\n base?: string;\n path?: string;\n};\n\ntype ExecFileResult = {\n stdout: string;\n stderr: string;\n};\n\nconst GIT_EXEC_MAX_BUFFER = 10 * 1024 * 1024;\nconst SAVEPOINT_REF_PREFIX = \"refs/poe-code/checkpoints/\";\n\nexport function makeGitModule(cwd: string): {\n head(): Promise<string>;\n checkpoint(): Promise<GitSavepoint>;\n commit(options: GitCommitOptions): Promise<string>;\n revert(savepoint: GitSavepoint): Promise<void>;\n diff(): Promise<string>;\n worktreeCreate(branch: string, options?: GitWorktreeCreateOptions): Promise<GitWorktree>;\n worktreeRemove(path: string): Promise<void>;\n worktreeList(): Promise<GitWorktree[]>;\n} {\n const normalizedCwd = readNonEmptyString(cwd, \"Git module cwd\");\n\n return {\n async head() {\n return runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n },\n\n async checkpoint() {\n const currentHead = await runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n const status = await runGitAndTrim(normalizedCwd, [\"status\", \"--porcelain\"]);\n\n if (status.length === 0) {\n return {\n head: currentHead\n };\n }\n\n const stashRef = createSavepointRef();\n const stashMessage = `poe-code checkpoint ${stashRef}`;\n\n await runGit(normalizedCwd, [\n \"stash\",\n \"push\",\n \"--include-untracked\",\n \"--message\",\n stashMessage\n ]);\n\n try {\n const stashOid = await runGitAndTrim(normalizedCwd, [\"rev-parse\", \"stash@{0}\"]);\n await runGit(normalizedCwd, [\"update-ref\", stashRef, stashOid]);\n await runGit(normalizedCwd, [\"stash\", \"apply\", \"--index\", stashRef]);\n await runGit(normalizedCwd, [\"stash\", \"drop\", \"stash@{0}\"]);\n\n return {\n head: currentHead,\n stashRef\n };\n } catch (error) {\n await cleanupFailedCheckpoint(normalizedCwd, stashRef);\n throw error;\n }\n },\n\n async commit(options) {\n const normalizedOptions = normalizeCommitOptions(options);\n\n if (normalizedOptions.files === undefined) {\n await runGit(normalizedCwd, [\"add\", \"--all\"]);\n await runGit(normalizedCwd, [\"commit\", \"--message\", normalizedOptions.message]);\n } else {\n await runGit(normalizedCwd, [\"add\", \"--\", ...normalizedOptions.files]);\n await runGit(normalizedCwd, [\n \"commit\",\n \"--message\",\n normalizedOptions.message,\n \"--\",\n ...normalizedOptions.files\n ]);\n }\n return runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n },\n\n async revert(savepoint) {\n const normalizedSavepoint = normalizeSavepoint(savepoint);\n\n try {\n await runGit(normalizedCwd, [\"reset\", \"--hard\", normalizedSavepoint.head]);\n await runGit(normalizedCwd, [\"clean\", \"--force\", \"-d\"]);\n\n if (normalizedSavepoint.stashRef !== undefined) {\n await runGit(normalizedCwd, [\"stash\", \"apply\", \"--index\", normalizedSavepoint.stashRef]);\n }\n } finally {\n if (normalizedSavepoint.stashRef !== undefined) {\n await deleteSavepointRef(normalizedCwd, normalizedSavepoint.stashRef);\n }\n }\n },\n\n async diff() {\n const { stdout } = await runGit(normalizedCwd, [\"diff\", \"HEAD\", \"--\"]);\n return stdout;\n },\n\n async worktreeCreate(branch, options) {\n const normalizedBranch = readNonEmptyString(branch, \"Git worktree branch\");\n const normalizedOptions = normalizeWorktreeCreateOptions(options);\n const repoRoot = await getRepoRoot(normalizedCwd);\n const worktreePath = await resolveWorktreePath(\n repoRoot,\n normalizedOptions.path ?? createDefaultWorktreePath(repoRoot, normalizedBranch),\n \"Git worktree path\"\n );\n\n if (await gitRefExists(normalizedCwd, `refs/heads/${normalizedBranch}`)) {\n throw new Error(`Git worktree branch '${normalizedBranch}' already exists.`);\n }\n\n await mkdir(dirname(worktreePath), { recursive: true });\n\n try {\n await runGit(normalizedCwd, [\n \"worktree\",\n \"add\",\n \"-b\",\n normalizedBranch,\n worktreePath,\n normalizedOptions.base\n ]);\n } catch (error) {\n if (isBranchAlreadyExistsError(error, normalizedBranch)) {\n throw new Error(`Git worktree branch '${normalizedBranch}' already exists.`);\n }\n\n throw error;\n }\n\n return {\n path: worktreePath,\n branch: normalizedBranch\n };\n },\n\n async worktreeRemove(path) {\n const repoRoot = await getRepoRoot(normalizedCwd);\n const worktreePath = await resolveWorktreePath(repoRoot, path, \"Git worktree path\");\n const worktrees = await listWorktrees(normalizedCwd);\n\n if (!worktrees.some((worktree) => resolve(worktree.path) === worktreePath)) {\n return;\n }\n\n await runGit(normalizedCwd, [\"worktree\", \"remove\", \"--force\", worktreePath]);\n await rm(worktreePath, { recursive: true, force: true });\n },\n\n async worktreeList() {\n return listWorktrees(normalizedCwd);\n }\n };\n}\n\nfunction normalizeCommitOptions(options: GitCommitOptions | unknown): GitCommitOptions {\n if (!isRecord(options)) {\n throw new Error(\"Git commit options must be an object.\");\n }\n\n const files = getOwnProperty(options, \"files\");\n\n return {\n message: readNonEmptyString(getOwnProperty(options, \"message\"), \"Git commit options message\"),\n files:\n files === undefined ? undefined : readNonEmptyStringArray(files, \"Git commit options files\")\n };\n}\n\nfunction normalizeSavepoint(savepoint: GitSavepoint | unknown): GitSavepoint {\n if (!isRecord(savepoint)) {\n throw new Error(\"Git savepoint must be an object.\");\n }\n\n const stashRefValue = getOwnProperty(savepoint, \"stashRef\");\n const stashRef =\n stashRefValue === undefined\n ? undefined\n : readNonEmptyString(stashRefValue, \"Git savepoint stashRef\");\n if (stashRef !== undefined && !stashRef.startsWith(SAVEPOINT_REF_PREFIX)) {\n throw new Error(\"Git savepoint stashRef must be a Poe checkpoint ref.\");\n }\n\n return {\n head: readNonEmptyString(getOwnProperty(savepoint, \"head\"), \"Git savepoint head\"),\n stashRef\n };\n}\n\nfunction normalizeWorktreeCreateOptions(\n options: GitWorktreeCreateOptions | unknown\n): GitWorktreeCreateOptions & {\n base: string;\n} {\n if (options === undefined) {\n return {\n base: \"HEAD\"\n };\n }\n\n if (!isRecord(options)) {\n throw new Error(\"Git worktree create options must be an object.\");\n }\n\n const base = getOwnProperty(options, \"base\");\n const path = getOwnProperty(options, \"path\");\n\n return {\n base:\n base === undefined ? \"HEAD\" : readNonEmptyString(base, \"Git worktree create options base\"),\n path:\n path === undefined ? undefined : readNonEmptyString(path, \"Git worktree create options path\")\n };\n}\n\nfunction createSavepointRef(): string {\n return `${SAVEPOINT_REF_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction createDefaultWorktreePath(repoRoot: string, branch: string): string {\n return resolve(repoRoot, \".poe-code\", \"worktrees\", createSafeBranchDirectoryName(branch));\n}\n\nfunction createSafeBranchDirectoryName(branch: string): string {\n return encodeURIComponent(branch);\n}\n\nasync function getRepoRoot(cwd: string): Promise<string> {\n return runGitAndTrim(cwd, [\"rev-parse\", \"--show-toplevel\"]);\n}\n\nasync function gitRefExists(cwd: string, ref: string): Promise<boolean> {\n try {\n await runGit(cwd, [\"show-ref\", \"--verify\", \"--quiet\", ref]);\n return true;\n } catch (error) {\n void error;\n return false;\n }\n}\n\nasync function listWorktrees(cwd: string): Promise<GitWorktree[]> {\n const { stdout } = await runGit(cwd, [\"worktree\", \"list\", \"--porcelain\"]);\n return parseWorktreeList(stdout);\n}\n\nfunction parseWorktreeList(output: string): GitWorktree[] {\n const worktrees: GitWorktree[] = [];\n let current: Partial<GitWorktree> = {};\n\n const finishCurrent = () => {\n if (current.path !== undefined && current.branch !== undefined) {\n worktrees.push({\n path: current.path,\n branch: current.branch\n });\n }\n\n current = {};\n };\n\n for (const line of output.split(\"\\n\")) {\n if (line.length === 0) {\n finishCurrent();\n continue;\n }\n\n if (line.startsWith(\"worktree \")) {\n current.path = line.slice(\"worktree \".length);\n continue;\n }\n\n if (line.startsWith(\"branch \")) {\n current.branch = parseBranchRef(line.slice(\"branch \".length));\n }\n }\n\n finishCurrent();\n return worktrees;\n}\n\nfunction parseBranchRef(ref: string): string {\n const branchPrefix = \"refs/heads/\";\n return ref.startsWith(branchPrefix) ? ref.slice(branchPrefix.length) : ref;\n}\n\nasync function resolveWorktreePath(repoRoot: string, path: string, label: string): Promise<string> {\n const resolvedRoot = resolve(repoRoot);\n const resolvedPath = isAbsolute(path) ? resolve(path) : resolve(resolvedRoot, path);\n const canonicalRoot = await realpath(resolvedRoot);\n const canonicalPath = await resolveCanonicalPath({ realpath, readlink }, resolvedPath);\n\n // A worktree lives somewhere under the repository, never at the repository root\n // itself, so root-itself is rejected alongside anything outside it. Both answers\n // come from the filesystem rather than the spelling: on a case-insensitive\n // filesystem a differently cased path still names the repository root.\n const [inside, isRootItself] = await Promise.all([\n containsPath(stat, canonicalRoot, canonicalPath),\n isSamePath(stat, canonicalPath, canonicalRoot)\n ]);\n\n if (!inside || isRootItself) {\n throw new Error(`${label} must be inside the git repository.`);\n }\n\n return canonicalPath;\n}\n\nfunction isBranchAlreadyExistsError(error: unknown, branch: string): boolean {\n return (\n error instanceof Error &&\n error.message.includes(branch) &&\n error.message.includes(\"already exists\")\n );\n}\n\nasync function runGitAndTrim(cwd: string, args: string[]): Promise<string> {\n const { stdout } = await runGit(cwd, args);\n return stdout.trim();\n}\n\nasync function runGit(cwd: string, args: string[]): Promise<ExecFileResult> {\n return new Promise((resolve, reject) => {\n execFile(\n \"git\",\n args,\n {\n cwd,\n encoding: \"utf8\",\n maxBuffer: GIT_EXEC_MAX_BUFFER\n },\n (error, stdout, stderr) => {\n if (error) {\n reject(\n new Error(\n `${formatGitCommand(args)} failed: ${pickGitFailureMessage(stdout, stderr, error)}`\n )\n );\n return;\n }\n\n resolve({\n stdout,\n stderr\n });\n }\n );\n });\n}\n\nasync function cleanupFailedCheckpoint(cwd: string, stashRef: string): Promise<void> {\n await deleteSavepointRef(cwd, stashRef);\n const restored = await tryRunGit(cwd, [\"stash\", \"apply\", \"--index\", \"stash@{0}\"]);\n if (restored) {\n await tryRunGit(cwd, [\"stash\", \"drop\", \"stash@{0}\"]);\n }\n}\n\nasync function deleteSavepointRef(cwd: string, stashRef: string): Promise<void> {\n await tryRunGit(cwd, [\"update-ref\", \"--delete\", stashRef]);\n}\n\nasync function tryRunGit(cwd: string, args: string[]): Promise<boolean> {\n try {\n await runGit(cwd, args);\n return true;\n } catch (error) {\n void error;\n return false;\n }\n}\n\nfunction formatGitCommand(args: string[]): string {\n return [\"git\", ...args].join(\" \");\n}\n\nfunction pickGitFailureMessage(stdout: string, stderr: string, error: Error): string {\n const stderrText = stderr.trim();\n\n if (stderrText.length > 0) {\n return stderrText;\n }\n\n const stdoutText = stdout.trim();\n\n if (stdoutText.length > 0) {\n return stdoutText;\n }\n\n return error.message;\n}\n\nfunction readNonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string.`);\n }\n\n return value;\n}\n\nfunction readNonEmptyStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(`${label} must be a non-empty array of strings.`);\n }\n\n const entries = value.map((entry, index) => readNonEmptyString(entry, `${label}[${index}]`));\n return [...entries];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getOwnProperty<Name extends PropertyKey>(value: object, name: Name): unknown {\n return hasOwnProperty(value, name) ? value[name] : undefined;\n}\n\nfunction hasOwnProperty<Name extends PropertyKey>(\n value: object,\n name: Name\n): value is Record<Name, unknown> {\n return Object.prototype.hasOwnProperty.call(value, name);\n}\n", "import { 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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AAC/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AM,GAAG,EAAE;AAAA,IACf,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;",
6
- "names": ["rawModules", "stat", "stat", "resolve", "resolve"]
3
+ "sources": ["../src/parse.ts", "../src/runner/run-harness.ts", "../src/loader/find-exported.ts", "../src/modules/git.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 { execFile } from \"node:child_process\";\nimport { mkdir, readlink, realpath, rm, stat } from \"node:fs/promises\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { containsPath, isSamePath, resolveCanonicalPath } from \"./canonical-path.js\";\n\nexport type GitSavepoint = {\n head: string;\n stashRef?: string;\n};\n\nexport type GitCommitOptions = {\n message: string;\n files?: string[];\n};\n\nexport type GitWorktree = {\n path: string;\n branch: string;\n};\n\nexport type GitWorktreeCreateOptions = {\n base?: string;\n path?: string;\n};\n\ntype ExecFileResult = {\n stdout: string;\n stderr: string;\n};\n\nconst GIT_EXEC_MAX_BUFFER = 10 * 1024 * 1024;\nconst SAVEPOINT_REF_PREFIX = \"refs/poe-code/checkpoints/\";\n\nexport function makeGitModule(cwd: string): {\n head(): Promise<string>;\n checkpoint(): Promise<GitSavepoint>;\n commit(options: GitCommitOptions): Promise<string>;\n revert(savepoint: GitSavepoint): Promise<void>;\n diff(): Promise<string>;\n worktreeCreate(branch: string, options?: GitWorktreeCreateOptions): Promise<GitWorktree>;\n worktreeRemove(path: string): Promise<void>;\n worktreeList(): Promise<GitWorktree[]>;\n} {\n const normalizedCwd = readNonEmptyString(cwd, \"Git module cwd\");\n\n return {\n async head() {\n return runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n },\n\n async checkpoint() {\n const currentHead = await runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n const status = await runGitAndTrim(normalizedCwd, [\"status\", \"--porcelain\"]);\n\n if (status.length === 0) {\n return {\n head: currentHead\n };\n }\n\n const stashRef = createSavepointRef();\n const stashMessage = `poe-code checkpoint ${stashRef}`;\n\n await runGit(normalizedCwd, [\n \"stash\",\n \"push\",\n \"--include-untracked\",\n \"--message\",\n stashMessage\n ]);\n\n try {\n const stashOid = await runGitAndTrim(normalizedCwd, [\"rev-parse\", \"stash@{0}\"]);\n await runGit(normalizedCwd, [\"update-ref\", stashRef, stashOid]);\n await runGit(normalizedCwd, [\"stash\", \"apply\", \"--index\", stashRef]);\n await runGit(normalizedCwd, [\"stash\", \"drop\", \"stash@{0}\"]);\n\n return {\n head: currentHead,\n stashRef\n };\n } catch (error) {\n await cleanupFailedCheckpoint(normalizedCwd, stashRef);\n throw error;\n }\n },\n\n async commit(options) {\n const normalizedOptions = normalizeCommitOptions(options);\n\n if (normalizedOptions.files === undefined) {\n await runGit(normalizedCwd, [\"add\", \"--all\"]);\n await runGit(normalizedCwd, [\"commit\", \"--message\", normalizedOptions.message]);\n } else {\n await runGit(normalizedCwd, [\"add\", \"--\", ...normalizedOptions.files]);\n await runGit(normalizedCwd, [\n \"commit\",\n \"--message\",\n normalizedOptions.message,\n \"--\",\n ...normalizedOptions.files\n ]);\n }\n return runGitAndTrim(normalizedCwd, [\"rev-parse\", \"HEAD\"]);\n },\n\n async revert(savepoint) {\n const normalizedSavepoint = normalizeSavepoint(savepoint);\n\n try {\n await runGit(normalizedCwd, [\"reset\", \"--hard\", normalizedSavepoint.head]);\n await runGit(normalizedCwd, [\"clean\", \"--force\", \"-d\"]);\n\n if (normalizedSavepoint.stashRef !== undefined) {\n await runGit(normalizedCwd, [\"stash\", \"apply\", \"--index\", normalizedSavepoint.stashRef]);\n }\n } finally {\n if (normalizedSavepoint.stashRef !== undefined) {\n await deleteSavepointRef(normalizedCwd, normalizedSavepoint.stashRef);\n }\n }\n },\n\n async diff() {\n const { stdout } = await runGit(normalizedCwd, [\"diff\", \"HEAD\", \"--\"]);\n return stdout;\n },\n\n async worktreeCreate(branch, options) {\n const normalizedBranch = readNonEmptyString(branch, \"Git worktree branch\");\n const normalizedOptions = normalizeWorktreeCreateOptions(options);\n const repoRoot = await getRepoRoot(normalizedCwd);\n const worktreePath = await resolveWorktreePath(\n repoRoot,\n normalizedOptions.path ?? createDefaultWorktreePath(repoRoot, normalizedBranch),\n \"Git worktree path\"\n );\n\n if (await gitRefExists(normalizedCwd, `refs/heads/${normalizedBranch}`)) {\n throw new Error(`Git worktree branch '${normalizedBranch}' already exists.`);\n }\n\n await mkdir(dirname(worktreePath), { recursive: true });\n\n try {\n await runGit(normalizedCwd, [\n \"worktree\",\n \"add\",\n \"-b\",\n normalizedBranch,\n worktreePath,\n normalizedOptions.base\n ]);\n } catch (error) {\n if (isBranchAlreadyExistsError(error, normalizedBranch)) {\n throw new Error(`Git worktree branch '${normalizedBranch}' already exists.`);\n }\n\n throw error;\n }\n\n return {\n path: worktreePath,\n branch: normalizedBranch\n };\n },\n\n async worktreeRemove(path) {\n const repoRoot = await getRepoRoot(normalizedCwd);\n const worktreePath = await resolveWorktreePath(repoRoot, path, \"Git worktree path\");\n const worktrees = await listWorktrees(normalizedCwd);\n\n if (!worktrees.some((worktree) => resolve(worktree.path) === worktreePath)) {\n return;\n }\n\n await runGit(normalizedCwd, [\"worktree\", \"remove\", \"--force\", worktreePath]);\n await rm(worktreePath, { recursive: true, force: true });\n },\n\n async worktreeList() {\n return listWorktrees(normalizedCwd);\n }\n };\n}\n\nfunction normalizeCommitOptions(options: GitCommitOptions | unknown): GitCommitOptions {\n if (!isRecord(options)) {\n throw new Error(\"Git commit options must be an object.\");\n }\n\n const files = getOwnProperty(options, \"files\");\n\n return {\n message: readNonEmptyString(getOwnProperty(options, \"message\"), \"Git commit options message\"),\n files:\n files === undefined ? undefined : readNonEmptyStringArray(files, \"Git commit options files\")\n };\n}\n\nfunction normalizeSavepoint(savepoint: GitSavepoint | unknown): GitSavepoint {\n if (!isRecord(savepoint)) {\n throw new Error(\"Git savepoint must be an object.\");\n }\n\n const stashRefValue = getOwnProperty(savepoint, \"stashRef\");\n const stashRef =\n stashRefValue === undefined\n ? undefined\n : readNonEmptyString(stashRefValue, \"Git savepoint stashRef\");\n if (stashRef !== undefined && !stashRef.startsWith(SAVEPOINT_REF_PREFIX)) {\n throw new Error(\"Git savepoint stashRef must be a Poe checkpoint ref.\");\n }\n\n return {\n head: readNonEmptyString(getOwnProperty(savepoint, \"head\"), \"Git savepoint head\"),\n stashRef\n };\n}\n\nfunction normalizeWorktreeCreateOptions(\n options: GitWorktreeCreateOptions | unknown\n): GitWorktreeCreateOptions & {\n base: string;\n} {\n if (options === undefined) {\n return {\n base: \"HEAD\"\n };\n }\n\n if (!isRecord(options)) {\n throw new Error(\"Git worktree create options must be an object.\");\n }\n\n const base = getOwnProperty(options, \"base\");\n const path = getOwnProperty(options, \"path\");\n\n return {\n base:\n base === undefined ? \"HEAD\" : readNonEmptyString(base, \"Git worktree create options base\"),\n path:\n path === undefined ? undefined : readNonEmptyString(path, \"Git worktree create options path\")\n };\n}\n\nfunction createSavepointRef(): string {\n return `${SAVEPOINT_REF_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction createDefaultWorktreePath(repoRoot: string, branch: string): string {\n return resolve(repoRoot, \".poe-code\", \"worktrees\", createSafeBranchDirectoryName(branch));\n}\n\nfunction createSafeBranchDirectoryName(branch: string): string {\n return encodeURIComponent(branch);\n}\n\nasync function getRepoRoot(cwd: string): Promise<string> {\n return runGitAndTrim(cwd, [\"rev-parse\", \"--show-toplevel\"]);\n}\n\nasync function gitRefExists(cwd: string, ref: string): Promise<boolean> {\n try {\n await runGit(cwd, [\"show-ref\", \"--verify\", \"--quiet\", ref]);\n return true;\n } catch (error) {\n void error;\n return false;\n }\n}\n\nasync function listWorktrees(cwd: string): Promise<GitWorktree[]> {\n const { stdout } = await runGit(cwd, [\"worktree\", \"list\", \"--porcelain\"]);\n return parseWorktreeList(stdout);\n}\n\nfunction parseWorktreeList(output: string): GitWorktree[] {\n const worktrees: GitWorktree[] = [];\n let current: Partial<GitWorktree> = {};\n\n const finishCurrent = () => {\n if (current.path !== undefined && current.branch !== undefined) {\n worktrees.push({\n path: current.path,\n branch: current.branch\n });\n }\n\n current = {};\n };\n\n for (const line of output.split(\"\\n\")) {\n if (line.length === 0) {\n finishCurrent();\n continue;\n }\n\n if (line.startsWith(\"worktree \")) {\n current.path = line.slice(\"worktree \".length);\n continue;\n }\n\n if (line.startsWith(\"branch \")) {\n current.branch = parseBranchRef(line.slice(\"branch \".length));\n }\n }\n\n finishCurrent();\n return worktrees;\n}\n\nfunction parseBranchRef(ref: string): string {\n const branchPrefix = \"refs/heads/\";\n return ref.startsWith(branchPrefix) ? ref.slice(branchPrefix.length) : ref;\n}\n\nasync function resolveWorktreePath(repoRoot: string, path: string, label: string): Promise<string> {\n const resolvedRoot = resolve(repoRoot);\n const resolvedPath = isAbsolute(path) ? resolve(path) : resolve(resolvedRoot, path);\n const canonicalRoot = await realpath(resolvedRoot);\n const canonicalPath = await resolveCanonicalPath({ realpath, readlink }, resolvedPath);\n\n // A worktree lives somewhere under the repository, never at the repository root\n // itself, so root-itself is rejected alongside anything outside it. Both answers\n // come from the filesystem rather than the spelling: on a case-insensitive\n // filesystem a differently cased path still names the repository root.\n const [inside, isRootItself] = await Promise.all([\n containsPath(stat, canonicalRoot, canonicalPath),\n isSamePath(stat, canonicalPath, canonicalRoot)\n ]);\n\n if (!inside || isRootItself) {\n throw new Error(`${label} must be inside the git repository.`);\n }\n\n return canonicalPath;\n}\n\nfunction isBranchAlreadyExistsError(error: unknown, branch: string): boolean {\n return (\n error instanceof Error &&\n error.message.includes(branch) &&\n error.message.includes(\"already exists\")\n );\n}\n\nasync function runGitAndTrim(cwd: string, args: string[]): Promise<string> {\n const { stdout } = await runGit(cwd, args);\n return stdout.trim();\n}\n\nasync function runGit(cwd: string, args: string[]): Promise<ExecFileResult> {\n return new Promise((resolve, reject) => {\n execFile(\n \"git\",\n args,\n {\n cwd,\n encoding: \"utf8\",\n maxBuffer: GIT_EXEC_MAX_BUFFER\n },\n (error, stdout, stderr) => {\n if (error) {\n reject(\n new Error(\n `${formatGitCommand(args)} failed: ${pickGitFailureMessage(stdout, stderr, error)}`\n )\n );\n return;\n }\n\n resolve({\n stdout,\n stderr\n });\n }\n );\n });\n}\n\nasync function cleanupFailedCheckpoint(cwd: string, stashRef: string): Promise<void> {\n await deleteSavepointRef(cwd, stashRef);\n const restored = await tryRunGit(cwd, [\"stash\", \"apply\", \"--index\", \"stash@{0}\"]);\n if (restored) {\n await tryRunGit(cwd, [\"stash\", \"drop\", \"stash@{0}\"]);\n }\n}\n\nasync function deleteSavepointRef(cwd: string, stashRef: string): Promise<void> {\n await tryRunGit(cwd, [\"update-ref\", \"--delete\", stashRef]);\n}\n\nasync function tryRunGit(cwd: string, args: string[]): Promise<boolean> {\n try {\n await runGit(cwd, args);\n return true;\n } catch (error) {\n void error;\n return false;\n }\n}\n\nfunction formatGitCommand(args: string[]): string {\n return [\"git\", ...args].join(\" \");\n}\n\nfunction pickGitFailureMessage(stdout: string, stderr: string, error: Error): string {\n const stderrText = stderr.trim();\n\n if (stderrText.length > 0) {\n return stderrText;\n }\n\n const stdoutText = stdout.trim();\n\n if (stdoutText.length > 0) {\n return stdoutText;\n }\n\n return error.message;\n}\n\nfunction readNonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string.`);\n }\n\n return value;\n}\n\nfunction readNonEmptyStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(`${label} must be a non-empty array of strings.`);\n }\n\n const entries = value.map((entry, index) => readNonEmptyString(entry, `${label}[${index}]`));\n return [...entries];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getOwnProperty<Name extends PropertyKey>(value: object, name: Name): unknown {\n return hasOwnProperty(value, name) ? value[name] : undefined;\n}\n\nfunction hasOwnProperty<Name extends PropertyKey>(\n value: object,\n name: Name\n): value is Record<Name, unknown> {\n return Object.prototype.hasOwnProperty.call(value, name);\n}\n", "import { 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 { makeGitModule } from \"./modules/git.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,SAAS,kBAAkB,UAAkB,aAAmD;AAC9F,SAAO;AAAA,IACL;AAAA,IACA,MAAM,YAAY,aAAa,MAAM;AAAA,IACrC,SAAS,YAAY,aAAa,SAAS;AAAA,EAC7C;AACF;AAEA,SAAS,4BAA4B,aAA4C;AAC/E,QAAM,SAAS,YAAY,aAAa,QAAQ;AAChD,MAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG;AAC1E;AAAA,EACF;AAEA,aAAW,CAAC,MAAM,UAAU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AAO,IAAI,MAAM,qBAAqB;AACxC;;;AC3FO,IAAMC,eAA6D;AACnE,IAAMC,WAGI;AAKV,IAAMC,uBAGT;",
6
+ "names": ["parse", "rawModules", "stat", "stat", "resolve", "resolve", "parseModule", "restore", "deepCopyFromSandbox"]
7
7
  }
@@ -4,6 +4,7 @@ import { type OtelSpan } from "../observability/otel.js";
4
4
  import type { Budget } from "./budget.js";
5
5
  import type { EvaluationResult } from "./exceptions.js";
6
6
  import type { InterpreterError, InterpreterSnapshot, LoopIterationSnapshot } from "./interpreter.js";
7
+ import { CompileScope } from "./regex/compile-guard.js";
7
8
  import type { Scope } from "./scope.js";
8
9
  import { type SandboxValue } from "./values.js";
9
10
  export type InterpreterYieldPoint = {
@@ -18,6 +19,7 @@ type ResumeBreakpoint = Omit<InterpreterYieldPoint, "snapshot">;
18
19
  export type AsyncInterpreterError = InterpreterError;
19
20
  export type AsyncEvaluationResult = EvaluationResult<AsyncInterpreterError>;
20
21
  export type AsyncEvaluationContext = {
22
+ compilation?: CompileScope;
21
23
  activeLoopIterations: Map<number, LoopIterationSnapshot>;
22
24
  budget: Budget;
23
25
  callStack: string[];
@@ -3,10 +3,11 @@ import { getBoundOtelSpan } from "../observability/otel.js";
3
3
  import { bindPattern } from "./patterns.js";
4
4
  import { getThenable, resolveSandboxValue } from "./promise.js";
5
5
  import { runAsyncPrefix, suspendJob } from "./jobs.js";
6
+ import { CompileScope } from "./regex/compile-guard.js";
6
7
  import { awaitSandboxValue } from "./cancel.js";
7
8
  import { hoistVarDeclarations } from "./var-hoist.js";
8
9
  import { boundIdentifiers, containsParameterExpression, getFunctionLength, hoistedVarDeclarations } from "../parse/bindings.js";
9
- import { createSandboxArguments, createSandboxClosure, createSandboxGenerator, createSandboxPromise, allocateProducedSandboxValue, isSandboxPromise } from "./values.js";
10
+ import { createSandboxArguments, createSandboxClosure, createSandboxGenerator, createSandboxPromise, allocateProducedSandboxValue, reconcileCompiledValues, isSandboxPromise } from "./values.js";
10
11
  export function emitResumeBreakpoint(context, breakpoint) {
11
12
  context.onYield?.({
12
13
  ...breakpoint,
@@ -48,6 +49,7 @@ export function createInterpretedClosure(node, context, evaluateNode) {
48
49
  const thisValue = {};
49
50
  const result = await executeClosure(node, args, thisValue, {
50
51
  ...context,
52
+ compilation: callContext?.compilation ?? context.compilation,
51
53
  callStack: [...(callContext?.stack ?? context.callStack)]
52
54
  }, evaluateNode);
53
55
  return isConstructResult(result) ? result : thisValue;
@@ -67,6 +69,7 @@ export function createInterpretedClosure(node, context, evaluateNode) {
67
69
  call: (args, callContext) => {
68
70
  const invocationContext = {
69
71
  ...context,
72
+ compilation: callContext?.compilation ?? context.compilation,
70
73
  callStack: [...(callContext?.stack ?? context.callStack)]
71
74
  };
72
75
  if (!node.async)
@@ -109,6 +112,7 @@ function createGeneratorClosure(node, context, evaluateNode) {
109
112
  call: async (args, callContext) => {
110
113
  const closureContext = {
111
114
  ...context,
115
+ compilation: callContext?.compilation ?? context.compilation,
112
116
  callStack: [...(callContext?.stack ?? context.callStack)]
113
117
  };
114
118
  const scope = await createClosureScope(node, args, callContext?.thisValue, closureContext, evaluateNode);
@@ -167,22 +171,34 @@ export async function evaluateAwaitExpression(node, context, evaluateNode) {
167
171
  }
168
172
  }
169
173
  async function executeClosure(node, args, thisValue, context, evaluateNode) {
170
- const scope = await createClosureScope(node, args, thisValue, context, evaluateNode);
171
- const result = await evaluateNode(node.body, {
172
- ...context,
173
- functionBody: node.body.type === "BlockStatement" ? node.body : undefined,
174
- scope
175
- });
176
- if (result.kind === "error") {
177
- throw result.error;
178
- }
179
- if (result.kind === "throw") {
180
- throw result.value;
174
+ const parent = context.compilation;
175
+ const operation = context.budget.acquireCompileOwner(false, parent?.owner);
176
+ const compilation = new CompileScope(operation.owner, parent);
177
+ context = { ...context, compilation };
178
+ try {
179
+ const scope = await createClosureScope(node, args, thisValue, context, evaluateNode);
180
+ const result = await evaluateNode(node.body, {
181
+ ...context,
182
+ functionBody: node.body.type === "BlockStatement" ? node.body : undefined,
183
+ scope
184
+ });
185
+ const value = "hasValue" in result && result.hasValue ? result.value : undefined;
186
+ reconcileCompiledValues(context.budget, [...scope.retainedValues(), ...context.budget.retainedValues(), value], compilation, parent, [value]);
187
+ if (result.kind === "error") {
188
+ throw result.error;
189
+ }
190
+ if (result.kind === "throw") {
191
+ throw result.value;
192
+ }
193
+ if (isBlockBody(node.body)) {
194
+ return result.hasValue ? result.value : undefined;
195
+ }
196
+ return result.value;
181
197
  }
182
- if (isBlockBody(node.body)) {
183
- return result.hasValue ? result.value : undefined;
198
+ finally {
199
+ compilation.dispose();
200
+ operation.release();
184
201
  }
185
- return result.value;
186
202
  }
187
203
  async function createClosureScope(node, args, thisValue, context, evaluateNode) {
188
204
  const scope = context.scope.child({}, { functionBoundary: true });
@@ -8,6 +8,12 @@ export type BudgetOptions = {
8
8
  dataSize?: number;
9
9
  };
10
10
  export declare const REGEX_STEP_LIMIT = 2000;
11
+ export declare const REGEX_COMPILE_LIMITS: Readonly<{
12
+ sourceLength: 4096;
13
+ flagsLength: 8;
14
+ depth: 64;
15
+ allocations: 16384;
16
+ }>;
11
17
  export declare class SandboxError extends Error {
12
18
  readonly code: "aborted" | "budgetExceeded" | "reentry";
13
19
  readonly budget?: BudgetName;
@@ -28,6 +34,13 @@ type BudgetLimits = {
28
34
  arrayLength?: number;
29
35
  dataSize?: number;
30
36
  };
37
+ export type CompileOwner = {
38
+ readonly budget: Budget;
39
+ readonly generation: number;
40
+ };
41
+ export type CompileTicket = {
42
+ readonly owner: CompileOwner;
43
+ };
31
44
  export declare class Budget {
32
45
  readonly deadline?: number;
33
46
  readonly limits: Readonly<BudgetLimits>;
@@ -42,6 +55,12 @@ export declare class Budget {
42
55
  private retainedDataSize;
43
56
  private readonly retainedData;
44
57
  private readonly retainedValueSources;
58
+ private compileGeneration;
59
+ private activeCompileOwner?;
60
+ private compileUses;
61
+ private provisionalScopes;
62
+ private readonly compileTickets;
63
+ private readonly completedCompileTickets;
45
64
  constructor(options?: BudgetOptions);
46
65
  visitNode(): void;
47
66
  allocateString(value: string): string;
@@ -51,6 +70,16 @@ export declare class Budget {
51
70
  setRetainedDataUsage(owner: object, usage: number): void;
52
71
  setRetainedValues(owner: object, values: (() => Iterable<unknown>) | undefined): void;
53
72
  retainedValues(): Iterable<unknown>;
73
+ acquireCompileOwner(reset?: boolean, owner?: CompileOwner): {
74
+ owner: CompileOwner;
75
+ release: () => void;
76
+ };
77
+ createCompileTicket(owner: CompileOwner): CompileTicket;
78
+ compileTicketUsage(ticket: CompileTicket): number;
79
+ resizeCompileTicket(ticket: CompileTicket, usage: number): void;
80
+ discardCompileTicket(ticket: CompileTicket): void;
81
+ reconcileCompileData(usage: number, included: ReadonlySet<CompileTicket>, transferred?: ReadonlySet<CompileTicket>, retainedOwner?: object, complete?: boolean): ReadonlySet<CompileTicket>;
82
+ chargeDataUsage(usage: number): void;
54
83
  provisionDataUsage(usage: number): () => void;
55
84
  enterCall(): () => void;
56
85
  enterAwait(): () => void;