topside-arch 0.0.0-stage → 0.1.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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +217 -2
  3. package/contrib/aur/.SRCINFO +20 -0
  4. package/contrib/aur/PKGBUILD +35 -0
  5. package/contrib/aur/topside-arch.install +28 -0
  6. package/contrib/icons/hicolor/scalable/apps/topside.svg +28 -0
  7. package/contrib/systemd/topside.service +10 -0
  8. package/contrib/themes/sakura.json +31 -0
  9. package/dist/adapters/claude/attach.js +92 -0
  10. package/dist/adapters/claude/hook-event.js +173 -0
  11. package/dist/adapters/claude/one-shot.js +30 -0
  12. package/dist/adapters/claude/settings.js +78 -0
  13. package/dist/adapters/claude/usage.js +76 -0
  14. package/dist/adapters/codex/codex.js +73 -0
  15. package/dist/adapters/codex/patch.js +39 -0
  16. package/dist/adapters/codex/usage.js +77 -0
  17. package/dist/adapters/pi/extension.js +271 -0
  18. package/dist/adapters/pi/risk-gate.js +256 -0
  19. package/dist/cli/commands.js +615 -0
  20. package/dist/cli/hook-log.js +32 -0
  21. package/dist/cli/main.js +100 -0
  22. package/dist/daemon/preview.js +70 -0
  23. package/dist/daemon/processes.js +105 -0
  24. package/dist/daemon/server.js +437 -0
  25. package/dist/daemon/session-state.js +179 -0
  26. package/dist/daemon/store.js +176 -0
  27. package/dist/dms/setup.js +137 -0
  28. package/dist/hosts/hosts.js +39 -0
  29. package/dist/jump/jump.js +199 -0
  30. package/dist/pill/config.js +92 -0
  31. package/dist/pill/launch.js +38 -0
  32. package/dist/sekaipop/setup.js +267 -0
  33. package/dist/service/unit.js +77 -0
  34. package/dist/shared/ancestry.js +27 -0
  35. package/dist/shared/client.js +29 -0
  36. package/dist/shared/package.js +25 -0
  37. package/dist/shared/paths.js +69 -0
  38. package/dist/shared/protocol.js +35 -0
  39. package/dist/shared/qml-lib.js +33 -0
  40. package/dist/shared/result.js +6 -0
  41. package/dist/shared/terminal.js +42 -0
  42. package/dist/themes/themes.js +84 -0
  43. package/package.json +49 -4
  44. package/shell/core/AgentIcon.qml +24 -0
  45. package/shell/core/AppLogo.qml +48 -0
  46. package/shell/core/ApprovalRow.qml +197 -0
  47. package/shell/core/BoardDetail.qml +336 -0
  48. package/shell/core/BoardList.qml +419 -0
  49. package/shell/core/BoardNotice.qml +189 -0
  50. package/shell/core/CardButton.qml +55 -0
  51. package/shell/core/CardHeader.qml +46 -0
  52. package/shell/core/ChalkBoard.qml +99 -0
  53. package/shell/core/CompletionCard.qml +106 -0
  54. package/shell/core/FlapText.qml +110 -0
  55. package/shell/core/KeyCap.qml +72 -0
  56. package/shell/core/Mascot.qml +13 -0
  57. package/shell/core/MascotBadge.qml +40 -0
  58. package/shell/core/MascotEffect.qml +40 -0
  59. package/shell/core/Paper.qml +54 -0
  60. package/shell/core/PixelGrid.qml +40 -0
  61. package/shell/core/QuestionRow.qml +161 -0
  62. package/shell/core/SessionRow.qml +257 -0
  63. package/shell/core/Stamp.qml +62 -0
  64. package/shell/core/StatusDots.qml +33 -0
  65. package/shell/core/Surface.qml +32 -0
  66. package/shell/core/Tag.qml +22 -0
  67. package/shell/core/TerminalIcon.qml +34 -0
  68. package/shell/core/Theme.qml +100 -0
  69. package/shell/core/TicketDetail.qml +657 -0
  70. package/shell/core/TicketList.qml +717 -0
  71. package/shell/core/TicketNotice.qml +198 -0
  72. package/shell/core/TopsideClient.qml +201 -0
  73. package/shell/core/UsageLine.qml +106 -0
  74. package/shell/core/agents.js +79 -0
  75. package/shell/core/board.js +132 -0
  76. package/shell/core/hiding.js +68 -0
  77. package/shell/core/pixels.js +542 -0
  78. package/shell/core/qmldir +30 -0
  79. package/shell/core/sounds.js +31 -0
  80. package/shell/core/themes.js +195 -0
  81. package/shell/core/ticket.js +170 -0
  82. package/shell/dms-plugin/TopsideSettings.qml +696 -0
  83. package/shell/dms-plugin/TopsideWidget.qml +554 -0
  84. package/shell/dms-plugin/plugin.json +14 -0
  85. package/shell/pill.qml +279 -0
  86. package/shell/sekaipop-plugin/Bar.qml +150 -0
  87. package/shell/sekaipop-plugin/Card.qml +296 -0
  88. package/shell/sekaipop-plugin/Floating.qml +74 -0
  89. package/shell/sekaipop-plugin/ListWindow.qml +156 -0
  90. package/shell/sekaipop-plugin/Popup.qml +70 -0
  91. package/shell/sekaipop-plugin/Service.qml +418 -0
  92. package/shell/sekaipop-plugin/ShellLook.qml +43 -0
  93. package/shell/sekaipop-plugin/StyledCard.qml +194 -0
  94. package/shell/sekaipop-plugin/place.js +28 -0
  95. package/shell/sekaipop-plugin/plugin.json +109 -0
