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,437 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chmodSync, mkdirSync, rmSync } from "node:fs";
|
|
3
|
+
import { connect, createServer } from "node:net";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
import { encode, parseClientMessage, } from "../shared/protocol.js";
|
|
7
|
+
import { err, ok } from "../shared/result.js";
|
|
8
|
+
import { previewFile, previewTool } from "./preview.js";
|
|
9
|
+
import { claudeArgs } from "../adapters/claude/one-shot.js";
|
|
10
|
+
import { isCodexBinary } from "../adapters/codex/codex.js";
|
|
11
|
+
import { extensionAgents, isAgentProcess, isExtensionAgent } from "../adapters/pi/extension.js";
|
|
12
|
+
import { agentPidOf, discoveredId, isInteractiveClaude, isInteractiveCodex, isInteractiveExtensionAgent, realProcessHost } from "./processes.js";
|
|
13
|
+
import { applyToSession, settledInTerminal, summarizeTool } from "./session-state.js";
|
|
14
|
+
// What ties a permission request to the tool call before it. Codex adds a
|
|
15
|
+
// `description` to the request's input that its PreToolUse didn't have, so
|
|
16
|
+
// a command is matched by the command alone (docs/notes/codex-hooks.md).
|
|
17
|
+
export function toolKey(toolInput) {
|
|
18
|
+
if (typeof toolInput === "object" && toolInput !== null) {
|
|
19
|
+
const command = toolInput.command;
|
|
20
|
+
if (typeof command === "string")
|
|
21
|
+
return `command:${command}`;
|
|
22
|
+
}
|
|
23
|
+
return JSON.stringify(toolInput);
|
|
24
|
+
}
|
|
25
|
+
function send(socket, message) {
|
|
26
|
+
if (!socket.destroyed)
|
|
27
|
+
socket.write(encode(message));
|
|
28
|
+
}
|
|
29
|
+
function isAlive(path) {
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
const probe = connect(path);
|
|
32
|
+
probe.once("connect", () => {
|
|
33
|
+
probe.destroy();
|
|
34
|
+
resolve(true);
|
|
35
|
+
});
|
|
36
|
+
probe.once("error", () => resolve(false));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
export async function startDaemon(socketPath, store, options = {}) {
|
|
40
|
+
const host = options.host ?? realProcessHost;
|
|
41
|
+
const codexUntrusted = options.codexUntrusted ?? (() => false);
|
|
42
|
+
const installedExtensions = options.extensions ?? (() => []);
|
|
43
|
+
// Spend per session, from pi and omp; the next turn sends it again.
|
|
44
|
+
const spend = {};
|
|
45
|
+
let untrusted = codexUntrusted();
|
|
46
|
+
if (await isAlive(socketPath))
|
|
47
|
+
return err(`a Topside daemon is already listening on ${socketPath}`);
|
|
48
|
+
store.expirePending();
|
|
49
|
+
const sessions = new Map(store.liveSessions().map((s) => [s.id, s]));
|
|
50
|
+
const approvals = new Map();
|
|
51
|
+
const waiters = new Map();
|
|
52
|
+
const lastToolStart = new Map();
|
|
53
|
+
// Questions live only as long as the hook holding them, so they aren't stored.
|
|
54
|
+
const questions = new Map();
|
|
55
|
+
const subscribers = new Set();
|
|
56
|
+
const usage = store.usage();
|
|
57
|
+
const snapshot = () => ({
|
|
58
|
+
sessions: [...sessions.values()]
|
|
59
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
60
|
+
.map((session) => (isUntracked(session) ? { ...session, untracked: true } : session)),
|
|
61
|
+
approvals: [...approvals.values()].filter((a) => a.status === "pending"),
|
|
62
|
+
questions: [...questions.values()].map((q) => q.question),
|
|
63
|
+
usage: { ...usage },
|
|
64
|
+
spend: { ...spend },
|
|
65
|
+
});
|
|
66
|
+
// A session that can't report yet: Codex before /hooks, or a pi or omp
|
|
67
|
+
// session found running from before its extension was loaded.
|
|
68
|
+
function isUntracked(session) {
|
|
69
|
+
if (session.agent === "codex")
|
|
70
|
+
return untrusted;
|
|
71
|
+
return isExtensionAgent(session.agent) && session.id.startsWith("pid-");
|
|
72
|
+
}
|
|
73
|
+
// The cue the next broadcast carries; a request outranks a finished turn.
|
|
74
|
+
let cue = null;
|
|
75
|
+
const callFor = (next, sessionId) => {
|
|
76
|
+
if (cue?.cue !== "attention")
|
|
77
|
+
cue = { cue: next, cueSession: sessionId };
|
|
78
|
+
};
|
|
79
|
+
const broadcast = () => {
|
|
80
|
+
const message = { op: "snapshot", snapshot: cue === null ? snapshot() : { ...snapshot(), ...cue } };
|
|
81
|
+
cue = null;
|
|
82
|
+
for (const subscriber of subscribers)
|
|
83
|
+
send(subscriber, message);
|
|
84
|
+
};
|
|
85
|
+
const finishApproval = (approval, status, decision) => {
|
|
86
|
+
approval.status = status;
|
|
87
|
+
store.saveApproval(approval);
|
|
88
|
+
approvals.delete(approval.id);
|
|
89
|
+
const waiter = waiters.get(approval.id);
|
|
90
|
+
waiters.delete(approval.id);
|
|
91
|
+
if (waiter)
|
|
92
|
+
send(waiter, { op: "decision", decision });
|
|
93
|
+
};
|
|
94
|
+
// Agent pids of sessions that ended in the last minute: discovery leaves
|
|
95
|
+
// them alone, so a session that just ended doesn't come straight back.
|
|
96
|
+
const recentlyEnded = new Map();
|
|
97
|
+
const applyEvent = (event) => {
|
|
98
|
+
store.logEvent(event);
|
|
99
|
+
for (const approval of approvals.values()) {
|
|
100
|
+
const settled = settledInTerminal(approval, event);
|
|
101
|
+
if (settled)
|
|
102
|
+
finishApproval(approval, settled, "none");
|
|
103
|
+
}
|
|
104
|
+
for (const { question } of questions.values()) {
|
|
105
|
+
if (settledInTerminal({ status: "pending", sessionId: question.sessionId, toolUseId: question.toolUseId }, event)) {
|
|
106
|
+
settleQuestion(question.id, null);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (event.type === "tool-start") {
|
|
110
|
+
lastToolStart.set(event.sessionId, { toolUseId: event.toolUseId, inputKey: toolKey(event.toolInput) });
|
|
111
|
+
}
|
|
112
|
+
const before = sessions.get(event.sessionId)?.status;
|
|
113
|
+
const session = applyToSession(sessions.get(event.sessionId), event);
|
|
114
|
+
if (event.pids.length > 0)
|
|
115
|
+
session.agentPid = agentPidOf(event.pids, host.cmdline, event.agent) || session.agentPid;
|
|
116
|
+
if (event.type === "turn-end" && session.status === "done" && before !== "done" && !session.endedInFront)
|
|
117
|
+
callFor("completion", session.id);
|
|
118
|
+
if (event.type === "approval-request" && event.inFront !== true)
|
|
119
|
+
callFor("attention", session.id);
|
|
120
|
+
if (event.type === "turn-end" && event.spend)
|
|
121
|
+
spend[session.id] = event.spend;
|
|
122
|
+
store.saveSession(session);
|
|
123
|
+
// One process, one session: /resume or /new switches sessions in place
|
|
124
|
+
// and sends no end for the old one (VIA-PARITY §17b). Tool events don't count.
|
|
125
|
+
// A placeholder from discovery gives way to the real session as soon as
|
|
126
|
+
// any hook event names the same process.
|
|
127
|
+
if (session.agentPid > 0) {
|
|
128
|
+
const switched = event.type === "session-start" || event.type === "prompt";
|
|
129
|
+
for (const other of [...sessions.values()]) {
|
|
130
|
+
if (other.id === session.id || other.agent !== session.agent || other.agentPid !== session.agentPid)
|
|
131
|
+
continue;
|
|
132
|
+
if (switched || other.id.startsWith("pid-"))
|
|
133
|
+
endSession(other);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (session.status === "ended" && session.agentPid > 0)
|
|
137
|
+
recentlyEnded.set(session.agentPid, Date.now());
|
|
138
|
+
if (session.status === "ended") {
|
|
139
|
+
sessions.delete(session.id);
|
|
140
|
+
lastToolStart.delete(session.id);
|
|
141
|
+
delete spend[session.id];
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
sessions.set(session.id, session);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
// A synthetic session-end: settles its pending requests and drops the row.
|
|
148
|
+
const endSession = (session) => {
|
|
149
|
+
applyEvent({ type: "session-end", agent: session.agent, sessionId: session.id, cwd: session.cwd, at: Date.now(), pids: [], terminal: session.terminal });
|
|
150
|
+
};
|
|
151
|
+
// Every few seconds, and at start: end sessions whose agent process is gone
|
|
152
|
+
// (a /exit doesn't always deliver SessionEnd, VIA-PARITY §14), and take each
|
|
153
|
+
// session's name from Claude Code's record for its process (§16). Sessions
|
|
154
|
+
// without pids are left alone; for one stored before agentPid existed, all
|
|
155
|
+
// of its recorded ancestry has to be gone.
|
|
156
|
+
// Sessions that were running before the hooks were installed send nothing
|
|
157
|
+
// until they do something. Discovery lists interactive Claude Code
|
|
158
|
+
// processes on a terminal that no live session accounts for and starts an
|
|
159
|
+
// idle session for each (VIA-PARITY §15).
|
|
160
|
+
const discover = () => {
|
|
161
|
+
const now = Date.now();
|
|
162
|
+
for (const [pid, at] of recentlyEnded)
|
|
163
|
+
if (now - at > 60_000)
|
|
164
|
+
recentlyEnded.delete(pid);
|
|
165
|
+
const known = new Set();
|
|
166
|
+
for (const session of sessions.values()) {
|
|
167
|
+
if (session.agentPid > 0)
|
|
168
|
+
known.add(session.agentPid);
|
|
169
|
+
for (const pid of session.pids)
|
|
170
|
+
known.add(pid);
|
|
171
|
+
}
|
|
172
|
+
let found = false;
|
|
173
|
+
const extensions = installedExtensions();
|
|
174
|
+
for (const pid of host.list()) {
|
|
175
|
+
if (known.has(pid) || recentlyEnded.has(pid))
|
|
176
|
+
continue;
|
|
177
|
+
// Codex's hooks report nothing until the user trusts them, so until
|
|
178
|
+
// then its sessions come from the process table (VIA-PARITY §19).
|
|
179
|
+
if (untrusted && isCodexBinary(host.cmdline(pid))) {
|
|
180
|
+
const info = host.inspect(pid);
|
|
181
|
+
if (info === null || !isInteractiveCodex(info, host.ancestry(pid).slice(1).map(host.cmdline)))
|
|
182
|
+
continue;
|
|
183
|
+
applyEvent({ type: "session-start", agent: "codex", sessionId: `pid-${pid}`, cwd: info.cwd, at: now, pids: host.ancestry(pid), terminal: info.terminal, name: "" });
|
|
184
|
+
found = true;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
const extension = extensionAgents.find((agent) => isAgentProcess(agent, host.cmdline(pid)));
|
|
188
|
+
if (extension !== undefined) {
|
|
189
|
+
if (!extensions.includes(extension))
|
|
190
|
+
continue;
|
|
191
|
+
const info = host.inspect(pid);
|
|
192
|
+
if (info === null || !isInteractiveExtensionAgent(extension, info, host.ancestry(pid).slice(1).map(host.cmdline)))
|
|
193
|
+
continue;
|
|
194
|
+
applyEvent({ type: "session-start", agent: extension, sessionId: `pid-${pid}`, cwd: info.cwd, at: now, pids: host.ancestry(pid), terminal: info.terminal, name: "" });
|
|
195
|
+
found = true;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
// Cheap test first; most processes stop here.
|
|
199
|
+
if (claudeArgs([host.cmdline(pid)]) === null)
|
|
200
|
+
continue;
|
|
201
|
+
const info = host.inspect(pid);
|
|
202
|
+
if (info === null || !isInteractiveClaude(info))
|
|
203
|
+
continue;
|
|
204
|
+
const record = host.record(pid);
|
|
205
|
+
const id = discoveredId(pid, info.argv, record);
|
|
206
|
+
if (sessions.has(id))
|
|
207
|
+
continue;
|
|
208
|
+
applyEvent({ type: "session-start", agent: "claude", sessionId: id, cwd: info.cwd, at: now, pids: host.ancestry(pid), terminal: info.terminal, name: record?.name ?? "" });
|
|
209
|
+
found = true;
|
|
210
|
+
}
|
|
211
|
+
return found;
|
|
212
|
+
};
|
|
213
|
+
const housekeeping = () => {
|
|
214
|
+
let changed = false;
|
|
215
|
+
const nowUntrusted = codexUntrusted();
|
|
216
|
+
if (nowUntrusted !== untrusted) {
|
|
217
|
+
untrusted = nowUntrusted;
|
|
218
|
+
changed = true;
|
|
219
|
+
}
|
|
220
|
+
for (const session of [...sessions.values()]) {
|
|
221
|
+
const gone = session.agentPid > 0 ? !host.alive(session.agentPid) : session.pids.length > 0 && !session.pids.some((pid) => host.alive(pid));
|
|
222
|
+
if (gone) {
|
|
223
|
+
endSession(session);
|
|
224
|
+
changed = true;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (session.agentPid === 0)
|
|
228
|
+
continue;
|
|
229
|
+
const record = host.record(session.agentPid);
|
|
230
|
+
if (record !== null && record.sessionId === session.id && record.name !== "" && record.name !== session.name) {
|
|
231
|
+
session.name = record.name;
|
|
232
|
+
store.saveSession(session);
|
|
233
|
+
changed = true;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (discover())
|
|
237
|
+
changed = true;
|
|
238
|
+
if (changed)
|
|
239
|
+
broadcast();
|
|
240
|
+
};
|
|
241
|
+
const requestApproval = (event, socket) => {
|
|
242
|
+
applyEvent(event);
|
|
243
|
+
// PermissionRequest carries no tool_use_id; pair it with the matching PreToolUse.
|
|
244
|
+
const start = lastToolStart.get(event.sessionId);
|
|
245
|
+
const approval = {
|
|
246
|
+
id: randomUUID().slice(0, 8),
|
|
247
|
+
sessionId: event.sessionId,
|
|
248
|
+
toolName: event.toolName,
|
|
249
|
+
summary: summarizeTool(event.toolName, event.toolInput),
|
|
250
|
+
preview: previewTool(event.toolName, event.toolInput),
|
|
251
|
+
file: previewFile(event.toolInput, event.toolName),
|
|
252
|
+
always: event.always ?? "",
|
|
253
|
+
toolUseId: start && start.inputKey === toolKey(event.toolInput) ? start.toolUseId : null,
|
|
254
|
+
createdAt: event.at,
|
|
255
|
+
status: "pending",
|
|
256
|
+
};
|
|
257
|
+
approvals.set(approval.id, approval);
|
|
258
|
+
waiters.set(approval.id, socket);
|
|
259
|
+
store.saveApproval(approval);
|
|
260
|
+
// A hook killed by its timeout can't deliver an answer anymore; the terminal still can.
|
|
261
|
+
socket.once("close", () => {
|
|
262
|
+
if (approval.status === "pending") {
|
|
263
|
+
waiters.delete(approval.id);
|
|
264
|
+
finishApproval(approval, "expired", "none");
|
|
265
|
+
broadcast();
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
const decide = (approvalId, decision) => {
|
|
270
|
+
const approval = approvals.get(approvalId);
|
|
271
|
+
if (!approval || approval.status !== "pending")
|
|
272
|
+
return err(`no pending approval ${approvalId}`);
|
|
273
|
+
if (decision === "always" && approval.always === "")
|
|
274
|
+
return err(`approval ${approvalId} has no Always Allow`);
|
|
275
|
+
// Auto mode is Claude Code's; Codex would refuse it.
|
|
276
|
+
if (decision === "auto" && sessions.get(approval.sessionId)?.agent !== "claude")
|
|
277
|
+
return err(`approval ${approvalId} has no Auto mode`);
|
|
278
|
+
finishApproval(approval, decision === "deny" ? "denied" : "allowed", decision);
|
|
279
|
+
const session = sessions.get(approval.sessionId);
|
|
280
|
+
if (session) {
|
|
281
|
+
session.status = "working";
|
|
282
|
+
store.saveSession(session);
|
|
283
|
+
}
|
|
284
|
+
return ok(undefined);
|
|
285
|
+
};
|
|
286
|
+
// The user looked at a finished session, e.g. jumped to it.
|
|
287
|
+
const seen = (sessionId) => {
|
|
288
|
+
const session = sessions.get(sessionId);
|
|
289
|
+
if (!session)
|
|
290
|
+
return err(`no live session ${sessionId}`);
|
|
291
|
+
if (session.status === "done") {
|
|
292
|
+
session.status = "idle";
|
|
293
|
+
store.saveSession(session);
|
|
294
|
+
}
|
|
295
|
+
return ok(undefined);
|
|
296
|
+
};
|
|
297
|
+
const setStatus = (sessionId, status) => {
|
|
298
|
+
const session = sessions.get(sessionId);
|
|
299
|
+
if (!session)
|
|
300
|
+
return;
|
|
301
|
+
session.status = status;
|
|
302
|
+
store.saveSession(session);
|
|
303
|
+
};
|
|
304
|
+
// Claude's question waits on its PermissionRequest hook while the terminal
|
|
305
|
+
// shows it too. The island answers it, the terminal settles it (see
|
|
306
|
+
// applyEvent), or the hook goes away.
|
|
307
|
+
const ask = (event, asked, socket) => {
|
|
308
|
+
applyEvent(event);
|
|
309
|
+
const start = lastToolStart.get(event.sessionId);
|
|
310
|
+
const question = {
|
|
311
|
+
id: randomUUID().slice(0, 8),
|
|
312
|
+
sessionId: event.sessionId,
|
|
313
|
+
questions: asked,
|
|
314
|
+
toolUseId: start && start.inputKey === toolKey(event.toolInput) ? start.toolUseId : null,
|
|
315
|
+
createdAt: event.at,
|
|
316
|
+
};
|
|
317
|
+
questions.set(question.id, { question, socket });
|
|
318
|
+
socket.once("close", () => {
|
|
319
|
+
if (questions.delete(question.id))
|
|
320
|
+
broadcast();
|
|
321
|
+
});
|
|
322
|
+
};
|
|
323
|
+
// `answers` null tells the hook the terminal already got it.
|
|
324
|
+
const settleQuestion = (questionId, answers) => {
|
|
325
|
+
const held = questions.get(questionId);
|
|
326
|
+
if (!held)
|
|
327
|
+
return err(`no open question ${questionId}`);
|
|
328
|
+
questions.delete(questionId);
|
|
329
|
+
if (answers !== null)
|
|
330
|
+
setStatus(held.question.sessionId, "working");
|
|
331
|
+
send(held.socket, { op: "answers", answers });
|
|
332
|
+
return ok(undefined);
|
|
333
|
+
};
|
|
334
|
+
const handleLine = (socket, line) => {
|
|
335
|
+
const parsed = parseClientMessage(line);
|
|
336
|
+
if (!parsed.ok) {
|
|
337
|
+
send(socket, { op: "error", error: parsed.error });
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const message = parsed.value;
|
|
341
|
+
switch (message.op) {
|
|
342
|
+
case "event":
|
|
343
|
+
applyEvent(message.event);
|
|
344
|
+
send(socket, { op: "ack" });
|
|
345
|
+
broadcast();
|
|
346
|
+
return;
|
|
347
|
+
case "approval":
|
|
348
|
+
requestApproval(message.event, socket);
|
|
349
|
+
broadcast();
|
|
350
|
+
return;
|
|
351
|
+
case "decide": {
|
|
352
|
+
const result = decide(message.approvalId, message.decision);
|
|
353
|
+
send(socket, result.ok ? { op: "ack" } : { op: "error", error: result.error });
|
|
354
|
+
if (result.ok)
|
|
355
|
+
broadcast();
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
case "seen": {
|
|
359
|
+
const result = seen(message.sessionId);
|
|
360
|
+
send(socket, result.ok ? { op: "ack" } : { op: "error", error: result.error });
|
|
361
|
+
if (result.ok)
|
|
362
|
+
broadcast();
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
case "ask":
|
|
366
|
+
ask(message.event, message.questions, socket);
|
|
367
|
+
broadcast();
|
|
368
|
+
return;
|
|
369
|
+
case "answer": {
|
|
370
|
+
const result = settleQuestion(message.questionId, message.answers);
|
|
371
|
+
send(socket, result.ok ? { op: "ack" } : { op: "error", error: result.error });
|
|
372
|
+
if (result.ok)
|
|
373
|
+
broadcast();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
case "usage": {
|
|
377
|
+
// The status line runs every few seconds; most runs repeat the last numbers.
|
|
378
|
+
const changed = JSON.stringify(usage[message.agent]) !== JSON.stringify(message.usage);
|
|
379
|
+
send(socket, { op: "ack" });
|
|
380
|
+
if (!changed)
|
|
381
|
+
return;
|
|
382
|
+
usage[message.agent] = message.usage;
|
|
383
|
+
store.saveUsage(message.agent, message.usage);
|
|
384
|
+
broadcast();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
case "snapshot":
|
|
388
|
+
send(socket, { op: "snapshot", snapshot: snapshot() });
|
|
389
|
+
return;
|
|
390
|
+
case "subscribe":
|
|
391
|
+
subscribers.add(socket);
|
|
392
|
+
send(socket, { op: "snapshot", snapshot: snapshot() });
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
const server = createServer((socket) => {
|
|
397
|
+
socket.on("error", () => socket.destroy());
|
|
398
|
+
socket.on("close", () => subscribers.delete(socket));
|
|
399
|
+
createInterface({ input: socket }).on("line", (line) => {
|
|
400
|
+
if (line.trim() !== "")
|
|
401
|
+
handleLine(socket, line);
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
try {
|
|
405
|
+
mkdirSync(dirname(socketPath), { recursive: true, mode: 0o700 });
|
|
406
|
+
rmSync(socketPath, { force: true });
|
|
407
|
+
}
|
|
408
|
+
catch (error) {
|
|
409
|
+
return err(`cannot prepare ${socketPath}: ${String(error)}`);
|
|
410
|
+
}
|
|
411
|
+
const listening = await new Promise((resolve) => {
|
|
412
|
+
server.once("error", (error) => resolve(err(`cannot listen on ${socketPath}: ${error.message}`)));
|
|
413
|
+
server.listen(socketPath, () => resolve(ok(undefined)));
|
|
414
|
+
});
|
|
415
|
+
if (!listening.ok)
|
|
416
|
+
return listening;
|
|
417
|
+
chmodSync(socketPath, 0o600);
|
|
418
|
+
housekeeping();
|
|
419
|
+
const ticker = setInterval(housekeeping, options.tickMs ?? 5000);
|
|
420
|
+
ticker.unref();
|
|
421
|
+
return ok({
|
|
422
|
+
snapshot,
|
|
423
|
+
close: () => new Promise((resolve) => {
|
|
424
|
+
clearInterval(ticker);
|
|
425
|
+
for (const waiter of waiters.values())
|
|
426
|
+
send(waiter, { op: "decision", decision: "none" });
|
|
427
|
+
// A question's hook waits with no timeout; answers null hands it back to the terminal.
|
|
428
|
+
const asking = [...questions.values()].map((held) => held.socket);
|
|
429
|
+
questions.clear();
|
|
430
|
+
for (const socket of asking)
|
|
431
|
+
send(socket, { op: "answers", answers: null });
|
|
432
|
+
for (const socket of [...subscribers, ...waiters.values(), ...asking])
|
|
433
|
+
socket.end();
|
|
434
|
+
server.close(() => resolve());
|
|
435
|
+
}),
|
|
436
|
+
});
|
|
437
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { describePatch, patchFiles } from "../adapters/codex/patch.js";
|
|
2
|
+
const titleLength = 80;
|
|
3
|
+
function statusAfter(prev, event) {
|
|
4
|
+
switch (event.type) {
|
|
5
|
+
case "session-start":
|
|
6
|
+
return "idle";
|
|
7
|
+
case "turn-end":
|
|
8
|
+
return "done";
|
|
9
|
+
case "session-end":
|
|
10
|
+
return "ended";
|
|
11
|
+
case "prompt":
|
|
12
|
+
case "tool-start":
|
|
13
|
+
case "tool-end":
|
|
14
|
+
return "working";
|
|
15
|
+
case "approval-request":
|
|
16
|
+
return "waiting";
|
|
17
|
+
case "attention":
|
|
18
|
+
if (event.reason === "permission")
|
|
19
|
+
return "waiting";
|
|
20
|
+
// Claude Code nags "waiting for input" a minute after a turn; that's
|
|
21
|
+
// not the user looking, so a finished turn stays done.
|
|
22
|
+
if (event.reason === "idle")
|
|
23
|
+
return prev === "done" ? "done" : "idle";
|
|
24
|
+
return prev;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// Lines that say nothing about the task: blank, a code fence, or a lone tag
|
|
28
|
+
// such as the <pasted_content> wrapper around a paste.
|
|
29
|
+
const noiseLine = /^(\s*|`{3,}.*|~{3,}.*|<\/?[\w-]+(\s[^>]*)?>)$/;
|
|
30
|
+
function firstLine(text) {
|
|
31
|
+
const line = text.split("\n").map((l) => l.trim()).find((l) => !noiseLine.test(l)) ?? "";
|
|
32
|
+
return line.length > titleLength ? `${line.slice(0, titleLength - 1)}…` : line;
|
|
33
|
+
}
|
|
34
|
+
function fallbackTitle(cwd) {
|
|
35
|
+
return cwd.split("/").filter(Boolean).at(-1) ?? "session";
|
|
36
|
+
}
|
|
37
|
+
function activityAfter(prev, event) {
|
|
38
|
+
switch (event.type) {
|
|
39
|
+
case "tool-start":
|
|
40
|
+
return describeTool(event.toolName, event.toolInput);
|
|
41
|
+
case "prompt":
|
|
42
|
+
case "turn-end":
|
|
43
|
+
case "session-start":
|
|
44
|
+
case "session-end":
|
|
45
|
+
return "";
|
|
46
|
+
default:
|
|
47
|
+
return prev;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function applyToSession(prev, event) {
|
|
51
|
+
const promptTitle = event.type === "prompt" ? firstLine(event.text) : "";
|
|
52
|
+
return {
|
|
53
|
+
id: event.sessionId,
|
|
54
|
+
agent: event.agent,
|
|
55
|
+
cwd: event.cwd || prev?.cwd || "",
|
|
56
|
+
// The first prompt names the session; later prompts don't rename it.
|
|
57
|
+
title: prev?.title && prev.title !== fallbackTitle(prev.cwd) ? prev.title : promptTitle || prev?.title || fallbackTitle(event.cwd),
|
|
58
|
+
status: statusAfter(prev?.status ?? "idle", event),
|
|
59
|
+
updatedAt: event.at,
|
|
60
|
+
// Both come from the same hook process, so they're replaced together.
|
|
61
|
+
pids: event.pids.length > 0 ? event.pids : (prev?.pids ?? []),
|
|
62
|
+
terminal: event.pids.length > 0 ? event.terminal : (prev?.terminal ?? event.terminal),
|
|
63
|
+
lastPrompt: promptTitle || prev?.lastPrompt || "",
|
|
64
|
+
activity: activityAfter(prev?.activity ?? "", event),
|
|
65
|
+
startedAt: prev?.startedAt || event.at,
|
|
66
|
+
// A hook from before these fields existed sends neither.
|
|
67
|
+
lastMessage: event.type === "turn-end" ? (event.message ?? "") : event.type === "prompt" ? "" : (prev?.lastMessage ?? ""),
|
|
68
|
+
name: (event.type === "session-start" || event.type === "prompt") && event.name ? event.name : (prev?.name ?? ""),
|
|
69
|
+
agentPid: prev?.agentPid ?? 0,
|
|
70
|
+
endedInFront: event.type === "turn-end" ? event.inFront === true : event.type === "prompt" ? false : (prev?.endedInFront ?? false),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// A pending approval gets settled in the terminal when its session moves on.
|
|
74
|
+
// See docs/notes/claude-hooks.md for the event order this relies on.
|
|
75
|
+
// Works for approvals and for questions (both wait on a PermissionRequest hook).
|
|
76
|
+
export function settledInTerminal(approval, event) {
|
|
77
|
+
if (approval.status !== "pending" || approval.sessionId !== event.sessionId)
|
|
78
|
+
return null;
|
|
79
|
+
switch (event.type) {
|
|
80
|
+
case "tool-end":
|
|
81
|
+
return event.toolUseId === approval.toolUseId ? "answered-in-terminal" : null;
|
|
82
|
+
case "prompt":
|
|
83
|
+
case "turn-end":
|
|
84
|
+
case "session-end":
|
|
85
|
+
case "session-start":
|
|
86
|
+
case "approval-request":
|
|
87
|
+
return "answered-in-terminal";
|
|
88
|
+
case "tool-start":
|
|
89
|
+
case "attention":
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export function summarizeTool(toolName, toolInput) {
|
|
94
|
+
// Codex's patch would read "*** Begin Patch"; the files say more.
|
|
95
|
+
if (toolName === "apply_patch") {
|
|
96
|
+
const files = patchFiles(rawField(toolInput, "command")).map((file) => baseName(file.path));
|
|
97
|
+
return files.length === 0 ? toolName : `${toolName}: ${files.join(", ")}`;
|
|
98
|
+
}
|
|
99
|
+
if (typeof toolInput === "object" && toolInput !== null) {
|
|
100
|
+
for (const key of ["command", "file_path", "url", "pattern", "description"]) {
|
|
101
|
+
const value = toolInput[key];
|
|
102
|
+
if (typeof value === "string" && value !== "")
|
|
103
|
+
return `${toolName}: ${firstLine(value)}`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return toolName;
|
|
107
|
+
}
|
|
108
|
+
function field(toolInput, key) {
|
|
109
|
+
if (typeof toolInput !== "object" || toolInput === null)
|
|
110
|
+
return "";
|
|
111
|
+
const value = toolInput[key];
|
|
112
|
+
return typeof value === "string" ? firstLine(value) : "";
|
|
113
|
+
}
|
|
114
|
+
function rawField(toolInput, key) {
|
|
115
|
+
if (typeof toolInput !== "object" || toolInput === null)
|
|
116
|
+
return "";
|
|
117
|
+
const value = toolInput[key];
|
|
118
|
+
return typeof value === "string" ? value : "";
|
|
119
|
+
}
|
|
120
|
+
const baseName = (path) => path.split("/").filter(Boolean).at(-1) ?? path;
|
|
121
|
+
// A short present-tense line for the island: "Editing auth.ts".
|
|
122
|
+
export function describeTool(toolName, toolInput) {
|
|
123
|
+
const file = baseName(field(toolInput, "file_path") || field(toolInput, "notebook_path"));
|
|
124
|
+
switch (toolName) {
|
|
125
|
+
case "Edit":
|
|
126
|
+
case "MultiEdit":
|
|
127
|
+
case "NotebookEdit":
|
|
128
|
+
return file ? `Editing ${file}` : "Editing";
|
|
129
|
+
case "Write":
|
|
130
|
+
return file ? `Writing ${file}` : "Writing";
|
|
131
|
+
case "Read":
|
|
132
|
+
return file ? `Reading ${file}` : "Reading";
|
|
133
|
+
case "Bash": {
|
|
134
|
+
// A heredoc body is noise on one line: keep what runs, not what it reads.
|
|
135
|
+
const command = field(toolInput, "command").split("<<")[0]?.trim() ?? "";
|
|
136
|
+
return command ? `Running ${command}` : "Running a command";
|
|
137
|
+
}
|
|
138
|
+
case "Grep":
|
|
139
|
+
case "Glob": {
|
|
140
|
+
const pattern = field(toolInput, "pattern");
|
|
141
|
+
return pattern ? `Searching ${pattern}` : "Searching";
|
|
142
|
+
}
|
|
143
|
+
case "WebFetch": {
|
|
144
|
+
const url = field(toolInput, "url");
|
|
145
|
+
try {
|
|
146
|
+
return `Fetching ${new URL(url).host}`;
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return "Fetching a page";
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
case "WebSearch":
|
|
153
|
+
return "Searching the web";
|
|
154
|
+
case "AskUserQuestion":
|
|
155
|
+
case "request_user_input_async":
|
|
156
|
+
return "Asking you a question";
|
|
157
|
+
// Codex's own tools (docs/notes/codex-hooks.md).
|
|
158
|
+
case "apply_patch":
|
|
159
|
+
return describePatch(rawField(toolInput, "command"));
|
|
160
|
+
case "clocksleep":
|
|
161
|
+
return "Waiting";
|
|
162
|
+
case "Task":
|
|
163
|
+
case "Agent": {
|
|
164
|
+
const description = field(toolInput, "description");
|
|
165
|
+
return description ? `Agent: ${description}` : "Running an agent";
|
|
166
|
+
}
|
|
167
|
+
default: {
|
|
168
|
+
// MCP tools are mcp__<server>__<tool>; the tool part reads best.
|
|
169
|
+
const name = toolName.startsWith("mcp__") ? (toolName.split("__").at(-1) ?? toolName) : toolName;
|
|
170
|
+
return `Using ${name}`;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|