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.
- package/LICENSE +21 -0
- package/README.md +217 -2
- package/contrib/aur/.SRCINFO +20 -0
- package/contrib/aur/PKGBUILD +35 -0
- package/contrib/aur/topside-arch.install +28 -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 +615 -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 +179 -0
- package/dist/daemon/store.js +176 -0
- package/dist/dms/setup.js +137 -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 +267 -0
- package/dist/service/unit.js +77 -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 +33 -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 +336 -0
- package/shell/core/BoardList.qml +419 -0
- package/shell/core/BoardNotice.qml +189 -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 +110 -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 +257 -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 +657 -0
- package/shell/core/TicketList.qml +717 -0
- package/shell/core/TicketNotice.qml +198 -0
- package/shell/core/TopsideClient.qml +201 -0
- package/shell/core/UsageLine.qml +106 -0
- package/shell/core/agents.js +79 -0
- package/shell/core/board.js +132 -0
- package/shell/core/hiding.js +68 -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 +170 -0
- package/shell/dms-plugin/TopsideSettings.qml +696 -0
- package/shell/dms-plugin/TopsideWidget.qml +554 -0
- package/shell/dms-plugin/plugin.json +14 -0
- package/shell/pill.qml +279 -0
- package/shell/sekaipop-plugin/Bar.qml +150 -0
- package/shell/sekaipop-plugin/Card.qml +296 -0
- package/shell/sekaipop-plugin/Floating.qml +74 -0
- package/shell/sekaipop-plugin/ListWindow.qml +156 -0
- package/shell/sekaipop-plugin/Popup.qml +70 -0
- package/shell/sekaipop-plugin/Service.qml +418 -0
- package/shell/sekaipop-plugin/ShellLook.qml +43 -0
- package/shell/sekaipop-plugin/StyledCard.qml +194 -0
- package/shell/sekaipop-plugin/place.js +28 -0
- package/shell/sekaipop-plugin/plugin.json +109 -0
|
@@ -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();
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// pi and omp run tools without asking. With the gate on, Topside asks first
|
|
2
|
+
// for the few shell commands that are hard to take back (VIA-PARITY §22).
|
|
3
|
+
// How long the hook waits for an answer. omp cuts a tool_call handler off
|
|
4
|
+
// after 30 s, so the answer has to come sooner; no answer is a deny.
|
|
5
|
+
export const gateTimeoutMs = 25_000;
|
|
6
|
+
export const gateTimeoutMessage = "Blocked: nobody answered in Topside within 25 seconds";
|
|
7
|
+
const shells = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
|
|
8
|
+
const downloaders = new Set(["curl", "wget"]);
|
|
9
|
+
// Why `command` is one to ask about first, or null when it can just run.
|
|
10
|
+
// The command is split the way a shell would, so the gate looks inside
|
|
11
|
+
// `sh -c '…'`, `$(…)`, `xargs`, `find -exec` and the like, and a risky word
|
|
12
|
+
// inside a quoted message doesn't count.
|
|
13
|
+
export function riskyCommandReason(command) {
|
|
14
|
+
return riskyIn(command, 0);
|
|
15
|
+
}
|
|
16
|
+
function riskyIn(script, depth) {
|
|
17
|
+
// Scripts inside scripts inside scripts: stop before it gets silly.
|
|
18
|
+
if (depth >= 5)
|
|
19
|
+
return null;
|
|
20
|
+
const lexed = lex(script);
|
|
21
|
+
let previous = "";
|
|
22
|
+
for (const command of lexed.commands) {
|
|
23
|
+
const words = unwrapped(command.words);
|
|
24
|
+
const name = baseName(words[0] ?? "");
|
|
25
|
+
if (command.piped && shells.has(name) && downloaders.has(previous))
|
|
26
|
+
return "runs a downloaded script";
|
|
27
|
+
const reason = riskyWords(words, depth);
|
|
28
|
+
if (reason !== null)
|
|
29
|
+
return reason;
|
|
30
|
+
previous = name;
|
|
31
|
+
}
|
|
32
|
+
for (const inner of lexed.substitutions) {
|
|
33
|
+
const reason = riskyIn(inner, depth + 1);
|
|
34
|
+
if (reason !== null)
|
|
35
|
+
return reason;
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
function riskyWords(words, depth) {
|
|
40
|
+
if (words.length === 0)
|
|
41
|
+
return null;
|
|
42
|
+
const name = baseName(words[0] ?? "");
|
|
43
|
+
const rest = words.slice(1);
|
|
44
|
+
const short = (letter) => rest.some((word) => word.startsWith("-") && !word.startsWith("--") && word.includes(letter));
|
|
45
|
+
switch (name) {
|
|
46
|
+
case "sudo":
|
|
47
|
+
case "doas":
|
|
48
|
+
return "runs as root";
|
|
49
|
+
case "rm": {
|
|
50
|
+
const recursive = short("r") || short("R") || rest.includes("--recursive");
|
|
51
|
+
return recursive && (short("f") || rest.includes("--force")) ? "deletes files for good" : null;
|
|
52
|
+
}
|
|
53
|
+
case "git":
|
|
54
|
+
if (rest.includes("push") && (short("f") || rest.some((word) => word.startsWith("--force"))))
|
|
55
|
+
return "overwrites the remote branch";
|
|
56
|
+
return rest.includes("reset") && rest.includes("--hard") ? "throws away local changes" : null;
|
|
57
|
+
case "find":
|
|
58
|
+
return findReason(rest, depth);
|
|
59
|
+
case "eval":
|
|
60
|
+
return riskyIn(rest.join(" "), depth + 1);
|
|
61
|
+
default: {
|
|
62
|
+
if (!shells.has(name))
|
|
63
|
+
return null;
|
|
64
|
+
const script = inlineScript(rest);
|
|
65
|
+
return script === null ? null : riskyIn(script, depth + 1);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// `find … -delete`, or what `-exec` and its kin run on each file.
|
|
70
|
+
function findReason(words, depth) {
|
|
71
|
+
if (words.includes("-delete"))
|
|
72
|
+
return "deletes files for good";
|
|
73
|
+
for (let i = 0; i < words.length; i++) {
|
|
74
|
+
if (!["-exec", "-execdir", "-ok", "-okdir"].includes(words[i] ?? ""))
|
|
75
|
+
continue;
|
|
76
|
+
const run = [];
|
|
77
|
+
for (let j = i + 1; j < words.length && words[j] !== ";" && words[j] !== "+"; j++)
|
|
78
|
+
run.push(words[j] ?? "");
|
|
79
|
+
const reason = riskyWords(unwrapped(run), depth);
|
|
80
|
+
if (reason !== null)
|
|
81
|
+
return reason;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
// The script in `sh -c '<script>'` (also `-lc`, `-ec`); null when the shell runs a file.
|
|
86
|
+
function inlineScript(words) {
|
|
87
|
+
for (let i = 0; i < words.length; i++) {
|
|
88
|
+
const word = words[i] ?? "";
|
|
89
|
+
if (!word.startsWith("-"))
|
|
90
|
+
return null;
|
|
91
|
+
if (!word.startsWith("--") && word.includes("c"))
|
|
92
|
+
return words[i + 1] ?? null;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
// Commands that run another command: their flags that take a value, and how
|
|
97
|
+
// many words come before the command they run.
|
|
98
|
+
const wrappers = {
|
|
99
|
+
env: { valueFlags: new Set(["-u", "-C", "-P", "-S"]), operands: 0 },
|
|
100
|
+
nohup: { valueFlags: new Set(), operands: 0 },
|
|
101
|
+
command: { valueFlags: new Set(), operands: 0 },
|
|
102
|
+
builtin: { valueFlags: new Set(), operands: 0 },
|
|
103
|
+
exec: { valueFlags: new Set(["-a"]), operands: 0 },
|
|
104
|
+
time: { valueFlags: new Set(), operands: 0 },
|
|
105
|
+
setsid: { valueFlags: new Set(), operands: 0 },
|
|
106
|
+
stdbuf: { valueFlags: new Set(), operands: 0 },
|
|
107
|
+
nice: { valueFlags: new Set(["-n"]), operands: 0 },
|
|
108
|
+
ionice: { valueFlags: new Set(["-c", "-n", "-p"]), operands: 0 },
|
|
109
|
+
timeout: { valueFlags: new Set(["-s", "-k", "--signal", "--kill-after"]), operands: 1 },
|
|
110
|
+
xargs: { valueFlags: new Set(["-I", "-n", "-P", "-L", "-d", "-E", "-s", "-J", "-R"]), operands: 0 },
|
|
111
|
+
};
|
|
112
|
+
const shellKeywords = new Set(["then", "do", "else", "elif", "if", "while", "until", "!", "{"]);
|
|
113
|
+
// `words` without what stands in front of the real command: `VAR=value`
|
|
114
|
+
// settings, shell keywords, and wrappers such as env, nohup, xargs.
|
|
115
|
+
function unwrapped(input) {
|
|
116
|
+
let words = input;
|
|
117
|
+
while (words.length > 0) {
|
|
118
|
+
const first = words[0] ?? "";
|
|
119
|
+
if (isAssignment(first) || shellKeywords.has(first)) {
|
|
120
|
+
words = words.slice(1);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const wrapper = wrappers[baseName(first)];
|
|
124
|
+
if (wrapper === undefined)
|
|
125
|
+
break;
|
|
126
|
+
words = words.slice(1);
|
|
127
|
+
while (words.length > 0 && (words[0] ?? "").startsWith("-"))
|
|
128
|
+
words = words.slice(wrapper.valueFlags.has(words[0] ?? "") ? 2 : 1);
|
|
129
|
+
words = words.slice(wrapper.operands);
|
|
130
|
+
}
|
|
131
|
+
return words;
|
|
132
|
+
}
|
|
133
|
+
function isAssignment(word) {
|
|
134
|
+
const equals = word.indexOf("=");
|
|
135
|
+
return equals > 0 && /^[\p{L}\p{N}_]+$/u.test(word.slice(0, equals));
|
|
136
|
+
}
|
|
137
|
+
function baseName(path) {
|
|
138
|
+
return path.split("/").filter((part) => part !== "").at(-1) ?? path;
|
|
139
|
+
}
|
|
140
|
+
// Splits a script into its simple commands, close enough to how a shell does
|
|
141
|
+
// it for the gate: quotes keep a word together; `;`, `&`, `|`, newlines and
|
|
142
|
+
// parentheses end a command; what `$(…)` or backticks would run is set aside
|
|
143
|
+
// to be read as a script of its own.
|
|
144
|
+
export function lex(script) {
|
|
145
|
+
const commands = [{ words: [], piped: false }];
|
|
146
|
+
const substitutions = [];
|
|
147
|
+
const chars = [...script];
|
|
148
|
+
let word = "";
|
|
149
|
+
let inWord = false;
|
|
150
|
+
let quote = null;
|
|
151
|
+
const current = () => commands[commands.length - 1];
|
|
152
|
+
const endWord = () => {
|
|
153
|
+
if (inWord)
|
|
154
|
+
current().words.push(word);
|
|
155
|
+
word = "";
|
|
156
|
+
inWord = false;
|
|
157
|
+
};
|
|
158
|
+
const endCommand = (piped) => {
|
|
159
|
+
endWord();
|
|
160
|
+
// A second "|" makes it "||": the next command doesn't read this one's output.
|
|
161
|
+
if (current().words.length === 0)
|
|
162
|
+
current().piped = piped && !current().piped;
|
|
163
|
+
else
|
|
164
|
+
commands.push({ words: [], piped });
|
|
165
|
+
};
|
|
166
|
+
// Sets aside the text up to the matching `close`; returns the index after it.
|
|
167
|
+
const substitution = (from, close) => {
|
|
168
|
+
let depth = 1;
|
|
169
|
+
let index = from;
|
|
170
|
+
while (index < chars.length) {
|
|
171
|
+
if (chars[index] === "(" && close === ")")
|
|
172
|
+
depth++;
|
|
173
|
+
if (chars[index] === close)
|
|
174
|
+
depth--;
|
|
175
|
+
if (depth === 0)
|
|
176
|
+
break;
|
|
177
|
+
index++;
|
|
178
|
+
}
|
|
179
|
+
substitutions.push(chars.slice(from, Math.min(index, chars.length)).join(""));
|
|
180
|
+
inWord = true;
|
|
181
|
+
return index + 1;
|
|
182
|
+
};
|
|
183
|
+
let index = 0;
|
|
184
|
+
while (index < chars.length) {
|
|
185
|
+
const char = chars[index] ?? "";
|
|
186
|
+
index++;
|
|
187
|
+
if (quote === "'") {
|
|
188
|
+
if (char === "'")
|
|
189
|
+
quote = null;
|
|
190
|
+
else
|
|
191
|
+
word += char;
|
|
192
|
+
}
|
|
193
|
+
else if (char === "\\" && chars[index] === "\n") {
|
|
194
|
+
// A line continuation: the shell drops both and joins the lines.
|
|
195
|
+
index++;
|
|
196
|
+
}
|
|
197
|
+
else if (char === "\\" && index < chars.length) {
|
|
198
|
+
word += chars[index] ?? "";
|
|
199
|
+
inWord = true;
|
|
200
|
+
index++;
|
|
201
|
+
}
|
|
202
|
+
else if (char === "$" && chars[index] === "(") {
|
|
203
|
+
index = substitution(index + 1, ")");
|
|
204
|
+
}
|
|
205
|
+
else if (char === "`") {
|
|
206
|
+
index = substitution(index, "`");
|
|
207
|
+
}
|
|
208
|
+
else if (quote !== null) {
|
|
209
|
+
if (char === quote)
|
|
210
|
+
quote = null;
|
|
211
|
+
else
|
|
212
|
+
word += char;
|
|
213
|
+
}
|
|
214
|
+
else if (char === "'" || char === '"') {
|
|
215
|
+
quote = char;
|
|
216
|
+
inWord = true;
|
|
217
|
+
}
|
|
218
|
+
else if (char === " " || char === "\t") {
|
|
219
|
+
endWord();
|
|
220
|
+
}
|
|
221
|
+
else if (char === "|") {
|
|
222
|
+
endCommand(true);
|
|
223
|
+
}
|
|
224
|
+
else if (char === ";" || char === "&" || char === "\n" || char === "(" || char === ")") {
|
|
225
|
+
endCommand(false);
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
word += char;
|
|
229
|
+
inWord = true;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
endWord();
|
|
233
|
+
return { commands, substitutions };
|
|
234
|
+
}
|
|
235
|
+
// A folder hides every session in it or below it (shell/core/hiding.js).
|
|
236
|
+
export function inHiddenFolder(cwd, folders) {
|
|
237
|
+
return folders.some((folder) => cwd === folder || cwd.startsWith(`${folder.replace(/\/$/, "")}/`));
|
|
238
|
+
}
|
|
239
|
+
// The command to ask about before this tool call runs, or null when it isn't
|
|
240
|
+
// the gate's business: the gate is off, the session's folder is hidden, the
|
|
241
|
+
// tool has no command, or the command isn't risky.
|
|
242
|
+
export function gatedCommand(toolInput, cwd, on, hiddenFolders) {
|
|
243
|
+
if (!on || inHiddenFolder(cwd, hiddenFolders))
|
|
244
|
+
return null;
|
|
245
|
+
if (typeof toolInput !== "object" || toolInput === null)
|
|
246
|
+
return null;
|
|
247
|
+
const command = toolInput.command;
|
|
248
|
+
if (typeof command !== "string")
|
|
249
|
+
return null;
|
|
250
|
+
return riskyCommandReason(command) === null ? null : command;
|
|
251
|
+
}
|
|
252
|
+
// The hook's answer in Claude Code's decision shape, which the extension reads.
|
|
253
|
+
export function gateDecision(allowed, message) {
|
|
254
|
+
const decision = allowed ? { behavior: "allow" } : { behavior: "deny", message };
|
|
255
|
+
return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", decision } })}\n`;
|
|
256
|
+
}
|