@niwa-labs/cli 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/log.ts ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * log.ts — `niwa log`: the journal as a person reads a log, like `journalctl` or `kubectl logs`.
3
+ *
4
+ * Every filter is one of the filters of `niwa.records.search`, so what the CLI shows and what an
5
+ * MCP client or a script reads for the same filter are the same records. Following is a read that
6
+ * waits for a commit, again and again; nothing in the CLI watches the journal itself.
7
+ *
8
+ * niwa log the last 20 records, without the noise
9
+ * niwa log -f --run run-1a2b what the run does, as it does it
10
+ * niwa log --type 'workflow.*' --since 10m
11
+ */
12
+
13
+ import { z } from "zod";
14
+
15
+ import { RECORDS_READ_ACTION, RECORDS_SEARCH_ACTION, storedRecordSchema } from "@niwa-labs/client";
16
+ import type { RecordFilterInput, Seq, StoredRecord } from "@niwa-labs/core";
17
+ import type { NiwaApi } from "@niwa-labs/client";
18
+ import { seq, resolveId } from "@niwa-labs/core";
19
+ import { logLine } from "./render.ts";
20
+
21
+ /** What the command line of `niwa log` said. */
22
+ interface LogOptions {
23
+ tail: number | undefined;
24
+ limit: number | undefined;
25
+ follow: boolean;
26
+ waitMs: number | undefined;
27
+ from: number;
28
+ stream: string | undefined;
29
+ filter: RecordFilterInput;
30
+ json: boolean;
31
+ }
32
+
33
+ /** What a read answers with, as the wire carries it. */
34
+ const Read = z.object({ records: z.array(storedRecordSchema), next: z.number() });
35
+
36
+ /** The record a session niwa started is named in: its pair, and the id niwa gave it. */
37
+ const SessionStarted = z.object({ session: z.string(), id: z.string() });
38
+
39
+ /**
40
+ * The ids niwa gave the sessions it started, by their pair, as the journal holds them now.
41
+ *
42
+ * The records of a session name it by its pair; a line names it by its id, and `--session` takes it.
43
+ */
44
+ async function sessionIdsOf(api: NiwaApi): Promise<Map<string, string>> {
45
+ const found = Read.parse(await api.call(RECORDS_READ_ACTION, { from: 0, types: ["session.started"] }));
46
+ const ids = new Map<string, string>();
47
+ for (const record of found.records) {
48
+ const started = SessionStarted.safeParse(record.data);
49
+ if (started.success) ids.set(started.data.session, started.data.id);
50
+ }
51
+ return ids;
52
+ }
53
+
54
+ /**
55
+ * The pair `--session` stands for: the session whose id the text is, or the start or the end of.
56
+ * A text that names no id is taken as it is: the pair, or the start of the harness's own id.
57
+ */
58
+ function sessionFilterOf(text: string, ids: ReadonlyMap<string, string>): string {
59
+ const named = resolveId(text, [...ids.values()], "session");
60
+ return named === undefined ? text : ([...ids].find(([, id]) => id === named)?.[0] ?? text);
61
+ }
62
+
63
+ /** The records that say what niwa did rather than what happened: shown with `--all`. */
64
+ const NOISE = ["!session.activity", "!niwa.step.decision", "!niwa.step.intent", "!niwa.subscription.position"];
65
+
66
+ /** The number of records a bare `niwa log` shows. */
67
+ const DEFAULT_TAIL = 20;
68
+
69
+ /** How long a follow waits for a commit before it asks again. */
70
+ const POLL_MS = 30_000;
71
+
72
+ const UNITS: Readonly<Record<string, number>> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
73
+
74
+ /** The usage line of `niwa log`, for the errors that name it. */
75
+ export const LOG_USAGE =
76
+ "niwa log [-n N] [-f] [--run ID] [--session ID] [--request ID] [--task ID] [--type T]... [--actor A] [--stream S] " +
77
+ "[--grep TEXT] [--since SEQ|10m] [--until SEQ|10m] [--limit N] [--wait-ms N] [--all] [--json]";
78
+
79
+ /** A wrong command line of `niwa log`. */
80
+ export class LogUsage extends Error {
81
+ override name = "LogUsage";
82
+ }
83
+
84
+ function numberOf(name: string, text: string | undefined): number {
85
+ const value = Number(text);
86
+ if (text === undefined || !Number.isInteger(value) || value < 1) throw new LogUsage(`${name} needs a positive integer, got "${String(text)}"`);
87
+ return value;
88
+ }
89
+
90
+ /** A position, or a span of time before now: `120` is the position 120, `10m` is ten minutes ago. */
91
+ function pointOf(name: string, text: string | undefined, now: number): { seq: number } | { at: number } {
92
+ const unit = /^(\d+)(ms|s|m|h|d)$/.exec(text ?? "");
93
+ if (unit !== null) return { at: now - Number(unit[1]) * (UNITS[unit[2] ?? "ms"] ?? 1) };
94
+ const position = Number(text);
95
+ if (text === undefined || !Number.isInteger(position) || position < 0) {
96
+ throw new LogUsage(`${name} needs a position or a span of time (120, 10m, 2h), got "${String(text)}"`);
97
+ }
98
+ return { seq: position };
99
+ }
100
+
101
+ function optionsOf(args: readonly string[], json: boolean, now: number): LogOptions {
102
+ const types: string[] = [];
103
+ const filter: { -readonly [K in keyof RecordFilterInput]: RecordFilterInput[K] } = {};
104
+ const options: LogOptions = { tail: undefined, limit: undefined, follow: false, waitMs: undefined, from: 0, stream: undefined, filter, json };
105
+ let all = false;
106
+ let since = false;
107
+ for (let index = 0; index < args.length; index += 1) {
108
+ const argument = args[index] ?? "";
109
+ const takes = (): string => {
110
+ const value = args[index + 1];
111
+ if (value === undefined) throw new LogUsage(`${argument} needs a value`);
112
+ index += 1;
113
+ return value;
114
+ };
115
+ switch (argument) {
116
+ case "-n": options.tail = numberOf("-n", takes()); break;
117
+ case "-f": options.follow = true; break;
118
+ case "--json": options.json = true; break;
119
+ case "--all": all = true; break;
120
+ case "--limit": options.limit = numberOf("--limit", takes()); break;
121
+ case "--wait-ms": options.waitMs = numberOf("--wait-ms", takes()); break;
122
+ case "--stream": options.stream = takes(); break;
123
+ case "--type": types.push(takes()); break;
124
+ case "--run": filter.run = takes(); break;
125
+ case "--session": filter.session = takes(); break;
126
+ case "--request": filter.request = takes(); break;
127
+ case "--task": filter.task = takes(); break;
128
+ case "--actor": filter.actor = takes(); break;
129
+ case "--grep": filter.grep = takes(); break;
130
+ case "--since": {
131
+ const point = pointOf("--since", takes(), now);
132
+ since = true;
133
+ if ("seq" in point) options.from = point.seq;
134
+ else filter.after = point.at;
135
+ break;
136
+ }
137
+ case "--until": {
138
+ const point = pointOf("--until", takes(), now);
139
+ if ("seq" in point) filter.until = point.seq;
140
+ else filter.before = point.at;
141
+ break;
142
+ }
143
+ default:
144
+ throw new LogUsage(`unexpected argument "${argument}"; usage: ${LOG_USAGE}`);
145
+ }
146
+ }
147
+ // The noise is hidden unless the records were asked for by type or `--all` asked for everything.
148
+ if (types.length === 0 && !all) types.push(...NOISE);
149
+ if (types.length > 0) filter.types = types;
150
+ // Without a span or a count, the last records; with a span, all that it holds.
151
+ if (options.tail === undefined && !since && filter.after === undefined && options.limit === undefined) options.tail = DEFAULT_TAIL;
152
+ return options;
153
+ }
154
+
155
+ /** Run `niwa log`: print what it was asked for, and with `-f` go on printing. */
156
+ export async function log(
157
+ api: NiwaApi,
158
+ args: readonly string[],
159
+ json: boolean,
160
+ width: number,
161
+ out: (text: string) => void,
162
+ ): Promise<void> {
163
+ const options = optionsOf(args, json, Date.now());
164
+ const sessions = await sessionIdsOf(api);
165
+ if (options.filter.session !== undefined) options.filter.session = sessionFilterOf(options.filter.session, sessions);
166
+ const read = async (from: Seq, extra: { tail?: number; limit?: number; waitMs?: number }) =>
167
+ Read.parse(
168
+ await api.call(RECORDS_SEARCH_ACTION, {
169
+ from,
170
+ filter: options.filter,
171
+ ...(options.stream === undefined ? {} : { stream: options.stream }),
172
+ ...extra,
173
+ }),
174
+ );
175
+ const show = (records: readonly StoredRecord[]): void => {
176
+ for (const record of records) {
177
+ const started = record.type === "session.started" ? SessionStarted.safeParse(record.data) : undefined;
178
+ if (started?.success === true) sessions.set(started.data.session, started.data.id);
179
+ out(options.json ? JSON.stringify(record) : logLine(record, width, sessions));
180
+ }
181
+ };
182
+
183
+ const first = await read(seq(options.from), {
184
+ ...(options.tail === undefined ? {} : { tail: options.tail }),
185
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
186
+ });
187
+ show(first.records);
188
+ if (!options.follow) return;
189
+
190
+ let from = seq(first.next);
191
+ let shown = first.records.length;
192
+ while (options.limit === undefined || shown < options.limit) {
193
+ const more = await read(from, {
194
+ waitMs: options.waitMs ?? POLL_MS,
195
+ ...(options.limit === undefined ? {} : { limit: options.limit - shown }),
196
+ });
197
+ show(more.records);
198
+ shown += more.records.length;
199
+ from = seq(more.next);
200
+ // With `--wait-ms` the follow ends when nothing came in that time: for a caller that is not a person at a terminal.
201
+ if (more.records.length === 0 && options.waitMs !== undefined) return;
202
+ }
203
+ }
package/src/render.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * render.ts — printing records, traces and requests.
3
+ *
4
+ * Two ways to print: what a person reads, and what a machine reads. The human form is the
5
+ * default; `--json` asks for the machine form. Both come from the same value, so the two never
6
+ * disagree about what happened.
7
+ *
8
+ * The human form is deliberately plain: a line per record, the data on one line, nothing that
9
+ * needs a terminal to understand. A person reads it in a terminal and a script reads it in a
10
+ * pipe, and neither needs the other.
11
+ */
12
+
13
+ import type { z } from "zod";
14
+
15
+ import { shortForm } from "@niwa-labs/core";
16
+ import type { StatusOutput, DescriptionAnswer, RecordAnswer, TracedRecordAnswer } from "@niwa-labs/client";
17
+ import type { JsonSchema } from "@niwa-labs/core";
18
+
19
+ /** How something is printed. */
20
+ export type Format = "text" | "json";
21
+
22
+ /** The value of one field, as it is printed. */
23
+ function field(value: unknown): string {
24
+ if (value === undefined) return "";
25
+ if (value === null) return "null";
26
+ if (typeof value === "string") return value;
27
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
28
+ return JSON.stringify(value);
29
+ }
30
+
31
+ /** One record as a person reads it: the position, the type, and what it says. */
32
+ export function recordLine(record: RecordAnswer): string {
33
+ const who = record.actor.kind === "host" ? "host" : record.actor.kind;
34
+ return `${String(record.seq).padStart(6)} ${record.type} ${who} ${field(record.data)}`;
35
+ }
36
+
37
+ /** The records, one per line. */
38
+ export function renderRecords(records: RecordAnswer[]): string {
39
+ if (records.length === 0) return "no records";
40
+ return records.map(recordLine).join("\n");
41
+ }
42
+
43
+ /** One traced record: how deep it was found. */
44
+ export function tracedLine(record: TracedRecordAnswer): string {
45
+ return `${" ".repeat(record.depth)}${recordLine(record)}`;
46
+ }
47
+
48
+ /** The trace, one record per line, deeper first. */
49
+ export function renderTrace(records: TracedRecordAnswer[]): string {
50
+ if (records.length === 0) return "nothing grew from that record";
51
+ return records.map(tracedLine).join("\n");
52
+ }
53
+
54
+ /** The fields of an input schema, with their types. */
55
+ export function fieldsOf(schema: JsonSchema): string[] {
56
+ const properties = (schema as { properties?: Record<string, unknown> }).properties;
57
+ if (properties === undefined) return [];
58
+ const required = (schema as { required?: string[] }).required ?? [];
59
+ return Object.entries(properties).map(([name, value]) => {
60
+ const type = (value as { type?: unknown }).type;
61
+ const shown = typeof type === "string" ? type : "any";
62
+ return required.includes(name) ? `${name}: ${shown}` : `${name}?: ${shown}`;
63
+ });
64
+ }
65
+
66
+ /** One action of the description, as a person reads it. */
67
+ export function actionLine(action: DescriptionAnswer["actions"][number]): string {
68
+ const fields = fieldsOf(action.input);
69
+ const shown = fields.length === 0 ? "no fields" : fields.join(", ");
70
+ return `${action.name}\n ${action.description}\n fields: ${shown} recovery: ${action.recovery}`;
71
+ }
72
+
73
+ /** The description, as a person reads it. */
74
+ export function renderDescription(description: DescriptionAnswer): string {
75
+ const lines: string[] = ["actions:"];
76
+ for (const action of description.actions) lines.push(` ${actionLine(action)}`);
77
+ lines.push("types:");
78
+ for (const record of description.types) {
79
+ lines.push(` ${record.name} (v${String(record.version)})`);
80
+ }
81
+ return lines.join("\n");
82
+ }
83
+
84
+ /**
85
+ * The value of a command, in the format that was asked for.
86
+ *
87
+ * The machine form is the value itself: the same JSON the host returned, so a script sees the
88
+ * facts and not a rendering of them.
89
+ */
90
+ export function renderValue(value: unknown, format: Format): string {
91
+ if (format === "json") return JSON.stringify(value, null, 2);
92
+ if (value === null || value === undefined) return "";
93
+ if (typeof value === "string") return shortForm(value);
94
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
95
+ if (Array.isArray(value)) {
96
+ return value.map((item) => renderValue(item, format)).join("\n");
97
+ }
98
+ if (typeof value === "object") {
99
+ const holder = value as Record<string, unknown>;
100
+ const lines: string[] = [];
101
+ for (const [key, item] of Object.entries(holder)) {
102
+ lines.push(`${key}: ${renderValue(item, format)}`);
103
+ }
104
+ return lines.join("\n");
105
+ }
106
+ return String(value);
107
+ }
108
+
109
+ /** The status of the host: one line for the host, one for each plugin that counts something. */
110
+ export function renderStatus(status: z.infer<typeof StatusOutput>): string {
111
+ const counts = (summary: Record<string, number>): string =>
112
+ Object.entries(summary).map(([name, count]) => `${name}=${String(count)}`).join(" ");
113
+ return [
114
+ `up pid ${String(status.pid)} ${status.home} journal seq ${String(status.seq)}`,
115
+ ...status.plugins.map((plugin) => `${plugin.name} ${plugin.summary === undefined ? "" : counts(plugin.summary)}`.trimEnd()),
116
+ ].join("\n");
117
+ }
118
+
119
+ /** The kinds of subject a line names, in the order it names them. */
120
+ const SUBJECT_FIELDS = ["run", "session", "request", "task", "invocation"] as const;
121
+
122
+ const UUID_TAIL = /^(.*?)([0-9a-f]{8})-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
123
+
124
+ /** An id short enough to read in a line: a uuid keeps its first eight characters, a session its harness and the start of its own id. */
125
+ export function shortId(id: string): string {
126
+ const [harness, native] = id.split(" ");
127
+ if (native !== undefined) return `${harness}:${shortId(native)}`;
128
+ return id.replace(UUID_TAIL, "$1$2");
129
+ }
130
+
131
+ /**
132
+ * What a record is about, as `run:1a2b3c4d session:s-9f8e7d`: a session niwa started is named by its
133
+ * id (`sessions`, by its pair), another by its harness and the start of its own id.
134
+ */
135
+ function subjectOf(data: Record<string, unknown>, id: string | undefined, sessions: ReadonlyMap<string, string>): string {
136
+ const named = SUBJECT_FIELDS.flatMap((kind) => {
137
+ const value = data[kind];
138
+ const text = typeof value === "string" ? value : undefined;
139
+ if (text === undefined) return [];
140
+ if (kind === "session") return [`session:${sessions.get(text) ?? shortId(text)}`];
141
+ return [`${kind}:${kind === "invocation" ? shortForm(text) : shortId(text)}`];
142
+ });
143
+ return named.length > 0 || id === undefined ? named.join(" ") : shortForm(shortId(id));
144
+ }
145
+
146
+ /** The data of a record as `key=value` pairs: the subject fields are in the subject, a long value is cut. */
147
+ function dataText(data: unknown): string {
148
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return field(data);
149
+ return Object.entries(data)
150
+ .filter(([key]) => !(SUBJECT_FIELDS as readonly string[]).includes(key))
151
+ .map(([key, value]) => `${key}=${cut(shortForm(field(value)), 80)}`)
152
+ .join(" ");
153
+ }
154
+
155
+ function cut(text: string, width: number): string {
156
+ const line = text.replace(/\s+/g, " ");
157
+ return line.length <= width ? line : `${line.slice(0, Math.max(0, width - 1))}…`;
158
+ }
159
+
160
+ /**
161
+ * One record as a line to read in a terminal: the time, a short type, what it is about, and the
162
+ * data cut to the width. The same shape for every type, so no type is special to it.
163
+ */
164
+ export function logLine(record: RecordAnswer, width: number, sessions: ReadonlyMap<string, string> = new Map()): string {
165
+ const time = new Date(record.at).toTimeString().slice(0, 8);
166
+ const data = typeof record.data === "object" && record.data !== null ? (record.data as Record<string, unknown>) : {};
167
+ const id = typeof data["id"] === "string" && record.type.includes(".") ? data["id"] : undefined;
168
+ const type = cut(record.type.replace(/^niwa\./, ""), 26).padEnd(26);
169
+ const subject = subjectOf(data, id, sessions);
170
+ const line = `${time} ${type} ${subject}${subject === "" ? "" : " "}${dataText(data)}`.trimEnd();
171
+ return line.length <= width ? line : `${line.slice(0, width - 1)}…`;
172
+ }
@@ -0,0 +1,190 @@
1
+ ---
2
+ name: niwa
3
+ description: >-
4
+ Use niwa, the owner's local agent host, for work that reaches beyond this session: start, resume,
5
+ message, read or search sessions of other coding agents (Claude Code, Codex, pi, mcode, ...), ask
6
+ the owner a question and get a typed answer, create and report on tracked tasks, write and run
7
+ durable workflow scripts. Activate when niwa MCP tools are present (session_start, message_send,
8
+ task_create, request_ask, workflow_start, ...) and the work needs one; when the user mentions
9
+ niwa, its host or cockpit, or an id like run-, req-, task-, wf-, s-, msg-, sub-; or when your
10
+ prompt says niwa started you. Do not activate for this harness's own subagents, todo lists or
11
+ workflow tools, or for work you can finish alone in this session.
12
+ ---
13
+
14
+ # niwa
15
+
16
+ niwa is the owner's local host: one background process that owns a journal and exposes typed
17
+ actions named `<group>.<action>`. Through it you reach other agents' sessions, the owner, tracked
18
+ tasks and durable workflow scripts.
19
+
20
+ This file ships inside niwa (`niwa skill` prints the current text). It names things; the host
21
+ defines them. Where this file and the host disagree, the host is right.
22
+
23
+ ## Reach it
24
+
25
+ - **MCP.** If tools such as `session_start` or `task_create` are in your tool list, use them. A tool
26
+ name is the action name with `.` and `-` written as `_` (`session.open-questions` is
27
+ `session_open_questions`).
28
+ - **CLI otherwise.** `niwa <group>.<action> --field value ...`, for example
29
+ `niwa task.get --id task-3f9a21`. A field that is an object or a list takes JSON
30
+ (`--visible '{"actions":["task.*"]}'`). Every flag is the field of the same name, so a field
31
+ called `input` is `--input`. After the command, `--json '{...}'` gives the whole input at once
32
+ (`--json -` reads it from stdin).
33
+ `--json` goes before the command and asks for the machine form: `niwa --json harness.list`.
34
+ - **Is the host up:** `niwa status`.
35
+ - You see the actions that whoever started you made visible. That set is your mandate. Do not route
36
+ around it through another surface.
37
+
38
+ Below, actions are written `group.action`; translate to your surface.
39
+
40
+ ## First moves
41
+
42
+ Once per session, before the first real call:
43
+
44
+ 1. `niwa status` - the host is up, and which plugins it runs.
45
+ 2. `niwa help` lists every action of the host and its fields. On MCP the tool list is the same thing. For the full input schema of an action:
46
+ `niwa --json niwa.describe`. Never guess a field name; read it there.
47
+ 3. `harness.list`, then `harness.get --name <name>` - the harness instances you may start sessions
48
+ on (names look like `claude-sonnet`, `codex-luna`), with their kind and the options block they
49
+ take.
50
+ 4. Before any workflow work: `workflow.guide`.
51
+
52
+ ## Use niwa, or do it yourself
53
+
54
+ Use niwa when the work:
55
+ - needs another harness or model (an independent review, a second opinion, parallel work);
56
+ - needs the owner's decision;
57
+ - must be visible to the owner or outlive your session (a task);
58
+ - is a multi-step procedure that must survive a restart or be repeated (a workflow);
59
+ - needs what other sessions already did (session search and read).
60
+
61
+ Do it yourself when your own tools finish it in this session. A quick nested lookup belongs to your
62
+ harness's own subagents. Your private todo list is not a niwa task.
63
+
64
+ ## Recipes
65
+
66
+ ### Hand work to another agent's session
67
+
68
+ 1. Pick an instance name from `harness.list`.
69
+ 2. `session.start` with `harness` set to that name and a `prompt`. The prompt must stand alone: the
70
+ new session knows nothing of yours. Give the goal, the files, the constraints and the shape of
71
+ the answer you want. Pass `cwd` (the working directory); `model`, `effort` and `mode`
72
+ (`ask`, `auto`, `full`) when you need other than the instance's. In `visible.actions` list only
73
+ the actions it needs. The session runs in a box: the host's default (its project and the
74
+ toolchains) and its own installation's profile. `box: {"allow": ["bun", {"write": "../out"}]}`
75
+ gives it more, within your `box.*` rules; `box: {"only": [{"read": "."}]}` gives it less.
76
+ 3. `session.start` returns the session id `s-...` and a receipt (delivered, queued, started or handled). A
77
+ receipt is not the answer. Read the session (`session.read`) for the reply.
78
+ 4. To continue, `session.send` or `session.resume` the same `s-...`. A new session loses the
79
+ context.
80
+ 5. If that session needs a permission or asks a question, the request comes to you as its starter.
81
+ `request.open` lists what waits; answer with `request.answer`. An unanswered request leaves the
82
+ session waiting.
83
+
84
+ `session.list`, `session.search` and `session.read` also cover sessions that niwa did not start.
85
+ `session.list` answers one page, the most recently active first; when `nextCursor` is present, pass it as
86
+ `cursor` (with the same filters) for the next page, or narrow by `harness` or `cwd`.
87
+ For handing work over from CLI or MCP, use `session.start`. A workflow uses the session SDK below.
88
+
89
+ ### Ask the owner
90
+
91
+ `request.ask` with `to: {"kind":"owner"}`, a `question` (a short name with no spaces) and an
92
+ `input` whose `kind` is one of `confirm`, `choice`, `multi`, `text`, `form`, with a `title`.
93
+
94
+ - The owner reads the question later and out of context. Put in the `title` and `detail` what is
95
+ needed to answer, and say which option you recommend.
96
+ - Prefer `choice` with concrete options over free text.
97
+ - One request per decision. Put related fields in one `form`, not five requests.
98
+ - Called directly (MCP or CLI), `request.ask` does not wait: it creates the request and returns
99
+ `{id, status: "open"}` at once, the id being `req-...`. Read the answer later with `request.get`
100
+ (its `status` leaves `open` and `answer` appears); `request.list` shows what still waits. Give a
101
+ `deadline` if the question may go stale.
102
+ - To block on the answer, ask from a workflow script (`ask.choice`, ...): as a step the ask waits
103
+ (the wait survives a host restart) and returns the answer.
104
+ - Before asking, check that the answer is not already in the records, a session or the repository.
105
+ - No answer, a cancel or an expiry is neither yes nor no. Take the safe path, or stop and report.
106
+
107
+ ### Tasks
108
+
109
+ A task is a contract: what to do, who asked, who is responsible, where to report, how it ended.
110
+
111
+ - **You assign:** `task.create`, with a `result` schema when you need a typed result. `task.result`
112
+ waits for the end; `task.list` and `task.get` show where it stands.
113
+ - **You were assigned** (your prompt names `task-...`): `task.get` it, `task.report` at real
114
+ milestones, and end with exactly one of `task.finish` (a result that fits the schema) or
115
+ `task.fail` (the reason). `task.assigned` lists what you still owe. Never leave a task silent.
116
+
117
+ ### Messages
118
+
119
+ `message.send` to an address (an agent, a session, a task, the owner) is for what needs no answer:
120
+ an update, a result. If you need an answer, that is a request. `message.list` and `message.get`
121
+ read them.
122
+
123
+ ### Workflows
124
+
125
+ 1. `workflow.guide` returns the language guide, the generated typings and the actions you may call.
126
+ It is the reference; nothing here replaces it.
127
+ 2. Write the script to a file.
128
+ 3. Run `workflow.check --file <file>` until it is clean.
129
+ 4. `workflow.start` runs a script: once from a file (`workflow.start --file <file>`), or a registered
130
+ workflow by its id. To keep one: `workflow.register --file <file>` gives `wf-...`, then
131
+ `workflow.start --id wf-... --args ...`. Registering with the same `--id` adds a version.
132
+ 5. Follow the run `run-...` with `workflow.inspect` or `workflow.wait`. History is in
133
+ `workflow.runs` and `workflow.stats`.
134
+ 6. A failure pauses the run: answer it with `workflow.resume --run <run> --choice retry|skip|cancel`.
135
+ To change the script, edit the file and `workflow.revise --run <run> --file <file>`; finished
136
+ steps keep their results. Do not start a fresh run to get past a pause.
137
+ 7. `workflow.install` is a subscription, not a run: it makes niwa start a run by itself for every
138
+ record that matches the workflow's `on` (`sub-...`), and starts nothing now. Use it only when the
139
+ owner asked for standing automation; to run a script now, use `workflow.start`.
140
+ `workflow.uninstall` ends a subscription.
141
+
142
+ Rules that scripts break most often:
143
+ - Label every step whose result must survive an edit of the script.
144
+ - Declare the phases in the header, `phases: [{ title: "Review" }, { title: "Fix" }]`, and enter
145
+ each by calling `phase("Review")` in the body. A phase belongs to the branch that entered it (a
146
+ `parallel` branch may be in another phase); steps take no phase option.
147
+ - Use `now()` and `random()` (recorded reads), not `Date.now()` and `Math.random()`, and no direct
148
+ I/O in the body; go through actions.
149
+ - Keep `uses` to the masks the script actually calls.
150
+ - Use `ask({ harness, schema, label }, prompt)` for one structured answer. The run closes the session
151
+ after the answer. For several turns with one model, use `const review = session({ harness, box })`,
152
+ then `await review.ask(prompt, { schema, label })` for each turn and `await review.end()` when done.
153
+ Choose a schema whenever you branch on an answer. Turns replay from the journal.
154
+ - Put the required session actions in `uses`. `workflow.guide` lists them and the box options
155
+ the caller's grant can permit. Helpers started by a run's session belong to the run too.
156
+ - Use `agent("rin").tell(text)` to send a message to the persistent agent's inbox.
157
+ Use `ask.confirm`, `ask.choice` and the other request helpers to ask the owner.
158
+
159
+ ## Ids
160
+
161
+ niwa issues every id as `<prefix>-<hex>`: `s-` session, `task-`, `req-`, `msg-`, `run-`, `wf-`,
162
+ `sub-` (an installed workflow). Never invent one. A `get` takes the id, or the start or the end of
163
+ it when that is unambiguous. Most entities have `list` and `get`. Quote ids when you report to the
164
+ owner or to another agent.
165
+
166
+ ## Rin
167
+
168
+ Rin is the owner's main agent. If the host has her, `rin.*` actions are in the action list, and
169
+ their descriptions say what she takes (notes, commitments, judging). If they are absent, she is not
170
+ on this host.
171
+
172
+ When the owner asks you to load Rin (or another agent: "load the reviewer"), run
173
+ `niwa agent attach [<agent>]` from your shell; without a name it attaches the host's default agent.
174
+ It finds your session from your environment, prints the agent's briefing, and from then on the agent
175
+ learns what this session does at its pauses. Under mcode, add `--session <id>`. What you say to the
176
+ agent yourself (`agent.tell`) is your word, not the owner's.
177
+
178
+ ## When it does not work
179
+
180
+ - **Host down** (`niwa status` fails, or MCP calls end in connection errors). Tell the owner. Do
181
+ not start the host yourself. Continue with what you can do directly.
182
+ - **An action is missing from your tools.** Your starter did not make it visible. Ask the starter
183
+ for it by name. Do not work around it.
184
+ - **Refused by the grant.** The refusal names the masks. It is an answer, not a glitch: do not
185
+ retry, do not vary the call. Narrow `uses` or `visible` to what you hold, or ask for the right.
186
+ - **Outcome `unknown`.** The call was cut off and its effect may have happened. Check with `get` or
187
+ `list` before repeating.
188
+ - **`input-invalid`.** The error lists the fields. Fix them from the schema, not by trial.
189
+ - **The harness refuses** a model, an effort, a mode or a resume. It cannot do that. Pick another
190
+ instance from `harness.list`.