@cotal-ai/runtime 0.169.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.
@@ -0,0 +1,309 @@
1
+ /** A run's seat watch: the checkpoint relay that tells a seat about an escalated pause and
2
+ * withdraws that relay, and the presence watch that reads whether a seat's incarnation is still
3
+ * live, superseded or lapsed. The mesh handler composes it; every input, the handler's own
4
+ * members included, is read through the handler at its use. */
5
+ import { EpEnvelopeError, IncompleteKvScan, isPresenceRow, liveKvEntries, readGoalIndex, readGoalResult, readGoalSpec, readGoalStatus, replyRefusedBeforeEffect, unansweredRequest, } from "@cotal-ai/core";
6
+ import { EffectError, stepKeyString } from "@cotal-ai/lang";
7
+ import { delay } from "./delay.js";
8
+ import { MANAGER_ROUTE_ATTEMPTS, TURN_ACCEPT_DEADLINE_MS, WAIT_POLL_MS, seatDownReading, } from "./mesh-handler.js";
9
+ import { renderRunContext } from "./run-context.js";
10
+ /**
11
+ * How long an incarnation's presence row must stay absent before `turn` and `wait(down)` read it as
12
+ * `lapsed`. A row is gone 6s after its last heartbeat, and a live seat whose connector stalls for
13
+ * longer (host load, a reconnect) comes back under the same lifecycle uid on its next heartbeat. One
14
+ * absent read failed a turn L4002 while the seat went on working (#2344). Five liveness windows lets
15
+ * a stalled seat renew, and stays short against a turn's deadline. A `superseded` read needs no
16
+ * wait: a different incarnation already holds the name. The window is measured from the end of the
17
+ * read that opened it to the start of the read that closes it, over reads {@link lapseWindow} chains.
18
+ */
19
+ const LAPSE_CONFIRM_MS = 30_000;
20
+ /**
21
+ * The longest span from the start of one presence read to the end of the next across which an
22
+ * absent row still counts as continuously absent: the presence bucket's 6s TTL. A heartbeat keeps
23
+ * the row live at least that long, so a renewal cannot fall between two reads that close. A slower
24
+ * read or a run of failed scans leaves the gap unobserved, and the lapse window starts over.
25
+ */
26
+ const PRESENCE_GAP_MS = 6_000;
27
+ /** The start of the lapse window after an absent read that ended at `now`: kept when the previous
28
+ * read began within {@link PRESENCE_GAP_MS}, otherwise this read opens a new one. */
29
+ const lapseWindow = (lapsedSince, lastReadAt, now) => lapsedSince === undefined || now - lastReadAt > PRESENCE_GAP_MS ? now : lapsedSince;
30
+ /** The checkpoint relay and presence watch members of a mesh handler, over the handler's own inputs. */
31
+ export class SeatWatch {
32
+ deps;
33
+ constructor(deps) {
34
+ this.deps = deps;
35
+ }
36
+ get handler() { return this.deps.self(); }
37
+ get binding() { return this.deps.binding(); }
38
+ get roster() { return this.deps.roster(); }
39
+ get managerServices() { return this.deps.managerServices(); }
40
+ now() { return this.deps.now(); }
41
+ actionCtx() { return this.deps.actionCtx(); }
42
+ presenceRegistry() { return this.deps.presenceRegistry(); }
43
+ seatAddress(name, uid) { return this.deps.seatAddress(name, uid); }
44
+ manager(command, instanceId) { return this.deps.manager(command, instanceId); }
45
+ invokeManager(service, command, args, opts) {
46
+ return this.deps.invokeManager(service, command, args, opts);
47
+ }
48
+ relayManagerBeforeSubmit(host, command, ref, kind, label) {
49
+ return this.deps.relayManagerBeforeSubmit(host, command, ref, kind, label);
50
+ }
51
+ /**
52
+ * An escalated checkpoint, delivered to the agent it names.
53
+ *
54
+ * `to` is legal only with `onExpiry: "escalate"` and the escalation is the SECOND mint, so this
55
+ * runs once per chain at most. The addressee is resolved through the run's own roster: a name
56
+ * this run spawned is a seat and is told, and anything else is a person — the pause is
57
+ * answerable from anywhere by design, its addressee is on the entry, and refusing a program
58
+ * that escalates to a human would be this host narrowing an option the reference leaves open.
59
+ *
60
+ * The relay is the ask's, because the two are the same act: one turn on the seat, carrying what
61
+ * is asked and the token to answer under, settling on the checkpoint plane rather than on the
62
+ * relay's own terminal.
63
+ */
64
+ async relayEscalation(req, ctx, token, deadlineAt) {
65
+ const to = req.to;
66
+ const step = stepKeyString(ctx.key);
67
+ // A seat is a roster entry whose acceptance floor was served: that is what carries the
68
+ // owner/actor coordinates a relay is addressed by. Anything else — a name this run never
69
+ // spawned, or one whose floor never landed — is not a seat, and the escalation stays the
70
+ // durable pause it already is, addressed on its entry and answerable from anywhere.
71
+ const seat = this.seatAddress(to);
72
+ if (seat.address === undefined)
73
+ return;
74
+ const context = renderRunContext({ run: this.binding.runId, step, notices: [] });
75
+ const payload = JSON.stringify({
76
+ run: this.binding.runId, step, context, noticeIds: [],
77
+ checkpoint: { token, prompt: req.prompt, schema: req.schema ?? null, deadlineAt, escalatedTo: to },
78
+ });
79
+ try {
80
+ await this.handler.relayToSeat(seat.address, token, payload, deadlineAt, "checkpoint", step);
81
+ }
82
+ catch (e) {
83
+ // THE PAUSE OUTLIVES ITS ADDRESSEE. The reference defines no failure for an escalation whose
84
+ // addressee cannot be reached: it "mints exactly one further checkpoint addressed to `to`",
85
+ // and a checkpoint is "a durable pause a human or an agent resolves from anywhere". A seat
86
+ // the endpoint reports gone is therefore the same case as a `to` that names a person: nobody
87
+ // is told, the addressee is on the entry, and anyone may still answer. L4002 is the turn's
88
+ // vocabulary, and this is not a turn the program asked for. Said once, not swallowed.
89
+ if (!(e instanceof EffectError && e.code === "L4002"))
90
+ throw e;
91
+ console.error(`run ${this.binding.runId}: the escalation at ${step} could not be told to ${to} (${e.message}); the pause stands, answerable from anywhere`);
92
+ }
93
+ }
94
+ /**
95
+ * Submit one relay to a seat as a `turn` goal, and read its acceptance.
96
+ *
97
+ * IDEMPOTENT BY THE GOAL RECORD, which is also the arbiter when the invoke does not come back:
98
+ * a relay that landed and lost its reply is a relay that landed, and re-submitting it would put
99
+ * a second turn on the seat for one request. A seat the serve boundary reports gone is the
100
+ * agent-down failure (L4002); every other refusal is this endpoint's and is uncatchable.
101
+ *
102
+ * The relay carries the pause's own `deadlineAt` and the manager holds it to that instant: a
103
+ * duration counted from the manager's acceptance would outlive the pause by the submit's trip
104
+ * plus skew and show the seat an attempt whose answer is refused. A relay the manager refuses as
105
+ * already past, and that is past on this clock too, has nobody left to tell, because the pause
106
+ * denies at that same instant; the arm that follows meets the passed deadline and decides the
107
+ * outcome.
108
+ */
109
+ async relayToSeat(seat, goalId, payload, deadlineAt, kind, step) {
110
+ const { name, uid } = seat;
111
+ const ref = { endpoint: this.binding.endpoint, caller: this.binding.caller, goalId };
112
+ const actx = await this.actionCtx();
113
+ if ((await readGoalStatus(actx, ref)) !== undefined)
114
+ return;
115
+ const service = await this.relayManagerBeforeSubmit(seat.host, "turn", ref, kind, `${kind}(${step})`);
116
+ let reply;
117
+ try {
118
+ reply = await this.invokeManager(service, "turn", { payload, deadlineAt }, {
119
+ id: goalId,
120
+ deadlineMs: TURN_ACCEPT_DEADLINE_MS,
121
+ target: { mode: "owner", owner: seat.owner, actor: seat.actor, lifecycleUid: uid },
122
+ });
123
+ }
124
+ catch (err) {
125
+ // The invoke did not come back — the goal record is the arbiter, exactly as in `turn`.
126
+ if ((await readGoalStatus(actx, ref)) === undefined)
127
+ throw err;
128
+ return;
129
+ }
130
+ if (reply.reply.ok === false) {
131
+ const err = reply.reply.error;
132
+ if (err.code === "expired")
133
+ throw new EffectError("L4002", kind, `${kind}(${step}): ${name}#${uid} ${seatDownReading(err, seat.host)} before its relay began: ${err.message}`);
134
+ if (err.code === "deadline-exceeded" && this.now() >= deadlineAt)
135
+ return;
136
+ throw new Error(`${kind}(${step}) was refused by the ${this.binding.endpoint} endpoint: ${err.message}`);
137
+ }
138
+ }
139
+ /**
140
+ * Withdraw the relay a cancelled step sent to a seat, through the manager's reserved `cancel`
141
+ * (SPEC 13.6 item 4), so the seat is not shown it again. A token no relay rode has no goal and
142
+ * nothing to withdraw, and a relay that already ended is the outcome either way: the manager
143
+ * refuses it with the cached terminal, so a repeated withdrawal is a no-op. Any other refusal
144
+ * throws under the code it was refused with, which leaves a discharge open to retry.
145
+ *
146
+ * Only the manager that accepted the relay holds it, and the class rail reaches any member, so a
147
+ * refusal is final only from the accepter its index entry names. One from another member is
148
+ * re-issued on the class rail, as the spawn discharge's despawn is.
149
+ */
150
+ async withdrawRelay(goalId) {
151
+ const ref = { endpoint: this.binding.endpoint, caller: this.binding.caller, goalId };
152
+ const actx = await this.actionCtx();
153
+ if ((await readGoalStatus(actx, ref)) === undefined)
154
+ return;
155
+ const accepter = (await readGoalIndex(actx, ref))?.iid;
156
+ for (let attempt = 0;; attempt += 1) {
157
+ const reply = await this.invokeManager(await this.manager("cancel"), "cancel", { goalId }, { deadlineMs: TURN_ACCEPT_DEADLINE_MS });
158
+ if (reply.reply.ok !== false || (await readGoalResult(actx, ref)) !== undefined)
159
+ return;
160
+ if (accepter === undefined || reply.responder.instanceId === accepter) {
161
+ const err = reply.reply.error;
162
+ throw new EpEnvelopeError(err.code, `the relay "${goalId}" could not be withdrawn from its seat: ${err.message}`);
163
+ }
164
+ if (attempt === MANAGER_ROUTE_ATTEMPTS)
165
+ throw new Error(`the relay "${goalId}" was accepted by manager instance ${accepter}, but none of ${attempt + 1} cancels was answered by it; the discharge stays open to retry`);
166
+ this.managerServices.delete("cancel");
167
+ }
168
+ }
169
+ /**
170
+ * Withdraw a cancelled step's relay before the cancellation leaves the step, so the scope it
171
+ * settles shows the seat nothing the run withdrew. A withdrawal that fails is tried again rather
172
+ * than left to the discharge, which runs only when the run ends: until then the relay would stay
173
+ * first on the seat and hold back the run's next turn to it. The retries stop when the relay's
174
+ * deadline passes, because the manager no longer serves it then, and a failure that outlasts it
175
+ * is the step's error. A refusal no retry can change is the step's error at once, since retrying
176
+ * it would only hold the cancelled step in its scope until that deadline: of the refusals, only
177
+ * `unavailable` (a manager still reconciling at boot) and `deadline-exceeded` (a lost reply) are
178
+ * tried again.
179
+ *
180
+ * That deadline is read from the relay's goal, where the accepting manager recorded the instant
181
+ * it stops serving the relay; a withdrawal holds only the goal id. No deadline is known until that
182
+ * goal is read, and the relay may be served until then, so a failed read is tried again as well.
183
+ * A goal record that can never yield a deadline is thrown.
184
+ */
185
+ async withdrawCancelledRelay(goalId, deadlineAt) {
186
+ for (;;) {
187
+ try {
188
+ if (deadlineAt === undefined) {
189
+ const spec = (await readGoalSpec(await this.actionCtx(), { endpoint: this.binding.endpoint, caller: this.binding.caller, goalId }))?.value;
190
+ if (spec === undefined)
191
+ return;
192
+ if (spec.readinessDeadlineMs === undefined)
193
+ throw new EpEnvelopeError("internal", `the relay "${goalId}" was accepted with no deadline on its goal; a garbled acceptance never authorizes (SPEC 13.6)`);
194
+ deadlineAt = spec.acceptedAt + spec.readinessDeadlineMs;
195
+ }
196
+ return await this.handler.withdrawRelay(goalId);
197
+ }
198
+ catch (e) {
199
+ const final = e instanceof EpEnvelopeError && e.code !== "unavailable" && e.code !== "deadline-exceeded";
200
+ if (deadlineAt === undefined ? e instanceof EpEnvelopeError : final || this.now() >= deadlineAt)
201
+ throw e;
202
+ }
203
+ await delay(WAIT_POLL_MS);
204
+ }
205
+ }
206
+ /** Every live presence row {@link isPresenceRow} accepts under its KV key. Foreign bytes in
207
+ * the bucket are skipped — a peer's malformed self-publish must not break another agent's name
208
+ * resolution — and what an ABSENT row means belongs to the caller: `resolveMemberPrincipal`
209
+ * refuses the join loudly, and `waitDown` reads it as the death it is waiting for. */
210
+ async presenceRows() {
211
+ const rows = [];
212
+ for (const e of await liveKvEntries(await this.presenceRegistry())) {
213
+ let row;
214
+ try {
215
+ row = e.json();
216
+ }
217
+ catch {
218
+ continue;
219
+ }
220
+ if (isPresenceRow(row, e.key))
221
+ rows.push(row);
222
+ }
223
+ return rows;
224
+ }
225
+ /** One poll of the presence death watch `wait(down)` and `turn` share. `undefined` means this
226
+ * incarnation is still live, or a lapse has not yet stood for {@link LAPSE_CONFIRM_MS}. A missing
227
+ * incarnation is `"superseded"` when a live row holds the name and `"lapsed"` when nothing does.
228
+ * `watch` is the caller's own window, written here and read on the next poll. An incomplete scan
229
+ * decides nothing and returns `undefined`; every other read failure is raised. */
230
+ async presenceDeath(name, uid, watch, decided) {
231
+ let rows;
232
+ const readAt = this.now();
233
+ try {
234
+ rows = await this.handler.presenceRows();
235
+ }
236
+ catch (e) {
237
+ // `liveKvEntries` REFUSES a pass cut short mid-scan instead of returning a partial view —
238
+ // and a partial view is exactly what must not decide a death. Its own contract says retry,
239
+ // so the next poll is the retry; a link that stays down keeps surfacing here rather than
240
+ // as a false DOWN, and the caller's deadline still ends the wait.
241
+ if (e instanceof IncompleteKvScan)
242
+ return undefined;
243
+ throw e;
244
+ }
245
+ if (!rows.some((p) => p.card.name === name && p.lifecycleUid === uid)) {
246
+ const reason = rows.some((p) => p.card.name === name) ? "superseded" : "lapsed";
247
+ watch.lapsedSince = lapseWindow(watch.lapsedSince, watch.lastReadAt ?? 0, this.now());
248
+ if (reason === "superseded" || readAt - watch.lapsedSince >= LAPSE_CONFIRM_MS) {
249
+ if (reason === "lapsed" && !(await this.lapseStands(name, uid, decided)))
250
+ watch.lapsedSince = undefined;
251
+ else {
252
+ watch.lastReadAt = readAt;
253
+ return reason;
254
+ }
255
+ }
256
+ }
257
+ else
258
+ watch.lapsedSince = undefined;
259
+ watch.lastReadAt = readAt;
260
+ return undefined;
261
+ }
262
+ /** Whether a lapse of `name#uid` confirmed from presence stands as the death, asked of the manager
263
+ * first. A lapse is only the seat's heartbeats going quiet: on a loaded host a live seat's presence
264
+ * writer stalls past {@link LAPSE_CONFIRM_MS} while its process goes on working (#2807), and the
265
+ * manager owns that process. Only the manager holding the seat has a running row under its
266
+ * incarnation, so that row keeps it alive whoever reports it. A miss decides only from the manager
267
+ * that allocated it, the committer of its spawn terminal: another member of the class rail knows
268
+ * only its own seats, so the class rail is asked again, as a spawn's discharge asks it. An allocator
269
+ * that does not answer leaves presence as the only witness, which is the case presence is the
270
+ * authority for: the manager died with the seat. The asking can outlast the caller's own
271
+ * cancellation, deadline or terminal, so once `decided` holds nothing stands and no refusal is
272
+ * raised: that authority decides at the caller's next check. */
273
+ async lapseStands(name, uid, decided) {
274
+ const entry = this.roster.get(name);
275
+ const spawned = entry?.uid === uid && entry.goalId !== undefined
276
+ ? await readGoalResult(await this.actionCtx(), { endpoint: this.binding.endpoint, caller: this.binding.caller, goalId: entry.goalId })
277
+ : undefined;
278
+ const allocator = spawned?.committer?.instanceId;
279
+ for (let attempt = 0; attempt <= MANAGER_ROUTE_ATTEMPTS; attempt += 1) {
280
+ if (await decided())
281
+ return false;
282
+ let answer;
283
+ try {
284
+ answer = await this.invokeManager(await this.manager("inspect"), "inspect", { name }, {});
285
+ }
286
+ catch (e) {
287
+ if (unansweredRequest(e))
288
+ break;
289
+ if (await decided())
290
+ return false;
291
+ throw e;
292
+ }
293
+ const { reply, responder } = answer;
294
+ const row = reply.ok ? reply.data : undefined;
295
+ if (row?.lifecycleUid === uid && row.status === "running")
296
+ return false;
297
+ if (responder.instanceId === allocator && !replyRefusedBeforeEffect(reply.error)) {
298
+ if (reply.ok || reply.error?.code === "not-found")
299
+ break;
300
+ if (await decided())
301
+ return false;
302
+ throw new Error(`inspect(${name}) was refused by manager instance ${allocator}, which allocated ${name}#${uid}: ${reply.error?.message ?? "refused with no message"}`);
303
+ }
304
+ this.managerServices.delete("inspect");
305
+ }
306
+ return !(await decided());
307
+ }
308
+ }
309
+ //# sourceMappingURL=mesh-seat-watch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mesh-seat-watch.js","sourceRoot":"","sources":["../src/mesh-seat-watch.ts"],"names":[],"mappings":"AAAA;;;gEAGgE;AAChE,OAAO,EACL,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,YAAY,EAAE,cAAc,EAC5H,wBAAwB,EAAE,iBAAiB,GAE5C,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,aAAa,EAA8C,MAAM,gBAAgB,CAAC;AAExG,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EACL,sBAAsB,EAAE,uBAAuB,EAAE,YAAY,EAAE,eAAe,GAE/E,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC;;;;;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AAC,MAAM,OAAO,EAAE,CAAC,CAAC;IAC5B,CAAC;CACF"}
@@ -0,0 +1,181 @@
1
+ /** A run's turn and ask clients: `turn` wakes a seat of this run and reads its yield, `ask` relays a
2
+ * schema-checked pause to a seat and judges its answers, and the roster lookups both share. The
3
+ * mesh handler composes it; the run-memory maps it writes are the handler's, mutated in place, and
4
+ * every input, the handler's own members included, is read through the handler at its use. */
5
+ import { type ActionContext, type CheckpointRef, type CheckpointSettleFact, type EpAttributedReply, type EpVerbTarget, type GoalRef, type ResolvedService } from "@cotal-ai/core";
6
+ import { type AgentHandleValue, type AskRequest, type CancelSignal, type EffectContext, type TurnRequest, type TurnResultValue } from "@cotal-ai/lang";
7
+ import type { KV } from "@nats-io/kv";
8
+ import { type LoopLagObserver } from "./host-starvation.js";
9
+ import { type MeshHandlerBinding, type RunMeshServices, type SeatAddress } from "./mesh-handler.js";
10
+ import type { DeathWatch } from "./mesh-seat-watch.js";
11
+ /** The roster fields the turn and ask clients read; the handler's entries carry more. */
12
+ interface TurnAskRosterEntry {
13
+ handle: AgentHandleValue;
14
+ owner?: string;
15
+ actor?: string;
16
+ uid: string;
17
+ permits?: {
18
+ turns?: number;
19
+ wallClockMs?: number;
20
+ };
21
+ spawnedAt?: number;
22
+ host?: string;
23
+ }
24
+ /** What the turn and ask clients read from the handler that composes them, each at its use. The
25
+ * maps are the handler's own instances, never copies. */
26
+ export interface TurnAskDeps {
27
+ self(): unknown;
28
+ binding(): MeshHandlerBinding;
29
+ kv(): KV;
30
+ services(): RunMeshServices | undefined;
31
+ lag(): LoopLagObserver;
32
+ onStarved(): (note: string) => void;
33
+ roster(): ReadonlyMap<string, TurnAskRosterEntry>;
34
+ turnsTaken(): Map<string, number>;
35
+ handoffMemos(): Map<string, {
36
+ to: string;
37
+ fromGoalId: string;
38
+ } | "ambiguous">;
39
+ turnGoals(): Map<string, Set<string>>;
40
+ now(): number;
41
+ actionCtx(): Promise<ActionContext>;
42
+ manager(command: string, instanceId?: string): Promise<ResolvedService>;
43
+ invokeManager(service: ResolvedService, command: string, args: Record<string, unknown> | undefined, opts: {
44
+ target?: EpVerbTarget;
45
+ deadlineMs?: number;
46
+ id?: string;
47
+ }): Promise<EpAttributedReply>;
48
+ relayManagerBeforeSubmit(host: string | undefined, command: string, ref: GoalRef, kind: "turn" | "ask" | "checkpoint", label: string): Promise<ResolvedService>;
49
+ arm(ref: CheckpointRef, deadline: number): Promise<void>;
50
+ expired(ref: CheckpointRef | undefined): Promise<CheckpointSettleFact | undefined>;
51
+ cancelTimer(ref: CheckpointRef): Promise<void>;
52
+ settle(ref: CheckpointRef, signal?: CancelSignal, relayed?: boolean): Promise<CheckpointSettleFact>;
53
+ presenceDeath(name: string, uid: string, watch: DeathWatch, decided: () => Promise<boolean>): Promise<"superseded" | "lapsed" | undefined>;
54
+ relayToSeat(seat: SeatAddress, goalId: string, payload: string, deadlineAt: number, kind: "ask" | "checkpoint", step: string): Promise<void>;
55
+ withdrawCancelledRelay(goalId: string, deadlineAt?: number): Promise<void>;
56
+ recordTurnGoal(handle: string, goalId: string): void;
57
+ recordHandoffMemo(scope: string, to: string, fromGoalId: string): void;
58
+ }
59
+ /** The turn and ask members of a mesh handler, over the handler's own inputs. */
60
+ export declare class TurnAsk {
61
+ private readonly deps;
62
+ constructor(deps: TurnAskDeps);
63
+ private get handler();
64
+ private get binding();
65
+ private get kv();
66
+ private get services();
67
+ private get lag();
68
+ private get onStarved();
69
+ private get roster();
70
+ private get turnsTaken();
71
+ private get handoffMemos();
72
+ private get turnGoals();
73
+ private now;
74
+ private actionCtx;
75
+ private manager;
76
+ private invokeManager;
77
+ private relayManagerBeforeSubmit;
78
+ private arm;
79
+ private expired;
80
+ private cancelTimer;
81
+ private settle;
82
+ private presenceDeath;
83
+ private relayToSeat;
84
+ private withdrawCancelledRelay;
85
+ private recordTurnGoal;
86
+ private recordHandoffMemo;
87
+ /**
88
+ * `turn` wakes ONE AGENT for one turn, over the manager's relay (a seat is not an endpoint):
89
+ * the manager accepts the goal, parks the rendered context durably, the seat pulls and yields
90
+ * under its own self reach, and the yield is this goal's terminal. The request id is the goalId,
91
+ * the same recovery discipline as `spawn`: a resumed run re-enters the poll, never re-submits.
92
+ *
93
+ * THREE AUTHORITIES END IT, one per ending. The seat's yield is the manager's `succeeded`
94
+ * terminal, carrying the TurnResult. The DEADLINE is double-covered: the manager arms a
95
+ * goal-bound hold (its expiry commits `failed` reason `turn-deadline`), and this client arms its
96
+ * OWN pause under the step's request id — the L4003 authority that survives a dead manager.
97
+ * DEATH: the manager's reap hook marks pending turns; death rides the deadline terminal as
98
+ * `agentDownAt`. This client's presence watch is the early L4002 authority even while the
99
+ * manager runs. The watch reads death the way `wait(down)` does: a superseded incarnation at
100
+ * once, a lapsed row only once it has stayed absent for {@link LAPSE_CONFIRM_MS} and its manager
101
+ * no longer runs the seat.
102
+ *
103
+ * Handoff honoring (lang §5.3) happens HERE: the scope's pending memo is spent at every turn's
104
+ * begin, and when this turn targets its `to`, the link rides the submission (`handoffFrom`, the
105
+ * manager mirrors it into the terminal) and the bound external state. A handoff YIELD is
106
+ * validated against the run roster: an addressee outside it is L4005, one in a different
107
+ * worktree is L4004.
108
+ */
109
+ turn(req: TurnRequest, ctx: EffectContext): Promise<TurnResultValue>;
110
+ /**
111
+ * A yielded handoff's refusal class: L4005 when the addressee is not in this run's roster,
112
+ * L4004 when it sits in a different worktree than the seat handing off, undefined when the
113
+ * handoff is honorable. One reading for the turn that raises it and the `wait(replied)` that
114
+ * must not count it, so the two observers never diverge on a spoofed or misdirected `to`.
115
+ */
116
+ handoffRefusal(fromWorktree: string | undefined, to: unknown): "L4005" | "L4004" | undefined;
117
+ /** Map a turn goal's terminal onto the effect's contract: `succeeded` carries the TurnResult
118
+ * (a handoff addressee resolved against the roster — L4005 outside it, L4004 across
119
+ * worktrees), `failed` splits on the manager's recorded reason, `cancelled` unwinds. The
120
+ * consumed notices are marked HERE, by the goal that carried them, tolerating the re-entry
121
+ * conflict (a crash between the terminal and the mark re-marks on resume). */
122
+ private turnOutcome;
123
+ /**
124
+ * `ask` is a schema-checked pause the ADDRESSED AGENT is expected to answer.
125
+ *
126
+ * Each attempt is one checkpoint-plane pause — the same mint, settle and answer record a
127
+ * `checkpoint` rides, answered through the run driver's `resolveCheckpoint` (`cotal run
128
+ * answer`), which is how "the agent publishes a record" reaches a holder-bound plane: the agent,
129
+ * or anyone the run's ACL admits on its behalf, answers through the driver exactly as a human
130
+ * answers a checkpoint. What `ask` adds is the handler-side contract of §6.5: the schema is read
131
+ * as the SHORTHAND (refused L4022 when it cannot be), every answer is checked against it, a
132
+ * non-conforming answer costs one attempt and the refusal reason is bound onto the entry for the
133
+ * answerer to read, and exhausted attempts are the effect's own catchable L4006.
134
+ *
135
+ * **One absolute deadline for the whole ask**, computed once and bound with the first attempt: a
136
+ * re-ask does not restart the clock, or a stream of non-conforming answers could stretch the
137
+ * pause forever. The deadline elapsing with no conforming answer is the ask's own L4006, the
138
+ * same outcome exhausted attempts name: the budget it ran out of is the ask's, and L4003 belongs
139
+ * to a `turn` whose own deadline elapsed.
140
+ *
141
+ * **Attempt N's token derives from the step's request id** (attempt 1 IS the request id), and
142
+ * the CURRENT attempt's token is bound as `askToken` before its pause is armed — so a resume
143
+ * re-enters the attempt in flight, an answer judged non-conforming just before a crash is
144
+ * re-judged identically from its durable settle, and the discharge and the adoption re-arm
145
+ * address the one timer that is actually armed.
146
+ */
147
+ ask(req: AskRequest, ctx: EffectContext): Promise<unknown>;
148
+ /**
149
+ * One ask attempt's relay to the addressed seat: a `turn` goal under the attempt's token whose
150
+ * payload carries the ask (token, schema, attempt, deadline, the previous refusal), rendered by
151
+ * the seat's connector as the request to answer. The goal is the seat's to yield when it has
152
+ * answered; the ask itself settles on the checkpoint plane, so the relay's terminal is never
153
+ * read here, and it is never a reply `wait(replied)` observes. A seat the serve boundary reports
154
+ * gone is the agent-down failure (L4002).
155
+ */
156
+ private askSeat;
157
+ /**
158
+ * Where a relay to an agent of this run is addressed: the roster entry under the handle's name,
159
+ * at the handle's incarnation, with the owner/actor coordinates its acceptance floor served.
160
+ * One resolver for the three relays (`turn`, `ask`, an escalation), because the three
161
+ * dispositions differ and the lookup does not: a turn and an ask refuse, an escalation stands.
162
+ */
163
+ seatAddress(name: string, uid?: string): {
164
+ address: SeatAddress;
165
+ why?: undefined;
166
+ } | {
167
+ address?: undefined;
168
+ why: "not-in-roster" | "no-floor";
169
+ };
170
+ /**
171
+ * The principal a `message` wait's `from` handle names, as `<owner>.<actor>`: the coordinates
172
+ * this run's roster recorded when it spawned the seat or bound the participant. A message
173
+ * answers only when its subject's sender is that principal. A handle outside the roster, or one
174
+ * whose coordinates were never served, refuses: matching it on a display name would let any peer
175
+ * that names itself after the agent answer.
176
+ */
177
+ waitSender(agent: string): string;
178
+ private relayAsk;
179
+ }
180
+ export {};
181
+ //# sourceMappingURL=mesh-turn-ask.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mesh-turn-ask.d.ts","sourceRoot":"","sources":["../src/mesh-turn-ask.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,OAAO,EAEL,KAAK,aAAa,EAAE,KAAK,aAAa,EAAE,KAAK,oBAAoB,EAAE,KAAK,iBAAiB,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EACrG,KAAK,eAAe,EAC1C,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,gBAAgB,EAAqB,KAAK,UAAU,EAAE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAE,KAAK,WAAW,EAClH,KAAK,eAAe,EACrB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EAA2B,KAAK,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACrF,OAAO,EAEL,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,KAAK,WAAW,EAChE,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,UAAU,EA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