@cotal-ai/runtime 0.170.0 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,17 +19,17 @@
19
19
  import { createHash } from "node:crypto";
20
20
  import { isAbsolute } from "node:path";
21
21
  import { realpathSync } from "node:fs";
22
- import { readCheckpointSettle, readCheckpointAnswer, reconcileCheckpointSchedule, chatStream, waitConsumerName, waitConsumerConfig, isConcreteChannel, assertSafePattern, assertValidChannel, presenceBucket, principalKey, parseSubject, isFromSubjectSender, IncompleteKvScan, openMembersRegistry, openChannelRegistry, openAclRegistry, readAcl, channelInAllow, memberKey, writeChannelConfig, readMember, commitMemberRevision, tombstoneMember, StaleMembershipWrite, runNoticeId, writeRunNotice, actionContext, invokeCommand, invokeRepairingSplit, replyRefusedBeforeEffect, readGoalResult, readGoalStatus, resolveService, listRunNotices, listRunMigrations, markRunNoticeConsumed, listRunNoticesForRun, EpEnvelopeError, replyTargetUnmapped, unansweredRequest, assertAdmittedPublish, assertAdmittedSubscribe, isStreamNotFound, } from "@cotal-ai/core";
23
- import { renderRunContext } from "./run-context.js";
22
+ import { readCheckpointSettle, readCheckpointAnswer, reconcileCheckpointSchedule, chatStream, waitConsumerName, waitConsumerConfig, isConcreteChannel, assertSafePattern, assertValidChannel, presenceBucket, principalKey, parseSubject, isFromSubjectSender, IncompleteKvScan, openMembersRegistry, openChannelRegistry, openAclRegistry, readAcl, channelInAllow, memberKey, writeChannelConfig, readMember, commitMemberRevision, tombstoneMember, StaleMembershipWrite, runNoticeId, writeRunNotice, actionContext, invokeCommand, invokeRepairingSplit, replyRefusedBeforeEffect, readGoalResult, readGoalStatus, resolveService, listRunMigrations, markRunNoticeConsumed, listRunNoticesForRun, EpEnvelopeError, replyTargetUnmapped, unansweredRequest, assertAdmittedPublish, assertAdmittedSubscribe, isStreamNotFound, } from "@cotal-ai/core";
24
23
  import { migrationSeats } from "./migrate.js";
25
24
  import { Kvm } from "@nats-io/kv";
26
- import { parseDuration, Cancelled, EffectError, Journal, askSchemaShape, conformsToAskSchema, digest, journalEntryKeyString, stepKeyString, } from "@cotal-ai/lang";
25
+ import { parseDuration, Cancelled, EffectError, Journal, digest, journalEntryKeyString, stepKeyString, } from "@cotal-ai/lang";
27
26
  import { PauseOverdue } from "./run-pause-host.js";
28
- import { loopLag, servedDespiteStarvation } from "./host-starvation.js";
29
- import { askAttemptToken, observeToken, pauseTokens, waitTimeoutToken, waitTimers } from "./pause-tokens.js";
27
+ import { loopLag } from "./host-starvation.js";
28
+ import { observeToken, pauseTokens, waitTimeoutToken, waitTimers } from "./pause-tokens.js";
30
29
  import { delay } from "./delay.js";
31
30
  import { FIRE_POLL_MS, PauseTimers, decodeMessage } from "./mesh-pause-timers.js";
32
31
  import { SeatWatch } from "./mesh-seat-watch.js";
