@niwa-labs/sessions 0.0.0-stage → 0.0.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.
package/src/records.ts ADDED
@@ -0,0 +1,395 @@
1
+ /**
2
+ * The records niwa writes about sessions.
3
+ *
4
+ * These are niwa's own records: what niwa knows about a session, said in niwa's own words. The
5
+ * harness's own records are NOT copied here — the reading side reads those on demand.
6
+ *
7
+ * What is written is what only niwa can know: that a session was started, that a turn began and
8
+ * ended, that there was activity, that the session ended, and whom it serves.
9
+ */
10
+
11
+ import { z } from "zod";
12
+
13
+ import { actionName, record, stableJson, Address } from "@niwa-labs/core";
14
+ import type { ActionName } from "@niwa-labs/core";
15
+ import {
16
+ DeliveryReceiptSchema,
17
+ InputOutcomeSchema,
18
+ ModelNameSchema,
19
+ OptionBlocksSchema,
20
+ PermissionMarkSchema,
21
+ ProtocolNameSchema,
22
+ SessionModeSchema,
23
+ ToolsModeSchema,
24
+ VariantNameSchema,
25
+ } from "@niwa-labs/harness";
26
+ import { BoxAccessSchema, BoxManifestSchema } from "@niwa-labs/sandbox";
27
+
28
+ import { NiwaSessionIdSchema, SessionRefSchema } from "./identity.ts";
29
+ import type { DeliveryReceipt } from "@niwa-labs/harness";
30
+
31
+ // What became of a message sent into a session: the harness defines it, and the modules that
32
+ // speak to sessions read it from here.
33
+ export { DeliveryReceiptSchema };
34
+ export type { DeliveryReceipt };
35
+
36
+ /** The name of the action that sends a message into a session. */
37
+ export const SESSION_SEND: ActionName = actionName("session.send");
38
+
39
+ /** What a module asks of the sessions module to send a message into a session. */
40
+ export interface SessionSendInput {
41
+ /** The session, as the sessions module names it. */
42
+ session: string;
43
+ /** The text of the message. */
44
+ message: string;
45
+ }
46
+
47
+ /** What the sessions module answers. */
48
+ export interface SessionSendOutput {
49
+ /** What became of the message. */
50
+ receipt: DeliveryReceipt;
51
+ }
52
+
53
+ const LaunchContext = {
54
+ execution: z.string().optional(),
55
+ run: z.string().min(1).optional(),
56
+ parentSession: SessionRefSchema.optional(),
57
+ /** Effective access items, including defaults; the starting point for nested boxes. */
58
+ boxAccess: BoxAccessSchema.optional(),
59
+ disabledTools: z.array(z.string()).optional(),
60
+ };
61
+
62
+ /**
63
+ * A session was started.
64
+ *
65
+ * The session is named here: niwa writes the record only once the harness has given the session
66
+ * its id. A start that has not produced an id yet has no record.
67
+ */
68
+ export const SessionStarted = record(
69
+ "session.started",
70
+ z.object({
71
+ /** The session that was started: the harness and the id it gave. */
72
+ session: SessionRefSchema,
73
+ ...LaunchContext,
74
+ /** The id niwa gave it, issued from the starting call. */
75
+ id: NiwaSessionIdSchema,
76
+ /** The working directory it was started in, when it was given one. */
77
+ cwd: z.string().optional(),
78
+ /** The effort it was asked to start with, when one was chosen. */
79
+ effort: z.string().optional(),
80
+ /** The working mode the session was given: the one asked for, or the instance's, or the default. */
81
+ mode: SessionModeSchema.optional(),
82
+ /** The options block of its kind the session was started with, so a resume starts it again with them; absent when it had none. */
83
+ options: OptionBlocksSchema.optional(),
84
+ /** The tools the session was started with, so a resume launches it with the same; absent for the harness's own. */
85
+ tools: ToolsModeSchema.optional(),
86
+ /** What the start asked of its box, so a resume launches it in the same; absent when it asked nothing. */
87
+ box: BoxAccessSchema.optional(),
88
+ /** How long, in milliseconds, a turn may go with no progress before the session counts as stuck; absent when none was set. */
89
+ stuckAfter: z.number().int().positive().optional(),
90
+ }),
91
+ { providerOnly: "sessions" },
92
+ );
93
+
94
+ /**
95
+ * The harness named the model the session runs.
96
+ *
97
+ * A session has one model: the one the harness says, not the alias it was asked for. The start
98
+ * cannot know it, as most harnesses name it only after the start, so it is a record of its own,
99
+ * written when the harness names it. Until then the model of the session is unknown. A resume
100
+ * starts the session with the latest one.
101
+ */
102
+ export const SessionModel = record(
103
+ "session.model",
104
+ z.object({
105
+ /** The session that runs the model. */
106
+ session: SessionRefSchema,
107
+ /** The model, as the harness named it. */
108
+ model: ModelNameSchema,
109
+ }),
110
+ );
111
+
112
+ /** A turn began: the session is working. */
113
+ export const SessionTurnStarted = record(
114
+ "session.turn-started",
115
+ z.object({
116
+ /** The session the turn belongs to. */
117
+ session: SessionRefSchema,
118
+ /** The number of the turn. */
119
+ turn: z.number().int().positive(),
120
+ }),
121
+ );
122
+
123
+ /**
124
+ * How a turn ended: `interrupted` when niwa interrupted it on request; otherwise what the harness
125
+ * said of it, `completed`, `failed` or `unknown` (nobody knows what became of it).
126
+ */
127
+ export const TurnEnding = z.enum(["completed", "interrupted", "failed", "unknown"]);
128
+ export type TurnEnding = z.infer<typeof TurnEnding>;
129
+
130
+ /** A turn ended: the session is not working on that turn any more. */
131
+ export const SessionTurnEnded = record(
132
+ "session.turn-ended",
133
+ z.object({
134
+ /** The session the turn belongs to. */
135
+ session: SessionRefSchema,
136
+ /** The number of the turn. */
137
+ turn: z.number().int().positive(),
138
+ /**
139
+ * How it ended: `interrupted` when niwa interrupted it on request, otherwise what the harness
140
+ * said of the turn, and `completed` when it said nothing. A record written before niwa said
141
+ * how has none: it reads as completed.
142
+ */
143
+ how: TurnEnding.optional(),
144
+ }),
145
+ );
146
+
147
+ /** The name of a tool: a short identifier, which cannot carry free text. */
148
+ export const ActivityToolSchema = z.string().regex(/^[A-Za-z0-9_.:\-]{1,64}$/);
149
+
150
+ /**
151
+ * Something happened in the session: a sign of life. Only that it happened, never what, except for
152
+ * the name of the tool it is a call of (a bounded identifier, never free text) and a decision the
153
+ * harness made on a tool call by itself (without its free-text reason): the latest of each in a
154
+ * throttle window is kept as it was said.
155
+ */
156
+ export const SessionActivity = record(
157
+ "session.activity",
158
+ z.object({
159
+ /** The session the activity belongs to. */
160
+ session: SessionRefSchema,
161
+ /** The decision the harness made on a tool call without asking, when the activity is one. */
162
+ permission: PermissionMarkSchema.optional(),
163
+ /** The tool the latest call of the window was of. */
164
+ tool: ActivityToolSchema.optional(),
165
+ }),
166
+ );
167
+
168
+ /**
169
+ * Claude Code's advisor (a stronger model it asks for a review) was called, or answered: the kind
170
+ * of the answer, never its text.
171
+ */
172
+ export const SessionAdvisor = record(
173
+ "session.advisor",
174
+ z.object({
175
+ session: SessionRefSchema,
176
+ phase: z.enum(["started", "finished"]),
177
+ /** The harness's id of the advisor's call, so the answer is paired with it. */
178
+ callId: z.string().min(1),
179
+ model: z.string().optional(),
180
+ result: z.enum(["text", "redacted", "error"]).optional(),
181
+ errorCode: z.string().optional(),
182
+ }),
183
+ );
184
+
185
+ /**
186
+ * The harness said something niwa does not know: a variant of its wire protocol that this build
187
+ * of niwa was not made for, because the harness got newer. The session goes on; the message is
188
+ * kept as it arrived, so that it can be read and the build taught.
189
+ */
190
+ export const SessionUnknownVariant = record(
191
+ "session.unknown-variant",
192
+ z.object({
193
+ /** The session the message came in. */
194
+ session: SessionRefSchema,
195
+ /** The wire protocol. */
196
+ protocol: ProtocolNameSchema,
197
+ /** The value of the message's discriminator that is not known. */
198
+ variant: VariantNameSchema,
199
+ /** The message as it arrived, or its beginning when it is long. */
200
+ raw: z.json(),
201
+ }),
202
+ );
203
+
204
+ /**
205
+ * The harness compacted the session by itself.
206
+ *
207
+ * The summary is the harness's own and niwa does not rewrite it. It is kept because it is the
208
+ * seed of the next session, and the best seed there is: the harness wrote it, knowing what it
209
+ * was dropping.
210
+ */
211
+ export const SessionCompacted = record(
212
+ "session.compacted",
213
+ z.object({
214
+ /** The session that was compacted. */
215
+ session: SessionRefSchema,
216
+ /** The harness's own summary. */
217
+ summary: z.string(),
218
+ }),
219
+ );
220
+
221
+ /** The session ended: it will not work again. */
222
+ export const SessionEnded = record(
223
+ "session.ended",
224
+ z.object({
225
+ /** The session that ended. */
226
+ session: SessionRefSchema,
227
+ /** Why it ended, when there is a reason to give. */
228
+ reason: z.string().optional(),
229
+ }),
230
+ );
231
+
232
+ /**
233
+ * Where an attachment came from.
234
+ *
235
+ * - `explicit` — a person or a plugin chose it;
236
+ * - `insert` — the insert inside the harness reported it;
237
+ * - `directory` — it was read from the working directory the session runs in;
238
+ * - `judgement` — it was inferred.
239
+ */
240
+ export const BelongingSource = z.enum(["explicit", "insert", "directory", "judgement"]);
241
+ export type BelongingSource = z.infer<typeof BelongingSource>;
242
+
243
+ /**
244
+ * Whom a session serves.
245
+ *
246
+ * A session has no relation fields of its own: where it came from is its cause. Whom it serves —
247
+ * an agent, a task — is a separate record of belonging, written with its source.
248
+ */
249
+ export const SessionBelongs = record(
250
+ "session.belongs",
251
+ z.object({
252
+ /** The session that serves this address. */
253
+ session: SessionRefSchema,
254
+ /**
255
+ * Whom the session serves.
256
+ *
257
+ * An address is a tagged value, never a bare string: the kind says what it is, so a reader
258
+ * does not have to guess.
259
+ */
260
+ to: Address,
261
+ /** Where the attachment came from. */
262
+ source: BelongingSource,
263
+ }),
264
+ );
265
+
266
+ /**
267
+ * Do two addresses name the same thing?
268
+ *
269
+ * The comparison is on the value: two addresses that say the same are the same address, however
270
+ * their keys were written.
271
+ */
272
+ export function sameAddress(one: Address, other: Address): boolean {
273
+ return stableJson(one) === stableJson(other);
274
+ }
275
+
276
+ /**
277
+ * The niwa MCP server a session was given carries this mark, and the mark names the session.
278
+ *
279
+ * The server is started by the harness, not by niwa, so it cannot know which session it serves;
280
+ * it is given a random mark in its environment (`NIWA_SESSION_MARK`) and asks niwa by the mark.
281
+ * The pairing is written once the harness has named the session: start and resume each write
282
+ * their own mark.
283
+ */
284
+ export const SessionMarked = record(
285
+ "session.marked",
286
+ z.object({
287
+ /** The session the server serves. */
288
+ session: SessionRefSchema,
289
+ /** The mark the server was given. */
290
+ mark: z.string().min(1),
291
+ }),
292
+ { providerOnly: "sessions" },
293
+ );
294
+
295
+ /**
296
+ * The box a session's process is about to be started in, kept before the process exists: the
297
+ * request with where each item came from, the paths it resolved to and where each came from, what
298
+ * was closed and left out, the rules of the caller's grant it took, and the policy the sandbox
299
+ * reports it applies. The mark is the one the session was started with, and `session.marked`
300
+ * pairs it with the session once the harness has named it. The environment of the process is kept
301
+ * by its names only: its values hold the session's token and the keys a harness is given for its
302
+ * provider, and the journal keeps neither.
303
+ */
304
+ export const SessionBoxManifest = record(
305
+ "session.box.manifest",
306
+ BoxManifestSchema.extend({
307
+ /** The mark of the session whose process this is. */
308
+ mark: z.string().min(1),
309
+ /** The harness instance that starts the process. */
310
+ harness: z.string().min(1),
311
+ }),
312
+ );
313
+
314
+ /**
315
+ * An input given an operation id by its caller is about to be sent into a session: written before
316
+ * the send, so a host that stops in the middle of it knows the input may have gone.
317
+ */
318
+ export const SessionInputSending = record(
319
+ "session.input.sending",
320
+ z.object({
321
+ session: SessionRefSchema,
322
+ /** The id the caller gave the operation: a retry with it is answered from these records. */
323
+ operation: z.string().min(1),
324
+ /** The SHA-256 of the input, so a retry with another body under the same id is told apart. */
325
+ digest: z.string().min(1),
326
+ }),
327
+ );
328
+
329
+ /** What became of an input that was given an operation id: accepted, never sent, or possibly sent. */
330
+ export const SessionInputSettled = record(
331
+ "session.input.settled",
332
+ z.object({
333
+ session: SessionRefSchema,
334
+ operation: z.string().min(1),
335
+ outcome: InputOutcomeSchema,
336
+ }),
337
+ );
338
+
339
+ /**
340
+ * A start given an operation id is about to ask its harness for a session: written before anything is
341
+ * sent, so a retry while it runs, or after a host stopped in the middle of it, never starts a second one.
342
+ */
343
+ export const SessionStartReserved = record(
344
+ "session.start.reserved",
345
+ z.object({
346
+ ...LaunchContext,
347
+ mark: z.string().optional(),
348
+ tools: ToolsModeSchema.optional(),
349
+ operation: z.string().min(1),
350
+ /** The SHA-256 of the starting identity and input, so another caller or request cannot replay it. */
351
+ digest: z.string().min(1),
352
+ /** The directory the session is started in, when it was given one. */
353
+ cwd: z.string().optional(),
354
+ }),
355
+ { providerOnly: "sessions" },
356
+ );
357
+
358
+ /** The harness named the session of a start under an operation, before its first prompt went. */
359
+ export const SessionStartNamed = record(
360
+ "session.start.named",
361
+ z.object({
362
+ operation: z.string().min(1),
363
+ session: SessionRefSchema,
364
+ }),
365
+ );
366
+
367
+ /** A start under an operation failed before anything reached its harness: a retry starts again. */
368
+ export const SessionStartUnsent = record(
369
+ "session.start.unsent",
370
+ z.object({
371
+ operation: z.string().min(1),
372
+ reason: z.string(),
373
+ }),
374
+ );
375
+
376
+ /** The record types this module declares, in the order they are declared. */
377
+ export const SESSION_TYPES = [
378
+ SessionStarted,
379
+ SessionModel,
380
+ SessionTurnStarted,
381
+ SessionTurnEnded,
382
+ SessionActivity,
383
+ SessionAdvisor,
384
+ SessionUnknownVariant,
385
+ SessionCompacted,
386
+ SessionEnded,
387
+ SessionBelongs,
388
+ SessionMarked,
389
+ SessionBoxManifest,
390
+ SessionInputSending,
391
+ SessionInputSettled,
392
+ SessionStartReserved,
393
+ SessionStartNamed,
394
+ SessionStartUnsent,
395
+ ] as const;
package/src/refusal.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { NotSent } from "@niwa-labs/core";
2
+
3
+ /** A refusal: a session that cannot be started as it was asked for. Nothing was sent to its harness. */
4
+ export class SessionRefusal extends NotSent {
5
+ override name = "SessionRefusal";
6
+ /** The code of the refusal, so a caller can tell one from another. */
7
+ override readonly code: string;
8
+
9
+ constructor(code: string, message: string) {
10
+ super(message);
11
+ this.code = code;
12
+ }
13
+ }
package/src/reverse.ts ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Reverse requests, routed.
3
+ *
4
+ * A harness adapter hands over a `Question` and the raw request of its harness, and gets an
5
+ * answer back. This module decides where the answer comes from:
6
+ *
7
+ * 1. a permission the session's grant covers (a `tool:` rule that does not ask), or a tool of niwa's own MCP server
8
+ * (the server of a session that sees niwa actions: the grant is what shows its tools), is allowed;
9
+ * 2. a permission the starter already answered "allow always" for, in this session, is allowed;
10
+ * 3. everything else is a request to the one who started the session, through `request.ask`.
11
+ *
12
+ * Every question writes `session.reverse.asked` (the question, the raw request, which of the
13
+ * three routes it took) and `session.reverse.answered` (the answer, and who gave it). niwa has no
14
+ * deadline of its own: the request waits for the harness, which cancels it when it stops waiting.
15
+ */
16
+
17
+ import { randomUUID } from "node:crypto";
18
+
19
+ import { z } from "zod";
20
+
21
+ import { AnswerSchema, isSuspend, isToolSubject, match, OptionIdSchema, optionOfFlavor, permissionKey, pickedOptions, QuestionSchema, record, seq, Address } from "@niwa-labs/core";
22
+ import type { Answer, Grant, Question, QuestionOption, Step } from "@niwa-labs/core";
23
+ import type { PluginApi } from "@niwa-labs/plugin";
24
+ import type { RequestId } from "@niwa-labs/requests/records";
25
+ import type { ReverseHandler } from "@niwa-labs/harness";
26
+ import { QuestionName, RequestCreated, answeredBy, requestAsk, requestCancel, requestFind } from "@niwa-labs/requests/records";
27
+
28
+ import { SessionRefSchema, sessionRef } from "./identity.ts";
29
+ import type { SessionRef } from "./identity.ts";
30
+ import { SessionEnded } from "./records.ts";
31
+
32
+ /** The id of one reverse request. */
33
+ export const ReverseIdSchema = z.string().min(1).brand<"ReverseId">();
34
+ export type ReverseId = z.output<typeof ReverseIdSchema>;
35
+
36
+ /** The name of the question the starter is asked. */
37
+ export const REVERSE_QUESTION = "session.reverse";
38
+ const QUESTION_NAME = QuestionName.parse(REVERSE_QUESTION);
39
+
40
+ /** The id of the option niwa adds to a permission, so that the starter may allow it for the rest of the session. */
41
+ const ALWAYS_OPTION_ID = OptionIdSchema.parse("niwa.allow_always");
42
+
43
+ /** Where an answer comes from. */
44
+ const ReverseRouteSchema = z.enum(["starter", "grant", "remembered"]);
45
+
46
+ /** What the harness asked, as it came. */
47
+ const RawRequestSchema = z.object({ method: z.string(), params: z.unknown() });
48
+
49
+ /** A harness asked its client for something: the question, and the harness's own request whole. */
50
+ export const SessionReverseAsked = record(
51
+ "session.reverse.asked",
52
+ z.object({
53
+ id: ReverseIdSchema,
54
+ session: SessionRefSchema,
55
+ /** Who answers it: the starter, the session's own grant, or niwa's memory of an "allow always". */
56
+ route: ReverseRouteSchema,
57
+ /** The one who started the session, when it is the one asked. */
58
+ starter: Address,
59
+ /** The question as the starter sees it: a permission carries the option to allow it always. */
60
+ question: QuestionSchema,
61
+ raw: RawRequestSchema,
62
+ }),
63
+ );
64
+
65
+ /** The question was answered, and by whom: the starter, a grant, or the memory of an "allow always"; or it ended with no answer. */
66
+ export const SessionReverseAnswered = record(
67
+ "session.reverse.answered",
68
+ z.object({
69
+ id: ReverseIdSchema,
70
+ session: SessionRefSchema,
71
+ by: z.enum(["starter", "grant", "remembered", "cancelled"]),
72
+ /** The answer the adapter was given. */
73
+ answer: AnswerSchema,
74
+ /** For the rest of the session, a permission of this key is allowed: set when the starter said "allow always". */
75
+ always: z.string().optional(),
76
+ }),
77
+ );
78
+
79
+ /** The harness stopped waiting for the answer. */
80
+ export const SessionReverseCancelled = record(
81
+ "session.reverse.cancelled",
82
+ z.object({
83
+ id: ReverseIdSchema,
84
+ session: SessionRefSchema,
85
+ starter: Address,
86
+ }),
87
+ );
88
+
89
+ /** The record types of reverse requests. */
90
+ export const REVERSE_TYPES = [SessionReverseAsked, SessionReverseAnswered, SessionReverseCancelled] as const;
91
+
92
+ /** A permission question with the option to allow it for the rest of the session, when it can be allowed at all. */
93
+ function withAlways(question: Question): Question {
94
+ if (question.kind !== "permission" || optionOfFlavor(question, "allow_once") === undefined) return question;
95
+ const always: QuestionOption = { id: ALWAYS_OPTION_ID, label: "Allow always (this session)", flavor: "allow_always" };
96
+ const [first, ...rest] = question.options;
97
+ return first === undefined ? question : { ...question, options: [first, ...rest, always] };
98
+ }
99
+
100
+ /**
101
+ * The answer the adapter is given, and what niwa remembers, from what the starter answered.
102
+ *
103
+ * niwa never hands "allow always" to a harness: it answers the option that allows once, and
104
+ * remembers the key.
105
+ */
106
+ function settled(asked: Question, answer: Answer): { answer: Answer; always?: string } {
107
+ if (asked.kind !== "permission" || !isToolSubject(asked.subject)) return { answer };
108
+ const picked = pickedOptions(asked, answer)[0];
109
+ const once = optionOfFlavor(asked, "allow_once");
110
+ if (picked?.flavor !== "allow_always" || once === undefined) return { answer };
111
+ return { answer: { ids: [once.id] }, always: permissionKey(asked.subject) };
112
+ }
113
+
114
+ /** Why a request ended with no answer, by the name of the error the requests module throws. */
115
+ function endedWithoutAnswer(error: unknown): boolean {
116
+ return error instanceof Error && (error.name === "RequestCancelled" || error.name === "RequestExpired");
117
+ }
118
+
119
+ /** What the plugin gives a session's launch for its reverse requests. */
120
+ export interface ReverseRouting {
121
+ /**
122
+ * The handler a control side calls for the reverse requests of a session whose grant is `rules`, started by `starter`.
123
+ * `ownToolPrefix` is what the harness's names of the tools of niwa's own MCP server start with, when the session was
124
+ * given that server: those tools are allowed without asking.
125
+ */
126
+ handlerFor(rules: Grant, starter: Address, ownToolPrefix: string | undefined): ReverseHandler;
127
+ }
128
+
129
+ /** Install the handlers of reverse requests into the plugin. */
130
+ export function installReverse(api: PluginApi): ReverseRouting {
131
+ /** The handlers of this process that wait for an answer, by request: a process that was restarted has none. */
132
+ const waiting = new Map<ReverseId, (answer: Answer) => void>();
133
+
134
+ /**
135
+ * The request the starter was asked for a reverse question, when there is one: what the handler of
136
+ * the question wrote while it ran on the record of the question. The requests module finds it.
137
+ */
138
+ const requestOf = async (step: Step, reverse: ReverseId, key: string): Promise<RequestId | undefined> => {
139
+ const asked = api.journal?.()?.find({ type: SessionReverseAsked.name, field: "id", equals: reverse }).at(0);
140
+ if (asked === undefined) return undefined;
141
+ return (await step(requestFind, { cause: asked.id, question: REVERSE_QUESTION }, { key })).id;
142
+ };
143
+
144
+ /** Is a permission of this key allowed for the rest of the session? Only the answers since the last end of the session count. */
145
+ const remembered = (session: SessionRef, key: string): boolean => {
146
+ const journal = api.journal?.();
147
+ if (journal === undefined) return false;
148
+ const ended = journal.find({ type: SessionEnded.name, field: "session", equals: session }).at(-1)?.seq ?? seq(0);
149
+ return journal
150
+ .find({ type: SessionReverseAnswered.name, field: "session", equals: session })
151
+ .some((stored) => stored.seq > ended && SessionReverseAnswered.schema.safeParse(stored.data).data?.always === key);
152
+ };
153
+
154
+ /** The route that decides a permission without asking anybody, when one does. */
155
+ const decidedWithout = (session: SessionRef, rules: Grant, ownToolPrefix: string | undefined, question: Question): "grant" | "remembered" | undefined => {
156
+ if (question.kind !== "permission" || optionOfFlavor(question, "allow_once") === undefined) return undefined;
157
+ const subject = question.subject;
158
+ if (!isToolSubject(subject)) return undefined;
159
+ if (subject.tool !== undefined) {
160
+ if (ownToolPrefix !== undefined && subject.tool.startsWith(ownToolPrefix)) return "grant";
161
+ const covering = match(rules, "tool", subject.tool);
162
+ if (covering !== undefined && !covering.ask) return "grant";
163
+ }
164
+ return remembered(session, permissionKey(subject)) ? "remembered" : undefined;
165
+ };
166
+
167
+ /** Close what the starter was asked: answer with nothing, in the record. */
168
+ const closeUnanswered = async (step: Step, data: z.output<typeof SessionReverseAsked.schema>): Promise<void> => {
169
+ await step.emit(SessionReverseAnswered, { id: data.id, session: data.session, by: "cancelled", answer: { cancelled: true } });
170
+ };
171
+
172
+ // Each question waits for its own answer: one that waits holds no other.
173
+ api.on(SessionReverseAsked, { id: "session-reverse-ask", concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
174
+ if (data.route !== "starter") return;
175
+ // Nobody waits for it in this process: the harness has gone, or this process is not the one that was asked.
176
+ // The request, if there is one, is closed so the starter is not left holding it.
177
+ if (!waiting.has(data.id)) {
178
+ const request = await requestOf(step, data.id, "find");
179
+ if (request !== undefined) await step.outcome(requestCancel, { id: request, by: data.starter, reason: "nobody waits for the answer" }, { key: "close" });
180
+ await closeUnanswered(step, data);
181
+ return;
182
+ }
183
+ try {
184
+ const { answer: answered } = answeredBy(
185
+ await step(requestAsk, { to: data.starter, question: QUESTION_NAME, input: data.question }, { key: "ask" }),
186
+ );
187
+ const given = settled(data.question, answered);
188
+ await step.emit(SessionReverseAnswered, {
189
+ id: data.id,
190
+ session: data.session,
191
+ by: "starter",
192
+ answer: given.answer,
193
+ ...(given.always === undefined ? {} : { always: given.always }),
194
+ });
195
+ waiting.get(data.id)?.(given.answer);
196
+ } catch (error) {
197
+ // The wait for the starter suspends the handler; it is run again when the answer comes.
198
+ if (isSuspend(error)) throw error;
199
+ // Whatever ended the ask, the harness is answered: a turn never hangs on a question.
200
+ waiting.get(data.id)?.({ cancelled: true });
201
+ if (!endedWithoutAnswer(error)) throw error;
202
+ await closeUnanswered(step, data);
203
+ }
204
+ });
205
+
206
+ api.on(SessionReverseCancelled, { id: "session-reverse-cancel" }, async (data, step) => {
207
+ // The harness no longer waits: the request is closed, and the ask that waits on it ends.
208
+ const request = await requestOf(step, data.id, "find");
209
+ if (request !== undefined) await step.outcome(requestCancel, { id: request, by: data.starter, reason: "the harness stopped waiting" }, { key: "cancel" });
210
+ });
211
+
212
+ // The harness may stop waiting before the handler of the question has written its request: the
213
+ // handler above then finds nothing to close, so the request is closed when it is written.
214
+ api.on(RequestCreated, { id: "session-reverse-late-cancel" }, async (data, step, created) => {
215
+ if (data.question !== REVERSE_QUESTION || created.cause === null) return;
216
+ const journal = api.journal?.();
217
+ const asked = SessionReverseAsked.schema.safeParse(journal?.get(created.cause)?.data);
218
+ if (journal === undefined || !asked.success) return;
219
+ if (journal.find({ type: SessionReverseCancelled.name, field: "id", equals: asked.data.id }).length === 0) return;
220
+ await step.outcome(requestCancel, { id: data.id, by: asked.data.starter, reason: "the harness stopped waiting" }, { key: "cancel" });
221
+ });
222
+
223
+ return {
224
+ handlerFor: (rules, starter, ownToolPrefix) => async (id, request) => {
225
+ const session = sessionRef(id);
226
+ const reverse = ReverseIdSchema.parse(`rev_${randomUUID()}`);
227
+ const original = request.question;
228
+ const route = decidedWithout(session, rules, ownToolPrefix, original);
229
+ if (route !== undefined) {
230
+ const once = optionOfFlavor(original, "allow_once");
231
+ if (once === undefined) return { cancelled: true };
232
+ await api.emit(SessionReverseAsked, { id: reverse, session, route, starter, question: original, raw: request.raw });
233
+ const answer: Answer = { ids: [once.id] };
234
+ await api.emit(SessionReverseAnswered, { id: reverse, session, by: route, answer });
235
+ return answer;
236
+ }
237
+
238
+ const answered = new Promise<Answer>((resolve) => waiting.set(reverse, resolve));
239
+ const stopped = (): void => {
240
+ waiting.get(reverse)?.({ cancelled: true });
241
+ waiting.delete(reverse);
242
+ void api.emit(SessionReverseCancelled, { id: reverse, session, starter }).catch(() => {});
243
+ };
244
+ try {
245
+ await api.emit(SessionReverseAsked, { id: reverse, session, route: "starter", starter, question: withAlways(original), raw: request.raw });
246
+ } catch (error) {
247
+ waiting.delete(reverse);
248
+ throw error;
249
+ }
250
+ if (request.signal.aborted) stopped();
251
+ else request.signal.addEventListener("abort", stopped, { once: true });
252
+ try {
253
+ return await answered;
254
+ } finally {
255
+ request.signal.removeEventListener("abort", stopped);
256
+ waiting.delete(reverse);
257
+ }
258
+ },
259
+ };
260
+ }