@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/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,11 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/cli
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 niwa command line as a library: a client of a host and nothing more.
4
+
5
+ The commands that are actions are generated from what the host describes, so a plugin that
6
+ declares a new action has a command at once. `niwa log` reads the journal the way a person reads
7
+ a log, `niwa insert report` carries an event from inside a harness to the host, and `niwa skill`
8
+ prints and installs the skill niwa ships.
9
+
10
+ Starting a host, the cockpit or the MCP server is not here: those commands compose other
11
+ packages. The kinds of harness that read skills are given to `runSkill` by whoever runs it.
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@niwa-labs/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@niwa-labs/client": "0.0.0",
11
+ "@niwa-labs/core": "0.0.0",
12
+ "zod": "^4.6.7"
13
+ },
14
+ "devDependencies": {
15
+ "@niwa-labs/testing": "0.0.0"
16
+ }
17
+ }
package/src/agent.ts ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * `niwa agent attach [<agent>]`: attach the native session this command runs in to an agent.
3
+ *
4
+ * The agent of a native session runs the command from its own shell, so the harness and the session are
5
+ * read from the environment the harness gives its tools. ZCode is asked first: it sets the variables of
6
+ * Claude Code as well as its own. mcode names no session in the environment: the command takes
7
+ * `--session <id>`, or the latest mcode session of the directory once it is confirmed. A command that can
8
+ * tell no session is refused, saying what it looked for.
9
+ *
10
+ * The CLI runs as the owner here (a native session is not a session niwa started), so the attachment is
11
+ * the owner's act. The answer is the agent's briefing.
12
+ */
13
+
14
+ import { actionName } from "@niwa-labs/core";
15
+ import type { NiwaApi } from "@niwa-labs/client";
16
+
17
+ /** The usage of the command. */
18
+ export const AGENT_USAGE = "niwa agent attach [<agent>] [--session <id>] [--kind <kind>] [--harness <name>] [--yes]";
19
+
20
+ /** The variables a harness names its session by, in the order they are asked. */
21
+ const SESSION_VARIABLES = [
22
+ { variable: "ZCODE_SESSION_ID", kind: "zcode" },
23
+ { variable: "CODEX_THREAD_ID", kind: "codex" },
24
+ { variable: "PI_SESSION_ID", kind: "pi" },
25
+ { variable: "CLAUDE_CODE_SESSION_ID", kind: "claude-code" },
26
+ ] as const;
27
+
28
+ /** The session a command runs in, as its environment names it. */
29
+ export interface CallerSession {
30
+ /** The kind of harness. */
31
+ readonly kind: string;
32
+ /** The harness's own id of the session. */
33
+ readonly native: string;
34
+ /** The variable it was read from. */
35
+ readonly from: string;
36
+ /** The process of the harness, when the environment names it. */
37
+ readonly pid?: number;
38
+ }
39
+
40
+ /** The session the environment names, or nothing when it names none. */
41
+ export function callerSession(env: Readonly<Record<string, string | undefined>>): CallerSession | undefined {
42
+ for (const { variable, kind } of SESSION_VARIABLES) {
43
+ const native = env[variable]?.trim();
44
+ if (native === undefined || native === "") continue;
45
+ const pid = kind === "claude-code" ? Number(env.CLAUDE_PID) : Number.NaN;
46
+ return { kind, native, from: variable, ...(Number.isInteger(pid) && pid > 0 ? { pid } : {}) };
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /** What the command reads besides its arguments. */
52
+ export interface AgentCommandContext {
53
+ readonly env: Readonly<Record<string, string | undefined>>;
54
+ readonly cwd: string;
55
+ }
56
+
57
+ /** What the command did: the text to print, or the reason it was refused. */
58
+ export type AgentCommandResult = { readonly ok: true; readonly answer: { briefing: string } & Record<string, unknown> } | { readonly ok: false; readonly reason: string };
59
+
60
+ interface Parsed {
61
+ agent?: string;
62
+ session?: string;
63
+ kind?: string;
64
+ harness?: string;
65
+ yes: boolean;
66
+ }
67
+
68
+ function parse(args: readonly string[]): Parsed | string {
69
+ const parsed: Parsed = { yes: false };
70
+ for (let index = 0; index < args.length; index += 1) {
71
+ const argument = args[index]!;
72
+ if (argument === "--yes") parsed.yes = true;
73
+ else if (argument === "--session" || argument === "--kind" || argument === "--harness") {
74
+ const value = args[index + 1];
75
+ if (value === undefined || value.startsWith("--")) return `${argument} needs a value`;
76
+ if (argument === "--session") parsed.session = value;
77
+ else if (argument === "--kind") parsed.kind = value;
78
+ else parsed.harness = value;
79
+ index += 1;
80
+ } else if (argument.startsWith("--")) return `unknown option ${argument}`;
81
+ else if (parsed.agent === undefined) parsed.agent = argument;
82
+ else return `one agent at most, not "${parsed.agent}" and "${argument}"`;
83
+ }
84
+ return parsed;
85
+ }
86
+
87
+ /** The kind of harness whose sessions name no id in the environment, and are found by their directory. */
88
+ const MCODE = "mcode";
89
+
90
+ /** The latest mcode session of a directory, as the host lists it. */
91
+ async function latestMcode(api: NiwaApi, cwd: string): Promise<{ native: string; title?: string } | undefined> {
92
+ const { items } = (await api.call(actionName("harness.list"), {})) as { items: { name: string; kind: string }[] };
93
+ for (const item of items.filter((one) => one.kind === MCODE)) {
94
+ const { sessions } = (await api.call(actionName("session.list"), { harness: item.name, cwd, limit: 1 })) as { sessions: { ref: string; title?: string }[] };
95
+ const [latest] = sessions;
96
+ if (latest !== undefined) return { native: latest.ref.slice(latest.ref.indexOf(" ") + 1), ...(latest.title === undefined ? {} : { title: latest.title }) };
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ /** Run `niwa agent <subcommand>`. */
102
+ export async function runAgentCommand(api: NiwaApi, args: readonly string[], context: AgentCommandContext): Promise<AgentCommandResult> {
103
+ const [subcommand, ...rest] = args;
104
+ if (subcommand !== "attach") return { ok: false, reason: `usage: ${AGENT_USAGE}` };
105
+ const parsed = parse(rest);
106
+ if (typeof parsed === "string") return { ok: false, reason: `${parsed}\nusage: ${AGENT_USAGE}` };
107
+
108
+ const found = callerSession(context.env);
109
+ let session: { kind: string; native: string; pid?: number };
110
+ if (parsed.session !== undefined) {
111
+ session = { kind: parsed.kind ?? found?.kind ?? MCODE, native: parsed.session };
112
+ } else if (found !== undefined) {
113
+ session = { kind: parsed.kind ?? found.kind, native: found.native, ...(found.pid === undefined ? {} : { pid: found.pid }) };
114
+ } else {
115
+ const latest = await latestMcode(api, context.cwd);
116
+ if (latest === undefined) {
117
+ return {
118
+ ok: false,
119
+ reason: [
120
+ "this command cannot tell which session it runs in:",
121
+ `none of ${SESSION_VARIABLES.map((one) => one.variable).join(", ")} is set, and no mcode session works in ${context.cwd}.`,
122
+ "Run it from the native session, or name the session with --session <id> (and its harness with --kind <kind>).",
123
+ ].join(" "),
124
+ };
125
+ }
126
+ if (!parsed.yes) {
127
+ return {
128
+ ok: false,
129
+ reason: `mcode names no session to its tools; the latest mcode session in ${context.cwd} is mcode ${latest.native}${latest.title === undefined ? "" : ` (${latest.title})`}. Attach it with --yes, or name another with --session <id>.`,
130
+ };
131
+ }
132
+ session = { kind: MCODE, native: latest.native };
133
+ }
134
+
135
+ const answer = (await api.call(actionName("agent.attach"), {
136
+ ...(parsed.agent === undefined ? {} : { agent: parsed.agent }),
137
+ // The installation, when the host has several of the kind: the kind alone is refused then.
138
+ ...(parsed.harness === undefined ? { kind: session.kind } : { harness: parsed.harness }),
139
+ native: session.native,
140
+ cwd: context.cwd,
141
+ ...(session.pid === undefined ? {} : { pid: session.pid }),
142
+ })) as { briefing: string } & Record<string, unknown>;
143
+ return { ok: true, answer };
144
+ }