32
+ import { TurnAsk } from "./mesh-turn-ask.js";
33
33
  /**
34
34
  * A checkpoint resumed with no answer to read.
35
35
  *
@@ -1500,434 +1500,6 @@ export class MeshHandler {
1500
1500
  this.roster.set(name, { handle, owner: caller.owner, actor: caller.actor, uid: caller.uid, host: admitted.instanceId });
1501
1501
  return handle;
1502
1502
  }
1503
- /**
1504
- * `turn` wakes ONE AGENT for one turn, over the manager's relay (a seat is not an endpoint):
1505
- * the manager accepts the goal, parks the rendered context durably, the seat pulls and yields
1506
- * under its own self reach, and the yield is this goal's terminal. The request id is the goalId,
1507
- * the same recovery discipline as `spawn`: a resumed run re-enters the poll, never re-submits.
1508
- *
1509
- * THREE AUTHORITIES END IT, one per ending. The seat's yield is the manager's `succeeded`
1510
- * terminal, carrying the TurnResult. The DEADLINE is double-covered: the manager arms a
1511
- * goal-bound hold (its expiry commits `failed` reason `turn-deadline`), and this client arms its
1512
- * OWN pause under the step's request id — the L4003 authority that survives a dead manager.
1513
- * DEATH: the manager's reap hook marks pending turns; death rides the deadline terminal as
1514
- * `agentDownAt`. This client's presence watch is the early L4002 authority even while the
1515
- * manager runs. The watch reads death the way `wait(down)` does: a superseded incarnation at
1516
- * once, a lapsed row only once it has stayed absent for {@link LAPSE_CONFIRM_MS} and its manager
1517
- * no longer runs the seat.
1518
- *
1519
- * Handoff honoring (lang §5.3) happens HERE: the scope's pending memo is spent at every turn's
1520
- * begin, and when this turn targets its `to`, the link rides the submission (`handoffFrom`, the
1521
- * manager mirrors it into the terminal) and the bound external state. A handoff YIELD is
1522
- * validated against the run roster: an addressee outside it is L4005, one in a different
1523
- * worktree is L4004.
1524
- */
1525
- async turn(req, ctx) {
1526
- if (ctx.signal.cancelled)
1527
- throw new Cancelled(ctx.signal.reason ?? "cancelled");
1528
- const { name, uid } = parseAgentHandle(req.agent.agent);
1529
- const goalId = ctx.requestId;
1530
- const ref = { endpoint: this.binding.endpoint, caller: this.binding.caller, goalId };
1531
- const primary = { endpoint: this.binding.endpoint, token: goalId };
1532
- const scope = scopeOf(ctx.key);
1533
- let ext = ctx.resume?.goalId === goalId ? ctx.resume : undefined;
1534
- if (ext === undefined) {
1535
- const seat = this.seatAddress(name, uid);
1536
- if (seat.address === undefined) {
1537
- if (seat.why === "not-in-roster")
1538
- throw new Error(`turn(${name}#${uid}) addresses an agent that is not in this run's roster; a turn wakes an agent this run spawned`);
1539
- throw new Error(`turn(${name}#${uid}) has no address: the spawn's acceptance floor was never served, so the seat's owner/actor coordinates are unknown`);
1540
- }
1541
- const { owner, actor, host } = seat.address;
1542
- // The permits are the roster entry's, not the address's: a budget is spent per spawn, and
1543
- // the address is only where this turn is sent.
1544
- const entry = this.roster.get(name);
1545
- // Spend the scope's handoff memo at BEGIN, honored or not — honoring is immediate-only.
1546
- const memo = this.handoffMemos.get(scope);
1547
- this.handoffMemos.delete(scope);
1548
- const handoffFrom = memo !== undefined && memo !== "ambiguous" && memo.to === name ? memo.fromGoalId : undefined;
1549
- // Render the seat's context: every unconsumed notice addressed to it, as one durable payload.
1550
- const step = stepKeyString(ctx.key);
1551
- // Addressed by the HANDLE COMPOSITE, exactly as `notify` filed them (an incarnation is the
1552
- // addressee, and a successor under the name is somebody else).
1553
- const notices = (await listRunNotices(this.kv, this.binding.endpoint, this.binding.runId, req.agent.agent))
1554
- .filter((n) => n.consumed === undefined);
1555
- const context = renderRunContext({ run: this.binding.runId, step, notices });
1556
- const deadlineMs = parseDuration(req.deadline ?? this.binding.defaultCheckpointTimeout);
1557
- // The agent's permits are budgets this run spends at the call that would exceed them
1558
- // (cotal-lang 6.5, L4001): one turn per `turns`, and a turn whose deadline runs past the
1559
- // agent's remaining wall clock is already over it. Counted on the fresh path only: a resume
1560
- // re-enters a turn the seed already counted from its journal entry.
1561
- const taken = this.turnsTaken.get(`${name}#${uid}`) ?? 0;
1562
- if (entry.permits?.turns !== undefined && taken >= entry.permits.turns)
1563
- throw new EffectError("L4001", "permit-turns", `turn(${name}#${uid}) would be that agent's turn ${taken + 1}, past its permit of ${entry.permits.turns}`);
1564
- if (entry.permits?.wallClockMs !== undefined && entry.spawnedAt !== undefined) {
1565
- const remaining = entry.spawnedAt + entry.permits.wallClockMs - this.now();
1566
- if (remaining <= 0)
1567
- throw new EffectError("L4001", "permit-wall-clock", `turn(${name}#${uid}): the agent's wall-clock permit (${entry.permits.wallClockMs}ms from its spawn) is spent`);
1568
- if (deadlineMs > remaining)
1569
- throw new EffectError("L4001", "permit-wall-clock", `turn(${name}#${uid}): a ${deadlineMs}ms deadline runs past the agent's remaining wall clock (${remaining}ms of its ${entry.permits.wallClockMs}ms permit)`);
1570
- }
1571
- const payload = JSON.stringify({ run: this.binding.runId, step, context, noticeIds: notices.map((n) => n.noticeId) });
1572
- let submitted = false;
1573
- const submit = async () => {
1574
- const service = submitted ? await this.manager("turn", host)
1575
- : await this.relayManagerBeforeSubmit(host, "turn", ref, "turn", `turn(${name}#${uid})`);
1576
- // After invocation may have run, retain the existing goal reconciliation.
1577
- submitted = true;
1578
- return this.invokeManager(service, "turn", { payload, deadlineMs, ...(handoffFrom !== undefined ? { handoffFrom } : {}) }, {
1579
- id: goalId,
1580
- deadlineMs: TURN_ACCEPT_DEADLINE_MS,
1581
- target: { mode: "owner", owner, actor, lifecycleUid: uid },
1582
- });
1583
- };
1584
- let reply;
1585
- try {
1586
- reply = await submit();
1587
- }
1588
- catch (err) {
1589
- // The invoke did not come back — the goal record is the arbiter, exactly as in `spawn`.
1590
- if ((await readGoalStatus(await this.actionCtx(), ref)) === undefined)
1591
- throw err;
1592
- }
1593
- // ONE reading of a refused acceptance, for both submits: a seat that dies between the first
1594
- // submit and the re-read is the same dead seat, and the resubmit path classing it as an
1595
- // ordinary refusal made an L4002 the program can catch arrive as an uncatchable L4000.
1596
- const refusal = (r, resubmitted) => {
1597
- const err = r.reply.error;
1598
- // `expired` is the serve boundary's "target is not a live managed agent". From the placed
1599
- // host that is the seat's own manager answering about it. From the class rail it is only
1600
- // the members this call reached, so the message does not claim more than that.
1601
- if (err?.code === "expired")
1602
- return new EffectError("L4002", "turn", `turn(${name}#${uid}) ${seatDownReading(err, host)} before the relay began: ${err.message}`);
1603
- return new Error(resubmitted
1604
- ? `turn(${name}#${uid}) landed but its acceptance could not be re-read: ${err?.message ?? "refused with no message"}`
1605
- : `turn(${name}#${uid}) was refused by the ${this.binding.endpoint} endpoint: ${err?.message ?? "refused with no message"}`);
1606
- };
1607
- if (reply !== undefined && reply.reply.ok === false)
1608
- throw refusal(reply, false);
1609
- if (reply === undefined) {
1610
- // The acceptance carries the deadline authority, so a lost reply is asked for again: the
1611
- // same goalId under the same fingerprint is served from the manager's acceptance cache.
1612
- reply = await submit();
1613
- if (reply.reply.ok === false)
1614
- throw refusal(reply, true);
1615
- }
1616
- const floor = reply.reply.data;
1617
- if (typeof floor?.deadlineAt !== "number")
1618
- throw new Error(`turn(${name}#${uid}) was accepted with no readable deadline (${JSON.stringify(reply.reply.data)}); a garbled acceptance never authorizes (SPEC 13.6)`);
1619
- // ONE deadline for the turn: the acceptance's `deadlineAt` is the instant the manager's own
1620
- // hold denies at, and the client's pause is armed on that same instant. A second clock read
1621
- // before the accept round-trip would fire first by the round-trip plus skew and throw away a
1622
- // yield the manager's window still admitted.
1623
- const deadlineAt = floor.deadlineAt;
1624
- ext = {
1625
- goalId, name, owner, actor, uid, deadlineAt,
1626
- noticeIds: notices.map((n) => n.noticeId),
1627
- ...(handoffFrom !== undefined ? { handoffFrom } : {}),
1628
- };
1629
- await ctx.bind(ext);
1630
- // Spent once the turn is RECORDED, which is the same event the adoption seed counts. Spending
1631
- // it before the submit charged a permit for a turn the seat never saw (a dead seat's L4002,
1632
- // an endpoint refusal), and a recovering run would then read a different number off the
1633
- // journal than the live one held.
1634
- this.turnsTaken.set(`${name}#${uid}`, taken + 1);
1635
- }
1636
- this.recordTurnGoal(`${name}#${uid}`, goalId);
1637
- const deadlineAt = ext.deadlineAt;
1638
- if (typeof deadlineAt !== "number")
1639
- throw new Error(`turn(${name}#${uid}) resumed with no recorded deadline; a garbled external state never authorizes`);
1640
- // The client's OWN deadline authority: minted on the first pass, attached to on re-entry.
1641
- await this.arm(primary, deadlineAt);
1642
- const actx = await this.actionCtx();
1643
- const watch = {};
1644
- // Only re-enter the read, never the relay submission or its outcome processing. Each read
1645
- // gets the pause plane's bounded timeout/starvation policy and names itself in diagnostics.
1646
- const poll = (what, read) => servedDespiteStarvation(async () => {
1647
- if (ctx.signal.cancelled)
1648
- throw new Cancelled(ctx.signal.reason ?? "cancelled");
1649
- return await read();
1650
- }, this.lag, `turn(${name}#${uid}) ${what}`, this.onStarved);
1651
- const result = () => poll("readGoalResult", () => readGoalResult(actx, ref));
1652
- const expired = () => poll("expired", () => this.expired(primary));
1653
- const decided = async () => ctx.signal.cancelled || (await result()) !== undefined || (await expired()) !== undefined;
1654
- try {
1655
- for (;;) {
1656
- if (ctx.signal.cancelled)
1657
- throw new Cancelled(ctx.signal.reason ?? "cancelled");
1658
- const fact = await result();
1659
- if (fact !== undefined) {
1660
- await this.cancelTimer(primary);
1661
- return await this.turnOutcome(req, fact, ext, scope, name, uid);
1662
- }
1663
- const ended = await expired();
1664
- if (ended !== undefined)
1665
- throw new EffectError("L4003", "turn-deadline", `turn(${name}#${uid}) deadline elapsed before a yield`);
1666
- const reason = await poll("presenceDeath", () => this.presenceDeath(name, uid, watch, decided));
1667
- if (reason !== undefined) {
1668
- await this.cancelTimer(primary);
1669
- throw new EffectError("L4002", "turn", `turn(${name}#${uid}) found the agent down (${reason}) before a yield`);
1670
- }
1671
- await delay(WAIT_POLL_MS);
1672
- }
1673
- }
1674
- catch (e) {
1675
- // A turn that ends on the run's side without a yield the run accepted (its deadline, the
1676
- // seat's death, a refused handoff, a cancellation) is not a reply, whatever the relay
1677
- // records later: `wait(replied)` reads the verdict this branch raised, never a stale yield.
1678
- this.turnGoals.get(`${name}#${uid}`)?.delete(goalId);
1679
- // In particular a read that exhausted its retry budget must not leave a live relay that
1680
- // tells the seat its later yield continued a turn the run already abandoned. The ordinary
1681
- // turn verdicts already have an authority: death, the shared deadline, or a yielded handoff.
1682
- // Do not ask a dead manager to confirm the client's independent deadline or death verdict.
1683
- const terminal = e instanceof EffectError && ["L4002", "L4003", "L4004", "L4005"].includes(e.code);
1684
- if (!terminal) {
1685
- // Neither cleanup failure may prevent the other resource from being retired.
1686
- const cleanup = await Promise.allSettled([
1687
- this.cancelTimer(primary),
1688
- this.withdrawCancelledRelay(goalId, deadlineAt),
1689
- ]);
1690
- const failures = cleanup.flatMap((r, i) => r.status === "rejected"
1691
- ? [{ resource: i === 0 ? "primary timer claim" : "relay withdrawal", error: r.reason }]
1692
- : []);
1693
- if (failures.length > 0) {
1694
- const message = `${e instanceof Error ? e.message : String(e)}; turn cleanup failed: `
1695
- + failures.map((f) => `${f.resource}: ${f.error instanceof Error ? f.error.message : String(f.error)}`).join("; ");
1696
- const cause = new AggregateError([e, ...failures.map((f) => f.error)], message);
1697
- if (e instanceof EffectError) {
1698
- const error = new EffectError(e.code, e.kind, message, e.detail);
1699
- error.cause = cause;
1700
- throw error;
1701
- }
1702
- throw cause;
1703
- }
1704
- }
1705
- throw e;
1706
- }
1707
- }
1708
- /**
1709
- * A yielded handoff's refusal class: L4005 when the addressee is not in this run's roster,
1710
- * L4004 when it sits in a different worktree than the seat handing off, undefined when the
1711
- * handoff is honorable. One reading for the turn that raises it and the `wait(replied)` that
1712
- * must not count it, so the two observers never diverge on a spoofed or misdirected `to`.
1713
- */
1714
- handoffRefusal(fromWorktree, to) {
1715
- const toName = typeof to === "string" ? to : "";
1716
- const target = this.roster.get(toName);
1717
- if (toName.length === 0 || target === undefined)
1718
- return "L4005";
1719
- if ((target.handle.worktree ?? undefined) !== (fromWorktree ?? undefined))
1720
- return "L4004";
1721
- return undefined;
1722
- }
1723
- /** Map a turn goal's terminal onto the effect's contract: `succeeded` carries the TurnResult
1724
- * (a handoff addressee resolved against the roster — L4005 outside it, L4004 across
1725
- * worktrees), `failed` splits on the manager's recorded reason, `cancelled` unwinds. The
1726
- * consumed notices are marked HERE, by the goal that carried them, tolerating the re-entry
1727
- * conflict (a crash between the terminal and the mark re-marks on resume). */
1728
- async turnOutcome(req, fact, ext, scope, name, uid) {
1729
- if (fact.state === "cancelled")
1730
- throw new Cancelled(`the turn goal for ${name}#${uid} was cancelled`);
1731
- if (fact.state === "failed") {
1732
- const d = fact.data;
1733
- // The one reasoned failure a relay commits. A dead target has no early terminal of its own
1734
- // on the goal plane (SPEC 13.6 item 7): the client's presence watch in the poll loop is the
1735
- // first L4002 authority, and a death that rode to the deadline arrives on this same deny,
1736
- // MARKED by the relay (`agentDownAt`) — read here as the agent-down failure it is, never as
1737
- // a deadline the program could have set longer.
1738
- if (d?.reason === "turn-deadline") {
1739
- if (typeof d.agentDownAt === "number")
1740
- throw new EffectError("L4002", "turn", `turn(${name}#${uid}) found the agent down (it left presence at ${new Date(d.agentDownAt).toISOString()}) before a yield; the deadline terminal carries its death`);
1741
- throw new EffectError("L4003", "turn-deadline", `turn(${name}#${uid}) deadline elapsed before a yield`);
1742
- }
1743
- throw new Error(`turn(${name}#${uid}) failed at the ${this.binding.endpoint} endpoint: ${typeof d?.error === "string" ? d.error : JSON.stringify(fact.data)}`);
1744
- }
1745
- if (fact.state !== "succeeded")
1746
- throw new Error(`turn(${name}#${uid}) settled ${fact.state}; a turn's yield is a succeeded terminal or a reasoned failure, never this`);
1747
- const d = fact.data;
1748
- if ((d?.status !== "done" && d?.status !== "blocked" && d?.status !== "handoff") || typeof d.at !== "number")
1749
- throw new Error(`turn(${name}#${uid}) succeeded with a malformed TurnResult (${JSON.stringify(fact.data)}); a garbled terminal never yields a result`);
1750
- let to;
1751
- if (d.status === "handoff") {
1752
- const toName = typeof d.to === "string" ? d.to : "";
1753
- const refusal = this.handoffRefusal(req.agent.worktree, d.to);
1754
- if (refusal === "L4005")
1755
- throw new EffectError("L4005", "turn-handoff", `turn(${name}#${uid}) yielded a handoff to "${toName}", which is not in this run's roster`);
1756
- const target = this.roster.get(toName);
1757
- if (refusal === "L4004")
1758
- throw new EffectError("L4004", "turn-handoff", `turn(${name}#${uid}) yielded a handoff to "${toName}" across worktrees (${req.agent.worktree ?? "none"} -> ${target.handle.worktree ?? "none"}); you cannot hand someone a working tree they are not in`);
1759
- to = target.handle;
1760
- }
1761
- // The notices this turn carried are consumed by THIS goal — the create-only CAS arbitrates,
1762
- // and a re-entry's conflict reads as "already recorded", never as a failure.
1763
- const noticeIds = Array.isArray(ext.noticeIds) ? ext.noticeIds.filter((n) => typeof n === "string") : [];
1764
- for (const noticeId of noticeIds) {
1765
- try {
1766
- await markRunNoticeConsumed(this.kv, this.binding.endpoint, this.binding.runId, req.agent.agent, noticeId, String(ext.goalId), this.now());
1767
- }
1768
- catch (e) {
1769
- if (!(e instanceof EpEnvelopeError && e.code === "conflict"))
1770
- throw e;
1771
- }
1772
- }
1773
- if (d.status === "handoff" && to !== undefined)
1774
- this.recordHandoffMemo(scope, parseAgentHandle(to.agent).name, String(ext.goalId));
1775
- return {
1776
- status: d.status,
1777
- ...(to !== undefined ? { to } : {}),
1778
- ...(typeof d.note === "string" ? { note: d.note } : {}),
1779
- at: d.at,
1780
- };
1781
- }
1782
- /**
1783
- * `ask` is a schema-checked pause the ADDRESSED AGENT is expected to answer.
1784
- *
1785
- * Each attempt is one checkpoint-plane pause — the same mint, settle and answer record a
1786
- * `checkpoint` rides, answered through the run driver's `resolveCheckpoint` (`cotal run
1787
- * answer`), which is how "the agent publishes a record" reaches a holder-bound plane: the agent,
1788
- * or anyone the run's ACL admits on its behalf, answers through the driver exactly as a human
1789
- * answers a checkpoint. What `ask` adds is the handler-side contract of §6.5: the schema is read
1790
- * as the SHORTHAND (refused L4022 when it cannot be), every answer is checked against it, a
1791
- * non-conforming answer costs one attempt and the refusal reason is bound onto the entry for the
1792
- * answerer to read, and exhausted attempts are the effect's own catchable L4006.
1793
- *
1794
- * **One absolute deadline for the whole ask**, computed once and bound with the first attempt: a
1795
- * re-ask does not restart the clock, or a stream of non-conforming answers could stretch the
1796
- * pause forever. The deadline elapsing with no conforming answer is the ask's own L4006, the
1797
- * same outcome exhausted attempts name: the budget it ran out of is the ask's, and L4003 belongs
1798
- * to a `turn` whose own deadline elapsed.
1799
- *
1800
- * **Attempt N's token derives from the step's request id** (attempt 1 IS the request id), and
1801
- * the CURRENT attempt's token is bound as `askToken` before its pause is armed — so a resume
1802
- * re-enters the attempt in flight, an answer judged non-conforming just before a crash is
1803
- * re-judged identically from its durable settle, and the discharge and the adoption re-arm
1804
- * address the one timer that is actually armed.
1805
- */
1806
- async ask(req, ctx) {
1807
- if (ctx.signal.cancelled)
1808
- throw new Cancelled(ctx.signal.reason ?? "cancelled");
1809
- const shape = askSchemaShape(req.schema);
1810
- if (shape === null) {
1811
- throw new EffectError("L4022", "ask-schema-unreadable", `L4022 Unreadable ask schema\n\n step ${stepKeyString(ctx.key)}\n\nThe schema is not the shorthand this handler enforces: a record mapping each field name to one of "string", "number", "boolean", "array", "record", "null".\n\nFix: write the shorthand, for example { steps: "array" }, or pass {} to accept any record.`);
1812
- }
1813
- const attempts = req.attempts ?? 1;
1814
- // The seat the ask is told to, resolved before anything binds: an ask addresses an agent this
1815
- // run spawned, and one it cannot tell opens no attempt.
1816
- const seat = this.askSeat(req, ctx);
1817
- const resume = askResume(ctx.resume);
1818
- const deadlineAt = resume?.deadlineAt
1819
- ?? this.now() + parseDuration(req.deadline ?? this.binding.defaultCheckpointTimeout);
1820
- let attempt = resume?.attempt ?? 1;
1821
- // The resumed attempt is already bound; every attempt this call opens binds before it arms.
1822
- let bindOwed = resume === undefined;
1823
- let refused = resume?.refused;
1824
- for (;;) {
1825
- const token = askAttemptToken(ctx.requestId, attempt);
1826
- if (bindOwed) {
1827
- await ctx.bind({
1828
- attempt,
1829
- askToken: token,
1830
- deadlineAt,
1831
- ...(refused !== undefined ? { refused } : {}),
1832
- });
1833
- }
1834
- bindOwed = true;
1835
- // The addressed agent is TOLD: the attempt rides the turn relay under the attempt's own
1836
- // token, carrying the token, the schema, the attempt count, the deadline and the previous
1837
- // refusal, so the seat can answer through `cotal run answer`. Idempotent by goal id: a
1838
- // re-entry finds the relay already accepted and submits nothing.
1839
- await this.relayAsk(seat, ctx, token, { attempt, attempts, deadlineAt, ...(refused !== undefined ? { refused } : {}) });
1840
- const ref = { endpoint: this.binding.endpoint, token };
1841
- // The deadline is the ask's whole budget of time: passing it with no conforming record
1842
- // is the same outcome exhausted attempts name (L4006), never a turn's deadline (L4003),
1843
- // and that holds when it passed while the attempt was bound and relayed, before its pause
1844
- // could be minted.
1845
- const expired = () => new EffectError("L4006", "ask-deadline", `ask(${stepKeyString(ctx.key)}) produced no conforming record before its recorded deadline: attempt ${attempt} of ${attempts} was still open when it passed`);
1846
- try {
1847
- await this.arm(ref, deadlineAt);
1848
- }
1849
- catch (e) {
1850
- if (e instanceof PauseOverdue)
1851
- throw expired();
1852
- throw e;
1853
- }
1854
- const settled = await this.settle(ref, ctx.signal, true);
1855
- if (settled.settle === "expired")
1856
- throw expired();
1857
- const answer = settled.answerId === undefined
1858
- ? undefined
1859
- : this.services ? await this.services.pauses.readAnswer(token) : await readCheckpointAnswer(this.kv, this.binding.endpoint, token, settled.answerId);
1860
- if (answer === undefined)
1861
- throw new CheckpointAnswerMissing(token, settled.answerId);
1862
- if (conformsToAskSchema(answer.value, shape))
1863
- return answer.value;
1864
- const why = askNonconformance(answer.value, shape);
1865
- if (attempt >= attempts) {
1866
- throw new EffectError("L4006", "ask-nonconforming", `L4006 ask never produced a conforming record\n\n step ${stepKeyString(ctx.key)}\n\n${attempts} repl${attempts === 1 ? "y was" : "ies were"} checked against the schema and none conformed; the last was refused: ${why}.\n\nFix: have the agent publish a record matching the schema, widen the schema, or raise attempts.`);
1867
- }
1868
- refused = why;
1869
- attempt += 1;
1870
- }
1871
- }
1872
- /**
1873
- * One ask attempt's relay to the addressed seat: a `turn` goal under the attempt's token whose
1874
- * payload carries the ask (token, schema, attempt, deadline, the previous refusal), rendered by
1875
- * the seat's connector as the request to answer. The goal is the seat's to yield when it has
1876
- * answered; the ask itself settles on the checkpoint plane, so the relay's terminal is never
1877
- * read here, and it is never a reply `wait(replied)` observes. A seat the serve boundary reports
1878
- * gone is the agent-down failure (L4002).
1879
- */
1880
- askSeat(req, ctx) {
1881
- const { name, uid } = parseAgentHandle(req.agent.agent);
1882
- const seat = this.seatAddress(name, uid);
1883
- const step = stepKeyString(ctx.key);
1884
- if (seat.address === undefined) {
1885
- if (seat.why === "not-in-roster")
1886
- throw new Error(`ask(${step}) addresses ${name}#${uid}, which is not in this run's roster; an ask is relayed to an agent this run spawned`);
1887
- throw new Error(`ask(${step}) has no address for ${name}#${uid}: the spawn's acceptance floor was never served, so the seat's owner/actor coordinates are unknown`);
1888
- }
1889
- return { ...seat.address, schema: req.schema };
1890
- }
1891
- /**
1892
- * Where a relay to an agent of this run is addressed: the roster entry under the handle's name,
1893
- * at the handle's incarnation, with the owner/actor coordinates its acceptance floor served.
1894
- * One resolver for the three relays (`turn`, `ask`, an escalation), because the three
1895
- * dispositions differ and the lookup does not: a turn and an ask refuse, an escalation stands.
1896
- */
1897
- seatAddress(name, uid) {
1898
- const entry = this.roster.get(name);
1899
- if (entry === undefined || (uid !== undefined && entry.uid !== uid))
1900
- return { why: "not-in-roster" };
1901
- if (entry.owner === undefined || entry.actor === undefined)
1902
- return { why: "no-floor" };
1903
- return { address: { name, uid: entry.uid, owner: entry.owner, actor: entry.actor, ...(entry.host !== undefined ? { host: entry.host } : {}) } };
1904
- }
1905
- /**
1906
- * The principal a `message` wait's `from` handle names, as `<owner>.<actor>`: the coordinates
1907
- * this run's roster recorded when it spawned the seat or bound the participant. A message
1908
- * answers only when its subject's sender is that principal. A handle outside the roster, or one
1909
- * whose coordinates were never served, refuses: matching it on a display name would let any peer
1910
- * that names itself after the agent answer.
1911
- */
1912
- waitSender(agent) {
1913
- const { name, uid } = parseAgentHandle(agent);
1914
- const seat = this.seatAddress(name, uid);
1915
- if (seat.address === undefined) {
1916
- if (seat.why === "not-in-roster")
1917
- throw new Error(`wait(message(..., { from: ${name}#${uid} })) names an agent that is not in this run's roster; \`from\` takes a handle this run spawned or bound with participant()`);
1918
- throw new Error(`wait(message(..., { from: ${name}#${uid} })) has no sender to match: the spawn's acceptance floor was never served, so the seat's owner/actor coordinates are unknown`);
1919
- }
1920
- return principalKey(seat.address.owner, seat.address.actor).key;
1921
- }
1922
- async relayAsk(seat, ctx, token, ask) {
1923
- const step = stepKeyString(ctx.key);
1924
- const context = renderRunContext({ run: this.binding.runId, step, notices: [] });
1925
- const payload = JSON.stringify({
1926
- run: this.binding.runId, step, context, noticeIds: [],
1927
- ask: { token, schema: seat.schema, attempt: ask.attempt, attempts: ask.attempts, deadlineAt: ask.deadlineAt, ...(ask.refused !== undefined ? { refused: ask.refused } : {}) },
1928
- });
1929
- await this.relayToSeat(seat, token, payload, ask.deadlineAt, "ask", step);
1930
- }
1931
1503
  /**
1932
1504
  * `monitor` registers interest: after it, `down(agent)` is an event a branch can await (§5.9).
1933
1505
  *
@@ -2185,6 +1757,40 @@ export class MeshHandler {
2185
1757
  async withdrawCancelledRelay(goalId, deadlineAt) { return this.seatWatch.withdrawCancelledRelay(goalId, deadlineAt); }
2186
1758
  async presenceRows() { return this.seatWatch.presenceRows(); }
2187
1759
  async presenceDeath(name, uid, watch, decided) { return this.seatWatch.presenceDeath(name, uid, watch, decided); }
1760
+ /** The turn and ask clients own no handler state: the run-memory maps they write are mutated in
1761
+ * place through getters, and each input, the handler's own members included, is read through
1762
+ * the handler at its use. */
1763
+ turnAsk = new TurnAsk({
1764
+ self: () => this,
1765
+ binding: () => this.binding,
1766
+ kv: () => this.kv,
1767
+ services: () => this.services,
1768
+ lag: () => this.lag,
1769
+ onStarved: () => this.onStarved,
1770
+ roster: () => this.roster,
1771
+ turnsTaken: () => this.turnsTaken,
1772
+ handoffMemos: () => this.handoffMemos,
1773
+ turnGoals: () => this.turnGoals,
1774
+ now: () => this.now(),
1775
+ actionCtx: () => this.actionCtx(),
1776
+ manager: (command, instanceId) => this.manager(command, instanceId),
1777
+ invokeManager: (service, command, args, opts) => this.invokeManager(service, command, args, opts),
1778
+ relayManagerBeforeSubmit: (host, command, ref, kind, label) => this.relayManagerBeforeSubmit(host, command, ref, kind, label),
1779
+ arm: (ref, deadline) => this.arm(ref, deadline),
1780
+ expired: (ref) => this.expired(ref),
1781
+ cancelTimer: (ref) => this.cancelTimer(ref),
1782
+ settle: (ref, signal, relayed) => this.settle(ref, signal, relayed),
1783
+ presenceDeath: (name, uid, watch, decided) => this.presenceDeath(name, uid, watch, decided),
1784
+ relayToSeat: (seat, goalId, payload, deadlineAt, kind, step) => this.relayToSeat(seat, goalId, payload, deadlineAt, kind, step),
1785
+ withdrawCancelledRelay: (goalId, deadlineAt) => this.withdrawCancelledRelay(goalId, deadlineAt),
1786
+ recordTurnGoal: (handle, goalId) => this.recordTurnGoal(handle, goalId),
1787
+ recordHandoffMemo: (scope, to, fromGoalId) => this.recordHandoffMemo(scope, to, fromGoalId),
1788
+ });
1789
+ async turn(req, ctx) { return this.turnAsk.turn(req, ctx); }
1790
+ async ask(req, ctx) { return this.turnAsk.ask(req, ctx); }
1791
+ handoffRefusal(fromWorktree, to) { return this.turnAsk.handoffRefusal(fromWorktree, to); }
1792
+ seatAddress(name, uid) { return this.turnAsk.seatAddress(name, uid); }
1793
+ waitSender(agent) { return this.turnAsk.waitSender(agent); }
2188
1794
  }
