@thurstonsand/pi-agent-switchboard 0.0.0-stage → 0.1.0

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/index.js +286 -0
  3. package/package.json +22 -5
  4. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thurston Sandberg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.js ADDED
@@ -0,0 +1,286 @@
1
+ // packages/shared/src/index.ts
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname as dirname2, join } from "node:path";
5
+
6
+ // packages/shared/src/db.ts
7
+ import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
8
+ import { createRequire } from "node:module";
9
+ import { dirname } from "node:path";
10
+ var require2 = createRequire(import.meta.url);
11
+ function connect(path) {
12
+ if (process.versions.bun) {
13
+ const { Database } = require2("bun:sqlite");
14
+ return new Database(path, { strict: false });
15
+ }
16
+ const { DatabaseSync } = require2("node:sqlite");
17
+ return new DatabaseSync(path);
18
+ }
19
+
20
+ class Db {
21
+ path;
22
+ #driver;
23
+ constructor(path, { create }) {
24
+ this.path = path;
25
+ if (create) {
26
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
27
+ closeSync(openSync(path, "a", 384));
28
+ } else if (!existsSync(path)) {
29
+ throw new Error(`no db at ${path}`);
30
+ }
31
+ this.#driver = connect(path);
32
+ this.#driver.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;");
33
+ }
34
+ get(sql, ...params) {
35
+ return this.#driver.prepare(sql).get(...params) ?? undefined;
36
+ }
37
+ all(sql, ...params) {
38
+ return this.#driver.prepare(sql).all(...params);
39
+ }
40
+ run(sql, ...params) {
41
+ this.#driver.prepare(sql).run(...params);
42
+ }
43
+ exec(sql) {
44
+ this.#driver.exec(sql);
45
+ }
46
+ userVersion() {
47
+ return Number(this.get("PRAGMA user_version")?.user_version);
48
+ }
49
+ dataVersion() {
50
+ return Number(this.get("PRAGMA data_version")?.data_version);
51
+ }
52
+ tx(body) {
53
+ this.#driver.exec("BEGIN IMMEDIATE");
54
+ try {
55
+ const result = body();
56
+ this.#driver.exec("COMMIT");
57
+ return result;
58
+ } catch (error) {
59
+ this.#driver.exec("ROLLBACK");
60
+ throw error;
61
+ }
62
+ }
63
+ close() {
64
+ this.#driver.close();
65
+ }
66
+ }
67
+
68
+ // packages/shared/src/index.ts
69
+ var SCHEMA_VERSION = 1;
70
+ function bootId() {
71
+ if (process.platform === "darwin")
72
+ return execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf8" }).trim();
73
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
74
+ }
75
+ function pidAlive(pid) {
76
+ try {
77
+ process.kill(pid, 0);
78
+ return true;
79
+ } catch (error) {
80
+ return error.code === "EPERM";
81
+ }
82
+ }
83
+ function git(cwd, ...args) {
84
+ try {
85
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ function projectRoot(cwd) {
91
+ const common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
92
+ return common ? dirname2(common) : cwd;
93
+ }
94
+ function branch(cwd) {
95
+ const name = git(cwd, "rev-parse", "--abbrev-ref", "HEAD");
96
+ return name === "HEAD" ? git(cwd, "rev-parse", "--short", "HEAD") : name;
97
+ }
98
+
99
+ // packages/pi/src/index.ts
100
+ import { Type } from "typebox";
101
+ var KEY = Symbol.for("agent-switchboard.recorder");
102
+ var store = globalThis;
103
+ function claim() {
104
+ const env = process.env;
105
+ if (env.SWB_MANAGED === "1" && env.SWB_DB && env.SWB_TMUX_SESSION) {
106
+ store[KEY] = { launch: Object.freeze({ db: env.SWB_DB, tmuxSession: env.SWB_TMUX_SESSION }), attention: new Set };
107
+ }
108
+ delete env.SWB_MANAGED;
109
+ delete env.SWB_DB;
110
+ delete env.SWB_TMUX_SESSION;
111
+ return store[KEY];
112
+ }
113
+ function liveHost(row) {
114
+ if (row && row.boot_id === bootId() && pidAlive(row.pid))
115
+ return row.tmux_session;
116
+ return;
117
+ }
118
+ function hostOfSession(db, proc, sessionId) {
119
+ return liveHost(db.get("SELECT tmux_session, boot_id, pid FROM runtimes WHERE session_id = ? AND tmux_session != ?", sessionId, proc.launch.tmuxSession));
120
+ }
121
+ function hostOfTranscript(db, proc, transcript) {
122
+ return liveHost(db.get("SELECT r.tmux_session, r.boot_id, r.pid FROM runtimes r JOIN sessions s USING (session_id) WHERE s.transcript = ? AND r.tmux_session != ?", transcript, proc.launch.tmuxSession));
123
+ }
124
+ function src_default(pi) {
125
+ const claimed = claim();
126
+ if (!claimed)
127
+ return;
128
+ const proc = claimed;
129
+ let ui;
130
+ const showFailure = () => ui?.setStatus("swb", ui.theme.fg("error", `swb: not recording: ${proc.failure}`));
131
+ const connect = () => {
132
+ proc.db ??= new Db(proc.launch.db, { create: false });
133
+ return proc.db;
134
+ };
135
+ const fail = (error) => {
136
+ proc.failure = error instanceof Error ? error.message : String(error);
137
+ showFailure();
138
+ ui?.notify(`swb: not recording: ${proc.failure}`, "error");
139
+ };
140
+ const write = (sessionId, body) => {
141
+ if (proc.failure) {
142
+ showFailure();
143
+ return;
144
+ }
145
+ try {
146
+ const db = connect();
147
+ db.tx(() => {
148
+ const version = db.userVersion();
149
+ if (version !== SCHEMA_VERSION)
150
+ throw new Error(`db schema is v${version}, this recorder writes v${SCHEMA_VERSION}`);
151
+ body(db, sessionId);
152
+ });
153
+ } catch (error) {
154
+ fail(error);
155
+ }
156
+ };
157
+ const writeFor = (ctx, body) => {
158
+ ui = ctx.ui;
159
+ write(ctx.sessionManager.getSessionId(), body);
160
+ };
161
+ let current;
162
+ pi.on("session_before_switch", (event, ctx) => {
163
+ if (event.reason !== "resume" || !event.targetSessionFile || proc.failure)
164
+ return;
165
+ ui = ctx.ui;
166
+ let host;
167
+ try {
168
+ host = hostOfTranscript(connect(), proc, event.targetSessionFile);
169
+ } catch (error) {
170
+ fail(error);
171
+ return;
172
+ }
173
+ if (!host)
174
+ return;
175
+ ctx.ui.notify(`swb: that session is already open in another pi (${host})`, "error");
176
+ return { cancel: true };
177
+ });
178
+ pi.on("session_start", (_event, ctx) => {
179
+ current = ctx.sessionManager.getSessionId();
180
+ proc.attention.clear();
181
+ writeFor(ctx, (db, id) => {
182
+ const host = hostOfSession(db, proc, id);
183
+ if (host)
184
+ throw new Error(`session ${id} is already open in another pi (${host})`);
185
+ db.run("DELETE FROM runtimes WHERE session_id = ? AND tmux_session != ?", id, proc.launch.tmuxSession);
186
+ db.run(`INSERT INTO runtimes (tmux_session, session_id, cwd, project_root, boot_id, pid, started_at) VALUES (?, ?, ?, ?, ?, ?, ?)
187
+ ON CONFLICT (tmux_session) DO UPDATE SET session_id = excluded.session_id, cwd = excluded.cwd,
188
+ project_root = excluded.project_root, boot_id = excluded.boot_id, pid = excluded.pid`, proc.launch.tmuxSession, id, ctx.cwd, projectRoot(ctx.cwd), bootId(), process.pid, Date.now());
189
+ const transcript = ctx.sessionManager.getSessionFile();
190
+ if (!transcript)
191
+ throw new Error("pi is running without a session file");
192
+ db.run("UPDATE sessions SET phase = 'idle', cwd = ?, project_root = ?, branch = ?, transcript = ? WHERE session_id = ?", ctx.cwd, projectRoot(ctx.cwd), branch(ctx.cwd), transcript, id);
193
+ });
194
+ });
195
+ pi.on("message_start", (event, ctx) => {
196
+ if (event.message.role !== "user")
197
+ return;
198
+ writeFor(ctx, (db, id) => {
199
+ const transcript = ctx.sessionManager.getSessionFile();
200
+ if (!transcript)
201
+ throw new Error("pi is running without a session file");
202
+ const now = Date.now();
203
+ db.run(`INSERT INTO sessions (session_id, tool, cwd, project_root, transcript, title, branch, phase, created_at, last_prompt_at)
204
+ VALUES (?, 'pi', ?, ?, ?, ?, ?, 'working', ?, ?)
205
+ ON CONFLICT (session_id) DO UPDATE SET phase = 'working', last_prompt_at = excluded.last_prompt_at`, id, ctx.cwd, projectRoot(ctx.cwd), transcript, ctx.sessionManager.getSessionName() ?? null, branch(ctx.cwd), now, now);
206
+ });
207
+ });
208
+ pi.on("agent_start", (_event, ctx) => {
209
+ writeFor(ctx, (db, id) => db.run("UPDATE sessions SET phase = 'working' WHERE session_id = ?", id));
210
+ });
211
+ const attention = (open) => (data) => {
212
+ const attentionId = data.attentionId;
213
+ if (typeof attentionId !== "string" || !current)
214
+ return;
215
+ if (open)
216
+ proc.attention.add(attentionId);
217
+ else
218
+ proc.attention.delete(attentionId);
219
+ const phase = proc.attention.size > 0 ? "blocked" : "working";
220
+ write(current, (db, id) => db.run("UPDATE sessions SET phase = ? WHERE session_id = ? AND phase != 'idle'", phase, id));
221
+ };
222
+ pi.events.on("glimpseui:attention:request", attention(true));
223
+ pi.events.on("glimpseui:attention:resolve", attention(false));
224
+ pi.on("agent_settled", (_event, ctx) => {
225
+ proc.attention.clear();
226
+ writeFor(ctx, (db, id) => {
227
+ db.run("UPDATE sessions SET phase = 'idle', last_settled_at = ?, cwd = ?, project_root = ?, branch = ?, title = ? WHERE session_id = ?", Date.now(), ctx.cwd, projectRoot(ctx.cwd), branch(ctx.cwd), ctx.sessionManager.getSessionName() ?? null, id);
228
+ db.run("UPDATE runtimes SET cwd = ?, project_root = ? WHERE tmux_session = ?", ctx.cwd, projectRoot(ctx.cwd), proc.launch.tmuxSession);
229
+ });
230
+ });
231
+ pi.on("session_info_changed", (event, ctx) => {
232
+ writeFor(ctx, (db, id) => db.run("UPDATE sessions SET title = ? WHERE session_id = ?", event.name ?? null, id));
233
+ });
234
+ const markArchived = (ctx) => {
235
+ let archived = false;
236
+ writeFor(ctx, (db, id) => {
237
+ if (!db.get("SELECT 1 FROM sessions WHERE session_id = ?", id))
238
+ return;
239
+ db.run("INSERT INTO marks (session_id, archived_at) VALUES (?, ?) ON CONFLICT (session_id) DO UPDATE SET archived_at = excluded.archived_at", id, Date.now());
240
+ archived = true;
241
+ });
242
+ return archived;
243
+ };
244
+ pi.registerCommand("archive", {
245
+ description: "Archive this session in swb and quit",
246
+ handler: async (_args, ctx) => {
247
+ if (!ctx.isIdle()) {
248
+ ctx.ui.notify("swb: turn running: wait for it to complete", "error");
249
+ return;
250
+ }
251
+ if (markArchived(ctx))
252
+ ctx.shutdown();
253
+ else if (!proc.failure)
254
+ ctx.ui.notify("swb: nothing to archive before the first prompt", "error");
255
+ }
256
+ });
257
+ pi.registerTool({
258
+ name: "swb_archive",
259
+ label: "Archive session",
260
+ description: "Archive this session in Agent Switchboard. It leaves the user's roster of open sessions, and pi quits as soon as this turn ends. The user can restore it with `swb unarchive <id>`.",
261
+ promptSnippet: "Archive this session when the user asks",
262
+ promptGuidelines: [
263
+ "Use swb_archive only when the user asks to archive this session; never archive on your own initiative.",
264
+ "Call swb_archive as the last action of the turn, then end with a brief final message: pi quits once the turn ends."
265
+ ],
266
+ parameters: Type.Object({}),
267
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
268
+ if (!markArchived(ctx)) {
269
+ throw new Error(proc.failure ? `swb: not recording: ${proc.failure}` : "swb: no session recorded yet");
270
+ }
271
+ ctx.shutdown();
272
+ return {
273
+ content: [{ type: "text", text: "Archived. pi quits when this turn ends." }],
274
+ details: undefined
275
+ };
276
+ }
277
+ });
278
+ pi.on("session_shutdown", (event, ctx) => {
279
+ if (event.reason !== "quit")
280
+ return;
281
+ writeFor(ctx, (db) => db.run("DELETE FROM runtimes WHERE tmux_session = ?", proc.launch.tmuxSession));
282
+ });
283
+ }
284
+ export {
285
+ src_default as default
286
+ };
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
- "name": "@thurstonsand/pi-agent-switchboard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@thurstonsand/pi-agent-switchboard",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Records managed pi sessions for Agent Switchboard (swb)",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/thurstonsand/agent-switchboard.git"
10
+ },
11
+ "keywords": [
12
+ "pi-package"
13
+ ],
14
+ "pi": {
15
+ "extensions": [
16
+ "./index.js"
17
+ ]
18
+ },
19
+ "peerDependencies": {
20
+ "@earendil-works/pi-coding-agent": "*",
21
+ "typebox": "*"
22
+ }
23
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.