Compare commits

..
Author SHA1 Message Date
Aiden Cline 71d7a84685 feat(plugin): add experimental WebSocket session hooks 2026-09-10 00:41:18 -05:00
20 changed files with 321 additions and 653 deletions
+4 -15
View File
@@ -58,7 +58,7 @@ ultimate source of truth.
- [x] Predeclare `let` and `const` bindings in every lexical scope, including program/block bodies, switch bodies, and
loop headers, so reads before initialization and self- or cross-referential initializers observe the JavaScript
temporal dead zone.
- [x] Function declarations are hoisted across all cases of a `switch`, like any other statement list.
- [ ] Hoist function declarations accepted directly in switch cases.
- [x] Computed object destructuring keys such as `const { [field]: value } = record`.
- [x] Object destructuring from arrays, such as `const { length } = values`.
- [x] Array binding and assignment destructuring from strings, Maps, Sets, URLSearchParams, custom synchronous
@@ -364,17 +364,6 @@ ultimate source of truth.
`entries`, `toString`, and `size`.
- [x] URL values serialize to their href; URLSearchParams serialize to `{}`.
## Web platform helpers
- [x] `atob` and `btoa` with forgiving-base64 decoding and WebIDL string conversion; invalid input throws an Error
named `InvalidCharacterError`, since there is no `DOMException`.
- [x] `crypto.randomUUID()`.
- [x] `structuredClone` over the data model: objects, arrays with holes, Date, RegExp (`lastIndex` reset), Map, Set,
URL, URLSearchParams, and Errors (name, message, and cause only); shared references stay shared within one
clone; functions, promises, and tool references throw an Error named `DataCloneError`.
- [ ] `crypto.getRandomValues` and `crypto.subtle`, `TextEncoder`/`TextDecoder`, and `Blob`: these need a binary
value type, which the JSON-like data model does not have yet.
## Errors and diagnostics
- [x] `Error`, `TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, `EvalError`, and `URIError`, callable with
@@ -391,6 +380,6 @@ ultimate source of truth.
shift them. The diagnostic names the rejected node type and attaches a short orientation to the supported
subset; this matrix is the full reference.
- [x] Model-visible host failure messages and underlying causes, including output-validation errors.
- [x] Caught errors do not distinguish user throws, interpreter failures, and tool failures; a program sees one
Error-shaped value with `name` and `message` in `catch`, rejection handlers, and `Promise.allSettled` reasons.
This is deliberate: the program should handle a failure the same way regardless of where it originated.
- [ ] Distinguish user-thrown failures from interpreter defects and explicit tool refusals from internal tool
failures; preserve those categories in caught errors, promise rejection handlers, and `Promise.allSettled`
reasons.
+1 -1
View File
@@ -138,6 +138,6 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
// Own data property regardless of the target's prototype, so a "__proto__" key on a host object or
// array never reaches the Object.prototype setter.
export const define = (target: object, key: string, value: unknown): void => {
const define = (target: object, key: string, value: unknown): void => {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
@@ -11,7 +11,6 @@ import { regexpGlobal } from "../stdlib/regexp.js"
import { stringGlobal } from "../stdlib/string.js"
import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js"
import { coercion, errorConstructors } from "../stdlib/value.js"
import { atobGlobal, btoaGlobal, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js"
import { ToolReference } from "../tool-runtime.js"
import { errorGlobal } from "./errors.js"
import { HostFunction } from "./host.js"
@@ -72,9 +71,5 @@ export const globals = <R>(host: Host<R>): ReadonlyArray<readonly [string, unkno
["encodeURIComponent", uriGlobal("encodeURIComponent")],
["decodeURI", uriGlobal("decodeURI")],
["decodeURIComponent", uriGlobal("decodeURIComponent")],
["atob", atobGlobal],
["btoa", btoaGlobal],
["crypto", cryptoGlobal],
["structuredClone", structuredCloneGlobal],
...[...errorConstructors].map((name) => [name, errorGlobal(name, host.runner)] as const),
]
+16 -14
View File
@@ -171,8 +171,6 @@ const collectPatternNames = (pattern: Pattern, out: Array<string> = []): Array<s
}
// `var` names declared anywhere in a function body except inside nested functions, which own theirs.
// Memoized per body: a function's var names never change, and hoisting runs on every call.
const varNames = new WeakMap<ReadonlyArray<Statement | ModuleDeclaration>, ReadonlyArray<string>>()
const collectVarNames = (
node: Statement | ModuleDeclaration | null | undefined,
out: Array<string> = [],
@@ -448,14 +446,12 @@ class Frame<R> {
// Hoisted `var` bindings start undefined, or copy a same-named parameter. Function bodies hoist
// into their own scope above the parameters so closures in parameter defaults keep seeing outer names.
private hoistVars(statements: ReadonlyArray<Statement | ModuleDeclaration>, parameters?: Map<string, Binding>): void {
const names =
varNames.get(statements) ??
statements.reduce<Array<string>>((out, statement) => collectVarNames(statement, out), [])
varNames.set(statements, names)
const scope = this.scopes.current()
for (const name of names) {
if (scope.has(name)) continue
scope.set(name, { mutable: true, value: parameters?.get(name)?.value, initialized: true })
for (const statement of statements) {
for (const name of collectVarNames(statement)) {
if (scope.has(name)) continue
scope.set(name, { mutable: true, value: parameters?.get(name)?.value, initialized: true })
}
}
}
@@ -496,9 +492,7 @@ class Frame<R> {
self.scopes.push()
return yield* Effect.gen(function* () {
const cases = node.cases
const statements = cases.flatMap((branch) => branch.consequent)
self.predeclareLexical(statements)
self.hoistFunctions(statements)
self.predeclareLexical(cases.flatMap((branch) => branch.consequent))
let defaultIndex: number | undefined
let selected: number | undefined
for (const [index, branch] of cases.entries()) {
@@ -1655,8 +1649,16 @@ class Frame<R> {
})
if (fn.generator) return Effect.succeed(this.createGenerator(invocation, run, fn.async))
if (!fn.async) return run
return this.runtime.promises.createWithSelf((self) =>
Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, fn.body, self)),
// The initial yield assigns the promise before the body can self-resolve.
const box: { promise?: Values.Promise } = {}
return Effect.map(
this.createPromise(
Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, fn.body, box)),
),
(promise) => {
box.promise = promise
return promise
},
)
}
-80
View File
@@ -1,80 +0,0 @@
import { define, type SafeObject } from "../data.js"
import { HostNamespace, sync } from "../interpreter/host.js"
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
import { describeValue, isRuntimeReference } from "../interpreter/references.js"
import { Values } from "../values.js"
import { coerceToString, createErrorValue, errorBrandName } from "./value.js"
// WebIDL DOMString conversion: a missing argument is a TypeError, anything else stringifies.
const base64 = (name: "atob" | "btoa") =>
sync(name, (args, node) => {
if (args.length === 0) {
throw new InterpreterRuntimeError(`${name} requires 1 argument, but only 0 were provided.`, node).as("TypeError")
}
const input = coerceToString(args[0])
try {
return name === "atob" ? atob(input) : btoa(input)
} catch {
throw new InterpreterRuntimeError("The string contains invalid characters.", node).as("InvalidCharacterError")
}
})
export const atobGlobal = base64("atob")
export const btoaGlobal = base64("btoa")
export const cryptoGlobal = new HostNamespace("crypto", {
randomUUID: sync("crypto.randomUUID", () => crypto.randomUUID()),
})
// HTML structured clone over the data model: wrappers are copied, shared references stay shared within
// one clone, Errors keep only name, message, and cause, and RegExp lastIndex resets like the spec.
const cloneValue = (value: unknown, seen: Map<object, unknown>, node: AstNode): unknown => {
if (value === null || typeof value !== "object") return value
if (value instanceof Values.Promise || (isRuntimeReference(value) && !Values.isValue(value))) {
throw new InterpreterRuntimeError(`${describeValue(value)} could not be cloned.`, node).as("DataCloneError")
}
const existing = seen.get(value)
if (existing !== undefined) return existing
const remember = <T extends object>(copied: T): T => {
seen.set(value, copied)
return copied
}
if (value instanceof Values.Date) return remember(new Values.Date(value.time))
if (value instanceof Values.RegExp) return remember(new Values.RegExp(value.regex.source, value.regex.flags))
if (value instanceof Values.URL) return remember(new Values.URL(new URL(value.url.href)))
if (value instanceof Values.URLSearchParams) {
return remember(new Values.URLSearchParams(new URLSearchParams(value.params)))
}
if (value instanceof Values.Map) {
const copied = remember(new Values.Map())
for (const [key, item] of value.map) copied.map.set(cloneValue(key, seen, node), cloneValue(item, seen, node))
return copied
}
if (value instanceof Values.Set) {
const copied = remember(new Values.Set())
for (const item of value.set) copied.set.add(cloneValue(item, seen, node))
return copied
}
if (Array.isArray(value)) {
const copied = remember(new Array<unknown>(value.length))
for (const [key, item] of Object.entries(value)) define(copied, key, cloneValue(item, seen, node))
return copied
}
const brand = errorBrandName(value)
if (brand !== undefined) {
const error = value as { name?: unknown; message?: unknown; cause?: unknown }
const copied = remember(createErrorValue(brand, coerceToString(error.message)))
if (Object.hasOwn(value, "cause")) copied.cause = cloneValue(error.cause, seen, node)
return copied
}
const copied = remember(Object.create(null) as SafeObject)
for (const [key, item] of Object.entries(value)) define(copied, key, cloneValue(item, seen, node))
return copied
}
export const structuredCloneGlobal = sync("structuredClone", (args, node) => {
if (args.length === 0) {
throw new InterpreterRuntimeError("structuredClone requires a value to clone.", node).as("TypeError")
}
return cloneValue(args[0], new Map(), node)
})
-11
View File
@@ -1,11 +0,0 @@
# The 3-Clause BSD License
Copyright © web-platform-tests contributors
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-82
View File
@@ -1,82 +0,0 @@
[
["", []],
["abcd", [105, 183, 29]],
[" abcd", [105, 183, 29]],
["abcd ", [105, 183, 29]],
[" abcd===", null],
["abcd=== ", null],
["abcd ===", null],
["a", null],
["ab", [105]],
["abc", [105, 183]],
["abcde", null],
["𐀀", null],
["=", null],
["==", null],
["===", null],
["====", null],
["=====", null],
["a=", null],
["a==", null],
["a===", null],
["a====", null],
["a=====", null],
["ab=", null],
["ab==", [105]],
["ab===", null],
["ab====", null],
["ab=====", null],
["abc=", [105, 183]],
["abc==", null],
["abc===", null],
["abc====", null],
["abc=====", null],
["abcd=", null],
["abcd==", null],
["abcd===", null],
["abcd====", null],
["abcd=====", null],
["abcde=", null],
["abcde==", null],
["abcde===", null],
["abcde====", null],
["abcde=====", null],
["=a", null],
["=a=", null],
["a=b", null],
["a=b=", null],
["ab=c", null],
["ab=c=", null],
["abc=d", null],
["abc=d=", null],
["ab\u000Bcd", null],
["ab\u3000cd", null],
["ab\u3001cd", null],
["ab\tcd", [105, 183, 29]],
["ab\ncd", [105, 183, 29]],
["ab\fcd", [105, 183, 29]],
["ab\rcd", [105, 183, 29]],
["ab cd", [105, 183, 29]],
["ab\u00a0cd", null],
["ab\t\n\f\r cd", [105, 183, 29]],
[" \t\n\f\r ab\t\n\f\r cd\t\n\f\r ", [105, 183, 29]],
["ab\t\n\f\r =\t\n\f\r =\t\n\f\r ", [105]],
["A", null],
["/A", [252]],
["//A", [255, 240]],
["///A", [255, 255, 192]],
["////A", null],
["/", null],
["A/", [3]],
["AA/", [0, 15]],
["AAAA/", null],
["AAA/", [0, 0, 63]],
["\u0000nonsense", null],
["abcd\u0000nonsense", null],
["YQ", [97]],
["YR", [97]],
["~~", null],
["..", null],
["--", null],
["__", null]
]
@@ -1,245 +0,0 @@
/**
* Portions adapted from web-platform-tests at revision 863077959ca8c1a7ceecfbe2534b75d2527b9013:
* - html/webappapis/structured-clone/structured-clone-battery-of-tests.js
*
* Copyright © web-platform-tests contributors. Governed by the 3-Clause BSD license in LICENSE.wpt.
*
* The battery's `check(description, input, compare)` shape and its `compare_*` helpers are kept, run
* inside the interpreter. Ported: primitives, Array/Object of primitives, Date, RegExp, Error, sparse
* arrays, identical (shared) property values, and the index-property-plus-length object. Not portable:
* boxed primitives, BigInt, Blob/File/ImageData/ArrayBuffer/typed arrays (no binary values), circular
* references (rejected at insertion here), property descriptors and prototype properties (no
* defineProperty or prototypes), and the throwing-getter case (no getters). `assert_throws_dom` for
* `DataCloneError` becomes an `error.name` check.
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
return result.value
}
// The WPT harness, minus async: assertions push a failure description instead of throwing so one run
// reports every failing check.
const harness = `
const failures = []
const assert_equals = (a, b, m) => { if (!Object.is(a, b) && !(a !== a && b !== b)) failures.push((m ?? "") + ": " + String(a) + " !== " + String(b)) }
const assert_not_equals = (a, b, m) => { if (a === b) failures.push((m ?? "") + ": unexpectedly identical") }
const assert_true = (a, m) => { if (a !== true) failures.push((m ?? "") + ": not true") }
const assert_false = (a, m) => { if (a !== false) failures.push((m ?? "") + ": not false") }
let current = ""
function check(description, input, callback) {
current = description
const newInput = typeof input === "function" ? input() : input
const copy = structuredClone(newInput)
const before = failures.length
callback(copy, newInput)
for (let i = before; i < failures.length; i++) failures[i] = description + " — " + failures[i]
}
function compare_primitive(actual, input) { assert_equals(actual, input) }
function compare_Array(callback) {
return function (actual, input) {
assert_true(Array.isArray(actual), "instanceof Array")
assert_not_equals(actual, input)
assert_equals(actual.length, input.length, "length")
callback(actual, input)
}
}
function compare_Object(callback) {
return function (actual, input) {
assert_true(actual instanceof Object, "instanceof Object")
assert_false(Array.isArray(actual), "instanceof Array")
assert_not_equals(actual, input)
callback(actual, input)
}
}
function enumerate_props(compare_func) {
return function (actual, input) { for (const x in input) compare_func(actual[x], input[x]) }
}
`
describe("structuredClone WPT battery", () => {
test("primitives, and arrays and objects of primitives", async () => {
expect(
await value(`
${harness}
check('primitive undefined', undefined, compare_primitive)
check('primitive null', null, compare_primitive)
check('primitive true', true, compare_primitive)
check('primitive false', false, compare_primitive)
check('primitive string, empty string', '', compare_primitive)
check('primitive string, lone high surrogate', '\\uD800', compare_primitive)
check('primitive string, lone low surrogate', '\\uDC00', compare_primitive)
check('primitive string, NUL', '\\u0000', compare_primitive)
check('primitive string, astral character', '\\uDBFF\\uDFFD', compare_primitive)
check('primitive number, 0.2', 0.2, compare_primitive)
check('primitive number, 0', 0, compare_primitive)
check('primitive number, -0', -0, compare_primitive)
check('primitive number, NaN', NaN, compare_primitive)
check('primitive number, Infinity', Infinity, compare_primitive)
check('primitive number, -Infinity', -Infinity, compare_primitive)
check('primitive number, 9007199254740992', 9007199254740992, compare_primitive)
check('primitive number, -9007199254740992', -9007199254740992, compare_primitive)
check('primitive number, 9007199254740994', 9007199254740994, compare_primitive)
check('primitive number, -9007199254740994', -9007199254740994, compare_primitive)
check('Array primitives', [undefined, null, true, false, '', '\\uD800', '\\uDC00', '\\u0000', '\\uDBFF\\uDFFD',
0.2, 0, -0, NaN, Infinity, -Infinity, 9007199254740992, -9007199254740992, 9007199254740994, -9007199254740994],
compare_Array(enumerate_props(compare_primitive)))
check('Object primitives', { 'undefined': undefined, 'null': null, 'true': true, 'false': false, 'empty': '',
'high surrogate': '\\uD800', 'low surrogate': '\\uDC00', 'nul': '\\u0000', 'astral': '\\uDBFF\\uDFFD',
'0.2': 0.2, '0': 0, '-0': -0, 'NaN': NaN, 'Infinity': Infinity, '-Infinity': -Infinity,
'9007199254740992': 9007199254740992, '-9007199254740992': -9007199254740992,
'9007199254740994': 9007199254740994, '-9007199254740994': -9007199254740994 },
compare_Object(enumerate_props(compare_primitive)))
return failures
`),
).toEqual([])
})
test("Date", async () => {
expect(
await value(`
${harness}
function compare_Date(actual, input) {
assert_true(actual instanceof Date, 'instanceof Date')
assert_equals(Number(actual), Number(input), 'converted to primitive')
assert_not_equals(actual, input)
}
check('Date 0', new Date(0), compare_Date)
check('Date -0', new Date(-0), compare_Date)
check('Date -8.64e15', new Date(-8.64e15), compare_Date)
check('Date 8.64e15', new Date(8.64e15), compare_Date)
check('Array Date objects', [new Date(0), new Date(-0), new Date(-8.64e15), new Date(8.64e15)],
compare_Array(enumerate_props(compare_Date)))
check('Object Date objects', { '0': new Date(0), '-0': new Date(-0), '-8.64e15': new Date(-8.64e15), '8.64e15': new Date(8.64e15) },
compare_Object(enumerate_props(compare_Date)))
return failures
`),
).toEqual([])
})
test("RegExp: flags copied, lastIndex reset, source escaped", async () => {
expect(
await value(`
${harness}
function compare_RegExp(expected_source) {
return function (actual, input) {
assert_true(actual instanceof RegExp, 'instanceof RegExp')
assert_equals(actual.global, input.global, 'global')
assert_equals(actual.ignoreCase, input.ignoreCase, 'ignoreCase')
assert_equals(actual.multiline, input.multiline, 'multiline')
assert_equals(actual.source, expected_source, 'source')
assert_equals(actual.sticky, input.sticky, 'sticky')
assert_equals(actual.unicode, input.unicode, 'unicode')
assert_equals(actual.lastIndex, 0, 'lastIndex')
assert_not_equals(actual, input)
}
}
function func_RegExp_flags_lastIndex() {
const r = /foo/gim
r.lastIndex = 2
return r
}
function func_RegExp_sticky() { return new RegExp('foo', 'y') }
function func_RegExp_unicode() { return new RegExp('foo', 'u') }
check('RegExp flags and lastIndex', func_RegExp_flags_lastIndex, compare_RegExp('foo'))
check('RegExp sticky flag', func_RegExp_sticky, compare_RegExp('foo'))
check('RegExp unicode flag', func_RegExp_unicode, compare_RegExp('foo'))
check('RegExp empty', new RegExp(''), compare_RegExp('(?:)'))
check('RegExp slash', new RegExp('/'), compare_RegExp('\\\\/'))
check('RegExp new line', new RegExp('\\n'), compare_RegExp('\\\\n'))
check('Array RegExp object, RegExp flags and lastIndex', [func_RegExp_flags_lastIndex()], compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp sticky flag', function () { return [func_RegExp_sticky()] }, compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp unicode flag', function () { return [func_RegExp_unicode()] }, compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp empty', [new RegExp('')], compare_Array(enumerate_props(compare_RegExp('(?:)'))))
check('Array RegExp object, RegExp slash', [new RegExp('/')], compare_Array(enumerate_props(compare_RegExp('\\\\/'))))
check('Array RegExp object, RegExp new line', [new RegExp('\\n')], compare_Array(enumerate_props(compare_RegExp('\\\\n'))))
check('Object RegExp object, RegExp flags and lastIndex', { 'x': func_RegExp_flags_lastIndex() }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp sticky flag', function () { return { 'x': func_RegExp_sticky() } }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp unicode flag', function () { return { 'x': func_RegExp_unicode() } }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp empty', { 'x': new RegExp('') }, compare_Object(enumerate_props(compare_RegExp('(?:)'))))
check('Object RegExp object, RegExp slash', { 'x': new RegExp('/') }, compare_Object(enumerate_props(compare_RegExp('\\\\/'))))
check('Object RegExp object, RegExp new line', { 'x': new RegExp('\\n') }, compare_Object(enumerate_props(compare_RegExp('\\\\n'))))
return failures
`),
).toEqual([])
})
test("Error: name and message kept, custom properties dropped", async () => {
expect(
await value(`
${harness}
function compare_Error(actual, input) {
assert_true(actual instanceof Error, "Checking instanceof")
assert_equals(actual.name, input.name, "Checking name")
assert_equals(Object.hasOwn(actual, "message"), Object.hasOwn(input, "message"), "Checking message existence")
assert_equals(actual.message, input.message, "Checking message")
assert_equals(actual.foo, undefined, "Checking for absence of custom property")
}
check('Empty Error object', new Error(), compare_Error)
for (const constructor of [Error, RangeError, ReferenceError, SyntaxError, TypeError, URIError]) {
check(constructor.name, () => {
const error = new constructor("Error message here")
error.foo = "testing"
return error
}, compare_Error)
}
return failures
`),
).toEqual([])
})
test("sparse arrays, index-property objects, and identical property values", async () => {
expect(
await value(`
${harness}
check('Array sparse', new Array(10), compare_Array(enumerate_props(compare_primitive)))
check('Object with index property and length', { '0': 'foo', 'length': 1 }, compare_Object(enumerate_props(compare_primitive)))
function check_identical_property_values(prop1, prop2) {
return function (actual) { assert_equals(actual[prop1], actual[prop2]) }
}
check('Array with identical property values', function () {
const obj = {}
return [obj, obj]
}, compare_Array(check_identical_property_values('0', '1')))
check('Object with identical property values', function () {
const obj = {}
return { 'x': obj, 'y': obj }
}, compare_Object(check_identical_property_values('x', 'y')))
return failures
`),
).toEqual([])
})
})
describe("structuredClone beyond the WPT battery", () => {
test("Map, Set, URL, and URLSearchParams are copied, with shared references preserved across containers", async () => {
expect(
await value(`
const shared = { n: 1 }
const input = { m: new Map([[shared, shared]]), s: new Set([shared]), u: new URL("https://a.b/c?d=1") }
const copy = structuredClone(input)
const [[key, item]] = [...copy.m]
copy.u.searchParams.set("d", "2")
return [
copy.m !== input.m, key !== shared, key === item, key === [...copy.s][0],
copy.u !== input.u, input.u.href, copy.u.href,
]
`),
).toEqual([true, true, true, true, true, "https://a.b/c?d=1", "https://a.b/c?d=2"])
})
test("functions, promises, and tool references throw DataCloneError", async () => {
expect(
await value(`
return [() => 1, Promise.resolve(1), tools, Math, { nested: [() => 1] }].map((input) => {
try { structuredClone(input); return "cloned" } catch (error) { return error.name }
})
`),
).toEqual(Array(5).fill("DataCloneError"))
expect(await value(`try { structuredClone() } catch (error) { return error.name }`)).toBe("TypeError")
})
})
@@ -233,10 +233,3 @@ describe("var semantics beyond Test262", () => {
expect(await value(`function* gen() { var t = 1; yield t; var t = 2; yield t } return [...gen()]`)).toEqual([1, 2])
})
})
describe("switch case function hoisting", () => {
test("function declarations are visible across all cases before their statement runs", async () => {
expect(await value(`switch (1) { case 1: return foo(); function foo() { return "hoisted" } }`)).toBe("hoisted")
expect(await value(`switch (2) { case 1: function foo() { return "a" } break; case 2: return foo() }`)).toBe("a")
})
})
-169
View File
@@ -1,169 +0,0 @@
/**
* Portions adapted from web-platform-tests at revision 863077959ca8c1a7ceecfbe2534b75d2527b9013:
* - html/webappapis/atob/base64.any.js (btoa reference encoder, input list, and atob WebIDL cases)
* - fetch/data-urls/resources/base64.json (copied to fixtures/wpt-base64.json)
* - WebCryptoAPI/randomUUID.https.any.js
*
* Copyright © web-platform-tests contributors. Governed by the 3-Clause BSD license in LICENSE.wpt.
*
* `assert_throws_dom("InvalidCharacterError", …)` becomes a check on `error.name`: CodeMode has no
* DOMException, so the name is carried on a plain Error.
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
const base64Cases = (await Bun.file(new URL("./fixtures/wpt-base64.json", import.meta.url)).json()) as Array<
[string, Array<number> | null]
>
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
return result.value
}
// The reference encoder from base64.any.js, run inside the interpreter so btoa is checked against
// an independent implementation rather than against the host's btoa.
const referenceEncoder = `
function btoaLookup(idx) {
if (idx < 26) return String.fromCharCode(idx + "A".charCodeAt(0))
if (idx < 52) return String.fromCharCode(idx - 26 + "a".charCodeAt(0))
if (idx < 62) return String.fromCharCode(idx - 52 + "0".charCodeAt(0))
if (idx == 62) return "+"
if (idx == 63) return "/"
}
function mybtoa(s) {
s = String(s)
for (var i = 0; i < s.length; i++) if (s.charCodeAt(i) > 255) return "INVALID_CHARACTER_ERR"
var out = ""
for (var i = 0; i < s.length; i += 3) {
var groupsOfSix = [undefined, undefined, undefined, undefined]
groupsOfSix[0] = s.charCodeAt(i) >> 2
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4
if (s.length > i + 1) {
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2
}
if (s.length > i + 2) {
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f
}
for (var j = 0; j < groupsOfSix.length; j++) {
out += typeof groupsOfSix[j] == "undefined" ? "=" : btoaLookup(groupsOfSix[j])
}
}
return out
}
function testBtoa(input) {
var expected = mybtoa(input)
if (expected === "INVALID_CHARACTER_ERR") {
try { btoa(input) } catch (error) { return error.name === "InvalidCharacterError" ? "ok" : error.name }
return "did not throw"
}
if (btoa(input) !== expected) return "btoa mismatch"
if (atob(btoa(input)) !== String(input)) return "roundtrip mismatch"
return "ok"
}
`
describe("btoa WPT parity (html/webappapis/atob/base64.any.js)", () => {
test("every input encodes like the reference encoder and round-trips through atob", async () => {
expect(
await value(`
${referenceEncoder}
var tests = ["עברית", "", "ab", "abc", "abcd", "abcde", "\\xff\\xff\\xc0", "\\0a", "a\\0b",
undefined, null, 7, 12, 1.5, true, false, NaN, +Infinity, -Infinity, 0, -0]
for (var i = 0; i < 258; i++) tests.push(String.fromCharCode(i))
tests.push(String.fromCharCode(10000), String.fromCharCode(65534), String.fromCharCode(65535))
tests.push(String.fromCharCode(0xd800, 0xdc00))
var everything = ""
for (var i = 0; i < 256; i++) everything += String.fromCharCode(i)
tests.push(everything)
return tests.map(testBtoa).filter((outcome) => outcome !== "ok")
`),
).toEqual([])
})
})
describe("atob WPT parity (fetch/data-urls/resources/base64.json)", () => {
const idlCases: Array<[unknown, Array<number> | null]> = [
[undefined, null],
[null, [158, 233, 101]],
[7, null],
[12, [215]],
[1.5, null],
[true, [182, 187]],
[false, null],
[NaN, [53, 163]],
[Infinity, [34, 119, 226, 158, 43, 114]],
[-Infinity, null],
[0, null],
[-0, null],
]
test(`${base64Cases.length} forgiving-base64 inputs decode to the expected bytes or throw InvalidCharacterError`, async () => {
expect(
await value(`
const cases = ${JSON.stringify(base64Cases)}
return cases.flatMap(([input, output]) => {
try {
const result = atob(input)
if (output === null) return [[input, "expected throw"]]
const bytes = Array.from({ length: result.length }, (_, i) => result.charCodeAt(i))
return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[input, bytes]]
} catch (error) {
return output === null && error.name === "InvalidCharacterError" ? [] : [[input, error.name]]
}
})
`),
).toEqual([])
})
test("WebIDL argument conversion stringifies non-string inputs", async () => {
const literal = (input: unknown) =>
Object.is(input, -0)
? "-0"
: typeof input === "number" || input === undefined
? String(input)
: JSON.stringify(input)
expect(
await value(`
const cases = [${idlCases.map(([input, output]) => `[${literal(input)}, ${JSON.stringify(output)}]`).join(",")}]
return cases.flatMap(([input, output]) => {
try {
const result = atob(input)
if (output === null) return [[String(input), "expected throw"]]
// The source loop checks only the listed prefix of the decoded bytes.
const bytes = output.map((_, i) => result.charCodeAt(i))
return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[String(input), bytes]]
} catch (error) {
return output === null && error.name === "InvalidCharacterError" ? [] : [[String(input), error.name]]
}
})
`),
).toEqual([])
})
})
describe("crypto.randomUUID WPT parity (WebCryptoAPI/randomUUID.https.any.js)", () => {
test("namespace format, version, and variant bits over 256 iterations without collision", async () => {
expect(
await value(`
const uuids = new Set()
const randomUUID = () => {
const uuid = crypto.randomUUID()
if (uuids.has(uuid)) throw new Error("uuid collision " + uuid)
uuids.add(uuid)
return uuid
}
const UUIDRegex = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
let format = true, version = true, variant = true
for (let i = 0; i < 256; i++) format = format && UUIDRegex.test(randomUUID())
for (let i = 0; i < 256; i++) version = version && (parseInt(randomUUID().split("-")[2].slice(0, 2), 16) & 0b11110000) === 0b01000000
for (let i = 0; i < 256; i++) variant = variant && (parseInt(randomUUID().split("-")[3].slice(0, 2), 16) & 0b11000000) === 0b10000000
return [format, version, variant, uuids.size]
`),
).toEqual([true, true, true, 768])
})
})
+33 -12
View File
@@ -178,29 +178,50 @@ export const AzurePlugin = define({
Effect.forkScoped({ startImmediately: true }),
)
// Entra bearer tokens are minted per request from the target URL's scope, so they are injected at the
// transport hooks rather than stored as a credential.
const bearer = Effect.fn(function* (url: string) {
const connection = yield* ctx.integration.connection.active(Provider.ID.azure)
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
: undefined
if (credential?.type !== "oauth" || credential.methodID !== methodID) return
const target = new URL(url)
const scope =
target.hostname.endsWith(".services.ai.azure.com") && !target.pathname.startsWith("/models")
? foundryScope
: cognitiveScope
const current = yield* token(scope).pipe(Effect.orDie)
return `Bearer ${current.access}`
})
yield* ctx.session.hook(
"http.request",
(evt) =>
Effect.gen(function* () {
if (evt.model.providerID !== Provider.ID.azure) return
const connection = yield* ctx.integration.connection.active(Provider.ID.azure)
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
: undefined
if (credential?.type !== "oauth" || credential.methodID !== methodID) return
const url = new URL(evt.request.url)
const scope =
url.hostname.endsWith(".services.ai.azure.com") && !url.pathname.startsWith("/models")
? foundryScope
: cognitiveScope
const current = yield* token(scope).pipe(Effect.orDie)
const authorization = yield* bearer(evt.request.url)
if (!authorization) return
evt.request.headers.delete("api-key")
evt.request.headers.delete("x-api-key")
evt.request.headers.set("authorization", `Bearer ${current.access}`)
evt.request.headers.set("authorization", authorization)
evt.request.headers.set("user-agent", App.useragent(ctx.app))
}),
{ providerID: Provider.ID.azure },
)
yield* ctx.session.hook(
"experimental.ws.handshake",
(evt) =>
Effect.gen(function* () {
if (evt.model.providerID !== Provider.ID.azure) return
const authorization = yield* bearer(evt.url)
if (!authorization) return
delete evt.headers["api-key"]
delete evt.headers["x-api-key"]
evt.headers.authorization = authorization
evt.headers["user-agent"] = App.useragent(ctx.app)
}),
{ providerID: Provider.ID.azure },
)
yield* ctx.aisdk.hook(
"sdk",
+17 -6
View File
@@ -316,17 +316,28 @@ export const layer = Layer.effect(
return HttpClientResponse.fromWeb(sent, after.response)
}).pipe(Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause)))))
: undefined
// HTTP hooks must observe every request, so they keep the provider on HTTP.
const webSocket =
input.webSocket === "session" &&
!hasHttpHooks &&
model.capabilities.responsesWebsockets === true &&
model.websocket
input.webSocket === "session" && model.capabilities.responsesWebsockets === true && model.websocket
const interceptor: SessionModelTransport.Interceptor = {
handshake: (connect) =>
hooks.trigger("session", "experimental.ws.handshake", {
...scope,
url: connect.url,
headers: connect.headers,
}),
send: (frame, mode) =>
hooks.trigger("session", "experimental.ws.send", { ...scope, mode, frame }).pipe(Effect.map((e) => e.frame)),
receive: (frame) =>
hooks.trigger("session", "experimental.ws.receive", { ...scope, frame }).pipe(Effect.map((e) => e.frame)),
}
return {
event: shaped,
request,
options: { ...(http ? { http } : {}), ...(webSocket ? { webSocket: transport.bind(session.id) } : {}) },
options: {
...(http ? { http } : {}),
...(webSocket ? { webSocket: transport.bind(session.id, interceptor) } : {}),
},
retry: (event: Parameters<Prepared["retry"]>[0]) =>
hooks.trigger("session", "retry", event).pipe(Effect.asVoid),
// Permission.assert and the question tool throw declines as defects so tools cannot
+30 -6
View File
@@ -2,6 +2,7 @@ export * as SessionModelTransport from "./model-transport.js"
import {
WebSocketTransport,
type ChannelCreate,
type ChannelObservation,
type ChannelCheckpoint,
type WebSocketChannelExchange,
@@ -13,6 +14,7 @@ import {
import { AIError, AIErrorReason, TransportError, type TransportOperation } from "@opencode/ai"
import { Hash } from "@opencode/util/hash"
import { Cause, Clock, Context, Effect, Fiber, Layer, Metric, Queue, Scope, Semaphore, Stream } from "effect"
import { Headers } from "effect/unstable/http"
import { Socket } from "effect/unstable/socket"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { SessionSchema } from "./schema.js"
@@ -52,8 +54,18 @@ interface State {
channel?: Channel
}
/** Per-exchange plugin hooks. `handshake` output selects the connection; frames are what crosses the wire. */
export interface Interceptor {
readonly handshake: (connect: {
readonly url: string
readonly headers: Record<string, string>
}) => Effect.Effect<{ readonly url: string; readonly headers: Record<string, string> }>
readonly send: (frame: string, mode: ChannelCreate["mode"]) => Effect.Effect<string>
readonly receive: (frame: string) => Effect.Effect<string>
}
export interface Interface {
readonly bind: (sessionID: SessionSchema.ID) => WebSocketChannelExecutor
readonly bind: (sessionID: SessionSchema.ID, interceptor?: Interceptor) => WebSocketChannelExecutor
readonly close: (sessionID: SessionSchema.ID) => Effect.Effect<void>
readonly closeAll: Effect.Effect<void>
}
@@ -267,7 +279,8 @@ export const makeLayer = (connector: WebSocketConnector) =>
const start = Effect.fn("SessionModelTransport.start")(function* (
owner: State,
exchange: WebSocketChannelExchange,
input: WebSocketChannelExchange,
interceptor?: Interceptor,
) {
if (owner.closed)
return yield* transportError("Session WebSocket owner is closed", {
@@ -276,7 +289,16 @@ export const makeLayer = (connector: WebSocketConnector) =>
phase: "queue",
delivery: "not-sent",
})
if (owner.httpFallback) return fallback(exchange)
if (owner.httpFallback) return fallback(input)
const handshake = interceptor
? yield* interceptor.handshake({ url: input.connect.url, headers: { ...input.connect.headers } })
: undefined
const exchange: WebSocketChannelExchange = handshake
? {
...input,
connect: { ...input.connect, url: handshake.url, headers: Headers.fromInput(handshake.headers) },
}
: input
const key = affinity(exchange)
const now = yield* Clock.currentTimeMillis
const current = owner.channel
@@ -337,6 +359,7 @@ export const makeLayer = (connector: WebSocketConnector) =>
Effect.onInterrupt(() => closeChannel(owner, channel)),
)
if (create.mode === "full") channel.checkpoint = undefined
const message = interceptor ? yield* interceptor.send(create.message, create.mode) : create.message
yield* Effect.logDebug("session websocket sending", {
sessionTransport: "websocket",
phase: "send",
@@ -347,7 +370,7 @@ export const makeLayer = (connector: WebSocketConnector) =>
delivery: "send-attempted",
}
channel.active = active
const sent = yield* channel.connection.sendText(create.message).pipe(
const sent = yield* channel.connection.sendText(message).pipe(
Effect.withSpan("SessionModelTransport.send"),
Effect.onInterrupt(() => closeChannel(owner, channel)),
Effect.result,
@@ -388,6 +411,7 @@ export const makeLayer = (connector: WebSocketConnector) =>
}),
),
}),
Stream.mapEffect((frame) => (interceptor ? interceptor.receive(frame) : Effect.succeed(frame))),
Stream.mapEffect((frame) => exchange.driver.observe(create, frame)),
Stream.tap((observation) =>
Effect.sync(() => {
@@ -465,7 +489,7 @@ export const makeLayer = (connector: WebSocketConnector) =>
return { frames, complete, http: channel.connection.http }
})
const bind = (sessionID: SessionSchema.ID): WebSocketChannelExecutor => ({
const bind = (sessionID: SessionSchema.ID, interceptor?: Interceptor): WebSocketChannelExecutor => ({
execute: (exchange) => {
const owner = state(sessionID)
let execution: WebSocketChannelExecution | undefined
@@ -475,7 +499,7 @@ export const makeLayer = (connector: WebSocketConnector) =>
},
frames: Stream.unwrap(
Effect.acquireRelease(owner.lock.take(1), () => owner.lock.release(1), { interruptible: true }).pipe(
Effect.andThen(start(owner, exchange)),
Effect.andThen(start(owner, exchange, interceptor)),
Effect.tap((started) =>
Effect.sync(() => {
execution = started
@@ -303,6 +303,20 @@ describe("AzurePlugin", () => {
})
expect(foundry.request.headers.get("authorization")).toBe("Bearer https://ai.azure.com/.default-token")
expect(foundry.request.headers.has("x-api-key")).toBe(false)
const handshake = yield* hooks.trigger("session", "experimental.ws.handshake", {
sessionID: Session.ID.make("ses_azure_ws"),
agent: Agent.ID.make("build"),
model,
kind: "primary",
url: "wss://test-resource.openai.azure.com/openai/v1/responses",
headers: { "api-key": "stored-token", "x-keep": "yes" },
})
expect(handshake.headers).toMatchObject({
authorization: "Bearer https://cognitiveservices.azure.com/.default-token",
"x-keep": "yes",
})
expect(handshake.headers["api-key"]).toBeUndefined()
}),
),
)
@@ -79,4 +79,68 @@ describe("SessionModelRequest HTTP hooks", () => {
)
}).pipe(Effect.provideService(SessionModelTransport.Service, transport)),
)
it.effect("runs experimental.ws hooks through the transport interceptor alongside http hooks", () =>
Effect.gen(function* () {
const hooks = yield* PluginHooks.Service
const seen: Array<string> = []
yield* hooks.register("session", "http.request", () => Effect.void)
yield* hooks.register("session", "experimental.ws.handshake", (event) =>
Effect.sync(() => {
seen.push(`handshake:${event.kind}:${event.agent}`)
event.url = `${event.url}?hooked`
event.headers.authorization = "Bearer hooked"
}),
)
yield* hooks.register("session", "experimental.ws.send", (event) =>
Effect.sync(() => {
seen.push(`send:${event.kind}:${event.mode}`)
event.frame = `${event.frame}:sent`
}),
)
yield* hooks.register("session", "experimental.ws.receive", (event) =>
Effect.sync(() => {
seen.push(`receive:${event.kind}`)
event.frame = `${event.frame}:received`
}),
)
let interceptor: SessionModelTransport.Interceptor | undefined
const capturing = SessionModelTransport.Service.of({
bind: (_sessionID, bound) => {
interceptor = bound
return { execute: () => Effect.die("unused WebSocket execution") }
},
close: () => Effect.void,
closeAll: Effect.void,
})
const requests = yield* SessionModelRequest.Service.pipe(
Effect.provide(SessionModelRequest.layer),
Effect.provideService(SessionModelTransport.Service, capturing),
)
const prepared = yield* requests.compaction({
session,
agent: Agent.ID.make("build"),
model: SessionRunnerModel.resolved(OpenAIChat.route.model({ id: "gpt-5.5", provider: "test" }), {
capabilities: { tools: true, input: ["text"], output: ["text"], responsesWebsockets: true },
cost: [],
limit: { context: 200_000, output: 32_000 },
websocket: true,
}),
system: [],
messages: [],
webSocket: "session",
})
expect(prepared.options.http).toBeDefined()
expect(prepared.options.webSocket).toBeDefined()
if (!interceptor) throw new Error("Expected the transport to receive an interceptor")
expect(yield* interceptor.handshake({ url: "wss://example.test/v1/responses", headers: {} })).toMatchObject({
url: "wss://example.test/v1/responses?hooked",
headers: { authorization: "Bearer hooked" },
})
expect(yield* interceptor.send("frame", "incremental")).toBe("frame:sent")
expect(yield* interceptor.receive("frame")).toBe("frame:received")
expect(seen).toEqual(["handshake:compaction:build", "send:compaction:incremental", "receive:compaction"])
}),
)
})
@@ -822,6 +822,36 @@ describe("SessionModelTransport", () => {
)
})
test("runs interceptors on the handshake and both frame directions", async () => {
const fixture = automatic()
const seen: Array<string> = []
let authorization = "one"
await run(
fixture.connector,
Effect.gen(function* () {
const transport = yield* SessionModelTransport.Service
const executor = transport.bind(session, {
handshake: (connect) =>
Effect.succeed({ url: `${connect.url}?hooked`, headers: { ...connect.headers, authorization } }),
send: (frame, mode) => Effect.succeed(`${frame}:${mode}`),
receive: (frame) =>
Effect.sync(() => {
seen.push(frame)
return frame.toUpperCase()
}),
})
expect(yield* collect(executor, exchange("first"))).toEqual(["COMPLETED:FIRST:FULL"])
authorization = "two"
expect(yield* collect(executor, exchange("second"))).toEqual(["COMPLETED:SECOND:FULL"])
expect(seen).toEqual(["completed:first:full", "completed:second:full"])
expect(fixture.connections).toHaveLength(2)
expect(fixture.connections.map((item) => item.headers.authorization)).toEqual(["one", "two"])
expect(fixture.connections.map((item) => item.sent)).toEqual([["first:full"], ["second:full"]])
}),
)
})
test("rotates when the connection exceeds its requested age limit", async () => {
const fixture = automatic()
+31
View File
@@ -86,6 +86,34 @@ export interface SessionHttpResponse {
response: Response
}
/** Connection a WebSocket request needs. Changing `url` or `headers` reopens the Session's socket. */
export interface SessionWebSocketHandshake {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
url: string
headers: Record<string, string>
}
export interface SessionWebSocketSend {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
/** Incremental frames carry only what changed since the provider's last checkpoint. */
readonly mode: "full" | "incremental"
frame: string
}
export interface SessionWebSocketReceive {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
frame: string
}
export type SessionRetryDecision = { retry: false } | { retry: true; delay: number }
export interface SessionRetry {
@@ -106,6 +134,9 @@ export interface SessionHooks {
readonly "model.request": SessionModelRequest
readonly "http.request": SessionHttpRequest
readonly "http.response": SessionHttpResponse
readonly "experimental.ws.handshake": SessionWebSocketHandshake
readonly "experimental.ws.send": SessionWebSocketSend
readonly "experimental.ws.receive": SessionWebSocketReceive
readonly retry: SessionRetry
}
+31
View File
@@ -86,6 +86,34 @@ export interface SessionHttpResponse {
response: Response
}
/** Connection a WebSocket request needs. Changing `url` or `headers` reopens the Session's socket. */
export interface SessionWebSocketHandshake {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
url: string
headers: Record<string, string>
}
export interface SessionWebSocketSend {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
/** Incremental frames carry only what changed since the provider's last checkpoint. */
readonly mode: "full" | "incremental"
frame: string
}
export interface SessionWebSocketReceive {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
readonly kind: SessionRequestKind
frame: string
}
export type SessionRetryDecision = { retry: false } | { retry: true; delay: number }
export interface SessionRetry {
@@ -106,6 +134,9 @@ export interface SessionHooks {
readonly "model.request": SessionModelRequest
readonly "http.request": SessionHttpRequest
readonly "http.response": SessionHttpResponse
readonly "experimental.ws.handshake": SessionWebSocketHandshake
readonly "experimental.ws.send": SessionWebSocketSend
readonly "experimental.ws.receive": SessionWebSocketReceive
readonly retry: SessionRetry
}
@@ -1151,6 +1151,24 @@ effect: (ctx) =>
}),
```
WebSocket providers do not issue one HTTP request per model call, so the HTTP hooks never see that traffic. Three
experimental hooks cover it: `experimental.ws.handshake` runs once per model call with the URL and headers the connection
needs (changing either reopens the session's socket), `experimental.ws.send` runs on the outbound frame, and
`experimental.ws.receive` on every inbound frame. Incremental `send` frames carry only what changed since the provider's
last checkpoint; rewriting them changes what the provider sees without changing what OpenCode believes it sent.
```ts
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.session.hook("experimental.ws.handshake", (event) =>
Effect.sync(() => {
event.headers.authorization = `Bearer ${token}`
}),
)
yield* ctx.session.hook("experimental.ws.receive", (event) => Effect.log(event.frame))
}),
```
Override the retry decision for a provider failure or replace its delay in milliseconds. The hook runs after OpenCode
classifies the failure and proposes its policy, but before any retry is scheduled. It does not expose how OpenCode
internally performs the next attempt.
@@ -1191,6 +1209,9 @@ interface SessionHooks {
readonly "model.request": SessionModelRequest
readonly "http.request": SessionHttpRequest
readonly "http.response": SessionHttpResponse
readonly "experimental.ws.handshake": SessionWebSocketHandshake
readonly "experimental.ws.send": SessionWebSocketSend
readonly "experimental.ws.receive": SessionWebSocketReceive
readonly retry: SessionRetry
}
@@ -1294,6 +1294,32 @@ await ctx.session.hook("http.response", (event) => {
})
```
#### WebSocket (experimental)
Providers that stream over a WebSocket do not issue one HTTP request per model call, so `http.request` and
`http.response` never see that traffic. Three experimental hooks cover it instead. `experimental.ws.handshake` runs
once per model call with the URL and headers the connection needs; changing either reopens the session's socket.
`experimental.ws.send` runs on the outbound frame, and `experimental.ws.receive` on every inbound frame. All three carry
the same `sessionID`, `agent`, `model`, and `kind` as the HTTP hooks.
```ts
await ctx.session.hook("experimental.ws.handshake", (event) => {
event.headers.authorization = `Bearer ${token}`
})
await ctx.session.hook("experimental.ws.send", (event) => {
if (event.mode === "full") event.frame = redact(event.frame)
})
await ctx.session.hook("experimental.ws.receive", (event) => {
log(event.frame)
})
```
`send` frames in `"incremental"` mode carry only what changed since the provider's last checkpoint. Rewriting them
changes what the provider sees without changing what OpenCode believes it sent, so treat them as read-only unless you
also handle the resulting drift.
#### Retry policy
Override the retry decision for a provider failure or replace its delay in milliseconds. The hook runs after OpenCode
@@ -1339,6 +1365,9 @@ interface SessionHooks {
"model.request": SessionModelRequestHook
"http.request": SessionHttpRequestHook
"http.response": SessionHttpResponseHook
"experimental.ws.handshake": SessionWebSocketHandshakeHook
"experimental.ws.send": SessionWebSocketSendHook
"experimental.ws.receive": SessionWebSocketReceiveHook
retry: SessionRetryHook
}