@lastweek-work/cli 0.1.1 → 0.2.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/dist/agents.js ADDED
@@ -0,0 +1,171 @@
1
+ import { appendFileSync, copyFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ // Registers lastweek's stdio MCP server (`lastweek mcp`) with coding agents other than Claude Code (which has its
5
+ // own CLI, see connectClaude). Local file edits only; a tool whose config directory doesn't exist is never touched.
6
+ // Config locations, as documented (checked 2026-11):
7
+ // Cursor ~/.cursor/mcp.json { "mcpServers": { name: { type: "stdio", command, args } } } cursor.com/docs/context/mcp
8
+ // Codex CLI ~/.codex/config.toml [mcp_servers.<name>] command = "…" args = […] learn.chatgpt.com/docs/extend/mcp
9
+ // Gemini CLI ~/.gemini/settings.json { "mcpServers": { name: { command, args } } } github.com/google-gemini/gemini-cli docs/tools/mcp-server.md
10
+ export const SERVER_NAME = "lastweek";
11
+ /** The server's name before the rename; removed when it is clearly ours, so tools don't show up twice. */
12
+ const LEGACY_NAME = "rewind";
13
+ const isDir = (p) => {
14
+ try {
15
+ return statSync(p).isDirectory();
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ /** Copies a file before we change it. The first backup (.bak-lastweek) is never overwritten; later ones get a stamp. */
22
+ export function backup(path) {
23
+ if (!existsSync(path))
24
+ return;
25
+ copyFileSync(path, existsSync(`${path}.bak-lastweek`) ? `${path}.bak-lastweek-${Date.now()}` : `${path}.bak-lastweek`);
26
+ }
27
+ /**
28
+ * Adds/replaces `mcpServers.lastweek` in a JSON config and keeps every other key. A file that exists but isn't a JSON
29
+ * object (or whose mcpServers isn't one) is never touched.
30
+ */
31
+ function registerJson(agent, label, dir, file, entry) {
32
+ const path = join(dir, file);
33
+ const result = (status) => ({ agent, label, path, status });
34
+ if (!isDir(dir))
35
+ return result("not-installed");
36
+ let current = {};
37
+ if (existsSync(path)) {
38
+ let parsed;
39
+ try {
40
+ const text = readFileSync(path, "utf8");
41
+ parsed = text.trim() ? JSON.parse(text) : {};
42
+ }
43
+ catch {
44
+ return result("unreadable");
45
+ }
46
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
47
+ return result("unreadable");
48
+ current = parsed;
49
+ }
50
+ const servers = current.mcpServers ?? {};
51
+ if (servers === null || typeof servers !== "object" || Array.isArray(servers))
52
+ return result("unreadable");
53
+ const next = { ...servers };
54
+ const legacy = next[LEGACY_NAME];
55
+ const dropLegacy = legacy !== undefined && (legacy?.command === "rewind" || legacy?.command === "lastweek");
56
+ if (dropLegacy)
57
+ delete next[LEGACY_NAME];
58
+ if (!dropLegacy && JSON.stringify(next[SERVER_NAME]) === JSON.stringify(entry))
59
+ return result("already");
60
+ next[SERVER_NAME] = entry;
61
+ backup(path);
62
+ writeFileSync(path, `${JSON.stringify({ ...current, mcpServers: next }, null, 2)}\n`);
63
+ return result("registered");
64
+ }
65
+ export const registerCursor = (home = homedir()) => registerJson("cursor", "Cursor", join(home, ".cursor"), "mcp.json", {
66
+ // Cursor's field table marks `type` as required for stdio servers.
67
+ type: "stdio",
68
+ command: SERVER_NAME,
69
+ args: ["mcp"],
70
+ });
71
+ export const registerGemini = (home = homedir()) => registerJson("gemini", "Gemini CLI", join(home, ".gemini"), "settings.json", {
72
+ command: SERVER_NAME,
73
+ args: ["mcp"],
74
+ });
75
+ const KEY = `(?:lastweek|"lastweek"|'lastweek')`;
76
+ const HEADER = /^[ \t]*\[\[?[ \t]*([^\]#]*?)[ \t]*\]/;
77
+ const OURS_HEADER = new RegExp(String.raw `^mcp_servers[ \t]*\.[ \t]*${KEY}[ \t]*(\.|$)`);
78
+ const OURS_ROOT_KEY = new RegExp(String.raw `^[ \t]*mcp_servers[ \t]*\.[ \t]*${KEY}[ \t]*[.=]`);
79
+ const OURS_SECTION_KEY = new RegExp(String.raw `^[ \t]*${KEY}[ \t]*[.=]`);
80
+ /**
81
+ * How config.toml defines lastweek's server: "ours" if a `[mcp_servers.lastweek]` table (or a sub-table, or a dotted
82
+ * / inline key of it) exists; "inline" if `mcp_servers = { … }` is written inline, where appending a table would make
83
+ * the file invalid TOML. Line-based on purpose: we only ever append, so we only need to know whether we may.
84
+ */
85
+ export function codexState(toml) {
86
+ let section = null; // null = root table
87
+ for (const line of toml.split(/\r?\n/)) {
88
+ const h = HEADER.exec(line);
89
+ if (h) {
90
+ section = h[1].replace(/[ \t]*\.[ \t]*/g, ".");
91
+ if (OURS_HEADER.test(section))
92
+ return "ours";
93
+ continue;
94
+ }
95
+ if (section === null) {
96
+ if (OURS_ROOT_KEY.test(line))
97
+ return "ours";
98
+ if (/^[ \t]*mcp_servers[ \t]*=/.test(line))
99
+ return "inline";
100
+ }
101
+ else if (section === "mcp_servers" && OURS_SECTION_KEY.test(line))
102
+ return "ours";
103
+ }
104
+ return "absent";
105
+ }
106
+ /**
107
+ * Codex CLI: appends a `[mcp_servers.lastweek]` table to ~/.codex/config.toml. The user's content is never rewritten
108
+ * or reordered (bytes before the appended table stay identical); an existing table is left as it is.
109
+ */
110
+ export function registerCodex(home = homedir()) {
111
+ const dir = join(home, ".codex");
112
+ const path = join(dir, "config.toml");
113
+ const result = (status) => ({ agent: "codex", label: "Codex CLI", path, status });
114
+ if (!isDir(dir))
115
+ return result("not-installed");
116
+ let text = "";
117
+ if (existsSync(path)) {
118
+ try {
119
+ text = readFileSync(path, "utf8");
120
+ }
121
+ catch {
122
+ return result("unreadable");
123
+ }
124
+ }
125
+ const state = codexState(text);
126
+ if (state === "ours")
127
+ return result("already");
128
+ if (state === "inline")
129
+ return result("unreadable");
130
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
131
+ const lead = text === "" ? "" : text.endsWith("\n") ? nl : nl + nl;
132
+ const table = [`[mcp_servers.${SERVER_NAME}]`, `command = "${SERVER_NAME}"`, `args = ["mcp"]`].join(nl);
133
+ backup(path);
134
+ appendFileSync(path, `${lead}${table}${nl}`);
135
+ return result("registered");
136
+ }
137
+ /** Every supported coding agent besides Claude Code, in a fixed order. */
138
+ export const registerCodingAgents = (home = homedir()) => [
139
+ registerCursor(home),
140
+ registerCodex(home),
141
+ registerGemini(home),
142
+ ];
143
+ /** Labels of the coding agents (besides Claude Code) whose config directory exists. */
144
+ export const installedCodingAgents = (home = homedir()) => [
145
+ [".cursor", "Cursor"],
146
+ [".codex", "Codex CLI"],
147
+ [".gemini", "Gemini CLI"],
148
+ ]
149
+ .filter(([dir]) => isDir(join(home, dir)))
150
+ .map(([, label]) => label);
151
+ /**
152
+ * The MCP client's self-reported name (initialize → clientInfo.name) as a short agent id, e.g. "cursor-vscode" →
153
+ * "cursor", "codex-mcp-client" → "codex". Unknown clients keep their own name, cleaned up; no name → undefined.
154
+ */
155
+ export function agentFromClient(name) {
156
+ const n = name?.trim().toLowerCase();
157
+ if (!n)
158
+ return undefined;
159
+ if (n.startsWith("claude-code") || n === "claude code")
160
+ return "claude-code";
161
+ if (n.includes("cursor"))
162
+ return "cursor";
163
+ if (n.includes("codex"))
164
+ return "codex";
165
+ if (n.includes("gemini"))
166
+ return "gemini-cli";
167
+ return (n
168
+ .replace(/[^a-z0-9._-]+/g, "-")
169
+ .replace(/^-+|-+$/g, "")
170
+ .slice(0, 40) || undefined);
171
+ }
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { appendFileSync, mkdirSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { parseArgs } from "node:util";
7
+ import { installedCodingAgents, registerCodingAgents } from "./agents.js";
7
8
  import { openBursts, recordCall, spoolIdle } from "./bursts.js";
8
9
  import { configPath, loadConfig } from "./config.js";
9
10
  import { ask, claudeInstalled, connectClaude, detectAuthorEmails, detectRepoRoots, gitEmail, mergeConfig, pair, readJson, say, writeConfig, } from "./connect.js";
@@ -18,7 +19,8 @@ import { openTasks } from "./tasks.js";
18
19
  const USAGE = `usage:
19
20
  lastweek connect <CODE> --server <url> [--name <device>] [--yes] [--no-agents] [--no-schedule] [--no-scan]
20
21
  set everything up with a code from the web app's setup tour
21
- lastweek connect --repos <folder> | --agents later additions: another code folder / Claude Code
22
+ lastweek connect --repos <folder> | --agents later additions: another code folder / coding agents
23
+ lastweek agents register the MCP server with Cursor, Codex CLI, Gemini CLI
22
24
  lastweek scan [since-iso] [--since <iso>] [--dry-run] collect git evidence (default since: last successful scan, else 8 days)
23
25
  lastweek log Claude Code hook: reads hook JSON on stdin, never fails, returns fast
24
26
  lastweek flush send spooled hook/MCP events now
@@ -176,21 +178,34 @@ async function connect(args) {
176
178
  }
177
179
  }
178
180
  }
179
- // Claude Code: hook + MCP, only after asking (or --yes / --agents).
180
- // A temporary npx copy would leave hooks pointing at a `lastweek` that isn't installed.
181
+ // Coding agents: Claude Code (hook + MCP) and Cursor / Codex CLI / Gemini CLI (MCP), only after asking (or --yes /
182
+ // --agents). A temporary npx copy would leave hooks and MCP entries pointing at a `lastweek` that isn't installed.
181
183
  const temporary = /[\\/]_npx[\\/]/.test(process.argv[1] ?? "");
182
- if ((code || values.agents) && !values["no-agents"] && claudeInstalled()) {
184
+ const claude = claudeInstalled();
185
+ const others = installedCodingAgents();
186
+ if ((code || values.agents) && !values["no-agents"] && (claude || others.length)) {
183
187
  if (temporary)
184
- console.log(say.claudeTemp);
185
- else if (values.yes || values.agents || (await ask(say.claudeAsk))) {
186
- const r = connectClaude();
187
- if (r.unreadable)
188
- console.error(say.claudeUnreadable(r.unreadable));
189
- else
190
- console.log(r.changed || r.mcp ? say.claudeDone(r.mcp) : say.claudeAlready);
188
+ console.log(others.length ? say.agentsTemp : say.claudeTemp);
189
+ else if (values.yes ||
190
+ values.agents ||
191
+ (await ask(say.agentsAsk([...(claude ? ["Claude Code"] : []), ...others])))) {
192
+ if (claude) {
193
+ const r = connectClaude();
194
+ if (r.unreadable)
195
+ console.error(say.claudeUnreadable(r.unreadable));
196
+ else
197
+ console.log(r.changed || r.mcp ? say.claudeDone(r.mcp) : say.claudeAlready);
198
+ }
199
+ // Tools that aren't installed are neither touched nor mentioned here; `lastweek agents` lists them.
200
+ for (const r of registerCodingAgents()) {
201
+ if (r.status === "unreadable")
202
+ console.error(say.agent(r));
203
+ else if (r.status !== "not-installed")
204
+ console.log(say.agent(r));
205
+ }
191
206
  }
192
207
  else
193
- console.log(say.claudeSkipped);
208
+ console.log(others.length ? say.agentsSkipped : say.claudeSkipped);
194
209
  }
195
210
  // First scan right away, so the browser shows data while the user is still there.
196
211
  if (code && !values["no-scan"]) {
@@ -314,6 +329,20 @@ async function main() {
314
329
  }
315
330
  break;
316
331
  }
332
+ case "agents": {
333
+ // Only the MCP registration for Cursor / Codex CLI / Gemini CLI; Claude Code stays with `connect --agents`.
334
+ if (/[\\/]_npx[\\/]/.test(process.argv[1] ?? "")) {
335
+ console.log(say.agentsTemp);
336
+ break;
337
+ }
338
+ for (const r of registerCodingAgents()) {
339
+ if (r.status === "unreadable")
340
+ console.error(say.agent(r));
341
+ else
342
+ console.log(say.agent(r));
343
+ }
344
+ break;
345
+ }
317
346
  case "mcp":
318
347
  await runMcp();
319
348
  break;
package/dist/connect.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
+ import { backup } from "./agents.js";
6
7
  // `lastweek connect <CODE>`: everything a non-technical user would otherwise do by hand, in one command.
7
8
  // Pair with the web app, find project folders and commit emails, write the config, start the background scan,
8
9
  // connect Claude Code (asks first, backs up its settings), run the first scan. Pure helpers are exported for tests.
@@ -191,9 +192,9 @@ export const say = {
191
192
  claudeTemp: de
192
193
  ? "ℹ Claude Code übersprungen: lastweek läuft nur temporär (npx). Dauerhaft installieren: npm install -g @lastweek-work/cli"
193
194
  : "ℹ Claude Code skipped: lastweek runs temporarily (npx). Install it for good: npm install -g @lastweek-work/cli",
194
- claudeAsk: de
195
- ? "Claude Code gefunden. Soll lastweek die Arbeit deiner Agenten mitzählen? (Hook + MCP, Sicherung wird angelegt) [J/n] "
196
- : "Claude Code found. Should lastweek count your agents' work? (hook + MCP, a backup is made) [Y/n] ",
195
+ agentsAsk: (found) => de
196
+ ? `${found.join(", ")} gefunden. Soll lastweek die Arbeit deiner Agenten mitzählen? (Hook/MCP, Sicherung wird angelegt) [J/n] `
197
+ : `Found ${found.join(", ")}. Should lastweek count your agents' work? (hook/MCP, a backup is made) [Y/n] `,
197
198
  claudeDone: (mcp) => de
198
199
  ? `✓ Claude Code verbunden (Hook${mcp ? " + MCP" : ""})`
199
200
  : `✓ Claude Code connected (hook${mcp ? " + MCP" : ""})`,
@@ -201,6 +202,26 @@ export const say = {
201
202
  claudeSkipped: de
202
203
  ? "– Claude Code übersprungen. Später: lastweek connect --agents"
203
204
  : "– Claude Code skipped. Later: lastweek connect --agents",
205
+ agentsTemp: de
206
+ ? "ℹ Coding-Agenten übersprungen: lastweek läuft nur temporär (npx). Dauerhaft installieren: npm install -g @lastweek-work/cli"
207
+ : "ℹ Coding agents skipped: lastweek runs temporarily (npx). Install it for good: npm install -g @lastweek-work/cli",
208
+ agentsSkipped: de
209
+ ? "– Coding-Agenten übersprungen. Später: lastweek agents"
210
+ : "– Coding agents skipped. Later: lastweek agents",
211
+ agent: (r) => {
212
+ switch (r.status) {
213
+ case "registered":
214
+ return de ? `✓ ${r.label} verbunden (MCP)` : `✓ ${r.label} connected (MCP)`;
215
+ case "already":
216
+ return de ? `✓ ${r.label} war schon verbunden` : `✓ ${r.label} was already connected`;
217
+ case "unreadable":
218
+ return de
219
+ ? `⚠ ${r.label} übersprungen: ${r.path} ließ sich nicht lesen; nichts geändert. Nach dem Prüfen der Datei: lastweek agents`
220
+ : `⚠ ${r.label} skipped (unreadable config): ${r.path}; nothing changed. After checking the file: lastweek agents`;
221
+ default:
222
+ return de ? `– ${r.label} nicht installiert` : `– ${r.label} not installed`;
223
+ }
224
+ },
204
225
  scanning: de ? "Erster Scan der letzten 8 Tage …" : "First scan of the last 8 days …",
205
226
  scanFailed: (reason) => de
206
227
  ? `⚠ Der erste Scan hat nicht geklappt (${reason}). Er läuft automatisch erneut; sofort geht es mit: lastweek scan`
@@ -246,10 +267,7 @@ export function connectClaude(home = homedir()) {
246
267
  const { settings, changed } = mergeClaudeHooks(current);
247
268
  if (changed) {
248
269
  mkdirSync(dirname(path), { recursive: true });
249
- if (existsSync(path)) {
250
- const backup = existsSync(`${path}.bak-lastweek`) ? `${path}.bak-lastweek-${Date.now()}` : `${path}.bak-lastweek`;
251
- copyFileSync(path, backup);
252
- }
270
+ backup(path);
253
271
  writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
254
272
  }
255
273
  let mcp = false;
package/dist/mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod";
4
+ import { agentFromClient } from "./agents.js";
4
5
  import { loadConfig } from "./config.js";
5
6
  import { mainRepoPath } from "./git.js";
6
7
  import { ingest } from "./ingest.js";
@@ -12,8 +13,10 @@ import { endTask, startTask } from "./tasks.js";
12
13
  */
13
14
  export async function runMcp() {
14
15
  const cfg = loadConfig();
15
- const agent = process.env.LASTWEEK_AGENT_NAME ?? process.env.REWIND_AGENT_NAME ?? "unknown";
16
+ const configured = process.env.LASTWEEK_AGENT_NAME || process.env.REWIND_AGENT_NAME || undefined;
16
17
  const server = new McpServer({ name: "lastweek", version: "0.1.0" });
18
+ // An explicit env name wins; otherwise the client's own name from the initialize request (clientInfo.name).
19
+ const agentName = () => configured ?? agentFromClient(server.server.getClientVersion()?.name) ?? "unknown";
17
20
  const repoOf = (repo) => (repo ? mainRepoPath(repo) : undefined);
18
21
  const flush = async () => {
19
22
  const r = await flushSpool((events) => ingest(cfg, events));
@@ -34,7 +37,7 @@ export async function runMcp() {
34
37
  ended_at: started_at && started_at !== at ? at : undefined,
35
38
  repo: r,
36
39
  summary,
37
- payload: { kind: "activity", agent },
40
+ payload: { kind: "activity", agent: agentName() },
38
41
  dedupe_key: `mcp:${r ?? "-"}:${at}:${summary.slice(0, 40)}`,
39
42
  },
40
43
  ]);
@@ -44,7 +47,7 @@ export async function runMcp() {
44
47
  summary: z.string().describe("What you are about to do, one line, in the user's language."),
45
48
  repo: z.string().optional().describe("Absolute repo path if known"),
46
49
  }, async ({ summary, repo }) => {
47
- const t = startTask(summary, repoOf(repo), new Date(), agent);
50
+ const t = startTask(summary, repoOf(repo), new Date(), agentName());
48
51
  return { content: [{ type: "text", text: `task ${t.id} started` }] };
49
52
  });
50
53
  server.tool("end_task", "Mark the end of a task started with start_task (the most recent one if no id is given).", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lastweek-work/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "The lastweek agent: collects git and coding-agent evidence on your machine and sends it to your lastweek account.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://lastweek.work",