@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/insert.ts ADDED
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The insert: a plugin inside the harness. It reports what cannot be seen from outside
3
+ *. It speaks the events below, never niwa's journal.
4
+ */
5
+
6
+ import { z } from "zod";
7
+
8
+ import { SessionIdSchema } from "./reading.ts";
9
+ import type { SessionId } from "./reading.ts";
10
+
11
+ /** The environment variable niwa sets in a session it starts, so the session is not taken for one opened by hand. */
12
+ export const NIWA_SESSION_ENV = "NIWA_SESSION";
13
+
14
+ /**
15
+ * The environment variable that names the program that runs niwa's CLI, which an insert reports
16
+ * through. Without it the insert runs `niwa` from the PATH.
17
+ */
18
+ export const NIWA_CLI_ENV = "NIWA_CLI";
19
+
20
+ /**
21
+ * The name of the action an insert reports through.
22
+ *
23
+ * An insert runs inside a harness and writes nothing of its own: it hands its event to
24
+ * `niwa insert report`, which calls this action on the host.
25
+ */
26
+ export const INSERT_REPORT_ACTION = "insert.report";
27
+
28
+ /** A nested session was spawned inside a session. */
29
+ export const NestedSpawnedEventSchema = z.object({
30
+ kind: z.literal("nested-spawned"),
31
+ /** The session the child was spawned in. */
32
+ parent: SessionIdSchema,
33
+ /** The child session. */
34
+ child: SessionIdSchema,
35
+ /** The harness's own name for what was spawned (a subagent, a task), when it says. */
36
+ role: z.string().optional(),
37
+ at: z.number().int().nonnegative().optional(),
38
+ });
39
+
40
+ export type NestedSpawnedEvent = z.output<typeof NestedSpawnedEventSchema>;
41
+
42
+ /** The context was compacted. */
43
+ export const CompactedEventSchema = z.object({
44
+ kind: z.literal("compacted"),
45
+ /** The session that was compacted. */
46
+ session: SessionIdSchema,
47
+ /** The harness's own summary, when it is available at the moment of compaction. */
48
+ summary: z.string().optional(),
49
+ at: z.number().int().nonnegative().optional(),
50
+ });
51
+
52
+ export type CompactedEvent = z.output<typeof CompactedEventSchema>;
53
+
54
+ /** The owner opened a session by hand. */
55
+ export const OpenedByHandEventSchema = z.object({
56
+ kind: z.literal("opened-by-hand"),
57
+ /** The session that was opened. */
58
+ session: SessionIdSchema,
59
+ /** The working directory it was opened in, when the harness says. */
60
+ cwd: z.string().optional(),
61
+ at: z.number().int().nonnegative().optional(),
62
+ });
63
+
64
+ export type OpenedByHandEvent = z.output<typeof OpenedByHandEventSchema>;
65
+
66
+ /** A tool asks for permission. */
67
+ export const PermissionAskedEventSchema = z.object({
68
+ kind: z.literal("permission-asked"),
69
+ /** The session the tool runs in. */
70
+ session: SessionIdSchema,
71
+ /** The harness's own id of the pending question, so its answer can be matched to it. */
72
+ requestId: z.string().min(1),
73
+ /** The tool that asks. */
74
+ tool: z.string().min(1),
75
+ /** What the tool wants to do, in the harness's own words. */
76
+ detail: z.string().optional(),
77
+ at: z.number().int().nonnegative().optional(),
78
+ });
79
+
80
+ export type PermissionAskedEvent = z.output<typeof PermissionAskedEventSchema>;
81
+
82
+ /** The harness ended a session: the owner left it, cleared it or moved to another. */
83
+ export const SessionEndedEventSchema = z.object({
84
+ kind: z.literal("session-ended"),
85
+ /** The session that ended. */
86
+ session: SessionIdSchema,
87
+ /** Why it ended, in the harness's own words, when it says. */
88
+ reason: z.string().optional(),
89
+ at: z.number().int().nonnegative().optional(),
90
+ });
91
+
92
+ export type SessionEndedEvent = z.output<typeof SessionEndedEventSchema>;
93
+
94
+ /** What cannot be seen from outside. */
95
+ export const InsertEventSchema = z.discriminatedUnion("kind", [
96
+ NestedSpawnedEventSchema,
97
+ CompactedEventSchema,
98
+ OpenedByHandEventSchema,
99
+ PermissionAskedEventSchema,
100
+ SessionEndedEventSchema,
101
+ ]);
102
+
103
+ export type InsertEvent = z.output<typeof InsertEventSchema>;
104
+
105
+ /** The kind of an insert event, by name. */
106
+ export type InsertEventKind = InsertEvent["kind"];
107
+
108
+ /** The answer to a permission question. */
109
+ export const PermissionAnswerSchema = z.object({
110
+ /** The question this answers. */
111
+ requestId: z.string().min(1),
112
+ /** Whether the tool may go on. */
113
+ allow: z.boolean(),
114
+ /** Why, when there is a reason to give. */
115
+ reason: z.string().optional(),
116
+ });
117
+
118
+ export type PermissionAnswer = z.output<typeof PermissionAnswerSchema>;
119
+
120
+ /** What an insert is given when it is put into the harness it belongs to. */
121
+ export interface InsertInstallOptions {
122
+ /** The home of the niwa host the plugin reports to. */
123
+ readonly home: string;
124
+ /**
125
+ * The program that runs niwa's CLI, which the plugin reports through (`niwa insert report`).
126
+ *
127
+ * Default: the `NIWA_CLI` of the environment, else `niwa` from the PATH.
128
+ */
129
+ readonly cli?: string;
130
+ }
131
+
132
+ /**
133
+ * The insert side of a harness.
134
+ *
135
+ * The insert is connected by the harness: it is a plugin inside the harness's own process, and
136
+ * this interface is what niwa sees of it. It is no client of the host: it hands its events to
137
+ * `niwa insert report` (`insert-report.ts`), the one command that calls the action.
138
+ *
139
+ * The kinds differ in how the insert works: one pulls its events out of the harness, the other is
140
+ * put into the harness and reports what it saw. An insert declares the ways it works and the
141
+ * abilities that go with them.
142
+ */
143
+ export interface HarnessInsert {
144
+ /**
145
+ * The events, as they happen.
146
+ *
147
+ * A side that is put into the harness has none: it reports them itself, through the command
148
+ * `niwa insert report`, which calls the action "insert.report".
149
+ */
150
+ events?(): AsyncIterable<InsertEvent>;
151
+
152
+ /**
153
+ * Puts the plugin into the harness, so it runs inside it.
154
+ *
155
+ * The side that is put in is installed; the side that pulls its events is already there.
156
+ */
157
+ install?(opts: InsertInstallOptions): Promise<void>;
158
+
159
+ /**
160
+ * Answers a permission question.
161
+ *
162
+ * The answer goes back to the harness that asked. An insert that cannot carry answers does not
163
+ * declare the ability.
164
+ */
165
+ answerPermission?(answer: PermissionAnswer): Promise<void>;
166
+ }
167
+
168
+ /** The session an event is about; for a nested spawn, the child. */
169
+ export function eventSession(event: InsertEvent): SessionId {
170
+ return event.kind === "nested-spawned" ? event.child : event.session;
171
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The harness instance: one concrete installation of a harness kind on one machine
3
+ *. The id belongs to the instance, not to the kind.
4
+ */
5
+
6
+ import { z } from "zod";
7
+
8
+ import { SideCapabilitiesSchema } from "./capabilities.ts";
9
+
10
+ /** The id of a harness instance: "claude-personal", "mcode-work". */
11
+ export const HarnessIdSchema = z
12
+ .string()
13
+ .regex(/^\S+$/, "a harness id must be non-empty and contain no whitespace")
14
+ .brand<"HarnessId">();
15
+ export type HarnessId = z.output<typeof HarnessIdSchema>;
16
+
17
+ /** The id of a harness kind: the code that serves an instance. */
18
+ export const HarnessKindSchema = z
19
+ .string()
20
+ .regex(/^\S+$/, "a harness kind must be non-empty and contain no whitespace")
21
+ .brand<"HarnessKind">();
22
+ export type HarnessKind = z.output<typeof HarnessKindSchema>;
23
+
24
+ /** The id of a machine: where an instance lives. */
25
+ export const MachineIdSchema = z
26
+ .string()
27
+ .regex(/^\S+$/, "a machine id must be non-empty and contain no whitespace")
28
+ .brand<"MachineId">();
29
+ export type MachineId = z.output<typeof MachineIdSchema>;
30
+
31
+ /** The binary of an installation; an SDK has none. */
32
+ export const HarnessBinarySchema = z.object({
33
+ path: z.string().min(1),
34
+ version: z.string().min(1),
35
+ });
36
+ export type HarnessBinary = z.output<typeof HarnessBinarySchema>;
37
+
38
+ /** Which sides an installation has and what each can do. */
39
+ export const HarnessSidesSchema = SideCapabilitiesSchema;
40
+ export type HarnessSides = z.output<typeof HarnessSidesSchema>;
41
+
42
+ /** A harness instance, as it is declared. */
43
+ export const HarnessSchema = z.object({
44
+ id: HarnessIdSchema,
45
+ kind: HarnessKindSchema,
46
+ machine: MachineIdSchema,
47
+ binary: HarnessBinarySchema.optional(),
48
+ /** The directory of its settings and sessions. */
49
+ home: z.string().min(1),
50
+ /** The model each of its sessions runs unless the start names another; absent, the harness's own. */
51
+ model: z.string().min(1).optional(),
52
+ sides: HarnessSidesSchema,
53
+ });
54
+ export type Harness = z.output<typeof HarnessSchema>;
55
+
56
+ export function harnessId(value: string): HarnessId {
57
+ return HarnessIdSchema.parse(value);
58
+ }
59
+
60
+ export function harnessKind(value: string): HarnessKind {
61
+ return HarnessKindSchema.parse(value);
62
+ }
63
+
64
+ export function machineId(value: string): MachineId {
65
+ return MachineIdSchema.parse(value);
66
+ }
package/src/options.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * What a session of a harness kind takes at its start besides the model, the effort and the mode:
3
+ * one block of options per kind, named by the kind.
4
+ *
5
+ * The block is the kind's own: the package of a kind declares its name and its schema
6
+ * (`kindOptions`), and `defineHarnessKind({ options })` carries it. Nothing here lists the kinds, so
7
+ * a kind from another package has a block as typed as the ones niwa ships. A start that carries the
8
+ * block of its own kind has it checked by that schema and applied; a start that carries the block
9
+ * of another kind is refused, and so is a field the block does not have. The schemas are strict
10
+ * for that reason: a key a kind does not know is an error, never ignored.
11
+ *
12
+ * A block travels beside the fields of a start (`claude: { advisor: false }`): every key of an input
13
+ * that is not one of its fields is a block (`blocksOf`).
14
+ */
15
+
16
+ import { z } from "zod";
17
+
18
+ /** The name of a block: the key in workflow session options, `session.start` and on the command line. */
19
+ export const OptionsBlockNameSchema = z
20
+ .string()
21
+ .regex(/^[a-z][a-z0-9-]*$/, "a block name is lower case letters, digits and dashes, starting with a letter");
22
+ export type OptionsBlock = z.output<typeof OptionsBlockNameSchema>;
23
+
24
+ /** One block, as it is carried: an object, checked against the schema of its kind before it is used. */
25
+ export type OptionsBlockValue = Readonly<Record<string, unknown>>;
26
+
27
+ /** The blocks a start, a question or a record carries, by name. A session carries the block of its own kind, or none. */
28
+ export type OptionBlocks = Readonly<Record<OptionsBlock, OptionsBlockValue>>;
29
+
30
+ /** The blocks as a record keeps them. */
31
+ export const OptionBlocksSchema = z.record(OptionsBlockNameSchema, z.record(z.string(), z.unknown()));
32
+
33
+ /** What a kind declares of its options: the name of its block, and the schema the block is checked by. */
34
+ export interface KindOptions {
35
+ readonly block: OptionsBlock;
36
+ readonly schema: z.ZodType<OptionsBlockValue, OptionsBlockValue>;
37
+ }
38
+
39
+ /** The block of a kind that has no option of its own yet: it takes nothing, and is checked all the same. */
40
+ export const NoOptions = z.strictObject({});
41
+
42
+ /** The options a kind declares: its block's name and schema. */
43
+ export function kindOptions(block: string, schema: z.ZodType<OptionsBlockValue, OptionsBlockValue>): KindOptions {
44
+ return { block: OptionsBlockNameSchema.parse(block), schema };
45
+ }
46
+
47
+ /** Is this a block: a plain object? */
48
+ function isBlock(value: unknown): value is OptionsBlockValue {
49
+ return typeof value === "object" && value !== null && !Array.isArray(value);
50
+ }
51
+
52
+ /**
53
+ * The schema of an input that carries options blocks beside its `fields`: every other key is a block, an object
54
+ * named after its kind. What is in a block is its kind's schema to check, once the harness is known; a key that is
55
+ * no field and holds anything but an object is refused here, with `refuse` saying so.
56
+ */
57
+ export function withBlocks<Shape extends z.ZodRawShape>(
58
+ fields: z.ZodObject<Shape>,
59
+ refuse: (key: string) => string = (key) => `there is no field "${key}", and an options block is an object`,
60
+ ) {
61
+ const known = new Set(Object.keys(fields.shape));
62
+ return fields.catchall(z.unknown()).superRefine((input, ctx) => {
63
+ for (const [key, value] of Object.entries(input)) {
64
+ if (known.has(key) || value === undefined || isBlock(value)) continue;
65
+ ctx.addIssue({ code: "custom", message: refuse(key), path: [key] });
66
+ }
67
+ });
68
+ }
69
+
70
+ /**
71
+ * The blocks an input carries: every key that is not one of its `fields` and has a value. A key that
72
+ * is not a field and holds anything but an object is neither a field nor a block, and is refused.
73
+ */
74
+ export function blocksOf(input: object, fields: Iterable<string>): OptionBlocks {
75
+ const known = new Set(fields);
76
+ const blocks: Record<string, OptionsBlockValue> = {};
77
+ for (const [name, value] of Object.entries(input)) {
78
+ if (known.has(name) || value === undefined) continue;
79
+ if (!isBlock(value)) throw new Error(`there is no field "${name}", and an options block is an object`);
80
+ blocks[OptionsBlockNameSchema.parse(name)] = value;
81
+ }
82
+ return blocks;
83
+ }