@meshpoint/cli 0.0.0-stage → 1.0.0-rc.2

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.
@@ -0,0 +1,67 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
+ import { installTapHooks, removeTapHooks } from "../claude-code/settings.js";
6
+ export const CODEX_TAP_COMMAND = "meshpoint tap codex";
7
+ // Codex truncates additionalContext at 2500 chars by default; a recall inject is up to ~12k.
8
+ const CONTEXT_LIMIT = 100_000;
9
+ export const CODEX_SPEC = {
10
+ command: CODEX_TAP_COMMAND,
11
+ events: [{ event: "SessionStart" }, { event: "UserPromptSubmit" }, { event: "Stop" }, { event: "PreCompact" }, { event: "SessionEnd" }],
12
+ extra: { additionalContextLimit: CONTEXT_LIMIT },
13
+ };
14
+ // Codex approves commands by prefix rules, not per skill; "allow" also runs them outside the
15
+ // sandbox, which the platform call needs for network access.
16
+ export const RULES = `# Managed by meshpoint connect codex. The checkpoint skill writes and retracts items.
17
+ prefix_rule(
18
+ pattern = ["meshpoint", "items", "put"],
19
+ decision = "allow",
20
+ justification = "Meshpoint checkpoint: write team knowledge items",
21
+ )
22
+
23
+ prefix_rule(
24
+ pattern = ["meshpoint", "items", "retract"],
25
+ decision = "allow",
26
+ justification = "Meshpoint checkpoint: retract obsolete items",
27
+ )
28
+ `;
29
+ // Project layout: <repo>/.codex/{hooks.json,rules/meshpoint.rules} and <repo>/.agents/skills/meshpoint.
30
+ // Global layout: $CODEX_HOME (~/.codex) and ~/.agents/skills/meshpoint.
31
+ export function codexPaths(projectDir, env = process.env, home = homedir()) {
32
+ const codexDir = projectDir ? path.join(projectDir, ".codex") : env.CODEX_HOME || path.join(home, ".codex");
33
+ const agentsDir = path.join(projectDir ?? home, ".agents");
34
+ return {
35
+ hooks: path.join(codexDir, "hooks.json"),
36
+ rules: path.join(codexDir, "rules", "meshpoint.rules"),
37
+ skillDir: path.join(agentsDir, "skills", SKILL_NAME),
38
+ };
39
+ }
40
+ export function connectCodex(opts) {
41
+ const paths = opts.paths ?? codexPaths(opts.projectDir);
42
+ let settings = {};
43
+ try {
44
+ settings = JSON.parse(readFileSync(paths.hooks, "utf8"));
45
+ }
46
+ catch (err) {
47
+ if (err.code !== "ENOENT")
48
+ throw new Error(`could not read ${paths.hooks}: ${err.message}`);
49
+ }
50
+ if (opts.remove) {
51
+ const next = removeTapHooks(settings);
52
+ if (Object.keys(next).length > 0)
53
+ writeFileSync(paths.hooks, `${JSON.stringify(next, null, 2)}\n`);
54
+ else
55
+ rmSync(paths.hooks, { force: true });
56
+ rmSync(paths.rules, { force: true });
57
+ rmSync(paths.skillDir, { recursive: true, force: true });
58
+ return `removed meshpoint hooks from ${paths.hooks}, ${paths.rules} and ${paths.skillDir}`;
59
+ }
60
+ mkdirSync(path.dirname(paths.hooks), { recursive: true });
61
+ writeFileSync(paths.hooks, `${JSON.stringify(installTapHooks(settings, CODEX_SPEC), null, 2)}\n`);
62
+ mkdirSync(path.dirname(paths.rules), { recursive: true });
63
+ writeFileSync(paths.rules, RULES);
64
+ mkdirSync(paths.skillDir, { recursive: true });
65
+ writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
66
+ return `installed meshpoint hooks in ${paths.hooks}, rules in ${paths.rules} and ${paths.skillDir}/SKILL.md. Project .codex files load only once the project is trusted in config.toml; Codex asks to trust new hooks on the next run (/hooks).`;
67
+ }
@@ -0,0 +1,59 @@
1
+ // Reads user and assistant text, and the files touched through apply_patch, out of a Codex CLI
2
+ // rollout (JSONL). Same TranscriptEntry shape as the Claude Code reader so the tap is shared.
3
+ const INJECTED_USER_PREFIXES = ["# AGENTS.md instructions", "<environment_context>", "<permissions instructions>", "<user_instructions>"];
4
+ const PATCH_PATH_RE = /^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm;
5
+ function isRecord(v) {
6
+ return typeof v === "object" && v !== null && !Array.isArray(v);
7
+ }
8
+ function patchPaths(args) {
9
+ if (typeof args !== "string")
10
+ return [];
11
+ let input;
12
+ try {
13
+ input = JSON.parse(args);
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ const patch = isRecord(input) ? (input.patch ?? input.input) : undefined;
19
+ if (typeof patch !== "string")
20
+ return [];
21
+ return [...patch.matchAll(PATCH_PATH_RE)].map((m) => m[1].trim()).filter(Boolean);
22
+ }
23
+ export function parseCodexTranscript(jsonl) {
24
+ const entries = [];
25
+ for (const line of jsonl.split("\n")) {
26
+ if (!line.trim())
27
+ continue;
28
+ let parsed;
29
+ try {
30
+ parsed = JSON.parse(line);
31
+ }
32
+ catch {
33
+ continue;
34
+ }
35
+ if (!isRecord(parsed) || parsed.type !== "response_item" || !isRecord(parsed.payload))
36
+ continue;
37
+ const payload = parsed.payload;
38
+ const at = typeof parsed.timestamp === "string" ? Date.parse(parsed.timestamp) || 0 : 0;
39
+ if (payload.type === "function_call" && payload.name === "apply_patch") {
40
+ const paths = patchPaths(payload.arguments);
41
+ if (paths.length)
42
+ entries.push({ role: "assistant", text: "", paths, at });
43
+ continue;
44
+ }
45
+ if (payload.type !== "message" || (payload.role !== "user" && payload.role !== "assistant") || !Array.isArray(payload.content))
46
+ continue;
47
+ const text = payload.content
48
+ .filter((b) => isRecord(b) && (b.type === "input_text" || b.type === "output_text") && typeof b.text === "string")
49
+ .map((b) => b.text)
50
+ .join("\n")
51
+ .trim();
52
+ if (!text)
53
+ continue;
54
+ if (payload.role === "user" && INJECTED_USER_PREFIXES.some((p) => text.startsWith(p)))
55
+ continue;
56
+ entries.push({ role: payload.role, text, paths: [], at });
57
+ }
58
+ return entries;
59
+ }
package/dist/config.js ADDED
@@ -0,0 +1,66 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { projectIdFromRemote } from "@meshpoint/sdk";
6
+ export function configPath(env = process.env, home = homedir()) {
7
+ return path.join(env.XDG_CONFIG_HOME ?? path.join(home, ".config"), "meshpoint", "config.json");
8
+ }
9
+ // Environment overrides the file; MESHPOINT_BASE_URL and MESHPOINT_TOKEN are enough on their own.
10
+ export function loadConfig(env = process.env, home = homedir()) {
11
+ let fromFile = {};
12
+ try {
13
+ fromFile = JSON.parse(readFileSync(configPath(env, home), "utf8"));
14
+ }
15
+ catch {
16
+ fromFile = {};
17
+ }
18
+ const baseUrl = env.MESHPOINT_BASE_URL ?? fromFile.baseUrl;
19
+ const token = env.MESHPOINT_TOKEN ?? fromFile.token;
20
+ if (!baseUrl || !token)
21
+ return null;
22
+ // An environment token stands alone: file-held refresh state belongs to the file's token.
23
+ if (env.MESHPOINT_TOKEN)
24
+ return { baseUrl, token };
25
+ return { ...fromFile, baseUrl, token };
26
+ }
27
+ export function saveConfig(config, env = process.env, home = homedir()) {
28
+ const file = configPath(env, home);
29
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
30
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
31
+ return file;
32
+ }
33
+ export function deleteConfig(env = process.env, home = homedir()) {
34
+ rmSync(configPath(env, home), { force: true });
35
+ }
36
+ export function stateDir(env = process.env, home = homedir()) {
37
+ return path.join(env.XDG_STATE_HOME ?? path.join(home, ".local", "state"), "meshpoint");
38
+ }
39
+ export function spoolDir(env = process.env, home = homedir()) {
40
+ return path.join(stateDir(env, home), "spool");
41
+ }
42
+ function git(args, cwd) {
43
+ try {
44
+ return execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).toString().trim() || null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ // The project is the origin remote; the branch is whatever is checked out. Detached heads capture
51
+ // under "HEAD". A directory outside a repo with an origin remote has no project and is skipped.
52
+ export function repoContext(cwd) {
53
+ const remote = git(["remote", "get-url", "origin"], cwd);
54
+ const root = git(["rev-parse", "--show-toplevel"], cwd);
55
+ if (!remote || !root)
56
+ return null;
57
+ let project;
58
+ try {
59
+ project = projectIdFromRemote(remote);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ const branch = git(["rev-parse", "--abbrev-ref", "HEAD"], cwd) ?? "HEAD";
65
+ return { project, branch, root };
66
+ }
@@ -0,0 +1,179 @@
1
+ // Control-plane calls for the CLI: login through the platform's AuthKit flow, token refresh,
2
+ // account and org administration.
3
+ import { spawn } from "node:child_process";
4
+ import { randomBytes } from "node:crypto";
5
+ import { createServer } from "node:http";
6
+ import { hostname } from "node:os";
7
+ import { saveConfig } from "./config.js";
8
+ export const REFRESH_WHEN_LEFT_S = 24 * 3600;
9
+ const LOGIN_TIMEOUT_MS = 5 * 60_000;
10
+ const ID_RE = /^[A-Za-z0-9._-]{1,128}$/;
11
+ export class ApiError extends Error {
12
+ status;
13
+ constructor(status, message) {
14
+ super(message);
15
+ this.status = status;
16
+ }
17
+ }
18
+ export async function api(baseUrl, method, path, opts = {}) {
19
+ const res = await (opts.fetch ?? fetch)(`${baseUrl.replace(/\/+$/, "")}${path}`, {
20
+ method,
21
+ headers: {
22
+ ...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),
23
+ ...(opts.body === undefined ? {} : { "content-type": "application/json" }),
24
+ },
25
+ ...(opts.body === undefined ? {} : { body: JSON.stringify(opts.body) }),
26
+ });
27
+ const text = await res.text();
28
+ let parsed;
29
+ try {
30
+ parsed = text ? JSON.parse(text) : undefined;
31
+ }
32
+ catch {
33
+ parsed = undefined;
34
+ }
35
+ if (!res.ok)
36
+ throw new ApiError(res.status, parsed?.error ?? `${method} ${path} -> ${res.status}`);
37
+ return parsed;
38
+ }
39
+ export function defaultAgentName(host = hostname()) {
40
+ const safe = host.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 100);
41
+ return `cli-${safe || "host"}`;
42
+ }
43
+ export function configFromGrant(baseUrl, g) {
44
+ return { baseUrl, token: g.token, refresh: g.refresh, exp: g.exp, org: g.org, orgName: g.org_name, user: g.user, email: g.email, agent: g.agent };
45
+ }
46
+ function openBrowser(url) {
47
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
48
+ try {
49
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => undefined).unref();
50
+ }
51
+ catch {
52
+ // the URL is printed as well
53
+ }
54
+ }
55
+ // Listens on 127.0.0.1 for the browser redirect, trades the grant code for tokens, returns the config.
56
+ export async function login(opts) {
57
+ const agent = opts.agent ?? defaultAgentName();
58
+ if (!ID_RE.test(agent))
59
+ throw new Error("agent name must match " + ID_RE.source);
60
+ if (opts.org !== undefined && !ID_RE.test(opts.org))
61
+ throw new Error("org id must match " + ID_RE.source);
62
+ const nonce = randomBytes(16).toString("base64url");
63
+ const log = opts.log ?? (() => undefined);
64
+ const server = createServer();
65
+ await new Promise((resolve, reject) => {
66
+ server.once("error", reject);
67
+ server.listen(0, "127.0.0.1", () => resolve());
68
+ });
69
+ const address = server.address();
70
+ if (!address || typeof address === "string")
71
+ throw new Error("could not bind a local port");
72
+ const grant = new Promise((resolve, reject) => {
73
+ const timer = setTimeout(() => reject(new Error("login timed out; run meshpoint login again")), opts.timeoutMs ?? LOGIN_TIMEOUT_MS);
74
+ server.on("request", (req, res) => {
75
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
76
+ const reply = (status, body) => {
77
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
78
+ res.end(`<!doctype html><meta charset="utf-8"><title>Meshpoint</title><body style="font-family:system-ui;padding:3rem"><p>${body}</p></body>`);
79
+ };
80
+ if (url.pathname !== "/callback" || url.searchParams.get("nonce") !== nonce)
81
+ return reply(404, "Not found.");
82
+ const error = url.searchParams.get("error");
83
+ if (error) {
84
+ reply(400, `Login failed: ${escapeHtml(error)} ${escapeHtml(url.searchParams.get("error_description") ?? "")}`);
85
+ clearTimeout(timer);
86
+ reject(new Error(`login failed: ${error} ${url.searchParams.get("error_description") ?? ""}`.trim()));
87
+ return;
88
+ }
89
+ const code = url.searchParams.get("code");
90
+ if (!code)
91
+ return reply(400, "Missing code.");
92
+ api(opts.baseUrl, "POST", "/v1/auth/exchange", { body: { code }, fetch: opts.fetch }).then((g) => {
93
+ reply(200, `Logged in to Meshpoint as ${escapeHtml(g.email)} (org ${escapeHtml(g.org_name)}). You can close this tab.`);
94
+ clearTimeout(timer);
95
+ resolve(g);
96
+ }, (err) => {
97
+ reply(502, `Login failed: ${escapeHtml(err instanceof Error ? err.message : String(err))}`);
98
+ clearTimeout(timer);
99
+ reject(err instanceof Error ? err : new Error(String(err)));
100
+ });
101
+ });
102
+ });
103
+ const q = new URLSearchParams({ port: String(address.port), nonce, agent });
104
+ if (opts.org)
105
+ q.set("org", opts.org);
106
+ const startUrl = `${opts.baseUrl.replace(/\/+$/, "")}/v1/auth/start?${q}`;
107
+ log(`Open this URL to log in (a browser should open):\n ${startUrl}`);
108
+ (opts.open ?? openBrowser)(startUrl);
109
+ try {
110
+ return configFromGrant(opts.baseUrl, await grant);
111
+ }
112
+ finally {
113
+ server.close();
114
+ }
115
+ }
116
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
117
+ export async function deviceLogin(opts) {
118
+ const agent = opts.agent ?? defaultAgentName();
119
+ if (!ID_RE.test(agent))
120
+ throw new Error("agent name must match " + ID_RE.source);
121
+ const log = opts.log ?? (() => undefined);
122
+ const sleep = opts.sleep ?? wait;
123
+ const start = await api(opts.baseUrl, "POST", "/v1/auth/device", { body: { agent, hostname: opts.host ?? hostname() }, fetch: opts.fetch });
124
+ log(`Open ${start.verification_uri_complete}`);
125
+ log(`or go to ${start.verification_uri} and enter ${start.user_code}`);
126
+ log(`Waiting for approval (expires in ${Math.max(1, Math.round(start.expires_in / 60))} min)…`);
127
+ let interval = Math.max(1, start.interval) * 1000;
128
+ let waited = 0;
129
+ while (waited < start.expires_in * 1000) {
130
+ await sleep(interval);
131
+ waited += interval;
132
+ try {
133
+ const g = await api(opts.baseUrl, "POST", "/v1/auth/device/token", { body: { device_code: start.device_code }, fetch: opts.fetch });
134
+ return configFromGrant(opts.baseUrl, g);
135
+ }
136
+ catch (err) {
137
+ if (err instanceof ApiError) {
138
+ if (err.status === 428)
139
+ continue;
140
+ if (err.status === 429) {
141
+ interval += 5000;
142
+ continue;
143
+ }
144
+ if (err.status === 403)
145
+ throw new Error("login denied in the console");
146
+ if (err.status === 410)
147
+ throw new Error("code expired, run meshpoint login again");
148
+ throw err;
149
+ }
150
+ // Network trouble: slow down and keep polling until the code expires.
151
+ interval += 5000;
152
+ }
153
+ }
154
+ throw new Error("code expired, run meshpoint login again");
155
+ }
156
+ // A browser can plausibly open: a graphical session, macOS or Windows, and not an SSH or CI shell.
157
+ export function canOpenBrowser(env = process.env, platform = process.platform) {
158
+ if (env.CI)
159
+ return false;
160
+ if (env.SSH_CONNECTION || env.SSH_TTY)
161
+ return false;
162
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY || platform === "darwin" || platform === "win32");
163
+ }
164
+ function escapeHtml(s) {
165
+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ?? c);
166
+ }
167
+ // Refreshes the agent token when it has under a day left, or always with `force` (after a 401: the
168
+ // org key rotated or the token was cut short). Returns the config to use; saves it when renewed.
169
+ export async function freshConfig(config, opts = {}) {
170
+ if (!config.refresh)
171
+ return config;
172
+ const now = opts.now ?? Date.now();
173
+ if (!opts.force && config.exp !== undefined && config.exp - now / 1000 > REFRESH_WHEN_LEFT_S)
174
+ return config;
175
+ const g = await api(config.baseUrl, "POST", "/v1/auth/refresh", { body: { refresh: config.refresh }, fetch: opts.fetch });
176
+ const next = configFromGrant(config.baseUrl, g);
177
+ saveConfig(next, opts.env, opts.home);
178
+ return next;
179
+ }
@@ -0,0 +1,64 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
+ export const CURSOR_TAP_COMMAND = "meshpoint tap cursor";
6
+ const HOOK_TIMEOUT_S = 30;
7
+ // afterAgentResponse carries the reply text; stop only decides on the checkpoint nudge.
8
+ export const CURSOR_EVENTS = ["sessionStart", "beforeSubmitPrompt", "afterAgentResponse", "stop", "preCompact", "sessionEnd"];
9
+ function isManaged(hook) {
10
+ return typeof hook.command === "string" && (hook.command.startsWith("meshpoint tap ") || hook.command.startsWith("meshpoint-tap "));
11
+ }
12
+ function withoutManaged(hooks) {
13
+ return (hooks ?? []).filter((hook) => !isManaged(hook));
14
+ }
15
+ export function installCursorHooks(file) {
16
+ const hooks = { ...file.hooks };
17
+ for (const event of CURSOR_EVENTS)
18
+ hooks[event] = [...withoutManaged(hooks[event]), { command: CURSOR_TAP_COMMAND, timeout: HOOK_TIMEOUT_S }];
19
+ return { ...file, version: file.version ?? 1, hooks };
20
+ }
21
+ // Drops the hooks key when nothing the user wrote remains.
22
+ export function removeCursorHooks(file) {
23
+ const hooks = {};
24
+ for (const [event, defs] of Object.entries(file.hooks ?? {})) {
25
+ const kept = withoutManaged(defs);
26
+ if (kept.length > 0)
27
+ hooks[event] = kept;
28
+ }
29
+ const { hooks: _dropped, ...rest } = file;
30
+ return Object.keys(hooks).length > 0 ? { ...rest, hooks } : rest;
31
+ }
32
+ // Project layout: <repo>/.cursor/{hooks.json,skills/meshpoint}; global: the same under ~/.cursor.
33
+ // Skills are the always-available instructions Cursor offers the agent by name
34
+ // (https://cursor.com/docs/skills, "Skill directories"), which is what the nudge asks for.
35
+ export function cursorPaths(projectDir, home = homedir()) {
36
+ const dir = path.join(projectDir ?? home, ".cursor");
37
+ return { hooks: path.join(dir, "hooks.json"), skillDir: path.join(dir, "skills", SKILL_NAME) };
38
+ }
39
+ export function connectCursor(opts) {
40
+ const paths = opts.paths ?? cursorPaths(opts.projectDir);
41
+ let file = {};
42
+ try {
43
+ file = JSON.parse(readFileSync(paths.hooks, "utf8"));
44
+ }
45
+ catch (err) {
46
+ if (err.code !== "ENOENT")
47
+ throw new Error(`could not read ${paths.hooks}: ${err.message}`);
48
+ }
49
+ if (opts.remove) {
50
+ const next = removeCursorHooks(file);
51
+ if (next.hooks)
52
+ writeFileSync(paths.hooks, `${JSON.stringify(next, null, 2)}\n`);
53
+ else
54
+ rmSync(paths.hooks, { force: true });
55
+ rmSync(paths.skillDir, { recursive: true, force: true });
56
+ return `removed meshpoint hooks from ${paths.hooks} and ${paths.skillDir}`;
57
+ }
58
+ mkdirSync(path.dirname(paths.hooks), { recursive: true });
59
+ writeFileSync(paths.hooks, `${JSON.stringify(installCursorHooks(file), null, 2)}\n`);
60
+ mkdirSync(paths.skillDir, { recursive: true });
61
+ // Cursor's SKILL.md frontmatter takes name and description; allowed-tools is Claude Code only.
62
+ writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
63
+ return `installed meshpoint hooks in ${paths.hooks} (${CURSOR_EVENTS.join(", ")}) and ${paths.skillDir}/SKILL.md. Cursor reloads hooks.json on save; the Hooks tab under Customize lists them.`;
64
+ }
@@ -0,0 +1,68 @@
1
+ import { lastAssistantTurn } from "../claude-code/transcript.js";
2
+ import { NUDGE_PREFIX, Tap } from "../tap.js";
3
+ import { parseCursorTranscript } from "./transcript.js";
4
+ const CONTINUE = '{"continue":true}';
5
+ // One Cursor hook event in, one JSON answer out. Same deps as the Claude Code wrapper so bin.ts
6
+ // builds one deps object; parseTranscript defaults to the Cursor reader. The Tap swallows mesh
7
+ // failures; this layer only speaks the protocol.
8
+ export async function runCursorTap(payload, deps) {
9
+ const event = payload.hook_event_name ?? "";
10
+ const empty = event === "beforeSubmitPrompt" ? CONTINUE : "{}";
11
+ // Project hooks run from the project root, user hooks from ~/.cursor; workspace_roots is right in both.
12
+ const repo = deps.repo(payload.workspace_roots?.[0] ?? process.cwd());
13
+ if (!repo)
14
+ return empty;
15
+ const tap = new Tap({
16
+ config: deps.config,
17
+ repo,
18
+ session: payload.conversation_id ?? payload.session_id ?? "unknown",
19
+ spool: deps.spool,
20
+ checkpoints: deps.checkpoints,
21
+ ...(deps.now ? { now: deps.now } : {}),
22
+ ...(deps.fetch ? { fetch: deps.fetch } : {}),
23
+ ...(deps.presenceWaitMs !== undefined ? { presenceWaitMs: deps.presenceWaitMs } : {}),
24
+ ...(deps.refresh ? { refresh: deps.refresh } : {}),
25
+ });
26
+ const transcript = () => {
27
+ if (!payload.transcript_path)
28
+ return [];
29
+ try {
30
+ return (deps.parseTranscript ?? parseCursorTranscript)(deps.readTranscript(payload.transcript_path));
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ };
36
+ switch (event) {
37
+ case "sessionStart": {
38
+ const text = await tap.start();
39
+ return text ? JSON.stringify({ additional_context: text }) : "{}";
40
+ }
41
+ case "beforeSubmitPrompt": {
42
+ // A stop hook's followup_message comes back through here as a user prompt; keep ours out of the capture.
43
+ const prompt = payload.prompt ?? "";
44
+ await tap.user(prompt.startsWith(NUDGE_PREFIX) ? "" : prompt);
45
+ return CONTINUE;
46
+ }
47
+ case "afterAgentResponse": {
48
+ // The documented text field is the reply; the transcript, when readable, adds the touched paths.
49
+ await tap.assistant(payload.text ?? "", lastAssistantTurn(transcript())?.paths ?? []);
50
+ return "{}";
51
+ }
52
+ case "stop": {
53
+ // A non-empty followup_message is auto-submitted as the next user message, which keeps the
54
+ // agent going so it writes its items now. Recording the nudge already stops it repeating;
55
+ // Cursor's own loop_limit (default 5 per script) caps follow-ups per conversation on top.
56
+ if (payload.status !== undefined && payload.status !== "completed")
57
+ return "{}";
58
+ const reason = tap.nudge(transcript());
59
+ return reason ? JSON.stringify({ followup_message: reason }) : "{}";
60
+ }
61
+ case "preCompact":
62
+ case "sessionEnd":
63
+ await tap.end();
64
+ return "{}";
65
+ default:
66
+ return empty;
67
+ }
68
+ }
@@ -0,0 +1,74 @@
1
+ // Cursor documents transcript_path only as "path to the main conversation transcript file"
2
+ // (https://cursor.com/docs/hooks, "Common schema"); the file format is undocumented. Try the two
3
+ // shapes Cursor itself reads for compatibility, Claude Code's and Codex's, then flat
4
+ // {role, content | text} records, as JSONL or one JSON array.
5
+ import { parseTranscript as parseClaudeCodeTranscript } from "../claude-code/transcript.js";
6
+ import { parseCodexTranscript } from "../codex/transcript.js";
7
+ function isRecord(v) {
8
+ return typeof v === "object" && v !== null && !Array.isArray(v);
9
+ }
10
+ function records(raw) {
11
+ const trimmed = raw.trim();
12
+ if (trimmed.startsWith("[")) {
13
+ try {
14
+ const parsed = JSON.parse(trimmed);
15
+ if (Array.isArray(parsed))
16
+ return parsed;
17
+ }
18
+ catch {
19
+ // Not one JSON document; read it as JSONL below.
20
+ }
21
+ }
22
+ const out = [];
23
+ for (const line of raw.split("\n")) {
24
+ if (!line.trim())
25
+ continue;
26
+ try {
27
+ out.push(JSON.parse(line));
28
+ }
29
+ catch {
30
+ continue;
31
+ }
32
+ }
33
+ return out;
34
+ }
35
+ function textOf(v) {
36
+ if (typeof v === "string")
37
+ return v;
38
+ if (!Array.isArray(v))
39
+ return "";
40
+ return v
41
+ .map((b) => (typeof b === "string" ? b : isRecord(b) && typeof b.text === "string" ? b.text : ""))
42
+ .filter(Boolean)
43
+ .join("\n");
44
+ }
45
+ function epochMs(v) {
46
+ if (typeof v === "number")
47
+ return v < 1e12 ? v * 1000 : v;
48
+ if (typeof v === "string")
49
+ return Date.parse(v) || 0;
50
+ return 0;
51
+ }
52
+ function parseGenericTranscript(raw) {
53
+ const entries = [];
54
+ for (const r of records(raw)) {
55
+ if (!isRecord(r))
56
+ continue;
57
+ const role = r.role ?? r.type;
58
+ if (role !== "user" && role !== "assistant")
59
+ continue;
60
+ const text = textOf(r.content ?? r.text).trim();
61
+ if (!text)
62
+ continue;
63
+ entries.push({ role, text, paths: [], at: epochMs(r.timestamp ?? r.createdAt ?? r.created_at) });
64
+ }
65
+ return entries;
66
+ }
67
+ export function parseCursorTranscript(raw) {
68
+ for (const parse of [parseClaudeCodeTranscript, parseCodexTranscript, parseGenericTranscript]) {
69
+ const entries = parse(raw);
70
+ if (entries.length > 0)
71
+ return entries;
72
+ }
73
+ return [];
74
+ }