longtable 0.1.35 → 0.1.37
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/bin/longtable.mjs +11 -3
- package/package.json +1 -1
- package/src/approve-server.mjs +104 -10
- package/src/claude.mjs +138 -30
- package/src/extras.mjs +2 -1
- package/src/inbox-hook.mjs +54 -0
- package/src/pointed.mjs +3 -2
- package/src/procs.mjs +152 -0
- package/src/repo.mjs +130 -12
- package/src/run.mjs +292 -38
- package/src/sessions.mjs +93 -0
package/bin/longtable.mjs
CHANGED
|
@@ -12,13 +12,15 @@
|
|
|
12
12
|
|
|
13
13
|
import { spawn } from "node:child_process";
|
|
14
14
|
import { rmSync } from "node:fs";
|
|
15
|
-
import { join
|
|
15
|
+
import { join } from "node:path";
|
|
16
16
|
import { fileURLToPath } from "node:url";
|
|
17
17
|
import { client, fetchConfig } from "../src/api.mjs";
|
|
18
18
|
import { claudeVersion, findClaude, installClaude, tokenWorks } from "../src/claude.mjs";
|
|
19
19
|
import { codexSignIn, codexSignedIn, codexVersion, findCodex } from "../src/codex.mjs";
|
|
20
20
|
import { disableAutostart, enableAutostart } from "../src/autostart.mjs";
|
|
21
|
-
import { forgetCopies, freshCopy, gitCanJoin, resolveSource } from "../src/repo.mjs";
|
|
21
|
+
import { folderFor, forgetCopies, freshCopy, gitCanJoin, resolveSource } from "../src/repo.mjs";
|
|
22
|
+
import { forgetTableSessions } from "../src/sessions.mjs";
|
|
23
|
+
import { stopLeftovers } from "../src/procs.mjs";
|
|
22
24
|
import { endConnection, runLoop, runningConnection } from "../src/run.mjs";
|
|
23
25
|
import { handOffTo } from "../src/update.mjs";
|
|
24
26
|
import { pathToFileURL } from "node:url";
|
|
@@ -91,7 +93,9 @@ async function connect() {
|
|
|
91
93
|
member_name: paired.member_name,
|
|
92
94
|
role: paired.role,
|
|
93
95
|
source,
|
|
94
|
-
|
|
96
|
+
// Connected with the table's repository from inside the project's own folder, that folder is still theirs:
|
|
97
|
+
// their own requests work in it.
|
|
98
|
+
folder: folderFor(repo, process.cwd()),
|
|
95
99
|
model: option("model") || null,
|
|
96
100
|
});
|
|
97
101
|
writeConfig(config);
|
|
@@ -181,6 +185,10 @@ async function disconnect() {
|
|
|
181
185
|
// The project copies and work folders it kept go too. The Claude sign-in stays: it is the person's own,
|
|
182
186
|
// and another table on this computer may still use it.
|
|
183
187
|
forgetCopies((config.connections || []).map((c) => c.table_id), (config.connections || []).map((c) => c.folder).filter(Boolean));
|
|
188
|
+
// Which chat had which session is forgotten too; the sessions themselves stay in their own Claude Code history.
|
|
189
|
+
forgetTableSessions((config.connections || []).map((c) => c.table_id));
|
|
190
|
+
// The connection was ended from outside, so what its sessions left running is stopped here.
|
|
191
|
+
stopLeftovers();
|
|
184
192
|
// Its own notes from those tables, and a client's ChatGPT sign-in kept for Longtable alone, go too.
|
|
185
193
|
for (const c of config.connections || []) { try { rmSync(join(home, "minds", `${String(c.table_id).replace(/[^0-9a-f-]/gi, "")}.md`), { force: true }); } catch {} }
|
|
186
194
|
if ((config.connections || []).some((c) => c.role === "client")) { try { rmSync(join(home, "codex"), { recursive: true, force: true }); } catch {} }
|
package/package.json
CHANGED
package/src/approve-server.mjs
CHANGED
|
@@ -2,22 +2,26 @@
|
|
|
2
2
|
// The permission prompts of a person's full Claude Code at the table, brought to them in Longtable. Claude Code starts
|
|
3
3
|
// this as an MCP server and calls its one tool, "approve", whenever it wants to do something the person's own rules
|
|
4
4
|
// do not already allow (--permission-prompt-tool). The request goes to Longtable; the person allows or denies it on
|
|
5
|
-
// their own screen; the answer comes back here and decides. Nobody else at the table can answer.
|
|
6
|
-
//
|
|
5
|
+
// their own screen; the answer comes back here and decides. Nobody else at the table can answer. It waits for them as
|
|
6
|
+
// Claude Code at home does, for as long as the job runs; when the job ends (stopped, finished, its computer gone), the
|
|
7
|
+
// request ends with it.
|
|
7
8
|
//
|
|
8
9
|
// It is given, through its environment: Longtable's address and public key, a key for this one job (never the
|
|
9
10
|
// connection's device token: a key that can only ask about this job, and dies when it ends), and the file where this
|
|
10
11
|
// person's "always allow" answers are kept on this computer.
|
|
11
12
|
|
|
12
|
-
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
13
|
-
import {
|
|
13
|
+
import { readFileSync, realpathSync, statSync, writeFileSync, mkdirSync } from "node:fs";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { basename, delimiter, dirname, extname, resolve, sep } from "node:path";
|
|
16
|
+
import { refused } from "./pointed.mjs";
|
|
14
17
|
import { client } from "./api.mjs";
|
|
15
18
|
|
|
16
19
|
const NL = String.fromCharCode(10);
|
|
17
20
|
const rpc = client({ supabaseUrl: process.env.LT_SUPABASE_URL, publishableKey: process.env.LT_KEY });
|
|
18
21
|
const key = process.env.LT_JOB_KEY;
|
|
19
22
|
const alwaysFile = process.env.LT_ALWAYS;
|
|
20
|
-
|
|
23
|
+
// No limit unless a test sets one.
|
|
24
|
+
const WAIT_MS = Number(process.env.LT_WAIT_MS || 0);
|
|
21
25
|
const POLL_MS = Number(process.env.LT_POLL_MS || 1500);
|
|
22
26
|
|
|
23
27
|
// What the person is asked: exactly what would be done. A command is shown whole; any other tool shows its whole
|
|
@@ -36,6 +40,18 @@ export function describe(tool, input) {
|
|
|
36
40
|
return text.length > SHOW_MAX ? null : text;
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
// Why it is wanted, in one plain line, so a person who reads no commands can still answer: what Claude Code wrote for
|
|
44
|
+
// the command, or the file it would change.
|
|
45
|
+
export function whyOf(tool, input) {
|
|
46
|
+
const i = input && typeof input === "object" ? input : {};
|
|
47
|
+
// Only a command's own description: another tool's "description" field is what it would write, not why.
|
|
48
|
+
const said = tool === "Bash" && typeof i.description === "string" ? i.description.replace(/\s+/g, " ").trim() : "";
|
|
49
|
+
if (said) return said.slice(0, 1000);
|
|
50
|
+
const file = String(i.file_path || i.notebook_path || "").split(/[\\/]/).pop();
|
|
51
|
+
if (["Edit", "Write", "MultiEdit", "NotebookEdit"].includes(tool) && file) return `Change ${file}`;
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
39
55
|
// The rule an "always allow" answer adds: one command, exactly as it was asked for, and nothing broader. Never a
|
|
40
56
|
// whole tool, and never a command Claude Code could read as a pattern or that chains other commands.
|
|
41
57
|
const PLAIN = /^[^*()\r\n;&|`$<>]{1,500}$/;
|
|
@@ -70,14 +86,18 @@ async function decide(tool, input) {
|
|
|
70
86
|
if (summary === null) return { behavior: "deny", message: "This was too long to show the person in full, so it was not asked and not done. Break it into smaller steps." };
|
|
71
87
|
let id;
|
|
72
88
|
try {
|
|
73
|
-
id = await rpc("runner_ask_approval", { key, tool, summary });
|
|
89
|
+
id = await rpc("runner_ask_approval", { key, tool, summary, why: whyOf(tool, input) });
|
|
74
90
|
} catch (e) {
|
|
75
91
|
return { behavior: "deny", message: `Longtable could not ask the person (${e.message}), so this was not done.` };
|
|
76
92
|
}
|
|
77
|
-
for (const end = Date.now() + WAIT_MS; Date.now() < end;) {
|
|
93
|
+
for (const end = WAIT_MS ? Date.now() + WAIT_MS : Infinity; Date.now() < end;) {
|
|
78
94
|
await sleep(POLL_MS);
|
|
79
95
|
let r;
|
|
80
|
-
try { r = await rpc("runner_approval", { key, a: id }); } catch {
|
|
96
|
+
try { r = await rpc("runner_approval", { key, a: id }); } catch (e) {
|
|
97
|
+
// The job ended and its key with it: nobody will answer now.
|
|
98
|
+
if (/not for a running job|no such request/i.test(e.message)) break;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
81
101
|
if (r?.status === "allowed") {
|
|
82
102
|
if (r.always) remember(ruleFor(tool, input));
|
|
83
103
|
return { behavior: "allow", updatedInput: input };
|
|
@@ -85,7 +105,64 @@ async function decide(tool, input) {
|
|
|
85
105
|
if (r?.status === "denied") return { behavior: "deny", message: "The person said no to this in Longtable. Do not try it another way; say what you would have done instead." };
|
|
86
106
|
if (r?.status === "expired") break;
|
|
87
107
|
}
|
|
88
|
-
return { behavior: "deny", message: "
|
|
108
|
+
return { behavior: "deny", message: "This work ended before the person answered in Longtable, so it was not done. Say what you would have done, and the person can ask again." };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// A question with choices for the person, as Claude Code's own question tool asks at home: a card in Longtable with a
|
|
112
|
+
// button for each choice and room for their own words. It waits for them as long as the job runs.
|
|
113
|
+
const ASK_ABOUT = "Ask your person a question with choices, the way you would at home: they see it in Longtable as a card with a button for each choice, and can answer in their own words. It waits for their answer. Use it when you need their decision to go on.";
|
|
114
|
+
async function askPerson(question, options) {
|
|
115
|
+
const opts = (Array.isArray(options) ? options : []).map((o) => ({ label: String(o?.label ?? "").slice(0, 400), about: String(o?.description ?? o?.about ?? "").slice(0, 1000) }));
|
|
116
|
+
let id;
|
|
117
|
+
try { id = await rpc("runner_ask_question", { key, question: String(question ?? "").slice(0, 4000), options: opts }); }
|
|
118
|
+
catch (e) { return `Longtable could not ask the person (${e.message}). Carry on with the safest choice and say which you took.`; }
|
|
119
|
+
for (const end = WAIT_MS ? Date.now() + WAIT_MS : Infinity; Date.now() < end;) {
|
|
120
|
+
await sleep(POLL_MS);
|
|
121
|
+
let r;
|
|
122
|
+
try { r = await rpc("runner_approval", { key, a: id }); } catch (e) {
|
|
123
|
+
if (/not for a running job|no such request/i.test(e.message)) break;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (r?.status === "allowed" && r.answer) return `They answered: ${r.answer}`;
|
|
127
|
+
if (r?.status && r.status !== "waiting") break;
|
|
128
|
+
}
|
|
129
|
+
return "This work ended before the person answered. Say what you would have needed to know.";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// A file or picture for its answer, as Claude in the app can send one: uploaded into the table's attachments (only into
|
|
133
|
+
// this job's own place) and shown on the answer. Never a secret file Longtable would refuse to open, never a folder,
|
|
134
|
+
// never over 15 MB.
|
|
135
|
+
const SHARE_ABOUT = "Put a file or a picture into your answer, the way you would send one in the Claude app: a screenshot you took, a spreadsheet or report you made. Give its path; it shows on your answer in Longtable for the team. Never keys or secret files.";
|
|
136
|
+
const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml",
|
|
137
|
+
".pdf": "application/pdf", ".csv": "text/csv", ".txt": "text/plain", ".md": "text/markdown", ".json": "application/json", ".html": "text/html",
|
|
138
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
139
|
+
".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".zip": "application/zip" };
|
|
140
|
+
async function shareFile(path) {
|
|
141
|
+
const where = resolve(String(path || ""));
|
|
142
|
+
let st;
|
|
143
|
+
try { st = statSync(where); } catch { return `There is no file at ${path}.`; }
|
|
144
|
+
if (!st.isFile()) return "That is not a file: share one file at a time.";
|
|
145
|
+
if (refused(where) || refused(realpathSync(where))) return "That file is one Longtable never shares (keys, passwords, sign-ins). Say so instead.";
|
|
146
|
+
// Only from the folder it works in (never the person's own notes laid beside it) or a screenshot it took: anything
|
|
147
|
+
// else on the computer is never put in front of the team by a tool that does not ask.
|
|
148
|
+
const real = realpathSync(where);
|
|
149
|
+
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
150
|
+
const roots = String(process.env.LT_SHARE_ROOTS || "").split(delimiter).filter(Boolean).map((r) => { try { return realpathSync(r); } catch { return resolve(r); } });
|
|
151
|
+
if (!roots.some((r) => fold(real).startsWith(fold(r.endsWith(sep) ? r : r + sep))) || /[\\/]\.longtable-yours([\\/]|$)/.test(real)) {
|
|
152
|
+
return "Only a file from the folder you work in, or a screenshot you took, can go on your answer. Say where the file is instead.";
|
|
153
|
+
}
|
|
154
|
+
if (st.size > 15 * 1024 * 1024) return "That file is over 15 MB, too big to put in the answer. Say where it is instead.";
|
|
155
|
+
const name = basename(where).replace(/[^\w.\- ()]/g, "_").slice(0, 120) || "file";
|
|
156
|
+
let prefix;
|
|
157
|
+
try { prefix = await rpc("runner_upload_slot", { key }); } catch (e) { return `Longtable could not take the file (${e.message}). Say where it is instead.`; }
|
|
158
|
+
const object = `${prefix}${randomUUID()}-${name}`;
|
|
159
|
+
const res = await fetch(`${process.env.LT_SUPABASE_URL}/storage/v1/object/attachments/${object.split("/").map(encodeURIComponent).join("/")}`, {
|
|
160
|
+
method: "POST", headers: { apikey: process.env.LT_KEY, "Content-Type": MIME[extname(name).toLowerCase()] || "application/octet-stream", "x-upsert": "false" },
|
|
161
|
+
body: readFileSync(where),
|
|
162
|
+
}).catch((e) => ({ ok: false, status: e.message }));
|
|
163
|
+
if (!res.ok) return `The file could not be uploaded (${res.status}). Say where it is instead.`;
|
|
164
|
+
try { await rpc("runner_attach", { key, path: object, name }); } catch (e) { return `The file was not kept (${e.message}). Say where it is instead.`; }
|
|
165
|
+
return `${name} is on your answer: the team sees it there.`;
|
|
89
166
|
}
|
|
90
167
|
|
|
91
168
|
// The MCP side: JSON-RPC over stdin and stdout, one message a line.
|
|
@@ -93,6 +170,8 @@ function serve() {
|
|
|
93
170
|
let buf = "";
|
|
94
171
|
const send = (m) => process.stdout.write(JSON.stringify(m) + NL);
|
|
95
172
|
process.stdin.setEncoding("utf8");
|
|
173
|
+
// Claude Code gone (its pipe closed): nobody is left to answer for, so it stops instead of polling on.
|
|
174
|
+
process.stdin.on("end", () => process.exit(0));
|
|
96
175
|
process.stdin.on("data", (d) => {
|
|
97
176
|
buf += d;
|
|
98
177
|
let at;
|
|
@@ -107,7 +186,22 @@ function serve() {
|
|
|
107
186
|
reply({ protocolVersion: m.params?.protocolVersion || "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "longtable", version: "1" } });
|
|
108
187
|
} else if (m.method === "tools/list") {
|
|
109
188
|
reply({ tools: [{ name: "approve", description: "Asks the person in Longtable whether their Claude may do this.",
|
|
110
|
-
inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } }
|
|
189
|
+
inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } },
|
|
190
|
+
{ name: "ask", description: ASK_ABOUT,
|
|
191
|
+
inputSchema: { type: "object", properties: { question: { type: "string", description: "The question, in plain words." },
|
|
192
|
+
options: { type: "array", minItems: 2, maxItems: 6, items: { type: "object", properties: { label: { type: "string", description: "A short choice." }, description: { type: "string", description: "One line on what choosing it means." } }, required: ["label"] } } },
|
|
193
|
+
required: ["question", "options"] } },
|
|
194
|
+
{ name: "share_file", description: SHARE_ABOUT,
|
|
195
|
+
inputSchema: { type: "object", properties: { path: { type: "string", description: "The file's path." } }, required: ["path"] } }] });
|
|
196
|
+
} else if (m.method === "tools/call" && m.params?.name === "share_file") {
|
|
197
|
+
shareFile(m.params?.arguments?.path).then(
|
|
198
|
+
(text) => reply({ content: [{ type: "text", text }] }),
|
|
199
|
+
() => reply({ content: [{ type: "text", text: "The file could not be shared. Say where it is instead." }] }));
|
|
200
|
+
} else if (m.method === "tools/call" && m.params?.name === "ask") {
|
|
201
|
+
const a = m.params?.arguments || {};
|
|
202
|
+
askPerson(a.question, a.options).then(
|
|
203
|
+
(text) => reply({ content: [{ type: "text", text }] }),
|
|
204
|
+
() => reply({ content: [{ type: "text", text: "Longtable could not ask the person. Carry on with the safest choice and say which you took." }] }));
|
|
111
205
|
} else if (m.method === "tools/call") {
|
|
112
206
|
const a = m.params?.arguments || {};
|
|
113
207
|
decide(String(a.tool_name || "a tool"), a.input || {}).then(
|
package/src/claude.mjs
CHANGED
|
@@ -5,6 +5,10 @@ import { existsSync, mkdirSync, readdirSync } from "node:fs";
|
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { delimiter, join } from "node:path";
|
|
7
7
|
import { home, loadSecret, log } from "./store.mjs";
|
|
8
|
+
import { below } from "./procs.mjs";
|
|
9
|
+
|
|
10
|
+
// A command that can leave a program running after it returns.
|
|
11
|
+
export const LEAVES_RUNNING = /(^|[^&<>])&(?![&>])|\bnohup\b|\bdisown\b|\bsetsid\b|\bnpm\s+(run\s+)?(dev|start)\b|\bnext\s+(dev|start)\b|\bvite\b|\bserve\b|docker\s+compose\s+up|\bpm2\b/i;
|
|
8
12
|
|
|
9
13
|
const isWindows = process.platform === "win32";
|
|
10
14
|
const exe = isWindows ? "claude.exe" : "claude";
|
|
@@ -72,20 +76,45 @@ export function childEnv(token, apiKey) {
|
|
|
72
76
|
|
|
73
77
|
// A full Claude Code run gets the person's own environment, as their Claude Code at home would (their PATH, their git
|
|
74
78
|
// and their tools), with the connection's own sign-in: never an API key or another account from whatever started it.
|
|
75
|
-
|
|
79
|
+
// Every character that can carry a repository address on past its end.
|
|
80
|
+
// (The table's repository is only ever an https or ssh address, whose names use few of these; the rest are here so
|
|
81
|
+
// an address on this computer, a path, is held to the same rule.)
|
|
82
|
+
const CONTINUES = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~+/@:%\\ #?=,;!$&'()*[]"];
|
|
83
|
+
|
|
84
|
+
// The environment a full run's commands see. `pushTo`: the only addresses git may push to (an empty list refuses
|
|
85
|
+
// every push; null leaves pushing to the person, as at home). `hooksOff`: git hooks point at an empty folder.
|
|
86
|
+
export function fullEnv(token, { hooksOff = true, pushTo = [] } = {}) {
|
|
76
87
|
const env = { ...process.env };
|
|
77
88
|
for (const k of Object.keys(env)) if (/^(ANTHROPIC_|CLAUDE_CODE_OAUTH_TOKEN$|CLAUDE_CODE_USE_|OPENAI_API_KEY$|LT_)/.test(k)) delete env[k];
|
|
78
89
|
if (token) env.CLAUDE_CODE_OAUTH_TOKEN = token;
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
90
|
+
// A permission request waits for its person as long as they take, as at home: Claude Code's own limit on a tool call
|
|
91
|
+
// (the approval is one) is set to a week, unless they set their own.
|
|
92
|
+
if (!env.MCP_TOOL_TIMEOUT) env.MCP_TOOL_TIMEOUT = String(7 * 24 * 3600 * 1000);
|
|
93
|
+
const conf = [];
|
|
94
|
+
// Git itself refuses a push from the commands this Claude runs, however the command is written (git -C, -c, an
|
|
95
|
+
// alias, a script): every push address is rewritten to one no git can reach. The addresses it may push to are
|
|
96
|
+
// rewritten to themselves, and git takes the longest match, so only those go through.
|
|
97
|
+
if (Array.isArray(pushTo)) {
|
|
98
|
+
const NO = "url.longtable-no-push://refused/.pushInsteadOf";
|
|
99
|
+
conf.push([NO, ""]);
|
|
100
|
+
const allowed = [...new Set(pushTo.filter((x) => typeof x === "string" && x && !/[\r\n]/.test(x)))];
|
|
101
|
+
for (const u of allowed) {
|
|
102
|
+
conf.push([`url.${u}.pushInsteadOf`, u]);
|
|
103
|
+
// The rewrite matches by prefix, so an address that only starts with an allowed one (team/app-old after
|
|
104
|
+
// team/app) is refused by a longer rule of its own. An allowed longer form (app.git) is longer still and wins.
|
|
105
|
+
for (const c of CONTINUES) if (!allowed.includes(u + c)) conf.push([NO, u + c]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// A hook from a branch other people's AIs push to never runs. In the person's own folder their hooks are theirs.
|
|
109
|
+
if (hooksOff) {
|
|
110
|
+
const noHooks = join(home, "no-hooks");
|
|
111
|
+
try { mkdirSync(noHooks, { recursive: true }); } catch {}
|
|
112
|
+
conf.push(["core.hooksPath", noHooks]);
|
|
113
|
+
}
|
|
114
|
+
if (conf.length) {
|
|
115
|
+
env.GIT_CONFIG_COUNT = String(conf.length);
|
|
116
|
+
conf.forEach(([k, v], i) => { env[`GIT_CONFIG_KEY_${i}`] = k; env[`GIT_CONFIG_VALUE_${i}`] = v; });
|
|
117
|
+
}
|
|
89
118
|
return env;
|
|
90
119
|
}
|
|
91
120
|
|
|
@@ -131,12 +160,22 @@ export const EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
|
|
|
131
160
|
// through the approval server (`full.mcp`, the MCP config that starts it), where the person allows or denies each one.
|
|
132
161
|
// Their "always allow" answers come back as `full.allow`. On Mac and Linux, commands also run in Claude Code's sandbox.
|
|
133
162
|
// A job that only reads may not change files (`edit` false).
|
|
134
|
-
|
|
163
|
+
// A run asked for in Auto on an account that cannot use it goes again in Accept edits, rather than failing.
|
|
164
|
+
export function ask(opts) {
|
|
165
|
+
return askOnce(opts).catch((e) => {
|
|
166
|
+
if (!e.noAuto) throw e;
|
|
167
|
+
log("Auto mode is not available to this Claude Code; running in Accept edits");
|
|
168
|
+
return askOnce({ ...opts, full: { ...opts.full, mode: "acceptEdits" } });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function askOnce({ claude, cwd, prompt, system, schema, model, tools = "Read,Grep,Glob", edit = false, long = false, onNote, control, apiKey, timeoutMs = 4 * 60 * 1000, addDirs = [], effort = null, fast = false, full = null, session = null }) {
|
|
135
173
|
// Work a person asked for takes as long as it takes: no time limit, and steps to match. It ends when it is done,
|
|
136
174
|
// when someone presses Stop, or when the connection itself goes away.
|
|
137
175
|
if (edit) { tools = "Read,Grep,Glob,Edit,Write"; timeoutMs = long ? 0 : 10 * 60 * 1000; }
|
|
138
|
-
//
|
|
139
|
-
|
|
176
|
+
// Their own full Claude Code takes as long as it takes, a question as much as work, as at home: no time limit and
|
|
177
|
+
// steps to match. It ends when it is done, when they press Stop, or when the connection goes away.
|
|
178
|
+
if (full) timeoutMs = 0;
|
|
140
179
|
const token = apiKey ? null : loadSecret("claude-token");
|
|
141
180
|
if (!token && !apiKey) return Promise.reject(new Error("This connection has no Claude sign-in yet. Run connect again."));
|
|
142
181
|
// Streamed output carries the plan's usage limits (a rate_limit_event) as well as the result.
|
|
@@ -145,17 +184,30 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
|
|
|
145
184
|
// Their own choice of how it asks (manual, accept edits, auto, plan), else as before: edits go ahead in work.
|
|
146
185
|
"--permission-mode", full.mode === "plan" ? "plan" : full.mode === "auto" ? "auto" : full.mode === "manual" ? "default" : full.mode === "acceptEdits" || edit ? "acceptEdits" : "default",
|
|
147
186
|
"--permission-prompt-tool", "mcp__longtable__approve",
|
|
148
|
-
"--mcp-config", full.mcp, "--max-turns", edit
|
|
187
|
+
"--mcp-config", full.mcp, "--max-turns", edit && !long ? "200" : "10000"]
|
|
149
188
|
: ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence", "--restricted", "--permission-mode", edit ? "acceptEdits" : "dontAsk",
|
|
150
189
|
"--strict-mcp-config", "--max-turns", edit ? (long ? "10000" : "60") : tools ? "25" : "4", "--tools", tools];
|
|
151
190
|
if (full) {
|
|
152
191
|
// Their own settings come from their own computer: their user settings, and their project's settings read from
|
|
153
192
|
// their own folder (full.project), never from the branch being worked on, which other people's AIs push to.
|
|
154
|
-
|
|
193
|
+
// In their own folder (full.folder) it is Claude Code as at home: every settings source of theirs, the project's
|
|
194
|
+
// and their local ones included, read by Claude Code itself.
|
|
195
|
+
args.push("--setting-sources", full.folder ? "user,project,local" : "user");
|
|
155
196
|
// Only the connection pushes, and only the task's branch: their Claude never pushes itself, whatever their rules.
|
|
156
|
-
// In
|
|
157
|
-
|
|
158
|
-
|
|
197
|
+
// In their own folder a push goes only to the table's repository (unless they let it push anywhere), asked like
|
|
198
|
+
// any command. In plan mode the plan is its answer here: there is
|
|
199
|
+
// no plan to approve, so it never asks to leave plan mode.
|
|
200
|
+
// A remote with a push address of its own is not covered by git's rewrite, so then pushing is refused outright.
|
|
201
|
+
// Its own question tool goes nowhere in a run like this; questions go to the person through Longtable's instead.
|
|
202
|
+
const no = ["AskUserQuestion", ...(full.folder && !full.noPush ? [] : ["Bash(git push:*)", "Bash(git push)"]), ...(edit ? [] : ["Edit", "Write", "NotebookEdit"]), ...(full.mode === "plan" ? ["ExitPlanMode"] : [])];
|
|
203
|
+
if (no.length) args.push("--disallowedTools", ...no);
|
|
204
|
+
// Asking its person a question, or putting a file on its answer, is never itself something to ask permission for.
|
|
205
|
+
args.push("--allowedTools", "mcp__longtable__ask", "mcp__longtable__share_file", ...(full.allow || []));
|
|
206
|
+
}
|
|
207
|
+
// A person's own chat in their own folder keeps one session, as at home: kept by Claude Code, picked up next time.
|
|
208
|
+
if (session && full) {
|
|
209
|
+
args.splice(args.indexOf("--no-session-persistence"), 1);
|
|
210
|
+
args.push(session.resume ? "--resume" : "--session-id", session.id);
|
|
159
211
|
}
|
|
160
212
|
if (system) args.push("--append-system-prompt", system);
|
|
161
213
|
if (schema) args.push("--json-schema", JSON.stringify(schema));
|
|
@@ -164,14 +216,18 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
|
|
|
164
216
|
if (EFFORTS.has(effort)) args.push("--effort", effort);
|
|
165
217
|
// On Mac and Linux commands also run in Claude Code's sandbox, and still ask: the sandbox alone never stands in for
|
|
166
218
|
// the person's answer.
|
|
167
|
-
|
|
168
|
-
|
|
219
|
+
// full.hooks: what the person says in the chat while it works reaches it after each step (added to the hooks of their
|
|
220
|
+
// own settings, which Claude Code still runs).
|
|
221
|
+
const settings = { ...(full?.project || {}), ...(fast ? { fastMode: true } : {}), ...(full?.hooks ? { hooks: full.hooks } : {}),
|
|
222
|
+
...(full && !full.folder && process.platform !== "win32" ? { sandbox: { ...(full?.project?.sandbox || {}), enabled: true, autoAllowBashIfSandboxed: false } } : {}) };
|
|
169
223
|
if (Object.keys(settings).length) args.push("--settings", JSON.stringify(settings));
|
|
170
224
|
// Folders beside the working one that this job may read: only ever ones the connection chose.
|
|
171
225
|
for (const d of addDirs) args.push("--add-dir", d);
|
|
172
226
|
return new Promise((resolve, reject) => {
|
|
173
227
|
const started = Date.now();
|
|
174
|
-
const child = spawn(claude, args, { cwd, env: full ? fullEnv(token) : childEnv(token, apiKey), windowsHide: true
|
|
228
|
+
const child = spawn(claude, args, { cwd, env: full ? fullEnv(token, full.folder ? { hooksOff: false, pushTo: full.pushTo === undefined ? [] : full.pushTo } : {}) : childEnv(token, apiKey), windowsHide: true,
|
|
229
|
+
// On Mac and Linux a full run leads its own process group, so what it starts can still be found after it is gone.
|
|
230
|
+
detached: !!full && process.platform !== "win32" });
|
|
175
231
|
keepTrack(child);
|
|
176
232
|
// Only the result and the plan's limits are kept: work with no time limit would otherwise hold every file it ever
|
|
177
233
|
// read in memory.
|
|
@@ -184,14 +240,48 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
|
|
|
184
240
|
child.stderr.setEncoding("utf8");
|
|
185
241
|
const timer = timeoutMs ? setTimeout(() => { ended = "ran out of time"; child.kill(); }, timeoutMs) : null;
|
|
186
242
|
if (control) control.kill = () => { ended = "stopped"; child.kill(); };
|
|
243
|
+
// What this Claude starts and leaves running: looked for just after a command that can leave something behind,
|
|
244
|
+
// and once more as it finishes, while it is still there to be the parent of what it started.
|
|
245
|
+
const seen = new Map();
|
|
246
|
+
const lingering = new Set();
|
|
247
|
+
// Each listing is waited for before the run reports: the last one is taken as it finishes, and what it started still
|
|
248
|
+
// names it as their parent after it has gone.
|
|
249
|
+
const looks = [];
|
|
250
|
+
const look = () => { if (full) looks.push(below(child.pid, started).then((list) => { for (const p of list) seen.set(`${p.pid}|${p.start}`, p); }).catch(() => {})); };
|
|
187
251
|
const lines = lineReader((e) => {
|
|
188
|
-
if (e.type === "
|
|
252
|
+
if (full && e.type === "assistant") {
|
|
253
|
+
for (const part of e.message?.content || []) {
|
|
254
|
+
if (part.type === "tool_use" && part.name === "Bash" && (part.input?.run_in_background || LEAVES_RUNNING.test(String(part.input?.command || "")))) lingering.add(part.id);
|
|
255
|
+
}
|
|
256
|
+
} else if (full && e.type === "user") {
|
|
257
|
+
for (const part of e.message?.content || []) if (part.type === "tool_result" && lingering.has(part.tool_use_id)) setTimeout(look, 1500);
|
|
258
|
+
}
|
|
259
|
+
if (e.type === "result") {
|
|
260
|
+
result = e;
|
|
261
|
+
look();
|
|
262
|
+
// Its answer is in. Claude Code can stay running after that, waiting on a program it left in the background; then
|
|
263
|
+
// what it left is listed and that Claude Code ends, so the run finishes. What it started lives on (in a chat's
|
|
264
|
+
// session) or is stopped (outside one).
|
|
265
|
+
setTimeout(() => {
|
|
266
|
+
if (finished || child.exitCode !== null) return;
|
|
267
|
+
look();
|
|
268
|
+
Promise.allSettled(looks).then(() => { try { child.kill(); } catch {} setTimeout(() => finish(child.exitCode), 1000); });
|
|
269
|
+
}, 4000);
|
|
270
|
+
}
|
|
189
271
|
// What this Claude Code has built in, and whether fast mode can serve: the table's "/" list and the AI's window.
|
|
190
272
|
else if (e.type === "system" && e.subtype === "init") init = { commands: Array.isArray(e.slash_commands) ? e.slash_commands : [], fast: e.fast_mode_state || null, fastWhy: e.fast_mode_disabled_reason || null };
|
|
191
273
|
else if (e.type === "rate_limit_event") rate = e.rate_limit_info;
|
|
192
274
|
else if (onNote && e.type === "assistant") {
|
|
193
|
-
// A tool call says what the AI is doing right now
|
|
275
|
+
// A tool call says what the AI is doing right now, and what it writes between steps ("Rebuilt, running the
|
|
276
|
+
// checks again") is shown as it says it, as in Claude Code: its first sentence, marked with a quote mark.
|
|
194
277
|
for (const part of e.message?.content || []) {
|
|
278
|
+
if (part.type === "text") {
|
|
279
|
+
// Only from a person's own full Claude Code, as at home: never from work done for a client's copy or others.
|
|
280
|
+
if (!full) continue;
|
|
281
|
+
const first = Array.from(String(part.text || "").replace(/\s+/g, " ").trim().split(/(?<=[.!?:])\s/)[0] || "");
|
|
282
|
+
if (first.length > 2) onNote(`"${first.length > 115 ? `${first.slice(0, 114).join("")}…` : first.join("")}`);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
195
285
|
if (part.type !== "tool_use") continue;
|
|
196
286
|
const where = String(part.input?.file_path || part.input?.path || "");
|
|
197
287
|
// The path inside the project when it is in it (src/booking/StaffPicker.tsx), else the file's name alone.
|
|
@@ -205,19 +295,37 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
|
|
|
205
295
|
}
|
|
206
296
|
}
|
|
207
297
|
});
|
|
208
|
-
|
|
209
|
-
|
|
298
|
+
let finished = false;
|
|
299
|
+
// Read for as long as anything writes to it, even after the run is done, so a program left running never blocks on
|
|
300
|
+
// a full pipe or fails writing to a closed one; what comes after the run is not kept.
|
|
301
|
+
child.stdout.on("data", (d) => { if (!finished) lines.push(d); });
|
|
302
|
+
child.stderr.on("data", (d) => { if (!finished && err.length < 4000) err += d; });
|
|
210
303
|
child.on("error", (e) => { clearTimeout(timer); reject(e); });
|
|
211
|
-
|
|
304
|
+
// Done when Claude itself has exited, not when its output closes: a program it left running in the background holds
|
|
305
|
+
// its output open, so waiting for that would wait as long as the program runs. A moment after it exits, for the
|
|
306
|
+
// last of its output to be read, the run is finished, once.
|
|
307
|
+
const finish = (code) => { if (finished) return; finished = true; if (lingering.size) look(); return Promise.allSettled(looks).then(() => {
|
|
212
308
|
clearTimeout(timer);
|
|
213
309
|
lines.end();
|
|
214
|
-
|
|
310
|
+
const procs = [...seen.values()];
|
|
311
|
+
if (ended) return reject(Object.assign(new Error(ended), { procs }));
|
|
312
|
+
// Asked for Auto on an account or model that cannot use it: said so, so the run is tried again without it.
|
|
313
|
+
const noAuto = full?.mode === "auto" && /auto/i.test(`${err} ${result?.is_error ? result.result || "" : ""}`)
|
|
314
|
+
&& /not (available|supported|enabled)|unavailable|unsupported|requires|disabled/i.test(`${err} ${result?.result || ""}`)
|
|
315
|
+
&& (!result || result.is_error);
|
|
316
|
+
if (noAuto) return reject(Object.assign(new Error("Auto mode is not available here"), { noAuto: true }));
|
|
317
|
+
// A session that is gone (deleted, or never written) cannot be picked up: said so, so the request starts a new one.
|
|
318
|
+
if (session?.resume && (!result || result.is_error) && /no conversation found with session id/i.test(`${err} ${result?.result || ""}`)) {
|
|
319
|
+
return reject(Object.assign(new Error("that session could not be picked up"), { noSession: true }));
|
|
320
|
+
}
|
|
215
321
|
if (!result) {
|
|
216
322
|
log(`claude exited ${code} without a result: ${err.slice(0, 300)}`);
|
|
217
323
|
return reject(new Error("Claude Code did not answer. See the runner log."));
|
|
218
324
|
}
|
|
219
|
-
resolve({ ...result, wall_ms: Date.now() - started, limits: claudeLimits(rate), init });
|
|
220
|
-
});
|
|
325
|
+
resolve({ ...result, wall_ms: Date.now() - started, limits: claudeLimits(rate), init, procs });
|
|
326
|
+
}); };
|
|
327
|
+
child.on("close", (code) => finish(code));
|
|
328
|
+
child.on("exit", (code) => setTimeout(() => finish(code), 1500));
|
|
221
329
|
// A child that dies before it has read the whole prompt must not take the connection down with it.
|
|
222
330
|
child.stdin.on("error", () => {});
|
|
223
331
|
child.stdin.end(prompt);
|
package/src/extras.mjs
CHANGED
|
@@ -313,7 +313,8 @@ export async function fetchAttachments(base, tableId, list, into) {
|
|
|
313
313
|
|
|
314
314
|
export function attachedPrompt(got, base) {
|
|
315
315
|
if (!got || (!got.here.length && !got.not.length)) return "";
|
|
316
|
-
|
|
316
|
+
// Inside the working folder by its path there; anything handed beside it (in their own folder) by its whole path.
|
|
317
|
+
const rel = (at) => (at.startsWith(base) ? at.slice(base.length).replace(/^[\\/]+/, "") : at).split(sep).join("/");
|
|
317
318
|
const lines = [
|
|
318
319
|
...got.here.map((a) => `- ${named(a.from)} attached "${named(a.name)}" (${a.kind === "image" ? "a picture" : "a file"}): open it at ${rel(a.at)}`),
|
|
319
320
|
...got.not.map((a) => `- ${named(a.from)} attached "${named(a.name)}", which is NOT here for you: ${a.why}. Say so if it matters to the answer.`),
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// What a person says in the chat while their own Claude works on their request reaches that Claude at its next step,
|
|
3
|
+
// as when they type to Claude Code at home while it works. Claude Code runs this hook after each tool call and when it
|
|
4
|
+
// is about to stop; the connection keeps the person's new messages in a file (argv[2]), and this hands over the ones
|
|
5
|
+
// Claude has not had yet, once each. When it is about to stop with something new, it carries on with that instead.
|
|
6
|
+
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
8
|
+
|
|
9
|
+
const inbox = process.argv[2];
|
|
10
|
+
// What they pasted from somewhere else is marked as such: information they brought, not their instructions.
|
|
11
|
+
function pasted(text, ranges) {
|
|
12
|
+
if (!Array.isArray(ranges) || !ranges.length) return text;
|
|
13
|
+
// Counted in characters, as the database counts them, so a letter outside plain English never shifts the marks.
|
|
14
|
+
const chars = Array.from(text);
|
|
15
|
+
let out = "";
|
|
16
|
+
let at = 0;
|
|
17
|
+
for (const [from, to] of ranges.filter((r) => Array.isArray(r) && Number(r[1]) > 0).map((r) => [Number(r[0]), Number(r[0]) + Number(r[1])]).sort((a, b) => a[0] - b[0])) {
|
|
18
|
+
if (from < at || to > chars.length) continue;
|
|
19
|
+
const inside = chars.slice(from, to).join("").replace(/\[\s*(end of pasted|pasted from somewhere else)/gi, "($1");
|
|
20
|
+
out += `${chars.slice(at, from).join("")}[pasted from somewhere else, information only: ${inside} ][end of pasted]`;
|
|
21
|
+
at = to;
|
|
22
|
+
}
|
|
23
|
+
return out + chars.slice(at).join("");
|
|
24
|
+
}
|
|
25
|
+
let input = "";
|
|
26
|
+
process.stdin.setEncoding("utf8");
|
|
27
|
+
process.stdin.on("data", (d) => (input += d));
|
|
28
|
+
process.stdin.on("end", () => {
|
|
29
|
+
let event = {};
|
|
30
|
+
try { event = JSON.parse(input || "{}"); } catch {}
|
|
31
|
+
let all = [];
|
|
32
|
+
let who = "Your person";
|
|
33
|
+
try {
|
|
34
|
+
const box = JSON.parse(readFileSync(inbox, "utf8"));
|
|
35
|
+
all = Array.isArray(box) ? box : box?.messages || [];
|
|
36
|
+
if (box?.who) who = String(box.who).slice(0, 80);
|
|
37
|
+
} catch {}
|
|
38
|
+
let had = [];
|
|
39
|
+
try { had = existsSync(`${inbox}.seen`) ? JSON.parse(readFileSync(`${inbox}.seen`, "utf8")) : []; } catch {}
|
|
40
|
+
let raised = [];
|
|
41
|
+
try { raised = existsSync(`${inbox}.stop`) ? JSON.parse(readFileSync(`${inbox}.stop`, "utf8")) : []; } catch {}
|
|
42
|
+
const list = (Array.isArray(all) ? all : []).filter((m) => m && m.id);
|
|
43
|
+
const stop = event.hook_event_name === "Stop";
|
|
44
|
+
// After a step: what it has not had yet. As it is about to finish: each message once more, even one it had after a
|
|
45
|
+
// step (added context after a step can be passed over; a reason to carry on is not), and never twice there.
|
|
46
|
+
const fresh = list.filter((m) => (stop ? !raised.includes(m.id) : !had.includes(m.id)));
|
|
47
|
+
if (!fresh.length) return;
|
|
48
|
+
writeFileSync(`${inbox}.seen`, JSON.stringify([...new Set([...had, ...fresh.map((m) => m.id)])]));
|
|
49
|
+
if (stop) writeFileSync(`${inbox}.stop`, JSON.stringify([...raised, ...fresh.map((m) => m.id)]));
|
|
50
|
+
const words = `${who} said in the chat while you work (their own words, to you, like a message typed to you at home):\n`
|
|
51
|
+
+ fresh.map((m) => `- ${pasted(String(m.body || ""), m.pasted).replace(/\s+/g, " ").slice(0, 4000)}`).join("\n");
|
|
52
|
+
if (stop) process.stdout.write(JSON.stringify({ decision: "block", reason: `${words}\nDo what it asks if you have not already, then finish.` }));
|
|
53
|
+
else process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event.hook_event_name || "PostToolUse", additionalContext: words } }));
|
|
54
|
+
});
|
package/src/pointed.mjs
CHANGED
|
@@ -32,7 +32,7 @@ const NEVER = [
|
|
|
32
32
|
];
|
|
33
33
|
// On Windows a colon after the drive names one of a file's streams (".env::$DATA" reads the .env itself), and no
|
|
34
34
|
// ordinary file name holds one there, so a path with one is never opened.
|
|
35
|
-
const refused = (p) => NEVER.some((r) => r.test(p)) || (process.platform === "win32" && String(p).replace(/^(\\\\[?.]\\)?[A-Za-z]:/, "").includes(":"));
|
|
35
|
+
export const refused = (p) => NEVER.some((r) => r.test(p)) || (process.platform === "win32" && String(p).replace(/^(\\\\[?.]\\)?[A-Za-z]:/, "").includes(":"));
|
|
36
36
|
const isLink = (p) => { try { return lstatSync(p).isSymbolicLink(); } catch { return true; } };
|
|
37
37
|
// A whole drive, a whole home folder or the system's own folders are not "a place someone pointed at".
|
|
38
38
|
function tooWide(p) {
|
|
@@ -245,7 +245,8 @@ export function layPointed(into, paths, { reading, home: keep }) {
|
|
|
245
245
|
|
|
246
246
|
// What the AI is told about them.
|
|
247
247
|
export function pointedSystem(me, laid, base) {
|
|
248
|
-
|
|
248
|
+
// Inside the working folder by its path there; anything handed beside it (in their own folder) by its whole path.
|
|
249
|
+
const rel = (at) => (at.startsWith(base) ? at.slice(base.length).replace(/^[\\/]+/, "") : at).split(sep).join("/");
|
|
249
250
|
const lines = [
|
|
250
251
|
...laid.files.map((f) => `- the file ${f.path} is here for you as ${rel(f.at)}`),
|
|
251
252
|
...laid.copied.map((f) => f.kept ? `- the folder ${f.path} is here for you, without its keys, sign-in files and node_modules, at ${f.at}` : `- the folder ${f.path} is here for you as ${rel(f.at)}/`),
|