2189
1795
  export { waitConsumerName, waitConsumerConfig } from "@cotal-ai/core";
2190
1796
  /** How long one poll of a wait's consumer blocks. The deadline itself is durable; this is only how
@@ -2296,12 +1902,6 @@ export const TURN_ACCEPT_DEADLINE_MS = 30_000;
2296
1902
  * probability (1 - ((m-1)/m)^17) / m: about 1/2 for m = 2 and 0.25 for m = 4. All 65 then miss
2297
1903
  * with probability about 2^-65 and 9e-9. */
2298
1904
  export const MANAGER_ROUTE_ATTEMPTS = 64;
2299
- /** A step key's enclosing scope: the journal's own rendering (`entry.scope`), re-derived so the
2300
- * live path and the adoption rebuild key the handoff memos identically. */
2301
- function scopeOf(key) {
2302
- const k = stepKeyString(key);
2303
- return k.slice(0, k.lastIndexOf("/"));
2304
- }
2305
1905
  /** The terminal wait a discharge grants a goal whose entry recorded no readiness window (the
2306
1906
  * crash-before-bind case). Matches the manager's default readiness budget. */
2307
1907
  const DISCHARGE_TERMINAL_BOUND_MS = 30_000;
@@ -2471,7 +2071,7 @@ function isConclavePlan(v) {
2471
2071
  }
