Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions docs/development.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions spec/Outbox.tla
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
(* send ID. (Slack: the adapter reads the channel history.) *)
(* - One call at a time per send ID (one tool call). A second concurrent *)
(* call fails on the primary key of gw_outbox and sends nothing. *)
(* - A send ID has one place. A call again with a send ID that gw_outbox *)
(* has, also from a script with another text and destination, sends the *)
(* first call's text to its destination, in that place's line. *)
(* - The sends come in the order of the calls, also when pi-durable runs *)
(* the unfinished ones again after a crash: it starts the tool calls of *)
(* an answer in call order, and resumes unfinished tasks in that order. *)
Expand Down
67 changes: 47 additions & 20 deletions src/bot/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type { Address, ChannelAdapter, ChannelConfig } from "../core/channel.ts"
import { MEMORY_DIR, POTS_HOME, SECRETS_DIR } from "../core/home.ts";
import { carriesOn, endedBy, type OutageLines, outageLines, waitingLine } from "../core/outage.ts";
import { KnownSecrets } from "../core/secrets.ts";
import { addMissingColumns } from "../core/sql.ts";
import { VERSION } from "../core/version.ts";
import type { Judge } from "../core/judge.ts";
import { formatTime } from "../core/time.ts";
Expand Down Expand Up @@ -98,10 +99,13 @@ CREATE TABLE IF NOT EXISTS bot_working (
`;

/** Columns added to tables of an earlier version. */
/** The crash and hold files of a bot folder work only in the tests, whose gateways have this set. */
const CRASH_TESTS = process.env.POTS_TEST_CRASH_FILES === "1";

const ADDED_COLUMNS = [
{ table: "bot_wakes", column: "at_address", type: "TEXT" },
{ table: "bot_wakes", column: "waited", type: "INTEGER NOT NULL DEFAULT 0" },
{ table: "bot_working", column: "event_at", type: "INTEGER NOT NULL DEFAULT 0" },
["bot_wakes", "at_address", "TEXT"],
["bot_wakes", "waited", "INTEGER NOT NULL DEFAULT 0"],
["bot_working", "event_at", "INTEGER NOT NULL DEFAULT 0"],
] as const;

/** The typing people wait to see for one submission. */
Expand Down Expand Up @@ -151,6 +155,16 @@ const WORKING_RESPOND = 0.8;
* its button, menu, command or form, or what the judge found it should very likely answer. A steer is judged by the
* same rules, without the judge, which does not see it.
*/
/** The model and thinking level of a definition, as one string to compare. */
function liveModel(definition: BotDefinition): string {
return JSON.stringify([definition.model, definition.thinking]);
}

/** A channel's settings with the bot's name, which its adapter takes too, as one string to compare. */
function liveChannel(channel: ChannelConfig, botName: string): string {
return JSON.stringify([botName, channel]);
}

function waitedOn(wake: PlaceWake): WakeEvent | undefined {
const answers = (event: WakeEvent) => ANSWER_KINDS.has(event.kind);
switch (wake.reason) {
Expand All @@ -177,6 +191,8 @@ export class Bot implements WakeTarget {
readonly id: string;
readonly paths: BotPaths;
#definition: BotDefinition;
/** What runs now: the model and each channel's settings. After an apply that failed, it may differ from the definition. */
readonly #live: { model?: string; channels: Map<string, string> };
readonly #env: BotEnvironment;
readonly #print: Print;
readonly #sql: Database;
Expand Down Expand Up @@ -249,6 +265,10 @@ export class Bot implements WakeTarget {
this.id = init.id;
this.paths = init.paths;
this.#definition = init.definition;
this.#live = {
model: liveModel(init.definition),
channels: new Map(init.definition.channels.map((channel) => [channel.id, liveChannel(channel, init.definition.name)])),
};
this.#env = init.env;
this.#print = init.print;
this.#sql = init.sql;
Expand Down Expand Up @@ -328,10 +348,7 @@ export class Bot implements WakeTarget {
opened: (agent: Agent) => void,
): Promise<Bot> {
await sql.exec(WAKES_SCHEMA);
for (const { table, column, type } of ADDED_COLUMNS) {
const columns = await sql.all<{ name: string }>(`PRAGMA table_info(${table})`);
if (!columns.some((each) => each.name === column)) await sql.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
}
await addMissingColumns(sql, ADDED_COLUMNS);
// The version whose prompt the conversation shows.
const shownVersion = (await sql.all<{ value: string }>("SELECT value FROM bot_state WHERE key = 'prompt_version'"))[0]?.value;

Expand Down Expand Up @@ -408,7 +425,7 @@ export class Bot implements WakeTarget {
login: { models: () => env.models, ...piLoginHelpers },
});
// Crash tests: between the steps of a password page's submission. The next start must finish the sequence.
Object.assign(pages.crashTests, secretCrashTests(paths.dir, print));
if (CRASH_TESTS) Object.assign(pages.crashTests, secretCrashTests(paths.dir, print));
// A person who had the screen through a desktop page before a stop keeps it, before any agent runs again.
await pages.desktop.holdScreens();
const machine = await MACHINE;
Expand Down Expand Up @@ -567,7 +584,7 @@ export class Bot implements WakeTarget {
bot = new Bot({ id, paths, definition, env, print, sql, gateway, timers, agent, pages, judge, notes, scopes, left });
// Crash tests: with one of these files in the bot folder, the process dies at that point, once.
const crashTest = (file: string, message: string, key: string) => (id: string) => {
if (!existsSync(file)) return;
if (!CRASH_TESTS || !existsSync(file)) return;
unlinkSync(file);
print(message, { [key]: id });
process.kill(process.pid, "SIGKILL");
Expand All @@ -586,7 +603,7 @@ export class Bot implements WakeTarget {
// Holds, each while its file is there: after a stop marked its children stopped, before their work ends; and in a
// child's start of a child, before it commits.
const hold = (file: string, message: string, key: string) => async (id: string) => {
if (!existsSync(file)) return;
if (!CRASH_TESTS || !existsSync(file)) return;
print(message, { [key]: id });
while (existsSync(file)) await new Promise((resolve) => setTimeout(resolve, 100));
};
Expand All @@ -595,7 +612,7 @@ export class Bot implements WakeTarget {
// After a child answered, before its reporter keeps the answer: held while the file is there, or until the reporter
// is aborted. A stop then must still keep the answer. A file with a child's ID holds only that child.
agent.crashTests.beforeChildKeep = async (child, signal) => {
if (!existsSync(paths.holdChildKeep)) return;
if (!CRASH_TESTS || !existsSync(paths.holdChildKeep)) return;
const only = (await readFile(paths.holdChildKeep, "utf8").catch(() => "")).trim();
if (only !== "" && only !== child) return;
print("crash test: holding the child's end", { child });
Expand Down Expand Up @@ -690,20 +707,30 @@ export class Bot implements WakeTarget {
this.#print("bot stopped");
}

/** Apply a changed bot.json while running. The new definition counts only once every step worked, so a retry redoes all. */
/**
* Apply a changed bot.json while running. It compares with what runs, not with the last definition, so after a step
* that failed the next apply redoes what is left, also with the definition that ran before.
*/
async applyDefinition(next: BotDefinition): Promise<void> {
const before = this.#definition;
const live = this.#live;
// Also for the children that have no model of their own: they use the main one.
if (before.model !== next.model || before.thinking !== next.thinking) await this.#agent.configure(next.model, next.thinking);
const old = new Map(before.channels.map((channel) => [channel.id, JSON.stringify(channel)]));
const fresh = new Map(next.channels.map((channel) => [channel.id, JSON.stringify(channel)]));
const nameChanged = before.name !== next.name;
for (const [channelId, config] of old) {
if (fresh.get(channelId) !== config || nameChanged) await this.#gateway.removeChannel(channelId);
if (live.model !== liveModel(next)) {
live.model = undefined;
await this.#agent.configure(next.model, next.thinking);
live.model = liveModel(next);
}
// A channel stops before its new adapter is made, which may read the state the old one saved as it stopped.
for (const [channelId, config] of live.channels) {
if (next.channels.some((channel) => channel.id === channelId && liveChannel(channel, next.name) === config)) continue;
live.channels.delete(channelId);
await this.#gateway.removeChannel(channelId);
}
for (const channel of next.channels) {
const running = this.#gateway.channels.some((adapter) => adapter.id === channel.id);
if (!running) await this.#gateway.addChannel(await this.#loadChannel(channel, next.name));
const config = liveChannel(channel, next.name);
if (live.channels.get(channel.id) === config) continue;
await this.#gateway.addChannel(await this.#loadChannel(channel, next.name));
live.channels.set(channel.id, config);
}
this.#definition = next;
if (before.judge !== next.judge) this.#judge = createJudge(next.judge, this.#env.models, () => this.#definition.model);
Expand Down
8 changes: 5 additions & 3 deletions src/cli/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,18 +403,20 @@ export const restarted = (before: BeforeRestart) =>
Effect.gen(function* () {
const deadline = Date.now() + RESTART_WAIT_MS;
const logs = "pots service logs";
let pid = runningGateway();
// Each process ID's command line is read once while this waits.
const checked = new Map<number, boolean>();
let pid = runningGateway(checked);
while (pid === undefined || pid === before.pid) {
if (Date.now() > deadline) return yield* Effect.fail(userError(`the gateway of ${POTS_HOME} did not start again within ${RESTART_WAIT_MS / 1000} seconds; see ${logs}`));
yield* Effect.sleep("500 millis");
pid = runningGateway();
pid = runningGateway(checked);
}
const bots = listBots();
let running = new Map<string, string | undefined>();
let failed = new Map<string, string>();
for (;;) {
// A gateway that ended while it started, and was started again by the service: what the first one said is gone.
const now = runningGateway();
const now = runningGateway(checked);
if (now !== undefined && now !== pid) {
pid = now;
running = new Map();
Expand Down
20 changes: 17 additions & 3 deletions src/core/env-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,32 @@ export const CLAIM_LINE = "# pots-secret-claim: ";
/**
* Set KEY=value lines in a file readable only by this user: keys already there are replaced, other lines are kept.
* Written whole: to a part file next to it first, then renamed, so a crash leaves the old file or the new one. With a
* claim, a comment line names it, in place of an earlier one, in the same write; readers skip comment lines.
* claim, a comment line names it in the same write; readers skip comment lines. The lines of other claims stay: another
* submission may not have recorded its outcome yet, and removes its own line once it has (removeClaim).
*/
export function writeSecrets(path: string, values: Record<string, string>, claim?: string): void {
const file = expandHome(path);
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
const lines = existsSync(file) ? readFileSync(file, "utf8").split("\n").filter((line) => line.trim()) : [];
const kept = lines.filter((line) => {
if (claim !== undefined && line.startsWith(CLAIM_LINE)) return false;
const key = /^\s*(?:export\s+)?([A-Za-z0-9_]+)\s*=/.exec(line)?.[1];
return !(key && key in values);
});
const text = [...kept, ...Object.entries(values).map(([key, value]) => `${key}=${value}`), ...(claim === undefined ? [] : [`${CLAIM_LINE}${claim}`])].join("\n");
writeWhole(file, [...kept, ...Object.entries(values).map(([key, value]) => `${key}=${value}`), ...(claim === undefined ? [] : [`${CLAIM_LINE}${claim}`])]);
}

/** Take a claim's comment line out of a file that writeSecrets wrote, once the claim's outcome is recorded. */
export function removeClaim(path: string, claim: string): void {
const file = expandHome(path);
if (!existsSync(file)) return;
const lines = readFileSync(file, "utf8").split("\n").filter((line) => line.trim());
const kept = lines.filter((line) => line !== `${CLAIM_LINE}${claim}`);
if (kept.length < lines.length) writeWhole(file, kept);
}

/** Write a file whole and readable only by this user: to a part file next to it, then renamed. */
function writeWhole(file: string, lines: readonly string[]): void {
const text = lines.join("\n");
const part = `${file}.${randomBytes(6).toString("hex")}.part`;
try {
writeFileSync(part, `${text}\n`, { mode: 0o600 });
Expand Down
64 changes: 61 additions & 3 deletions src/core/home.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
Expand All @@ -19,12 +20,69 @@ export const LOGS_DIR = join(POTS_HOME, "logs");
/** The process ID of the running gateway. There is at most one per POTS_HOME. */
export const PID_FILE = join(POTS_HOME, "gateway.pid");

/** The process ID in the pid file, when that process is still running. */
export function runningGateway(): number | undefined {
/**
* The process ID in the pid file, when that process is still running and is a gateway. After a crash, the file is left,
* and its process ID may be another program's by now. Checked holds the answers for process IDs checked before, for a
* caller that asks again and again; reading a command line on Windows starts PowerShell.
*/
export function runningGateway(checked?: Map<number, boolean>): number | undefined {
if (!existsSync(PID_FILE)) return undefined;
const pid = Number(readFileSync(PID_FILE, "utf8").trim());
if (!Number.isInteger(pid) || pid <= 0) return undefined;
return processRunning(pid) ? pid : undefined;
if (!processRunning(pid)) return undefined;
if (pid === process.pid) return pid;
let gateway = checked?.get(pid);
if (gateway === undefined) {
const args = commandLine(pid);
// A command line that cannot be read counts as a gateway's.
gateway = args === undefined || args.length === 0 || gatewayCommand(args);
checked?.set(pid, gateway);
}
return gateway ? pid : undefined;
}

/** The global options of the pots command that take a value in the next argument. */
const VALUE_OPTIONS = new Set(["--log-level", "--completions"]);

/**
* Whether a command line runs `pots start`: an argument that is the pots command (pots, pots.js, pots.ts or pots.cmd,
* as the bin, the package or the Windows shim), and then start as the first argument that is not an option. The bin
* without an extension counts only as a path, as node gets it: macOS's ps joins the arguments with spaces, so a text
* argument "pots start" of another program comes back as the two words.
*/
export function gatewayCommand(args: readonly string[]): boolean {
const entry = args.findIndex((arg) => {
const name = arg.split(/[\\/]/).pop()!;
return /^pots(?:\.[cm]?[jt]s|\.cmd)$/i.test(name) || (/^pots$/i.test(name) && name !== arg);
});
if (entry < 0) return false;
for (let i = entry + 1; i < args.length; i++) {
const arg = args[i]!;
if (!arg.startsWith("-")) return arg === "start";
if (VALUE_OPTIONS.has(arg)) i++;
}
return false;
}

/**
* A process's arguments, or undefined when they cannot be read. Linux keeps them apart; macOS's ps and Windows give one
* line, which is split at spaces outside double quotes.
*/
function commandLine(pid: number): string[] | undefined {
try {
if (process.platform === "linux") return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter(Boolean);
const line =
process.platform === "win32"
? execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine`], {
encoding: "utf8",
timeout: 15_000,
windowsHide: true,
})
: execFileSync("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: 5_000 });
return [...line.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]!);
} catch {
return undefined;
}
}

