@niwa-labs/harness 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/control.ts ADDED
@@ -0,0 +1,448 @@
1
+ /**
2
+ * The control side: how niwa starts, steers and stops the sessions of a harness
3
+ *. It owns the processes it starts and their termination.
4
+ */
5
+
6
+ import { z } from "zod";
7
+
8
+ import type { Timestamp } from "@niwa-labs/core";
9
+
10
+ import type { SessionMode } from "./capabilities.ts";
11
+ import type { BoxRequest } from "@niwa-labs/sandbox";
12
+ import type { OptionBlocks } from "./options.ts";
13
+ import type { SessionId } from "./reading.ts";
14
+ import type { ReverseHandler } from "./reverse.ts";
15
+
16
+ /** How often a prompt section changes, so plugins can contribute without breaking each other's cache. */
17
+ export const PromptTierSchema = z.enum(["constant", "stable", "volatile"]);
18
+ export type PromptTier = z.output<typeof PromptTierSchema>;
19
+
20
+ export const PromptSectionSchema = z.object({
21
+ id: z.string().min(1),
22
+ tier: PromptTierSchema,
23
+ text: z.string(),
24
+ });
25
+ export type PromptSection = z.output<typeof PromptSectionSchema>;
26
+
27
+ /** A prompt is sections, in the order they are sent. */
28
+ export const PromptSchema = z.object({
29
+ sections: z.array(PromptSectionSchema),
30
+ });
31
+ export type Prompt = z.output<typeof PromptSchema>;
32
+
33
+ /** Plain text becomes one volatile section, before any intercept sees it. */
34
+ export function promptFromText(text: string): Prompt {
35
+ return { sections: [{ id: "prompt", tier: "volatile", text }] };
36
+ }
37
+
38
+ /**
39
+ * Which niwa actions a session sees and which harness tools are switched off. The tool names are
40
+ * the harness's own. A harness that cannot switch a tool off refuses the request with
41
+ * `Unsupported`: a tool left on silently would be a promise broken.
42
+ */
43
+ export interface VisibleActions {
44
+ readonly actions: readonly string[];
45
+ readonly disabledTools: readonly string[];
46
+ }
47
+
48
+ /** An allow-list of the harness's own tools: the names are the harness's own. */
49
+ export interface ToolAllowance {
50
+ readonly allow: readonly string[];
51
+ }
52
+
53
+ /**
54
+ * The tools a session may use, for its whole life:
55
+ *
56
+ * - `all`: the harness's own tools, as the harness has them;
57
+ * - `niwa-only`: none of the harness's own tools, only those of the MCP servers niwa gives it;
58
+ * - `{ allow }`: exactly the harness's own tools named, and those of the servers niwa gives it.
59
+ *
60
+ * A kind that cannot hold a session to the mode refuses it with `Unsupported` before the first
61
+ * prompt; a tool left on silently would be a promise broken.
62
+ */
63
+ export type ToolsMode = "all" | "niwa-only" | ToolAllowance;
64
+
65
+ export const ToolsModeSchema = z.union([
66
+ z.literal("all"),
67
+ z.literal("niwa-only"),
68
+ z.object({ allow: z.array(z.string().min(1)).readonly() }).strict(),
69
+ ]);
70
+
71
+ /** The mode said the way a refusal says it. */
72
+ export function describeToolsMode(mode: ToolsMode): string {
73
+ return typeof mode === "string" ? `tools ${mode}` : `tools allow [${mode.allow.join(", ")}]`;
74
+ }
75
+
76
+ export const NO_VISIBLE_ACTIONS: VisibleActions = { actions: [], disabledTools: [] };
77
+
78
+ /**
79
+ * One MCP server a session is given, as niwa says it.
80
+ *
81
+ * The spec is niwa's own: each harness kind maps it to the dialect that kind speaks, because the
82
+ * dialects differ (Claude Code's ACP names the servers of a session, mcode the servers of a
83
+ * handshake).
84
+ */
85
+ export interface McpServerSpec {
86
+ /** The name the session knows the server by. */
87
+ readonly name: string;
88
+ /** The program that starts the server. */
89
+ readonly command: string;
90
+ /** The arguments of the program, the first of which may carry the home. */
91
+ readonly args: readonly string[];
92
+ /** The environment the server is given. */
93
+ readonly env: Readonly<Record<string, string>>;
94
+ /**
95
+ * The exact MCP tool names available to the session, when niwa knows them without connecting.
96
+ * Its own server uses the tool names of the actions the session may see. A harness can use
97
+ * the list to restrict this server or to include its tools in a session-wide allow-list.
98
+ * Omit the list when the tools are unknown. An empty list names no tools.
99
+ */
100
+ readonly tools?: readonly string[];
101
+ }
102
+
103
+ /**
104
+ * What happened to a message sent into a session: `delivered` into the running turn, `queued`
105
+ * after the current turn, `started` a new turn, or `handled` by the harness itself with no turn
106
+ * (a command it answers on its own). A busy session queues by default.
107
+ */
108
+ export const DeliveryReceiptSchema = z.object({
109
+ status: z.enum(["delivered", "queued", "started", "handled"]),
110
+ turn: z.number().int().positive().optional(),
111
+ at: z.number().int().nonnegative().optional(),
112
+ });
113
+ export type DeliveryReceipt = z.output<typeof DeliveryReceiptSchema>;
114
+
115
+ /**
116
+ * What the harness says it decided about a tool call without asking: allow or deny, who decided
117
+ * (a classifier, a rule, the mode, a hook, the user). The words of `decidedBy`, `ruleKind` and `mode`
118
+ * are the harness's own and may grow, so they are kept as it says them. The harness's free-text
119
+ * reason is not part of it: a session record carries no free text, and the schema drops it.
120
+ */
121
+ export const PermissionMarkSchema = z.object({
122
+ decision: z.enum(["allow", "deny"]).optional(),
123
+ decidedBy: z.string().optional(),
124
+ /** The kind of the rule that decided, `null` when no rule did; a mark without the key (an older build) reads as `null`. */
125
+ ruleKind: z.string().nullable().default(null),
126
+ mode: z.string().optional(),
127
+ });
128
+ export type PermissionMark = z.output<typeof PermissionMarkSchema>;
129
+
130
+ /**
131
+ * The model a session really runs, as the harness names it: the answer the harness gave, never the
132
+ * alias or the request. It is what a resume pins the session to.
133
+ */
134
+ export const ModelNameSchema = z.string().min(1).brand<"ModelName">();
135
+ export type ModelName = z.output<typeof ModelNameSchema>;
136
+
137
+ /** The model a harness named; a name that is empty is no name. */
138
+ export function modelName(value: string): ModelName {
139
+ return ModelNameSchema.parse(value);
140
+ }
141
+
142
+ /** The name of a wire protocol, in the harness's own words: `codex app-server`. */
143
+ export const ProtocolNameSchema = z.string().min(1).brand<"ProtocolName">();
144
+ export type ProtocolName = z.output<typeof ProtocolNameSchema>;
145
+
146
+ /** The value of the discriminator of a message in a wire protocol (a method, a type): what a build of niwa knows or does not. */
147
+ export const VariantNameSchema = z.string().brand<"VariantName">();
148
+ export type VariantName = z.output<typeof VariantNameSchema>;
149
+
150
+ /**
151
+ * How a turn ended, as far as the harness knows: `completed` (its result says it finished), `failed`
152
+ * (the harness refused it or reported an error for it), `unknown` (the connection went, or the
153
+ * harness did not answer, so nobody knows what became of it). A harness that says none leaves it out.
154
+ */
155
+ export const TurnOutcomeSchema = z.enum(["completed", "failed", "unknown"]);
156
+ export type TurnOutcome = z.output<typeof TurnOutcomeSchema>;
157
+
158
+ /** A sign of life. */
159
+ export const LifeEventSchema = z.discriminatedUnion("kind", [
160
+ z.object({
161
+ kind: z.literal("turn-started"),
162
+ turn: z.number().int().positive(),
163
+ at: z.number().int().nonnegative().optional(),
164
+ }),
165
+ z.object({
166
+ kind: z.literal("turn-ended"),
167
+ turn: z.number().int().positive(),
168
+ at: z.number().int().nonnegative().optional(),
169
+ outcome: TurnOutcomeSchema.optional(),
170
+ }),
171
+ z.object({
172
+ kind: z.literal("activity"),
173
+ at: z.number().int().nonnegative(),
174
+ detail: z.string().optional(),
175
+ /** The name of the tool the activity is a call of, when the harness says it; the sessions record keeps it only as a short identifier. */
176
+ tool: z.string().optional(),
177
+ /** The decision on a tool call the harness made by itself, when it says so. */
178
+ permission: PermissionMarkSchema.optional(),
179
+ }),
180
+ /**
181
+ * Claude Code's advisor (a stronger model it asks for a review) was called, or answered. The
182
+ * answer is named by its kind, never by its text; the model is known only once it answered.
183
+ */
184
+ z.object({
185
+ kind: z.literal("advisor"),
186
+ at: z.number().int().nonnegative(),
187
+ phase: z.enum(["started", "finished"]),
188
+ callId: z.string().min(1),
189
+ model: z.string().optional(),
190
+ result: z.enum(["text", "redacted", "error"]).optional(),
191
+ errorCode: z.string().optional(),
192
+ }),
193
+ /**
194
+ * A message of the harness's protocol that niwa's snapshot of the protocol does not know (the
195
+ * harness got newer): the protocol, the value of its discriminator, and the message as it came.
196
+ */
197
+ z.object({
198
+ kind: z.literal("unknown-variant"),
199
+ at: z.number().int().nonnegative(),
200
+ /** The wire protocol the message came in. */
201
+ protocol: ProtocolNameSchema,
202
+ /** The value of the message's discriminator that this build of niwa does not know. */
203
+ variant: VariantNameSchema,
204
+ /** The message as it arrived. */
205
+ raw: z.json(),
206
+ }),
207
+ z.object({
208
+ /**
209
+ * The harness named the model the session runs. A harness says it as soon as it knows, which
210
+ * is after the start for the ones whose program names it with its first turn.
211
+ */
212
+ kind: z.literal("model"),
213
+ model: ModelNameSchema,
214
+ }),
215
+ ]);
216
+ export type LifeEvent = z.output<typeof LifeEventSchema>;
217
+
218
+ /**
219
+ * A message as JSON, by its JSON text: what a harness put together from its parts may hold
220
+ * `undefined` (no params), which JSON leaves out, and the message is not lost for it. A value that
221
+ * has no JSON text (a cycle) reads as `null`.
222
+ */
223
+ export function rawJson(value: unknown): Extract<LifeEvent, { kind: "unknown-variant" }>["raw"] {
224
+ try {
225
+ const text = JSON.stringify(value);
226
+ return text === undefined ? null : z.json().parse(JSON.parse(text));
227
+ } catch {
228
+ return null;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * The signs of life of a message that is not in niwa's snapshot of a protocol (the harness got
234
+ * newer): the typed unknown, which the sessions plugin writes once for each variant, and an activity.
235
+ * A session that keeps sending what niwa does not know is at work, and the unknown alone, written
236
+ * once, would not say so. `detail` is what the activity says; it is the variant when not given.
237
+ */
238
+ export function unknownVariantSigns(
239
+ at: number,
240
+ protocol: ProtocolName,
241
+ variant: VariantName,
242
+ raw: unknown,
243
+ detail: string = variant,
244
+ ): [LifeEvent, LifeEvent] {
245
+ return [
246
+ { kind: "unknown-variant", at, protocol, variant, raw: rawJson(raw) },
247
+ { kind: "activity", at, detail },
248
+ ];
249
+ }
250
+
251
+ /**
252
+ * After a restart a last "turn started" proves nothing about now, so `unknown` is a first-class
253
+ * answer, different from both `idle` and `running`.
254
+ */
255
+ export type SessionState = "running" | "idle" | "unknown";
256
+
257
+ /**
258
+ * What a question is asked with. The options blocks are the ones the session was started with: a
259
+ * control side that asks in a process of its own gives it what the session's own process was given.
260
+ */
261
+ export interface AskOptions<T> {
262
+ /** The options block of the session's kind it was started with, by name; a control side reads its own. */
263
+ readonly blocks?: OptionBlocks;
264
+ /** The schema the answer must pass. */
265
+ readonly schema: z.ZodType<T>;
266
+ readonly prompt: Prompt;
267
+ /**
268
+ * The id of the question, when the harness cannot answer natively.
269
+ *
270
+ * Then niwa gives the session the action to submit an answer, bound to this question, and the
271
+ * session calls it with this id. A harness that answers natively does not need it.
272
+ */
273
+ readonly question?: string;
274
+ }
275
+
276
+ export interface AskAnswer<T> {
277
+ readonly session: SessionId;
278
+ /** The value that passed the schema. */
279
+ readonly value: T;
280
+ readonly at: Timestamp;
281
+ }
282
+
283
+ /**
284
+ * Where a message goes into a session. By default a message to a busy session is queued after
285
+ * the current turn; `into: "turn"` asks for delivery into the running turn instead.
286
+ */
287
+ export interface SendOptions {
288
+ readonly into?: "turn";
289
+ }
290
+
291
+ /**
292
+ * How long a turn may run before the control side gives up on it, when the instance sets none
293
+ * (`control.turnTimeoutMs`). A turn is the agent's work, not a call: it is bounded by hours, never
294
+ * by the seconds a call to the harness may take.
295
+ */
296
+ export const DEFAULT_TURN_TIMEOUT_MS = 6 * 60 * 60 * 1000;
297
+
298
+ /**
299
+ * What a session is started with. The options blocks (`claude`, `codex`, ...) are the options of the
300
+ * kind the session is of, checked by niwa before the start: a control side reads its own block.
301
+ */
302
+ export interface StartOptions {
303
+ /** The options block of the session's kind (`{ claude: { advisor: false } }`), checked by niwa before the start. */
304
+ readonly blocks?: OptionBlocks;
305
+ /**
306
+ * The first message of the session. When it has text, it becomes the session's first turn,
307
+ * delivered the way a send delivers a message: the start does not wait for that turn to end.
308
+ */
309
+ readonly prompt: Prompt;
310
+ readonly model?: string;
311
+ readonly effort?: string;
312
+ /** The working mode, for the whole life of the session; the instance's own, else `auto`, when absent. */
313
+ readonly mode?: SessionMode;
314
+ readonly visible?: VisibleActions;
315
+ readonly cwd?: string;
316
+ /** The MCP servers the session is given, as niwa names them. */
317
+ readonly servers?: readonly McpServerSpec[];
318
+ /**
319
+ * The environment the session's own process runs in, on top of the one it inherits: niwa puts
320
+ * the session's token in it (`NIWA_ID`), so `niwa` run from the agent's Bash is that session.
321
+ * Every session has a process of its own, so every side applies it.
322
+ */
323
+ readonly env?: Readonly<Record<string, string>>;
324
+ /** The tools the session may use; the harness's own when absent. */
325
+ readonly tools?: ToolsMode;
326
+ /** Run the session's process in a sandbox (L2): the process is started through the `spawnAgent` funnel. */
327
+ readonly box?: BoxRequest;
328
+ /**
329
+ * Where the session's reverse requests go: the permissions and the questions its agent asks of its
330
+ * client. Without it a side answers them by its own policy, as a side used on its own does.
331
+ */
332
+ readonly reverse?: ReverseHandler;
333
+ /**
334
+ * Told the session's id as soon as the harness names it, before the first prompt is sent, by a
335
+ * side whose harness names the session first. The caller writes it down, so a start cut off
336
+ * while its prompt was going finds the session it made instead of making another.
337
+ */
338
+ readonly named?: (session: SessionId) => Promise<void> | void;
339
+ }
340
+
341
+ /**
342
+ * What a session is resumed with. The options blocks are the ones the session was started with: a
343
+ * process that is launched again is launched as the first one was.
344
+ */
345
+ export interface ResumeOptions {
346
+ /** The options block the session was started with, by name. */
347
+ readonly blocks?: OptionBlocks;
348
+ /** The mode the session was started in, for a process that is launched again: a session keeps its mode. */
349
+ readonly mode?: SessionMode;
350
+ /**
351
+ * The model the harness named for the session, for a process that is launched again: a session
352
+ * keeps its model, not the alias it was asked for. Without it the instance's own stands.
353
+ */
354
+ readonly model?: ModelName;
355
+ readonly prompt?: Prompt;
356
+ readonly visible?: VisibleActions;
357
+ /** The directory the session was started in, for a process that is launched again: a harness that loads a session by its directory needs the one it has. */
358
+ readonly cwd?: string;
359
+ /** The MCP servers the session is given, as niwa names them. */
360
+ readonly servers?: readonly McpServerSpec[];
361
+ /** The environment of the session's process, as in `StartOptions`. */
362
+ readonly env?: Readonly<Record<string, string>>;
363
+ /** The tools the session may use, as in `StartOptions`: the ones it was started with. */
364
+ readonly tools?: ToolsMode;
365
+ /** The box of the session's process, as in `StartOptions`. */
366
+ readonly box?: BoxRequest;
367
+ /** Where the session's reverse requests go, as in `StartOptions`: a resume names the handler the session has from now on. */
368
+ readonly reverse?: ReverseHandler;
369
+ }
370
+
371
+ /**
372
+ * A session the harness has named, and what became of its first message.
373
+ *
374
+ * `first` is the receipt of the first turn, as a send would give it (`started` or `queued`);
375
+ * a start without a prompt has none. The end of that turn is not part of the start: it is
376
+ * observed like the end of any turn, through the signs of life and the state.
377
+ */
378
+ export interface StartedSession {
379
+ readonly session: SessionId;
380
+ readonly first?: DeliveryReceipt;
381
+ /** The working mode the session was given: the one asked for, or the instance's, or the default. */
382
+ readonly mode?: SessionMode;
383
+ }
384
+
385
+ /** An operation the harness cannot do is refused by name, never emulated (capabilities.ts). */
386
+ export interface SessionControl {
387
+ /**
388
+ * Starts a session. Until the harness names it there is no session, only a start in progress
389
+ * whose result is that id.
390
+ *
391
+ * It returns as soon as the harness has named the session — never later than the moment the
392
+ * first turn has begun, and never after waiting for that turn to end. A harness whose protocol
393
+ * names the session only with the first prompt returns once the protocol has named it, which
394
+ * is at the start of that turn. A start that fails before the session is named leaves no
395
+ * session behind; a first turn that fails after the start returned is a turn that failed,
396
+ * reported through the signs of life, and the session stays.
397
+ */
398
+ start(options: StartOptions): Promise<StartedSession>;
399
+
400
+ resume(id: SessionId, options?: ResumeOptions): Promise<void>;
401
+
402
+ /**
403
+ * Sends into a session and says what happened to the message. A send that fails says how far the
404
+ * message got (delivery.ts): `InputNotSent` when the harness never had it, `InputPossiblySent`
405
+ * when it may have; any other failure is taken for possibly sent, and is never sent again.
406
+ */
407
+ send(id: SessionId, message: string, options?: SendOptions): Promise<DeliveryReceipt>;
408
+
409
+ /** Interrupts a running turn. Only on explicit request, and only where the harness can. */
410
+ interrupt(id: SessionId): Promise<void>;
411
+
412
+ /**
413
+ * Asks a session and returns a value that passed the schema.
414
+ *
415
+ * A busy session queues the question behind what is running and already queued, like a send:
416
+ * the answer comes after those turns, never instead of them.
417
+ */
418
+ ask<T>(id: SessionId, options: AskOptions<T>): Promise<AskAnswer<T>>;
419
+
420
+ /**
421
+ * Signs of life, as they happen.
422
+ *
423
+ * The stream is forward-only, with one exception: the turn signs a session gave before anyone
424
+ * watched it (the first turn begins inside the start, before the caller holds the id) are kept,
425
+ * a bounded few, and given to the first stream opened on the session. After that nothing is
426
+ * kept.
427
+ */
428
+ life(id: SessionId): AsyncIterable<LifeEvent>;
429
+
430
+ state(id: SessionId): Promise<SessionState>;
431
+
432
+ /**
433
+ * Stops the process of one session and lets it go: what is running in it stops, and the session
434
+ * is the harness's to resume later where it can. A side that holds a process or a query per
435
+ * session implements it: ending a session releases nothing otherwise. A side that holds none
436
+ * may leave it out.
437
+ */
438
+ close?(id: SessionId): Promise<void>;
439
+
440
+ /**
441
+ * Stops every session this side owns.
442
+ *
443
+ * A side that owns processes — the harness CLI and the MCP servers it was given — stops them
444
+ * here, so nothing it started outlives the host that started it. A side that owns nothing may
445
+ * leave it out.
446
+ */
447
+ dispose?(): Promise<void>;
448
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * What a kind declares it can serve: every ability, one by one, with no default.
3
+ *
4
+ * A kind says of each ability that it is `supported` or `unsupported`; a supported one is
5
+ * `verified` (proved against a live harness) or `admitted` (taken from the harness's own
6
+ * documentation or code). A new ability in this contract is a new decision for every kind, and a
7
+ * kind that leaves one out does not register.
8
+ *
9
+ * An instance is an installation of a kind, and what it may claim is bounded by the declaration:
10
+ * what is found on a machine can narrow it, never widen it.
11
+ */
12
+
13
+ import { z } from "zod";
14
+
15
+ import { SessionModeSchema } from "./capabilities.ts";
16
+ import type { SideCapabilities } from "./capabilities.ts";
17
+ import type { Harness } from "./instance.ts";
18
+
19
+ /** One ability, as a kind declares it. */
20
+ export const SupportSchema = z.discriminatedUnion("supported", [
21
+ z.object({ supported: z.literal(false) }).strict(),
22
+ z.object({ supported: z.literal(true), status: z.enum(["verified", "admitted"]) }).strict(),
23
+ ]);
24
+ export type Support = z.output<typeof SupportSchema>;
25
+
26
+ /** Supported, and proved against a live harness. */
27
+ export const VERIFIED: Support = { supported: true, status: "verified" };
28
+ /** Supported by the harness's own documentation or code, not yet proved live. */
29
+ export const ADMITTED: Support = { supported: true, status: "admitted" };
30
+ /** Not supported. */
31
+ export const UNSUPPORTED: Support = { supported: false };
32
+
33
+ export const ReadingDeclarationSchema = z
34
+ .object({ list: SupportSchema, read: SupportSchema, watch: SupportSchema })
35
+ .strict();
36
+
37
+ export const LaunchDeclarationSchema = z
38
+ .object({
39
+ model: SupportSchema,
40
+ /** The effort levels a session can be started with; none when the kind takes no effort. */
41
+ effort: z.array(z.string().min(1)).readonly(),
42
+ /** The working modes a session can be started in. */
43
+ modes: z.array(SessionModeSchema).readonly(),
44
+ })
45
+ .strict();
46
+
47
+ /**
48
+ * The tool modes a kind can hold a session to (`StartOptions.tools`) beyond `all`: only niwa's
49
+ * tools, and an allow-list of the harness's own.
50
+ */
51
+ export const ToolsDeclarationSchema = z.object({ niwaOnly: SupportSchema, allow: SupportSchema }).strict();
52
+
53
+ export const ControlDeclarationSchema = z
54
+ .object({
55
+ start: SupportSchema,
56
+ resume: SupportSchema,
57
+ send: SupportSchema,
58
+ interrupt: SupportSchema,
59
+ ask: SupportSchema,
60
+ structuredOutput: SupportSchema,
61
+ launch: LaunchDeclarationSchema,
62
+ tools: ToolsDeclarationSchema,
63
+ })
64
+ .strict();
65
+
66
+ export const InsertDeclarationSchema = z
67
+ .object({ nested: SupportSchema, compaction: SupportSchema, manualOpen: SupportSchema, permission: SupportSchema, end: SupportSchema })
68
+ .strict();
69
+
70
+ /** Every ability of every side. A side the kind has no code for declares all of its abilities unsupported. */
71
+ export const KindCapabilitiesSchema = z
72
+ .object({
73
+ reading: ReadingDeclarationSchema,
74
+ control: ControlDeclarationSchema,
75
+ insert: InsertDeclarationSchema,
76
+ })
77
+ .strict();
78
+ export type KindCapabilities = z.output<typeof KindCapabilitiesSchema>;
79
+
80
+ /** A control side that declares nothing: for a kind without one. */
81
+ export const NO_CONTROL: KindCapabilities["control"] = {
82
+ start: UNSUPPORTED,
83
+ resume: UNSUPPORTED,
84
+ send: UNSUPPORTED,
85
+ interrupt: UNSUPPORTED,
86
+ ask: UNSUPPORTED,
87
+ structuredOutput: UNSUPPORTED,
88
+ launch: { model: UNSUPPORTED, effort: [], modes: [] },
89
+ tools: { niwaOnly: UNSUPPORTED, allow: UNSUPPORTED },
90
+ };
91
+
92
+ /** An insert side that declares nothing: for a kind without one. */
93
+ export const NO_INSERT: KindCapabilities["insert"] = {
94
+ nested: UNSUPPORTED,
95
+ compaction: UNSUPPORTED,
96
+ manualOpen: UNSUPPORTED,
97
+ permission: UNSUPPORTED,
98
+ end: UNSUPPORTED,
99
+ };
100
+
101
+ /** A reading side that declares nothing: for a kind without one. */
102
+ export const NO_READING: KindCapabilities["reading"] = { list: UNSUPPORTED, read: UNSUPPORTED, watch: UNSUPPORTED };
103
+
104
+ function on(support: Support): boolean {
105
+ return support.supported;
106
+ }
107
+
108
+ /**
109
+ * Does a side declare anything: a supported ability, at any depth? The nested launch and tools
110
+ * blocks count (a model choice, a tool mode, an effort level, a working mode), so a side that
111
+ * serves only those is a side, not an absent one.
112
+ */
113
+ function anyOn(side: Readonly<Record<string, unknown>>): boolean {
114
+ return Object.values(side).some((value) => {
115
+ if (Array.isArray(value)) return value.length > 0;
116
+ if (typeof value === "object" && value !== null && !("supported" in value)) return anyOn(value as Record<string, unknown>);
117
+ return SupportSchema.safeParse(value).data?.supported === true;
118
+ });
119
+ }
120
+
121
+ /**
122
+ * The sides an installation of the kind has when nothing narrows them: every supported ability
123
+ * on, the rest off. A side with no supported ability is absent.
124
+ */
125
+ export function sidesOf(declared: KindCapabilities): SideCapabilities {
126
+ const { reading, control, insert } = declared;
127
+ return {
128
+ ...(anyOn(reading) ? { reading: { list: on(reading.list), read: on(reading.read), watch: on(reading.watch) } } : {}),
129
+ ...(anyOn(control)
130
+ ? {
131
+ control: {
132
+ start: on(control.start),
133
+ resume: on(control.resume),
134
+ send: on(control.send),
135
+ interrupt: on(control.interrupt),
136
+ ask: on(control.ask),
137
+ structuredOutput: on(control.structuredOutput),
138
+ launch: { model: on(control.launch.model), effort: [...control.launch.effort], modes: [...control.launch.modes] },
139
+ tools: { niwaOnly: on(control.tools.niwaOnly), allow: on(control.tools.allow) },
140
+ },
141
+ }
142
+ : {}),
143
+ ...(anyOn(insert)
144
+ ? {
145
+ insert: {
146
+ nested: on(insert.nested),
147
+ compaction: on(insert.compaction),
148
+ manualOpen: on(insert.manualOpen),
149
+ permission: on(insert.permission),
150
+ end: on(insert.end),
151
+ },
152
+ }
153
+ : {}),
154
+ };
155
+ }
156
+
157
+ /**
158
+ * What `sides` claims beyond the declaration, one line each: an ability the kind does not
159
+ * support, a side whose code the kind does not have, a model choice, an effort level or a working
160
+ * mode the kind does not declare. Empty when the sides stay within it.
161
+ */
162
+ export function excessOf(
163
+ sides: SideCapabilities,
164
+ declared: KindCapabilities,
165
+ implemented: { readonly reading: boolean; readonly control: boolean; readonly insert: boolean },
166
+ ): string[] {
167
+ const excess: string[] = [];
168
+ const check = (side: string, claimed: Readonly<Record<string, unknown>> | undefined, allowed: Readonly<Record<string, unknown>>) => {
169
+ if (claimed === undefined) return;
170
+ for (const [ability, value] of Object.entries(claimed)) {
171
+ if (value !== true) continue;
172
+ const support = SupportSchema.safeParse(allowed[ability]);
173
+ if (!support.success || !support.data.supported) excess.push(`${side}.${ability}`);
174
+ }
175
+ };
176
+ for (const side of ["reading", "control", "insert"] as const) {
177
+ if (sides[side] !== undefined && !implemented[side]) excess.push(`${side} (the kind has no ${side} side)`);
178
+ }
179
+ check("reading", sides.reading, declared.reading);
180
+ check("insert", sides.insert, declared.insert);
181
+ if (sides.control !== undefined) {
182
+ const { launch, tools, ...abilities } = sides.control;
183
+ check("control", abilities, declared.control);
184
+ if (tools !== undefined) check("control.tools", tools, declared.control.tools);
185
+ if (launch.model && !declared.control.launch.model.supported) excess.push("control.launch.model");
186
+ for (const level of launch.effort) {
187
+ if (!declared.control.launch.effort.includes(level)) excess.push(`control.launch.effort "${level}"`);
188
+ }
189
+ for (const mode of launch.modes) {
190
+ if (!declared.control.launch.modes.includes(mode)) excess.push(`control.launch.modes "${mode}"`);
191
+ }
192
+ }
193
+ return excess;
194
+ }
195
+
196
+ /** An installation claims what its kind cannot serve. */
197
+ export class CapabilityExceeded extends Error {
198
+ override name = "CapabilityExceeded";
199
+ readonly code = "CapabilityExceeded";
200
+
201
+ constructor(
202
+ readonly harness: Harness["id"],
203
+ readonly kind: string,
204
+ readonly excess: readonly string[],
205
+ ) {
206
+ super(`harness "${harness}" claims what its kind "${kind}" cannot serve: ${excess.join(", ")}`);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Narrow the declared sides by what was found on a machine. What was found may switch an ability
212
+ * off; claiming one the declaration does not have is an error, never a widening.
213
+ */
214
+ export function narrowSides(
215
+ harness: Harness["id"],
216
+ kind: string,
217
+ declared: KindCapabilities,
218
+ found: SideCapabilities,
219
+ implemented: { readonly reading: boolean; readonly control: boolean; readonly insert: boolean },
220
+ ): SideCapabilities {
221
+ const excess = excessOf(found, declared, implemented);
222
+ if (excess.length > 0) throw new CapabilityExceeded(harness, kind, excess);
223
+ return found;
224
+ }