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,173 @@
1
+ import { err, ok } from "../../shared/result.js";
2
+ function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+ function str(input, key) {
6
+ const value = input[key];
7
+ return typeof value === "string" ? value : "";
8
+ }
9
+ // Background sessions run under Claude's own daemon with no terminal of their
10
+ // own. Topside leaves them to Claude: no row, no approvals. One started with
11
+ // claude --bg has CLAUDE_CODE_SESSION_KIND=bg; one moved there with /bg only
12
+ // has CLAUDE_JOB_DIR. Foreground sessions have neither (Claude Code 2.1.323).
13
+ export function isBackgroundSession(env) {
14
+ return env.CLAUDE_CODE_SESSION_KIND === "bg" || Boolean(env.CLAUDE_JOB_DIR);
15
+ }
16
+ // Maps one Claude Code hook stdin payload to an agent-neutral event.
17
+ // Returns ok(null) for hook events Topside doesn't track. Codex's payloads
18
+ // have the same fields (docs/notes/codex-hooks.md), so they come through
19
+ // here too, tagged with their own agent.
20
+ export function parseHookInput(raw, origin, agent = "claude") {
21
+ let input;
22
+ try {
23
+ input = JSON.parse(raw);
24
+ }
25
+ catch {
26
+ return err("hook input is not JSON");
27
+ }
28
+ if (!isRecord(input))
29
+ return err("hook input is not an object");
30
+ const sessionId = str(input, "session_id");
31
+ if (sessionId === "")
32
+ return err("hook input has no session_id");
33
+ const base = { agent, sessionId, cwd: str(input, "cwd"), ...origin };
34
+ switch (str(input, "hook_event_name")) {
35
+ case "SessionStart":
36
+ return ok({ ...base, type: "session-start", name: str(input, "session_title") });
37
+ case "SessionEnd":
38
+ return ok({ ...base, type: "session-end" });
39
+ case "UserPromptSubmit":
40
+ return ok({ ...base, type: "prompt", text: str(input, "prompt"), name: str(input, "session_title") });
41
+ case "PreToolUse":
42
+ return ok({
43
+ ...base,
44
+ type: "tool-start",
45
+ toolUseId: str(input, "tool_use_id"),
46
+ toolName: str(input, "tool_name"),
47
+ toolInput: input.tool_input,
48
+ });
49
+ case "PostToolUse":
50
+ return ok({
51
+ ...base,
52
+ type: "tool-end",
53
+ toolUseId: str(input, "tool_use_id"),
54
+ toolName: str(input, "tool_name"),
55
+ });
56
+ case "PermissionRequest":
57
+ return ok({
58
+ ...base,
59
+ type: "approval-request",
60
+ toolName: str(input, "tool_name"),
61
+ toolInput: input.tool_input,
62
+ always: describeSuggestions(input.permission_suggestions),
63
+ inFront: false, // filled in by the hook command, like turn-end's
64
+ });
65
+ case "Notification":
66
+ return ok({ ...base, type: "attention", reason: attentionReason(str(input, "notification_type")), message: str(input, "message") });
67
+ case "Stop":
68
+ // inFront is filled in by the hook command, which can ask the compositor.
69
+ return ok({ ...base, type: "turn-end", message: str(input, "last_assistant_message"), inFront: false, ...spendOf(input) });
70
+ default:
71
+ return ok(null);
72
+ }
73
+ }
74
+ // topside_spend, which the pi and omp extension adds to Stop. The model it
75
+ // names isn't shown, so it isn't read.
76
+ function spendOf(input) {
77
+ const fields = input.topside_spend;
78
+ if (!isRecord(fields))
79
+ return {};
80
+ const cost = typeof fields.cost === "number" && fields.cost > 0 ? fields.cost : 0;
81
+ const tokens = typeof fields.tokens === "number" && fields.tokens > 0 ? Math.round(fields.tokens) : 0;
82
+ return cost > 0 || tokens > 0 ? { spend: { cost, tokens } } : {};
83
+ }
84
+ function attentionReason(notificationType) {
85
+ if (notificationType === "permission_prompt")
86
+ return "permission";
87
+ if (notificationType === "idle_prompt")
88
+ return "idle";
89
+ return "other";
90
+ }
91
+ // The permission_suggestions of a PermissionRequest payload, or null.
92
+ // Always Allow sends them back unchanged as updatedPermissions.
93
+ export function permissionSuggestions(raw) {
94
+ try {
95
+ const input = JSON.parse(raw);
96
+ return isRecord(input) ? (input.permission_suggestions ?? null) : null;
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ // What Always Allow will do with these suggestions, in a few words; "" when
103
+ // there's nothing to apply, so the card hides the button. Measured shapes are
104
+ // in docs/notes/claude-hooks.md.
105
+ export function describeSuggestions(suggestions) {
106
+ if (!Array.isArray(suggestions) || suggestions.length === 0)
107
+ return "";
108
+ const parts = suggestions.map(describeSuggestion).filter((part) => part !== "");
109
+ return parts.length === 0 ? "Apply Claude Code's suggestion" : parts.join("; ");
110
+ }
111
+ // One entry in words; "" for entries that ride along unlabeled, such as addDirectories.
112
+ function describeSuggestion(entry) {
113
+ if (!isRecord(entry))
114
+ return "";
115
+ switch (str(entry, "type")) {
116
+ case "setMode": {
117
+ const mode = str(entry, "mode");
118
+ if (mode === "")
119
+ return "";
120
+ return mode === "acceptEdits" ? "Accept edits for the rest of this session" : `Switch this session to ${mode} mode`;
121
+ }
122
+ case "addRules": {
123
+ const rules = Array.isArray(entry.rules) ? entry.rules.filter(isRecord) : [];
124
+ const names = rules
125
+ .filter((rule) => str(rule, "toolName") !== "")
126
+ .map((rule) => (str(rule, "ruleContent") === "" ? str(rule, "toolName") : `${str(rule, "toolName")}(${str(rule, "ruleContent")})`));
127
+ if (names.length === 0)
128
+ return "";
129
+ const place = str(entry, "destination") === "session" ? "this session" : "this project";
130
+ return `Always allow ${names.join(", ")} in ${place}`;
131
+ }
132
+ default:
133
+ return "";
134
+ }
135
+ }
136
+ // stdout for a PermissionRequest hook. Empty string leaves the terminal prompt in charge.
137
+ // Bypass isn't offered: setMode bypassPermissions does nothing in a session
138
+ // that wasn't started with it, while setMode auto does take effect.
139
+ export function formatDecision(decision, suggestions = null) {
140
+ if (decision === "none")
141
+ return "";
142
+ const body = decision === "deny"
143
+ ? { behavior: "deny", message: "Denied from Topside" }
144
+ : decision === "always" && Array.isArray(suggestions) && suggestions.length > 0
145
+ ? { behavior: "allow", updatedPermissions: suggestions }
146
+ : decision === "auto"
147
+ ? { behavior: "allow", updatedPermissions: [{ type: "setMode", mode: "auto", destination: "session" }] }
148
+ : { behavior: "allow" };
149
+ return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: body } })}\n`;
150
+ }
151
+ // AskUserQuestion's tool_input.questions, read tolerantly. Empty when the
152
+ // input doesn't look like a question we can show.
153
+ export function parseQuestions(toolInput) {
154
+ if (!isRecord(toolInput) || !Array.isArray(toolInput.questions))
155
+ return [];
156
+ const questions = [];
157
+ for (const item of toolInput.questions) {
158
+ if (!isRecord(item) || !Array.isArray(item.options))
159
+ return [];
160
+ const options = item.options.filter(isRecord).map((o) => ({ label: str(o, "label"), description: str(o, "description") }));
161
+ if (str(item, "question") === "" || options.length === 0 || options.some((o) => o.label === ""))
162
+ return [];
163
+ questions.push({ question: str(item, "question"), header: str(item, "header"), options, multiSelect: item.multiSelect === true });
164
+ }
165
+ return questions;
166
+ }
167
+ // stdout for a PermissionRequest hook that answers AskUserQuestion: allow, plus
168
+ // the original questions with the answers (updatedInput replaces the whole input).
169
+ export function formatAnswers(toolInput, answers) {
170
+ const questions = isRecord(toolInput) ? toolInput.questions : [];
171
+ const decision = { behavior: "allow", updatedInput: { questions, answers } };
172
+ return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision } })}\n`;
173
+ }
@@ -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
+ }