repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/voice/__serial__/fixtures/speech-peer.mjs
Raw// Scripted adversarial peer for response+notification batches missing from fake-native.
// Test-only JSON control/text; no models, devices, network, or production fallback.
import { appendFileSync, existsSync, readFileSync, watch } from "node:fs";
import { dirname } from "node:path";
import { createInterface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
if (process.argv.length !== 4 || process.argv[3] !== "serve")
throw new Error("Expected script prefix followed by serve");
const script = JSON.parse(readFileSync(process.argv[2], "utf8"));
let index = 0;
let seq = 0;
let epoch = 1;
let renderFrame = 0;
const operations = new Map();
function waitForRelease(release) {
return new Promise((resolve, reject) => {
const directory = dirname(release.path);
let settled = false;
const finish = (error) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
watcher.close();
if (error) reject(error);
else resolve();
};
const watcher = watch(directory, { persistent: false }, () => {
if (!existsSync(release.path)) finish();
});
const timeout = setTimeout(
() => finish(new Error(`Timed out waiting for release ${release.path}`)),
5000,
);
if (!existsSync(release.path)) finish();
});
}
function notification(value) {
if (value.method === "operation.ended")
operations.delete(value.params.operation);
if (value.method === "playback.progress") {
renderFrame = Math.max(renderFrame, value.params.data.through_frame);
if (operations.has(value.params.operation))
operations.get(value.params.operation).frame =
value.params.data.through_frame;
}
return {
jsonrpc: "2.0",
method: value.method,
params: {
instance: "scripted",
seq: ++seq,
resource: "device",
epoch,
operation: null,
...value.params,
},
};
}
const input = createInterface({ input: process.stdin });
input.on("line", (line) => {
const request = JSON.parse(line);
appendFileSync(script.trace, `${line}\n`);
if (request.method === "service.shutdown") {
process.stdout.write(
`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { stopped: true } })}\n`,
() => process.exit(0),
);
return;
}
if (
request.method === "resource.close" &&
script.steps[index]?.method !== "resource.close"
) {
const frames = [...operations].map(([operation, value]) =>
notification({
method: "operation.ended",
params: {
operation,
data: {
outcome: "cancelled",
reason: "closed",
stop_frame: value.frame,
error: null,
},
},
}),
);
frames.push(
notification({
method: "resource.closed",
params: { data: { capture_frame: 0, render_frame: renderFrame } },
}),
);
frames.push({ jsonrpc: "2.0", id: request.id, result: { closed: true } });
process.stdout.write(
`${frames.map((frame) => JSON.stringify(frame)).join("\n")}\n`,
);
return;
}
const step = script.steps[index++];
if (
!step ||
step.method !== request.method ||
(step.params && !isDeepStrictEqual(step.params, request.params))
) {
process.stdout.write(
`${JSON.stringify({ jsonrpc: "2.0", id: request.id, error: { code: -32602, message: `Unexpected request ${request.method} at step ${index}` } })}\n`,
);
return;
}
const send = async () => {
if (step.releaseFile && !step.releaseFile.afterResult)
await waitForRelease(step.releaseFile);
if (step.result?.operation)
operations.set(step.result.operation, {
frame:
request.method === "synthesis.start" ||
request.method === "sound.play"
? 0
: null,
});
const before = (step.before ?? []).map(notification);
if (step.result?.epoch) epoch = step.result.epoch;
const response = [
...before,
{
jsonrpc: "2.0",
id: request.id,
...(step.error ? { error: step.error } : { result: step.result }),
},
];
if (step.releaseFile?.afterResult) {
process.stdout.write(
`${response.map((frame) => JSON.stringify(frame)).join("\n")}\n`,
);
await waitForRelease(step.releaseFile);
const after = (step.after ?? []).map(notification);
if (after.length)
process.stdout.write(
`${after.map((frame) => JSON.stringify(frame)).join("\n")}\n`,
);
return;
}
const frames = [...response, ...(step.after ?? []).map(notification)];
process.stdout.write(
`${frames.map((frame) => JSON.stringify(frame)).join("\n")}\n`,
);
};
void send().catch((error) => {
process.stderr.write(`${error.stack ?? error}\n`);
process.exit(1);
});
});
input.on("close", () => process.exit(0));