Skip to content

Commit 8e76adb

Browse files
authored
feat(codemode): support promise chaining with .then/.catch/.finally (anomalyco#36304)
1 parent 0bb24a4 commit 8e76adb

16 files changed

Lines changed: 486 additions & 214 deletions

‎packages/codemode/codemode.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,13 @@ path lookup, namespace browsing, deterministic ranking, and pagination.
6464
### Tool execution
6565

6666
Every sandbox promise starts eagerly on a run-once fiber owned by the whole CodeMode execution, including tool calls,
67-
async functions, `Promise.all`, `Promise.allSettled`, `Promise.race`, `Promise.resolve`, and `Promise.reject`. Nested
68-
functions therefore cannot end the lifetime of work they started. Independent aggregate batches overlap, and rejection
69-
is observed at the eventual `await`. `Promise.race` uses native non-cancelling settlement semantics: its first result
70-
wins while losers continue running. At normal completion CodeMode interrupts everything still running - race losers,
67+
async functions, chained `.then`/`.catch`/`.finally` reactions, `Promise.all`, `Promise.allSettled`, `Promise.race`,
68+
`Promise.resolve`, and `Promise.reject`. Nested functions therefore cannot end the lifetime of work they started.
69+
Independent aggregate batches overlap, and rejection is observed at the eventual `await` or chained rejection handler.
70+
`Promise.race` uses native non-cancelling settlement semantics: its first result wins while losers continue running.
71+
Reaction ordering matches what V8 makes observable - handlers and await continuations are deferred and run in attach
72+
order, and a combinator settles one reaction turn after its deciding member - without promising exact microtask-count
73+
parity beyond that. At normal completion CodeMode interrupts everything still running - race losers,
7174
fail-fast `Promise.all` stragglers, and fire-and-forget calls alike: the program has returned, so no future await can
7275
exist, and work whose completion matters must be awaited by the program. Waiting for any class of leftover instead
7376
would let it hold the execution open, or deadlock it when queued work needs tool-call permits the leftovers occupy.

‎packages/codemode/interpreter-support.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ ultimate source of truth.
9292
- [x] Optional property access and optional calls.
9393
- [x] Function/tool calls and spread arguments.
9494
- [x] Sequence expressions (the comma operator).
95-
- [x] `await` for sandbox promises; awaiting a plain value is a no-op.
95+
- [x] `await` for sandbox promises; a plain value passes through unchanged, though every `await` still defers its
96+
continuation one reaction turn.
9697
- [x] `new` for Error types, Date, RegExp, Map, Set, URL, and URLSearchParams.
9798
- [x] Arithmetic operators: `+`, `-`, `*`, `/`, `%`, and `**`.
9899
- [x] Equality and ordering: `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, and `>=`.
@@ -116,12 +117,21 @@ ultimate source of truth.
116117
- [x] `Promise.race` settles from the first result without cancelling losers at settlement time.
117118
- [x] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`; separately constructed
118119
combinator batches overlap as in normal JavaScript.
120+
- [x] Promise chaining with `.then`, `.catch`, and `.finally`: handlers run deferred in attach order, returned
121+
promises are adopted, handler throws reject the derived promise, `.finally` preserves the original settlement
122+
unless its cleanup fails, and direct self-resolution rejects with a `TypeError`.
123+
- [x] Every `await` (including of plain values and already-settled promises) defers its continuation one reaction
124+
turn, so concurrent async functions interleave at await points as in JavaScript.
125+
- [x] Combinators settle one reaction turn after their deciding member (V8-observable ordering): reactions already
126+
attached to members run first, and an aggregate cannot beat a plain value settling in the same turn into a
127+
`Promise.race`. Exact microtask-count parity beyond this observable ordering is not a documented guarantee.
119128
- [x] All still-pending work (race losers, fail-fast `Promise.all` stragglers, and un-awaited calls alike) is
120129
interrupted when the program returns; rejections that settled un-awaited become `Success.warnings`
121-
diagnostics.
130+
diagnostics. A combinator abandoned inside its final settlement turn counts as pending and is interrupted
131+
without a warning.
122132
- [x] `try`/`catch` can handle awaited tool and promise failures.
123133
- [ ] `Promise.any`.
124-
- [ ] Promise chaining with `.then`, `.catch`, and `.finally`.
134+
- [ ] Thenable assimilation (objects with a `then` method are plain data, not promises).
125135
- [ ] Custom promise construction with `new Promise(...)`.
126136
- [ ] Async iterables, host streams, and stream consumption.
127137

‎packages/codemode/src/codemode.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
import { Effect, Schema } from "effect"
22
import { executeWithLimits } from "./interpreter/runtime.js"
3-
import {
4-
type HostTools,
5-
type Services,
6-
type ToolDescription,
7-
ToolRuntime,
8-
} from "./tool-runtime.js"
3+
import { type HostTools, type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js"
94
import type { Definition } from "./tool.js"
105

116
/** A tool call admitted during an execution. */
@@ -130,11 +125,7 @@ export type Runtime<R = never> = {
130125
readonly execute: (code: string) => Effect.Effect<Result, never, R>
131126
}
132127

133-
const validateLimit = <Value extends number | undefined>(
134-
name: keyof ExecutionLimits,
135-
value: Value,
136-
minimum: number,
137-
): Value => {
128+
const validateLimit = (name: keyof ExecutionLimits, value: number | undefined, minimum: number): number | undefined => {
138129
if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) {
139130
throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`)
140131
}

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { SafeObject } from "../tool-runtime.js"
2-
import type { SandboxURL } from "../values.js"
2+
import type { SandboxPromise, SandboxURL } from "../values.js"
33

44
export type SourcePosition = {
55
line: number
@@ -67,6 +67,15 @@ export class PromiseMethodReference {
6767
constructor(readonly name: PromiseMethodName) {}
6868
}
6969

70+
export type PromiseInstanceMethodName = "then" | "catch" | "finally"
71+
72+
export class PromiseInstanceMethodReference {
73+
constructor(
74+
readonly promise: SandboxPromise,
75+
readonly name: PromiseInstanceMethodName,
76+
) {}
77+
}
78+
7079
export type GlobalNamespaceName =
7180
| "Object"
7281
| "Math"
@@ -122,11 +131,11 @@ export type DiagnosticKind =
122131
export const OptionalShortCircuit: unique symbol = Symbol("codemode.optional-short-circuit")
123132

124133
export const supportedSyntaxMessage =
125-
"Supported orchestration syntax: tools.* calls (they return promises - resolve them with await), data literals, destructuring, optional chaining, template literals, conditionals, switch, loops (incl. for...of and for...in over object/array/tools keys), arrow functions, spread, try/catch, array methods (map/filter/find/findIndex/some/every/reduce/flatMap/forEach/sort/slice/concat/indexOf/lastIndexOf/at/flat/reverse/includes/join), string methods (incl. match/matchAll/replace/split with regular expressions), Date/RegExp/Map/Set/URL/URLSearchParams, URI encoding helpers, Object/Math/JSON helpers, captured console.log/warn/error/dir/table, and Promise.all/allSettled/race/resolve/reject over arrays mixing promises and plain values for parallel tool calls (promise chaining with .then/.catch is not supported - use await with try/catch)."
134+
"Supported orchestration syntax: tools.* calls (they return promises - resolve them with await), data literals, destructuring, optional chaining, template literals, conditionals, switch, loops (incl. for...of and for...in over object/array/tools keys), arrow functions, spread, try/catch, array methods (map/filter/find/findIndex/some/every/reduce/flatMap/forEach/sort/slice/concat/indexOf/lastIndexOf/at/flat/reverse/includes/join), string methods (incl. match/matchAll/replace/split with regular expressions), Date/RegExp/Map/Set/URL/URLSearchParams, URI encoding helpers, Object/Math/JSON helpers, captured console.log/warn/error/dir/table, Promise.all/allSettled/race/resolve/reject over arrays mixing promises and plain values for parallel tool calls, and promise chaining with .then/.catch/.finally."
126135

127136
export class InterpreterRuntimeError extends Error {
128137
readonly node?: AstNode
129-
errorName: string = "Error"
138+
errorName = "Error"
130139

131140
constructor(
132141
message: string,

0 commit comments

Comments
 (0)