diff --git a/integrations/blender/plugin/src/integration.ts b/integrations/blender/plugin/src/integration.ts index 353f2b4..c4d38e9 100644 --- a/integrations/blender/plugin/src/integration.ts +++ b/integrations/blender/plugin/src/integration.ts @@ -23,6 +23,7 @@ import { isWslDaemon, loadMethodRegistry, type OfferRegistry, + offerRegistryName, registerPluginTools, requestHost, type SessionBindings, @@ -166,13 +167,13 @@ export function helloParams(_options: BlenderOptions) { // hellos by: after an upgrade without restarting OpenCode, an older plugin version stays loaded in the same // process, and a list keyed by the application alone would judge this version's add-on by the older range. export function registryName(expected: HostExpectation) { - return `${APP}.protocol-${expected.protocol}.part-${expected.range}.app-${expected.appVersions}` + return offerRegistryName(APP, expected) } export function createRegistry(marker: IntegrationMarker, options: BlenderOptions): OfferRegistry { const host = marker.host as NonNullable const expected = { protocol: host.protocol, range: host.range, appVersions: host.appVersions } - return sharedOfferRegistry(registryName(expected), { + return sharedOfferRegistry(APP, { expected, hello: (endpoint) => requestHost(endpoint, "hello", helloParams(options), { timeoutMs: HELLO_TIMEOUT_MS }), }) diff --git a/integrations/blender/test/registry.test.ts b/integrations/blender/test/registry.test.ts index 82e189f..4ad610d 100644 --- a/integrations/blender/test/registry.test.ts +++ b/integrations/blender/test/registry.test.ts @@ -6,8 +6,8 @@ import assert from "node:assert/strict" import { after, it } from "node:test" import { startFakeHost } from "../../../packages/testing/src/index.ts" -import { createRegistry, readPackage, registryName } from "../plugin/src/integration.ts" -import { offerRegistryKey, sharedOfferRegistry } from "../plugin/src/kit.ts" +import { APP, createRegistry, readPackage, registryName } from "../plugin/src/integration.ts" +import { createOfferRegistry, offerRegistryKey, sharedOfferRegistry } from "../plugin/src/kit.ts" import { readOptions } from "../plugin/src/options.ts" import { announcement } from "./helpers/plugin.ts" @@ -24,7 +24,8 @@ it("a plugin loaded after an older version in the same process judges its own ad const fake = await startFakeHost({ hostVersion: readPackage().version, appVersion: "5.3.0" }) try { // What 0.2.0 created when it loaded: the kit's shared list under "blender", with its own expectation. - const older = sharedOfferRegistry("blender", { expected: { protocol: 1, range: "^0.2.0", appVersions: ">=5.2" } }) + const older = createOfferRegistry({ expected: { protocol: 1, range: "^0.2.0", appVersions: ">=5.2" } }) + store[offerRegistryKey("blender")] = { generation: 2, registry: older } const registry = createRegistry(marker, readOptions(undefined, {})) assert.notEqual(registry, older, "this version keeps its own list") assert.deepEqual(await registry.advertise(announcement(fake.endpoint, fake.scriptHandle)), { outcome: "accepted" }) @@ -37,6 +38,9 @@ it("a plugin loaded after an older version in the same process judges its own ad await older.advertise(announcement(fake.endpoint, fake.scriptHandle)) assert.equal(older.hosts().offers[0]?.protocol, "incompatible") assert.equal(createRegistry(marker, readOptions(undefined, {})), registry, "one list per contract and process") + // The kit names the list as 0.4.8 did: the published Blender versions find theirs. + assert.equal(registryName(expected), `blender.protocol-1.part-${host.range}.app-${host.appVersions}`) + assert.ok(store[offerRegistryKey(registryName(expected))]) } finally { await fake.close() } @@ -48,7 +52,7 @@ it("an upgrade from 0.4.1 without restarting OpenCode keeps this version's add-o const published = { protocol: 1, range: "^0.4.1", appVersions: ">=5.3" } keys.push(offerRegistryKey(registryName(published))) try { - const older = sharedOfferRegistry(registryName(published), { expected: published }) + const older = sharedOfferRegistry(APP, { expected: published }) const registry = createRegistry(marker, readOptions(undefined, {})) assert.notEqual(registry, older) await registry.advertise(announcement(fake.endpoint, fake.scriptHandle, "after-upgrade")) diff --git a/integrations/gaffer/host/python/GafferOpenCode/Host.py b/integrations/gaffer/host/python/GafferOpenCode/Host.py index 13c624d..c4f3b78 100644 --- a/integrations/gaffer/host/python/GafferOpenCode/Host.py +++ b/integrations/gaffer/host/python/GafferOpenCode/Host.py @@ -73,6 +73,40 @@ def _jsonValue( value ) : return repr( value ) +# The error codes of the wire protocol (spec/README.md); a host code outside them travels as data["reason"]. +WIRE_CODES = ( + "unauthorized", "invalid_request", "method_not_found", "method_disabled", "invalid_args", "stale_handle", + "stale_revision", "expectation_failed", "mode_conflict", "busy", "quarantined", "permission_denied", "internal", +) +WIRE_ALIASES = { + "unknown_script" : "stale_handle", "revision_conflict" : "stale_revision", + "unknown_method" : "method_not_found", "script_quarantined" : "quarantined", + "rollback_failed" : "quarantined", "request_too_large" : "invalid_request", + "read_only" : "permission_denied", +} +WIRE_MESSAGE_MAX = 2000 +WIRE_DATA_MAX = 64 * 1024 + +def wireError( error ) : + + """The refusal sent to the plugin: its wire code, the host's own message and data, and the host's code.""" + + code = WIRE_ALIASES.get( error.code, error.code ) + if code.startswith( ( "invalid_", "unsupported_" ) ) and code != "invalid_request" : + code = "invalid_args" + if code not in WIRE_CODES : + code = "internal" + data = _jsonValue( dict( error.data or {} ) ) + if code != error.code : + data["reason"] = error.code + if len( json.dumps( data, allow_nan = False ) ) > WIRE_DATA_MAX : + data = { "reason" : error.code, "truncated" : True } + refusal = { "code" : code, "message" : str( error )[:WIRE_MESSAGE_MAX] } + if data : + refusal["data"] = data + return refusal + + def _valuesEqual( observed, expected ) : if isinstance( observed, ( int, float ) ) and not isinstance( observed, bool ) and isinstance( expected, ( int, float ) ) and not isinstance( expected, bool ) : @@ -1754,19 +1788,10 @@ def __handleClient( self, client ) : result = self.host.dispatch( str( request.get( "method", "" ) ), request.get( "params" ) or {} ) response = { "id" : requestID, "ok" : True, "result" : result } except HostError as error : - code = { - "unknown_script" : "stale_handle", "revision_conflict" : "stale_revision", - "unknown_method" : "method_not_found", "script_quarantined" : "quarantined", - "rollback_failed" : "quarantined", "request_too_large" : "invalid_request", - "read_only" : "permission_denied", - }.get( error.code, error.code ) - if code.startswith( ( "invalid_", "unsupported_" ) ) and code != "invalid_request" : - code = "invalid_args" - if code not in ( "unauthorized", "invalid_request", "method_not_found", "method_disabled", "invalid_args", "stale_handle", "stale_revision", "expectation_failed", "mode_conflict", "busy", "quarantined", "permission_denied", "internal" ) : - code = "internal" - response = { "id" : requestID, "ok" : False, "error" : { "code" : code, "message" : str( error )[:300] } } + response = { "id" : requestID, "ok" : False, "error" : wireError( error ) } except Exception as error : - response = { "id" : requestID, "ok" : False, "error" : { "code" : "internal", "message" : str( error )[:300] } } + message = "{}: {}".format( type( error ).__name__, error )[:WIRE_MESSAGE_MAX] + response = { "id" : requestID, "ok" : False, "error" : { "code" : "internal", "message" : message } } try : client.sendall( ( json.dumps( response, allow_nan = False ) + "\n" ).encode( "utf-8" ) ) diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.2.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.2.0.zip index 993b341..173e7f1 100644 Binary files a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.2.0.zip and b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.2.0.zip differ diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index 1b0258d..43bfc0d 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -61,7 +61,7 @@ "range": "^0.2.0", "appVersions": ">=1.6", "payload": "host/gaffer/opencode_link-0.2.0.zip", - "sha256": "d11773ecfd29d6608ee84293be76b7145713264f4b72c8308b33272bc2b37b53" + "sha256": "4db41db5c28953af8d56266e9f49b62d8ebf2ded7136e6b9051cf4b72ed2bf29" } } } diff --git a/integrations/gaffer/plugin/src/integration.ts b/integrations/gaffer/plugin/src/integration.ts index b178bcb..c3f8f9b 100644 --- a/integrations/gaffer/plugin/src/integration.ts +++ b/integrations/gaffer/plugin/src/integration.ts @@ -19,6 +19,17 @@ export function readPackage(): { version: string; opencodeIntegration: Integrati return JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) } +// The offer list shared by the daemon's Locations, named after this version's host contract (the kit's +// sharedOfferRegistry): after an upgrade without restarting OpenCode, the new host is judged by this range. +export function createRegistry(marker: IntegrationMarker): OfferRegistry { + const host = marker.host as NonNullable + return sharedOfferRegistry("gaffer", { + expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, + hello: (endpoint, scriptHandle) => + requestHost(endpoint, "hello", { script_handle: scriptHandle }, { timeoutMs: HELLO_TIMEOUT_MS }), + }) +} + export function resultContent(result: Record) { const clean = JSON.parse(JSON.stringify(result)) const jobs = [clean.job, ...(clean.jobs ?? [])].filter(Boolean) as Array<{ @@ -47,15 +58,8 @@ export function resultContent(result: Record) { export async function setupGaffer(ctx: Plugin.Context, deps: { registry?: OfferRegistry; wsl?: () => boolean } = {}) { const pkg = readPackage() const marker = pkg.opencodeIntegration - const host = marker.host - if (!host) throw new Error("Gaffer requires a native host marker.") - const registry = - deps.registry ?? - sharedOfferRegistry("gaffer", { - expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, - hello: (endpoint, scriptHandle) => - requestHost(endpoint, "hello", { script_handle: scriptHandle }, { timeoutMs: HELLO_TIMEOUT_MS }), - }) + if (!marker.host) throw new Error("Gaffer requires a native host marker.") + const registry = deps.registry ?? createRegistry(marker) const rpc = createIntegrationRpc({ marker, version: pkg.version, diff --git a/integrations/gaffer/test/conformance.test.ts b/integrations/gaffer/test/conformance.test.ts index c5e8cb6..f585b5f 100644 --- a/integrations/gaffer/test/conformance.test.ts +++ b/integrations/gaffer/test/conformance.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path" import { createInterface } from "node:readline" import { it } from "node:test" import { checkCodeExecutionGate, checkHostListener, runSentinelScenario } from "../../../packages/testing/src/index.ts" -import { requestHost } from "../plugin/src/kit.ts" +import { type HostError, requestHost } from "../plugin/src/kit.ts" import { loadPlugin } from "./helpers.ts" it("real Gaffer HostServer: loopback-only, 256-bit token, constant-time authentication and valid hello", async () => { @@ -50,6 +50,15 @@ it("real Gaffer HostServer: loopback-only, 256-bit token, constant-time authenti }), }) assert.deepEqual(errors, []) + // A refusal keeps the host's message, its data (made JSON-safe) and its own code (data.reason). + await assert.rejects(requestHost(endpoint, "refuse", { script_handle: "test-script" }), (error: HostError) => { + assert.equal(error.code, "invalid_args") + assert.match(error.message, /\(invalid_args\): SceneView renderer is not registered: Arnold /) + assert.deepEqual(error.data?.registered_renderers, ["OpenGL"]) + assert.equal(error.data?.reason, "unsupported_renderer") + assert.equal(typeof error.data?.plug, "string") + return true + }) } finally { await plugin.cleanup() } diff --git a/integrations/gaffer/test/helpers.ts b/integrations/gaffer/test/helpers.ts index 0766a81..b4a6989 100644 --- a/integrations/gaffer/test/helpers.ts +++ b/integrations/gaffer/test/helpers.ts @@ -6,7 +6,13 @@ import { readPackage, setupGaffer } from "../plugin/src/integration.ts" import { createOfferRegistry } from "../plugin/src/kit.ts" export async function loadPlugin( - input: { now?: () => number; wsl?: () => boolean; answer?: (action: string) => Promise } = {}, + input: { + now?: () => number + wsl?: () => boolean + answer?: (action: string) => Promise + // The daemon's shared offer list, as the plugin creates it, instead of a private one. + shared?: boolean + } = {}, ) { const host = readPackage().opencodeIntegration.host! const registry = createOfferRegistry({ @@ -58,11 +64,14 @@ export async function loadPlugin( }, }, } as unknown as Plugin.Context - const cleanup = await setupGaffer(ctx, { registry, wsl: input.wsl ?? (() => false) }) + const cleanup = await setupGaffer(ctx, { + registry: input.shared ? undefined : registry, + wsl: input.wsl ?? (() => false), + }) const signal = new AbortController().signal return { cleanup, - registry, + registry: cleanup.internals.registry, events, permissions, sessions, diff --git a/integrations/gaffer/test/python/real_host.py b/integrations/gaffer/test/python/real_host.py index a301908..51ccdcc 100644 --- a/integrations/gaffer/test/python/real_host.py +++ b/integrations/gaffer/test/python/real_host.py @@ -96,6 +96,16 @@ def probe(): client.sendall((json.dumps({"id": "bad-handle", "token": info["token"], "method": "hello", "params": {"script_handle": "gone"}}) + "\n").encode()) response = json.loads(client.makefile("rb").readline()) assert response["error"]["code"] == "stale_handle" + # A refusal keeps the host's message, its data and its own code (data.reason). + with socket.create_connection((info["host"], info["port"]), timeout=5) as client: + request = {"id": "newer", "token": info["token"], "method": "context", + "params": {"script_handle": handle, "session_id": "private-smoke", "if_revision": 10 ** 6}} + client.sendall((json.dumps(request) + "\n").encode()) + error = json.loads(client.makefile("rb").readline())["error"] + assert error["code"] == "stale_revision", error + assert error["message"] == "Requested revision is newer than the Gaffer graph", error + assert error["data"]["reason"] == "revision_conflict", error + assert isinstance(error["data"]["current_revision"], int), error wire.append("ok") except Exception as error: wire.append(type(error).__name__) diff --git a/integrations/gaffer/test/python/stub_host.py b/integrations/gaffer/test/python/stub_host.py index 5e00951..cce06d4 100644 --- a/integrations/gaffer/test/python/stub_host.py +++ b/integrations/gaffer/test/python/stub_host.py @@ -29,6 +29,9 @@ def dispatch(self, method, params): if params.get("script_handle") != state.handle: raise module.HostError("stale_handle", "Select the exact script") return state.hello() + if method == "refuse": + raise module.HostError("unsupported_renderer", "SceneView renderer is not registered: Arnold", + {"registered_renderers": ["OpenGL"], "plug": object()}) raise module.HostError("method_not_found", "Unknown method") server = module.HostServer(Host()) diff --git a/integrations/gaffer/test/registry.test.ts b/integrations/gaffer/test/registry.test.ts new file mode 100644 index 0000000..ecfe316 --- /dev/null +++ b/integrations/gaffer/test/registry.test.ts @@ -0,0 +1,79 @@ +// An upgrade without restarting OpenCode: the daemon loaded an older OpenCode for Gaffer, whose offer list lives +// on globalThis under the application's name alone, then this version in the same process. This version's list +// never reuses that one, which judges hellos by the older range and calls this version's host incompatible. + +import assert from "node:assert/strict" +import { after, it } from "node:test" + +import { startFakeHost } from "../../../packages/testing/src/index.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { createOfferRegistry, offerRegistryKey, offerRegistryName } from "../plugin/src/kit.ts" +import { loadPlugin } from "./helpers.ts" + +const marker = readPackage().opencodeIntegration +const host = marker.host as NonNullable +const expected = { protocol: host.protocol, range: host.range, appVersions: host.appVersions } +const store = globalThis as unknown as Record +const keys = [offerRegistryKey("gaffer"), offerRegistryKey(offerRegistryName("gaffer", expected))] +after(() => { + for (const key of keys) delete store[key] +}) + +const announce = (fake: Awaited>, offerKey: string) => ({ + ...fake.endpoint, + script_handle: fake.scriptHandle, + label: "Gaffer", + protocol: 1, + offer_key: offerKey, +}) + +it("a plugin loaded after an older version in the same process judges its own host ok", async () => { + const fake = await startFakeHost({ hostVersion: readPackage().version, appVersion: "1.7.1.0" }) + // What an older version created when it loaded: the kit's shared list under "gaffer", with its own range. + const older = createOfferRegistry({ expected: { ...expected, range: "^0.1.0" } }) + store[offerRegistryKey("gaffer")] = { generation: 2, registry: older } + const plugin = await loadPlugin({ shared: true }) + try { + assert.notEqual(plugin.registry, older, "this version keeps its own list") + assert.deepEqual(await plugin.rpc("advertise", announce(fake, "after-upgrade")), { outcome: "accepted" }) + assert.deepEqual( + plugin.registry.hosts().offers.map((offer) => offer.protocol), + ["ok"], + ) + await older.advertise(announce(fake, "after-upgrade")) + assert.equal(older.hosts().offers[0]?.protocol, "incompatible") + } finally { + await plugin.cleanup() + await fake.close() + } +}) + +it("a tool's error carries the host's own message and data", async () => { + const fake = await startFakeHost({ + hostVersion: readPackage().version, + appVersion: "1.7.1.0", + methods: { + context: () => { + throw { + code: "invalid_args", + message: "SceneView renderer is not registered: Arnold", + data: { reason: "unsupported_renderer", registered_renderers: ["OpenGL", "Cycles"] }, + } + }, + }, + }) + const plugin = await loadPlugin() + try { + await plugin.rpc("advertise", announce(fake, "errors")) + const offerID = plugin.registry.hosts().offers[0]?.offerID as string + assert.deepEqual(await plugin.rpc("attachHost", { offerID, sessionID: "ses_test" }), { outcome: "attached" }) + await assert.rejects(plugin.tool("gaffer_context", { script_handle: fake.scriptHandle }), (error: Error) => { + assert.match(error.message, /\(invalid_args\): SceneView renderer is not registered: Arnold/) + assert.match(error.message, /"reason":"unsupported_renderer","registered_renderers":\["OpenGL","Cycles"\]/) + return true + }) + } finally { + await plugin.cleanup() + await fake.close() + } +}) diff --git a/integrations/houdini/host/scripts/opencode_houdini/host.py b/integrations/houdini/host/scripts/opencode_houdini/host.py index 7fce464..ee9bca9 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/host.py +++ b/integrations/houdini/host/scripts/opencode_houdini/host.py @@ -106,6 +106,39 @@ def __init__(self, code: str, message: str, data: dict[str, Any] | None = None) self.data = data or {} +# The error codes of the wire protocol (spec/README.md); a host code outside them travels as data["reason"]. +WIRE_CODES = ( + "unauthorized", "invalid_request", "method_not_found", "method_disabled", "invalid_args", "stale_handle", + "stale_revision", "expectation_failed", "mode_conflict", "busy", "quarantined", "permission_denied", "internal", +) +WIRE_ALIASES = { + "unknown_script": "stale_handle", "revision_conflict": "stale_revision", "script_quarantined": "quarantined", + "unknown_method": "method_not_found", "ui_timeout": "busy", +} +WIRE_MESSAGE_MAX = 2000 +WIRE_DATA_MAX = 64 * 1024 + + +def _wire_message(text: Any) -> str: + return str(text)[:WIRE_MESSAGE_MAX] + + +def wire_error(error: HostError) -> dict[str, Any]: + """The refusal sent to the plugin: its wire code, the host's own message and data, and the host's code.""" + code = WIRE_ALIASES.get(error.code, error.code) + if code not in WIRE_CODES: + code = "invalid_args" + data = _json_value(dict(error.data or {})) + if code != error.code: + data["reason"] = error.code + if len(json.dumps(data, allow_nan=False)) > WIRE_DATA_MAX: + data = {"reason": error.code, "truncated": True} + refusal: dict[str, Any] = {"code": code, "message": _wire_message(error)} + if data: + refusal["data"] = data + return refusal + + def _json_value(value: Any) -> Any: if isinstance(value, float) and not math.isfinite(value): return "NaN" if math.isnan(value) else ("Infinity" if value > 0 else "-Infinity") @@ -1277,16 +1310,12 @@ def _handle_client(self, client: socket.socket) -> None: if len(json.dumps(response).encode("utf-8")) > 8 * 1024 * 1024: raise HostError("invalid_request", "Narrow the requested working set") except HostError as error: - response = { - "id": request_id, - "ok": False, - "error": {"code": {"unknown_script": "stale_handle", "revision_conflict": "stale_revision", "script_quarantined": "quarantined", "unknown_method": "method_not_found", "ui_timeout": "busy"}.get(error.code, error.code if error.code in ("unauthorized", "invalid_request", "expectation_failed", "mode_conflict", "permission_denied") else "invalid_args"), "message": "Houdini refused the request"}, - } + response = {"id": request_id, "ok": False, "error": wire_error(error)} except Exception as error: response = { "id": request_id, "ok": False, - "error": {"code": "internal", "message": "Houdini host request failed"}, + "error": {"code": "internal", "message": _wire_message("%s: %s" % (type(error).__name__, error))}, } try: client.sendall((json.dumps(response, allow_nan=False) + "\n").encode("utf-8")) diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.2.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.2.1.zip index 2db9cb2..fcc09c6 100644 Binary files a/integrations/houdini/plugin/host/houdini/opencode_link-0.2.1.zip and b/integrations/houdini/plugin/host/houdini/opencode_link-0.2.1.zip differ diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index a7fbcf5..503ad2b 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -63,7 +63,7 @@ "range": "^0.2.0", "appVersions": ">=21.0", "payload": "host/houdini/opencode_link-0.2.1.zip", - "sha256": "518330d99122b6cf090acb64543c6513b172a4798ecd4a5b3af776c0bfa5bc8f" + "sha256": "25feefc3f10e5820116e0b8c625bb5a66872ad70b0e0369d3944fa44b9676ffc" } } } diff --git a/integrations/houdini/plugin/src/integration.ts b/integrations/houdini/plugin/src/integration.ts index 295b71b..346e842 100644 --- a/integrations/houdini/plugin/src/integration.ts +++ b/integrations/houdini/plugin/src/integration.ts @@ -19,6 +19,16 @@ export function readPackage() { } } +// The offer list shared by the daemon's Locations, named after this version's host contract (the kit's +// sharedOfferRegistry): after an upgrade without restarting OpenCode, the new host is judged by this range. +export function createRegistry(marker: IntegrationMarker): OfferRegistry { + const host = marker.host as NonNullable + return sharedOfferRegistry("houdini", { + expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, + hello: (endpoint) => requestHost(endpoint, "hello", {}, { timeoutMs: 2000 }), + }) +} + const contextSchema = { type: "object", properties: { @@ -60,13 +70,7 @@ export async function setupHoudini( ) { const pkg = readPackage() const marker = pkg.opencodeIntegration - const host = marker.host as NonNullable - const registry = - deps.registry ?? - sharedOfferRegistry("houdini", { - expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, - hello: (endpoint) => requestHost(endpoint, "hello", {}, { timeoutMs: 2000 }), - }) + const registry = deps.registry ?? createRegistry(marker) const raw = ctx.options as { hostInspectionDir?: unknown } | undefined const preferences = typeof raw?.hostInspectionDir === "string" diff --git a/integrations/houdini/test/conformance.test.ts b/integrations/houdini/test/conformance.test.ts index 0daae7e..1787891 100644 --- a/integrations/houdini/test/conformance.test.ts +++ b/integrations/houdini/test/conformance.test.ts @@ -3,7 +3,7 @@ import { spawn, spawnSync } from "node:child_process" import { join } from "node:path" import { createInterface } from "node:readline" import { it } from "node:test" -import { requestHost } from "../../../packages/integration-kit/src/index.ts" +import { type HostError, requestHost } from "../../../packages/integration-kit/src/index.ts" import { checkCodeExecutionGate, checkHostListener, runSentinelScenario } from "../../../packages/testing/src/index.ts" import { loadPlugin } from "./helpers.ts" @@ -47,6 +47,21 @@ it("the actual Houdini host transport is authenticated, loopback-only and has no await assert.rejects( requestHost(endpoint, "execute_code", { script_handle: "hip:test-document", code: "raise Exception()" }), ) + // A refusal keeps the host's message, its data and its own code (data.reason). + await assert.rejects( + requestHost(endpoint, "apply", { + script_handle: "hip:test-document", + session_id: "ses_test", + if_revision: 0, + command_id: "stale", + }), + (error: HostError) => { + assert.equal(error.code, "stale_revision") + assert.match(error.message, /\(stale_revision\): The Houdini graph changed after the intent was prepared /) + assert.deepEqual(error.data, { expected_revision: 0, current_revision: 1, reason: "revision_conflict" }) + return true + }, + ) } finally { await plugin.cleanup() const stopped = new Promise((resolve) => child.once("exit", resolve)) diff --git a/integrations/houdini/test/helpers.ts b/integrations/houdini/test/helpers.ts index 4c9ce47..c55cf54 100644 --- a/integrations/houdini/test/helpers.ts +++ b/integrations/houdini/test/helpers.ts @@ -12,6 +12,8 @@ export async function loadPlugin( options?: object state?: string wsl?: () => boolean + // The daemon's shared offer list, as the plugin creates it, instead of a private one. + shared?: boolean } = {}, ) { const marker = readPackage().opencodeIntegration @@ -69,10 +71,14 @@ export async function loadPlugin( }, }, } as unknown as Plugin.Context - const cleanup = await setupHoudini(ctx, { registry, wsl: input.wsl ?? (() => false), state: input.state }) + const cleanup = await setupHoudini(ctx, { + registry: input.shared ? undefined : registry, + wsl: input.wsl ?? (() => false), + state: input.state, + }) const signal = new AbortController().signal return { - registry, + registry: cleanup.internals.registry, cleanup, events, permissions, diff --git a/integrations/houdini/test/host_probe.py b/integrations/houdini/test/host_probe.py index 6a258ef..b1c37ab 100644 --- a/integrations/houdini/test/host_probe.py +++ b/integrations/houdini/test/host_probe.py @@ -82,6 +82,19 @@ def test_read_bounds_and_replay_ledger(self): value.apply({"session_id": "ses_test", "command_id": "new"}) self.assertEqual(caught.exception.code, "busy") + def test_refusals_keep_message_data_and_code(self): + refusal = module.wire_error(module.HostError("busy", "Too many commands", {"limit": 256})) + self.assertEqual(refusal, {"code": "busy", "message": "Too many commands", "data": {"limit": 256}}) + refusal = module.wire_error(module.HostError("unknown_ref", "Unknown ref: /obj/geo1", {"ref": object()})) + self.assertEqual(refusal["code"], "invalid_args") + self.assertEqual(refusal["message"], "Unknown ref: /obj/geo1") + self.assertEqual(refusal["data"]["reason"], "unknown_ref") + self.assertIsInstance(refusal["data"]["ref"], str) + json.dumps(refusal, allow_nan=False) + refusal = module.wire_error(module.HostError("expectation_failed", "x" * 5000, {"observed": "y" * 100000})) + self.assertEqual(len(refusal["message"]), module.WIRE_MESSAGE_MAX) + self.assertEqual(refusal["data"], {"reason": "expectation_failed", "truncated": True}) + def test_unknown_method_and_stale_handle(self): host = module.Host.__new__(module.Host) host.state = state() diff --git a/integrations/houdini/test/registry.test.ts b/integrations/houdini/test/registry.test.ts new file mode 100644 index 0000000..6272be1 --- /dev/null +++ b/integrations/houdini/test/registry.test.ts @@ -0,0 +1,86 @@ +// An upgrade without restarting OpenCode: the daemon loaded an older OpenCode for Houdini, whose offer list lives +// on globalThis under the application's name alone, then this version in the same process. This version's list +// never reuses that one, which judges hellos by the older range and calls this version's host incompatible. + +import assert from "node:assert/strict" +import { after, it } from "node:test" + +import { + createOfferRegistry, + offerRegistryKey, + offerRegistryName, +} from "../../../packages/integration-kit/src/index.ts" +import { startFakeHost } from "../../../packages/testing/src/index.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { loadPlugin } from "./helpers.ts" + +const marker = readPackage().opencodeIntegration +const host = marker.host as NonNullable +const expected = { protocol: host.protocol, range: host.range, appVersions: host.appVersions } +const store = globalThis as unknown as Record +const keys = [offerRegistryKey("houdini"), offerRegistryKey(offerRegistryName("houdini", expected))] +after(() => { + for (const key of keys) delete store[key] +}) + +const announce = (fake: Awaited>, offerKey: string) => ({ + ...fake.endpoint, + script_handle: fake.scriptHandle, + label: "Houdini", + protocol: 1, + offer_key: offerKey, +}) + +it("a plugin loaded after an older version in the same process judges its own host ok", async () => { + const fake = await startFakeHost({ hostVersion: readPackage().version, appVersion: "22.0.429" }) + // What an older version created when it loaded: the kit's shared list under "houdini", with its own range. + const older = createOfferRegistry({ expected: { ...expected, range: "^0.1.0" } }) + store[offerRegistryKey("houdini")] = { generation: 2, registry: older } + const plugin = await loadPlugin({ shared: true }) + try { + assert.notEqual(plugin.registry, older, "this version keeps its own list") + assert.deepEqual(await plugin.rpc("advertise", announce(fake, "after-upgrade")), { outcome: "accepted" }) + assert.deepEqual( + plugin.registry.hosts().offers.map((offer) => offer.protocol), + ["ok"], + ) + await older.advertise(announce(fake, "after-upgrade")) + assert.equal(older.hosts().offers[0]?.protocol, "incompatible") + } finally { + await plugin.cleanup() + await fake.close() + } +}) + +it("a tool's error carries the host's own message and data", async () => { + const fake = await startFakeHost({ + hostVersion: readPackage().version, + appVersion: "22.0.429", + methods: { + context: () => { + throw { + code: "stale_revision", + message: "The Houdini graph changed after the intent was prepared: /obj/geo1", + data: { reason: "revision_conflict", expected_revision: 3, current_revision: 5 }, + } + }, + }, + }) + const plugin = await loadPlugin() + try { + await plugin.rpc("advertise", announce(fake, "errors")) + const offerID = plugin.registry.hosts().offers[0]?.offerID as string + assert.deepEqual(await plugin.rpc("attachHost", { offerID, sessionID: "ses_test" }), { outcome: "attached" }) + await assert.rejects(plugin.tool("context", { script_handle: fake.scriptHandle }), (error: Error) => { + assert.match( + error.message, + /\(stale_revision\): The Houdini graph changed after the intent was prepared: \/obj\/geo1/, + ) + assert.match(error.message, /"reason":"revision_conflict","expected_revision":3,"current_revision":5/) + return true + }) + } finally { + await plugin.cleanup() + await fake.close() + } +}) diff --git a/packages/integration-kit/README.md b/packages/integration-kit/README.md index de0234b..d097668 100644 --- a/packages/integration-kit/README.md +++ b/packages/integration-kit/README.md @@ -2,23 +2,23 @@ Shared core of the integration plugins: the plugin side of [`spec/README.md`](../../spec/README.md) (`spec: 0`, RPC contract 1). Each plugin bundles it into its build, so two integrations loaded in the same OpenCode daemon cannot diverge. It is not published to npm. -| Module | Role | -| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `types.ts` | Method manifest types (`methods/**.json`) | -| `method-registry.ts` | Loads the manifests of a plugin, sorted by name | -| `manifest-args.ts` | Validates and normalizes tool arguments against a manifest | -| `plugin-tools.ts` | Builds OpenCode V2 tools (`@opencode/plugin` 2.2) from manifests and registers them under the integration's namespace, honoring cancellation; executors return text or content parts (`ToolContent`, for attachments) | -| `coherence-check.ts` | Checks manifests, handlers and the tools mentioned by skills against each other | -| `marker.ts` | Marker types, the draft specification integer and ID helpers | -| `contract.ts` | RPC status contract 1: constants (lease, bounds), types, wire schemas (`rpcDefinition` registers them without `pattern`, which OpenCode 2.2.5 refuses), `advertise`/`withdraw` input validation, display bounds | -| `integration-rpc.ts` | `createIntegrationRpc`: handlers for `ctx.rpc.register`, `status` assembly, bounded `installHost`, payload-free event relay and lease sweeping | -| `offer-registry.ts` | Offer registry with injectable clock and hello transport; `sharedOfferRegistry` keeps it on `globalThis[Symbol.for("neuralnomads..offers")]`; `liveHellos()` also gives each live host's method table | -| `session-bindings.ts` | Per-Location exact native session snapshots, bounded lookups and synchronous registry/generation/revision fencing for reads, attachments and host access | -| `host-client.ts` | Loopback client of host wire protocol 1 (127.0.0.1 only, bounded, cancellable; errors never carry the endpoint, `HostError.detail` keeps the host's bounded explanation) | -| `hello.ts` | `hello` validation, canonical JSON and capability hash, compatibility with the marker's `host` block | -| `host-state.ts` | Derivation of `status.host.state`, WSL detection | -| `validators.ts`, `output.ts` | Small JSON helpers | -| `python/opencode_service.py` | Reference discovery client of headless hosts (standard library only): service registrations, the `global.config` Location with the `OPENCODE_CONFIG_DIR` fallback setting, `service-` targeting, capability hash. Host parts vendor it. | +| Module | Role | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | Method manifest types (`methods/**.json`) | +| `method-registry.ts` | Loads the manifests of a plugin, sorted by name | +| `manifest-args.ts` | Validates and normalizes tool arguments against a manifest | +| `plugin-tools.ts` | Builds OpenCode V2 tools (`@opencode/plugin` 2.2) from manifests and registers them under the integration's namespace, honoring cancellation; executors return text or content parts (`ToolContent`, for attachments) | +| `coherence-check.ts` | Checks manifests, handlers and the tools mentioned by skills against each other | +| `marker.ts` | Marker types, the draft specification integer and ID helpers | +| `contract.ts` | RPC status contract 1: constants (lease, bounds), types, wire schemas (`rpcDefinition` registers them without `pattern`, which OpenCode 2.2.5 refuses), `advertise`/`withdraw` input validation, display bounds | +| `integration-rpc.ts` | `createIntegrationRpc`: handlers for `ctx.rpc.register`, `status` assembly, bounded `installHost`, payload-free event relay and lease sweeping | +| `offer-registry.ts` | Offer registry with injectable clock and hello transport; `sharedOfferRegistry(app, options)` keeps one per host contract on `globalThis[Symbol.for("neuralnomads..offers")]` (`.protocol-

.part-.app-`), so a newer plugin version loaded without restarting OpenCode judges hellos by its own range; `liveHellos()` also gives each live host's method table | +| `session-bindings.ts` | Per-Location exact native session snapshots, bounded lookups and synchronous registry/generation/revision fencing for reads, attachments and host access | +| `host-client.ts` | Loopback client of host wire protocol 1 (127.0.0.1 only, bounded, cancellable; errors never carry the endpoint, a refusal's message carries the host's text and its `error.data` object, also kept as `HostError.data`; `HostError.detail` keeps its explanation without path separators) | +| `hello.ts` | `hello` validation, canonical JSON and capability hash, compatibility with the marker's `host` block | +| `host-state.ts` | Derivation of `status.host.state`, WSL detection | +| `validators.ts`, `output.ts` | Small JSON helpers | +| `python/opencode_service.py` | Reference discovery client of headless hosts (standard library only): service registrations, the `global.config` Location with the `OPENCODE_CONFIG_DIR` fallback setting, `service-` targeting, capability hash. Host parts vendor it. | Skill loading lives in the Blender pilot (`integrations/blender/plugin/src/skills.ts`) until a second integration needs it. @@ -36,10 +36,10 @@ Host discovery prepares each candidate Location with the integration's payload-f The kit reconciles the two OpenCode V2 migrations of the previous runtime, reviewed file by file: -| Module | Taken from | Notes | -| ---------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `plugin-tools.ts` | Verified V2 port (the M365 variant) | The only variant built on `@opencode/plugin` V2 `ToolEditor`/`Info`: namespaced tools, argument validation before execution, abort checks. The other variants still targeted the V1 `tool()` helper or a hand-written schema type. Checked against the 2.2.5 type definitions. | -| `manifest-args.ts`, `method-registry.ts`, `validators.ts`, `output.ts` | Shared runtime | Identical in every copy apart from line endings. | -| `coherence-check.ts` | Shared runtime | Unused import removed; `bundleName` renamed `integration`. | -| `types.ts` | Shared runtime | Bridge transport types removed with the host dispatcher; `requires.bridgeMethods` renamed `hostMethods`; `dangerous` flag added. | -| host dispatcher | Not taken | It inlined Python scripts from the npm package and sent them to the host's code-execution primitive, which the specification forbids: `native` hosts expose a fixed method table and never import code from the package. Its V2 cancellation fix lives on in `plugin-tools.ts`: executors receive the tool context and its abort `signal`. | +| Module | Taken from | Notes | +| ---------------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `plugin-tools.ts` | Verified V2 port (the M365 variant) | The only variant built on `@opencode/plugin` V2 `ToolEditor`/`Info`: namespaced tools, argument validation before execution, abort checks. The other variants still targeted the V1 `tool()` helper or a hand-written schema type. Checked against the 2.2.5 type definitions. | +| `manifest-args.ts`, `method-registry.ts`, `validators.ts`, `output.ts` | Shared runtime | Identical in every copy apart from line endings. | +| `coherence-check.ts` | Shared runtime | Unused import removed; `bundleName` renamed `integration`. | +| `types.ts` | Shared runtime | Bridge transport types removed with the host dispatcher; `requires.bridgeMethods` renamed `hostMethods`; `dangerous` flag added. | +| host dispatcher | Not taken | It inlined Python scripts from the npm package and sent them to the host's code-execution primitive. The kit keeps no such dispatcher: an integration that runs code in its application sends it through its own host method (Blender sends its fixed programs to its add-on's `execute_code`). Its V2 cancellation fix lives on in `plugin-tools.ts`: executors receive the tool context and its abort `signal`. | diff --git a/packages/integration-kit/src/host-client.ts b/packages/integration-kit/src/host-client.ts index 404e830..77be214 100644 --- a/packages/integration-kit/src/host-client.ts +++ b/packages/integration-kit/src/host-client.ts @@ -34,14 +34,44 @@ export class HostError extends Error { readonly code: string // The host's own explanation of a refusal, as bounded display text; never the endpoint. readonly detail: string | undefined - constructor(code: string, message: string, detail?: string) { + // The details the host gave with its refusal (`error.data`, a JSON object), such as the current revision. + readonly data: Record | undefined + constructor(code: string, message: string, detail?: string, data?: Record) { super(message) this.name = "HostError" this.code = code this.detail = detail + this.data = data } } +// What a refusal's message carries of the host's text and data, so that an agent reading the error reads them. +const MESSAGE_TEXT_MAX = 300 +const MESSAGE_DATA_MAX = 2_000 + +function refusalText(message: unknown) { + if (typeof message !== "string") return undefined + const clean = message + .replace(/\p{Cc}/gu, " ") + .replace(/\s+/g, " ") + .trim() + return clean ? [...clean].slice(0, MESSAGE_TEXT_MAX).join("") : undefined +} + +function refusalData(data: unknown): Record | undefined { + if (typeof data !== "object" || data === null || Array.isArray(data) || !Object.keys(data).length) return undefined + return data as Record +} + +function refusalMessage(code: string, text: string | undefined, data: Record | undefined) { + let message = `Host refused the request (${code})${text ? `: ${text}` : "."}` + if (data) { + const json = JSON.stringify(data) + message += ` ${json.length > MESSAGE_DATA_MAX ? `${json.slice(0, MESSAGE_DATA_MAX)}…` : json}` + } + return message +} + // Messages never carry the endpoint: port and token stay out of errors and logs. export async function requestHost( endpoint: HostEndpoint, @@ -95,14 +125,16 @@ export async function requestHost( id?: unknown ok?: unknown result?: unknown - error?: { code?: unknown; message?: unknown } + error?: { code?: unknown; message?: unknown; data?: unknown } } if (response.id !== id) return finish(new HostError("invalid_response", "Host returned an invalid envelope.")) if (response.ok === false) { const raw = response.error?.code const code = typeof raw === "string" && HOST_ERROR_CODES.includes(raw) ? raw : "internal" const detail = typeof response.error?.message === "string" ? boundedDetail(response.error.message) : undefined - return finish(new HostError(code, `Host refused the request (${code}).`, detail)) + const data = refusalData(response.error?.data) + const message = refusalMessage(code, refusalText(response.error?.message), data) + return finish(new HostError(code, message, detail, data)) } if (response.ok !== true || !("result" in response)) { return finish(new HostError("invalid_response", "Host returned an invalid envelope.")) diff --git a/packages/integration-kit/src/index.ts b/packages/integration-kit/src/index.ts index 58ceace..c81c87d 100644 --- a/packages/integration-kit/src/index.ts +++ b/packages/integration-kit/src/index.ts @@ -69,7 +69,13 @@ export { export type { MethodRegistry } from "./method-registry.ts" export { loadMethodRegistry } from "./method-registry.ts" export type { HelloProbe, HostBinding, OfferChange, OfferRegistry, OfferRegistryOptions } from "./offer-registry.ts" -export { createOfferRegistry, MAX_SESSIONS, offerRegistryKey, sharedOfferRegistry } from "./offer-registry.ts" +export { + createOfferRegistry, + MAX_SESSIONS, + offerRegistryKey, + offerRegistryName, + sharedOfferRegistry, +} from "./offer-registry.ts" export { errorToMessage, toJson } from "./output.ts" export type { ManifestExecutor, ToolContent } from "./plugin-tools.ts" export { buildPluginTools, buildToolInput, registerPluginTools } from "./plugin-tools.ts" diff --git a/packages/integration-kit/src/offer-registry.ts b/packages/integration-kit/src/offer-registry.ts index 073cf8a..037b539 100644 --- a/packages/integration-kit/src/offer-registry.ts +++ b/packages/integration-kit/src/offer-registry.ts @@ -387,13 +387,20 @@ const REGISTRY_GENERATION = 2 type RegistrySlot = { generation: number; registry: OfferRegistry } -export function offerRegistryKey(app: string) { - return Symbol.for(`neuralnomads.${app}.offers`) +export function offerRegistryKey(name: string) { + return Symbol.for(`neuralnomads.${name}.offers`) } -// The registry shared by every Location of the daemon process. +// The name of an application's shared offer list: it carries the contract the list judges hellos by. After an +// upgrade without restarting OpenCode, the older plugin version stays loaded in the same process; a list named +// after the application alone would judge the new version's application part by the older range. +export function offerRegistryName(app: string, expected: HostExpectation) { + return `${app}.protocol-${expected.protocol}.part-${expected.range}.app-${expected.appVersions}` +} + +// The registry shared by every Location of the daemon process that loaded this contract of `app`. export function sharedOfferRegistry(app: string, options: OfferRegistryOptions): OfferRegistry { - const key = offerRegistryKey(app) + const key = offerRegistryKey(offerRegistryName(app, options.expected)) const store = globalThis as unknown as Record const slot = store[key] if (slot?.generation === REGISTRY_GENERATION) return slot.registry diff --git a/packages/integration-kit/test/contract.test.ts b/packages/integration-kit/test/contract.test.ts index e5eebb9..f1b1683 100644 --- a/packages/integration-kit/test/contract.test.ts +++ b/packages/integration-kit/test/contract.test.ts @@ -16,6 +16,7 @@ import { isWslDaemon, MAX_OFFERS, offerRegistryKey, + offerRegistryName, parseAdvertiseInput, parseHello, parseWithdrawInput, @@ -515,13 +516,19 @@ describe("offer registry", () => { assert.deepEqual(strict.attach(offer?.offerID ?? "", "ses_1"), { outcome: "refused" }) }) - it("is shared by every module instance through Symbol.for", () => { - const key = offerRegistryKey("demo-shared") - assert.equal(key, Symbol.for("neuralnomads.demo-shared.offers")) + it("is shared by every module instance through Symbol.for, one list per host contract", () => { + const name = offerRegistryName("demo-shared", expected) + assert.equal(name, `demo-shared.protocol-${expected.protocol}.part-${expected.range}.app-${expected.appVersions}`) + const key = offerRegistryKey(name) + assert.equal(key, Symbol.for(`neuralnomads.${name}.offers`)) const one = sharedOfferRegistry("demo-shared", { expected }) const two = sharedOfferRegistry("demo-shared", { expected }) assert.equal(one, two) assert.ok((globalThis as unknown as Record)[key]) + // A plugin version expecting another host range, loaded in the same process, gets its own list. + const other = sharedOfferRegistry("demo-shared", { expected: { ...expected, range: "^9.0.0" } }) + assert.notEqual(other, one) + assert.equal(sharedOfferRegistry("demo-shared", { expected }), one) }) }) @@ -535,6 +542,16 @@ describe("host client and versions", () => { busy: () => { throw Object.assign(new Error("x"), { code: "busy" }) }, + refuse: () => { + throw { + code: "stale_revision", + message: "Node /obj/geo1\nchanged", + data: { current_revision: 4, reason: "revision_conflict" }, + } + }, + long: () => { + throw { code: "internal", message: "x".repeat(5_000), data: { blob: "y".repeat(10_000) } } + }, }, }) await assert.rejects(requestHost(host.endpoint, "leak"), (error: HostError) => { @@ -543,6 +560,22 @@ describe("host client and versions", () => { return true }) await assert.rejects(requestHost(host.endpoint, "busy"), (error: HostError) => error.code === "busy") + // The host's own message and data reach the error's message, which a tool's caller reads. + await assert.rejects(requestHost(host.endpoint, "refuse"), (error: HostError) => { + assert.equal(error.code, "stale_revision") + assert.equal( + error.message, + 'Host refused the request (stale_revision): Node /obj/geo1 changed {"current_revision":4,"reason":"revision_conflict"}', + ) + assert.equal(error.detail, "Node obj geo1 changed") + assert.deepEqual(error.data, { current_revision: 4, reason: "revision_conflict" }) + return true + }) + await assert.rejects(requestHost(host.endpoint, "long"), (error: HostError) => { + assert.ok(error.message.length < 2_400, String(error.message.length)) + assert.match(error.message, /^Host refused the request \(internal\): x{300} \{"blob":"y+…$/) + return true + }) await assert.rejects(requestHost({ ...host.endpoint, host: "localhost" }, "hello"), /127.0.0.1 only/) const wrongID = net.createServer((socket) => { socket.resume() diff --git a/packages/integration-kit/test/session-bindings.test.ts b/packages/integration-kit/test/session-bindings.test.ts index a12cc59..f7c0fb2 100644 --- a/packages/integration-kit/test/session-bindings.test.ts +++ b/packages/integration-kit/test/session-bindings.test.ts @@ -6,6 +6,7 @@ import { advanceBindingAuthority, createOfferRegistry, offerRegistryKey, + offerRegistryName, sharedOfferRegistry, } from "../src/offer-registry.ts" import { createSessionBindings } from "../src/session-bindings.ts" @@ -123,7 +124,7 @@ describe("binding authority", () => { symbol, { generation: number; registry: ReturnType } | undefined > - const key = offerRegistryKey(app) + const key = offerRegistryKey(offerRegistryName(app, expected)) try { const old = sharedOfferRegistry(app, { expected, hello: async () => hello }) await old.advertise(offer) diff --git a/packages/testing/src/fake-host.ts b/packages/testing/src/fake-host.ts index 88db9e1..2dbdef6 100644 --- a/packages/testing/src/fake-host.ts +++ b/packages/testing/src/fake-host.ts @@ -106,8 +106,15 @@ export async function startFakeHost(options: FakeHostOptions = {}): Promise) }) } catch (error) { - const code = (error as { code?: string }).code ?? "internal" - return reply({ id, ok: false, error: { code } }) + // A thrown Error answers its code alone; a thrown plain { code, message?, data? } is the host's refusal, + // answered as such. + const thrown = error as { code?: string; message?: unknown; data?: unknown } + const refusal: Record = { code: thrown.code ?? "internal" } + if (!(error instanceof Error)) { + if (typeof thrown.message === "string" && thrown.message) refusal.message = thrown.message + if (thrown.data !== undefined) refusal.data = thrown.data + } + return reply({ id, ok: false, error: refusal }) } }) socket.on("error", () => {}) diff --git a/spec/README.md b/spec/README.md index 2eee5ba..fec5418 100644 --- a/spec/README.md +++ b/spec/README.md @@ -91,10 +91,10 @@ withdraw({ offer_key, token }) => { outcome: "withdrawn" | "none" } ``` { "id", "token", "method", "params" } // at most 1 MiB -{ "id", "ok": true, "result" } | { "id", "ok": false, "error": { "code", "message"? } } // at most 8 MiB +{ "id", "ok": true, "result" } | { "id", "ok": false, "error": { "code", "message"?, "data"? } } // at most 8 MiB ``` -A request without the exact token gets `unauthorized`. The other error codes are `invalid_request`, `method_not_found`, `method_disabled`, `invalid_args`, `stale_handle`, `stale_revision`, `expectation_failed`, `mode_conflict`, `busy`, `quarantined`, `permission_denied` and `internal`; the plugin reads an unknown code as `internal`. `hello` answers: +A request without the exact token gets `unauthorized`. The other error codes are `invalid_request`, `method_not_found`, `method_disabled`, `invalid_args`, `stale_handle`, `stale_revision`, `expectation_failed`, `mode_conflict`, `busy`, `quarantined`, `permission_denied` and `internal`; the plugin reads an unknown code as `internal`. `message` is the application's explanation and `data` an object of details (such as the current revision, or the application's own code as `reason`); the plugin passes both on in the tool's error. `hello` answers: ```ts { protocol, host_version, app_version, capabilities: { methods, operations, undo, background },