@niwa-labs/niwa 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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/bin/niwa.ts +128 -0
  4. package/examples/01-my-harness.ts +90 -0
  5. package/examples/02-event-and-handler.ts +73 -0
  6. package/examples/03-action.ts +64 -0
  7. package/examples/04-step.ts +68 -0
  8. package/examples/05-intercept.ts +51 -0
  9. package/examples/06-sessions.ts +79 -0
  10. package/examples/07-task.ts +37 -0
  11. package/examples/08-request.ts +57 -0
  12. package/examples/09-workflow.ts +56 -0
  13. package/examples/10-observe.ts +68 -0
  14. package/examples/11-plugin.ts +40 -0
  15. package/examples/12-quick-script.ts +44 -0
  16. package/examples/13-workflow-client.ts +60 -0
  17. package/examples/14-workflow-subscription.ts +46 -0
  18. package/examples/15-git-worktree.ts +31 -0
  19. package/package.json +54 -4
  20. package/src/cockpit-pages.ts +74 -0
  21. package/src/composition.ts +96 -0
  22. package/src/index.ts +39 -0
  23. package/src/inserts.ts +40 -0
  24. package/src/kinds.ts +40 -0
  25. package/src/mcp.ts +37 -0
  26. package/src/serve.ts +158 -0
  27. package/src/skills.ts +20 -0
  28. package/src/web.ts +89 -0
  29. package/test/acp-protocol.test.ts +508 -0
  30. package/test/addresses.test.ts +363 -0
  31. package/test/agent-attach.test.ts +112 -0
  32. package/test/agent-attachment-replay.test.ts +57 -0
  33. package/test/agent-cli.test.ts +87 -0
  34. package/test/agent-digest.test.ts +201 -0
  35. package/test/agent-schema.test.ts +76 -0
  36. package/test/agent-task-message.test.ts +56 -0
  37. package/test/agent.test.ts +333 -0
  38. package/test/allow-after-adjust.test.ts +85 -0
  39. package/test/answer-by-schema.test.ts +292 -0
  40. package/test/busy-session.test.ts +277 -0
  41. package/test/call-operation.test.ts +246 -0
  42. package/test/caller.test.ts +57 -0
  43. package/test/claude-code-reverse.test.ts +581 -0
  44. package/test/claude-sdk-control.test.ts +501 -0
  45. package/test/claude-sdk-reverse.test.ts +450 -0
  46. package/test/cli-principal.test.ts +66 -0
  47. package/test/cli.test.ts +596 -0
  48. package/test/cockpit-app.test.ts +382 -0
  49. package/test/cockpit.test.ts +99 -0
  50. package/test/codex-reverse.test.ts +684 -0
  51. package/test/compose.test.ts +89 -0
  52. package/test/confirm.test.ts +276 -0
  53. package/test/day-of-work.test.ts +202 -0
  54. package/test/discover.test.ts +285 -0
  55. package/test/dispose.test.ts +92 -0
  56. package/test/doors.test.ts +266 -0
  57. package/test/fixtures/acp/mcode-0.7.1-upstream.jsonl +32 -0
  58. package/test/fixtures/acp/ncode-0.7.2-fork.jsonl +2 -0
  59. package/test/fixtures/acp-replay.ts +79 -0
  60. package/test/fixtures/agent-host.ts +181 -0
  61. package/test/fixtures/ask-owner-host.ts +244 -0
  62. package/test/fixtures/browser.ts +32 -0
  63. package/test/fixtures/busy-host.ts +79 -0
  64. package/test/fixtures/codex-frames.ts +88 -0
  65. package/test/fixtures/composition.ts +16 -0
  66. package/test/fixtures/day-host.ts +127 -0
  67. package/test/fixtures/day.workflow.js +100 -0
  68. package/test/fixtures/forge-plugin.ts +65 -0
  69. package/test/fixtures/insert-host.ts +28 -0
  70. package/test/fixtures/mcp-pair.ts +50 -0
  71. package/test/fixtures/niwa-cli.ts +14 -0
  72. package/test/fixtures/requests-host.ts +121 -0
  73. package/test/fixtures/schema-host.ts +245 -0
  74. package/test/fixtures/surface-host.ts +156 -0
  75. package/test/fixtures/task-mcp-agent-host.ts +133 -0
  76. package/test/fixtures/task-mcp-host.ts +164 -0
  77. package/test/fixtures/workflow-agents-host.ts +96 -0
  78. package/test/fixtures/workflow-agents-script.js +34 -0
  79. package/test/follow-stream.test.ts +63 -0
  80. package/test/generated-commands.test.ts +120 -0
  81. package/test/generated-tools.test.ts +91 -0
  82. package/test/grant-target.test.ts +52 -0
  83. package/test/grant-wiring.test.ts +653 -0
  84. package/test/history-read.test.ts +150 -0
  85. package/test/history-watch.test.ts +328 -0
  86. package/test/host-access.test.ts +114 -0
  87. package/test/insert-hooks.test.ts +259 -0
  88. package/test/insert-report.test.ts +87 -0
  89. package/test/inserts.test.ts +115 -0
  90. package/test/irreversible-grant.test.ts +108 -0
  91. package/test/kind-exports.test.ts +42 -0
  92. package/test/kinds.test.ts +1062 -0
  93. package/test/launch.test.ts +405 -0
  94. package/test/mcode-reverse.test.ts +538 -0
  95. package/test/mcp-scalar-input.test.ts +56 -0
  96. package/test/mcp-tool-changes.test.ts +117 -0
  97. package/test/mcp-visible.test.ts +88 -0
  98. package/test/pi-insert.test.ts +220 -0
  99. package/test/pi-live.test.ts +229 -0
  100. package/test/pi-reverse.test.ts +485 -0
  101. package/test/prompt-normalization.test.ts +78 -0
  102. package/test/read-under-ask.test.ts +56 -0
  103. package/test/read-without-copying.test.ts +398 -0
  104. package/test/read.test.ts +202 -0
  105. package/test/reading-unknown-records.test.ts +211 -0
  106. package/test/report-session.test.ts +137 -0
  107. package/test/request-ids.test.ts +190 -0
  108. package/test/requests.test.ts +881 -0
  109. package/test/run-allow.test.ts +62 -0
  110. package/test/service.test.ts +177 -0
  111. package/test/session-asks-owner.test.ts +196 -0
  112. package/test/session-box.test.ts +247 -0
  113. package/test/session-caps.test.ts +192 -0
  114. package/test/session-identity.test.ts +243 -0
  115. package/test/session-ids-surfaces.test.ts +76 -0
  116. package/test/session-options.test.ts +384 -0
  117. package/test/session-send-operation.test.ts +266 -0
  118. package/test/sessions-control.test.ts +1495 -0
  119. package/test/sessions-kind-instances.test.ts +153 -0
  120. package/test/short-ids.test.ts +170 -0
  121. package/test/skill.test.ts +172 -0
  122. package/test/task-api.test.ts +290 -0
  123. package/test/task-mcp-agent.test.ts +212 -0
  124. package/test/task-through-mcp.test.ts +359 -0
  125. package/test/telegram-agent.test.ts +220 -0
  126. package/test/uses-template.test.ts +138 -0
  127. package/test/wait-key.test.ts +439 -0
  128. package/test/workflow-agents.test.ts +323 -0
  129. package/test/workflow-client-example.test.ts +99 -0
  130. package/test/workflow-hold.test.ts +221 -0
  131. package/test/workflow-register-owner.test.ts +59 -0
  132. package/test/workflow-registry.test.ts +392 -0
  133. package/test/workflow-stats.test.ts +238 -0
  134. package/test/workflow-subscriptions.test.ts +451 -0
  135. package/test/working-directory.test.ts +77 -0
  136. package/test/worktree-box.test.ts +70 -0
  137. package/test/zcode-reverse.test.ts +570 -0
  138. package/tsconfig.json +9 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/niwa
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The umbrella package: the `niwa` command and the standard composition of the host, the base
4
+ plugins and the surfaces.
5
+
6
+ ## Install and start
7
+
8
+ Install Bun, then add Niwa to the directory that holds your host configuration.
9
+
10
+ ```sh
11
+ npm install @niwa-labs/niwa
12
+ ```
13
+
14
+ Create `host.ts` next to your `package.json`.
15
+
16
+ ```ts
17
+ import { homedir } from "node:os";
18
+ import { join } from "node:path";
19
+ import { defaultComposition, HarnessInstanceRegistry } from "@niwa-labs/niwa";
20
+
21
+ export default defaultComposition({
22
+ home: process.env.NIWA_HOME ?? join(homedir(), ".niwa"),
23
+ harnesses: new HarnessInstanceRegistry(),
24
+ });
25
+ ```
26
+
27
+ ```sh
28
+ npx niwa serve -d ./host.ts
29
+ npx niwa status
30
+ npx niwa web
31
+ ```
32
+
33
+ Open the local login link printed by `niwa web`. The host stores its journal in
34
+ `~/.niwa` by default. Set `NIWA_HOME` to choose another persistent directory.
35
+ Use `npx niwa stop` to stop the host. For agent configuration and optional
36
+ plugins, see the [Niwa configuration guide](https://github.com/niwa-labs/niwa#run-from-source).
37
+
38
+ ## Package contents
39
+
40
+ - `bin/niwa.ts` is the command. Actions of the host are commands (`niwa <action> --field value`);
41
+ `niwa serve` runs a host from a composition file, `niwa mcp` serves MCP over stdio, `niwa web`
42
+ serves the web surface, `niwa skill` installs the skill, and `niwa insert report` is what the
43
+ inserts inside a harness run to report an event.
44
+ - `src/index.ts` re-exports the foundation, the base plugins and the harness kinds, so a program
45
+ that runs a host imports from one place.
46
+ - `NIWA_CLI` is the absolute path of the bin. Inserts installed from here (`installInsert`,
47
+ `insertEnv`, `cliReporter`) report through it, so they work where `niwa` is not on the PATH.
48
+ - `examples/` are programs and workflow scripts that show one thing each. They are type-checked
49
+ with the package.
50
+ - `test/` holds the acceptance tests: they compose a host with the plugins and the kinds, run the
51
+ command and the hooks as programs, and drive real harnesses when `NIWA_LIVE=1`.
package/bin/niwa.ts ADDED
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env bun
2
+ // The `niwa` command. The commands that are actions come from `@niwa-labs/cli`, which is a client
3
+ // and nothing more; `serve`, `web`, `mcp` and the kinds of `skill` are composed here.
4
+ //
5
+ // Usage: bun bin/niwa.ts [--home <dir>] <command> [--field value ...]
6
+ //
7
+ // The commands are the actions the host declares: they are generated from the description, so
8
+ // a plugin that declares a new action has a command at once, with no change to this file.
9
+ //
10
+ // The home of the host: --home, else NIWA_HOME, else ~/.niwa.
11
+ //
12
+ // The output is for a person by default and for a machine under --json. A failure exits
13
+ // non-zero, and the exit code says what went wrong.
14
+
15
+ import { homedir } from "node:os";
16
+
17
+ import { homeOf, run, runInsert, runSkill, usageAt } from "@niwa-labs/cli";
18
+ import { tokenOf } from "@niwa-labs/client";
19
+
20
+ import { runMcp } from "../src/mcp.ts";
21
+ import { serveComposition, serveDetached } from "../src/serve.ts";
22
+ import { KINDS_WITH_SKILLS } from "../src/skills.ts";
23
+ import { portOf, runWeb } from "../src/web.ts";
24
+
25
+ const argv = process.argv.slice(2);
26
+
27
+ /**
28
+ * Split the command line into the CLI's own flags and the command.
29
+ *
30
+ * The CLI's flags are the ones before the command: `--home`, `--json`. Everything after the
31
+ * command belongs to the command, so an action may have a field called "json" and the CLI does
32
+ * not take it away.
33
+ */
34
+ function splitFlags(args: string[]): { flags: string[]; rest: string[] } {
35
+ const flags: string[] = [];
36
+ for (let index = 0; index < args.length; index += 1) {
37
+ const argument = args[index];
38
+ if (argument === undefined) continue;
39
+ if (argument === "--home") {
40
+ const value = args[index + 1];
41
+ if (value === undefined) {
42
+ console.error("--home needs a directory");
43
+ process.exit(2);
44
+ }
45
+ flags.push(argument, value);
46
+ index += 1;
47
+ continue;
48
+ }
49
+ if (argument.startsWith("--home=") || argument === "--json") {
50
+ flags.push(argument);
51
+ continue;
52
+ }
53
+ return { flags, rest: args.slice(index) };
54
+ }
55
+ return { flags, rest: [] };
56
+ }
57
+
58
+ const { flags, rest } = splitFlags(argv);
59
+ const command = rest[0];
60
+
61
+ if (command === undefined) {
62
+ const home = homeOf(flags, process.env);
63
+ console.error(await usageAt(home, tokenOf(home)));
64
+ process.exit(2);
65
+ }
66
+
67
+ // `niwa skill` prints and installs the skill niwa ships: a file of niwa's own, so it needs no host.
68
+ //
69
+ // `niwa serve` starts a host instead of talking to one: it has no host to connect to yet.
70
+ // `niwa mcp` and `niwa web` are the other two programs of a home: the MCP server over stdio, and
71
+ // the cockpit. Like serve they run until they are stopped.
72
+ if (command === "skill") {
73
+ const result = runSkill(rest.slice(1), { home: homedir(), cwd: process.cwd() }, KINDS_WITH_SKILLS);
74
+ (result.code === 0 ? console.log : console.error)(result.output);
75
+ process.exit(result.code);
76
+ } else if (command === "insert") {
77
+ // `niwa insert report`: an insert inside a harness reports an event, given as JSON on stdin.
78
+ const result = await runInsert(rest.slice(1), homeOf(flags, process.env));
79
+ if (result.output !== "") (result.code === 0 ? console.log : console.error)(result.output);
80
+ process.exit(result.code);
81
+ } else if (command === "mcp") {
82
+ await runMcp(homeOf(flags, process.env), process.env);
83
+ } else if (command === "web") {
84
+ const port = portOf(rest.slice(1));
85
+ if (port === undefined) {
86
+ console.error("usage: niwa web [--port N] (N between 0 and 65535)");
87
+ process.exit(2);
88
+ }
89
+ await runWeb(homeOf(flags, process.env), port, process.env);
90
+ } else if (command === "serve") {
91
+ const detach = rest[1] === "-d";
92
+ const file = rest[detach ? 2 : 1];
93
+ if (file === undefined) {
94
+ console.error("usage: niwa serve [-d] <composition.ts>");
95
+ process.exit(2);
96
+ }
97
+ if (detach) {
98
+ const started = await serveDetached({ file, home: homeOf(flags, process.env), entry: import.meta.path });
99
+ (started.code === 0 ? console.log : console.error)(started.output);
100
+ process.exit(started.code);
101
+ }
102
+ try {
103
+ await serveComposition({ file, home: homeOf(flags, process.env) });
104
+ } catch (error) {
105
+ console.error(error instanceof Error ? error.message : String(error));
106
+ process.exit(1);
107
+ }
108
+ } else {
109
+ const home = homeOf(flags, process.env);
110
+ const token = tokenOf(home);
111
+ const result = await run(
112
+ {
113
+ home,
114
+ ...(token === undefined ? {} : { token }),
115
+ command,
116
+ args: rest.slice(1),
117
+ json: flags.includes("--json"),
118
+ },
119
+ (text) => console.log(text),
120
+ );
121
+ if (result.code !== 0) {
122
+ console.error(result.output);
123
+ if (result.errorCode !== undefined) console.error(`(${result.errorCode})`);
124
+ } else if (result.output !== "") {
125
+ console.log(result.output);
126
+ }
127
+ process.exit(result.code);
128
+ }
@@ -0,0 +1,90 @@
1
+ // Needs a live host and harnesses: running it serves a host on your real `~/.niwa`, with Claude
2
+ // Code, Codex and MiniMax Code installed under `~/.claude`, `~/.codex` and `~/.mcode`.
3
+ //
4
+ // Your harness is one file. What is connected is visible in one place.
5
+ // There are no profiles and no configuration files beside it.
6
+ //
7
+ // This program is the host: the one background process that owns the journal
8
+ // and runs the plugins. Everything else connects to it (see 10-observe.ts).
9
+
10
+ import { homedir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ import { createNiwa } from "@niwa-labs/host";
14
+ import { git } from "@niwa-labs/git";
15
+ import { HarnessInstanceRegistry } from "@niwa-labs/harness";
16
+ import { claudeCodeKind } from "@niwa-labs/harness-claude";
17
+ import { codexKind } from "@niwa-labs/harness-codex";
18
+ import { mcodeKind } from "@niwa-labs/harness-mcode";
19
+ import { messages } from "@niwa-labs/messages";
20
+ import { owner } from "@niwa-labs/core";
21
+ import { requests } from "@niwa-labs/requests";
22
+
23
+ import { sessions } from "@niwa-labs/sessions";
24
+ import { tasks } from "@niwa-labs/tasks";
25
+ import { chatId, telegram } from "@niwa-labs/telegram";
26
+ import { timers } from "@niwa-labs/timer";
27
+ import { workflow } from "@niwa-labs/workflow";
28
+ import nightDigest from "./11-plugin.ts";
29
+
30
+ const niwa = createNiwa({ home: join(homedir(), ".niwa") });
31
+ // `niwa` here is the host. The plugins it installs receive a different object, the plugin
32
+ // API, which the examples call `api` (see 11-plugin.ts). The host installs and serves; the
33
+ // plugin API declares, listens and registers.
34
+
35
+ // What is installed on this machine. A kind is code (how Claude Code, Codex, MiniMax Code are
36
+ // read and driven); an instance is one installation of it, with an id the owner gives, its own home
37
+ // and its own model. One kind may have several: two Claude Code installations that differ in the model
38
+ // are two binds. `harness.discover` can propose the instances and `harnessConfirm` registers what the
39
+ // owner confirms; here they are written out by hand.
40
+ const machine = "laptop";
41
+ const harnesses = new HarnessInstanceRegistry();
42
+ harnesses.register(claudeCodeKind.bind({ id: "claude-haiku", machine, model: "haiku" }));
43
+ harnesses.register(claudeCodeKind.bind({ id: "claude-sonnet", machine, model: "sonnet" }));
44
+ harnesses.register(codexKind.bind({ id: "codex", machine, home: join(homedir(), ".codex") }));
45
+ harnesses.register(mcodeKind.bind({ id: "mcode-work", machine, home: join(homedir(), ".mcode") }));
46
+ niwa.use(sessions({ harnesses }));
47
+
48
+ // Every base module is a factory: call it, `tasks()`, `timers([...])`.
49
+ // Who a client speaks as is the composition's to say: here every client is the owner.
50
+ const bind = () => owner;
51
+ niwa.use(
52
+ messages({ bind }),
53
+ tasks({ messages: { bind } }),
54
+ requests({ bind }),
55
+ // Worktrees sessions work in (`ask({ harness, worktree: true }, prompt)`). The old ones are removed by a
56
+ // workflow the module ships, every day at four on a timer it offers: `git({ cleanup: false })` turns it off.
57
+ git(),
58
+ // The timers. A module offers the timers it needs itself (git's cleanup), and a handler of a timer's
59
+ // trigger offers that timer by subscribing (the night digest's): the list is for the owner's own.
60
+ timers([]),
61
+ );
62
+
63
+ // A surface people reach niwa through. The token and the chat are the owner's.
64
+ niwa.use(
65
+ telegram({
66
+ token: process.env.TELEGRAM_TOKEN ?? "",
67
+ owner: chatId(Number(process.env.TELEGRAM_CHAT)),
68
+ // Without it the instance is a plain client, and the owner's requests are not answered by it.
69
+ speaksFor: "owner",
70
+ }),
71
+ );
72
+
73
+ // The MCP server and the web cockpit are not plugins: they are clients of this host, started
74
+ // beside it (`niwa mcp`, `niwa web`, or `serveMcp` / `serveWeb` from
75
+ // `@niwa-labs/mcp` and `@niwa-labs/web`). They connect to the socket like any other client.
76
+
77
+ // Built-in workflows (git's cleanup, say) are scripts a plugin ships: the workflow module, installed
78
+ // after the plugins that ship them, registers and installs them when the host starts. A host with a
79
+ // plugin that ships one and no workflow module refuses to serve.
80
+ niwa.use(workflow({ harnesses: ["claude-haiku", "claude-sonnet"] }));
81
+
82
+ // Your own plugins.
83
+ niwa.use(nightDigest);
84
+
85
+ await niwa.serve();
86
+
87
+ // `serve()` returns as soon as the host is up. It does not run until it is killed.
88
+ // The process stays alive because the host listens on its socket, so a program
89
+ // that is only the host can end here. A script that serves and then does its own
90
+ // work keeps going after this line, and stops the host with `await niwa.close()`.
@@ -0,0 +1,73 @@
1
+ // A plugin file: a host loads it with `niwa.use(...)`; run on its own it does nothing.
2
+ //
3
+ // A record type is a value you import, not a string. A typo is a compile error.
4
+ // A declared type is not yet known to the host: the plugin declares it with
5
+ // `api.declare(...)`, and only then may it be written.
6
+ //
7
+ // `api` is the plugin API: what a plugin is given while it is loaded. It is not the host
8
+ // object (`niwa`, from `createNiwa`) and not the client object (`niwa`, from `connect`).
9
+ // A plugin declares, listens and registers through `api`; a script that only reads and calls
10
+ // uses the host or a client.
11
+
12
+ import { plugin } from "@niwa-labs/plugin";
13
+ import { record } from "@niwa-labs/core";
14
+ import { owner } from "@niwa-labs/core";
15
+ import { executor, taskCreate } from "@niwa-labs/tasks";
16
+ import { z } from "zod";
17
+
18
+ const BuildFailure = z.object({
19
+ repo: z.string(),
20
+ branch: z.string(),
21
+ log: z.string(),
22
+ });
23
+ export const BuildFailed = record("ci.build-failed", BuildFailure);
24
+
25
+ // Stand-in: not part of niwa. Whatever watches your CI (a webhook, a poller) calls back with a
26
+ // failure. This one never fails a build.
27
+ function watchBuilds(onFailure: (failure: z.output<typeof BuildFailure>) => void): void {
28
+ void onFailure;
29
+ }
30
+
31
+ export default plugin("ci", (api) => {
32
+ // The type is declared to the host first. Without this, writing a record of
33
+ // it is rejected: the host does not know the type.
34
+ api.declare(BuildFailed);
35
+
36
+ // A plugin that watches the build writes the fact.
37
+ watchBuilds((failure) => {
38
+ void api.emit(BuildFailed, failure);
39
+ });
40
+
41
+ // Anyone else reacts to it. A handler runs after the record is written.
42
+ // `taskCreate` is the typed reference of the tasks module: the step checks the input
43
+ // against its schema, and the result is typed.
44
+ api.on(BuildFailed, async (failed, step) => {
45
+ await step(taskCreate, {
46
+ kind: "fix",
47
+ description: "Fix the failed build",
48
+ text: `The build of ${failed.repo}/${failed.branch} failed. Find out why and fix it.`,
49
+ askedBy: owner,
50
+ responsible: executor("codex"),
51
+ reportTo: owner,
52
+ });
53
+ });
54
+ });
55
+
56
+ // A script that emits does not get the handler's result from `emit`. `emit`
57
+ // returns when the record is committed. The handler runs after that, so the
58
+ // journal read right away holds the record and not yet what the handler wrote.
59
+ // For durability: the fact is on disk first, the work follows and survives a crash.
60
+ // A script that wants the outcome waits for the record the handler writes:
61
+ //
62
+ // import { TaskCreated } from "@niwa-labs/tasks";
63
+ // const failed = await niwa.emit(BuildFailed, { repo, branch, log });
64
+ // for await (const rec of niwa.records.since({ from: failed.seq, types: [TaskCreated] })) {
65
+ // console.log("the handler created", rec.data);
66
+ // break; // `since` never ends by itself: stop it when you have the answer
67
+ // }
68
+ //
69
+ // To wait for the handler to end, follow `niwa.invocation.state` records instead and
70
+ // stop at the state "done" or "paused".
71
+
72
+ // The task created here remembers, without any code of ours,
73
+ // that this record caused it and what external input started the chain.
@@ -0,0 +1,64 @@
1
+ // Declares an action; the plugin that registers it is shown in a comment below. A host loads that
2
+ // plugin with `niwa.use(...)`; run on its own this file does nothing.
3
+ //
4
+ // An action is something the system can do. Declare it once and it appears
5
+ // as an MCP tool, as a CLI command, and in the list of what niwa can do.
6
+ // Declaring it is not enough: the plugin registers it with `api.action(...)`,
7
+ // and only then is it in that list and callable by name.
8
+
9
+ import { action } from "@niwa-labs/core";
10
+ import { z } from "zod";
11
+
12
+ // Stand-ins: not part of niwa. A bot that sends a text and says the id of the message, and the
13
+ // chat the owner reads. The real Telegram surface is `telegram()` from "@niwa-labs/telegram".
14
+ const ownerChat = "owner";
15
+ const bot = {
16
+ send: async (chat: string, text: string): Promise<{ messageId: number }> => {
17
+ console.log(`[${chat}] ${text}`);
18
+ return { messageId: 1 };
19
+ },
20
+ };
21
+
22
+ export const sendTelegram = action("telegram.send", {
23
+ description: "Send a text message to a Telegram chat.",
24
+ input: z.object({
25
+ text: z.string(),
26
+ chat: z.string().optional(),
27
+ }),
28
+ output: z.object({ messageId: z.number() }),
29
+
30
+ // What is allowed after a call that was cut off by a crash:
31
+ // "repeat" safe to call again
32
+ // "repeat-with-key" safe, the other side dedupes by the operation id we pass
33
+ // "do-not-repeat" the message may already have been delivered
34
+ recovery: "do-not-repeat",
35
+
36
+ // What a call changes: "read", "record" (only niwa's own records), "write" or
37
+ // "irreversible", and where: "niwa", "local" or "external". A hold refuses writes, and only
38
+ // a rule that names an irreversible action grants it.
39
+ effect: "write",
40
+ world: "external",
41
+
42
+ run: async ({ text, chat }) => bot.send(chat ?? ownerChat, text),
43
+ });
44
+
45
+ // A plugin registers the action with the host. After this, the action is in
46
+ // the list of what niwa can do, and `niwa.call(sendTelegram, ...)` works. `sendTelegram`
47
+ // is a typed value: the type checker knows its input and its output, and a client that
48
+ // imports it calls it the same way the host does. (A bare name "telegram.send" is accepted
49
+ // too, and then nothing is checked.)
50
+ //
51
+ // export default plugin("notify", (api) => {
52
+ // api.action(sendTelegram);
53
+ // });
54
+ //
55
+ // An action of a module is split in two: a typed reference, `actionRef(name, {description,
56
+ // input, output})`, which a caller imports, and the real action made from it,
57
+ // `action(ref, {recovery, run})`, which the module's factory registers. The schemas live in
58
+ // the reference only, so the two cannot drift. `taskCreate` from "@niwa-labs/tasks" is such a
59
+ // reference.
60
+
61
+ // An agent sees the tool `telegram_send` with this schema.
62
+ // A person in a terminal runs:
63
+ //
64
+ // niwa telegram send --text "done"
@@ -0,0 +1,68 @@
1
+ // A plugin file: a host loads it with `niwa.use(...)`; run on its own it does nothing. Its step
2
+ // asks a session of the harness `mcode-work`, so that host needs MiniMax Code installed.
3
+ //
4
+ // A step is a recorded boundary inside an invocation: the intent is recorded,
5
+ // the call is made, the outcome is recorded.
6
+ //
7
+ // An invocation is this handler woken by one record. It is durable.
8
+
9
+ import { plugin } from "@niwa-labs/plugin";
10
+ import { sessionAsk } from "@niwa-labs/sessions";
11
+ import { TaskDone } from "@niwa-labs/tasks";
12
+ import { z } from "zod";
13
+
14
+ import { sendTelegram } from "./03-action.ts";
15
+
16
+ // The shape of the answer. The session is given it as a JSON schema, and the value that comes
17
+ // back is `unknown` until it is parsed with the same schema.
18
+ const Short = z.object({ text: z.string() });
19
+
20
+ export default plugin("notify", (api) => {
21
+ api.on(TaskDone, async (done, step) => {
22
+ // A task can end without a result: only a result is worth shortening.
23
+ if (done.outcome.status !== "result") return;
24
+
25
+ // Step 1. `await step(...)` returns the value; `sessionAsk` is a typed reference,
26
+ // so the input and the `{ value }` it returns are checked. The value passed the schema the
27
+ // session was given, but its type is `unknown`: parse it before reading its fields.
28
+ const asked = await step(sessionAsk, {
29
+ session: "mcode-work s_01",
30
+ prompt: `Shorten this result to three lines:\n${String(done.outcome.result)}`,
31
+ schema: z.toJSONSchema(Short),
32
+ });
33
+ const short = Short.parse(asked.value);
34
+
35
+ // Step 2.
36
+ await step(sendTelegram, { text: short.text });
37
+ });
38
+
39
+ // Code that wants to decide for itself asks for the outcome instead.
40
+ api.on(TaskDone, { id: "notify-carefully" }, async (done, step) => {
41
+ const sent = await step.outcome(sendTelegram, { text: done.task });
42
+
43
+ if (sent.status === "unknown") {
44
+ // The call was cut off. The message may or may not have been delivered.
45
+ }
46
+ // sent.status is "completed" | "denied" | "failed" | "unknown"
47
+ });
48
+ });
49
+
50
+ // The process dies between the steps:
51
+ // after restart the invocation runs again, step 1 returns its recorded value,
52
+ // step 2 runs.
53
+ //
54
+ // The process dies in the middle of step 2:
55
+ // sendTelegram says "do-not-repeat", so the step ends as "unknown".
56
+ // With plain `await step(...)` the invocation is paused with that outcome and
57
+ // becomes a request: retry, skip or cancel. Nothing is retried blindly.
58
+ //
59
+ // A step has a key inside its invocation: by default the order of the call.
60
+ // Give an explicit key where order can change:
61
+ //
62
+ // await step(sendTelegram, { text }, { key: `notify:${task.id}` });
63
+ //
64
+ // The same key with a different input is a mismatch and pauses the invocation.
65
+ // It never silently sends a second message.
66
+ //
67
+ // Code between steps must be reproducible. The clock and random numbers
68
+ // are read through steps too.
@@ -0,0 +1,51 @@
1
+ // A plugin file: a host loads it with `niwa.use(...)`; run on its own it does nothing.
2
+ //
3
+ // A handler reacts after something happened. An intercept runs before an action.
4
+ // There are two kinds: `adjust` may change the input, `guard` may deny it.
5
+ //
6
+ // The order is fixed: the requested input is validated, all
7
+ // adjusts run, the adjusted input is validated again, then all guards run on that final input.
8
+ // Nothing a guard approved can be changed afterwards.
9
+
10
+ import { deny } from "@niwa-labs/core";
11
+ import { plugin } from "@niwa-labs/plugin";
12
+ import { executor, taskCreate } from "@niwa-labs/tasks";
13
+ import { sessionStart } from "@niwa-labs/sessions";
14
+ import { sendTelegram } from "./03-action.ts";
15
+
16
+ // Stand-ins: not part of niwa. Where the lessons of a harness come from, and what counts as night.
17
+ function lessonsFor(harness: string): string {
18
+ return `Lessons learned on ${harness}: run the tests before you report.`;
19
+ }
20
+ function isNight(): boolean {
21
+ const hour = new Date().getHours();
22
+ return hour >= 23 || hour < 7;
23
+ }
24
+
25
+ export default plugin("policies", (api) => {
26
+ // Choosing who does the work: reading goes to a cheap model
27
+ // unless the caller already chose.
28
+ api.adjust(taskCreate, (task) => {
29
+ if (task.kind === "read" && !task.responsible) {
30
+ return { ...task, responsible: executor("mcode-work") };
31
+ }
32
+ });
33
+
34
+ // Lessons go into the prompt of every new session of that kind of work.
35
+ // A caller may pass the prompt as plain text or as `{ sections }`; by the time an intercept
36
+ // sees it, it has been validated into `{ sections }`, each with an id and a tier, so several
37
+ // plugins can add their own without breaking each other's cache.
38
+ api.adjust(sessionStart, (start) => ({
39
+ ...start,
40
+ prompt: {
41
+ sections: [...start.prompt.sections, { id: "lessons", tier: "stable" as const, text: lessonsFor(start.harness) }],
42
+ },
43
+ }));
44
+
45
+ // A refusal. It is recorded, with the reason.
46
+ api.guard(sendTelegram, () => {
47
+ if (isNight()) return deny("no messages at night");
48
+ });
49
+ });
50
+
51
+ // Returning nothing lets the action pass unchanged.
@@ -0,0 +1,79 @@
1
+ // A client: it needs a live host serving `~/.niwa` (see 01-my-harness.ts) with the harnesses
2
+ // `claude-personal` and `codex` installed.
3
+ //
4
+ // Sessions of any harness are read the same way: old ones, running ones,
5
+ // and ones started without niwa.
6
+ //
7
+ // Every call here is `niwa.call(typedAction, input)`. The typed actions are imported
8
+ // from the module that owns them; the type checker knows the input and the output of
9
+ // each, on the host and on a client. `niwa` is the host (`createNiwa`) or a client
10
+ // (`connect`): there is no `niwa.sessions` and no `niwa.harness(...)`.
11
+
12
+ import { connect } from "@niwa-labs/client";
13
+ import { harnessSupports } from "@niwa-labs/sessions";
14
+ import { sessionAsk, sessionList, sessionRead, sessionSend, sessionStart } from "@niwa-labs/sessions";
15
+ import { z } from "zod";
16
+
17
+ // Stand-in: not part of niwa. Where the lines of the transcript are shown.
18
+ function print(...parts: string[]): void {
19
+ console.log(parts.join(" "));
20
+ }
21
+
22
+ const niwa = await connect({ home: "~/.niwa" });
23
+
24
+ // The sessions niwa knows about, of one harness.
25
+ const { sessions, unreadable } = await niwa.call(sessionList, { harness: "claude-personal" });
26
+ for (const s of sessions) {
27
+ console.log(s.ref, s.cwd, s.state);
28
+ }
29
+ // A harness whose sessions could not be listed is named, not skipped silently.
30
+ for (const u of unreadable) console.log("could not read", u.harness, u.reason);
31
+
32
+ // The transcript of one session, through the harness's reading side.
33
+ const [first] = sessions;
34
+ if (first === undefined) throw new Error("no sessions of claude-personal yet");
35
+ const { records, coverage } = await niwa.call(sessionRead, { session: first.ref });
36
+ for (const rec of records) {
37
+ if (rec.kind === "assistant") print(rec.text);
38
+ if (rec.kind === "tool-call") print("tool:", rec.name);
39
+ if (rec.kind === "compaction") print("the harness compacted its context:", rec.summary);
40
+ if (rec.kind === "nested") print("nested session:", rec.child.harness, rec.child.native);
41
+ // The harness's own record, whole, is asked for separately; nothing is lost.
42
+ }
43
+ // `coverage` says how much was read: only "empty" says there is nothing.
44
+
45
+ // Starting a session and asking for an answer that must match a schema.
46
+ // The schema is one zod value: the session is given it as a JSON schema, and the answer,
47
+ // which comes back as `unknown`, is parsed with it before its fields are read.
48
+ const Verdict = z.object({ safe: z.boolean(), why: z.string() });
49
+
50
+ const { session } = await niwa.call(sessionStart, {
51
+ harness: "codex",
52
+ cwd: "~/projects/niwa",
53
+ prompt: "Find where the input hash is computed.",
54
+ });
55
+
56
+ const { value } = await niwa.call(sessionAsk, {
57
+ session,
58
+ prompt: "Is it safe to change?",
59
+ // The schema the answer must pass, as a JSON schema.
60
+ schema: z.toJSONSchema(Verdict),
61
+ });
62
+ const verdict = Verdict.parse(value);
63
+
64
+ if (!verdict.safe) console.log(verdict.why);
65
+
66
+ // Sending to a session that is busy returns an honest receipt.
67
+ const { receipt } = await niwa.call(sessionSend, { session, message: "Also check the tests." });
68
+ // receipt.status is "delivered" | "queued" | "started" | "handled"
69
+
70
+ // What a harness cannot do is refused explicitly, never silently ignored.
71
+ // "Can harness X do Y" is an action too: `harness.supports`.
72
+ const { supported } = await niwa.call(harnessSupports, {
73
+ harness: "codex",
74
+ side: "control",
75
+ ability: "interrupt",
76
+ });
77
+ if (!supported) {
78
+ // do not offer an interrupt, or choose another harness
79
+ }
@@ -0,0 +1,37 @@
1
+ // A client: it needs a live host serving `~/.niwa` (see 01-my-harness.ts) with the tasks module
2
+ // and the harness `codex` installed.
3
+ //
4
+ // A task is a contract: what to do, who asked, who is responsible, where to report,
5
+ // how it ended. Assign it and you are free.
6
+ //
7
+ // `taskCreate` and `taskResult` are typed actions of the tasks module. `niwa` is the host
8
+ // or a client; there is no `niwa.tasks`.
9
+
10
+ import { connect } from "@niwa-labs/client";
11
+ import { owner } from "@niwa-labs/core";
12
+ import { executor, taskCreate, taskResult } from "@niwa-labs/tasks";
13
+
14
+ const niwa = await connect({ home: "~/.niwa" });
15
+
16
+ const task = await niwa.call(taskCreate, {
17
+ kind: "change", // an open label: what sort of work this is
18
+ description: "Split argument parsing", // a few words a list shows
19
+ text: "Move argument parsing into its own module.",
20
+ askedBy: owner, // who asks
21
+ responsible: executor("codex"), // one address; here, an agent in that harness
22
+ reportTo: owner, // where updates and the result go
23
+ });
24
+
25
+ // The task is already running in the background. Nothing here waits.
26
+ console.log(task.id);
27
+
28
+ // When you do want the result: this works whether the task finished a second ago
29
+ // or will finish next week.
30
+ const done = await niwa.call(taskResult, { task: task.id });
31
+ console.log(done.outcome.status, done.outcome);
32
+
33
+ // How the work gets done is the business of the responsible party, not of the task.
34
+ // A strong model simply does it. A different way of working (a second session
35
+ // kept beside a weak executor to keep it on course, a review before acceptance,
36
+ // several attempts in a race) is a strategy: a plugin that accepts the task as the
37
+ // responsible party. None is shipped: a composition writes the ones it needs.