@santori/station 0.9.9 → 0.9.11

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/dist/codex.js CHANGED
@@ -109,7 +109,7 @@ export function sandboxedThread(home, thread, env = process.env) {
109
109
  return null;
110
110
  let originator = "";
111
111
  try {
112
- const first = JSON.parse(tailFirstLine(rollout));
112
+ const first = JSON.parse(firstLine(rollout));
113
113
  originator = first.payload?.originator ?? "";
114
114
  }
115
115
  catch {
@@ -118,11 +118,14 @@ export function sandboxedThread(home, thread, env = process.env) {
118
118
  const host = /desktop|app/i.test(originator) ? "app" : /exec/i.test(originator) ? "exec" : "terminal";
119
119
  return { thread, pid: 0, procStart: null, executable: env.CODEX_EXECUTABLE ?? "codex", host };
120
120
  }
121
- /** A file's first line, read without the rest of it. */
122
- function tailFirstLine(path) {
121
+ /** A rollout's first line (its session_meta), read without the rest of
122
+ * a plain file. It carries Codex's instructions, so it can run long. */
123
+ function firstLine(path) {
124
+ if (path.endsWith(".zst"))
125
+ return unzst(path).toString("utf8").split("\n")[0];
123
126
  const fd = openSync(path, "r");
124
127
  try {
125
- const buf = Buffer.alloc(64 * 1024);
128
+ const buf = Buffer.alloc(1024 * 1024);
126
129
  const read = readSync(fd, buf, 0, buf.length, 0);
127
130
  return buf.subarray(0, read).toString("utf8").split("\n")[0];
128
131
  }
@@ -130,6 +133,42 @@ function tailFirstLine(path) {
130
133
  closeSync(fd);
131
134
  }
132
135
  }
136
+ /** The folder the thread runs in, from its rollout's session_meta, while
137
+ * that folder is there. */
138
+ export function threadFolder(home, thread) {
139
+ const rollout = rolloutPath(home, thread);
140
+ return rollout ? rolloutFolder(rollout) : null;
141
+ }
142
+ function rolloutFolder(rollout) {
143
+ try {
144
+ const cwd = JSON.parse(firstLine(rollout)).payload?.cwd;
145
+ return typeof cwd === "string" && existsSync(cwd) ? cwd : null;
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ }
151
+ /** The folder Codex worked in last on this computer: the thread written to
152
+ * last (a resumed older chat writes to its old rollout), while its folder
153
+ * is there. Null when Codex has no thread here. */
154
+ export function lastFolder(home) {
155
+ const written = (path) => {
156
+ try {
157
+ return statSync(path).mtimeMs;
158
+ }
159
+ catch {
160
+ return 0;
161
+ }
162
+ };
163
+ const newest = [...rollouts(home)].map((path) => ({ path, at: written(path) })).sort((a, b) => b.at - a.at);
164
+ // Past these, a person with many deleted folders gets none.
165
+ for (const { path } of newest.slice(0, 50)) {
166
+ const cwd = rolloutFolder(path);
167
+ if (cwd)
168
+ return cwd;
169
+ }
170
+ return null;
171
+ }
133
172
  /** The Codex thread this process runs inside: `CODEX_THREAD_ID`, vouched for
134
173
  * by the nearest `codex` above it holding the thread's lock. */
135
174
  export function callingThread(home, env = process.env, from = process.ppid, ps = systemPs, holders = systemHolders) {
@@ -139,19 +178,31 @@ export function callingThread(home, env = process.env, from = process.ppid, ps =
139
178
  let pid = from;
140
179
  for (let hops = 0; hops < 64 && pid > 1; hops++) {
141
180
  const executable = ps(pid, "comm");
142
- // Codex's own sandbox hides the processes above a command it runs (ps
143
- // and lsof are refused there). The thread is then vouched for by its own
144
- // files instead: its rollout, and its writer lock while it is loaded.
145
181
  if (!executable)
146
- return env.CODEX_SANDBOX ? sandboxedThread(home, thread, env) : null;
182
+ break;
147
183
  if (basename(executable) === "codex")
148
184
  return describe(home, thread, pid, ps, holders);
149
185
  const parent = Number(ps(pid, "ppid"));
150
186
  if (!Number.isInteger(parent) || parent <= 1 || parent === pid)
151
- return null;
187
+ break;
152
188
  pid = parent;
153
189
  }
154
- return null;
190
+ // Codex's own sandbox hides the Codex above a command it runs: on macOS
191
+ // ps and lsof are refused, and on Linux the command runs in a process
192
+ // namespace of its own, whose first process is the sandbox's and not the
193
+ // thread's Codex. The thread is then vouched for by its own files: its
194
+ // rollout, and its writer lock while it is loaded.
195
+ return inCodexSandbox(env, ps) ? sandboxedThread(home, thread, env) : null;
196
+ }
197
+ /** Whether this process runs in Codex's sandbox. Codex sets CODEX_SANDBOX
198
+ * on macOS, and CODEX_SANDBOX_NETWORK_DISABLED wherever the sandbox has no
199
+ * network (Linux sets only this one). A Linux sandbox with network sets
200
+ * neither, but its first process is Codex's. */
201
+ function inCodexSandbox(env = process.env, ps = systemPs) {
202
+ if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED)
203
+ return true;
204
+ const first = ps(1, "comm");
205
+ return !!first && basename(first) === "codex";
155
206
  }
156
207
  /** Why `callingThread` found nothing, step by step, for a process Codex
157
208
  * started (it has `CODEX_THREAD_ID`); null when it is not one. */
@@ -200,18 +251,27 @@ export function liveThread(home, thread, ps = systemPs, holders = systemHolders)
200
251
  * newest day first. Codex compresses older rollouts in place to
201
252
  * `.jsonl.zst`; the plain file wins when both are there. */
202
253
  export function rolloutPath(home, thread) {
254
+ for (const names of rolloutDays(home)) {
255
+ const found = names.find((file) => file.endsWith(`-${thread}.jsonl`)) ?? names.find((file) => file.endsWith(`-${thread}.jsonl.zst`));
256
+ if (found)
257
+ return found;
258
+ }
259
+ return null;
260
+ }
261
+ /** Each day's rollouts, newest day first and newest first within it. */
262
+ function* rolloutDays(home) {
203
263
  const root = join(home, "sessions");
204
264
  const down = (dir) => (existsSync(dir) ? readdirSync(dir).sort().reverse() : []);
205
265
  for (const year of down(root))
206
266
  for (const month of down(join(root, year)))
207
267
  for (const day of down(join(root, year, month))) {
208
268
  const dir = join(root, year, month, day);
209
- const names = down(dir).filter((file) => file.startsWith("rollout-"));
210
- const name = names.find((file) => file.endsWith(`-${thread}.jsonl`)) ?? names.find((file) => file.endsWith(`-${thread}.jsonl.zst`));
211
- if (name)
212
- return join(dir, name);
269
+ yield down(dir).filter((file) => file.startsWith("rollout-")).map((file) => join(dir, file));
213
270
  }
214
- return null;
271
+ }
272
+ function* rollouts(home) {
273
+ for (const names of rolloutDays(home))
274
+ yield* names;
215
275
  }
216
276
  const TAIL_BYTES = 4 * 1024 * 1024;
217
277
  /** Whether the rollout's last turn is still open: a `task_started` with no
@@ -319,7 +379,11 @@ export function queued(code, stdout) {
319
379
  const QUEUE_TIMEOUT_MS = 20_000;
320
380
  function queueMessage(home, session, text) {
321
381
  return new Promise((resolve) => {
322
- execFile(session.executable, queueArgs(session.thread, text), { timeout: QUEUE_TIMEOUT_MS, env: { ...process.env, CODEX_HOME: home }, maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {
382
+ execFile(session.executable, queueArgs(session.thread, text),
383
+ // In the thread's own folder, where Codex reads its project config.
384
+ // Never the daemon's: that is whichever session started it, and once
385
+ // that folder is deleted Codex fails "failed to resolve config cwd".
386
+ { cwd: threadFolder(home, session.thread) ?? homedir(), timeout: QUEUE_TIMEOUT_MS, env: { ...process.env, CODEX_HOME: home }, maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {
323
387
  if (error && error.killed) {
324
388
  return resolve({ kind: "in-doubt", reason: "codex queue did not finish in time." });
325
389
  }
package/dist/commands.js CHANGED
@@ -7,21 +7,25 @@
7
7
  // A tool is offered as a command when its listing carries
8
8
  // _meta "station/cli": { command, args, stdin?, usage }. `command` is the
9
9
  // word after `station`, or two words ("board ls") for one of a group, and
10
- // `station board` alone lists the group; `args` are the inputs given in order without a
10
+ // `station board` alone lists the group; `aliases` are other words for it
11
+ // ({ "take": "task take" }: `station take 12` runs `station task take 12`);
12
+ // `args` are the inputs given in order without a
11
13
  // flag; every other input is --its-name (an input named if_rev is
12
- // --if-rev); `stdin` names the input read from stdin when it is not given,
14
+ // --if-rev; a list of objects takes each as JSON); `stdin` names the input read from stdin when it is not given,
13
15
  // and that input also takes @<path> for a file's text. What the flags are,
14
16
  // what they mean and what the command prints all come from the tool's own
15
17
  // schema and answer, so a new command or a new flag needs only a relay
16
18
  // deploy.
17
19
  import { readFileSync } from "node:fs";
20
+ import { distance } from "./args.js";
18
21
  import { files, readJson } from "./home.js";
19
22
  import { Usage } from "./usage.js";
20
23
  export function cliOf(tool) {
21
24
  const meta = tool._meta?.["station/cli"];
22
25
  if (!meta || typeof meta.command !== "string" || !/^[a-z][a-z0-9-]*( [a-z][a-z0-9-]*)?$/.test(meta.command))
23
26
  return null;
24
- return { command: meta.command, args: Array.isArray(meta.args) ? meta.args.filter((arg) => typeof arg === "string") : [], stdin: typeof meta.stdin === "string" ? meta.stdin : undefined, usage: typeof meta.usage === "string" ? meta.usage : undefined };
27
+ const aliases = Object.fromEntries(Object.entries(meta.aliases ?? {}).filter(([word, means]) => /^[a-z][a-z0-9-]*$/.test(word) && typeof means === "string"));
28
+ return { command: meta.command, args: Array.isArray(meta.args) ? meta.args.filter((arg) => typeof arg === "string") : [], stdin: typeof meta.stdin === "string" ? meta.stdin : undefined, usage: typeof meta.usage === "string" ? meta.usage : undefined, aliases };
25
29
  }
26
30
  /** The tools Station listed last, without asking it. */
27
31
  export function cachedTools(home) {
@@ -32,13 +36,44 @@ export function commandNamed(tools, command) {
32
36
  return tools.find((tool) => cliOf(tool)?.command === command) ?? null;
33
37
  }
34
38
  /** The command the words after `station` start with, two words before
35
- * one, and the words left for it. */
36
- export function commandFrom(tools, argv) {
37
- const two = argv.length > 1 ? commandNamed(tools, `${argv[0]} ${argv[1]}`) : null;
39
+ * one, and the words left for it. A first word that is another word for a
40
+ * command (`take` for "task take") is read as the words it stands for. */
41
+ export function commandFrom(tools, argv, aliased = false) {
42
+ // An action's second word as mutate spells it: `room claim_link` is "room claim-link".
43
+ const two = argv.length > 1 ? commandNamed(tools, `${argv[0]} ${argv[1].replace(/_/g, "-")}`) : null;
38
44
  if (two)
39
45
  return { tool: two, rest: argv.slice(2) };
40
46
  const one = argv.length ? commandNamed(tools, argv[0]) : null;
41
- return one ? { tool: one, rest: argv.slice(1) } : null;
47
+ if (one)
48
+ return { tool: one, rest: argv.slice(1) };
49
+ const means = aliased || !argv.length ? undefined : tools.map((tool) => cliOf(tool)?.aliases[argv[0]]).find(Boolean);
50
+ return means ? commandFrom(tools, [...means.split(" "), ...argv.slice(1)], true) : null;
51
+ }
52
+ /** The command a mistyped word most likely is, or null. Stricter than for
53
+ * a flag, since following a wrong guess runs another command (`log` must
54
+ * not suggest `logout`): the word with letters after it (`tasks`), the
55
+ * first 4 letters or more of one, or 1 letter off (2 in a word of 7 or more). */
56
+ function closestCommand(word, known) {
57
+ const starts = known.filter((one) => (one.length >= 3 && word.startsWith(one)) || (word.length >= 4 && one.startsWith(word))).sort((a, b) => b.length - a.length)[0];
58
+ if (starts)
59
+ return starts;
60
+ const near = known.map((one) => ({ one, far: distance(word, one) })).sort((a, b) => a.far - b.far)[0];
61
+ return near && near.far <= (word.length >= 7 ? 2 : 1) ? near.one : null;
62
+ }
63
+ /** The MCP tool whose shell command has another word: agents that read
64
+ * Station's MCP tools typed `station send`. */
65
+ const MCP_WORDS = { send: "say" };
66
+ /** What a word that is no command gets back: the closest real command,
67
+ * then the names only. The whole help is over 5 KB, and an agent asked
68
+ * for none of it. `own`: the CLI's own commands, as the help lists them. */
69
+ export function unknownCommand(me, word, own, tools) {
70
+ const offered = tools.flatMap((tool) => cliOf(tool)?.command ?? []);
71
+ const groups = [...new Set(offered.map((command) => command.split(" ")[0]))];
72
+ const aliases = tools.flatMap((tool) => Object.keys(cliOf(tool)?.aliases ?? {}));
73
+ const typed = word.toLowerCase().replace(/_/g, "-");
74
+ // What Station's MCP tools call it, then the second word of a command typed alone (`done` is "task done").
75
+ const near = MCP_WORDS[typed] ?? offered.find((command) => command.split(" ")[1] === typed) ?? closestCommand(typed, [...own, ...groups, ...aliases]);
76
+ return `Unknown command: ${word}.${near ? ` Did you mean ${me} ${near}?` : ""} The commands: ${[...new Set([...own, ...groups])].join(", ")}. ${me} help says what each does.`;
42
77
  }
43
78
  /** The tools whose command is one of this group: `board` for "board ls". */
44
79
  export function groupOf(tools, group) {
@@ -69,6 +104,17 @@ function scalar(word, prop) {
69
104
  return Number(word);
70
105
  return word;
71
106
  }
107
+ /** A list item that is an object, given as JSON on the command line. */
108
+ function jsonOf(word, wrong) {
109
+ try {
110
+ return JSON.parse(word);
111
+ }
112
+ catch {
113
+ throw wrong();
114
+ }
115
+ }
116
+ /** An object's names as JSON with "..." values: {"old": "...", "new": "..."}. */
117
+ const exampleOf = (prop) => `{${Object.keys(prop?.properties ?? {}).map((name) => `"${name}": "..."`).join(", ")}}`;
72
118
  /** The command as its help shows it: station ls [path] [--recursive] ... */
73
119
  export function usageLine(me, tool) {
74
120
  const cli = cliOf(tool);
@@ -99,21 +145,36 @@ export function commandHelp(me, tool) {
99
145
  const more = [
100
146
  name === "room" ? "Leave it out for the room this session has a seat in." : null,
101
147
  name === cli?.stdin ? `Or @<path> for a file's text, or leave it out and send the text on stdin.` : null,
102
- allows(prop, "array") && !allows(prop, "string") ? "Give it once for each." : null,
148
+ allows(prop, "array") && !allows(prop, "string") ? `Give it once for each${allows(prop.items, "object") && !allows(prop.items, "string") ? `, as JSON: ${exampleOf(prop.items)}` : ""}.` : null,
103
149
  allows(prop, "object") && !allows(prop, "string") ? "Give it once for each name." : null,
104
150
  ].filter(Boolean);
105
151
  lines.push(` ${label.padEnd(14)} ${[prop.description, ...more].filter(Boolean).join(" ")}`);
106
152
  }
107
153
  return lines.join("\n");
108
154
  }
109
- /** The lines `station help` adds for the commands Station defines. */
110
- export function commandLines(me, tools) {
155
+ /** The lines `station help` adds for the commands Station defines. A
156
+ * command with no usage line of its own is named under its first word
157
+ * only, on one line for all of that word's: there are 30 of them for a
158
+ * person's rooms, teams and agents, and `station team` lists a word's in
159
+ * full. `full`: every command on its own line, as that listing has them. */
160
+ export function commandLines(me, tools, full = false) {
111
161
  const offered = tools.filter((tool) => cliOf(tool));
112
162
  if (!offered.length)
113
163
  return [];
114
- const starts = offered.map((tool) => ` ${me} ${cliOf(tool).command} ${cliOf(tool).args.map((arg) => (required(tool).includes(arg) ? `<${arg}>` : `[${arg}]`)).join(" ")}`.trimEnd());
115
- const width = Math.max(...starts.map((start) => start.length)) + 2;
116
- return ["", `From Station itself (${me} <command> --help for each one's flags):`, ...offered.map((tool, index) => `${starts[index].padEnd(width)}${cliOf(tool).usage ?? tool.title ?? ""}`)];
164
+ const own = offered.filter((tool) => full || cliOf(tool).usage);
165
+ const starts = own.map((tool) => ` ${me} ${cliOf(tool).command} ${cliOf(tool).args.map((arg) => (required(tool).includes(arg) ? `<${arg}>` : `[${arg}]`)).join(" ")}`.trimEnd());
166
+ const width = Math.max(0, ...starts.map((start) => start.length)) + 2;
167
+ const rest = new Map();
168
+ for (const tool of offered.filter((one) => !own.includes(one))) {
169
+ const [first, second] = cliOf(tool).command.split(" ");
170
+ rest.set(first, [...(rest.get(first) ?? []), second ?? ""]);
171
+ }
172
+ return [
173
+ "",
174
+ `From Station itself (${me} <command> --help for each one's flags):`,
175
+ ...own.map((tool, index) => `${starts[index].padEnd(width)}${cliOf(tool).usage ?? tool.title ?? ""}`),
176
+ ...(rest.size ? [`For your person's rooms, teams and agents, when they ask (${me} <first word> lists what each does):`, ...[...rest].map(([first, seconds]) => ` ${me} ${first} ${seconds.filter(Boolean).join("|")}`.trimEnd())] : []),
177
+ ];
117
178
  }
118
179
  export const reads = {
119
180
  file: (path) => readFileSync(path, "utf8"),
@@ -147,9 +208,13 @@ export async function inputsFrom(me, tool, argv, io = reads) {
147
208
  const prop = known[name];
148
209
  let given = match[2];
149
210
  if (given === undefined) {
150
- // A yes-or-no flag stands alone; any other takes the next word.
211
+ // A yes-or-no flag stands alone; any other takes the next word. In a
212
+ // command with nothing left to give without a flag, the true or false
213
+ // after it is its value (`room invite --on false`, as agents type an
214
+ // action's input). Elsewhere that word is the next thing given
215
+ // (`board grep --ignore-case true` searches for "true").
151
216
  if (allows(prop, "boolean") && !allows(prop, "string") && !allows(prop, "number"))
152
- given = "true";
217
+ given = positional.length >= cli.args.length && (argv[i + 1] === "true" || argv[i + 1] === "false") ? argv[++i] : "true";
153
218
  else if (i + 1 < argv.length)
154
219
  given = argv[++i];
155
220
  else
@@ -165,7 +230,7 @@ export async function inputsFrom(me, tool, argv, io = reads) {
165
230
  held[key] = key in held ? [...(Array.isArray(held[key]) ? held[key] : [held[key]]), value] : value;
166
231
  }
167
232
  else if (allows(prop, "array") && !allows(prop, "string")) {
168
- (inputs[name] ??= []).push(scalar(given, prop.items));
233
+ (inputs[name] ??= []).push(allows(prop.items, "object") && !allows(prop.items, "string") ? jsonOf(given, () => wrong(`${match[1]} takes JSON, such as ${exampleOf(prop.items)}.`)) : scalar(given, prop.items));
169
234
  }
170
235
  else if (name === cli.stdin && given.startsWith("@")) {
171
236
  try {
@@ -196,7 +261,13 @@ export async function inputsFrom(me, tool, argv, io = reads) {
196
261
  throw wrong(`${cli.command} needs ${missing.map((name) => (cli.args.includes(name) ? `<${name}>` : flagOf(name))).join(" and ")}.`);
197
262
  return inputs;
198
263
  }
199
- /** What a tool answered, as a command prints it. */
264
+ /** A part only for the agent, beside the answer: a file's rev beside its text. */
265
+ const aside = (part) => part.type === "text" && Array.isArray(part.annotations?.audience) && part.annotations.audience.length === 1 && part.annotations.audience[0] === "assistant";
266
+ /** What a tool answered, as a command prints it on stdout. */
200
267
  export function answerText(result) {
201
- return (result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
268
+ return (result.content ?? []).filter((part) => !aside(part)).map((part) => (part.type === "text" ? part.text : "")).join("\n");
269
+ }
270
+ /** The lines beside the answer, as a command prints them on stderr. */
271
+ export function asideText(result) {
272
+ return (result.content ?? []).filter(aside).map((part) => (part.type === "text" ? part.text : "")).join("\n");
202
273
  }