Skip to content

Commit 08e28fb

Browse files
authored
refactor(codemode): name the data boundary and prepare tools once (anomalyco#48021)
1 parent 74b0fa9 commit 08e28fb

18 files changed

Lines changed: 263 additions & 307 deletions

File tree

‎packages/codemode/src/codemode.ts‎

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Effect, Schema } from "effect"
2-
import { executeWithLimits } from "./interpreter/execute.js"
2+
import { executeProgram } from "./interpreter/execute.js"
33
import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js"
44
import type { Tools } from "./tools.js"
55

@@ -30,26 +30,23 @@ export type ResolvedExecutionLimits = {
3030
readonly maxOutputBytes: number | undefined
3131
}
3232

33-
/** Options for one CodeMode execution. */
34-
export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = {
35-
/** Source for one program in the supported JavaScript subset. */
36-
code: string
33+
/** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
34+
export type Options<Provided extends Record<string, unknown> = {}> = ToolRuntime.ToolCallHooks<Services<Provided>> & {
3735
/** Explicit tools exposed to the program as `tools`. */
3836
tools?: Provided & Tools<Services<Provided>>
39-
/** Per-execution overrides for the default resource limits. */
37+
/** Resource limits enforced on each execution. */
4038
limits?: ExecutionLimits
41-
/** Observes decoded tool input immediately before tool execution. */
42-
onToolCallStart?: (call: ToolRuntime.ToolCallStarted) => Effect.Effect<void, never, Services<Provided>>
43-
/** Observes each admitted tool call as it succeeds, fails, or is interrupted. */
44-
onToolCallEnd?: (call: ToolRuntime.ToolCallEnded) => Effect.Effect<void, never, Services<Provided>>
39+
}
40+
41+
/** Options for one CodeMode execution. */
42+
export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = Options<Provided> & {
43+
/** Source for one program in the supported JavaScript subset. */
44+
code: string
4545
}
4646

4747
/** A JSON value that can cross the confined interpreter boundary. */
4848
export type DataValue = Schema.Json
4949

50-
/** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
51-
export type Options<Provided extends Record<string, unknown> = {}> = Omit<ExecuteOptions<Provided>, "code">
52-
5350
/** Schema for a host tool input containing CodeMode source. */
5451
export const Input = Schema.Struct({ code: Schema.String })
5552
export type Input = typeof Input.Type
@@ -128,21 +125,16 @@ const resolveExecutionLimits = (limits?: ExecutionLimits): ResolvedExecutionLimi
128125
/** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
129126
export const execute = <const Provided extends Record<string, unknown>>(
130127
options: ExecuteOptions<Provided>,
131-
): Effect.Effect<Result, never, Services<Provided>> => {
132-
const tools = (options.tools ?? {}) as Tools<Services<Provided>>
133-
return executeWithLimits(options, resolveExecutionLimits(options.limits), ToolRuntime.searchIndex(tools))
134-
}
128+
): Effect.Effect<Result, never, Services<Provided>> => make(options).execute(options.code)
135129

136130
/** Creates an Effect-native runtime over explicit, schema-described tools. */
137131
export const make = <const Provided extends Record<string, unknown> = {}>(
138-
options: Options<Provided> = {} as Options<Provided>,
132+
options: Options<Provided> = {},
139133
): Runtime<Services<Provided>> => {
140-
const tools = (options.tools ?? {}) as Tools<Services<Provided>>
134+
const prepared = ToolRuntime.prepare((options.tools ?? {}) as Tools<Services<Provided>>)
141135
const limits = resolveExecutionLimits(options.limits)
142-
const prepared = ToolRuntime.prepare(tools)
143-
144136
return {
145137
catalog: () => prepared.catalog,
146-
execute: (code) => executeWithLimits<Provided>({ ...options, code }, limits, prepared.searchIndex),
138+
execute: (code) => executeProgram(code, prepared, limits, options),
147139
}
148140
}

