From 546b9fb3c1225f3b7fce95238cc25fb2b2f8c391 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:46:16 -0500 Subject: [PATCH] refactor(codemode): consolidate duplicated interpreter helpers (#48009) --- packages/codemode/src/interpreter/methods.ts | 76 +++++++------------ packages/codemode/src/interpreter/model.ts | 13 +--- .../codemode/src/interpreter/references.ts | 53 +++++-------- packages/codemode/src/interpreter/runtime.ts | 21 +---- packages/codemode/src/stdlib/json.ts | 9 +-- packages/codemode/src/stdlib/number.ts | 5 +- packages/codemode/src/stdlib/string.ts | 3 +- packages/codemode/src/stdlib/url.ts | 7 +- packages/codemode/src/stdlib/value.ts | 7 +- packages/codemode/src/tool-runtime.ts | 30 +++----- 10 files changed, 73 insertions(+), 151 deletions(-) diff --git a/packages/codemode/src/interpreter/methods.ts b/packages/codemode/src/interpreter/methods.ts index 28847a1db92..801c5f3964d 100644 --- a/packages/codemode/src/interpreter/methods.ts +++ b/packages/codemode/src/interpreter/methods.ts @@ -15,7 +15,7 @@ import { UriFunction, } from "./model.js" import { containsOpaqueReference, isRuntimeReference, rejectCircularInsertion, typeofValue } from "./references.js" -import { isBlockedMember, type SafeObject } from "../tool-runtime.js" +import { compareText, isBlockedMember, type SafeObject } from "../tool-runtime.js" import { Values } from "../values.js" import { dateSetterArgumentCount, invokeDateMethod, invokeDateStatic } from "../stdlib/date.js" import { invokeMathMethod } from "../stdlib/math.js" @@ -122,35 +122,43 @@ export const invokeIntrinsic = ( throw new InterpreterRuntimeError(`Method '${ref.name}' is not available.`, node) } -const coerceNumericArgument = ( +/** + * ToPrimitive: tries an object's own `valueOf`/`toString` in hint order and returns the first + * primitive result. Runtime values behave like their JS counterparts (Date yields its time under a + * number hint; the rest yield their string form). An inherited `toString` yields the default + * string form, so plain objects become "[object Object]" and arrays join. + */ +export const toPrimitive = ( runner: CallbackRunner, value: unknown, + hint: "number" | "string", node: AstNode, -): Effect.Effect => { - if (value === null || typeof value !== "object" || Array.isArray(value) || Values.isValue(value)) { - return Effect.succeed(coerceToNumber(value)) +): Effect.Effect => { + if (value === null || typeof value !== "object") return Effect.succeed(value) + if (Values.isValue(value)) { + return Effect.succeed(value instanceof Values.Date && hint === "number" ? value.time : coerceToString(value)) } const object = value as Record + const order = hint === "number" ? ["valueOf", "toString"] : ["toString", "valueOf"] return Effect.gen(function* () { - if (Object.hasOwn(object, "valueOf") && typeofValue(object.valueOf) === "function") { - const result = yield* runner.invokeCallable(object.valueOf, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) { - return coerceToNumber(result) - } - } - if (!Object.hasOwn(object, "toString")) return coerceToNumber(value) - if (typeofValue(object.toString) === "function") { - const result = yield* runner.invokeCallable(object.toString, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) { - return coerceToNumber(result) - } + for (const method of order) { + if (method === "toString" && !Object.hasOwn(object, "toString")) return coerceToString(value) + if (!Object.hasOwn(object, method) || typeofValue(object[method]) !== "function") continue + const result = yield* runner.invokeCallable(object[method], [], node) + if (result === null || (typeof result !== "object" && typeof result !== "function")) return result } throw new InterpreterRuntimeError("Cannot convert object to primitive value.", node).as("TypeError") }) } +const coerceNumericArgument = ( + runner: CallbackRunner, + value: unknown, + node: AstNode, +): Effect.Effect => Effect.map(toPrimitive(runner, value, "number", node), coerceToNumber) + +// console is intercepted by the interpreter before reaching here. export const invokeGlobalMethod = (ref: GlobalMethodReference, args: Array, node: AstNode): unknown => { - if (ref.namespace === "console") throw new InterpreterRuntimeError(`console.${ref.name} is not available.`, node) if (ref.namespace === "Object") return invokeObjectMethod(ref.name, args, node) if (ref.namespace === "Math") return invokeMathMethod(ref.name, args, node) if (ref.namespace === "Array") return invokeArrayStatic(ref.name, args, node) @@ -159,9 +167,6 @@ export const invokeGlobalMethod = (ref: GlobalMethodReference, args: Array( value: unknown, node: AstNode, ): Effect.Effect => { - if (value === null || typeof value !== "object" || Array.isArray(value) || Values.isValue(value)) { - return Effect.succeed(coerceToString(value)) - } if (value instanceof Values.Promise) return Effect.succeed("[object Promise]") - if (isRuntimeReference(value)) { + if (!Values.isValue(value) && isRuntimeReference(value)) { throw new InterpreterRuntimeError("Object.groupBy callback must return a data value.", node, "InvalidDataValue") } - const object = value as Record - if (!Object.hasOwn(object, "toString")) return Effect.succeed(coerceToString(value)) - return Effect.gen(function* () { - if (typeofValue(object.toString) === "function") { - const result = yield* runner.invokeCallable(object.toString, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) { - return coerceToString(result) - } - } - if (Object.hasOwn(object, "valueOf") && typeofValue(object.valueOf) === "function") { - const result = yield* runner.invokeCallable(object.valueOf, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) { - return coerceToString(result) - } - } - throw new InterpreterRuntimeError("Cannot convert object to primitive value.", node).as("TypeError") - }) + return Effect.map(toPrimitive(runner, value, "string", node), coerceToString) } const invokeStringReplacer = ( @@ -1124,11 +1110,7 @@ const sortArray = ( ): Effect.Effect, unknown, R> => { if (comparator === undefined) { return Effect.sync(() => - [...target].sort((a, b) => { - const left = coerceToString(a) - const right = coerceToString(b) - return left < right ? -1 : left > right ? 1 : 0 - }), + [...target].sort((a, b) => compareText(coerceToString(a), coerceToString(b))), ) } const apply = applyCollectionCallback(runner, comparator, name, node) diff --git a/packages/codemode/src/interpreter/model.ts b/packages/codemode/src/interpreter/model.ts index 22cc5633bb1..3baec723772 100644 --- a/packages/codemode/src/interpreter/model.ts +++ b/packages/codemode/src/interpreter/model.ts @@ -1,4 +1,5 @@ import type { Effect } from "effect" +import type { DiagnosticKind } from "../codemode.js" import type { SafeObject } from "../tool-runtime.js" import type { Values } from "../values.js" @@ -158,18 +159,6 @@ export class ErrorConstructorReference { constructor(readonly name: string) {} } -export type DiagnosticKind = - | "ParseError" - | "UnsupportedSyntax" - | "UnknownTool" - | "InvalidToolInput" - | "InvalidToolOutput" - | "InvalidDataValue" - | "ToolCallLimitExceeded" - | "TimeoutExceeded" - | "ToolFailure" - | "ExecutionFailure" - export const OptionalShortCircuit: unique symbol = Symbol("codemode.optional-short-circuit") export const supportedSyntaxMessage = diff --git a/packages/codemode/src/interpreter/references.ts b/packages/codemode/src/interpreter/references.ts index 12b784c6361..e075b07a61c 100644 --- a/packages/codemode/src/interpreter/references.ts +++ b/packages/codemode/src/interpreter/references.ts @@ -52,9 +52,14 @@ function* childValues(value: object): Generator { } } -export const containsRuntimeReference = (value: unknown): boolean => { +// Depth-first search over a value tree. `match` stops the walk; `skip` prunes a subtree without matching it. +const find = ( + value: unknown, + match: (current: unknown) => boolean, + skip: (current: unknown) => boolean, + seen: Set, +): boolean => { const pending: Array> = [[value].values()] - const seen = new Set() while (pending.length > 0) { const next = pending.at(-1)!.next() if (next.done) { @@ -62,33 +67,22 @@ export const containsRuntimeReference = (value: unknown): boolean => { continue } const current = next.value - if (isRuntimeReference(current)) return true - if (current === null || typeof current !== "object" || seen.has(current)) continue + if (match(current)) return true + if (current === null || typeof current !== "object" || skip(current) || seen.has(current)) continue seen.add(current) pending.push(childValues(current)) } return false } +const never = () => false + +export const containsRuntimeReference = (value: unknown): boolean => + find(value, isRuntimeReference, never, new Set()) + // CodeMode values are data here, not opaque interpreter references. -export const containsOpaqueReference = (value: unknown): boolean => { - const pending: Array> = [[value].values()] - const seen = new Set() - while (pending.length > 0) { - const next = pending.at(-1)!.next() - if (next.done) { - pending.pop() - continue - } - const current = next.value - if (Values.isValue(current)) continue - if (isRuntimeReference(current)) return true - if (current === null || typeof current !== "object" || seen.has(current)) continue - seen.add(current) - pending.push(childValues(current)) - } - return false -} +export const containsOpaqueReference = (value: unknown): boolean => + find(value, (current) => !Values.isValue(current) && isRuntimeReference(current), Values.isValue, new Set()) // Reject cycles before mutation so later boundary walks remain safe. export const rejectCircularInsertion = ( @@ -98,19 +92,8 @@ export const rejectCircularInsertion = ( node: AstNode, seen = new Set(), ): void => { - const pending: Array> = [[value].values()] - while (pending.length > 0) { - const next = pending.at(-1)!.next() - if (next.done) { - pending.pop() - continue - } - const current = next.value - if (current === container) - throw new InterpreterRuntimeError(`${label} contains a circular value.`, node, "InvalidDataValue") - if (current === null || typeof current !== "object" || isRuntimeReference(current) || seen.has(current)) continue - seen.add(current) - pending.push(childValues(current)) + if (find(value, (current) => current === container, isRuntimeReference, seen)) { + throw new InterpreterRuntimeError(`${label} contains a circular value.`, node, "InvalidDataValue") } } diff --git a/packages/codemode/src/interpreter/runtime.ts b/packages/codemode/src/interpreter/runtime.ts index e572335bff5..a0c66ac9ff3 100644 --- a/packages/codemode/src/interpreter/runtime.ts +++ b/packages/codemode/src/interpreter/runtime.ts @@ -50,6 +50,7 @@ import { invokeGlobalMethod, invokeGroupBy, invokeIntrinsic, + toPrimitive, } from "./methods.js" import { preserveConsumerError, type SyncIteratorRunner } from "./iterator.js" import { @@ -1474,7 +1475,7 @@ export class Interpreter { if (args.length === 1) { const arg = args[0] if (arg instanceof Values.Date) return Effect.succeed(new Values.Date(arg.time)) - return Effect.map(this.toDatePrimitive(arg, node), (value) => + return Effect.map(toPrimitive(this.runner, arg, "number", node), (value) => typeof value === "string" ? new Values.Date(Date.parse(value)) : new Values.Date(new Date(coerceToNumber(value)).getTime()), @@ -1484,24 +1485,6 @@ export class Interpreter { return Effect.succeed(new Values.Date(new Date(...(parts as [number, number])).getTime())) } - private toDatePrimitive(value: unknown, node: AstNode): Effect.Effect { - if (value === null || (typeof value !== "object" && typeof value !== "function")) return Effect.succeed(value) - const object = value as Record - const self = this - return Effect.gen(function* () { - if (Object.hasOwn(object, "valueOf") && typeofValue(object.valueOf) === "function") { - const result = yield* self.runner.invokeCallable(object.valueOf, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) return result - } - if (!Object.hasOwn(object, "toString")) return coerceToString(value) - if (typeofValue(object.toString) === "function") { - const result = yield* self.runner.invokeCallable(object.toString, [], node) - if (result === null || (typeof result !== "object" && typeof result !== "function")) return result - } - throw new InterpreterRuntimeError("Cannot convert object to primitive value.", node).as("TypeError") - }) - } - private constructRegExp(args: Array, node: AstNode): Values.RegExp { const first = args[0] const pattern = diff --git a/packages/codemode/src/stdlib/json.ts b/packages/codemode/src/stdlib/json.ts index c763f80fa98..26907e591d2 100644 --- a/packages/codemode/src/stdlib/json.ts +++ b/packages/codemode/src/stdlib/json.ts @@ -132,11 +132,4 @@ const toJSONValue = (value: unknown): unknown => { } const isPlainObject = (value: unknown): value is SafeObject => - value !== null && - typeof value === "object" && - !(value instanceof Values.Date) && - !(value instanceof Values.RegExp) && - !(value instanceof Values.Map) && - !(value instanceof Values.Set) && - !(value instanceof Values.URL) && - !(value instanceof Values.URLSearchParams) + value !== null && typeof value === "object" && !Values.isValue(value) diff --git a/packages/codemode/src/stdlib/number.ts b/packages/codemode/src/stdlib/number.ts index 8055b046ea1..afdf76f6584 100644 --- a/packages/codemode/src/stdlib/number.ts +++ b/packages/codemode/src/stdlib/number.ts @@ -1,3 +1,6 @@ +import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js" +import { boundedData, coerceToString } from "./value.js" + export const numberMethods = new Set(["toFixed", "toPrecision", "toExponential", "toString", "valueOf"]) export const numberConstants = new Set([ @@ -74,5 +77,3 @@ export const invokeNumberStatic = (name: string, args: Array, node: Ast throw new InterpreterRuntimeError(`Number.${name} is not available.`, node) } } -import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js" -import { boundedData, coerceToString } from "./value.js" diff --git a/packages/codemode/src/stdlib/string.ts b/packages/codemode/src/stdlib/string.ts index 7070c645a4b..a3ec3e8f1a3 100644 --- a/packages/codemode/src/stdlib/string.ts +++ b/packages/codemode/src/stdlib/string.ts @@ -1,3 +1,5 @@ +import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js" + export const stringMethods = new Set([ "toLowerCase", "toUpperCase", @@ -46,4 +48,3 @@ export const invokeStringStatic = (name: string, args: Array, node: Ast throw new InterpreterRuntimeError(`String.${name} is not available.`, node) } } -import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js" diff --git a/packages/codemode/src/stdlib/url.ts b/packages/codemode/src/stdlib/url.ts index 457bcafb70c..7de4df8cad7 100644 --- a/packages/codemode/src/stdlib/url.ts +++ b/packages/codemode/src/stdlib/url.ts @@ -1,3 +1,7 @@ +import { type AstNode, InterpreterRuntimeError, UriFunction } from "../interpreter/model.js" +import { Values } from "../values.js" +import { boundedData, coerceToString } from "./value.js" + export const urlProperties = new Set([ "href", "origin", @@ -85,6 +89,3 @@ export const invokeURLMethod = (value: Values.URL, name: string, node: AstNode): if (name === "toString" || name === "toJSON") return value.url.href throw new InterpreterRuntimeError(`URL method '${name}' is not available.`, node) } -import { type AstNode, InterpreterRuntimeError, UriFunction } from "../interpreter/model.js" -import { Values } from "../values.js" -import { boundedData, coerceToString } from "./value.js" diff --git a/packages/codemode/src/stdlib/value.ts b/packages/codemode/src/stdlib/value.ts index dd36d5971e5..dddd9ccfcdd 100644 --- a/packages/codemode/src/stdlib/value.ts +++ b/packages/codemode/src/stdlib/value.ts @@ -1,3 +1,7 @@ +import { type AstNode, CoercionFunction, InterpreterRuntimeError } from "../interpreter/model.js" +import { copyIn, type SafeObject } from "../tool-runtime.js" +import { Values } from "../values.js" + export const errorConstructors = new Set([ "Error", "TypeError", @@ -101,6 +105,3 @@ export const invokeCoercion = (ref: CoercionFunction, args: Array, node if (ref.name === "parseFloat") return parseFloat(coerceToString(value)) return coerceToString(value) } -import { type AstNode, CoercionFunction, InterpreterRuntimeError } from "../interpreter/model.js" -import { copyIn, type SafeObject } from "../tool-runtime.js" -import { Values } from "../values.js" diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index da49e2f27de..8582586067f 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -1,4 +1,5 @@ import { Cause, Effect, Exit, Formatter, Schema } from "effect" +import type { DiagnosticKind } from "./codemode.js" import { toolError } from "./tool-error.js" import { decodeInput as decodeToolInput, @@ -14,7 +15,7 @@ import { isTool, type Tool } from "./tool.js" import type { Tools } from "./tools.js" import { Values } from "./values.js" -const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0) +export const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0) export type Services = ServicesOf @@ -97,12 +98,10 @@ const MAX_VALUE_DEPTH = 32 export class ToolRuntimeError extends Error { constructor( - readonly kind: - | "UnknownTool" - | "InvalidToolInput" - | "InvalidToolOutput" - | "InvalidDataValue" - | "ToolCallLimitExceeded", + readonly kind: Extract< + DiagnosticKind, + "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded" + >, message: string, readonly suggestions: ReadonlyArray = [], ) { @@ -151,16 +150,7 @@ const copyBounded = ( } if (preserveCodeModeValues) { - if ( - value instanceof Values.Date || - value instanceof Values.RegExp || - value instanceof Values.Map || - value instanceof Values.Set || - value instanceof Values.URL || - value instanceof Values.URLSearchParams - ) { - return value - } + if (Values.isValue(value)) return value if (value instanceof Date) return new Values.Date(value.getTime()) if (value instanceof RegExp) return new Values.RegExp(value.source, value.flags) if (value instanceof Map) { @@ -187,11 +177,9 @@ const copyBounded = ( } if (value instanceof Values.URL) return value.url.href if (value instanceof URL) return value.href + // Remaining runtime values and their host counterparts serialize as empty objects, like JSON.stringify. if ( - value instanceof Values.RegExp || - value instanceof Values.Map || - value instanceof Values.Set || - value instanceof Values.URLSearchParams || + Values.isValue(value) || value instanceof RegExp || value instanceof Map || value instanceof Set ||