refactor(codemode): consolidate duplicated interpreter helpers (#48009)

This commit is contained in:
Aiden Cline
2026-09-08 14:46:16 -05:00
committed by GitHub
Unverified
parent 83288921f6
commit 546b9fb3c1
10 changed files with 73 additions and 151 deletions
+29 -47
View File
@@ -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 = <R>(
throw new InterpreterRuntimeError(`Method '${ref.name}' is not available.`, node)
}
const coerceNumericArgument = <R>(
/**
* 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 = <R>(
runner: CallbackRunner<R>,
value: unknown,
hint: "number" | "string",
node: AstNode,
): Effect.Effect<number, unknown, R> => {
if (value === null || typeof value !== "object" || Array.isArray(value) || Values.isValue(value)) {
return Effect.succeed(coerceToNumber(value))
): Effect.Effect<unknown, unknown, R> => {
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<string, unknown>
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 = <R>(
runner: CallbackRunner<R>,
value: unknown,
node: AstNode,
): Effect.Effect<number, unknown, R> => Effect.map(toPrimitive(runner, value, "number", node), coerceToNumber)
// console is intercepted by the interpreter before reaching here.
export const invokeGlobalMethod = (ref: GlobalMethodReference, args: Array<unknown>, 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<unkno
if (ref.namespace === "URL") return invokeURLStatic(ref.name, args, node)
if (ref.namespace === "Date") return invokeDateStatic(ref.name, args, node)
if (ref.namespace === "RegExp") return invokeRegExpStatic(ref.name, args, node)
if (ref.namespace === "Map" || ref.namespace === "Set" || ref.namespace === "URLSearchParams") {
throw new InterpreterRuntimeError(`${ref.namespace}.${ref.name} is not available.`, node)
}
throw new InterpreterRuntimeError(`${ref.namespace}.${ref.name} is not available.`, node)
}
@@ -479,30 +484,11 @@ const coerceGroupByPropertyKey = <R>(
value: unknown,
node: AstNode,
): Effect.Effect<string, unknown, R> => {
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<string, unknown>
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 = <R>(
@@ -1124,11 +1110,7 @@ const sortArray = <R>(
): Effect.Effect<Array<unknown>, 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)
+1 -12
View File
@@ -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 =
+18 -35
View File
@@ -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<object>,
): boolean => {
const pending: Array<Iterator<unknown>> = [[value].values()]
const seen = new Set<object>()
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<Iterator<unknown>> = [[value].values()]
const seen = new Set<object>()
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<object>(),
): void => {
const pending: Array<Iterator<unknown>> = [[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")
}
}
+2 -19
View File
@@ -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<R> {
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<R> {
return Effect.succeed(new Values.Date(new Date(...(parts as [number, number])).getTime()))
}
private toDatePrimitive(value: unknown, node: AstNode): Effect.Effect<unknown, unknown, R> {
if (value === null || (typeof value !== "object" && typeof value !== "function")) return Effect.succeed(value)
const object = value as Record<string, unknown>
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<unknown>, node: AstNode): Values.RegExp {
const first = args[0]
const pattern =
+1 -8
View File
@@ -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)
+3 -2
View File
@@ -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<unknown>, 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"
+2 -1
View File
@@ -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<unknown>, node: Ast
throw new InterpreterRuntimeError(`String.${name} is not available.`, node)
}
}
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
+4 -3
View File
@@ -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"
+4 -3
View File
@@ -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<unknown>, 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"
+9 -21
View File
@@ -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<T> = ServicesOf<T, []>
@@ -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<string> = [],
) {
@@ -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 ||