‎packages/codemode/src/data.ts‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
export * as Data from "./data.js"
2+
3+
import type { DiagnosticKind } from "./codemode.js"
4+
import { Values } from "./values.js"
5+
6+
/** A null-prototype object owned by the program. */
7+
export type SafeObject = Record<string, unknown>
8+
9+
const MAX_VALUE_DEPTH = 32
10+
11+
export class ToolRuntimeError extends Error {
12+
constructor(
13+
readonly kind: Extract<
14+
DiagnosticKind,
15+
"UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded"
16+
>,
17+
message: string,
18+
readonly suggestions: ReadonlyArray<string> = [],
19+
) {
20+
super(message)
21+
this.name = "ToolRuntimeError"
22+
}
23+
}
24+
25+
const blockedMemberNames = new Set(["__proto__", "constructor", "prototype"])
26+
27+
export const isBlockedMember = (name: string): boolean => blockedMemberNames.has(name)
28+
29+
/**
30+
* Brings a host-produced runtime value into the program: runtime values pass through, their host
31+
* counterparts (Date, RegExp, Map, Set, URL, URLSearchParams) are wrapped, and objects become
32+
* null-prototype copies. Arrays keep extra enumerable properties such as `index` and `groups`.
33+
*/
34+
export const toProgram = (value: unknown, label: string): unknown => copy(value, label, "program", 0, new Set())
35+
36+
/**
37+
* Brings host data into the program: Date and URL become strings, other host collections become
38+
* empty objects, and objects become null-prototype copies. Used for tool results and parsed JSON.
39+
*/
40+
export const fromData = (value: unknown, label: string): unknown => copy(value, label, "data", 0, new Set())
41+
42+
/**
43+
* Takes a program value out as plain JSON: runtime values serialize like `JSON.stringify` would,
44+
* non-finite numbers become null, and array holes become null. `undefined` object properties are
45+
* dropped ("json") or become null ("result", for program results where the consumer must never see
46+
* undefined); a bare `undefined` follows the same rule.
47+
*/
48+
export const toData = (value: unknown, label: string, undefinedAs: "json" | "result" = "json"): unknown =>
49+
copy(value, label, undefinedAs, 0, new Set())
50+
51+
// "program" and "data" build program-owned null-prototype objects; "json" and "result" build
52+
// ordinary objects for the host.
53+
type Mode = "program" | "data" | "json" | "result"
54+
55+
const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Set<object>): unknown => {
56+
if (depth > MAX_VALUE_DEPTH) {
57+
throw new ToolRuntimeError("InvalidDataValue", `${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`)
58+
}
59+
if (value === undefined) return mode === "result" ? null : undefined
60+
if (typeof value === "number") return (mode === "json" || mode === "result") && !Number.isFinite(value) ? null : value
61+
if (value === null || typeof value === "string" || typeof value === "boolean") return value
62+
if (typeof value !== "object") {
63+
throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`)
64+
}
65+
if (value instanceof Values.Promise) {
66+
throw new ToolRuntimeError(
67+
"InvalidDataValue",
68+
`${label} contains an un-awaited Promise; await tool calls (e.g. \`const result = await tools.ns.tool(...)\`) before using their results.`,
69+
)
70+
}
71+
72+
if (mode === "program") {
73+
if (Values.isValue(value)) return value
74+
if (value instanceof Date) return new Values.Date(value.getTime())
75+
if (value instanceof RegExp) return new Values.RegExp(value.source, value.flags)
76+
if (value instanceof Map) {
77+
const wrapped = new Values.Map()
78+
for (const [key, item] of value.entries()) {
79+
wrapped.map.set(copy(key, label, mode, depth + 1, seen), copy(item, label, mode, depth + 1, seen))
80+
}
81+
return wrapped
82+
}
83+
if (value instanceof Set) {
84+
const wrapped = new Values.Set()
85+
for (const item of value.values()) wrapped.set.add(copy(item, label, mode, depth + 1, seen))
86+
return wrapped
87+
}
88+
if (value instanceof URL) return new Values.URL(new URL(value.href))
89+
if (value instanceof URLSearchParams) return new Values.URLSearchParams(new URLSearchParams(value))
90+
}
91+
92+
const plain = mode === "program" || mode === "data"
93+
if (value instanceof Values.Date) return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null
94+
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
95+
if (value instanceof Values.URL) return value.url.href
96+
if (value instanceof URL) return value.href
97+
// Remaining runtime values and their host counterparts serialize as empty objects, like JSON.stringify.
98+
if (
99+
Values.isValue(value) ||
100+
value instanceof RegExp ||
101+
value instanceof Map ||
102+
value instanceof Set ||
103+
value instanceof URLSearchParams
104+
) {
105+
return plain ? (Object.create(null) as SafeObject) : {}
106+
}
107+
108+
if (seen.has(value)) {
109+
throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`)
110+
}
111+
seen.add(value)
112+
113+
if (Array.isArray(value)) {
114+
// Host output densifies holes to null like JSON; program copies keep them.
115+
const copied = plain
116+
? value.map((item) => copy(item, label, mode, depth + 1, seen))
117+
: Array.from(value, (item) => copy(item, label, mode, depth + 1, seen) ?? null)
118+
if (mode === "program") {
119+
for (const [key, item] of Object.entries(value)) {
120+
if (Object.hasOwn(copied, key)) continue
121+
if (isBlockedMember(key)) {
122+
throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`)
123+
}
124+
Reflect.set(copied, key, copy(item, label, mode, depth + 1, seen))
125+
}
126+
}
127+
seen.delete(value)
128+
return copied
129+
}
130+
131+
const prototype = Object.getPrototypeOf(value)
132+
if (prototype !== Object.prototype && prototype !== null) {
133+
throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`)
134+
}
135+
136+
const copied: SafeObject = plain ? (Object.create(null) as SafeObject) : {}
137+
for (const [key, item] of Object.entries(value)) {
138+
if (isBlockedMember(key)) {
139+
throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`)
140+
}
141+
const next = copy(item, label, mode, depth + 1, seen)
142+
if (next === undefined && mode === "json") continue
143+
copied[key] = next
144+
}
145+
seen.delete(value)
146+
return copied
147+
}