2472
2072
  /** Split an agent handle `<name>#<lifecycleUid>` on its LAST `#` — the uid alphabet
2473
2073
  * (`[a-z0-9]{26,32}`) cannot carry one, a name could. */
2474
- function parseAgentHandle(agent) {
2074
+ export function parseAgentHandle(agent) {
2475
2075
  const i = agent.lastIndexOf("#");
2476
2076
  if (i <= 0 || i === agent.length - 1)
2477
2077
  throw new Error(`"${agent}" is not an agent handle of the form <name>#<lifecycleUid>`);
@@ -2496,36 +2096,6 @@ function assertConclaveChannel(channel) {
2496
2096
  throw new Error(`conclave channel "${channel}" is a wildcard; a conclave joins its members to one concrete channel`);
2497
2097
  return channel;
2498
2098
  }
2499
- /** The recorded ask progress a resume re-enters at, or undefined for a fresh first attempt. The
2500
- * external is bytes from an earlier process, so the shape is checked rather than trusted. */
2501
- function askResume(v) {
2502
- if (v === undefined)
2503
- return undefined;
2504
- if (!(typeof v.attempt === "number" && v.attempt >= 1 && typeof v.deadlineAt === "number"))
2505
- return undefined;
2506
- // The refusal is bound with the attempt it belongs to. A resume that dropped it would re-ask the
2507
- // seat with no reason its last answer failed, which is the one thing the re-ask exists to say.
2508
- return {
2509
- attempt: v.attempt,
2510
- deadlineAt: v.deadlineAt,
2511
- ...(typeof v.refused === "string" ? { refused: v.refused } : {}),
2512
- };
2513
- }
2514
- /** WHY a reply does not conform, per declared field — the refusal an answerer reads off the entry
2515
- * before answering again. Judged with the same single-field check that judged the reply, so the
2516
- * description can never disagree with the verdict. */
2517
- function askNonconformance(value, shape) {
2518
- if (typeof value !== "object" || value === null || Array.isArray(value))
2519
- return "the reply is not a record";
2520
- const record = value;
2521
- const bad = [];
2522
- for (const [field, kind] of Object.entries(shape)) {
2523
- if (conformsToAskSchema({ [field]: record[field] }, { [field]: kind }))
2524
- continue;
2525
- bad.push(field in record ? `"${field}" wants ${kind}` : `"${field}" is missing (wants ${kind})`);
2526
- }
2527
- return bad.join("; ");
2528
- }
2529
2099
  /**
2530
2100
  * A `matches` pattern, admitted through the repo's bounded-regex subset before it is compiled.
2531
2101
  *