S3 ask-once-ts: the TypeScript stdio asks once; the kind stopping goes

Builds: design 47 H2 H-A-570 (2) (3) (4)
This commit is contained in:
2026-11-25 17:05:11 +01:00
parent e5b66a77ba
commit a123ebd643
4 changed files with 53 additions and 79 deletions
+25 -43
View File
@@ -22,27 +22,10 @@ import { runAs } from "../callers/index.js";
/** The protocol version this speaks; the runtime says the same. */
export const PROTOCOL = "2025-03-26";
/** The typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542): the runtime's
* answer's `error-kind`, kept on the error as `errorKind`. */
export const ERROR_KIND_STOPPING = "stopping";
/** Whether err is a call a stopping tool runner did not take: told by its kind, never by its words (H-A-542). */
export function isStopping(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { errorKind?: unknown }).errorKind === ERROR_KIND_STOPPING;
}
/** The setting of how long a call is asked again while the tool runner is stopping, and its default: the Go stdio Ask's
* (H-A-544, H-A-549). */
/** The setting of how long a call waits for its answer, and its default: the Go stdio Ask's (design 47 H2 H-A-570 (4)). */
export const ASK_BOUND_SETTING = "ask-bound";
const DEFAULT_ASK_BOUND_MS = 60_000;
/** How a call waits between two asks while the tool runner is stopping, and its clock: a test's to replace, as the Go
* stdio's pause and askNow are, so nothing sleeps. */
export const askPacing = {
pause: (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms)),
now: (): number => Date.now(),
};
/** A duration setting as the node-engine composes it (MESH_CONFIG_<KEY>, design 47 H2 H-A-370), in milliseconds: Go's
* duration text ("1s", "250ms", "1m30s"); an absent setting is its default, one that is no duration is an error naming it. */
function settingMs(key: string, fallback: number): number {
@@ -60,31 +43,31 @@ function settingMs(key: string, fallback: number): number {
return ms;
}
/** Asks once and again, while the answer is the typed fault stopping, after a pause at the kept-call pace (the settings
* kept-call-pace-first and kept-call-pace-max, 1 s doubling to 30 s by default, as the Go stdio's Ask), until the new
* runner answers or the bound (the setting ask-bound, 60 s by default) ends; then the stopping fault is the caller's as such (H-A-542, H-A-544). A plain refusal
* and a bare timeout are never asked again. */
async function askAgainWhileStopping(key: string, once: () => Promise<unknown>): Promise<unknown> {
const start = askPacing.now();
/** Asks once, as the Go stdio's Ask does, and asks nothing again itself: a call its caller marks safe to repeat is called
* again by a kept call through no responders as through every transport fault. A call met by no responders is the runtime's
* refusal, returned as such; at the bound (the setting ask-bound, 60 s by default) the fault is "no answer within <bound>"
* (design 47 H2 H-A-570 (2), (4)). */
async function askWithinBound(once: () => Promise<unknown>): Promise<unknown> {
const bound = settingMs(ASK_BOUND_SETTING, DEFAULT_ASK_BOUND_MS);
let wait = settingMs("kept-call-pace-first", 1000);
const most = settingMs("kept-call-pace-max", 30_000);
for (;;) {
try {
return await once();
} catch (err) {
const left = bound - (askPacing.now() - start);
if (!isStopping(err) || wait >= left) {
if (isStopping(err)) (err as Error).message = `${key}: the tool runner was stopping, asked again until the bound of ${bound}ms: ${(err as Error).message}`;
throw err;
}
process.stderr.write(`[mesh-sdk] ${key}: the tool runner is stopping (${(err as Error).message}); asked again in ${wait}ms\n`);
await askPacing.pause(wait);
wait = Math.min(wait * 2, most);
}
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`no answer within ${boundText(bound)}`)), bound);
});
try {
return await Promise.race([once(), late]);
} finally {
clearTimeout(timer);
}
}
/** A bound as Go's duration prints it for the whole milliseconds a setting gives ("50ms", "10s", "1m0s"). */
function boundText(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const s = ms / 1000;
if (s < 60) return `${s}s`;
return `${Math.floor(s / 60)}m${s % 60}s`;
}
interface Request {
jsonrpc: string;
id?: number | string | null;
@@ -171,10 +154,9 @@ function startSession(): Session {
throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`);
}
},
// A call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound
// ends, as the Go stdio's Ask does (design 47 H2 H-A-542, H-A-544).
// A call is made once and its fault said at the bound, as the Go stdio's Ask does (design 47 H2 H-A-570 (2), (4)).
request: (async <Req, Res>(key: string, body: Req): Promise<Res> =>
(await askAgainWhileStopping(key, () => ask("mesh/ask", { key, body }))) as Res) as Broker["request"],
(await askWithinBound(() => 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"],
@@ -302,7 +284,7 @@ function startSession(): Session {
if (reply.method === undefined && typeof reply.id === "string" && awaiting.has(reply.id)) {
const waiting = awaiting.get(reply.id)!;
awaiting.delete(reply.id);
// A typed fault rides as the error's data `error-kind` (a stopping tool runner's stopping, H-A-542): kept as errorKind.
// A typed fault rides as the error's data `error-kind` (an `away`, §776): kept as errorKind.
if (reply.error) waiting.reject(Object.assign(new Error(reply.error.message ?? "the runtime refused"),
{ code: reply.error.code, errorKind: reply.error.data?.["error-kind"] }));
else waiting.resolve(reply.result);
+16
View File
@@ -0,0 +1,16 @@
// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or the
// words of its fault (design 47 H2 H-A-570 (2), (4)).
import { broker } from "../../dist/messaging/index.js";
import { registerModuleTools } from "../../dist/tools/index.js";
import { serveRegisteredOverStdio } from "../../dist/stdio/index.js";
registerModuleTools("builder", () => [
{ name: "publish", description: "asks the registry", input: {}, run: async () => {
try {
return { answer: await broker().request("seat:go-package-registry.publish", {}) };
} catch (err) {
return { words: err.message };
}
} },
]);
await serveRegisteredOverStdio();
-24
View File
@@ -1,24 +0,0 @@
// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or
// whether its fault was the typed fault stopping, and the pauses between its asks (design 47 H2 H-A-542, H-A-544,
// H-A-549). Its pause moves a clock instead of sleeping.
import { broker } from "../../dist/messaging/index.js";
import { registerModuleTools } from "../../dist/tools/index.js";
import { serveRegisteredOverStdio, isStopping, askPacing } from "../../dist/stdio/index.js";
let clock = 0;
let paused = [];
askPacing.now = () => clock;
askPacing.pause = async (ms) => { paused.push(ms); clock += ms; };
registerModuleTools("builder", () => [
{ name: "publish", description: "asks the registry", input: {}, run: async () => {
clock = 0;
paused = [];
try {
return { answer: await broker().request("seat:go-package-registry.publish", {}), paused };
} catch (err) {
return { stopping: isStopping(err), words: err.message, paused };
}
} },
]);
await serveRegisteredOverStdio();
+12 -12
View File
@@ -379,10 +379,10 @@ async function aBundlesFindingWriter(): Promise<void> {
}
}
test("a call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound ends; a plain refusal and a bare timeout are not (design 47 H2 H-A-542, H-A-544, H-A-549)", async () => {
const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-stopping.mjs", import.meta.url))],
test("a call is made once: no responders is returned after one ask, a reply of the withdrawn kind stopping is a refusal, and at the bound the fault is no answer within <bound> (design 47 H2 H-A-570 (2), (4))", async () => {
const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-ask.mjs", import.meta.url))],
{ stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, MESH_SERVED_MODULE: "builder",
MESH_CONFIG_KEPT_CALL_PACE_FIRST: "2s", MESH_CONFIG_KEPT_CALL_PACE_MAX: "4s", MESH_CONFIG_ASK_BOUND: "10s" } });
MESH_CONFIG_ASK_BOUND: "50ms" } });
const seen: any[] = [];
let buffered = "";
let said = "";
@@ -404,16 +404,16 @@ test("a call a stopping tool runner did not take is asked again after a pause un
try {
send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {} } });
await until((m) => m.id === 1);
const noResponders = { code: -32000, message: "nats: no responders available for request" };
for (const row of [
// The pace and the bound are the settings (2 s doubling to 4 s, a bound of 10 s, H-A-549); the pause moves a clock.
{ id: 2, answers: [{ error: stopping }, { error: stopping }, { result: { published: true } }],
want: { answer: { published: true }, paused: [2000, 4000] } },
{ id: 3, answers: [{ error: stopping }, { error: stopping }, { error: stopping }],
want: { stopping: true, words: `seat:go-package-registry.publish: the tool runner was stopping, asked again until the bound of 10000ms: ${stopping.message}`, paused: [2000, 4000] } },
{ id: 4, answers: [{ error: { code: -32000, message: "refused" } }], want: { stopping: false, words: "refused", paused: [] } },
{ id: 5, answers: [{ error: { code: -32000, message: "timeout" } }], want: { stopping: false, words: "timeout", paused: [] } },
{ id: 2, answers: [{ result: { published: true } }], want: { answer: { published: true } } },
{ id: 3, answers: [{ error: noResponders }], want: { words: noResponders.message } },
{ id: 4, answers: [{ error: stopping }], want: { words: stopping.message } },
{ id: 5, answers: [{ error: { code: -32000, message: "refused" } }], want: { words: "refused" } },
{ id: 6, answers: [], want: { words: "no answer within 50ms" } },
]) {
send({ jsonrpc: "2.0", id: row.id, method: "tools/call", params: { name: "publish", arguments: {} } });
if (row.answers.length === 0) await until((m) => m.method === "mesh/ask" && !m.answered).then((m) => { m.answered = true; });
for (const a of row.answers) {
const asked = await until((m) => m.method === "mesh/ask" && !m.answered);
assert.ok(asked, `the bundle did not ask again (row ${row.id})`);
@@ -422,9 +422,9 @@ test("a call a stopping tool runner did not take is asked again after a pause un
}
const done = await until((m) => m.id === row.id);
assert.deepEqual(JSON.parse(done.result.content[0].text), row.want);
assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${row.answers.length} times`);
assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${Math.max(row.answers.length, 1)} times`);
}
assert.match(said, /the tool runner is stopping/);
assert.doesNotMatch(said, /asked again/);
} finally {
child.kill();
}