@sema-agent/core
Version:
Stateless, task-oriented AI agent core
854 lines (853 loc) • 38.8 kB
JavaScript
import { A2A_STATE_TABLE } from "./a2a-task-state.js";
import { mintCompletionId } from "./completion-id.js";
import { admitNewPeerTask, isPeerTaskUnsettled, nextPeerTaskOnUpdate, peerTaskRequestDigest } from "./peer-task-store.js";
import { ProtocolRevokedRefusal } from "./protocol-revocation.js";
import { oweTerminalDelivery, peerTaskNotification } from "./task-notification.js";
import { occupantAdmits, stampActivity } from "./task-registry-shared.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { scopeKeyOf } from "./isolation-scope.js";
import { foreignLine } from "./protocol-http-auth.js";
import { strayMembersOf } from "./own-property-receipt.js";
export const PEER_TASK_FAILURE_CODES = Object.freeze({
internal_no_final_response: "a2a.internal_no_final_response",
external_no_response: "a2a.external_no_response",
peer_awaiting_own_approval: "a2a.peer_awaiting_own_approval",
peer_task_outcome_unknown: "a2a.peer_task_outcome_unknown",
});
export const PEER_TASK_TERMS_DEFAULTS = Object.freeze({
shortWaitMs: 20_000,
finalWithinMs: 600_000,
approvalWaitMs: 86_400_000,
ackWithinMs: Object.freeze({ inside: 120_000, outside: 600_000 }),
});
const POLL_FIRST_MS = 500;
const POLL_FACTOR = 2;
const POLL_MAX_MS = 30_000;
const TIMER_MAX_MS = 2_147_483_647;
const PEER_TASK_PERSON_EVENTS_MAX = 4;
const RESPOND_MEMBERS = Object.freeze(["shortWaitMs", "ackWithinMs", "finalWithinMs", "approvalWaitMs"]);
export function a2aRespondProblem(respond) {
if (respond === undefined)
return undefined;
if (typeof respond !== "object" || respond === null || Array.isArray(respond))
return "that is not an object of terms";
const stray = strayMembersOf(respond, { subject: "respond", unit: "term", moment: "where the declaration is read" }, RESPOND_MEMBERS);
if (stray !== undefined)
return `that it cannot read: ${stray.sentence}`;
const term = (member) => Reflect.get(respond, member);
for (const member of RESPOND_MEMBERS) {
const v = term(member);
if (v === undefined)
continue;
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0 || v > TIMER_MAX_MS)
return `whose ${member} is not a whole number of milliseconds from 0 to ${TIMER_MAX_MS}`;
}
const declaredFinal = term("finalWithinMs");
if (declaredFinal === 0)
return "whose finalWithinMs is 0 (a final deadline at the moment of dispatch)";
const final = typeof declaredFinal === "number" ? declaredFinal : PEER_TASK_TERMS_DEFAULTS.finalWithinMs;
for (const member of ["shortWaitMs", "ackWithinMs"]) {
const v = term(member);
if (typeof v === "number" && v > final)
return `whose ${member} is past the final deadline in force (${final} ms)`;
}
return undefined;
}
export function peerTaskTermsOf(respond, boundary) {
const finalWithinMs = respond?.finalWithinMs ?? PEER_TASK_TERMS_DEFAULTS.finalWithinMs;
return {
shortWaitMs: respond?.shortWaitMs ?? Math.min(PEER_TASK_TERMS_DEFAULTS.shortWaitMs, finalWithinMs),
ackWithinMs: respond?.ackWithinMs ?? Math.min(PEER_TASK_TERMS_DEFAULTS.ackWithinMs[boundary], finalWithinMs),
finalWithinMs,
approvalWaitMs: respond?.approvalWaitMs ?? PEER_TASK_TERMS_DEFAULTS.approvalWaitMs,
};
}
export function peerRowScopeOf(identity) {
return scopeKeyOf({ ...(identity.principal !== undefined ? { principal: identity.principal } : {}), ...(identity.isolationScope !== undefined ? { isolationScope: identity.isolationScope } : {}) });
}
const drivenHere = new Set();
function declaredPeerLabel(peer) {
return inlineUntrusted(peer, 120);
}
export function peerNoCompletionLaneText(peer) {
return `a2a: the call to peer "${declaredPeerLabel(peer)}" is not sent — no completion would come back from it here: a peer task answers by notification, and this call carries no completion lane. Mount the peer through a task (TaskSpec.a2a) run by a Runner.`;
}
export function peerFramesUndeclaredText(peer) {
return `a2a: the call to peer "${declaredPeerLabel(peer)}" is not sent — this deployment has not declared that its readers read peer_task notification frames (RunnerDeps.a2a.peerTaskFrames), so its answer could not be delivered. The deployment sets it once its hosts read them.`;
}
function refusedBeforeSend(text, peer, wire) {
return { content: [{ type: "text", text: text.slice(0, 600) }], details: wire.card({ peer }), isError: true, terminate: false };
}
const at = (ms) => new Date(ms).toISOString();
export async function dispatchPeerTask(d) {
const peer = d.destination.peer;
if (d.reach === undefined || d.reach.sink === undefined)
return refusedBeforeSend(peerNoCompletionLaneText(peer), peer, d.wire);
if (d.seat?.frames !== true)
return refusedBeforeSend(peerFramesUndeclaredText(peer), peer, d.wire);
const run = new PeerTaskRun(d, d.reach.registry, d.reach.sink, d.seat);
return run.start();
}
class PeerTaskRun {
d;
registry;
sink;
seat;
row;
handle;
abort = new AbortController();
key;
hardCap;
windowOpen = true;
framesOwed = false;
resolveWindow;
ended = false;
personEvents = 0;
unmounted = false;
onUnmount = () => {
this.unmounted = true;
if (this.row.status !== "running")
this.guarded(() => this.closeTail());
};
shown = {};
lastCard;
sendInFlight = false;
personTurn = false;
pollDelay = POLL_FIRST_MS;
pollTimer;
timers = new Set();
written = Promise.resolve();
storeState = "live";
constructor(d, registry, sink, seat) {
this.d = d;
this.registry = registry;
this.sink = sink;
this.seat = seat;
const id = registry.mintTaskId("peer_task");
if (seat.store !== undefined)
drivenHere.add(id);
this.key = `${d.access.scope}\u0000${id}`;
const now = Date.now();
const finalBy = now + d.terms.finalWithinMs;
this.hardCap = finalBy + d.terms.approvalWaitMs;
const sessionId = d.access.sessionId;
this.row = admitNewPeerTask({
task_id: id,
scope: d.access.scope,
rev: 0,
owner: d.access.owner,
sessionScoped: d.sessionScoped,
...(sessionId !== undefined && !d.sessionScoped ? { parentSessionId: sessionId } : {}),
...(d.access.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: d.access.rootSessionIncarnation } : {}),
...(d.dispatchingTaskId !== undefined ? { parentTaskId: d.dispatchingTaskId } : {}),
type: "peer_task",
destination: d.destination,
skillId: d.skillId,
...(d.fingerprint !== undefined ? { peerFingerprint: d.fingerprint } : {}),
messageId: d.messageId,
request: { paramsJson: d.paramsJson },
requestDigest: peerTaskRequestDigest(d.paramsJson),
submittedAt: now,
delivery: "recorded",
waitingFor: "unknown",
followUps: "not_accepted",
cancel: "not_requested",
ackBy: now + d.terms.ackWithinMs,
finalBy,
approvalWaitMs: d.terms.approvalWaitMs,
fallback: "stop_and_report",
lastSeq: 0,
status: "running",
}, () => this.key).row;
this.handle = registry.registerPeerTask({
id,
owner: d.access.owner,
scope: d.access.scope,
...(sessionId !== undefined ? { sessionId } : {}),
...(d.access.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: d.access.rootSessionIncarnation } : {}),
...(d.sessionScoped ? { sessionScoped: true } : {}),
...(d.dispatchingTaskId !== undefined ? { parentTaskId: d.dispatchingTaskId } : {}),
description: d.description,
toolUseId: d.toolUseId,
abort: this.abort,
lane: { poll: () => this.pollAnswer(), stop: () => this.stopAnswer() },
});
d.ledger?.memberDispatched?.(id, d.toolUseId);
this.abort.signal.addEventListener("abort", () => this.guarded(() => this.onStop()), { once: true });
if (!d.sessionScoped)
d.mount?.addEventListener("abort", this.onUnmount, { once: true });
}
get remoteTaskId() {
return this.row.remote?.taskId;
}
async start() {
const window = new Promise((resolve) => (this.resolveWindow = resolve));
if (this.seat.store !== undefined) {
await this.recorded(this.seat.store);
if (this.row.status !== "running")
return this.answer(await window);
}
this.advance({ delivery: "sent_unconfirmed" });
this.arm(this.row.finalBy, () => this.expire(), true);
this.arm(this.hardCap, () => this.closeTail(), false);
const windowTimer = this.d.completionComesBack ? setTimeout(() => this.closeWindow({ kind: "receipt" }), this.d.terms.shortWaitMs) : undefined;
const onCallAbort = () => this.closeWindow({ kind: "receipt" });
this.d.signal?.addEventListener("abort", onCallAbort, { once: true });
if (this.d.signal?.aborted === true)
onCallAbort();
this.detached(this.send());
const answer = await window;
clearTimeout(windowTimer);
this.d.signal?.removeEventListener("abort", onCallAbort);
return this.answer(answer);
}
async answer(answer) {
let minted;
try {
minted = { ok: answer.kind === "inline" ? this.endingAnswer(answer.result) : this.receipt(answer.words) };
}
catch (err) {
minted = { thrown: err };
}
if (this.seat.store !== undefined)
await this.written;
if ("thrown" in minted)
throw minted.thrown;
return minted.ok;
}
async recorded(store) {
const put = {};
const row = this.row;
this.written = Promise.resolve()
.then(() => store.put(row))
.then(undefined, (err) => {
this.storeState = "broken";
put.refused = { err };
});
await this.written;
if (put.refused === undefined)
return;
this.storeFault(put.refused.err, "a2a-peer-task-store-unrecorded");
this.settle({ status: "failed", summary: `The call to peer "${this.peerLabel}" was not sent: the deployment's peer task store could not record task ${row.task_id}.`, nothingSent: true });
}
persist(row) {
const store = this.seat.store;
if (store === undefined || this.storeState !== "live")
return;
this.written = this.written.then(async () => {
if (this.storeState !== "live")
return;
try {
if (await store.updateIf(row.task_id, row.scope, row, { rev: row.rev - 1 }))
return;
this.storeState = "lost";
this.storeFault(new Error(`peer task ${row.task_id}: the store no longer holds the row this lane wrote (moved by another writer, or deleted with its session) — this lane writes it no more`), "a2a-peer-task-store-lost");
}
catch (err) {
this.storeState = "broken";
this.storeFault(err, "a2a-peer-task-store-unwritten");
}
});
}
handOn(step) {
if (this.seat.store === undefined)
step();
else
void this.written.then(step);
}
leaveWhenWritten() {
if (this.seat.store === undefined)
return;
const tail = this.written;
void tail.then(() => {
if (this.written !== tail)
this.leaveWhenWritten();
else if (this.storeState === "live")
drivenHere.delete(this.row.task_id);
});
}
storeFault(err, classification) {
try {
this.seat.onError?.(err, { phase: "a2a", sessionId: this.d.access.sessionId ?? "", classification });
}
catch {
}
}
endingAnswer(result) {
const row = this.row;
if (row.status === "running")
return result();
const named = { task_id: row.task_id, status: row.status };
const line = `task_id: ${row.task_id} · ${row.status} (this answer is its ending)`;
let answer;
try {
answer = result();
}
catch (err) {
nameThrown(err, line, named);
throw err;
}
return { ...answer, content: [...answer.content, { type: "text", text: `\n${line}` }], details: { ...recordOf(answer.details), ...named } };
}
closeWindow(answer) {
if (!this.windowOpen)
return;
this.windowOpen = false;
if (answer.kind === "receipt" && this.d.completionComesBack) {
this.framesOwed = true;
oweTerminalDelivery(this.sink, { task_id: this.row.task_id, task_type: "peer_task" });
}
this.resolveWindow(answer);
}
async send() {
this.sendInFlight = true;
let observation;
try {
observation = await this.d.wire.send(this.d.paramsJson, this.abort.signal);
}
catch (err) {
this.sendInFlight = false;
if (this.abort.signal.aborted)
return;
if (err instanceof ProtocolRevokedRefusal) {
this.revoked(err, () => this.d.wire.revoked(err), err.afterSentHop !== true);
return;
}
const code = codeOf(err);
const words = this.d.wire.failure(err);
if (this.row.status === "running")
this.settle({ status: "failed", ...(code !== undefined ? { code } : {}), summary: `The call to peer "${this.peerLabel}" failed before it answered task ${this.row.task_id}.`, words, inline: () => { throw err; } });
else
this.closeTail();
return;
}
this.sendInFlight = false;
this.observe(observation);
}
observe(o) {
if (this.ended)
return;
const changed = this.row.remote?.stateClass !== o.remote.stateClass;
const remote = { ...o.remote, stateChangedAt: changed || this.row.remote?.stateChangedAt === undefined ? Date.now() : this.row.remote.stateChangedAt };
if (this.row.status !== "running") {
if (o.ending !== undefined) {
this.took(() => this.lateArrival(o, remote));
return;
}
if (!this.took(() => this.advance({ delivery: "accepted", remote })))
return;
this.shown = o.shown;
this.lastCard = o.details;
this.schedulePoll();
return;
}
if (o.ending !== undefined) {
if (this.took(() => this.settleFromPeer(o, remote)))
this.shown = o.shown;
return;
}
const classWaits = o.remote.stateClass !== undefined ? A2A_STATE_TABLE[o.remote.stateClass].waitingFor : undefined;
const person = classWaits === "caller" || classWaits === "peer_approver";
if (!this.took(() => this.advance({ delivery: "accepted", remote, waitingFor: o.waitingFor ?? "unknown" })))
return;
this.shown = o.shown;
this.lastCard = o.details;
const turnStarts = person && (!this.personTurn || changed);
this.personTurn = person;
if (this.windowOpen) {
if (person && this.d.completionComesBack)
this.closeWindow({ kind: "receipt", words: o.words });
else if (person) {
this.closeWindow({ kind: "inline", result: () => o.inline() });
this.end();
return;
}
}
else if (this.framesOwed && turnStarts && this.personEvents < PEER_TASK_PERSON_EVENTS_MAX) {
this.personEvents++;
this.frame("event", { summary: this.waitingSentence(this.row.waitingFor), result: o.words });
}
this.schedulePoll();
}
took(step) {
try {
step();
return true;
}
catch (err) {
if (!(err instanceof RowContractRefusal))
throw err;
if (this.row.status === "running") {
this.settle({ status: "failed", summary: `Peer "${this.peerLabel}" answered task ${this.row.task_id} with a task this row cannot take (a task id other than the one it gave, or a task that is not over and names none); nothing more is asked of it, and it may still be working.` });
}
else
this.closeTail();
return false;
}
}
settleFromPeer(o, remote) {
const label = this.peerLabel;
const from = { words: o.words, inline: () => o.inline(), remoteEnded: true, remote };
if (o.ending === "completed")
this.settle({ status: "completed", summary: `Peer "${label}" (${this.skillLabel}) finished task ${this.row.task_id}.`, ...from });
else if (o.ending === "cancelled")
this.settle({ status: "cancelled", summary: `Peer "${label}" cancelled task ${this.row.task_id} on its own side.`, ...from });
else
this.settle({ status: "failed", summary: `Peer "${label}" ended task ${this.row.task_id} as ${o.shown.state ?? "failed"}.`, ...from });
}
expire() {
if (this.row.status !== "running")
return;
const label = this.peerLabel;
const finalBy = at(this.row.finalBy);
const tail = this.hardCap > Date.now();
if (this.d.destination.boundary === "outside") {
this.settle({ status: "failed", code: PEER_TASK_FAILURE_CODES.external_no_response, summary: `Peer "${label}" did not answer by ${finalBy}. For an outside peer this is a possible outcome. No stop was requested from it; it may still be working. Act on your plan.`, tail });
}
else if (this.row.waitingFor === "peer_approver") {
this.settle({ status: "failed", code: PEER_TASK_FAILURE_CODES.peer_awaiting_own_approval, summary: `Peer "${label}" had no answer by ${finalBy}: it is waiting for an approval on its own side. This is not a fault. No stop was requested from it; its answer is still watched until ${at(this.hardCap)}. Act on your plan.`, tail });
}
else {
const summary = `Peer "${label}" did not give a final answer by ${finalBy}. For an inside peer this is a fault and it was recorded for operations. Act on the plan you set when you sent the task.`;
const fault = Object.assign(new Error(`a2a: peer task ${this.row.task_id} to inside peer "${label}" (${this.skillLabel}) had no final answer by ${finalBy}`), { code: PEER_TASK_FAILURE_CODES.internal_no_final_response });
try {
this.seat.onError?.(fault, { phase: "a2a", sessionId: this.d.access.sessionId ?? "", classification: "a2a-internal-no-final-response" });
}
catch {
}
this.settle({ status: "failed", code: PEER_TASK_FAILURE_CODES.internal_no_final_response, summary, tail });
}
}
revoked(err, inline, nothingSent) {
if (this.row.status !== "running") {
this.closeTail();
return;
}
this.settle({
status: "failed",
code: err.code,
summary: `Peer "${this.peerLabel}" ${err.why === "unreadable" ? "could not be checked against the revocation ledger" : "was revoked by the operator"} while task ${this.row.task_id} was in flight; nothing more is sent to it${nothingSent ? " (the request itself was not sent)" : ", and it may still be working"}.`,
inline,
nothingSent,
});
}
onStop() {
if (this.row.status !== "running") {
this.closeTail();
return;
}
const stoppedBy = this.handle.stopSource ?? "parent";
const runEnd = this.handle.stopRunEnd;
this.settle({
status: "killed",
summary: `No longer waiting for peer "${this.peerLabel}" on task ${this.row.task_id}; no stop was requested from it (it does not accept one), so it may still be working.`,
stoppedBy,
...(runEnd !== undefined ? { runEnd } : {}),
});
}
settle(s) {
if (this.row.status !== "running")
return;
const word = s.status;
const outcome = {
kind: "peer_task",
outcome: word,
...(s.code !== undefined ? { code: s.code } : {}),
...(s.status === "killed" && s.stoppedBy !== undefined ? { stoppedBy: s.stoppedBy } : {}),
...(s.status === "killed" && s.runEnd !== undefined ? { runEnd: { cause: s.runEnd } } : {}),
provenance: "live",
};
const remoteEnded = s.remoteEnded === true || (this.row.remote?.stateClass !== undefined && A2A_STATE_TABLE[this.row.remote.stateClass].waitingFor === undefined);
const sent = this.row.delivery !== "recorded" && s.nothingSent !== true;
const remoteMayContinue = sent && !remoteEnded && this.row.cancel !== "confirmed";
const tail = s.tail === true && this.framesOwed && remoteMayContinue && (this.remoteTaskId !== undefined || this.sendInFlight) && !this.unmounted;
const completionId = mintCompletionId(this.handle);
const frameOwed = this.framesOwed;
this.advance({
...(s.remote !== undefined ? { delivery: "accepted", remote: s.remote } : {}),
status: s.status,
outcome,
settledAt: Date.now(),
waitingFor: undefined,
...(remoteMayContinue ? { remoteMayContinue: true } : {}),
...(tail ? { overdueTail: { until: this.hardCap } } : {}),
});
this.handle.status = s.status;
this.handle.outcome = outcome;
if (s.status === "killed" && s.stoppedBy !== undefined)
this.handle.stoppedBy = s.stoppedBy;
stampActivity(this.handle);
this.registry.notePeerTaskSettled(this.row.task_id);
if (!tail)
this.end();
if (frameOwed) {
this.frame(s.status, {
summary: s.summary,
...(s.words !== undefined ? (s.status === "completed" ? { result: s.words } : { error: s.words }) : s.status === "failed" ? { error: s.summary } : {}),
...(s.code !== undefined ? { errorCode: s.code } : {}),
...(s.status === "killed" && s.stoppedBy !== undefined ? { stoppedBy: s.stoppedBy } : {}),
outcome,
completionId,
});
}
else {
const inline = s.inline ?? (() => ({ content: [{ type: "text", text: s.summary }], details: this.d.wire.card({ kind: "peer_task", task_id: this.row.task_id, status: s.status, ...(s.code !== undefined ? { code: s.code } : {}) }), isError: s.status !== "completed", terminate: false }));
this.closeWindow({ kind: "inline", result: inline });
}
}
lateArrival(o, remote) {
this.advance({ delivery: "accepted", remote, overdueTail: undefined, remoteMayContinue: undefined });
this.frame("event", {
summary: `Peer "${this.peerLabel}" answered task ${this.row.task_id} after its deadline (${o.ending === "completed" ? "it finished" : o.ending === "cancelled" ? "it cancelled the task" : "it failed"}); the row's ending stands. Its answer is below.`,
result: o.words,
overdueTail: true,
});
this.end();
}
closeTail() {
if (this.ended)
return;
if (this.row.status === "running")
return;
if (this.row.overdueTail !== undefined)
this.advance({ overdueTail: undefined });
this.end();
}
end() {
this.ended = true;
if (this.pollTimer !== undefined)
clearTimeout(this.pollTimer);
this.pollTimer = undefined;
for (const t of this.timers)
clearTimeout(t);
this.timers.clear();
this.d.mount?.removeEventListener("abort", this.onUnmount);
if (!this.abort.signal.aborted)
this.abort.abort();
this.leaveWhenWritten();
}
schedulePoll() {
if (this.ended || this.remoteTaskId === undefined || this.pollTimer !== undefined)
return;
const delay = this.pollDelay;
this.pollDelay = Math.min(this.pollDelay * POLL_FACTOR, POLL_MAX_MS);
const remoteTaskId = this.remoteTaskId;
this.pollTimer = setTimeout(() => {
this.pollTimer = undefined;
if (this.row.status !== "running" && Date.now() >= this.hardCap)
this.guarded(() => this.closeTail());
else
this.detached(this.pollOnce(remoteTaskId));
}, delay);
if (this.row.status !== "running")
this.pollTimer.unref?.();
}
async pollOnce(remoteTaskId) {
if (this.ended)
return;
let o;
try {
o = await this.d.wire.poll(remoteTaskId, this.abort.signal);
}
catch (err) {
if (this.ended || this.abort.signal.aborted)
return;
if (err instanceof ProtocolRevokedRefusal) {
const accepted = { taskId: this.shown.taskId };
this.revoked(err, () => this.d.wire.revoked(err, accepted), false);
return;
}
if (this.row.status === "running" && this.d.wire.answeredByPeer(err)) {
this.settle({ status: "failed", summary: `Peer "${this.peerLabel}" answered an ask after task ${this.row.task_id} with an error; nothing more is asked of it.`, words: this.d.wire.failure(err), inline: () => { throw err; } });
return;
}
this.schedulePoll();
return;
}
this.observe(o);
}
detached(step) {
step.catch((err) => this.faulted(err));
}
guarded(step) {
try {
step();
}
catch (err) {
this.faulted(err);
}
}
faulted(err) {
try {
this.seat.onError?.(err, { phase: "a2a", sessionId: this.d.access.sessionId ?? "", classification: "a2a-peer-task-lane-fault" });
}
catch {
}
if (this.row.status === "running") {
try {
this.settle({ status: "failed", summary: `The lane driving task ${this.row.task_id} for peer "${this.peerLabel}" failed; the task is no longer watched.` });
return;
}
catch {
}
}
this.end();
}
arm(at, fire, ref) {
const step = Math.max(0, Math.min(at - Date.now(), TIMER_MAX_MS));
const t = setTimeout(() => {
this.timers.delete(t);
if (Date.now() < at)
this.arm(at, fire, ref);
else
this.guarded(fire);
}, step);
if (!ref)
t.unref?.();
this.timers.add(t);
}
frame(status, f) {
const seq = this.row.lastSeq + 1;
this.advance({ lastSeq: seq });
const row = this.row;
const payload = peerTaskNotification({
task_id: row.task_id,
status,
seq,
summary: f.summary,
...(f.result !== undefined ? { result: f.result } : {}),
...(f.error !== undefined ? { error: f.error } : {}),
...(f.errorCode !== undefined ? { errorCode: f.errorCode } : {}),
...(f.stoppedBy !== undefined ? { stoppedBy: f.stoppedBy } : {}),
...(f.outcome !== undefined ? { outcome: f.outcome } : {}),
...(f.completionId !== undefined ? { completionId: f.completionId } : {}),
...(f.overdueTail === true ? { overdueTail: true } : {}),
peerTask: {
destination: row.destination,
followUps: row.followUps,
cancel: row.cancel,
ackBy: row.ackBy,
finalBy: row.finalBy,
...(row.waitingFor !== undefined ? { waitingFor: row.waitingFor } : {}),
...(row.remoteMayContinue === true ? { remoteMayContinue: true } : {}),
},
});
this.handOn(() => {
try {
const out = this.sink(payload, { priority: "next" });
if (out !== null && typeof out === "object" && typeof out.then === "function")
Promise.resolve(out).catch(() => undefined);
}
catch {
}
});
}
advance(patch) {
const candidate = { ...this.row };
for (const [k, v] of Object.entries(patch)) {
if (v === undefined)
Reflect.deleteProperty(candidate, k);
else
Reflect.set(candidate, k, v);
}
const next = nextPeerTaskOnUpdate(this.row, this.key, this.row.task_id, this.row.scope, candidate, { rev: this.row.rev });
if (next === null)
throw new RowContractRefusal(`peer task ${this.row.task_id}: the lane wrote a transition the row contract refuses`);
this.row = next;
this.persist(next);
}
get peerLabel() {
return declaredPeerLabel(this.d.destination.peer);
}
get skillLabel() {
return this.d.description;
}
waitingSentence(w) {
const label = this.peerLabel;
const id = this.row.task_id;
if (w === "caller")
return `Peer "${label}" is asking you something on task ${id} — its message is below.`;
if (w === "peer_approver")
return `Peer "${label}" is waiting for an approval on its own side for task ${id}. Nothing is needed from you; the final deadline ${at(this.row.finalBy)} stands.`;
if (w === "peer")
return `Peer "${label}" is working on task ${id} again.`;
return `Peer "${label}" reports a state on task ${id} that does not say whom it waits on; the final deadline ${at(this.row.finalBy)} stands.`;
}
receipt(words) {
const row = this.row;
const remote = row.remote;
const state = remote?.state !== undefined ? `state: ${foreignLine(remote.state, 40)}` : row.delivery === "accepted" ? "state: accepted" : "delivery not yet confirmed";
const lines = [
`${row.delivery === "accepted" ? `Peer "${this.peerLabel}" (${this.skillLabel}) accepted the request.` : `The request to "${this.peerLabel}" (${this.skillLabel}) has no answer yet; whether it has reached the peer is not known.`} Not finished yet — it continues in the background.`,
`task_id: ${row.task_id} · ${state}`,
`deadline: final answer by ${at(row.finalBy)}`,
...(words !== undefined ? [words] : []),
this.d.completionComesBack
? "You will be notified when it settles, when it needs something from you, or when the deadline passes. Do not poll and do not send the request again."
: "This run ends before its answer could come back, so nothing more about it reaches you. Do not send the request again.",
`This peer does not accept additions or reminders after submission.${this.d.taskStopMounted ? ` To stop waiting: TaskStop({ task_id: "${row.task_id}" }).` : ""}`,
"This deployment does not keep waiting across a restart.",
`Decide now what you will do if no answer arrives by ${at(row.finalBy)}.`,
];
return {
content: [{ type: "text", text: lines.join("\n") }],
details: this.d.wire.card({
...this.lastCard,
kind: "peer_task",
task_id: row.task_id,
delivery: row.delivery,
peerTask: { destination: row.destination, followUps: row.followUps, cancel: row.cancel, ackBy: row.ackBy, finalBy: row.finalBy, ...(row.waitingFor !== undefined ? { waitingFor: row.waitingFor } : {}) },
}),
terminate: false,
};
}
pollAnswer() {
const row = this.row;
const settled = row.status !== "running";
const content = settled
? `${row.task_id} ${row.status}${row.outcome?.code !== undefined ? ` (${row.outcome.code})` : ""} — its notification carried the ending${row.overdueTail !== undefined ? `; the peer is still watched until ${at(row.overdueTail.until)}` : ""}.`
: `${row.task_id} running — peer "${this.peerLabel}", ${row.waitingFor !== undefined ? `waiting on ${row.waitingFor}` : "no state read yet"}; final answer by ${at(row.finalBy)}. You will be notified; do not poll.`;
return {
content,
details: {
task_id: row.task_id,
type: "peer_task",
status: row.status,
retrieval_status: settled ? "success" : "not_ready",
...(row.status === "killed" && this.handle.stoppedBy !== undefined ? { stoppedBy: this.handle.stoppedBy } : {}),
...(row.outcome !== undefined ? { outcome: row.outcome } : {}),
...(this.handle.completionId !== undefined ? { completionId: this.handle.completionId } : {}),
...(row.outcome?.code !== undefined ? { errorCode: row.outcome.code } : {}),
},
};
}
async stopAnswer() {
const wasRunning = this.row.status === "running";
if (!this.abort.signal.aborted)
this.abort.abort();
const minted = this.stopRead(wasRunning);
if (this.seat.store !== undefined)
await this.written;
return minted;
}
stopRead(wasRunning) {
const row = this.row;
return {
content: wasRunning
? `Terminated ${row.task_id}: no longer waiting for peer "${this.peerLabel}". No stop was requested from it (it does not accept one), so it may still be working.`
: `${row.task_id} already ${row.status} — nothing to stop${row.overdueTail !== undefined ? "" : "; the peer is no longer watched"}.`,
details: {
task_id: row.task_id,
type: "peer_task",
status: row.status,
retrieval_status: "success",
...(row.status === "killed" && this.handle.stoppedBy !== undefined ? { stoppedBy: this.handle.stoppedBy } : {}),
},
};
}
}
export async function settleOrphanedPeerRows(seat) {
const frames = [];
const fault = (err) => {
try {
seat.onError?.(err, { phase: "a2a", sessionId: seat.sessionId, classification: "a2a-peer-task-restart-settle" });
}
catch {
}
};
let listed;
try {
listed = await seat.store.listBySession(seat.scope, seat.sessionId);
}
catch (err) {
fault(err);
return frames;
}
for (const s of listed) {
if ("rowVerdict" in s || !isPeerTaskUnsettled(s) || drivenHere.has(s.task_id))
continue;
if ((s.sessionScoped ? s.owner : s.parentSessionId) !== seat.sessionId)
continue;
if (!occupantAdmits(s, seat.occupant !== undefined ? { rootSessionIncarnation: seat.occupant } : {}))
continue;
try {
const row = await seat.store.get(s.task_id, seat.scope);
if (row === null || !isPeerTaskUnsettled(row) || drivenHere.has(row.task_id))
continue;
const running = row.status === "running";
const next = running ? orphanSettled(row) : tailClosed(row);
const frame = running ? orphanFrame(next) : undefined;
if (!(await seat.store.updateIf(row.task_id, seat.scope, next, { rev: row.rev })))
continue;
if (frame !== undefined)
frames.push(frame);
}
catch (err) {
fault(err);
}
}
return frames;
}
function orphanSettled(row) {
const next = {
...row,
status: "failed",
outcome: { kind: "peer_task", outcome: "failed", code: PEER_TASK_FAILURE_CODES.peer_task_outcome_unknown, provenance: "live" },
settledAt: Date.now(),
remoteMayContinue: true,
lastSeq: row.lastSeq + 1,
};
Reflect.deleteProperty(next, "waitingFor");
return next;
}
function tailClosed(row) {
const next = { ...row };
Reflect.deleteProperty(next, "overdueTail");
return next;
}
function orphanFrame(row) {
const summary = `The peer task ${row.task_id} for peer "${declaredPeerLabel(row.destination.peer)}" was not settled when the process waiting on it stopped. Whether the peer finished it is not known, and it may still be working; nothing more is asked of it here.`;
return peerTaskNotification({
task_id: row.task_id,
status: "failed",
seq: row.lastSeq,
summary,
error: summary,
errorCode: PEER_TASK_FAILURE_CODES.peer_task_outcome_unknown,
...(row.outcome !== undefined ? { outcome: row.outcome } : {}),
peerTask: { destination: row.destination, followUps: row.followUps, cancel: row.cancel, ackBy: row.ackBy, finalBy: row.finalBy, remoteMayContinue: true },
});
}
const recordOf = (v) => (typeof v === "object" && v !== null && !Array.isArray(v) ? v : {});
function nameThrown(err, line, named) {
if (!(err instanceof Error))
return;
const hadDetails = Object.prototype.hasOwnProperty.call(err, "details");
const prior = Reflect.get(err, "details");
try {
if (!Reflect.set(err, "details", { ...recordOf(prior), ...named }))
return;
if (Reflect.set(err, "message", `${err.message}\n${line}`))
return;
}
catch {
}
try {
if (hadDetails)
Reflect.set(err, "details", prior);
else
Reflect.deleteProperty(err, "details");
}
catch {
}
}
class RowContractRefusal extends Error {
}
function codeOf(err) {
const details = typeof err === "object" && err !== null ? Reflect.get(err, "details") : undefined;
const fromDetails = typeof details === "object" && details !== null ? Reflect.get(details, "code") : undefined;
if (typeof fromDetails === "string")
return fromDetails;
const own = typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
return typeof own === "string" ? own : undefined;
}