nemu-cli 1.3.2 → 1.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.0
4
+
5
+ `nemu login key` signs in with a workspace API key, the same `sk_` key that calls the gateway. It
6
+ asks for the key, or reads `NEMU_API_KEY`, and shows the workspace and access the key has. Context
7
+ and vault commands use the unified routes under `/api/v1`, and work in the workspace you choose, so
8
+ members share the workspace's Context. Earlier versions call routes that no longer exist and need
9
+ this update.
10
+
11
+ ## 1.4.0
12
+
13
+ `nemu setup opencode` adds the Nemu MCP server to OpenCode's global config,
14
+ `~/.config/opencode/opencode.json` (or `opencode.jsonc` when that is the file you have), as a local
15
+ server that runs `nemu mcp --client opencode`. Like the other editors, only the `nemu` entry is
16
+ written, the previous file is kept with a `.nemu-backup` suffix, `nemu uninstall opencode` removes
17
+ it, `nemu status` lists it and `nemu mcp config opencode` prints it.
18
+
19
+ The Stop hook no longer shows up as "Stop hook error" after every few edits. Claude Code shows any
20
+ Stop request that way, so the reminder to save a handoff now arrives quietly after the third edit,
21
+ as context the agent reads and you do not see. Stop asks at most once per session, and only when the
22
+ work is still unsaved. Saving with `memory_write` resets the count. Only files inside the project
23
+ count, so an agent's scratchpad or a temp folder no longer triggers a request, and the reminder no
24
+ longer tells the agent to hide it from you.
25
+
26
+ On Windows, `git`, editors and every other command the CLI starts are now found on `PATH` only.
27
+ Before, the current folder was searched first, so a `git.cmd` inside a cloned repository ran in
28
+ place of the real git.
29
+
30
+ `nemu setup`, `nemu uninstall` and the update repair keep the permissions of
31
+ `~/.claude/settings.json` and `~/.codex/hooks.json`. A file you locked to `0600` used to come back
32
+ readable by every user on the machine. Files the CLI creates from nothing are now `0600`.
33
+
34
+ `nemu login` opens the sign-in page only when it is on the same server the CLI talks to, over https
35
+ (or http on localhost), and on Windows it opens it without going through `cmd`. It now opens the
36
+ page without the code filled in, matching the device page, so you type the code shown in the
37
+ terminal.
38
+
3
39
  ## 1.3.2
4
40
 
5
41
  After an update, the CLI checks once whether what setup installed still matches what this version
package/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -141,14 +141,17 @@ nemu setup claude # or: nemu setup codex (aliases: cc, claude-code)
141
141
 
142
142
  Setup registers a `nemu` MCP server with the client through the client's own command
143
143
  (`claude mcp add --scope user`, `codex mcp add`) and asks whether to install hooks. Hooks load the
144
- project's notes when a session starts and ask the agent to save a handoff before it stops. Codex runs
144
+ project's notes when a session starts and, after a few edits inside the project, remind the agent to
145
+ save a handoff when it finishes. If the work is still unsaved when the agent stops, the Stop hook asks
146
+ once per session (Claude Code shows that one request as "Stop hook error"). Codex runs
145
147
  hooks only after you trust them once with `/hooks`. Pass `--hooks`, `--no-hooks` or `--yes` to skip
146
148
  the question.
147
149
 
148
- Editors work the same way without hooks: `nemu setup cursor`, `vscode`, `gemini`, `windsurf` or
149
- `zed` writes only the `nemu` entry into that editor's config (`~/.cursor/mcp.json`, VS Code's user
150
- `mcp.json` through `code --add-mcp`, `~/.gemini/settings.json`,
151
- `~/.codeium/windsurf/mcp_config.json`, Zed's `settings.json`). Everything else in the file,
150
+ Editors work the same way without hooks: `nemu setup cursor`, `vscode`, `gemini`, `windsurf`, `zed`
151
+ or `opencode` writes only the `nemu` entry into that editor's config (`~/.cursor/mcp.json`, VS Code's
152
+ user `mcp.json` through `code --add-mcp`, `~/.gemini/settings.json`,
153
+ `~/.codeium/windsurf/mcp_config.json`, Zed's `settings.json`, OpenCode's
154
+ `~/.config/opencode/opencode.json` or `opencode.jsonc`). Everything else in the file,
152
155
  comments included, stays as it was, the previous file is kept with a `.nemu-backup` suffix, and a
153
156
  file that cannot be parsed is never touched.
154
157
 
@@ -160,7 +163,7 @@ file that cannot be parsed is never touched.
160
163
  | `nemu claude load sessions [--limit n]` | Open Claude with your recent sessions and let it save what matters |
161
164
  | `nemu codex load sessions [--limit n]` | The same for Codex |
162
165
  | `nemu mcp` | The stdio MCP bridge clients start; it uses your login and refreshes it |
163
- | `nemu mcp config <client>` | Config for `cursor`, `gemini`, `vscode`, `windsurf`, `zed`, `claude`, `codex`, `remote` |
166
+ | `nemu mcp config <client>` | Config for `cursor`, `gemini`, `vscode`, `windsurf`, `zed`, `opencode`, `claude`, `codex`, `remote` |
164
167
  | `nemu context` | What an agent sees for this folder |
