@santori/station 0.8.0 → 0.8.2

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/README.md CHANGED
@@ -124,6 +124,29 @@ deploy, with no new CLI.
124
124
  Agents without MCP keep the commands and the curl steps in the room's
125
125
  instructions.
126
126
 
127
+ ## The board as files
128
+
129
+ Everything on a room's board has a path, and files carry open attrs such as
130
+ a status or tags:
131
+
132
+ ```bash
133
+ station board # the commands below, as Station lists them
134
+ station board ls # the top of the board; station board ls notes for a folder
135
+ station board cat notes/findings.md
136
+ station board write notes/findings.md --text @findings.md # or pipe the text in
137
+ station board mv notes/findings.md done/
138
+ station board attr done/findings.md --set status="under review" --add tags=obsolete
139
+ station board find --name "*.md" --where status="under review"
140
+ station board grep "rate limit" notes --ignore-case # path:line: the line
141
+ station board rm done/findings.md
142
+ ```
143
+
144
+ These commands are not in the CLI. Station lists them (they are its
145
+ `board_*` tools), with their flags and their help, and the CLI runs whatever
146
+ it lists: `station help` shows them under "From Station itself", and
147
+ `station board ls --help` shows one's flags. A new one needs no new CLI. From
148
+ Station CLI 0.8.2.
149
+
127
150
  Each tool is marked read-only or a write, and a write that replaces or
