ccdeck 3.82.3 → 4.0.0
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/LICENSING.md +42 -4
- package/README.md +183 -72
- package/THIRD_PARTY_NOTICES.md +243 -17
- package/bin/cli/login-item.js +5 -0
- package/bin/cli/tui.js +58 -4
- package/bin/deck.js +27 -1
- package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
- package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
- package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
- package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
- package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
- package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
- package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
- package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
- package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
- package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
- package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
- package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
- package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
- package/dist/web/assets/app-40gNTTfq.js +361 -0
- package/dist/web/assets/app-BRjYF6oD.css +1 -0
- package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
- package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
- package/dist/web/assets/screens-9_ivqfcF.js +12 -0
- package/dist/web/assets/screens-DUniTTbC.css +1 -0
- package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
- package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
- package/dist/web/assets/xterm-4jYizCpg.js +27 -0
- package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
- package/dist/web/index.html +16 -6
- package/package.json +13 -1
- package/release-notes.json +79 -0
- package/src/server/account-client.mjs +196 -0
- package/src/server/account-connect.mjs +238 -0
- package/src/server/account-flag.mjs +106 -0
- package/src/server/account-projects.mjs +1 -1
- package/src/server/account-service.mjs +532 -0
- package/src/server/account-status.mjs +293 -0
- package/src/server/account-store.mjs +137 -0
- package/src/server/account-sync.mjs +473 -0
- package/src/server/account-token-store.mjs +216 -0
- package/src/server/account-ui-fields.mjs +126 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/browser-watch-log.mjs +1 -1
- package/src/server/browser-watch-store.mjs +1 -1
- package/src/server/ccdeck-account-routes.mjs +252 -0
- package/src/server/ccusage-install.mjs +2 -2
- package/src/server/ccusage-registry.mjs +4 -4
- package/src/server/ccusage-session.mjs +11 -0
- package/src/server/claude-accounts.mjs +1 -1
- package/src/server/claude-recovery.mjs +9 -4
- package/src/server/claude-settings-catalog.mjs +6 -6
- package/src/server/claude-settings.mjs +1 -1
- package/src/server/codex-auto.mjs +1 -1
- package/src/server/codex-cost-usage.mjs +7 -2
- package/src/server/codex-live-checkpoint.mjs +24 -9
- package/src/server/codex-live-engine.mjs +14 -4
- package/src/server/codex-live-handoff.mjs +53 -9
- package/src/server/codex-names.mjs +49 -0
- package/src/server/codex-translate.mjs +1 -1
- package/src/server/codex-ultrafast.d.mts +3 -0
- package/src/server/codex-ultrafast.mjs +5 -0
- package/src/server/codex-watch.mjs +25 -0
- package/src/server/command-panel-engine.mjs +300 -0
- package/src/server/command-panel-platform.mjs +99 -0
- package/src/server/cswap-auto-choice.mjs +1 -1
- package/src/server/cswap-auto-loop.mjs +1 -1
- package/src/server/cswap-install.mjs +21 -40
- package/src/server/deck-home.mjs +6 -0
- package/src/server/deck-prefs.mjs +53 -1
- package/src/server/detach.mjs +1 -1
- package/src/server/engine-download.mjs +277 -0
- package/src/server/engine-install.mjs +378 -0
- package/src/server/engine-package.mjs +267 -0
- package/src/server/event-log.mjs +7 -1
- package/src/server/event-pipeline.mjs +29 -1
- package/src/server/ghostty-handoff.mjs +81 -0
- package/src/server/index.mjs +143 -5
- package/src/server/installer.mjs +4 -1
- package/src/server/integrations/jira-write-guard.mjs +14 -208
- package/src/server/integrations/store.mjs +37 -19
- package/src/server/integrations/write-guard.mjs +223 -0
- package/src/server/intel-cpu-temperature.mjs +26 -0
- package/src/server/lifecycle.mjs +69 -6
- package/src/server/log-replay.mjs +4 -0
- package/src/server/login-service.mjs +116 -14
- package/src/server/macmon.mjs +1 -1
- package/src/server/npm-latest.mjs +1 -1
- package/src/server/org-telemetry.mjs +1 -1
- package/src/server/output-watch.mjs +4 -1
- package/src/server/panel-provenance.mjs +390 -0
- package/src/server/pinned-build.mjs +14 -0
- package/src/server/prefs-refusal.mjs +8 -1
- package/src/server/prefs-routes.mjs +60 -11
- package/src/server/pro-engine-client.mjs +339 -0
- package/src/server/pro-engine-install.mjs +294 -0
- package/src/server/pro-engine-terminal.mjs +308 -0
- package/src/server/project-discovery.mjs +139 -0
- package/src/server/provider-session-name.mjs +58 -0
- package/src/server/quota-closes.mjs +1 -1
- package/src/server/quota-history.mjs +1 -1
- package/src/server/reports.mjs +86 -21
- package/src/server/request-gates.mjs +34 -5
- package/src/server/restart-note.mjs +1 -1
- package/src/server/seed-boundary.mjs +489 -0
- package/src/server/session-counts.mjs +244 -0
- package/src/server/session-deck-names.mjs +143 -0
- package/src/server/session-enrichment.mjs +43 -6
- package/src/server/session-name-route.mjs +73 -0
- package/src/server/session-summary.mjs +12 -1
- package/src/server/session-transcript-routes.mjs +167 -0
- package/src/server/swap-log.mjs +1 -1
- package/src/server/system-metrics.mjs +57 -0
- package/src/server/terminal-bridge.mjs +485 -0
- package/src/server/terminal-folder.mjs +61 -0
- package/src/server/terminal-js-routes.mjs +752 -0
- package/src/server/terminal-routes.mjs +553 -0
- package/src/server/terminal-sessions.mjs +759 -0
- package/src/server/terminal-socket.mjs +403 -0
- package/src/server/terminal-target.mjs +928 -0
- package/src/server/thermal-metrics.mjs +13 -9
- package/src/server/tmux-control.mjs +1319 -0
- package/src/server/tmux-download.mjs +220 -0
- package/src/server/tmux.mjs +542 -0
- package/src/server/token-redact.mjs +42 -3
- package/src/server/tool-audit-report.mjs +44 -6
- package/src/server/tool-audit-routes.mjs +12 -1
- package/src/server/tool-audit.mjs +42 -8
- package/src/server/traffic-radar-monitor.mjs +1 -1
- package/src/server/traffic-radar-permission.mjs +1 -1
- package/src/server/transcript-gate.mjs +1 -1
- package/src/server/transcript-scan.mjs +15 -7
- package/src/server/transcript-turns.mjs +154 -0
- package/src/server/tui-network.mjs +1 -0
- package/src/server/tui-view.mjs +28 -0
- package/src/server/utf8-carry.mjs +159 -0
- package/src/server/uv-bootstrap.mjs +2 -2
- package/src/server/windows-acl.mjs +158 -0
- package/src/server/ws-frames.mjs +690 -0
- package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
- package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
- package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
- package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
- package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
- package/dist/web/assets/app-CbXmr9rC.css +0 -1
- package/dist/web/assets/app-DZdZoqJ6.js +0 -358
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
// Which terminal a session on the board can be reached through, and how — the
|
|
2
|
+
// question every click on a node asks before the terminal panel opens.
|
|
3
|
+
//
|
|
4
|
+
// The deck knows a session by its id and its working directory, because that
|
|
5
|
+
// is all the hooks and the Codex rollouts carry. It does not know the process,
|
|
6
|
+
// and without the process there is no telling a session the panel can attach
|
|
7
|
+
// to from one it cannot. A throwaway spike, measured against real Claude and
|
|
8
|
+
// Codex processes before any of this was written, found the way; this is that
|
|
9
|
+
// spike made into something the server can ask on every click, with every
|
|
10
|
+
// answer the panel has to tell apart:
|
|
11
|
+
//
|
|
12
|
+
// A the deck started it, in its own tmux server: attach.
|
|
13
|
+
// B it runs in the user's own tmux: join that pane, at the pane's
|
|
14
|
+
// size, so the user's terminal is never resized under them.
|
|
15
|
+
// D it is one of Claude's background sessions: `claude attach`
|
|
16
|
+
// inside a deck pane is its only door.
|
|
17
|
+
// C a plain process in some other terminal: nothing to attach to.
|
|
18
|
+
// It can be reopened here, once it has stopped.
|
|
19
|
+
// gone nothing holds it any more: it can be reopened here.
|
|
20
|
+
// unsupported no tmux the panel can drive, or a question that was not one.
|
|
21
|
+
//
|
|
22
|
+
// WHERE THE PROCESS COMES FROM. Claude Code writes <config dir>/sessions/
|
|
23
|
+
// <pid>.json for every live session, interactive and background alike, with
|
|
24
|
+
// the sessionId, the kind and `procStart` — the process's start time as the
|
|
25
|
+
// kernel tells it (field 22 of /proc/<pid>/stat on Linux; `ps -o lstart=` in
|
|
26
|
+
// the C locale and UTC on macOS, read off the 2.1.294 bundle). A pid is
|
|
27
|
+
// evidence only while the process holding it is the one that wrote the record,
|
|
28
|
+
// and a start time is what catches a recycled pid that happens to be alive.
|
|
29
|
+
// The `<pid>.<hash>.key` files beside those records are secrets: they are never
|
|
30
|
+
// opened, and the name filter below is the whole of that guarantee, so it is
|
|
31
|
+
// an anchored pattern rather than an extension check.
|
|
32
|
+
//
|
|
33
|
+
// A record is not written the moment a session starts, though: a live Claude
|
|
34
|
+
// 2.1.301 measured in a fresh config dir had its `.key` and no `<pid>.json`
|
|
35
|
+
// yet, while its hooks had already put it on the board. Reading no record as
|
|
36
|
+
// "nothing holds it" offered to reopen a session that was running, which
|
|
37
|
+
// would put two writers on one conversation. So when no record names the
|
|
38
|
+
// session, a live Claude that no record accounts for, started in the
|
|
39
|
+
// session's own folder, is taken as possibly holding it (`unrecordedClaude`):
|
|
40
|
+
// case C or a pane, never `gone`. It can name a different session in the same
|
|
41
|
+
// folder; that costs a reopen that waits for it to stop, and the other way
|
|
42
|
+
// round costs a conversation.
|
|
43
|
+
//
|
|
44
|
+
// Codex keeps no such file. A Codex the deck launched is found by the session
|
|
45
|
+
// option the deck set on its pane; one whose id the deck did not know yet, by
|
|
46
|
+
// the rollout file its process holds open. Anything else is found the same way
|
|
47
|
+
// where /proc exists, and by `codex resume <id>` on its command line where it
|
|
48
|
+
// does not — see WHAT THIS CANNOT SEE.
|
|
49
|
+
//
|
|
50
|
+
// WHY BACKGROUND BEFORE TMUX. The spike asked for a pane first. A Claude
|
|
51
|
+
// background session's pty belongs to its `claude bg-pty-host`, whatever tmux
|
|
52
|
+
// the daemon happened to be started from, so a pane found by ancestry would be
|
|
53
|
+
// the user's shell, not the session. So the record's `kind` decides, and a
|
|
54
|
+
// `bg-pty-host` as the session's PARENT decides when the record carries no
|
|
55
|
+
// kind: three of the five sessions measured had been reparented to systemd
|
|
56
|
+
// after a daemon restart and were still attachable. The parent, not any
|
|
57
|
+
// ancestor — the spike looked at the whole chain, and the first run of this
|
|
58
|
+
// module against a real process table showed why that is wrong: every process
|
|
59
|
+
// started from inside a background session has a pty host somewhere above it,
|
|
60
|
+
// including an ordinary interactive `claude` an agent launched there, and
|
|
61
|
+
// `claude attach` with that session's id opens nothing.
|
|
62
|
+
//
|
|
63
|
+
// WHY A PANE HAS TO SHOW THE PROCESS. Ancestry says a process descends from a
|
|
64
|
+
// pane, not that the pane draws it. `claude -p` run by another session's tool
|
|
65
|
+
// descends from that session's pane and writes into a pipe; attaching to the
|
|
66
|
+
// pane would show the other session. So on Linux, where a process's terminal
|
|
67
|
+
// can be read off its file descriptors, a pane is only the answer when the
|
|
68
|
+
// process draws on that pane's tty — a process with no terminal at all is in
|
|
69
|
+
// no pane. macOS reports the controlling terminal instead, which such a child
|
|
70
|
+
// inherits, so there it is a weaker test.
|
|
71
|
+
//
|
|
72
|
+
// WHY EVERYTHING IS A PARAMETER. Every read of the filesystem, /proc, `ps` and
|
|
73
|
+
// tmux goes through `deps`, so the suite classifies fixtures — a recycled pid,
|
|
74
|
+
// a torn record, a forged TMUX_PANE, a macOS process table — without reading a
|
|
75
|
+
// single real process, and without a tmux on the machine that runs it.
|
|
76
|
+
//
|
|
77
|
+
// A CODEX THAT KEEPS ITS ROLLOUT IN A DAEMON. Codex 0.162 hands the rollout to
|
|
78
|
+
// `codex app-server`, a daemon with no terminal that one machine's Codex
|
|
79
|
+
// sessions may share, so the process holding the file is not the one on the
|
|
80
|
+
// screen, and its ancestry leads to systemd, not to a pane. For a Codex the
|
|
81
|
+
// deck launched, the pane is found the other way round: Codex names its
|
|
82
|
+
// sessions with UUIDv7, whose first 48 bits are when it began, so a session
|
|
83
|
+
// that began after exactly one of the deck's unlabelled Codex panes in the
|
|
84
|
+
// same folder opened is that pane's — unless a Codex drawing on another
|
|
85
|
+
// terminal in that folder could have begun it just as well. Then it is not
|
|
86
|
+
// guessed at.
|
|
87
|
+
//
|
|
88
|
+
// WHAT THIS CANNOT SEE, said here so nobody has to rediscover it:
|
|
89
|
+
// - An idle Codex holds no rollout open (one appears after the first message)
|
|
90
|
+
// and a plain `codex` carries no id on its command line, so a Codex that is
|
|
91
|
+
// running outside the deck and has not been sent anything reads as `gone`.
|
|
92
|
+
// macOS has no /proc to find an open rollout through at all; there, only a
|
|
93
|
+
// `codex resume <id>` is found. The adopt route's "still running" check
|
|
94
|
+
// asks this module and shares the blind spot.
|
|
95
|
+
// - A record written in another pid namespace or on another machine (a
|
|
96
|
+
// devcontainer sharing ~/.claude) names a pid that means nothing here; it is
|
|
97
|
+
// ignored rather than believed.
|
|
98
|
+
// - On macOS no other process's environment can be read reliably (`ps eww`
|
|
99
|
+
// shows it for the same user at best), so the pane is found by `pane_pid`
|
|
100
|
+
// ancestry against the user's default tmux server only, never through
|
|
101
|
+
// TMUX_PANE; a session in a tmux server under another name reads as C there.
|
|
102
|
+
import { readdirSync, readFileSync, readlinkSync, statSync } from "node:fs";
|
|
103
|
+
import { basename, isAbsolute, join } from "node:path";
|
|
104
|
+
import { claudeConfigDir } from "./claude-dir.mjs";
|
|
105
|
+
import { run } from "./exec.mjs";
|
|
106
|
+
import { deadDeckSessions, findDeckSession, listDeckSessions } from "./terminal-sessions.mjs";
|
|
107
|
+
import { DECK_SOCKET, findTmux, runTmux, tmuxHasNoServer } from "./tmux.mjs";
|
|
108
|
+
|
|
109
|
+
/** Both providers name a session with a UUID. Anything else is refused before
|
|
110
|
+
* it reaches a file name or an argument vector: an id is later handed to
|
|
111
|
+
* `claude --resume`, and one spelled `--something` would be read as a flag. */
|
|
112
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
113
|
+
|
|
114
|
+
/** The only names in sessions/ this module will open. Anchored on both ends,
|
|
115
|
+
* because `1234.ab12cd.key` sits in the same folder and holds a secret. */
|
|
116
|
+
export const SESSION_FILE = /^\d+\.json$/;
|
|
117
|
+
|
|
118
|
+
/** Bounds on what one question may read. The sessions folder holds one file
|
|
119
|
+
* per live session (tens); the bound is for a folder nothing ever cleans. */
|
|
120
|
+
const MAX_SESSION_FILES = 512;
|
|
121
|
+
const MAX_ANCESTRY = 64;
|
|
122
|
+
const MAX_FDS = 1024;
|
|
123
|
+
const MAX_CODEX_PROCESSES = 64;
|
|
124
|
+
|
|
125
|
+
/** The deck sessions that are a session in their own right. An `attach`
|
|
126
|
+
* session is the wrapper around somebody else's background session (case D)
|
|
127
|
+
* and is reported as that session's wrapper, never as case A. */
|
|
128
|
+
const OWN_KINDS = Object.freeze(["launch", "resume"]);
|
|
129
|
+
|
|
130
|
+
/** The user's own tmux server, which is where a process with no TMUX in its
|
|
131
|
+
* environment would be if it were in tmux at all. */
|
|
132
|
+
const DEFAULT_SOCKET = Object.freeze({ name: "default" });
|
|
133
|
+
|
|
134
|
+
/** A terminal a pane can be: a pts on Linux, a ttys on macOS. `/dev/pts/ptmx`
|
|
135
|
+
* is the multiplexer, not a terminal, and bare `/dev/tty` names none. */
|
|
136
|
+
const TTY_PATH = /^\/dev\/(?:pts\/\d+|tty[A-Za-z0-9.]+)$/;
|
|
137
|
+
|
|
138
|
+
/** The `claude bg-pty-host` command line, as Claude Code 2.1.294 spells it:
|
|
139
|
+
* `claude bg-pty-host --bg-pty-host <sock> <cols> <rows> -- <claude>`. */
|
|
140
|
+
const PTY_HOST = /(^|\s)(--)?bg-pty-host(\s|$)/;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The `list-panes -a -F` format the default lister asks for. The session name
|
|
144
|
+
* goes last because it is the one field a user chooses, so it is the one field
|
|
145
|
+
* that may contain the separator.
|
|
146
|
+
*/
|
|
147
|
+
export const PANE_FORMAT = [
|
|
148
|
+
"#{pane_id}", "#{pane_pid}", "#{pane_dead}", "#{pane_tty}", "#{socket_path}", "#{session_name}",
|
|
149
|
+
].join("\t");
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* `ps` arguments for the process table on a platform without /proc. `lstart`
|
|
153
|
+
* is how Claude Code spells a process's start time there, so it is what makes
|
|
154
|
+
* a record's `procStart` checkable; the C locale and UTC are what Claude Code
|
|
155
|
+
* runs it under, and the string is compared as it wrote it.
|
|
156
|
+
*/
|
|
157
|
+
export const PS_TABLE_ARGS = ["-A", "-ww", "-o", "pid=,ppid=,tty=,lstart=,command="];
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Check the three things a target question is made of, before any of them
|
|
161
|
+
* reaches a file name, a pattern or an argument vector.
|
|
162
|
+
*
|
|
163
|
+
* Exported so the routes can answer a malformed question with a 400 before
|
|
164
|
+
* asking anything; resolveTarget checks again on its own, because a module
|
|
165
|
+
* that hands a session id to `claude --resume` cannot rely on its caller.
|
|
166
|
+
* A missing or relative `cwd` is not an error: it only means the session
|
|
167
|
+
* cannot be reopened here, which the target says.
|
|
168
|
+
*/
|
|
169
|
+
export function checkTargetQuery(query) {
|
|
170
|
+
// Lower case, because that is how both providers write the id into every
|
|
171
|
+
// file this module compares it with: the records, the rollout names, argv.
|
|
172
|
+
const sessionId = typeof query?.sessionId === "string" ? query.sessionId.trim().toLowerCase() : "";
|
|
173
|
+
if (!SESSION_ID.test(sessionId)) return { ok: false, error: "That is not a session id." };
|
|
174
|
+
const provider = query?.provider;
|
|
175
|
+
if (provider !== "claude" && provider !== "codex") {
|
|
176
|
+
return { ok: false, error: "The provider must be claude or codex." };
|
|
177
|
+
}
|
|
178
|
+
const cwd = typeof query?.cwd === "string" && isAbsolute(query.cwd) ? query.cwd : "";
|
|
179
|
+
return { ok: true, sessionId, provider, cwd };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* One `/proc/<pid>/stat` line, or null: the pid, the parent, the tty and the
|
|
184
|
+
* start time in clock ticks (field 22), as a string because that is how Claude
|
|
185
|
+
* Code records it.
|
|
186
|
+
*
|
|
187
|
+
* Read from the LAST `)`, because field 2 is the command name and may hold
|
|
188
|
+
* spaces and parentheses of its own; `(tmux: server)` would otherwise shift
|
|
189
|
+
* every field after it. Field 3 is then the first word, so field N is at N - 3.
|
|
190
|
+
*/
|
|
191
|
+
export function parseProcStat(text) {
|
|
192
|
+
const s = String(text ?? "");
|
|
193
|
+
const open = s.indexOf("(");
|
|
194
|
+
const close = s.lastIndexOf(")");
|
|
195
|
+
if (open < 0 || close < open) return null;
|
|
196
|
+
const pid = Number(s.slice(0, open).trim());
|
|
197
|
+
const f = s.slice(close + 1).trim().split(/\s+/);
|
|
198
|
+
if (f.length < 20) return null;
|
|
199
|
+
const ppid = Number(f[1]);
|
|
200
|
+
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid)) return null;
|
|
201
|
+
return { pid, comm: s.slice(open + 1, close), ppid, ttyNr: Number(f[4]), start: f[19] };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** `/proc/<pid>/environ` as an object. It is the environment the process
|
|
205
|
+
* started with, which is exactly what TMUX and TMUX_PANE are wanted from. */
|
|
206
|
+
export function parseEnviron(text) {
|
|
207
|
+
const env = {};
|
|
208
|
+
for (const kv of String(text ?? "").split("\0")) {
|
|
209
|
+
const i = kv.indexOf("=");
|
|
210
|
+
if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1);
|
|
211
|
+
}
|
|
212
|
+
return env;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The server socket out of a TMUX variable, which tmux writes as
|
|
217
|
+
* `<socket path>,<server pid>,<session index>`. Taken from the right, because
|
|
218
|
+
* the path is the one part that may itself contain a comma. Empty when the
|
|
219
|
+
* value is not that shape.
|
|
220
|
+
*/
|
|
221
|
+
export function tmuxSocketPath(value) {
|
|
222
|
+
const m = /^(.*),(\d+),(-?\d+)$/.exec(String(value ?? ""));
|
|
223
|
+
return m && m[1] && m[1].startsWith("/") ? m[1] : "";
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** `list-panes -a -F PANE_FORMAT` output, one pane per line. A line that does
|
|
227
|
+
* not start with a pane id is not a pane and is skipped. */
|
|
228
|
+
export function parsePaneList(text) {
|
|
229
|
+
const out = [];
|
|
230
|
+
for (const line of String(text ?? "").split("\n")) {
|
|
231
|
+
const [id, pid, dead, tty, socketPath, ...name] = line.replace(/\r$/, "").split("\t");
|
|
232
|
+
if (!/^%\d+$/.test(id ?? "")) continue;
|
|
233
|
+
out.push({
|
|
234
|
+
id,
|
|
235
|
+
pid: Number(pid) || 0,
|
|
236
|
+
dead: dead === "1",
|
|
237
|
+
tty: tty ?? "",
|
|
238
|
+
socketPath: socketPath ?? "",
|
|
239
|
+
session: name.join("\t"),
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** `ps PS_TABLE_ARGS` output as rows of { pid, ppid, tty, start, cmd }. The
|
|
246
|
+
* start time is five words with a padded day ("Thu Oct 8 09:12:33 2026"),
|
|
247
|
+
* kept with its spacing collapsed, and a record's `procStart` is collapsed
|
|
248
|
+
* the same way before the two are compared. */
|
|
249
|
+
export function parsePsTable(text) {
|
|
250
|
+
const out = [];
|
|
251
|
+
const row = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)(?:\s+(.*))?$/;
|
|
252
|
+
for (const line of String(text ?? "").split("\n")) {
|
|
253
|
+
const m = row.exec(line);
|
|
254
|
+
if (!m) continue;
|
|
255
|
+
const tty = m[3];
|
|
256
|
+
out.push({
|
|
257
|
+
pid: Number(m[1]),
|
|
258
|
+
ppid: Number(m[2]),
|
|
259
|
+
tty: tty === "?" || tty === "??" || tty === "-" ? "" : `/dev/${tty}`,
|
|
260
|
+
start: collapse(m[4]),
|
|
261
|
+
cmd: (m[5] ?? "").trim(),
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Every Claude Code session record in `<claudeDir>/sessions`, as far as each
|
|
269
|
+
* one parses. Only `<digits>.json` is opened. A record that does not parse is
|
|
270
|
+
* a write caught half way and is skipped, not an error; one whose pid differs
|
|
271
|
+
* from its file name is not trusted with either.
|
|
272
|
+
*/
|
|
273
|
+
export function readClaudeSessions(claudeDir, { readdir, readFile }) {
|
|
274
|
+
const dir = join(claudeDir, "sessions");
|
|
275
|
+
let names;
|
|
276
|
+
try { names = readdir(dir); } catch { return []; }
|
|
277
|
+
if (!Array.isArray(names)) return [];
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const name of names.map(String).filter((n) => SESSION_FILE.test(n)).slice(0, MAX_SESSION_FILES)) {
|
|
280
|
+
let raw;
|
|
281
|
+
try { raw = JSON.parse(String(readFile(join(dir, name)))); } catch { continue; }
|
|
282
|
+
const rec = sessionRecordOf(raw, Number(name.slice(0, -".json".length)));
|
|
283
|
+
if (rec) out.push(rec);
|
|
284
|
+
}
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function sessionRecordOf(raw, filePid) {
|
|
289
|
+
if (!raw || typeof raw !== "object") return null;
|
|
290
|
+
const { pid, sessionId } = raw;
|
|
291
|
+
if (!Number.isInteger(pid) || pid <= 1 || pid !== filePid) return null;
|
|
292
|
+
if (typeof sessionId !== "string" || !sessionId) return null;
|
|
293
|
+
const start = typeof raw.procStart === "string" || typeof raw.procStart === "number" ? String(raw.procStart) : "";
|
|
294
|
+
return {
|
|
295
|
+
pid,
|
|
296
|
+
sessionId,
|
|
297
|
+
kind: typeof raw.kind === "string" ? raw.kind : "",
|
|
298
|
+
procStart: start || null,
|
|
299
|
+
jobId: typeof raw.jobId === "string" ? raw.jobId : "",
|
|
300
|
+
pidDomain: typeof raw.pidDomain === "string" ? raw.pidDomain : "",
|
|
301
|
+
startedAt: Number.isFinite(raw.startedAt) ? raw.startedAt : 0,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* What `claude attach` is handed for a background session: the record's own
|
|
307
|
+
* short id, which is what `claude --bg` prints and `claude attach --help`
|
|
308
|
+
* names, else the first eight characters of the session id, which is how
|
|
309
|
+
* Claude Code forms that short id. Never anything that could read as a flag.
|
|
310
|
+
*/
|
|
311
|
+
export function attachIdOf(rec, sessionId) {
|
|
312
|
+
const job = typeof rec?.jobId === "string" ? rec.jobId : "";
|
|
313
|
+
return /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(job) ? job : String(sessionId).slice(0, 8);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Where a session can be reached from, or why it cannot. See the header for
|
|
318
|
+
* the kinds; the shapes are:
|
|
319
|
+
*
|
|
320
|
+
* { kind: "A", socket, pane, name, learnedId?, launchKey? }
|
|
321
|
+
* socket is the deck's own (DECK_SOCKET)
|
|
322
|
+
* { kind: "B", socket: { path }, pane }
|
|
323
|
+
* { kind: "D", attachId, tty?, wrapper? }
|
|
324
|
+
* tty: the background session's own
|
|
325
|
+
* terminal, whose size a wrapper takes;
|
|
326
|
+
* wrapper: a live deck pane already
|
|
327
|
+
* running `claude attach` for it
|
|
328
|
+
* { kind: "C", adoptable, pid }
|
|
329
|
+
* { kind: "gone", adoptable, deadSessions? }
|
|
330
|
+
* { kind: "unsupported", reason, install? }
|
|
331
|
+
* reason: "missing" | "too-old" | "unsupported-platform" (as findTmux
|
|
332
|
+
* says it) or "invalid" for a question that was not a session
|
|
333
|
+
*
|
|
334
|
+
* `adoptable` says the session could be reopened here: a provider that
|
|
335
|
+
* resumes by id and a working directory that still exists. It does not say
|
|
336
|
+
* the original has stopped — for C it has not — which is the adopt route's
|
|
337
|
+
* check to make when somebody asks.
|
|
338
|
+
*
|
|
339
|
+
* Three fields are for the routes and never reach the page (describeTarget
|
|
340
|
+
* leaves them out). `launchKey` is on an A in a deck pane a page launch
|
|
341
|
+
* named, for the claim route to say whether that launch became this
|
|
342
|
+
* session. `learnedId` is on an A that was found by its process
|
|
343
|
+
* because its pane's `@ccdeck-session` is still empty — a Codex the deck
|
|
344
|
+
* launched, recognised by the rollout it holds open — and is the id that
|
|
345
|
+
* process was found by, for the open route to write into the option so the
|
|
346
|
+
* next lookup is the listing alone. `deadSessions` is on a gone: the names of
|
|
347
|
+
* the dead deck panes this session left behind, which the adopt route clears
|
|
348
|
+
* before it reopens the session (terminal-sessions' deadDeckSessions).
|
|
349
|
+
*
|
|
350
|
+
* This module still writes nothing; it only says what it saw.
|
|
351
|
+
*
|
|
352
|
+
* Never rejects for a state of the machine: a missing tmux, a tmux that does
|
|
353
|
+
* not answer, a dead pane, a torn record or an unreadable /proc are all
|
|
354
|
+
* answers. `deps`, every one
|
|
355
|
+
* optional: platform, claudeDir, readdir/readFile/readlink (synchronous,
|
|
356
|
+
* string-returning), isDir, processTable (async; the `ps` table where there
|
|
357
|
+
* is no /proc), tmux (findTmux's answer), deckSocket, listDeckSessions (async)
|
|
358
|
+
* and listPanes(socket) (async; panes as parsePaneList shapes them).
|
|
359
|
+
*/
|
|
360
|
+
/**
|
|
361
|
+
* A tmux that did not answer: it outran runTmux's timeout, or failed for a
|
|
362
|
+
* reason other than having no server to ask. Its silence says nothing about
|
|
363
|
+
* where a session is. Read as "no panes", a live session in a tmux that had
|
|
364
|
+
* stalled for three seconds was offered "Reopen here" as if it had ended, and
|
|
365
|
+
* the card stayed after tmux came back. resolveTarget answers it as what it
|
|
366
|
+
* is instead, and the panel offers to try again.
|
|
367
|
+
*/
|
|
368
|
+
export class TmuxNotAnswering extends Error {
|
|
369
|
+
constructor() {
|
|
370
|
+
super("tmux did not answer.");
|
|
371
|
+
this.name = "TmuxNotAnswering";
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export async function resolveTarget(query, deps = {}) {
|
|
376
|
+
const q = checkTargetQuery(query);
|
|
377
|
+
if (!q.ok) return { kind: "unsupported", reason: "invalid" };
|
|
378
|
+
const platform = deps.platform ?? process.platform;
|
|
379
|
+
// Windows is refused before anything is asked of it: there is no tmux there,
|
|
380
|
+
// and findTmux would only spend a probe to say so.
|
|
381
|
+
if (platform === "win32") return { kind: "unsupported", reason: "unsupported-platform" };
|
|
382
|
+
|
|
383
|
+
const tmux = deps.tmux ?? await findTmux({ platform });
|
|
384
|
+
// Every door below is a tmux pane — the deck's, the user's, or the deck pane
|
|
385
|
+
// that runs `claude attach` — and so is reopening a session here. Without a
|
|
386
|
+
// tmux that works there is nothing to offer, whatever state the session is in.
|
|
387
|
+
if (!tmux?.ok) {
|
|
388
|
+
return { kind: "unsupported", reason: tmux?.reason || "missing", ...(tmux?.install ? { install: tmux.install } : {}) };
|
|
389
|
+
}
|
|
390
|
+
const io = ioFor(deps, tmux, platform);
|
|
391
|
+
try {
|
|
392
|
+
return await locateIn(q, io, platform);
|
|
393
|
+
} catch (err) {
|
|
394
|
+
if (err instanceof TmuxNotAnswering) return { kind: "unsupported", reason: "not-answering" };
|
|
395
|
+
throw err;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function locateIn(q, io, platform) {
|
|
400
|
+
const deck = await deckSessionsOf(io);
|
|
401
|
+
const own = findDeckSession(deck, q.sessionId, { kinds: OWN_KINDS });
|
|
402
|
+
if (own && !own.dead) return deckTarget(io, own, q.sessionId);
|
|
403
|
+
// A dead deck pane is not the end of it: the session may have been resumed
|
|
404
|
+
// somewhere else since, so it is looked for like any other.
|
|
405
|
+
|
|
406
|
+
const proc = platform === "linux" ? procView(io) : await psView(io);
|
|
407
|
+
const holder = q.provider === "claude"
|
|
408
|
+
? claudeHolder(q.sessionId, io, proc) ?? unrecordedClaude(q, io, proc)
|
|
409
|
+
: codexHolder(q.sessionId, proc);
|
|
410
|
+
if (!holder) {
|
|
411
|
+
// Where no process's open files can be read (macOS), no holder says
|
|
412
|
+
// nothing — and offering to reopen a Codex the deck is running would put
|
|
413
|
+
// two writers on one rollout.
|
|
414
|
+
if (q.provider === "codex" && platform !== "linux") {
|
|
415
|
+
const began = launchedCodexPane(q, deck, proc, io);
|
|
416
|
+
if (began) return deckTarget(io, began, q.sessionId);
|
|
417
|
+
}
|
|
418
|
+
const dead = deadDeckSessions(deck, q.sessionId);
|
|
419
|
+
return { kind: "gone", adoptable: resumable(q, io), ...(dead.length ? { deadSessions: dead } : {}) };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if (holder.background) {
|
|
423
|
+
const found = findDeckSession(deck, q.sessionId, { kinds: ["attach"] });
|
|
424
|
+
const wrapper = found && !found.dead ? found : null;
|
|
425
|
+
const tty = proc.tty(holder.pid);
|
|
426
|
+
return {
|
|
427
|
+
kind: "D",
|
|
428
|
+
attachId: holder.attachId,
|
|
429
|
+
...(tty ? { tty } : {}),
|
|
430
|
+
...(wrapper ? { wrapper: { name: wrapper.name, pane: wrapper.pane } } : {}),
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// A process under one of the deck's own panes is case A whatever its option
|
|
435
|
+
// says: a Codex the deck launched has no id to set until its first message,
|
|
436
|
+
// and this is how it is recognised before then. The deck's list carries no
|
|
437
|
+
// pane tty, so the one check available here is that the process draws on a
|
|
438
|
+
// terminal at all.
|
|
439
|
+
holder.tty = proc.tty(holder.pid);
|
|
440
|
+
const pids = new Set(holder.chain.map((c) => c.pid));
|
|
441
|
+
const under = holder.tty === "" ? undefined
|
|
442
|
+
: deck.find((s) => !s.dead && OWN_KINDS.includes(s.kind) && pids.has(s.panePid));
|
|
443
|
+
if (under) return deckTarget(io, under, q.sessionId);
|
|
444
|
+
// Held by a process with no terminal: a Codex daemon (see the header).
|
|
445
|
+
if (q.provider === "codex" && holder.tty === "") {
|
|
446
|
+
const began = launchedCodexPane(q, deck, proc, io);
|
|
447
|
+
if (began) return deckTarget(io, began, q.sessionId);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const found = await hostPane(holder, proc, io);
|
|
451
|
+
if (found && onSocket(found.socketPath, io.deckSocket)) {
|
|
452
|
+
return { kind: "A", socket: io.deckSocket, pane: found.pane, name: found.session };
|
|
453
|
+
}
|
|
454
|
+
if (found) return { kind: "B", socket: found.socket, pane: found.pane };
|
|
455
|
+
return { kind: "C", adoptable: resumable(q, io), pid: holder.pid };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* The sentence the panel shows for a target, and the little it needs beside
|
|
460
|
+
* it. No paths, no pids, no pane ids: the panel never needs them, and the
|
|
461
|
+
* target itself stays on the server, bound to the ticket the panel is given.
|
|
462
|
+
*
|
|
463
|
+
* Case C's copy is the plan's, word for word (ux.md, "Not startable here"):
|
|
464
|
+
* honest, not apologetic, and with the cost of reopening named inline. Its
|
|
465
|
+
* `hint` is the step before that button can work — the original has to stop
|
|
466
|
+
* first — so the panel can say it before the click rather than after a 409.
|
|
467
|
+
*/
|
|
468
|
+
export function describeTarget(target) {
|
|
469
|
+
const kind = target?.kind;
|
|
470
|
+
switch (kind) {
|
|
471
|
+
case "A":
|
|
472
|
+
return { kind, label: "This session runs in a terminal the deck started, so the panel attaches to it directly." };
|
|
473
|
+
case "B":
|
|
474
|
+
return { kind, label: "This session runs in your own tmux, so the panel joins that pane at its own size and leaves your terminal as it is." };
|
|
475
|
+
case "D":
|
|
476
|
+
// The panel fits the session to itself and puts its own size back as it
|
|
477
|
+
// closes (terminal-js-routes, keepSize). The engine says the same words.
|
|
478
|
+
return { kind, label: "This is a Claude background session, so the panel opens it the way claude attach does, fitted to the panel, and when the panel closes it keeps running at the size it had before." };
|
|
479
|
+
case "C":
|
|
480
|
+
return target.adoptable
|
|
481
|
+
? {
|
|
482
|
+
kind,
|
|
483
|
+
label: "This session was started outside the deck, so there is no pane to attach to. Reopening it here continues the conversation; the old terminal's scrollback stays behind.",
|
|
484
|
+
adoptable: true,
|
|
485
|
+
hint: "Quit it in the terminal it is running in first, then reopen it here.",
|
|
486
|
+
}
|
|
487
|
+
: { kind, label: "This session was started outside the deck, so there is no pane to attach to.", adoptable: false };
|
|
488
|
+
case "gone":
|
|
489
|
+
return target.adoptable
|
|
490
|
+
? { kind, label: "This session has ended; reopening it here continues the conversation in a new terminal.", adoptable: true }
|
|
491
|
+
: { kind, label: "This session has ended, and its project folder is no longer there to reopen it in.", adoptable: false };
|
|
492
|
+
case "unsupported": {
|
|
493
|
+
const reason = typeof target.reason === "string" ? target.reason : "";
|
|
494
|
+
const install = typeof target.install === "string" && target.install ? { install: target.install } : {};
|
|
495
|
+
return { kind, label: UNSUPPORTED_COPY[reason] ?? UNSUPPORTED_COPY.other, reason: reason || "other", ...install };
|
|
496
|
+
}
|
|
497
|
+
default:
|
|
498
|
+
return { kind: "unsupported", label: UNSUPPORTED_COPY.other, reason: "other" };
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** One fact each, not an error: the ux brief's "tmux missing" row. The install
|
|
503
|
+
* line, when findTmux has one for this platform, travels beside the label. */
|
|
504
|
+
const UNSUPPORTED_COPY = {
|
|
505
|
+
"missing": "The terminal runs on tmux, which is not installed on this machine.",
|
|
506
|
+
"too-old": "The terminal needs tmux 3.2 or newer, and this machine has an older one.",
|
|
507
|
+
"unsupported-platform": "The terminal is not available on this operating system yet.",
|
|
508
|
+
"invalid": "The deck could not tell which session this is.",
|
|
509
|
+
"not-answering": "tmux is not answering right now, so the deck cannot tell where this session is. Nothing was changed; try again in a moment.",
|
|
510
|
+
"other": "The terminal is not available here.",
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
// ---------------------------------------------------------------------------
|
|
514
|
+
|
|
515
|
+
function ioFor(deps, tmux, platform) {
|
|
516
|
+
return {
|
|
517
|
+
platform,
|
|
518
|
+
claudeDir: deps.claudeDir ?? claudeConfigDir(),
|
|
519
|
+
readdir: deps.readdir ?? ((p) => readdirSync(p)),
|
|
520
|
+
readFile: deps.readFile ?? ((p) => readFileSync(p, "utf8")),
|
|
521
|
+
readlink: deps.readlink ?? ((p) => readlinkSync(p)),
|
|
522
|
+
isDir: deps.isDir ?? isDirectory,
|
|
523
|
+
processTable: deps.processTable ?? readPsTable,
|
|
524
|
+
deckSocket: deps.deckSocket ?? DECK_SOCKET,
|
|
525
|
+
listDeckSessions: deps.listDeckSessions ?? (() => listDeckSessions({ tmux })),
|
|
526
|
+
listPanes: deps.listPanes ?? ((socket) => listPanesOn(tmux, socket)),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Every pane on one tmux server. A server that is not running answers
|
|
531
|
+
* non-zero, and that is not an error: it means there is no pane on it. A
|
|
532
|
+
* server that does not answer at all is TmuxNotAnswering. */
|
|
533
|
+
async function listPanesOn(tmux, socket) {
|
|
534
|
+
const r = await runTmux(tmux, socket, ["list-panes", "-a", "-F", PANE_FORMAT]);
|
|
535
|
+
if (r?.code === 0) return parsePaneList(r.stdout);
|
|
536
|
+
if (tmuxHasNoServer(r?.stderr)) return [];
|
|
537
|
+
throw new TmuxNotAnswering();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async function readPsTable() {
|
|
541
|
+
const r = await run("ps", PS_TABLE_ARGS, { timeout: 3_000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } });
|
|
542
|
+
return r.ok ? parsePsTable(r.stdout) : [];
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function isDirectory(p) {
|
|
546
|
+
try { return statSync(p).isDirectory(); } catch { return false; }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** The deck's own sessions. No server is an empty list (listDeckSessions
|
|
550
|
+
* says so); a listing that failed is not, and is TmuxNotAnswering. */
|
|
551
|
+
async function deckSessionsOf(io) {
|
|
552
|
+
let list;
|
|
553
|
+
try {
|
|
554
|
+
list = await io.listDeckSessions();
|
|
555
|
+
} catch {
|
|
556
|
+
throw new TmuxNotAnswering();
|
|
557
|
+
}
|
|
558
|
+
return Array.isArray(list) ? list : [];
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Case A on a deck session. A session whose `@ccdeck-session` is empty was
|
|
562
|
+
* found by its process, and the id it was found by is handed on as
|
|
563
|
+
* `learnedId`; a label already there is never offered a replacement, because
|
|
564
|
+
* a Claude that ran /clear holds a newer id than its pane's label and the
|
|
565
|
+
* label is the one the deck launched it under. */
|
|
566
|
+
function deckTarget(io, s, sessionId) {
|
|
567
|
+
return {
|
|
568
|
+
kind: "A", socket: io.deckSocket, pane: s.pane, name: s.name,
|
|
569
|
+
...(!s.sessionId && sessionId ? { learnedId: sessionId } : {}),
|
|
570
|
+
...(s.launchKey ? { launchKey: s.launchKey } : {}),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function resumable(q, io) {
|
|
575
|
+
return Boolean(q.cwd) && io.isDir(q.cwd);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function collapse(s) {
|
|
579
|
+
return String(s).trim().replace(/\s+/g, " ");
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Whether a socket path is the deck's own server, by name or by path. */
|
|
583
|
+
function onSocket(socketPath, deckSocket) {
|
|
584
|
+
if (!socketPath || !deckSocket) return false;
|
|
585
|
+
if (deckSocket.path) return socketPath === deckSocket.path;
|
|
586
|
+
return Boolean(deckSocket.name) && basename(socketPath) === deckSocket.name;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// ---------------------------------------------------------------------------
|
|
590
|
+
// The two ways of looking at processes. Both answer the same questions —
|
|
591
|
+
// a process's parent, start time and command line, its tty, and on Linux its
|
|
592
|
+
// environment and open files — so everything above is written once.
|
|
593
|
+
|
|
594
|
+
function procView(io) {
|
|
595
|
+
const commands = new Map();
|
|
596
|
+
const command = (pid) => {
|
|
597
|
+
if (!commands.has(pid)) {
|
|
598
|
+
let cmd = "";
|
|
599
|
+
try { cmd = String(io.readFile(`/proc/${pid}/cmdline`)).split("\0").filter(Boolean).join(" "); } catch { cmd = ""; }
|
|
600
|
+
commands.set(pid, cmd);
|
|
601
|
+
}
|
|
602
|
+
return commands.get(pid);
|
|
603
|
+
};
|
|
604
|
+
const infos = new Map();
|
|
605
|
+
return {
|
|
606
|
+
info(pid) {
|
|
607
|
+
if (!infos.has(pid)) {
|
|
608
|
+
let st = null;
|
|
609
|
+
try { st = parseProcStat(io.readFile(`/proc/${pid}/stat`)); } catch { st = null; }
|
|
610
|
+
infos.set(pid, st && { pid: st.pid, ppid: st.ppid, start: st.start, cmd: command(pid) });
|
|
611
|
+
}
|
|
612
|
+
return infos.get(pid);
|
|
613
|
+
},
|
|
614
|
+
command,
|
|
615
|
+
env(pid) {
|
|
616
|
+
try { return parseEnviron(io.readFile(`/proc/${pid}/environ`)); } catch { return null; }
|
|
617
|
+
},
|
|
618
|
+
// The terminal the process draws on, "" when its standard streams are all
|
|
619
|
+
// something else (pipes, files, /dev/null), and null when they could not
|
|
620
|
+
// be read or only say "the controlling terminal" without naming it.
|
|
621
|
+
tty(pid) {
|
|
622
|
+
let seen = false, vague = false;
|
|
623
|
+
for (const fd of ["0", "1", "2"]) {
|
|
624
|
+
try {
|
|
625
|
+
const t = String(io.readlink(`/proc/${pid}/fd/${fd}`));
|
|
626
|
+
seen = true;
|
|
627
|
+
if (TTY_PATH.test(t)) return t;
|
|
628
|
+
if (t === "/dev/tty") vague = true;
|
|
629
|
+
} catch { /* closed, or not ours to read */ }
|
|
630
|
+
}
|
|
631
|
+
return seen && !vague ? "" : null;
|
|
632
|
+
},
|
|
633
|
+
pids() {
|
|
634
|
+
try { return io.readdir("/proc").map(String).filter((n) => /^\d+$/.test(n)).map(Number); } catch { return []; }
|
|
635
|
+
},
|
|
636
|
+
fds(pid) {
|
|
637
|
+
let names;
|
|
638
|
+
try { names = io.readdir(`/proc/${pid}/fd`); } catch { return []; }
|
|
639
|
+
const out = [];
|
|
640
|
+
for (const n of names.slice(0, MAX_FDS)) {
|
|
641
|
+
try { out.push(String(io.readlink(`/proc/${pid}/fd/${n}`))); } catch { /* closed meanwhile */ }
|
|
642
|
+
}
|
|
643
|
+
return out;
|
|
644
|
+
},
|
|
645
|
+
// Which pid namespace and machine this deck sees, for records written
|
|
646
|
+
// somewhere else. Claude Code spells the record's as
|
|
647
|
+
// `linux:<machine-id>:pid:[<namespace inode>]`.
|
|
648
|
+
domain() {
|
|
649
|
+
let ns = "", machine = "";
|
|
650
|
+
try { ns = String(io.readlink("/proc/self/ns/pid")); } catch { ns = ""; }
|
|
651
|
+
try { machine = String(io.readFile("/etc/machine-id")).trim(); } catch { machine = ""; }
|
|
652
|
+
return { ns, machine };
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async function psView(io) {
|
|
658
|
+
let rows = [];
|
|
659
|
+
try { rows = await io.processTable(); } catch { rows = []; }
|
|
660
|
+
const byPid = new Map((Array.isArray(rows) ? rows : []).map((r) => [r.pid, r]));
|
|
661
|
+
return {
|
|
662
|
+
info(pid) {
|
|
663
|
+
const r = byPid.get(pid);
|
|
664
|
+
return r ? { pid, ppid: r.ppid, start: r.start || null, cmd: r.cmd ?? "" } : null;
|
|
665
|
+
},
|
|
666
|
+
command: (pid) => byPid.get(pid)?.cmd ?? "",
|
|
667
|
+
// No /proc: another process's environment is out of reach, and its open
|
|
668
|
+
// files would need an lsof per click — more than what it finds is worth.
|
|
669
|
+
env: () => null,
|
|
670
|
+
tty: (pid) => (byPid.has(pid) ? byPid.get(pid).tty || "" : null),
|
|
671
|
+
pids: () => [...byPid.keys()],
|
|
672
|
+
fds: () => [],
|
|
673
|
+
domain: () => ({ ns: "", machine: "" }),
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function ancestry(proc, pid) {
|
|
678
|
+
const chain = [];
|
|
679
|
+
const seen = new Set();
|
|
680
|
+
for (let p = pid; p > 1 && chain.length < MAX_ANCESTRY && !seen.has(p);) {
|
|
681
|
+
const info = proc.info(p);
|
|
682
|
+
if (!info) break;
|
|
683
|
+
seen.add(p);
|
|
684
|
+
chain.push(info);
|
|
685
|
+
p = info.ppid;
|
|
686
|
+
}
|
|
687
|
+
return chain;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// ---------------------------------------------------------------------------
|
|
691
|
+
// Finding the process that holds a session.
|
|
692
|
+
|
|
693
|
+
/** A record from another machine or pid namespace names a pid that is not
|
|
694
|
+
* this one's. Unknown on either side means no evidence either way. */
|
|
695
|
+
function foreignRecord(rec, here) {
|
|
696
|
+
const m = /^linux:([0-9a-f]+):(pid:\[\d+\])$/i.exec(rec.pidDomain);
|
|
697
|
+
if (!m) return false;
|
|
698
|
+
if (here.machine && m[1].toLowerCase() !== here.machine.toLowerCase()) return true;
|
|
699
|
+
return Boolean(here.ns) && m[2] !== here.ns;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/** The ways Claude Code is started: the native binary by name or under its
|
|
703
|
+
* versions folder, or the npm package's script under node. Used only where a
|
|
704
|
+
* record carries no start time to compare. */
|
|
705
|
+
function looksLikeClaude(cmd) {
|
|
706
|
+
const first = String(cmd).split(" ")[0] ?? "";
|
|
707
|
+
return /^claude(\.exe)?$/i.test(basename(first))
|
|
708
|
+
|| first.includes("/claude/versions/")
|
|
709
|
+
|| String(cmd).includes("@anthropic-ai/claude-code/");
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** The process a Claude record names, if it is still the one that wrote it. */
|
|
713
|
+
function liveProcess(rec, proc) {
|
|
714
|
+
const p = proc.info(rec.pid);
|
|
715
|
+
if (!p) return null;
|
|
716
|
+
if (rec.procStart != null && p.start != null) return collapse(rec.procStart) === collapse(p.start) ? p : null;
|
|
717
|
+
// No start time to compare on one side or the other: the pid has to at least
|
|
718
|
+
// still be running Claude Code, or a recycled pid would pass for the session.
|
|
719
|
+
return looksLikeClaude(p.cmd) ? p : null;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function claudeHolder(sessionId, io, proc) {
|
|
723
|
+
const recs = readClaudeSessions(io.claudeDir, io).filter((r) => r.sessionId.toLowerCase() === sessionId);
|
|
724
|
+
if (recs.length === 0) return null;
|
|
725
|
+
const here = proc.domain();
|
|
726
|
+
const live = [];
|
|
727
|
+
for (const rec of recs) {
|
|
728
|
+
if (foreignRecord(rec, here)) continue;
|
|
729
|
+
const p = liveProcess(rec, proc);
|
|
730
|
+
if (!p) continue;
|
|
731
|
+
const chain = ancestry(proc, rec.pid);
|
|
732
|
+
// The parent only: see WHY BACKGROUND BEFORE TMUX for the run that showed
|
|
733
|
+
// what looking further up gets wrong.
|
|
734
|
+
const host = chain.length > 1 && PTY_HOST.test(chain[1].cmd);
|
|
735
|
+
live.push({ rec, chain, background: rec.kind === "bg" || host });
|
|
736
|
+
}
|
|
737
|
+
if (live.length === 0) return null;
|
|
738
|
+
// Two live records for one session is a background session with something
|
|
739
|
+
// else beside it, or a resume that started a copy. The background one is the
|
|
740
|
+
// session itself; otherwise the newest is the one still being written to.
|
|
741
|
+
const pick = live.find((l) => l.background)
|
|
742
|
+
?? live.sort((a, b) => b.rec.startedAt - a.rec.startedAt)[0];
|
|
743
|
+
return {
|
|
744
|
+
pid: pick.rec.pid,
|
|
745
|
+
chain: pick.chain,
|
|
746
|
+
background: pick.background,
|
|
747
|
+
attachId: pick.background ? attachIdOf(pick.rec, sessionId) : undefined,
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** Words after the binary that make a Claude process something other than an
|
|
752
|
+
* interactive session: a one-shot print, a background host or client, a
|
|
753
|
+
* server, a maintenance command. */
|
|
754
|
+
const NOT_A_SESSION = /^(-p|--print|attach|bg-pty-host|--bg-pty-host|bg-spare|--bg-spare|daemon|mcp|doctor|update|install|config|setup-token|migrate-installer|api-key)$/;
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* A live Claude that no record accounts for, started in the session's folder,
|
|
758
|
+
* when no record names the session at all — see the header for why a record
|
|
759
|
+
* can be missing. Linux only: a process's folder is read off /proc/<pid>/cwd,
|
|
760
|
+
* and macOS has no cheap equivalent, so there a session without a record
|
|
761
|
+
* still reads as gone. The newest such process wins, as with records.
|
|
762
|
+
*/
|
|
763
|
+
function unrecordedClaude(q, io, proc) {
|
|
764
|
+
if (!q.cwd || io.platform !== "linux") return null;
|
|
765
|
+
const recorded = new Set(readClaudeSessions(io.claudeDir, io).map((r) => r.pid));
|
|
766
|
+
let best = null;
|
|
767
|
+
let looked = 0;
|
|
768
|
+
for (const pid of proc.pids()) {
|
|
769
|
+
if (recorded.has(pid)) continue;
|
|
770
|
+
const cmd = proc.command(pid);
|
|
771
|
+
if (!looksLikeClaude(cmd)) continue;
|
|
772
|
+
if (++looked > MAX_CODEX_PROCESSES) break;
|
|
773
|
+
const words = cmd.split(" ").slice(1);
|
|
774
|
+
if (words.some((w) => NOT_A_SESSION.test(w))) continue;
|
|
775
|
+
let cwd = "";
|
|
776
|
+
try { cwd = String(io.readlink(`/proc/${pid}/cwd`)); } catch { continue; }
|
|
777
|
+
if (cwd !== q.cwd) continue;
|
|
778
|
+
const info = proc.info(pid);
|
|
779
|
+
if (!info) continue;
|
|
780
|
+
if (!best || Number(info.start ?? 0) > Number(best.start ?? 0)) best = info;
|
|
781
|
+
}
|
|
782
|
+
if (!best) return null;
|
|
783
|
+
const chain = ancestry(proc, best.pid);
|
|
784
|
+
return chain.length ? { pid: best.pid, chain, background: false } : null;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Whether a command line is Codex: the native binary, or the npm launcher's
|
|
788
|
+
* script under node. Only the first two words are looked at, so a process
|
|
789
|
+
* that merely mentions codex — a browser profile, an editor — is not one. */
|
|
790
|
+
function looksLikeCodex(cmd) {
|
|
791
|
+
return String(cmd).split(" ").slice(0, 2).some((w) => /^codex(\.js|\.exe)?$/i.test(basename(w)));
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function isRolloutFor(target, sessionId) {
|
|
795
|
+
const name = basename(String(target));
|
|
796
|
+
return name.startsWith("rollout-") && name.endsWith(".jsonl") && name.toLowerCase().includes(sessionId);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* The Codex process holding a session: the one with its rollout open, which
|
|
801
|
+
* is the native binary once the session has had a message, else one started
|
|
802
|
+
* as `codex resume <id>`. Null when neither is found — which, for an idle
|
|
803
|
+
* Codex started without an id, is not proof it has stopped (see the header).
|
|
804
|
+
*
|
|
805
|
+
* It costs one command-line read per process on the machine, because Codex
|
|
806
|
+
* writes nothing that names its pid: measured at 12.7 ms over 811 processes on
|
|
807
|
+
* the machine this was written on, once per click on a Codex node. Open files
|
|
808
|
+
* are read only for processes that are Codex, so a browser holding thousands
|
|
809
|
+
* of descriptors costs nothing here.
|
|
810
|
+
*/
|
|
811
|
+
function codexHolder(sessionId, proc) {
|
|
812
|
+
let byArgs = 0;
|
|
813
|
+
let looked = 0;
|
|
814
|
+
for (const pid of proc.pids()) {
|
|
815
|
+
const cmd = proc.command(pid);
|
|
816
|
+
if (!looksLikeCodex(cmd)) continue;
|
|
817
|
+
if (++looked > MAX_CODEX_PROCESSES) break;
|
|
818
|
+
if (proc.fds(pid).some((t) => isRolloutFor(t, sessionId))) return codexAt(pid, proc);
|
|
819
|
+
if (!byArgs && cmd.toLowerCase().split(" ").includes(sessionId)) byArgs = pid;
|
|
820
|
+
}
|
|
821
|
+
return byArgs ? codexAt(byArgs, proc) : null;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** When a Codex session began, read off its id: Codex names sessions with
|
|
825
|
+
* UUIDv7, whose first 48 bits are the time in milliseconds. Null for an id
|
|
826
|
+
* of any other version, which then says nothing about when. */
|
|
827
|
+
export function codexIdTime(sessionId) {
|
|
828
|
+
const id = String(sessionId ?? "").toLowerCase();
|
|
829
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) return null;
|
|
830
|
+
return parseInt(id.replace(/-/g, "").slice(0, 12), 16);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** How far a pane's start (whole seconds, from tmux) may sit after the
|
|
834
|
+
* session it began. */
|
|
835
|
+
const PANE_CLOCK_SLACK_MS = 1_000;
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* The deck pane a Codex session began in, when the process holding its
|
|
839
|
+
* rollout is a daemon and cannot say (see the header): the one unlabelled,
|
|
840
|
+
* live deck Codex pane in the session's folder that opened before the
|
|
841
|
+
* session began. Null when there is not exactly one, and when a Codex on some
|
|
842
|
+
* other terminal could have begun it: in the same folder where /proc says
|
|
843
|
+
* where a process runs, anywhere where it cannot.
|
|
844
|
+
*/
|
|
845
|
+
function launchedCodexPane(q, deck, proc, io) {
|
|
846
|
+
const began = codexIdTime(q.sessionId);
|
|
847
|
+
if (began == null || !q.cwd) return null;
|
|
848
|
+
const panes = deck.filter((s) => !s.dead && s.agent === "codex" && OWN_KINDS.includes(s.kind)
|
|
849
|
+
&& !s.sessionId && s.cwd === q.cwd && Number.isFinite(s.created) && s.created <= began + PANE_CLOCK_SLACK_MS);
|
|
850
|
+
if (panes.length !== 1) return null;
|
|
851
|
+
const deckPids = new Set(deck.filter((s) => !s.dead).map((s) => s.panePid));
|
|
852
|
+
let looked = 0;
|
|
853
|
+
for (const pid of proc.pids()) {
|
|
854
|
+
const cmd = proc.command(pid);
|
|
855
|
+
if (!looksLikeCodex(cmd)) continue;
|
|
856
|
+
if (++looked > MAX_CODEX_PROCESSES) return null;
|
|
857
|
+
// The daemon that holds every session's rollout began none of them. Any
|
|
858
|
+
// other Codex with no terminal could have: `codex exec` run by a script or
|
|
859
|
+
// by another agent's shell begins a session of its own in its folder.
|
|
860
|
+
if (isCodexDaemon(cmd)) continue;
|
|
861
|
+
if (ancestry(proc, pid).some((c) => deckPids.has(c.pid))) continue;
|
|
862
|
+
if (io.platform === "linux") {
|
|
863
|
+
let cwd = "";
|
|
864
|
+
try { cwd = String(io.readlink(`/proc/${pid}/cwd`)); } catch { return null; }
|
|
865
|
+
if (cwd !== q.cwd) continue;
|
|
866
|
+
}
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
return panes[0];
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/** `codex app-server`: the daemon Codex 0.162+ hands every rollout to. */
|
|
873
|
+
function isCodexDaemon(cmd) {
|
|
874
|
+
return String(cmd).split(" ").includes("app-server");
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
function codexAt(pid, proc) {
|
|
878
|
+
const chain = ancestry(proc, pid);
|
|
879
|
+
return chain.length ? { pid, chain, background: false } : null;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* The tmux pane a process runs in, if any.
|
|
884
|
+
*
|
|
885
|
+
* TMUX in the process's own environment names the server; TMUX_PANE names the
|
|
886
|
+
* pane, and is believed only when that pane's process is one of this
|
|
887
|
+
* process's ancestors — a pane id is a counter, and an environment outlives
|
|
888
|
+
* the pane it was copied from. Ancestry alone catches a process started deeper
|
|
889
|
+
* in the pane; the tty catches one moved in later (reptyr), whose ancestry
|
|
890
|
+
* never passes through the pane at all.
|
|
891
|
+
*
|
|
892
|
+
* With no TMUX to go on — macOS, where the environment is out of reach, or a
|
|
893
|
+
* Linux process started outside tmux — only the user's default server is
|
|
894
|
+
* asked. A process in some other server under another name is then C, which
|
|
895
|
+
* is the honest answer when nothing says where that server is.
|
|
896
|
+
*/
|
|
897
|
+
async function hostPane(holder, proc, io) {
|
|
898
|
+
const env = proc.env(holder.pid);
|
|
899
|
+
const fromEnv = env?.TMUX ? tmuxSocketPath(env.TMUX) : "";
|
|
900
|
+
const socket = fromEnv ? { path: fromEnv } : DEFAULT_SOCKET;
|
|
901
|
+
let panes;
|
|
902
|
+
try {
|
|
903
|
+
panes = await io.listPanes(socket);
|
|
904
|
+
} catch (err) {
|
|
905
|
+
if (err instanceof TmuxNotAnswering) throw err;
|
|
906
|
+
panes = [];
|
|
907
|
+
}
|
|
908
|
+
// A pane that cannot be showing this process is not a candidate at all: a
|
|
909
|
+
// dead one, or one on another terminal than the one the process draws on
|
|
910
|
+
// (see WHY A PANE HAS TO SHOW THE PROCESS). An unknown tty on either side is
|
|
911
|
+
// no evidence against.
|
|
912
|
+
const tty = holder.tty;
|
|
913
|
+
const shows = (p) => !p.dead && (tty == null || (tty !== "" && (!p.tty || p.tty === tty)));
|
|
914
|
+
const live = (Array.isArray(panes) ? panes : []).filter(shows);
|
|
915
|
+
if (live.length === 0) return null;
|
|
916
|
+
const pids = new Set(holder.chain.map((c) => c.pid));
|
|
917
|
+
const byEnv = env?.TMUX_PANE ? live.find((p) => p.id === env.TMUX_PANE && pids.has(p.pid)) : undefined;
|
|
918
|
+
const byChain = live.find((p) => pids.has(p.pid));
|
|
919
|
+
const pane = byEnv ?? byChain ?? (tty ? live.find((p) => p.tty === tty) : undefined);
|
|
920
|
+
if (!pane) return null;
|
|
921
|
+
const socketPath = pane.socketPath || fromEnv;
|
|
922
|
+
return {
|
|
923
|
+
pane: pane.id,
|
|
924
|
+
session: pane.session,
|
|
925
|
+
socketPath,
|
|
926
|
+
socket: socketPath ? { path: socketPath } : socket,
|
|
927
|
+
};
|
|
928
|
+
}
|