165
168
  | `nemu context search <words>` | Search this project's notes |
166
169
  | `nemu context projects` / `export --out file` | List projects, or export everything as JSON |
@@ -97,7 +97,7 @@ export async function fresh_credentials() {
97
97
  if (current === null) {
98
98
  throw new CliError("Not signed in. Run nemu login.", "not_signed_in");
99
99
  }
100
- if (is_fresh(current))
100
+ if (current.kind === "key" || is_fresh(current))
101
101
  return current;
102
102
  const release = await acquire_lock();
103
103
  try {
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { access } from "node:fs/promises";
2
3
  import { homedir } from "node:os";
3
4
  import { basename, join } from "node:path";
@@ -37,6 +38,13 @@ function vscode_user_dir() {
37
38
  return join(home(), "Library", "Application Support", "Code", "User");
38
39
  return join(config_home(), "Code", "User");
39
40
  }
41
+ function opencode_dir() {
42
+ return join(config_home(), "opencode");
43
+ }
44
+ function opencode_config() {
45
+ const jsonc = join(opencode_dir(), "opencode.jsonc");
46
+ return existsSync(jsonc) ? jsonc : join(opencode_dir(), "opencode.json");
47
+ }
40
48
  function zed_dir() {
41
49
  return on_windows() ? join(app_data(), "Zed") : join(config_home(), "zed");
42
50
  }
@@ -56,10 +64,13 @@ export function is_nemu_entry(value) {
56
64
  if (typeof value !== "object" || value === null)
57
65
  return false;
58
66
  const entry = value;
59
- if (typeof entry.command !== "string" || !Array.isArray(entry.args))
67
+ const [command, first] = Array.isArray(entry.command)
68
+ ? [entry.command[0], entry.command[1]]
69
+ : [entry.command, Array.isArray(entry.args) ? entry.args[0] : undefined];
70
+ if (typeof command !== "string")
60
71
  return false;
61
- const program = basename(entry.command.replaceAll("\\", "/")).replace(/\.(cmd|exe|ps1)$/i, "");
62
- return program === "nemu" && entry.args[0] === "mcp";
72
+ const program = basename(command.replaceAll("\\", "/")).replace(/\.(cmd|exe|ps1)$/i, "");
73
+ return program === "nemu" && first === "mcp";
63
74
  }
64
75
  async function guard_foreign(path, keys) {
65
76
  const existing = await read_entry(path, keys);
@@ -120,6 +131,7 @@ export const EDITORS = {
120
131
  ...(on_mac() ? ["/Applications/Windsurf.app"] : []),
121
132
  ]), (nemu) => bridge(nemu, "windsurf"), ["Restart Windsurf, or refresh the MCP servers in Cascade."]),
122
133
  zed: file_editor("zed", "Zed", () => join(zed_dir(), "settings.json"), () => ["context_servers", MCP_NAME], () => any_present(["zed"], [zed_dir(), ...(on_mac() ? ["/Applications/Zed.app"] : [])]), (nemu) => ({ ...bridge(nemu, "zed"), env: {} }), ["Zed picks the server up by itself. Open the Agent panel settings to check it is running."]),
134
+ opencode: file_editor("opencode", "OpenCode", opencode_config, () => ["mcp", MCP_NAME], () => any_present(["opencode"], [opencode_dir(), join(home(), ".opencode")]), (nemu) => ({ type: "local", command: [nemu, "mcp", "--client", "opencode"], enabled: true }), ["Start OpenCode and run opencode mcp list to see the nemu server."]),
123
135
  };
