T-3: a bundle's finding writer publishes with ack and listens with deliver new through the runtime channel

Builds: design 47 G §559 (the finding-calls word check waits on a design question)

Claude-Session: https://claude.ai/code/session_01JG73KEq4zoDfM9WtYpcQgZ
This commit is contained in:
2026-11-11 13:55:44 +01:00
parent 9dda6f7540
commit 37a288b749
6 changed files with 132 additions and 9 deletions
+22 -4
View File
@@ -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<Req, Res>(key: string, handler: (body: Req) => Promise<Res>): Promise<() => void>;
/** Emit an event onto the mesh. */
publish<T>(env: Envelope<T>): Promise<void>;
/** React to events matching a routing-key pattern. Returns an unsubscribe. */
subscribe<T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>): 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<T>(env: Envelope<T>, options?: PublishOptions): Promise<void>;
/**
* 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<T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>, options?: SubscribeOptions): Promise<() => void>;
close(): Promise<void>;
}
+13 -5
View File
@@ -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<unknown>) => Promise<void> }[] = [];
const viaRuntime: Broker = {
publish: async <T>(env: Envelope<T>) => {
await ask("mesh/publish", env);
publish: async <T>(env: Envelope<T>, 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 <Req, Res>(key: string, body: Req): Promise<Res> =>
(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 <T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>) => {
subscribe: (async <T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>, options?: SubscribeOptions) => {
const listener = { pattern, handler: handler as (env: Envelope<unknown>) => Promise<void> };
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).
+36
View File
@@ -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
// `<seat>.<event>`), 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<void>;
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" },
),
};
}
+1
View File
@@ -564,3 +564,4 @@ export function statusTools(
];
}
export * from "./writer.js";
export * from "./bundle.js";
+22
View File
@@ -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();
+38
View File
@@ -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();
}
});