@santori/station 0.9.10 → 0.9.12

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
@@ -137,8 +137,9 @@ function firstLine(path) {
137
137
  * that folder is there. */
138
138
  export function threadFolder(home, thread) {
139
139
  const rollout = rolloutPath(home, thread);
140
- if (!rollout)
141
- return null;
140
+ return rollout ? rolloutFolder(rollout) : null;
141
+ }
142
+ function rolloutFolder(rollout) {
142
143
  try {
143
144
  const cwd = JSON.parse(firstLine(rollout)).payload?.cwd;
144
145
  return typeof cwd === "string" && existsSync(cwd) ? cwd : null;
@@ -147,6 +148,27 @@ export function threadFolder(home, thread) {
147
148
  return null;
148
149
  }
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
+ }
150
172
  /** The Codex thread this process runs inside: `CODEX_THREAD_ID`, vouched for
151
173
  * by the nearest `codex` above it holding the thread's lock. */
152
174
  export function callingThread(home, env = process.env, from = process.ppid, ps = systemPs, holders = systemHolders) {
@@ -156,19 +178,31 @@ export function callingThread(home, env = process.env, from = process.ppid, ps =
156
178
  let pid = from;
157
179
  for (let hops = 0; hops < 64 && pid > 1; hops++) {
158
180
  const executable = ps(pid, "comm");
159
- // Codex's own sandbox hides the processes above a command it runs (ps
160
- // and lsof are refused there). The thread is then vouched for by its own
161
- // files instead: its rollout, and its writer lock while it is loaded.
162
181
  if (!executable)
163
- return env.CODEX_SANDBOX ? sandboxedThread(home, thread, env) : null;
182
+ break;
164
183
  if (basename(executable) === "codex")
165
184
  return describe(home, thread, pid, ps, holders);
166
185
  const parent = Number(ps(pid, "ppid"));
167
186
  if (!Number.isInteger(parent) || parent <= 1 || parent === pid)
168
- return null;
187
+ break;
169
188
  pid = parent;
170
189
  }
171
- 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";
172
206
  }
173
207
  /** Why `callingThread` found nothing, step by step, for a process Codex
174
208
  * started (it has `CODEX_THREAD_ID`); null when it is not one. */
@@ -217,18 +251,27 @@ export function liveThread(home, thread, ps = systemPs, holders = systemHolders)
217
251
  * newest day first. Codex compresses older rollouts in place to
218
252
  * `.jsonl.zst`; the plain file wins when both are there. */
219
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) {
220
263
  const root = join(home, "sessions");
221
264
  const down = (dir) => (existsSync(dir) ? readdirSync(dir).sort().reverse() : []);
222
265
  for (const year of down(root))
223
266
  for (const month of down(join(root, year)))
224
267
  for (const day of down(join(root, year, month))) {
225
268
  const dir = join(root, year, month, day);
226
- const names = down(dir).filter((file) => file.startsWith("rollout-"));
227
- const name = names.find((file) => file.endsWith(`-${thread}.jsonl`)) ?? names.find((file) => file.endsWith(`-${thread}.jsonl.zst`));
228
- if (name)
229
- return join(dir, name);
269
+ yield down(dir).filter((file) => file.startsWith("rollout-")).map((file) => join(dir, file));
230
270
  }
231
- return null;
271
+ }
272
+ function* rollouts(home) {
273
+ for (const names of rolloutDays(home))
274
+ yield* names;
232
275
  }
233
276
  const TAIL_BYTES = 4 * 1024 * 1024;
234
277
  /** Whether the rollout's last turn is still open: a `task_started` with no
@@ -313,6 +356,48 @@ export function threadIdle(home, thread) {
313
356
  return false;
314
357
  }
315
358
  }
359
+ export const stopDeliveryMarker = (token) => `[Station delivery: ${token}]`;
360
+ /** Codex 0.172 spills Stop reasons over 2,500 approximate tokens, at four UTF-8 bytes per token. */
361
+ export const STOP_OUTPUT_BYTES = 10_000;
362
+ /** Codex persists an accepted Stop reason as a user-role hook_prompt,
363
+ * before the turn's terminal event: `<hook_prompt hook_run_id="stop:…">`
364
+ * then the reason, ending in our marker (tests/fixtures holds a real
365
+ * Codex 0.171 turn). A veto never records that prompt. A spill preview
366
+ * adds a footer after our marker and does not count. */
367
+ export function stopDeliveryStatus(home, thread, turnId, token) {
368
+ let status = "unknown";
369
+ try {
370
+ const path = rolloutPath(home, thread);
371
+ if (!path)
372
+ return status;
373
+ const marker = stopDeliveryMarker(token) + "</hook_prompt>";
374
+ for (const line of tailLines(path)) {
375
+ if (!line.includes(token) && !line.includes(turnId))
376
+ continue;
377
+ try {
378
+ const { type, payload } = JSON.parse(line);
379
+ if (type === "response_item" && payload?.type === "message" && payload.role === "user" &&
380
+ Array.isArray(payload.content) && payload.content.some((item) => item?.type === "input_text" &&
381
+ typeof item.text === "string" && item.text.startsWith("<hook_prompt ") &&
382
+ item.text.endsWith(marker)))
383
+ return "accepted";
384
+ if (type === "event_msg" && payload?.turn_id === turnId) {
385
+ if (payload.type === "task_started")
386
+ status = "running";
387
+ if (payload.type === "task_complete" || payload.type === "turn_aborted")
388
+ status = "ended";
389
+ }
390
+ }
391
+ catch {
392
+ // The writer may still be adding the last line.
393
+ }
394
+ }
395
+ }
396
+ catch {
397
+ // The rollout may be moving or not yet visible.
398
+ }
399
+ return status;
400
+ }
316
401
  /** Codex takes text, tabs and newlines; any other control character could
317
402
  * edit or submit what it is part of. */
318
403
  export const MAX_TEXT_BYTES = 14_336;
package/dist/commands.js CHANGED
@@ -7,7 +7,9 @@
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
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,
@@ -15,13 +17,15 @@
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) {
@@ -117,14 +152,29 @@ export function commandHelp(me, tool) {
117
152
  }
118
153
  return lines.join("\n");
119
154
  }
120
- /** The lines `station help` adds for the commands Station defines. */
121
- 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) {
122
161
  const offered = tools.filter((tool) => cliOf(tool));
123
162
  if (!offered.length)
124
163
  return [];
125
- const starts = offered.map((tool) => ` ${me} ${cliOf(tool).command} ${cliOf(tool).args.map((arg) => (required(tool).includes(arg) ? `<${arg}>` : `[${arg}]`)).join(" ")}`.trimEnd());
126
- const width = Math.max(...starts.map((start) => start.length)) + 2;
127
- 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
+ ];
128
178
  }