‎packages/codemode/src/interpreter/errors.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Effect } from "effect"
22
import type { Diagnostic } from "../codemode.js"
33
import { ToolError } from "../tool-error.js"
4-
import { copyOut, ToolRuntimeError, type SafeObject } from "../tool-runtime.js"
4+
import { type SafeObject, toData, ToolRuntimeError } from "../data.js"
55
import { type AstNode, formatLocation, InterpreterRuntimeError, ProgramThrow, sourceLocation } from "./model.js"
66
import { containsRuntimeReference } from "./references.js"
77
import { type SyncIteratorRunner } from "./iterator.js"
@@ -45,7 +45,7 @@ export const normalizeError = (error: unknown): Diagnostic => {
4545
message = (value as { message: string }).message
4646
} else {
4747
try {
48-
message = JSON.stringify(copyOut(value, "json")) ?? String(value)
48+
message = JSON.stringify(toData(value, "Thrown value")) ?? String(value)
4949
} catch {
5050
message = String(value)
5151
}

‎packages/codemode/src/interpreter/execute.ts‎

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,21 @@ import { Cause, Effect, Scope } from "effect"
33
// #transpile: conditional import — full typescript on node/bun, an identity
44
// pass-through on workerd (the compiler is ~11 MiB and can't init there).
55
import { transpile } from "#transpile"
6-
import type { DataValue, Diagnostic, ExecuteOptions, ResolvedExecutionLimits, Result } from "../codemode.js"
7-
import { copyIn, copyOut, ToolRuntime, type Services } from "../tool-runtime.js"
8-
import type { Tools } from "../tools.js"
6+
import type { DataValue, Diagnostic, ResolvedExecutionLimits, Result } from "../codemode.js"
7+
import { toData } from "../data.js"
8+
import { ToolRuntime } from "../tool-runtime.js"
99
import { normalizeError } from "./errors.js"
1010
import { InterpreterRuntimeError, isRecord, type ProgramNode } from "./model.js"
1111
import { PromiseRuntime } from "./promises.js"
1212
import { Interpreter } from "./runtime.js"
1313

14-
export const executeWithLimits = <const Provided extends Record<string, unknown>>(
15-
options: ExecuteOptions<Provided>,
14+
export const executeProgram = <R>(
15+
code: string,
16+
prepared: ToolRuntime.Prepared<R>,
1617
limits: ResolvedExecutionLimits,
17-
searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"],
18-
): Effect.Effect<Result, never, Services<Provided>> => {
19-
if (options.code.trim().length === 0) {
18+
hooks: ToolRuntime.ToolCallHooks<R>,
19+
): Effect.Effect<Result, never, R> => {
20+
if (code.trim().length === 0) {
2021
return Effect.succeed({
2122
ok: false,
2223
error: { kind: "ParseError", message: "Code cannot be empty." },
@@ -26,35 +27,21 @@ export const executeWithLimits = <const Provided extends Record<string, unknown>
2627

2728
// Allocate execution state inside suspension so reused Effects never share it.
2829
return Effect.suspend(() => {
29-
const tools = ToolRuntime.make(
30-
(options.tools ?? {}) as Tools<Services<Provided>>,
31-
limits.maxToolCalls,
32-
searchIndex,
33-
{
34-
onToolCallStart: options.onToolCallStart,
35-
onToolCallEnd: options.onToolCallEnd,
36-
},
37-
)
30+
const tools = ToolRuntime.make(prepared, limits.maxToolCalls, hooks)
3831
const logs: Array<string> = []
3932
const logged = () => (logs.length > 0 ? { logs: [...logs] } : {})
4033
// Set only after copy-out so timeouts cannot report invalid values as completed.
41-
let returned: { value: DataValue; promises: PromiseRuntime<Services<Provided>> } | undefined
34+
let returned: { value: DataValue; promises: PromiseRuntime<R> } | undefined
4235

4336
const base = Effect.acquireUseRelease(
4437
Scope.make("parallel"),
4538
(scope) =>
4639
Effect.gen(function* () {
47-
const program = parseProgram(options.code)
48-
const promises = new PromiseRuntime<Services<Provided>>(scope)
49-
const interpreter = new Interpreter<Services<Provided>>(
50-
tools.execute,
51-
tools.search,
52-
tools.keys,
53-
promises,
54-
logs,
55-
)
40+
const program = parseProgram(code)
41+
const promises = new PromiseRuntime<R>(scope)
42+
const interpreter = new Interpreter<R>(tools.execute, tools.search, tools.keys, promises, logs)
5643
const value = yield* interpreter.run(program)
57-
const result = copyOut(copyIn(value, "Execution result"), "nullify") as DataValue
44+
const result = toData(value, "Execution result", "result") as DataValue
5845
returned = { value: result, promises }
5946
const warnings = yield* promises.interrupt()
6047
return {

‎packages/codemode/src/interpreter/methods.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import {
1515
UriFunction,
1616
} from "./model.js"
1717
import { containsOpaqueReference, isRuntimeReference, rejectCircularInsertion, typeofValue } from "./references.js"
18-
import { compareText, isBlockedMember, type SafeObject } from "../tool-runtime.js"
18+
import { isBlockedMember, type SafeObject, toProgram } from "../data.js"
19+
import { compareText } from "../tool-runtime.js"
1920
import { Values } from "../values.js"
2021
import { dateSetterArgumentCount, invokeDateMethod, invokeDateStatic } from "../stdlib/date.js"
2122
import { invokeMathMethod } from "../stdlib/math.js"
@@ -24,7 +25,7 @@ import { invokeObjectMethod } from "../stdlib/object.js"
2425
import { invokeRegExpMethod, invokeRegExpStatic, matchToValue, toHostRegex } from "../stdlib/regexp.js"
2526
import { invokeStringStatic } from "../stdlib/string.js"
2627
import { invokeURLMethod, invokeURLStatic, uriArgument } from "../stdlib/url.js"
27-
import { boundedData, coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js"
28+
import { coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js"
2829
import { preserveConsumerError, type SyncIteratorRunner } from "./iterator.js"
2930

3031
export type CallbackRunner<R> = {
@@ -292,7 +293,7 @@ const invokeStringMethod = (value: string, name: string, args: Array<unknown>, n
292293
const matched = value.match(pattern)
293294
if (matched === null) return null
294295
// Preserve the own `index` and `groups` properties on non-global matches.
295-
if (pattern.global) return boundedData(matched, "String.match result")
296+
if (pattern.global) return toProgram(matched, "String.match result")
296297
return matchToValue(matched)
297298
}
298299
case "matchAll": {
@@ -347,7 +348,7 @@ const invokeStringMethod = (value: string, name: string, args: Array<unknown>, n
347348
default:
348349
throw new InterpreterRuntimeError(`String method '${name}' is not available.`, node)
349350
}
350-
return boundedData(result, `String.${name} result`)
351+
return toProgram(result, `String.${name} result`)
351352
}
352353

353354
export const arrayStatics = new Set(["isArray", "of", "from"])
@@ -540,19 +541,19 @@ const invokeStringReplacer = <R>(
540541
let end = 0
541542
for (const match of matches) {
542543
const replacement = yield* apply(match.args)
543-
// Error values are branded plain objects; boundedData would strip the brand before coercion.
544+
// Error values are branded plain objects; toProgram would strip the brand before coercion.
544545
output.push(
545546
value.slice(end, match.offset),
546547
replacement instanceof Values.Promise
547548
? "[object Promise]"
548549
: errorBrandName(replacement)
549550
? coerceToString(replacement)
550-
: coerceToString(boundedData(replacement, `String.${name} replacer result`)),
551+
: coerceToString(toProgram(replacement, `String.${name} replacer result`)),
551552
)
552553
end = match.offset + match.match.length
553554
}
554555
output.push(value.slice(end))
555-
return boundedData(output.join(""), `String.${name} result`)
556+
return toProgram(output.join(""), `String.${name} result`)
556557
})
557558
}
558559

@@ -876,7 +877,7 @@ const invokeArrayMethod = <R>(
876877
if (args.length > 1 || (args.length === 1 && typeof args[0] !== "string")) {
877878
throw new InterpreterRuntimeError("Array.join expects zero arguments or one string separator.", node)
878879
}
879-
const input = boundedData(target, "Array.join input") as Array<unknown>
880+
const input = toProgram(target, "Array.join input") as Array<unknown>
880881
return Effect.succeed(
881882
input.map((item) => coerceToString(item ?? "")).join(args.length === 0 ? "," : (args[0] as string)),
882883
)

‎packages/codemode/src/interpreter/model.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Effect } from "effect"
22
import type { DiagnosticKind } from "../codemode.js"
3-
import type { SafeObject } from "../tool-runtime.js"
3+
import type { SafeObject } from "../data.js"
44
import type { Values } from "../values.js"
55

66
export type SourcePosition = {

‎packages/codemode/src/interpreter/promises.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Cause, Deferred, Effect, Exit, Fiber, Scope } from "effect"
22
import type { Diagnostic } from "../codemode.js"
3-
import type { SafeObject } from "../tool-runtime.js"
3+
import type { SafeObject } from "../data.js"
44
import {
55
type AstNode,
66
CodeModeFunction,

0 commit comments

Comments
 (0)