@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/LICENSE +21 -0
- package/README.md +17 -2
- package/package.json +46 -4
- package/src/actions.ts +350 -0
- package/src/ask.ts +230 -0
- package/src/box.ts +87 -0
- package/src/caps.ts +149 -0
- package/src/catalog.ts +146 -0
- package/src/cockpit/actions.ts +52 -0
- package/src/cockpit/index.tsx +36 -0
- package/src/cockpit/pages.tsx +190 -0
- package/src/cockpit/transcript.ts +64 -0
- package/src/confirm.ts +228 -0
- package/src/discover.ts +107 -0
- package/src/identity.ts +64 -0
- package/src/index.ts +1874 -0
- package/src/insert-plugin.ts +263 -0
- package/src/insert-routing.ts +84 -0
- package/src/life.ts +59 -0
- package/src/prompt.ts +50 -0
- package/src/records-entry.ts +91 -0
- package/src/records.ts +395 -0
- package/src/refusal.ts +13 -0
- package/src/reverse.ts +260 -0
- package/src/support.ts +93 -0
- package/src/visible.ts +28 -0
- package/test/access-self-answer.test.ts +197 -0
- package/test/box-socket.test.ts +132 -0
- package/test/cockpit-actions.test.ts +19 -0
- package/test/cockpit-transcript.test.ts +71 -0
- package/test/fixtures/restart-host.ts +175 -0
- package/test/grant-box.test.ts +102 -0
- package/test/insert-permission.test.ts +285 -0
- package/test/restart.test.ts +168 -0
- package/test/sessions-reverse.test.ts +341 -0
- package/test/sessions.test.ts +658 -0
- package/tsconfig.json +15 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,1874 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sessions module: a session as niwa sees it, whatever the harness.
|
|
3
|
+
*
|
|
4
|
+
* The plugin registers:
|
|
5
|
+
*
|
|
6
|
+
* - `session.list` — the sessions there are, from the catalog and from the reading sides;
|
|
7
|
+
* - `session.belong` — says whom a session serves, with the source of the choice;
|
|
8
|
+
* - `session.read` — the transcript of one session, read through the harness's reading side and
|
|
9
|
+
* never journaled;
|
|
10
|
+
* - `session.search` — a text search through the transcript of one session, through the same
|
|
11
|
+
* reading side, with the index and a snippet of each record that matched;
|
|
12
|
+
* - `session.running` — what is running now, and what cannot be known;
|
|
13
|
+
* - `session.start` — starts a session, and returns as soon as the harness has named it; the
|
|
14
|
+
* prompt is the session's first turn, and the start says what became of it without waiting
|
|
15
|
+
* for its end;
|
|
16
|
+
* - `session.resume` — resumes a session;
|
|
17
|
+
* - `session.send` — sends into a session and says what happened to the message;
|
|
18
|
+
* - `session.interrupt` — interrupts a running turn, only where the harness declares it;
|
|
19
|
+
* - `session.ask` — asks a session and returns a value that passed a schema;
|
|
20
|
+
* - `session.open-questions` — the open questions of the session a niwa MCP server serves, found
|
|
21
|
+
* by the mark the server was given, each with the schema its answer must pass.
|
|
22
|
+
*
|
|
23
|
+
* The signs of life the control side reports are written as `session.*` records.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { PluginApi } from "@niwa-labs/plugin";
|
|
27
|
+
import type { PlanInput } from "@niwa-labs/sandbox";
|
|
28
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
29
|
+
import { mkdtempSync, realpathSync, rmSync } from "node:fs";
|
|
30
|
+
import { tmpdir } from "node:os";
|
|
31
|
+
import { join } from "node:path";
|
|
32
|
+
|
|
33
|
+
import { z } from "zod";
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
AccessClosed,
|
|
37
|
+
runIdOfPrincipal,
|
|
38
|
+
AccessGranted,
|
|
39
|
+
Address,
|
|
40
|
+
DESCRIPTION_MAX,
|
|
41
|
+
EntityDescription,
|
|
42
|
+
IdIndex,
|
|
43
|
+
JsonSchemaValue,
|
|
44
|
+
TOKEN_ENV,
|
|
45
|
+
UnknownId,
|
|
46
|
+
ValidationError,
|
|
47
|
+
accessMine,
|
|
48
|
+
actionName,
|
|
49
|
+
callerOf,
|
|
50
|
+
principalOf,
|
|
51
|
+
action,
|
|
52
|
+
assertNever,
|
|
53
|
+
closedPlacesOf,
|
|
54
|
+
effectPossibleAfter,
|
|
55
|
+
grant,
|
|
56
|
+
owner,
|
|
57
|
+
narrow,
|
|
58
|
+
rule,
|
|
59
|
+
specOf,
|
|
60
|
+
stableJson,
|
|
61
|
+
seq,
|
|
62
|
+
specsOf,
|
|
63
|
+
toolNameOf,
|
|
64
|
+
valueSchemaOf,
|
|
65
|
+
} from "@niwa-labs/core";
|
|
66
|
+
import { COCKPIT_MODULE, plugin, bindingOf } from "@niwa-labs/plugin";
|
|
67
|
+
import { fileURLToPath } from "node:url";
|
|
68
|
+
import type { ActionContext, Caller, Grant, JournalReader, JsonValue, Timestamp, Token } from "@niwa-labs/core";
|
|
69
|
+
import type { Plugin, CallerBinding } from "@niwa-labs/plugin";
|
|
70
|
+
import {
|
|
71
|
+
DeliveryReceiptSchema,
|
|
72
|
+
HarnessInstanceRegistry,
|
|
73
|
+
InputNotSent,
|
|
74
|
+
InputPossiblySent,
|
|
75
|
+
blocksOf,
|
|
76
|
+
outcomeOf,
|
|
77
|
+
requireAbility,
|
|
78
|
+
requireLaunch,
|
|
79
|
+
requireOwnBlocks,
|
|
80
|
+
requireTools,
|
|
81
|
+
supports,
|
|
82
|
+
} from "@niwa-labs/harness";
|
|
83
|
+
import { WorktreeCreated, gitWorktreeCreate } from "@niwa-labs/git/records";
|
|
84
|
+
import { readTranscript, searchSession } from "@niwa-labs/history";
|
|
85
|
+
import type { Worktree, WorktreeOption } from "@niwa-labs/git/records";
|
|
86
|
+
import type {
|
|
87
|
+
DeliveryReceipt,
|
|
88
|
+
Harness,
|
|
89
|
+
HarnessBinding,
|
|
90
|
+
InputOutcome,
|
|
91
|
+
KindOptions,
|
|
92
|
+
McpServerSpec,
|
|
93
|
+
ModelName,
|
|
94
|
+
OptionBlocks,
|
|
95
|
+
PermissionMark,
|
|
96
|
+
SessionControl,
|
|
97
|
+
SessionId,
|
|
98
|
+
SessionInfo,
|
|
99
|
+
SessionReading,
|
|
100
|
+
ToolAllowance,
|
|
101
|
+
VisibleActions,
|
|
102
|
+
} from "@niwa-labs/harness";
|
|
103
|
+
import { BoxRefused, admit, boxManifest, onBoxManifest, requireSandbox, sandbox as sandboxHost, sandboxOf } from "@niwa-labs/sandbox";
|
|
104
|
+
import type { BoxAccess, BoxAccessInput, BoxPlan, BoxRequest, SandboxHost } from "@niwa-labs/sandbox";
|
|
105
|
+
import { RequestCreated, requestOpen } from "@niwa-labs/requests/records";
|
|
106
|
+
|
|
107
|
+
import { heldRule, inheritedLaunch, isLaunchRule, toolsOfGrant, toolsOfSession } from "./box.ts";
|
|
108
|
+
import { SessionRefusal } from "./refusal.ts";
|
|
109
|
+
import { REVERSE_TYPES, installReverse } from "./reverse.ts";
|
|
110
|
+
import { askNonNative, questionText, submitAnswerAction, SUBMIT_ANSWER_ACTION } from "./ask.ts";
|
|
111
|
+
import { SessionCatalog } from "./catalog.ts";
|
|
112
|
+
import type { SessionEntry } from "./catalog.ts";
|
|
113
|
+
import { SessionRefSchema, sessionOf, sessionRef } from "./identity.ts";
|
|
114
|
+
import type { NiwaSessionId, SessionRef } from "./identity.ts";
|
|
115
|
+
import { HarnessCaps } from "./caps.ts";
|
|
116
|
+
import type { Slot } from "./caps.ts";
|
|
117
|
+
import { PromptInputSchema, promptFrom } from "./prompt.ts";
|
|
118
|
+
import {
|
|
119
|
+
SESSION_TYPES,
|
|
120
|
+
BelongingSource,
|
|
121
|
+
ActivityToolSchema,
|
|
122
|
+
SessionActivity,
|
|
123
|
+
SessionAdvisor,
|
|
124
|
+
SessionBelongs,
|
|
125
|
+
SessionBoxManifest,
|
|
126
|
+
SessionInputSending,
|
|
127
|
+
SessionInputSettled,
|
|
128
|
+
SessionStartNamed,
|
|
129
|
+
SessionStartReserved,
|
|
130
|
+
SessionStartUnsent,
|
|
131
|
+
SessionEnded,
|
|
132
|
+
SessionMarked,
|
|
133
|
+
SessionModel,
|
|
134
|
+
SessionStarted,
|
|
135
|
+
SessionTurnEnded,
|
|
136
|
+
SessionTurnStarted,
|
|
137
|
+
SessionUnknownVariant,
|
|
138
|
+
sameAddress,
|
|
139
|
+
SESSION_SEND,
|
|
140
|
+
} from "./records.ts";
|
|
141
|
+
import type { SessionSendInput, SessionSendOutput } from "./records.ts";
|
|
142
|
+
import {
|
|
143
|
+
SessionRefInput,
|
|
144
|
+
sessionAsk,
|
|
145
|
+
sessionBelong,
|
|
146
|
+
sessionGet,
|
|
147
|
+
sessionEnd,
|
|
148
|
+
sessionInterrupt,
|
|
149
|
+
sessionList,
|
|
150
|
+
SESSION_LIST_DEFAULT,
|
|
151
|
+
SESSION_START_FIELDS,
|
|
152
|
+
sessionOpenQuestions,
|
|
153
|
+
sessionRead,
|
|
154
|
+
sessionResume,
|
|
155
|
+
harnessGet,
|
|
156
|
+
harnessList,
|
|
157
|
+
sessionRunning,
|
|
158
|
+
sessionSearch,
|
|
159
|
+
sessionSend,
|
|
160
|
+
sessionStart,
|
|
161
|
+
} from "./actions.ts";
|
|
162
|
+
import { VisibleActionsInputSchema, visibleActionsOf } from "./visible.ts";
|
|
163
|
+
import type { VisibleActionsInput } from "./visible.ts";
|
|
164
|
+
|
|
165
|
+
const SESSION_TYPE_NAMES = SESSION_TYPES.map((type) => type.name);
|
|
166
|
+
|
|
167
|
+
/** The plugin name. */
|
|
168
|
+
const PLUGIN_NAME = "sessions";
|
|
169
|
+
|
|
170
|
+
/** How many sessions `session.running` lists of each kind when it is not told. */
|
|
171
|
+
const DEFAULT_RUNNING_LIMIT = 20;
|
|
172
|
+
|
|
173
|
+
/** Where a page of sessions ends: the activity time and the ref of its last session. */
|
|
174
|
+
const PageCursor = z.tuple([z.number(), z.string()]);
|
|
175
|
+
|
|
176
|
+
const recency = (entry: SessionEntry): number => entry.lastActivityAt ?? entry.startedAt ?? 0;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* One page of the sessions, the most recently active first. The cursor names the last session
|
|
180
|
+
* given, not an offset, so a session that appears or ends between two calls moves none of the
|
|
181
|
+
* others across a page.
|
|
182
|
+
*/
|
|
183
|
+
function pageOf(entries: readonly SessionEntry[], limit: number, cursor: string | undefined): { page: SessionEntry[]; nextCursor?: string } {
|
|
184
|
+
const ordered = [...entries].sort((a, b) => recency(b) - recency(a) || a.ref.localeCompare(b.ref));
|
|
185
|
+
let start = 0;
|
|
186
|
+
if (cursor !== undefined) {
|
|
187
|
+
let after: z.infer<typeof PageCursor>;
|
|
188
|
+
try {
|
|
189
|
+
after = PageCursor.parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")));
|
|
190
|
+
} catch {
|
|
191
|
+
throw new Error("the cursor is not one that session.list gave: pass nextCursor of the previous page unchanged");
|
|
192
|
+
}
|
|
193
|
+
start = ordered.findIndex((entry) => recency(entry) < after[0] || (recency(entry) === after[0] && entry.ref.localeCompare(after[1]) > 0));
|
|
194
|
+
if (start < 0) start = ordered.length;
|
|
195
|
+
}
|
|
196
|
+
const page = ordered.slice(start, start + limit);
|
|
197
|
+
const last = page.at(-1);
|
|
198
|
+
if (last === undefined || start + limit >= ordered.length) return { page };
|
|
199
|
+
return { page, nextCursor: Buffer.from(JSON.stringify([recency(last), last.ref])).toString("base64url") };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A session as one line: its id (the pointer for a session niwa did not start), the time of its last sign of life, its model, and its title. */
|
|
203
|
+
function runningLine(entry: SessionEntry): string {
|
|
204
|
+
const active = entry.lastActivityAt === undefined ? "" : new Date(entry.lastActivityAt).toTimeString().slice(0, 8);
|
|
205
|
+
const title = (entry.title ?? "").replace(/\s+/g, " ").trim();
|
|
206
|
+
return [entry.id ?? entry.ref, active, entry.model ?? "", title.length > 60 ? `${title.slice(0, 59)}…` : title].filter((part) => part !== "").join(" ");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** What the plugin is given: the harness installations it may read from. */
|
|
210
|
+
export interface SessionsOptions {
|
|
211
|
+
/**
|
|
212
|
+
* The installations, each with the sides that serve it (`kind.bind(...)`): the bindings
|
|
213
|
+
* themselves, or the registry they are kept in. Two installations of one kind are two
|
|
214
|
+
* bindings, each with its own sides.
|
|
215
|
+
*/
|
|
216
|
+
readonly harnesses?: readonly HarnessBinding[] | HarnessInstanceRegistry;
|
|
217
|
+
/**
|
|
218
|
+
* How niwa's own MCP server is started, for the sessions that may see niwa actions.
|
|
219
|
+
*
|
|
220
|
+
* The command is the program and its arguments, which carry the home of the host. Without it a session that may see niwa actions cannot be
|
|
221
|
+
* started: the start is refused, not silently made without the server.
|
|
222
|
+
*/
|
|
223
|
+
readonly niwaMcp?: NiwaMcp;
|
|
224
|
+
/**
|
|
225
|
+
* The host's sandbox: its adapter (default srt), its profiles and its closed list
|
|
226
|
+
* (`sandbox({ ... })` of `@niwa-labs/sandbox`). The profile of every installation is given to it,
|
|
227
|
+
* so every other box finds that installation's places closed. Default: the catalog alone.
|
|
228
|
+
*/
|
|
229
|
+
readonly sandbox?: SandboxHost;
|
|
230
|
+
/** Trusted host lookup for Git metadata required by a managed checkout. */
|
|
231
|
+
readonly worktreeFor?: (api: Pick<PluginApi, "home" | "journal">, cwd: string) => PlanInput["worktree"];
|
|
232
|
+
/**
|
|
233
|
+
* What a session's box has when its start asks for nothing: `allow` (the default
|
|
234
|
+
* `["project", "toolchains"]`) or `only`. Every session runs in a box, with the profile of its
|
|
235
|
+
* installation; a sandbox that cannot run here stops every start.
|
|
236
|
+
*/
|
|
237
|
+
readonly box?: BoxAccess;
|
|
238
|
+
/**
|
|
239
|
+
* The ceiling of a harness, by its id: how many of its sessions may run a turn at once on this host.
|
|
240
|
+
* A start or a send over it waits until a turn ends; a sleeping session holds no slot. Absent, a
|
|
241
|
+
* harness has none.
|
|
242
|
+
*/
|
|
243
|
+
readonly caps?: Readonly<Record<string, number>>;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* How niwa's own MCP server is started.
|
|
248
|
+
*
|
|
249
|
+
* The arguments carry the home; the environment is the server's own and holds only what the
|
|
250
|
+
* session may see.
|
|
251
|
+
*/
|
|
252
|
+
export interface NiwaMcp {
|
|
253
|
+
/** The program that starts the server. */
|
|
254
|
+
readonly command: string;
|
|
255
|
+
/** The arguments of the program. */
|
|
256
|
+
readonly args: readonly string[];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The name the niwa MCP server is known by in a session. */
|
|
260
|
+
const NIWA_MCP_NAME = "niwa";
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The ids niwa gave the sessions it started, each with the pointer it names, from the journal.
|
|
264
|
+
*
|
|
265
|
+
* The seed of an id is the operation of the starting call, which is the start of the record's own id.
|
|
266
|
+
*/
|
|
267
|
+
function sessionIdsOf(journal: JournalReader | undefined): { id: NiwaSessionId; ref: SessionRef; seed: string }[] {
|
|
268
|
+
if (journal === undefined) return [];
|
|
269
|
+
return journal.find({ type: SessionStarted.name }).flatMap((stored) => {
|
|
270
|
+
const parsed = SessionStarted.schema.safeParse(stored.data);
|
|
271
|
+
return parsed.success ? [{ id: parsed.data.id, ref: parsed.data.session, seed: stored.id.replace(/\/emit\/\d+$/, "") }] : [];
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** How long stopping a control side waits for the records its streams of life leave. */
|
|
276
|
+
const FOLLOWER_WAIT_MS = 1_000;
|
|
277
|
+
|
|
278
|
+
/** The least time between two `session.activity` records of one session. */
|
|
279
|
+
const ACTIVITY_EVERY_MS = 5_000;
|
|
280
|
+
|
|
281
|
+
/** How much of a message a harness sent that niwa does not know is kept in its record. */
|
|
282
|
+
const UNKNOWN_RAW_CHARS = 16_384;
|
|
283
|
+
|
|
284
|
+
/** The message as it arrived, or its beginning: a message may carry the whole output of a command. */
|
|
285
|
+
function keptRaw(raw: JsonValue): JsonValue {
|
|
286
|
+
const text = JSON.stringify(raw);
|
|
287
|
+
return text.length <= UNKNOWN_RAW_CHARS ? raw : { truncated: true, chars: text.length, head: text.slice(0, UNKNOWN_RAW_CHARS) };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The sessions plugin.
|
|
292
|
+
*
|
|
293
|
+
* It keeps no record state of its own: the catalog is built from niwa's session records and from
|
|
294
|
+
* what the reading sides list. Nothing is copied out of a harness. The only thing held in memory
|
|
295
|
+
* is the sessions whose signs of life are followed. A question that waits for an answer is a
|
|
296
|
+
* request, so it is in the journal and not in this process.
|
|
297
|
+
*/
|
|
298
|
+
export function sessions(options: SessionsOptions = {}): SessionsPlugin {
|
|
299
|
+
const bindings = resolveBindings(options);
|
|
300
|
+
// The session a mark names, once the plugin is installed: what the binding of a session's own client reads.
|
|
301
|
+
let sessionOfClientMark: ((mark: string) => SessionRef | undefined) | undefined;
|
|
302
|
+
// A turn left open before this moment proves nothing about now.
|
|
303
|
+
const bootedAt = Date.now() as Timestamp;
|
|
304
|
+
// The sessions whose signs of life are being followed: one loop per session.
|
|
305
|
+
const followed = new Set<SessionRef>();
|
|
306
|
+
/** The sessions `session.end` ended: their end is written once, by it, not again when their stream closes. */
|
|
307
|
+
const ending = new Set<SessionRef>();
|
|
308
|
+
const closing = new Map<SessionRef, Promise<void>>();
|
|
309
|
+
// The sessions niwa was asked to interrupt: their next turn end is written as interrupted.
|
|
310
|
+
const interrupting = new Set<SessionRef>();
|
|
311
|
+
// The numbering of each session's turns. A harness counts its turns from 1 in each process: the
|
|
312
|
+
// journal's last number is where a process that was launched again goes on, so a turn is known
|
|
313
|
+
// by the same number in its records and in the receipt of a message sent into it.
|
|
314
|
+
const turnCounts = new Map<SessionRef, { last: number; offset: number }>();
|
|
315
|
+
/** The starts under an operation that are running now: a retry waits for the one running. */
|
|
316
|
+
const startsRunning = new Map<string, { digest: string; answer: Promise<z.output<typeof sessionStart.output>> }>();
|
|
317
|
+
// The loops that follow them, by control side, so that stopping a side waits for the last
|
|
318
|
+
// records of its sessions to be written.
|
|
319
|
+
const followers = new Map<SessionControl, Set<Promise<void>>>();
|
|
320
|
+
// The launches that are waiting for their box to be recorded, by mark: the funnel's manifest
|
|
321
|
+
// listener is global, and a manifest is the business of the plugin that asked for that box.
|
|
322
|
+
const boxManifests = new Map<string, (made: SandboxManifestOf) => Promise<unknown>>();
|
|
323
|
+
// The host's sandbox: every installation's profile is given to it, so each is closed to every other box.
|
|
324
|
+
const boxes = options.sandbox ?? sandboxHost();
|
|
325
|
+
for (const binding of bindings) if (binding.profile !== undefined) boxes.install(binding.instance.id, binding.profile);
|
|
326
|
+
const boxDefault: BoxAccess = options.box ?? { allow: ["project", "toolchains"] };
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* The MCP servers a session is given, from the actions it may see.
|
|
330
|
+
*
|
|
331
|
+
* A session that may see no niwa action is given no server: it has no use for one. A session
|
|
332
|
+
* that may see some is given niwa's own server, which shows it exactly those actions. Without
|
|
333
|
+
* the `niwaMcp` option the server cannot be started, and the start is refused — a session that
|
|
334
|
+
* was promised niwa's actions and gets none is worse than a refusal.
|
|
335
|
+
*
|
|
336
|
+
* The server is given a mark (`NIWA_SESSION_MARK`): the pairing of the mark with the session is
|
|
337
|
+
* written once the session is named, so the server can ask what the session it serves is asked.
|
|
338
|
+
*/
|
|
339
|
+
const serversOf = (
|
|
340
|
+
actions: readonly string[],
|
|
341
|
+
mark: string,
|
|
342
|
+
token: Token,
|
|
343
|
+
): readonly McpServerSpec[] | undefined => {
|
|
344
|
+
if (actions.length === 0) return undefined;
|
|
345
|
+
if (options.niwaMcp === undefined) {
|
|
346
|
+
throw new SessionRefusal(
|
|
347
|
+
"no-niwa-mcp",
|
|
348
|
+
"the session may see niwa actions, but no niwa MCP server was given to start it",
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
return [
|
|
352
|
+
{
|
|
353
|
+
name: NIWA_MCP_NAME,
|
|
354
|
+
command: options.niwaMcp.command,
|
|
355
|
+
args: options.niwaMcp.args,
|
|
356
|
+
env: { NIWA_VISIBLE: actions.join(","), NIWA_SESSION_MARK: mark, [TOKEN_ENV]: token },
|
|
357
|
+
tools: actions.map(toolNameOf),
|
|
358
|
+
},
|
|
359
|
+
];
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* What a harness names the tools of niwa's own server (`mcp__<server>__<tool>`), for a session that is given the
|
|
364
|
+
* server: the session's grant is what the server shows, so a request to call one of them is not put to anybody.
|
|
365
|
+
*/
|
|
366
|
+
const ownToolPrefix = (actions: readonly string[]): string | undefined =>
|
|
367
|
+
actions.length === 0 ? undefined : `mcp__${NIWA_MCP_NAME}__`;
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The actions a session of a harness may see, with the one that answers a question.
|
|
371
|
+
*
|
|
372
|
+
* A harness that cannot answer natively is asked through the request, and the session
|
|
373
|
+
* answers it by calling `submit-answer`. That action must be among the ones the session
|
|
374
|
+
* sees, or the question cannot be answered at all: it is added here.
|
|
375
|
+
*
|
|
376
|
+
* A harness that answers natively has no use for that action: it is not added, and one that
|
|
377
|
+
* was given is taken away, so a session of such a harness needs no server for it.
|
|
378
|
+
*
|
|
379
|
+
* A session that is given no niwa action at all sees none: nothing is implied, and a
|
|
380
|
+
* session that sees nothing has no server to call the action through.
|
|
381
|
+
*/
|
|
382
|
+
const visibleFor = (harness: string, input: VisibleActionsInput | undefined): VisibleActions => {
|
|
383
|
+
const visible = visibleActionsOf(input);
|
|
384
|
+
if (input === undefined || visible.actions.length === 0) return visible;
|
|
385
|
+
if (supports(instanceOf(bindings, harness), "control", "structuredOutput")) {
|
|
386
|
+
if (!visible.actions.includes(SUBMIT_ANSWER_ACTION)) return visible;
|
|
387
|
+
return {
|
|
388
|
+
actions: visible.actions.filter((name) => name !== SUBMIT_ANSWER_ACTION),
|
|
389
|
+
disabledTools: visible.disabledTools,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (visible.actions.includes(SUBMIT_ANSWER_ACTION)) return visible;
|
|
393
|
+
return { actions: [...visible.actions, SUBMIT_ANSWER_ACTION], disabledTools: visible.disabledTools };
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* The address a client speaks as: the client a session's own token gives is its session, so a
|
|
398
|
+
* session answers a question addressed to it and no other; every other client speaks as
|
|
399
|
+
* `fallback` says. The composition hands it to the requests module (`requests({ bind })`).
|
|
400
|
+
*/
|
|
401
|
+
const bind = (fallback: CallerBinding = bindingOf()): CallerBinding => {
|
|
402
|
+
return (caller) => {
|
|
403
|
+
const principal = caller.kind === "client" ? caller.principal : undefined;
|
|
404
|
+
const session = principal?.kind === "session" ? sessionOfClientMark?.(principal.id) : undefined;
|
|
405
|
+
if (session === undefined) return fallback(caller);
|
|
406
|
+
const id = sessionOf(session);
|
|
407
|
+
return { kind: "session", harness: id.harness, id: id.native };
|
|
408
|
+
};
|
|
409
|
+
};
|
|
410
|
+
/** The one who started a session: the address its caller speaks as. A run asks the owner, as a script's own ask does. */
|
|
411
|
+
const starterOf = (caller: Caller): Address => {
|
|
412
|
+
const principal = caller.kind === "client" ? caller.principal : undefined;
|
|
413
|
+
if (principal?.kind === "run") return owner;
|
|
414
|
+
return bind()(caller) ?? owner;
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
const made = plugin(PLUGIN_NAME, (api) => {
|
|
418
|
+
// The page of this plugin in the cockpit: a client module, offered by the path of its source.
|
|
419
|
+
api.offer(COCKPIT_MODULE, { id: "sessions", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
|
|
420
|
+
api.declare(...SESSION_TYPES, ...REVERSE_TYPES);
|
|
421
|
+
const reverse = installReverse(api);
|
|
422
|
+
const sessionIds = new IdIndex("session", () => sessionIdsOf(api.journal?.()));
|
|
423
|
+
const caps = new HarnessCaps(options.caps ?? {}, {
|
|
424
|
+
journal: () => api.journal?.(),
|
|
425
|
+
untilCommit: (ms) => api.untilCommit(ms),
|
|
426
|
+
followed: () => followed,
|
|
427
|
+
harnessOf: (ref) => sessionOf(ref).harness,
|
|
428
|
+
servedAfter: () => servedAfter,
|
|
429
|
+
});
|
|
430
|
+
// The last record before this host served: turns that began by then ran in processes of another host.
|
|
431
|
+
let servedAfter = seq(0);
|
|
432
|
+
api.service(() => {
|
|
433
|
+
servedAfter = api.journal?.()?.last() ?? seq(0);
|
|
434
|
+
return () => {};
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The pointer of the session a caller named: the id niwa gave it or any text that names one, or
|
|
439
|
+
* the pair of a session niwa did not start. A text that names no session is `UnknownId`.
|
|
440
|
+
*/
|
|
441
|
+
const refOf = (input: z.output<typeof SessionRefInput>): SessionRef => {
|
|
442
|
+
if (typeof input !== "string") return SessionRefSchema.parse(`${input.harness} ${input.native}`);
|
|
443
|
+
if (input.includes(" ")) return SessionRefSchema.parse(input);
|
|
444
|
+
const id = sessionIds.require(input);
|
|
445
|
+
const found = sessionIdsOf(api.journal?.()).find((entry) => entry.id === id);
|
|
446
|
+
if (found === undefined) throw new UnknownId(input, "session");
|
|
447
|
+
return found.ref;
|
|
448
|
+
};
|
|
449
|
+
api.action(submitAnswerAction(() => api.journal?.()));
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The control sides this plugin holds are stopped when the host stops.
|
|
453
|
+
*
|
|
454
|
+
* A control side owns processes: the harness CLI, and the MCP servers the CLI was given.
|
|
455
|
+
* Nothing it started may outlive the host that started it, so every side is disposed here —
|
|
456
|
+
* once per side, and a side that fails to stop does not keep the others alive.
|
|
457
|
+
*/
|
|
458
|
+
api.service(() => {
|
|
459
|
+
const stopped = new Set<SessionControl>();
|
|
460
|
+
return async (): Promise<void> => {
|
|
461
|
+
for (const binding of bindings) {
|
|
462
|
+
const control = binding.control;
|
|
463
|
+
if (control === undefined || stopped.has(control)) continue;
|
|
464
|
+
stopped.add(control);
|
|
465
|
+
try {
|
|
466
|
+
if (control.dispose !== undefined) {
|
|
467
|
+
await control.dispose();
|
|
468
|
+
// Disposing ends the streams of life: the records they leave are written first.
|
|
469
|
+
// A side whose streams stay open does not hold the stop: the wait is short.
|
|
470
|
+
await Promise.race([
|
|
471
|
+
Promise.allSettled([...(followers.get(control) ?? [])]),
|
|
472
|
+
new Promise<void>((resolve) => setTimeout(resolve, FOLLOWER_WAIT_MS).unref()),
|
|
473
|
+
]);
|
|
474
|
+
}
|
|
475
|
+
} catch (error) {
|
|
476
|
+
// One side that does not stop keeps the others from stopping: the rest are stopped.
|
|
477
|
+
console.error(
|
|
478
|
+
`niwa: stopping the control side of "${binding.instance.id}" failed: ${
|
|
479
|
+
error instanceof Error ? error.message : String(error)
|
|
480
|
+
}`,
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
/** The manifest of every box a session of this plugin is started in is written before its process starts. */
|
|
488
|
+
api.service(() => {
|
|
489
|
+
const stop = onBoxManifest(async (made) => {
|
|
490
|
+
const write = made.mark === undefined ? undefined : boxManifests.get(made.mark);
|
|
491
|
+
if (made.mark === undefined || write === undefined) return;
|
|
492
|
+
await write(made.manifest);
|
|
493
|
+
});
|
|
494
|
+
return async () => stop();
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* A question niwa asked of a session reaches the session.
|
|
499
|
+
*
|
|
500
|
+
* The request is what waits for the answer; the session is told nothing by it. So the
|
|
501
|
+
* session that may answer gets the question as a message, with the id of the request it
|
|
502
|
+
* must answer by, and how to answer it.
|
|
503
|
+
*
|
|
504
|
+
* The delivery is a step: a step is not made twice, so a question is not asked twice
|
|
505
|
+
* after a restart.
|
|
506
|
+
*/
|
|
507
|
+
api.on(RequestCreated, { id: "session-question" }, async (data, step) => {
|
|
508
|
+
if (data.to.kind !== "session") return;
|
|
509
|
+
await step<SessionSendInput, SessionSendOutput>(SESSION_SEND, {
|
|
510
|
+
session: `${data.to.harness} ${data.to.id}`,
|
|
511
|
+
message: questionText({
|
|
512
|
+
request: data.id,
|
|
513
|
+
question: data.question,
|
|
514
|
+
input: data.input,
|
|
515
|
+
}),
|
|
516
|
+
});
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
// Control of another session lets a caller speak through its grant and box.
|
|
520
|
+
// A run can direct its own sessions; a helper can direct itself and its descendants.
|
|
521
|
+
const authorizeControl = (ref: SessionRef, caller: Caller): void => {
|
|
522
|
+
if (caller.kind !== "client" || caller.principal?.kind === "owner") return;
|
|
523
|
+
const principal = caller.principal;
|
|
524
|
+
const own = principal?.kind === "session" ? sessionOfMark(principal.id) : undefined;
|
|
525
|
+
const run = principal?.kind === "run" ? runIdOfPrincipal(principal.id) : own === undefined ? undefined : startedOf(own)?.run;
|
|
526
|
+
const target = startedOf(ref);
|
|
527
|
+
if (run === undefined && target?.run === undefined) return;
|
|
528
|
+
if (run !== undefined && run === target?.run) {
|
|
529
|
+
if (principal?.kind === "run") {
|
|
530
|
+
if (principal.id === (target?.execution ?? target?.run)) return;
|
|
531
|
+
throw new SessionRefusal("earlier-execution", "this session belongs to an earlier execution; recompute from the step that opened the conversation");
|
|
532
|
+
}
|
|
533
|
+
const seen = new Set<SessionRef>();
|
|
534
|
+
for (let next: SessionRef | undefined = ref; next !== undefined && !seen.has(next); next = startedOf(next)?.parentSession) {
|
|
535
|
+
if (next === own) return;
|
|
536
|
+
seen.add(next);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
throw new SessionRefusal("foreign-session", "the session is outside the caller's run or its session tree");
|
|
540
|
+
};
|
|
541
|
+
/** The control side that serves a session, refused before anything is attempted if it cannot. */
|
|
542
|
+
const controlOf = (input: z.output<typeof SessionRefInput>, ability: ControlAbility, caller: Caller) => {
|
|
543
|
+
const ref = refOf(input);
|
|
544
|
+
authorizeControl(ref, caller);
|
|
545
|
+
const id = sessionOf(ref);
|
|
546
|
+
return { ref, id, control: controlFor(bindings, id.harness, ability) };
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Write the signs of life a control side reports as records.
|
|
551
|
+
*
|
|
552
|
+
* They have no calling action — they arrive while the harness works — so they go through the
|
|
553
|
+
* plugin's own `emit`. A record says that something happened, never what.
|
|
554
|
+
*/
|
|
555
|
+
const follow = (control: SessionControl, ref: SessionRef, id: SessionId): void => {
|
|
556
|
+
if (followed.has(ref)) return;
|
|
557
|
+
followed.add(ref);
|
|
558
|
+
// A busy turn reports a sign of life many times a second: one record in a few seconds says it as well.
|
|
559
|
+
let activeAt = -Infinity;
|
|
560
|
+
// The latest decision seen since the last record: a record carries it, so a burst of marked
|
|
561
|
+
// tool calls is throttled like the rest and says what was decided last.
|
|
562
|
+
let pending: PermissionMark | undefined;
|
|
563
|
+
// The latest tool name seen since the last record, when it is a short identifier.
|
|
564
|
+
let pendingTool: string | undefined;
|
|
565
|
+
// The model the session is known to run: the harness says it again on every launch, and a
|
|
566
|
+
// record says it once.
|
|
567
|
+
let named = modelOf(ref);
|
|
568
|
+
// The unknown variants already written: one record for each.
|
|
569
|
+
const unknown = new Set<string>();
|
|
570
|
+
const loop = (async () => {
|
|
571
|
+
try {
|
|
572
|
+
for await (const event of control.life(id)) {
|
|
573
|
+
switch (event.kind) {
|
|
574
|
+
case "model":
|
|
575
|
+
if (event.model !== named) {
|
|
576
|
+
named = event.model;
|
|
577
|
+
await api.emit(SessionModel, { session: ref, model: event.model });
|
|
578
|
+
}
|
|
579
|
+
break;
|
|
580
|
+
case "turn-started":
|
|
581
|
+
activeAt = -Infinity;
|
|
582
|
+
pending = undefined;
|
|
583
|
+
pendingTool = undefined;
|
|
584
|
+
// An interrupt that ended no turn says nothing about the turn that begins now.
|
|
585
|
+
interrupting.delete(ref);
|
|
586
|
+
await api.emit(SessionTurnStarted, { session: ref, turn: beginning(ref, event.turn) });
|
|
587
|
+
break;
|
|
588
|
+
case "turn-ended": {
|
|
589
|
+
// An interrupt niwa asked for says how the turn ended; otherwise the harness does.
|
|
590
|
+
const interrupted = interrupting.delete(ref);
|
|
591
|
+
await api.emit(SessionTurnEnded, {
|
|
592
|
+
session: ref,
|
|
593
|
+
turn: numbered(ref, event.turn),
|
|
594
|
+
how: interrupted ? "interrupted" : (event.outcome ?? "completed"),
|
|
595
|
+
});
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
case "activity":
|
|
599
|
+
if (event.permission !== undefined) pending = event.permission;
|
|
600
|
+
if (event.tool !== undefined) {
|
|
601
|
+
const tool = ActivityToolSchema.safeParse(event.tool);
|
|
602
|
+
if (tool.success) pendingTool = tool.data;
|
|
603
|
+
}
|
|
604
|
+
if (Date.now() - activeAt >= ACTIVITY_EVERY_MS) {
|
|
605
|
+
activeAt = Date.now();
|
|
606
|
+
const permission = pending;
|
|
607
|
+
const tool = pendingTool;
|
|
608
|
+
pending = undefined;
|
|
609
|
+
pendingTool = undefined;
|
|
610
|
+
await api.emit(SessionActivity, {
|
|
611
|
+
session: ref,
|
|
612
|
+
...(permission === undefined ? {} : { permission }),
|
|
613
|
+
...(tool === undefined ? {} : { tool }),
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
break;
|
|
617
|
+
// Rare and meaningful: each is written, not throttled.
|
|
618
|
+
case "advisor": {
|
|
619
|
+
const { kind: _kind, at: _at, ...advisor } = event;
|
|
620
|
+
await api.emit(SessionAdvisor, { session: ref, ...advisor });
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
case "unknown-variant": {
|
|
624
|
+
// One record for each variant: the first message of it is the one worth reading.
|
|
625
|
+
const kind = `${event.protocol} ${event.variant}`;
|
|
626
|
+
if (!unknown.has(kind)) {
|
|
627
|
+
unknown.add(kind);
|
|
628
|
+
await api.emit(SessionUnknownVariant, {
|
|
629
|
+
session: ref,
|
|
630
|
+
protocol: event.protocol,
|
|
631
|
+
variant: event.variant,
|
|
632
|
+
raw: keptRaw(event.raw),
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
default:
|
|
638
|
+
assertNever(event, "sign of life");
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
// The control side closes the stream of a session only when the session is over.
|
|
642
|
+
if (!ending.has(ref)) await api.emit(SessionEnded, { session: ref, reason: "the control side closed the session" });
|
|
643
|
+
} catch {
|
|
644
|
+
// The stream stopped, or the host closed. What was written stays; the state of the
|
|
645
|
+
// session reads as unknown from here on.
|
|
646
|
+
} finally {
|
|
647
|
+
followed.delete(ref);
|
|
648
|
+
}
|
|
649
|
+
})();
|
|
650
|
+
const loops = followers.get(control) ?? new Set<Promise<void>>();
|
|
651
|
+
followers.set(control, loops);
|
|
652
|
+
loops.add(loop);
|
|
653
|
+
void loop.finally(() => loops.delete(loop));
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* The catalog, merged with what the reading sides list.
|
|
658
|
+
*
|
|
659
|
+
* A side that cannot list is named in `unreadable`: its sessions may exist, and the answer
|
|
660
|
+
* must not read as "there are none".
|
|
661
|
+
*/
|
|
662
|
+
const survey = async (harness: string | undefined, cwd: string | undefined, managedOnly = false) => {
|
|
663
|
+
const journal = api.journal?.();
|
|
664
|
+
const catalog = SessionCatalog.fromRecords(
|
|
665
|
+
journal === undefined ? [] : journal.since(seq(0), SESSION_TYPE_NAMES),
|
|
666
|
+
bootedAt,
|
|
667
|
+
);
|
|
668
|
+
// The sessions niwa runs are the ones its own records name; the others are found on the machine.
|
|
669
|
+
const managed = catalog.all();
|
|
670
|
+
const own = new Set(managed.map((entry) => entry.ref));
|
|
671
|
+
const { listed, unreadable } = managedOnly
|
|
672
|
+
? { listed: [], unreadable: [] }
|
|
673
|
+
: await listFromSides(bindings, harness, cwd);
|
|
674
|
+
for (const info of listed) {
|
|
675
|
+
catalog.remember({
|
|
676
|
+
ref: sessionRef(info.id),
|
|
677
|
+
title: info.title,
|
|
678
|
+
cwd: info.cwd,
|
|
679
|
+
startedAt: info.startedAt,
|
|
680
|
+
lastActivityAt: info.updatedAt,
|
|
681
|
+
state: "unknown",
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
const entries = (managedOnly ? managed : catalog.all())
|
|
685
|
+
.filter((entry) => harness === undefined || sessionOf(entry.ref).harness === harness)
|
|
686
|
+
.filter((entry) => cwd === undefined || entry.cwd === cwd);
|
|
687
|
+
return { catalog, entries, unreadable, own };
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
// The sessions niwa runs that work now, for `niwa.host.status`.
|
|
691
|
+
api.summarize(() => {
|
|
692
|
+
const journal = api.journal?.();
|
|
693
|
+
const catalog = SessionCatalog.fromRecords(journal === undefined ? [] : journal.since(seq(0), SESSION_TYPE_NAMES), bootedAt);
|
|
694
|
+
return { running: catalog.all().filter((entry) => entry.state === "running").length };
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Does the journal already hold this belonging?
|
|
699
|
+
*
|
|
700
|
+
* The record is one fact of the pair: the same session and the same address are one
|
|
701
|
+
* belonging, however many times they are said.
|
|
702
|
+
*/
|
|
703
|
+
const belongs = (ref: SessionRef, to: Address): boolean => {
|
|
704
|
+
const journal = api.journal?.();
|
|
705
|
+
if (journal === undefined) return false;
|
|
706
|
+
return journal
|
|
707
|
+
.find({ type: SessionBelongs.name, field: "session", equals: ref })
|
|
708
|
+
.some((stored) => {
|
|
709
|
+
const parsed = SessionBelongs.schema.safeParse(stored.data);
|
|
710
|
+
if (!parsed.success) return false;
|
|
711
|
+
return parsed.data.session === ref && sameAddress(parsed.data.to, to);
|
|
712
|
+
});
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
api.action(
|
|
716
|
+
action(sessionList, {
|
|
717
|
+
// A read changes nothing: it may be made again.
|
|
718
|
+
recovery: "repeat",
|
|
719
|
+
effect: "read",
|
|
720
|
+
world: "niwa",
|
|
721
|
+
run: async (input) => {
|
|
722
|
+
const { catalog, entries, unreadable } = await survey(input.harness, input.cwd, input.managedOnly);
|
|
723
|
+
const { page, nextCursor } = pageOf(entries, input.limit ?? SESSION_LIST_DEFAULT, input.cursor);
|
|
724
|
+
return {
|
|
725
|
+
sessions: page,
|
|
726
|
+
total: entries.length,
|
|
727
|
+
...(nextCursor === undefined
|
|
728
|
+
? {}
|
|
729
|
+
: { nextCursor, hint: `${page.length} of ${entries.length} sessions shown: pass nextCursor as cursor for the next page, or narrow by harness or cwd.` }),
|
|
730
|
+
belongings: catalog.belongings(new Set(page.map((entry) => entry.ref))),
|
|
731
|
+
unreadable,
|
|
732
|
+
};
|
|
733
|
+
},
|
|
734
|
+
}),
|
|
735
|
+
);
|
|
736
|
+
|
|
737
|
+
api.action(
|
|
738
|
+
action(sessionGet, {
|
|
739
|
+
// A read changes nothing: it may be made again.
|
|
740
|
+
recovery: "repeat",
|
|
741
|
+
effect: "read",
|
|
742
|
+
world: "niwa",
|
|
743
|
+
run: async (input) => {
|
|
744
|
+
const ref = refOf(input.id);
|
|
745
|
+
const { catalog } = await survey(sessionOf(ref).harness, undefined);
|
|
746
|
+
const entry = catalog.get(ref);
|
|
747
|
+
if (entry?.id === undefined) throw new UnknownId(input.id, "session");
|
|
748
|
+
return { ...entry, id: entry.id, belongings: catalog.belongings(new Set([ref])) };
|
|
749
|
+
},
|
|
750
|
+
}),
|
|
751
|
+
);
|
|
752
|
+
|
|
753
|
+
api.action(
|
|
754
|
+
action(sessionBelong, {
|
|
755
|
+
// The belonging is one fact: the same session and the same address are one record, so a
|
|
756
|
+
// call that was cut off may be made again.
|
|
757
|
+
recovery: "repeat",
|
|
758
|
+
effect: "record",
|
|
759
|
+
world: "niwa",
|
|
760
|
+
run: async (input, ctx) => {
|
|
761
|
+
const ref = refOf(input.session);
|
|
762
|
+
const to = input.to;
|
|
763
|
+
// The write is skipped when the journal already holds this belonging: saying it twice
|
|
764
|
+
// is one fact, not two.
|
|
765
|
+
if (belongs(ref, to)) {
|
|
766
|
+
return { session: ref, to, source: input.source, known: true };
|
|
767
|
+
}
|
|
768
|
+
await ctx.emit(SessionBelongs, { session: ref, to, source: input.source });
|
|
769
|
+
return { session: ref, to, source: input.source, known: false };
|
|
770
|
+
},
|
|
771
|
+
}),
|
|
772
|
+
);
|
|
773
|
+
|
|
774
|
+
api.action(
|
|
775
|
+
action(sessionRead, {
|
|
776
|
+
// A read changes nothing: it may be made again.
|
|
777
|
+
recovery: "repeat",
|
|
778
|
+
effect: "read",
|
|
779
|
+
world: "local",
|
|
780
|
+
run: async (input) => {
|
|
781
|
+
const id = sessionOf(refOf(input.session));
|
|
782
|
+
return await readTranscript(bindings.find((candidate) => candidate.instance.id === id.harness), id, input);
|
|
783
|
+
},
|
|
784
|
+
}),
|
|
785
|
+
);
|
|
786
|
+
|
|
787
|
+
api.action(
|
|
788
|
+
action(sessionSearch, {
|
|
789
|
+
// A search reads and changes nothing: it may be made again.
|
|
790
|
+
recovery: "repeat",
|
|
791
|
+
effect: "read",
|
|
792
|
+
world: "local",
|
|
793
|
+
run: async (input) => {
|
|
794
|
+
const id = sessionOf(refOf(input.session));
|
|
795
|
+
return await searchSession(bindings.find((candidate) => candidate.instance.id === id.harness), id, input);
|
|
796
|
+
},
|
|
797
|
+
}),
|
|
798
|
+
);
|
|
799
|
+
|
|
800
|
+
// The harnesses as they are bound: the same bindings session.start refuses a foreign block by, so what these say
|
|
801
|
+
// and what a start takes agree.
|
|
802
|
+
const harnessItem = (binding: HarnessBinding) => ({
|
|
803
|
+
name: binding.instance.id,
|
|
804
|
+
kind: binding.instance.kind,
|
|
805
|
+
...(binding.instance.model === undefined ? {} : { model: binding.instance.model }),
|
|
806
|
+
capabilities: binding.instance.sides,
|
|
807
|
+
...(binding.options === undefined
|
|
808
|
+
? {}
|
|
809
|
+
: { block: binding.options.block, options: JsonSchemaValue.parse(z.toJSONSchema(binding.options.schema, { io: "input" })) }),
|
|
810
|
+
});
|
|
811
|
+
api.action(
|
|
812
|
+
action(harnessList, {
|
|
813
|
+
// A read of how the harnesses are bound: it may be made again.
|
|
814
|
+
recovery: "repeat",
|
|
815
|
+
effect: "read",
|
|
816
|
+
world: "niwa",
|
|
817
|
+
run: () => ({ items: bindings.map(harnessItem) }),
|
|
818
|
+
}),
|
|
819
|
+
);
|
|
820
|
+
api.action(
|
|
821
|
+
action(harnessGet, {
|
|
822
|
+
recovery: "repeat",
|
|
823
|
+
effect: "read",
|
|
824
|
+
world: "niwa",
|
|
825
|
+
run: (input) => {
|
|
826
|
+
const binding = bindings.find((one) => one.instance.id === input.name);
|
|
827
|
+
if (binding === undefined) throw new Error(`harness "${input.name}" is not known: harness.list names the harnesses`);
|
|
828
|
+
return {
|
|
829
|
+
...harnessItem(binding),
|
|
830
|
+
machine: binding.instance.machine,
|
|
831
|
+
};
|
|
832
|
+
},
|
|
833
|
+
}),
|
|
834
|
+
);
|
|
835
|
+
|
|
836
|
+
api.action(
|
|
837
|
+
action(sessionRunning, {
|
|
838
|
+
// A read changes nothing: it may be made again.
|
|
839
|
+
recovery: "repeat",
|
|
840
|
+
effect: "read",
|
|
841
|
+
world: "niwa",
|
|
842
|
+
run: async (input) => {
|
|
843
|
+
const { entries, unreadable, own } = await survey(input.harness, undefined);
|
|
844
|
+
const limit = input.limit ?? DEFAULT_RUNNING_LIMIT;
|
|
845
|
+
const shown = entries.filter((entry) => input.all === true || own.has(entry.ref));
|
|
846
|
+
const latestFirst = (state: SessionEntry["state"]): SessionEntry[] =>
|
|
847
|
+
shown.filter((entry) => entry.state === state).sort((a, b) => (b.lastActivityAt ?? 0) - (a.lastActivityAt ?? 0));
|
|
848
|
+
const running = latestFirst("running");
|
|
849
|
+
const unknown = latestFirst("unknown");
|
|
850
|
+
return {
|
|
851
|
+
running: running.slice(0, limit).map(runningLine),
|
|
852
|
+
unknown: unknown.slice(0, limit).map(runningLine),
|
|
853
|
+
omitted: Math.max(0, running.length - limit) + Math.max(0, unknown.length - limit),
|
|
854
|
+
unreadable,
|
|
855
|
+
};
|
|
856
|
+
},
|
|
857
|
+
}),
|
|
858
|
+
);
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* The token of a session that is being started or resumed.
|
|
862
|
+
*
|
|
863
|
+
* The session is the principal and its mark names it: the session has no name until the
|
|
864
|
+
* harness gives it one, and the mark is what the pairing records. The token carries what the
|
|
865
|
+
* session sees, so the core refuses every call outside it, and it is the one thing the
|
|
866
|
+
* session's process is given.
|
|
867
|
+
*/
|
|
868
|
+
const tokenFor = (mark: string, rules: Grant, parent: Caller): Token =>
|
|
869
|
+
api.issueToken("session", mark, { grant: rules, parent });
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* The launch of a session: the tools its grant allows, and its box. The box is the host's
|
|
873
|
+
* default, what the start asks for, and the installation's profile, with a temp directory of
|
|
874
|
+
* its own and the host's socket; what goes beyond the default is held to the caller's grant. A
|
|
875
|
+
* box that cannot be had stops the start with every reason: this runs before a mark, a token
|
|
876
|
+
* or a process exists.
|
|
877
|
+
*/
|
|
878
|
+
const launchFor = async (rules: Grant, cwd: string | undefined, harness: string, request: BoxAccessInput | undefined, caller: Caller, defaults: BoxAccessInput | BoxAccess = boxDefault): Promise<Launch> => {
|
|
879
|
+
const tools = toolsOfGrant(rules);
|
|
880
|
+
const adapter = sandboxOf(boxes.adapter ?? "srt");
|
|
881
|
+
await requireSandbox(adapter);
|
|
882
|
+
const temp = realpathSync(mkdtempSync(join(tmpdir(), "niwa-box-")));
|
|
883
|
+
const rights = api.rights(caller);
|
|
884
|
+
try {
|
|
885
|
+
const plan = boxes.plan({
|
|
886
|
+
cwd: cwd ?? process.cwd(),
|
|
887
|
+
worktree: cwd === undefined ? undefined : options.worktreeFor?.(api, cwd),
|
|
888
|
+
...(cwd === undefined ? { noProject: "the session names no working directory" } : {}),
|
|
889
|
+
defaults,
|
|
890
|
+
request,
|
|
891
|
+
owner: harness,
|
|
892
|
+
writes: [{ path: temp, from: "temp" }],
|
|
893
|
+
closed: [...closedPlacesOf(api.home()), api.secrets.dir].map((path) => ({ path, from: "niwa" })),
|
|
894
|
+
network: true,
|
|
895
|
+
});
|
|
896
|
+
const admitted = admit(plan, adapter, (needed) => heldRule(rights, needed), { sockets: [api.socket()] });
|
|
897
|
+
return { ...(tools === undefined ? {} : { tools }), box: { sandbox: adapter, spec: admitted.spec }, plan, rules: admitted.rules, temp };
|
|
898
|
+
} catch (error) {
|
|
899
|
+
rmSync(temp, { recursive: true, force: true });
|
|
900
|
+
if (error instanceof BoxRefused) throw new SessionRefusal("box-refused", error.message);
|
|
901
|
+
throw error;
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
|
|
905
|
+
/** The launch as the control side takes it: the box carries the mark its manifest is recorded under. */
|
|
906
|
+
const launchOptions = (launch: Launch | undefined, mark: string) =>
|
|
907
|
+
launch === undefined
|
|
908
|
+
? {}
|
|
909
|
+
: { ...(launch.tools === undefined ? {} : { tools: launch.tools }), box: { ...launch.box, mark } };
|
|
910
|
+
|
|
911
|
+
/** What the process of a launch is given besides its token: its own temp directory. */
|
|
912
|
+
const launchEnv = (launch: Launch | undefined): Record<string, string> => (launch === undefined ? {} : { TMPDIR: launch.temp });
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* Runs the launch of a session whose process is born in a box, with the manifest of that box
|
|
916
|
+
* written to the journal by the action that launches it, before the process starts.
|
|
917
|
+
*/
|
|
918
|
+
const recording = async <T>(mark: string, harness: string, launch: Launch | undefined, ctx: ActionContext, work: () => Promise<T>): Promise<T> => {
|
|
919
|
+
if (launch === undefined) return await work();
|
|
920
|
+
boxManifests.set(mark, (made) => ctx.emit(SessionBoxManifest, { mark, harness, ...boxManifest(launch.plan, launch.rules, made) }));
|
|
921
|
+
try {
|
|
922
|
+
return await work();
|
|
923
|
+
} finally {
|
|
924
|
+
boxManifests.delete(mark);
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* The grant of a session: what the caller asked for, narrowed to what the caller has, and what
|
|
930
|
+
* the module gives every session for itself.
|
|
931
|
+
*
|
|
932
|
+
* Asking for more than the caller has creates no session and answers with the masks refused.
|
|
933
|
+
* The answering action is added to the request by the module for every session that cannot
|
|
934
|
+
* answer natively, so it is not compared with the caller's rights. When the request names no
|
|
935
|
+
* tool, the caller's `tool:` rules are taken: a child is never wider than a limited caller, and
|
|
936
|
+
* an unlimited caller's child stays as it asked.
|
|
937
|
+
*/
|
|
938
|
+
const grantOfSession = (caller: Caller, requested: VisibleActionsInput | undefined, visible: VisibleActions): Grant => {
|
|
939
|
+
// The answering action is the module's to give, whoever asked for it.
|
|
940
|
+
const asked = (requested?.actions ?? []).filter((spec) => {
|
|
941
|
+
const entry = rule(spec);
|
|
942
|
+
return entry.verb !== "call" || String(entry.name) !== SUBMIT_ANSWER_ACTION;
|
|
943
|
+
});
|
|
944
|
+
const narrowed = api.narrow(caller, [...asked, ...inheritedLaunch(api.rights(caller), asked)]);
|
|
945
|
+
if ("refused" in narrowed) {
|
|
946
|
+
throw new SessionRefusal(
|
|
947
|
+
"wider-than-caller",
|
|
948
|
+
`the caller does not have ${narrowed.refused.join(", ")}: a session it starts cannot see more than it does`,
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
const own = [...visible.actions.filter((name) => name === SUBMIT_ANSWER_ACTION), sessionOpenQuestions.name, accessMine];
|
|
952
|
+
return grant([...specsOf(narrowed.rules), ...own]);
|
|
953
|
+
};
|
|
954
|
+
|
|
955
|
+
/** The session a mark names: the mark is what the pairing recorded when the session was started. */
|
|
956
|
+
const sessionOfMark = (mark: string): SessionRef | undefined => {
|
|
957
|
+
let session: SessionRef | undefined;
|
|
958
|
+
for (const record of api.journal?.()?.since(seq(0), [SessionMarked.name]) ?? []) {
|
|
959
|
+
const marked = SessionMarked.schema.safeParse(record.data);
|
|
960
|
+
if (marked.success && marked.data.mark === mark) session = marked.data.session;
|
|
961
|
+
}
|
|
962
|
+
return session;
|
|
963
|
+
};
|
|
964
|
+
|
|
965
|
+
sessionOfClientMark = sessionOfMark;
|
|
966
|
+
const ended = (ref: SessionRef): boolean =>
|
|
967
|
+
(api.journal?.()?.find({ type: SessionEnded.name, field: "session", equals: ref }).length ?? 0) > 0;
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
const sessionGrantClosed = (mark: string): boolean => (api.journal?.()?.find({
|
|
971
|
+
type: AccessClosed.name, field: "principal.id", equals: mark,
|
|
972
|
+
}) ?? []).some((row) => AccessClosed.schema.parse(row.data).principal.kind === "session");
|
|
973
|
+
|
|
974
|
+
// A close and the first mark can arrive in either order. The second record
|
|
975
|
+
// always observes the first, including when a host replays its handlers.
|
|
976
|
+
api.on(SessionMarked, { id: "check-mark-lifetime", concurrency: Infinity }, async ({ session, mark }, step) => {
|
|
977
|
+
if (sessionGrantClosed(mark)) {
|
|
978
|
+
await step(sessionEnd, { session, reason: "its grant was closed" });
|
|
979
|
+
} else if (ended(session) && startedOf(session)?.run !== undefined) {
|
|
980
|
+
await step.outcome(actionName("access.grant.close"), { principal: principalOf("session", mark), reason: "the session ended" });
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
api.on(SessionEnded, { id: "close-run-session-grants", concurrency: Infinity }, async ({ session }, step) => {
|
|
984
|
+
if (startedOf(session)?.run === undefined) return;
|
|
985
|
+
for (const row of api.journal?.()?.find({ type: SessionMarked.name, field: "session", equals: session }) ?? []) {
|
|
986
|
+
const { mark } = SessionMarked.schema.parse(row.data);
|
|
987
|
+
if (!sessionGrantClosed(mark)) await step.outcome(actionName("access.grant.close"), {
|
|
988
|
+
principal: principalOf("session", mark), reason: "the session ended",
|
|
989
|
+
}, { key: mark });
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
/** The latest `session.started` of a session, from the journal. */
|
|
994
|
+
const startedOf = (ref: SessionRef): z.output<typeof SessionStarted.schema> | undefined =>
|
|
995
|
+
api.journal?.()
|
|
996
|
+
?.find({ type: SessionStarted.name, field: "session", equals: ref })
|
|
997
|
+
.flatMap((stored) => {
|
|
998
|
+
const parsed = SessionStarted.schema.safeParse(stored.data);
|
|
999
|
+
return parsed.success ? [parsed.data] : [];
|
|
1000
|
+
})
|
|
1001
|
+
.at(-1);
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* The last send of a session under an operation id, from the journal: the digest of its message,
|
|
1005
|
+
* and its outcome once it was settled. A send that has no outcome was cut off while it went.
|
|
1006
|
+
*/
|
|
1007
|
+
const inputOf = (ref: SessionRef, operation: string): { digest: string; outcome?: InputOutcome } | undefined => {
|
|
1008
|
+
const journal = api.journal?.();
|
|
1009
|
+
if (journal === undefined) return undefined;
|
|
1010
|
+
const sent = journal
|
|
1011
|
+
.find({ type: SessionInputSending.name, field: "operation", equals: operation })
|
|
1012
|
+
.flatMap((stored) => {
|
|
1013
|
+
const parsed = SessionInputSending.schema.safeParse(stored.data);
|
|
1014
|
+
return parsed.success && parsed.data.session === ref ? [{ seq: stored.seq, digest: parsed.data.digest }] : [];
|
|
1015
|
+
})
|
|
1016
|
+
.at(-1);
|
|
1017
|
+
if (sent === undefined) return undefined;
|
|
1018
|
+
const settled = journal
|
|
1019
|
+
.find({ type: SessionInputSettled.name, field: "operation", equals: operation })
|
|
1020
|
+
.flatMap((stored) => {
|
|
1021
|
+
const parsed = SessionInputSettled.schema.safeParse(stored.data);
|
|
1022
|
+
return parsed.success && parsed.data.session === ref && stored.seq > sent.seq ? [parsed.data.outcome] : [];
|
|
1023
|
+
})
|
|
1024
|
+
.at(-1);
|
|
1025
|
+
return settled === undefined ? { digest: sent.digest } : { digest: sent.digest, outcome: settled };
|
|
1026
|
+
};
|
|
1027
|
+
|
|
1028
|
+
/**
|
|
1029
|
+
* The start whose prompt was an input under an operation, from the journal: the digest of the input, and what
|
|
1030
|
+
* the start answered. A send under the operation is an input too, with another digest.
|
|
1031
|
+
*/
|
|
1032
|
+
const startUnder = (operation: string): { digest: string; answer?: z.output<typeof sessionStart.output> } | undefined => {
|
|
1033
|
+
const journal = api.journal?.();
|
|
1034
|
+
if (journal === undefined) return undefined;
|
|
1035
|
+
const sent = journal
|
|
1036
|
+
.find({ type: SessionInputSending.name, field: "operation", equals: operation })
|
|
1037
|
+
.flatMap((stored) => {
|
|
1038
|
+
const parsed = SessionInputSending.schema.safeParse(stored.data);
|
|
1039
|
+
return parsed.success ? [parsed.data] : [];
|
|
1040
|
+
})
|
|
1041
|
+
.at(0);
|
|
1042
|
+
if (sent === undefined) return undefined;
|
|
1043
|
+
const issued = sessionIdsOf(journal).find((entry) => entry.ref === sent.session);
|
|
1044
|
+
const outcome = inputOf(sent.session, operation)?.outcome;
|
|
1045
|
+
// An input under the operation that is not the prompt of a start niwa made answers nothing but its conflict.
|
|
1046
|
+
if (issued === undefined) return { digest: sent.digest };
|
|
1047
|
+
const cwd = startedOf(sent.session)?.cwd;
|
|
1048
|
+
const made = cwd === undefined
|
|
1049
|
+
? undefined
|
|
1050
|
+
: journal.find({ type: WorktreeCreated.name, field: "path", equals: cwd }).flatMap((stored) => {
|
|
1051
|
+
const parsed = WorktreeCreated.schema.safeParse(stored.data);
|
|
1052
|
+
return parsed.success ? [parsed.data] : [];
|
|
1053
|
+
}).at(-1);
|
|
1054
|
+
return {
|
|
1055
|
+
digest: sent.digest,
|
|
1056
|
+
answer: {
|
|
1057
|
+
session: issued.id,
|
|
1058
|
+
ref: sent.session,
|
|
1059
|
+
...(outcome?.status === "accepted" ? { receipt: outcome.receipt } : {}),
|
|
1060
|
+
...(made === undefined ? {} : { worktree: { id: made.id, path: made.path, branch: made.branch } }),
|
|
1061
|
+
operation,
|
|
1062
|
+
},
|
|
1063
|
+
};
|
|
1064
|
+
};
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* The last reservation of a start under an operation, from the journal: the digest it was made with, the
|
|
1068
|
+
* directory, the session its harness named, and whether it failed with nothing sent.
|
|
1069
|
+
*/
|
|
1070
|
+
const reservationOf = (operation: string) => {
|
|
1071
|
+
const journal = api.journal?.();
|
|
1072
|
+
if (journal === undefined) return undefined;
|
|
1073
|
+
const last = journal
|
|
1074
|
+
.find({ type: SessionStartReserved.name, field: "operation", equals: operation })
|
|
1075
|
+
.flatMap((stored) => {
|
|
1076
|
+
const parsed = SessionStartReserved.schema.safeParse(stored.data);
|
|
1077
|
+
return parsed.success ? [{ seq: stored.seq, ...parsed.data }] : [];
|
|
1078
|
+
})
|
|
1079
|
+
.at(-1);
|
|
1080
|
+
if (last === undefined) return undefined;
|
|
1081
|
+
const after = <T>(type: { name: string; schema: z.ZodType<T> }): T[] =>
|
|
1082
|
+
journal.find({ type: type.name as never, field: "operation", equals: operation }).flatMap((stored) => {
|
|
1083
|
+
const parsed = type.schema.safeParse(stored.data);
|
|
1084
|
+
return parsed.success && stored.seq > last.seq ? [parsed.data] : [];
|
|
1085
|
+
});
|
|
1086
|
+
const named = after(SessionStartNamed).at(-1)?.session;
|
|
1087
|
+
return {
|
|
1088
|
+
...last,
|
|
1089
|
+
...(named === undefined ? {} : { named }),
|
|
1090
|
+
released: after(SessionStartUnsent).length > 0,
|
|
1091
|
+
};
|
|
1092
|
+
};
|
|
1093
|
+
|
|
1094
|
+
/** The number of the last turn the journal holds for a session. */
|
|
1095
|
+
const lastTurnOf = (ref: SessionRef): number =>
|
|
1096
|
+
Math.max(
|
|
1097
|
+
0,
|
|
1098
|
+
...(api.journal?.()?.find({ type: SessionTurnStarted.name, field: "session", equals: ref }) ?? []).flatMap((stored) => {
|
|
1099
|
+
const parsed = SessionTurnStarted.schema.safeParse(stored.data);
|
|
1100
|
+
return parsed.success ? [parsed.data.turn] : [];
|
|
1101
|
+
}),
|
|
1102
|
+
);
|
|
1103
|
+
|
|
1104
|
+
/** The turn counting of a session, started from the journal the first time it is needed. */
|
|
1105
|
+
const countOf = (ref: SessionRef): { last: number; offset: number } => {
|
|
1106
|
+
const known = turnCounts.get(ref);
|
|
1107
|
+
if (known !== undefined) return known;
|
|
1108
|
+
const made = { last: lastTurnOf(ref), offset: 0 };
|
|
1109
|
+
turnCounts.set(ref, made);
|
|
1110
|
+
return made;
|
|
1111
|
+
};
|
|
1112
|
+
|
|
1113
|
+
/** The number a turn of the harness has in the records. */
|
|
1114
|
+
const numbered = (ref: SessionRef, turn: number): number => turn + countOf(ref).offset;
|
|
1115
|
+
|
|
1116
|
+
/** The harness counts from 1 again: the next turn it names goes on after the last one written. */
|
|
1117
|
+
const restart = (ref: SessionRef): void => {
|
|
1118
|
+
const count = countOf(ref);
|
|
1119
|
+
count.offset = count.last;
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
/** A turn of the harness began: its number in the records, always after the last one written. */
|
|
1123
|
+
const beginning = (ref: SessionRef, turn: number): number => {
|
|
1124
|
+
const count = countOf(ref);
|
|
1125
|
+
if (turn + count.offset <= count.last) count.offset = count.last - turn + 1;
|
|
1126
|
+
count.last = turn + count.offset;
|
|
1127
|
+
return count.last;
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1130
|
+
/** The model the harness last named for a session, from the journal: `undefined` until it names one. */
|
|
1131
|
+
const modelOf = (ref: SessionRef): ModelName | undefined =>
|
|
1132
|
+
api.journal?.()
|
|
1133
|
+
?.find({ type: SessionModel.name, field: "session", equals: ref })
|
|
1134
|
+
.flatMap((stored) => {
|
|
1135
|
+
const parsed = SessionModel.schema.safeParse(stored.data);
|
|
1136
|
+
return parsed.success ? [parsed.data.model] : [];
|
|
1137
|
+
})
|
|
1138
|
+
.at(-1);
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* What a session was last launched with, from the journal: the request its grant answered
|
|
1142
|
+
* and the cwd its box was made for (the box's own, else the one it started in). Nothing is recorded for a session niwa did not launch.
|
|
1143
|
+
*
|
|
1144
|
+
* The grant is the record of the last mark the session was given. The rules the module adds
|
|
1145
|
+
* to every session are left out of the request, as they are added again.
|
|
1146
|
+
*/
|
|
1147
|
+
const lastLaunchOf = (ref: SessionRef): { request: VisibleActionsInput; cwd: string | undefined; rules: Grant; mark: string; parent?: Caller } | undefined => {
|
|
1148
|
+
const journal = api.journal?.();
|
|
1149
|
+
if (journal === undefined) return undefined;
|
|
1150
|
+
const marks = journal.find({ type: SessionMarked.name, field: "session", equals: ref });
|
|
1151
|
+
const mark = marks.flatMap((stored) => {
|
|
1152
|
+
const parsed = SessionMarked.schema.safeParse(stored.data);
|
|
1153
|
+
return parsed.success ? [parsed.data.mark] : [];
|
|
1154
|
+
}).at(-1);
|
|
1155
|
+
if (mark === undefined) return undefined;
|
|
1156
|
+
const granted = journal
|
|
1157
|
+
.find({ type: AccessGranted.name, field: "principal.id", equals: mark })
|
|
1158
|
+
.flatMap((stored) => {
|
|
1159
|
+
const parsed = AccessGranted.schema.safeParse(stored.data);
|
|
1160
|
+
return parsed.success && parsed.data.principal.kind === "session" ? [parsed.data] : [];
|
|
1161
|
+
})
|
|
1162
|
+
.at(-1);
|
|
1163
|
+
if (granted === undefined) return undefined;
|
|
1164
|
+
const own = new Set<string>([sessionOpenQuestions.name, accessMine]);
|
|
1165
|
+
const actions = granted.rules
|
|
1166
|
+
.map((spec) => rule(spec))
|
|
1167
|
+
.filter((each) => each.verb !== "call" || !own.has(each.name))
|
|
1168
|
+
.map(specOf);
|
|
1169
|
+
const boxed = journal
|
|
1170
|
+
.find({ type: SessionBoxManifest.name, field: "mark", equals: mark })
|
|
1171
|
+
.flatMap((stored) => {
|
|
1172
|
+
const parsed = SessionBoxManifest.schema.safeParse(stored.data);
|
|
1173
|
+
return parsed.success ? [parsed.data.cwd] : [];
|
|
1174
|
+
})
|
|
1175
|
+
.at(-1);
|
|
1176
|
+
// The directory as the session was started in it, as its harness knows it; the box's own when there is none.
|
|
1177
|
+
const started = startedOf(ref)?.cwd;
|
|
1178
|
+
return { request: { actions, disabledTools: startedOf(ref)?.disabledTools }, rules: grant(granted.rules), mark,
|
|
1179
|
+
...(granted.parent === undefined ? {} : { parent: callerOf(granted.parent.principal) }), cwd: started === undefined ? boxed : String(started) };
|
|
1180
|
+
};
|
|
1181
|
+
|
|
1182
|
+
/**
|
|
1183
|
+
* A session whose grant was closed is stopped: the turn it runs is interrupted through
|
|
1184
|
+
* the action that does it, and its end is written. The token it holds buys nothing any more.
|
|
1185
|
+
*/
|
|
1186
|
+
api.on(AccessClosed, { id: "session-grant-closed" }, async (data, step) => {
|
|
1187
|
+
if (data.principal.kind !== "session") return;
|
|
1188
|
+
const session = sessionOfMark(data.principal.id);
|
|
1189
|
+
if (session === undefined) return;
|
|
1190
|
+
// A harness that cannot interrupt, or a session with no turn, is not a reason to keep it.
|
|
1191
|
+
await step(sessionEnd, { session, reason: `its grant was closed: ${data.reason}` });
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1194
|
+
api.action(
|
|
1195
|
+
action(sessionStart, {
|
|
1196
|
+
// A harness names the session once: a start that was cut off may have made one
|
|
1197
|
+
// that nothing knows of, so it is not made again.
|
|
1198
|
+
recovery: "do-not-repeat",
|
|
1199
|
+
effect: "write",
|
|
1200
|
+
world: "local",
|
|
1201
|
+
run: async (input, ctx) => {
|
|
1202
|
+
// The prompt is an input under an operation: a retry with it answers the session it made.
|
|
1203
|
+
const operation = input.operation ?? ctx.operationId;
|
|
1204
|
+
const digest = createHash("sha256").update(stableJson([ctx.caller.kind === "client" ? ctx.caller.principal ?? ctx.caller.id : ctx.caller.kind, input])).digest("hex");
|
|
1205
|
+
const conflict = () => new SessionRefusal("operation-conflict", `operation "${operation}" was another input of a session`);
|
|
1206
|
+
// A retry while the start runs waits for it: the harness is asked once.
|
|
1207
|
+
const running = startsRunning.get(operation);
|
|
1208
|
+
if (running !== undefined) {
|
|
1209
|
+
if (running.digest !== digest) throw conflict();
|
|
1210
|
+
return await running.answer;
|
|
1211
|
+
}
|
|
1212
|
+
const before = startUnder(operation);
|
|
1213
|
+
if (before !== undefined) {
|
|
1214
|
+
if (before.digest !== digest || before.answer === undefined) throw conflict();
|
|
1215
|
+
return before.answer;
|
|
1216
|
+
}
|
|
1217
|
+
// A start that was cut off after it asked its harness is never asked again: the session it made is
|
|
1218
|
+
// answered when the harness named one, and otherwise its prompt may have gone with a session nobody knows.
|
|
1219
|
+
const reserved = reservationOf(operation);
|
|
1220
|
+
if (reserved !== undefined && !reserved.released) {
|
|
1221
|
+
if (reserved.digest !== digest) throw conflict();
|
|
1222
|
+
if (reserved.named === undefined) {
|
|
1223
|
+
throw new InputPossiblySent(instanceOf(bindings, input.harness).id, "start", "a start under this operation was cut off after it asked the harness for a session");
|
|
1224
|
+
}
|
|
1225
|
+
const ref = reserved.named;
|
|
1226
|
+
await ctx.emit(SessionStarted, {
|
|
1227
|
+
session: ref,
|
|
1228
|
+
id: sessionIds.issue(ctx.operationId),
|
|
1229
|
+
cwd: reserved.cwd,
|
|
1230
|
+
run: reserved.run,
|
|
1231
|
+
execution: reserved.execution,
|
|
1232
|
+
parentSession: reserved.parentSession,
|
|
1233
|
+
boxAccess: reserved.boxAccess,
|
|
1234
|
+
disabledTools: reserved.disabledTools,
|
|
1235
|
+
effort: input.effort,
|
|
1236
|
+
mode: input.mode,
|
|
1237
|
+
tools: reserved.tools,
|
|
1238
|
+
...(input.box === undefined ? {} : { box: input.box }),
|
|
1239
|
+
...(input.stuckAfter === undefined ? {} : { stuckAfter: input.stuckAfter }),
|
|
1240
|
+
});
|
|
1241
|
+
if (reserved.mark !== undefined) await ctx.emit(SessionMarked, { session: ref, mark: reserved.mark });
|
|
1242
|
+
await ctx.emit(SessionInputSending, { session: ref, operation, digest });
|
|
1243
|
+
const reason = "the start was cut off after its harness named the session, while its prompt was going";
|
|
1244
|
+
await ctx.emit(SessionInputSettled, { session: ref, operation, outcome: { status: "possibly-sent", reason } });
|
|
1245
|
+
const answer = startUnder(operation)?.answer;
|
|
1246
|
+
if (answer === undefined) throw new Error(`the start under operation "${operation}" was written and cannot be read back`);
|
|
1247
|
+
return answer;
|
|
1248
|
+
}
|
|
1249
|
+
const answer = starting(input, ctx, operation, digest);
|
|
1250
|
+
startsRunning.set(operation, { digest, answer });
|
|
1251
|
+
try {
|
|
1252
|
+
return await answer;
|
|
1253
|
+
} finally {
|
|
1254
|
+
startsRunning.delete(operation);
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
}),
|
|
1258
|
+
);
|
|
1259
|
+
|
|
1260
|
+
/** A start that nothing answered yet: the harness is asked for a session, once. */
|
|
1261
|
+
const starting = async (
|
|
1262
|
+
input: z.output<typeof sessionStart.input>,
|
|
1263
|
+
ctx: ActionContext,
|
|
1264
|
+
operation: string,
|
|
1265
|
+
digest: string,
|
|
1266
|
+
): Promise<z.output<typeof sessionStart.output>> => {
|
|
1267
|
+
const control = controlFor(bindings, input.harness, "start");
|
|
1268
|
+
// A model or an effort the kind cannot apply is refused here, before anything is made.
|
|
1269
|
+
const instance = instanceOf(bindings, input.harness);
|
|
1270
|
+
requireLaunch(instance.id, instance.sides.control?.launch ?? { model: false, effort: [], modes: [] }, input);
|
|
1271
|
+
// The options block of another kind is refused here too: nothing is ignored.
|
|
1272
|
+
const blocks = requireOwnBlocks(instance.id, optionsOf(bindings, input.harness), blocksOf(input, SESSION_START_FIELDS));
|
|
1273
|
+
// A tool mode the installation cannot hold is refused here too, before any prompt.
|
|
1274
|
+
requireTools(instance.id, instance.sides.control?.tools, input.tools);
|
|
1275
|
+
const principal = ctx.caller.kind === "client" ? ctx.caller.principal : undefined;
|
|
1276
|
+
const parentSession = principal?.kind === "session" ? sessionOfMark(principal.id) : undefined;
|
|
1277
|
+
const parent = parentSession === undefined ? undefined : startedOf(parentSession);
|
|
1278
|
+
if (principal?.kind === "session" && parentSession === undefined && api.journal?.()?.find({
|
|
1279
|
+
type: AccessGranted.name, field: "principal.id", equals: principal.id,
|
|
1280
|
+
}).some((row) => AccessGranted.schema.parse(row.data).parent !== undefined)) {
|
|
1281
|
+
throw new SessionRefusal("unnamed-parent", "the parent session has not been named yet");
|
|
1282
|
+
}
|
|
1283
|
+
if (parent?.run !== undefined && parentSession !== undefined && ended(parentSession)) {
|
|
1284
|
+
throw new SessionRefusal("ended-parent", "the session that asked for a helper has ended");
|
|
1285
|
+
}
|
|
1286
|
+
const run = principal?.kind === "run" ? runIdOfPrincipal(principal.id) : parent?.run;
|
|
1287
|
+
const execution = principal?.kind === "run" ? principal.id : parent?.execution;
|
|
1288
|
+
if (parent?.run !== undefined && (input.worktree !== undefined ||
|
|
1289
|
+
(input.cwd !== undefined && (parent.cwd === undefined || realpathSync(input.cwd) !== realpathSync(parent.cwd))))) {
|
|
1290
|
+
throw new SessionRefusal("different-project", "a helper starts in its parent's working directory");
|
|
1291
|
+
}
|
|
1292
|
+
const rights = api.rights(ctx.caller);
|
|
1293
|
+
const inherited = run !== undefined && input.visible?.actions === undefined && rights !== "unlimited"
|
|
1294
|
+
? specsOf(rights).filter((spec) => ![sessionOpenQuestions.name, accessMine].some((own) => String(rule(spec).name) === own))
|
|
1295
|
+
: undefined;
|
|
1296
|
+
const requested = {
|
|
1297
|
+
actions: input.visible?.actions ?? (run === undefined ? undefined : [...(inherited ?? []), SUBMIT_ANSWER_ACTION]),
|
|
1298
|
+
disabledTools: [...new Set([...(parent?.disabledTools ?? []), ...(input.visible?.disabledTools ?? [])])],
|
|
1299
|
+
};
|
|
1300
|
+
const visible = visibleFor(input.harness, callsOf(requested));
|
|
1301
|
+
// Refused before a mark or a token is made: a start that asks for too much, or for a
|
|
1302
|
+
// box this machine cannot give, creates nothing.
|
|
1303
|
+
const rules = grantOfSession(ctx.caller, requested, visible);
|
|
1304
|
+
// A session asked to run in a worktree gets one made by the git module, and runs in it.
|
|
1305
|
+
const worktree = input.worktree === undefined ? undefined : await worktreeFor(ctx, input.harness, input.worktree, input.cwd);
|
|
1306
|
+
const cwd = worktree?.path ?? input.cwd ?? parent?.cwd;
|
|
1307
|
+
const launch = await launchFor(rules, cwd, input.harness, input.box, ctx.caller, parent?.run !== undefined ? parent.boxAccess : parent?.box?.only === undefined ? undefined : parent.box);
|
|
1308
|
+
// The mode asked for, within the allow-list of the grant: what the grant adds is held too.
|
|
1309
|
+
const toolRequest = parent?.tools === "niwa-only" ? "niwa-only" :
|
|
1310
|
+
toolsOfSession(input.tools, typeof parent?.tools === "object" ? parent.tools : undefined);
|
|
1311
|
+
const tools = toolsOfSession(toolRequest, launch.tools);
|
|
1312
|
+
requireTools(instance.id, instance.sides.control?.tools, tools);
|
|
1313
|
+
// The mark is made in the run: a replay returns what the run returned, and the mark
|
|
1314
|
+
// is in the journal with the session it names.
|
|
1315
|
+
const mark = randomUUID();
|
|
1316
|
+
const context = { run, execution, parentSession, disabledTools: [...visible.disabledTools], boxAccess: { only: launch.plan.request.items.map(({ item }) => item) }, tools: run === undefined && parent === undefined ? input.tools : tools };
|
|
1317
|
+
// A harness at its ceiling takes the start once one of its turns ends.
|
|
1318
|
+
const slot = await caps.admit(instance.id);
|
|
1319
|
+
// Written before the harness is asked: from here on a retry never asks it again.
|
|
1320
|
+
let token: Token;
|
|
1321
|
+
let servers: readonly McpServerSpec[] | undefined;
|
|
1322
|
+
try {
|
|
1323
|
+
const current = grantOfSession(ctx.caller, requested, visible);
|
|
1324
|
+
if (stableJson(specsOf(current)) !== stableJson(specsOf(rules)) ||
|
|
1325
|
+
launch.plan.rules.some((needed) => heldRule(api.rights(ctx.caller), needed) === undefined) ||
|
|
1326
|
+
(parent?.run !== undefined && parentSession !== undefined && ended(parentSession))) {
|
|
1327
|
+
throw new SessionRefusal("grant-changed", "the parent grant changed while the session was starting");
|
|
1328
|
+
}
|
|
1329
|
+
token = tokenFor(mark, current, ctx.caller);
|
|
1330
|
+
servers = serversOf(visible.actions, mark, token);
|
|
1331
|
+
} catch (error) {
|
|
1332
|
+
slot.release();
|
|
1333
|
+
rmSync(launch.temp, { recursive: true, force: true });
|
|
1334
|
+
throw error;
|
|
1335
|
+
}
|
|
1336
|
+
await ctx.emit(SessionStartReserved, { operation, digest, mark, ...context, ...(cwd === undefined ? {} : { cwd }) }).catch((error: unknown) => {
|
|
1337
|
+
slot.release();
|
|
1338
|
+
throw error;
|
|
1339
|
+
});
|
|
1340
|
+
const asking = recording(mark, instance.id, launch, ctx, () =>
|
|
1341
|
+
control.start({
|
|
1342
|
+
prompt: input.prompt,
|
|
1343
|
+
model: input.model,
|
|
1344
|
+
effort: input.effort,
|
|
1345
|
+
mode: input.mode,
|
|
1346
|
+
cwd,
|
|
1347
|
+
...(Object.keys(blocks).length === 0 ? {} : { blocks }),
|
|
1348
|
+
visible,
|
|
1349
|
+
servers,
|
|
1350
|
+
env: { [TOKEN_ENV]: token, ...launchEnv(launch) },
|
|
1351
|
+
reverse: reverse.handlerFor(rules, run === undefined ? starterOf(ctx.caller) : owner, ownToolPrefix(visible.actions)),
|
|
1352
|
+
...launchOptions(launch, mark),
|
|
1353
|
+
...(tools === undefined ? {} : { tools }),
|
|
1354
|
+
named: async (named) => {
|
|
1355
|
+
await ctx.emit(SessionStartNamed, { operation, session: sessionRef(named) });
|
|
1356
|
+
},
|
|
1357
|
+
}),
|
|
1358
|
+
);
|
|
1359
|
+
const { session: id, first, mode } = await asking.catch(async (error: unknown) => {
|
|
1360
|
+
slot.release();
|
|
1361
|
+
// Nothing reached the harness: the reservation is let go, and a retry asks again.
|
|
1362
|
+
if (!effectPossibleAfter(error)) {
|
|
1363
|
+
await ctx.emit(SessionStartUnsent, { operation, reason: error instanceof Error ? error.message : String(error) });
|
|
1364
|
+
}
|
|
1365
|
+
throw error;
|
|
1366
|
+
});
|
|
1367
|
+
slot.reached(sessionRef(id), first);
|
|
1368
|
+
// The harness named the session: only now is there a session at all. Its first turn
|
|
1369
|
+
// may be running already; the side keeps the signs of that turn for the first stream
|
|
1370
|
+
// of life, and that stream is the one followed here, so none of them is lost.
|
|
1371
|
+
const ref = sessionRef(id);
|
|
1372
|
+
const issued = sessionIds.issue(ctx.operationId);
|
|
1373
|
+
await ctx.emit(SessionStarted, {
|
|
1374
|
+
session: ref,
|
|
1375
|
+
id: issued,
|
|
1376
|
+
...context,
|
|
1377
|
+
cwd,
|
|
1378
|
+
effort: input.effort,
|
|
1379
|
+
mode: mode ?? input.mode,
|
|
1380
|
+
options: Object.keys(blocks).length === 0 ? undefined : blocks,
|
|
1381
|
+
...(input.box === undefined ? {} : { box: input.box }),
|
|
1382
|
+
...(input.stuckAfter === undefined ? {} : { stuckAfter: input.stuckAfter }),
|
|
1383
|
+
});
|
|
1384
|
+
await ctx.emit(SessionMarked, { session: ref, mark });
|
|
1385
|
+
// The session has a name only now, so the input of its prompt is written once the harness took it; a start
|
|
1386
|
+
// without a prompt is written too, so a retry of it finds the session it made.
|
|
1387
|
+
await ctx.emit(SessionInputSending, { session: ref, operation, digest });
|
|
1388
|
+
if (first !== undefined) await ctx.emit(SessionInputSettled, { session: ref, operation, outcome: { status: "accepted", receipt: first } });
|
|
1389
|
+
follow(control, ref, id);
|
|
1390
|
+
return {
|
|
1391
|
+
session: issued,
|
|
1392
|
+
ref,
|
|
1393
|
+
...(first === undefined ? {} : { receipt: first }),
|
|
1394
|
+
...(worktree === undefined ? {} : { worktree: { id: worktree.id, path: worktree.path, branch: worktree.branch } }),
|
|
1395
|
+
operation,
|
|
1396
|
+
};
|
|
1397
|
+
};
|
|
1398
|
+
|
|
1399
|
+
api.action(
|
|
1400
|
+
action(sessionResume, {
|
|
1401
|
+
// The harness takes the session on again: a resume that was cut off may have
|
|
1402
|
+
// happened, so it is not made again.
|
|
1403
|
+
recovery: "do-not-repeat",
|
|
1404
|
+
effect: "write",
|
|
1405
|
+
world: "local",
|
|
1406
|
+
run: async (input, ctx) => {
|
|
1407
|
+
const { ref, id, control } = controlOf(input.session, "resume", ctx.caller);
|
|
1408
|
+
const prompt = input.prompt;
|
|
1409
|
+
// A resume with a prompt begins a turn: a harness at its ceiling takes it once one of its turns ends.
|
|
1410
|
+
// The slot is taken before anything is decided of the session, which may change while it waits.
|
|
1411
|
+
// A resume without a prompt takes the session on and runs nothing, so it waits for nothing.
|
|
1412
|
+
const slot = prompt === undefined ? undefined : await caps.admit(id.harness, ref);
|
|
1413
|
+
try {
|
|
1414
|
+
// A resume that is given no `visible` takes the grant the session was last launched
|
|
1415
|
+
// with: the session is the same, and so are its tools, its box and its rights.
|
|
1416
|
+
const restored = lastLaunchOf(ref);
|
|
1417
|
+
const owned = startedOf(ref);
|
|
1418
|
+
if (owned?.run !== undefined && (ended(ref) || restored === undefined || sessionGrantClosed(restored.mark))) {
|
|
1419
|
+
throw new SessionRefusal("ended-session", "the run-owned session no longer has a live grant");
|
|
1420
|
+
}
|
|
1421
|
+
const issuer = owned?.run === undefined ? ctx.caller : restored?.parent ?? callerOf(principalOf("run", owned.run));
|
|
1422
|
+
const requested = input.visible === undefined ? restored?.request : {
|
|
1423
|
+
...input.visible, disabledTools: [...new Set([...(owned?.disabledTools ?? []), ...(input.visible.disabledTools ?? [])])],
|
|
1424
|
+
};
|
|
1425
|
+
const visible = visibleFor(id.harness, callsOf(requested));
|
|
1426
|
+
let rules = grantOfSession(issuer, requested, visible);
|
|
1427
|
+
if (owned?.run !== undefined && restored !== undefined) {
|
|
1428
|
+
const kept = narrow(restored.rules, specsOf(rules), { irreversible: (name) => api.effectOf(name) === "irreversible" });
|
|
1429
|
+
if ("refused" in kept) throw new SessionRefusal("wider-than-session", "a resumed session cannot widen its grant");
|
|
1430
|
+
rules = kept.rules;
|
|
1431
|
+
}
|
|
1432
|
+
// A process that is still running keeps what it was born with: only a process that is
|
|
1433
|
+
// gone is launched again, and only then are its tools, box and servers asked for.
|
|
1434
|
+
const gone = (await control.state(id)) === "unknown";
|
|
1435
|
+
const launches = input.visible !== undefined || gone;
|
|
1436
|
+
// A process that is launched again counts its turns from 1: the records go on from the last.
|
|
1437
|
+
if (gone) restart(ref);
|
|
1438
|
+
// The directory the session was started in: a harness that loads a session by it needs the same one.
|
|
1439
|
+
const startedIn = restored?.cwd ?? startedOf(ref)?.cwd;
|
|
1440
|
+
const launch = launches ? await launchFor(rules, startedIn, id.harness, owned?.run === undefined ? owned?.box : owned.boxAccess, issuer, owned?.run === undefined ? undefined : owned.boxAccess) : undefined;
|
|
1441
|
+
// A process launched again keeps the tools the session was started with, within its grant.
|
|
1442
|
+
const tools = launch === undefined ? undefined : toolsOfSession(startedOf(ref)?.tools, launch.tools);
|
|
1443
|
+
// Relaunch the same run-owned principal, including its current grant
|
|
1444
|
+
// and children. A second identity could outlive a later narrowing.
|
|
1445
|
+
const mark = owned?.run !== undefined && restored !== undefined ? restored.mark : randomUUID();
|
|
1446
|
+
if (owned?.run !== undefined && restored !== undefined) {
|
|
1447
|
+
const current = api.rights(callerOf(principalOf("session", mark)));
|
|
1448
|
+
if (sessionGrantClosed(mark) || current === "unlimited" || stableJson(specsOf(current)) !== stableJson(specsOf(restored.rules))) {
|
|
1449
|
+
throw new SessionRefusal("grant-changed", "the session grant changed while it was resuming");
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
const token = tokenFor(mark, rules, issuer);
|
|
1453
|
+
const servers = launches ? serversOf(visible.actions, mark, token) : undefined;
|
|
1454
|
+
// The session is named already: the pairing is written before the harness takes it
|
|
1455
|
+
// on, so the server it is given finds the session from its first list of tools.
|
|
1456
|
+
await ctx.emit(SessionMarked, { session: ref, mark });
|
|
1457
|
+
const started = startedOf(ref);
|
|
1458
|
+
const mode = started?.mode;
|
|
1459
|
+
// The session starts again with the model the harness named for it, not the alias it was asked for.
|
|
1460
|
+
const model = modelOf(ref);
|
|
1461
|
+
await recording(mark, id.harness, launch, ctx, () =>
|
|
1462
|
+
control.resume(id, {
|
|
1463
|
+
...(mode === undefined ? {} : { mode }),
|
|
1464
|
+
...(model === undefined ? {} : { model }),
|
|
1465
|
+
...blocksOfSession(started),
|
|
1466
|
+
...(prompt === undefined ? {} : { prompt }),
|
|
1467
|
+
...(launches && startedIn !== undefined ? { cwd: startedIn } : {}),
|
|
1468
|
+
...(launches && requested !== undefined ? { visible } : {}),
|
|
1469
|
+
...(servers === undefined ? {} : { servers }),
|
|
1470
|
+
env: { [TOKEN_ENV]: token, ...launchEnv(launch) },
|
|
1471
|
+
reverse: reverse.handlerFor(rules, owned?.run === undefined ? starterOf(ctx.caller) : owner, ownToolPrefix(visible.actions)),
|
|
1472
|
+
...launchOptions(launch, mark),
|
|
1473
|
+
...(tools === undefined ? {} : { tools }),
|
|
1474
|
+
}),
|
|
1475
|
+
);
|
|
1476
|
+
slot?.reached(ref, { status: "started" });
|
|
1477
|
+
follow(control, ref, id);
|
|
1478
|
+
return { resumed: true };
|
|
1479
|
+
} catch (error) {
|
|
1480
|
+
slot?.release();
|
|
1481
|
+
throw error;
|
|
1482
|
+
}
|
|
1483
|
+
},
|
|
1484
|
+
}),
|
|
1485
|
+
);
|
|
1486
|
+
|
|
1487
|
+
api.action(
|
|
1488
|
+
action(sessionSend, {
|
|
1489
|
+
// The message is delivered into the session: a send that was cut off may have
|
|
1490
|
+
// been delivered, so it is not made again.
|
|
1491
|
+
recovery: "do-not-repeat",
|
|
1492
|
+
effect: "write",
|
|
1493
|
+
world: "local",
|
|
1494
|
+
run: async (input, ctx) => {
|
|
1495
|
+
const { ref, id, control } = controlOf(input.session, "send", ctx.caller);
|
|
1496
|
+
// The slot of the harness is taken before anything is written of the send, so a send that waits
|
|
1497
|
+
// for one is not taken for possibly sent if the host stops while it waits.
|
|
1498
|
+
const sending = async (slot: Slot): Promise<DeliveryReceipt> => {
|
|
1499
|
+
try {
|
|
1500
|
+
const receipt = await control.send(id, input.message, input.into === undefined ? undefined : { into: input.into });
|
|
1501
|
+
slot.reached(ref, receipt);
|
|
1502
|
+
return receipt;
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
slot.release();
|
|
1505
|
+
throw error;
|
|
1506
|
+
}
|
|
1507
|
+
};
|
|
1508
|
+
// The turn is named as the records name it, not as the harness counts it in this process.
|
|
1509
|
+
const named = (receipt: DeliveryReceipt) => (receipt.turn === undefined ? receipt : { ...receipt, turn: numbered(ref, receipt.turn) });
|
|
1510
|
+
// A harness at its ceiling takes the message once one of its turns ends.
|
|
1511
|
+
if (input.operation === undefined) return { receipt: named(await sending(await caps.admit(id.harness, ref))) };
|
|
1512
|
+
|
|
1513
|
+
const operation = input.operation;
|
|
1514
|
+
const digest = createHash("sha256").update(JSON.stringify([input.message, input.into ?? null])).digest("hex");
|
|
1515
|
+
const before = inputOf(ref, operation);
|
|
1516
|
+
if (before !== undefined) {
|
|
1517
|
+
if (before.digest !== digest) {
|
|
1518
|
+
throw new SessionRefusal("operation-conflict", `operation "${operation}" was a send of another message into this session`);
|
|
1519
|
+
}
|
|
1520
|
+
// What became of it is answered from the records; only a message that never went is sent again.
|
|
1521
|
+
if (before.outcome?.status === "accepted") return { receipt: before.outcome.receipt };
|
|
1522
|
+
if (before.outcome?.status !== "unsent") {
|
|
1523
|
+
throw new InputPossiblySent(id.harness, "send", before.outcome?.reason ?? "the send was cut off before its outcome was known");
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
const slot = await caps.admit(id.harness, ref);
|
|
1527
|
+
await ctx.emit(SessionInputSending, { session: ref, operation, digest }).catch((error: unknown) => {
|
|
1528
|
+
slot.release();
|
|
1529
|
+
throw error;
|
|
1530
|
+
});
|
|
1531
|
+
const outcome = await outcomeOf(sending(slot).then(named));
|
|
1532
|
+
await ctx.emit(SessionInputSettled, { session: ref, operation, outcome });
|
|
1533
|
+
switch (outcome.status) {
|
|
1534
|
+
case "accepted":
|
|
1535
|
+
return { receipt: outcome.receipt };
|
|
1536
|
+
case "unsent":
|
|
1537
|
+
throw new InputNotSent(id.harness, "send", outcome.reason);
|
|
1538
|
+
case "possibly-sent":
|
|
1539
|
+
throw new InputPossiblySent(id.harness, "send", outcome.reason);
|
|
1540
|
+
}
|
|
1541
|
+
},
|
|
1542
|
+
}),
|
|
1543
|
+
);
|
|
1544
|
+
|
|
1545
|
+
api.action(
|
|
1546
|
+
action(sessionInterrupt, {
|
|
1547
|
+
// The turn is interrupted once: an interrupt that was cut off may have happened,
|
|
1548
|
+
// so it is not made again.
|
|
1549
|
+
recovery: "do-not-repeat",
|
|
1550
|
+
effect: "write",
|
|
1551
|
+
world: "local",
|
|
1552
|
+
run: async (input, ctx) => {
|
|
1553
|
+
// Refused before anything is attempted: niwa does not emulate an interrupt.
|
|
1554
|
+
const { ref, id, control } = controlOf(input.session, "interrupt", ctx.caller);
|
|
1555
|
+
interrupting.add(ref);
|
|
1556
|
+
try {
|
|
1557
|
+
await control.interrupt(id);
|
|
1558
|
+
} catch (error) {
|
|
1559
|
+
interrupting.delete(ref);
|
|
1560
|
+
throw error;
|
|
1561
|
+
}
|
|
1562
|
+
return { interrupted: true };
|
|
1563
|
+
},
|
|
1564
|
+
}),
|
|
1565
|
+
);
|
|
1566
|
+
|
|
1567
|
+
api.action(
|
|
1568
|
+
action(sessionEnd, {
|
|
1569
|
+
// Ending a session that ended already leaves it as it is: it may be made again.
|
|
1570
|
+
recovery: "repeat",
|
|
1571
|
+
effect: "write",
|
|
1572
|
+
world: "local",
|
|
1573
|
+
run: async (input, ctx) => {
|
|
1574
|
+
const ref = refOf(input.session);
|
|
1575
|
+
authorizeControl(ref, ctx.caller);
|
|
1576
|
+
const pending = closing.get(ref);
|
|
1577
|
+
if (pending !== undefined) {
|
|
1578
|
+
await pending;
|
|
1579
|
+
return { ended: false };
|
|
1580
|
+
}
|
|
1581
|
+
if (ended(ref)) return { ended: false };
|
|
1582
|
+
const close = async () => {
|
|
1583
|
+
const id = sessionOf(ref);
|
|
1584
|
+
const control = bindings.find((binding) => binding.instance.id === id.harness)?.control;
|
|
1585
|
+
ending.add(ref);
|
|
1586
|
+
try {
|
|
1587
|
+
if (control !== undefined && instanceOf(bindings, id.harness).sides.control?.interrupt === true &&
|
|
1588
|
+
await control.state(id).catch(() => "unknown") === "running") {
|
|
1589
|
+
interrupting.add(ref);
|
|
1590
|
+
await control.interrupt(id).catch(() => interrupting.delete(ref));
|
|
1591
|
+
}
|
|
1592
|
+
await control?.close?.(id);
|
|
1593
|
+
await ctx.emit(SessionEnded, { session: ref, reason: input.reason });
|
|
1594
|
+
} finally {
|
|
1595
|
+
closing.delete(ref);
|
|
1596
|
+
if (!ended(ref)) ending.delete(ref);
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
const done = close();
|
|
1600
|
+
closing.set(ref, done);
|
|
1601
|
+
await done;
|
|
1602
|
+
return { ended: true };
|
|
1603
|
+
},
|
|
1604
|
+
}),
|
|
1605
|
+
);
|
|
1606
|
+
|
|
1607
|
+
api.action(
|
|
1608
|
+
action(sessionOpenQuestions, {
|
|
1609
|
+
// A read of what waits changes nothing: it may be made again.
|
|
1610
|
+
recovery: "repeat",
|
|
1611
|
+
effect: "read",
|
|
1612
|
+
world: "niwa",
|
|
1613
|
+
run: async (input, ctx) => {
|
|
1614
|
+
const journal = api.journal?.();
|
|
1615
|
+
if (journal === undefined) return { questions: [] };
|
|
1616
|
+
const principal = ctx.caller.kind === "client" ? ctx.caller.principal : undefined;
|
|
1617
|
+
if (principal?.kind === "session" && principal.id !== input.mark) throw new SessionRefusal("foreign-mark", "the mark belongs to another session");
|
|
1618
|
+
const session = sessionOfMark(input.mark);
|
|
1619
|
+
if (session === undefined) return { questions: [] };
|
|
1620
|
+
// The questions are the requests module's open requests addressed to the session, as
|
|
1621
|
+
// a non-native ask addresses them.
|
|
1622
|
+
const id = sessionOf(session);
|
|
1623
|
+
const { requests: open } = await ctx.step(requestOpen, {
|
|
1624
|
+
to: { kind: "session", harness: id.harness, id: id.native },
|
|
1625
|
+
});
|
|
1626
|
+
const questions: { request: string; schema: JsonSchemaValue }[] = [];
|
|
1627
|
+
for (const entry of open) {
|
|
1628
|
+
if ("kind" in entry) continue;
|
|
1629
|
+
questions.push({ request: entry.id, schema: valueSchemaOf(entry.input) });
|
|
1630
|
+
}
|
|
1631
|
+
return { questions };
|
|
1632
|
+
},
|
|
1633
|
+
}),
|
|
1634
|
+
);
|
|
1635
|
+
|
|
1636
|
+
api.action(
|
|
1637
|
+
action(sessionAsk, {
|
|
1638
|
+
// The session is asked: an ask that was cut off may have reached the harness, so
|
|
1639
|
+
// it is not made again.
|
|
1640
|
+
recovery: "do-not-repeat",
|
|
1641
|
+
effect: "write",
|
|
1642
|
+
world: "local",
|
|
1643
|
+
run: async (input, ctx) => {
|
|
1644
|
+
const { ref, id, control } = controlOf(input.session, "ask", ctx.caller);
|
|
1645
|
+
const schema = z.fromJSONSchema(input.schema);
|
|
1646
|
+
const prompt = input.prompt;
|
|
1647
|
+
if (supports(instanceOf(bindings, id.harness), "control", "structuredOutput")) {
|
|
1648
|
+
// The answer is a turn of the session: a harness at its ceiling takes it once one of its turns ends.
|
|
1649
|
+
const slot = await caps.admit(id.harness, ref);
|
|
1650
|
+
const answer = await control.ask(id, { schema, prompt, ...blocksOfSession(startedOf(ref)) }).finally(() => slot.release());
|
|
1651
|
+
// The harness said the answer is structured; niwa checks it all the same.
|
|
1652
|
+
const parsed = schema.safeParse(answer.value);
|
|
1653
|
+
if (!parsed.success) {
|
|
1654
|
+
throw new ValidationError(`the answer of the session "${ref}" does not pass its schema`, parsed.error.issues);
|
|
1655
|
+
}
|
|
1656
|
+
return { value: parsed.data };
|
|
1657
|
+
}
|
|
1658
|
+
// The harness cannot answer natively: the question niwa asks of the session is a
|
|
1659
|
+
// request, and the answer comes back through `submit-answer`. The request waits, and
|
|
1660
|
+
// the wait survives a restart.
|
|
1661
|
+
const value = await askNonNative(ctx, {
|
|
1662
|
+
to: { kind: "session", harness: id.harness, id: id.native },
|
|
1663
|
+
prompt,
|
|
1664
|
+
schema,
|
|
1665
|
+
});
|
|
1666
|
+
return { value };
|
|
1667
|
+
},
|
|
1668
|
+
}),
|
|
1669
|
+
);
|
|
1670
|
+
});
|
|
1671
|
+
|
|
1672
|
+
return Object.assign(made, { bind });
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/** The sessions plugin: a plugin that also says what address a session's own client speaks as. */
|
|
1676
|
+
export type SessionsPlugin = Plugin & { bind(fallback?: CallerBinding): CallerBinding };
|
|
1677
|
+
|
|
1678
|
+
/** What the sandbox reports of a box, as the funnel hears it before the process starts. */
|
|
1679
|
+
type SandboxManifestOf = Parameters<Parameters<typeof onBoxManifest>[0]>[0]["manifest"];
|
|
1680
|
+
|
|
1681
|
+
/** What a start or a resume launches with: its tools, and its box with the plan it was resolved from. */
|
|
1682
|
+
interface Launch {
|
|
1683
|
+
readonly tools?: ToolAllowance;
|
|
1684
|
+
readonly box: BoxRequest;
|
|
1685
|
+
readonly plan: BoxPlan;
|
|
1686
|
+
/** The rules of the caller's grant the box took. */
|
|
1687
|
+
readonly rules: readonly string[];
|
|
1688
|
+
/** The box's own temp directory: `TMPDIR` of the process. */
|
|
1689
|
+
readonly temp: string;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/** What a request asks for besides the niwa actions: its `tool:` rules are for the launch. */
|
|
1693
|
+
function callsOf(input: VisibleActionsInput | undefined): VisibleActionsInput | undefined {
|
|
1694
|
+
if (input?.actions === undefined) return input;
|
|
1695
|
+
return { ...input, actions: input.actions.filter((spec) => rule(spec).verb === "call" && !isLaunchRule(spec)) };
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/** The installations the plugin may read from and start sessions on, with their sides. */
|
|
1699
|
+
function resolveBindings(options: SessionsOptions): HarnessBinding[] {
|
|
1700
|
+
const { harnesses } = options;
|
|
1701
|
+
if (harnesses instanceof HarnessInstanceRegistry) return harnesses.bindings();
|
|
1702
|
+
const bindings = [...(harnesses ?? [])];
|
|
1703
|
+
const seen = new Set<string>();
|
|
1704
|
+
for (const { instance } of bindings) {
|
|
1705
|
+
// Two bindings under one id would be one installation with two sets of sides.
|
|
1706
|
+
if (seen.has(instance.id)) throw new Error(`harness instance "${instance.id}" is bound twice`);
|
|
1707
|
+
seen.add(instance.id);
|
|
1708
|
+
}
|
|
1709
|
+
return bindings;
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
/** The options block a session was started with, as a control side is given it again. */
|
|
1713
|
+
function blocksOfSession(started: { readonly options?: OptionBlocks } | undefined): { blocks?: OptionBlocks } {
|
|
1714
|
+
return started?.options === undefined ? {} : { blocks: started.options };
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
/** The options block the kind of a harness takes, when it declares one. */
|
|
1718
|
+
function optionsOf(bindings: readonly HarnessBinding[], harness: string): KindOptions | undefined {
|
|
1719
|
+
return bindings.find((binding) => binding.instance.id === harness)?.options;
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
/** An ability of the control side, as an installation declares it. */
|
|
1723
|
+
type ControlAbility = "start" | "resume" | "send" | "interrupt" | "ask";
|
|
1724
|
+
|
|
1725
|
+
/** The installation of a harness, as the bindings know it. */
|
|
1726
|
+
function instanceOf(bindings: readonly HarnessBinding[], harness: string): Harness {
|
|
1727
|
+
const found = bindings.find((binding) => binding.instance.id === harness);
|
|
1728
|
+
if (found === undefined) throw new Error(`harness "${harness}" is not known`);
|
|
1729
|
+
return found.instance;
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
/**
|
|
1733
|
+
* The control side of a harness, once the installation has declared the ability.
|
|
1734
|
+
*
|
|
1735
|
+
* An undeclared ability is refused by name before anything is attempted. A declared one with no
|
|
1736
|
+
* code behind it is a wiring mistake, and is said as such.
|
|
1737
|
+
*/
|
|
1738
|
+
function controlFor(bindings: readonly HarnessBinding[], harness: string, ability: ControlAbility): SessionControl {
|
|
1739
|
+
const instance = instanceOf(bindings, harness);
|
|
1740
|
+
requireAbility(instance, "control", ability);
|
|
1741
|
+
const control = bindings.find((binding) => binding.instance.id === harness)?.control;
|
|
1742
|
+
if (control === undefined) throw new Error(`harness "${harness}" declares a control side but none is bound`);
|
|
1743
|
+
return control;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
/**
|
|
1747
|
+
* The sessions the reading sides list, and the harnesses that could not be asked.
|
|
1748
|
+
*
|
|
1749
|
+
* A side without a reading side, or without the ability to list, is not asked and not blamed.
|
|
1750
|
+
* A side that fails is reported: the list is what is known, not proof that there is nothing more.
|
|
1751
|
+
*/
|
|
1752
|
+
/**
|
|
1753
|
+
* Make the worktree a session runs in, through the git module's action: the repository is the one
|
|
1754
|
+
* asked for, else the session's cwd, else the host's directory; the description is the one asked
|
|
1755
|
+
* for, else the harness's.
|
|
1756
|
+
*/
|
|
1757
|
+
async function worktreeFor(ctx: ActionContext, harness: string, option: WorktreeOption, cwd: string | undefined): Promise<Worktree> {
|
|
1758
|
+
const asked = option === true ? {} : option;
|
|
1759
|
+
return ctx.step(gitWorktreeCreate, {
|
|
1760
|
+
repo: asked.repo ?? cwd ?? process.cwd(),
|
|
1761
|
+
...(asked.base === undefined ? {} : { base: asked.base }),
|
|
1762
|
+
description: asked.description ?? EntityDescription.parse(`a session of ${harness}`.slice(0, DESCRIPTION_MAX)),
|
|
1763
|
+
}, ctx.caller.kind === "client" && ctx.caller.principal !== undefined ? { as: ctx.caller.principal } : {});
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
async function listFromSides(
|
|
1767
|
+
bindings: readonly HarnessBinding[],
|
|
1768
|
+
harness: string | undefined,
|
|
1769
|
+
cwd: string | undefined,
|
|
1770
|
+
): Promise<{ listed: SessionInfo[]; unreadable: { harness: string; reason: string }[] }> {
|
|
1771
|
+
const listed: SessionInfo[] = [];
|
|
1772
|
+
const unreadable: { harness: string; reason: string }[] = [];
|
|
1773
|
+
for (const binding of bindings) {
|
|
1774
|
+
if (harness !== undefined && binding.instance.id !== harness) continue;
|
|
1775
|
+
if (binding.reading === undefined || !supports(binding.instance, "reading", "list")) continue;
|
|
1776
|
+
try {
|
|
1777
|
+
for await (const info of binding.reading.list(cwd === undefined ? undefined : { cwd })) listed.push(info);
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
unreadable.push({
|
|
1780
|
+
harness: binding.instance.id,
|
|
1781
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
return { listed, unreadable };
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
export { SessionCatalog } from "./catalog.ts";
|
|
1789
|
+
export { SessionRefusal } from "./refusal.ts";
|
|
1790
|
+
export { REVERSE_QUESTION, REVERSE_TYPES, ReverseIdSchema, SessionReverseAnswered, SessionReverseAsked, SessionReverseCancelled } from "./reverse.ts";
|
|
1791
|
+
export type { ReverseId } from "./reverse.ts";
|
|
1792
|
+
export { heldRule, isLaunchRule, toolsOfGrant } from "./box.ts";
|
|
1793
|
+
export type { Belonging, SessionEntry } from "./catalog.ts";
|
|
1794
|
+
export { NiwaSessionIdSchema, SessionRefSchema, sessionOf, sessionRef } from "./identity.ts";
|
|
1795
|
+
export type { NiwaSessionId, SessionRef } from "./identity.ts";
|
|
1796
|
+
export { lifeOf } from "./life.ts";
|
|
1797
|
+
export type { LifeState } from "./life.ts";
|
|
1798
|
+
export {
|
|
1799
|
+
SESSION_TYPES,
|
|
1800
|
+
BelongingSource,
|
|
1801
|
+
SessionCompacted,
|
|
1802
|
+
SessionActivity,
|
|
1803
|
+
SessionAdvisor,
|
|
1804
|
+
SessionBelongs,
|
|
1805
|
+
SessionBoxManifest,
|
|
1806
|
+
SessionEnded,
|
|
1807
|
+
SessionMarked,
|
|
1808
|
+
SessionModel,
|
|
1809
|
+
SessionStarted,
|
|
1810
|
+
SessionTurnEnded,
|
|
1811
|
+
SessionTurnStarted,
|
|
1812
|
+
SessionUnknownVariant,
|
|
1813
|
+
sameAddress,
|
|
1814
|
+
SESSION_SEND,
|
|
1815
|
+
DeliveryReceiptSchema,
|
|
1816
|
+
} from "./records.ts";
|
|
1817
|
+
export type { DeliveryReceipt, SessionSendInput, SessionSendOutput } from "./records.ts";
|
|
1818
|
+
export {
|
|
1819
|
+
SESSION_QUESTION,
|
|
1820
|
+
SUBMIT_ANSWER_ACTION,
|
|
1821
|
+
askNonNative,
|
|
1822
|
+
questionText,
|
|
1823
|
+
submitAnswerAction,
|
|
1824
|
+
} from "./ask.ts";
|
|
1825
|
+
export { PromptInputSchema, promptFrom } from "./prompt.ts";
|
|
1826
|
+
export { VisibleActionsInputSchema, visibleActionsOf } from "./visible.ts";
|
|
1827
|
+
export {
|
|
1828
|
+
sessionAsk,
|
|
1829
|
+
sessionBelong,
|
|
1830
|
+
sessionGet,
|
|
1831
|
+
sessionEnd,
|
|
1832
|
+
sessionInterrupt,
|
|
1833
|
+
sessionList,
|
|
1834
|
+
sessionOpenQuestions,
|
|
1835
|
+
sessionRead,
|
|
1836
|
+
sessionResume,
|
|
1837
|
+
harnessGet,
|
|
1838
|
+
harnessList,
|
|
1839
|
+
sessionRunning,
|
|
1840
|
+
sessionSearch,
|
|
1841
|
+
sessionSend,
|
|
1842
|
+
sessionStart,
|
|
1843
|
+
} from "./actions.ts";
|
|
1844
|
+
|
|
1845
|
+
export {
|
|
1846
|
+
HARNESS_DISCOVER_ACTION,
|
|
1847
|
+
HarnessDiscoverOutputSchema,
|
|
1848
|
+
HarnessProposed,
|
|
1849
|
+
harnessDiscover,
|
|
1850
|
+
harnessDiscovery,
|
|
1851
|
+
proposalIdOf,
|
|
1852
|
+
} from "./discover.ts";
|
|
1853
|
+
export type { HarnessDiscoveryOptions, HarnessDiscoverOutput } from "./discover.ts";
|
|
1854
|
+
export {
|
|
1855
|
+
HARNESS_CONFIRM_QUESTION,
|
|
1856
|
+
HarnessConfirmAnswerSchema,
|
|
1857
|
+
HarnessConfirmed,
|
|
1858
|
+
harnessConfirm,
|
|
1859
|
+
} from "./confirm.ts";
|
|
1860
|
+
export type { HarnessConfirmAnswer, HarnessConfirmOptions } from "./confirm.ts";
|
|
1861
|
+
export { harnessSupport, harnessSupports } from "./support.ts";
|
|
1862
|
+
export {
|
|
1863
|
+
Compacted,
|
|
1864
|
+
InsertReportOutputSchema,
|
|
1865
|
+
NestedSpawned,
|
|
1866
|
+
OpenedByHand,
|
|
1867
|
+
PERMISSION_QUESTION,
|
|
1868
|
+
PermissionAsked,
|
|
1869
|
+
SessionEndedByHarness,
|
|
1870
|
+
insertPlugin,
|
|
1871
|
+
} from "./insert-plugin.ts";
|
|
1872
|
+
export type { InsertPluginOptions, InsertReportOutput } from "./insert-plugin.ts";
|
|
1873
|
+
export { PermissionIdSchema, PermissionRouter, permissionId } from "./insert-routing.ts";
|
|
1874
|
+
export type { PermissionId } from "./insert-routing.ts";
|