@niwa-labs/harness-zcode 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/reading.ts ADDED
@@ -0,0 +1,506 @@
1
+ /**
2
+ * The reading side of a ZCode installation. It reads the
3
+ * harness's SQLite database read-only and copies nothing. The format is in `format.ts`, the
4
+ * layout in `paths.ts`.
5
+ *
6
+ * A locator is `zcode:v1:<message>:<part>:<sub>`: the `sequence` of the message, the `sequence`
7
+ * of the part inside it, and which of the part's records it is (a tool part is two: the call,
8
+ * then its result, and a third, the checklist, when the call wrote one). The sequences are the
9
+ * harness's own order, so a locator names the same place however the session grows. A session
10
+ * spawned inside this one sits where it was created: right after the last part that existed
11
+ * then, with a `sub` of 3 and up.
12
+ *
13
+ * Only the tail of a running session is half written: the last message while its answer has no
14
+ * completion time, and the tool parts of it that still run. Those records are marked incomplete.
15
+ * An older message that was never completed (its process was killed) is whole as it stands.
16
+ */
17
+
18
+ import { existsSync } from "node:fs";
19
+
20
+ import { Database } from "bun:sqlite";
21
+ import { z } from "zod";
22
+
23
+ import { assertNever, optionalJsonOf, timestamp } from "@niwa-labs/core";
24
+ import {
25
+ EMPTY,
26
+ LocatorSchema,
27
+ NOT_SCANNED,
28
+ NativeSessionIdSchema,
29
+ failedCoverage,
30
+ unavailableCoverage,
31
+ } from "@niwa-labs/harness";
32
+ import type {
33
+ Coverage,
34
+ HarnessId,
35
+ Locator,
36
+ SessionFilter,
37
+ SessionId,
38
+ SessionInfo,
39
+ SessionReading,
40
+ SessionRecord,
41
+ } from "@niwa-labs/harness";
42
+
43
+ import { isHumanMessage, isRunning, millisOf, modelOf, readMessage, readPart, resultOf } from "./format.ts";
44
+ import type { MessageData } from "./format.ts";
45
+ import { configuredModeOf } from "./config.ts";
46
+ import { dbPathOf } from "./paths.ts";
47
+ import { zcodeChecklist, zcodeToolShape } from "./tools.ts";
48
+
49
+ export interface ZcodeReadingOptions {
50
+ /** The id of the installation this side serves. */
51
+ readonly harness: HarnessId;
52
+ /** The directory that holds `cli/db/db.sqlite`. */
53
+ readonly home: string;
54
+ }
55
+
56
+ /** The sub of the first nested session at a place: the parts' own records take 0 to 2. */
57
+ const FIRST_NESTED_SUB = 3;
58
+ /** How many ids a query names at most; more than that is filtered after the query. */
59
+ const MAX_NAMED = 500;
60
+
61
+ /** A record before the reading side has put its locator in. */
62
+ type Unlocated = SessionRecord extends infer R ? (R extends unknown ? Omit<R, "locator"> : never) : never;
63
+
64
+ /** The place of a record in its session. */
65
+ interface Position {
66
+ readonly message: number;
67
+ readonly part: number;
68
+ readonly sub: number;
69
+ }
70
+
71
+ interface Item {
72
+ readonly at: Position;
73
+ readonly record: Unlocated;
74
+ }
75
+
76
+ const LOCATOR = /^zcode:v1:(-?\d+):(-?\d+):(\d+)$/;
77
+
78
+ function encode(at: Position): Locator {
79
+ return LocatorSchema.parse(`zcode:v1:${at.message}:${at.part}:${at.sub}`);
80
+ }
81
+
82
+ function decode(locator: Locator): Position {
83
+ const match = LOCATOR.exec(locator);
84
+ if (match === null) throw new Error(`zcode: ${locator} is not a locator of this side`);
85
+ return { message: Number(match[1]), part: Number(match[2]), sub: Number(match[3]) };
86
+ }
87
+
88
+ function compare(a: Position, b: Position): number {
89
+ return a.message - b.message || a.part - b.part || a.sub - b.sub;
90
+ }
91
+
92
+ /** The database, read-only: no write lock is ever taken, and a short wait rides out a checkpoint. */
93
+ function open(path: string): Database {
94
+ const db = new Database(path, { readonly: true });
95
+ try {
96
+ db.run("pragma busy_timeout = 250");
97
+ } catch (error) {
98
+ db.close();
99
+ throw error;
100
+ }
101
+ return db;
102
+ }
103
+
104
+ interface Row {
105
+ readonly mseq: number;
106
+ readonly pseq: number;
107
+ readonly mdata: string;
108
+ readonly pdata: string;
109
+ readonly ptime: number;
110
+ }
111
+
112
+ function sessionExists(db: Database, native: string): boolean {
113
+ return db.query("select 1 from session where id = ?").get(native) !== null;
114
+ }
115
+
116
+ /** The sessions spawned inside a session, each anchored after the last part that existed when it was created. */
117
+ function nestedOf(db: Database, harness: HarnessId, native: string): Item[] {
118
+ const children = new Map<string, number>();
119
+ const direct = db.query("select id, time_created as created from session where parent_id = ?").all(native) as {
120
+ id: string;
121
+ created: number;
122
+ }[];
123
+ for (const child of direct) children.set(child.id, child.created);
124
+ // Workflow actors name their parent only in the link table, which an older database lacks.
125
+ try {
126
+ const linked = db
127
+ .query(
128
+ "select s.id as id, s.time_created as created from session_task_link l join session s on s.id = l.child_session_id where l.parent_session_id = ?",
129
+ )
130
+ .all(native) as { id: string; created: number }[];
131
+ for (const child of linked) children.set(child.id, child.created);
132
+ } catch {
133
+ // No link table: the parent ids are all there is.
134
+ }
135
+ if (children.size === 0) return [];
136
+ // Where the parts sit in the session's order, read once: a child is anchored after the last of
137
+ // them that existed when it was created.
138
+ const parts = db
139
+ .query(
140
+ "select m.sequence as message, p.sequence as part, p.time_created as created from part p join message m on m.id = p.message_id where p.session_id = ? order by m.sequence, p.sequence",
141
+ )
142
+ .all(native) as { message: number; part: number; created: number }[];
143
+ const anchorOf = (created: number): { message: number; part: number } => {
144
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
145
+ const found = parts[index];
146
+ if (found !== undefined && found.created <= created) return found;
147
+ }
148
+ return { message: -1, part: -1 };
149
+ };
150
+ const sorted = [...children].sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]));
151
+ const taken = new Map<string, number>();
152
+ return sorted.map(([id, created]) => {
153
+ const anchor = anchorOf(created);
154
+ const place = { message: anchor.message, part: anchor.part };
155
+ const key = `${place.message}:${place.part}`;
156
+ const index = taken.get(key) ?? 0;
157
+ taken.set(key, index + 1);
158
+ return {
159
+ at: { ...place, sub: FIRST_NESTED_SUB + index },
160
+ record: {
161
+ kind: "nested",
162
+ child: { harness, native: NativeSessionIdSchema.parse(id) },
163
+ at: millisOf(created),
164
+ incomplete: false,
165
+ },
166
+ };
167
+ });
168
+ }
169
+
170
+ /** What a part says, as common records: none for what is not conversation. */
171
+ function recordsOf(
172
+ db: Database,
173
+ message: MessageData | undefined,
174
+ row: Row,
175
+ running: boolean,
176
+ open: boolean,
177
+ ): Array<{ sub: number; record: Unlocated }> {
178
+ const read = readPart(row.pdata);
179
+ const unknown = (raw: unknown): Array<{ sub: number; record: Unlocated }> => [
180
+ { sub: 0, record: { kind: "unknown", raw, at: millisOf(row.ptime), incomplete: false } },
181
+ ];
182
+ // A part of a type ZCode has added since, or one that is not JSON: kept whole.
183
+ if (read.kind === "unknown") return unknown(read.raw);
184
+ const part = read.part;
185
+ const at = (value: unknown): number | undefined => millisOf(value) ?? millisOf(row.ptime);
186
+ switch (part.type) {
187
+ // The model's thought: the text it wrote, from when it began. Only the tail can still be thinking.
188
+ case "reasoning":
189
+ return [{ sub: 0, record: { kind: "thinking", text: part.text ?? "", redacted: false, at: at(part.time?.start), incomplete: running } }];
190
+ // The harness's own bookkeeping is not conversation: no record.
191
+ case "step-start":
192
+ case "step-finish":
193
+ case "timeline":
194
+ return [];
195
+ // What a person or the model wrote that no common record has a kind for, or the harness's file bookkeeping:
196
+ // kept whole as the harness's own part, which is what an unknown record is.
197
+ case "file": // an attachment
198
+ case "agent": // an @agent mention
199
+ case "subtask": // the request to spawn a subtask (the session it spawned is the `nested` record)
200
+ case "retry": // a request of the model that was tried again
201
+ case "snapshot": // the hash of a snapshot of the files
202
+ case "patch": // the files a step changed
203
+ return unknown(part);
204
+ case "text": {
205
+ if (message === undefined) return unknown(part);
206
+ if (part.synthetic === true) return [];
207
+ const base = { at: at(part.time?.start), incomplete: running };
208
+ if (message.role === "user") {
209
+ // The messages ZCode keeps for the model alone and the parts it marks synthetic are left out above,
210
+ // so what is read here is what the person typed.
211
+ return isHumanMessage(message) ? [{ sub: 0, record: { kind: "user", text: part.text, inserted: [], ...base } }] : [];
212
+ }
213
+ if (message.role === "assistant") {
214
+ const model = modelOf(message);
215
+ return [{ sub: 0, record: { kind: "assistant", text: part.text, ...(model === undefined ? {} : { model }), ...base } }];
216
+ }
217
+ return [{ sub: 0, record: { kind: "unknown", raw: part, ...base } }];
218
+ }
219
+ case "tool": {
220
+ if (message === undefined) return unknown(part);
221
+ const started = at(part.state.time?.start);
222
+ const call: Unlocated = {
223
+ kind: "tool-call",
224
+ callId: part.callID,
225
+ name: part.tool,
226
+ ...zcodeToolShape(part.tool, part.state.input),
227
+ input: optionalJsonOf(part.state.input),
228
+ at: started,
229
+ // A call left running in an older message was abandoned (its process died): it has no result
230
+ // and never will, so it does not hold the reader back. Only the last message can still be at work.
231
+ incomplete: running || (open && isRunning(part)),
232
+ };
233
+ if (isRunning(part)) return [{ sub: 0, record: call }];
234
+ const result: Unlocated = {
235
+ kind: "tool-result",
236
+ callId: part.callID,
237
+ name: part.tool,
238
+ output: optionalJsonOf(resultOf(part)),
239
+ ok: part.state.status === "completed",
240
+ at: at(part.state.time?.end),
241
+ incomplete: running,
242
+ };
243
+ const checklist = part.state.status === "completed" ? zcodeChecklist(part.tool, part.state.input) : undefined;
244
+ return [
245
+ { sub: 0, record: call },
246
+ { sub: 1, record: result },
247
+ ...(checklist === undefined
248
+ ? []
249
+ : [{ sub: 2, record: { kind: "checklist" as const, callId: part.callID, items: checklist.items, at: call.at, incomplete: running } }]),
250
+ ];
251
+ }
252
+ case "compaction": {
253
+ if (message === undefined) return unknown(part);
254
+ const summary = part.summaryMessageId === undefined ? undefined : summaryOf(db, part.summaryMessageId);
255
+ return [{ sub: 0, record: { kind: "compaction", summary: summary ?? "", at: at(undefined), incomplete: false } }];
256
+ }
257
+ default:
258
+ return assertNever(part, "part type");
259
+ }
260
+ }
261
+
262
+ /** The summary a compaction left, in the message it names. */
263
+ function summaryOf(db: Database, messageId: string): string | undefined {
264
+ const found = db.query("select data from message where id = ?").get(messageId) as { data: string } | null;
265
+ return found === null ? undefined : readMessage(found.data)?.summary?.body;
266
+ }
267
+
268
+ /** The records of a session in the order they sit, with where each is. Only what follows `after` is given. */
269
+ export function* itemsOf(db: Database, harness: HarnessId, native: string, after: Position | undefined): Generator<Item> {
270
+ // One snapshot for the marker of the tail, the sessions spawned inside and the rows: a message that
271
+ // is written between two of the reads must not be taken for a finished one. The connection is closed
272
+ // by the caller, which ends the read.
273
+ db.run("begin");
274
+ const last = (db.query("select max(sequence) as last from message where session_id = ?").get(native) as {
275
+ last: number | null;
276
+ }).last;
277
+ const pending = nestedOf(db, harness, native);
278
+ const rows = db
279
+ .query(
280
+ "select m.sequence as mseq, p.sequence as pseq, m.data as mdata, p.data as pdata, p.time_created as ptime from message m join part p on p.message_id = m.id where m.session_id = ? and m.sequence >= ? order by m.sequence, p.sequence",
281
+ )
282
+ .iterate(native, Math.max(after?.message ?? 0, 0)) as IterableIterator<Row>;
283
+ let current: { sequence: number; message: MessageData | undefined } | undefined;
284
+ // From the first record that is not whole on, nothing is: a reader does not move past a half-written line.
285
+ let tail = false;
286
+ const given = (item: Item): boolean => after === undefined || compare(item.at, after) > 0;
287
+
288
+ for (const row of rows) {
289
+ const place = { message: row.mseq, part: row.pseq };
290
+ while (pending[0] !== undefined && compare({ ...pending[0].at, sub: 0 }, { ...place, sub: 0 }) < 0) {
291
+ const nested = pending.shift();
292
+ if (nested !== undefined && given(nested)) yield nested;
293
+ }
294
+ if (current?.sequence !== row.mseq) current = { sequence: row.mseq, message: readMessage(row.mdata) };
295
+ const unfinished =
296
+ row.mseq === last && current.message?.role === "assistant" && current.message.time?.completed === undefined;
297
+ for (const { sub, record } of recordsOf(db, current.message, row, unfinished, row.mseq === last)) {
298
+ tail ||= record.incomplete;
299
+ const item: Item = { at: { ...place, sub }, record: tail ? { ...record, incomplete: true } : record };
300
+ if (given(item)) yield item;
301
+ }
302
+ }
303
+ for (const nested of pending) if (given(nested)) yield nested;
304
+ }
305
+
306
+ /** What `raw` gives back: the harness's own rows whole, or the session that was spawned. */
307
+ const RawRecordSchema = z.union([
308
+ z.looseObject({ kind: z.literal("part"), message: z.unknown(), part: z.unknown() }),
309
+ z.looseObject({ kind: z.literal("child"), session: z.string() }),
310
+ ]);
311
+
312
+ function jsonOrText(text: string): unknown {
313
+ try {
314
+ return JSON.parse(text) as unknown;
315
+ } catch {
316
+ return text;
317
+ }
318
+ }
319
+
320
+ /** The directory a session ran in, as the database has it; `undefined` when it is not there. */
321
+ export function directoryOf(home: string, native: string): string | undefined {
322
+ const path = dbPathOf(home);
323
+ if (!existsSync(path)) return undefined;
324
+ let db: Database | undefined;
325
+ try {
326
+ db = open(path);
327
+ const found = db.query("select directory from session where id = ?").get(native) as { directory: string } | null;
328
+ return found?.directory;
329
+ } catch {
330
+ return undefined;
331
+ } finally {
332
+ db?.close();
333
+ }
334
+ }
335
+
336
+ /** ZCode's built-in mode when nothing else names one (`DefaultRuntimeConfig.permission.mode`). */
337
+ const BUILT_IN_MODE = "build";
338
+
339
+ /**
340
+ * The mode ZCode restores a resumed session in, as it derives it: the `mode` stamped on the last
341
+ * assistant message; else the project's permission mode in `local_setting` (the project of the
342
+ * session's row); else the user's config file `permission.mode` (project config files cannot set
343
+ * it, see `config.ts`); else ZCode's built-in default. `undefined` when the database cannot say (no
344
+ * database, no such session, a read that fails).
345
+ */
346
+ export function persistedModeOf(home: string, native: string): string | undefined {
347
+ const path = dbPathOf(home);
348
+ if (!existsSync(path)) return undefined;
349
+ let db: Database | undefined;
350
+ try {
351
+ db = open(path);
352
+ const rows = db.query("select data from message where session_id = ? order by sequence desc").all(native) as Array<{ data: string }>;
353
+ for (const row of rows) {
354
+ const message = readMessage(row.data);
355
+ if (message?.role !== "assistant") continue;
356
+ const mode = message["mode"];
357
+ if (typeof mode === "string" && mode !== "") return mode;
358
+ }
359
+ const session = db.query("select project_id from session where id = ?").get(native) as { project_id: string } | null;
360
+ if (session === null) return undefined;
361
+ const setting = db
362
+ .query("select value from local_setting where scope = 'project' and scope_id = ? and namespace = 'permission' and key = 'mode'")
363
+ .get(session.project_id) as { value: string } | null;
364
+ if (setting !== null) {
365
+ const mode = (jsonOrText(setting.value) as { mode?: unknown } | null)?.mode;
366
+ if (typeof mode === "string" && mode !== "") return mode;
367
+ }
368
+ return configuredModeOf(home) ?? BUILT_IN_MODE;
369
+ } catch {
370
+ return undefined;
371
+ } finally {
372
+ db?.close();
373
+ }
374
+ }
375
+
376
+ export class ZcodeReading implements SessionReading {
377
+ readonly #harness: HarnessId;
378
+ readonly #path: string;
379
+
380
+ constructor(options: ZcodeReadingOptions) {
381
+ this.#harness = options.harness;
382
+ this.#path = dbPathOf(options.home);
383
+ }
384
+
385
+ readonly rawSchema = RawRecordSchema;
386
+
387
+ /** The sessions of the database, last changed first. */
388
+ async *list(filter?: SessionFilter): AsyncIterable<SessionInfo> {
389
+ if (!existsSync(this.#path)) return;
390
+ const db = open(this.#path);
391
+ try {
392
+ const named = filter?.natives !== undefined && filter.natives.length <= MAX_NAMED;
393
+ const where = ["time_deleted is null"];
394
+ const args: Array<string | number> = [];
395
+ if (filter?.cwd !== undefined) {
396
+ where.push("directory = ?");
397
+ args.push(filter.cwd);
398
+ }
399
+ if (filter?.since !== undefined) {
400
+ where.push("time_updated >= ?");
401
+ args.push(filter.since);
402
+ }
403
+ if (named) {
404
+ where.push(`id in (${filter.natives.map(() => "?").join(", ")})`);
405
+ args.push(...filter.natives);
406
+ }
407
+ const wanted = filter?.natives !== undefined && !named ? new Set(filter.natives) : undefined;
408
+ const rows = db
409
+ .query(
410
+ `select id, directory, title, title_source as source, time_created as created, time_updated as updated from session where ${where.join(" and ")} order by time_updated desc`,
411
+ )
412
+ .iterate(...args) as IterableIterator<{
413
+ id: string;
414
+ directory: string;
415
+ title: string;
416
+ source: string;
417
+ created: number;
418
+ updated: number;
419
+ }>;
420
+ for (const row of rows) {
421
+ if (wanted !== undefined && !wanted.has(row.id)) continue;
422
+ // A title the harness has not made yet is its placeholder, not a title.
423
+ const title = row.source === "default" ? "" : row.title.replace(/\s+/g, " ").trim();
424
+ yield {
425
+ id: { harness: this.#harness, native: NativeSessionIdSchema.parse(row.id) },
426
+ ...(title === "" ? {} : { title }),
427
+ cwd: row.directory,
428
+ startedAt: timestamp(row.created),
429
+ updatedAt: timestamp(row.updated),
430
+ };
431
+ }
432
+ } finally {
433
+ db.close();
434
+ }
435
+ }
436
+
437
+ /** Records of a session, after `from` when given. */
438
+ async *read(id: SessionId, from?: Locator): AsyncIterable<SessionRecord> {
439
+ if (!existsSync(this.#path)) return;
440
+ const after = from === undefined ? undefined : decode(from);
441
+ const db = open(this.#path);
442
+ try {
443
+ if (!sessionExists(db, id.native)) return;
444
+ for (const { at, record } of itemsOf(db, this.#harness, id.native, after)) {
445
+ yield { ...record, locator: encode(at) } as SessionRecord;
446
+ }
447
+ } finally {
448
+ db.close();
449
+ }
450
+ }
451
+
452
+ /** The harness's own rows, whole, at a locator. */
453
+ async raw(id: SessionId, locator: Locator): Promise<unknown> {
454
+ const at = decode(locator);
455
+ const db = this.#openFor(id);
456
+ try {
457
+ if (at.sub >= FIRST_NESTED_SUB) {
458
+ const child = nestedOf(db, this.#harness, id.native).find((item) => compare(item.at, at) === 0);
459
+ if (child?.record.kind === "nested") return { kind: "child", session: child.record.child.native };
460
+ } else {
461
+ const row = db
462
+ .query(
463
+ "select m.data as mdata, p.data as pdata from message m join part p on p.message_id = m.id where m.session_id = ? and m.sequence = ? and p.sequence = ?",
464
+ )
465
+ .get(id.native, at.message, at.part) as { mdata: string; pdata: string } | null;
466
+ if (row !== null) return { kind: "part", message: jsonOrText(row.mdata), part: jsonOrText(row.pdata) };
467
+ }
468
+ } finally {
469
+ db.close();
470
+ }
471
+ throw new Error(`zcode: no record at ${locator} in session ${id.native}`);
472
+ }
473
+
474
+ /**
475
+ * `unavailable` — not in the database; `failed` — the scan broke; `empty` — nothing in the range;
476
+ * `not-scanned` — there are records niwa has not read: it copies nothing, so a range is only
477
+ * read when a caller asks `read`. The answer comes from the generator `read` uses, so the two
478
+ * never disagree about what is a record.
479
+ */
480
+ async coverage(id: SessionId, from?: Locator): Promise<Coverage> {
481
+ if (!existsSync(this.#path)) return unavailableCoverage(`zcode: there is no database at ${this.#path}`);
482
+ try {
483
+ const after = from === undefined ? undefined : decode(from);
484
+ const db = open(this.#path);
485
+ try {
486
+ if (!sessionExists(db, id.native)) return unavailableCoverage(`zcode: session ${id.native} is not in the database`);
487
+ for (const _ of itemsOf(db, this.#harness, id.native, after)) return NOT_SCANNED;
488
+ return EMPTY;
489
+ } finally {
490
+ db.close();
491
+ }
492
+ } catch (error) {
493
+ return failedCoverage(`zcode: session ${id.native} could not be scanned: ${error instanceof Error ? error.message : String(error)}`);
494
+ }
495
+ }
496
+
497
+ #openFor(id: SessionId): Database {
498
+ if (!existsSync(this.#path)) throw new Error(`zcode: there is no database at ${this.#path}`);
499
+ const db = open(this.#path);
500
+ if (!sessionExists(db, id.native)) {
501
+ db.close();
502
+ throw new Error(`zcode: session ${id.native} is not in the database`);
503
+ }
504
+ return db;
505
+ }
506
+ }
package/src/reverse.ts ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * What ZCode asks of its client in the middle of a turn, mapped to niwa's common question and back. The wire is ZCode's `zcode-protocol`:
3
+ *
4
+ * - `interaction/requestPermission`: a tool asks leave. The server lists its options, each with the
5
+ * `response` it takes for it; the client answers with one response, not with an option id.
6
+ * - `interaction/requestUserInput`, in two forms: `questions` (AskUserQuestion, plan approval, an MCP
7
+ * server's elicitation), each with options of a `value` and a `label`, answered by
8
+ * `{ action: "accept", content: { answers: { <question text>: <value> } } }`; and a bare `prompt`
9
+ * with no questions, answered by `{ action: "accept", content: { answer: <text> } }`.
10
+ *
11
+ * The params arrive read (`protocol/`) and the answers are the types ZCode's protocol gives them. Nothing
12
+ * here talks to a process: the control side owns the wire, this module owns the meaning.
13
+ */
14
+
15
+ import { OptionIdSchema, pickedOptions, stableJson } from "@niwa-labs/core";
16
+ import type { Answer, OptionId, Question, QuestionOption } from "@niwa-labs/core";
17
+
18
+ import type { RequestPermissionParams, RequestUserInputParams } from "./protocol/generated/zcode-protocol.ts";
19
+ import type { RequestAnswer } from "./protocol/index.ts";
20
+
21
+ /** What an input a request carries is cut to, in the detail of the question. */
22
+ const DETAIL_CHARS = 500;
23
+
24
+ /** The value ZCode gives an option that means "type your answer" (an MCP elicitation of a free text). */
25
+ const FREE_TEXT_VALUE = "__zcode_free_text__";
26
+
27
+ /** The answer to a permission request, as ZCode takes it. */
28
+ export type PermissionAnswer = RequestAnswer<"interaction/requestPermission">;
29
+
30
+ /** The answer to a user input request, as ZCode takes it. */
31
+ export type InputAnswer = RequestAnswer<"interaction/requestUserInput">;
32
+
33
+ /** What the client says when a request cannot be asked: no one could be told, or it was cancelled. */
34
+ const CANCELLED_REASON = "niwa: the request was cancelled before it was answered";
35
+
36
+ /** One request of ZCode, read: its id (the same for every announcement of it) and the call it belongs to. */
37
+ export interface ReadRequest<T> {
38
+ readonly requestId: string;
39
+ readonly toolCallId: string | undefined;
40
+ readonly ask: T;
41
+ }
42
+
43
+ /** A permission as a question, and how an answer to it goes back. */
44
+ export interface PermissionAsk {
45
+ readonly question: Question;
46
+ answer(answer: Answer): PermissionAnswer;
47
+ }
48
+
49
+ /** One question of a user input request, and the text an answer to it comes to. */
50
+ export interface InputQuestion {
51
+ /** The key the answer goes under: the text of the question. */
52
+ readonly key: string;
53
+ readonly question: Question;
54
+ /** The words an answer says: the value of the option picked, or the text given. Nothing when it says none. */
55
+ textOf(answer: Answer): string | undefined;
56
+ }
57
+
58
+ /** A user input request as the questions to ask, and how the answers go back. */
59
+ export interface InputAsk {
60
+ readonly questions: readonly InputQuestion[];
61
+ /** The answer to the request: the texts of its questions, in order. */
62
+ answer(texts: readonly string[]): InputAnswer;
63
+ }
64
+
65
+ /** The id of the option a question's `index`-th choice has: ZCode gives its choices none. */
66
+ const choiceId = (index: number): OptionId => OptionIdSchema.parse(`option-${index + 1}`);
67
+
68
+ /** A permission request as a question. */
69
+ export function readPermission(request: RequestPermissionParams): ReadRequest<PermissionAsk> {
70
+ // Only the once-only options are carried: niwa remembers an "always" itself and never picks ZCode's own
71
+ // (`allow_project`, `allow_session`). A once-only option ZCode did not offer is made with the answer it takes.
72
+ const allow = request.options.find((option) => option.kind === "allow_once");
73
+ const deny = request.options.find((option) => option.kind === "deny");
74
+ // Only the decision and its reason go back: the rule updates and the changed input of an option are never carried.
75
+ const answerOf = (option: RequestPermissionParams["options"][number]): PermissionAnswer => ({
76
+ decision: option.response.decision,
77
+ ...(option.response.reason === undefined ? {} : { reason: option.response.reason }),
78
+ });
79
+ const offered = [
80
+ { id: allow?.optionId ?? "allow_once", label: allow?.name ?? "Allow once", flavor: "allow_once" as const, description: allow?.description, response: allow === undefined ? { decision: "allow", reason: "Approved once" } satisfies PermissionAnswer : answerOf(allow) },
81
+ { id: deny?.optionId ?? "deny", label: deny?.name ?? "Deny", flavor: "reject_once" as const, description: deny?.description, response: deny === undefined ? { decision: "deny", reason: "niwa: denied" } satisfies PermissionAnswer : answerOf(deny) },
82
+ ];
83
+ const options: QuestionOption[] = offered.map((option) => ({
84
+ id: OptionIdSchema.parse(option.id),
85
+ label: option.label,
86
+ ...(option.description === undefined || option.description === "" ? {} : { description: option.description }),
87
+ flavor: option.flavor,
88
+ }));
89
+
90
+ const input = request.input === undefined ? undefined : stableJson(request.input);
91
+ const detail = [request.reason, input].filter((part): part is string => part !== undefined && part !== "").join("\n");
92
+ const question: Question = {
93
+ kind: "permission",
94
+ title: request.toolName,
95
+ ...(detail === "" ? {} : { detail: detail.slice(0, DETAIL_CHARS) }),
96
+ options,
97
+ // ZCode names no kind of tool: the tool is the kind, and its input is what it acts on.
98
+ subject: { tool: request.toolName, kind: request.toolName, target: input ?? request.toolName },
99
+ };
100
+
101
+ return {
102
+ requestId: request.requestId,
103
+ toolCallId: request.toolCallId,
104
+ ask: {
105
+ question,
106
+ answer: (answer) => {
107
+ const picked = pickedOptions(question, answer)[0];
108
+ const response = offered.find((option) => option.id === picked?.id)?.response;
109
+ // ZCode has no cancel for a permission: a request nobody answered is a denial of it.
110
+ return response ?? { decision: "deny", reason: CANCELLED_REASON };
111
+ },
112
+ },
113
+ };
114
+ }
115
+
116
+ /** A user input request as the questions to ask. */
117
+ export function readUserInput(request: RequestUserInputParams): ReadRequest<InputAsk> {
118
+ const common = { requestId: request.requestId, toolCallId: request.toolCallId };
119
+
120
+ const asked = request.questions;
121
+ if (asked === undefined) {
122
+ // The bare form: a prompt and a free text back.
123
+ const text: InputQuestion = {
124
+ key: "answer",
125
+ question: { kind: "text", title: request.prompt ?? request.toolName ?? "The agent asks for input" },
126
+ textOf: textAnswer,
127
+ };
128
+ return { ...common, ask: { questions: [text], answer: ([answer]) => ({ action: "accept", content: { answer: answer ?? "" } }) } };
129
+ }
130
+
131
+ const questions: InputQuestion[] = asked.map((entry) => {
132
+ const wording = { title: entry.question, detail: entry.header };
133
+ // A question whose one choice is "type your answer" is a free text.
134
+ if (entry.options.length === 1 && entry.options[0]?.value === FREE_TEXT_VALUE) {
135
+ return { key: entry.question, question: { kind: "text", ...wording }, textOf: textAnswer };
136
+ }
137
+ const options: QuestionOption[] = entry.options.map((option, index) => ({
138
+ id: choiceId(index),
139
+ label: option.label,
140
+ ...(option.description === undefined || option.description === "" ? {} : { description: option.description }),
141
+ flavor: "plain",
142
+ }));
143
+ const question: Question = { kind: entry.multiSelect === true ? "multi" : "choice", ...wording, options, allowOther: true };
144
+ return {
145
+ key: entry.question,
146
+ question,
147
+ // ZCode takes the value of a choice, which is its label for AskUserQuestion and something else for a plan or an MCP enum.
148
+ textOf: (answer) => {
149
+ if ("text" in answer) return answer.text;
150
+ const picked = pickedOptions(question, answer);
151
+ if (picked.length === 0) return undefined;
152
+ return picked.map((option) => entry.options[options.indexOf(option)]?.value ?? option.label).join(", ");
153
+ },
154
+ };
155
+ });
156
+ return {
157
+ ...common,
158
+ ask: {
159
+ questions,
160
+ answer: (texts) => ({ action: "accept", content: { answers: Object.fromEntries(questions.map((entry, index) => [entry.key, texts[index] ?? ""])) } }),
161
+ },
162
+ };
163
+ }
164
+
165
+ function textAnswer(answer: Answer): string | undefined {
166
+ return "text" in answer ? answer.text : undefined;
167
+ }
168
+
169
+ /** A user input request nobody answered: ZCode takes a cancel. */
170
+ export const INPUT_CANCELLED: InputAnswer = { action: "cancel" };
package/src/skills.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** Where ZCode reads skills from: the root shared by the agents that read `.agents/skills`. */
2
+
3
+ import { SHARED_AGENTS_SKILLS } from "@niwa-labs/harness";
4
+ import type { KindSkills } from "@niwa-labs/harness";
5
+
6
+ export const zcodeSkills: KindSkills = { kind: "zcode", roots: SHARED_AGENTS_SKILLS };