360 lines
13 KiB
JavaScript
360 lines
13 KiB
JavaScript
// delivery.js - sending, the queue and the turn gate.
|
|
//
|
|
// Plain ES module: no gpui-kit, no gpui-base, no herdr. The `hc` runner is
|
|
// injected (ctx.hc), so the whole delivery layer runs in plain Node
|
|
// (tests/delivery.test.mjs) without the app.
|
|
//
|
|
// The state model is the only writer: drain takes the state, moves the entry
|
|
// through `reduce` and hands a new state back. Nothing here changes a queue
|
|
// on its own.
|
|
//
|
|
// FACT (measured 2026-11-17 on herdr-core 0.1.16, `hc send --json`):
|
|
// `hc send` returns {"started":null,"status":null,"turn":0} and exits 0 - also
|
|
// for a plain shell with no agent, and also when it fails. Neither the exit
|
|
// code nor those fields say whether the agent got the message. Therefore:
|
|
// - ok:true means "the text was pasted and Enter pressed", NOT "the agent
|
|
// received it" - the UI says "Wysłano do terminala";
|
|
// - the only failure is a non-zero exit code (its stderr becomes the notice);
|
|
// - every `--json` call checks the payload for an "error" field, because `hc`
|
|
// exits 0 even on error (measured: `hc wait t3 --json` for a missing
|
|
// terminal -> {"error":{"kind":"not_found",...}}, exit 0);
|
|
// - a payload that is not JSON at all is an unknown result, not a success;
|
|
// - delivery confirmation comes from the agent's status (agents() /
|
|
// `hc get <t> --json`), never from the result of `hc send`;
|
|
// - exit codes are not mapped to meanings (9/11 - unproven, against the
|
|
// measurement);
|
|
// - the runner's `ok` flag carries no information the exit code does not
|
|
// already carry, so only the code and the payload are looked at.
|
|
|
|
import { reduce } from "./state.js";
|
|
|
|
/**
|
|
* @typedef {"idle"|"working"|"blocked"|"done"} Status
|
|
*
|
|
* @typedef {object} HcResult
|
|
* @property {boolean} [ok]
|
|
* @property {number} code
|
|
* @property {string} stdout
|
|
* @property {string} stderr
|
|
*
|
|
* @typedef {object} Ctx
|
|
* @property {string} terminal
|
|
* @property {(args:string[]) => Promise<HcResult>} hc
|
|
*
|
|
* @typedef {object} DrainCtx
|
|
* @property {string} agent - whose queue this is; the queue is `state.queue[agent]`
|
|
* @property {string} terminal
|
|
* @property {(args:string[]) => Promise<HcResult>} hc
|
|
* @property {() => Status} status
|
|
* @property {() => boolean} gate
|
|
* @property {(state:object) => void} [onState] - the caller persists the state
|
|
* here; it is called after every transition, the first time while the entry
|
|
* is on the wire (before the send runs), so a crash during the send leaves
|
|
* "sending" on disk and not "queued"
|
|
*
|
|
* @typedef {{ok:true} | {ok:false, code:number, message:string}} Result
|
|
* @typedef {{kind:"send"|"queue"|"hold"}} Decision
|
|
* @typedef {{state:object, sent:boolean, id?:string, reason?:string}} DrainResult
|
|
*
|
|
* @typedef {object} QueueItem
|
|
* @property {string} id
|
|
* @property {string} text
|
|
* @property {"queued"|"countdown"|"sending"|"held"|"uncertain"} state
|
|
* @property {number} createdAt
|
|
* @property {number} [left] - seconds to the send, while the state is "countdown"
|
|
* @property {string} [reason]
|
|
*/
|
|
|
|
/**
|
|
* What to do with a message, given the agent's status.
|
|
*
|
|
* @param {Status|string} status
|
|
* @returns {Decision}
|
|
*/
|
|
export function decide(status) {
|
|
switch (status) {
|
|
case "idle":
|
|
case "done":
|
|
return { kind: "send" };
|
|
case "working":
|
|
return { kind: "queue" };
|
|
case "blocked":
|
|
// The agent waits for an answer: what the person writes IS the answer,
|
|
// so it goes out at once. (The queue does not start on its own while
|
|
// the agent is blocked - see `shouldDrain`.)
|
|
return { kind: "send" };
|
|
default:
|
|
// A status we do not know (the core also reports "error") - wait for a
|
|
// known one instead of pasting into an agent that may not be there.
|
|
return { kind: "queue" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Does a change of the agent's status start the queue (the countdown)?
|
|
*
|
|
* Only the end of a turn does: the agent was working (or waiting for the
|
|
* person) and is idle or done now. A turn that the composer stopped itself
|
|
* (the Stop button, Esc) never starts anything.
|
|
*
|
|
* @param {Status|string} prev
|
|
* @param {Status|string} next
|
|
* @param {boolean} stoppedByComposer
|
|
* @returns {boolean}
|
|
*/
|
|
export function shouldDrain(prev, next, stoppedByComposer) {
|
|
if (stoppedByComposer) return false;
|
|
const was = prev === "working" || prev === "blocked";
|
|
const is = next === "idle" || next === "done";
|
|
return was && is;
|
|
}
|
|
|
|
/**
|
|
* Does the queue start counting down now? A rule of the state, not of a
|
|
* change: a turn that ended unseen (shorter than one poll) or a status that
|
|
* was unknown for a while must not leave a message waiting for ever.
|
|
*
|
|
* Yes when the agent is idle or done, an entry waits in the queue (`queued`;
|
|
* a `held` one does not count, an `uncertain` one in front of it does not
|
|
* block), nothing counts down or is on the wire, the turn gate is open and the
|
|
* composer did not stop the agent itself.
|
|
*
|
|
* @param {{status:Status|string, queue:QueueItem[], gateOpen:boolean, stopped:boolean}} input
|
|
* @returns {boolean}
|
|
*/
|
|
export function shouldStartCountdown({ status, queue, gateOpen, stopped }) {
|
|
if (stopped || !gateOpen) return false;
|
|
if (!ready(status)) return false;
|
|
if (!Array.isArray(queue)) return false;
|
|
if (queue.some((item) => item.state === "countdown" || item.state === "sending")) return false;
|
|
return queue.some((item) => item.state === "queued");
|
|
}
|
|
|
|
/**
|
|
* The turn gate: the next message goes out only after a whole turn was seen -
|
|
* the agent was working and then came back to idle/done. Without that
|
|
* transition a message could land in the middle of the agent's turn.
|
|
*
|
|
* @param {Status|string} status
|
|
* @param {boolean} seenWorking
|
|
* @returns {boolean}
|
|
*/
|
|
export function gateAfter(status, seenWorking) {
|
|
if (!seenWorking) return false;
|
|
return status === "idle" || status === "done";
|
|
}
|
|
|
|
/**
|
|
* The arguments of `hc send`.
|
|
*
|
|
* The text goes after `--`: a message that starts with a dash ("- fix bug",
|
|
* "--help") would otherwise be read by hc as an option and fail with a usage
|
|
* error. Everything after `--` is the text, whatever it looks like.
|
|
*
|
|
* `force` is `--force`: "type even if the program is blocked" (hc 0.1.21).
|
|
* Only the person's own Enter, answering an agent that waits for them, asks
|
|
* for it - the queue never does.
|
|
*
|
|
* @param {string} terminal
|
|
* @param {string} text
|
|
* @param {{force?:boolean}} [options]
|
|
* @returns {string[]}
|
|
*/
|
|
export function sendArgs(terminal, text, { force = false } = {}) {
|
|
return ["send", "--json", ...(force ? ["--force"] : []), terminal, "--", text];
|
|
}
|
|
|
|
/**
|
|
* The fields of the arguments `sendArgs` built - so a caller that watches
|
|
* the calls (the history) reads them by name, not by position.
|
|
*
|
|
* @param {unknown} args
|
|
* @returns {{terminal:string, text:string, force:boolean}|null} null when this is not a send
|
|
*/
|
|
export function parseSendArgs(args) {
|
|
if (!Array.isArray(args) || args[0] !== "send") return null;
|
|
const dashes = args.indexOf("--");
|
|
if (dashes < 0 || args.length !== dashes + 2) return null;
|
|
|
|
const terminal = args.slice(1, dashes).find((arg) => typeof arg === "string" && !arg.startsWith("-"));
|
|
if (typeof terminal !== "string" || typeof args[dashes + 1] !== "string") return null;
|
|
return { terminal, text: args[dashes + 1], force: args.slice(1, dashes).includes("--force") };
|
|
}
|
|
|
|
/**
|
|
* Paste the text into the terminal and press Enter.
|
|
*
|
|
* `ok:true` means the text was pasted - not that the agent read it. The only
|
|
* failure is a non-zero exit code, an "error" in the `--json` payload, or a
|
|
* payload that is not JSON at all.
|
|
*
|
|
* @param {Ctx} ctx
|
|
* @param {string} text
|
|
* @param {{force?:boolean}} [options] - `force`: type even if the agent is blocked
|
|
* @returns {Promise<Result>}
|
|
*/
|
|
export async function sendNow(ctx, text, options = {}) {
|
|
const res = await callHc(ctx, sendArgs(ctx.terminal, text, options));
|
|
|
|
if (res.failure) {
|
|
// The runner itself failed - there is no exit code to report.
|
|
return { ok: false, code: 0, message: res.failure };
|
|
}
|
|
|
|
if (res.code !== 0) {
|
|
return {
|
|
ok: false,
|
|
code: res.code,
|
|
message: res.stderr.trim() || `hc send zakończone kodem ${res.code}`,
|
|
};
|
|
}
|
|
|
|
const payload = parseJson(res.stdout);
|
|
if (!isPayload(payload)) {
|
|
// An unknown result is not a success: the text may or may not have gone
|
|
// out, so the caller must not treat this as delivered.
|
|
return { ok: false, code: res.code, message: "Nieznany wynik hc send" };
|
|
}
|
|
|
|
const failure = errorFrom(payload);
|
|
if (failure) return { ok: false, code: res.code, message: failure };
|
|
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Send the first queued entry of the agent's queue, if the agent is ready and
|
|
* the gate is open. The queue is `state.queue[ctx.agent]` - the queues are per
|
|
* agent, and the status and the gate belong to that one agent.
|
|
*
|
|
* The state model is the only writer: the entry is claimed (`sending`) before
|
|
* we wait for `hc`, so it is on the wire while the send runs. On success the
|
|
* entry leaves the queue; on a failure it becomes `uncertain` - never
|
|
* `queued`, because `hc` exits 0 even on error and the text may have gone
|
|
* out. Nothing is repeated on its own.
|
|
*
|
|
* Every transition is handed to `ctx.onState` (the caller persists it) before
|
|
* the next step - the first time while the entry is on the wire, so a crash
|
|
* during the send leaves `sending` on disk and the restart turns it into
|
|
* `uncertain` instead of sending the message a second time.
|
|
*
|
|
* The gate is the caller's (ctx.gate()); the caller also resets it (sawWorking
|
|
* = false) after a successful send.
|
|
*
|
|
* @param {DrainCtx} ctx
|
|
* @param {object} state - the composer's state
|
|
* @returns {Promise<DrainResult>}
|
|
*/
|
|
export async function drain(ctx, state) {
|
|
const agent = ctx.agent;
|
|
const items = state.queue?.[agent] ?? [];
|
|
const item = items.find(sendable);
|
|
if (!item) return { state, sent: false };
|
|
|
|
if (!ready(ctx.status())) return { state, sent: false };
|
|
if (!ctx.gate()) return { state, sent: false };
|
|
|
|
// On the wire before we wait for `hc`: a restart in the middle must find the
|
|
// entry as `sending` and turn it into `uncertain`.
|
|
const claimed = reduce(state, { type: "claim", agent, id: item.id });
|
|
ctx.onState?.(claimed);
|
|
|
|
const result = await sendNow(ctx, item.text);
|
|
|
|
if (result.ok) {
|
|
const sent = reduce(claimed, { type: "settle", agent, id: item.id, outcome: "sent" });
|
|
ctx.onState?.(sent);
|
|
return { state: sent, sent: true, id: item.id };
|
|
}
|
|
|
|
const failed = reduce(claimed, {
|
|
type: "settle",
|
|
agent,
|
|
id: item.id,
|
|
outcome: "uncertain",
|
|
reason: result.message,
|
|
});
|
|
ctx.onState?.(failed);
|
|
return { state: failed, sent: false, reason: result.message };
|
|
}
|
|
|
|
/**
|
|
* After a restart an entry that was on the wire is `uncertain`: the message
|
|
* may or may not have reached the agent, so it is never sent again on its own.
|
|
*
|
|
* @param {QueueItem[]} queue
|
|
* @returns {QueueItem[]}
|
|
*/
|
|
export function onRestart(queue) {
|
|
if (!Array.isArray(queue)) return [];
|
|
return queue.map((item) => {
|
|
if (item.state === "sending") return { ...item, state: "uncertain" };
|
|
if (item.state === "countdown") {
|
|
// Nothing goes out on its own after a restart.
|
|
const { left, ...rest } = item;
|
|
return { ...rest, state: "held" };
|
|
}
|
|
return item;
|
|
});
|
|
}
|
|
|
|
/** The agent can take the next message when it is not working and not blocked. */
|
|
function ready(status) {
|
|
// "done" counts as ready: the core reports "done" for a turn that finished
|
|
// unseen, and it turns into "idle" only once somebody looks at it
|
|
// (herdr-app src/model.rs:596-604). A queue that waited for "idle" would
|
|
// never drain for an agent nobody watches.
|
|
return status === "idle" || status === "done";
|
|
}
|
|
|
|
/** Only an entry that waits in the queue, or whose countdown ran out, may go out. */
|
|
function sendable(item) {
|
|
if (item?.state === "queued") return true;
|
|
return item?.state === "countdown" && !(item.left > 0);
|
|
}
|
|
|
|
/** Run `hc` and normalize what comes back. */
|
|
async function callHc(ctx, args) {
|
|
try {
|
|
const res = await ctx.hc(args);
|
|
return {
|
|
code: Number.isFinite(res?.code) ? res.code : 0,
|
|
stdout: typeof res?.stdout === "string" ? res.stdout : "",
|
|
stderr: typeof res?.stderr === "string" ? res.stderr : "",
|
|
failure: null,
|
|
};
|
|
} catch (err) {
|
|
return {
|
|
code: 0,
|
|
stdout: "",
|
|
stderr: "",
|
|
failure: err?.message ?? String(err),
|
|
};
|
|
}
|
|
}
|
|
|
|
/** The "error" of a `--json` payload, if it carries one. */
|
|
function errorFrom(payload) {
|
|
if (!payload.error) return null;
|
|
|
|
const err = payload.error;
|
|
if (typeof err === "string") return err;
|
|
if (typeof err.message === "string" && err.message) return err.message;
|
|
if (typeof err.kind === "string" && err.kind) return err.kind;
|
|
return JSON.stringify(err);
|
|
}
|
|
|
|
/** A `--json` payload is an object - anything else is an unknown result. */
|
|
function isPayload(value) {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
function parseJson(text) {
|
|
if (typeof text !== "string" || text.trim() === "") return null;
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|