meksus 0.5.0 → 0.6.1

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/README.md CHANGED
@@ -29,6 +29,7 @@ The project's exact `<owner/project>` name is shown on its page in the dashboard
29
29
 
30
30
  ```sh
31
31
  meksus hooks install # in the repo: adds Claude Code hooks to .claude/settings.local.json
32
+ meksus hooks install --codex # Codex: once per computer (~/.codex/hooks.json)
32
33
  meksus task-lines steps # optional: show the step Claude is on, in one line
33
34
  meksus watch --label "build" -- npm run build # any command; a failure opens an incident and alerts Discord
34
35
  ```
@@ -41,7 +42,9 @@ Start a new Claude Code session after installing the hooks. It then appears on t
41
42
  meksus statusline install --global # once per computer (use --replace if you already have a status line)
42
43
  ```
43
44
 
44
- Claude Code's status line then shows how much of your plan's 5-hour and weekly limits you've used and when each resets, and the dashboard's **Agents** page shows the same with a live countdown. A Discord DM tells you when a limit resets (turn it off on the Agents page). Claude Code provides these numbers for claude.ai Pro and Max plans, after the first reply in a session.
45
+ Then **start Claude Code in a terminal** (`claude`; in VS Code: Terminal → New Terminal) and send it one message. The VS Code chat panel doesn't draw a status line, so it can't pass the numbers on. The bottom of the terminal then shows how much of your plan's 5-hour and weekly limits you've used and when each resets, and the dashboard's **Agents** page shows the same with a live countdown within a minute. A Discord DM tells you when a limit resets (turn it off on the Agents page). Claude Code provides these numbers for claude.ai Pro and Max plans.
46
+
47
+ Not showing up? `meksus statusline doctor` checks every step and says which one is missing.
45
48
 
46
49
  ## Check
47
50
 
@@ -76,6 +79,7 @@ With `meksus statusline` installed, your Claude plan limits are sent too: the us
76
79
  | `meksus project create <name> [--in <parent>] [--use]` | Create a project (owners and admins) |
77
80
  | `meksus project use <owner/project>` | Write this repo's `.meksus` |
78
81
  | `meksus hooks install` / `uninstall` | Watch Claude Code in this repo |
82
+ | `meksus hooks install --codex` / `uninstall --codex` | Watch Codex on this computer (repositories with a `.meksus` file) |
79
83
  | `meksus task-lines off \| steps \| prompt` | Opt-in one-line "working on" |
80
84
  | `meksus statusline install [--global]` / `uninstall` | Claude plan limits in the status line and on the dashboard |
81
85
  | `meksus watch [--label <name>] -- <cmd>` | Run a command and report how it ends |
package/bin/meksus.mjs CHANGED
@@ -22,9 +22,11 @@ const HELP = `M.E.K.S.U.S. CLI ${VERSION}
22
22
  meksus project create <name> [--in <parent>] [--slug <slug>] [--use]
23
23
  meksus project use <owner/project> Write this repo's .meksus file (commit it)
24
24
  meksus hooks install | uninstall Watch Claude Code in the current repository
25
+ meksus hooks install --codex | uninstall --codex Watch Codex (once per computer; repos with .meksus)
25
26
  meksus task-lines [off | steps | prompt] Show what Claude is working on, in one line (opt-in)
26
27
  meksus statusline install [--global] Claude's plan limits (5-hour and weekly) in Claude Code's
27
28
  status line and on your M.E.K.S.U.S. dashboard
29
+ meksus statusline doctor Check the plan-limits setup step by step
28
30
  meksus watch [--label <name>] -- <cmd> … Run a command and report its status; a failure opens an incident
29
31
 
30
32
  Status only: code, prompts and command output never leave your machine. With task-lines on, the title
