topside-arch 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +213 -2
- package/contrib/aur/PKGBUILD +35 -0
- package/contrib/aur/topside-arch.install +25 -0
- package/contrib/icons/hicolor/scalable/apps/topside.svg +28 -0
- package/contrib/systemd/topside.service +10 -0
- package/contrib/themes/sakura.json +31 -0
- package/dist/adapters/claude/attach.js +92 -0
- package/dist/adapters/claude/hook-event.js +173 -0
- package/dist/adapters/claude/one-shot.js +30 -0
- package/dist/adapters/claude/settings.js +78 -0
- package/dist/adapters/claude/usage.js +76 -0
- package/dist/adapters/codex/codex.js +73 -0
- package/dist/adapters/codex/patch.js +39 -0
- package/dist/adapters/codex/usage.js +77 -0
- package/dist/adapters/pi/extension.js +271 -0
- package/dist/adapters/pi/risk-gate.js +256 -0
- package/dist/cli/commands.js +563 -0
- package/dist/cli/hook-log.js +32 -0
- package/dist/cli/main.js +100 -0
- package/dist/daemon/preview.js +70 -0
- package/dist/daemon/processes.js +105 -0
- package/dist/daemon/server.js +437 -0
- package/dist/daemon/session-state.js +173 -0
- package/dist/daemon/store.js +176 -0
- package/dist/dms/setup.js +126 -0
- package/dist/hosts/hosts.js +39 -0
- package/dist/jump/jump.js +199 -0
- package/dist/pill/config.js +92 -0
- package/dist/pill/launch.js +38 -0
- package/dist/sekaipop/setup.js +210 -0
- package/dist/shared/ancestry.js +27 -0
- package/dist/shared/client.js +29 -0
- package/dist/shared/package.js +25 -0
- package/dist/shared/paths.js +69 -0
- package/dist/shared/protocol.js +35 -0
- package/dist/shared/qml-lib.js +32 -0
- package/dist/shared/result.js +6 -0
- package/dist/shared/terminal.js +42 -0
- package/dist/themes/themes.js +84 -0
- package/package.json +49 -4
- package/shell/core/AgentIcon.qml +24 -0
- package/shell/core/AppLogo.qml +48 -0
- package/shell/core/ApprovalRow.qml +197 -0
- package/shell/core/BoardDetail.qml +296 -0
- package/shell/core/BoardList.qml +433 -0
- package/shell/core/BoardNotice.qml +187 -0
- package/shell/core/CardButton.qml +55 -0
- package/shell/core/CardHeader.qml +46 -0
- package/shell/core/ChalkBoard.qml +99 -0
- package/shell/core/CompletionCard.qml +106 -0
- package/shell/core/FlapText.qml +95 -0
- package/shell/core/KeyCap.qml +72 -0
- package/shell/core/Mascot.qml +13 -0
- package/shell/core/MascotBadge.qml +40 -0
- package/shell/core/MascotEffect.qml +40 -0
- package/shell/core/Paper.qml +54 -0
- package/shell/core/PixelGrid.qml +40 -0
- package/shell/core/QuestionRow.qml +161 -0
- package/shell/core/SessionRow.qml +220 -0
- package/shell/core/Stamp.qml +62 -0
- package/shell/core/StatusDots.qml +33 -0
- package/shell/core/Surface.qml +32 -0
- package/shell/core/Tag.qml +22 -0
- package/shell/core/TerminalIcon.qml +34 -0
- package/shell/core/Theme.qml +100 -0
- package/shell/core/TicketDetail.qml +588 -0
- package/shell/core/TicketList.qml +639 -0
- package/shell/core/TicketNotice.qml +198 -0
- package/shell/core/TopsideClient.qml +198 -0
- package/shell/core/UsageLine.qml +106 -0
- package/shell/core/agents.js +79 -0
- package/shell/core/board.js +138 -0
- package/shell/core/hiding.js +29 -0
- package/shell/core/pixels.js +542 -0
- package/shell/core/qmldir +30 -0
- package/shell/core/sounds.js +31 -0
- package/shell/core/themes.js +195 -0
- package/shell/core/ticket.js +131 -0
- package/shell/dms-plugin/TopsideSettings.qml +696 -0
- package/shell/dms-plugin/TopsideWidget.qml +572 -0
- package/shell/dms-plugin/plugin.json +14 -0
- package/shell/pill.qml +279 -0
- package/shell/sekaipop-plugin/Bar.qml +151 -0
- package/shell/sekaipop-plugin/Card.qml +291 -0
- package/shell/sekaipop-plugin/Floating.qml +83 -0
- package/shell/sekaipop-plugin/ListWindow.qml +156 -0
- package/shell/sekaipop-plugin/Popup.qml +70 -0
- package/shell/sekaipop-plugin/Service.qml +414 -0
- package/shell/sekaipop-plugin/ShellLook.qml +43 -0
- package/shell/sekaipop-plugin/StyledCard.qml +179 -0
- package/shell/sekaipop-plugin/plugin.json +109 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
// One-shot runs (`claude -p` / `--print`) come from scripts and other tools,
|
|
4
|
+
// live for seconds, and would each flash a row. The hook leaves them out.
|
|
5
|
+
// The arguments of the nearest Claude Code process in `cmdlines` (one argv
|
|
6
|
+
// per process, nearest first): the native `claude` binary, or node running
|
|
7
|
+
// Claude Code's script. null when none is found.
|
|
8
|
+
export function claudeArgs(cmdlines) {
|
|
9
|
+
for (const argv of cmdlines) {
|
|
10
|
+
const [first = "", second = ""] = argv;
|
|
11
|
+
if (basename(first) === "claude")
|
|
12
|
+
return argv.slice(1);
|
|
13
|
+
if (basename(first) === "node" && (basename(second) === "claude" || second.includes("claude-code")))
|
|
14
|
+
return argv.slice(2);
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
export function isOneShot(cmdlines) {
|
|
19
|
+
const args = claudeArgs(cmdlines);
|
|
20
|
+
return args !== null && args.some((arg) => arg === "-p" || arg === "--print" || arg.startsWith("--print="));
|
|
21
|
+
}
|
|
22
|
+
// A process's argv from /proc; [] when it's gone or unreadable.
|
|
23
|
+
export function readCmdline(pid) {
|
|
24
|
+
try {
|
|
25
|
+
return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter((part) => part !== "");
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Adds and removes Topside's hook entries in a Claude Code settings object
|
|
2
|
+
// without touching anyone else's hooks.
|
|
3
|
+
export const managedMarker = "# topside-managed";
|
|
4
|
+
// What the marker said before the rename from via. Still recognized, so an
|
|
5
|
+
// install replaces the old entries and an uninstall removes them.
|
|
6
|
+
const legacyMarker = "# via-managed";
|
|
7
|
+
// PermissionRequest waits for an answer from the island; the terminal prompt shows
|
|
8
|
+
// in parallel, so a long timeout only costs an idle process (docs/notes/claude-hooks.md).
|
|
9
|
+
export const claudeHookTimeouts = {
|
|
10
|
+
SessionStart: 5,
|
|
11
|
+
SessionEnd: 5,
|
|
12
|
+
UserPromptSubmit: 5,
|
|
13
|
+
PreToolUse: 5,
|
|
14
|
+
PostToolUse: 5,
|
|
15
|
+
PermissionRequest: 600,
|
|
16
|
+
Notification: 5,
|
|
17
|
+
Stop: 5,
|
|
18
|
+
};
|
|
19
|
+
export const managedEvents = Object.keys(claudeHookTimeouts);
|
|
20
|
+
function isRecord(value) {
|
|
21
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
function isManaged(handler) {
|
|
24
|
+
return isRecord(handler) && typeof handler.command === "string" && (handler.command.includes(managedMarker) || handler.command.includes(legacyMarker));
|
|
25
|
+
}
|
|
26
|
+
export function withoutTopsideHooks(settings) {
|
|
27
|
+
if (!isRecord(settings.hooks))
|
|
28
|
+
return settings;
|
|
29
|
+
const hooks = {};
|
|
30
|
+
for (const [event, groups] of Object.entries(settings.hooks)) {
|
|
31
|
+
if (!Array.isArray(groups)) {
|
|
32
|
+
hooks[event] = groups;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const kept = groups.flatMap((group) => {
|
|
36
|
+
if (!isRecord(group) || !Array.isArray(group.hooks))
|
|
37
|
+
return [group];
|
|
38
|
+
const handlers = group.hooks.filter((handler) => !isManaged(handler));
|
|
39
|
+
if (handlers.length === group.hooks.length)
|
|
40
|
+
return [group];
|
|
41
|
+
return handlers.length === 0 ? [] : [{ ...group, hooks: handlers }];
|
|
42
|
+
});
|
|
43
|
+
if (kept.length > 0)
|
|
44
|
+
hooks[event] = kept;
|
|
45
|
+
}
|
|
46
|
+
const next = { ...settings };
|
|
47
|
+
if (Object.keys(hooks).length === 0)
|
|
48
|
+
delete next.hooks;
|
|
49
|
+
else
|
|
50
|
+
next.hooks = hooks;
|
|
51
|
+
return next;
|
|
52
|
+
}
|
|
53
|
+
// `command` runs the Topside CLI; the marker is appended as a shell comment.
|
|
54
|
+
// `timeouts` names the events to hook; Codex's hooks.json has the same shape
|
|
55
|
+
// as Claude Code's settings, so it goes through here with its own table.
|
|
56
|
+
export function withTopsideHooks(settings, command, timeouts = claudeHookTimeouts) {
|
|
57
|
+
const base = withoutTopsideHooks(settings);
|
|
58
|
+
const hooks = isRecord(base.hooks) ? { ...base.hooks } : {};
|
|
59
|
+
for (const [event, timeout] of Object.entries(timeouts)) {
|
|
60
|
+
const existing = Array.isArray(hooks[event]) ? hooks[event] : [];
|
|
61
|
+
const handler = { type: "command", command: `${command} ${managedMarker}`, timeout };
|
|
62
|
+
hooks[event] = [...existing, { hooks: [handler] }];
|
|
63
|
+
}
|
|
64
|
+
return { ...base, hooks };
|
|
65
|
+
}
|
|
66
|
+
export function hooksState(settings, command) {
|
|
67
|
+
if (!isRecord(settings.hooks))
|
|
68
|
+
return "none";
|
|
69
|
+
const commands = Object.values(settings.hooks)
|
|
70
|
+
.filter(Array.isArray)
|
|
71
|
+
.flat()
|
|
72
|
+
.flatMap((group) => (isRecord(group) && Array.isArray(group.hooks) ? group.hooks : []))
|
|
73
|
+
.filter(isManaged)
|
|
74
|
+
.map((handler) => handler.command);
|
|
75
|
+
if (commands.length === 0)
|
|
76
|
+
return "none";
|
|
77
|
+
return commands.every((c) => c === `${command} ${managedMarker}`) ? "this" : "other";
|
|
78
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Plan usage from Claude Code's status line. Claude Code hands its rate
|
|
2
|
+
// limits only to the status line command (rate_limits.five_hour and
|
|
3
|
+
// .seven_day, each with used_percentage and resets_at), never to hooks. So
|
|
4
|
+
// `topside statusline` wraps the user's own status line: it forwards the
|
|
5
|
+
// numbers to the daemon, then runs the original command on the same input.
|
|
6
|
+
import { managedMarker } from "./settings.js";
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
function window(limits, key) {
|
|
11
|
+
const entry = limits[key];
|
|
12
|
+
if (!isRecord(entry) || typeof entry.used_percentage !== "number" || typeof entry.resets_at !== "number")
|
|
13
|
+
return undefined;
|
|
14
|
+
return { usedPercentage: entry.used_percentage, resetsAt: entry.resets_at };
|
|
15
|
+
}
|
|
16
|
+
// The usage in one status line input; null when it carries none (before the
|
|
17
|
+
// first API response, or on an API key without a plan).
|
|
18
|
+
export function parseStatusLineUsage(raw) {
|
|
19
|
+
let input;
|
|
20
|
+
try {
|
|
21
|
+
input = JSON.parse(raw);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
if (!isRecord(input) || !isRecord(input.rate_limits))
|
|
27
|
+
return null;
|
|
28
|
+
const fiveHour = window(input.rate_limits, "five_hour");
|
|
29
|
+
const sevenDay = window(input.rate_limits, "seven_day");
|
|
30
|
+
if (fiveHour === undefined && sevenDay === undefined)
|
|
31
|
+
return null;
|
|
32
|
+
return { ...(fiveHour && { fiveHour }), ...(sevenDay && { sevenDay }) };
|
|
33
|
+
}
|
|
34
|
+
const wrapFlag = " --wrap ";
|
|
35
|
+
function isManaged(command) {
|
|
36
|
+
return command.includes(managedMarker);
|
|
37
|
+
}
|
|
38
|
+
// The status line command the bridge wraps, decoded from its --wrap argument.
|
|
39
|
+
export function wrappedStatusLine(command) {
|
|
40
|
+
const at = command.indexOf(wrapFlag);
|
|
41
|
+
if (at < 0)
|
|
42
|
+
return null;
|
|
43
|
+
const encoded = command.slice(at + wrapFlag.length).split(" ")[0] ?? "";
|
|
44
|
+
return encoded === "" ? null : Buffer.from(encoded, "base64").toString("utf8");
|
|
45
|
+
}
|
|
46
|
+
// `settings` with the status line routed through `command` (`topside
|
|
47
|
+
// statusline`). The original command rides along base64-encoded, so it runs
|
|
48
|
+
// unchanged and comes back byte for byte on uninstall.
|
|
49
|
+
export function withUsageBridge(settings, command) {
|
|
50
|
+
const existing = isRecord(settings.statusLine) ? settings.statusLine : null;
|
|
51
|
+
const current = existing && typeof existing.command === "string" ? existing.command : "";
|
|
52
|
+
const original = isManaged(current) ? (wrappedStatusLine(current) ?? "") : current;
|
|
53
|
+
const bridged = original === "" ? command : `${command}${wrapFlag}${Buffer.from(original, "utf8").toString("base64")}`;
|
|
54
|
+
return { ...settings, statusLine: { ...(existing ?? { type: "command" }), command: `${bridged} ${managedMarker}` } };
|
|
55
|
+
}
|
|
56
|
+
// `settings` with the bridge taken out: the original status line back, or
|
|
57
|
+
// none if there wasn't one.
|
|
58
|
+
export function withoutUsageBridge(settings) {
|
|
59
|
+
const existing = isRecord(settings.statusLine) ? settings.statusLine : null;
|
|
60
|
+
if (!existing || typeof existing.command !== "string" || !isManaged(existing.command))
|
|
61
|
+
return settings;
|
|
62
|
+
const original = wrappedStatusLine(existing.command);
|
|
63
|
+
if (original !== null)
|
|
64
|
+
return { ...settings, statusLine: { ...existing, command: original } };
|
|
65
|
+
const next = { ...settings };
|
|
66
|
+
delete next.statusLine;
|
|
67
|
+
return next;
|
|
68
|
+
}
|
|
69
|
+
// Whether the bridge wraps the status line, and whether it runs `command`.
|
|
70
|
+
export function usageState(settings, command) {
|
|
71
|
+
const existing = isRecord(settings.statusLine) ? settings.statusLine : null;
|
|
72
|
+
const current = existing && typeof existing.command === "string" ? existing.command : "";
|
|
73
|
+
if (!isManaged(current))
|
|
74
|
+
return "none";
|
|
75
|
+
return current === `${command} ${managedMarker}` || current.startsWith(`${command}${wrapFlag}`) ? "this" : "other";
|
|
76
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, openSync, rmSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { err, ok } from "../../shared/result.js";
|
|
4
|
+
// What Topside hooks in Codex (docs/notes/codex-hooks.md). Codex has no
|
|
5
|
+
// Notification event. PermissionRequest waits for the island, like Claude Code's.
|
|
6
|
+
export const codexHookTimeouts = {
|
|
7
|
+
SessionStart: 5,
|
|
8
|
+
SessionEnd: 5,
|
|
9
|
+
UserPromptSubmit: 5,
|
|
10
|
+
PreToolUse: 5,
|
|
11
|
+
PostToolUse: 5,
|
|
12
|
+
PermissionRequest: 600,
|
|
13
|
+
Stop: 5,
|
|
14
|
+
};
|
|
15
|
+
// Flags of the codex command that take a value, so the subcommand after them is found.
|
|
16
|
+
const valueFlags = new Set(["-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a", "--ask-for-approval", "-C", "--cd", "-i", "--image", "--add-dir", "--enable", "--disable", "--local-provider"]);
|
|
17
|
+
// The native codex binary, not the npm launcher (node running bin/codex.js).
|
|
18
|
+
export function isCodexBinary(argv) {
|
|
19
|
+
return basename(argv[0] ?? "") === "codex";
|
|
20
|
+
}
|
|
21
|
+
// Process ancestry cut to start at the nearest codex binary, so the session
|
|
22
|
+
// is watched through Codex itself, not the short-lived shell that ran the
|
|
23
|
+
// hook. null when no codex binary is an ancestor.
|
|
24
|
+
export function fromCodex(pids, cmdline) {
|
|
25
|
+
const at = pids.findIndex((pid) => isCodexBinary(cmdline(pid)));
|
|
26
|
+
return at < 0 ? null : pids.slice(at);
|
|
27
|
+
}
|
|
28
|
+
// `codex exec` (alias `e`) and `codex review` run once from scripts: no row for them.
|
|
29
|
+
export function isCodexOneShot(argv) {
|
|
30
|
+
const args = argv.slice(1);
|
|
31
|
+
for (let i = 0; i < args.length; i++) {
|
|
32
|
+
const arg = args[i] ?? "";
|
|
33
|
+
if (valueFlags.has(arg)) {
|
|
34
|
+
i++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (arg.startsWith("-"))
|
|
38
|
+
continue;
|
|
39
|
+
return arg === "exec" || arg === "e" || arg === "review";
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
// stdout for Codex's PermissionRequest hook. Codex fails closed on
|
|
44
|
+
// updatedPermissions and updatedInput, so every allow is a plain allow.
|
|
45
|
+
export function formatCodexDecision(decision) {
|
|
46
|
+
if (decision === "none")
|
|
47
|
+
return "";
|
|
48
|
+
const body = decision === "deny" ? { behavior: "deny", message: "Denied from Topside" } : { behavior: "allow" };
|
|
49
|
+
return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: body } })}\n`;
|
|
50
|
+
}
|
|
51
|
+
// Codex runs a handler only once the user trusts it with /hooks, and a
|
|
52
|
+
// changed command loses that trust. Topside can't check the hash, so an
|
|
53
|
+
// install that changes hooks.json leaves this empty file in the data folder,
|
|
54
|
+
// and the first `hook codex` that runs removes it.
|
|
55
|
+
export function untrustedFlagPath(dbPath) {
|
|
56
|
+
return join(dirname(dbPath), "codex-hooks-untrusted");
|
|
57
|
+
}
|
|
58
|
+
export function setUntrusted(path) {
|
|
59
|
+
try {
|
|
60
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
61
|
+
closeSync(openSync(path, "a", 0o600));
|
|
62
|
+
return ok(undefined);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
return err(`cannot write ${path}: ${String(error)}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function clearUntrusted(path) {
|
|
69
|
+
rmSync(path, { force: true });
|
|
70
|
+
}
|
|
71
|
+
export function isUntrusted(path) {
|
|
72
|
+
return existsSync(path);
|
|
73
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/;
|
|
2
|
+
export function patchFiles(patch) {
|
|
3
|
+
const files = [];
|
|
4
|
+
for (const line of patch.split("\n")) {
|
|
5
|
+
const match = header.exec(line);
|
|
6
|
+
if (match === null)
|
|
7
|
+
continue;
|
|
8
|
+
const action = match[1] === "Add" ? "add" : match[1] === "Delete" ? "delete" : "update";
|
|
9
|
+
files.push({ action, path: (match[2] ?? "").trim() });
|
|
10
|
+
}
|
|
11
|
+
return files;
|
|
12
|
+
}
|
|
13
|
+
// The change itself, without the `***` and `@@` lines.
|
|
14
|
+
export function patchLines(patch) {
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const line of patch.replace(/\n$/, "").split("\n")) {
|
|
17
|
+
if (line.startsWith("***") || line.startsWith("@@"))
|
|
18
|
+
continue;
|
|
19
|
+
if (line.startsWith("+"))
|
|
20
|
+
out.push({ kind: "add", text: line.slice(1) });
|
|
21
|
+
else if (line.startsWith("-"))
|
|
22
|
+
out.push({ kind: "remove", text: line.slice(1) });
|
|
23
|
+
else if (line.startsWith(" "))
|
|
24
|
+
out.push({ kind: "context", text: line.slice(1) });
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
// "Writing a.ts", "Editing a.ts", "Deleting a.ts", or "Editing N files".
|
|
29
|
+
export function describePatch(patch) {
|
|
30
|
+
const files = patchFiles(patch);
|
|
31
|
+
if (files.length === 0)
|
|
32
|
+
return "Editing files";
|
|
33
|
+
if (files.length > 1)
|
|
34
|
+
return `Editing ${files.length} files`;
|
|
35
|
+
const [file] = files;
|
|
36
|
+
const name = file.path.split("/").at(-1) ?? file.path;
|
|
37
|
+
const verb = file.action === "add" ? "Writing" : file.action === "delete" ? "Deleting" : "Editing";
|
|
38
|
+
return `${verb} ${name}`;
|
|
39
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
// The first `rate_limits` object anywhere in a parsed line.
|
|
6
|
+
function findLimits(value) {
|
|
7
|
+
if (!isRecord(value))
|
|
8
|
+
return null;
|
|
9
|
+
if (isRecord(value.rate_limits))
|
|
10
|
+
return value.rate_limits;
|
|
11
|
+
for (const child of Object.values(value)) {
|
|
12
|
+
const found = findLimits(child);
|
|
13
|
+
if (found !== null)
|
|
14
|
+
return found;
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
function window(entry) {
|
|
19
|
+
if (!isRecord(entry))
|
|
20
|
+
return null;
|
|
21
|
+
const { used_percent: used, window_minutes: minutes, resets_at: resets } = entry;
|
|
22
|
+
if (typeof used !== "number" || typeof minutes !== "number" || typeof resets !== "number")
|
|
23
|
+
return null;
|
|
24
|
+
return { minutes, window: { usedPercentage: used, resetsAt: resets } };
|
|
25
|
+
}
|
|
26
|
+
// The last limits in the tail of a session file; null when it has none.
|
|
27
|
+
// A window of a day or less is the 5 h slot, a longer one the 7 d slot.
|
|
28
|
+
export function codexUsage(tail) {
|
|
29
|
+
const lines = tail.split("\n");
|
|
30
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
31
|
+
const line = lines[i] ?? "";
|
|
32
|
+
if (!line.includes('"rate_limits"'))
|
|
33
|
+
continue;
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(line);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
continue; // the first line of a tail is usually cut
|
|
40
|
+
}
|
|
41
|
+
const limits = findLimits(parsed);
|
|
42
|
+
if (limits === null)
|
|
43
|
+
continue;
|
|
44
|
+
const usage = {};
|
|
45
|
+
for (const entry of [limits.primary, limits.secondary]) {
|
|
46
|
+
const read = window(entry);
|
|
47
|
+
if (read === null)
|
|
48
|
+
continue;
|
|
49
|
+
if (read.minutes <= 1440)
|
|
50
|
+
usage.fiveHour = read.window;
|
|
51
|
+
else
|
|
52
|
+
usage.sevenDay = read.window;
|
|
53
|
+
}
|
|
54
|
+
if (usage.fiveHour !== undefined || usage.sevenDay !== undefined)
|
|
55
|
+
return usage;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
// The last `bytes` of a file as text; "" when it can't be read.
|
|
60
|
+
export function readTail(path, bytes = 256 * 1024) {
|
|
61
|
+
let fd = null;
|
|
62
|
+
try {
|
|
63
|
+
fd = openSync(path, "r");
|
|
64
|
+
const size = fstatSync(fd).size;
|
|
65
|
+
const length = Math.min(size, bytes);
|
|
66
|
+
const buffer = Buffer.alloc(length);
|
|
67
|
+
readSync(fd, buffer, 0, length, size - length);
|
|
68
|
+
return buffer.toString("utf8");
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
if (fd !== null)
|
|
75
|
+
closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { err, ok } from "../../shared/result.js";
|
|
5
|
+
export const extensionAgents = ["pi", "omp"];
|
|
6
|
+
export function isExtensionAgent(value) {
|
|
7
|
+
return value === "pi" || value === "omp";
|
|
8
|
+
}
|
|
9
|
+
// The marker on the file's first line: the file is ours to replace or remove.
|
|
10
|
+
export const extensionMarker = "topside-managed";
|
|
11
|
+
// The agent's own folder; the agent is set up when it exists.
|
|
12
|
+
export function agentHome(agent, home = homedir()) {
|
|
13
|
+
return join(home, agent === "pi" ? ".pi" : ".omp", "agent");
|
|
14
|
+
}
|
|
15
|
+
export function extensionPath(agent, home = homedir()) {
|
|
16
|
+
return join(agentHome(agent, home), "extensions", "topside.ts");
|
|
17
|
+
}
|
|
18
|
+
// The extension for `agent`, reporting to `command` (argv of the Topside CLI)
|
|
19
|
+
// on `socket` ("" for the default socket).
|
|
20
|
+
export function extensionSource(agent, command, socket) {
|
|
21
|
+
return template
|
|
22
|
+
.replace("__AGENT_PLAIN__", agent)
|
|
23
|
+
.replace("__AGENT__", JSON.stringify(agent))
|
|
24
|
+
.replace("__COMMAND__", JSON.stringify(command))
|
|
25
|
+
.replace("__SOCKET__", JSON.stringify(socket));
|
|
26
|
+
}
|
|
27
|
+
// The lines that say which copy of Topside and which socket a file reports to.
|
|
28
|
+
export function extensionTarget(source) {
|
|
29
|
+
return source.split("\n").filter((line) => line.startsWith("const COMMAND = ") || line.startsWith("const SOCKET = "));
|
|
30
|
+
}
|
|
31
|
+
function read(path) {
|
|
32
|
+
try {
|
|
33
|
+
return readFileSync(path, "utf8");
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Writes or removes the file. A file at that path without the marker isn't
|
|
40
|
+
// ours and is never touched. `changed` is false when there was nothing to do.
|
|
41
|
+
export function updateExtension(action, path, source) {
|
|
42
|
+
const existing = read(path);
|
|
43
|
+
if (existing !== null && !existing.includes(extensionMarker))
|
|
44
|
+
return err(`${path} isn't Topside's; left alone`);
|
|
45
|
+
try {
|
|
46
|
+
if (action === "uninstall") {
|
|
47
|
+
if (existing === null)
|
|
48
|
+
return ok({ changed: false });
|
|
49
|
+
rmSync(path, { force: true });
|
|
50
|
+
return ok({ changed: true });
|
|
51
|
+
}
|
|
52
|
+
if (existing === source)
|
|
53
|
+
return ok({ changed: false });
|
|
54
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
55
|
+
// Written beside it, then moved, so the agent never loads half a file.
|
|
56
|
+
const temporary = join(dirname(path), `.${basename(path)}.${process.pid}`);
|
|
57
|
+
writeFileSync(temporary, source);
|
|
58
|
+
renameSync(temporary, path);
|
|
59
|
+
return ok({ changed: true });
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
return err(`cannot ${action === "install" ? "write" : "remove"} ${path}: ${String(error)}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// none: no file of ours; this: ours, reporting to this copy; other: ours,
|
|
66
|
+
// reporting elsewhere (another install, or another socket).
|
|
67
|
+
export function extensionState(path, source) {
|
|
68
|
+
const existing = read(path);
|
|
69
|
+
if (existing === null || !existing.includes(extensionMarker))
|
|
70
|
+
return "none";
|
|
71
|
+
return extensionTarget(existing).join("\n") === extensionTarget(source).join("\n") ? "this" : "other";
|
|
72
|
+
}
|
|
73
|
+
// At daemon start: brings each installed file up to what this version writes,
|
|
74
|
+
// so an update needs no click. Only a file that already reports to this copy
|
|
75
|
+
// and socket; one that points elsewhere is left for "Use this copy".
|
|
76
|
+
// Returns the agents whose file was rewritten.
|
|
77
|
+
export function refreshExtensions(command, socket, home = homedir()) {
|
|
78
|
+
return extensionAgents.filter((agent) => {
|
|
79
|
+
const path = extensionPath(agent, home);
|
|
80
|
+
const installed = read(path);
|
|
81
|
+
const current = extensionSource(agent, command, socket);
|
|
82
|
+
if (installed === null || !installed.includes(extensionMarker) || installed === current)
|
|
83
|
+
return false;
|
|
84
|
+
const target = extensionTarget(installed);
|
|
85
|
+
if (target.length === 0 || target.join("\n") !== extensionTarget(current).join("\n"))
|
|
86
|
+
return false;
|
|
87
|
+
return updateExtension("install", path, current).ok;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
// Whether the agent's extension is installed (by any copy), for discovery.
|
|
91
|
+
export function hasExtension(agent, home = homedir()) {
|
|
92
|
+
const path = extensionPath(agent, home);
|
|
93
|
+
return existsSync(path) && (read(path) ?? "").includes(extensionMarker);
|
|
94
|
+
}
|
|
95
|
+
// What makes an open session load a new file: pi reloads extensions with
|
|
96
|
+
// /reload; omp only loads them at startup.
|
|
97
|
+
export function reloadAdvice(agent) {
|
|
98
|
+
return agent === "omp" ? "restart omp" : "run /reload in pi";
|
|
99
|
+
}
|
|
100
|
+
// pi: node running the launcher named pi (or a process titled pi). omp: its
|
|
101
|
+
// Bun-compiled binary, or bun running a script named omp.
|
|
102
|
+
export function isPiProcess(argv) {
|
|
103
|
+
const [first = "", second = ""] = argv;
|
|
104
|
+
return basename(first) === "pi" || (basename(first) === "node" && basename(second) === "pi");
|
|
105
|
+
}
|
|
106
|
+
export function isOmpProcess(argv) {
|
|
107
|
+
const [first = "", second = ""] = argv;
|
|
108
|
+
return basename(first) === "omp" || (basename(first) === "bun" && basename(second) === "omp");
|
|
109
|
+
}
|
|
110
|
+
export function isAgentProcess(agent, argv) {
|
|
111
|
+
return agent === "pi" ? isPiProcess(argv) : isOmpProcess(argv);
|
|
112
|
+
}
|
|
113
|
+
// The extension's source. pi runs it under Node, omp under Bun; every handler
|
|
114
|
+
// swallows its own errors, since a monitor must never break the agent it
|
|
115
|
+
// watches. Kept free of backticks, placeholders and backslashes so it sits in
|
|
116
|
+
// a plain template string.
|
|
117
|
+
const template = `
|
|
118
|
+
// topside-managed: written by Topside. Edits are lost on reinstall.
|
|
119
|
+
// Remove it with "topside hooks uninstall __AGENT_PLAIN__" or by deleting this file.
|
|
120
|
+
import { spawn } from "node:child_process";
|
|
121
|
+
|
|
122
|
+
const AGENT = __AGENT__;
|
|
123
|
+
const COMMAND = __COMMAND__;
|
|
124
|
+
const SOCKET = __SOCKET__;
|
|
125
|
+
|
|
126
|
+
export default function (pi: any) {
|
|
127
|
+
const text = (message: any): string =>
|
|
128
|
+
(Array.isArray(message?.content) ? message.content : [])
|
|
129
|
+
.filter((part: any) => part?.type === "text" && typeof part.text === "string")
|
|
130
|
+
.map((part: any) => part.text)
|
|
131
|
+
.join(String.fromCharCode(10));
|
|
132
|
+
|
|
133
|
+
const assistants = (ctx: any): any[] => {
|
|
134
|
+
const manager = ctx?.sessionManager;
|
|
135
|
+
const entries = manager?.getBranch?.() ?? manager?.getEntries?.() ?? [];
|
|
136
|
+
return entries
|
|
137
|
+
.filter((entry: any) => entry?.type === "message" && entry.message?.role === "assistant")
|
|
138
|
+
.map((entry: any) => entry.message);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// What the session has cost: omp keeps totals; for pi, add up the replies.
|
|
142
|
+
const spend = (ctx: any) => {
|
|
143
|
+
const model = ctx?.model?.id ?? ctx?.model?.name ?? "";
|
|
144
|
+
const stats = ctx?.sessionManager?.getUsageStatistics?.();
|
|
145
|
+
if (stats) return { cost: Number(stats.cost) || 0, tokens: Number(stats.totalTokens) || 0, model };
|
|
146
|
+
let cost = 0;
|
|
147
|
+
let tokens = 0;
|
|
148
|
+
for (const message of assistants(ctx)) {
|
|
149
|
+
cost += Number(message?.usage?.cost?.total) || 0;
|
|
150
|
+
tokens += Number(message?.usage?.totalTokens) || 0;
|
|
151
|
+
}
|
|
152
|
+
return { cost, tokens, model };
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// Starts the hook with one payload. With "wait", resolves with what the
|
|
156
|
+
// hook printed once it exits; otherwise at once, with "".
|
|
157
|
+
const run = (ctx: any, name: string, extra: Record<string, unknown>, wait: boolean): Promise<string> =>
|
|
158
|
+
new Promise((resolve) => {
|
|
159
|
+
try {
|
|
160
|
+
// One-shot and scripted runs come and go; only a terminal session shows.
|
|
161
|
+
if (ctx?.mode && ctx.mode !== "tui") return resolve("");
|
|
162
|
+
if (ctx?.agent?.kind === "sub") return resolve("");
|
|
163
|
+
const manager = ctx?.sessionManager;
|
|
164
|
+
const session = manager?.getSessionId?.();
|
|
165
|
+
if (!session) return resolve("");
|
|
166
|
+
const payload = {
|
|
167
|
+
hook_event_name: name,
|
|
168
|
+
session_id: session,
|
|
169
|
+
cwd: ctx?.cwd ?? process.cwd(),
|
|
170
|
+
session_title: manager?.getSessionName?.() ?? "",
|
|
171
|
+
transcript_path: manager?.getSessionFile?.() ?? "",
|
|
172
|
+
...extra,
|
|
173
|
+
};
|
|
174
|
+
const env = SOCKET ? { ...process.env, TOPSIDE_SOCKET: SOCKET } : process.env;
|
|
175
|
+
const child = spawn(COMMAND[0], [...COMMAND.slice(1), "hook", AGENT], { stdio: ["pipe", wait ? "pipe" : "ignore", "ignore"], env });
|
|
176
|
+
let printed = "";
|
|
177
|
+
child.stdout?.on("data", (chunk: any) => (printed += String(chunk)));
|
|
178
|
+
child.on("error", () => resolve(""));
|
|
179
|
+
child.on("close", () => resolve(printed));
|
|
180
|
+
child.stdin?.on("error", () => {});
|
|
181
|
+
child.stdin?.end(JSON.stringify(payload));
|
|
182
|
+
if (!wait) resolve("");
|
|
183
|
+
} catch {
|
|
184
|
+
// Topside isn't there, or isn't runnable: carry on without it.
|
|
185
|
+
resolve("");
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const send = (ctx: any, name: string, extra: Record<string, unknown> = {}) => {
|
|
190
|
+
void run(ctx, name, extra, false);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// The island's gate: a shell command waits for the hook, which asks on the
|
|
194
|
+
// island when the gate is on and the command is on its list. The hook
|
|
195
|
+
// answers within 25 s; the timer here is for a hook that never comes back.
|
|
196
|
+
const gate = async (ctx: any, extra: Record<string, unknown>) => {
|
|
197
|
+
const late = new Promise<string>((resolve) => setTimeout(() => resolve("late"), 28000));
|
|
198
|
+
const printed = await Promise.race([run(ctx, "PreToolUse", extra, true), late]);
|
|
199
|
+
if (printed === "late") return { block: true, reason: "Blocked: Topside didn't answer" };
|
|
200
|
+
if (!printed.trim()) return undefined;
|
|
201
|
+
const decision = JSON.parse(printed)?.hookSpecificOutput?.decision;
|
|
202
|
+
if (decision?.behavior !== "deny") return undefined;
|
|
203
|
+
return { block: true, reason: String(decision.message || "Denied from Topside") };
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const on = (event: string, handler: (event: any, ctx: any) => void) => {
|
|
207
|
+
try {
|
|
208
|
+
pi.on(event, (payload: any, ctx: any) => {
|
|
209
|
+
try {
|
|
210
|
+
handler(payload, ctx);
|
|
211
|
+
} catch {
|
|
212
|
+
// Never let a report get in the agent's way.
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
} catch {
|
|
216
|
+
// This agent doesn't have that event.
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// pi calls its tools "bash", "read", "edit"; Topside knows them capitalized,
|
|
221
|
+
// with the file under "file_path".
|
|
222
|
+
const tool = (name: unknown) => {
|
|
223
|
+
const text = String(name ?? "");
|
|
224
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
225
|
+
};
|
|
226
|
+
const input = (value: any) =>
|
|
227
|
+
value && typeof value === "object" && value.path && !value.file_path ? { ...value, file_path: value.path } : value;
|
|
228
|
+
|
|
229
|
+
const finished = (ctx: any) => {
|
|
230
|
+
const replies = assistants(ctx);
|
|
231
|
+
send(ctx, "Stop", { last_assistant_message: text(replies[replies.length - 1]), topside_spend: spend(ctx) });
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
on("session_start", (_event, ctx) => send(ctx, "SessionStart"));
|
|
235
|
+
on("before_agent_start", (event, ctx) => send(ctx, "UserPromptSubmit", { prompt: String(event?.prompt ?? "") }));
|
|
236
|
+
try {
|
|
237
|
+
pi.on("tool_call", async (event: any, ctx: any) => {
|
|
238
|
+
try {
|
|
239
|
+
const extra = {
|
|
240
|
+
tool_name: tool(event?.toolName),
|
|
241
|
+
tool_input: input(event?.input),
|
|
242
|
+
tool_use_id: String(event?.toolCallId ?? ""),
|
|
243
|
+
};
|
|
244
|
+
if (typeof event?.input?.command === "string") return await gate(ctx, extra);
|
|
245
|
+
send(ctx, "PreToolUse", extra);
|
|
246
|
+
} catch {
|
|
247
|
+
// A broken report must not stop the tool.
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
});
|
|
251
|
+
} catch {
|
|
252
|
+
// This agent doesn't have that event.
|
|
253
|
+
}
|
|
254
|
+
on("tool_result", (event, ctx) =>
|
|
255
|
+
send(ctx, "PostToolUse", { tool_name: tool(event?.toolName), tool_use_id: String(event?.toolCallId ?? "") }),
|
|
256
|
+
);
|
|
257
|
+
// omp can ask before a tool runs; Topside shows the session as waiting.
|
|
258
|
+
on("tool_approval_requested", (event, ctx) =>
|
|
259
|
+
send(ctx, "Notification", {
|
|
260
|
+
notification_type: "permission_prompt",
|
|
261
|
+
message: "Wants to run " + tool(event?.toolName),
|
|
262
|
+
}),
|
|
263
|
+
);
|
|
264
|
+
// The turn is over: pi says so with agent_settled, omp with session_stop.
|
|
265
|
+
on(AGENT === "omp" ? "session_stop" : "agent_settled", (_event, ctx) => finished(ctx));
|
|
266
|
+
on("session_shutdown", (event, ctx) => {
|
|
267
|
+
// A reload keeps the session; the next session_start picks it up again.
|
|
268
|
+
if (event?.reason !== "reload") send(ctx, "SessionEnd");
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
`.trimStart();
|