@executor-js/codemode-core 1.5.20 → 1.5.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effect-errors.d.ts +43 -0
- package/dist/effect-errors.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/effect-errors.d.ts
CHANGED
|
@@ -24,5 +24,48 @@ export declare class CodeExecutionError extends CodeExecutionError_base<{
|
|
|
24
24
|
readonly cause?: unknown;
|
|
25
25
|
}> {
|
|
26
26
|
}
|
|
27
|
+
declare const CodeCompilationError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
28
|
+
readonly _tag: "CodeCompilationError";
|
|
29
|
+
} & Readonly<A>;
|
|
30
|
+
/**
|
|
31
|
+
* Raised when user code fails to compile before it ever runs: a genuine
|
|
32
|
+
* syntax/parse error (smart quotes from a copy-paste, an unbalanced
|
|
33
|
+
* brace, `const = 5`) caught while stripping TypeScript ahead of the
|
|
34
|
+
* JS-only sandbox. Unlike `CodeExecutionError` this is the user's
|
|
35
|
+
* mistake, not a sandbox defect, so runtimes surface its `message`
|
|
36
|
+
* through the descriptive `ExecuteResult.error` channel instead of
|
|
37
|
+
* collapsing it to an opaque internal-error string. The original parser
|
|
38
|
+
* message (e.g. "Unexpected token (1:54)") is carried verbatim so the
|
|
39
|
+
* model can see and fix it.
|
|
40
|
+
*/
|
|
41
|
+
export declare class CodeCompilationError extends CodeCompilationError_base<{
|
|
42
|
+
readonly runtime: string;
|
|
43
|
+
readonly message: string;
|
|
44
|
+
readonly cause?: unknown;
|
|
45
|
+
}> {
|
|
46
|
+
}
|
|
47
|
+
declare const SandboxRuntimeError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
48
|
+
readonly _tag: "SandboxRuntimeError";
|
|
49
|
+
} & Readonly<A>;
|
|
50
|
+
/**
|
|
51
|
+
* Raised when the sandbox cannot run the user's code to completion for a
|
|
52
|
+
* reason that is not a syntax error but is still safe and useful to
|
|
53
|
+
* report back: the returned value is not serializable across the sandbox
|
|
54
|
+
* boundary (a Symbol, a host object like `Cloudflare`), the code exceeded
|
|
55
|
+
* the isolate's CPU or memory limit, or the sandbox is momentarily at
|
|
56
|
+
* capacity. Like `CodeCompilationError`, and unlike `CodeExecutionError`,
|
|
57
|
+
* this describes the user's own code or a transient, retryable condition
|
|
58
|
+
* rather than an executor defect, so runtimes surface its verbatim
|
|
59
|
+
* `message` through the descriptive `ExecuteResult.error` channel instead
|
|
60
|
+
* of collapsing it to an opaque internal-error string. Genuinely
|
|
61
|
+
* unexpected sandbox defects stay on `CodeExecutionError` and remain
|
|
62
|
+
* opaque, preserving the host's failure-channel boundary.
|
|
63
|
+
*/
|
|
64
|
+
export declare class SandboxRuntimeError extends SandboxRuntimeError_base<{
|
|
65
|
+
readonly runtime: string;
|
|
66
|
+
readonly message: string;
|
|
67
|
+
readonly cause?: unknown;
|
|
68
|
+
}> {
|
|
69
|
+
}
|
|
27
70
|
export {};
|
|
28
71
|
//# sourceMappingURL=effect-errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect-errors.d.ts","sourceRoot":"","sources":["../src/effect-errors.ts"],"names":[],"mappings":";;;AAEA,qBAAa,qBAAsB,SAAQ,2BAA0C;IACnF,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG;;;;AAEL;;;;;;;GAOG;AACH,qBAAa,kBAAmB,SAAQ,wBAAuC;IAC7E,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG"}
|
|
1
|
+
{"version":3,"file":"effect-errors.d.ts","sourceRoot":"","sources":["../src/effect-errors.ts"],"names":[],"mappings":";;;AAEA,qBAAa,qBAAsB,SAAQ,2BAA0C;IACnF,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG;;;;AAEL;;;;;;;GAOG;AACH,qBAAa,kBAAmB,SAAQ,wBAAuC;IAC7E,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG;;;;AAEL;;;;;;;;;;GAUG;AACH,qBAAa,oBAAqB,SAAQ,0BAAyC;IACjF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG;;;;AAEL;;;;;;;;;;;;;GAaG;AACH,qBAAa,mBAAoB,SAAQ,yBAAwC;IAC/E,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;CAAG"}
|
package/dist/index.js
CHANGED
|
@@ -19,6 +19,10 @@ var KernelCoreEffectError = class extends Data.TaggedError("KernelCoreEffectErro
|
|
|
19
19
|
};
|
|
20
20
|
var CodeExecutionError = class extends Data.TaggedError("CodeExecutionError") {
|
|
21
21
|
};
|
|
22
|
+
var CodeCompilationError = class extends Data.TaggedError("CodeCompilationError") {
|
|
23
|
+
};
|
|
24
|
+
var SandboxRuntimeError = class extends Data.TaggedError("SandboxRuntimeError") {
|
|
25
|
+
};
|
|
22
26
|
|
|
23
27
|
// src/validation.ts
|
|
24
28
|
var getSchemaValidator = (schema) => {
|
|
@@ -234,8 +238,10 @@ var stripTypeScript = (code) => transform(code, {
|
|
|
234
238
|
keepUnusedImports: true
|
|
235
239
|
}).code;
|
|
236
240
|
export {
|
|
241
|
+
CodeCompilationError,
|
|
237
242
|
CodeExecutionError,
|
|
238
243
|
KernelCoreEffectError,
|
|
244
|
+
SandboxRuntimeError,
|
|
239
245
|
asToolPath,
|
|
240
246
|
recoverExecutionBody,
|
|
241
247
|
standardSchemaFromJsonSchema,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/validation.ts","../src/effect-errors.ts","../src/json-schema.ts","../src/code-recovery.ts","../src/strip-types.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type * as Cause from \"effect/Cause\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { CodeExecutionError } from \"./effect-errors\";\n\n/** Branded tool path */\nexport type ToolPath = string & { readonly __toolPath: unique symbol };\n\nexport const asToolPath = (value: string): ToolPath => value as ToolPath;\n\n/** Standard Schema alias */\nexport type StandardSchema<Input = unknown, Output = unknown> = StandardSchemaV1<Input, Output>;\n\n/** A tool that can be invoked */\nexport interface Tool {\n readonly path: ToolPath;\n readonly description?: string;\n readonly inputSchema: StandardSchema;\n readonly outputSchema?: StandardSchema;\n readonly execute: (input: unknown) => unknown | Promise<unknown>;\n}\n\n/** Invoke a tool by path from inside a sandbox */\nexport interface SandboxToolInvoker {\n invoke(input: { path: string; args: unknown }): Effect.Effect<unknown, unknown, never>;\n}\n\n/** User-visible output accumulated by sandbox helpers. */\nexport type ExecuteOutputItem =\n | {\n readonly type: \"file\";\n readonly file: unknown;\n }\n | {\n readonly type: \"content\";\n readonly content: unknown;\n };\n\n/** Result of executing code in a sandbox */\nexport type ExecuteResult = {\n result: unknown;\n output?: ExecuteOutputItem[];\n error?: string;\n logs?: string[];\n};\n\n/**\n * Executes code in a sandboxed runtime with tool access.\n *\n * Error channel is constrained to Effect's `YieldableError` (the base\n * shape `Data.TaggedError(...)` produces) so callers always get a\n * structurally tagged error, never untyped `unknown`. Defaults to\n * `CodeExecutionError`; runtimes can parameterize with their own\n * `Data.TaggedError` subclass — e.g. `CodeExecutor<WorkerLoaderError>`.\n */\nexport interface CodeExecutor<E extends Cause.YieldableError = CodeExecutionError> {\n execute(code: string, toolInvoker: SandboxToolInvoker): Effect.Effect<ExecuteResult, E>;\n}\n\n/** Accept-anything schema for tools with no input validation */\nexport const unknownInputSchema: StandardSchema = {\n \"~standard\": {\n version: 1,\n vendor: \"@executor-js/codemode-core\",\n validate: (value: unknown) => ({\n value,\n }),\n },\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport * as Effect from \"effect/Effect\";\n\nimport { KernelCoreEffectError } from \"./effect-errors\";\n\nconst getSchemaValidator = (\n schema: unknown,\n):\n | ((\n value: unknown,\n ) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>)\n | null => {\n if (!schema || (typeof schema !== \"object\" && typeof schema !== \"function\")) {\n return null;\n }\n\n const standard = (schema as { \"~standard\"?: unknown })[\"~standard\"];\n if (!standard || typeof standard !== \"object\") {\n return null;\n }\n\n const validate = (standard as { validate?: unknown }).validate;\n return typeof validate === \"function\"\n ? (validate as (\n value: unknown,\n ) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>)\n : null;\n};\n\nconst formatIssuePath = (\n path: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment> | undefined,\n): string => {\n if (!path || path.length === 0) {\n return \"$\";\n }\n\n return path\n .map((segment) =>\n typeof segment === \"object\" && segment !== null && \"key\" in segment\n ? String(segment.key)\n : String(segment),\n )\n .join(\".\");\n};\n\nconst formatIssues = (issues: ReadonlyArray<StandardSchemaV1.Issue>): string =>\n issues.map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`).join(\"; \");\n\n/** Validate a value against a Standard Schema */\nexport const validateInput = (input: {\n schema: unknown;\n value: unknown;\n path: string;\n}): Effect.Effect<unknown, Error> => {\n const validate = getSchemaValidator(input.schema);\n if (!validate) {\n return Effect.fail(\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Tool ${input.path} has no Standard Schema validator on inputSchema`,\n }),\n );\n }\n\n return Effect.tryPromise({\n try: () => Promise.resolve(validate(input.value)),\n catch: (cause) =>\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Validation error for ${input.path}`,\n cause,\n }),\n }).pipe(\n Effect.flatMap((result) => {\n if (\"issues\" in result && result.issues) {\n return Effect.fail(\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Input validation failed for ${input.path}: ${formatIssues(result.issues)}`,\n }),\n );\n }\n return Effect.succeed(result.value);\n }),\n );\n};\n","import * as Data from \"effect/Data\";\n\nexport class KernelCoreEffectError extends Data.TaggedError(\"KernelCoreEffectError\")<{\n readonly module: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Default failure type for any `CodeExecutor.execute` implementation —\n * surfaces sandbox-level defects (isolate crash, module load failure,\n * worker loader error) as a typed error so callers can handle them\n * structurally instead of untyped `unknown`. Runtimes that want a\n * narrower error shape can define their own `Data.TaggedError` subclass\n * and parameterize `CodeExecutor<MyError>`.\n */\nexport class CodeExecutionError extends Data.TaggedError(\"CodeExecutionError\")<{\n readonly runtime: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n","import type { ErrorObject } from \"ajv\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport addFormats from \"ajv-formats\";\n\nimport type { StandardSchema } from \"./types\";\nimport { unknownInputSchema } from \"./types\";\n\nconst ajv = new Ajv2020({\n allErrors: true,\n strict: false,\n validateSchema: false,\n allowUnionTypes: true,\n});\n\naddFormats(ajv);\n\nconst decodePointerSegment = (segment: string): PropertyKey => {\n const decoded = segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n return /^\\d+$/.test(decoded) ? Number(decoded) : decoded;\n};\n\nconst pointerToPath = (pointer: string | undefined): ReadonlyArray<PropertyKey> | undefined => {\n if (!pointer || pointer.length === 0 || pointer === \"/\") {\n return undefined;\n }\n\n return pointer\n .split(\"/\")\n .slice(1)\n .filter((segment) => segment.length > 0)\n .map(decodePointerSegment);\n};\n\nconst toIssueMessage = (error: ErrorObject): string => {\n const keyword = error.keyword.trim();\n // oxlint-disable-next-line executor/no-unknown-error-message -- typed AJV ErrorObject exposes optional validation message copy\n const message = (error.message ?? \"Invalid value\").trim();\n return keyword.length > 0 ? `${keyword}: ${message}` : message;\n};\n\nexport const standardSchemaFromJsonSchema = (\n schema: unknown,\n options?: {\n vendor?: string;\n fallback?: StandardSchema;\n },\n): StandardSchema => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: AJV compile throws for invalid schemas and this adapter preserves fallback behavior\n try {\n const validate = ajv.compile(schema as Record<string, unknown>);\n\n return {\n \"~standard\": {\n version: 1,\n vendor: options?.vendor ?? \"json-schema\",\n validate: (value: unknown) => {\n const valid = validate(value);\n if (valid) {\n return { value };\n }\n\n const issues = (validate.errors ?? []).map((error) => ({\n message: toIssueMessage(error),\n path: pointerToPath(error.instancePath),\n }));\n\n return {\n issues: issues.length > 0 ? issues : [{ message: \"Invalid value\" }],\n };\n },\n },\n };\n } catch {\n return options?.fallback ?? unknownInputSchema;\n }\n};\n","import { parse } from \"@babel/parser\";\n\nconst FENCED_CODE_BLOCK = /```(?:[^\\n`]*)?\\s*\\n([\\s\\S]*?)```/i;\nconst FUNCTION_DECLARATION = /^(?:async\\s+)?function(?:\\s+([a-zA-Z_$][a-zA-Z0-9_$]*))?\\s*\\(/;\nconst CALLABLE_ERROR = \"Code must evaluate to a function\";\n\nconst extractCandidateSource = (code: string): string => {\n const trimmed = code.trim();\n if (!trimmed) return \"\";\n\n const fenced = trimmed.match(FENCED_CODE_BLOCK)?.[1];\n return (fenced ?? trimmed).trim();\n};\n\nconst wrapCallableBody = (source: string): string =>\n [\n \"const __fn = (\",\n source,\n \");\",\n `if (typeof __fn !== \"function\") throw new Error(${JSON.stringify(CALLABLE_ERROR)});`,\n \"return await __fn();\",\n ].join(\"\\n\");\n\nconst wrapNamedFunctionBody = (source: string, name: string): string =>\n [source, `return await ${name}();`].join(\"\\n\");\n\nconst wrapAnonymousFunctionBody = (source: string): string => `return await (${source})();`;\n\nconst sliceNode = (\n source: string,\n node: {\n start?: number | null;\n end?: number | null;\n },\n): string => {\n const start = node.start ?? 0;\n const end = node.end ?? source.length;\n return source.slice(start, end);\n};\n\nconst unwrapExpression = (expression: { type: string; expression?: unknown }): unknown => {\n switch (expression.type) {\n case \"ParenthesizedExpression\":\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSTypeAssertion\":\n case \"TSNonNullExpression\":\n case \"TSInstantiationExpression\":\n return expression.expression\n ? unwrapExpression(expression.expression as { type: string })\n : expression;\n default:\n return expression;\n }\n};\n\nconst renderExportDefaultBody = (\n source: string,\n declaration: ExportDefaultDeclarationNode,\n): string => {\n if (declaration.type === \"FunctionDeclaration\") {\n const fnSource = sliceNode(source, declaration);\n const name = declaration.id?.name;\n return name ? wrapNamedFunctionBody(fnSource, name) : wrapAnonymousFunctionBody(fnSource);\n }\n\n const expression = unwrapExpression(declaration) as {\n type?: string;\n };\n const expressionSource = sliceNode(source, declaration);\n\n if (expression?.type === \"ArrowFunctionExpression\" || expression?.type === \"FunctionExpression\") {\n return wrapCallableBody(expressionSource);\n }\n\n return `return (${expressionSource});`;\n};\n\ntype ExportDefaultDeclarationNode = {\n type: string;\n start?: number | null;\n end?: number | null;\n id?: { name?: string | null } | null;\n expression?: unknown;\n};\n\nconst renderParsedBody = (source: string): string => {\n const program = parse(source, {\n sourceType: \"module\",\n allowAwaitOutsideFunction: true,\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: [\"typescript\"],\n }).program;\n\n if (program.body.length !== 1) return source;\n\n const [statement] = program.body;\n if (!statement) return source;\n\n switch (statement.type) {\n case \"ExpressionStatement\": {\n const expression = unwrapExpression(\n statement.expression as { type: string; expression?: unknown },\n ) as {\n type?: string;\n };\n return expression?.type === \"ArrowFunctionExpression\" ||\n expression?.type === \"FunctionExpression\"\n ? wrapCallableBody(source)\n : source;\n }\n case \"FunctionDeclaration\":\n return statement.id?.name ? wrapNamedFunctionBody(source, statement.id.name) : source;\n case \"ExportDefaultDeclaration\":\n return renderExportDefaultBody(source, statement.declaration);\n default:\n return source;\n }\n};\n\nconst renderHeuristicBody = (source: string): string => {\n const withoutDefaultExport = source.replace(/^export\\s+default\\s+/, \"\").trim();\n\n if (\n (withoutDefaultExport.startsWith(\"async\") || withoutDefaultExport.startsWith(\"(\")) &&\n withoutDefaultExport.includes(\"=>\")\n ) {\n return wrapCallableBody(withoutDefaultExport);\n }\n\n if (FUNCTION_DECLARATION.test(withoutDefaultExport)) {\n const name = withoutDefaultExport.match(FUNCTION_DECLARATION)?.[1];\n return name\n ? wrapNamedFunctionBody(withoutDefaultExport, name)\n : wrapAnonymousFunctionBody(withoutDefaultExport);\n }\n\n return withoutDefaultExport;\n};\n\nexport const recoverExecutionBody = (code: string): string => {\n const source = extractCandidateSource(code);\n if (!source) return \"\";\n\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: Babel parser throws for malformed candidate code, then recovery falls back to heuristics\n try {\n return renderParsedBody(source);\n } catch {\n return renderHeuristicBody(source);\n }\n};\n","import { transform } from \"sucrase\";\n\n/**\n * Strip TypeScript type syntax (`: T`, `as T`, `<T>`, type aliases,\n * interfaces, etc.) from user-submitted code so it can run in a\n * JavaScript-only sandbox (workerd's WorkerLoader, QuickJS, raw V8).\n * Deno-style runtimes that handle TypeScript natively should skip\n * this step — they get better source-map fidelity by parsing the\n * original input.\n *\n * The execute tool description tells callers to write TypeScript, and\n * `tools.describe.tool` hands them TypeScript shapes — without stripping,\n * a single `: number` annotation throws \"Unexpected token ':'\" inside\n * the sandbox, which used to surface as a 180s client-side timeout\n * before the engine `raceFirst` fix.\n *\n * Sucrase's TypeScript transform is purely syntactic — no semantic\n * checks, no decorator metadata — which keeps the cost low and matches\n * what `tsc --isolatedModules` / Node's experimental type-stripping do.\n *\n * On parse failure we rethrow the original error so the caller can map\n * it into the runtime's tagged error type. We deliberately do NOT fall\n * back to the raw input — passing TS syntax through to a JS-only\n * sandbox trades a clean error here for an opaque one downstream.\n */\nexport const stripTypeScript = (code: string): string =>\n transform(code, {\n transforms: [\"typescript\"],\n // No JSX in user code, no React-specific transforms. `disableESTransforms`\n // keeps sucrase from rewriting `import`/`export` etc — we want only\n // type-syntax removal.\n disableESTransforms: true,\n keepUnusedImports: true,\n }).code;\n"],"mappings":";AASO,IAAM,aAAa,CAAC,UAA4B;AAoDhD,IAAM,qBAAqC;AAAA,EAChD,aAAa;AAAA,IACX,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU,CAAC,WAAoB;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AACF;;;ACpEA,YAAY,YAAY;;;ACDxB,YAAY,UAAU;AAEf,IAAM,wBAAN,cAAyC,iBAAY,uBAAuB,EAIhF;AAAC;AAUG,IAAM,qBAAN,cAAsC,iBAAY,oBAAoB,EAI1E;AAAC;;;ADfJ,IAAM,qBAAqB,CACzB,WAKU;AACV,MAAI,CAAC,UAAW,OAAO,WAAW,YAAY,OAAO,WAAW,YAAa;AAC3E,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,OAAqC,WAAW;AAClE,MAAI,CAAC,YAAY,OAAO,aAAa,UAAU;AAC7C,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,SAAoC;AACtD,SAAO,OAAO,aAAa,aACtB,WAGD;AACN;AAEA,IAAM,kBAAkB,CACtB,SACW;AACX,MAAI,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D;AAEA,SAAO;AACT;AAEO,IAAM,uBAAuB,CAAC,SAAyB;AAC5D,QAAM,SAAS,uBAAuB,IAAI;AAC1C,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI;AACF,WAAO,iBAAiB,MAAM;AAAA,EAChC,QAAQ;AACN,WAAO,oBAAoB,MAAM;AAAA,EACnC;AACF;;;ACvJA,SAAS,iBAAiB;AAyBnB,IAAM,kBAAkB,CAAC,SAC9B,UAAU,MAAM;AAAA,EACd,YAAY,CAAC,YAAY;AAAA;AAAA;AAAA;AAAA,EAIzB,qBAAqB;AAAA,EACrB,mBAAmB;AACrB,CAAC,EAAE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/validation.ts","../src/effect-errors.ts","../src/json-schema.ts","../src/code-recovery.ts","../src/strip-types.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type * as Cause from \"effect/Cause\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { CodeExecutionError } from \"./effect-errors\";\n\n/** Branded tool path */\nexport type ToolPath = string & { readonly __toolPath: unique symbol };\n\nexport const asToolPath = (value: string): ToolPath => value as ToolPath;\n\n/** Standard Schema alias */\nexport type StandardSchema<Input = unknown, Output = unknown> = StandardSchemaV1<Input, Output>;\n\n/** A tool that can be invoked */\nexport interface Tool {\n readonly path: ToolPath;\n readonly description?: string;\n readonly inputSchema: StandardSchema;\n readonly outputSchema?: StandardSchema;\n readonly execute: (input: unknown) => unknown | Promise<unknown>;\n}\n\n/** Invoke a tool by path from inside a sandbox */\nexport interface SandboxToolInvoker {\n invoke(input: { path: string; args: unknown }): Effect.Effect<unknown, unknown, never>;\n}\n\n/** User-visible output accumulated by sandbox helpers. */\nexport type ExecuteOutputItem =\n | {\n readonly type: \"file\";\n readonly file: unknown;\n }\n | {\n readonly type: \"content\";\n readonly content: unknown;\n };\n\n/** Result of executing code in a sandbox */\nexport type ExecuteResult = {\n result: unknown;\n output?: ExecuteOutputItem[];\n error?: string;\n logs?: string[];\n};\n\n/**\n * Executes code in a sandboxed runtime with tool access.\n *\n * Error channel is constrained to Effect's `YieldableError` (the base\n * shape `Data.TaggedError(...)` produces) so callers always get a\n * structurally tagged error, never untyped `unknown`. Defaults to\n * `CodeExecutionError`; runtimes can parameterize with their own\n * `Data.TaggedError` subclass — e.g. `CodeExecutor<WorkerLoaderError>`.\n */\nexport interface CodeExecutor<E extends Cause.YieldableError = CodeExecutionError> {\n execute(code: string, toolInvoker: SandboxToolInvoker): Effect.Effect<ExecuteResult, E>;\n}\n\n/** Accept-anything schema for tools with no input validation */\nexport const unknownInputSchema: StandardSchema = {\n \"~standard\": {\n version: 1,\n vendor: \"@executor-js/codemode-core\",\n validate: (value: unknown) => ({\n value,\n }),\n },\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport * as Effect from \"effect/Effect\";\n\nimport { KernelCoreEffectError } from \"./effect-errors\";\n\nconst getSchemaValidator = (\n schema: unknown,\n):\n | ((\n value: unknown,\n ) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>)\n | null => {\n if (!schema || (typeof schema !== \"object\" && typeof schema !== \"function\")) {\n return null;\n }\n\n const standard = (schema as { \"~standard\"?: unknown })[\"~standard\"];\n if (!standard || typeof standard !== \"object\") {\n return null;\n }\n\n const validate = (standard as { validate?: unknown }).validate;\n return typeof validate === \"function\"\n ? (validate as (\n value: unknown,\n ) => StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>)\n : null;\n};\n\nconst formatIssuePath = (\n path: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment> | undefined,\n): string => {\n if (!path || path.length === 0) {\n return \"$\";\n }\n\n return path\n .map((segment) =>\n typeof segment === \"object\" && segment !== null && \"key\" in segment\n ? String(segment.key)\n : String(segment),\n )\n .join(\".\");\n};\n\nconst formatIssues = (issues: ReadonlyArray<StandardSchemaV1.Issue>): string =>\n issues.map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`).join(\"; \");\n\n/** Validate a value against a Standard Schema */\nexport const validateInput = (input: {\n schema: unknown;\n value: unknown;\n path: string;\n}): Effect.Effect<unknown, Error> => {\n const validate = getSchemaValidator(input.schema);\n if (!validate) {\n return Effect.fail(\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Tool ${input.path} has no Standard Schema validator on inputSchema`,\n }),\n );\n }\n\n return Effect.tryPromise({\n try: () => Promise.resolve(validate(input.value)),\n catch: (cause) =>\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Validation error for ${input.path}`,\n cause,\n }),\n }).pipe(\n Effect.flatMap((result) => {\n if (\"issues\" in result && result.issues) {\n return Effect.fail(\n new KernelCoreEffectError({\n module: \"validation\",\n message: `Input validation failed for ${input.path}: ${formatIssues(result.issues)}`,\n }),\n );\n }\n return Effect.succeed(result.value);\n }),\n );\n};\n","import * as Data from \"effect/Data\";\n\nexport class KernelCoreEffectError extends Data.TaggedError(\"KernelCoreEffectError\")<{\n readonly module: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Default failure type for any `CodeExecutor.execute` implementation —\n * surfaces sandbox-level defects (isolate crash, module load failure,\n * worker loader error) as a typed error so callers can handle them\n * structurally instead of untyped `unknown`. Runtimes that want a\n * narrower error shape can define their own `Data.TaggedError` subclass\n * and parameterize `CodeExecutor<MyError>`.\n */\nexport class CodeExecutionError extends Data.TaggedError(\"CodeExecutionError\")<{\n readonly runtime: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Raised when user code fails to compile before it ever runs: a genuine\n * syntax/parse error (smart quotes from a copy-paste, an unbalanced\n * brace, `const = 5`) caught while stripping TypeScript ahead of the\n * JS-only sandbox. Unlike `CodeExecutionError` this is the user's\n * mistake, not a sandbox defect, so runtimes surface its `message`\n * through the descriptive `ExecuteResult.error` channel instead of\n * collapsing it to an opaque internal-error string. The original parser\n * message (e.g. \"Unexpected token (1:54)\") is carried verbatim so the\n * model can see and fix it.\n */\nexport class CodeCompilationError extends Data.TaggedError(\"CodeCompilationError\")<{\n readonly runtime: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n/**\n * Raised when the sandbox cannot run the user's code to completion for a\n * reason that is not a syntax error but is still safe and useful to\n * report back: the returned value is not serializable across the sandbox\n * boundary (a Symbol, a host object like `Cloudflare`), the code exceeded\n * the isolate's CPU or memory limit, or the sandbox is momentarily at\n * capacity. Like `CodeCompilationError`, and unlike `CodeExecutionError`,\n * this describes the user's own code or a transient, retryable condition\n * rather than an executor defect, so runtimes surface its verbatim\n * `message` through the descriptive `ExecuteResult.error` channel instead\n * of collapsing it to an opaque internal-error string. Genuinely\n * unexpected sandbox defects stay on `CodeExecutionError` and remain\n * opaque, preserving the host's failure-channel boundary.\n */\nexport class SandboxRuntimeError extends Data.TaggedError(\"SandboxRuntimeError\")<{\n readonly runtime: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n","import type { ErrorObject } from \"ajv\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport addFormats from \"ajv-formats\";\n\nimport type { StandardSchema } from \"./types\";\nimport { unknownInputSchema } from \"./types\";\n\nconst ajv = new Ajv2020({\n allErrors: true,\n strict: false,\n validateSchema: false,\n allowUnionTypes: true,\n});\n\naddFormats(ajv);\n\nconst decodePointerSegment = (segment: string): PropertyKey => {\n const decoded = segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n return /^\\d+$/.test(decoded) ? Number(decoded) : decoded;\n};\n\nconst pointerToPath = (pointer: string | undefined): ReadonlyArray<PropertyKey> | undefined => {\n if (!pointer || pointer.length === 0 || pointer === \"/\") {\n return undefined;\n }\n\n return pointer\n .split(\"/\")\n .slice(1)\n .filter((segment) => segment.length > 0)\n .map(decodePointerSegment);\n};\n\nconst toIssueMessage = (error: ErrorObject): string => {\n const keyword = error.keyword.trim();\n // oxlint-disable-next-line executor/no-unknown-error-message -- typed AJV ErrorObject exposes optional validation message copy\n const message = (error.message ?? \"Invalid value\").trim();\n return keyword.length > 0 ? `${keyword}: ${message}` : message;\n};\n\nexport const standardSchemaFromJsonSchema = (\n schema: unknown,\n options?: {\n vendor?: string;\n fallback?: StandardSchema;\n },\n): StandardSchema => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: AJV compile throws for invalid schemas and this adapter preserves fallback behavior\n try {\n const validate = ajv.compile(schema as Record<string, unknown>);\n\n return {\n \"~standard\": {\n version: 1,\n vendor: options?.vendor ?? \"json-schema\",\n validate: (value: unknown) => {\n const valid = validate(value);\n if (valid) {\n return { value };\n }\n\n const issues = (validate.errors ?? []).map((error) => ({\n message: toIssueMessage(error),\n path: pointerToPath(error.instancePath),\n }));\n\n return {\n issues: issues.length > 0 ? issues : [{ message: \"Invalid value\" }],\n };\n },\n },\n };\n } catch {\n return options?.fallback ?? unknownInputSchema;\n }\n};\n","import { parse } from \"@babel/parser\";\n\nconst FENCED_CODE_BLOCK = /```(?:[^\\n`]*)?\\s*\\n([\\s\\S]*?)```/i;\nconst FUNCTION_DECLARATION = /^(?:async\\s+)?function(?:\\s+([a-zA-Z_$][a-zA-Z0-9_$]*))?\\s*\\(/;\nconst CALLABLE_ERROR = \"Code must evaluate to a function\";\n\nconst extractCandidateSource = (code: string): string => {\n const trimmed = code.trim();\n if (!trimmed) return \"\";\n\n const fenced = trimmed.match(FENCED_CODE_BLOCK)?.[1];\n return (fenced ?? trimmed).trim();\n};\n\nconst wrapCallableBody = (source: string): string =>\n [\n \"const __fn = (\",\n source,\n \");\",\n `if (typeof __fn !== \"function\") throw new Error(${JSON.stringify(CALLABLE_ERROR)});`,\n \"return await __fn();\",\n ].join(\"\\n\");\n\nconst wrapNamedFunctionBody = (source: string, name: string): string =>\n [source, `return await ${name}();`].join(\"\\n\");\n\nconst wrapAnonymousFunctionBody = (source: string): string => `return await (${source})();`;\n\nconst sliceNode = (\n source: string,\n node: {\n start?: number | null;\n end?: number | null;\n },\n): string => {\n const start = node.start ?? 0;\n const end = node.end ?? source.length;\n return source.slice(start, end);\n};\n\nconst unwrapExpression = (expression: { type: string; expression?: unknown }): unknown => {\n switch (expression.type) {\n case \"ParenthesizedExpression\":\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n case \"TSTypeAssertion\":\n case \"TSNonNullExpression\":\n case \"TSInstantiationExpression\":\n return expression.expression\n ? unwrapExpression(expression.expression as { type: string })\n : expression;\n default:\n return expression;\n }\n};\n\nconst renderExportDefaultBody = (\n source: string,\n declaration: ExportDefaultDeclarationNode,\n): string => {\n if (declaration.type === \"FunctionDeclaration\") {\n const fnSource = sliceNode(source, declaration);\n const name = declaration.id?.name;\n return name ? wrapNamedFunctionBody(fnSource, name) : wrapAnonymousFunctionBody(fnSource);\n }\n\n const expression = unwrapExpression(declaration) as {\n type?: string;\n };\n const expressionSource = sliceNode(source, declaration);\n\n if (expression?.type === \"ArrowFunctionExpression\" || expression?.type === \"FunctionExpression\") {\n return wrapCallableBody(expressionSource);\n }\n\n return `return (${expressionSource});`;\n};\n\ntype ExportDefaultDeclarationNode = {\n type: string;\n start?: number | null;\n end?: number | null;\n id?: { name?: string | null } | null;\n expression?: unknown;\n};\n\nconst renderParsedBody = (source: string): string => {\n const program = parse(source, {\n sourceType: \"module\",\n allowAwaitOutsideFunction: true,\n allowReturnOutsideFunction: true,\n allowImportExportEverywhere: true,\n plugins: [\"typescript\"],\n }).program;\n\n if (program.body.length !== 1) return source;\n\n const [statement] = program.body;\n if (!statement) return source;\n\n switch (statement.type) {\n case \"ExpressionStatement\": {\n const expression = unwrapExpression(\n statement.expression as { type: string; expression?: unknown },\n ) as {\n type?: string;\n };\n return expression?.type === \"ArrowFunctionExpression\" ||\n expression?.type === \"FunctionExpression\"\n ? wrapCallableBody(source)\n : source;\n }\n case \"FunctionDeclaration\":\n return statement.id?.name ? wrapNamedFunctionBody(source, statement.id.name) : source;\n case \"ExportDefaultDeclaration\":\n return renderExportDefaultBody(source, statement.declaration);\n default:\n return source;\n }\n};\n\nconst renderHeuristicBody = (source: string): string => {\n const withoutDefaultExport = source.replace(/^export\\s+default\\s+/, \"\").trim();\n\n if (\n (withoutDefaultExport.startsWith(\"async\") || withoutDefaultExport.startsWith(\"(\")) &&\n withoutDefaultExport.includes(\"=>\")\n ) {\n return wrapCallableBody(withoutDefaultExport);\n }\n\n if (FUNCTION_DECLARATION.test(withoutDefaultExport)) {\n const name = withoutDefaultExport.match(FUNCTION_DECLARATION)?.[1];\n return name\n ? wrapNamedFunctionBody(withoutDefaultExport, name)\n : wrapAnonymousFunctionBody(withoutDefaultExport);\n }\n\n return withoutDefaultExport;\n};\n\nexport const recoverExecutionBody = (code: string): string => {\n const source = extractCandidateSource(code);\n if (!source) return \"\";\n\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: Babel parser throws for malformed candidate code, then recovery falls back to heuristics\n try {\n return renderParsedBody(source);\n } catch {\n return renderHeuristicBody(source);\n }\n};\n","import { transform } from \"sucrase\";\n\n/**\n * Strip TypeScript type syntax (`: T`, `as T`, `<T>`, type aliases,\n * interfaces, etc.) from user-submitted code so it can run in a\n * JavaScript-only sandbox (workerd's WorkerLoader, QuickJS, raw V8).\n * Deno-style runtimes that handle TypeScript natively should skip\n * this step — they get better source-map fidelity by parsing the\n * original input.\n *\n * The execute tool description tells callers to write TypeScript, and\n * `tools.describe.tool` hands them TypeScript shapes — without stripping,\n * a single `: number` annotation throws \"Unexpected token ':'\" inside\n * the sandbox, which used to surface as a 180s client-side timeout\n * before the engine `raceFirst` fix.\n *\n * Sucrase's TypeScript transform is purely syntactic — no semantic\n * checks, no decorator metadata — which keeps the cost low and matches\n * what `tsc --isolatedModules` / Node's experimental type-stripping do.\n *\n * On parse failure we rethrow the original error so the caller can map\n * it into the runtime's tagged error type. We deliberately do NOT fall\n * back to the raw input — passing TS syntax through to a JS-only\n * sandbox trades a clean error here for an opaque one downstream.\n */\nexport const stripTypeScript = (code: string): string =>\n transform(code, {\n transforms: [\"typescript\"],\n // No JSX in user code, no React-specific transforms. `disableESTransforms`\n // keeps sucrase from rewriting `import`/`export` etc — we want only\n // type-syntax removal.\n disableESTransforms: true,\n keepUnusedImports: true,\n }).code;\n"],"mappings":";AASO,IAAM,aAAa,CAAC,UAA4B;AAoDhD,IAAM,qBAAqC;AAAA,EAChD,aAAa;AAAA,IACX,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU,CAAC,WAAoB;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AACF;;;ACpEA,YAAY,YAAY;;;ACDxB,YAAY,UAAU;AAEf,IAAM,wBAAN,cAAyC,iBAAY,uBAAuB,EAIhF;AAAC;AAUG,IAAM,qBAAN,cAAsC,iBAAY,oBAAoB,EAI1E;AAAC;AAaG,IAAM,uBAAN,cAAwC,iBAAY,sBAAsB,EAI9E;AAAC;AAgBG,IAAM,sBAAN,cAAuC,iBAAY,qBAAqB,EAI5E;AAAC;;;ADpDJ,IAAM,qBAAqB,CACzB,WAKU;AACV,MAAI,CAAC,UAAW,OAAO,WAAW,YAAY,OAAO,WAAW,YAAa;AAC3E,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,OAAqC,WAAW;AAClE,MAAI,CAAC,YAAY,OAAO,aAAa,UAAU;AAC7C,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,SAAoC;AACtD,SAAO,OAAO,aAAa,aACtB,WAGD;AACN;AAEA,IAAM,kBAAkB,CACtB,SACW;AACX,MAAI,CAAC,QAAQ,KAAK,WAAW,GAAG;AAC9B,WAAO;AAAA,EACT;AAEA,SAAO,KACJ;AAAA,IAAI,CAAC,YACJ,OAAO,YAAY,YAAY,YAAY,QAAQ,SAAS,UACxD,OAAO,QAAQ,GAAG,IAClB,OAAO,OAAO;AAAA,EACpB,EACC,KAAK,GAAG;AACb;AAEA,IAAM,eAAe,CAAC,WACpB,OAAO,IAAI,CAAC,UAAU,GAAG,gBAAgB,MAAM,IAAI,CAAC,KAAK,MAAM,OAAO,EAAE,EAAE,KAAK,IAAI;AAG9E,IAAM,gBAAgB,CAAC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