longtable 0.1.15 → 0.1.17

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
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": {
package/src/claude.mjs CHANGED
@@ -91,9 +91,8 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
91
91
  return new Promise((resolve, reject) => {
92
92
  const started = Date.now();
93
93
  const child = spawn(claude, args, { cwd, env: childEnv(token, apiKey), windowsHide: true });
94
- // Output arrives a line at a time, each line one event. Only the result and the plan's limits are kept: work
95
- // with no time limit would otherwise hold every file it ever read in memory.
96
- let rest = "";
94
+ // Only the result and the plan's limits are kept: work with no time limit would otherwise hold every file it ever
95
+ // read in memory.
97
96
  let err = "";
98
97
  let ended = "";
99
98
  let result = null;
@@ -102,10 +101,7 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
102
101
  child.stderr.setEncoding("utf8");
103
102
  const timer = timeoutMs ? setTimeout(() => { ended = "ran out of time"; child.kill(); }, timeoutMs) : null;
104
103
  if (control) control.kill = () => { ended = "stopped"; child.kill(); };
105
- const take = (line) => {
106
- if (!line.trim()) return;
107
- let e;
108
- try { e = JSON.parse(line); } catch { return; }
104
+ const lines = lineReader((e) => {
109
105
  if (e.type === "result") result = e;
110
106
  else if (e.type === "rate_limit_event") rate = e.rate_limit_info;
111
107
  else if (onNote && e.type === "assistant") {
@@ -116,21 +112,13 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
116
112
  onNote(part.name === "Edit" || part.name === "Write" ? `editing ${file}` : part.name === "Read" ? `reading ${file}` : "searching the code");
117
113
  }
118
114
  }
119
- };
120
- child.stdout.on("data", (d) => {
121
- rest += d;
122
- let at;
123
- while ((at = rest.indexOf(String.fromCharCode(10))) !== -1) {
124
- const line = rest.slice(0, at);
125
- rest = rest.slice(at + 1);
126
- try { take(line); } catch {}
127
- }
128
115
  });
116
+ child.stdout.on("data", (d) => lines.push(d));
129
117
  child.stderr.on("data", (d) => { if (err.length < 4000) err += d; });
130
118
  child.on("error", (e) => { clearTimeout(timer); reject(e); });
131
119
  child.on("close", (code) => {
132
120
  clearTimeout(timer);
133
- try { take(rest); } catch {}
121
+ lines.end();
134
122
  if (ended) return reject(new Error(ended));
135
123
  if (!result) {
136
124
  log(`claude exited ${code} without a result: ${err.slice(0, 300)}`);
@@ -144,6 +132,30 @@ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,
144
132
  });
145
133
  }
146
134
 
135
+ // Output arrives a line at a time, each line one event: every whole line that is JSON goes to onEvent, blank and
136
+ // other lines are passed over, and a last line with no end is read when the output ends.
137
+ export function lineReader(onEvent) {
138
+ let rest = "";
139
+ const take = (line) => {
140
+ if (!line.trim()) return;
141
+ let e;
142
+ try { e = JSON.parse(line); } catch { return; }
143
+ onEvent(e);
144
+ };
145
+ return {
146
+ push(d) {
147
+ rest += d;
148
+ let at;
149
+ while ((at = rest.indexOf(String.fromCharCode(10))) !== -1) {
150
+ const line = rest.slice(0, at);
151
+ rest = rest.slice(at + 1);
152
+ try { take(line); } catch {}
153
+ }
154
+ },
155
+ end() { try { take(rest); } catch {} rest = ""; },
156
+ };
157
+ }
158
+
147
159
  // The plan's limits as Longtable shows them: each window's use in percent and when it resets.
148
160
  export function claudeLimits(rate) {
149
161
  if (!rate) return null;
package/src/extras.mjs CHANGED
@@ -11,7 +11,7 @@ const codexHome = () => process.env.LONGTABLE_CODEX_HOME || process.env.CODEX_HO
11
11
  const folderOf = (seat) => seat.folder || (String(seat.source || "").startsWith("file:///") ? seat.source.slice(8) : null);
12
12
  // A file's name and a person's name come from the table like any other words (a client names their own attachment),
13
13
  // so neither may close a fence, and a name stays on its own one line. The same markers as inert() in run.mjs.
14
- const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)\b|\b(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
14
+ const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)|(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
15
15
  const named = (t) => inert(t).replace(/\s+/g, " ").replace(/"/g, "'").trim().slice(0, 200);
16
16
 
17
17
  // The top of a command or skill file: "---", lines of "key: value", "---".
@@ -37,8 +37,49 @@ function walk(dir, depth = 3) {
37
37
  return out;
38
38
  }
39
39
 
40
- // Every command and skill this person's AI has on this computer, for this project and for themselves. The project's
41
- // own win over the person's when two share a name.
40
+ // The commands every Claude Code has built in that mean something at a table, in Longtable's own words. Claude
41
+ // Code's own versions are not files, and run as they are they reach for a shell and for git, which no AI at the table
42
+ // has: tried under the table's lock, one answered nothing and one never came back. These do the same jobs with what an
43
+ // AI here does have, which is reading the code and, when it is doing work, changing files. The ones that only steer
44
+ // Claude Code's own window (clear, compact, model, config and the like) have nothing to steer here and are left out.
45
+ const HERE = "You cannot run commands, tests or git here, so read the code itself and say plainly what you could not confirm by running it.";
46
+ const BUILTIN = {
47
+ "review": { about: "Read code for bugs and say what is wrong, most serious first", body: `Review code for bugs. What to review: $ARGUMENTS
48
+ If nothing is named, review what the most recent work in this conversation changed. Read every file you report on; do not review from memory. Report only what is really wrong, most serious first, each with the file and line, what goes wrong, one concrete case that triggers it, and the fix. Do not change any file unless you were asked to fix what you find. ${HERE}` },
49
+ "code-review": { about: "Read code for bugs and say what is wrong, most serious first", same: "review" },
50
+ "security-review": { about: "Look for ways the code could be misused or leak something", body: `Review code for security problems. What to review: $ARGUMENTS
51
+ If nothing is named, review what the most recent work in this conversation changed, and the code it touches. Look for: input trusted without a check, missing permission checks, secrets in code or logs, injection (SQL, shell, HTML), unsafe file paths, requests to addresses a person controls, and data one person can read of another's. Report only real, reachable problems, most serious first, each with the file and line, how it would be used against the product, and the fix. Do not change any file unless you were asked to fix what you find. ${HERE}` },
52
+ "simplify": { about: "Make code simpler without changing what it does", body: `Clean up code without changing what it does. What to clean up: $ARGUMENTS
53
+ If nothing is named, clean up what the most recent work in this conversation changed. Look for code that repeats something the project already has, more steps or layers than the job needs, and needless work. When you can change files here, make the changes and say what you changed; when you cannot, list each change with its file and line. Leave behaviour, names other code relies on, and anything unrelated alone. ${HERE}` },
54
+ "init": { about: "Write or improve the project's CLAUDE.md", body: `Write a CLAUDE.md for this project, or improve the one it has, for the next AI that works here. $ARGUMENTS
55
+ Cover how to build, run and test it (and how to run one test), and the parts of its design that take reading several files to understand. Leave out generic advice and anything obvious from one file. Take in what a README or other instruction files already say. When you can change files here, write the file; when you cannot, give its full text in your answer. ${HERE}` },
56
+ "debug": { about: "Find the cause of a problem by reading the code", body: `Find the cause of this problem: $ARGUMENTS
57
+ If no problem is described, take the one being talked about in this conversation. Follow it through the code from where it shows to where it starts. Say the cause, the lines that prove it, and the fix. Keep what you know apart from what you suspect. Do not change any file unless you were asked to fix it. ${HERE}` },
58
+ "verify": { about: "Check that a change does what it claims", body: `Check that a change does what it is meant to. What to check: $ARGUMENTS
59
+ If nothing is named, check the most recent work in this conversation. Read the change and what calls it, follow each path through it including the awkward ones (nothing given, too much given, the wrong person asking, the same thing twice), and say for each claim whether the code bears it out. ${HERE}` },
60
+ };
61
+
62
+ // The plugins this person has for this project or for themselves, switched on in their settings: each one's folder.
63
+ function plugins(folder) {
64
+ const out = [];
65
+ const same = (a, b) => !!a && !!b && String(a).replace(/[\\/]+$/, "").toLowerCase().split("\\").join("/") === String(b).replace(/[\\/]+$/, "").toLowerCase().split("\\").join("/");
66
+ const on = new Set();
67
+ for (const file of [join(claudeHome(), "settings.json"), folder && join(folder, ".claude", "settings.json"), folder && join(folder, ".claude", "settings.local.json")].filter(Boolean)) {
68
+ try { for (const [key, value] of Object.entries(JSON.parse(readFileSync(file, "utf8")).enabledPlugins || {})) { if (value === true) on.add(key); else on.delete(key); } } catch {}
69
+ }
70
+ let installed = {};
71
+ try { installed = JSON.parse(readFileSync(join(claudeHome(), "plugins", "installed_plugins.json"), "utf8")).plugins || {}; } catch {}
72
+ for (const [key, entries] of Object.entries(installed)) {
73
+ if (!on.has(key)) continue;
74
+ const hit = (Array.isArray(entries) ? entries : []).find((e) => e && typeof e.installPath === "string" && (e.scope === "user" || same(e.projectPath, folder)));
75
+ if (hit) out.push({ name: key.split("@")[0], dir: hit.installPath });
76
+ }
77
+ return out;
78
+ }
79
+
80
+ // Every command and skill this person's AI has on this computer, for this project and for themselves, then the ones
81
+ // their plugins add, then the built-in ones. The project's own win over the person's when two share a name, and
82
+ // anything of theirs wins over a built-in one.
42
83
  export function scanCommands(seat) {
43
84
  const found = new Map();
44
85
  const add = (name, about, kind, file) => {
@@ -67,6 +108,26 @@ export function scanCommands(seat) {
67
108
  } catch {}
68
109
  }
69
110
  }
111
+ // A plugin's commands and skills carry its name in front, the way Claude Code itself shows them.
112
+ for (const plugin of plugins(folder)) {
113
+ const dir = join(plugin.dir, "commands");
114
+ for (const file of walk(dir)) {
115
+ try {
116
+ const f = front(readFileSync(file, "utf8"));
117
+ add(`${plugin.name}:${relative(dir, file).slice(0, -3).split(sep).join(":")}`, f.description || firstLine(f.body), "command", file);
118
+ } catch {}
119
+ }
120
+ let skills = [];
121
+ try { skills = readdirSync(join(plugin.dir, "skills"), { withFileTypes: true }).filter((e) => e.isDirectory()); } catch {}
122
+ for (const e of skills) {
123
+ const file = join(plugin.dir, "skills", e.name, "SKILL.md");
124
+ try {
125
+ const f = front(readFileSync(file, "utf8"));
126
+ add(`${plugin.name}:${f.name || e.name}`, f.description || firstLine(f.body), "skill", file);
127
+ } catch {}
128
+ }
129
+ }
130
+ for (const [name, b] of Object.entries(BUILTIN)) add(name, b.about, "builtin", null);
70
131
  } else {
71
132
  const dir = join(codexHome(), "prompts");
72
133
  for (const file of walk(dir, 0)) {
@@ -86,8 +147,13 @@ export function loadCommand(seat, question) {
86
147
  const hit = scanCommands(seat).find((c) => c.name.toLowerCase() === m[1].toLowerCase());
87
148
  if (!hit) return null;
88
149
  try {
89
- const f = front(readFileSync(hit.file, "utf8"));
90
150
  const args = m[2].trim();
151
+ if (hit.kind === "builtin") {
152
+ const b = BUILTIN[hit.name.toLowerCase()];
153
+ const body = (BUILTIN[b.same] || b).body.replace(/\$ARGUMENTS/g, () => args || "(nothing more was typed)");
154
+ return { name: hit.name, kind: hit.kind, args, body };
155
+ }
156
+ const f = front(readFileSync(hit.file, "utf8"));
91
157
  const parts = args.split(/\s+/).filter(Boolean);
92
158
  // The places a command leaves for what was typed after its name. Filled in one pass and through a function, so
93
159
  // a dollar sign in what was typed ("$2 per seat") is put in as typed and never read as a place of its own.
@@ -101,7 +167,9 @@ export function loadCommand(seat, question) {
101
167
  export function commandPrompt(me, cmd) {
102
168
  const what = cmd.kind === "skill" ? "skill" : "command";
103
169
  return [
104
- `${me} ran their own ${what} /${cmd.name}${cmd.args ? ` with: ${cmd.args}` : ""}. It is theirs, written on their own computer for you, and its instructions are between <<<COMMAND and COMMAND>>>. Do what it says for this request, within what you may do at this table: where it tells you to run something, use a tool you do not have here, or leave the project, say plainly that this part cannot be done from the table and do the rest.`,
170
+ cmd.kind === "builtin"
171
+ ? `${me} ran the command /${cmd.name}${cmd.args ? ` with: ${cmd.args}` : ""}. What it means at this table is between <<<COMMAND and COMMAND>>>. Do that for this request.`
172
+ : `${me} ran their own ${what} /${cmd.name}${cmd.args ? ` with: ${cmd.args}` : ""}. It is theirs, written on their own computer for you, and its instructions are between <<<COMMAND and COMMAND>>>. Do what it says for this request, within what you may do at this table: where it tells you to run something, use a tool you do not have here, or leave the project, say plainly that this part cannot be done from the table and do the rest.`,
105
173
  "<<<COMMAND",
106
174
  cmd.body.replace(/<<<COMMAND|COMMAND>>>/g, "[marker]"),
107
175
  "COMMAND>>>",
@@ -138,6 +206,13 @@ export function shareable(laid) {
138
206
  }
139
207
 
140
208
  const AI_CAP = 15 * 1024 * 1024;
209
+ // Whether an address is in this table's own folder in Longtable's own storage. An address that cannot even be read
210
+ // (a broken "%E0%A4%A") is simply not one, and must not throw: that took the whole job down with it.
211
+ export function attachmentAddress(base, tableId, url) {
212
+ let path;
213
+ try { path = decodeURIComponent(url.pathname); } catch { return false; }
214
+ return url.origin === new URL(base).origin && path.includes(`/storage/v1/object/sign/attachments/${tableId}/`);
215
+ }
141
216
  // Brings what was attached in the chat to where the AI can read it. Only ever from this table's own folder in
142
217
  // Longtable's storage: an address pointing anywhere else is left alone.
143
218
  export async function fetchAttachments(base, tableId, list, into) {
@@ -151,7 +226,7 @@ export async function fetchAttachments(base, tableId, list, into) {
151
226
  if (Number(a.size) > AI_CAP) { out.not.push({ ...label, why: "it is larger than 15 MB" }); continue; }
152
227
  let url;
153
228
  try { url = new URL(a.url, base); } catch { out.not.push({ ...label, why: "its address is not readable" }); continue; }
154
- if (url.origin !== new URL(base).origin || !decodeURIComponent(url.pathname).includes(`/storage/v1/object/sign/attachments/${tableId}/`)) { out.not.push({ ...label, why: "its address is not this table's" }); continue; }
229
+ if (!attachmentAddress(base, tableId, url)) { out.not.push({ ...label, why: "its address is not this table's" }); continue; }
155
230
  try {
156
231
  const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
157
232
  if (!res.ok) { out.not.push({ ...label, why: res.status === 400 || res.status === 403 ? "its link has run out" : "it could not be fetched" }); continue; }
package/src/pointed.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // C:\Users\me\notes\plan.md". Their AI may read them, the way it would if they had said so at their own keyboard.
3
3
  // Nobody else's message can do this, and some places are never opened whoever asks.
4
4
 
5
- import { cpSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
5
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
7
  import { basename, isAbsolute, join, parse, resolve, sep } from "node:path";
8
8
 
@@ -29,7 +29,10 @@ const NEVER = [
29
29
  /[\\/]Library[\\/](Keychains|Application Support[\\/](Google|BraveSoftware|Firefox))([\\/]|$)/i,
30
30
  /^[\\/](etc[\\/](shadow|sudoers)|proc|sys|dev)([\\/]|$)/i,
31
31
  ];
32
- const refused = (p) => NEVER.some((r) => r.test(p));
32
+ // On Windows a colon after the drive names one of a file's streams (".env::$DATA" reads the .env itself), and no
33
+ // ordinary file name holds one there, so a path with one is never opened.
34
+ const refused = (p) => NEVER.some((r) => r.test(p)) || (process.platform === "win32" && String(p).replace(/^(\\\\[?.]\\)?[A-Za-z]:/, "").includes(":"));
35
+ const isLink = (p) => { try { return lstatSync(p).isSymbolicLink(); } catch { return true; } };
33
36
  // A whole drive, a whole home folder or the system's own folders are not "a place someone pointed at".
34
37
  function tooWide(p) {
35
38
  const { root } = parse(p);
@@ -58,7 +61,9 @@ export function pointedPaths(text) {
58
61
  const p = tidy(raw);
59
62
  if (!p || !isAbsolute(p) || found.length >= 5) return;
60
63
  let real;
61
- try { real = realpathSync(p); } catch { return; }
64
+ // The system's own answer, which also turns an old short name ("ENV~1") into the long one it stands for, so the
65
+ // check below sees ".env" and not a name that only means it.
66
+ try { real = realpathSync.native(p); } catch { return; }
62
67
  if (seen.has(real.toLowerCase())) return;
63
68
  seen.add(real.toLowerCase());
64
69
  if (refused(p) || refused(real)) { found.push({ path: p, refused: "that place is never opened from the table" }); return; }
@@ -107,7 +112,7 @@ function weigh(dir) {
107
112
  if (files > DIR_FILES || bytes > DIR_BYTES) return;
108
113
  if (e.name === "node_modules" || e.name === ".git") continue;
109
114
  const p = join(d, e.name);
110
- if (refused(p)) continue;
115
+ if (refused(p) || e.isSymbolicLink()) continue;
111
116
  if (e.isDirectory()) walk(p);
112
117
  else if (e.isFile()) { files++; try { bytes += statSync(p).size; } catch {} }
113
118
  }
@@ -129,6 +134,8 @@ function whyNotInPlace(dir) {
129
134
  if (e.name === "node_modules" || e.name === ".git") continue;
130
135
  const p = join(d, e.name);
131
136
  if (refused(p)) return "secret";
137
+ // A link (or a Windows junction) leads out of the folder, to a place nobody looked through.
138
+ if (e.isSymbolicLink()) return "link";
132
139
  if (++looked > 20000) return "many";
133
140
  const why = e.isDirectory() ? walk(p) : "";
134
141
  if (why) return why;
@@ -140,6 +147,7 @@ function whyNotInPlace(dir) {
140
147
  const NOT_IN_PLACE = {
141
148
  secret: "the folder has a key or a sign-in file inside it and is too big to bring along without them; point at a folder or a file inside it",
142
149
  many: "the folder is too big to look through for keys and sign-in files before opening it; point at a folder or a file inside it",
150
+ link: "the folder has a link inside it to somewhere else and is too big to bring along without it; point at a folder or a file inside it",
143
151
  unreadable: "part of the folder could not be looked through for keys and sign-in files, and it is too big to bring along as a copy; point at a folder or a file inside it",
144
152
  };
145
153
 
@@ -173,7 +181,7 @@ export function layPointed(into, paths, { reading }) {
173
181
  const at = join(dest, `${++n}-${basename(p.real)}`);
174
182
  try {
175
183
  mkdirSync(dest, { recursive: true });
176
- cpSync(p.real, at, { recursive: true, filter: (src) => !refused(src) && !/[\\/](node_modules|\.git)([\\/]|$)/.test(src) });
184
+ cpSync(p.real, at, { recursive: true, filter: (src) => src === p.real || !isLink(src) && !refused(src) && !/[\\/](node_modules|\.git)([\\/]|$)/.test(src) });
177
185
  out.copied.push({ path: p.path, at });
178
186
  } catch { out.skipped.push({ path: p.path, why: "it could not be read" }); }
179
187
  }
package/src/repo.mjs CHANGED
@@ -42,7 +42,7 @@ export function resolveSource(repo) {
42
42
  // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
43
43
  // repository can never point the AI at a file outside the copy.
44
44
  export function freshCopy(tableId, source) {
45
- const dir = join(home, "copies", tableId);
45
+ const dir = join(home, "copies", safeTable(tableId));
46
46
  if (!source) {
47
47
  mkdirSync(dir, { recursive: true });
48
48
  return { dir, read: "no code connected" };
@@ -66,14 +66,14 @@ export function freshCopy(tableId, source) {
66
66
  }
67
67
 
68
68
  export function copyIsClean(tableId) {
69
- const dir = join(home, "copies", tableId);
69
+ const dir = join(home, "copies", safeTable(tableId));
70
70
  if (!existsSync(join(dir, ".git"))) return true;
71
71
  return git(["-C", dir, "status", "--porcelain"]) === "";
72
72
  }
73
73
 
74
74
  // Work the team asked for happens in a second folder that holds the files and nothing else: no .git inside it, so
75
75
  // nothing the AI writes there can change what git itself runs. Git reaches it from outside, with its own index.
76
- const places = (tableId, name = "work") => ({ G: join(home, "copies", tableId, ".git"), W: join(home, name, tableId), I: join(home, name, `${tableId}.index`) });
76
+ const places = (tableId, name = "work") => ({ G: join(home, "copies", safeTable(tableId), ".git"), W: join(home, name, safeTable(tableId)), I: join(home, name, `${safeTable(tableId)}.index`) });
77
77
  // File names come back as they are. Left to itself git writes a name with letters outside plain English in quotes
78
78
  // with numbers for the letters, and then the name is neither a file that can be read nor one a rule can match.
79
79
  const wgit = (p, args, env = {}) => execFileSync("git", ["-c", "core.quotePath=false", "--git-dir", p.G, "--work-tree", p.W, ...args],
@@ -86,15 +86,22 @@ export function safeBranch(b) {
86
86
  return b;
87
87
  }
88
88
 
89
+ // A table's id becomes a folder name on this computer, so it must be one: a server that is not the real one could
90
+ // otherwise name "../../somewhere" and have that folder written to or wiped.
91
+ export function safeTable(t) {
92
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(t))) throw new Error("the table named itself in a way this connection will not use as a folder");
93
+ return t;
94
+ }
95
+
89
96
  export const workBranch = (chatName) => "longtable/" + (String(chatName || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "work");
90
97
 
91
98
  // A folder laid beside the code for the AI to read, and never to be committed: the repository's own exclude list says so.
92
99
  export function neverCommit(tableId, name) {
93
- const file = join(home, "copies", tableId, ".git", "info", "exclude");
100
+ const file = join(home, "copies", safeTable(tableId), ".git", "info", "exclude");
94
101
  // Git does not always make the info folder (a person's own template may leave it out). If the list cannot be
95
102
  // written this throws and the job stops: better no answer than their own notes pushed to the team's branch.
96
103
  try {
97
- mkdirSync(join(home, "copies", tableId, ".git", "info"), { recursive: true });
104
+ mkdirSync(join(home, "copies", safeTable(tableId), ".git", "info"), { recursive: true });
98
105
  const now = existsSync(file) ? readFileSync(file, "utf8") : "";
99
106
  if (!now.split(/\r?\n/).includes(`${name}/`)) writeFileSync(file, `${now}${now.endsWith(String.fromCharCode(10)) || !now ? "" : String.fromCharCode(10)}${name}/${String.fromCharCode(10)}`);
100
107
  } catch (e) {
@@ -179,7 +186,7 @@ export function changedSoFar(tableId, work) {
179
186
  // default branch's files, so whatever was tried in it before is gone from what the hosting puts up.
180
187
  export function openBranch(tableId, branch, fresh = false) {
181
188
  safeBranch(branch);
182
- const G = join(home, "copies", tableId, ".git");
189
+ const G = join(home, "copies", safeTable(tableId), ".git");
183
190
  try {
184
191
  git(["--git-dir", G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
185
192
  git(["--git-dir", G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
@@ -206,7 +213,7 @@ export function openBranch(tableId, branch, fresh = false) {
206
213
  export function patchOf(tableId, branch, commit) {
207
214
  safeBranch(branch);
208
215
  if (!/^[0-9a-f]{7,40}$/.test(String(commit || ""))) return "";
209
- const G = join(home, "copies", tableId, ".git");
216
+ const G = join(home, "copies", safeTable(tableId), ".git");
210
217
  try {
211
218
  // The commit itself, by its full name; a host that will not serve one commit gets the branch asked for instead.
212
219
  try { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "2", "origin", commit]); }
@@ -255,6 +262,9 @@ export function landWork(tableId, work, branch, message, who) {
255
262
  }
256
263
  // A name with no Latin letters in it leaves nothing to name the branch by, so it is just "part".
257
264
  const side = `${branch}-${String(who || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20).replace(/^-+|-+$/g, "") || "part"}`;
265
+ // A tripwire, written to this computer's log and nothing more: a side branch from a long branch name can be longer
266
+ // than the connection's own rule for branches, and a later job handed it could not write to it.
267
+ try { safeBranch(side); } catch { try { log("tripwire: a side branch came out longer than the connection's own branch rule"); } catch {} }
258
268
  if (push(commit, side)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch: side, apart: true };
259
269
  // Nothing could be pushed. Keep the commit findable on this computer, so the work is not lost with the folder.
260
270
  try { git(["--git-dir", p.G, "update-ref", `refs/longtable/${branch.slice(10)}`, commit]); } catch {}
package/src/run.mjs CHANGED
@@ -12,7 +12,7 @@ import { client } from "./api.mjs";
12
12
  import { ask, findClaude } from "./claude.mjs";
13
13
  import { askCodex, codexLimits, findCodex } from "./codex.mjs";
14
14
  import { packCode } from "./pack.mjs";
15
- import { changedSoFar, freshCopy, landWork, neverCommit, openBranch, openWork, patchOf, workBranch } from "./repo.mjs";
15
+ import { changedSoFar, freshCopy, landWork, neverCommit, openBranch, openWork, patchOf, safeTable, workBranch } from "./repo.mjs";
16
16
  import { hideSecrets, home, loadSecret, log, readConfig } from "./store.mjs";
17
17
 
18
18
  const SOURCES = {
@@ -107,11 +107,18 @@ export const KINDS = {
107
107
  };
108
108
 
109
109
  const NL = String.fromCharCode(10);
110
- // Text from the table, a file or another AI is fenced so it reads as information. Nothing inside may close a fence.
111
- const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)\b|\b(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
110
+ // Text from the table, a file or another AI is fenced so it reads as information. Nothing inside may close a fence,
111
+ // and a marker glued to a letter ("xTABLE>>>") is still a marker to whoever reads it, so no word edge is asked for.
112
+ export const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)|(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
113
+ // A tripwire: something that should never happen, written to this computer's log in one fixed sentence (never a
114
+ // path, a name or anything from a file) and nothing more. It never stops or changes the job. sweep-notes/rules.md
115
+ // lists each one.
116
+ export function trip(what) { try { log(`tripwire: ${what}`); } catch {} }
117
+ const MARKER = /<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)|(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/;
118
+ const fenced = (inner) => { if (MARKER.test(inner)) trip("a fence marker was still in the table's text after cleaning"); return inner; };
112
119
  // The conversation as it is, newest kept: every message whole, back to wherever a generous size runs out. There is
113
120
  // no count of messages: a long talk between people is all there.
114
- function recent(history, room) {
121
+ export function recent(history, room) {
115
122
  const out = [];
116
123
  let used = 0;
117
124
  for (const m of [...(history || [])].reverse()) {
@@ -145,7 +152,7 @@ const fence = (job) => {
145
152
  parts.push("The back room so far, oldest first:" + NL + (job.views?.length ? job.views.map((v) => `${v.name}'s AI (${label(v)}): ${v.view}`).join(NL) : "Nothing yet."));
146
153
  } else if (job.kind === "combine") parts.push("Back-room views:\n" + (job.views?.length ? job.views.map((v) => `${v.name}'s AI (${v.meta?.confidence ?? "unsure"}): ${v.view}`).join("\n") : "None came in."));
147
154
  if (job.question) parts.push(`Question from ${job.asker}:\n${job.question}`);
148
- return ["<<<TABLE", inert(parts.join("\n\n")), "TABLE>>>"].join("\n");
155
+ return ["<<<TABLE", fenced(inert(parts.join("\n\n"))), "TABLE>>>"].join("\n");
149
156
  };
150
157
 
151
158
  // What a client's AI sees: only that client's own requests, what they were told, and their chat with it.
@@ -159,7 +166,7 @@ const fenceClient = (job) => {
159
166
  + job.work.map((w) => `- "${w.title}": ${w.status === "done" ? "finished" : "under way"}`).join("\n"));
160
167
  if (job.history?.length) parts.push("Your chat with them so far:\n" + job.history.map((l) => `${l.who === "client" ? job.me : "You"}: ${l.body}`).join("\n"));
161
168
  parts.push(`Their latest message:\n${job.question}`);
162
- return ["<<<TABLE", inert(parts.join("\n\n")), "TABLE>>>"].join("\n");
169
+ return ["<<<TABLE", fenced(inert(parts.join("\n\n"))), "TABLE>>>"].join("\n");
163
170
  };
164
171
 
165
172
  // What the table's answer is told when it may also do the work.
@@ -222,8 +229,8 @@ export function listenPrompt(job) {
222
229
  // The conversation as far back as a generous size reaches, never a fixed number of messages.
223
230
  const before = recent(job.history, 48000).map((m) => `${who(m)}: ${short(m.body, 3000)}`).join(NL);
224
231
  const tasks = (job.tasks || []).map((t, i) => `T${i + 1}: "${t.title}" (${t.status === "working" ? "being worked on now" : t.status}, asked by ${t.asked_by || "someone"}, in ${t.chat})`).join(NL);
225
- return ["<<<TABLE", inert([facts(job), "", `Work the AIs have taken on lately:${NL}${tasks || "(none)"}`, "", before || "(nothing earlier)", `${job.asker}: ${short(job.question, 6000)}`,
226
- ...(job.command ? ["", `That message runs ${job.asker}'s own AI command /${job.command.name}${job.command.about ? `, which is for: ${job.command.about}` : ""}. Running a command is asking for it to be done: choose look, or work when the command is about changing the project. Never silent, never reply.`] : [])].join(NL)), "TABLE>>>"].join(NL);
232
+ return ["<<<TABLE", fenced(inert([facts(job), "", `Work the AIs have taken on lately:${NL}${tasks || "(none)"}`, "", before || "(nothing earlier)", `${job.asker}: ${short(job.question, 6000)}`,
233
+ ...(job.command ? ["", `That message runs ${job.asker}'s own AI command /${job.command.name}${job.command.about ? `, which is for: ${job.command.about}` : ""}. Running a command is asking for it to be done: choose look, or work when the command is about changing the project. Never silent, never reply.`] : [])].join(NL))), "TABLE>>>"].join(NL);
227
234
  }
228
235
  export function listenSystem(job) {
229
236
  return [
@@ -269,8 +276,11 @@ export function knows(seat) {
269
276
  // The end of their own conversation about this project comes first: it is what the two of them were just doing.
270
277
  let talk = "";
271
278
  if (folder) { try { talk = recentSession(folder, 16000); } catch {} }
272
- const rest = parts.join(NL + NL).slice(0, 34000);
273
- return (talk ? `## The latest of your own conversation with them about this project (newest last)${NL}${talk}${NL}${NL}` : "") + rest;
279
+ // The rest has what room the conversation leaves, so the whole stays within 36,000 characters.
280
+ const head = talk ? `## The latest of your own conversation with them about this project (newest last)${NL}${talk}${NL}${NL}` : "";
281
+ const out = head + parts.join(NL + NL).slice(0, Math.max(0, 36000 - head.length));
282
+ if (out.length > 36000) trip("what a person's Claude knows came out over its 36,000 characters");
283
+ return out;
274
284
  }
275
285
 
276
286
  // Everything this person's Claude knows on their own computer, whole, laid in a folder beside the code for it to
@@ -306,6 +316,8 @@ export function recentSession(folder, room = 90000) {
306
316
  for (let i = lines.length - 1; i >= 0 && used < room; i--) {
307
317
  let e;
308
318
  try { e = JSON.parse(lines[i]); } catch { continue; }
319
+ // A line that is valid JSON but not a turn ("null", left by a crash) is skipped, not allowed to stop the rest.
320
+ if (!e || typeof e !== "object") continue;
309
321
  if (e.isSidechain || (e.type !== "user" && e.type !== "assistant")) continue;
310
322
  const words = said(e.message?.content).trim();
311
323
  // Reminders the app adds to a message are not something either of them said.
@@ -354,7 +366,7 @@ export function layYours(seat, dir) {
354
366
 
355
367
  // Each person's AI keeps its own short notes on that person's computer. They are what makes one person's AI differ
356
368
  // from another's on the same model: what it has learned here, in its own words. They never leave this computer.
357
- const mindFile = (tableId) => join(home, "minds", `${tableId}.md`);
369
+ const mindFile = (tableId) => join(home, "minds", `${safeTable(tableId)}.md`);
358
370
  export function mind(tableId) {
359
371
  try { return readFileSync(mindFile(tableId), "utf8").trim(); } catch { return ""; }
360
372
  }
@@ -374,7 +386,8 @@ export function cleanSources(dir, sources) {
374
386
  let p = s.trim().replace(/^\.\//, "");
375
387
  if (isAbsolute(p)) p = relative(dir, p);
376
388
  p = normalize(p).replace(/\\/g, "/");
377
- if (p.startsWith("..") || isAbsolute(p) || p.startsWith(YOURS)) continue;
389
+ // On Windows and macOS ".LONGTABLE-YOURS" is the same folder, so the person's own is matched in any letter case.
390
+ if (p.startsWith("..") || isAbsolute(p) || p.toLowerCase().startsWith(YOURS)) continue;
378
391
  if (existsSync(join(dir, p)) && !out.includes(p)) out.push(p);
379
392
  }
380
393
  return out.slice(0, 6);
@@ -616,7 +629,8 @@ function planText(job, s) {
616
629
 
617
630
  // Why a job failed, as the table may see it: the last line of the error, with no sign-in from a repository address
618
631
  // and nothing shaped like a key.
619
- const plain = (e) => hideSecrets(String(e?.message || e).split(/\r?\n/).filter(Boolean).pop() || "it failed").replace(/\/\/[^/@\s]+@/g, "//").slice(0, 300);
632
+ // The sign-in runs to the LAST @ before the host: a name or a password may hold an @ of its own ("a@b:p@ss@host").
633
+ export const plain = (e) => hideSecrets(String(e?.message || e).split(/\r?\n/).filter(Boolean).pop() || "it failed").replace(/\/\/[^/\s]*@/g, "//").slice(0, 300);
620
634
 
621
635
  // The listener's one small request. Its only output is what to do next; the table does the rest.
622
636
  async function workListen(rpc, seat, engines, job) {
@@ -823,10 +837,12 @@ export function runningConnection() {
823
837
  }
824
838
 
825
839
  // The names of this person's own commands and skills, and a line on each, so "/" at the table can offer them. Never
826
- // what is in them: that stays on this computer and is read only when they run one.
840
+ // what is in them: that stays on this computer and is read only when they run one. A line is the first line of a
841
+ // file the person wrote, which can hold a key, so it is cleaned before it leaves.
842
+ export const toldCommands = (list) => list.map(({ name, about, kind }) => ({ name, about: hideSecrets(about), kind }));
827
843
  async function tellCommands(rpc, seat) {
828
844
  try {
829
- const list = scanCommands(seat).map(({ name, about, kind }) => ({ name, about, kind }));
845
+ const list = toldCommands(scanCommands(seat));
830
846
  const key = JSON.stringify(list);
831
847
  if (seat.told === key) return;
832
848
  await rpc("runner_commands", { token: seat.token, list });