@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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * What the control side does with each message ZCode sends: a pure map from a message of the
3
+ * snapshot (`protocol/`) to an action, with no process in it. Every notification, every session
4
+ * event and every request of the snapshot is a case of an exhaustive `switch`: one the snapshot
5
+ * gains does not compile until someone decides what niwa does with it.
6
+ */
7
+
8
+ import { assertNever } from "@niwa-labs/core";
9
+
10
+ import type { Notification, RequestAnswer, RequestMethod, ServerRequest, SessionEvent } from "./protocol/index.ts";
11
+ import type { NotificationSessionEventTurnCompleted, RequestPermissionParams, RequestUserInputParams } from "./protocol/generated/zcode-protocol.ts";
12
+
13
+ /** How a turn ended, with the answer the server gave. */
14
+ export interface TurnEnd {
15
+ readonly outcome: "completed" | "cancelled" | "failed";
16
+ readonly response: string;
17
+ readonly error?: string;
18
+ }
19
+
20
+ /** What the control side does with a notification. */
21
+ export type EventAction =
22
+ /** The turn is over. */
23
+ | { readonly do: "end-turn"; readonly end: TurnEnd }
24
+ /** The server stopped waiting for a request: what it asked is no longer wanted. */
25
+ | { readonly do: "stop-asking"; readonly requestId: string | undefined; readonly toolCallId: string | undefined; readonly detail: string }
26
+ /** A sign of life, told in the session's log by `detail`. */
27
+ | { readonly do: "activity"; readonly detail: string }
28
+ /** Nothing: it means nothing to a session's driver. */
29
+ | { readonly do: "ignore" };
30
+
31
+ /** The words a turn that ended in error says: what the server gave as the kind of result. */
32
+ function turnEndOf(resultType: NonNullable<NotificationSessionEventTurnCompleted["payload"]>["resultType"] | undefined, response: string): TurnEnd {
33
+ switch (resultType) {
34
+ // A turn that says nothing of its result ended as turns do.
35
+ case undefined:
36
+ case "success":
37
+ return { outcome: "completed", response };
38
+ // A stopped turn is a normal end of ZCode's, reported as a completion.
39
+ case "cancelled":
40
+ return { outcome: "cancelled", response };
41
+ // The turn ran out of turns, budget or tool calls, or broke while it ran: its words are not an answer.
42
+ case "error_max_turns":
43
+ case "error_max_budget":
44
+ case "error_during_execution":
45
+ case "error_max_tool_calls":
46
+ return { outcome: "failed", response: "", error: `the turn ended with ${resultType}` };
47
+ default:
48
+ return assertNever(resultType, "turn result type");
49
+ }
50
+ }
51
+
52
+ /** What a session event comes to. The event of a subagent is told apart by the caller, which knows the session. */
53
+ export function sessionEventAction(event: SessionEvent): EventAction {
54
+ const sign: EventAction = { do: "activity", detail: event.type };
55
+ switch (event.type) {
56
+ case "turn.completed":
57
+ return { do: "end-turn", end: turnEndOf(event.payload?.resultType, event.payload?.response ?? "") };
58
+ case "turn.failed":
59
+ return { do: "end-turn", end: { outcome: "failed", response: "", error: event.payload?.error.message ?? "the turn failed" } };
60
+ // The server says it no longer waits for a request when it resolves it, by whom or why: that is all niwa sees of a cancel.
61
+ case "permission.resolved":
62
+ return { do: "stop-asking", requestId: event.payload?.requestId, toolCallId: event.payload?.toolCallId, detail: event.type };
63
+ case "userInput.resolved":
64
+ return { do: "stop-asking", requestId: event.payload?.requestId, toolCallId: undefined, detail: event.type };
65
+ // The rest are signs of life. The request a `*.requested` event announces comes as a request of its own, which is answered there.
66
+ case "session.created":
67
+ case "session.resumed":
68
+ case "session.updated":
69
+ case "session.titleUpdated":
70
+ case "session.closed":
71
+ case "turn.started":
72
+ case "turn.steerQueued":
73
+ case "turn.steerDrained":
74
+ case "message.upserted":
75
+ case "message.removed":
76
+ case "part.started":
77
+ case "part.delta":
78
+ case "part.upserted":
79
+ case "part.removed":
80
+ case "model.streaming":
81
+ case "tool.updated":
82
+ case "permission.requested":
83
+ case "userInput.requested":
84
+ case "checkpoint.created":
85
+ case "rewind.triggered":
86
+ case "streamRecovery.updated":
87
+ return sign;
88
+ default:
89
+ return assertNever(event, "session event");
90
+ }
91
+ }
92
+
93
+ /** What a notification comes to. */
94
+ export function notificationAction(notification: Notification): EventAction {
95
+ switch (notification.method) {
96
+ case "session/event":
97
+ return sessionEventAction(notification.params);
98
+ // The rest are not about a turn: the state of the process and the host's own views of it. A turn is seen by its events.
99
+ case "state.updated": // a patch of the state the host mirrors
100
+ case "session/lifecycle/changed": // the runtime of the session starting, stopping: the calls that wait for it say it
101
+ case "startup/pluginsDegraded": // plugins that did not start in time: the session does not need them
102
+ case "startup/storageState": // progress of the database migration before the session exists
103
+ case "interaction/providerRuntimeHeadersCancelled": // the end of a refresh of provider headers niwa never took up
104
+ case "process/mcpTelemetry": // the host's telemetry
105
+ case "process/mcpResourceSamples": // the host's resource view
106
+ case "process/toolExecResource": // the host's resource view
107
+ case "plugins/operationProgress": // the plugin manager's progress, of an operation niwa did not start
108
+ case "process/resourceSample": // the host's resource view
109
+ case "process/networkRequests": // the host's network capture
110
+ case "computer-use/operation-event": // the host's computer-use hints
111
+ return { do: "ignore" };
112
+ default:
113
+ return assertNever(notification, "notification");
114
+ }
115
+ }
116
+
117
+ /** What the control side needs to know of its session to answer a request. */
118
+ export interface RequestContext {
119
+ /** Whether a question goes to someone. A session with none has the server answer its questions itself, after a countdown. */
120
+ readonly asksQuestions: boolean;
121
+ }
122
+
123
+ /** What goes back to a request: the answer ZCode takes for its method, or the empty one for a method it does not know. */
124
+ export type Answered = RequestAnswer<RequestMethod> | Readonly<Record<string, never>>;
125
+
126
+ /** What the control side does with a request: ZCode waits for every one of them, or its turn waits forever. */
127
+ export type RequestAction =
128
+ | { readonly do: "answer"; readonly result: Answered }
129
+ /** A JSON-RPC error: niwa does not serve this. */
130
+ | { readonly do: "error"; readonly code: number; readonly message: string }
131
+ /** A question for whoever answers for the session. */
132
+ | { readonly do: "permission"; readonly params: RequestPermissionParams }
133
+ | { readonly do: "user-input"; readonly params: RequestUserInputParams };
134
+
135
+ /** JSON-RPC's "method not found": what a request niwa does not serve is answered with. */
136
+ const NOT_SERVED = -32601;
137
+ const refuse = (method: string): RequestAction => ({ do: "error", code: NOT_SERVED, message: `niwa does not serve ${method}` });
138
+
139
+ /** What a permission request the client could not read is answered with: no leave. */
140
+ const PERMISSION_UNREADABLE = { decision: "deny", reason: "niwa could not read this permission request" } satisfies RequestAnswer<"interaction/requestPermission">;
141
+
142
+ /** What a user input request the client could not read is answered with: declined. */
143
+ const INPUT_UNREADABLE = { action: "decline", reason: "niwa could not read this question" } satisfies RequestAnswer<"interaction/requestUserInput">;
144
+
145
+ /** What a request the snapshot does not know is answered with: an empty answer, which ZCode takes (the language of the reply, say). */
146
+ const EMPTY: Answered = {};
147
+
148
+ /** What a request of ZCode comes to; `undefined` stands for a method the snapshot does not know. */
149
+ export function requestAction(request: ServerRequest | undefined, context: RequestContext): RequestAction {
150
+ if (request === undefined) return { do: "answer", result: EMPTY };
151
+ switch (request.method) {
152
+ case "session/requestRuntimePreferences":
153
+ return {
154
+ do: "answer",
155
+ result: {
156
+ nativeSearchEnhancementsEnabled: false,
157
+ memoryEnabled: false,
158
+ // The server answers a question on its own after a countdown: a session whose questions are asked of someone gets no such answer.
159
+ askUserQuestionAutoResolutionEnabled: !context.asksQuestions,
160
+ modelContextBudgetStrategy: "preflight-v1",
161
+ } satisfies RequestAnswer<"session/requestRuntimePreferences">,
162
+ };
163
+ case "interaction/requestPermission":
164
+ return request.params === undefined ? { do: "answer", result: PERMISSION_UNREADABLE } : { do: "permission", params: request.params };
165
+ case "interaction/requestUserInput":
166
+ return request.params === undefined ? { do: "answer", result: INPUT_UNREADABLE } : { do: "user-input", params: request.params };
167
+ // niwa holds no credentials of ZCode's account: each of these is told so in the words its own answer has.
168
+ case "interaction/requestProviderRuntimeHeaders":
169
+ return { do: "answer", result: { headersApplied: false } satisfies RequestAnswer<"interaction/requestProviderRuntimeHeaders"> };
170
+ case "interaction/requestOfficialMcpAuthHeaders":
171
+ return { do: "answer", result: { ok: false, reason: "official_auth_unavailable" } satisfies RequestAnswer<"interaction/requestOfficialMcpAuthHeaders"> };
172
+ case "interaction/requestCredentialCipher":
173
+ return request.params === undefined
174
+ ? refuse(request.method)
175
+ : {
176
+ do: "answer",
177
+ result: {
178
+ requestId: request.params.requestId,
179
+ result: { ok: false, error: { code: "unavailable", message: "niwa holds no credential cipher" } },
180
+ } satisfies RequestAnswer<"interaction/requestCredentialCipher">,
181
+ };
182
+ // No browser is attached to a session niwa drives: an empty list says so, and a command has nowhere to go.
183
+ case "interaction/browserList":
184
+ return { do: "answer", result: { browsers: [] } satisfies RequestAnswer<"interaction/browserList"> };
185
+ case "interaction/browserExecute":
186
+ return refuse(request.method);
187
+ // The host's own services: niwa is not a host. The app-control intents are only offered to a session whose
188
+ // runtime preferences ask for them (`appControlEnabled`), and a bot's channel and topic resources are the host's.
189
+ case "subagents/readRuntimeConfig":
190
+ case "bot/channel/reply":
191
+ case "topic/resource/read":
192
+ case "appControl/listProjects":
193
+ case "appControl/listSessions":
194
+ case "appControl/readSession":
195
+ case "appControl/createSession":
196
+ case "appControl/forkSession":
197
+ case "appControl/sendToSession":
198
+ case "appControl/waitSessions":
199
+ case "appControl/interruptSession":
200
+ case "appControl/renameSession":
201
+ case "appControl/openSession":
202
+ case "appControl/setSessionArchived":
203
+ case "appControl/setSessionPinned":
204
+ case "appControl/cancel":
205
+ return refuse(request.method);
206
+ case "topic/resource/cancel":
207
+ return { do: "answer", result: { cancelled: false } satisfies RequestAnswer<"topic/resource/cancel"> };
208
+ default:
209
+ return assertNever(request, "request");
210
+ }
211
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The fixtures of the conformance suite for ZCode: the four scenarios written the way the harness
3
+ * writes them (format.ts, paths.ts). `home` is the directory the reading side is opened on.
4
+ *
5
+ * The database is a copy of the harness's own tables, with the columns the reading side uses, in
6
+ * rollback-journal mode so no `-wal` or `-shm` file is left behind.
7
+ */
8
+
9
+ import { mkdir, rm, writeFile } from "node:fs/promises";
10
+ import { dirname } from "node:path";
11
+
12
+ import { Database } from "bun:sqlite";
13
+
14
+ import { harnessId, sessionId } from "@niwa-labs/harness";
15
+ import type { FixtureResult, FixtureWriter, Scenario } from "@niwa-labs/harness";
16
+
17
+ import { dbPathOf } from "./paths.ts";
18
+
19
+ /** The installation id the fixtures are written for; the suite opens its reading side with it. */
20
+ export const FIXTURE_HARNESS = harnessId("zcode");
21
+
22
+ const SCHEMA = [
23
+ `create table session (id text primary key, project_id text not null, directory text not null, title text not null,
24
+ title_source text not null, parent_id text, time_created integer not null, time_updated integer not null, time_deleted integer)`,
25
+ `create table message (id text primary key, session_id text not null, time_created integer not null,
26
+ time_updated integer not null, data text not null, sequence integer)`,
27
+ `create table part (id text primary key, message_id text not null, session_id text not null,
28
+ time_created integer not null, time_updated integer not null, data text not null, sequence integer)`,
29
+ `create table local_setting (scope text not null, scope_id text not null, namespace text not null, key text not null,
30
+ value text not null, schema_version integer not null, time_created integer not null, time_updated integer not null,
31
+ primary key(scope, scope_id, namespace, key))`,
32
+ ];
33
+
34
+ /** The session as a database of the harness holds it, and what the tests write into it. */
35
+ export function createDatabase(path: string): Database {
36
+ const db = new Database(path, { create: true });
37
+ for (const statement of SCHEMA) db.run(statement);
38
+ return db;
39
+ }
40
+
41
+ /** One message of a session: its row, and the rows of its parts. */
42
+ export interface FixtureMessage {
43
+ readonly id: string;
44
+ readonly data: Record<string, unknown>;
45
+ /** The JSON of each part; a string is written as it is, so a part that is not JSON can be made. */
46
+ readonly parts: ReadonlyArray<Record<string, unknown> | string>;
47
+ }
48
+
49
+ /** Writes a session with its messages, in the order given. `at` is the time of the first message. */
50
+ export function writeSession(
51
+ db: Database,
52
+ native: string,
53
+ messages: readonly FixtureMessage[],
54
+ options: { readonly directory?: string; readonly parent?: string; readonly at?: number; readonly title?: string; readonly project?: string } = {},
55
+ ): void {
56
+ const at = options.at ?? 1_000;
57
+ db.query(
58
+ "insert into session (id, project_id, directory, title, title_source, parent_id, time_created, time_updated) values (?, ?, ?, ?, 'generated', ?, ?, ?)",
59
+ ).run(native, options.project ?? "p", options.directory ?? "/work/zcode", options.title ?? `title of ${native}`, options.parent ?? null, at, at + messages.length * 10);
60
+ const insertMessage = db.query(
61
+ "insert into message (id, session_id, time_created, time_updated, data, sequence) values (?, ?, ?, ?, ?, ?)",
62
+ );
63
+ const insertPart = db.query(
64
+ "insert into part (id, message_id, session_id, time_created, time_updated, data, sequence) values (?, ?, ?, ?, ?, ?, ?)",
65
+ );
66
+ for (const [index, message] of messages.entries()) {
67
+ const created = at + index * 10;
68
+ insertMessage.run(message.id, native, created, created, JSON.stringify(message.data), index);
69
+ for (const [place, part] of message.parts.entries()) {
70
+ insertPart.run(`${message.id}_part${place}`, message.id, native, created, created, typeof part === "string" ? part : JSON.stringify(part), place);
71
+ }
72
+ }
73
+ }
74
+
75
+ export const user = (id: string, text: string): FixtureMessage => ({
76
+ id,
77
+ data: { role: "user", time: { created: 1000 }, semantics: { uiVisibility: "visible" } },
78
+ parts: [{ type: "text", text, time: { start: 1000, end: 1000 } }],
79
+ });
80
+
81
+ export const assistant = (id: string, text: string, completed = true): FixtureMessage => ({
82
+ id,
83
+ data: {
84
+ role: "assistant",
85
+ time: completed ? { created: 2000, completed: 2100 } : { created: 2000 },
86
+ modelId: "fixture-model",
87
+ providerId: "fixture",
88
+ },
89
+ parts: [{ type: "text", text, time: { start: 2000 } }],
90
+ });
91
+
92
+ export const writeZcodeFixtures: FixtureWriter = async (home, scenario) => {
93
+ const native = `sess_fixture-${scenario}`;
94
+ const path = dbPathOf(home);
95
+ await mkdir(dirname(path), { recursive: true });
96
+ const db = createDatabase(path);
97
+ try {
98
+ writeSession(db, native, messagesOf(scenario), { at: 1_000 });
99
+ if (scenario === "nested") {
100
+ writeSession(db, "sess_subagent_agent_fixture", [user("child_user", "work")], { parent: native, at: 1_000 + 25 });
101
+ }
102
+ } finally {
103
+ db.close();
104
+ }
105
+
106
+ const result: FixtureResult = {
107
+ session: sessionId(FIXTURE_HARNESS, native),
108
+ ...(scenario === "nested" ? { child: sessionId(FIXTURE_HARNESS, "sess_subagent_agent_fixture") } : {}),
109
+ ...(scenario === "compaction" ? { summary: "what happened so far" } : {}),
110
+ ...(scenario === "running"
111
+ ? {
112
+ finish: async () => {
113
+ const writable = new Database(path);
114
+ try {
115
+ writable
116
+ .query("update message set data = ? where id = 'm_final'")
117
+ .run(JSON.stringify({ ...assistant("m_final", "").data, time: { created: 2000, completed: 2100 } }));
118
+ } finally {
119
+ writable.close();
120
+ }
121
+ },
122
+ }
123
+ : {}),
124
+ makeUnreadable: () => writeFile(path, "this is not a database"),
125
+ remove: () => rm(path, { force: true }),
126
+ };
127
+ return result;
128
+ };
129
+
130
+ function messagesOf(scenario: Scenario): FixtureMessage[] {
131
+ const start = [user("m_user", "hello"), assistant("m_answer", "hi there")];
132
+ switch (scenario) {
133
+ case "running":
134
+ return [...start, assistant("m_final", "the finished answer", false)];
135
+ case "nested":
136
+ return [
137
+ ...start,
138
+ {
139
+ id: "m_tool",
140
+ data: { role: "assistant", time: { created: 2000, completed: 2100 } },
141
+ parts: [
142
+ {
143
+ type: "tool",
144
+ callID: "call_1",
145
+ tool: "Agent",
146
+ state: { status: "completed", input: { prompt: "work" }, output: "done", time: { start: 2000, end: 2100 } },
147
+ },
148
+ ],
149
+ },
150
+ ];
151
+ case "compaction":
152
+ return [
153
+ ...start,
154
+ {
155
+ id: "m_summary",
156
+ data: { role: "user", time: { created: 3000 }, summary: { title: "Compact summary", body: "what happened so far" } },
157
+ parts: [{ type: "text", text: "This session is being continued from a previous conversation." }],
158
+ },
159
+ {
160
+ id: "m_boundary",
161
+ data: { role: "assistant", time: { created: 3000, completed: 3000 } },
162
+ parts: [{ type: "compaction", summaryMessageId: "m_summary", time: { start: 3000, end: 3000 } }],
163
+ },
164
+ ];
165
+ case "broken":
166
+ return [
167
+ ...start,
168
+ {
169
+ id: "m_odd",
170
+ data: { role: "assistant", time: { created: 3000, completed: 3000 } },
171
+ parts: [{ type: "frobnicate", shape: "unfamiliar" }, "not json at all"],
172
+ },
173
+ ];
174
+ }
175
+ }
package/src/format.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The native format of a ZCode session: what its rows say.
3
+ *
4
+ * A session is three tables. `session` is the session itself; `message` holds its messages in
5
+ * `sequence` order, the JSON in `data` saying who spoke and when; `part` holds what a message is
6
+ * made of, again in `sequence` order, one JSON per part. A part is text, a thought, a call of a
7
+ * tool together with its result, a compaction mark, a file, or a marker of the harness's own
8
+ * (`step-start`, `step-finish`, `timeline`) that is not conversation. Nothing here touches the disk.
9
+ *
10
+ * The part types are all thirteen of ZCode's `MessagePart`. ZCode has no schema for them: it keeps
11
+ * them as TypeScript interfaces (`apps/zcode-cli/packages/contracts/src/interfaces/session-store.port.ts`,
12
+ * ZCode 3.18.2, commit fec975905a2abd4c07e35c40d51fa097a2258ec9), and what it writes to a row is not
13
+ * checked, so the union below is written by hand from them, with objects that are loose and require
14
+ * only what the reader uses. (The part of the wire protocol, `zcodeMessagePartSchema`, is another shape of
15
+ * them: `callId` and `startedAt` where a row has `callID` and `time.start`.)
16
+ */
17
+
18
+ import { z } from "zod";
19
+
20
+ /** The message JSON: what the reading side needs of it, the rest is kept as it was. */
21
+ export const MessageDataSchema = z.looseObject({
22
+ role: z.string(),
23
+ time: z.looseObject({ created: z.number().optional(), completed: z.number().optional() }).optional(),
24
+ modelId: z.string().optional(),
25
+ modelID: z.string().optional(),
26
+ providerId: z.string().optional(),
27
+ providerID: z.string().optional(),
28
+ /** Set on the message that carries the summary a compaction left. */
29
+ summary: z.looseObject({ body: z.string().optional() }).optional(),
30
+ metadata: z.looseObject({ visibility: z.string().optional() }).optional(),
31
+ semantics: z.looseObject({ uiVisibility: z.string().optional() }).optional(),
32
+ });
33
+ export type MessageData = z.output<typeof MessageDataSchema>;
34
+
35
+ const TimeSchema = z.looseObject({ start: z.number().optional(), end: z.number().optional() });
36
+
37
+ const TextPartSchema = z.looseObject({
38
+ type: z.literal("text"),
39
+ text: z.string(),
40
+ synthetic: z.boolean().optional(),
41
+ time: TimeSchema.optional(),
42
+ });
43
+
44
+ const ReasoningPartSchema = z.looseObject({
45
+ type: z.literal("reasoning"),
46
+ text: z.string().optional(),
47
+ time: TimeSchema.optional(),
48
+ });
49
+
50
+ const ToolPartSchema = z.looseObject({
51
+ type: z.literal("tool"),
52
+ callID: z.string().min(1),
53
+ tool: z.string().min(1),
54
+ state: z.looseObject({
55
+ status: z.string().optional(),
56
+ input: z.unknown().optional(),
57
+ output: z.unknown().optional(),
58
+ error: z.unknown().optional(),
59
+ time: TimeSchema.optional(),
60
+ }),
61
+ });
62
+
63
+ const CompactionPartSchema = z.looseObject({
64
+ type: z.literal("compaction"),
65
+ summaryMessageId: z.string().optional(),
66
+ });
67
+
68
+ /** A part of which the reader needs only the type: it is not conversation, or it is kept whole. */
69
+ const bare = <T extends string>(type: T) => z.looseObject({ type: z.literal(type) });
70
+
71
+ /** Every part type ZCode writes; the reading side says what each comes to. */
72
+ export const PartDataSchema = z.discriminatedUnion("type", [
73
+ TextPartSchema,
74
+ ReasoningPartSchema,
75
+ bare("file"),
76
+ bare("agent"),
77
+ CompactionPartSchema,
78
+ bare("timeline"),
79
+ bare("subtask"),
80
+ bare("retry"),
81
+ bare("step-start"),
82
+ bare("step-finish"),
83
+ bare("snapshot"),
84
+ bare("patch"),
85
+ ToolPartSchema,
86
+ ]);
87
+ export type PartData = z.output<typeof PartDataSchema>;
88
+
89
+ /** The part types of the union: the reading side's mapping has a case for each. */
90
+ export const PART_TYPES = PartDataSchema.options.map((option) => option.shape.type.value);
91
+
92
+ /** What a part's JSON is, as the reading side takes it. */
93
+ export type ReadPart = { readonly kind: "part"; readonly part: PartData } | { readonly kind: "unknown"; readonly raw: unknown };
94
+
95
+ /**
96
+ * Reads the JSON of a part; a part that is not JSON, whose type ZCode has since added, or whose shape is
97
+ * not one the reader can use, is `unknown` with what it was.
98
+ */
99
+ export function readPart(text: string): ReadPart {
100
+ let value: unknown;
101
+ try {
102
+ value = JSON.parse(text);
103
+ } catch {
104
+ return { kind: "unknown", raw: text };
105
+ }
106
+ const parsed = PartDataSchema.safeParse(value);
107
+ return parsed.success ? { kind: "part", part: parsed.data } : { kind: "unknown", raw: value };
108
+ }
109
+
110
+ /** Reads the JSON of a message; `undefined` when it is not one a reader can use. */
111
+ export function readMessage(text: string): MessageData | undefined {
112
+ try {
113
+ const parsed = MessageDataSchema.safeParse(JSON.parse(text));
114
+ return parsed.success ? parsed.data : undefined;
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ /** Whether a message is what a person said: not the harness's own injection or a summary. */
121
+ export function isHumanMessage(message: MessageData): boolean {
122
+ return (
123
+ message.role === "user" &&
124
+ message.summary === undefined &&
125
+ message.metadata?.visibility !== "model-only" &&
126
+ message.semantics?.uiVisibility !== "hidden"
127
+ );
128
+ }
129
+
130
+ /** The model an assistant message names: `providerId/modelId`, or the model alone. */
131
+ export function modelOf(message: MessageData): string | undefined {
132
+ const model = message.modelId ?? message.modelID;
133
+ if (model === undefined) return undefined;
134
+ const provider = message.providerId ?? message.providerID;
135
+ return provider === undefined ? model : `${provider}/${model}`;
136
+ }
137
+
138
+ /** The result of a tool part: its error when it failed, else its output. */
139
+ export function resultOf(part: z.output<typeof ToolPartSchema>): unknown {
140
+ return part.state.status === "error" ? (part.state.error ?? part.state.output) : part.state.output;
141
+ }
142
+
143
+ /** Whether a tool part is still being worked on. */
144
+ export function isRunning(part: z.output<typeof ToolPartSchema>): boolean {
145
+ return part.state.status === "running" || part.state.status === "pending";
146
+ }
147
+
148
+ /** Whole milliseconds, or `undefined` when the value is not a usable time. */
149
+ export function millisOf(value: unknown): number | undefined {
150
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
151
+ const whole = Math.max(0, Math.floor(value));
152
+ return Number.isSafeInteger(whole) ? whole : undefined;
153
+ }
package/src/index.ts ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The ZCode harness kind.
3
+ *
4
+ * It serves the reading side and the control side. The reading side reads the SQLite database
5
+ * ZCode writes; the control side drives ZCode over `zcode app-server --stdio`. It has no insert
6
+ * side.
7
+ */
8
+
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ import { ADMITTED, NO_INSERT, NoOptions, UNSUPPORTED, VERIFIED, defineHarnessKind, kindOptions } from "@niwa-labs/harness";
13
+ import type { HarnessBinding, InstanceOptions, KindCapabilities, SideCapabilities } from "@niwa-labs/harness";
14
+
15
+ import { ZCODE_LAUNCH, zcodeControl } from "./control.ts";
16
+ import type { ZcodeControlOptions } from "./control.ts";
17
+ import { ZcodeReading } from "./reading.ts";
18
+
19
+ export { ZcodeReading } from "./reading.ts";
20
+ export type { ZcodeReadingOptions } from "./reading.ts";
21
+ export { zcodeControl } from "./control.ts";
22
+ export type { ZcodeControlOptions, ZcodeMcpOptions, ZcodePermissionPolicy, ZcodeSessionControl } from "./control.ts";
23
+
24
+ /**
25
+ * The sides a ZCode instance has by default.
26
+ *
27
+ * The reading side lists and reads the sessions in the database; it does not follow a session
28
+ * while it grows. The control side starts, resumes, sends, interrupts and asks; the session is
29
+ * asked for JSON that matches the schema and the control side validates the answer: `ask` returns
30
+ * a value that passed the schema.
31
+ */
32
+ export const zcodeSides: SideCapabilities = {
33
+ reading: { list: true, read: true, watch: false },
34
+ control: {
35
+ start: true,
36
+ resume: true,
37
+ send: true,
38
+ interrupt: true,
39
+ ask: true,
40
+ structuredOutput: true,
41
+ launch: ZCODE_LAUNCH,
42
+ tools: { niwaOnly: true, allow: true },
43
+ },
44
+ };
45
+
46
+ /** What the kind declares it can serve, proved against a live ZCode. */
47
+ export const ZCODE_CAPABILITIES: KindCapabilities = {
48
+ reading: { list: VERIFIED, read: VERIFIED, watch: UNSUPPORTED },
49
+ control: {
50
+ start: VERIFIED,
51
+ resume: VERIFIED,
52
+ send: VERIFIED,
53
+ interrupt: VERIFIED,
54
+ ask: VERIFIED,
55
+ structuredOutput: VERIFIED,
56
+ launch: { model: VERIFIED, effort: ZCODE_LAUNCH.effort, modes: ZCODE_LAUNCH.modes },
57
+ tools: { niwaOnly: ADMITTED, allow: ADMITTED },
58
+ },
59
+ insert: NO_INSERT,
60
+ };
61
+
62
+ /** The block a ZCode session takes at its start: `zcode`, with no option of its own yet. */
63
+ export const ZCODE_OPTIONS = kindOptions("zcode", NoOptions);
64
+
65
+ /** How a ZCode installation is found: the program that runs it, and the directory it keeps its sessions in. */
66
+ const ZCODE_DETECTION = {
67
+ binary: "zcode",
68
+ home: "~/.zcode",
69
+ } as const;
70
+
71
+ /** What an installation of ZCode is given: its id, home and model, and how its control side is set up. */
72
+ export interface ZcodeInstanceOptions extends InstanceOptions {
73
+ /**
74
+ * How the control side is set up: the reasoning level, what it does with a permission request,
75
+ * the binary it drives and the ZCode fields of its MCP servers. Its own defaults are used when it
76
+ * is absent. The model of the installation (`model`) is a `providerId/modelId`.
77
+ */
78
+ readonly control?: Omit<ZcodeControlOptions, "harness" | "home" | "model">;
79
+ }
80
+
81
+ /** What the caller names of one installation: every part has a default. */
82
+ export type ZcodeOptions = Partial<ZcodeInstanceOptions>;
83
+
84
+ /**
85
+ * The kind "zcode". Each installation is bound to its own home (default `~/.zcode`): its sessions
86
+ * are read from the database there, and its processes keep their sessions there.
87
+ */
88
+ export const zcodeKind = defineHarnessKind<ZcodeInstanceOptions>({
89
+ name: "zcode",
90
+ capabilities: ZCODE_CAPABILITIES,
91
+ implements: ["reading", "control"],
92
+ sides: zcodeSides,
93
+ detect: ZCODE_DETECTION,
94
+ options: ZCODE_OPTIONS,
95
+ home: () => join(homedir(), ".zcode"),
96
+ // Its launcher, the runtime it runs on, and its home (sessions, their database, sign-in and
97
+ // configuration). Its model endpoint depends on the provider: the installation names it (`net`).
98
+ profile: {
99
+ status: "admitted",
100
+ of: ({ home, control }) => ({ bin }) => ({
101
+ read: [...bin(control?.binary ?? "zcode"), ...bin("node")],
102
+ write: [home],
103
+ }),
104
+ },
105
+ bind: ({ id, home, model, control }) => ({
106
+ reading: new ZcodeReading({ harness: id, home }),
107
+ control: zcodeControl({ harness: id, home, ...(control ?? {}), ...(model === undefined ? {} : { model }) }),
108
+ }),
109
+ });
110
+
111
+ /** One installation of ZCode: `zcode` at `~/.zcode` unless the options say otherwise. */
112
+ export function zcode(options: ZcodeOptions = {}): HarnessBinding {
113
+ return zcodeKind.bind({ ...options, id: options.id ?? "zcode" });
114
+ }
115
+
116
+ export { zcodeSkills } from "./skills.ts";
package/src/paths.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Where a ZCode installation keeps its sessions: one SQLite database, `<home>/cli/db/db.sqlite`.
3
+ * The desktop app and the CLI share it, and `~/.zai` holds the same layout under another root.
4
+ */
5
+
6
+ import { join } from "node:path";
7
+
8
+ /** The database of an installation. */
9
+ export function dbPathOf(home: string): string {
10
+ return join(home, "cli", "db", "db.sqlite");
11
+ }
12
+
13
+ /** The user's config file of an installation: `<home>/cli/config.json`, ZCode's default `~/.zcode/cli/config.json`. */
14
+ export function configPathOf(home: string): string {
15
+ return join(home, "cli", "config.json");
16
+ }
17
+
18
+ /** The ids ZCode gives its sessions: `sess_<uuid>`, and `sess_subagent_agent_<uuid>` for a subagent. */
19
+ export function isSessionName(name: string): boolean {
20
+ return /^sess_[A-Za-z0-9_-]+$/.test(name);
21
+ }