From 37a288b749609c5c4154f6595d38241942b3e625 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 11 Nov 2026 13:55:44 +0100 Subject: [PATCH] T-3: a bundle's finding writer publishes with ack and listens with deliver new through the runtime channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds: design 47 G §559 (the finding-calls word check waits on a design question) Claude-Session: https://claude.ai/code/session_01JG73KEq4zoDfM9WtYpcQgZ --- src/messaging/index.ts | 26 +++++++++++++++--- src/stdio/index.ts | 18 +++++++++---- src/views/bundle.ts | 36 +++++++++++++++++++++++++ src/views/index.ts | 1 + test/fixtures/stdio-finding-calls.mjs | 22 ++++++++++++++++ test/stdio.test.ts | 38 +++++++++++++++++++++++++++ 6 files changed, 132 insertions(+), 9 deletions(-) create mode 100644 src/views/bundle.ts create mode 100644 test/fixtures/stdio-finding-calls.mjs diff --git a/src/messaging/index.ts b/src/messaging/index.ts index d717458b..56ad3cf6 100644 --- a/src/messaging/index.ts +++ b/src/messaging/index.ts @@ -7,6 +7,18 @@ import type { Envelope, EventHeaders } from "../contracts/index.js"; export type { Envelope, EventHeaders }; +/** How a publish is asked of the runtime. */ +export interface PublishOptions { + /** Resolve once the bus acknowledged the message (the runtime's `mesh/publish` takes `ack: true`). */ + readonly ack?: boolean; +} + +/** How a subscription is asked of the runtime. */ +export interface SubscribeOptions { + /** `new`: only messages published after the subscription (the runtime's `mesh/subscribe` takes `deliver: new`). */ + readonly deliver?: "new"; +} + /** A request/reply call and a publish/subscribe surface over the mesh broker. */ export interface Broker { /** Ask one question and await one answer — the client side; the shape mesh-controller's command @@ -15,10 +27,16 @@ export interface Broker { /** Answer a question — the server side of request/reply. A tool runtime serves invocations this * way. Returns an unregister. */ handle(key: string, handler: (body: Req) => Promise): Promise<() => void>; - /** Emit an event onto the mesh. */ - publish(env: Envelope): Promise; - /** React to events matching a routing-key pattern. Returns an unsubscribe. */ - subscribe(pattern: string, handler: (env: Envelope) => Promise): Promise<() => void>; + /** + * Emit an event onto the mesh. With `ack: true` a bundle's publish resolves only once the bus acknowledged it and + * rejects with the reason where it did not (design 47 G §559). + */ + publish(env: Envelope, options?: PublishOptions): Promise; + /** + * React to events matching a routing-key pattern. Returns an unsubscribe. With `deliver: "new"` the handler is given + * only the messages published after the subscription is made (design 47 G §559). + */ + subscribe(pattern: string, handler: (env: Envelope) => Promise, options?: SubscribeOptions): Promise<() => void>; close(): Promise; } diff --git a/src/stdio/index.ts b/src/stdio/index.ts index 375defd5..759a6139 100644 --- a/src/stdio/index.ts +++ b/src/stdio/index.ts @@ -14,7 +14,7 @@ */ import type { ToolDefinition } from "../contracts/index.js"; import { collectTools } from "../tools/index.js"; -import { useBroker, type Broker, type Envelope } from "../messaging/index.js"; +import { useBroker, type Broker, type Envelope, type PublishOptions, type SubscribeOptions } from "../messaging/index.js"; import { useStateChannel, type StateChange } from "../state/index.js"; import { useRuntime } from "../runtime/index.js"; import { runAs } from "../callers/index.js"; @@ -97,15 +97,23 @@ function startSession(): Session { // redelivered until it expires — the consumer's filter is the controller's and may be wider. const listeners: { pattern: string; handler: (env: Envelope) => Promise }[] = []; const viaRuntime: Broker = { - publish: async (env: Envelope) => { - await ask("mesh/publish", env); + publish: async (env: Envelope, options?: PublishOptions) => { + if (!options?.ack) { + await ask("mesh/publish", env); + return; + } + // The runtime answers an acknowledged publish with the bus's sequence, or `{error}` (design 47 G §559). + const answer = (await ask("mesh/publish", { ...env, ack: true })) as { error?: unknown } | null; + if (answer && typeof answer === "object" && answer.error !== undefined) { + throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`); + } }, request: (async (key: string, body: Req): Promise => (await ask("mesh/ask", { key, body })) as Res) as Broker["request"], handle: (async () => { throw new Error("a launched bundle answers through its tools, not by binding subjects (novox/hq ADR 0193)"); }) as Broker["handle"], - subscribe: (async (pattern: string, handler: (env: Envelope) => Promise) => { + subscribe: (async (pattern: string, handler: (env: Envelope) => Promise, options?: SubscribeOptions) => { const listener = { pattern, handler: handler as (env: Envelope) => Promise }; listeners.push(listener); const remove = (): void => { @@ -113,7 +121,7 @@ function startSession(): Session { if (at >= 0) listeners.splice(at, 1); }; try { - await ask("mesh/subscribe", { pattern }); + await ask("mesh/subscribe", options?.deliver ? { pattern, deliver: options.deliver } : { pattern }); } catch (err) { // Refused: nothing is bound, and a handler left behind would be handed each event twice once // the module asks again (novox/hq issue 276). diff --git a/src/views/bundle.ts b/src/views/bundle.ts new file mode 100644 index 00000000..227c3632 --- /dev/null +++ b/src/views/bundle.ts @@ -0,0 +1,36 @@ +// The finding writer's transport in a tools bundle (design 47 G §559): a bundle holds no bus connection, so the writer says +// each event through the runtime channel's `mesh/publish` with `ack: true` and makes its consumer of `findings-asked` +// through `mesh/subscribe` with `deliver: new`. The runtime publishes on the subject the module's membership names for the +// event, so the writer is handed the events' names (`finding-written`, and a seat's event by its local name +// `.`), not subjects. + +import { broker } from "../messaging/index.js"; +import type { EventHeaders } from "../contracts/index.js"; +import { randomUUID } from "node:crypto"; + +/** The `publish` and `listen` of a writer's options, over the runtime channel of the bundle's process. */ +export function bundleTransport(module = process.env.MESH_MODULE ?? "unknown", node = process.env.MESH_NODE ?? "unknown"): { + publish(event: string, body: unknown, id: string): Promise; + listen(event: string, handle: (body: unknown) => void): Promise<() => void>; +} { + return { + publish: async (event, body, id) => { + const headers: EventHeaders = { + "x-event-id": id || randomUUID(), + "x-source": module, + "x-node": node, + "x-time": new Date().toISOString(), + "content-type": "application/json", + }; + await broker().publish({ key: event, node, body, headers }, { ack: true }); + }, + listen: (event, handle) => + broker().subscribe( + event, + async (env) => { + handle(env.body); + }, + { deliver: "new" }, + ), + }; +} diff --git a/src/views/index.ts b/src/views/index.ts index 5496130f..903b8bcc 100644 --- a/src/views/index.ts +++ b/src/views/index.ts @@ -564,3 +564,4 @@ export function statusTools( ]; } export * from "./writer.js"; +export * from "./bundle.js"; diff --git a/test/fixtures/stdio-finding-calls.mjs b/test/fixtures/stdio-finding-calls.mjs new file mode 100644 index 00000000..0f35ac30 --- /dev/null +++ b/test/fixtures/stdio-finding-calls.mjs @@ -0,0 +1,22 @@ +// A launched bundle whose finding writer's transport is the bundle's (design 47 G §559): the writer's publish asks the +// runtime for an acknowledged publish, its consumer of the asks a subscription that delivers only new messages. +import { bundleTransport } from "../../dist/views/index.js"; +import { registerModuleTools } from "../../dist/tools/index.js"; +import { serveRegisteredOverStdio } from "../../dist/stdio/index.js"; + +const t = bundleTransport("keeper", "anchor"); +await t.listen("mesh-conditions.findings-asked", (b) => process.stderr.write(`asked ${JSON.stringify(b)}\n`)); +registerModuleTools("keeper", () => [ + { + name: "say", description: "says a finding", input: {}, + run: async () => { + try { + await t.publish("finding-written", { kind: "k" }, "id-1"); + return { said: true }; + } catch (e) { + return { said: false, why: String(e.message) }; + } + }, + }, +]); +await serveRegisteredOverStdio(); diff --git a/test/stdio.test.ts b/test/stdio.test.ts index 4a979531..31741f91 100644 --- a/test/stdio.test.ts +++ b/test/stdio.test.ts @@ -333,3 +333,41 @@ test("a launched bundle announces what it keeps as it is imported, and binds no child.kill(); } }); + +test("a bundle's finding writer publishes with ack and listens with deliver new through the runtime channel (design 47 G §559)", async () => { + const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-finding-calls.mjs", import.meta.url))], + { stdio: ["pipe", "pipe", "inherit"], env: { ...process.env, MESH_SERVED_MODULE: "keeper" } }); + const seen: any[] = []; + let buffered = ""; + child.stdout.on("data", (d) => { + buffered += d.toString(); + let at: number; + while ((at = buffered.indexOf("\n")) >= 0) { + seen.push(JSON.parse(buffered.slice(0, at))); + buffered = buffered.slice(at + 1); + } + }); + const until = async (match: (m: any) => boolean) => { + for (let i = 0; i < 150 && !seen.some(match); i++) await new Promise((r) => setTimeout(r, 20)); + return seen.find(match); + }; + const send = (m: unknown) => child.stdin.write(JSON.stringify(m) + "\n"); + try { + const sub = await until((m) => m.method === "mesh/subscribe"); + assert.deepEqual(sub.params, { pattern: "mesh-conditions.findings-asked", deliver: "new" }); + send({ jsonrpc: "2.0", id: sub.id, result: {} }); + send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {} } }); + await until((m) => m.id === 1); + send({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "say", arguments: {} } }); + const pub = await until((m) => m.method === "mesh/publish"); + assert.equal(pub.params.ack, true); + assert.equal(pub.params.key, "finding-written"); + assert.equal(pub.params.headers["x-event-id"], "id-1"); + // The runtime answers an unacknowledged publish with {error}: the writer's publish fails, so it sends again. + send({ jsonrpc: "2.0", id: pub.id, result: { error: "no stream" } }); + const answered = await until((m) => m.id === 2); + assert.deepEqual(JSON.parse(answered.result.content[0].text), { said: false, why: "the bus did not acknowledge finding-written: no stream" }); + } finally { + child.kill(); + } +});