129
179
  export const reads = {
130
180
  file: (path) => readFileSync(path, "utf8"),
@@ -138,6 +188,19 @@ export const reads = {
138
188
  },
139
189
  };
140
190
  /** The tool's inputs from the words after the command. */
191
+ /** The room a command acts in: the one given with --room, else the room
192
+ * this session has a seat in. A tool that needs a room and gets neither
193
+ * says how to get one; one that can do without (a report to Station's
194
+ * team) goes with none. */
195
+ export function roomFor(me, tool, inputs, seat, threadHint = "") {
196
+ if (!("room" in (tool.inputSchema.properties ?? {})) || inputs.room !== undefined)
197
+ return inputs.room;
198
+ if (seat)
199
+ return `${seat.relayUrl}/${seat.roomId}`;
200
+ if (!(tool.inputSchema.required ?? []).includes("room"))
201
+ return undefined;
202
+ throw new Usage(`This session has no seat in a room. Run ${me} join <room-url> first, or name the room with --room.${threadHint}`);
203
+ }
141
204
  export async function inputsFrom(me, tool, argv, io = reads) {
142
205
  const cli = cliOf(tool);
143
206
  const known = props(tool);
@@ -158,9 +221,13 @@ export async function inputsFrom(me, tool, argv, io = reads) {
158
221
  const prop = known[name];
159
222
  let given = match[2];
160
223
  if (given === undefined) {
161
- // A yes-or-no flag stands alone; any other takes the next word.
224
+ // A yes-or-no flag stands alone; any other takes the next word. In a
225
+ // command with nothing left to give without a flag, the true or false
226
+ // after it is its value (`room invite --on false`, as agents type an
227
+ // action's input). Elsewhere that word is the next thing given
228
+ // (`board grep --ignore-case true` searches for "true").
162
229
  if (allows(prop, "boolean") && !allows(prop, "string") && !allows(prop, "number"))
163
- given = "true";
230
+ given = positional.length >= cli.args.length && (argv[i + 1] === "true" || argv[i + 1] === "false") ? argv[++i] : "true";
164
231
  else if (i + 1 < argv.length)
165
232
  given = argv[++i];
166
233
  else
@@ -186,8 +253,11 @@ export async function inputsFrom(me, tool, argv, io = reads) {
186
253
  throw wrong(`Could not read ${given.slice(1)}.`);
187
254
  }
188
255
  }
189
- else
190
- inputs[name] = scalar(given, prop);
256
+ else {
257
+ const value = scalar(given, prop);
258
+ // A flag that also takes a list, given again, is a list of each (`--to A --to B`).
259
+ inputs[name] = allows(prop, "array") && name in inputs ? [...(Array.isArray(inputs[name]) ? inputs[name] : [inputs[name]]), value] : value;
260
+ }
191
261
  }
192
262
  if (positional.length > cli.args.length)
193
263
  throw wrong(`${cli.command} takes ${cli.args.length === 1 ? "one thing" : `${cli.args.length} things`} without a flag; ${JSON.stringify(positional[cli.args.length])} is one too many.`);