124
136
  const ALIASES = {
125
137
  cursor: "cursor",
@@ -130,6 +142,8 @@ const ALIASES = {
130
142
  "gemini-cli": "gemini",
131
143
  windsurf: "windsurf",
132
144
  zed: "zed",
145
+ opencode: "opencode",
146
+ "open-code": "opencode",
133
147
  };
134
148
  export function editor_from_name(name) {
135
149
  const id = ALIASES[(name ?? "").toLowerCase()];
@@ -1,11 +1,11 @@
1
- import { readFile, writeFile, mkdir, rename, copyFile, access } from "node:fs/promises";
1
+ import { readFile, writeFile, mkdir, rename, copyFile, access, chmod, stat } from "node:fs/promises";
2
2
  import { dirname, win32 } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { CliError } from "../errors.js";
5
5
  export const HOOK_SPECS = {
6
6
  "claude-code": [
7
7
  { event: "SessionStart", hook: "start", matcher: "startup|resume|clear|compact", timeout: 20 },
8
- { event: "PostToolUse", hook: "tool", matcher: "Edit|Write|MultiEdit|NotebookEdit", timeout: 5 },
8
+ { event: "PostToolUse", hook: "tool", matcher: "Edit|Write|MultiEdit|NotebookEdit|mcp__nemu__memory_write", timeout: 5 },
9
9
  { event: "Stop", hook: "stop", timeout: 10 },
10
10
  { event: "PreCompact", hook: "compact", matcher: "manual|auto", timeout: 5 },
11
11
  { event: "SessionEnd", hook: "end", timeout: 3 },
@@ -80,8 +80,10 @@ async function write_config(path, config) {
80
80
  const backup = `${path}.nemu-backup`;
81
81
  if ((await exists(path)) && !(await exists(backup)))
82
82
  await copyFile(path, backup);
83
+ const mode = (await exists(path)) ? (await stat(path)).mode & 0o777 : 0o600;
83
84
  const temporary = `${path}.${process.pid}.tmp`;
84
- await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
85
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { encoding: "utf-8", mode });
86
+ await chmod(temporary, mode).catch(() => undefined);
85
87
  await rename(temporary, path);
86
88
  }
87
89
  function without_own(config) {
@@ -47,7 +47,7 @@ function parse_object(path, text) {
47
47
  }
48
48
  async function write_atomic(path, text, original) {
49
49
  await mkdir(dirname(path), { recursive: true });
50
- const mode = original === null ? 0o644 : (await stat(path)).mode & 0o777;
50
+ const mode = original === null ? 0o600 : (await stat(path)).mode & 0o777;
51
51
  const backup = original === null ? null : `${path}${BACKUP_SUFFIX}`;
52
52
  if (backup !== null)
53
53
  await copyFile(path, backup);
@@ -65,7 +65,7 @@ export function client_from_name(name) {
65
65
  case "codex":
66
66
  return CLIENTS.codex;
67
67
  default:
68
- throw new CliError("Pick a client: claude (aliases cc, claude-code), codex, cursor, vscode, gemini, windsurf or zed. Others: nemu mcp config <client>", "invalid_client");
68
+ throw new CliError("Pick a client: claude (aliases cc, claude-code), codex, cursor, vscode, gemini, windsurf, zed or opencode. Others: nemu mcp config <client>", "invalid_client");
69
69
  }
70
70
  }
71
71
  export async function client_installed(spec) {
@@ -1,4 +1,4 @@
1
- import { join } from "node:path";
1
+ import { isAbsolute, join, relative, resolve } from "node:path";
2
2
  import { mkdir, readFile, readdir, rm, stat, appendFile } from "node:fs/promises";
3
3
  import { z } from "zod";
4
4
  import { flag } from "../args.js";
@@ -35,6 +35,8 @@ const state_schema = z.object({
35
35
  edits_since_checkpoint: z.number(),
36
36
  last_asked_at: z.number().nullable(),
37
37
  compacted: z.boolean(),
38
+ nudged: z.boolean().default(false),
39
+ stop_asked: z.boolean().default(false),
38
40
  updated_at: z.number(),
39
41
  });
40
42
  const pending_schema = z.record(z.string(), z.object({ files: z.array(z.string()), ended_at: z.number(), client: z.string() }));
@@ -132,6 +134,8 @@ async function on_start(client, input) {
132
134
  edits_since_checkpoint: 0,
133
135
  last_asked_at: null,
134
136
  compacted: false,
137
+ nudged: false,
138
+ stop_asked: false,
135
139
  updated_at: Date.now(),
136
140
  };
137
141
  await write_private(state_path(client, session), JSON.stringify({ ...state, branch: info.branch, updated_at: Date.now() }));
@@ -204,26 +208,65 @@ function paths_from_tool(input) {
204
208
  return [...found];
205
209
  }
206
210
  const EDITING_TOOL = /edit|write|patch|notebook|create|delete|move|rename/i;
211
+ const SAVING_TOOL = /memory_write$/;
212
+ export function project_file(root, cwd, file) {
213
+ const absolute = isAbsolute(file) ? file : resolve(cwd, file);
214
+ const inside = relative(root, absolute);
215
+ if (inside.length === 0 || inside.startsWith("..") || isAbsolute(inside))
216
+ return null;
217
+ return inside.replaceAll("\\", "/");
218
+ }
219
+ function emit_tool_context(text) {
220
+ process.stdout.write(`${JSON.stringify({
221
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text },
222
+ })}\n`);
223
+ }
224
+ function save_request(state) {
225
+ const recent = state.since_checkpoint.slice(-10);
226
+ return [
227
+ `Nemu Context: when this task is done, save a handoff named '${handoff_name(state.branch)}' with memory_write (what changed, what is unfinished, the next step), and any durable fact you learned under its own '<tag>/<name>'.`,
228
+ `Files changed since the last save: ${recent.join(", ")}${state.since_checkpoint.length > recent.length ? ", ..." : ""}.`,
229
+ `Never save secrets. If nothing is worth saving, skip it.`,
230
+ ].join("\n");
231
+ }
207
232
  async function on_tool(client, input) {
208
- if (input.tool_name !== undefined && !EDITING_TOOL.test(input.tool_name))
209
- return;
210
233
  const session = input.session_id ?? "unknown";
211
234
  const path = state_path(client, session);
235
+ if (input.tool_name !== undefined && SAVING_TOOL.test(input.tool_name)) {
236
+ const state = await read_json_file(path, state_schema);
237
+ if (state === null)
238
+ return;
239
+ await write_private(path, JSON.stringify({
240
+ ...state,
241
+ edits_since_checkpoint: 0,
242
+ since_checkpoint: [],
243
+ compacted: false,
244
+ nudged: false,
245
+ updated_at: Date.now(),
246
+ }));
247
+ return;
248
+ }
249
+ if (input.tool_name !== undefined && !EDITING_TOOL.test(input.tool_name))
250
+ return;
212
251
  const state = await read_json_file(path, state_schema);
213
252
  if (state === null)
214
253
  return;
215
- const files = paths_from_tool(input).map((file) => file.startsWith(state.root) ? file.slice(state.root.length).replace(/^[\\/]+/, "") : file);
254
+ const files = paths_from_tool(input)
255
+ .map((file) => project_file(state.root, input.cwd ?? state.cwd, file))
256
+ .filter((file) => file !== null);
216
257
  if (files.length === 0)
217
258
  return;
218
- const merged = [...new Set([...state.files, ...files])].slice(-MAX_FILES);
219
- const recent = [...new Set([...state.since_checkpoint, ...files])].slice(-MAX_FILES);
220
- await write_private(path, JSON.stringify({
259
+ const next = {
221
260
  ...state,
222
- files: merged,
223
- since_checkpoint: recent,
261
+ files: [...new Set([...state.files, ...files])].slice(-MAX_FILES),
262
+ since_checkpoint: [...new Set([...state.since_checkpoint, ...files])].slice(-MAX_FILES),
224
263
  edits_since_checkpoint: state.edits_since_checkpoint + files.length,
225
264
  updated_at: Date.now(),
226
- }));
265
+ };
266
+ const nudge = client === "claude-code" && !next.nudged && next.edits_since_checkpoint >= CHECKPOINT_EDITS;
267
+ await write_private(path, JSON.stringify(nudge ? { ...next, nudged: true } : next));
268
+ if (nudge)
269
+ emit_tool_context(save_request(next));
227
270
  }
228
271
  async function on_stop(client, input) {
229
272
  const session = input.session_id ?? "unknown";
@@ -231,32 +274,16 @@ async function on_stop(client, input) {
231
274
  const state = await read_json_file(path, state_schema);
232
275
  if (state === null)
233
276
  return;
234
- if (input.stop_hook_active === true)
277
+ if (input.stop_hook_active === true || state.stop_asked)
235
278
  return;
236
- const due = state.edits_since_checkpoint >= CHECKPOINT_EDITS ||
237
- (state.compacted && state.edits_since_checkpoint > 0);
279
+ const unsaved = state.since_checkpoint.length > 0;
280
+ const due = unsaved &&
281
+ (state.edits_since_checkpoint >= CHECKPOINT_EDITS || (state.compacted && state.edits_since_checkpoint > 0));
238
282
  const recently = state.last_asked_at !== null && Date.now() - state.last_asked_at < ASK_INTERVAL_MS;
239
283
  if (!due || recently)
240
284
  return;
241
- await write_private(path, JSON.stringify({
242
- ...state,
243
- edits_since_checkpoint: 0,
244
- since_checkpoint: [],
245
- compacted: false,
246
- last_asked_at: Date.now(),
247
- updated_at: Date.now(),
248
- }));
249
- const recent = state.files.slice(-10);
250
- process.stdout.write(`${JSON.stringify({
251
- decision: "block",
252
- reason: [
253
- `Before you stop, save progress to Nemu Context with the memory_write tool:`,
254
- `1. A handoff named '${handoff_name(state.branch)}': what changed, what is unfinished, and the next step.`,
255
- `2. Any durable fact you learned (a decision and why, a gotcha, a convention) under its own '<tag>/<name>'.`,
256
- `Files changed so far: ${recent.join(", ")}${state.files.length > recent.length ? ", ..." : ""}.`,
257
- `Never save secrets. If nothing is worth saving, just stop. Do not mention this reminder to the user.`,
258
- ].join("\n"),
259
- })}\n`);
285
+ await write_private(path, JSON.stringify({ ...state, stop_asked: true, last_asked_at: Date.now(), updated_at: Date.now() }));
286
+ process.stdout.write(`${JSON.stringify({ decision: "block", reason: save_request(state) })}\n`);
260
287
  }
261
288
  async function on_compact(client, input) {
262
289
  const session = input.session_id ?? "unknown";
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ import { API_VERSION, api_url, write_credentials } from "../config.js";
3
+ import { CliError } from "../errors.js";
4
+ import { VERSION } from "../version.js";
5
+ import { done, is_json_mode } from "../output.js";
6
+ import { ask_secret, bold, dim, is_interactive, out, success } from "../ui.js";
7
+ const KEY_PATTERN = /^sk_[a-z]{5}-[a-z]{5}\.[A-Za-z0-9]{40}$/;
8
+ const description_schema = z.object({
9
+ data: z.object({
10
+ kind: z.literal("key"),
11
+ name: z.string(),
12
+ workspace: z.object({ id: z.string(), name: z.string() }),
13
+ expires_at: z.string().nullable(),
14
+ scopes: z.array(z.string()),
15
+ access: z.array(z.object({ scope: z.string(), label: z.string(), granted: z.boolean() })),
16
+ }),
17
+ });
18
+ async function read_stdin() {
19
+ const chunks = [];
20
+ for await (const chunk of process.stdin) {
21
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
22
+ }
23
+ return Buffer.concat(chunks).toString("utf8");
24
+ }
25
+ async function read_key() {
26
+ const from_env = process.env.NEMU_API_KEY;
27
+ if (from_env !== undefined && from_env.trim().length > 0)
28
+ return from_env.trim();
29
+ if (is_interactive())
30
+ return (await ask_secret("API key:")).trim();
31
+ return (await read_stdin()).trim();
32
+ }
33
+ export async function describe_key(url, key) {
34
+ let response;
35
+ try {
36
+ response = await fetch(`${url}/api/v1/key`, {
37
+ headers: {
38
+ authorization: `Bearer ${key}`,
39
+ "nemu-api-version": API_VERSION,
40
+ "user-agent": `nemu-cli/${VERSION}`,
41
+ },
42
+ signal: AbortSignal.timeout(20_000),
43
+ });
44
+ }
45
+ catch {
46
+ throw new CliError(`Could not reach ${url}.`, "network_failed");
47
+ }
48
+ if (response.status === 401 || response.status === 403) {
49
+ throw new CliError("This key is invalid, disabled, expired or not allowed from this address.", "key_rejected");
50
+ }
51
+ const parsed = description_schema.safeParse(await response.json().catch(() => null));
52
+ if (!response.ok || !parsed.success) {
53
+ throw new CliError("Nemu could not describe this key.", "key_describe_failed", {
54
+ status: response.status,
55
+ });
56
+ }
57
+ return parsed.data.data;
58
+ }
59
+ export async function login_key() {
60
+ const url = api_url();
61
+ const key = await read_key();
62
+ if (!KEY_PATTERN.test(key)) {
63
+ throw new CliError("That is not a Nemu API key. Keys look like sk_xxxxx-xxxxx. followed by 40 letters and digits.", "invalid_key_format");
64
+ }
65
+ const description = await describe_key(url, key);
66
+ await write_credentials({
67
+ kind: "key",
68
+ access_token: key,
69
+ expires_at: Number.MAX_SAFE_INTEGER,
70
+ scope: description.scopes.join(" "),
71
+ api_url: url,
72
+ account: `key ${description.name}`,
73
+ workspace: description.workspace,
74
+ });
75
+ if (is_json_mode()) {
76
+ done("Signed in with an API key", {
77
+ key: description.name,
78
+ workspace: description.workspace,
79
+ scopes: description.scopes,
80
+ expires_at: description.expires_at,
81
+ });
82
+ return 0;
83
+ }
84
+ success(`Signed in with the key ${bold(description.name)} for the workspace ${bold(description.workspace.name)}`);
85
+ out();
86
+ for (const row of description.access) {
87
+ out(` ${row.granted ? "yes" : " no"} ${row.label}`);
88
+ }
89
+ out();
90
+ if (description.expires_at !== null) {
91
+ out(dim(` The key expires on ${description.expires_at.slice(0, 10)}.`));
92
+ }
93
+ out(dim(" The key is stored only on this machine. nemu logout removes it."));
94
+ return 0;
95
+ }
@@ -1,6 +1,7 @@
1
1
  import { NemuDeviceError } from "@nemu-ai/sdk";
2
2
  import { api_url, is_expired, read_credentials, write_credentials, } from "../config.js";
3
3
  import { device_client } from "../session.js";
4
+ import { login_key } from "./key.js";
4
5
  import { verify_device } from "../device.js";
5
6
  import { bool_flag } from "../args.js";
6
7
  import { done, is_json_mode } from "../output.js";
@@ -15,6 +16,8 @@ async function account_name(nemu) {
15
16
  }
16
17
  }
17
18
  export async function login(args) {
19
+ if (args.positional[0] === "key")
20
+ return login_key();
18
21
  const url = api_url();
19
22
  const force = bool_flag(args, "force", "f");
20
23
  const no_browser = bool_flag(args, "no-browser");
@@ -44,8 +47,10 @@ export async function login(args) {
44
47
  out(` Code ${bold(authorization.user_code)}`);
45
48
  out();
46
49
  if (!no_browser) {
47
- open_browser(authorization.verification_uri_complete);
48
- out(dim(" Opening your browser. Use the link above if it does not."));
50
+ const is_opened = open_browser(authorization.verification_uri, api_url());
51
+ out(dim(is_opened
52
+ ? " Opening your browser. Use the link above if it does not."
53
+ : " The sign-in link is not on your Nemu server, so it was not opened."));
49
54
  out();
50
55
  }
51
56
  }
@@ -8,7 +8,7 @@ import { current_project } from "../context/project.js";
8
8
  import { repository } from "../git.js";
9
9
  import { VERSION } from "../version.js";
10
10
  import { out } from "../ui.js";
11
- const CLIENTS = ["claude-code", "codex", "cursor", "zed", "gemini", "vscode", "windsurf", "mcp"];
11
+ const CLIENTS = ["claude-code", "codex", "cursor", "zed", "gemini", "vscode", "windsurf", "opencode", "mcp"];
12
12
  const rpc_schema = z.object({
13
13
  jsonrpc: z.literal("2.0"),
14
14
  id: z.union([z.string(), z.number()]).optional(),
@@ -191,9 +191,13 @@ const SNIPPETS = {
191
191
  where: "Zed settings.json",
192
192
  text: JSON.stringify({ context_servers: { nemu: { command: "nemu", args: ["mcp", "--client", "zed"] } } }, null, 2),
193
193
  },
194
+ opencode: {
195
+ where: "~/.config/opencode/opencode.json",
196
+ text: JSON.stringify({ mcp: { nemu: { type: "local", command: ["nemu", "mcp", "--client", "opencode"], enabled: true } } }, null, 2),
197
+ },
194
198
  remote: {
195
- where: "Any client that supports remote MCP over HTTP (create a Context key in the dashboard first)",
196
- text: JSON.stringify({ url: "https://app.nemu.cc/api/mcp", headers: { Authorization: "Bearer <your Context key>" } }, null, 2),
199
+ where: "Any client that supports remote MCP over HTTP (create an API key with Context access on the Keys page first)",
200
+ text: JSON.stringify({ url: "https://app.nemu.cc/api/mcp", headers: { Authorization: "Bearer <your API key>" } }, null, 2),
197
201
  },
198
202
  };
199
203
  function mcp_config(args) {
@@ -2,6 +2,7 @@ import { is_expired, read_credentials } from "../config.js";
2
2
  import { client } from "../session.js";
3
3
  import { detail, is_json_mode } from "../output.js";
4
4
  import { bold, dim, out } from "../ui.js";
5
+ import { describe_key } from "./key.js";
5
6
  export async function whoami() {
6
7
  const credentials = await read_credentials();
7
8
  if (credentials === null) {
@@ -16,6 +17,24 @@ export async function whoami() {
16
17
  out("Your session has expired. Run nemu login.");
17
18
  return 1;
18
19
  }
20
+ if (credentials.kind === "key") {
21
+ const key = await describe_key(credentials.api_url, credentials.access_token);
22
+ if (is_json_mode()) {
23
+ detail({
24
+ signed_in: true,
25
+ kind: "key",
26
+ key: key.name,
27
+ workspace: key.workspace,
28
+ scopes: key.scopes,
29
+ api_url: credentials.api_url,
30
+ });
31
+ return 0;
32
+ }
33
+ out(`${bold(`key ${key.name}`)} ${dim(`in ${key.workspace.name}`)}`);
34
+ out(dim(` ${credentials.api_url}`));
35
+ out(dim(` access ${key.scopes.join(", ") || "none"}`));
36
+ return 0;
37
+ }
19
38
  const nemu = await client();
20
39
  const account = await nemu.user.get();
21
40
  if (is_json_mode()) {
package/dist/config.js CHANGED
@@ -6,12 +6,16 @@ export const DEFAULT_API_URL = "https://app.nemu.cc";
6
6
  export const DEFAULT_CLIENT_ID = "nemu_cli";
7
7
  export const API_VERSION = "2026-07-14";
8
8
  const credentials_schema = z.object({
9
+ kind: z.enum(["oauth", "key"]).default("oauth"),
9
10
  access_token: z.string().min(1),
10
11
  refresh_token: z.string().min(1).optional(),
11
12
  expires_at: z.number(),
12
13
  scope: z.string(),
13
14
  api_url: z.string().url(),
14
15
  account: z.string().optional(),
16
+ workspace: z
17
+ .object({ id: z.string().min(1), name: z.string() })
18
+ .optional(),
15
19
  });
16
20
  const settings_schema = z.object({
17
21
  device_id: z
@@ -25,6 +29,7 @@ const settings_schema = z.object({
25
29
  update_declined_version: z.string().max(64).optional(),
26
30
  update_declined_at: z.number().optional(),
27
31
  setup_version: z.string().max(64).optional(),
32
+ context_workspace: z.string().min(1).max(64).optional(),
28
33
  });
29
34
  export function api_url() {
30
35
  return (process.env.NEMU_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, "");
@@ -52,23 +52,23 @@ const device_schema = z.object({
52
52
  name: z.string(),
53
53
  });
54
54
  export async function open_project(identity) {
55
- const result = await api("POST", "/api/v1/context/projects", z.object({ data: project_schema }), { body: identity });
55
+ const result = await api("POST", "/api/v1/projects", z.object({ data: project_schema }), { body: identity });
56
56
  return result.data;
57
57
  }
58
58
  export async function list_projects() {
59
- const result = await api("GET", "/api/v1/context/projects", z.object({ data: z.array(project_schema) }));
59
+ const result = await api("GET", "/api/v1/projects", z.object({ data: z.array(project_schema) }));
60
60
  return result.data;
61
61
  }
62
62
  export async function load_project(project_id, branch) {
63
- const result = await api("GET", `/api/v1/context/projects/${encodeURIComponent(project_id)}/load`, z.object({ data: load_schema }), { query: { branch } });
63
+ const result = await api("GET", `/api/v1/projects/${encodeURIComponent(project_id)}/load`, z.object({ data: load_schema }), { query: { branch } });
64
64
  return result.data;
65
65
  }
66
66
  export async function search_project(project_id, query, limit = 10) {
67
- const result = await api("GET", `/api/v1/context/projects/${encodeURIComponent(project_id)}/search`, z.object({ data: z.array(entry_schema) }), { query: { q: query, limit } });
67
+ const result = await api("GET", `/api/v1/projects/${encodeURIComponent(project_id)}/search`, z.object({ data: z.array(entry_schema) }), { query: { q: query, limit } });
68
68
  return result.data;
69
69
  }
70
70
  export async function write_batch(project_id, entries) {
71
- const result = await api("POST", `/api/v1/context/projects/${encodeURIComponent(project_id)}/entries/batch`, z.object({
71
+ const result = await api("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/entries/batch`, z.object({
72
72
  data: z.array(z.object({
73
73
  name: z.string(),
74
74
  status: z.enum(["created", "updated", "skipped"]),
@@ -79,21 +79,21 @@ export async function write_batch(project_id, entries) {
79
79
  return result.data;
80
80
  }
81
81
  export async function register_device(input) {
82
- const result = await api("POST", "/api/v1/context/devices", z.object({ data: device_schema }), { body: input, device: false });
82
+ const result = await api("POST", "/api/v1/devices", z.object({ data: device_schema }), { body: input, device: false });
83
83
  return result.data;
84
84
  }
85
85
  export async function mark_stale(project_id, stale, fresh) {
86
86
  if (stale.length === 0 && fresh.length === 0)
87
87
  return;
88
- await api("POST", `/api/v1/context/projects/${encodeURIComponent(project_id)}/stale`, z.object({ marked: z.number(), cleared: z.number() }), { body: { stale: stale.slice(0, 400), fresh: fresh.slice(0, 400) } });
88
+ await api("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/stale`, z.object({ marked: z.number(), cleared: z.number() }), { body: { stale: stale.slice(0, 400), fresh: fresh.slice(0, 400) } });
89
89
  }
90
90
  export async function list_devices() {
91
- const result = await api("GET", "/api/v1/context/devices", z.object({
91
+ const result = await api("GET", "/api/v1/devices", z.object({
92
92
  data: z.array(z.object({ id: z.string(), name: z.string(), revoked_at: z.string().nullable() })),
93
93
  }), { device: false });
94
94
  return result.data;
95
95
  }
96
96
  export async function export_all() {
97
- const result = await api("GET", "/api/v1/context/export", z.object({ data: z.unknown() }));
97
+ const result = await api("GET", "/api/v1/projects/export", z.object({ data: z.unknown() }));
98
98
  return result.data;
99
99
  }
package/dist/http.js CHANGED
@@ -23,11 +23,16 @@ export async function api(method, path, schema, options = {}) {
23
23
  };
24
24
  if (options.body !== undefined)
25
25
  headers["content-type"] = "application/json";
26
- if (options.device !== false &&
26
+ const is_key = credentials.kind === "key";
27
+ if (!is_key &&
28
+ options.device !== false &&
27
29
  settings.device_id !== undefined &&
28
30
  settings.device_api_url === credentials.api_url) {
29
31
  headers["x-nemu-device"] = settings.device_id;
30
32
  }
33
+ if (!is_key && settings.context_workspace !== undefined) {
34
+ headers["x-nemu-workspace"] = settings.context_workspace;
35
+ }
31
36
  let response;
32
37
  try {
33
38
  response = await fetch(url, {
package/dist/index.js CHANGED
@@ -64,7 +64,7 @@ const HELP = `
64
64
  ${bold("Context for coding agents")}
65
65
  setup <claude|codex> [--hooks|--no-hooks] [--yes]
66
66
  Connect Claude Code (aliases cc, claude-code) or Codex
67
- setup <cursor|vscode|gemini|windsurf|zed>
67
+ setup <cursor|vscode|gemini|windsurf|zed|opencode>
68
68
  Add the Nemu MCP server to that editor's config
69
69
  claude [-- <claude args>] Set up if needed, then start Claude Code
70
70
  codex [-- <codex args>] Set up if needed, then start Codex
@@ -74,7 +74,7 @@ const HELP = `
74
74
  codex load sessions [--limit n] The same for Codex
75
75
  mcp Run the MCP bridge (what clients start)
76
76
  mcp config <client> Print config for cursor, gemini, vscode, windsurf,
77
- zed, claude, codex or remote
77
+ zed, opencode, claude, codex or remote
78
78
  context [load] Show what an agent sees for this folder
79
79
  context search <words> Search this project's saved notes
80
80
  context projects | export [--out f] List projects or export everything
@@ -87,6 +87,7 @@ const HELP = `
87
87
 
88
88
  ${bold("Account")}
89
89
  login [--force] [--no-browser] Sign in with the device flow
90
+ login key Sign in with a workspace API key (asked for, or NEMU_API_KEY)
90
91
  logout Delete the stored token
91
92
  whoami Show the signed in account
92
93
  user Full account record
package/dist/system.js CHANGED
@@ -1,8 +1,19 @@
1
1
  import spawn from "cross-spawn";
2
2
  import { access, constants } from "node:fs/promises";
3
- import { delimiter, join } from "node:path";
3
+ import { delimiter, isAbsolute, join } from "node:path";
4
4
  const MAX_OUTPUT = 4 * 1024 * 1024;
5
- export function run(command, args, options = {}) {
5
+ const NOT_FOUND = { code: 127, stdout: "", stderr: "" };
6
+ async function resolve_command(command) {
7
+ if (process.platform !== "win32")
8
+ return command;
9
+ if (/[\\/]/.test(command))
10
+ return isAbsolute(command) ? command : null;
11
+ return which(command);
12
+ }
13
+ export async function run(command, args, options = {}) {
14
+ const resolved = await resolve_command(command);
15
+ if (resolved === null)
16
+ return NOT_FOUND;
6
17
  return new Promise((resolve) => {
7
18
  const stdout = [];
8
19
  const stderr = [];
@@ -25,7 +36,7 @@ export function run(command, args, options = {}) {
25
36
  size += chunk.length;
26
37
  target.push(chunk);
27
38
  };
28
- const child = spawn(command, args, {
39
+ const child = spawn(resolved, args, {
29
40
  env: options.env ?? process.env,
30
41
  cwd: options.cwd,
31
42
  windowsHide: true,
@@ -41,17 +52,21 @@ export function run(command, args, options = {}) {
41
52
  child.on("close", (code) => finish(code ?? 127));
42
53
  });
43
54
  }
44
- export function launch(command, args) {
55
+ export async function launch(command, args) {
56
+ const resolved = await resolve_command(command);
57
+ if (resolved === null)
58
+ return 127;
45
59
  return new Promise((resolve) => {
46
- const child = spawn(command, args, { stdio: "inherit" });
60
+ const child = spawn(resolved, args, { stdio: "inherit" });
47
61
  child.on("error", () => resolve(127));
48
62
  child.on("exit", (code, signal) => resolve(code ?? (signal !== null ? 1 : 0)));
49
63
  });
50
64
  }
51
65
  export async function which(name) {
52
66
  const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
53
- for (const directory of (process.env.PATH ?? "").split(delimiter)) {
54
- if (directory.length === 0)
67
+ for (const entry of (process.env.PATH ?? "").split(delimiter)) {
68
+ const directory = entry.replace(/^"(.*)"$/, "$1");
69
+ if (directory.length === 0 || !isAbsolute(directory))
55
70
  continue;
56
71
  for (const extension of extensions) {
57
72
  const candidate = join(directory, `${name}${extension.toLowerCase()}`);
package/dist/ui.js CHANGED
@@ -37,20 +37,40 @@ export function spinner(label) {
37
37
  },
38
38
  };
39
39
  }
40
- export function open_browser(url) {
40
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
41
+ export function safe_browser_url(url, expected_origin) {
42
+ try {
43
+ const parsed = new URL(url);
44
+ const is_secure = parsed.protocol === "https:" ||
45
+ (parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname));
46
+ if (!is_secure)
47
+ return null;
48
+ if (parsed.origin !== new URL(expected_origin).origin)
49
+ return null;
50
+ return parsed.href;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ export function open_browser(url, expected_origin) {
57
+ const target = safe_browser_url(url, expected_origin);
58
+ if (target === null)
59
+ return false;
41
60
  const command = process.platform === "darwin"
42
61
  ? "open"
43
62
  : process.platform === "win32"
44
- ? "cmd"
63
+ ? "rundll32"
45
64
  : "xdg-open";
46
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
65
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", target] : [target];
47
66
  try {
48
- const child = spawn(command, args, { stdio: "ignore", detached: true });
67
+ const child = spawn(command, args, { stdio: "ignore", detached: true, windowsHide: true });
49
68
  child.on("error", () => { });
50
69
  child.unref();
70
+ return true;
51
71
  }
52
72
  catch {
53
- return;
73
+ return false;
54
74
  }
55
75
  }
56
76
  export function is_interactive() {
@@ -73,3 +93,38 @@ export async function confirm(question, fallback) {
73
93
  reader.close();
74
94
  }
75
95
  }
96
+ export async function ask_secret(question) {
97
+ const input = process.stdin;
98
+ process.stdout.write(` ${question} `);
99
+ input.setRawMode(true);
100
+ input.resume();
101
+ input.setEncoding("utf8");
102
+ return new Promise((resolve, reject) => {
103
+ let value = "";
104
+ const finish = (error) => {
105
+ input.setRawMode(false);
106
+ input.pause();
107
+ input.removeListener("data", on_data);
108
+ process.stdout.write("\n");
109
+ if (error === null)
110
+ resolve(value);
111
+ else
112
+ reject(error);
113
+ };
114
+ const on_data = (chunk) => {
115
+ for (const character of chunk) {
116
+ if (character === "\r" || character === "\n")
117
+ return finish(null);
118
+ if (character === "\u0003")
119
+ return finish(new Error("Cancelled."));
120
+ if (character === "\u007f" || character === "\b") {
121
+ value = value.slice(0, -1);
122
+ continue;
123
+ }
124
+ if (character >= " ")
125
+ value += character;
126
+ }
127
+ };
128
+ input.on("data", on_data);
129
+ });
130
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "1.3.2";
1
+ export const VERSION = "1.5.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemu-cli",
3
- "version": "1.3.2",
3
+ "version": "1.5.0",
4
4
  "description": "Command line access to Nemu, and portable project memory for Claude Code, Codex and any MCP client.",
5
5
  "bin": {
6
6
  "nemu": "./dist/index.js"