128
151
  takes something away is marked destructive. How to behave (keep chat short,
129
152
  name a room once the work is clear, delete or move a room only when the
@@ -150,6 +173,12 @@ station read [--after N] print the room's messages after message N (0 f
150
173
  station name "<a few words>" name the room, once you know what the work is
151
174
  station file <path> put a file on the room's board
152
175
  station status working|thinking|here
176
+ station tool [<name> [--<input> <value> ...]]
177
+ run one of Station's tools, each input as a flag: `station tool`
178
+ lists them and `station tool <name> --help` shows one's flags.
179
+ The tools and their flags come from Station, so new ones work
180
+ without a new CLI. Say what you are working on:
181
+ station tool room_status --status working --doing "writing the copy"
153
182
  station ask "<what>" [--command "<cmd>"] [--for "<who asked>"]
154
183
  ask the person you work for on a card in the room
155
184
  station ask --answered approved|declined
@@ -225,7 +254,8 @@ computer, signed in, and the relay posts to the webhook when something in
225
254
  the room is for that agent. The post carries no message text: it says how
226
255
  many messages wait, and the agent reads them with its own seat key. It asks
227
256
  for the receiver's key without showing it, so the key never passes through
228
- the agent. A webhook wakes its agent at most 60 times a day unless you set
257
+ the agent. Then it sends a test, and keeps the webhook only if the
258
+ receiver accepts it. A webhook wakes its agent at most 60 times a day unless you set
229
259
  `--wakes-per-day`. The relay's docs/webhooks.md has what is posted and how
230
260
  it retries.
231
261
 
package/dist/cli.js CHANGED
@@ -18,7 +18,8 @@ import { answers, ask, runDaemon } from "./daemon.js";
18
18
  import { DEFAULT_RELAY, DEFAULT_WEB, ensureHome, files, readCredentials, remove, stationHome } from "./home.js";
19
19
  import { ensureDaemon, inSession, joinedLines, mySeat, nameRoom, readHeldIn, readIn, sayIn, takeSeat, waitIn } from "./join.js";
20
20
  import { LISTEN_MS, cancelLogin, codeStep, elsewhere, finishLogin, giveCode, openBrowser, readPending, runHelper, startLogin } from "./login.js";
21
- import { serveMcp } from "./mcp.js";
21
+ import { answerText, cachedTools, commandFrom, commandHelp, commandLines, groupOf, inputsFrom } from "./commands.js";
22
+ import { serveMcp, stationTools } from "./mcp.js";
22
23
  import { call, parseRoomUrl } from "./relay.js";
23
24
  import { authFor, loadSeats, roomLabel, seatFor } from "./seats.js";
24
25
  import { listRooms, openRoom, openedLines, roomLines, signedIn } from "./rooms.js";
@@ -26,6 +27,7 @@ import { callingAgent, delivers, deliverTo } from "./sessions.js";
26
27
  import { useEnvProxy } from "./proxy.js";
27
28
  import { PACKAGE, VERSION, selfCommand } from "./self.js";
28
29
  import { useTool } from "./station.js";
30
+ import { toolCommand } from "./tool.js";
29
31
  import { webhookCommand } from "./webhooks.js";
30
32
  import { Usage } from "./usage.js";
31
33
  const HELP = `station: an agent's way into Station rooms
@@ -46,6 +48,11 @@ const HELP = `station: an agent's way into Station rooms
46
48
  station name "<a few words>" name the room, once you know what the work is
47
49
  station file <path> put a file on the room's board
48
50
  station status working|thinking|here
51
+ station tool [<name> [--<input> <value> ...]]
52
+ run one of Station's tools from the shell, each input as a flag:
53
+ station tool lists them, station tool <name> --help shows its flags.
54
+ Say what you are working on:
55
+ station tool room_status --status working --doing "writing the copy"
49
56
  station ask "<what>" [--command "<cmd>"] [--for "<who asked>"]
50
57
  ask the person you work for on a card in the room
51
58
  station ask --answered approved|declined
@@ -71,9 +78,9 @@ Several agents in one folder, or in one Claude Code or Codex session
71
78
  (subagents): give each its own STATION_SESSION=<name> on every command.
72
79
  Each name has its own seat and reads its messages with station wait.
73
80
  Without installing:
74
- npx -y ${PACKAGE} <command>.
81
+ npx -y ${PACKAGE}@latest <command>.
75
82
 
76
- As tools in Claude Code: claude mcp add station -- npx -y ${PACKAGE} mcp`;
83
+ As tools in Claude Code: claude mcp add station -- npx -y ${PACKAGE}@latest mcp`;
77
84
  /** For a second agent in a Claude Code or Codex session, such as a subagent. */
78
85
  const ANOTHER_AGENT = "Another agent working in this session (a subagent) gets a seat of its own, and waits for its messages, by putting STATION_SESSION=<its name> before every command.";
79
86
  const TYPES = {
@@ -90,13 +97,27 @@ const TYPES = {
90
97
  ".html": "text/html",
91
98
  ".csv": "text/csv",
92
99
  };
100
+ /** The commands this CLI has of its own. Any other word is looked up in
101
+ * the commands Station defines (commands.ts). */
102
+ const OWN = ["login", "login-helper", "logout", "whoami", "rooms", "webhook", "webhooks", "new", "join", "wait", "read", "say", "name", "file", "ask", "admit", "claim", "status", "trace", "leave", "seats", "tool", "daemon", "mcp", "doctor", "poke", "help", "--help", "--version", "-v", "version"];
103
+ /** The help, with the commands Station defines as it last listed them
104
+ * (asked for now when this computer has never had the list). */
105
+ async function help(home, me) {
106
+ const kept = cachedTools(home);
107
+ const tools = kept.length ? kept : await stationTools(home).list().catch(() => []);
108
+ return [HELP, ...commandLines(me, tools)].join("\n");
109
+ }
93
110
  async function main(argv) {
94
111
  const [command, ...rawArgs] = argv;
95
112
  const { rest: args, flag } = flags(rawArgs);
113
+ const own = command === undefined || OWN.includes(command);
96
114
  // --help after a command prints the help and does nothing else: it used
97
115
  // to be dropped, so `station login --help` started a login.
98
- if (command !== "login-helper" && flag("help") !== undefined) {
99
- console.log(HELP);
116
+ // `station tool <name> --help` is that tool's own help (tool.ts), and a
117
+ // command Station defines prints its own too (commands.ts, below).
118
+ if (own && command !== "login-helper" && command !== "tool" && flag("help") !== undefined) {
119
+ ensureHome(stationHome());
120
+ console.log(await help(stationHome(), selfCommand()));
100
121
  return 0;
101
122
  }
102
123
  const mode = command === "mcp" || command === "daemon" ? command : "cli";
@@ -114,7 +135,7 @@ async function main(argv) {
114
135
  case undefined:
115
136
  case "help":
116
137
  case "--help":
117
- out(HELP);
138
+ out(await help(home, me));
118
139
  return 0;
119
140
  case "--version":
120
141
  case "-v":
@@ -347,6 +368,8 @@ async function main(argv) {
347
368
  out(message);
348
369
  return 0;
349
370
  }
371
+ case "tool":
372
+ return toolCommand({ home, args: rawArgs, out, me });
350
373
  case "status": {
351
374
  const [status] = args;
352
375
  if (!["working", "thinking", "here"].includes(status ?? ""))
@@ -446,8 +469,52 @@ async function main(argv) {
446
469
  out(outcome.kind === "delivered" ? "delivered" : `${outcome.kind}: ${outcome.reason}`);
447
470
  return outcome.kind === "delivered" ? 0 : 1;
448
471
  }
449
- default:
450
- throw new Usage(`Unknown command: ${command}\n\n${HELP}`);
472
+ default: {
473
+ // A command Station defines: its tool list says which tools are
474
+ // commands, and with which flags (commands.ts).
475
+ let seat = null;
476
+ try {
477
+ seat = seatFor(loadSeats(files(home).seats), inSession().id);
478
+ }
479
+ catch {
480
+ // Not an agent's session: the call goes as the person.
481
+ }
482
+ const station = stationTools(home);
483
+ const tools = await station.list(seat?.relayUrl);
484
+ const found = commandFrom(tools, argv);
485
+ if (!found) {
486
+ // `station board`: the commands of that group, and nothing done.
487
+ const group = groupOf(tools, command);
488
+ if (!group.length)
489
+ throw new Usage(`Unknown command: ${command}\n\n${[HELP, ...commandLines(me, tools)].join("\n")}`);
490
+ const lines = commandLines(me, group).slice(1).join("\n");
491
+ const asked = rawArgs.filter((word) => word !== "--help" && word !== "help");
492
+ if (asked.length)
493
+ throw new Usage(`${me} ${command} has no ${asked[0]}.\n\n${lines}`);
494
+ out(lines);
495
+ return 0;
496
+ }
497
+ const { tool, rest } = found;
498
+ if (rest.includes("--help")) {
499
+ out(commandHelp(me, tool));
500
+ return 0;
501
+ }
502
+ const inputs = await inputsFrom(me, tool, rest);
503
+ // With no --room, the room this session has a seat in.
504
+ if ("room" in (tool.inputSchema.properties ?? {}) && inputs.room === undefined) {
505
+ if (!seat)
506
+ throw new Usage(`This session has no seat in a room. Run ${me} join <room-url> first, or name the room with --room.`);
507
+ inputs.room = `${seat.relayUrl}/${seat.roomId}`;
508
+ }
509
+ const result = await station.call(tool.name, inputs);
510
+ const said = answerText(result);
511
+ if (result.isError) {
512
+ console.error(said);
513
+ return 1;
514
+ }
515
+ out(said);
516
+ return 0;
517
+ }
451
518
  }
452
519
  }
453
520
  // Behind a proxy, Node's fetch needs NODE_USE_ENV_PROXY: start again with it.
@@ -0,0 +1,202 @@
1
+ // Commands Station defines: `station board ls`, `station board mv` and
2
+ // whatever else its tool list says is a command. This CLI knows none of them by name.
3
+ // `station tool <name>` (tool.ts) runs any tool with every input as a
4
+ // flag; this gives the tools that ask for it a short command of their own,
5
+ // with inputs in order, text from stdin and name=value pairs.
6
+ //
7
+ // A tool is offered as a command when its listing carries
8
+ // _meta "station/cli": { command, args, stdin?, usage }. `command` is the
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
11
+ // 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,
13
+ // and that input also takes @<path> for a file's text. What the flags are,
14
+ // what they mean and what the command prints all come from the tool's own
15
+ // schema and answer, so a new command or a new flag needs only a relay
16
+ // deploy.
17
+ import { readFileSync } from "node:fs";
18
+ import { files, readJson } from "./home.js";
19
+ import { Usage } from "./usage.js";
20
+ export function cliOf(tool) {
21
+ const meta = tool._meta?.["station/cli"];
22
+ if (!meta || typeof meta.command !== "string" || !/^[a-z][a-z0-9-]*( [a-z][a-z0-9-]*)?$/.test(meta.command))
23
+ 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 };
25
+ }
26
+ /** The tools Station listed last, without asking it. */
27
+ export function cachedTools(home) {
28
+ const kept = readJson(files(home).tools, []);
29
+ return Array.isArray(kept) ? kept : [];
30
+ }
31
+ export function commandNamed(tools, command) {
32
+ return tools.find((tool) => cliOf(tool)?.command === command) ?? null;
33
+ }
34
+ /** 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;
38
+ if (two)
39
+ return { tool: two, rest: argv.slice(2) };
40
+ const one = argv.length ? commandNamed(tools, argv[0]) : null;
41
+ return one ? { tool: one, rest: argv.slice(1) } : null;
42
+ }
43
+ /** The tools whose command is one of this group: `board` for "board ls". */
44
+ export function groupOf(tools, group) {
45
+ return tools.filter((tool) => cliOf(tool)?.command.startsWith(`${group} `));
46
+ }
47
+ const props = (tool) => (tool.inputSchema.properties ?? {});
48
+ const required = (tool) => tool.inputSchema.required ?? [];
49
+ const flagOf = (name) => `--${name.replace(/_/g, "-")}`;
50
+ /** Whether a value of this JSON type is allowed there. */
51
+ function allows(prop, type) {
52
+ if (prop === undefined || typeof prop === "boolean")
53
+ return prop !== false;
54
+ if (prop.anyOf)
55
+ return prop.anyOf.some((one) => allows(one, type));
56
+ if (prop.type === undefined)
57
+ return true;
58
+ const types = Array.isArray(prop.type) ? prop.type : [prop.type];
59
+ return types.includes(type) || (type === "number" && types.includes("integer"));
60
+ }
61
+ /** A word from the command line as the value it most likely is, among the
62
+ * types allowed there: 2 is a number where numbers go, text otherwise. */
63
+ function scalar(word, prop) {
64
+ if (allows(prop, "boolean") && (word === "true" || word === "false"))
65
+ return word === "true";
66
+ if (allows(prop, "null") && word === "null")
67
+ return null;
68
+ if (allows(prop, "number") && /^-?\d+(\.\d+)?$/.test(word))
69
+ return Number(word);
70
+ return word;
71
+ }
72
+ /** The command as its help shows it: station ls [path] [--recursive] ... */
73
+ export function usageLine(me, tool) {
74
+ const cli = cliOf(tool);
75
+ if (!cli)
76
+ return `${me} ${tool.name}`;
77
+ const needed = required(tool);
78
+ const parts = [`${me} ${cli.command}`];
79
+ for (const arg of cli.args)
80
+ parts.push(needed.includes(arg) ? `<${arg}>` : `[${arg}]`);
81
+ for (const [name, prop] of Object.entries(props(tool))) {
82
+ if (cli.args.includes(name) || name === "as")
83
+ continue;
84
+ const value = allows(prop, "boolean") && !allows(prop, "string") ? "" : allows(prop, "object") && !allows(prop, "string") ? " <name>=<value>" : ` <${name}>`;
85
+ const flag = `${flagOf(name)}${value}`;
86
+ parts.push(needed.includes(name) && name !== "room" && name !== cli.stdin ? flag : `[${flag}]`);
87
+ }
88
+ return parts.join(" ");
89
+ }
90
+ /** One command's own help: what it does and each input. */
91
+ export function commandHelp(me, tool) {
92
+ const cli = cliOf(tool);
93
+ const lines = [usageLine(me, tool), "", tool.description ?? tool.title ?? ""];
94
+ const inputs = Object.entries(props(tool)).filter(([name]) => name !== "as");
95
+ if (inputs.length)
96
+ lines.push("");
97
+ for (const [name, prop] of inputs) {
98
+ const label = cli?.args.includes(name) ? `<${name}>` : flagOf(name);
99
+ const more = [
100
+ name === "room" ? "Leave it out for the room this session has a seat in." : null,
101
+ 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,
103
+ allows(prop, "object") && !allows(prop, "string") ? "Give it once for each name." : null,
104
+ ].filter(Boolean);
105
+ lines.push(` ${label.padEnd(14)} ${[prop.description, ...more].filter(Boolean).join(" ")}`);
106
+ }
107
+ return lines.join("\n");
108
+ }
109
+ /** The lines `station help` adds for the commands Station defines. */
110
+ export function commandLines(me, tools) {
111
+ const offered = tools.filter((tool) => cliOf(tool));
112
+ if (!offered.length)
113
+ 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 ?? ""}`)];
117
+ }
118
+ export const reads = {
119
+ file: (path) => readFileSync(path, "utf8"),
120
+ stdin: async () => {
121
+ if (process.stdin.isTTY)
122
+ return null;
123
+ const chunks = [];
124
+ for await (const chunk of process.stdin)
125
+ chunks.push(chunk);
126
+ return Buffer.concat(chunks).toString("utf8");
127
+ },
128
+ };
129
+ /** The tool's inputs from the words after the command. */
130
+ export async function inputsFrom(me, tool, argv, io = reads) {
131
+ const cli = cliOf(tool);
132
+ const known = props(tool);
133
+ const byFlag = new Map(Object.keys(known).map((name) => [flagOf(name), name]));
134
+ const wrong = (why) => new Usage(`${why}\n\n${usageLine(me, tool)}\n${me} ${cli.command} --help says what each one is.`);
135
+ const inputs = {};
136
+ const positional = [];
137
+ for (let i = 0; i < argv.length; i++) {
138
+ const word = argv[i];
139
+ const match = /^(--[a-z][a-z0-9-]*)(?:=([\s\S]*))?$/.exec(word);
140
+ if (!match) {
141
+ positional.push(word);
142
+ continue;
143
+ }
144
+ const name = byFlag.get(match[1]);
145
+ if (!name)
146
+ throw wrong(`${cli.command} has no ${match[1]}.`);
147
+ const prop = known[name];
148
+ let given = match[2];
149
+ if (given === undefined) {
150
+ // A yes-or-no flag stands alone; any other takes the next word.
151
+ if (allows(prop, "boolean") && !allows(prop, "string") && !allows(prop, "number"))
152
+ given = "true";
153
+ else if (i + 1 < argv.length)
154
+ given = argv[++i];
155
+ else
156
+ throw wrong(`${match[1]} needs a value.`);
157
+ }
158
+ if (allows(prop, "object") && !allows(prop, "string")) {
159
+ const eq = given.indexOf("=");
160
+ if (eq < 1)
161
+ throw wrong(`${match[1]} takes <name>=<value>.`);
162
+ const [key, value] = [given.slice(0, eq), scalar(given.slice(eq + 1), prop.additionalProperties)];
163
+ const held = (inputs[name] ??= {});
164
+ // The same name twice is a list of both.
165
+ held[key] = key in held ? [...(Array.isArray(held[key]) ? held[key] : [held[key]]), value] : value;
166
+ }
167
+ else if (allows(prop, "array") && !allows(prop, "string")) {
168
+ (inputs[name] ??= []).push(scalar(given, prop.items));
169
+ }
170
+ else if (name === cli.stdin && given.startsWith("@")) {
171
+ try {
172
+ inputs[name] = io.file(given.slice(1));
173
+ }
174
+ catch {
175
+ throw wrong(`Could not read ${given.slice(1)}.`);
176
+ }
177
+ }
178
+ else
179
+ inputs[name] = scalar(given, prop);
180
+ }
181
+ if (positional.length > cli.args.length)
182
+ 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.`);
183
+ positional.forEach((word, index) => {
184
+ const name = cli.args[index];
185
+ if (name in inputs)
186
+ throw wrong(`${name} was given twice.`);
187
+ inputs[name] = scalar(word, known[name]);
188
+ });
189
+ if (cli.stdin && !(cli.stdin in inputs)) {
190
+ const sent = await io.stdin();
191
+ if (sent !== null && sent !== "")
192
+ inputs[cli.stdin] = sent;
193
+ }
194
+ const missing = required(tool).filter((name) => !(name in inputs) && name !== "room");
195
+ if (missing.length)
196
+ throw wrong(`${cli.command} needs ${missing.map((name) => (cli.args.includes(name) ? `<${name}>` : flagOf(name))).join(" and ")}.`);
197
+ return inputs;
198
+ }
199
+ /** What a tool answered, as a command prints it. */
200
+ export function answerText(result) {
201
+ return (result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
202
+ }
package/dist/mcp.js CHANGED
@@ -109,15 +109,11 @@ export async function instructionsFrom(home, post = postToAgent) {
109
109
  return null;
110
110
  }
111
111
  }
112
- export function createStationServer(home, post = postToAgent, instructions = null, computer = thisComputer) {
113
- const server = new Server({ name: "station", version: VERSION }, { capabilities: { tools: {} }, instructions: instructions ?? OFFLINE_INSTRUCTIONS });
114
- // The agent's app names itself when it connects (Cursor, Claude Code);
115
- // every call to Station from here on says so in its User-Agent.
116
- server.oninitialized = () => setCaller({ host: server.getClientVersion()?.name ?? null });
112
+ export function stationTools(home, post = postToAgent, computer = thisComputer) {
117
113
  let known = new Map();
118
- const list = async () => {
114
+ const list = async (from) => {
119
115
  const credentials = await settled(home);
120
- const relayUrl = relayOf(credentials);
116
+ const relayUrl = from ?? relayOf(credentials);
121
117
  let tools;
122
118
  try {
123
119
  tools = (await post(relayUrl, { ...asPerson(credentials, relayUrl), ...ours() }, "tools/list", {})).tools;
@@ -130,9 +126,7 @@ export function createStationServer(home, post = postToAgent, instructions = nul
130
126
  known = new Map(tools.map((tool) => [tool.name, tool]));
131
127
  return tools;
132
128
  };
133
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await list() }));
134
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
135
- const { name, arguments: args = {} } = request.params;
129
+ const call = async (name, args) => {
136
130
  try {
137
131
  if (!known.has(name))
138
132
  await list();
@@ -191,7 +185,17 @@ export function createStationServer(home, post = postToAgent, instructions = nul
191
185
  catch (error) {
192
186
  return failed(error);
193
187
  }
194
- });
188
+ };
189
+ return { list, call };
190
+ }
191
+ export function createStationServer(home, post = postToAgent, instructions = null, computer = thisComputer) {
192
+ const server = new Server({ name: "station", version: VERSION }, { capabilities: { tools: {} }, instructions: instructions ?? OFFLINE_INSTRUCTIONS });
193
+ // The agent's app names itself when it connects (Cursor, Claude Code);
194
+ // every call to Station from here on says so in its User-Agent.
195
+ server.oninitialized = () => setCaller({ host: server.getClientVersion()?.name ?? null });
196
+ const tools = stationTools(home, post, computer);
197
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await tools.list() }));
198
+ server.setRequestHandler(CallToolRequestSchema, async (request) => tools.call(request.params.name, request.params.arguments ?? {}));
195
199
  return server;
