longtable 0.1.35 → 0.1.38

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 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, resolve } from "node:path";
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
- folder: /^(https?:|git@|ssh:)/.test(repo || "") ? null : resolve(repo || process.cwd()),
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.35",
3
+ "version": "0.1.38",
4
4
  "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
5
  "homepage": "https://longtable.chat",
6
6
  "repository": {
@@ -2,31 +2,37 @@
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. An answer that does
6
- // not come in 10 minutes is a no.
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 { dirname } from "node:path";
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
- const WAIT_MS = Number(process.env.LT_WAIT_MS || 10 * 60 * 1000);
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
24
28
  // input. Nothing is ever cut short: a request too long to show in full is refused instead (null).
25
29
  export const SHOW_MAX = 2000;
30
+ // The tools that run a command: Bash, and on Windows Claude Code's PowerShell. Each is shown, explained and remembered alike.
31
+ export const SHELLS = ["Bash", "PowerShell"];
26
32
  export function describe(tool, input) {
27
33
  const i = input && typeof input === "object" ? input : {};
28
34
  let text = "";
29
- if (tool === "Bash") {
35
+ if (SHELLS.includes(tool)) {
30
36
  // The command, and anything else it asks for that changes what it may do: never hidden behind the command.
31
37
  text = String(i.command || "");
32
38
  if (i.dangerouslyDisableSandbox) text += "\n(outside the sandbox)";
@@ -36,6 +42,18 @@ export function describe(tool, input) {
36
42
  return text.length > SHOW_MAX ? null : text;
37
43
  }
38
44
 
45
+ // Why it is wanted, in one plain line, so a person who reads no commands can still answer: what Claude Code wrote for
46
+ // the command, or the file it would change.
47
+ export function whyOf(tool, input) {
48
+ const i = input && typeof input === "object" ? input : {};
49
+ // Only a command's own description: another tool's "description" field is what it would write, not why.
50
+ const said = SHELLS.includes(tool) && typeof i.description === "string" ? i.description.replace(/\s+/g, " ").trim() : "";
51
+ if (said) return said.slice(0, 1000);
52
+ const file = String(i.file_path || i.notebook_path || "").split(/[\\/]/).pop();
53
+ if (["Edit", "Write", "MultiEdit", "NotebookEdit"].includes(tool) && file) return `Change ${file}`;
54
+ return null;
55
+ }
56
+
39
57
  // The rule an "always allow" answer adds: one command, exactly as it was asked for, and nothing broader. Never a
40
58
  // whole tool, and never a command Claude Code could read as a pattern or that chains other commands.
41
59
  const PLAIN = /^[^*()\r\n;&|`$<>]{1,500}$/;
@@ -43,7 +61,7 @@ export function ruleFor(tool, input) {
43
61
  const command = String(input?.command || "").trim();
44
62
  // Not for a command that asks to leave the sandbox or keep running: those are asked about every time.
45
63
  if (input?.dangerouslyDisableSandbox || input?.run_in_background) return null;
46
- return tool === "Bash" && PLAIN.test(command) ? `Bash(${command})` : null;
64
+ return SHELLS.includes(tool) && PLAIN.test(command) ? `${tool}(${command})` : null;
47
65
  }
48
66
 
49
67
  // The rules kept on this computer, checked every time they are read: anything that is not one plain command is
@@ -51,7 +69,7 @@ export function ruleFor(tool, input) {
51
69
  export function alwaysRules(file) {
52
70
  try {
53
71
  const list = JSON.parse(readFileSync(file, "utf8"));
54
- return Array.isArray(list) ? list.filter((r) => typeof r === "string" && /^Bash\(.+\)$/.test(r) && PLAIN.test(r.slice(5, -1))) : [];
72
+ return Array.isArray(list) ? list.filter((r) => typeof r === "string" && /^(Bash|PowerShell)\(.+\)$/.test(r) && PLAIN.test(r.slice(r.indexOf("(") + 1, -1))) : [];
55
73
  } catch { return []; }
56
74
  }
57
75
 
@@ -70,14 +88,18 @@ async function decide(tool, input) {
70
88
  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
89
  let id;
72
90
  try {
73
- id = await rpc("runner_ask_approval", { key, tool, summary });
91
+ id = await rpc("runner_ask_approval", { key, tool, summary, why: whyOf(tool, input) });
74
92
  } catch (e) {
75
93
  return { behavior: "deny", message: `Longtable could not ask the person (${e.message}), so this was not done.` };
76
94
  }
77
- for (const end = Date.now() + WAIT_MS; Date.now() < end;) {
95
+ for (const end = WAIT_MS ? Date.now() + WAIT_MS : Infinity; Date.now() < end;) {
78
96
  await sleep(POLL_MS);
79
97
  let r;
80
- try { r = await rpc("runner_approval", { key, a: id }); } catch { continue; }
98
+ try { r = await rpc("runner_approval", { key, a: id }); } catch (e) {
99
+ // The job ended and its key with it: nobody will answer now.
100
+ if (/not for a running job|no such request/i.test(e.message)) break;
101
+ continue;
102
+ }
81
103
  if (r?.status === "allowed") {
82
104
  if (r.always) remember(ruleFor(tool, input));
83
105
  return { behavior: "allow", updatedInput: input };
@@ -85,7 +107,64 @@ async function decide(tool, input) {
85
107
  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
108
  if (r?.status === "expired") break;
87
109
  }
88
- return { behavior: "deny", message: "Nobody answered this in Longtable in time, so it was not done. Say what you would have done, and the person can ask again." };
110
+ 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." };
111
+ }
112
+
113
+ // A question with choices for the person, as Claude Code's own question tool asks at home: a card in Longtable with a
114
+ // button for each choice and room for their own words. It waits for them as long as the job runs.
115
+ 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.";
116
+ async function askPerson(question, options) {
117
+ const opts = (Array.isArray(options) ? options : []).map((o) => ({ label: String(o?.label ?? "").slice(0, 400), about: String(o?.description ?? o?.about ?? "").slice(0, 1000) }));
118
+ let id;
119
+ try { id = await rpc("runner_ask_question", { key, question: String(question ?? "").slice(0, 4000), options: opts }); }
120
+ catch (e) { return `Longtable could not ask the person (${e.message}). Carry on with the safest choice and say which you took.`; }
121
+ for (const end = WAIT_MS ? Date.now() + WAIT_MS : Infinity; Date.now() < end;) {
122
+ await sleep(POLL_MS);
123
+ let r;
124
+ try { r = await rpc("runner_approval", { key, a: id }); } catch (e) {
125
+ if (/not for a running job|no such request/i.test(e.message)) break;
126
+ continue;
127
+ }
128
+ if (r?.status === "allowed" && r.answer) return `They answered: ${r.answer}`;
129
+ if (r?.status && r.status !== "waiting") break;
130
+ }
131
+ return "This work ended before the person answered. Say what you would have needed to know.";
132
+ }
133
+
134
+ // A file or picture for its answer, as Claude in the app can send one: uploaded into the table's attachments (only into
135
+ // this job's own place) and shown on the answer. Never a secret file Longtable would refuse to open, never a folder,
136
+ // never over 15 MB.
137
+ 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.";
138
+ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml",
139
+ ".pdf": "application/pdf", ".csv": "text/csv", ".txt": "text/plain", ".md": "text/markdown", ".json": "application/json", ".html": "text/html",
140
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
141
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".zip": "application/zip" };
142
+ async function shareFile(path) {
143
+ const where = resolve(String(path || ""));
144
+ let st;
145
+ try { st = statSync(where); } catch { return `There is no file at ${path}.`; }
146
+ if (!st.isFile()) return "That is not a file: share one file at a time.";
147
+ if (refused(where) || refused(realpathSync(where))) return "That file is one Longtable never shares (keys, passwords, sign-ins). Say so instead.";
148
+ // Only from the folder it works in (never the person's own notes laid beside it) or a screenshot it took: anything
149
+ // else on the computer is never put in front of the team by a tool that does not ask.
150
+ const real = realpathSync(where);
151
+ const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
152
+ const roots = String(process.env.LT_SHARE_ROOTS || "").split(delimiter).filter(Boolean).map((r) => { try { return realpathSync(r); } catch { return resolve(r); } });
153
+ if (!roots.some((r) => fold(real).startsWith(fold(r.endsWith(sep) ? r : r + sep))) || /[\\/]\.longtable-yours([\\/]|$)/.test(real)) {
154
+ 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.";
155
+ }
156
+ 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.";
157
+ const name = basename(where).replace(/[^\w.\- ()]/g, "_").slice(0, 120) || "file";
158
+ let prefix;
159
+ try { prefix = await rpc("runner_upload_slot", { key }); } catch (e) { return `Longtable could not take the file (${e.message}). Say where it is instead.`; }
160
+ const object = `${prefix}${randomUUID()}-${name}`;
161
+ const res = await fetch(`${process.env.LT_SUPABASE_URL}/storage/v1/object/attachments/${object.split("/").map(encodeURIComponent).join("/")}`, {
162
+ method: "POST", headers: { apikey: process.env.LT_KEY, "Content-Type": MIME[extname(name).toLowerCase()] || "application/octet-stream", "x-upsert": "false" },
163
+ body: readFileSync(where),
164
+ }).catch((e) => ({ ok: false, status: e.message }));
165
+ if (!res.ok) return `The file could not be uploaded (${res.status}). Say where it is instead.`;
166
+ try { await rpc("runner_attach", { key, path: object, name }); } catch (e) { return `The file was not kept (${e.message}). Say where it is instead.`; }
167
+ return `${name} is on your answer: the team sees it there.`;
89
168
  }
90
169
 
91
170
  // The MCP side: JSON-RPC over stdin and stdout, one message a line.
@@ -93,6 +172,8 @@ function serve() {
93
172
  let buf = "";
94
173
  const send = (m) => process.stdout.write(JSON.stringify(m) + NL);
95
174
  process.stdin.setEncoding("utf8");
175
+ // Claude Code gone (its pipe closed): nobody is left to answer for, so it stops instead of polling on.
176
+ process.stdin.on("end", () => process.exit(0));
96
177
  process.stdin.on("data", (d) => {
97
178
  buf += d;
98
179
  let at;
@@ -107,7 +188,22 @@ function serve() {
107
188
  reply({ protocolVersion: m.params?.protocolVersion || "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "longtable", version: "1" } });
108
189
  } else if (m.method === "tools/list") {
109
190
  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"] } }] });
191
+ inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } },
192
+ { name: "ask", description: ASK_ABOUT,
193
+ inputSchema: { type: "object", properties: { question: { type: "string", description: "The question, in plain words." },
194
+ 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"] } } },
195
+ required: ["question", "options"] } },
196
+ { name: "share_file", description: SHARE_ABOUT,
197
+ inputSchema: { type: "object", properties: { path: { type: "string", description: "The file's path." } }, required: ["path"] } }] });
198
+ } else if (m.method === "tools/call" && m.params?.name === "share_file") {
199
+ shareFile(m.params?.arguments?.path).then(
200
+ (text) => reply({ content: [{ type: "text", text }] }),
201
+ () => reply({ content: [{ type: "text", text: "The file could not be shared. Say where it is instead." }] }));
202
+ } else if (m.method === "tools/call" && m.params?.name === "ask") {
203
+ const a = m.params?.arguments || {};
204
+ askPerson(a.question, a.options).then(
205
+ (text) => reply({ content: [{ type: "text", text }] }),
206
+ () => reply({ content: [{ type: "text", text: "Longtable could not ask the person. Carry on with the safest choice and say which you took." }] }));
111
207
  } else if (m.method === "tools/call") {
112
208
  const a = m.params?.arguments || {};
113
209
  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
- export function fullEnv(token) {
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
- // Git itself refuses every push from the commands this Claude runs, however the command is written (git -C, -c,
80
- // an alias, a script): every push address is rewritten to one no git can reach. Only the connection pushes, and
81
- // only the task's longtable/ branch. Git hooks point at an empty folder, so a hook from the branch never runs.
82
- const noHooks = join(home, "no-hooks");
83
- try { mkdirSync(noHooks, { recursive: true }); } catch {}
84
- env.GIT_CONFIG_COUNT = "2";
85
- env.GIT_CONFIG_KEY_0 = "url.longtable-no-push://refused/.pushInsteadOf";
86
- env.GIT_CONFIG_VALUE_0 = "";
87
- env.GIT_CONFIG_KEY_1 = "core.hooksPath";
88
- env.GIT_CONFIG_VALUE_1 = noHooks;
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
- export function ask({ 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 }) {
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
- // A full run can wait on the person's answers, so a short job gets longer than a locked one.
139
- if (full && !edit) timeoutMs = Math.max(timeoutMs, 15 * 60 * 1000);
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 ? (long ? "10000" : "200") : "60"]
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
- args.push("--setting-sources", "user");
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 plan mode the plan is its answer here: there is no plan to approve, so it never asks to leave plan mode.
157
- args.push("--disallowedTools", "Bash(git push:*)", "Bash(git push)", ...(edit ? [] : ["Edit", "Write", "NotebookEdit"]), ...(full.mode === "plan" ? ["ExitPlanMode"] : []));
158
- if (full.allow?.length) args.push("--allowedTools", ...full.allow);
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
- const settings = { ...(full?.project || {}), ...(fast ? { fastMode: true } : {}),
168
- ...(full && process.platform !== "win32" ? { sandbox: { ...(full?.project?.sandbox || {}), enabled: true, autoAllowBashIfSandboxed: false } } : {}) };
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 === "result") result = e;
252
+ if (full && e.type === "assistant") {
253
+ for (const part of e.message?.content || []) {
254
+ if (part.type === "tool_use" && (part.name === "Bash" || part.name === "PowerShell") && (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.
@@ -199,25 +289,43 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
199
289
  const file = inside && inside.length <= 80 ? inside : where.split(/[/\\]/).pop();
200
290
  if (/[/\\]\.longtable-yours([/\\]|$)/.test(where) || /^\.longtable-yours([/\\]|$)/.test(where)) onNote("reading what it knows");
201
291
  // A command is named by its program only: the rest of a command line can hold a secret.
202
- else if (part.name === "Bash") onNote(`running ${String(part.input?.command || "").trim().split(/\s+/)[0].replace(/[^A-Za-z0-9._-]/g, "").slice(0, 30) || "a command"}`);
292
+ else if (part.name === "Bash" || part.name === "PowerShell") onNote(`running ${String(part.input?.command || "").trim().split(/\s+/)[0].replace(/[^A-Za-z0-9._-]/g, "").slice(0, 30) || "a command"}`);
203
293
  else onNote(part.name === "Edit" || part.name === "Write" ? `editing ${file}` : part.name === "Read" ? `reading ${file}`
204
294
  : (part.name === "Grep" || part.name === "Glob") && part.input?.pattern ? `searching for ${String(part.input.pattern).replace(/\s+/g, " ").slice(0, 40)}` : "searching the code");
205
295
  }
206
296
  }
207
297
  });
208
- child.stdout.on("data", (d) => lines.push(d));
209
- child.stderr.on("data", (d) => { if (err.length < 4000) err += d; });
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
- child.on("close", (code) => {
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
- if (ended) return reject(new Error(ended));
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
- const rel = (at) => at.slice(base.length).replace(/^[\\/]+/, "").split(sep).join("/");
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
- const rel = (at) => at.slice(base.length).replace(/^[\\/]+/, "").split(sep).join("/");
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)}/`),