@santori/station 0.9.7 → 0.9.9
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 +3 -1
- package/dist/agentToken.js +26 -0
- package/dist/agents.js +137 -0
- package/dist/claude.js +14 -0
- package/dist/cli.js +84 -17
- package/dist/codex.js +76 -5
- package/dist/daemon.js +51 -14
- package/dist/frame.js +10 -0
- package/dist/handover.js +11 -7
- package/dist/home.js +7 -1
- package/dist/join.js +149 -40
- package/dist/limits.js +210 -0
- package/dist/login.js +17 -4
- package/dist/mcp.js +60 -9
- package/dist/proxy.js +5 -0
- package/dist/relay.js +38 -1
- package/dist/seats.js +24 -4
- package/dist/self.js +31 -1
- package/dist/sessions.js +12 -3
- package/dist/signup.js +4 -2
- package/dist/starts.js +174 -0
- package/dist/waking.js +293 -0
- package/dist/webhooks.js +16 -4
- package/package.json +2 -2
package/dist/starts.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Starting an agent on this computer with no window open, for an ask the
|
|
2
|
+
// relay sent its local install (the daemon's GET /cli/wakes). Codex runs
|
|
3
|
+
// as `codex exec`, Claude Code as `claude -p`, in the folder the agent
|
|
4
|
+
// last worked in here, and each gets Station's tools as this same CLI's
|
|
5
|
+
// `station mcp`, acting as a session Station named for it
|
|
6
|
+
// (STATION_STARTED). The next ask for that agent in that room resumes the
|
|
7
|
+
// same thread, so it keeps what it learned.
|
|
8
|
+
//
|
|
9
|
+
// A started agent runs with the narrow permissions a person would give a
|
|
10
|
+
// task they did not watch: Codex in its workspace-write sandbox, Claude
|
|
11
|
+
// Code allowed to edit files and use Station's tools, nothing else without
|
|
12
|
+
// asking (which, with no window, it cannot). Anyone the person's agents
|
|
13
|
+
// work with can send it an ask, so it never runs with more.
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
16
|
+
import { existsSync } from "node:fs";
|
|
17
|
+
import { files, readJson, writeJson } from "./home.js";
|
|
18
|
+
import { fromMessage } from "./limits.js";
|
|
19
|
+
import { onPath } from "./self.js";
|
|
20
|
+
export const startsFile = (home) => `${files(home).seats.replace(/seats\.json$/, "")}starts.json`;
|
|
21
|
+
const keyOf = (agent, room) => `${agent}:${room}`;
|
|
22
|
+
export function loadStarts(home) {
|
|
23
|
+
return Object.fromEntries(Object.entries(readJson(startsFile(home), {})).filter((entry) => typeof entry[1] === "object"));
|
|
24
|
+
}
|
|
25
|
+
export function saveStart(home, agent, room, started) {
|
|
26
|
+
writeJson(startsFile(home), { ...readJson(startsFile(home), {}), [keyOf(agent, room)]: started });
|
|
27
|
+
}
|
|
28
|
+
/** Where Station starts the agent when it has no room of its own here yet:
|
|
29
|
+
* the folder `station add` ran in. */
|
|
30
|
+
export function saveFolder(home, agent, cwd) {
|
|
31
|
+
const starts = readJson(startsFile(home), {});
|
|
32
|
+
writeJson(startsFile(home), { ...starts, [`${agent}:folder`]: cwd });
|
|
33
|
+
}
|
|
34
|
+
export function folderOf(home, agent) {
|
|
35
|
+
const value = readJson(startsFile(home), {})[`${agent}:folder`];
|
|
36
|
+
return typeof value === "string" ? value : null;
|
|
37
|
+
}
|
|
38
|
+
/** The session a started agent of this agent in this room acts as: the same one every time. */
|
|
39
|
+
export const startedSessionId = (agent, room) => `started-${createHash("sha256").update(keyOf(agent, room)).digest("hex").slice(0, 24)}`;
|
|
40
|
+
/** Where and how to start the agent for this wake: the room's earlier
|
|
41
|
+
* start, else a new one in `cwd`. */
|
|
42
|
+
export function planFor(home, wake, kind, cwd) {
|
|
43
|
+
const known = loadStarts(home)[keyOf(wake.agent.id, wake.room)];
|
|
44
|
+
if (known && existsSync(known.cwd))
|
|
45
|
+
return known;
|
|
46
|
+
if (!cwd || !existsSync(cwd))
|
|
47
|
+
return null;
|
|
48
|
+
return { kind, session: startedSessionId(wake.agent.id, wake.room), cwd, resume: null };
|
|
49
|
+
}
|
|
50
|
+
/** What the started agent is told: the ask, and how to answer it with Station's tools. */
|
|
51
|
+
export function startPrompt(wake, relayUrl, started = true) {
|
|
52
|
+
const room = `${relayUrl}/${wake.room}`;
|
|
53
|
+
return [
|
|
54
|
+
`${started ? `Station started you, ${wake.agent.name}, to answer` : "Station has"} an ask ${started ? "" : "for you "}in the room ${wake.room_title ? `"${wake.room_title}" ` : ""}(${room}). Use Station's tools with room ${room}, whatever room you were in before.`,
|
|
55
|
+
`1. Take the ask: call mutate with action "ask.take", room ${room}, and args {"message": ${wake.message}}. If it says another agent has it, stop.`,
|
|
56
|
+
`2. Do what it asks, in this folder.`,
|
|
57
|
+
`3. Answer in its thread: call send with room ${room}, reply_to ${wake.thread}, and a short answer.`,
|
|
58
|
+
`4. Mark it done: call mutate with action "ask.done", room ${room}, and args {"message": ${wake.message}, "result": <the id of your answer>}.`,
|
|
59
|
+
...(started ? ["Then stop. Station starts you again when the next ask comes for you."] : []),
|
|
60
|
+
"",
|
|
61
|
+
// Station starts an agent only for an ask from its own person or one of their agents (the relay's wake.ts).
|
|
62
|
+
`The ask, from ${wake.from}, for the person you work for (message ${wake.message}):`,
|
|
63
|
+
wake.text,
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
66
|
+
const toml = (value) => JSON.stringify(value);
|
|
67
|
+
/** `codex exec` (or `codex exec resume <thread>`) with Station's tools. */
|
|
68
|
+
export function codexArgs(plan, server, prompt) {
|
|
69
|
+
const [command, ...args] = server.command;
|
|
70
|
+
const env = `{${Object.entries(server.env).map(([name, value]) => `${name}=${toml(value)}`).join(", ")}}`;
|
|
71
|
+
return [
|
|
72
|
+
"exec",
|
|
73
|
+
...(plan.resume ? ["resume"] : []),
|
|
74
|
+
"--json",
|
|
75
|
+
"--skip-git-repo-check",
|
|
76
|
+
"-c",
|
|
77
|
+
`mcp_servers.station.command=${toml(command)}`,
|
|
78
|
+
"-c",
|
|
79
|
+
`mcp_servers.station.args=[${args.map(toml).join(", ")}]`,
|
|
80
|
+
"-c",
|
|
81
|
+
`mcp_servers.station.env=${env}`,
|
|
82
|
+
// With no window, nobody can approve a tool call: Station's own tools need no approval.
|
|
83
|
+
"-c",
|
|
84
|
+
'mcp_servers.station.default_tools_approval_mode="approve"',
|
|
85
|
+
"-c",
|
|
86
|
+
'sandbox_mode="workspace-write"',
|
|
87
|
+
...(plan.resume ? [plan.resume] : []),
|
|
88
|
+
prompt,
|
|
89
|
+
];
|
|
90
|
+
}
|
|
91
|
+
/** `claude -p` in a session Station names, or resuming it, with Station's tools. */
|
|
92
|
+
export function claudeArgs(plan, server, prompt, sessionId) {
|
|
93
|
+
const [command, ...args] = server.command;
|
|
94
|
+
const config = { mcpServers: { station: { command, args, env: server.env } } };
|
|
95
|
+
return [
|
|
96
|
+
"-p",
|
|
97
|
+
...(plan.resume ? ["--resume", plan.resume] : ["--session-id", sessionId]),
|
|
98
|
+
"--output-format",
|
|
99
|
+
"json",
|
|
100
|
+
"--mcp-config",
|
|
101
|
+
JSON.stringify(config),
|
|
102
|
+
"--strict-mcp-config",
|
|
103
|
+
"--permission-mode",
|
|
104
|
+
"acceptEdits",
|
|
105
|
+
"--allowedTools",
|
|
106
|
+
"mcp__station",
|
|
107
|
+
prompt,
|
|
108
|
+
];
|
|
109
|
+
}
|
|
110
|
+
/** Starts the agent for the wake. `onStart` hears that it is running;
|
|
111
|
+
* the promise ends with the run. */
|
|
112
|
+
export function startAgent(plan, wake, relayUrl, server, options = {}) {
|
|
113
|
+
const env = options.env ?? process.env;
|
|
114
|
+
const log = options.log ?? (() => { });
|
|
115
|
+
const program = plan.kind === "codex" ? "codex" : "claude";
|
|
116
|
+
const executable = onPath(program, env);
|
|
117
|
+
if (!executable)
|
|
118
|
+
return Promise.resolve({ code: null, why: `${program} is not on this computer's PATH`, limit: null, resume: plan.resume });
|
|
119
|
+
const prompt = startPrompt(wake, relayUrl);
|
|
120
|
+
const claudeSession = plan.resume ?? randomUUID();
|
|
121
|
+
const args = plan.kind === "codex" ? codexArgs(plan, server, prompt) : claudeArgs(plan, server, prompt, claudeSession);
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
// Never a key from the daemon's environment: the agent uses its own sign-in.
|
|
124
|
+
const { ANTHROPIC_API_KEY: _key, ...rest } = env;
|
|
125
|
+
const child = spawn(executable, args, { cwd: plan.cwd, env: { ...rest, ...server.env }, stdio: ["ignore", "pipe", "pipe"] });
|
|
126
|
+
let resume = plan.kind === "claude-code" ? claudeSession : plan.resume;
|
|
127
|
+
let output = "";
|
|
128
|
+
let pending = "";
|
|
129
|
+
/** What the agent said last, for the daemon's log. */
|
|
130
|
+
let said = "";
|
|
131
|
+
child.stdout.on("data", (chunk) => {
|
|
132
|
+
const text = chunk.toString("utf8");
|
|
133
|
+
output = (output + text).slice(-4000);
|
|
134
|
+
if (plan.kind !== "codex")
|
|
135
|
+
return;
|
|
136
|
+
pending += text;
|
|
137
|
+
const lines = pending.split("\n");
|
|
138
|
+
pending = lines.pop() ?? "";
|
|
139
|
+
for (const line of lines) {
|
|
140
|
+
try {
|
|
141
|
+
const event = JSON.parse(line);
|
|
142
|
+
if (event.type === "thread.started" && event.thread_id)
|
|
143
|
+
resume = event.thread_id;
|
|
144
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message" && event.item.text)
|
|
145
|
+
said = event.item.text;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// not an event
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
child.stderr.on("data", (chunk) => {
|
|
153
|
+
output = (output + chunk.toString("utf8")).slice(-4000);
|
|
154
|
+
});
|
|
155
|
+
child.once("spawn", () => {
|
|
156
|
+
log(`started ${program} (pid ${child.pid}) in ${plan.cwd}${plan.resume ? `, resuming ${plan.resume}` : ""} for message ${wake.message}`);
|
|
157
|
+
options.onStart?.();
|
|
158
|
+
});
|
|
159
|
+
child.once("error", (error) => resolve({ code: null, why: `${program} did not start: ${error.message}`, limit: null, resume: plan.resume }));
|
|
160
|
+
child.once("close", (code) => {
|
|
161
|
+
const why = output.trim().split("\n").slice(-2).join(" | ").slice(0, 300);
|
|
162
|
+
if (plan.kind === "claude-code") {
|
|
163
|
+
try {
|
|
164
|
+
said = String(JSON.parse(output.trim().split("\n").pop() ?? "{}").result ?? "");
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// not the json result
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
log(`${program} (pid ${child.pid}) ended with code ${code}${code ? `: ${why}` : ""}${said ? `; it said: ${said.replace(/\s+/g, " ").slice(0, 300)}` : ""}`);
|
|
171
|
+
resolve({ code, why: code ? `${program} stopped with code ${code}${why ? `: ${why}` : ""}` : "", limit: fromMessage(output), resume });
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
}
|
package/dist/waking.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// The daemon's side of a local install: it asks the relay for wakes
|
|
2
|
+
// (GET /cli/wakes, which also tells the relay this computer's installs are
|
|
3
|
+
// on), and for each one reaches the agent here:
|
|
4
|
+
//
|
|
5
|
+
// - The agent's last chat on this computer (its newest Claude Code or Codex
|
|
6
|
+
// window, in any room) open: the ask goes into it, and the relay hears
|
|
7
|
+
// `started` (or `queued` while the chat is busy).
|
|
8
|
+
// - That chat closed: the ask continues the same chat in the background
|
|
9
|
+
// (codex exec resume, claude -p --resume), so the work is in it when the
|
|
10
|
+
// person opens it again, not in a hidden thread of its own.
|
|
11
|
+
// - The agent out of usage (limits.ts): the relay hears `out`, and hands
|
|
12
|
+
// the ask to another of the person's agents.
|
|
13
|
+
// - A session here that took an ask (the relay lists them with each read,
|
|
14
|
+
// as `held`) runs out of usage while it works: its files say so, and the
|
|
15
|
+
// relay hears it (POST /cli/limits), so the ask's sender reads `out` with
|
|
16
|
+
// the reset time. It hears again once the limit clears. Nothing is handed
|
|
17
|
+
// on from there.
|
|
18
|
+
// - Otherwise Station starts the agent with no window open (starts.ts),
|
|
19
|
+
// with a seat of its own in the room, and the relay hears `started`; a
|
|
20
|
+
// start that fails is `failed`, and the ask becomes unreachable.
|
|
21
|
+
//
|
|
22
|
+
// One run at a time for each agent in each room: a wake that comes while
|
|
23
|
+
// one runs waits for it.
|
|
24
|
+
import { rmSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
import { readCredentials, readJson, writeJson } from "./home.js";
|
|
27
|
+
import { agentLimit, describeLimit } from "./limits.js";
|
|
28
|
+
import { call, RelayError } from "./relay.js";
|
|
29
|
+
import { mcpCommand } from "./self.js";
|
|
30
|
+
import { delivers, deliverTo, isLocalKind, isRunning } from "./sessions.js";
|
|
31
|
+
import { folderOf, loadStarts, planFor, startPrompt, saveStart, startAgent, startedSessionId } from "./starts.js";
|
|
32
|
+
/** The newest session of the agent on this computer whose files say how
|
|
33
|
+
* much usage it has left, and the folder it worked in. */
|
|
34
|
+
function lastSession(seats, agent, room) {
|
|
35
|
+
const mine = seats.filter((seat) => seat.agentId === agent && seat.cwd).sort((a, b) => b.joinedAt.localeCompare(a.joinedAt));
|
|
36
|
+
return (room ? mine.find((seat) => seat.roomId === room) : null) ?? mine[0] ?? null;
|
|
37
|
+
}
|
|
38
|
+
/** This computer's secret for one of its installs, kept in installs.json
|
|
39
|
+
* (asked for from the relay the first time), traded for an hour's sign-in
|
|
40
|
+
* as the install's agent. */
|
|
41
|
+
export async function installSignIn(home, credentials, install) {
|
|
42
|
+
const path = join(home, "installs.json");
|
|
43
|
+
const secrets = readJson(path, {});
|
|
44
|
+
const trade = (secret) => call(credentials.relayUrl, "/installs/token", null, { body: { secret } });
|
|
45
|
+
if (secrets[install]) {
|
|
46
|
+
try {
|
|
47
|
+
return await trade(secrets[install]);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (!(error instanceof RelayError && error.status === 401))
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const { secret } = await call(credentials.relayUrl, `/cli/installs/${install}/secret`, { token: credentials.token }, { method: "POST" });
|
|
55
|
+
writeJson(path, { ...readJson(path, {}), [install]: secret });
|
|
56
|
+
return trade(secret);
|
|
57
|
+
}
|
|
58
|
+
/** The agent's last chat on this computer: the newest Claude Code or Codex
|
|
59
|
+
* window session it had, in any room, open now or not. */
|
|
60
|
+
export function lastChat(seats, agent) {
|
|
61
|
+
return seats.filter((seat) => seat.agentId === agent && (seat.harness === "claude-code" || seat.harness === "codex")).sort((a, b) => b.joinedAt.localeCompare(a.joinedAt))[0] ?? null;
|
|
62
|
+
}
|
|
63
|
+
export function createWaking(deps) {
|
|
64
|
+
const { home, log } = deps;
|
|
65
|
+
const start = deps.start ?? startAgent;
|
|
66
|
+
const limitOf = deps.limitOf ?? ((harness, id) => agentLimit(harness, id));
|
|
67
|
+
const deliver = deps.deliver ?? deliverTo;
|
|
68
|
+
const isOpen = deps.isOpen ?? ((seat) => delivers(seat.harness) && isRunning(seat.harness, seat.sessionId));
|
|
69
|
+
const sleep = deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
70
|
+
/** Runs under way, by agent and room. */
|
|
71
|
+
const runs = new Map();
|
|
72
|
+
/** The asks being started or waiting to be, by agent, room and message. */
|
|
73
|
+
const asks = new Set();
|
|
74
|
+
let installsOn = false;
|
|
75
|
+
let stopped = false;
|
|
76
|
+
/** What the relay last heard about each seat that holds an ask: out, and why, or null. */
|
|
77
|
+
const toldOut = new Map();
|
|
78
|
+
/** Reads the files of each session here that holds an ask, and tells the
|
|
79
|
+
* relay when one runs out of usage or its limit clears. */
|
|
80
|
+
async function watchHeld(credentials, held) {
|
|
81
|
+
const seats = deps.seats();
|
|
82
|
+
for (const key of [...toldOut.keys()])
|
|
83
|
+
if (!held.some((one) => one.seat === key))
|
|
84
|
+
toldOut.delete(key);
|
|
85
|
+
for (const one of held) {
|
|
86
|
+
const session = seats.find((seat) => seat.participantId === one.seat);
|
|
87
|
+
if (!session || (session.harness !== "claude-code" && session.harness !== "codex"))
|
|
88
|
+
continue;
|
|
89
|
+
const limit = limitOf(session.harness, session.sessionId);
|
|
90
|
+
const out = limit?.state === "out" && !limit.switchModel ? describeLimit(session.harness, limit) : null;
|
|
91
|
+
// Said once per change. A seat not heard about yet (a daemon that just
|
|
92
|
+
// started) is said either way, so a limit that cleared meanwhile clears.
|
|
93
|
+
if (toldOut.has(one.seat) && toldOut.get(one.seat) === out)
|
|
94
|
+
continue;
|
|
95
|
+
try {
|
|
96
|
+
await call(credentials.relayUrl, "/cli/limits", { token: credentials.token }, { body: { seat: one.seat, out } });
|
|
97
|
+
toldOut.set(one.seat, out);
|
|
98
|
+
if (out)
|
|
99
|
+
log(`seat ${one.seat} holds message ${one.messages.join(", ")}: ${out}`);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
log(`limit for seat ${one.seat} not sent: ${error instanceof Error ? error.message : String(error)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const answer = (credentials, wake, outcome, why) => call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { body: { room: wake.room, message: wake.message, agent: wake.agent.id, outcome, ...(why ? { why } : {}) } }).catch((error) => log(`wake ${wake.message} answer ${outcome} not sent: ${error instanceof Error ? error.message : String(error)}`));
|
|
107
|
+
/** Out of usage, by the agent's newest session here, or the room's earlier start. */
|
|
108
|
+
function outOfUsage(kind, wake) {
|
|
109
|
+
const sessions = [];
|
|
110
|
+
const known = loadStarts(home)[`${wake.agent.id}:${wake.room}`];
|
|
111
|
+
if (known?.resume)
|
|
112
|
+
sessions.push([kind, known.resume]);
|
|
113
|
+
const last = lastSession(deps.seats(), wake.agent.id);
|
|
114
|
+
if (last && last.harness !== "shell")
|
|
115
|
+
sessions.push([last.harness, last.sessionId]);
|
|
116
|
+
for (const [harness, id] of sessions) {
|
|
117
|
+
const limit = limitOf(harness, id);
|
|
118
|
+
if (limit?.state === "out" && !limit.switchModel)
|
|
119
|
+
return describeLimit(harness, limit);
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
async function run(credentials, wake, kind, last = null) {
|
|
124
|
+
const out = outOfUsage(kind, wake);
|
|
125
|
+
if (out) {
|
|
126
|
+
log(`wake ${wake.message}: ${out}`);
|
|
127
|
+
await answer(credentials, wake, "out", out.replace(/\.$/, ""));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
// The agent's last chat, closed: the ask continues that same chat in the
|
|
131
|
+
// background, so it is there when the person opens it. Else a run of its own.
|
|
132
|
+
const folder = last?.cwd ?? folderOf(home, wake.agent.id);
|
|
133
|
+
const fresh = last && folder ? null : planFor(home, wake, kind, lastSession(deps.seats(), wake.agent.id, wake.room)?.cwd ?? folderOf(home, wake.agent.id));
|
|
134
|
+
// One agent, one presence in a room: a run of its own acts as the agent's
|
|
135
|
+
// seat there that no session holds now (a codex exec that ended, a closed
|
|
136
|
+
// window), so it takes that seat back rather than a second one.
|
|
137
|
+
const there = fresh ? deps.seats().find((seat) => seat.agentId === wake.agent.id && seat.roomId === wake.room && !isOpen(seat) && seat.sessionId !== fresh.session) : undefined;
|
|
138
|
+
const plan = last && folder ? { kind, session: last.sessionId, cwd: folder, resume: last.sessionId } : fresh && there ? { ...fresh, session: there.sessionId } : fresh;
|
|
139
|
+
if (!plan) {
|
|
140
|
+
await answer(credentials, wake, "failed", `Station knows no folder on this computer to start ${wake.agent.name} in. Run station add ${kind === "codex" ? "codex" : "claude"} in the folder it should work in`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
let seat;
|
|
144
|
+
try {
|
|
145
|
+
seat = await deps.join({ harness: "shell", id: plan.session, cwd: plan.cwd, name: null, why: null, host: kind }, `${credentials.relayUrl}/${wake.room}`);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
await answer(credentials, wake, "failed", `${wake.agent.name} could not take a seat in the room: ${error instanceof Error ? error.message : String(error)}`);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// The started agent signs in as itself, with an hour's sign-in its install's secret bought (decision A).
|
|
152
|
+
let signIn;
|
|
153
|
+
try {
|
|
154
|
+
signIn = await (deps.signIn ?? installSignIn)(home, credentials, wake.install);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
deps.leave(seat);
|
|
158
|
+
await answer(credentials, wake, "failed", `${wake.agent.name} could not sign in to Station: ${error instanceof Error ? error.message : String(error)}`);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// In a file only this user reads, never in the agent's command line, which anyone here can list.
|
|
162
|
+
const tokenFile = join(home, `sign-in-${plan.session}`);
|
|
163
|
+
writeFileSync(tokenFile, signIn.token, { mode: 0o600 });
|
|
164
|
+
const server = {
|
|
165
|
+
command: mcpCommand(),
|
|
166
|
+
env: {
|
|
167
|
+
STATION_STARTED: `${kind}:${plan.session}`,
|
|
168
|
+
STATION_AGENT_TOKEN_FILE: tokenFile,
|
|
169
|
+
STATION_AGENT_NAME: wake.agent.name,
|
|
170
|
+
STATION_RELAY_URL: credentials.relayUrl,
|
|
171
|
+
...(process.env.STATION_HOME ? { STATION_HOME: process.env.STATION_HOME } : {}),
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
let told = false;
|
|
175
|
+
const end = await start(plan, wake, credentials.relayUrl, server, {
|
|
176
|
+
log,
|
|
177
|
+
onStart: () => {
|
|
178
|
+
told = true;
|
|
179
|
+
void answer(credentials, wake, "started");
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
rmSync(tokenFile, { force: true });
|
|
183
|
+
deps.leave(seat);
|
|
184
|
+
if (end.code === 0) {
|
|
185
|
+
if (!last)
|
|
186
|
+
saveStart(home, wake.agent.id, wake.room, { ...plan, resume: end.resume });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
// A thread Codex cannot resume any more: the next start is a new one.
|
|
190
|
+
if (plan.resume && /no (?:rollout|session|thread|conversation)|not found/i.test(end.why))
|
|
191
|
+
saveStart(home, wake.agent.id, wake.room, { ...plan, resume: null });
|
|
192
|
+
if (end.limit?.state === "out")
|
|
193
|
+
await answer(credentials, wake, "out", describeLimit(kind, end.limit).replace(/\.$/, ""));
|
|
194
|
+
else
|
|
195
|
+
await answer(credentials, wake, "failed", end.why || `${wake.agent.name} stopped before it answered`);
|
|
196
|
+
if (!told)
|
|
197
|
+
log(`wake ${wake.message}: ${end.why}`);
|
|
198
|
+
}
|
|
199
|
+
async function handle(credentials, wake) {
|
|
200
|
+
const kind = wake.agent.kind;
|
|
201
|
+
if (!isLocalKind(kind)) {
|
|
202
|
+
await answer(credentials, wake, "failed", `this computer cannot start ${wake.agent.name}`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
// The agent's last chat here: its newest Claude Code or Codex window, in any room.
|
|
206
|
+
const last = lastChat(deps.seats(), wake.agent.id);
|
|
207
|
+
const key = `${wake.agent.id}:${last ? last.sessionId : wake.room}`;
|
|
208
|
+
// One run per ask, however often it is handed out.
|
|
209
|
+
const ask = `${wake.agent.id}:${wake.room}:${wake.message}`;
|
|
210
|
+
if (asks.has(ask))
|
|
211
|
+
return;
|
|
212
|
+
asks.add(ask);
|
|
213
|
+
try {
|
|
214
|
+
// Its window is open: the ask goes into that chat, once it can take a turn.
|
|
215
|
+
if (last && isOpen(last) && (await intoWindow(credentials, wake, last)))
|
|
216
|
+
return;
|
|
217
|
+
// Someone else's ask: Station starts the agent only for its own person.
|
|
218
|
+
if (wake.may_start === false) {
|
|
219
|
+
await answer(credentials, wake, "failed", `Station starts ${wake.agent.name} only for asks from its own person or their agents, and no window of it is open here`);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const before = runs.get(key);
|
|
223
|
+
// A run of that chat is under way: this ask goes in when it ends.
|
|
224
|
+
if (before)
|
|
225
|
+
await answer(credentials, wake, "queued");
|
|
226
|
+
const next = (before ?? Promise.resolve()).then(() => run(credentials, wake, kind, last)).catch((error) => log(`wake ${wake.message} failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
227
|
+
runs.set(key, next);
|
|
228
|
+
await next;
|
|
229
|
+
if (runs.get(key) === next)
|
|
230
|
+
runs.delete(key);
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
asks.delete(ask);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** Puts the ask into the agent's open chat, waiting while it is busy.
|
|
237
|
+
* False when the chat closed meanwhile: the ask then continues it in the background. */
|
|
238
|
+
async function intoWindow(credentials, wake, chat) {
|
|
239
|
+
let told = false;
|
|
240
|
+
for (let attempt = 0; attempt < 120 && isOpen(chat); attempt++) {
|
|
241
|
+
const outcome = await deliver(chat.harness, chat.sessionId, `station-ask-${wake.room}-${wake.message}`, startPrompt(wake, credentials.relayUrl, false));
|
|
242
|
+
if (outcome.kind !== "retry") {
|
|
243
|
+
log(`wake ${wake.message}: put into ${wake.agent.name}'s open chat ${chat.sessionId}`);
|
|
244
|
+
await answer(credentials, wake, "started");
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
if (!told) {
|
|
248
|
+
told = true;
|
|
249
|
+
await answer(credentials, wake, "queued");
|
|
250
|
+
}
|
|
251
|
+
await sleep(15_000);
|
|
252
|
+
}
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
/** Whether any install on this computer is on: the daemon stays up for it. */
|
|
257
|
+
installsOn: () => installsOn,
|
|
258
|
+
running: () => runs.size > 0,
|
|
259
|
+
/** One read of the relay's wakes. */
|
|
260
|
+
async once(waitSeconds = 25) {
|
|
261
|
+
const credentials = readCredentials(home);
|
|
262
|
+
if (!credentials)
|
|
263
|
+
return null;
|
|
264
|
+
const got = await call(credentials.relayUrl, `/cli/wakes?wait=${waitSeconds}`, { token: credentials.token });
|
|
265
|
+
installsOn = got.installs.some((install) => install.on);
|
|
266
|
+
for (const wake of got.wakes) {
|
|
267
|
+
log(`wake for ${wake.agent.name} in room ${wake.room}, message ${wake.message}`);
|
|
268
|
+
void handle(credentials, wake);
|
|
269
|
+
}
|
|
270
|
+
await watchHeld(credentials, got.held ?? []);
|
|
271
|
+
return got;
|
|
272
|
+
},
|
|
273
|
+
/** Reads wakes until stopped. A computer that is not signed in has no installs. */
|
|
274
|
+
async loop() {
|
|
275
|
+
while (!stopped) {
|
|
276
|
+
try {
|
|
277
|
+
const got = await this.once();
|
|
278
|
+
if (!got)
|
|
279
|
+
await sleep(30_000);
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
log(`wakes not read: ${error instanceof Error ? error.message : String(error)}`);
|
|
283
|
+
await sleep(15_000);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
stop() {
|
|
288
|
+
stopped = true;
|
|
289
|
+
},
|
|
290
|
+
handle,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
export { startedSessionId };
|
package/dist/webhooks.js
CHANGED
|
@@ -77,12 +77,12 @@ export function webhookLines(hooks) {
|
|
|
77
77
|
const header = h.header ? `, header ${h.header.name}: ${h.header.value}` : "";
|
|
78
78
|
const debounce = h.debounce_seconds ? `, debounce ${h.debounce_seconds}s` : "";
|
|
79
79
|
const wakes = h.wakes_per_day ? `, ${h.wakes_today ?? 0} of ${h.wakes_per_day} wakes today` : "";
|
|
80
|
-
return `${h.id} ${h.agent ?? h.participant_id} → ${h.url} on ${h.on.join(",")}${debounce}${wakes}${header}; ${last}`;
|
|
80
|
+
return `${h.id} ${h.agent ?? h.participant_id} → ${h.url} on ${h.on.join(",")}${debounce}${wakes}${header}${h.signed ? ", signed" : ""}; ${last}`;
|
|
81
81
|
});
|
|
82
82
|
}
|
|
83
83
|
export async function webhookCommand(credentials, args, flag, out, me) {
|
|
84
84
|
const [sub, room, id] = args;
|
|
85
|
-
const usage = `${me} webhook add <room> --url <https url> [--agent "<name>"] [--header-name Authorization] [--on message,approval,asked] [--debounce 30] [--wakes-per-day 60]
|
|
85
|
+
const usage = `${me} webhook add <room> --url <https url> [--agent "<name>"] [--header-name Authorization] [--sign] [--on message,approval,asked] [--debounce 30] [--wakes-per-day 60]
|
|
86
86
|
${me} webhook list <room>
|
|
87
87
|
${me} webhook test <room> <webhook id>
|
|
88
88
|
${me} webhook remove <room> <webhook id>`;
|
|
@@ -109,9 +109,21 @@ ${me} webhook remove <room> <webhook id>`;
|
|
|
109
109
|
}
|
|
110
110
|
const debounce = flag("debounce");
|
|
111
111
|
const wakes = flag("wakes-per-day");
|
|
112
|
-
const
|
|
113
|
-
|
|
112
|
+
const sign = flag("sign");
|
|
113
|
+
if (sign !== undefined && sign !== "true" && sign !== "false")
|
|
114
|
+
throw new Usage("Use --sign to generate a signing secret.");
|
|
115
|
+
const { webhook, signing_secret } = await call(relayUrl, base, auth, {
|
|
116
|
+
body: { participant: agent.id, url, header, sign: sign === "true" ? true : undefined, on: flag("on")?.split(","), debounce_seconds: debounce === undefined ? undefined : Number(debounce.replace(/s$/, "")), wakes_per_day: wakes === undefined ? undefined : Number(wakes) },
|
|
114
117
|
});
|
|
118
|
+
if (sign === "true") {
|
|
119
|
+
if (!signing_secret) {
|
|
120
|
+
await call(relayUrl, `${base}/${webhook.id}`, auth, { method: "DELETE" });
|
|
121
|
+
throw new Error("The relay did not return a signing secret. Try again on a relay that supports signing.");
|
|
122
|
+
}
|
|
123
|
+
out(`Signing secret (shown once): ${signing_secret}`);
|
|
124
|
+
out(`Set this secret on the receiver, then run: ${me} webhook test ${roomId} ${webhook.id}`);
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
115
127
|
// Send the test now, so the person learns here whether the key works. A
|
|
116
128
|
// webhook the receiver refuses is removed: it would only fail on every wake.
|
|
117
129
|
const result = await call(relayUrl, `${base}/${webhook.id}/test`, auth, { body: {} });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@santori/station",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.9",
|
|
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",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"README.md"
|
|
27
27
|
],
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": ">=
|
|
29
|
+
"node": ">=20"
|
|
30
30
|
},
|
|
31
31
|
"publishConfig": {
|
|
32
32
|
"access": "public"
|