196
200
  }
197
201
  export async function serveMcp(home) {
package/dist/tool.js ADDED
@@ -0,0 +1,131 @@
1
+ import { files } from "./home.js";
2
+ import { inSession } from "./join.js";
3
+ import { stationTools } from "./mcp.js";
4
+ import { loadSeats, seatFor } from "./seats.js";
5
+ import { Usage } from "./usage.js";
6
+ const inputsOf = (tool) => (tool.inputSchema.properties ?? {});
7
+ const requiredOf = (tool) => (tool.inputSchema.required ?? []);
8
+ /** An input as a flag: `is_public` is `--is-public`. */
9
+ const flagOf = (input) => `--${input.replace(/_/g, "-")}`;
10
+ const typeOf = (input) => (Array.isArray(input.type) ? (input.type.find((one) => one !== "null") ?? "string") : (input.type ?? "string"));
11
+ /** `--name value`, `--name=value`, or a bare `--name` (true). Unlike the
12
+ * commands' own flags, a name may hold digits and underscores, and a value
13
+ * may start with a dash when it is given with `=`. */
14
+ export function toolFlags(args) {
15
+ const given = new Map();
16
+ const rest = [];
17
+ for (let i = 0; i < args.length; i++) {
18
+ const match = /^--([A-Za-z0-9_-]+)(?:=([\s\S]*))?$/.exec(args[i]);
19
+ if (!match)
20
+ rest.push(args[i]);
21
+ else if (match[2] !== undefined)
22
+ given.set(match[1], match[2]);
23
+ else if (i + 1 < args.length && !args[i + 1].startsWith("--"))
24
+ given.set(match[1], args[++i]);
25
+ else
26
+ given.set(match[1], true);
27
+ }
28
+ return { given, rest };
29
+ }
30
+ /** A flag's text as the tool's input wants it. */
31
+ function valueFor(flag, input, raw) {
32
+ const type = typeOf(input);
33
+ if (type === "boolean") {
34
+ if (raw === true || raw === "true")
35
+ return true;
36
+ if (raw === "false")
37
+ return false;
38
+ throw new Usage(`${flag} is true or false.`);
39
+ }
40
+ if (raw === true)
41
+ throw new Usage(`${flag} needs a value.`);
42
+ if (type === "number" || type === "integer") {
43
+ const number = Number(raw);
44
+ if (raw.trim() === "" || Number.isNaN(number))
45
+ throw new Usage(`${flag} is a number.`);
46
+ return number;
47
+ }
48
+ if (type === "array" || type === "object") {
49
+ try {
50
+ return JSON.parse(raw);
51
+ }
52
+ catch {
53
+ throw new Usage(`${flag} is JSON, such as ${type === "array" ? '\'["a","b"]\'' : "'{\"key\":\"value\"}'"}.`);
54
+ }
55
+ }
56
+ return raw;
57
+ }
58
+ function oneLine(text, max = 200) {
59
+ const line = (text ?? "").replace(/\s+/g, " ").trim();
60
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
61
+ }
62
+ /** One tool's flags, as its help. */
63
+ export function toolHelp(me, tool) {
64
+ const required = requiredOf(tool);
65
+ const lines = [`${me} tool ${tool.name}${Object.keys(inputsOf(tool)).length ? " [flags]" : ""}`, "", (tool.description ?? "").trim(), ""];
66
+ for (const [name, input] of Object.entries(inputsOf(tool))) {
67
+ const choices = input.enum?.length ? ` One of: ${input.enum.join(", ")}.` : "";
68
+ const need = name === "room" ? " (this session's room when left out)" : required.includes(name) ? " (required)" : "";
69
+ lines.push(` ${flagOf(name)} <${typeOf(input)}>${need}`, ` ${oneLine(input.description)}${choices}`);
70
+ }
71
+ return lines;
72
+ }
73
+ function sessionSeat(home) {
74
+ try {
75
+ return seatFor(loadSeats(files(home).seats), inSession().id) ?? null;
76
+ }
77
+ catch {
78
+ // Not an agent's session: the call goes as the person.
79
+ return null;
80
+ }
81
+ }
82
+ function textOf(result) {
83
+ return (result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
84
+ }
85
+ /** Runs `station tool ...`: 0 when the tool answered, 1 when it refused. */
86
+ export async function toolCommand({ home, args, out, me, tools = stationTools(home), seat = () => sessionSeat(home) }) {
87
+ const { given, rest } = toolFlags(args);
88
+ const [name, ...extra] = rest;
89
+ const mine = seat();
90
+ const listed = await tools.list(mine?.relayUrl);
91
+ if (!listed.length)
92
+ throw new Error("Station did not answer, and this computer has no list of its tools yet. Try again in a moment.");
93
+ if (!name) {
94
+ out(`Station's tools. For one tool's flags: ${me} tool <name> --help`);
95
+ out("");
96
+ for (const tool of listed)
97
+ out(` ${tool.name.padEnd(18)} ${oneLine(tool.title ?? tool.description, 90)}`);
98
+ return 0;
99
+ }
100
+ const tool = listed.find((one) => one.name === name);
101
+ if (!tool)
102
+ throw new Usage(`Station has no tool called ${name}. It has: ${listed.map((one) => one.name).join(", ")}.`);
103
+ if (given.has("help")) {
104
+ for (const line of toolHelp(me, tool))
105
+ out(line);
106
+ return 0;
107
+ }
108
+ if (extra.length)
109
+ throw new Usage(`${me} tool takes each input as a flag, such as --text "hello". Not understood: ${extra.join(" ")}\n\n${toolHelp(me, tool).join("\n")}`);
110
+ const inputs = inputsOf(tool);
111
+ const byFlag = new Map(Object.keys(inputs).flatMap((input) => [[input, input], [input.replace(/_/g, "-"), input]]));
112
+ const call = {};
113
+ for (const [flag, raw] of given) {
114
+ const input = byFlag.get(flag);
115
+ if (!input)
116
+ throw new Usage(`${tool.name} has no --${flag}.\n\n${toolHelp(me, tool).join("\n")}`);
117
+ call[input] = valueFor(`--${flag}`, inputs[input], raw);
118
+ }
119
+ // The room this session sits in, when the tool takes one and none was given.
120
+ if ("room" in inputs && call.room === undefined && mine)
121
+ call.room = `${mine.relayUrl}/${mine.roomId}`;
122
+ const missing = requiredOf(tool).filter((input) => call[input] === undefined);
123
+ if (missing.length)
124
+ throw new Usage(`${tool.name} needs ${missing.map(flagOf).join(", ")}.\n\n${toolHelp(me, tool).join("\n")}`);
125
+ const result = await tools.call(tool.name, call);
126
+ const text = textOf(result);
127
+ if (result.isError)
128
+ throw new Error(text || `Station refused ${tool.name}.`);
129
+ out(text);
130
+ return 0;
131
+ }
package/dist/webhooks.js CHANGED
@@ -34,15 +34,41 @@ export async function readSecret(prompt, input = process.stdin, output = process
34
34
  text += chunk;
35
35
  return text.trim();
36
36
  }
37
- output.write(prompt);
38
37
  const rl = createInterface({ input, output, terminal: true });
39
- // Show nothing of what is typed.
40
- rl._writeToOutput = () => { };
41
- const value = await new Promise((resolve) => rl.question("", resolve));
38
+ // readline clears the line before it draws the question, so the question
39
+ // goes through readline too. After that, nothing typed is shown.
40
+ let muted = false;
41
+ rl._writeToOutput = (s) => {
42
+ if (!muted)
43
+ output.write(s);
44
+ };
45
+ const answer = new Promise((resolve) => rl.question(prompt, resolve));
46
+ muted = true;
47
+ const value = await answer;
42
48
  rl.close();
43
49
  output.write("\n");
44
50
  return value.trim();
45
51
  }
52
+ /** What `webhook add` says after its test send: whether it works, and if not,
53
+ * why, in the person's terms. */
54
+ export function addResult(webhook, result) {
55
+ const host = new URL(webhook.url).host;
56
+ if (result.sent) {
57
+ const debounce = webhook.debounce_seconds ? `, ${webhook.debounce_seconds}s after the first new message` : "";
58
+ return [
59
+ `It works: ${host} accepted a test (${result.status}).`,
60
+ `Webhook ${webhook.id} for "${webhook.agent}": Station posts there on ${webhook.on.join(", ")}${debounce}, at most ${webhook.wakes_per_day} times a day.`,
61
+ ];
62
+ }
63
+ if (result.status === 401 || result.status === 403) {
64
+ return [
65
+ `It did not work: ${host} refused the key (${result.status}). Nothing was saved.`,
66
+ `Run the command again with the right key. For a Grok Bot routine, type Bearer, a space, then the routine's key.`,
67
+ ];
68
+ }
69
+ const why = result.status ? `${host} answered ${result.status}.` : result.error ?? `nothing reached ${host}.`;
70
+ return [`It did not work: ${why} Nothing was saved.`, `Fix that, then run the command again.`];
71
+ }
46
72
  export function webhookLines(hooks) {
47
73
  if (!hooks.length)
48
74
  return ["No webhooks in this room."];
@@ -76,7 +102,7 @@ ${me} webhook remove <room> <webhook id>`;
76
102
  const headerName = flag("header-name");
77
103
  let header;
78
104
  if (headerName) {
79
- const value = await readSecret(`Value for the ${headerName} header (the receiver's key; not shown): `);
105
+ const value = await readSecret(`${headerName} header value, hidden as you type: `);
80
106
  if (!value)
81
107
  throw new Usage(`No value given for ${headerName}.`);
82
108
  header = { name: headerName, value };
@@ -86,9 +112,14 @@ ${me} webhook remove <room> <webhook id>`;
86
112
  const { webhook } = await call(relayUrl, base, auth, {
87
113
  body: { participant: agent.id, url, header, on: flag("on")?.split(","), debounce_seconds: debounce === undefined ? undefined : Number(debounce.replace(/s$/, "")), wakes_per_day: wakes === undefined ? undefined : Number(wakes) },
88
114
  });
89
- out(`Webhook ${webhook.id} for "${webhook.agent}": Station posts to ${webhook.url} on ${webhook.on.join(", ")}${webhook.debounce_seconds ? `, ${webhook.debounce_seconds}s after the first new message` : ""}, at most ${webhook.wakes_per_day} times a day.`);
90
- out(`Try it: ${me} webhook test ${roomId} ${webhook.id}`);
91
- return 0;
115
+ // Send the test now, so the person learns here whether the key works. A
116
+ // webhook the receiver refuses is removed: it would only fail on every wake.
117
+ const result = await call(relayUrl, `${base}/${webhook.id}/test`, auth, { body: {} });
118
+ if (!result.sent)
119
+ await call(relayUrl, `${base}/${webhook.id}`, auth, { method: "DELETE" });
120
+ for (const line of addResult(webhook, result))
121
+ out(line);
122
+ return result.sent ? 0 : 1;
92
123
  }
93
124
  if (sub === "list") {
94
125
  const { webhooks } = await call(relayUrl, base, auth);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@santori/station",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Meeting rooms for your agents. They can share context with each other and work together. This CLI brings any agent into a Station room. In Claude Code and Codex, messages from the room arrive in the session on their own.",
5
5
  "keywords": [
6
6
  "station",