export function processRunning(pid: number): boolean {
Expand Down
13 changes: 13 additions & 0 deletions src/core/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,16 @@ export interface SqlExecutor {
}

export type SqlValue = null | number | bigint | string | Uint8Array;

/**
* Add the columns a table from an earlier version does not have yet. In a transaction: it holds the write lock from the
* check on, so two processes that open the same file do not both add a column.
*/
export function addMissingColumns(sql: Sql, columns: readonly (readonly [table: string, column: string, type: string])[]): Promise<void> {
return sql.transaction(async (tx) => {
for (const [table, column, type] of columns) {
const names = new Set((await tx.all<{ name: string }>(`PRAGMA table_info(${table})`)).map((each) => each.name));
if (!names.has(column)) await tx.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
}
});
}
3 changes: 2 additions & 1 deletion src/gateway/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ export interface InboxRow {
export interface OutboxRecord {
send_id: string;
to_address: string;
text: string;
state: string;
message: string | null;
created_at: number;
Expand Down Expand Up @@ -457,7 +458,7 @@ function makeLog(sql: Sql): MessageLog["Service"] {
return new Map(rows.map((row) => [row.address, row.name]));
}),

outbox: (sendId) => db(() => sql.get<OutboxRecord>("SELECT send_id, to_address, state, message, created_at FROM gw_outbox WHERE send_id = ?", sendId)),
outbox: (sendId) => db(() => sql.get<OutboxRecord>("SELECT send_id, to_address, text, state, message, created_at FROM gw_outbox WHERE send_id = ?", sendId)),

outboxStart: (sendId, to, text) =>
dbAt((now) => sql.run("INSERT INTO gw_outbox (send_id, to_address, text, state, created_at) VALUES (?, ?, ?, 'sending', ?)", sendId, to, text, now)),
Expand Down
Loading
Loading