@@ -45,14 +47,14 @@ switch (command) {
45
47
  case "resolve": code = await incidentCommand("resolve", rest[0]); break;
46
48
  case "project": case "projects": code = (await requireAccess()) ? await projectCommand(rest) : 1; break;
47
49
  case "hooks":
48
- if (rest[0] === "install") code = (await requireAccess()) ? install() : 1;
49
- else if (rest[0] === "uninstall") code = uninstall();
50
- else { console.error("Usage: meksus hooks install | uninstall"); code = 2; }
50
+ if (rest[0] === "install") code = (await requireAccess()) ? install(process.cwd(), { codex: flag("--codex") }) : 1;
51
+ else if (rest[0] === "uninstall") code = uninstall(process.cwd(), { codex: flag("--codex") });
52
+ else { console.error("Usage: meksus hooks install | uninstall [--codex]"); code = 2; }
51
53
  break;
52
- case "hook": code = await runHook(); break; // called by Claude Code, silent
54
+ case "hook": code = await runHook(rest[0] === "--agent" && rest[1] === "codex" ? "codex" : "claude-code"); break; // called by the agent, silent
53
55
  case "task-lines": code = taskLinesCommand(rest); break;
54
56
  case "statusline":
55
- code = rest.length ? ((rest[0] === "install" && !(await requireAccess())) ? 1 : statuslineCommand(rest)) : await runStatusline();
57
+ code = rest.length ? ((rest[0] === "install" && !(await requireAccess())) ? 1 : await statuslineCommand(rest)) : await runStatusline();
56
58
  break;
57
59
  case "limits-flush": await limitsFlush(); break; // internal, detached
58
60
  case "flush": await flush(); break; // internal, detached
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meksus",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "M.E.K.S.U.S. CLI: see what your AI coding agents (Claude Code) and builds are doing, live, and get Discord alerts when they fail or need you. Status only: code, prompts and output never leave your machine.",
5
5
  "keywords": [
6
6
  "meksus",
package/src/hooks.mjs CHANGED
@@ -1,10 +1,13 @@
1
- // Claude Code integration.
2
- // `meksus hook` the hook command itself: reads the hook JSON on stdin, records a status
3
- // line, exits 0 and prints NOTHING (some hooks feed stdout back to Claude).
1
+ // Claude Code and Codex integration.
2
+ // `meksus hook [--agent codex]` the hook command itself: reads the hook JSON on stdin, records a status
3
+ // line, exits 0 and prints NOTHING (some hooks feed stdout back to the agent).
4
4
  // `meksus hooks install` adds the hook to <repo>/.claude/settings.local.json (personal, gitignored)
5
- // `meksus hooks uninstall` removes only our entries
5
+ // `meksus hooks install --codex` adds it to ~/.codex/hooks.json (Codex's own hooks, same shape; once per
6
+ // computer: repositories without a .meksus file are never reported)
7
+ // `meksus hooks uninstall [--codex]` removes only our entries
6
8
  import { createHash } from "node:crypto";
7
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
8
11
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
9
12
  import { fileURLToPath } from "node:url";
10
13
  import { readProjectFile } from "./project.mjs";
@@ -13,6 +16,8 @@ import { trackTurn } from "./turns.mjs";
13
16
  import { taskFrom, taskMode } from "./tasks.mjs";
14
17
 
15
18
  const EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Notification", "Stop", "SessionEnd"];
19
+ // Codex (learn.chatgpt.com/docs/hooks): the same events, "PermissionRequest" instead of "Notification".
20
+ const CODEX_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PermissionRequest", "Stop", "SessionEnd"];
16
21
  const TOOL_EVENTS = new Set(["PreToolUse", "PostToolUse"]);
17
22
  const CLI = fileURLToPath(new URL("../bin/meksus.mjs", import.meta.url));
18
23
  const MARK = "meksus.mjs\" hook";
@@ -21,8 +26,18 @@ export function sessionKey(agent, id) {
21
26
  return createHash("sha256").update(`${agent}:${id}`).digest("hex").slice(0, 32); // never the raw id
22
27
  }
23
28
 
29
+ /** Where Claude Code runs, from the CLAUDE_CODE_ENTRYPOINT it sets for hooks: "cli" is the terminal (the only
30
+ * surface that runs the status line, so the only one with live plan limits); IDE panels and the SDK aren't. */
31
+ export function surfaceOf(entrypoint = process.env.CLAUDE_CODE_ENTRYPOINT) {
32
+ if (typeof entrypoint !== "string" || !entrypoint) return null;
33
+ if (entrypoint === "cli") return "terminal";
34
+ if (/vscode|jetbrains|cursor|windsurf|zed|ide|desktop/i.test(entrypoint)) return "ide";
35
+ if (/^sdk|headless|print/i.test(entrypoint)) return "sdk";
36
+ return "other";
37
+ }
38
+
24
39
  /** Maps one Claude Code hook payload to a status line (or null to ignore). Exported for tests. */
25
- export function toStatus(input, now = new Date()) {
40
+ export function toStatus(input, now = new Date(), agent = "claude-code") {
26
41
  const name = input?.hook_event_name;
27
42
  if (!name || !input.session_id) return null;
28
43
  // PRJ-10/13: status belongs to the project named by the repo's .meksus file; no file → not reported.
@@ -30,11 +45,14 @@ export function toStatus(input, now = new Date()) {
30
45
  if (!project) return null;
31
46
  const e = {
32
47
  project,
33
- session: sessionKey("claude-code", input.session_id),
34
- agent: "claude-code",
48
+ session: sessionKey(agent, input.session_id),
49
+ agent,
35
50
  label: repoLabel(input.cwd),
36
51
  at: now.toISOString(),
37
- transcript: typeof input.transcript_path === "string" ? input.transcript_path : null,
52
+ // Token usage is read from Claude Code's transcript format; Codex reports its model name instead.
53
+ transcript: agent === "claude-code" && typeof input.transcript_path === "string" ? input.transcript_path : null,
54
+ ...(agent === "claude-code" && surfaceOf() ? { surface: surfaceOf() } : {}),
55
+ ...(agent === "codex" && typeof input.model === "string" && /^[a-z0-9][a-z0-9.\-]{0,62}$/.test(input.model) ? { model: input.model } : {}),
38
56
  };
39
57
  switch (name) {
40
58
  case "SessionStart": return { ...e, state: "idle", started_at: e.at };
@@ -43,6 +61,7 @@ export function toStatus(input, now = new Date()) {
43
61
  case "PostToolUse": return { ...e, state: "working", tool_failure: toolFailed(input.tool_response) };
44
62
  case "PostToolUseFailure": return { ...e, state: "working", tool_failure: true };
45
63
  case "Notification": return { ...e, state: "waiting" };
64
+ case "PermissionRequest": return { ...e, state: "waiting" }; // Codex asks before running something
46
65
  case "Stop": return { ...e, state: "finished" };
47
66
  case "SessionEnd": return { ...e, state: "finished", ended: true };
48
67
  default: return null;
@@ -102,12 +121,12 @@ export function repoLabel(cwd) {
102
121
  return basename(root).slice(0, 80);
103
122
  }
104
123
 
105
- export async function runHook() {
124
+ export async function runHook(agent = "claude-code") {
106
125
  try {
107
126
  const chunks = [];
108
127
  for await (const c of process.stdin) chunks.push(c);
109
128
  const input = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
110
- const status = toStatus(input);
129
+ const status = toStatus(input, new Date(), agent);
111
130
  if (status) {
112
131
  // Opt-in one-line "working on" from the agent's own step list (`meksus task-lines`).
113
132
  const mode = taskMode();
@@ -160,18 +179,30 @@ export function writeSettings(file, settings) {
160
179
  `);
161
180
  }
162
181
 
163
- export function install(cwd = process.cwd()) {
164
- const file = settingsPath(cwd);
182
+ export const codexHooksPath = () => join(homedir(), ".codex", "hooks.json");
183
+
184
+ export function install(cwd = process.cwd(), { codex = false } = {}) {
185
+ const file = codex ? codexHooksPath() : settingsPath(cwd);
165
186
  const settings = readSettings(file);
166
187
  if (!settings) return 1;
167
188
  settings.hooks ??= {};
168
- const command = `node "${CLI}" hook`;
169
- for (const event of EVENTS) {
189
+ const command = codex ? `node "${CLI}" hook --agent codex` : `node "${CLI}" hook`;
190
+ for (const event of codex ? CODEX_EVENTS : EVENTS) {
170
191
  const groups = (settings.hooks[event] ??= []);
171
192
  const clean = groups.map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !String(h.command).includes(MARK)) })).filter((g) => g.hooks.length);
172
- clean.push({ ...(TOOL_EVENTS.has(event) ? { matcher: "*" } : {}), hooks: [{ type: "command", command, timeout: 10 }] });
193
+ // Claude Code's tool matcher "*" means every tool; Codex matchers are regexes, so none = every tool.
194
+ clean.push({ ...(TOOL_EVENTS.has(event) && !codex ? { matcher: "*" } : {}), hooks: [{ type: "command", command, timeout: 10 }] });
173
195
  settings.hooks[event] = clean;
174
196
  }
197
+ if (codex) {
198
+ mkdirSync(dirname(file), { recursive: true });
199
+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
200
+ console.log(`✔ Codex hooks installed in ${file}`);
201
+ console.log(" Every Codex session in a repository with a .meksus file now reports: working, needs you, finished.");
202
+ console.log(" Sent: state, timings, tool-call counts and the model name. Never code, prompts or output.");
203
+ console.log(" Start a new Codex session to activate. Hooks are on by default in Codex ([features] hooks).");
204
+ return 0;
205
+ }
175
206
  mkdirSync(dirname(file), { recursive: true });
176
207
  writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
177
208
  console.log(`✔ Claude Code hooks installed in ${file}`);
@@ -181,8 +212,8 @@ export function install(cwd = process.cwd()) {
181
212
  return 0;
182
213
  }
183
214
 
184
- export function uninstall(cwd = process.cwd()) {
185
- const file = settingsPath(cwd);
215
+ export function uninstall(cwd = process.cwd(), { codex = false } = {}) {
216
+ const file = codex ? codexHooksPath() : settingsPath(cwd);
186
217
  if (!existsSync(file)) { console.log("No hooks file here."); return 0; }
187
218
  const settings = readSettings(file);
188
219
  if (!settings) return 1;
package/src/spool.mjs CHANGED
@@ -73,6 +73,8 @@ export function aggregate(events) {
73
73
  if (e.ended) cur.ended = true;
74
74
  if (e.transcript) cur.transcript = e.transcript;
75
75
  if (e.turn) cur.turn = e.turn;
76
+ if (e.model) cur.model = e.model; // Codex names its model in every hook call
77
+ if (e.surface) cur.surface = e.surface; // terminal / ide / sdk (Claude Code's entrypoint)
76
78
  if (e.started_at && e.started_at < cur.started_at) cur.started_at = e.started_at;
77
79
  if (typeof e.task === "string") {
78
80
  Object.assign(cur, { task: e.task, task_source: e.task_source, task_done: e.task_done ?? 0, task_total: e.task_total ?? 0, task_at: e.at });
@@ -1,18 +1,25 @@
1
1
  // Claude plan limits on the M.E.K.S.U.S. dashboard (Rik, 2026-09-26).
2
2
  // `meksus statusline` Claude Code's status line command. Reads the status line JSON on stdin and
3
3
  // prints one short line ("5h 23% · resets in 2h 14m │ week 41% · Tue 09:00").
4
- // Keeps ONLY rate_limits (percentages + reset times) in ~/.meksus/limits.json and,
5
- // when they changed (or every 5 minutes), starts a detached `meksus limits-flush`,
6
- // at most once a minute (G-1). Never blocks, never breaks the status line.
4
+ // Keeps ONLY rate_limits (percentages + reset times) in ~/.meksus/limits.json, with
5
+ // WHEN each Claude Code session last got them from Anthropic (observed_at). Only the
6
+ // newest reading on this computer is sent, with that time, so an idle session's old
7
+ // numbers never overwrite a newer reading (the server keeps the newest too).
8
+ // Sends: numbers changed → at most once a minute; same numbers re-confirmed by newer
9
+ // activity → at most every 5 minutes; nothing new → nothing sent (G-1).
10
+ // Never blocks, never breaks the status line.
7
11
  // `meksus statusline install [--global] [--replace]` / `uninstall [--global]`
8
12
  // <repo>/.claude/settings.local.json, or ~/.claude/settings.json with --global.
9
13
  // `meksus limits-flush` internal, detached: one POST /v1/claude-limits as the signed-in user.
14
+ // `meksus statusline doctor` checks every step (CLI, sign-in, access, the setting, whether Claude Code
15
+ // ran the status line and gave plan limits, the last send) and says what's missing.
10
16
  import { spawn } from "node:child_process";
11
- import { readFileSync, writeFileSync } from "node:fs";
17
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
12
18
  import { homedir } from "node:os";
13
19
  import { join } from "node:path";
14
20
  import { fileURLToPath } from "node:url";
15
21
  import { getAccessToken } from "./auth.mjs";
22
+ import { hasAccess } from "./access.mjs";
16
23
  import { apiBase, dir, ensureDir, readConfig } from "./config.mjs";
17
24
  import { readSettings, settingsPath, writeSettings } from "./hooks.mjs";
18
25
  import { VERSION } from "./version.mjs";
@@ -23,6 +30,9 @@ const WINDOWS = ["five_hour", "seven_day", "spend_limit"];
23
30
  export const SEND_MIN_MS = 60_000;
24
31
  export const SEND_EVERY_MS = 5 * 60_000;
25
32
  const limitsFile = () => join(dir(), "limits.json");
33
+ const seenFile = () => join(dir(), "statusline-seen.json"); // when Claude Code last ran us, and with what (no numbers)
34
+ function readSeen() { try { return JSON.parse(readFileSync(seenFile(), "utf8")); } catch { return {}; } }
35
+ function writeSeen(patch) { try { ensureDir(); writeFileSync(seenFile(), JSON.stringify({ ...readSeen(), ...patch })); } catch { /* diagnostics only */ } }
26
36
 
27
37
  /** Only the numbers: { five_hour: { used_percentage, resets_at }, … }, or null. */
28
38
  export function pickLimits(input) {
@@ -50,33 +60,69 @@ export function renderLine(limits, nowMs = Date.now()) {
50
60
  return [part("5h", limits.five_hour), part("week", limits.seven_day), part("spend", limits.spend_limit)].filter(Boolean).join(" │ ");
51
61
  }
52
62
 
53
- const signature = (l) => JSON.stringify(WINDOWS.map((w) => (l?.[w] ? [Math.round(l[w].used_percentage), l[w].resets_at] : null)));
63
+ export const signature = (l) => JSON.stringify(WINDOWS.map((w) => (l?.[w] ? [Math.round(l[w].used_percentage), l[w].resets_at] : null)));
64
+ const SESSIONS_MAX = 20;
65
+ const SESSION_TTL_MS = 24 * 3600_000;
54
66
 
55
- /** Should this run start a send? (changed and a minute since the last one, or 5 minutes regardless) */
56
- export function sendDue(state, limits, nowMs = Date.now()) {
57
- if (!limits) return false;
58
- const since = nowMs - (state?.sent_at ?? 0);
59
- return (signature(limits) !== state?.sent_sig && since >= SEND_MIN_MS) || since >= SEND_EVERY_MS;
67
+ /**
68
+ * Records one status line run. Claude Code hands every session its own last rate_limits (from that session's
69
+ * last API response) and re-runs the status line every 30 s even when idle, so the numbers alone don't say
70
+ * how old they are. Per session: first sight → the transcript's last write (≈ the last reply); numbers
71
+ * changed → now (a reply just arrived); same numbers → re-confirmed at the transcript's last write.
72
+ * The state's reading is the newest across this computer's sessions.
73
+ */
74
+ export function observe(state, sessionId, limits, transcriptMs, nowMs = Date.now()) {
75
+ const next = { ...(state ?? {}), sessions: { ...(state?.sessions ?? {}) } };
76
+ if (!limits) return next;
77
+ const sid = String(sessionId ?? "unknown").slice(0, 64);
78
+ const sig = signature(limits);
79
+ const mt = Number.isFinite(transcriptMs) ? Math.min(transcriptMs, nowMs) : null;
80
+ const prev = next.sessions[sid];
81
+ const obs = !prev ? (mt ?? nowMs) : prev.sig !== sig ? nowMs : Math.max(prev.obs, mt ?? prev.obs);
82
+ next.sessions[sid] = { sig, obs, seen: nowMs };
83
+ for (const [k, v] of Object.entries(next.sessions)) if (nowMs - (v.seen ?? 0) > SESSION_TTL_MS) delete next.sessions[k];
84
+ const keep = Object.entries(next.sessions).sort((a, b) => b[1].seen - a[1].seen).slice(0, SESSIONS_MAX);
85
+ next.sessions = Object.fromEntries(keep);
86
+ if (!next.observed_at || obs >= next.observed_at) { next.limits = limits; next.observed_at = obs; next.sig = sig; }
87
+ return next;
88
+ }
89
+
90
+ /** Should this run start a send? New numbers: a minute since the last try. Same numbers seen again later: 5 minutes. */
91
+ export function sendDue(state, nowMs = Date.now()) {
92
+ if (!state?.limits || !state.observed_at) return false;
93
+ if (state.observed_at <= (state.sent_obs ?? 0)) return false; // nothing newer than what the server has
94
+ const since = nowMs - (state.tried_at ?? 0);
95
+ return state.sig !== state.sent_sig ? since >= SEND_MIN_MS : since >= SEND_EVERY_MS;
60
96
  }
61
97
 
62
98
  function readState() { try { return JSON.parse(readFileSync(limitsFile(), "utf8")); } catch { return null; } }
63
99
  function writeState(s) { try { ensureDir(); writeFileSync(limitsFile(), JSON.stringify(s)); } catch { /* read-only home: just don't send */ } }
100
+ function mtimeMs(path) { try { return typeof path === "string" && path ? statSync(path).mtimeMs : null; } catch { return null; } }
64
101
 
65
102
  export async function runStatusline() {
66
103
  let limits = null;
104
+ let claude = null;
105
+ let sessionId = null;
106
+ let transcript = null;
67
107
  try {
68
108
  const chunks = [];
69
109
  for await (const c of process.stdin) chunks.push(c);
70
- limits = pickLimits(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
110
+ const input = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
111
+ limits = pickLimits(input);
112
+ claude = typeof input.version === "string" ? input.version.slice(0, 20) : null;
113
+ sessionId = input.session_id ?? null;
114
+ transcript = input.transcript_path ?? null;
71
115
  } catch { /* bad input: still print something */ }
116
+ writeSeen({ last_run: Date.now(), had_limits: Boolean(limits), claude_version: claude, ...(limits ? { last_limits: Date.now() } : {}) });
72
117
  const state = readState();
73
- const shown = limits ?? state?.limits ?? null;
74
- process.stdout.write(`${renderLine(shown)}\n`);
75
- if (limits && sendDue(state, limits) && readConfig()?.session) {
76
- writeState({ limits, at: Date.now(), sent_at: Date.now(), sent_sig: signature(limits) }); // claim before spawning
118
+ process.stdout.write(`${renderLine(limits ?? state?.limits ?? null)}\n`);
119
+ if (!limits) return 0;
120
+ const next = observe(state, sessionId, limits, mtimeMs(transcript));
121
+ if (sendDue(next) && readConfig()?.session) {
122
+ writeState({ ...next, tried_at: Date.now() }); // claim before spawning
77
123
  try { spawn(process.execPath, [CLI, "limits-flush"], { detached: true, stdio: "ignore", windowsHide: true, env: process.env }).unref(); } catch { /* next run */ }
78
- } else if (limits) {
79
- writeState({ ...(state ?? {}), limits, at: Date.now() });
124
+ } else {
125
+ writeState(next);
80
126
  }
81
127
  return 0;
82
128
  }
@@ -87,16 +133,19 @@ export async function limitsFlush() {
87
133
  if (!state?.limits || !config?.session) return 0;
88
134
  const token = await getAccessToken(config);
89
135
  if (!token) return 0;
136
+ const sent = { limits: state.limits, observed_at: state.observed_at ?? Date.now(), sig: state.sig ?? signature(state.limits) };
90
137
  try {
91
138
  const res = await fetch(`${apiBase(config)}/v1/claude-limits`, {
92
139
  method: "POST",
93
140
  headers: { "Content-Type": "application/json", "User-Agent": `meksus-cli/${VERSION}`, Authorization: `Bearer ${token}` },
94
- body: JSON.stringify({ rate_limits: state.limits }),
141
+ body: JSON.stringify({ rate_limits: sent.limits, observed_at: sent.observed_at }),
95
142
  signal: AbortSignal.timeout(8000),
96
143
  });
97
144
  await res.body?.cancel();
145
+ writeSeen({ sent_at: Date.now(), sent_status: res.status });
146
+ if (res.ok) { const now = readState() ?? state; writeState({ ...now, sent_obs: Math.max(now.sent_obs ?? 0, sent.observed_at), sent_sig: sent.sig }); }
98
147
  return res.status;
99
- } catch { return 0; } // dropped; the next status line run sends again (G-11)
148
+ } catch { writeSeen({ sent_at: Date.now(), sent_status: 0 }); return 0; } // dropped; the next status line run sends again (G-11)
100
149
  }
101
150
 
102
151
  // ── install / uninstall ─────────────────────────────────────────
@@ -130,6 +179,40 @@ export function statuslineCommand(args) {
130
179
  console.log(`✔ Status line removed from ${file}`);
131
180
  return 0;
132
181
  }
133
- console.error("Usage: meksus statusline install [--global] [--replace] | uninstall [--global]");
182
+ if (args[0] === "doctor") return doctor();
183
+ console.error("Usage: meksus statusline install [--global] [--replace] | uninstall [--global] | doctor");
134
184
  return 2;
135
185
  }
186
+
187
+ const ago = (ms) => { const s = Math.round((Date.now() - ms) / 1000); return s < 90 ? `${s} s ago` : s < 5400 ? `${Math.round(s / 60)} min ago` : s < 172800 ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} days ago`; };
188
+
189
+ /** Walks the whole path and stops at the first missing step, in plain words. */
190
+ async function doctor() {
191
+ const ok = (t) => console.log(`✔ ${t}`);
192
+ const bad = (t, fix) => { console.log(`✖ ${t}`); if (fix) console.log(` → ${fix}`); return 1; };
193
+ ok(`meksus ${VERSION}`);
194
+ const config = readConfig();
195
+ if (!config?.session) return bad("Not signed in to M.E.K.S.U.S. on this computer.", "Run: meksus login");
196
+ ok(`Signed in as ${config.user?.name ?? config.user?.email ?? "you"}`);
197
+ const access = await hasAccess({ fresh: true });
198
+ if (access === false) return bad("This account has no access to M.E.K.S.U.S. (private preview).", "Ask your team's admin to invite you.");
199
+ if (access === true) ok("Access: yes");
200
+ const places = [globalSettings(), settingsPath(process.cwd())].filter((f, i, a) => a.indexOf(f) === i);
201
+ const installed = places.find((f) => { try { return existsSync(f) && String(JSON.parse(readFileSync(f, "utf8")).statusLine?.command ?? "").includes(MARK); } catch { return false; } });
202
+ if (!installed) return bad("Claude Code's status line isn't set to meksus.", "Run: meksus statusline install --global (then start a new Claude Code session)");
203
+ ok(`Status line set in ${installed}`);
204
+ const seen = readSeen();
205
+ if (!seen.last_run) return bad("Claude Code hasn't run the status line on this computer yet.",
206
+ "Start Claude Code in a terminal (type: claude) and send it one message. The VS Code chat panel doesn't draw a status line; use a terminal, e.g. VS Code's Terminal → New Terminal.");
207
+ ok(`Claude Code last ran it ${ago(seen.last_run)}${seen.claude_version ? ` (Claude Code ${seen.claude_version})` : ""}`);
208
+ if (!seen.last_limits) return bad("Claude Code hasn't included plan limits yet.",
209
+ "Send Claude a message in that terminal session. If you signed in to Claude Code with an API key instead of a Pro or Max plan, there are no plan limits to show.");
210
+ ok(`Plan limits last seen ${ago(seen.last_limits)}`);
211
+ if (!seen.sent_at) return bad("Not sent to M.E.K.S.U.S. yet.", "It sends within a minute of the next reply. Run this again in a minute.");
212
+ if (seen.sent_status < 200 || seen.sent_status >= 300) {
213
+ return bad(`The last send failed (${seen.sent_status ? `HTTP ${seen.sent_status}` : "no connection"}, ${ago(seen.sent_at)}).`,
214
+ seen.sent_status === 401 ? "Sign in again: meksus login" : seen.sent_status === 403 ? "This account has no access (private preview)." : "It retries with the next reply. Check your connection.");
215
+ }
216
+ ok(`Sent to M.E.K.S.U.S. ${ago(seen.sent_at)}. Open the dashboard → Agents: the Claude plan limits card is live.`);
217
+ return 0;
218
+ }
package/src/turns.mjs CHANGED
@@ -9,6 +9,18 @@ import { join } from "node:path";
9
9
  import { dir, ensureDir } from "./config.mjs";
10
10
 
11
11
  const EDITS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
12
+
13
+ /** Files a tool call changes: Claude Code's edit tools name one file_path; Codex's apply_patch lists them
14
+ * in the patch ("*** Update File: src/a.js"). Paths only, used here and never sent. */
15
+ export function editedFiles(input) {
16
+ const target = input?.tool_input?.file_path ?? input?.tool_input?.notebook_path;
17
+ if (EDITS.has(input?.tool_name) && typeof target === "string") return [target];
18
+ if (/apply_patch/i.test(String(input?.tool_name ?? ""))) {
19
+ const text = Object.values(input.tool_input ?? {}).filter((v) => typeof v === "string").join("\n");
20
+ return [...text.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim()).slice(0, 200);
21
+ }
22
+ return [];
23
+ }
12
24
  const KEEP = 50; // sessions remembered at most
13
25
  const file = () => join(dir(), "turns.json");
14
26
 
@@ -27,8 +39,7 @@ export function trackTurn(input, session, now = Date.now()) {
27
39
  if (name === "UserPromptSubmit" || !t) t = { start: now, tools: 0, files: [], at: now };
28
40
  if (name === "PreToolUse") {
29
41
  t.tools += 1;
30
- const target = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
31
- if (EDITS.has(input.tool_name) && typeof target === "string") {
42
+ for (const target of editedFiles(input)) {
32
43
  const h = createHash("sha256").update(target).digest("hex").slice(0, 16);
33
44
  if (!t.files.includes(h) && t.files.length < 500) t.files.push(h);
34
45
  }