@@ -0,0 +1,615 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { copyFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { env, pid, stdin } from "node:process";
6
+ import { findAttachClient, findSessionRecord, listAttachClients, readEnviron, readSessionRecord } from "../adapters/claude/attach.js";
7
+ import { formatAnswers, formatDecision, isBackgroundSession, parseHookInput, parseQuestions, permissionSuggestions } from "../adapters/claude/hook-event.js";
8
+ import { hooksState, withoutTopsideHooks, withTopsideHooks } from "../adapters/claude/settings.js";
9
+ import { isOneShot, readCmdline } from "../adapters/claude/one-shot.js";
10
+ import { codexUsage, readTail } from "../adapters/codex/usage.js";
11
+ import { gateDecision, gatedCommand, gateTimeoutMessage, gateTimeoutMs } from "../adapters/pi/risk-gate.js";
12
+ import { agentHome, extensionAgents, extensionPath, extensionSource, extensionState, hasExtension, isExtensionAgent, refreshExtensions, reloadAdvice, updateExtension, } from "../adapters/pi/extension.js";
13
+ import { clearUntrusted, codexHookTimeouts, formatCodexDecision, fromCodex, isCodexOneShot, isUntrusted, setUntrusted, untrustedFlagPath } from "../adapters/codex/codex.js";
14
+ import { parseStatusLineUsage, usageState, withoutUsageBridge, withUsageBridge } from "../adapters/claude/usage.js";
15
+ import { startDaemon } from "../daemon/server.js";
16
+ import { daemonIsStale, packageUnitPath, refreshUnit, serviceState, userUnitPath, writeUnit } from "../service/unit.js";
17
+ import { openStore } from "../daemon/store.js";
18
+ import { hiddenFoldersOfShells, setupShells, syncThemesOfShells } from "../hosts/hosts.js";
19
+ import { isInFront, jump, realHost as realJumpHost } from "../jump/jump.js";
20
+ import { allThemes, findTheme, formatCheck, formatThemes, themesDir, userThemes } from "../themes/themes.js";
21
+ import { configPath, parseAppearance, parseFontSize, parsePillPosition, parseTheme, readConfig, writeConfig } from "../pill/config.js";
22
+ import { launchPill } from "../pill/launch.js";
23
+ import { ancestry } from "../shared/ancestry.js";
24
+ import { request } from "../shared/client.js";
25
+ import { packageInfo } from "../shared/package.js";
26
+ import { claudeConfigDir, claudeSettingsPath, codexHome, codexHooksPath, dbPath, socketPath, topsideCommand } from "../shared/paths.js";
27
+ import { err, ok } from "../shared/result.js";
28
+ import { terminalHint } from "../shared/terminal.js";
29
+ import { appendHookLog, hookLogPath } from "./hook-log.js";
30
+ const done = (out) => ({ code: 0, out });
31
+ const failed = (out) => ({ code: 1, out: out.endsWith("\n") ? out : `${out}\n` });
32
+ export async function daemonCommand() {
33
+ const store = openStore(dbPath());
34
+ if (!store.ok)
35
+ return failed(store.error);
36
+ const flag = untrustedFlagPath(dbPath());
37
+ // A newer Topside may write a newer extension; bring installed ones up to date.
38
+ const refreshed = refreshExtensions(topsideCommand(), extensionSocket());
39
+ for (const agent of refreshed)
40
+ process.stdout.write(`updated the ${agent} extension; open sessions pick it up when you ${reloadAdvice(agent)}\n`);
41
+ const started = await startDaemon(socketPath(), store.value, {
42
+ codexUntrusted: () => isUntrusted(flag),
43
+ extensions: () => extensionAgents.filter((agent) => hasExtension(agent)),
44
+ });
45
+ if (!started.ok) {
46
+ store.value.close();
47
+ return failed(started.error);
48
+ }
49
+ process.stdout.write(`topside daemon listening on ${socketPath()}\n`);
50
+ await new Promise((resolve) => {
51
+ process.once("SIGINT", resolve);
52
+ process.once("SIGTERM", resolve);
53
+ });
54
+ await started.value.close();
55
+ store.value.close();
56
+ return done("topside daemon stopped\n");
57
+ }
58
+ async function readStdin() {
59
+ const chunks = [];
60
+ for await (const chunk of stdin)
61
+ chunks.push(chunk);
62
+ return Buffer.concat(chunks).toString("utf8");
63
+ }
64
+ // Runs inside Claude Code. It must never fail the hook or print anything
65
+ // except a permission decision, so every problem ends in a silent exit 0.
66
+ export async function hookCommand(agent) {
67
+ if (agent === undefined || agent === "")
68
+ return done("");
69
+ const raw = await readStdin();
70
+ // Logged before anything else, for any agent name, so a new agent's
71
+ // payloads can be captured before its adapter exists.
72
+ const log = hookLogPath(env);
73
+ if (log !== null)
74
+ appendHookLog(log, raw, agent);
75
+ if (agent === "codex")
76
+ return codexHook(raw);
77
+ if (isExtensionAgent(agent))
78
+ return extensionHook(raw, agent);
79
+ if (agent !== "claude")
80
+ return done("");
81
+ const parsed = parseHookInput(raw, { at: Date.now(), pids: ancestry(pid), terminal: terminalHint(env) });
82
+ if (!parsed.ok || parsed.value === null)
83
+ return done("");
84
+ // `claude -p` runs come from scripts and last seconds: no row for them.
85
+ if (isOneShot(parsed.value.pids.map(readCmdline)))
86
+ return done("");
87
+ const event = isBackgroundSession(env) ? throughAttachClient(parsed.value) : parsed.value;
88
+ if (event === null)
89
+ return done("");
90
+ return relay(event, raw);
91
+ }
92
+ // Codex's hooks carry Claude Code's fields (docs/notes/codex-hooks.md). Its
93
+ // answers are allow and deny only, and it has no AskUserQuestion.
94
+ async function codexHook(raw) {
95
+ // A hook that runs is a trusted hook: whatever install came before, /hooks was done.
96
+ clearUntrusted(untrustedFlagPath(dbPath()));
97
+ const pids = fromCodex(ancestry(pid), readCmdline);
98
+ // No codex binary above us (a test, a wrapper we don't know): nothing to watch.
99
+ if (pids === null)
100
+ return done("");
101
+ if (isCodexOneShot(readCmdline(pids[0] ?? 0)))
102
+ return done("");
103
+ const parsed = parseHookInput(raw, { at: Date.now(), pids, terminal: terminalHint(env) }, "codex");
104
+ if (!parsed.ok || parsed.value === null)
105
+ return done("");
106
+ const event = parsed.value;
107
+ // Codex's plan limits are in its session file; read them when a turn ends
108
+ // or a session starts, where they can have changed.
109
+ if (event.type === "turn-end" || event.type === "session-start") {
110
+ const usage = codexUsage(readTail(transcriptPath(raw)));
111
+ if (usage !== null)
112
+ await request(socketPath(), { op: "usage", agent: "codex", usage }, 500);
113
+ }
114
+ if (event.type !== "approval-request")
115
+ return relay(event, raw);
116
+ const asking = { ...event, always: "", inFront: isInFront({ ...event, title: "" }, realJumpHost) };
117
+ const reply = await request(socketPath(), { op: "approval", event: asking }, 0);
118
+ return done(reply.ok && reply.value.op === "decision" ? formatCodexDecision(reply.value.decision) : "");
119
+ }
120
+ // pi and omp report through Topside's extension, which spawns this hook
121
+ // directly, so the parent is the agent. They run tools without asking; the
122
+ // extension awaits this hook for every shell command, and with the gate on
123
+ // a risky one waits for an answer on the island (VIA-PARITY §22).
124
+ async function extensionHook(raw, agent) {
125
+ const parsed = parseHookInput(raw, { at: Date.now(), pids: ancestry(pid), terminal: terminalHint(env) }, agent);
126
+ if (!parsed.ok || parsed.value === null || parsed.value.type === "approval-request")
127
+ return done("");
128
+ const event = parsed.value;
129
+ if (event.type === "tool-start" && gatedCommand(event.toolInput, event.cwd, readConfig(configPath()).gate, hiddenFolders()) !== null) {
130
+ return gate(event);
131
+ }
132
+ return relay(event, raw);
133
+ }
134
+ // Asks on the island before a risky command. No daemon means no gate: print
135
+ // nothing and the command runs. No answer within 25 s is a deny, since omp
136
+ // blocks a handler that takes 30 s anyway. Afterwards the row leaves
137
+ // "waiting": the tool starts again when allowed, or ends when blocked.
138
+ async function gate(event) {
139
+ const sent = await request(socketPath(), { op: "event", event });
140
+ if (!sent.ok)
141
+ return done("");
142
+ const asking = { ...event, type: "approval-request", always: "", inFront: isInFront({ ...event, title: "" }, realJumpHost) };
143
+ const reply = await request(socketPath(), { op: "approval", event: asking }, gateTimeoutMs);
144
+ const decision = reply.ok && reply.value.op === "decision" ? reply.value.decision : null;
145
+ const allowed = decision === "allow" || decision === "always" || decision === "auto";
146
+ const after = allowed
147
+ ? { ...event, at: Date.now() }
148
+ : { agent: event.agent, sessionId: event.sessionId, cwd: event.cwd, pids: event.pids, terminal: event.terminal, at: Date.now(), type: "tool-end", toolUseId: event.toolUseId, toolName: event.toolName };
149
+ await request(socketPath(), { op: "event", event: after });
150
+ return done(gateDecision(allowed, decision === null ? gateTimeoutMessage : "Denied from Topside"));
151
+ }
152
+ // Folders hidden in any shell; a session there is never gated.
153
+ function hiddenFolders() {
154
+ return hiddenFoldersOfShells();
155
+ }
156
+ // `topside gate on|off`: ask on the island before risky pi and omp commands, or not.
157
+ export function gateCommand(action) {
158
+ const path = configPath();
159
+ if (action === undefined)
160
+ return done(`${readConfig(path).gate ? "on" : "off"}\n`);
161
+ if (action !== "on" && action !== "off")
162
+ return failed("Usage: topside gate [on|off]");
163
+ const written = writeConfig(path, { ...readConfig(path), gate: action === "on" });
164
+ if (!written.ok)
165
+ return failed(written.error);
166
+ return done(action === "on" ? "Topside asks before risky pi and omp commands.\n" : "pi and omp commands run without asking Topside.\n");
167
+ }
168
+ // The socket an extension should name: only one set explicitly, so a file
169
+ // stays valid while the default moves with XDG_RUNTIME_DIR.
170
+ function extensionSocket() {
171
+ return env.TOPSIDE_SOCKET ?? env.VIA_SOCKET ?? "";
172
+ }
173
+ function transcriptPath(raw) {
174
+ try {
175
+ const input = JSON.parse(raw);
176
+ const path = typeof input === "object" && input !== null ? input.transcript_path : "";
177
+ return typeof path === "string" ? path : "";
178
+ }
179
+ catch {
180
+ return "";
181
+ }
182
+ }
183
+ // Sends one event to the daemon; a permission request waits for the answer.
184
+ async function relay(event, raw) {
185
+ if (event.type !== "approval-request") {
186
+ // A turn that ends while its terminal has the focus was seen finishing:
187
+ // the island opens no completion card for it.
188
+ const sent = event.type === "turn-end" ? { ...event, inFront: isInFront({ ...event, title: "" }, realJumpHost) } : event;
189
+ await request(socketPath(), { op: "event", event: sent });
190
+ return done("");
191
+ }
192
+ // A request whose terminal has the focus makes no sound: the user sees it there.
193
+ const asking = { ...event, inFront: isInFront({ ...event, title: "" }, realJumpHost) };
194
+ // No timeout here: Claude Code's hook timeout bounds the wait, and the
195
+ // terminal prompt stays usable the whole time.
196
+ // AskUserQuestion asks permission too; the island shows it as a question
197
+ // and answers through updatedInput (docs/notes/claude-hooks.md).
198
+ const questions = event.toolName === "AskUserQuestion" ? parseQuestions(event.toolInput) : [];
199
+ if (questions.length > 0) {
200
+ const asked = await request(socketPath(), { op: "ask", event: asking, questions }, 0);
201
+ return done(asked.ok && asked.value.op === "answers" && asked.value.answers !== null ? formatAnswers(event.toolInput, asked.value.answers) : "");
202
+ }
203
+ const reply = await request(socketPath(), { op: "approval", event: asking }, 0);
204
+ return done(reply.ok && reply.value.op === "decision" ? formatDecision(reply.value.decision, permissionSuggestions(raw)) : "");
205
+ }
206
+ // A background session counts only while `claude attach` shows it in a
207
+ // terminal; then the client stands in for it, so jump lands on that terminal.
208
+ // Without a client the hook stays out, and Claude handles the session alone.
209
+ function throughAttachClient(event) {
210
+ const record = findSessionRecord(event.pids, readSessionRecord(claudeConfigDir()));
211
+ const client = findAttachClient(listAttachClients(), event.sessionId, record);
212
+ if (client === null)
213
+ return null;
214
+ return { ...event, pids: ancestry(client.pid), terminal: terminalHint(readEnviron(client.pid)) };
215
+ }
216
+ function commandLine(...args) {
217
+ const quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
218
+ return [...topsideCommand(), ...args].map(quote).join(" ");
219
+ }
220
+ function readSettings(path) {
221
+ if (!existsSync(path))
222
+ return ok({});
223
+ try {
224
+ const value = JSON.parse(readFileSync(path, "utf8"));
225
+ if (typeof value !== "object" || value === null || Array.isArray(value))
226
+ return err(`${path} is not a JSON object`);
227
+ return ok(value);
228
+ }
229
+ catch (error) {
230
+ return err(`cannot read ${path}: ${String(error)}`);
231
+ }
232
+ }
233
+ export function hooksCommand(action, agent = "claude") {
234
+ if ((action !== "install" && action !== "uninstall") || (agent !== "claude" && agent !== "codex" && !isExtensionAgent(agent))) {
235
+ return failed("Usage: topside hooks install|uninstall [claude|codex|pi|omp]");
236
+ }
237
+ if (agent === "codex")
238
+ return codexHooksCommand(action);
239
+ if (isExtensionAgent(agent))
240
+ return extensionCommand(action, agent);
241
+ return rewriteSettings((settings) => (action === "install" ? withTopsideHooks(settings, commandLine("hook", "claude")) : withoutTopsideHooks(settings)), action === "install" ? "Installed Topside hooks" : "Removed Topside hooks");
242
+ }
243
+ // pi and omp have no hooks: Topside writes its extension into the agent's
244
+ // extensions folder, or removes it. A file there without Topside's marker is left alone.
245
+ function extensionCommand(action, agent) {
246
+ if (action === "install" && !existsSync(agentHome(agent)))
247
+ return failed(`${agent} isn't set up: ${agentHome(agent)} doesn't exist`);
248
+ const path = extensionPath(agent);
249
+ const result = updateExtension(action, path, extensionSource(agent, topsideCommand(), extensionSocket()));
250
+ if (!result.ok)
251
+ return failed(result.error);
252
+ if (!result.value.changed)
253
+ return done(`Nothing to change in ${path}\n`);
254
+ if (action === "uninstall")
255
+ return done(`Removed Topside's extension: ${path}\n`);
256
+ return done(`Wrote Topside's extension: ${path}\nNew ${agent} sessions report at once; open ones when you ${reloadAdvice(agent)}.\n`);
257
+ }
258
+ // Codex keeps its hooks in hooks.json, in Claude Code's shape. A changed
259
+ // handler isn't trusted until the user runs /hooks in Codex, so a change
260
+ // sets the flag the settings page shows (docs/notes/codex-hooks.md).
261
+ function codexHooksCommand(action) {
262
+ const flag = untrustedFlagPath(dbPath());
263
+ const path = codexHooksPath();
264
+ if (action === "install" && !existsSync(codexHome()))
265
+ return failed(`Codex isn't set up: ${codexHome()} doesn't exist`);
266
+ const result = rewriteSettings((hooks) => (action === "install" ? withTopsideHooks(hooks, commandLine("hook", "codex"), codexHookTimeouts) : withoutTopsideHooks(hooks)), action === "install" ? "Installed Topside hooks" : "Removed Topside hooks", path);
267
+ if (result.code !== 0)
268
+ return result;
269
+ if (action === "uninstall") {
270
+ clearUntrusted(flag);
271
+ return result;
272
+ }
273
+ if (result.out.startsWith("Nothing to change"))
274
+ return result;
275
+ const flagged = setUntrusted(flag);
276
+ if (!flagged.ok)
277
+ return failed(flagged.error);
278
+ return done(`${result.out}Codex runs them once you trust them: run /hooks in Codex and trust Topside's hooks.\n`);
279
+ }
280
+ // Plan usage in the island's header: wraps Claude Code's status line so the
281
+ // numbers reach the daemon. The user's own status line keeps running.
282
+ export function usageCommand(action) {
283
+ if (action !== "install" && action !== "uninstall")
284
+ return failed("Usage: topside usage install|uninstall");
285
+ return rewriteSettings((settings) => (action === "install" ? withUsageBridge(settings, commandLine("statusline")) : withoutUsageBridge(settings)), action === "install" ? "Routed Claude Code's status line through Topside" : "Gave Claude Code its own status line back");
286
+ }
287
+ // Runs as Claude Code's status line. Sends the plan usage on to the daemon
288
+ // (giving up after half a second), then runs the user's original status line
289
+ // on the same input and prints what it prints. Never fails.
290
+ export async function statuslineCommand(args) {
291
+ const raw = await readStdin();
292
+ const usage = parseStatusLineUsage(raw);
293
+ if (usage !== null)
294
+ await request(socketPath(), { op: "usage", agent: "claude", usage }, 500);
295
+ const at = args.indexOf("--wrap");
296
+ const encoded = at >= 0 ? (args[at + 1] ?? "") : "";
297
+ if (encoded === "")
298
+ return done("");
299
+ const original = Buffer.from(encoded, "base64").toString("utf8");
300
+ const result = spawnSync("sh", ["-c", original], { input: raw, encoding: "utf8", stdio: ["pipe", "pipe", "inherit"] });
301
+ return done(typeof result.stdout === "string" ? result.stdout : "");
302
+ }
303
+ export function integrations(version) {
304
+ const settings = readSettings(claudeSettingsPath());
305
+ const codexHooks = readSettings(codexHooksPath());
306
+ const command = topsideCommand();
307
+ const script = command[command.length - 1] ?? "";
308
+ const enabled = spawnSync("systemctl", ["--user", "is-enabled", "topside"], { encoding: "utf8" });
309
+ return {
310
+ hooks: settings.ok ? hooksState(settings.value, commandLine("hook", "claude")) : "none",
311
+ usage: settings.ok ? usageState(settings.value, commandLine("statusline")) : "none",
312
+ login: typeof enabled.stdout === "string" && enabled.stdout.trim() === "enabled",
313
+ version,
314
+ author: packageInfo().author,
315
+ // dist/cli/main.js sits two folders below the package.
316
+ runningFrom: script.endsWith("main.js") ? dirname(dirname(dirname(script))) : script,
317
+ dataFolder: dirname(dbPath()),
318
+ settingsError: settings.ok ? "" : settings.error,
319
+ codex: existsSync(codexHome()),
320
+ codexHooks: codexHooks.ok ? hooksState(codexHooks.value, commandLine("hook", "codex")) : "none",
321
+ codexUntrusted: isUntrusted(untrustedFlagPath(dbPath())),
322
+ pi: existsSync(agentHome("pi")),
323
+ piExtension: extensionState(extensionPath("pi"), extensionSource("pi", topsideCommand(), extensionSocket())),
324
+ omp: existsSync(agentHome("omp")),
325
+ ompExtension: extensionState(extensionPath("omp"), extensionSource("omp", topsideCommand(), extensionSocket())),
326
+ gate: readConfig(configPath()).gate,
327
+ };
328
+ }
329
+ // `topside integrations`: the state as JSON for the settings page.
330
+ // `topside integrations adopt`: point every installed hook and bridge at this copy.
331
+ export function integrationsCommand(action, version) {
332
+ if (action === undefined || action === "--json")
333
+ return done(`${JSON.stringify(integrations(version))}\n`);
334
+ if (action !== "adopt")
335
+ return failed("Usage: topside integrations [adopt]");
336
+ const state = integrations(version);
337
+ const out = [];
338
+ if (state.hooks !== "none") {
339
+ const result = hooksCommand("install");
340
+ if (result.code !== 0)
341
+ return result;
342
+ out.push(result.out);
343
+ }
344
+ if (state.usage !== "none") {
345
+ const result = usageCommand("install");
346
+ if (result.code !== 0)
347
+ return result;
348
+ out.push(result.out);
349
+ }
350
+ if (state.codexHooks !== "none") {
351
+ const result = hooksCommand("install", "codex");
352
+ if (result.code !== 0)
353
+ return result;
354
+ out.push(result.out);
355
+ }
356
+ for (const agent of extensionAgents) {
357
+ if ((agent === "pi" ? state.piExtension : state.ompExtension) === "none")
358
+ continue;
359
+ const result = hooksCommand("install", agent);
360
+ if (result.code !== 0)
361
+ return result;
362
+ out.push(result.out);
363
+ }
364
+ return done(out.join("") || "Nothing installed to adopt.\n");
365
+ }
366
+ function systemctl(...args) {
367
+ const result = spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" });
368
+ if (result.error)
369
+ return err(`cannot run systemctl: ${result.error.message}`);
370
+ if (result.status !== 0)
371
+ return err(result.stderr.trim() || `systemctl exited with ${result.status}`);
372
+ return ok(result.stdout);
373
+ }
374
+ // `topside login on|off`. On writes the daemon's unit first (src/service/unit.ts)
375
+ // unless the AUR package brought one, then enables and starts it. Off only
376
+ // disables it; the daemon runs until you stop it or log out.
377
+ export function loginCommand(action) {
378
+ if (action !== "on" && action !== "off")
379
+ return failed("Usage: topside login on|off");
380
+ if (action === "off") {
381
+ const off = systemctl("disable", "topside");
382
+ return off.ok ? done("Topside no longer starts at login.\n") : failed(off.error);
383
+ }
384
+ let out = "";
385
+ const path = userUnitPath();
386
+ if (!existsSync(packageUnitPath) || existsSync(path)) {
387
+ const command = topsideCommand();
388
+ const wrote = writeUnit(path, command);
389
+ if (!wrote.ok)
390
+ return failed(wrote.error);
391
+ if (wrote.value === "written") {
392
+ const reload = systemctl("daemon-reload");
393
+ if (!reload.ok)
394
+ return failed(reload.error);
395
+ out += `Wrote ${path}: it runs ${command.join(" ")} daemon.\n`;
396
+ }
397
+ }
398
+ const on = systemctl("enable", "--now", "topside");
399
+ return on.ok ? done(`${out}Topside runs now and starts at login.\n`) : failed(on.error);
400
+ }
401
+ function rewriteSettings(change, said, path = claudeSettingsPath()) {
402
+ const current = readSettings(path);
403
+ if (!current.ok)
404
+ return failed(current.error);
405
+ const next = change(current.value);
406
+ if (isDeepStrictEqual(next, current.value)) {
407
+ return done(`Nothing to change in ${path}\n`);
408
+ }
409
+ try {
410
+ let backup = "";
411
+ if (existsSync(path)) {
412
+ backup = `${path}.topside-backup-${Date.now()}`;
413
+ copyFileSync(path, backup);
414
+ }
415
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`);
416
+ return done(`${said} in ${path}\n${backup ? `Backup: ${backup}\n` : ""}`);
417
+ }
418
+ catch (error) {
419
+ return failed(`cannot write ${path}: ${String(error)}`);
420
+ }
421
+ }
422
+ export function formatSnapshot(snapshot) {
423
+ if (snapshot.sessions.length === 0)
424
+ return "No live sessions.\n";
425
+ const titles = new Map(snapshot.sessions.map((s) => [s.id, s.title]));
426
+ const lines = ["SESSIONS (topside jump <id>)"];
427
+ for (const s of snapshot.sessions) {
428
+ lines.push(` ${s.id.slice(0, 8).padEnd(8)} ${s.status.padEnd(8)} ${s.title.padEnd(40).slice(0, 40)} ${s.cwd}`);
429
+ }
430
+ if (snapshot.approvals.length > 0) {
431
+ lines.push("", "WAITING FOR YOU (topside approve <id> | topside deny <id>)");
432
+ for (const a of snapshot.approvals) {
433
+ lines.push(` ${a.id} ${a.summary.padEnd(40).slice(0, 40)} ${titles.get(a.sessionId) ?? a.sessionId}`);
434
+ }
435
+ }
436
+ if (snapshot.questions.length > 0) {
437
+ lines.push("", "CLAUDE ASKS (answer on the island)");
438
+ for (const q of snapshot.questions) {
439
+ const text = q.questions.map((item) => item.question).join(" / ");
440
+ lines.push(` ${q.id} ${text.padEnd(40).slice(0, 40)} ${titles.get(q.sessionId) ?? q.sessionId}`);
441
+ }
442
+ }
443
+ return `${lines.join("\n")}\n`;
444
+ }
445
+ export async function statusCommand() {
446
+ const reply = await request(socketPath(), { op: "snapshot" });
447
+ if (!reply.ok)
448
+ return failed(reply.error);
449
+ if (reply.value.op !== "snapshot")
450
+ return failed("unexpected reply from the Topside daemon");
451
+ return done(formatSnapshot(reply.value.snapshot));
452
+ }
453
+ export async function decideCommand(decision, approvalId) {
454
+ if (!approvalId)
455
+ return failed(`Usage: topside ${decision === "allow" ? "approve" : "deny"} <id>`);
456
+ const reply = await request(socketPath(), { op: "decide", approvalId, decision });
457
+ if (!reply.ok)
458
+ return failed(reply.error);
459
+ if (reply.value.op === "error")
460
+ return failed(reply.value.error);
461
+ return done(`${decision === "allow" ? "Approved" : "Denied"} ${approvalId}\n`);
462
+ }
463
+ export async function pillCommand(args) {
464
+ const [action, value] = args;
465
+ if (action === undefined) {
466
+ const launched = await launchPill();
467
+ return launched.ok ? done("") : failed(launched.error);
468
+ }
469
+ const path = configPath();
470
+ const current = readConfig(path);
471
+ const save = (next, said) => {
472
+ const written = writeConfig(path, next);
473
+ return written.ok ? done(`${said} (${path})\n`) : failed(written.error);
474
+ };
475
+ switch (action) {
476
+ case "position": {
477
+ if (value === undefined)
478
+ return done(`${current.pill.position}\n`);
479
+ const position = parsePillPosition(value);
480
+ if (!position.ok)
481
+ return failed(position.error);
482
+ return save({ ...current, pill: { ...current.pill, position: position.value } }, `Pill position set to ${position.value}`);
483
+ }
484
+ case "theme": {
485
+ if (value === undefined)
486
+ return done(`${current.theme}\n`);
487
+ const theme = parseTheme(value);
488
+ if (!theme.ok)
489
+ return failed(theme.error);
490
+ return save({ ...current, theme: theme.value }, `Pill theme set to ${theme.value}`);
491
+ }
492
+ case "mode": {
493
+ if (value === undefined)
494
+ return done(`${current.appearance}\n`);
495
+ const appearance = parseAppearance(value);
496
+ if (!appearance.ok)
497
+ return failed(appearance.error);
498
+ return save({ ...current, appearance: appearance.value }, `Pill mode set to ${appearance.value}`);
499
+ }
500
+ case "text-size": {
501
+ if (value === undefined)
502
+ return done(`${current.fontSize}\n`);
503
+ const size = parseFontSize(value);
504
+ if (!size.ok)
505
+ return failed(size.error);
506
+ return save({ ...current, fontSize: size.value }, `Pill text size set to ${size.value}`);
507
+ }
508
+ default:
509
+ return failed(`Unknown pill command: ${action}\nUsage: topside pill [position|theme|mode|text-size [<value>]]`);
510
+ }
511
+ }
512
+ // `topside theme list [--json]` and `topside theme check <id|file>`: the
513
+ // built-in themes and your own files, read the way the island reads them.
514
+ export function themeCommand(args) {
515
+ const [action, value] = args;
516
+ switch (action) {
517
+ case undefined:
518
+ case "list":
519
+ if (value === "--json")
520
+ return done(`${JSON.stringify(allThemes().map(({ id, title, source, usable, problems }) => ({ id, title, source, usable, problems })))}\n`);
521
+ return done(formatThemes(allThemes()));
522
+ case "sync": {
523
+ const synced = syncThemesOfShells();
524
+ return synced.ok ? done(synced.value) : failed(synced.error);
525
+ }
526
+ case "check": {
527
+ if (value === undefined) {
528
+ const yours = userThemes();
529
+ if (yours.length === 0)
530
+ return done(`No themes of your own in ${themesDir()}.\n`);
531
+ const out = yours.map(formatCheck).join("\n");
532
+ return yours.every((t) => t.problems.length === 0) ? done(out) : failed(out);
533
+ }
534
+ const found = findTheme(value);
535
+ if (!found.ok)
536
+ return failed(found.error);
537
+ const out = formatCheck(found.value);
538
+ return found.value.problems.length === 0 ? done(out) : failed(out);
539
+ }
540
+ default:
541
+ return failed(`Unknown theme command: ${action}\nUsage: topside theme [list [--json]|check [<id>|<file>]|sync]`);
542
+ }
543
+ }
544
+ // Joins every running shell's bar (src/hosts/hosts.ts); with none, setup
545
+ // points at the standalone pill.
546
+ // Also points the daemon's unit at this copy, so an upgrade, a new prefix or
547
+ // the old unit that ran /usr/bin/topside heals here.
548
+ // `topside setup [--no-restart]`: every running shell, then the daemon's
549
+ // unit. Whatever still runs old files is restarted (the shells by their
550
+ // hosts; the daemon here) unless --no-restart, which says what to run instead.
551
+ export async function setupCommand(args = []) {
552
+ const restart = !args.includes("--no-restart");
553
+ const result = await setupShells(undefined, { restart });
554
+ if (!result.ok)
555
+ return failed(result.error);
556
+ const path = userUnitPath();
557
+ const command = topsideCommand();
558
+ const unit = refreshUnit(path, command);
559
+ if (!unit.ok)
560
+ return done(`${result.value}Couldn't update the daemon's unit: ${unit.error}\n`);
561
+ const written = unit.value === "written";
562
+ let said = result.value;
563
+ if (written) {
564
+ const reload = systemctl("daemon-reload");
565
+ said += `Pointed ${path} at this copy${reload.ok ? "" : ` (daemon-reload failed: ${reload.error})`}.\n`;
566
+ }
567
+ const show = systemctl("show", "topside", "-p", "ActiveState,ExecMainStartTimestamp", "--timestamp=unix");
568
+ // When this copy's script was written: an upgrade in place rewrites it.
569
+ const builtAt = Math.floor((statSync(command[command.length - 1] ?? "", { throwIfNoEntry: false })?.mtimeMs ?? 0) / 1000);
570
+ if (!daemonIsStale(serviceState(show.ok ? show.value : ""), builtAt, written))
571
+ return done(said);
572
+ if (!restart)
573
+ return done(`${said}The daemon runs older code: systemctl --user restart topside\n`);
574
+ const restarted = systemctl("restart", "topside");
575
+ return done(`${said}${restarted.ok ? "Restarted the daemon on this copy.\n" : `Couldn't restart the daemon (${restarted.error}): systemctl --user restart topside\n`}`);
576
+ }
577
+ // Accepts the full session id or any unique prefix, like the ids `topside status` prints.
578
+ export function findSession(sessions, id) {
579
+ const exact = sessions.find((s) => s.id === id);
580
+ if (exact)
581
+ return ok(exact);
582
+ const matches = sessions.filter((s) => s.id.startsWith(id));
583
+ if (matches.length === 1 && matches[0])
584
+ return ok(matches[0]);
585
+ return err(matches.length === 0 ? `No live session matches ${id}` : `${id} matches ${matches.length} sessions, give more of the id`);
586
+ }
587
+ // `topside front <id>`: "yes" when the session's terminal window has the
588
+ // focus, else "no". The island skips a reminder the user can already see.
589
+ export async function frontCommand(id) {
590
+ if (!id)
591
+ return failed("Usage: topside front <session id>");
592
+ const reply = await request(socketPath(), { op: "snapshot" });
593
+ if (!reply.ok || reply.value.op !== "snapshot")
594
+ return done("no\n");
595
+ const session = findSession(reply.value.snapshot.sessions, id);
596
+ return done(session.ok && isInFront(session.value, realJumpHost) ? "yes\n" : "no\n");
597
+ }
598
+ export async function jumpCommand(id) {
599
+ if (!id)
600
+ return failed("Usage: topside jump <session id>");
601
+ const reply = await request(socketPath(), { op: "snapshot" });
602
+ if (!reply.ok)
603
+ return failed(reply.error);
604
+ if (reply.value.op !== "snapshot")
605
+ return failed("unexpected reply from the Topside daemon");
606
+ const session = findSession(reply.value.snapshot.sessions, id);
607
+ if (!session.ok)
608
+ return failed(session.error);
609
+ const result = jump(session.value, realJumpHost);
610
+ if (!result.ok)
611
+ return failed(result.error);
612
+ // Best effort: the jump already happened, a stale "done" dot is harmless.
613
+ await request(socketPath(), { op: "seen", sessionId: session.value.id });
614
+ return done(result.value);
615
+ }
@@ -0,0 +1,32 @@
1
+ import { appendFileSync, closeSync, openSync } from "node:fs";
2
+ import { err, ok } from "../shared/result.js";
3
+ // The file named by TOPSIDE_HOOK_LOG (or the old VIA_HOOK_LOG), or null when unset.
4
+ export function hookLogPath(env) {
5
+ const path = env.TOPSIDE_HOOK_LOG ?? env.VIA_HOOK_LOG;
6
+ return path === undefined || path === "" ? null : path;
7
+ }
8
+ // `{"agent": "...", "payload": <the payload>}` on one line; a payload that
9
+ // isn't JSON is kept as text.
10
+ export function hookLogLine(raw, agent) {
11
+ let payload;
12
+ try {
13
+ payload = JSON.parse(raw);
14
+ }
15
+ catch {
16
+ payload = raw;
17
+ }
18
+ return `${JSON.stringify({ agent, payload })}\n`;
19
+ }
20
+ // A development aid: what an agent really sends, so it can be compared with
21
+ // docs/notes. Payloads hold prompts and commands, so a new file is mode 600
22
+ // and nothing leaves the machine.
23
+ export function appendHookLog(path, raw, agent) {
24
+ try {
25
+ closeSync(openSync(path, "a", 0o600));
26
+ appendFileSync(path, hookLogLine(raw, agent));
27
+ return ok(undefined);
28
+ }
29
+ catch (error) {
30
+ return err(`cannot write hook log ${path}: ${String(error)}`);
31
+ }
32
+ }