Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8a8bb71a3 | ||
|
|
1a692f588e | ||
|
|
b68b098d1c | ||
|
|
03e6a159b1 | ||
|
|
29f76e7ec3 | ||
|
|
bc2d42c2c8 | ||
|
|
af8d0ef69c | ||
|
|
7eaa39a67e | ||
|
|
9faf567d41 | ||
|
|
91750d4bd5 | ||
|
|
63ac10dcc0 | ||
|
|
48e91fc1d9 | ||
|
|
3975089af3 | ||
|
|
9ad43fbd88 | ||
|
|
5e83cd3885 | ||
|
|
1172ef56f8 | ||
|
|
0996f99fbb | ||
|
|
b15033259a | ||
|
|
0feb5658ca | ||
|
|
82d588a339 | ||
|
|
1f41eacd87 | ||
|
|
a8b8530722 | ||
|
|
c3cee40f56 | ||
|
|
b7c18ab5b7 | ||
|
|
70e03b8ae7 | ||
|
|
de06cb12d1 | ||
|
|
eaa9044520 | ||
|
|
6c7d63d45e | ||
|
|
6bbfc44054 | ||
|
|
3d341f46a4 | ||
|
|
f0b762e745 | ||
|
|
771c23e261 | ||
|
|
0ff9b798af | ||
|
|
33c6cf5d20 | ||
|
|
9b9752d997 | ||
|
|
60fd71470c | ||
|
|
836402c2c4 | ||
|
|
f073742cf7 | ||
|
|
f3d7a86c16 | ||
|
|
34b867025d | ||
|
|
5d31e42db0 | ||
|
|
a6ce52d3e7 | ||
|
|
5ac27f3eec | ||
|
|
a38eab49cd | ||
|
|
9c56f7823d | ||
|
|
076f62fa1b | ||
|
|
90034d07d7 | ||
|
|
887ee7fe64 | ||
|
|
62227145dc | ||
|
|
2e65daff83 | ||
|
|
0e11012470 | ||
|
|
5b8313988f | ||
|
|
628b6e5832 | ||
|
|
aca358126d | ||
|
|
239f15437b | ||
|
|
f78b820302 | ||
|
|
d571c41fb1 | ||
|
|
f9f00bdb5e | ||
|
|
78ed6bf004 | ||
|
|
43568775e6 | ||
|
|
36f8afdaba | ||
|
|
1855d9423b | ||
|
|
7ba1e51c51 | ||
|
|
b4c87360d3 | ||
|
|
ee038ad83c | ||
|
|
f2d5af2b4c | ||
|
|
dedf56e24b | ||
|
|
71647e090d | ||
|
|
35e21dd676 | ||
|
|
3072449c94 | ||
|
|
bade1f1966 | ||
|
|
5205649889 | ||
|
|
e65b4f35e6 | ||
|
|
50a1b58d2b | ||
|
|
9e8a851a2c | ||
|
|
03a9259ae1 | ||
|
|
ba5649bcd4 | ||
|
|
c1fde8e639 | ||
|
|
1c19641280 | ||
|
|
79b9181932 | ||
|
|
0168444fda | ||
|
|
5a13073657 | ||
|
|
8f62faf130 | ||
|
|
7b4832b3e4 | ||
|
|
7dd78d9d71 | ||
|
|
06f1e5ddc8 | ||
|
|
4544379b3b | ||
|
|
fa23f8be2a | ||
|
|
bc940a3953 | ||
|
|
432faf7254 | ||
|
|
69aa5724e7 | ||
|
|
876dbca074 | ||
|
|
fe50ad0be3 | ||
|
|
ded7911d1e | ||
|
|
2797098aa5 | ||
|
|
4ecf7fa228 | ||
|
|
c041a418e0 | ||
|
|
59b92f2991 | ||
|
|
ef071ed485 | ||
|
|
683a1c218f | ||
|
|
435a56be10 | ||
|
|
5b8c73827e | ||
|
|
3c08971ff8 | ||
|
|
6bfc1b88d8 | ||
|
|
6bffc0481c | ||
|
|
f5e59283f9 | ||
|
|
8d92e577f8 | ||
|
|
ecb2e3d8f3 | ||
|
|
8e2594a274 | ||
|
|
3857fba065 | ||
|
|
28b41efa58 | ||
|
|
063e6fc076 | ||
|
|
136f11549b | ||
|
|
dd7774f9ad | ||
|
|
d6c87bbd27 | ||
|
|
3ea1e03aaf | ||
|
|
afab34608a | ||
|
|
eaf924a291 | ||
|
|
da7ffec734 | ||
|
|
1010d80b4f | ||
|
|
7d46a9d336 | ||
|
|
3e75e7509f | ||
|
|
b620e42ffa | ||
|
|
b33d6da58a | ||
|
|
d157911166 | ||
|
|
cde90a465b | ||
|
|
34c903da41 | ||
|
|
551a7f2792 | ||
|
|
331841f482 | ||
|
|
aa3730aace | ||
|
|
6234aae919 | ||
|
|
34439d18e5 | ||
|
|
0fced6ea97 | ||
|
|
79fd2dc8e4 | ||
|
|
0ae679553b | ||
|
|
2c55fe907e | ||
|
|
3d59e59e37 | ||
|
|
019118ba9d | ||
|
|
45a205b4e5 | ||
|
|
7a4d520cd0 | ||
|
|
08d7fa1985 | ||
|
|
0c6cbd0718 | ||
|
|
8b2cb49940 | ||
|
|
fb5c1bfca5 | ||
|
|
7b95856cc5 | ||
|
|
df1a493b8c | ||
|
|
3a40dae1dd | ||
|
|
a81d344fb5 | ||
|
|
16980d644d | ||
|
|
e2453fe97b | ||
|
|
b538429f6e | ||
|
|
7689a43782 | ||
|
|
950450b137 | ||
|
|
55cd59a346 | ||
|
|
209a539489 | ||
|
|
71e6cfa0a2 | ||
|
|
be9454a29b | ||
|
|
29c2701f83 | ||
|
|
f152d551d1 | ||
|
|
6844cccd18 | ||
|
|
89177651a6 | ||
|
|
ac8e0bdcbb | ||
|
|
9d6c010819 | ||
|
|
183efacc93 | ||
|
|
4a94eb9ba7 | ||
|
|
e589004926 | ||
|
|
5f373a9324 | ||
|
|
ac5f2aa3f4 | ||
|
|
2881ef5fa5 | ||
|
|
9644892a5a | ||
|
|
310a4c2489 | ||
|
|
29d8ca16b4 | ||
|
|
92e54163e0 | ||
|
|
39a91a0c7f | ||
|
|
cea199651a | ||
|
|
656ab98934 | ||
|
|
e6382ecfc0 | ||
|
|
4d6d187883 | ||
|
|
d3fc07ee28 | ||
|
|
b2de04c730 | ||
|
|
ed6f5f6856 | ||
|
|
eada647d7b | ||
|
|
233d5f25c4 | ||
|
|
cf9022ac9a | ||
|
|
87f1c9ccd4 | ||
|
|
586aafa8de | ||
|
|
d8c23210bb | ||
|
|
7c3877016b | ||
|
|
7c4ad22f9c | ||
|
|
dd7a5b9275 | ||
|
|
217c90b6a1 | ||
|
|
93642fa616 | ||
|
|
6db526dbad | ||
|
|
e6deab98a6 | ||
|
|
5e0cea6ec8 | ||
|
|
2cc6ea1cfd | ||
|
|
c5ddb77adc | ||
|
|
d2d2ba3e4a | ||
|
|
33ad314bea | ||
|
|
3f4af2aa2e | ||
|
|
cf11a253d3 | ||
|
|
17824f1847 | ||
|
|
b3d3c647cf | ||
|
|
1b3f40bba7 | ||
|
|
fc7ffe1ad8 | ||
|
|
5fb56b0889 | ||
|
|
d7198dd058 | ||
|
|
53f61ca539 | ||
|
|
a4926e49f1 | ||
|
|
2eff6dcbdd | ||
|
|
b8ccfc33d1 | ||
|
|
3be03c6896 | ||
|
|
ba36cc36d4 | ||
|
|
7aecbd29df | ||
|
|
b59145effd | ||
|
|
f12b5ac88b | ||
|
|
5206a044bb | ||
|
|
abc8598100 | ||
|
|
6ba311f38d | ||
|
|
decd263b17 | ||
|
|
82aeeaec02 | ||
|
|
ad57394618 | ||
|
|
fda1897109 | ||
|
|
eceaecf076 | ||
|
|
6f87186deb | ||
|
|
aa4217b8b1 | ||
|
|
c75d62ce04 | ||
|
|
c2e55fc210 | ||
|
|
24e51a3b8e | ||
|
|
0481db569d | ||
|
|
6d862d5323 | ||
|
|
57d5c7b1c2 | ||
|
|
9c63c41283 | ||
|
|
26487f0ec5 | ||
|
|
8da4a07a60 | ||
|
|
3a0cee6b90 | ||
|
|
5e2e9bb833 | ||
|
|
28708cfa14 | ||
|
|
c638c88739 | ||
|
|
a4511a0e48 | ||
|
|
be3436f5b3 | ||
|
|
330203c08b | ||
|
|
9d38cbf51a | ||
|
|
ecd577157b | ||
|
|
c614241c48 | ||
|
|
1def7de146 | ||
|
|
82c87f56d1 | ||
|
|
cdb3c34ae0 | ||
|
|
eb5d982c38 | ||
|
|
e39a750749 | ||
|
|
daf7330d6e | ||
|
|
41643f2b38 | ||
|
|
37ddcbe2f0 | ||
|
|
18c8b5c280 | ||
|
|
7409ad2655 | ||
|
|
a96a94fb7e | ||
|
|
24a73ecd81 | ||
|
|
312a8faa06 | ||
|
|
4fe843a94e | ||
|
|
155372f7a8 | ||
|
|
f855b5d274 | ||
|
|
ccd52583e2 | ||
|
|
2c267276c3 | ||
|
|
efb3fa112d | ||
|
|
fe1acd625e | ||
|
|
432bd5fc0a | ||
|
|
f79f530f93 | ||
|
|
48f54ec090 | ||
|
|
34f211538a | ||
|
|
0868286661 | ||
|
|
d7140c32b4 | ||
|
|
af4e3e6ed7 | ||
|
|
e86c3d1ed3 | ||
|
|
1ee566e7a1 | ||
|
|
1105d646f3 | ||
|
|
ff2f81541a | ||
|
|
02c65e988a | ||
|
|
4502bfe8a9 | ||
|
|
ce6e4cc6e6 | ||
|
|
e5417310f8 | ||
|
|
28df21f4bb | ||
|
|
5c08e29a08 | ||
|
|
7f26b4ba46 | ||
|
|
5c357d699f | ||
|
|
c2340ae88a | ||
|
|
0f5613ba46 | ||
|
|
a049c69cbb | ||
|
|
2c066eb2f0 | ||
|
|
3bfb3ddfc5 | ||
|
|
7e2b9ed8f6 | ||
|
|
7d8c188f83 | ||
|
|
f3b2080e69 | ||
|
|
a58991e6d8 | ||
|
|
3fe5d1b278 | ||
|
|
112c533ac7 | ||
|
|
e7d661158b | ||
|
|
db168cdbe5 | ||
|
|
b539780f33 | ||
|
|
40560aced1 | ||
|
|
09d3b9a3bf | ||
|
|
34cbd5015b | ||
|
|
a1d07a56e5 | ||
|
|
2accd804f9 | ||
|
|
6644962d70 | ||
|
|
1568e489eb | ||
|
|
4ee382832a | ||
|
|
1296223403 | ||
|
|
deb11bade2 | ||
|
|
bd3c368512 | ||
|
|
42147d30c0 | ||
|
|
e308e99f05 | ||
|
|
382d7dd406 | ||
|
|
f5acf19a11 | ||
|
|
3904428a4f | ||
|
|
aa8e06c162 | ||
|
|
9b28c277f0 | ||
|
|
f7a41b3fae | ||
|
|
d630e62114 | ||
|
|
b1def488c4 | ||
|
|
b8dbef6241 | ||
|
|
f01f54e614 | ||
|
|
6fa807c2c3 | ||
|
|
17bc2f02e9 | ||
|
|
354c4641a9 | ||
|
|
bb4e7943c5 | ||
|
|
03629c966e | ||
|
|
5ba729fcbb | ||
|
|
5a0018fc86 | ||
|
|
91bdaee724 | ||
|
|
56978f2cc9 | ||
|
|
9230b53ccd | ||
|
|
66c8fef97f | ||
|
|
45492a3013 | ||
|
|
fe77b5238e | ||
|
|
c30128d3f0 | ||
|
|
fc6e911888 | ||
|
|
16e44aa1d1 | ||
|
|
107e87e457 | ||
|
|
09daf0fe49 | ||
|
|
3ae22f64a4 | ||
|
|
90649fc363 | ||
|
|
f21ab39a89 | ||
|
|
0c71b753ef | ||
|
|
310f20b288 | ||
|
|
55cafc282f | ||
|
|
bb5fd5ee97 | ||
|
|
bebf0db792 | ||
|
|
e3dfbf6591 | ||
|
|
9b0d305223 | ||
|
|
aad9c248dc | ||
|
|
4c2fdd5f5a | ||
|
|
ab7e89873f | ||
|
|
c36be7bb94 | ||
|
|
51b6be3e7a | ||
|
|
0ae5ce017a | ||
|
|
ab96e74e69 | ||
|
|
d00229ee29 | ||
|
|
7d3e27fb6d | ||
|
|
c1811fd716 | ||
|
|
2d0ffb71aa | ||
|
|
d65ee4f89d | ||
|
|
e85b4f34dd | ||
|
|
bfab172608 | ||
|
|
4edb7b8f80 | ||
|
|
0b122e2c76 | ||
|
|
0720526b64 | ||
|
|
cbb1435a46 | ||
|
|
8e4606c57b |
@@ -10,7 +10,7 @@
|
||||
"name": "codeman",
|
||||
"source": "./plugins/codeman",
|
||||
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts only inside a Codeman-managed session.",
|
||||
"version": "1.35.0",
|
||||
"version": "1.41.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -55,7 +55,9 @@ npm run test:all # literally everything, environmental failures included
|
||||
|
||||
Expect `test:browser`/`test:mobile`/`test:perf` to fail where the machine cannot provide what they need; read that as "not runnable here", not as a regression. `config/test-suites.ts` holds the globs, and both configs derive from it, so the exclusions and those runners cannot drift apart.
|
||||
|
||||
If you add a test that binds a port, pick a unique one at 3150 or above (search the repo for `const PORT =` first). Never 3000.
|
||||
The browser suite also runs nightly (and on demand) in `.github/workflows/browser-suite.yml`; it is informational, not a gate.
|
||||
|
||||
If you add a test that binds a port, bind port 0 (`new WebServer(0, …)` + `server.boundPort`, or `listen({ port: 0 })` + `address().port`), or use `app.inject()` when no socket is needed; mobile tests call `createTestServer()` and read `server.boundPort`. `test/test-ports-guard.test.ts` fails a `WebServer` built on any other port and a raw `listen` on a fixed one. Never 3000.
|
||||
|
||||
Tests are tmux-safe by design: under vitest, the tmux layer becomes an in-memory mock, so tests cannot touch real sessions.
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Browser suite
|
||||
|
||||
# The per-push CI gate deliberately skips the Playwright-driven suite (config/test-suites.ts),
|
||||
# so a browser-only regression can merge green. This job runs that suite on a schedule and on
|
||||
# demand, so such a regression (the Shift+Enter keypress bug was one) is caught within a day
|
||||
# instead of by a user. It is NOT a merge gate: a red run means "look", and it never blocks a
|
||||
# push or a PR.
|
||||
#
|
||||
# Needs: chromium (installed below), tmux, and the live server the tests start themselves.
|
||||
# Not run here: test:mobile (per-machine PNG baselines), test:perf (wall-clock), and
|
||||
# codex-predictive-echo (needs a real codex binary; it also skips itself without one).
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '29 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
browser:
|
||||
name: Playwright browser suite
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install tmux
|
||||
run: |
|
||||
if ! command -v tmux >/dev/null; then
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y tmux
|
||||
fi
|
||||
|
||||
- name: Install chromium
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run the browser suite
|
||||
run: npm run test:browser -- --exclude test/codex-predictive-echo.test.ts
|
||||
@@ -219,6 +219,8 @@ jobs:
|
||||
run: npx vitest run
|
||||
working-directory: packages/xterm-zerolag-input
|
||||
|
||||
# The browser suite also runs nightly (and on demand) in .github/workflows/browser-suite.yml;
|
||||
# that job is informational and never gates a push or a PR.
|
||||
# Note: three suites are excluded from CI, each with its own local runner:
|
||||
# npm run test:browser Playwright + chromium (+ a live server, and a real
|
||||
# codex binary for codex-predictive-echo)
|
||||
|
||||
@@ -84,6 +84,23 @@ tmp/
|
||||
# added there). No trailing slash so it still matches the symlink, not just dirs.
|
||||
/public
|
||||
|
||||
# Video never goes to GitHub (docs/media-assets.md). The only tracked moving
|
||||
# images are the GIFs a public page embeds, in docs/images/; masters, promo cuts,
|
||||
# drafts and captures live in the local media library pr/media/ (ignored above).
|
||||
# The promo branch tracks its Remotion render inputs, so those stay addable.
|
||||
# A deliberate exception elsewhere takes `git add -f`.
|
||||
*.mp4
|
||||
*.webm
|
||||
*.mov
|
||||
*.m4v
|
||||
*.mkv
|
||||
*.avi
|
||||
*.gif
|
||||
!/docs/images/*.gif
|
||||
!/scripts/remotion/public/**/*.mp4
|
||||
!/scripts/remotion/public/**/*.webm
|
||||
!/scripts/remotion/public/**/*.gif
|
||||
|
||||
# Opt-in gesture overlay runtime assets: large MediaPipe wasm + model (~27 MB)
|
||||
# fetched at build/install by scripts/fetch-gesture-assets.mjs, kept out of git.
|
||||
# (The gesture bundle itself, gesture-codeman.js, IS tracked — built from
|
||||
@@ -107,7 +124,9 @@ todo.md
|
||||
@fix_plan.md
|
||||
readme-preview.mjs
|
||||
|
||||
# Uploaded images land here under each session working dir (runtime artifact)
|
||||
# Prompt uploads land here under each session working dir (runtime artifact);
|
||||
# .claude-images/ is where they landed before the move.
|
||||
.codeman-uploads/
|
||||
.claude-images/
|
||||
|
||||
# Local-LLM harness smoke-test config (real IPs/keys) — see the .example.json
|
||||
|
||||
@@ -24,8 +24,9 @@ src/web/public/settings-ui.js
|
||||
src/web/public/sw.js
|
||||
src/web/public/terminal-ui.js
|
||||
src/web/public/voice-input.js
|
||||
src/web/public/upload.html
|
||||
scripts/remotion/
|
||||
|
||||
# Hand-maintained; Prettier escapes underscores in glob paths and corrupts paragraphs.
|
||||
CLAUDE.md
|
||||
src/web/CLAUDE.md
|
||||
docs/releasing.md
|
||||
|
||||
@@ -12,6 +12,6 @@ Quick pointers:
|
||||
|
||||
- Type check: `tsc --noEmit` · Lint: `npm run lint` · Format: `npm run format:check`
|
||||
- Tests: `npm test` (the CI gate, safe to run bare) or `npm test -- test/<file>.test.ts` for one file
|
||||
- Route tests use `app.inject()`; new tests needing ports must pick a unique `const PORT =`
|
||||
- Route tests use `app.inject()`; new tests needing a socket bind port 0 (`new WebServer(0, …)` + `boundPort`); mobile tests use `createTestServer()` and read `server.boundPort`
|
||||
- Branch off `master` for all work; Conventional Commit-style messages (`fix(mobile): ...`)
|
||||
- Never commit secrets or local state from `~/.codeman/`
|
||||
|
||||
@@ -1,5 +1,153 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.41.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ### Thanks
|
||||
- @timkjr for four PRs: shells that reload from tmux's rendered history instead of replaying old full-screen repaints (#601), the full scrollback of a remote SSH session read from the remote tmux (#602) with no rows lost at the join (#609), and a phone shell Paste that inserts a multi-line block instead of running it line by line (#600).
|
||||
- @aakhter for three PRs: Codex panes that page their transcript with the wheel and touch (#527, fixes #508), new and spawned tabs that land in tab groups (#528), and a Focus section of shortcuts at the top of the vertical rail (#582).
|
||||
- @JDProfresh for three PRs: Claude Code's prompt-cache state per session (#607, step 1 of #554), the phone Attach button with camera-roll video uploads (#606, part two of #553), and an upload that no longer stalls the server on a dead network mount (#605).
|
||||
- @Randalix for clickable `~/`, relative and hard-wrapped file paths plus a folder grid for browsing a whole folder of renders (#604, closes #603).
|
||||
- @opticon454 for three PRs: a Working folder row with a Copy button in Session Options (#593), tab colour, pin and image watcher surviving a restart (#591), and Link Existing saying why it refused a case (#590).
|
||||
- @ideaCompany, a first-time contributor, for rendering local HTML files as real pages in the File Viewer (#547), and for the careful security write-up behind it.
|
||||
- @zomby1, a first-time contributor, for OSC 52 clipboard support (#611).
|
||||
- @Hugo-DDT, a first-time contributor, for two PRs: MCP server sync reading Gemini's bare `url`, OpenCode's V2 layout and `opencode.jsonc` (#599, fixes #586), and DeepSeek permission prompts that no longer offer Approve/Deny buttons that cannot work (#610, from #598).
|
||||
|
||||
**HTML files open as pages, and markdown opens rendered from the terminal (#547).** Click an `.html` path an agent printed (a test report, a coverage page, a dashboard) and the File Viewer now shows it as a real page, with its own scripts, styles, images and data files from its folder, instead of raw source. A **Page** pill switches to the source and its Edit button. The page runs in a sandbox with an opaque origin: it cannot read Codeman's cookies, use Codeman's API or read files outside its own folder. Network access is open, so a dashboard that loads Chart.js or fonts from a CDN works as it would opened from disk. Broad folders (`/`, home, `/tmp`, a drive's mount point) are refused, so put a report in a folder of its own. And a `.md` or `.markdown` path clicked in the terminal now opens the rendered markdown viewer everywhere (main terminal, tiles, split pane, touch), instead of the live log viewer that showed "streaming"; the MD pill still gives the source. Logs, `.txt`, `.json` and code keep the live log viewer.
|
||||
|
||||
**`codeman mcp`: drive Codeman from any MCP client (#615).** A stdio Model Context Protocol server with seven tools (list, start, send, wait, read, interrupt, delete), so Claude Code, Codex, Gemini CLI, Cursor or Claude Desktop can start worker sessions in any installed agent CLI, prompt them, wait for them and read what they did. It is a client of the existing HTTP API with the same guards as `codeman agent`: it refuses control characters in input, never acts on the session it runs in, and by default only touches sessions it started. Setup lines for Claude Code, JSON clients and Codex are in the README and the wiki page "Driving Codeman From An Agent".
|
||||
|
||||
**The codeman skill for every agent CLI (#613).** With **Codeman Agent Skill** on (App Settings > Agents & CLIs > All agent CLIs, still off by default), Codex, Gemini CLI, OpenCode, Antigravity, Grok Build, DeepSeek Harness and OMP sessions now get the same `codeman` skill Claude Code had, in `.agents/skills/codeman`, so an agent in any mode knows how to start and manage worker sessions. `codeman skill install --mode <cli>` installs it by hand.
|
||||
|
||||
**Tiles: move them by hand, or tear one off into its own window (#584).** With the camera gesture overlay on, pinch a tile and carry it onto another tile to swap them, onto an empty cell to move it, or carry a tab onto the grid to add it. With the new **Detach Tiles** setting (App Settings > Appearance, off by default), drag a tile's header out of the window and it pops out into its own window; drop it on another Codeman window's tiles and it moves there. Known limits: all Codeman windows in one browser share one saved tile layout, a drag between two browser profiles is not seen by the source window, and a drag-out held for more than a few seconds can be blocked as a pop-up.
|
||||
|
||||
**Focus section on the vertical rail (#582).** "Add to Focus" in a row's menu (or right-click a web tab) pins a shortcut to that tab in a small collapsible section at the top of the rail. The tab itself stays where it is.
|
||||
|
||||
**Tabs land in groups (#528).** A tab group's menu has **New session**, which starts a session straight into that group. A session an agent spawns lands right after its parent; App Settings > Appearance > Tabs > **Spawned tabs follow their parent** (off by default) keeps it moving with the parent.
|
||||
|
||||
**Folder grid and more clickable paths (#604).** Paths written as `~/...`, relative to the session folder, or broken across terminal lines are now clickable in the terminal and the Response Viewer, and folders are too: a folder opens a grid of its files (renders, screenshots, reports) that you can page through with the arrow keys.
|
||||
|
||||
**Phone Attach button and videos (#606).** On a phone the toolbar has an Attach button that opens the system file sheet directly, without raising the keyboard, and camera-roll videos (mp4, mov, webm, up to 1 GB) upload into `.codeman-uploads/` like images.
|
||||
|
||||
**OSC 52 clipboard (#611).** A program in a session that sets the clipboard with OSC 52 (Claude Code's `/copy`, a tmux yank, vim) now puts the text on your browser's clipboard, in the main terminal and in every tile. Read requests are refused, and a replayed buffer never copies.
|
||||
|
||||
**Prompt-cache readout (#607).** Claude sessions show whether their prompt cache is warm (`cache:until HH:MM`) or cold in the footer and in Session Options > Respawn, restored after a restart, with a reason when a launch will never report it. Display only, nothing changes behaviour.
|
||||
|
||||
**Faster tab switches to fullscreen Claude (#588, #583).** Switching back to a fullscreen Claude tab now loads only its current screen (a few KB) instead of replaying a 1 MB tail of old redraws (about 1.3 to 1.7 s saved per switch). The "Showing the most recent 1.0 MB" bar now appears only when there really is older history and you scroll to the top looking for it, gives a line count, and stays closed once you close it.
|
||||
|
||||
**Fixes.**
|
||||
- **Shells reload cleanly (#601).** A shell tab, tile or split pane reloads from tmux's rendered history, so a prompt no longer appears four or five times and lines no longer go missing after a resize or a full-screen program.
|
||||
- **Remote SSH sessions keep their scrollback (#602, #609).** Loading a remote session's full history reads it from the remote tmux in one bounded ssh round trip, where the local pane kept only a fraction (48 of 279 lines in one measurement, none after a reattach).
|
||||
- **Codex pages with the wheel and touch (#527).** A Codex pane on its alternate screen pages its transcript with PageUp/PageDown from the first wheel notch or swipe, in the main terminal and in tiles, and never pages into an open permission dialog.
|
||||
- **openpyxl spreadsheets preview (#612).** An `.xlsx` written by openpyxl with a cell comment, a table or a chart now opens in the File Viewer instead of failing.
|
||||
- **Phone shell Paste (#600).** A multi-line paste in a shell is inserted as one bracketed paste and waits for Enter, instead of running each line as it arrives.
|
||||
- **Restart keeps tab colour, pin and image watcher (#591).**
|
||||
- **Session Options shows the working folder (#593)**, with a Copy button and a label that says when the folder is on a remote host or mounted into a Docker container.
|
||||
- **Link Existing says why (#590)**, for example "Invalid case name format", instead of "Invalid request body".
|
||||
- **Uploads on a dead mount (#605).** A prompt upload into a workspace on a network mount that stopped answering is refused at once instead of tying up a server thread.
|
||||
- **MCP server sync (#599).** Gemini servers with a bare `url` sync as HTTP, OpenCode's V2 `mcp.servers` layout and `opencode.jsonc` are read.
|
||||
- **DeepSeek approvals (#610).** DeepSeek Harness permission prompts show "Answer in the terminal" in the Approvals Inbox, the phone NEEDS YOU strip and push notifications, instead of Approve/Deny buttons the server always refused.
|
||||
|
||||
**Fixes applied while landing.** Remote SSH and Docker tabs keep their scrollback on a tab switch (they were about to lose it with #588). No colour bleed where remote history meets the live screen (#602, #609). A bare `~` in a Docker case no longer lists the host's home folder, and shell prompts (`user@host:~/proj$`) no longer turn into broken folder links (#604). Spawned sibling tabs keep their creation order (#528). An OSC 52 copy over plain HTTP gives keyboard focus back to the terminal (#611). A refused video upload answers instead of hanging, and the zh-CN "Attach" label of the tile grid is back (#606). The Working folder row fits on phones, with zh-CN text (#593). OpenCode sync no longer stalls on a server named `servers` (#599). Moving a tile to another window no longer overwrites that window's saved layout (#584). HTML pages: a `~/` link to an `.html` file renders as a page instead of falling back to source, `/tmp` is refused even when `TMPDIR` points elsewhere, symlinks cannot get around the hidden-file and file-type rules, workspace confinement is re-checked on every request, media in a page can seek, and the service worker never caches a page (#547). Codex users of `codeman mcp`: the config now forwards the session id, so its self-protection works (#615).
|
||||
|
||||
## 1.41.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 87f1c9c: ### Thanks
|
||||
- @Randalix for `codeman agent` (#557), the session verbs (`ls`, `spawn`, `send`, `wait`, `read`, `interrupt`, `rm`) for agents in every CLI mode, and for moving every test server onto an ephemeral port (#570), which finishes #440. Thanks also for reporting and fixing git's clone errors on non-English hosts (#568, shipped as #572 with your commit).
|
||||
- @opticon454 for five PRs: MCP server sync for GitHub Copilot CLI (#581), an Apply button that saves Settings without closing them (#565), configurable toast and browser-notification display times (#564), in-document links in rendered markdown that scroll to their heading (#563), and npm-based CLI installs that work when the system npm prefix is root-owned (#562).
|
||||
- @JDProfresh for three PRs: pasted and uploaded files moving into a hidden, self-ignoring `.codeman-uploads/` folder (#574, after your #553 proposal), local echo that keeps painting on phones when the view sits above the bottom (#576), and upload failures that say why they failed (#578).
|
||||
- @aakhter for session search on the vertical tab rail (#580), built on the sidebar's existing filter instead of a second one, and for keeping alerted tabs visible during a search.
|
||||
|
||||

|
||||
|
||||
**Tile Animations (#571).** The tile grid from 1.40.0 can now open with a show. App Settings has a new **Animations** section (right after Appearance) that holds every animation setting: the Entrance Theme (moved out of Appearance), the new **Tile Animations** row, and a button that opens the animation lab. Tile styles: **CRT** (each tile switches on as a hot line in a diagonal wave, and switches off to a line and a dot), **Fly from tab** (each tile grows out of its session tab and flies back into it), **Deal** (dealt out of the Tiles button like cards), **Beam down**, **Cascade**, **Pop**, **Soft** and **None**. A styled tile plays in two beats: the frame enters in the tile style, then its screen powers on in the terminal style of your Entrance Theme. Picking a theme presets a matching tile style, and a new **Launch** theme flies the tiles out of their tabs. Off by default (the grid keeps its quick fade), per device, nothing moves under reduced motion, and the animations never cost an extra PTY resize. The terminal pane's Boot entrance style is gone; a saved Boot falls back to off.
|
||||
|
||||
**Tiles open the sessions you care about, and keep your layout.** With no grid arranged yet, the Tiles button (or `Ctrl+Shift+G`) now fills the grid with the sessions that are working first (most recently started first), then the ones waiting on you (a permission prompt or a finished turn you have not seen), then the most recently used, instead of the tabs in strip order, which opened the oldest ones. The session you are on is still always included. Once you arrange a grid (which session sits where, empty cells, the tile count, divider sizes, the focused and zoomed tile), that layout is remembered in this browser and the Tiles button brings it back exactly, however the grid was closed, and so does a reload while it was open. A session that has gone since frees its place, which the same ranking fills. A grid larger than the window opens in full with the focused tile zoomed, instead of being trimmed (and losing the rest of your layout).
|
||||
|
||||
**The wheel scrolls Claude inside a tile (#577).** In a tile or the split's second pane, a Claude session on its fullscreen renderer now scrolls its own conversation with the mouse wheel, exactly like the main terminal: the wheel goes to Claude as mouse reports, aimed at that tile's session and computed from the tile's own screen. Before, the wheel did nothing or scrolled the stale frames left over from loading the tile. Shift+wheel (scroll local history) works in every tile on Windows and Linux too; it was dead there.
|
||||
|
||||
**`codeman agent`: session verbs for every CLI (#557).** Agents in any mode (Codex, OpenCode, Gemini, Pi and the rest, not just Claude) can now drive other Codeman sessions from the command line: `codeman agent ls | spawn | send | wait | read | interrupt | rm`. It is a thin client over the existing session API: every call names the session that made it, `wait` blocks on a signal (`--until stop,exit`) or a literal output marker (`--match`), and exit codes say what happened (`0` ok, `1` error, `2` timeout, `3` exited, `4` refused). Ids shorter than 8 characters are refused, so a stray `rm 9` can never pick a session at random, and `rm` never deletes the session it runs in. See the README section "`codeman agent`" and the wiki page Driving Codeman From An Agent. This is phase 1 of #445.
|
||||
|
||||
**Settings: Apply (#565).** Next to Save, an Apply button saves the same way but keeps Settings open. Switching on MCP server sync makes its Preview and Sync usable straight away, and CLI management's add, enable and disable work without closing and reopening Settings.
|
||||
|
||||
**MCP server sync reaches GitHub Copilot CLI (#581).** With MCP server sync on (App Settings, off by default), Copilot CLI's `~/.copilot/mcp-config.json` now takes part like the agent CLIs' own files: its servers are copied to the others and theirs to it, additively, with the previous file kept as `.codeman-bak`. Copilot joins only when it is installed or already has that file, a server switched off in Copilot is never copied, and `COPILOT_HOME` is followed. Copilot is a sync target only, not a new run mode.
|
||||
|
||||
**Notifications stay up longer if you want (#564).** Settings → Notifications has a Toast display time and a Browser notification display time (1 second to 5 minutes, per device; the defaults stay 3 s and 8 s).
|
||||
|
||||
**CLI logos on tabs can be switched off (#569).** App Settings → Appearance → Tabs → **CLI Logos on Tabs** hides the agent logo on every tab surface (header strip, rails, sidebar, phone chips, the desktop home list) on this device. On by default. Tile headers, split pane headers and the Run menus keep their logos.
|
||||
|
||||
**Search sessions on the vertical rail (#580).** The vertical tab rail has a **Search sessions** box at the top: type part of a name and the rail narrows to the tabs that match (a web tab by its title), across every group, collapsed ones included, without touching your groups, their collapse or the tab order. A tab with an alert stays visible even when its name does not match, so a prompt waiting on you is never filtered away. Escape or × clears it, you can still drag a found tab into a group, and nothing is saved. The sidebar's filter box shares the same filter: a tab with an alert stays visible there too, and in the by-case tab layout a case with no match now hides.
|
||||
|
||||
**Closing a tab is instant.** Closing a session used to take half a second or more before the tab went away. The tab, tile or split pane now goes (and the next session is selected) the moment you click, while the server shuts the session down in the background, and the server side is faster too (about 450 ms down to 200-260 ms for a Claude session): it no longer sleeps fixed intervals, no longer freezes for about 70 ms per close on a synchronous tmux call, and scans for a session's subagents once instead of once per subagent. If the server refuses the close, the tab comes back where it was with the error. This also fixes a bug where a failed close still said "Session closed" while the session kept running.
|
||||
|
||||
**Fixes.**
|
||||
- **Clone errors on non-English hosts (#572, from #568).** Cloning a repository as a case now classifies a failed clone correctly whatever the host's language: a missing branch or tag is "does not exist on the remote" (400) and a missing repository is a 404, instead of a generic 422 with git's German (or any other) error text. Git runs with `LC_ALL=C` for clones and repo status, so the repo status card's error text is English on every host as well.
|
||||
- **Links within a markdown file (#563).** A link to another heading of the same document (`[Install](#installation)`) in the File Viewer or Response Viewer scrolls to that heading instead of doing nothing. Headings get GitHub-style slugs, repeated titles are numbered, and non-ASCII headings work.
|
||||
- **npm CLI installs on a root-owned prefix (#562).** Installing an npm-based CLI from Settings (DeepSeek's `dsh`, pi, ...) no longer fails with EACCES when the system node keeps its global prefix under `/usr`: the install goes to `~/.local`, where Codeman already looks for CLIs. A prefix you set yourself, or one you can write to, is left alone, including when Codeman runs under `npm run`.
|
||||
- **Uploads go to a hidden `.codeman-uploads/` folder (#574).** Images you paste or upload into a prompt are saved in `<workspace>/.codeman-uploads/` instead of `.claude-images/`. The folder ignores itself in git (it carries a `.gitignore` of `*`), stays hidden in the Files panel, and is cleaned up as before: files older than 7 days in an hourly sweep, and the folder when the last session in that workspace closes. The old `.claude-images/` folder gets nothing new and is still swept and removed during 1.41.x. An upload to a remote (SSH) session is now refused with a clear message, since the file would land on the Codeman host where the remote agent cannot read it.
|
||||
- **Typing on a phone after a tab switch (#576, fixes #575).** With local echo on (the default on touch devices), text typed while the terminal sat above the bottom was buffered but never painted, so the keyboard looked dead. The view sits there after every tab switch and after the keyboard closes. The overlay now paints whenever the prompt row is on screen, and hides only when you scroll the prompt out of view.
|
||||
- **Upload failures say why (#578).** When a prompt image upload fails, the toast shows the server's reason (for example a rate limit) instead of only "1 failed".
|
||||
- **The npm page shows the English README.** npmjs.com had been rendering the Chinese README, because npm picks the package's readme from an unsorted file match at publish time. The publish now moves `README.zh-CN.md` aside while it runs (the file and every link to it stay as they are), and the package description and homepage say what Codeman is and point at getcodeman.com.
|
||||
- **New cases ask for clickable file paths.** The CLAUDE.md generated into a new case asks the agent to report every file it created as a full absolute path, which Codeman turns into a link that opens the File Viewer, and mentions the codeman skill for starting and managing worker sessions.
|
||||
|
||||
**For contributors (#570).** Every in-process test server binds an ephemeral port, the mobile suite included, and the port guard now also refuses raw listeners on a fixed port, so two test runs on one machine never collide.
|
||||
|
||||
**Fixes applied while landing.** zh-CN translations for the two new notification display-time settings and for the new Animations section. A session whose name matches an interface word ("Lab", "New session") is no longer translated in the tab strip when the interface is in Chinese. Plus test and doc cleanups left over from review.
|
||||
|
||||
## 1.40.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- ### Thanks
|
||||
- @opticon454 for four PRs in this release: the end of Android autocorrect duplicating a line (#541), a Run dropdown that fits and scrolls on any screen (#542), Git status that copes with big folders and slow shares (#543), and a nightly browser-suite workflow plus the three stale browser tests it needed (#540). Thanks also for confirming #550 on a live install.
|
||||
- @JDProfresh, a first-time contributor, for four PRs: Respawn and Ralph back in Claude's Session Options (#550), removing the broken tunnel Upload URL page (#551), the wiki's Contributing page catching up with CONTRIBUTING.md (#552), and a remote-wake test that no longer pins its budget to the millisecond (#559).
|
||||
- @Randalix for making opencode tabs selectable and scrollable again (#555), and for the server reporting the port it really bound, which let the test suite move off fixed ports (#556).
|
||||
- @shenlvkang-collab for Default Codex model and reasoning effort settings (#546), and for the opt-in `window.CodemanHost` bridge that lets a native wrapper app pop a session or a file preview out into a window of its own (#432).
|
||||
- @aakhter for `.xlsx` spreadsheets in the File Viewer (#502), parsed entirely in the browser behind admission limits that held up to round after round of review.
|
||||
|
||||
This is the biggest visual overhaul Codeman has had: a tile grid for driving several sessions at once, a new header, CLI logos everywhere an agent is named, lineage trees, a calmer welcome screen and optional new tab layouts. The defaults are chosen so an upgrade looks familiar: the tab strip stays Classic, the header gets the Compact stats, and the Tiles button is there to try.
|
||||
|
||||
**The tile grid: up to six live sessions side by side.** Click **Tiles** in the header (or press `Ctrl+Shift+G`) and the window splits into a grid of real terminals, each one a full session you can read and type in, with its own connection. Every tile has a small header naming the session, the agent (its logo) and the model it runs (`Claude on Opus 5.5`, `DeepSeek on qwen3.8-27b`, following an in-session `/model` switch), a status dot that turns red and pulses the tile's border when that session needs you, a session menu, zoom (`⤢` or `Alt+Shift+Enter`) and remove (`×`, the session keeps running). Right-click the button for a 2 / 4 / 6 count menu (remembered per device; a hover card explains both clicks). Add sessions by `Ctrl`/`Cmd`+clicking a tab, dragging a tab onto a tile or an empty cell, "Open group as tiles" in a tab group's menu, or just Run while the grid is open. Rearrange by dragging a tile by its header (onto another tile they swap, and an empty cell can sit anywhere), with `Ctrl+Shift+Arrows`, and resize with the column and row dividers; `Alt+Shift+Arrows`, `Ctrl+Tab` and `Alt+[` / `]` move the focus, and the focused tile is the session every panel follows (files, git status, respawn, subagent windows, voice, image paste). Picking a tab that is not tiled shows it on its own and one click brings the grid back; app-driven selections never collapse it. The grid survives a reload (per device, session ids only), opens and closes with a short animation (off under reduced motion), auto-zooms the focused tile when the window gets too small, shows an Attach overlay for a session that is not attached or whose agent exited, and is fully translated into 简体中文. It was built to stay fast with six busy agents: tiles paint first and load their terminals one per frame, a tile replays its history at xterm's own pace and never reads more scrollback than it keeps, the main terminal is parked (no SSE terminal stream) while tiles own the screen, and a window resize refits each tile exactly once. Desktop only (a window at least 1180px wide); the setting is App Settings → Header & Panels → Tiles, on by default on desktop and opt-in on touch tablets. The user guide is the new [Tile Grid](https://github.com/Ark0N/Codeman/wiki/Tile-Grid) wiki page.
|
||||
|
||||
**Split view, rebuilt on the same terminal (#560).** The split's second pane is now a `TerminalTile`, the same component every tile is: its input goes through the exactly-once queue, so a dropped link can no longer lose or double a keystroke; it reconnects on its own after a drop or a server restart; it and its PTY never disagree about size; file paths are clickable and `Ctrl+V` pastes images into it; and app shortcuts, voice and image paste follow the pane you are in. Both panes now name their agent and model above them.
|
||||
|
||||
**A new header.** The header stats come in three styles (App Settings → Header & Panels → Header Stats Style, per device): **Compact**, the new default, draws WS, CPU, MEM and the plan usage windows as two pills where every reading is a ring, a label and a value; **Tiles** gives each one its own box; **As before** keeps the old readout. The icon buttons beside them take the matching shape, and hover now moves the icon, never the button.
|
||||
|
||||
**CLI logos everywhere an agent is named (#532).** The Run menus (toolbar, phone overview picker, custom endpoints, model picker), every agent tab (header strip, rail, sidebar, phone chips, the desktop home rail, Claude's tabs included), the tile and split headers and the welcome screen now show each CLI's own logo instead of a colour dot or a two-letter pill. The marks are inline SVG, follow every skin, and a CLI you added through `clis.json` gets a plain dot.
|
||||
|
||||
**Lineage trees (#544).** The lines from a tab to the tabs it spawned are now one rounded tree per spawning tab, routed through the gaps between tab rows so they never cross a tab or reach the terminal. Every family is always drawn, the selected tab's family is drawn thicker and on top, and a dashed branch now means that child is working.
|
||||
|
||||
**Tab layouts (#538, optional).** App Settings → Appearance → Tabs → **Tab Layout** adds three opt-in arrangements next to the default **Classic** strip: **By state** (a row each for Needs you, Waiting, Working and the rest, most urgent first, flippable with State Order), **By case** (one labelled box per case) and **Ledger** (an aligned grid of equal cells). By state and By case also group the vertical rail and the sidebar. Per device; phones keep their scrolling chip row.
|
||||
|
||||
**A calmer welcome screen.** One primary launcher for the first agent in your catalog (Claude Code on a stock install, the next agent if it is disabled) with its real logo, every other CLI as a slim pill under it, and Cloudflare Tunnel as a quiet link above its QR. The toolbar's "+" and case gear moved into the case picker as "New or link a case…" and "Case settings…" rows, and the duplicate instance stepper is gone (#428).
|
||||
|
||||
**Every session knows its model.** Sessions publish the model they run (`displayModel` on the session state): a custom endpoint's model id, else what the running CLI itself reports (Claude's statusLine, codex's, pi's and opencode's footers, the dsh status line), else the model its config pins (a DeepSeek route) or the one it was launched with. It is persisted, follows `/model` switches, and is stripped of control characters and capped.
|
||||
|
||||
**Idle detection for every agent.** OpenCode, Gemini, Pi and OMP turns now end: their composer bars and spinners are read so a session goes idle when the agent is done instead of spinning "working" forever, codex 0.162's new footer row no longer hides its model or its background-terminal row, and a freshly started or re-attached agent pane now announces its idle to open pages (it used to stay `busy` until a reload). A pane prompted within its first seconds is never settled idle at launch, so send-and-wait cannot resolve before the turn starts.
|
||||
|
||||
**Spreadsheets in the File Viewer (#502).** `.xlsx` files open as a read-only grid with sheet tabs, number formats, merged cells and colours, from the Files panel, attachments or a path an agent prints. They are parsed entirely in your browser in a worker (up to 10 MB) behind admission limits on everything the parser would expand. `.xls` and `.ods` stay download-only, and `file-content` now reports `type: 'spreadsheet'` for `.xlsx`.
|
||||
|
||||
**Default Codex model and reasoning effort (#546).** App Settings has a Default Codex model and a Default Codex reasoning effort, applied to new local Codex sessions (Run menu, Resume and the HTTP API) unless the launch names its own; custom endpoints, Docker and remote sessions keep their own settings.
|
||||
|
||||
**Pop-out windows for native wrapper apps (#432).** A native wrapper (for example an Android app on a foldable) can pop a session, a file preview or a web tab out into a window of its own beside the dashboard through an opt-in, experimental `window.CodemanHost` bridge. Browsers behave exactly as before.
|
||||
|
||||
**Git status for big folders and slow shares (#543).** Two per-device settings under Settings → Bottom bar set how many repositories it lists (up to 50, default 12) and how long one git command may take (5 to 120 s, now 30 s by default), and a repository git cannot read is listed with the reason and counted as `? N` in the indicator instead of silently disappearing.
|
||||
|
||||
**Behaviour change: `Ctrl+W` no longer closes a session.** It is delete-word in every shell and agent CLI, and muscle memory used to kill a session (its pane and CLI, with no confirm) mid-sentence. Close Session has no default key now; bind one in App Settings → Shortcuts if you want it.
|
||||
|
||||
**Removed: the tunnel Upload URL page (#551).** Since the response envelope change it reported "Saved: undefined" and listed nothing. Use the in-app image paste instead. `POST /api/screenshots`, `GET /api/screenshots` and `GET /api/screenshots/:name` (and their `/api/v1` aliases) still work unchanged but log a one-time deprecation warning and will be removed in a future major release.
|
||||
|
||||
**Fixes.** Android keyboards that autocorrect as you type (SwiftKey, Gboard) no longer duplicate the line in the prompt: the corrected word reaches the session exactly once, including when Enter arrives in the same keyboard transaction (#541). opencode tabs: a drag selects text again (so copy-on-select works and `Ctrl+C` copies instead of closing opencode), and the wheel and touch swipes page through opencode's conversation (#555). The Run dropdown no longer runs off the top of the screen: with many CLIs, endpoints and saved URLs it fits between the header and the toolbar, follows the on-screen keyboard and the iPhone safe areas, and scrolls (#542). Claude sessions show the Respawn and Ralph / Todo tabs and the auto-resume toggle in Session Options again, hidden since 1.33.0 (#550, fixes #549). The terminal refits when only its box changes size (a header that grows with the state rows or the lineage gutter used to leave the bottom rows clipped behind the toolbar until a tab switch). A device with any shortcut override no longer gets every App Settings save rejected while the toast still said "Settings saved". Image paste and dictation land in the session they started in. App Settings search finds Split and Tiles by what they do. The Run button family, the Help modal, the shortcut overlay leftovers and the exited-agent tab badge are translated into Chinese.
|
||||
|
||||
**For contributors.** The server reports the port it actually bound (`boundPort`), the tests that shared fixed ports bind ephemeral ones, and a static guard keeps new fixed ports out, so two test runs on one machine no longer collide (#556). A nightly (and on-demand) Playwright browser-suite workflow runs the suites the CI gate cannot, informational and never a gate (#540). The wiki's Contributing page says `npm test` is the CI gate (#552).
|
||||
|
||||
**A final review before shipping.** A last adversarially verified review of the whole release fixed these in the tile view: an image dropped on a tile uploads to that tile's session instead of navigating the browser away; a Claude session started into the grid keeps its welcome banner and transcript; a tile refresh never blanks the screen while it waits; a remote close or a reconnect no longer moves your keyboard into another session's tile; dictation and the phone keyboard's Path and Clear keys reach the focused tile or split pane; each tile caps its live-output backlog and recovers dropped output with one bounded refresh; Redraw on a tile forces the resize it reports; popping out the last tile leaves no frozen view; and "Open group as tiles" no longer pulls an open split into the grid. Also from that review: the By case layout stays one scrolling row on 600 to 767px tablets, the needs-you pulse animates opacity only, a codex session on the ultra effort shows its model, codex's launch defaults are CLI registry data instead of an id check, `npm run build` checks its dependencies before it deletes anything, and the release's new strings (case picker rows, Git status settings, toasts, tile and spreadsheet texts, the Redraw toasts) have zh-CN translations.
|
||||
|
||||
**Fixes applied while landing.** Tiles and the split's Pane B got the same two fixes the main terminal got from contributors: opencode's wheel paging and click reports (#555), and the Android keyboard handling that stops autocorrect duplicating a line (#541). Android: a word composed right before Enter in the same keyboard transaction was sent twice; it now arrives once (#541). Codex: App Settings refuses a Default Codex model the server would reject instead of failing the whole save behind a "Settings saved" toast, and the two Codex rows stack under their labels on phones (#546). Run dropdown: its height follows the on-screen keyboard and both iPhone safe areas, a long custom-endpoint label no longer adds a horizontal scrollbar, and the open menu sits above the keyboard accessory bar (#542). Git status: a lone repository git cannot read is no longer shown as clean and empty, a repeated `timeout` query parameter no longer answers 500, and the timeout field accepts any whole number of seconds (#543). Spreadsheets: cells clipped to nothing at the edge of a very large sheet no longer grow its scroll area, and the preview's fixed texts have zh-CN translations (#502). Pop-out windows: the bridge refuses to pop out without a window channel (the tab could never re-dock), the tab menu follows the host-aware default, and Close window works inside a host window (#432). Every deprecated `/api/screenshots` route now logs its warning, pinned per route (#551). Across the new tab layouts and header styles: lineage lines run between the state labels and the tabs and never through a case box, an open Tiles or Split button stays highlighted in the boxed header styles, a phone keeps the active chip in view when it changes state band, and the Tab Layout and Header Stats Style settings are translated.
|
||||
|
||||
## 1.35.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -19,16 +19,12 @@
|
||||
<a href="https://github.com/Ark0N/Codeman/commits/master"><img src="https://img.shields.io/github/commit-activity/t/Ark0N/Codeman?style=flat-square&color=1e3a5f" alt="Total commits"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
⭐ <strong>Like Codeman? <a href="https://github.com/Ark0N/Codeman">Give it a star on GitHub!</a></strong> It takes one click and helps more people find the project. ⭐
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — parallel subagent visualization" width="900">
|
||||
<img src="docs/images/tiles-crt-stats-1600-20261010.gif" alt="Codeman tile grid: six live agents (DeepSeek Harness, Claude Code, Pi, Codex, OpenCode and a shell) powering on and off with the CRT animation, with the live header strip showing CPU, memory and Claude plan usage" width="800">
|
||||
</p>
|
||||
|
||||
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, Gemini, Pi, Grok, DeepSeek Harness, or OMP inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
|
||||
@@ -50,11 +46,12 @@ The installer asks before every system change, and re-running the same line upda
|
||||
- **Truly phone-friendly** - a [touch-optimized terminal](#mobile-optimized-web-ui) with instant local echo, QR login, swipe navigation, and push notifications
|
||||
- **Runs while you sleep** - [idle detection + respawn cycling](#respawn-controller) and auto-resume when a subscription limit resets, for 24+ hour unattended runs
|
||||
- **See your agents think** - [live floating windows](#live-agent-visualization) for every subagent and teammate, with real-time transcripts
|
||||
- **Agents can drive it too** - the [codeman skill](#the-agent-skill-start-here) (for every agent CLI), [`codeman agent`](#codeman-agent--session-to-session-verbs-in-every-cli-mode) and an [MCP server](#mcp-server-codeman-mcp-drive-codeman-from-any-mcp-client) let one agent start workers in any CLI, prompt them, wait for them and collect their answers
|
||||
- **Nothing gets lost** - tmux persistence across restarts and network drops, exactly-once input delivery, full-scrollback replay
|
||||
- **Self-hosted and private** - loopback-only by default, MIT licensed, no telemetry, runs entirely on your machine
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/codeman-tour-20260724.png" alt="Codeman dashboard tour: session tabs per case, one-click Run for new agents, live plan usage in the header" width="900">
|
||||
<img src="docs/images/codeman-tour-20261010.png" alt="Codeman dashboard tour: session tabs per case, one-click Run for new agents, live plan usage in the header" width="900">
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -216,6 +213,8 @@ The most responsive AI coding agent experience on any phone. Full xterm.js termi
|
||||
|
||||
- **Keyboard accessory bar** — `/init`, `/clear`, `/compact` quick-action buttons above the virtual keyboard; destructive commands require a double-press to confirm, so you never fire one by accident; on Codex sessions the bar also shows `⇧←` / `⇧→` (Shift+Left / Shift+Right: edit the last queued message / return through the prompt stack)
|
||||
- **Dedicated Enter button** — replays the keypress through the terminal, so text buffered by local echo is flushed first rather than stranded
|
||||
- **Attach button**: the picture icon beside the mic opens the system photo and file sheet without raising the keyboard. Photos and camera-roll videos (mp4, mov, webm, up to 1 GB) upload into the session's folder and their path lands on your prompt, unsent
|
||||
- **Paste in a shell**: a multi-line paste goes in as one block and waits for your Enter, instead of running line by line as it arrives
|
||||
- **Swipe navigation & smart keyboard handling** — swipe left/right to switch sessions; toolbar and terminal shift up when the keyboard opens (`visualViewport` API)
|
||||
- **Built for phones** — safe-area insets for notch and home indicator, 44px touch targets, bottom-sheet case picker, native momentum scrolling; on a folding phone (iPhone Duo) dialogs stay clear of the hinge, and opening or closing the device is never mistaken for the keyboard
|
||||
|
||||
@@ -268,18 +267,18 @@ Hit start — Codeman spawns the CLI via a real PTY and streams it to your brows
|
||||
|
||||
### 3. Read the dashboard
|
||||
|
||||
- **Tabs (top)** — one per session. `Alt+1`-`9` to jump, `Ctrl+Tab` for next, drag to reorder (tab order syncs across your devices). Prefer a list? **App Settings → Appearance → Tabs** moves it into a left sidebar with a filter box (`Alt+B` collapses it) or a vertical rail whose rows sort by activity: blocked on you first, then longest running, then most recently quiet.
|
||||
- **Tabs (top)** — one per session. `Alt+1`-`9` to jump, `Ctrl+Tab` for next, drag to reorder (tab order syncs across your devices). Prefer a list? **App Settings → Appearance → Tabs** moves it into a left sidebar with a filter box (`Alt+B` collapses it) or a vertical rail whose rows sort by activity: blocked on you first, then longest running, then most recently quiet. The rail also has a **Search sessions** box, named **tab groups** (a group's menu starts a **New session** straight into it), and a **Focus** section of shortcuts to the tabs you keep coming back to.
|
||||
- **Terminal (center)** — a real `xterm.js` terminal; full TUIs render correctly. Type directly and press **Enter** to send. `Shift+Enter` inserts a newline.
|
||||
- **Side panels** — Respawn, Orchestrator, Cron, Subagents, Settings (toggled from the toolbar).
|
||||
|
||||
### 4. Talk to the agent
|
||||
|
||||
- **Type prompts** straight into the terminal — input is delivered exactly-once even across reconnects (a dropped link never loses or double-sends a prompt).
|
||||
- **Paste or drag-and-drop images** directly into the session.
|
||||
- **Paste, drop or attach images and videos** directly into the session. They are saved in a hidden `.codeman-uploads/` folder in the workspace (it ignores itself in git and is swept after 7 days), and the file's path lands on your prompt, unsent.
|
||||
- **Voice input** — `Ctrl+Shift+V` (Deepgram Nova-3, or this machine's Claude Code login with no API key; auto-silence stop).
|
||||
- **Attachments** — register external files/docs and preview Office/PDF inline; any file path an agent prints is clickable, in the terminal and in the chat view.
|
||||
- **Attachments** — register external files/docs and preview Office/PDF inline; any file path an agent prints is clickable, in the terminal and in the chat view, including `~/` and relative paths and paths broken across lines. An `.html` report opens as a real page, Markdown opens rendered, and a folder opens as a grid of its files.
|
||||
- **When it needs you** — the tab turns yellow (waiting for input) or red (a question is blocking). The **Approvals Inbox** _(opt-in)_ queues every pending prompt across sessions, answerable from the header bell or the phone home screen, and 🧠 **Read My Mind** _(opt-in)_ drafts your next prompt from the case's goals and recent work.
|
||||
- **Copy what you see** — `Shift+drag` selects text even while the CLI owns the mouse, right-click copies it, and Auto Copy _(opt-in)_ copies a selection the moment you release it.
|
||||
- **Copy what you see** — `Shift+drag` selects text even while the CLI owns the mouse, right-click copies it, and Auto Copy _(opt-in)_ copies a selection the moment you release it. A program that copies with OSC 52 (Claude Code's `/copy`, a tmux yank, vim) puts the text on your browser's clipboard too.
|
||||
|
||||
### 5. Make it autonomous
|
||||
|
||||
@@ -298,7 +297,7 @@ Hit start — Codeman spawns the CLI via a real PTY and streams it to your brows
|
||||
|
||||
### 7. Operate & maintain
|
||||
|
||||
- **App Settings** — model, effort, permission startup mode, theme/skin, terminal font family and weight, entrance animations, notifications, display toggles, per-CLI options, a synced custom display name, and per-device English/Simplified Chinese UI language.
|
||||
- **App Settings** — model, effort, permission startup mode, theme/skin, terminal font family and weight, entrance and tile animations (their own **Animations** section), notifications (with adjustable toast and browser-notification display times), display toggles, per-CLI options, a synced custom display name, and per-device English/Simplified Chinese UI language. **Apply** saves without closing Settings.
|
||||
- **Run it in the background** — `codeman web -d` detaches from your shell (`--status`, `--stop`); `codeman service install` makes it a systemd user unit / macOS LaunchAgent that survives reboots. Both verify the server actually answers before reporting success, and both refuse to start a second server on one data dir. See [Keep it running in the background](#quick-start---installation).
|
||||
- **Self-update** — git-clone installs update in place from **App Settings → System → Updates**.
|
||||
- **Deploy your own changes** — see [Development](#development).
|
||||
@@ -385,6 +384,21 @@ Beyond single-session respawn, the **Orchestrator** turns a high-level goal into
|
||||
|
||||
Run **20 parallel sessions** with full visibility — real-time xterm.js terminals at 60fps, per-session token and cost tracking, tab-based navigation, and one-click management.
|
||||
|
||||
### Tile Grid
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tile-grid-20261009.gif" alt="Tile grid: the Tiles button opens six live sessions side by side (DeepSeek Harness, Claude Code, Codex, a shell, OpenCode and Pi), and a second click returns to a single session" width="800">
|
||||
</p>
|
||||
|
||||
Watch and drive up to **six sessions side by side** in one window. Click **Tiles** in the header (or press `Ctrl+Shift+G`) and your sessions open as a grid of live terminals: every tile takes your keystrokes and shows its agent's logo, model and state in its header. Right-click **Tiles** to choose 2, 4 or 6 tiles, and drag a tile by its header to move it. Click **Tiles** again to return to a single session. Desktop only (a window about 1180px wide or more). Full guide: [Tile Grid](docs/wiki/Tile-Grid.md).
|
||||
|
||||
- **Opens what matters**: with no grid arranged yet, it fills the tiles with the sessions that are working first, then the ones waiting on you, then the most recently used, and always includes the one you are on.
|
||||
- **Keeps your layout**: once you arrange a grid (which session sits where, empty cells, tile count, divider sizes, the focused and zoomed tile), the Tiles button brings it back exactly, and so does a page reload while it was open.
|
||||
- **Tile animations** _(opt-in)_: **App Settings → Animations → Tile Animations** makes the grid open with a show: **CRT** (each tile switches on as a hot line, as in the GIF at the top), **Fly from tab**, **Deal**, **Beam down**, **Cascade**, **Pop** or **Soft**. Nothing moves under reduced motion.
|
||||
- **Scrolls like the main terminal**: the mouse wheel scrolls a fullscreen Claude conversation inside its tile, a Codex tile pages its transcript, and `Shift+wheel` scrolls the tile's local history.
|
||||
- **Detach Tiles** _(beta, opt-in)_: with **App Settings → Appearance → Detach Tiles** on, drag a tile's header out of the browser and it pops out into its own window; drop it on another Codeman window's tiles and it moves there.
|
||||
- **Hands-free**: with the [gesture overlay](#more-features) on, pinch a tile and carry it onto another tile to swap them, onto an empty cell to move it, or carry a tab onto the grid to add it.
|
||||
|
||||
### Persistent Sessions
|
||||
|
||||
Every session runs inside **tmux** — sessions survive server restarts, network drops, and machine sleep. Auto-recovery on startup with dual redundancy. Ghost session discovery finds orphaned tmux sessions. Managed sessions are environment-tagged so the agent won't kill its own session.
|
||||
@@ -418,7 +432,7 @@ The title is templated into the served HTML on first byte, so it's correct from
|
||||
### Tab Alerts
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tab-alerts-glow-20260815.gif" alt="Session tabs: a regular active tab beside a yellow waiting-for-input tab and a red needs-decision tab, both with a breathing glow" width="900">
|
||||
<a href="docs/images/codeman-tab-states-20261010.png"><img src="docs/images/codeman-tab-states-20261010.gif" alt="Tab states, annotated: a working tab with a spinning green ring, a red tab blocked on the agent's question shown below it, and a yellow tab whose turn is done, both alert tabs breathing" width="900"></a>
|
||||
</p>
|
||||
|
||||
Every tab tells you its state at a glance. A running session keeps its green status dot. When a session stops and waits for input, its tab turns **yellow**: steady ring, tinted background, yellow dot, with a slow breathing glow on top. When a permission prompt or question is **blocking** the agent, the tab turns **red** with a faster pulse. The base tint never blinks off, so even a split-second glance (or a screenshot) reads the true state; the ring stays visible while the tab is selected, and a page reload re-arms pending alerts from the server, so a blocked session can never hide behind a fresh-looking tab.
|
||||
@@ -460,10 +474,15 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
|
||||
- **Gesture control** _(opt-in)_ — a MediaPipe hand-tracking overlay to grab/drag session windows and pinch buttons, hands-free. Enable with `CODEMAN_GESTURE=1` + App Settings → Terminal & Input
|
||||
- **Multi-monitor span** _(macOS)_ — one click opens a browser window maximized across all displays, so floating agent/gesture panels can cross the physical seam
|
||||
- **File Viewer button** _(opt-in)_ — a header button that toggles the built-in file browser panel with one tap; enable under App Settings → Header & Panels → Header buttons
|
||||
- **HTML reports open as pages**: click an `.html` path an agent printed (a test report, a coverage page, a dashboard) and the File Viewer shows it as a real page, with the scripts, styles, images and data files from its folder; the **Page** pill switches to the source and its Edit button. The page runs sandboxed with an opaque origin, so it cannot read Codeman's cookies, call Codeman's API or read files outside its own folder. Network access stays open, so a dashboard that loads Chart.js or fonts from a CDN works as it would from disk. Broad folders (`/`, your home, `/tmp`) are refused, so give a report a folder of its own. A `.md` path clicked in the terminal opens rendered too
|
||||
- **Clickable paths and the folder grid**: paths written as `~/…`, relative to the session folder, or broken across terminal lines are clickable in the terminal and the Response Viewer, and so are folders: a folder opens a grid of its files (renders, screenshots, reports) that you page through with the arrow keys
|
||||
- **OSC 52 clipboard**: a program in a session that sets the clipboard with OSC 52 (Claude Code's `/copy`, a tmux yank, vim) puts the text on your browser's clipboard, in the main terminal and in every tile. Clipboard read requests are refused, and replaying a buffer never copies
|
||||
- **MCP server sync** _(opt-in)_: copies the user-level MCP servers each installed CLI has (Claude, Codex, Gemini, OpenCode, Antigravity, and GitHub Copilot CLI) into the others' own config files. Additive only, a server you switched off is never copied, **Preview** shows the changes first, and the previous file is kept as `.codeman-bak`. App Settings → Agents & CLIs; admin only in multi-user mode
|
||||
- **CJK / IME input** — full composition support for Chinese / Japanese / Korean, with Ctrl- and Alt-modified navigation keys passed through to the CLI
|
||||
- **Plan usage in the header** — live Claude subscription usage (the 5-hour and weekly windows) from a statusline exporter Codeman hands to `claude` at spawn and never writes into your settings files, plus Codex limits from its own app-server; per device, on for desktops and off for phones
|
||||
- **Session list, your way** — the header strip, a left sidebar with a filter box, or a vertical rail whose detailed rows carry created and state stamps and sort by activity; the phone home screen and the desktop home rail use the same order
|
||||
- **Terminal looks** — seven skins, four of them light, per-device font family and weight (the bundled JetBrains Mono covers weights 100 to 800), and opt-in entrance animations for tabs, agent windows, the terminal pane and connection lines
|
||||
- **Prompt-cache readout**: each Claude session shows whether its prompt cache is warm (`cache:until HH:MM`) or cold, in the footer (when you have no statusline of your own) and in Session Options → Respawn, with the cost of a re-cache and a note after a compaction. Display only; it survives a restart
|
||||
- **Session list, your way** — the header strip, a left sidebar with a filter box, or a vertical rail whose detailed rows carry created and state stamps and sort by activity; the phone home screen and the desktop home rail use the same order. On the rail, **Search sessions** narrows the list to the tabs that match, across every group, and a tab with an alert stays visible even when its name does not. Named **tab groups** collapse, reorder and take drags; a group's menu has **New session**, and a worker an agent spawns lands right after its parent (**Spawned tabs follow their parent**, off by default, keeps it moving with the parent). **Add to Focus** pins a shortcut to any tab in a section at the top of the rail, and **CLI Logos on Tabs** can be switched off per device
|
||||
- **Terminal looks** — seven skins, four of them light, per-device font family and weight (the bundled JetBrains Mono covers weights 100 to 800), and opt-in animations for tabs, agent windows, the terminal pane, connection lines and [tile-grid tiles](#tile-grid), all in App Settings → Animations (with a lab to try them)
|
||||
- **OS notifications & hostname-aware titles** — desktop alerts and tab titles are prefixed `codeman:<host>` so multi-host setups stay unambiguous
|
||||
|
||||
---
|
||||
@@ -495,6 +514,7 @@ Point a case at another machine and run the agent **there**, over SSH, with the
|
||||
- **Shared sessions**: several clients can attach the same remote session at different window sizes without clamping each other; discovery shows a "shared" badge with the client count.
|
||||
- **Injection-safe**: every ssh command line flows through a single shell-escaping builder, and host/path/identity fields are schema-guarded.
|
||||
- **Files too**: previews, downloads and text reads in a remote case go over the same ssh connection (one `realpath` + `stat` probe, then a streamed `cat`, `Range` seeking included), so a clicked path opens the file on the machine the agent is on. Nothing is copied to the Codeman host; editing and Office previews answer a clear 400 instead of a misleading 404.
|
||||
- **Full scrollback**: loading a remote session's history reads it from the remote tmux in one bounded ssh round trip, so a session keeps its whole scrollback after a reattach or a tab switch, with no rows lost where the history meets the live screen.
|
||||
|
||||
Set it up under **New Case → Remote** (host, user, identity file, optional jump host). Full design: [`docs/remote-sessions.md`](docs/remote-sessions.md).
|
||||
|
||||
@@ -665,7 +685,7 @@ These run for **every** request — before auth, even on the default no-password
|
||||
### Input, files & headers
|
||||
|
||||
- **Schema-validated inputs** — every API body is checked with Zod v4 schemas; a `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `ANTIGRAVITY_*` / `GEMINI_*` / `GOOGLE_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `OMP_*` env-prefix allowlist gates which settings each CLI can receive, and the keys that could redirect a CLI's traffic (base URLs, config homes) are clamped for non-admin users
|
||||
- **Path containment** — file routes `realpath` before boundary checks (no TOCTOU); `..`, absolute paths, and symlinks resolving outside the working dir are rejected. Caps: 10 MB text preview / 2 GB raw & download (`CODEMAN_MAX_DOWNLOAD_BYTES`; bodies stream and answer `Range` requests, so the cap is a sanity bound rather than memory protection); `/api/download` blocklists sensitive paths (`.env`, `*credentials*`, `~/.ssh/`, `.aws/credentials`). SVG/HTML is served `octet-stream` + `nosniff` + attachment so it downloads rather than executes
|
||||
- **Path containment** — file routes `realpath` before boundary checks (no TOCTOU); `..`, absolute paths, and symlinks resolving outside the working dir are rejected. Caps: 10 MB text preview / 2 GB raw & download (`CODEMAN_MAX_DOWNLOAD_BYTES`; bodies stream and answer `Range` requests, so the cap is a sanity bound rather than memory protection); `/api/download` blocklists sensitive paths (`.env`, `*credentials*`, `~/.ssh/`, `.aws/credentials`). SVG/HTML is served `octet-stream` + `nosniff` + attachment so it downloads rather than executes. The one place HTML renders is the File Viewer's page view: a separate `/html-view/<capability>/` address scoped to the file's own folder, served under `Content-Security-Policy: sandbox` without `allow-same-origin`, so the page has an opaque origin and can never read Codeman's cookies or drive its API; hidden folders and broad roots (`/`, home, `/tmp`) are refused, and the capabilities are revoked on logout
|
||||
- **Security headers** — `Content-Security-Policy` (`default-src 'self'`, every exception enumerated), `X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, HSTS over HTTPS, and CORS reflected **only** for `localhost` / `127.0.0.1` / `::1`
|
||||
|
||||
### Supply chain & isolation
|
||||
@@ -699,7 +719,7 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t
|
||||
|
||||
| Shortcut | Action |
|
||||
| ------------------------------- | ------------------------------------------------------------- |
|
||||
| `Ctrl/Cmd+W` | Kill active session |
|
||||
| `Ctrl+W` | Not a Codeman shortcut: it reaches the terminal (delete the previous word). **Close Session** has no default key and can be bound in App Settings → Shortcuts |
|
||||
| `Ctrl/Cmd/Option+K` | Find open session or start a new one |
|
||||
| `Ctrl/Cmd+Tab` | Next session |
|
||||
| `Alt/Option+[` / `Alt/Option+]` | Previous / next session |
|
||||
@@ -712,6 +732,10 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t
|
||||
| `Ctrl/Cmd+L` | Clear terminal |
|
||||
| `Ctrl+Shift+R` | Restore terminal size |
|
||||
| `Ctrl+Shift+V` | Toggle voice input |
|
||||
| `Ctrl+Shift+G` | Open or close the tile grid |
|
||||
| `Alt+Shift+Arrows` | Focus the tile to the left, right, above or below |
|
||||
| `Ctrl+Shift+Arrows` | Move the focused tile one place (into an empty cell, or swap) |
|
||||
| `Alt+Shift+Enter` | Zoom the focused tile, or restore the grid |
|
||||
| `Ctrl/Cmd +` / `-` | Font size |
|
||||
| `Ctrl/Cmd+?` | Keyboard help |
|
||||
| `Shift+Enter` | Insert newline (sent to terminal) |
|
||||
@@ -729,19 +753,23 @@ For AI agents and automation that control Codeman without a browser: an agent th
|
||||
|
||||
### The agent skill (start here)
|
||||
|
||||
Everything in this section also ships as a **Claude Code skill** in [`skills/codeman`](skills/codeman/SKILL.md). Install it once and you never paste API docs into a prompt again. You ask for what you want in plain English, and the agent already sitting inside a Codeman session loads the recipes and drives the API itself.
|
||||
Everything in this section also ships as an **agent skill**, [`skills/codeman`](skills/codeman/SKILL.md), in the `SKILL.md` format Claude Code, Codex, Gemini CLI, OpenCode, Grok, OMP and most other agent CLIs read. Install it once and you never paste API docs into a prompt again. You ask for what you want in plain English, and the agent already sitting inside a Codeman session loads the recipes and drives the API itself.
|
||||
|
||||
<p align="center">
|
||||
<a href="docs/images/codeman-skill-crt-20261010.png"><img src="docs/images/codeman-skill-crt-20261010.gif" alt="A real codeman skill run: one short prompt typed into Claude Code, the tile grid powering on, then a DeepSeek Harness worker on a local qwen model and a Claude Code worker powering on as new tiles, with lineage lines from the lead to both" width="900"></a>
|
||||
</p>
|
||||
|
||||
#### Step 1: install it
|
||||
|
||||
| How | Command | Scope |
|
||||
| -------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | Global, works for any skills-aware agent |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | Global, for any skills-aware agent ([skills.sh](https://skills.sh)); the way to give it to pi |
|
||||
| Claude Code plugin | `/plugin marketplace add Ark0N/Codeman` then `/plugin install codeman@codeman` | Global, through Claude Code's plugin manager; `/plugin update codeman` follows releases. Pick this OR a `codeman skill install`, not both: a Claude Code with both lists the skill twice (`codeman` and `codeman:codeman`) |
|
||||
| Bundled CLI | `codeman skill install` | Global (`~/.claude/skills/codeman`), for npm installs that never cloned the repo |
|
||||
| Bundled CLI | `codeman skill install --case <name>` | One case only |
|
||||
| Web UI | App Settings → Agents & CLIs → Claude → **Agent Skill** | Auto-injects into each case on Claude session create (`agentSkillEnabled`, SYNCED, default off) |
|
||||
| Bundled CLI | `codeman skill install --case <name> [--mode <mode>]` | One case only; `--mode codex` (or any other run mode) writes it where that CLI looks for skills |
|
||||
| Web UI | App Settings → Agents & CLIs → All agent CLIs → **Codeman Agent Skill** | Auto-injects into each case on session create, where that session's CLI looks: `.claude/skills/` for Claude Code, `.agents/skills/` for Codex, Gemini CLI, OpenCode, Antigravity, Grok, DeepSeek and OMP; not pi, whose project skills trigger a trust prompt (`agentSkillEnabled`, SYNCED, default off) |
|
||||
|
||||
`codeman skill uninstall [--case <name>]` reverses the CLI installs, and never touches a `skills/codeman` you wrote yourself.
|
||||
`codeman skill uninstall [--case <name>]` reverses the CLI installs (with `--case`, every Codeman-managed copy in that case, whichever CLI's directory it sits in), and never touches a `skills/codeman` you wrote yourself.
|
||||
|
||||
#### Step 2: ask for things
|
||||
|
||||
@@ -794,7 +822,7 @@ Every recipe in there was verified against a live server, and the comments recor
|
||||
- **It self-gates.** Outside a Codeman session (`CODEMAN_MUX` unset) the skill refuses to act and does not guess an API URL, so a global install costs an unrelated Claude Code session nothing.
|
||||
- **It is deliberately conservative.** Unprompted, it may only spawn sessions, prompt them, and delete ones **it created in that same conversation, by exact id**, through a fail-closed guard that refuses to delete the agent's own session. Deleting a case (which erases a real directory of your code), bulk kills, respawn/ralph/cron/orchestrator changes and settings writes all require you to ask, naming the target.
|
||||
|
||||
⚠️ Turning `agentSkillEnabled` back off **does not remove already-injected copies** (a create-time sweep would yank the skill out from under other live sessions sharing that `.claude/` dir). Remove them per case with `codeman skill uninstall --case <name>`.
|
||||
⚠️ Turning `agentSkillEnabled` back off **does not remove already-injected copies** (a create-time sweep would yank the skill out from under other live sessions sharing that workspace). Remove them per case with `codeman skill uninstall --case <name>`.
|
||||
|
||||
---
|
||||
|
||||
@@ -936,6 +964,74 @@ codeman tui --list # numbered session list (plain tex
|
||||
codeman tui 3 # attach to session 3 of that list
|
||||
```
|
||||
|
||||
### `codeman agent` — session-to-session verbs in every CLI mode
|
||||
|
||||
The skill above drives the API with `curl` and `jq` from a preamble Codeman seeds per session. Where it does not reach (a `pi` or `shell` session, a machine without `jq`), the same environment is still there (`CODEMAN_MUX=1`, `CODEMAN_SESSION_ID`, `CODEMAN_API_URL` are exported into every pane), so `codeman agent` packages the same verbs as commands. It is a thin client over the endpoints listed under [API](#api): no new route, no new transport, auth and ownership unchanged. One line in a case's `AGENTS.md` is enough: *"other sessions: `codeman agent --help`"*.
|
||||
|
||||
```bash
|
||||
codeman agent ls # sessions; * marks this one
|
||||
SID=$(codeman agent spawn scratch-1 --mode claude) # quick-start + wait for the composer where the mode has a ready mark
|
||||
codeman agent send "$SID" 'review src/, then say DONE' --until stop,exit --timeout 300000 # --wait = default signal set
|
||||
codeman agent read "$SID" # last answer (as the server reads it for that mode)
|
||||
codeman agent read "$SID" --tail 3000 # terminal tail, ANSI stripped (every mode)
|
||||
codeman agent send "$SID" 'run the tests, then print WORKDONE followed by _4711' # hook-less modes (opencode, pi, …): ask for the marker in halves …
|
||||
codeman agent wait "$SID" --match WORKDONE_4711 # … and wait on the joined form, which the prompt's echo never contains
|
||||
codeman agent interrupt "$SID" # a bare ESC, conversation intact
|
||||
codeman agent rm "$SID" # any session except this one
|
||||
```
|
||||
|
||||
Rules the commands enforce rather than document: they refuse outside a Codeman session and never guess a URL; `send` transmits printable text plus Enter only (a control byte such as `Ctrl+C` is `app_exit` in opencode — ESC exists solely as `interrupt`, which never appends Enter); `rm` refuses an empty id, an unprovable self id and a prefix match in either direction. Ids may be the 8-character prefixes `ls` prints (resolved through the list; an ambiguous prefix refuses, anything shorter than 8 characters refuses on every verb). A prompt that starts with `-` goes after `--` (`send "$SID" -- "- fix the bug"`). The echo of the prompt you sent is output too: a `--match` marker that appears verbatim in the prompt matches at once, before the worker has done anything, so the prompt asks for it in halves. A remote session whose host is asleep answers a fire-and-forget `send` with `buffered` (Codeman wakes the host and types the prompt once the pane is back) or `dropped` (over the wake buffer's cap, nothing will be typed: exit `1`). Exit codes: `0` delivered/matched/signal, `1` error, `2` timeout, `3` the worker exited or the wait ended without an answer (`delivered:false`, `ended:true`), `4` refused. `spawn` prints the id alone on stdout (prose goes to stderr), so `SID=$(…)` captures exactly the id. `--json` prints the envelope's `data` for every verb. `--until stop` on a mode without hook signals is the server's 400, passed through — the marker path (`--match`) is the answer there, exactly as for the skill.
|
||||
|
||||
### MCP server (`codeman mcp`): drive Codeman from any MCP client
|
||||
|
||||
`codeman mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server on stdio, so any MCP client (Claude Code, Claude Desktop, Codex, Gemini CLI, Cursor, ...) can start Codeman sessions in any installed agent CLI, prompt them, wait for them, read their answers and clean up, from inside Codeman or from outside it. Like `codeman agent`, it is a client of the HTTP API: no new route, auth and ownership unchanged.
|
||||
|
||||
```bash
|
||||
# Claude Code
|
||||
claude mcp add codeman -e CODEMAN_API_URL=https://127.0.0.1:3000 -- codeman mcp
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"codeman": {
|
||||
"command": "codeman",
|
||||
"args": ["mcp"],
|
||||
"env": { "CODEMAN_API_URL": "https://127.0.0.1:3000" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
# Codex (~/.codex/config.toml): raise the 60 s default tool timeout for long waits
|
||||
[mcp_servers.codeman]
|
||||
command = "codeman"
|
||||
args = ["mcp"]
|
||||
env = { CODEMAN_API_URL = "https://127.0.0.1:3000" }
|
||||
env_vars = ["CODEMAN_MUX", "CODEMAN_SESSION_ID"] # Codex passes MCP servers a minimal env; these let it know the Codeman session it runs in
|
||||
tool_timeout_sec = 120
|
||||
```
|
||||
|
||||
The JSON form is what Claude Desktop, Cursor and Gemini CLI take. Add `"CODEMAN_PASSWORD"` to `env` when the server has a password (or let it read the data dir's `.env`). Without the `codeman` command on PATH (a git checkout run without the installer), use `node /path/to/Codeman/dist/index.js mcp`.
|
||||
|
||||
| Tool | Does |
|
||||
| ---- | ---- |
|
||||
| `list_sessions` | Every session you can see, with its run mode, status, folder, and whether these tools may prompt it |
|
||||
| `start_session` | A new worker in a case (a fresh scratch folder, or an existing case) in any installed CLI; waits until it can take a prompt |
|
||||
| `send_prompt` | Types a one-line prompt and presses Enter; optionally waits for the end of the turn |
|
||||
| `wait_for_session` | Waits for a signal (`stop`, `blocked`, `idle`, `working`, `exit`) or a literal marker in the output |
|
||||
| `read_output` | The last answer, the whole conversation, or the last bytes of the terminal |
|
||||
| `interrupt_session` | One Escape: stops the current turn, keeps the conversation |
|
||||
| `delete_session` | Closes a worker (its case folder stays) |
|
||||
|
||||
Rules the server enforces rather than documents:
|
||||
|
||||
- **It never guesses a server.** The URL comes from `CODEMAN_API_URL` or `--url`; without one it still starts and lists its tools, and every call says how to configure it.
|
||||
- **Only its own sessions.** Prompting, interrupting and deleting are limited to sessions this server started (and, run inside a Codeman session, that session's own workers). Listing, reading and waiting work on everything. `codeman mcp --allow-any-session` lifts the limit, for a user who wants an assistant to drive their existing tabs. It never acts on the session it runs in.
|
||||
- **Waits fit the client.** A wait defaults to 45 s (Codex cuts MCP tools off at 60 s by default) and is capped at 600 s; `timed_out` / `still_working` means call again.
|
||||
- **Both protocol eras.** It answers the 2026-07-28 revision (per-request `_meta`, `server/discover`) and the `initialize` handshake of 2024-11-05 to 2025-11-25.
|
||||
|
||||
### Hooks (events flowing _back_ to Codeman)
|
||||
|
||||
Codeman registers Claude Code hooks that `POST /api/hook-event` (`permission_prompt`, `idle_prompt`, `stop`, `task_completed`, …) so the dashboard reacts in real time. This endpoint is auth-exempt on loopback but, under a managed tunnel, requires the `X-Codeman-Hook-Secret` header (read it from `$CODEMAN_HOOK_SECRET_FILE`). You normally don't call this by hand — Codeman wires it up — but it's how the autonomy layers "see" what the agent is doing.
|
||||
|
||||
@@ -24,11 +24,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
⭐ <strong>喜欢 Codeman?<a href="https://github.com/Ark0N/Codeman">在 GitHub 上给它点个 Star 吧!</a></strong>只需轻点一下,就能帮助更多人发现这个项目。⭐
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — 并行子智能体可视化" width="900">
|
||||
<img src="docs/images/tiles-crt-stats-1600-20261010.gif" alt="Codeman 平铺视图:六个实时智能体(DeepSeek Harness、Claude Code、Pi、Codex、OpenCode 和一个 shell)以 CRT 动画开启与关闭,顶部实时显示 CPU、内存和 Claude 套餐用量" width="800">
|
||||
</p>
|
||||
|
||||
> 本文档由英文版 [`README.md`](README.md) 翻译而来。如有出入,以英文版为准。
|
||||
@@ -52,11 +48,12 @@ codeman web
|
||||
- **真正的手机友好**:[触控优化的终端](#移动端优化的-web-ui),即时本地回显、二维码登录、滑动导航与推送通知
|
||||
- **睡觉时也在跑**:[空闲检测 + 重生循环](#重生控制器respawn-controller),订阅限额重置后自动续跑,支持 24 小时以上的无人值守运行
|
||||
- **看见智能体在想什么**:每个子智能体和团队成员都有[实时浮动窗口](#实时智能体可视化),附带实时活动记录
|
||||
- **智能体也能驱动它**:[codeman 技能](#智能体技能从这里开始)(适用于所有智能体 CLI)、[`codeman agent`](#codeman-agent每种-cli-模式都能用的会话间命令) 和一个 [MCP 服务器](#mcp-服务器codeman-mcp从任意-mcp-客户端驱动-codeman),让一个智能体在任意 CLI 里拉起工作会话、给它们发提示、等它们完成并收回答案
|
||||
- **什么都不会丢**:tmux 让会话挺过重启和断网,输入精确一次送达,完整的回滚缓冲区回放
|
||||
- **自托管、私有**:默认仅环回、MIT 许可、无遥测,完全运行在你自己的机器上
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/codeman-tour-20260724.png" alt="Codeman 仪表盘导览:按项目分组的会话标签页、一键 Run 启动新智能体、页头实时用量" width="900">
|
||||
<img src="docs/images/codeman-tour-20261010.png" alt="Codeman 仪表盘导览:按项目分组的会话标签页、一键 Run 启动新智能体、页头实时用量" width="900">
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -67,12 +64,13 @@ codeman web
|
||||
curl -fsSL https://getcodeman.com/install | bash
|
||||
```
|
||||
|
||||
该脚本会在缺失时自动安装 Node.js、tmux 和一套构建工具链(node-pty 没有 Linux 预编译包,需要从源码编译),把 Codeman 克隆到 `~/.codeman/app` 并完成构建。几点须知:
|
||||
该脚本会在缺失时自动安装 Node.js、tmux 和一套构建工具链(node-pty 没有 Linux 预编译包,需要从源码编译),把 Codeman 克隆到 `~/.codeman/app` 并完成构建。它会先看看机器上已有什么,最多问三个问题,然后无人值守地完成所有工作,最后给出访问 URL 和一个供手机扫描的二维码。几点须知:
|
||||
|
||||
- **先询问,后改动。** 所有系统级改动(安装软件包、下载 AI CLI)都会先征求确认;结束时的菜单可选择:直接在本终端运行、安装为后台服务(systemd/launchd,开机自启),或暂不启动。不选就不会有任何后台进程。
|
||||
- **怎么访问,由你决定。** 安装器提供三种到达仪表盘的方式:**Tailscale**(环回绑定,由 `tailscale serve` 代理,得到带真实证书的 `https://<机器名>.<tailnet>.ts.net`,用你的 tailnet 当登录,无需密码)、**局域网内任意设备**(`0.0.0.0`,会提示设置一个强烈推荐的密码),或**仅本机**(`127.0.0.1`,最安全)。绑定网络却跳过密码需要显式确认,并以醒目警告收尾。高亮的默认项反映机器上已有的状态(已在用 Tailscale 时默认 Tailscale,重跑时沿用现有绑定),直接回车绝不会引入新软件。手动运行的 `codeman web` 仍默认仅环回。
|
||||
- **重跑即更新。** 再次运行同一条命令即可原地更新已完成的安装:`~/.codeman/app` 中的本地改动会被 stash(绝不丢弃),运行中的服务会自动重启并校验。若首次安装中途失败,重跑会继续完成完整的安装流程。也可以使用 `install.sh update` 与 `install.sh uninstall`。
|
||||
- **CI / 无终端环境:** 没有终端时,涉及系统改动的步骤会带着说明中止,而不是静默执行;在自动化场景设置 `CODEMAN_NONINTERACTIVE=1` 即可批准这些步骤。
|
||||
- **三个问题,全部在开头问完。** 仪表盘怎么访问、(可选)这台机器在你的 tailnet 里叫什么,以及是否把 Codeman 作为后台服务运行(systemd/launchd,开机自启;直接回车即为「是」)。所有需要你出面的事,包括对所有缺失软件包的一次性同意、一次 sudo 密码和 Tailscale 登录,都在构建之前完成,所以编译期间你可以走开。
|
||||
- **怎么访问,由你决定。** 安装器提供三种到达仪表盘的方式:**Tailscale**(环回绑定,由 `tailscale serve` 代理,得到带真实证书的 `https://<机器名>.<tailnet>.ts.net`,用你的 tailnet 当登录,无需密码)、**局域网内任意设备**(`0.0.0.0`,会提示设置一个强烈推荐的密码),或**仅本机**(`127.0.0.1`,最安全)。绑定网络却跳过密码需要显式确认,并以醒目警告收尾。高亮的默认项反映机器上已有的状态(已在用 Tailscale 时默认 Tailscale,重跑时沿用现有绑定),直接回车绝不会引入新软件。如果你节点上的 `:443` 已被别的应用占用,Codeman 会改用 `https://<机器名>.<tailnet>.ts.net/codeman` 或第二个端口,而不是把它替换掉。手动运行的 `codeman web` 仍默认仅环回。
|
||||
- **名字由你来定。** 默认情况下,URL 用的是这台机器在 tailnet 里现有的名字。第二个问题答「是」会把机器改名为 `codeman-<hostname>`(这也会改掉它在 SSH 里的名字,所以默认是「否」);之后也可以用 `install.sh name` 来改。
|
||||
- **重跑即更新。** 再次运行同一条命令即可原地更新已完成的安装:`~/.codeman/app` 中的本地改动会被 stash(绝不丢弃),运行中的服务会自动重启并校验。若首次安装中途失败,重跑会继续完成完整的安装流程。`install.sh status` 会再次打印 URL 和二维码;另外还有 `install.sh update`、`install.sh tailscale` 和 `install.sh uninstall`。
|
||||
- **给急性子的参数。** `curl -fsSL https://getcodeman.com/install | bash -s -- --tailscale --service` 直接在命令行上回答这些问题(还有 `--lan`、`--local`、`--run`、`--no-start`、`--name <n>`、`--port <n>`、`--yes`)。**CI / 无终端环境:** 没有终端时,涉及系统改动的步骤会带着说明中止,而不是静默执行;在自动化场景设置 `CODEMAN_NONINTERACTIVE=1` 即可批准这些步骤。
|
||||
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli)、[Pi](https://pi.dev)、[Grok Build](https://github.com/xai-org/grok-build)、[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 或 [OMP](https://github.com/can1357/oh-my-pi)(任意组合均可;自 Google 面向消费者停售后,Gemini CLI 仅限企业版,Antigravity 是其继任者)。安装器会自动检测这九个中已安装的任意一个;若一个都没有,会给出一个菜单让你安装其中任意一个(DeepSeek 除外,它的 npm 包只装一个启动器,没有可运行的 profile),也可以选择跳过、稍后自行安装。安装完成后:
|
||||
|
||||
@@ -217,6 +215,8 @@ Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.
|
||||
|
||||
- **键盘配件栏** —— 在虚拟键盘上方提供 `/init`、`/clear`、`/compact` 快捷按钮;破坏性命令需双击确认,绝不误触;在 Codex 会话上还会显示 `⇧←` / `⇧→`(Shift+Left / Shift+Right:编辑上一条排队的消息 / 在提示栈里回退)
|
||||
- **独立的 Enter 按钮** —— 以按键方式回放,先冲刷本地回显缓冲的文本,不会让内容滞留在屏幕上
|
||||
- **附件按钮**:麦克风旁边的图片图标会直接打开系统的照片与文件面板,不会弹出键盘。照片和相册里的视频(mp4、mov、webm,最大 1 GB)会上传到会话所在的文件夹,文件路径落在你的提示里,但不会自动发送
|
||||
- **在 shell 里粘贴**:多行粘贴会作为一整块插入并等你按 Enter,而不是一边到达一边逐行执行
|
||||
- **滑动导航与智能键盘处理** —— 左右滑动切换会话;键盘弹出时工具栏与终端整体上移(`visualViewport` API)
|
||||
- **为手机而生** —— 刘海与 Home 指示条的安全区适配、44px 触控目标、底部抽屉式 case 选择器、原生惯性滚动;折叠屏手机(iPhone Duo)上对话框会避开铰链,开合设备也绝不会被误判成键盘弹出
|
||||
|
||||
@@ -225,7 +225,7 @@ codeman web --https
|
||||
# 在手机上打开:https://<你的IP>:3000
|
||||
```
|
||||
|
||||
> `localhost` 走纯 HTTP 即可。从其他设备访问时请使用 `--https`,或使用 [Tailscale](https://tailscale.com/)(推荐):安装器可以替你配好(在网络访问提示处选择 **Tailscale**,或在已有安装上运行 `bash ~/.codeman/app/install.sh tailscale`)。这样你会得到带真实证书的 `https://<你的机器>.<tailnet>.ts.net`:只对你的 tailnet 可见、无需密码,手机上的 PWA 安装和推送通知也都能用。
|
||||
> `localhost` 走纯 HTTP 即可。从其他设备访问时请使用 `--https`,或使用 [Tailscale](https://tailscale.com/)(推荐):安装器可以替你配好(在网络访问提示处选择 **Tailscale**,或在已有安装上运行 `bash ~/.codeman/app/install.sh tailscale`)。这样你会得到带真实证书的 `https://<你的机器>.<tailnet>.ts.net`:只对你的 tailnet 可见、无需密码,手机上的 PWA 安装和推送通知也都能用。安装器最后会给出这个 URL 和一个可扫描的二维码,之后随时可以用 `bash ~/.codeman/app/install.sh status` 再次打印。
|
||||
|
||||
### 安全的二维码认证
|
||||
|
||||
@@ -269,18 +269,18 @@ codeman service install # systemd/launchd 服务:重启后自动回
|
||||
|
||||
### 3. 读懂仪表盘
|
||||
|
||||
- **标签(顶部)** —— 每个会话一个。`Alt+1`–`9` 跳转,`Ctrl+Tab` 下一个,拖拽排序(标签顺序会跨设备同步)。更喜欢列表?**App Settings → Appearance → Tabs** 可以把它挪进左侧边栏(带筛选框,`Alt+B` 折叠)或一条竖向导轨,导轨的行按活动状态排序:先是等你处理的,然后是跑得最久的,最后是刚刚安静下来的。
|
||||
- **标签(顶部)** —— 每个会话一个。`Alt+1`–`9` 跳转,`Ctrl+Tab` 下一个,拖拽排序(标签顺序会跨设备同步)。更喜欢列表?**App Settings → Appearance → Tabs** 可以把它挪进左侧边栏(带筛选框,`Alt+B` 折叠)或一条竖向导轨,导轨的行按活动状态排序:先是等你处理的,然后是跑得最久的,最后是刚刚安静下来的。导轨上还有一个 **Search sessions** 搜索框、命名的**标签分组**(分组菜单里的 **New session** 会直接在该组里新建会话),以及一个 **Focus** 区,放着你常回去的那些标签的快捷方式。
|
||||
- **终端(中央)** —— 真实的 `xterm.js` 终端;完整 TUI 正常渲染。直接输入并按 **Enter** 发送。`Shift+Enter` 插入换行。
|
||||
- **侧边面板** —— Respawn、Orchestrator、Cron、Subagents、Settings(从工具栏切换)。
|
||||
|
||||
### 4. 与智能体对话
|
||||
|
||||
- **直接在终端输入提示** —— 即使跨越重连,输入也是精确一次送达(连接中断绝不会丢失或重复发送提示)。
|
||||
- **粘贴或拖放图片**,直接进入会话。
|
||||
- **粘贴、拖放或附加图片和视频**,直接进入会话。它们保存在工作区里一个隐藏的 `.codeman-uploads/` 文件夹中(它在 git 里会忽略自己,7 天后被清理),文件路径会落在你的提示里,但不会自动发送。
|
||||
- **语音输入** —— `Ctrl+Shift+V`(Deepgram Nova-3,或者直接用这台机器的 Claude Code 登录、不需要任何 API key;自动静音停止)。
|
||||
- **附件** —— 注册外部文件/文档,并内联预览 Office/PDF;智能体打印出的任何文件路径都可以点击,终端里和对话视图里都行。
|
||||
- **附件** —— 注册外部文件/文档,并内联预览 Office/PDF;智能体打印出的任何文件路径都可以点击,终端里和对话视图里都行,包括 `~/` 路径、相对路径和被折成多行的路径。`.html` 报告会以真实网页打开,Markdown 会渲染后打开,文件夹则以其文件的网格打开。
|
||||
- **需要你的时候** —— 标签会变黄(等待输入)或变红(有个问题挡住了它)。**审批收件箱(Approvals Inbox)**(可选启用)把所有会话里等着你的提示排成一个队列,可以从页头的铃铛或手机首页直接作答;🧠 **Read My Mind**(可选启用)会根据这个 case 的目标和最近的工作替你起草下一条提示。
|
||||
- **看到什么就能复制什么** —— `Shift+拖动` 在 CLI 接管了鼠标时也能选中文本,右键复制选中内容,自动复制(Auto Copy,可选启用)在松开鼠标的瞬间就复制。
|
||||
- **看到什么就能复制什么** —— `Shift+拖动` 在 CLI 接管了鼠标时也能选中文本,右键复制选中内容,自动复制(Auto Copy,可选启用)在松开鼠标的瞬间就复制。用 OSC 52 复制的程序(Claude Code 的 `/copy`、tmux 的 yank、vim)也会把文本放进你浏览器的剪贴板。
|
||||
|
||||
### 5. 让它自主运行
|
||||
|
||||
@@ -299,7 +299,7 @@ codeman service install # systemd/launchd 服务:重启后自动回
|
||||
|
||||
### 7. 运维与维护
|
||||
|
||||
- **App Settings** —— 模型、effort、权限启动模式、主题/皮肤、终端字体与字重、入场动画、通知、显示开关、各 CLI 的专属选项,以及跨设备同步的自定义显示名称和按设备保存的英文/简体中文界面语言。
|
||||
- **App Settings** —— 模型、effort、权限启动模式、主题/皮肤、终端字体与字重、入场与平铺动画(有自己的 **Animations** 分区)、通知(toast 和浏览器通知的显示时长可调)、显示开关、各 CLI 的专属选项,以及跨设备同步的自定义显示名称和按设备保存的英文/简体中文界面语言。**Apply** 按钮保存设置但不关闭设置窗口。
|
||||
- **让它在后台运行** —— `codeman web -d` 脱离你的 shell(`--status`、`--stop`);`codeman service install` 把它装成 systemd 用户单元 / macOS LaunchAgent,重启后自动回来。两者都会先确认服务器真正应答再报告成功,也都拒绝在同一个数据目录上启动第二个服务器。见[让它在后台一直运行](#快速开始--安装)。
|
||||
- **自更新** —— git-clone 安装可在 **App Settings → System → Updates** 中原地更新。
|
||||
- **部署你自己的改动** —— 见[开发](#开发)。
|
||||
@@ -386,6 +386,21 @@ WATCHING → IDLE DETECTED → SEND UPDATE → /clear → /init → CONTINUE →
|
||||
|
||||
运行 **20 个并行会话**且全程可见 —— 60fps 的实时 xterm.js 终端、按会话的 token 与成本跟踪、基于标签的导航,以及一键管理。
|
||||
|
||||
### 平铺网格
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tile-grid-20261009.gif" alt="平铺网格:点击平铺按钮,六个实时会话并排打开(DeepSeek Harness、Claude Code、Codex、一个 shell、OpenCode 和 Pi),再点击一次即回到单个会话" width="800">
|
||||
</p>
|
||||
|
||||
在一个窗口里并排查看和操作最多**六个会话**。点击顶栏的**平铺**按钮(或按 `Ctrl+Shift+G`),会话会以实时终端网格的形式打开:每个窗格都能直接接收键盘输入,并在窗格标题栏中显示智能体的图标、模型和状态。右键单击**平铺**可选择 2、4 或 6 个窗格,按住窗格标题栏拖动即可移动窗格。再次点击**平铺**即回到单个会话。仅限桌面端(窗口宽度约 1180px 以上)。完整说明:[Tile Grid](docs/wiki/Tile-Grid.md)(英文)。
|
||||
|
||||
- **先开重要的**:还没有排好网格时,它会先放正在工作的会话,然后是等你处理的,再是最近用过的,并且总会包含你当前所在的会话。
|
||||
- **记住你的布局**:一旦你排好网格(哪个会话在哪、空着的格子、窗格数、分隔条大小、聚焦和放大的窗格),平铺按钮会原样恢复它,网格打开时刷新页面也一样。
|
||||
- **平铺动画**(可选启用):**App Settings → Animations → Tile Animations** 让网格华丽登场:**CRT**(每个窗格像老显像管一样以一道亮线开机,就是顶部 GIF 里那样)、**Fly from tab**、**Deal**、**Beam down**、**Cascade**、**Pop** 或 **Soft**。开启「减少动态效果」时一切静止。
|
||||
- **滚动和主终端一样**:鼠标滚轮会在窗格里滚动全屏 Claude 的对话,Codex 窗格会翻页查看它的记录,`Shift+滚轮` 滚动窗格的本地历史。
|
||||
- **分离窗格(Detach Tiles)**(测试版,可选启用):打开 **App Settings → Appearance → Detach Tiles** 后,把窗格标题栏拖出浏览器,它就弹出成独立窗口;拖到另一个 Codeman 窗口的窗格上,它就移到那边。
|
||||
- **徒手操作**:开启[手势叠加层](#更多特性)后,捏住一个窗格拖到另一个窗格上即可交换,拖到空格子上即可移动,把一个标签拖进网格即可加入。
|
||||
|
||||
### 持久化会话
|
||||
|
||||
每个会话都运行在 **tmux** 内 —— 会话可在服务器重启、网络中断与机器休眠后存续。启动时自动恢复,具备双重冗余。幽灵会话发现机制能找到孤立的 tmux 会话。受管会话带有环境标签,因此智能体不会杀掉自己的会话。
|
||||
@@ -419,7 +434,7 @@ codeman web --title-hostname dev-box # codeman:dev-box(用于覆盖嘈
|
||||
### 标签提醒(Tab Alerts)
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tab-alerts-glow-20260815.gif" alt="会话标签:一个普通的活动标签,旁边是黄色的等待输入标签和红色的需要决定标签,都带着呼吸式光晕" width="900">
|
||||
<a href="docs/images/codeman-tab-states-20261010.png"><img src="docs/images/codeman-tab-states-20261010.gif" alt="标签状态(带标注):一个绿色描边在转的工作中标签,一个被智能体的问题挡住的红色标签(问题显示在它下方),以及一个回合已完成的黄色标签,两个提醒标签都在呼吸闪烁" width="900"></a>
|
||||
</p>
|
||||
|
||||
每个标签一眼就能看出状态。运行中的会话保持绿色状态点。会话停下来等待输入时,标签变**黄**:稳定的描边、着色的背景、黄色的点,上面叠一层缓慢的呼吸光晕。当权限提示或提问**挡住**了智能体,标签变**红**,脉动更快。底色永远不会闪灭,所以哪怕只瞥一眼(或截一张图)也能读到真实状态;标签被选中时描边依然可见,页面刷新后会从服务端重新装载待处理的提醒,因此一个被挡住的会话绝不可能藏在一个看起来正常的标签后面。
|
||||
@@ -445,8 +460,11 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
## 更多特性
|
||||
|
||||
- **后台守护进程与服务安装** —— `codeman web -d` 以脱离终端的方式运行服务器,带 pid 文件、`~/.codeman/web.log` 和经过校验的启动(它会轮询到服务器应答为止,所以端口冲突绝不会被当成成功);`codeman service install` 写入一个 systemd 用户单元(Linux)或 LaunchAgent(macOS),并把你 shell 的 PATH 一并写进去,这样 nvm 或 Homebrew 装的 `node`、`tmux` 和 `claude` 才真的找得到。机密永远不会写进单元文件
|
||||
- **设置里的诊断**:**App Settings → System → Diagnostics → Run checks** 会在服务器上运行 `codeman doctor`,列出 Node、tmux、每个智能体 CLI 以及可选的 Office 工具,附带版本、路径和安装提示。除了 `PATH`,它还会查找每个 CLI 惯常的安装目录(`~/.local/bin`、`~/.npm-global/bin` 之类),所以即使服务只拿到一个最小的 `PATH`,大多数安装也能被找到。多用户模式下仅管理员可用
|
||||
- **自更新** —— systemd/launchd 管理下的 git-clone 安装可在 **App Settings → System → Updates** 中原地更新:它会检测最新发行版,自动暂存(stash)脏工作树,并在服务重启期间流式展示构建进度(npm 安装会被报告为不可更新)
|
||||
- **底栏里的 Git 状态**:默认关闭(**App Settings → Header & Panels → Bottom bar → Git status**,按设备生效)。底栏右侧的一个小指示器让你一眼看清当前会话所在仓库的状态:`● 3` 表示未提交的文件,`↑ 2` 表示未推送的提交,`⚠` 表示合并冲突,`✓` 表示全部已提交并推送。点击它会打开一个可拖动的窗口,列出已暂存、未暂存、未跟踪和有冲突的文件(按折叠的文件夹分组,关掉该设置则显示为平铺列表)以及未推送的提交;**点击文件即可查看它的 diff**(新文件全部显示为新增,已删除的文件全部显示为删除),**Open file** 可直接跳到查看器。一个包含多个项目的文件夹,会为向下两层内找到的每个仓库各给一个可折叠分区,打开之前全部折叠。只读且离线(Codeman 绝不 fetch,也绝不改动仓库);Docker 和远程会话不显示
|
||||
- **把 GitHub 仓库克隆成 case** —— 在 **Add Case → Clone Repo** 里粘贴一个仓库 URL,Codeman 会把它克隆到 `~/codeman-cases/<name>` 并注册为普通 case,随时可以跑智能体。输入时它会预检 URL(告诉你能否匿名克隆,并为可选的分支/标签字段提供仓库真实的分支与标签),从 URL 里填好 case 名,还让你选 Run 按钮该用哪个 CLI。支持 `https://` 的公开仓库;Codeman 绝不收集或保存凭据
|
||||
- **在自定义文件夹里创建 case**:在 **Add Case → Create New** 里勾选 **Create in a custom folder**,选一个父文件夹(可用 Browse 浏览)和一个名字,Codeman 就会在那里而不是 `~/codeman-cases` 里搭建新 case。目标必须是一个新的或空的文件夹;系统目录、你的主目录本身、`~/.ssh` 这类凭据目录,以及 Codeman 自己的数据目录都会被拒绝。多用户模式下仅管理员可用
|
||||
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode**、**Codex**、**Antigravity**、**Gemini**、**Pi**、**Grok**、**DeepSeek Harness** 或 **OMP**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*`、`CODEX_*`、`ANTIGRAVITY_*`、`GEMINI_*`/`GOOGLE_*`、`PI_*`、`GROK_*`/`XAI_*`、`DSH_*`/`DEEPSEEK_*` 与 `OMP_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)、[`docs/pi-integration.md`](docs/pi-integration.md)、[`docs/grok-integration.md`](docs/grok-integration.md)、[`docs/deepseek-integration.md`](docs/deepseek-integration.md) 与 [`docs/omp-integration.md`](docs/omp-integration.md)
|
||||
- **自定义模型端点**(1.29.0 新增,目前仅 HTTP API)—— 让某个会话的 CLI 指向任意 OpenAI 兼容端点,而不是它自己的官方后端:本地的 llama.cpp、llama-swap、Ollama 或 vLLM 机器,也可以是 Azure AI Foundry、OpenRouter 这类云端网关。端点只需保存一次(`POST /api/model-endpoints`,模型列表从它的 `/v1/models` 自动发现),再应用到会话(`POST /api/sessions/:id/custom-model`),CLI 就会在原地重启并接上该端点。Claude、OpenCode、Pi、Grok 与 OMP 已实测通过;Codex、Gemini 与 DeepSeek 存在已记录的缺口,Antigravity 没有可用机制。工具栏选择器是下一步。详见 [`docs/custom-model-endpoints.md`](docs/custom-model-endpoints.md)
|
||||
- **Web 标签页** —— 把 Grafana、Uptime Kuma、一个 Vite 开发服务器或任何仪表盘 URL 作为标签页打开在会话旁边(Run 下拉菜单 → **Web / URL** → **Add URL**)。仪表盘通过 Codeman 自己的源代理,因此 `http://` 目标在手机上走 HTTPS 也能用、走隧道也能用;单页应用能在自己的路径上正常路由,页面自己重载后也能自行恢复。智能体打印出的 `localhost` 链接会自动以 Web 标签页打开。详见 [`docs/web-tabs.md`](docs/web-tabs.md)
|
||||
@@ -458,10 +476,15 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
- **手势控制** _(可选)_ —— 一个 MediaPipe 手部追踪叠加层,可徒手抓取/拖动会话窗口并捏合按钮。用 `CODEMAN_GESTURE=1` + App Settings → Terminal & Input 启用
|
||||
- **多显示器横跨** _(macOS)_ —— 一键打开一个横跨所有显示器最大化的浏览器窗口,让浮动的智能体/手势面板可以跨越物理拼接缝
|
||||
- **文件查看器按钮** _(可选)_ —— 页头新增一个按钮,一键切换内置文件浏览器面板;在 App Settings → Header & Panels → Header buttons 中启用
|
||||
- **HTML 报告以网页打开**:点击智能体打印出的 `.html` 路径(测试报告、覆盖率页面、仪表盘),文件查看器会把它显示成一个真实网页,并带上同一文件夹里的脚本、样式、图片和数据文件;**Page** 胶囊按钮可切到源码及其 Edit 按钮。页面在沙箱里以不透明源运行,所以它读不到 Codeman 的 cookie、调不了 Codeman 的 API,也读不了自己文件夹以外的文件。网络访问保持开放,因此从 CDN 加载 Chart.js 或字体的仪表盘和直接从磁盘打开时一样能用。范围过大的文件夹(`/`、你的主目录、`/tmp`)会被拒绝,所以请给报告一个单独的文件夹。在终端里点击的 `.md` 路径也会渲染后打开
|
||||
- **可点击的路径与文件夹网格**:写成 `~/…`、相对于会话文件夹或被折成多行的路径,在终端和回复查看器(Response Viewer)里都能点击,文件夹也可以:点击文件夹会打开它的文件网格(渲染图、截图、报告),用方向键翻看
|
||||
- **OSC 52 剪贴板**:会话里的程序用 OSC 52 设置剪贴板时(Claude Code 的 `/copy`、tmux 的 yank、vim),文本会进入你浏览器的剪贴板,主终端和每个平铺窗格都一样。读取剪贴板的请求一律拒绝,回放缓冲区也绝不会触发复制
|
||||
- **MCP 服务器同步**(可选启用):把每个已安装 CLI 的用户级 MCP 服务器(Claude、Codex、Gemini、OpenCode、Antigravity,以及 GitHub Copilot CLI)复制进其他 CLI 自己的配置文件。只增不改,你关掉的服务器绝不会被复制,**Preview** 会先列出改动,原文件保留为 `.codeman-bak`。位于 App Settings → Agents & CLIs;多用户模式下仅管理员可用
|
||||
- **CJK / 输入法支持** —— 完整支持中文 / 日文 / 韩文的组合输入,Ctrl、Alt 修饰的导航键也会原样透传给 CLI
|
||||
- **页头里的套餐用量** —— 页头实时显示 Claude 订阅用量(5 小时窗口与每周窗口),数据来自 Codeman 在拉起 `claude` 时临时交给它的 statusline 导出器,绝不会写进你的设置文件;Codex 的限额则来自它自己的 app-server。按设备生效:桌面默认开,手机默认关
|
||||
- **会话列表,随你摆** —— 页头横条、带筛选框的左侧边栏,或一条竖向导轨,导轨的详细行带有创建时间与状态时长并按活动状态排序;手机首页和桌面首页导轨用的是同一套顺序
|
||||
- **终端外观** —— 七套皮肤(其中四套浅色)、按设备保存的字体与字重(内置的 JetBrains Mono 覆盖 100 到 800 的字重),以及可选启用的入场动画,覆盖标签、智能体窗口、终端面板和连接线
|
||||
- **提示缓存状态**:每个 Claude 会话都会显示它的提示缓存是热的(`cache:until HH:MM`)还是冷的,显示在页脚(前提是你没有自己的 statusline)和 Session Options → Respawn 中,并给出重新缓存的代价,压缩上下文后还会附一条说明。只做显示,重启后依然保留
|
||||
- **会话列表,随你摆** —— 页头横条、带筛选框的左侧边栏,或一条竖向导轨,导轨的详细行带有创建时间与状态时长并按活动状态排序;手机首页和桌面首页导轨用的是同一套顺序。导轨上的 **Search sessions** 会把列表筛到名字匹配的标签,跨所有分组;带提醒的标签即使名字不匹配也始终可见。命名的**标签分组**可以折叠、重排和拖入拖出;分组菜单里有 **New session**,智能体拉起的工作会话会落在它的父会话后面(**Spawned tabs follow their parent**,默认关闭,开启后它会跟着父会话移动)。**Add to Focus** 会在导轨顶部的一个区里为任意标签放一个快捷方式,**CLI Logos on Tabs** 可以按设备关闭
|
||||
- **终端外观** —— 七套皮肤(其中四套浅色)、按设备保存的字体与字重(内置的 JetBrains Mono 覆盖 100 到 800 的字重),以及可选启用的动画,覆盖标签、智能体窗口、终端面板、连接线和[平铺网格的窗格](#平铺网格),全部位于 App Settings → Animations(附带一个试玩用的动画实验室)
|
||||
- **操作系统通知与主机名感知标题** —— 桌面提醒与标签标题以 `codeman:<host>` 为前缀,使多主机配置不再含糊
|
||||
|
||||
---
|
||||
@@ -476,7 +499,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
- **默认加固** —— 非 root、`--cap-drop ALL`、`no-new-privileges`、PID/内存上限,绝不使用 `--privileged` 或 docker socket;**密封(sealed)** 配置(不注入主机凭据、关闭网络)只需一个开关。
|
||||
- **无感认证、凭据隔离** —— 主机上的 Claude / Codex / Antigravity / Gemini / OpenCode / Pi / Grok / OMP 登录在容器内开箱即用:凭据在启动时以只读种子方式复制注入,onboarding/信任提示已预先答复,不会弹出登录向导。容器保留自己的副本,绝不回写主机的凭据存储;跨边界共享的只有对话转录,导出文件也绝不包含机密。
|
||||
- **挂到你已经在跑的容器上** —— 在 Docker 面板勾选 **Attach to an existing container**,就能把 case 链接到一个现成容器,而不是新建一个。Codeman 只 `exec` 进去,绝不启动、停止、重启或删除它;一个被接管的容器可以在不同目录下支撑多个 case,**复制一个已有 case** 会用同一容器上的兄弟 case 预填表单。多用户模式下仅管理员可用,因为容器的挂载属于启动它的人。
|
||||
- **迁移到另一台机器** —— 把容器的完整环境(工具链 + 工作区)导出为可移植的 `.tar.gz`,在另一台机器上导入到新案例即可继续。
|
||||
- **迁移到另一台机器** —— 把容器的完整环境(工具链 + 工作区)导出为可移植的 `.tar.gz`,在另一台机器上用 `docker load` 载入,再导入到一个新案例即可继续。
|
||||
- **持久耐用** —— Codeman 重启后重连会回到同一个存活的智能体;容器停止/重启后则从绑定挂载的转录恢复对话。
|
||||
|
||||
前置条件:只需 Docker(或 Podman)。智能体基础镜像会在首次使用时自动构建,构建进度实时显示在 UI 中(也可用 `node scripts/build-agent-image.mjs` 预构建)。完整指南:[`docs/docker-cases.md`](docs/docker-cases.md)。
|
||||
@@ -493,6 +516,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
- **共享会话**:多个客户端可以以不同窗口尺寸同时附着同一个远程会话而互不挤压;发现列表会显示带客户端计数的「shared」徽标。
|
||||
- **注入安全**:所有 ssh 命令行都经由单一的 shell 转义构建器生成,主机/路径/身份文件字段均有模式校验。
|
||||
- **文件也行**:远程 case 里的预览、下载和文本读取走同一条 ssh 连接(一次 `realpath` + `stat` 探测,然后流式 `cat`,支持 `Range` 拖动进度),所以点一个路径打开的就是智能体所在那台机器上的文件。什么都不会复制到 Codeman 主机;编辑和 Office 预览会明确返回 400,而不是一个误导性的 404。
|
||||
- **完整的回滚历史**:加载远程会话的历史时,会通过一次有上限的 ssh 往返直接从远程 tmux 读取,所以重新附着或切换标签之后,会话依然保有完整的回滚缓冲区,历史与实时屏幕衔接处也不会丢行。
|
||||
|
||||
在 **New Case → Remote** 中配置(主机、用户、身份文件、可选跳板机)。完整设计:[`docs/remote-sessions.md`](docs/remote-sessions.md)。
|
||||
|
||||
@@ -645,7 +669,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
|
||||
|
||||
### 网络与访问
|
||||
|
||||
- **默认仅环回** —— 绑定 `127.0.0.1`,仅可从本机访问,因此「无密码」默认配置开箱即安全。在未设置 `CODEMAN_PASSWORD` 的情况下绑定非环回主机会*启动但打印一条醒目警告*,并给出三个具体修复方案(设置密码、环回 + 一个带认证的隧道,或用 `--allow-unauthenticated-network` 显式确认)
|
||||
- **默认仅环回** —— 服务器程序本身绑定 `127.0.0.1`,仅可从本机访问,因此「无密码」默认配置开箱即安全(引导式安装器会询问网络访问方式,并替你配置绑定和密码)。在未设置 `CODEMAN_PASSWORD` 的情况下绑定非环回主机会*启动但打印一条醒目警告*,并给出三个具体修复方案(设置密码、环回 + 一个带认证的隧道,或用 `--allow-unauthenticated-network` 显式确认)
|
||||
- **可选认证,真实会话** —— 通过 `CODEMAN_USERNAME`(默认 `admin`)/ `CODEMAN_PASSWORD` 的 HTTP Basic 认证。成功后签发一个不透明的 256 位 `codeman_session` cookie(`randomBytes(32)`)—— 服务端校验,而非客户端签名,因此无法离线伪造(24h TTL、自动延长、设备上下文审计日志)
|
||||
- **按 IP 速率限制** —— 失败 10 次 → `429` 并带 `Retry-After`(15 分钟衰减)。即便攻击者在同一 IP 上猛攻,有效 cookie 或正确密码也能*立即*恢复 —— 这很重要,因为所有隧道流量共享同一个环回 IP。二维码认证有自己独立的限制器
|
||||
- **可配置的权限模式**:`--dangerously-skip-permissions` 只是默认值。**App Settings → Agents & CLIs → Claude → Startup Mode** 可以把新会话切换为 Anthropic 的分类器护栏 `auto` 模式(低打扰,需要 Claude Code 2.1.207+)、`normal` 提示模式,或一份显式的允许工具列表。多用户模式下,未获授权的用户会被强制为 `auto`,shell 会话与跳过权限需要按用户显式授权
|
||||
@@ -663,7 +687,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
|
||||
### 输入、文件与响应头
|
||||
|
||||
- **模式校验的输入** —— 每个 API 请求体都用 Zod v4 模式检查;一个 `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `ANTIGRAVITY_*` / `GEMINI_*` / `GOOGLE_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `OMP_*` 环境变量前缀允许列表把控每个 CLI 能接收哪些设置,而那些能把 CLI 流量改道的键(base URL、配置目录)对非管理员用户会被钳制
|
||||
- **路径限定** —— 文件路由在边界检查前先 `realpath`(无 TOCTOU);`..`、绝对路径、以及解析到工作目录之外的符号链接都会被拒绝。上限:10 MB 文本预览 / 2 GB 原始与下载(`CODEMAN_MAX_DOWNLOAD_BYTES`;响应体是流式的并支持 `Range` 请求,所以这个上限只是合理性边界,不是内存保护);`/api/download` 对敏感路径(`.env`、`*credentials*`、`~/.ssh/`、`.aws/credentials`)做黑名单。SVG/HTML 以 `octet-stream` + `nosniff` + attachment 提供,因此会被下载而非执行
|
||||
- **路径限定** —— 文件路由在边界检查前先 `realpath`(无 TOCTOU);`..`、绝对路径、以及解析到工作目录之外的符号链接都会被拒绝。上限:10 MB 文本预览 / 2 GB 原始与下载(`CODEMAN_MAX_DOWNLOAD_BYTES`;响应体是流式的并支持 `Range` 请求,所以这个上限只是合理性边界,不是内存保护);`/api/download` 对敏感路径(`.env`、`*credentials*`、`~/.ssh/`、`.aws/credentials`)做黑名单。SVG/HTML 以 `octet-stream` + `nosniff` + attachment 提供,因此会被下载而非执行。HTML 唯一会被渲染的地方是文件查看器的网页视图:一个独立的 `/html-view/<capability>/` 地址,只覆盖该文件所在的文件夹,响应带 `Content-Security-Policy: sandbox` 且不含 `allow-same-origin`,因此页面是不透明源,永远读不到 Codeman 的 cookie,也驱动不了它的 API;隐藏文件夹和范围过大的根目录(`/`、主目录、`/tmp`)会被拒绝,退出登录时这些凭证也会被吊销
|
||||
- **安全响应头** —— `Content-Security-Policy`(`default-src 'self'`,每个例外都逐条列举)、`X-Content-Type-Options: nosniff`、`X-Frame-Options: SAMEORIGIN`、HTTPS 下的 HSTS,以及**仅**对 `localhost` / `127.0.0.1` / `::1` 反射的 CORS
|
||||
|
||||
### 供应链与隔离
|
||||
@@ -697,7 +721,7 @@ Web UI 仍是主要界面;完整指南见 **[docs/tui.md](docs/tui.md)**(英
|
||||
|
||||
| 快捷键 | 动作 |
|
||||
| ------------------------------- | -------------------------------------------------------- |
|
||||
| `Ctrl/Cmd+W` | 杀掉当前会话 |
|
||||
| `Ctrl+W` | 不是 Codeman 快捷键:它会到达终端(删除前一个词)。**Close Session** 默认没有按键,可在 App Settings → Shortcuts 里绑定 |
|
||||
| `Ctrl/Cmd/Option+K` | 查找已打开的会话或新建一个 |
|
||||
| `Ctrl/Cmd+Tab` | 下一个会话 |
|
||||
| `Alt/Option+[` / `Alt/Option+]` | 上一个 / 下一个会话 |
|
||||
@@ -710,6 +734,10 @@ Web UI 仍是主要界面;完整指南见 **[docs/tui.md](docs/tui.md)**(英
|
||||
| `Ctrl/Cmd+L` | 清屏 |
|
||||
| `Ctrl+Shift+R` | 恢复终端尺寸 |
|
||||
| `Ctrl+Shift+V` | 切换语音输入 |
|
||||
| `Ctrl+Shift+G` | 打开或关闭平铺网格 |
|
||||
| `Alt+Shift+方向键` | 聚焦左、右、上、下方的窗格 |
|
||||
| `Ctrl+Shift+方向键` | 把聚焦的窗格移动一格(移进空格子,或与邻居交换) |
|
||||
| `Alt+Shift+Enter` | 放大聚焦的窗格,或恢复网格 |
|
||||
| `Ctrl/Cmd +` / `-` | 字体大小 |
|
||||
| `Ctrl/Cmd+?` | 键盘帮助 |
|
||||
| `Shift+Enter` | 插入换行(发送到终端) |
|
||||
@@ -727,19 +755,23 @@ Web UI 仍是主要界面;完整指南见 **[docs/tui.md](docs/tui.md)**(英
|
||||
|
||||
### 智能体技能(从这里开始)
|
||||
|
||||
这一节的所有内容也打包成了一个 **Claude Code 技能**,位于 [`skills/codeman`](skills/codeman/SKILL.md)。装一次,就再也不用把 API 文档粘进提示词。你用大白话说想要什么,已经坐在 Codeman 会话里的智能体会自己加载配方并驱动 API。
|
||||
这一节的所有内容也打包成了一个**智能体技能**,位于 [`skills/codeman`](skills/codeman/SKILL.md),采用 Claude Code、Codex、Gemini CLI、OpenCode、Grok、OMP 以及大多数其他智能体 CLI 都能读取的 `SKILL.md` 格式。装一次,就再也不用把 API 文档粘进提示词。你用大白话说想要什么,已经坐在 Codeman 会话里的智能体会自己加载配方并驱动 API。
|
||||
|
||||
<p align="center">
|
||||
<a href="docs/images/codeman-skill-crt-20261010.png"><img src="docs/images/codeman-skill-crt-20261010.gif" alt="一次真实的 codeman 技能运行:在 Claude Code 里输入一句简短的提示,平铺网格开机,然后一个跑在本地 qwen 模型上的 DeepSeek Harness 工作会话和一个 Claude Code 工作会话作为新窗格开机,主会话到两者之间画出派生连线" width="900"></a>
|
||||
</p>
|
||||
|
||||
#### 第 1 步:安装
|
||||
|
||||
| 方式 | 命令 | 范围 |
|
||||
| ---------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | 全局,任何支持技能的智能体都能用 |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | 全局,任何支持技能的智能体都能用([skills.sh](https://skills.sh));给 pi 装技能就用这个方式 |
|
||||
| Claude Code 插件 | `/plugin marketplace add Ark0N/Codeman`,然后 `/plugin install codeman@codeman` | 全局,通过 Claude Code 自带的插件管理器;`/plugin update codeman` 跟随新版本。与 `codeman skill install` 二选一:两者都装会让技能出现两次(`codeman` 和 `codeman:codeman`) |
|
||||
| 内置 CLI | `codeman skill install` | 全局(`~/.claude/skills/codeman`),给那些从 npm 安装、从未克隆过仓库的用户 |
|
||||
| 内置 CLI | `codeman skill install --case <name>` | 仅一个 case |
|
||||
| Web UI | App Settings → Agents & CLIs → Claude → **Agent Skill** | 每次在某个 case 创建 Claude 会话时自动注入(`agentSkillEnabled`,跨设备同步,默认关闭) |
|
||||
| 内置 CLI | `codeman skill install --case <name> [--mode <mode>]` | 仅一个 case;`--mode codex`(或任何其他运行模式)会把它写到那个 CLI 查找技能的位置 |
|
||||
| Web UI | App Settings → Agents & CLIs → All agent CLIs → **Codeman Agent Skill** | 每次创建会话时自动注入到 case 里该会话的 CLI 查找技能的位置:Claude Code 是 `.claude/skills/`,Codex、Gemini CLI、OpenCode、Antigravity、Grok、DeepSeek 和 OMP 是 `.agents/skills/`;pi 除外,因为它的项目级技能会触发信任提示(`agentSkillEnabled`,跨设备同步,默认关闭) |
|
||||
|
||||
`codeman skill uninstall [--case <name>]` 可以撤销 CLI 安装,并且绝不会碰你自己写的 `skills/codeman`。
|
||||
`codeman skill uninstall [--case <name>]` 可以撤销 CLI 安装(带 `--case` 时,删除该 case 里所有由 Codeman 管理的副本,不论它在哪个 CLI 的目录里),并且绝不会碰你自己写的 `skills/codeman`。
|
||||
|
||||
#### 第 2 步:开口要
|
||||
|
||||
@@ -792,7 +824,7 @@ deleted 9f2d8e5f, aff9c691, be9f1f15 标签消失
|
||||
- **它会自我门禁。** 不在 Codeman 会话里(`CODEMAN_MUX` 未设置)时,技能拒绝动作,也不去猜 API 地址,所以全局安装对无关的 Claude Code 会话没有任何代价。
|
||||
- **它刻意保守。** 未经提示,它只会拉起会话、给它们发提示,并删除**它在同一段对话里自己创建的**会话(按精确 id,经由一个拒绝删除智能体自身会话的失败即关闭守卫)。删除 case(会抹掉一个真实的代码目录)、批量杀会话、改动 respawn/ralph/cron/orchestrator 以及写设置,都需要你开口并指名目标。
|
||||
|
||||
⚠️ 把 `agentSkillEnabled` 关回去**不会删掉已经注入的副本**(在创建时做清扫,会把技能从共用同一个 `.claude/` 目录的其他活动会话脚下抽走)。要删就按 case 删:`codeman skill uninstall --case <name>`。
|
||||
⚠️ 把 `agentSkillEnabled` 关回去**不会删掉已经注入的副本**(在创建时做清扫,会把技能从共用同一个工作区的其他活动会话脚下抽走)。要删就按 case 删:`codeman skill uninstall --case <name>`。
|
||||
|
||||
---
|
||||
|
||||
@@ -929,6 +961,76 @@ codeman tui --list # 带编号的会话列表(管
|
||||
codeman tui 3 # 附着到该列表里的第 3 个会话
|
||||
```
|
||||
|
||||
### `codeman agent`:每种 CLI 模式都能用的会话间命令
|
||||
|
||||
上面的技能靠 Codeman 为每个会话写入的一段前导脚本,用 `curl` 和 `jq` 驱动 API。在它够不着的地方(`pi` 或 `shell` 会话、没有 `jq` 的机器),同样的环境依然存在(每个面板里都导出了 `CODEMAN_MUX=1`、`CODEMAN_SESSION_ID`、`CODEMAN_API_URL`),所以 `codeman agent` 把同一批动词打包成了命令。它只是 [API](#api) 一节所列端点之上的一层薄客户端:没有新路由,没有新的传输方式,认证和归属规则不变。在 case 的 `AGENTS.md` 里写一行就够了:*"other sessions: `codeman agent --help`"*。
|
||||
|
||||
```bash
|
||||
codeman agent ls # 列出会话;* 标记当前这个
|
||||
SID=$(codeman agent spawn scratch-1 --mode claude) # quick-start,并在该模式有就绪标记时等到输入框出现
|
||||
codeman agent send "$SID" 'review src/, then say DONE' --until stop,exit --timeout 300000 # --wait = 默认信号集
|
||||
codeman agent read "$SID" # 最后一条回答(按服务端对该模式的读取方式)
|
||||
codeman agent read "$SID" --tail 3000 # 终端尾部,已去掉 ANSI(所有模式)
|
||||
codeman agent send "$SID" 'run the tests, then print WORKDONE followed by _4711' # 没有 hook 的模式(opencode、pi 等):让它分两半输出标记……
|
||||
codeman agent wait "$SID" --match WORKDONE_4711 # ……然后等拼接后的形式,提示本身的回显里永远不会出现它
|
||||
codeman agent interrupt "$SID" # 只发一个 ESC,对话保持完整
|
||||
codeman agent rm "$SID" # 除当前会话外的任何会话
|
||||
```
|
||||
|
||||
这些规则由命令强制执行,而不只是写在文档里:在 Codeman 会话之外它们拒绝运行,也绝不猜测 URL;`send` 只发送可打印文本加 Enter(像 `Ctrl+C` 这样的控制字节在 opencode 里就是 `app_exit`,所以 ESC 只以 `interrupt` 的形式存在,而且它从不追加 Enter);`rm` 拒绝空 id、无法证明不是自己的 id,以及任一方向的前缀匹配。id 可以用 `ls` 打印的 8 字符前缀(通过列表解析;有歧义的前缀会被拒绝,短于 8 个字符的 id 在所有动词上都会被拒绝)。以 `-` 开头的提示要放在 `--` 之后(`send "$SID" -- "- fix the bug"`)。
|
||||
|
||||
你发出的提示的回显也算输出:如果 `--match` 标记原样出现在提示里,它会立刻匹配,工作会话还什么都没做,所以提示要让它分两半输出。主机正在休眠的远程会话,对不等待结果的 `send` 会回答 `buffered`(Codeman 唤醒主机,等面板恢复后再敲入提示)或 `dropped`(超出唤醒缓冲区的上限,什么都不会敲入:退出码 `1`)。退出码:`0` 已送达/已匹配/收到信号,`1` 错误,`2` 超时,`3` 工作会话已退出或等待在没有回答的情况下结束(`delivered:false`、`ended:true`),`4` 被拒绝。`spawn` 在 stdout 上只打印 id(说明文字走 stderr),所以 `SID=$(…)` 恰好拿到 id。`--json` 让每个动词打印响应信封里的 `data`。在没有 hook 信号的模式上使用 `--until stop`,会原样透传服务端的 400:那里的答案是标记路径(`--match`),和技能完全一样。
|
||||
|
||||
### MCP 服务器(`codeman mcp`):从任意 MCP 客户端驱动 Codeman
|
||||
|
||||
`codeman mcp` 是一个走 stdio 的 [Model Context Protocol](https://modelcontextprotocol.io) 服务器,因此任何 MCP 客户端(Claude Code、Claude Desktop、Codex、Gemini CLI、Cursor 等)都能在任意已安装的智能体 CLI 里启动 Codeman 会话、给它们发提示、等它们完成、读取回答并清理,无论是在 Codeman 内部还是外部。和 `codeman agent` 一样,它是 HTTP API 的客户端:没有新路由,认证和归属规则不变。
|
||||
|
||||
```bash
|
||||
# Claude Code
|
||||
claude mcp add codeman -e CODEMAN_API_URL=https://127.0.0.1:3000 -- codeman mcp
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"codeman": {
|
||||
"command": "codeman",
|
||||
"args": ["mcp"],
|
||||
"env": { "CODEMAN_API_URL": "https://127.0.0.1:3000" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
# Codex(~/.codex/config.toml):为长时间等待调高默认 60 秒的工具超时
|
||||
[mcp_servers.codeman]
|
||||
command = "codeman"
|
||||
args = ["mcp"]
|
||||
env = { CODEMAN_API_URL = "https://127.0.0.1:3000" }
|
||||
env_vars = ["CODEMAN_MUX", "CODEMAN_SESSION_ID"] # Codex 只给 MCP 服务器一个最小环境;这两个变量让它知道自己运行在哪个 Codeman 会话里
|
||||
tool_timeout_sec = 120
|
||||
```
|
||||
|
||||
JSON 形式适用于 Claude Desktop、Cursor 和 Gemini CLI。服务器设置了密码时,在 `env` 里加上 `"CODEMAN_PASSWORD"`(或者让它读取数据目录里的 `.env`)。如果 PATH 上没有 `codeman` 命令(没走安装器的 git 检出),改用 `node /path/to/Codeman/dist/index.js mcp`。
|
||||
|
||||
| 工具 | 作用 |
|
||||
| ---- | ---- |
|
||||
| `list_sessions` | 你能看到的每个会话,附带运行模式、状态、文件夹,以及这些工具是否可以给它发提示 |
|
||||
| `start_session` | 在一个 case 里(全新的临时文件夹或已有的 case)用任意已安装的 CLI 起一个新工作会话;等到它能接收提示为止 |
|
||||
| `send_prompt` | 输入一行提示并按 Enter;可选择等到这一回合结束 |
|
||||
| `wait_for_session` | 等待一个信号(`stop`、`blocked`、`idle`、`working`、`exit`)或输出里的一个字面标记 |
|
||||
| `read_output` | 最后一条回答、整段对话,或终端的最后若干字节 |
|
||||
| `interrupt_session` | 一次 Escape:停止当前回合,保留对话 |
|
||||
| `delete_session` | 关闭一个工作会话(它的 case 文件夹会保留) |
|
||||
|
||||
这些规则由服务器强制执行,而不只是写在文档里:
|
||||
|
||||
- **它绝不猜测服务器。** URL 来自 `CODEMAN_API_URL` 或 `--url`;没有配置时它照样启动并列出工具,每次调用都会说明该如何配置。
|
||||
- **只动自己的会话。** 发提示、中断和删除只限于这个服务器自己启动的会话(以及它运行在某个 Codeman 会话里时,该会话自己的工作会话)。列出、读取和等待对所有会话都可用。`codeman mcp --allow-any-session` 会解除这个限制,适合想让助手驱动自己现有标签的用户。它永远不会对自己所在的会话下手。
|
||||
- **等待时长适配客户端。** 一次等待默认 45 秒(Codex 默认在 60 秒时切断 MCP 工具),上限 600 秒;返回 `timed_out` / `still_working` 时再调用一次即可。
|
||||
- **两个协议时代都支持。** 它既能应答 2026-07-28 版本(每个请求带 `_meta`、`server/discover`),也能应答 2024-11-05 到 2025-11-25 的 `initialize` 握手。
|
||||
|
||||
### Hook(事件*回流*到 Codeman)
|
||||
|
||||
Codeman 会注册 Claude Code hook,它们 `POST /api/hook-event`(`permission_prompt`、`idle_prompt`、`stop`、`task_completed` 等),让仪表盘实时响应。该端点在环回上免认证,但在受管隧道下需要 `X-Codeman-Hook-Secret` 头(从 `$CODEMAN_HOOK_SECRET_FILE` 读取)。通常你不需要手动调用它 —— Codeman 会自动接好 —— 但自主层正是靠它「看见」智能体在做什么。
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
||||
"name": "io.github.Ark0N/codeman",
|
||||
"title": "Codeman",
|
||||
"description": "Start, prompt and read AI coding agent sessions (Claude Code, Codex, Gemini CLI and more) in Codeman",
|
||||
"version": "1.41.1",
|
||||
"websiteUrl": "https://getcodeman.com",
|
||||
"repository": {
|
||||
"url": "https://github.com/Ark0N/Codeman",
|
||||
"source": "github"
|
||||
},
|
||||
"packages": [
|
||||
{
|
||||
"registryType": "npm",
|
||||
"identifier": "aicodeman",
|
||||
"version": "1.41.1",
|
||||
"transport": {
|
||||
"type": "stdio"
|
||||
},
|
||||
"packageArguments": [
|
||||
{
|
||||
"type": "positional",
|
||||
"value": "mcp"
|
||||
}
|
||||
],
|
||||
"environmentVariables": [
|
||||
{
|
||||
"name": "CODEMAN_API_URL",
|
||||
"description": "Where your Codeman server runs, for example https://127.0.0.1:3000. Never guessed.",
|
||||
"isRequired": true,
|
||||
"format": "string"
|
||||
},
|
||||
{
|
||||
"name": "CODEMAN_PASSWORD",
|
||||
"description": "Codeman's HTTP Basic password, when the server has one.",
|
||||
"isRequired": false,
|
||||
"isSecret": true,
|
||||
"format": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/tab-rail-resize.browser.test.ts',
|
||||
'test/tab-activation.browser.test.ts',
|
||||
'test/tab-layout-editing.browser.test.ts',
|
||||
'test/tab-rail-search.browser.test.ts',
|
||||
'test/tab-focus.browser.test.ts',
|
||||
'test/session-sidebar-ux.browser.test.ts',
|
||||
'test/session-options-responsive.browser.test.ts',
|
||||
'test/inline-rename.test.ts',
|
||||
@@ -33,6 +35,8 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/capture-geometry-retry.browser.test.ts',
|
||||
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
|
||||
'test/split-pane-terminal.browser.test.ts',
|
||||
'test/terminal-tile-scroll.browser.test.ts',
|
||||
'test/terminal-touch-paging.browser.test.ts',
|
||||
'test/shift-enter-keypress.browser.test.ts',
|
||||
'test/key-tester.browser.test.ts',
|
||||
'test/webhook-settings.browser.test.ts',
|
||||
@@ -41,7 +45,11 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/git-status.browser.test.ts',
|
||||
'test/split-pane-orchestration.browser.test.ts',
|
||||
'test/split-pane-auto-collapse.browser.test.ts',
|
||||
'test/spreadsheet-preview.browser.test.ts',
|
||||
'test/mobile-ime-preview.browser.test.ts',
|
||||
'test/run-mode-menu-scroll.browser.test.ts',
|
||||
'test/markdown-anchor-links.browser.test.ts',
|
||||
'test/fullscreen-tab-switch-capture.browser.test.ts',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -43,8 +43,16 @@ payload return `{ "success": true, "data": {} }`.
|
||||
|
||||
> Non-JSON endpoints are exempt from the envelope: `GET /api/sessions/:id/file-raw`,
|
||||
> `GET /api/sessions/:id/tail-file` (SSE), `GET /api/download`,
|
||||
> `GET /api/screenshots/:name`, `GET /q/:code` (QR redirect), and the
|
||||
> `GET /ws/sessions/:id/terminal` WebSocket upgrade.
|
||||
> `GET /api/screenshots/:name`, `GET /q/:code` (QR redirect),
|
||||
> `GET /html-view/:cap/*` (a [rendered HTML file](#rendered-html-files) and its
|
||||
> assets), and the `GET /ws/sessions/:id/terminal` WebSocket upgrade.
|
||||
>
|
||||
> **Deprecated:** `POST /api/screenshots`, `GET /api/screenshots` and
|
||||
> `GET /api/screenshots/:name` keep working but log a one-time warning on first
|
||||
> use. They are removed in a later MAJOR, after at least one MINOR release that
|
||||
> carries this warning (see `docs/versioning-policy.md`). To hand
|
||||
> a file to an agent, use `POST /api/sessions/:id/paste-image`, which saves it into
|
||||
> that session's workspace.
|
||||
|
||||
> The [agent wait endpoints](#long-polling-agent-wait) use the normal envelope but
|
||||
> are the only JSON endpoints that deliberately **hold the connection open**, for up
|
||||
@@ -80,6 +88,93 @@ the HTTP status.
|
||||
|
||||
Adding a new error code is non-breaking; removing or renaming one is a major change.
|
||||
|
||||
## Cron jobs
|
||||
|
||||
Saved jobs and their launch history are separate from the legacy `/api/scheduled`
|
||||
duration-bounded loops. Use `/api/v1/cron/...` in external clients; `/api/cron/...`
|
||||
is the unversioned alias. These routes use the response envelope above; the table
|
||||
lists the value inside `data` on success.
|
||||
|
||||
| Method | Path | Request body | Response `data` |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/api/v1/cron/jobs` | None | `CronJob[]` |
|
||||
| POST | `/api/v1/cron/jobs` | Full job definition below | `{ job: CronJob }` |
|
||||
| GET | `/api/v1/cron/jobs/:id` | None | `CronJob` |
|
||||
| PUT | `/api/v1/cron/jobs/:id` | Partial job definition | `{ job: CronJob }` |
|
||||
| DELETE | `/api/v1/cron/jobs/:id` | None | `{}` |
|
||||
| PUT | `/api/v1/cron/jobs/:id/enabled` | `{ enabled: boolean }` | `{ job: CronJob }` |
|
||||
| POST | `/api/v1/cron/jobs/:id/run` | None | `{ run: CronJobRun, activeAgents: number }` |
|
||||
| GET | `/api/v1/cron/jobs/:id/runs` | None | `CronJobRun[]` |
|
||||
| GET | `/api/v1/cron/runs` | None | `CronJobRun[]` |
|
||||
|
||||
### Job request fields
|
||||
|
||||
The create body requires `name`, `agentType`, `workingDir`, `promptMode`,
|
||||
`inputMode`, `scheduleType`, `enabled`, and `concurrencyPolicy`. Additional fields
|
||||
are required according to the selected prompt and schedule:
|
||||
|
||||
| Field | Type / validation |
|
||||
| --- | --- |
|
||||
| `name` | String, 1–200 characters |
|
||||
| `agentType` | A supported session mode (including `shell`) |
|
||||
| `workingDir` | Existing, allowed working-directory path |
|
||||
| `launchCommand` | Optional single-line string, at most 2000 characters; for shell jobs |
|
||||
| `promptMode` | `inline_text` or `prompt_file_path` |
|
||||
| `promptText` | Required for `inline_text`; nonempty single-line string, at most 100000 characters |
|
||||
| `promptFilePath` | Required for `prompt_file_path`; absolute path inside `workingDir` to a regular file, at most 1 MiB, read when the job fires |
|
||||
| `inputMode` | `paste` or `typed` |
|
||||
| `scheduleType` | `once`, `interval`, `daily`, or `weekly` |
|
||||
| `runAt` | Required for `once`; positive integer Unix timestamp in milliseconds |
|
||||
| `intervalMinutes` | Required for `interval`; integer from 1 to 525600 |
|
||||
| `dailyTime` | Required for `daily`; `HH:MM` in server-local time |
|
||||
| `weeklyDays` | Required for `weekly`; 1–7 weekday integers, 0 (Sunday) through 6 (Saturday) |
|
||||
| `weeklyTime` | Required for `weekly`; `HH:MM` in server-local time |
|
||||
| `enabled` | Boolean |
|
||||
| `concurrencyPolicy` | `warn_only` or `skip_if_same_agent_running`; scheduled runs only |
|
||||
| `autoClosePreviousSession` | Optional boolean, default `true`; ignored for `once` |
|
||||
| `notes` | Optional string, at most 2000 characters |
|
||||
|
||||
`PUT /jobs/:id` accepts any subset of these fields, then validates the merged job.
|
||||
When changing `promptMode` or `scheduleType`, supply the fields the new mode needs.
|
||||
`Run Now` works even when the job is disabled, bypasses the scheduled concurrency
|
||||
policy, and does not change the schedule. `activeAgents` counts live sessions of
|
||||
the same agent type, excluding sessions created by this job.
|
||||
For recurring jobs with `autoClosePreviousSession` enabled (the default), `Run Now`
|
||||
also closes the previous run's session before launching, even if it is still working.
|
||||
|
||||
### Job and run response fields
|
||||
|
||||
`CronJob` contains the request fields plus server-maintained `id`, optional
|
||||
`owner` (multi-user mode), `createdAt`, `updatedAt`, `lastRunAt`, `nextRunAt`,
|
||||
`lastStatus`, `lastDueKey`, and optional `completedOnce`. Times are Unix
|
||||
milliseconds; `lastRunAt`, `nextRunAt`, `lastStatus`, and `lastDueKey` can be `null`.
|
||||
`lastDueKey` is an opaque internal duplicate-launch guard, not a stable API format.
|
||||
|
||||
`CronJobRun` contains `id`, `cronJobId`, nullable `sessionId` and `sessionName`,
|
||||
`startedAt`, nullable `finishedAt`, `status`, optional `errorMessage`,
|
||||
`triggerType` (`scheduled` or `manual_run_now`), and nullable `createdSessionUrl`.
|
||||
Run times are also Unix milliseconds. Status is one of `created`,
|
||||
`session_started`, `prompt_sent`, `failed`, or `skipped`.
|
||||
|
||||
Prompt delivery continues asynchronously after session launch, so `Run Now` can
|
||||
return `session_started` before the prompt is sent. Read run history for subsequent
|
||||
updates, but do not assume a terminal status will follow: if the session is closed
|
||||
during the readiness wait or the server restarts before delivery, the run can remain
|
||||
`session_started` indefinitely with `finishedAt: null`.
|
||||
`finishedAt` refers to the launch/prompt-delivery attempt, **not completion
|
||||
of the agent's task**; `prompt_sent` does not prove that the task succeeded.
|
||||
|
||||
In multi-user mode, list/history endpoints filter to accessible jobs. An unknown
|
||||
or inaccessible job returns `NOT_FOUND`. Job creation and updates can return
|
||||
`403 FORBIDDEN` for a working directory outside the owner's workspace or a shell /
|
||||
launch-command job without the required privilege grant. Invalid definitions or
|
||||
working directories return `INVALID_INPUT`; launch/delivery failures are recorded
|
||||
on the run, so inspect its `status` and `errorMessage` even after an HTTP success.
|
||||
|
||||
See [Cron Jobs](wiki/Cron-Jobs.md) for the UI, scheduling, and prompt-file rules.
|
||||
See the [complete cron guide](cron-guide.md) for the `cron:runCreated` and
|
||||
`cron:runUpdated` SSE events.
|
||||
|
||||
## Long-polling (agent wait)
|
||||
|
||||
Three calls block until something happens instead of answering immediately. They
|
||||
@@ -449,15 +544,105 @@ client that opens many concurrent waits against one session will still hit the c
|
||||
|
||||
What a session's terminal shows, for a client to replay: `data.terminalBuffer`,
|
||||
with `source` (`mux-visible`, `mux-full-history` or `history`), `truncated`,
|
||||
`truncationReason`, `fullSize`, and `captureCols`/`captureRows` when the pane's
|
||||
geometry was read. The capture runs synchronous tmux calls on the server; the
|
||||
`truncationReason`, `fullSize`, `historyLinesCut` (a `lines=` bound left older
|
||||
lines in tmux, so the remainder is more than `fullSize - retainedBytes`), and
|
||||
`captureCols`/`captureRows` when the pane's geometry was read. `paneHistoryLines`
|
||||
(present when the body is a pane capture whose geometry was read, like
|
||||
`captureCols`/`captureRows`, and absent for a remote SSH session, whose local pane
|
||||
cannot see the remote history) is the number of scrollback rows tmux holds above the
|
||||
visible frame, which is the most a `full=1` request can add. `truncated` describes
|
||||
the byte stream instead: for a pane with `paneHistoryLines: 0` (a fullscreen CLI in
|
||||
the alternate screen) the bytes a `tail` cut dropped are earlier repaints that no
|
||||
request returns. The capture runs synchronous tmux calls on the server; the
|
||||
`Server-Timing` header reports `capture`, `prepare` and `total`.
|
||||
|
||||
| Query | Meaning |
|
||||
|---|---|
|
||||
| `full=1` | tmux's scrollback, not only the visible frame (`source: 'mux-full-history'`), ending with a relative cursor move back to the pane's caret. |
|
||||
| `tail=<bytes>` | Keep the newest `<bytes>` of the result (`truncationReason: 'tail'` when it cut). |
|
||||
| `lines=<n>` | With `full=1` only: read at most `<n>` lines of tmux history above the visible frame. An integer of at least 1, clamped to the configured history limit; absent or malformed, the whole limit (100,000 lines by default), as before. `truncated` and `truncationReason` describe byte cuts only, not this bound. Without it a full capture reads all of that history before `tail` cuts it, so a client that keeps a fixed number of lines (the tile grid sends its xterm's scrollback plus its rows) should send it. |
|
||||
| `lines=<n>` | With `full=1` only: read at most `<n>` lines of tmux history above the visible frame. An integer of at least 1, clamped to the configured history limit; absent or malformed, the whole limit (100,000 lines by default), as before. When a bound below the configured limit left older lines in tmux (its `history_size` is deeper), `truncated` is true with `truncationReason: 'tail'`; a byte cap still reports `'capped'`. Without it a full capture reads all of that history before `tail` cuts it, so a client that keeps a fixed number of lines (the tile grid sends its xterm's scrollback plus its rows) should send it. |
|
||||
| `alt=recording` | With `full=1` only: if the pane is in the alternate screen (a nested tmux, where tmux keeps no history, or any full-screen app such as vim or less while it is open), answer with the visible frame over the byte recording instead (`source: 'mux-visible'`, `tail` applied as without `full=1`). Shells' automatic loads send it. |
|
||||
|
||||
## The `codeman agent` CLI (client over these endpoints)
|
||||
|
||||
`codeman agent ls|spawn|send|wait|read|interrupt|rm` (`src/cli-agent.ts`) is the command-line client for the endpoints above, for agents the skill does not reach (a pi or shell session, a machine without `jq`). It adds no route: `spawn` is `POST /api/v1/quick-start` (+ `wait-output` on the mode's `capabilities.composerReadyMark` from the CLI registry, where it declares one), `send` is `POST …/input` with `clientId`+`seq` (and `wait`/`waitTimeout` for `--wait` / `--until <signals>`; `delivered:false` without `duplicate` and `wait.ended` both exit 3 — the CLI never reports a dead worker as done), `wait` is `GET …/wait` (`--until`) or `GET …/wait-output` (`--match`, `from=buffer` by default), `read` is `GET …/last-response` or `GET …/terminal?tail=`, `interrupt` is `POST …/input` with a bare `\u001b`, `rm` is `DELETE …/sessions/:id`. A fire-and-forget `send` to a sleeping wake-on-LAN host reads the route's `buffered` (own line, exit 0) and `dropped` (exit 1: the chunk is gone). An id may be the 8-character form `ls` prints, resolved through `GET /api/v1/sessions`; anything shorter refuses before any request, the same floor as `PARENT_SESSION_ID_MIN_PREFIX`. Every call carries `X-Codeman-Parent-Session`; only `spawn`'s quick-start carries `X-Codeman-Agent-Origin: codeman-agent-cli` (the agent-scratch label must never reach a request that cannot create the case directory). Basic auth comes from `CODEMAN_PASSWORD` or the data dir's `.env`. Server-side error codes are shown verbatim (`INVALID_INPUT: until=stop …` on a hook-less mode is not hidden); exit codes are `0` ok, `1` error, `2` timeout, `3` the session exited, `4` refused by a client-side guard. See the README section "`codeman agent`" for the guards and `test/cli-agent.test.ts` for the pinned behaviour.
|
||||
|
||||
`codeman mcp` (`src/mcp-server.ts`) is a Model Context Protocol server on stdio over the same endpoints, for MCP clients: `list_sessions` (`GET /api/v1/sessions`), `start_session` (`POST /api/v1/quick-start` with `X-Codeman-Agent-Origin: codeman-mcp`, then `wait-output` on the mode's ready mark), `send_prompt` (`POST …/input` with `wait`/`waitTimeout`), `wait_for_session` (`GET …/wait` or `…/wait-output`), `read_output` (`GET …/last-response` or `…/terminal?tail=`), `interrupt_session` and `delete_session`. It adds no route. The URL comes from `CODEMAN_API_URL` or `--url`, never a guess; prompting, interrupting and deleting are limited to sessions the process started (or the calling session's own children) unless it runs with `--allow-any-session`. See the README section "MCP server" and `test/mcp-server.test.ts`.
|
||||
|
||||
## Prompt uploads (`POST /api/v1/sessions/:id/paste-image`)
|
||||
|
||||
A `multipart/form-data` body with one `image` part. The file is written into the
|
||||
session's workspace as `<workingDir>/.codeman-uploads/paste-<ms>-<hex>.<ext>`, and
|
||||
`data` carries `path` and `filename` for the client to type the path into the
|
||||
prompt. The folder is Codeman's own: hidden, created on first use with a
|
||||
`.gitignore` containing `*` (written once, never over a file already there), and
|
||||
cleaned up the way pasted images always were: `paste-*` files older than 7 days
|
||||
go in an hourly sweep, and the folder goes when the last session of that
|
||||
workspace is killed. Uploads made before this release sit in `.claude-images/`;
|
||||
that folder receives nothing new, and is swept and removed the same way for one
|
||||
release. A remote (SSH) session answers 400, since the file would land on the
|
||||
Codeman host under a path the remote agent cannot read. A Docker session of an
|
||||
owned case is fine, its workspace is bind-mounted at the same absolute path; an
|
||||
adopted container (`owned: false`) mounts nothing, so its agent can open the file
|
||||
only if the container itself exposes that host path.
|
||||
|
||||
The optional query flag `?kind=video` selects a second path for a camera-roll
|
||||
video: the file streams to disk instead of being buffered, under a far larger
|
||||
per-file cap (`MAX_PASTE_VIDEO_BYTES`, 1 GB by default, env
|
||||
`CODEMAN_MAX_PASTE_VIDEO_BYTES`), and only video container types are accepted
|
||||
(mp4, webm, mov, m4v, ogv, single-sourced from the file viewer's playable set).
|
||||
The container is checked from the first bytes as
|
||||
the body arrives; a file whose bytes do not match its declared type is unlinked
|
||||
and answered 415, one over the cap is unlinked and answered 413, and a transfer
|
||||
that dies midway leaves nothing behind. Because one video can be 1 GB,
|
||||
`?kind=video` draws on its own rate limit, 3 uploads per minute per (IP, session),
|
||||
beside the 30 per minute the image path keeps; without the flag the route is
|
||||
byte-identical to the image-only version, same 50 MB image cap and same 30/min
|
||||
bucket. The response shape is unchanged (`path`, `filename`).
|
||||
|
||||
## Rendered HTML files
|
||||
|
||||
An `.html`/`.htm` file renders as a page in a sandbox, in two steps
|
||||
(`src/web/routes/html-view-routes.ts`).
|
||||
|
||||
**`POST /api/v1/sessions/:id/html-view`** with `{ "path": "<file>" }` (absolute,
|
||||
relative to the session's workspace, or `~/` for this host's home, which a Docker
|
||||
case refuses with `400` since its `~` is the container's; a non-empty string of at most 4096 characters
|
||||
without NUL or line breaks, and no other keys) answers `data: { url }`, a
|
||||
`/html-view/<cap>/<file>` URL. The capability grants GET access to the files under
|
||||
that file's own folder, so a page's relative CSS, scripts, images and data files
|
||||
resolve. It is held in memory only (a restart invalidates it), has a rolling TTL
|
||||
(`CODEMAN_WEBVIEW_CAPABILITY_TTL_MS`, default 12 h), is reused for the same folder,
|
||||
and is revoked on logout, admin logout and user deletion. Refusals:
|
||||
|
||||
- `400`: an invalid body, a remote (SSH) session, or a file that is not HTML (the
|
||||
symlink-resolved name counts too);
|
||||
- `404`: no such file;
|
||||
- `403`: a file outside the workspace that the attachment guard blocks (a blocked
|
||||
tree, or `attachmentConfineToWorkspace` on), a file in a hidden directory (inside
|
||||
the workspace, one below the workspace root), or a file directly in a folder too
|
||||
broad to serve recursively: `/`, the home folder, `/tmp`, `/var/tmp`, `$TMPDIR`,
|
||||
the cases and user-space roots, a drive's mount point (`/mnt/d`), or any folder
|
||||
above one of those (`/home`, `/Users`).
|
||||
|
||||
**`GET /html-view/:cap/*`** serves the page and its assets. It needs no cookie: the
|
||||
capability in the path is the credential, because the page runs in an opaque origin
|
||||
that never sends one. It is not under `/api`, so it has no `/api/v1` alias and no
|
||||
envelope. `GET` and `HEAD` only; a CORS preflight on a live capability is answered
|
||||
with `Access-Control-Allow-Methods: GET, HEAD`. What it serves: files under the
|
||||
capability's folder whose path (requested and symlink-resolved) has no dot segment
|
||||
and whose extension is on an asset allowlist (html, css, js/mjs, json, map, txt,
|
||||
csv, md, svg and common image, font, wasm, audio, video and PDF types), never
|
||||
outside the folder, never a blocked tree, and, for a folder outside the workspace,
|
||||
not while `attachmentConfineToWorkspace` is on. Every response carries
|
||||
`Content-Security-Policy: sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads`
|
||||
as its whole policy (never `allow-same-origin`, so the page cannot read Codeman's
|
||||
document, cookies or API, even opened as a top-level tab; and no fetch directive, so
|
||||
by the owner's decision the page may load from and send requests to any host), `Cache-Control: no-store`,
|
||||
`Referrer-Policy: no-referrer` and `Access-Control-Allow-Origin: *`. A `Range`
|
||||
request is answered with `206` + `Content-Range` (`416` past the end), like
|
||||
`file-raw`. Every refusal is a plain-text `404 Not found`; with a password set, an
|
||||
unknown or revoked capability is the auth hook's `401` instead.
|
||||
|
||||
## Session lineage (`parentSessionId`)
|
||||
|
||||
@@ -510,6 +695,52 @@ most 64 characters, but treat it as untrusted text. A `statusline` or `screen` v
|
||||
persisted and restored after a server restart until the next report replaces it; a
|
||||
`config` value is read again at every pane start, attach and relaunch instead.
|
||||
|
||||
## Prompt cache (`promptCache`)
|
||||
|
||||
Claude-mode session state (`GET /api/v1/sessions`) carries the main conversation's
|
||||
prompt-cache state as Claude Code last reported it on the statusline (v2.1.251+), with a
|
||||
change-only `session:promptCache` event (`{ sessionId, ...promptCache }`):
|
||||
|
||||
```json
|
||||
"promptCache": { "warm": true, "ttl": "1h", "expiresAt": 1791653039000, "recacheTokensIfCold": 45000, "misses": 2, "expectedRebuilds": 1, "hitRatio": 0.91, "lastMissCauses": ["ttl_expired_1h"], "compactedAt": 1791649439872 }
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| --------------------- | --------------------------------------------------------------------------------------------------------- |
|
||||
| `warm` | Whether the cached prefix is still within its TTL. The only field always present. |
|
||||
| `ttl` | `5m` or `1h`; absent when Claude reported neither. |
|
||||
| `expiresAt` | Epoch MILLISECONDS when the prefix goes cold (the statusline reports seconds). Absent once cold. |
|
||||
| `recacheTokensIfCold` | Tokens the next request re-writes if the cache has gone cold. Absent right after a compaction. |
|
||||
| `misses` | Requests that re-processed content the cache already held. |
|
||||
| `expectedRebuilds` | Cache rebuilds that followed a compaction or a clearing of old tool results. |
|
||||
| `hitRatio` | Cache read tokens as a fraction of all input tokens this session, 0 to 1. |
|
||||
| `lastMissCauses` | Claude Code's diagnosis of the last miss (e.g. `ttl_expired_1h`, `tools_changed`); untrusted text. |
|
||||
| `compactedAt` | Epoch MILLISECONDS when the context was compacted or its old tool results cleared: the first warm report without `recacheTokensIfCold` after one that had it. Derived, not reported; dropped at the next request. |
|
||||
|
||||
The whole object is absent until the first report, and restored after a server restart
|
||||
(so the readout is not blank until the pane's next render) rather than recomputed; a value
|
||||
whose `expiresAt` has passed reads as cold. The statusline re-runs when a warm cache hits
|
||||
`expiresAt`, so the cold flip arrives on its own. A post-`/clear` conversation switch drops
|
||||
it. Shown in Session Options → Respawn and, for sessions without a statusline of their own,
|
||||
as a `cache:until HH:MM` / `cache:cold` group in the terminal footer.
|
||||
|
||||
Beside it, `statusLineExporter` says whether this launch carries the statusline exporter
|
||||
that sends the report, decided when the pane starts: `injected` (it does), `collection-off`
|
||||
(Plan Usage was off at launch), `workspace-statusline` (the workspace's
|
||||
`.claude/settings.local.json` sets its own `statusLine`, which Codeman never replaces) or
|
||||
`remote` (remote and Docker sessions). Absent when unknown.
|
||||
|
||||
## Placing a new session in a tab group (`tabGroupId`)
|
||||
|
||||
`POST /api/v1/sessions` and `POST /api/v1/quick-start` accept an optional
|
||||
`tabGroupId` (1 to 100 characters): the id of a group in the caller's tab layout
|
||||
(`GET /api/v1/tab-layout`). The session is created as usual and placed at the end
|
||||
of that group in the same layout write; the response then also carries the
|
||||
committed layout as `tabLayout`. An id the caller's layout does not contain (a
|
||||
deleted group, another user's group) is ignored and the session lands where it
|
||||
otherwise would, never a `400`. A malformed value (`null`, an empty string, a
|
||||
non-string) is a `400 INVALID_INPUT`. Requests without the field are unchanged.
|
||||
|
||||
## Approvals Inbox
|
||||
|
||||
Cross-session queue of prompts waiting on a human (permission dialogs,
|
||||
@@ -764,11 +995,13 @@ Admin only in multi-user mode (`403`), like `POST /api/cases/link`: it writes ou
|
||||
**Which repositories.** git finds a repository by walking *up* from the session's working directory, so:
|
||||
|
||||
- Inside a repository (or at its root): that one repository, whole (a subfolder reports its enclosing repo, `path` says where it is, e.g. `../..`). A nested repo below it is just an untracked folder to the outer one and is not scanned; start the session inside it to see it.
|
||||
- **Not** inside one (a folder that holds several projects): every repository found up to **two levels down**, nearest and alphabetical first, at most 12 (`reposTruncated` says when there were more). Dot-folders, `node_modules`, `dist`, `build`, `target`, `vendor`, `venv` and `__pycache__` are skipped, symlinks are never followed, and a repository's own contents are not searched. The list of repositories is re-scanned at most every 30 s; each repository's status is cached for 4 s.
|
||||
- **Not** inside one (a folder that holds several projects): every repository found up to **two levels down**, nearest and alphabetical first, at most `maxRepos` of them (default 12, 1 to 50; `reposTruncated` says when there were more and `repoLimit` is the limit that was applied). Dot-folders, `node_modules`, `dist`, `build`, `target`, `vendor`, `venv` and `__pycache__` are skipped, symlinks are never followed, and a repository's own contents are not searched. The list of repositories is re-scanned at most every 30 s; each repository's status is cached for 4 s.
|
||||
- A repository that merely sits **above** the workspace and is the home folder or higher (a dotfiles repo in `$HOME`, or `/`) is ignored: its dirty files are not this session's work. A workspace that *is* that repository's root is not ignored.
|
||||
- A worktree (whose `.git` is a file) counts as a repository. A submodule's own uncommitted files are not reported, only a changed submodule pointer.
|
||||
|
||||
`data` is `{ state, repos, reposTruncated, checkedAt }`:
|
||||
Both routes accept two optional query parameters, which the UI sends from its per-device settings and the server clamps again: `maxRepos` (1 to 50, default 12) and `timeout` (seconds one git command may run, 5 to 120, default 30). An empty or non-numeric value means the default. A repository whose `git status` fails (typically a timeout on a slow network share) is **kept in `repos[]`** with `status.state: 'error'` and the reason in `status.error`, not dropped, so it is visible that something is not being reported.
|
||||
|
||||
`data` is `{ state, repos, reposTruncated, repoLimit, checkedAt }` (`repoLimit` in the folder-of-projects case only):
|
||||
|
||||
- `state: 'ok'`: `repos[]`, each `{ name, path, status }` where `name` is the repository folder's name, `path` its root relative to the working directory, and `status` is:
|
||||
`branch` (null when `detached`), `upstream`, `ahead`, `behind`, `hasRemote`, `counts` (`staged`, `unstaged`, `untracked`, `conflicted`, `uncommitted` = distinct paths, `stashes`), `files[]` (`path` relative to `repoRoot`, `origPath` for a rename, `index` and `worktree` status letters, `kind`: `staged` \| `unstaged` \| `untracked` \| `conflicted`; a file that is staged *and* modified again appears once per kind), `filesTruncated`, `unpushedCount` (exact) and `unpushed[]` (newest first: `hash`, `author`, `time` in epoch seconds, `subject`), `repoRoot`, `checkedAt`.
|
||||
@@ -803,10 +1036,10 @@ Copies MCP servers between the agent CLIs' own user-level config files (`docs/cl
|
||||
Result (`data`):
|
||||
|
||||
- `applied` — `false` for the dry run.
|
||||
- `targets[]` — one per enabled CLI that declares an MCP config: `id`, `label`, `file`, `status`, `error?`, `servers` (names it already has), `added` (names added, or that would be), `skipped` (names its dialect cannot express, e.g. SSE for Codex and Antigravity).
|
||||
- `targets[]` — one per enabled CLI that declares an MCP config, plus GitHub Copilot CLI (`id: "copilot"`, a sync-only target that is not a run mode): `id`, `label`, `file`, `status`, `error?`, `servers` (names it already has), `added` (names added, or that would be), `skipped` (names its dialect cannot express, e.g. SSE for Codex and Antigravity).
|
||||
- `status`: `ok`; `absent` (not installed and no config file, so not read or created); `skipped` (the CLI's relocation env var, e.g. `CODEX_HOME`, is set to a relative path in the server's environment, so its file cannot be located safely and is neither read nor written); `unreadable` (the file exists but cannot be parsed safely, so it is not written); `failed` (a read or write error, the file may be unchanged).
|
||||
- `error` says why a target is not `ok`. A parse failure is reported by position only (`not valid TOML (line 3, column 21)`, `not valid JSON`), never with text from the file.
|
||||
- `file` honours each CLI's own relocation env var as the server process sees it (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_CONFIG_HOME`, `GEMINI_CLI_HOME`); see `docs/cli-registry.md`.
|
||||
- `file` honours each CLI's own relocation env var as the server process sees it (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_CONFIG_HOME`, `GEMINI_CLI_HOME`, and `COPILOT_HOME` for the sync-only Copilot CLI); see `docs/cli-registry.md`.
|
||||
- `conflicts[]` — names defined differently by different CLIs. Existing definitions are kept; the first CLI's is copied where the name is missing.
|
||||
- `disabled[]` — names left out because every definition is switched off in its own CLI (codex `enabled = false`, opencode `enabled: false`, antigravity `disabled: true`).
|
||||
- `unsupported[]` — labels of enabled agent CLIs with no known MCP config file (nothing is guessed).
|
||||
|
||||
@@ -71,17 +71,23 @@ We tested three browser automation frameworks against the Codeman web UI:
|
||||
|
||||
## Test File Structure
|
||||
|
||||
### Port Allocation
|
||||
### Ports
|
||||
|
||||
| Port Range | Test File |
|
||||
|------------|-----------|
|
||||
| 3150-3153 | browser-e2e.test.ts (existing) |
|
||||
| 3154 | file-link-click.test.ts |
|
||||
| 3155 | browser-playwright.test.ts |
|
||||
| 3156 | browser-puppeteer.test.ts |
|
||||
| 3157 | browser-agent.test.ts |
|
||||
| 3158-3160 | browser-comparison.test.ts |
|
||||
| 3180-3182 | scripts/browser-comparison.mjs |
|
||||
A test that starts a server binds an ephemeral port, never a fixed one:
|
||||
|
||||
- `WebServer`: `new WebServer(0, false, true)`, then read the port the OS handed out from
|
||||
`server.boundPort` after `await server.start()`. `test/test-ports-guard.test.ts` fails
|
||||
any `WebServer` built under `test/` on a non-zero port.
|
||||
- A raw `http`, `net`, Fastify or `ws` server: `listen({ port: 0 })`, then
|
||||
`address().port`. The guard also fails a raw listen on a number or a `…PORT` constant.
|
||||
- The mobile suite (`test/mobile/**`) gets its server from `createTestServer()`, which
|
||||
binds an ephemeral port too; read it from `server.boundPort`.
|
||||
- The one exception is `test/codex-predictive-echo.test.ts`, which starts a separate lab
|
||||
server process on port 3222 that the guard cannot see.
|
||||
- Never port 3000: that is the live instance.
|
||||
|
||||
`scripts/browser-comparison.mjs` is a standalone script outside the guard and still uses
|
||||
fixed ports 3180-3182.
|
||||
|
||||
### File Purposes
|
||||
|
||||
@@ -106,7 +112,7 @@ const browser = await chromium.launch({
|
||||
});
|
||||
|
||||
const page = await browser.newPage();
|
||||
await page.goto('http://localhost:3000');
|
||||
await page.goto(BASE_URL);
|
||||
|
||||
// Auto-waiting selectors
|
||||
await page.click('.btn-claude');
|
||||
@@ -140,7 +146,7 @@ const browser = await puppeteer.launch({
|
||||
});
|
||||
|
||||
const page = await browser.newPage();
|
||||
await page.goto('http://localhost:3000');
|
||||
await page.goto(BASE_URL);
|
||||
|
||||
// Manual waiting often needed
|
||||
await page.click('.btn-claude');
|
||||
@@ -186,7 +192,7 @@ function agentBrowserJson<T>(cmd: string): T {
|
||||
}
|
||||
|
||||
// Usage
|
||||
agentBrowser('open http://localhost:3000');
|
||||
agentBrowser(`open ${BASE_URL}`);
|
||||
agentBrowser('click ".btn-claude"');
|
||||
const title = agentBrowserJson<{title: string}>('get title');
|
||||
|
||||
@@ -246,11 +252,14 @@ npx playwright install chromium
|
||||
### 4. Wait for Server Startup
|
||||
|
||||
```typescript
|
||||
const server = new WebServer(PORT);
|
||||
const server = new WebServer(0, false, true); // port 0 (the OS picks one), no TLS, testMode
|
||||
await server.start();
|
||||
await new Promise(r => setTimeout(r, 1000)); // Allow server to stabilize
|
||||
const BASE_URL = `http://localhost:${server.boundPort}`;
|
||||
```
|
||||
|
||||
`boundPort` holds the real port only once `start()` has resolved. The `BASE_URL` used by the
|
||||
other snippets on this page is this one.
|
||||
|
||||
### 5. Clean Up Sessions
|
||||
|
||||
Track created sessions for cleanup:
|
||||
|
||||
@@ -25,7 +25,7 @@ Every run mode Codeman can launch — Claude Code, Terminal/Shell, OpenCode, Cod
|
||||
App Settings → Agents & CLIs → **CLI management** (`cliManagementEnabled`, default OFF; admin-only in multi-user mode) lists every entry with an installed/not-installed badge and:
|
||||
|
||||
- toggles any entry on or off. A `kind: 'shell'` entry cannot be disabled, and the row shows no switch for it. A disabled CLI disappears from the Run menu, the welcome screen and the phone overview, and new session requests for it are rejected.
|
||||
- installs a missing **stock** CLI by running its shipped install command, after a confirm that names the exact command. Only one install per CLI runs at a time, and the command runs without any `CODEMAN_*` variable in its environment. A custom entry's install command is never executed.
|
||||
- installs a missing **stock** CLI by running its shipped install command, after a confirm that names the exact command. Only one install per CLI runs at a time, and the command runs without any `CODEMAN_*` variable in its environment. An `npm install -g` command is pointed at `~/.local` (which every resolver searches) when the npm global prefix is not writable by the server user, for example a system node under `/usr`; a writable prefix, a prefix that does not exist yet but could be created, and an explicit `NPM_CONFIG_PREFIX` are left alone. A custom entry's install command is never executed.
|
||||
- adds, edits and deletes **custom** entries (id, label, badge, binaries, launch argv). The server re-validates the whole assembled entry through `CliEntrySchema`, so the form cannot bypass the load-time rules.
|
||||
|
||||
These are the only writes to `clis.json`. They are serialized, and a file that does not parse or has unsafe permissions is refused rather than overwritten; fix it (or `chmod 600` it) and retry. The HTTP routes are listed in `docs/api-reference.md` under *CLI management*.
|
||||
@@ -36,7 +36,7 @@ These are the only writes to `clis.json`. They are serialized, and a file that d
|
||||
interface CliEntry {
|
||||
id: CliId; // 'codex'
|
||||
label: string; // 'Codex' — shown in menus
|
||||
shortBadge: string; // tab badge, e.g. 'CX'
|
||||
shortBadge: string; // short label ("Run CX", the Settings CLI list), e.g. 'CX'; tabs show the run-mode-dot logo instead (no mark at all with CLI Logos on Tabs off)
|
||||
accent: string; // single hex colour
|
||||
enabled: boolean;
|
||||
stock: boolean; // set by the loader; a custom entry can never claim it
|
||||
@@ -51,6 +51,9 @@ interface CliEntry {
|
||||
// that ended waiting for workers it will resume from
|
||||
// .modelDetect?: { screenLine, screenLines? }
|
||||
// (where this CLI's own chrome names the model it runs: SessionState.displayModel)
|
||||
// .launchDefaults?: { [launchParam]: settingsKey }
|
||||
// (synced App Settings that seed a LOCAL launch's params the caller left unset;
|
||||
// codex's model and reasoning effort, via src/web/launch-defaults.ts)
|
||||
overlays: CliOverlays; // remote-SSH / Docker pane commands, credential store
|
||||
}
|
||||
```
|
||||
@@ -63,7 +66,7 @@ Five capability fields carry a regular expression an override file can set: `dis
|
||||
|
||||
`workingLine` is the one that matters most, because it is compiled once per session and then run against every accumulated PTY chunk and every pane capture. A nested quantifier there is a ReDoS against the event loop for the whole server, not just that session. The guard therefore runs in two places, and neither is redundant: `schema.ts` rejects the entry at LOAD time so a bad pattern never reaches a session, and `_workingLinePattern()` in `session.ts` compiles through the same helper so the runtime cannot end up with a pattern the schema would have refused.
|
||||
|
||||
`modelDetect.screenLine` names the model a session runs, for the tile grid's and the split pane's headers (`SessionState.displayModel`). It must have exactly ONE capture group, the model, which `schema.ts` checks at LOAD time, and it runs over the last `screenLines` (1 to 4, default 1) non-blank rows of the capture the idle/working probe already takes, joined with newlines so a pattern can anchor on the row above. Like `watchingLine`, the rows are pane text the agent writes most of, so a pattern must anchor on chrome only that CLI draws. The two stock ones, measured on live panes: dsh-TUI's status line on the row under its composer's rounded border (`╰─+╯\n ?(<model>)`, three rows), and codex's ` <model> <effort> · ` footer on its last row. A screen that does not match keeps the last model the session reported; a CLI without the field shows its launch model, if any. Claude needs none: its statusLine exporter reports `model.display_name` on every render. ⚠️ dsh-TUI's first field is the model only while its status bar's model field is on; switched off, it is the next field: the reasoning effort (` medium · <cwd>`), the session mode, or the folder name. So a captured field is not taken when it is one of the CLI's declared `modelDetect.rejectWords` (single tokens, compared ignoring case; dsh lists every effort id its adapters offer and the shipped mode ids) or the session's own working-directory basename (the shared reader's rule, for every CLI). Anything else the pattern captures is the model, so the official `deepseek-chat` / `deepseek-reasoner` ids are read.
|
||||
`modelDetect.screenLine` names the model a session runs, for the tile grid's and the split pane's headers (`SessionState.displayModel`). It must have exactly ONE capture group, the model, which `schema.ts` checks at LOAD time, and it runs over the last `screenLines` (1 to 8, default 1) non-blank rows of the capture the idle/working probe already takes, joined with newlines so a pattern can anchor on the row above. Like `watchingLine`, the rows are pane text the agent writes most of, so a pattern must anchor on chrome only that CLI draws. The two stock ones, measured on live panes: dsh-TUI's status line on the row under its composer's rounded border (`╰─+╯\n ?(<model>)`, three rows), codex's ` <model> <effort> · ` footer (its last row, or the row above codex 0.162's indented hint row, so a two-row window), and opencode's composer agent row (`┃ Build <model> <provider>`, directly above the box's `╹` edge, eight rows because its home screen puts up to five rows of its own chrome below it). opencode's field is the model AND the provider, since only colour separates them on that row; the pattern takes the LAST such row in the window, so a composer-shaped row the agent prints higher up cannot stand in for it. A screen that does not match keeps the last model the session reported; a CLI without the field shows its launch model, if any. Claude needs none: its statusLine exporter reports `model.display_name` on every render. ⚠️ dsh-TUI's first field is the model only while its status bar's model field is on; switched off, it is the next field: the reasoning effort (` medium · <cwd>`), the session mode, or the folder name. So a captured field is not taken when it is one of the CLI's declared `modelDetect.rejectWords` (single tokens, compared ignoring case; dsh lists every effort id its adapters offer and the shipped mode ids) or the session's own working-directory basename (the shared reader's rule, for every CLI). Anything else the pattern captures is the model, so the official `deepseek-chat` / `deepseek-reasoner` ids are read.
|
||||
|
||||
`modelDetect.configResolver` names a READER in `src/model-config-resolvers.ts` (a name, never code in config, like a launcher profile) that resolves the model the CLI's own config pins for one session, for while its screen names none (the `config` source of `displayModel`, ranked below any report from the running CLI). It runs at every pane start, attach and relaunch, with the session's own launch config and env, and must be read-only, bounded (probe before read, no synchronous filesystem call) and return the model id alone. The one stock reader, `deepseek-route` (`src/deepseek-route-config.ts`), resolves dsh-TUI's route the way dsh composes it for the session's profile under the session's `DSH_HOME`: the last of `profiles/<profile>/cordis.patch.yml` and `$DSH_HOME/cordis.patch.yml` carrying `config` for the `dsh-tui` row counts, and only when it names both `provider` and `model`. Anything in doubt answers nothing: a half-pinned route, a profile without dsh-TUI, an unreadable, oversized or symlinked-out layer, a file beyond its narrow YAML subset.
|
||||
|
||||
@@ -81,10 +84,11 @@ Two CLIs declare such a row today, and they put it in different places. Claude w
|
||||
chip on the last row of the screen, so it keeps the default one-row window and anchors on
|
||||
the `·` its footer joins items with. Codex pins
|
||||
`1 background terminal running · /ps to view · /stop to close` ABOVE its composer, which
|
||||
puts the row third from the bottom once the status line and the composer are counted, so its
|
||||
entry declares `watchingLines: 3` and matches that row end to end. Both were measured
|
||||
against live panes rather than read out of a binary, which is the standard for adding a
|
||||
third.
|
||||
puts the row third from the bottom once the status line and the composer are counted, and
|
||||
fourth on codex 0.162+ at rest, where a `← for agents · ? for shortcuts` hint row sits under
|
||||
the status line (it disappears while a prompt is typed). So its entry declares
|
||||
`watchingLines: 4` and matches that row end to end. Both were measured against live panes
|
||||
rather than read out of a binary, which is the standard for adding a third.
|
||||
|
||||
`awaitingLine` covers the quiet pane that is neither idle nor watching: a turn that ENDED
|
||||
to wait for workers the CLI will resume from by itself. When background agents or an
|
||||
@@ -124,6 +128,18 @@ sure its row is one the agent cannot write.
|
||||
|
||||
`test/cli-capability-predicates.test.ts` asserts that no two of the three are equivalent across the catalog, so collapsing them fails the build rather than a user's session.
|
||||
|
||||
### Where the agent skill lands
|
||||
|
||||
`agentSkillInjection` says a CLI's sessions get the agent skill (`skills/codeman`) and its per-session preamble when the synced `agentSkillEnabled` setting is on; `agentSkillDir` says which workspace directory the CLI scans for skills, read through `agentSkillDir()` (hooks-config.ts), so no call site branches on a CLI id. Absent with the boolean on means `.claude/skills`, which is what the boolean meant before the field existed.
|
||||
|
||||
| CLI | Skill directory |
|
||||
| --- | --- |
|
||||
| claude | `.claude/skills/codeman` |
|
||||
| codex, gemini, opencode, antigravity, grok, deepseek, omp | `.agents/skills/codeman` |
|
||||
| pi, shell | none |
|
||||
|
||||
Measured 2026-10-11 against the installed builds or their source: every CLI in the middle row scans `<workspace>/.agents/skills/` (gemini only in its cwd, dsh only at the git root, else cwd), and Claude Code does not read it, so a case shared with a claude session lists the skill once there (opencode, grok and omp read both directories and see the same skill twice, identical, under one name). ⚠️ pi is left out on purpose: any project-level `.agents/skills` or `.pi/skills` makes pi ask "Trust project folder?" at startup, which would stall a spawned worker on a dialog; it reads the user-level `~/.agents/skills` without the prompt (`npx skills add Ark0N/Codeman --skill codeman -g`). A codex, gemini or other session's copy in a case that pi sessions also use triggers that prompt once for the human there. ⚠️ `agentSkillDir` is a closed enum (`AGENT_SKILL_DIRS`, schema.ts), never a free path: `clis.json` can set it and it decides where the server writes. ⚠️ Two codex traps the skill names rather than fixes: codex's default sandbox blocks network even to loopback (the skill needs **Bypass approvals and sandbox**), and codex 0.162 runs tool commands through a shared `app-server` daemon whose environment (`CODEMAN_SESSION_ID`, `CODEMAN_API_URL`) is that of the session that started it.
|
||||
|
||||
## The newline chord
|
||||
|
||||
`capabilities.newline` (`'line-feed'` | `'esc-enter'`, absent = line feed) is the byte sequence the `send-key` route types into the pane for Shift+Enter. A line feed (`0x0a`, also Ctrl+Enter) is what Claude Code's Ink input reads as "insert a newline"; `esc-enter` (`ESC CR`, the Option/Alt+Enter chord) is there for a composer that ignores a bare line feed. No stock CLI declares it today: the bytes are typed by tmux on the server, so the browser's OS cannot change what a CLI reads, and Codex 0.147.0 was checked to take a line feed (a Shift+Enter that submits is the keypress leak fixed in #520, not a byte problem). A user `clis.json` can set it for a CLI that needs it. It is an enum rather than a byte string on purpose: config never carries bytes that get typed into a pane. Settings → Terminal & Input → **Key tester** prints what a browser reports for keydown/keypress/keyup, to see whether a device is sending what you think.
|
||||
@@ -261,9 +277,11 @@ A module-level const freezes at first import, and the failure is asymmetric: a C
|
||||
|
||||
## MCP server sync
|
||||
|
||||
`capabilities.mcpConfig` (`{ path, format, relocation? }`, `path` relative to the home directory) names the file a CLI keeps its user-level MCP server list in and the dialect it is written in. `src/mcp-sync.ts` reads that list from every ENABLED CLI that declares one, and that is installed or already has the file (a CLI that is neither is reported `absent`, never created), and adds any server a CLI is missing from the others. It writes other tools' own config, so it is **opt-in**: `mcpSyncEnabled` (synced, default OFF) gates `GET`/`POST /api/mcp-sync` (403 while off) and the Settings → Agents & CLIs → MCP servers controls. Declared today for claude, gemini, codex, opencode and antigravity; every format was checked against what the CLI's own `mcp add` writes, except opencode's (documented, not installed to check). A CLI with no entry (pi, grok, omp, deepseek) is not guessed at: it is listed as `unsupported` in the result when enabled. Adding one is a registry entry plus a small adapter in `mcp-sync.ts`, and a verified fixture in `test/mcp-sync.test.ts`.
|
||||
`capabilities.mcpConfig` (`{ path, format, relocation? }`, `path` relative to the home directory) names the file a CLI keeps its user-level MCP server list in and the dialect it is written in. `src/mcp-sync.ts` reads that list from every ENABLED CLI that declares one, and that is installed or already has the file (a CLI that is neither is reported `absent`, never created), and adds any server a CLI is missing from the others. It writes other tools' own config, so it is **opt-in**: `mcpSyncEnabled` (synced, default OFF) gates `GET`/`POST /api/mcp-sync` (403 while off) and the Settings → Agents & CLIs → MCP servers controls. Declared today for claude, gemini, codex, opencode and antigravity (plus GitHub Copilot CLI as a sync-only target, below); every format was checked against what the CLI's own `mcp add` writes, except opencode's (documented, not installed to check). A CLI with no entry (pi, grok, omp, deepseek) is not guessed at: it is listed as `unsupported` in the result when enabled. Adding one is a registry entry plus a small adapter in `mcp-sync.ts`, and a verified fixture in `test/mcp-sync.test.ts`.
|
||||
|
||||
`relocation` (`{ envVar, path }`) names the env var the CLI itself reads to move that file: claude `CLAUDE_CONFIG_DIR` (`.claude.json` under it), codex `CODEX_HOME` (`config.toml`), opencode `XDG_CONFIG_HOME` (`opencode/opencode.json`) and gemini `GEMINI_CLI_HOME` (`.gemini/settings.json`); antigravity follows `$HOME` only, so it declares none. The var is read from the SERVER process env at call time, which is the env the CLIs Codeman spawns inherit. An absolute value moves the file to `<value>/<relocation.path>`, an empty one counts as unset (as it does for each CLI), and anything else reports the target `skipped` with the reason instead of writing a file the CLI never reads. A per-session relocation (a session's own `CLAUDE_CONFIG_DIR` in `envOverrides`) is not followed: the sync only knows the server's environment.
|
||||
**Tools that are not run modes.** GitHub Copilot CLI keeps an MCP list worth syncing but Codeman does not launch it, so it has no registry entry. `src/mcp-sync-targets.ts` declares such tools as plain data (`MCP_SYNC_ONLY_TOOLS`: id, label, config path, dialect, relocation var, the binary whose presence means "installed"). They join the registry CLIs as sync targets (listed after them, so a registry CLI's definition wins a same-name difference), under the same rules: installed or already configured, otherwise `absent`. Copilot's dialect is `copilot-json` (`~/.copilot/mcp-config.json`, relocated by `COPILOT_HOME`; checked against `copilot mcp add` 1.0.94): `mcpServers`, each entry with `tools` (`["*"]` = all), `type` `local` | `http` | `sse`, `command`/`args`/`env` or `url`/`headers`. `copilot mcp disable` does not mark the entry: it lists the name under `disabledMcpServers` in `settings.json` beside the config. Sync reads that list (never writes it) so a disabled server is not copied, and reports the target `unreadable` if `settings.json` is not valid JSON rather than guessing.
|
||||
|
||||
`relocation` (`{ envVar, path }`) names the env var the CLI itself reads to move that file: claude `CLAUDE_CONFIG_DIR` (`.claude.json` under it), codex `CODEX_HOME` (`config.toml`), opencode `XDG_CONFIG_HOME` (`opencode/opencode.json`), gemini `GEMINI_CLI_HOME` (`.gemini/settings.json`) and, for the sync-only Copilot CLI, `COPILOT_HOME` (`mcp-config.json`); antigravity follows `$HOME` only, so it declares none. The var is read from the SERVER process env at call time, which is the env the CLIs Codeman spawns inherit. An absolute value moves the file to `<value>/<relocation.path>`, an empty one counts as unset (as it does for each CLI), and anything else reports the target `skipped` with the reason instead of writing a file the CLI never reads. A per-session relocation (a session's own `CLAUDE_CONFIG_DIR` in `envOverrides`) is not followed: the sync only knows the server's environment.
|
||||
|
||||
The rules the module keeps and the tests pin: it only ADDS (a name already defined, in any shape, is never edited or removed; a same-name difference is reported as a conflict); a server switched off in its own CLI is not copied; it never writes a file it could not parse (opencode JSONC with comments, a TOML file with a duplicate table) and re-parses the new text before writing; codex TOML is read with a real parser (`smol-toml`), so CRLF files and inline tables are handled; names such as `__proto__` are ignored and every table keyed by an untrusted name has no prototype; a symlinked config is written through, not replaced; a file that receives `env`/`headers` is left `0600`; only one apply runs at a time; and its result carries server names only, never env values or headers, and never file text: a parse failure is reported by line and column, not by the parser's message (smol-toml prints a code frame of the offending lines and V8's JSON errors quote source, either of which can hold a secret). The schema restricts `path` and `relocation.path` to a relative path without `..`, since sync writes to it.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ spin up a Claude (or shell / OpenCode / Codex / Antigravity / Gemini / Pi) sessi
|
||||
feed it a prompt. Think "cron for agent sessions": _"every weekday at 3am, open a
|
||||
Claude session in `~/proj` and tell it to update dependencies and open a PR."_
|
||||
|
||||
- **UI**: the **⏰ Cron** button in the header → the Cron Jobs modal (`#cronModal`).
|
||||
- **UI**: the **⏰ Cron** button in the bottom toolbar → the Cron Jobs modal (`#cronModal`).
|
||||
- **API**: `/api/cron/jobs*` and `/api/cron/runs`.
|
||||
- **Code**: `src/cron/cron-service.ts`, `src/cron/cron-time.ts`, `src/cron/cron-input.ts`,
|
||||
types in `src/types/cron.ts`, routes in `src/web/routes/cron-routes.ts`,
|
||||
@@ -24,7 +24,7 @@ Claude session in `~/proj` and tell it to update dependencies and open a PR."_
|
||||
|
||||
### In the browser
|
||||
|
||||
1. Click **⏰ Cron** in the header.
|
||||
1. Click **⏰ Cron** in the bottom toolbar.
|
||||
2. Click **+ New Job**.
|
||||
3. Fill in a **name**, pick an **agent type** and **working directory**, choose a
|
||||
**prompt** (inline text or a file path), pick a **schedule**, and leave
|
||||
|
||||
@@ -163,9 +163,14 @@ respawn, Ralph, the orchestrator, search, and admin. Each route module carries a
|
||||
If the caller is an agent running _inside_ a Codeman session, install the packaged
|
||||
agent skill instead of teaching it these calls by hand: `skills/codeman` in the repo
|
||||
(`npx skills add Ark0N/Codeman --skill codeman -g`, or `codeman skill install
|
||||
[--case <name>]`, or the synced `agentSkillEnabled` App Setting for automatic
|
||||
per-case injection on Claude session create). The skill carries the guard, the
|
||||
safety rules, and verified wait/orchestration recipes.
|
||||
[--case <name>] [--mode <mode>]`, or the synced `agentSkillEnabled` App Setting for
|
||||
automatic per-case injection on session create, into the directory each CLI scans for
|
||||
skills). The skill carries the guard, the safety rules, and verified
|
||||
wait/orchestration recipes.
|
||||
|
||||
If the caller speaks the Model Context Protocol (Claude Desktop, Cursor, Codex, any MCP
|
||||
client), point it at `codeman mcp` instead: seven tools over these same endpoints,
|
||||
configured with `CODEMAN_API_URL`. See the README section "MCP server".
|
||||
|
||||
The common ones:
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 859 KiB |
|
After Width: | Height: | Size: 706 KiB |
|
After Width: | Height: | Size: 5.2 MiB |
|
After Width: | Height: | Size: 548 KiB |
|
After Width: | Height: | Size: 3.6 MiB |
|
After Width: | Height: | Size: 774 KiB |
|
After Width: | Height: | Size: 379 KiB |
|
Before Width: | Height: | Size: 583 KiB |
|
Before Width: | Height: | Size: 4.3 MiB |
|
Before Width: | Height: | Size: 207 KiB |
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 7.1 MiB |
@@ -0,0 +1,68 @@
|
||||
# Media assets: videos and GIFs
|
||||
|
||||
Codeman produces a lot of video: README GIFs, website loops, release-note clips, promo videos and their drafts, raw screen captures. This page says where each kind lives and which of them belong in git.
|
||||
|
||||
## The rule
|
||||
|
||||
**Only media that a public page embeds is pushed to GitHub. Everything else stays on the maintainer's machine, in the local media library.**
|
||||
|
||||
| Kind | Where it lives | On GitHub? |
|
||||
| --- | --- | --- |
|
||||
| GIFs the README, the wiki or a published article embeds | `docs/images/` on `master` | yes |
|
||||
| Release-note and media-kit clips | the orphan `design-assets` branch | yes, but never on `master` |
|
||||
| getcodeman.com videos and GIFs | `pr/website/assets/` (local, deployed to Cloudflare Pages) | no |
|
||||
| Masters, promo videos, drafts, shorts, feature clips, raw captures | `pr/media/` (the local media library) | no |
|
||||
| Remotion render inputs for the promo videos | `scripts/remotion/public/` on the unpushed promo branch | no |
|
||||
|
||||
`.gitignore` enforces it: `*.mp4`, `*.webm`, `*.mov`, `*.m4v`, `*.mkv`, `*.avi` and `*.gif` are ignored everywhere except `docs/images/*.gif`, plus `scripts/remotion/public/`, whose render inputs the promo branch tracks. A video that really must be committed needs `git add -f`, which makes the exception visible in review.
|
||||
|
||||
A GIF that leaves `docs/images/` stays in git history, so removing it does not shrink a clone. The rule keeps new weight out and the tree honest about what is actually used.
|
||||
|
||||
## Tracked GIFs (`docs/images/`)
|
||||
|
||||
| File | Embedded in | Shows |
|
||||
| --- | --- | --- |
|
||||
| `tiles-crt-stats-1600-20261010.gif` | README hero (en + zh-CN) | six live agents in the tile grid, powering on and off with the CRT animation, header stats on |
|
||||
| `tile-grid-20261009.gif` | README, Tile Grid section | the Tiles button opening six live sessions side by side, and closing them |
|
||||
| `zerolag-demo-20260728.gif` | README, wiki `Input-And-Voice`, `packages/xterm-zerolag-input/README.md`, CHANGELOG, getcodeman.com docs | instant local echo next to slow server echo, on two phones |
|
||||
| `codeman-tab-states-20261010.gif` | README, Tab Alerts section | annotated tab states: working, blocked on a question, idle |
|
||||
| `codeman-skill-crt-20261010.gif` | README, agent skill section | one prompt to Claude Code spawning and driving two worker sessions through the skill |
|
||||
| `subagent-demo-20260724.gif` | the "mission control" article on dev.to, Hashnode and Medium (hotlinked from `master`) | subagent windows fanning out |
|
||||
|
||||
Before removing one, search for hotlinks: `README*.md`, `docs/wiki/`, `packages/*/README.md`, `CHANGELOG.md`, the site (`pr/website/`), and published articles, which link `raw.githubusercontent.com/Ark0N/Codeman/master/docs/images/<file>` and break silently.
|
||||
|
||||
On 2026-10-13, seven GIFs that no page embedded left `docs/images/` and moved into the library: `codeman-demo.gif`, `codeman-skill-20261010.gif`, `subagent-demo-new.gif`, `subagent-demo-opt.gif`, `tab-alerts-glow-20260815.gif`, `tiles-crt-20261010.gif`, `tiles-crt-stats-20261010.gif`.
|
||||
|
||||
### Adding or replacing a README GIF
|
||||
|
||||
1. Keep the master (the lossless MP4 or the full-size GIF) in `pr/media/clips/<feature>/`, or in the project folder it came from.
|
||||
2. Commit only the size the README shows, named `<feature>-<YYYYMMDD>.gif`, and keep it lean: the current ones are 0.8 to 7 MB.
|
||||
3. A replaced GIF leaves `docs/images/` in the same commit, unless something outside the repo hotlinks it (see above).
|
||||
|
||||
## Website media (getcodeman.com)
|
||||
|
||||
The site is built and deployed from `pr/website/` (gitignored) with `pr/deploy-site.sh`. Its videos and GIFs sit in `pr/website/assets/` because that directory is what gets uploaded: they are web cuts (1280 to 1600 px wide, high CRF, posters next to them) derived from masters in the library. `pr/site-notes.md` records how each one was cut and from which master. A few superseded files stay deployed on purpose, so links that point at them keep resolving.
|
||||
|
||||
## Release notes and the media kit (`design-assets` branch)
|
||||
|
||||
GitHub releases and the Announcements discussions embed clips from the orphan `design-assets` branch (`release-1.40/`, `release-1.41/`, `media-kit-2026-10/`). They are referenced by a commit-pinned raw URL, so the branch can change later without breaking old notes, and none of it ever touches `master`.
|
||||
|
||||
## The local media library (`pr/media/`)
|
||||
|
||||
`pr/` is gitignored, so the library is never pushed. It holds every master, every finished promo cut and every superseded draft in one tree:
|
||||
|
||||
```
|
||||
pr/media/
|
||||
README.md curated guide: what each collection is, which cut is current, where it is published
|
||||
INVENTORY.md generated list of every file (size, length, resolution, fps, date, published-or-not)
|
||||
inventory.mjs regenerates INVENTORY.md: node pr/media/inventory.mjs
|
||||
videos/<production>/ finished promo videos; superseded renders in drafts/
|
||||
shorts/<episode>/ per-feature cuts of a promo; older sets in drafts/
|
||||
clips/<feature>/ feature loops and GIF masters (README / site / release clips start here)
|
||||
crt-gifs/ CRT tile-animation loops
|
||||
files-one-click-20261011/ the Files panel loop project (own README)
|
||||
screenshots-hq/ high-res stills and their capture masters
|
||||
raw-captures/ unedited screen recordings, safe to prune
|
||||
```
|
||||
|
||||
Two working directories keep files the library only archives, because tools read them from fixed paths: `pr/website/assets/` (the deploy upload) and the promo worktree's `scripts/remotion/public/` (Remotion's `staticFile()` inputs). Renders still land in `scripts/remotion/out/` and are filed into `pr/media/videos/<production>/` once checked. A finished render never goes to `tmp/`.
|
||||
@@ -158,7 +158,7 @@ Codeman now ships a global **Startup Mode** picker (App Settings, Claude CLI tab
|
||||
| `GET /api/away-digest` | Aggregate only owned sessions/events |
|
||||
| `GET /api/subagents`, workflow runs | Filter by owning session (`claudeSessionId -> session -> owner`); agents not attributable to any session: admin-only |
|
||||
| Push (`push-routes.ts`) | Subscription records currently carry NO identity (keyed by endpoint only): `subscribe` stamps `username`. All 8 `PUSH_EVENT_MAP` events are session-scoped, so routing = resolve owner from `data.sessionId`, deliver to that owner's (plus admins') subscriptions. Legacy identity-less subscriptions: admin-only delivery |
|
||||
| Screenshots `/api/screenshots` | Per-user subdir `~/.codeman/screenshots/<username>/` in multi-user mode. Note: `GET /:name` deliberately rejects `/` in names as traversal, so derive the subdir server-side from `req.authUser` and keep client-visible names flat |
|
||||
| Screenshots `/api/screenshots` (deprecated) | Deprecated: removed in a later MAJOR, so no per-user subdir is planned; the replacement `POST /api/sessions/:id/paste-image` is already session-scoped. Former plan: per-user subdir `~/.codeman/screenshots/<username>/` in multi-user mode. Note: `GET /:name` deliberately rejects `/` in names as traversal, so derive the subdir server-side from `req.authUser` and keep client-visible names flat |
|
||||
| Attachments | Already session-scoped; inherits the session owner check. `attachmentConfineToWorkspace` is a global, default-OFF setting today: in multi-user mode it is FORCED ON for non-admins regardless of the setting (their attachments must resolve inside their own space); the setting keeps meaning what it means for admins |
|
||||
| File routes (browse/preview) | Path allowlist adds: non-admin paths must resolve (realpath) inside their own space or their own sessions' workingDirs |
|
||||
| Settings (`settings.json`) | Global, admin-only writes in multi-user mode; reads allowed (per-device display keys stay in localStorage as today). Per-user server settings: out of scope v1 |
|
||||
@@ -228,7 +228,7 @@ These operate directly on `users.json` via `user-store.ts` (no server needed), h
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Default (no flag) | No behavior change. No new file reads on the hot path. All new fields optional in state |
|
||||
| State round-trip | `SessionState.owner`, `MuxSession.owner`, `CronJob.owner`, registry `owner` fields are optional; old state loads clean; new state loaded by an old build ignores unknown fields (existing tolerant parsing) |
|
||||
| Instance isolation | `users.json`, audit log, screenshots subdirs all via `dataPath()`; user spaces dir is shared across instances like `~/codeman-cases` is today (documented) |
|
||||
| Instance isolation | `users.json` and the audit log via `dataPath()`; user spaces dir is shared across instances like `~/codeman-cases` is today (documented) |
|
||||
| API versioning | HTTP API is internal per `docs/versioning-policy.md`; still, all changes are additive. Ship as a **minor** version |
|
||||
| Hooks | Unchanged (instance-level hook secret; owner resolved from the session) |
|
||||
|
||||
|
||||
@@ -163,9 +163,13 @@ remote user's home, so resolving locally would pin a stranger's id. See
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **No idle/completion hook.** Idle detection falls back to output-stabilization
|
||||
like every other external CLI. If omp ever ships a hooks system, a Codeman hook
|
||||
POSTing to `/api/hook-event` would be the highest-value follow-up.
|
||||
- **No idle/completion hook.** Idle detection reads the screen instead: the
|
||||
registry entry's `workDetect` names omp's `╰─` input row as the glyph that arms
|
||||
the idle check, and the status bar's spinner plus elapsed time (` ⠼ 14s > ⬢ …`)
|
||||
or the `⎋ Working…` row as the working line, measured on omp 18.8.6 and 18.0.11.
|
||||
Without it an omp session that had started a turn never left `busy`. If omp ever
|
||||
ships a hooks system, a Codeman hook POSTing to `/api/hook-event` would still be
|
||||
the highest-value follow-up.
|
||||
- **Killing a pane mid-turn loses the conversation for real.** `tmux kill-session`
|
||||
before an in-TUI `/exit` beats omp's own session-file flush — confirmed by direct
|
||||
testing (kill after a clean `/exit` resumes correctly; kill without `/exit` first
|
||||
|
||||
@@ -920,6 +920,8 @@ const mode = cmd.includes('opencode') ? 'opencode' : 'claude';
|
||||
|
||||
> **DEFERRED**: This entire phase (except `waitForOpenCodeReady()`) is out of MVP scope. Idle detection, ANSI content filter, working/busy state tracking, and token parsing are all deferred until we have real PTY output data from stable OpenCode sessions. Only the basic TUI ready detection from `waitForOpenCodeReady()` is needed for the MVP and is included in Phase 3.
|
||||
|
||||
> **Update 2026-10-09 (working/idle shipped, from measured data):** the registry entry now declares `capabilities.workDetect` for opencode, measured on a live opencode 1.3.0 pane (pane captures every 250-300 ms through real turns at 40, 60, 120 and 200 columns, plus the raw PTY stream). Every composer row starts with a `┃` bar, which arms the shared screen-probed idle check; a running turn puts an 8-cell knight-rider spinner (`⬝■■■■■■⬝ esc interrupt`) at the head of the footer row, redrawn about every 40 ms, and `[⬝■]{8}` is the working line. The label is not the anchor: tmux ships `esc` and `interrupt` as separate words joined by cursor moves, and below about 45 columns the footer wraps it. At rest the TUI is silent (no cursor or timer redraws), and a pending permission prompt replaces the composer and stops the spinner, so it reads as idle. Before this, a turn that ran a tool latched the session `busy` for good (the tool row's braille spinner tripped the generic spinner detector, and nothing ever armed the idle check). Token parsing and the ANSI content filter remain deferred.
|
||||
|
||||
### Goal
|
||||
Detect OpenCode's state from terminal output (idle, working, ready).
|
||||
|
||||
|
||||
@@ -223,9 +223,13 @@ command override instead.
|
||||
## Known gaps
|
||||
|
||||
- **No idle/completion hook.** Pi has no hook system Codeman can install into, so
|
||||
idle detection falls back to output-stabilization like the other external CLIs.
|
||||
Pi 0.84.0 shipped an `agent_settled` extension event that is a genuine idle
|
||||
signal; a Codeman pi extension using it is the highest-value follow-up.
|
||||
idle detection reads the screen: the registry entry's `workDetect` names pi's
|
||||
composer rule (`─`) as the glyph that arms the idle check and the spinner pi embeds
|
||||
in that rule while a turn runs (`── ⠏ Working ───`) as the working line, measured
|
||||
on pi 1.1.0. Without it a pi session that had started a turn never left `busy`,
|
||||
since pi never draws Claude's `❯`. Pi 0.84.0 shipped an `agent_settled` extension
|
||||
event that is a genuine idle signal; a Codeman pi extension using it is still the
|
||||
highest-value follow-up.
|
||||
- **No response viewer.** Pi writes JSONL v3 session files under
|
||||
`~/.pi/agent/sessions/`; nothing reads them yet.
|
||||
- **Cron jobs mis-detect readiness.** The cron readiness poll looks for `❯` or a
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Releasing Codeman (the COM procedure)
|
||||
|
||||
> Moved from the root `CLAUDE.md`, which keeps a pointer here. What SemVer covers is defined in `docs/versioning-policy.md`. The root file's Session Safety rules (branch check, explicit paths, never `git add -A`) apply to every step.
|
||||
|
||||
When user says "COM":
|
||||
|
||||
1. **Determine bump type**: `COM` = patch (default), `COM minor` = minor, `COM major` = major
|
||||
2. **Create a changeset file** (no interactive prompts). Write a `.md` file in `.changeset/` with a random filename:
|
||||
|
||||
```bash
|
||||
cat > .changeset/$(openssl rand -hex 4).md << 'CHANGESET'
|
||||
---
|
||||
"aicodeman": patch
|
||||
---
|
||||
|
||||
Detailed description of ALL changes since last release (not just the most recent commit — review full git log since last version tag)
|
||||
CHANGESET
|
||||
```
|
||||
|
||||
Replace `patch` with `minor` or `major` as needed. Include `"xterm-zerolag-input": patch` on a separate line if that package changed too.
|
||||
|
||||
3. **Consume the changeset**: `npm run version-packages` (auto-bumps `package.json` files, updates `CHANGELOG.md`, runs `npm install --package-lock-only`, and verifies lockfile sync via `scripts/check-lockfile-sync.mjs` — all in one command; never hand-edit `CHANGELOG.md` or `package-lock.json` versions)
|
||||
4. **Sync CLAUDE.md version**: Update the `**Version**` line in the root `CLAUDE.md` (under COM Shorthand) to match the new version from `package.json`
|
||||
5. **Commit and deploy**: verify the branch first (`git branch --show-current`), then stage EXPLICIT paths — never `git add -A`, which has swept another session's WIP into a release. `git status --short` and account for every line before committing:
|
||||
`git add <paths> && git commit -m "chore: version packages" && git push && npm run build && systemctl --user restart codeman-web`
|
||||
6. **Refresh the getcodeman.com version badge**: the landing page's status bar carries the release version (`v<x.y.z> · getcodeman.com · MIT`), so it goes stale on every release if nobody bumps it. The site source and its deploy script are maintained outside this repository, on the maintainer's machine only; follow the local site handbook there, which also covers the numbers strip and `sitemap.xml` refresh that belong in the same pass. Poll production (`curl -s https://getcodeman.com/ | grep v<x.y.z>`) before calling it done, since the edge lags a deploy by up to a minute. Not applicable to contributor clones — skip it and say so.
|
||||
7. **Wait for CI**: after `git push`, TWO workflows fire per master push — `CI` and `Release` (the npm publish + GitHub release). List both runs for the pushed commit with `gh run list --commit $(git rev-parse HEAD) --json databaseId,workflowName` and watch EACH with `gh run watch <id> --exit-status`. Confirm both pass before considering the release done (`gh run list -L 1` returns only one of the two).
|
||||
|
||||
8. **Publish the new version to the MCP registry**: `codeman mcp` is listed in the official MCP registry as `io.github.Ark0N/codeman`, and the registry does not follow npm, so every release is published there by hand or the listing stays on the old version. `npm run version-packages` has already written the new version into `config/mcp-registry/server.json` (`scripts/sync-plugin.mjs`). Wait until npm serves it (`npm view aicodeman version`; it can lag the green `Release` run by several minutes), because the registry checks that the npm package exists and carries `mcpName: io.github.Ark0N/codeman`. Then run `cd config/mcp-registry && mcp-publisher publish`, preceded by `mcp-publisher login github` when the saved login has expired, signed in as the account that owns the `io.github.Ark0N/` namespace. Use mcp-publisher 1.8.1 or newer (`mcp-publisher --version`), the release binary from https://github.com/modelcontextprotocol/registry/releases: the Snap Store package is stuck at 1.1.0 and rejects the current `$schema` with a false "deprecated schema detected", so never edit `server.json` for that error. Older publishers also save their login as `.mcpregistry_github_token` and `.mcpregistry_registry_token` (live tokens) in the current directory; move those out of the repo, never commit them. Confirm with `curl -s 'https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Ark0N/codeman' | jq -r '.servers[] | "\(.server.version) latest=\(._meta["io.modelcontextprotocol.registry/official"].isLatest)"'`: the new version must be the one with `latest=true`. Maintainer only (it needs that GitHub account); contributor clones skip it and say so.
|
||||
|
||||
9. **Announce it in Discussions**: every release gets a post in the [Announcements](https://github.com/Ark0N/Codeman/discussions/categories/announcements) category, shaped like #418 and #302: the short version first (one bold lead-in per theme, features before fixes, what it does for the user rather than how it works), contributor @-mentions inline where their work is described (a mention notifies them, and a contributor reposting is the cheapest reach this project has), a link to the release, and the Thanks names at the end. Casual first-person voice, no em-dashes, humanizer pass when the skill is available. A same-day follow-on patch (1.28.1 after 1.28.0) is folded into the previous post as an edit, never a second thread. Post it with `gh api graphql -F body=@<file> -f title='Codeman <x.y.z>: <hook>' -f repo=R_kgDOQ-SMDg -f cat=DIC_kwDOQ-SMDs4DCHZE -f query='mutation($repo:ID!,$cat:ID!,$title:String!,$body:String!){createDiscussion(input:{repositoryId:$repo,categoryId:$cat,title:$title,body:$body}){discussion{number url}}}'` (the repo's node id and its Announcements category id; `pinDiscussion` does not exist in the API, so pinning stays a click in the UI). This step exists because announcements stopped at 1.18 (#302) while ten releases shipped with nobody notified; #418 is the backfill covering 1.19.0 to 1.28.1, and release notes only count as content once they reach a surface people are subscribed to.
|
||||
|
||||
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
||||
@@ -251,6 +251,71 @@ unreachable host answers "unknown", which also means do not revive. The answer
|
||||
is cached per session and cleared whenever the pane is next seen alive, so a
|
||||
stale `true` from one transport drop can never revive the NEXT clean exit.
|
||||
|
||||
## Terminal history from the remote tmux
|
||||
|
||||
The local pane runs the ssh attach, so it only sees the remote tmux client's
|
||||
full-screen repaints and keeps a fraction of the scrollback (none after a
|
||||
reattach). A full-history load (`GET /api/sessions/:id/terminal?full=1`) of a
|
||||
remote session therefore reads the scrollback rows from the REMOTE pane in one
|
||||
ssh round trip (`src/remote-pane-history.ts`) and splices them above the local
|
||||
visible frame and caret. Bounded (5 s for the round trip, at most 1.5 s queued
|
||||
for a slot in the shared ssh limiter) and fail-soft: any failure keeps the
|
||||
local capture, and a transport failure (ssh exit 255, a timeout, output that is
|
||||
not the script's) also skips that host for 30 s; a failure of the remote
|
||||
command itself (a remote tmux session that is gone) affects that session only.
|
||||
How much history exists is the remote tmux's own `history-limit`, which the
|
||||
launch command does not set (tmux's default is 2000 lines).
|
||||
|
||||
The same round trip also reads the remote SCREEN, in the same tmux command list
|
||||
as the history, because two seams would otherwise drop rows at the join:
|
||||
|
||||
- **Rows that scroll during the round trip.** The local frame is captured only
|
||||
once the round trip is back, so rows that scrolled off the screen in between
|
||||
are in neither the remote history nor the local frame (measured before this
|
||||
read existed: 13 lines lost with a 150 ms round trip and fast output).
|
||||
- **A shared remote session with a taller client.** Under `window-size latest`
|
||||
a remote session attached elsewhere is sized by its latest client; when that
|
||||
client is taller than this pane, the rows above this pane's frame are only
|
||||
on the remote screen (measured before: 20 rows).
|
||||
|
||||
Both are rows of the remote screen above where the local frame begins, so the
|
||||
load keeps them between the history and the frame (`joinScrollbackAndFrame`,
|
||||
`findFrameInScreen` in `src/tmux-manager.ts`). The frame is placed by matching
|
||||
its top rows against the screen as text (escape sequences and trailing blanks
|
||||
ignored, since the two tmuxes need not encode attributes alike); the screen's
|
||||
trailing blank rows and its last content row, which output in flight can still
|
||||
change, are left out of the match, the overlap must be at least three rows
|
||||
with two of them non-blank, and the highest match wins. A placement too low
|
||||
would REPEAT the rows between it and the true one, so a shorter overlap (a lone
|
||||
`$` row that happens to match after a spinner row changed) is not trusted.
|
||||
When the frame cannot be placed (more output scrolled than the screen held, or
|
||||
nothing matches), the join is history over frame, as without the screen read.
|
||||
That includes an agent TUI mid-turn (Claude Code, codex, opencode): it keeps a
|
||||
live region (spinner, composer, footer) pinned to the bottom and inserts new
|
||||
rows above it, so the frame is not a shifted copy of the screen and is not
|
||||
placed. A plain shell places, unless the frame's top row is the second half
|
||||
of a wrapped line (the screen holds that line as one joined row, so nothing
|
||||
matches and the join is history over frame). What is left: when the screen
|
||||
repeats a whole block of rows, the frame can be placed at the higher copy,
|
||||
which leaves out the rows between the two copies.
|
||||
|
||||
The history, the history size and the screen are ONE tmux command list
|
||||
(`capture-pane … \; display-message … \; capture-pane …`), not separate `tmux`
|
||||
runs. tmux runs a client's command list back to back without reading pane
|
||||
output in between, so the screen begins exactly where the history ends. As
|
||||
separate runs the shell kept writing between them and the rows that scrolled in
|
||||
those milliseconds were in neither capture (measured with output streaming: 1-2
|
||||
rows per load on a LAN host, every read on a local busy pane). This rests on how
|
||||
tmux's command queue behaves, not on a documented guarantee. A random marker row
|
||||
(`display-message`) separates the history from the size and the screen, since
|
||||
tmux output cannot carry the NUL markers around it. tmux before 3.2 prints no
|
||||
newline after `capture-pane -p` output, so when the history ends inside a
|
||||
wrapped line the marker is glued onto that row; the parser accepts the marker
|
||||
at the end of a row and re-terminates the history. The remote `tail -c` bound
|
||||
applies to that whole output, history first, and is the configured byte cap
|
||||
plus 1 MiB for the marker, size and screen, so a cut lands in the history; the
|
||||
route trims what it returns to the cap itself.
|
||||
|
||||
## File access over SSH
|
||||
|
||||
A remote case's `workingDir` is an absolute path on the **remote** host
|
||||
@@ -270,6 +335,8 @@ and it follows the same rule as the launch path: every ssh command line comes fr
|
||||
| `GET /api/sessions/:id/file-thumbnail` | `400` for remote files |
|
||||
| `POST /api/sessions/:id/attachments` | Registers an absolute path that lives on the **remote** host (a clicked link pointing outside the case directory) by probing it there |
|
||||
| `GET /api/sessions/:id/attachments/:attachmentId/raw` | Streams the registered remote file over ssh, same 200/206/416 contract; `preview` (office) and `thumbnail` answer `400` |
|
||||
| `POST /api/sessions/:id/folders` | Lists a folder (absolute or `~/`) on the **remote** host in one ssh round trip (`remoteListFolder`): resolved with `cd -P`, missing → `404`, a file → `400 Not a folder` |
|
||||
| `GET /api/sessions/:id/folders/:folderId/files/:name/raw` | Streams one file of a granted remote folder over ssh after the same re-probe + guard as an attachment; `preview` (office) and `thumbnail` answer `400` |
|
||||
| `GET /api/sessions/:id/attachments/:attachmentId`, `GET …/attachments` (history) | Size/mtime/existence resolved over ssh, so a remote entry is not reported `missing`; the history list resolves EVERY entry in one batched probe, never one connection per entry |
|
||||
|
||||
⚠️ The attachment route is the one a clicked path takes when it is **outside** the case
|
||||
|
||||
@@ -278,8 +278,8 @@ Touch is always-local by design, and Claude sessions keep content in the normal
|
||||
- The `terminalWheelLocalScrollback` opt-out setting keeps working (pins plain wheel to local).
|
||||
- The viewport-at-bottom gate stays: once the user scrolled up locally, wheel stays local until they return to bottom.
|
||||
- 40ms SGR coalescing: never send per-event writes to the server.
|
||||
- Strip parity triangle: `session.ts` live strip ↔ `session-routes.ts` replay strip ↔ `_sessionUsesServerMouseStrip()` in the frontend. If you touch mode lists, update all three.
|
||||
- Don't add `opencode`/`antigravity` to any strip/forward list; their TUI wheel behavior is unverified (documented at `_shouldForwardWheelToApp`).
|
||||
- Strip parity: `session.ts` live strip ↔ `stripReplayBuffer()` in `session-routes.ts`, both driven by the registry's `altScreen` value and pinned together for every stock CLI in `test/claude-scrollback-strip.test.ts`. The frontend keeps no mode list: `_shouldReportMouseToCli()` reads only the server-published `cliMouseTracking`.
|
||||
- Don't add `opencode`/`antigravity` to the wheel-FORWARD list; their TUI wheel behavior is unverified (documented at `_shouldForwardWheelToApp`). ⚠️ 2026-09-16: opencode's half is now MEASURED — 1.18.31 ignores SGR wheel reports but pages its transcript on PageUp/PageDown — so it belongs in the **paging** list (`_localScrollbackIsHollow`). ⚠️ It also joined a STRIP list that same day, for a different reason: `isMuxMouseStripMode` removes its mouse DECSETs so a drag selects text again (see `docs/architecture-invariants.md` §Three strip flavors). antigravity/grok/deepseek/omp remain unverified.
|
||||
- The chunk-boundary sequence carry in `_handleTerminalOutput` must not be weakened.
|
||||
|
||||
## Testing (per repo rules)
|
||||
|
||||
@@ -354,8 +354,9 @@ is by id (`GET /api/sessions/:id/attachments/:attachmentId/raw`, same download c
|
||||
the `/root` and `/etc` trees, extendable via `attachmentBlockedPaths` /
|
||||
`CODEMAN_ATTACHMENT_BLOCKED_PATHS`) on every request. Unlike the workspace file
|
||||
routes, attachments are intentionally **cross‑workspace** — so the effective gate
|
||||
is the blocklist + a 6‑extension allowlist (`png/pdf/docx/pptx/md/txt`), not
|
||||
realpath containment.
|
||||
is the blocklist + an extension allowlist (`SUPPORTED_ATTACHMENT_EXTENSIONS` in
|
||||
`src/attachment-registry.ts`: images, pdf/docx/pptx/xlsx, audio/video, md/txt and
|
||||
other text), not realpath containment.
|
||||
|
||||
Two registration paths, with **different trust**:
|
||||
|
||||
@@ -373,6 +374,23 @@ Two registration paths, with **different trust**:
|
||||
file outside the session's own workspace. Cross‑workspace attach must go through
|
||||
the explicit POST path above.
|
||||
|
||||
**Folder grid grants** (`POST /api/sessions/:id/folders`, `src/folder-listing.ts`)
|
||||
follow the explicit-POST trust level: a deliberate, Origin‑guarded request, allowed
|
||||
cross‑workspace subject to the same guard (blocklist on the folder AND on every
|
||||
listed file, `confineToWorkspace` when set, hidden entries and unsupported types
|
||||
left out). The grant is an id for a resolved folder; files are served by
|
||||
`folderId` + a bare file name only (no `/`, `..` or NUL, supported type), and each
|
||||
request re‑runs `resolveServableAttachmentPath` on the joined path, so a file that
|
||||
was swapped for a symlink to a blocked target after listing is still refused.
|
||||
The file a symlink resolves to is held to the attachment gate as well (supported
|
||||
extension, regular file), so a supported-looking name cannot serve an arbitrary
|
||||
file, and a FIFO or device node is never opened.
|
||||
In multi‑user mode a regular user is held to the filesystem path picker's rule
|
||||
(`folderAllowedForUser`): the folder, and again each served file after symlink
|
||||
resolution, must sit inside their own `userSpacePath` or the session's
|
||||
`workingDir`, else 403. User spaces live inside `homedir()`, so without it one user
|
||||
could list and read another's space.
|
||||
|
||||
### SSE log‑tail route — intentional extra read roots
|
||||
|
||||
The live file‑tail SSE route (`FileStreamManager`, used to stream a growing log
|
||||
@@ -528,6 +546,7 @@ A saved dashboard URL renders as a tab, served through Codeman's own origin at `
|
||||
- **The proxy is exempt from cookie auth and the Origin/CSRF guard, and that is deliberate.** The iframe is sandboxed without `allow-same-origin`, so it is opaque‑origin: its requests are cross‑site, meaning the `SameSite=lax` session cookie is never attached and its writes and WS upgrades arrive with `Origin: null`. The credential is instead a 192‑bit capability in the path, minted only by an authenticated `POST /api/webviews/:id/open`, held in memory (a restart invalidates every one), rolling TTL, bound to the minting user, and granting nothing but "relay bytes to this one saved URL". ⚠️ **The Host allowlist is NOT bypassed**, so DNS‑rebinding protection is unaffected. A second `Referer`‑keyed form exists for root‑absolute assets and is the only exemption decided by a request‑supplied header, so it is fenced to safe methods on non‑`/api`, non‑`/ws`, non‑`/q` paths. Edges pinned by `test/webview-auth-exemption.test.ts`.
|
||||
- **The lost‑frame recovery page is the third unauthenticated 200, and the only one decided by request headers alone.** The proxy's runtime shim masks `/webview/<cap>/` off the page's own URL so a single‑page app routes on the path it expects; a navigation the page then starts itself (`location.reload()`, a root‑absolute `location.href`) lands on Codeman's root with no capability anywhere, no cookie (opaque origin) and a Referer naming the masked page. `serveLostWebviewFrame()` in `middleware/auth.ts` recognises it by shape (`GET`/`HEAD`, `Sec-Fetch-Dest: iframe` or `frame`, `Accept: text/html`, `Sec-Fetch-Mode: navigate` or absent) and answers, BEFORE the credential checks and without counting an auth failure, with a static page whose only content is a `postMessage` of the lost path to the parent tab (`default-src 'none'` plus the hash of that one script, `no-store`, `referrer: no-referrer`, no reflected input). It is fenced to paths that are NOT registered routes and never `/api/`, `/ws/` or `/q/`, with one carve‑out: `/` itself, because the landing page masks to exactly `/` and its reload otherwise rendered Codeman's app shell inside the web tab. `/` is admitted only when the request carries neither the `codeman_session` cookie nor an `Authorization` header: nothing in Codeman frames its own root and a sandboxed frame has neither, while a framed `/` that does carry credentials still gets the shell. On a passwordless install no auth hook runs, so the index route applies the same test itself (`isLostWebviewRootFrame`). ⚠️ Known property, accepted rather than mitigated: those headers are trivially set by a non‑browser client, so an unauthenticated caller can distinguish a registered route (401) from a non‑route (200) and enumerate the route table; the routes are public in `docs/api-reference.md`, so nothing is learned. Pinned by `test/webview-auth-exemption.test.ts` (password) and `test/webview-lost-root-frame.test.ts` (passwordless).
|
||||
- **Sandboxed by default; `allow-same-origin` is an explicit per‑dashboard opt‑in.** A proxied page is same‑origin with Codeman, so without the sandbox its JavaScript could read the Codeman document and call the agent‑spawning API. ⚠️ In BOTH modes the `Authorization` header and the `codeman_session` cookie are stripped before the upstream request, because a trusted (same‑origin) frame makes the browser attach Codeman's own Basic‑auth credentials to every proxied request; forwarding them would hand `CODEMAN_PASSWORD` to the dashboard.
|
||||
- **Rendered HTML files (`/html-view/<capability>/`) are the other capability-gated route that skips cookie auth.** A clicked `.html` file renders through it so an agent's report can be viewed from any device. The exemption is narrower than the proxy's: `GET`/`HEAD` only (plus the page's CORS preflight, which `registerSecurityHeaders` answers itself with `Access-Control-Allow-Methods: GET, HEAD` and never hands to a route), the capability in the path only (no `Referer` form), and it is a separate store, so a web-tab capability never opens a page and vice versa. The capability is minted by an authenticated `POST /api/sessions/:id/html-view` (session ownership via `findSessionOrFail`, the attachment guard for out-of-workspace files), held in memory with a rolling TTL and revoked with the web-tab ones on logout, admin logout and user deletion. Every response carries `Content-Security-Policy: sandbox` without `allow-same-origin`, so the page is opaque-origin even when opened as a top-level tab and cannot read Codeman's document, cookies or API. **Network access is open, by the owner's decision (2026-10-13):** that `sandbox` directive is the whole policy (it replaces Codeman's own `default-src 'self'` CSP and carries no fetch directive), so a rendered page behaves like a file opened from disk in a browser. What a page CAN do: load scripts, styles, fonts, images and media from any host (an agent's dashboard pulling Chart.js from a CDN), make fetch, XHR, WebSocket, beacon and form requests to any host, and read the files of its own folder through its capability. What it CANNOT do: act as Codeman's origin, read Codeman's cookies or document, use Codeman's API (a write arrives with `Origin: null` and the Origin guard refuses it; a read's response stays unreadable, because Codeman answers CORS only for its own localhost origins, and with a password set the request carries no session cookie either), or read any folder other than its own. The accepted consequence is that a page can send what it can read, its own folder, to any host, which is why the folder rules below are the boundary that matters. `Referrer-Policy: no-referrer` keeps the capability URL out of the `Referer` the page's third-party requests carry. Pinned by the exact-header test in `test/routes/html-view-routes.test.ts`. It may read its own directory tree (non-dot, asset-allowlisted, realpath-confined, blocklist applied; the dot and extension rules hold for the symlink-resolved target as well as the requested name), so minting is refused for an HTML file in a hidden directory or directly in a broad root (`/`, home, `/tmp`, `/var/tmp` and `$TMPDIR`, the cases and user-space roots, a drive's mount point) or in a directory above one (`/home`, `/Users`). Pinned by `test/routes/html-view-routes.test.ts` and the html-view block in `test/webview-auth-exemption.test.ts`.
|
||||
- **Not an open relay, and not a privilege boundary.** `resolveUpstreamUrl()` refuses anything leaving the saved origin, and cross‑origin redirects are handed back unchanged rather than followed. The proxy does reach whatever the SERVER can reach, which is not an escalation for someone who already commands `--dangerously-skip-permissions` agents, but in multi‑user mode it means a non‑admin's dashboard is fetched from the server's network position. Saved URLs are validated to plain http(s) with no embedded credentials, and there is deliberately **no magic‑link path**: terminal output can never create a webview (the mistake the attachment scanner had to be walled off from). The one refused destination class is link‑local and cloud‑metadata addresses (`169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`, `168.63.129.16`, `100.100.100.200`, `metadata.google.internal`): `webview-egress-policy.ts` refuses them at save time, and `webview-egress.ts` re‑judges the RESOLVED address at connect time through a `lookup` hook on the proxy's undici Agent and on its WebSocket client, so a DNS name pointing into those ranges is refused as well. Loopback and RFC1918 stay allowed on purpose. Capabilities are revoked on logout, admin logout and user deletion, and proxied responses carry `Referrer-Policy: same-origin` so a dashboard cannot hand the capability‑bearing URL to a third‑party host it links.
|
||||
|
||||
---
|
||||
|
||||
@@ -92,7 +92,15 @@ view needs a wide viewport). So:
|
||||
keyboard accessory bar. On a desktop, typing directly into an xterm
|
||||
instance with no overlay is exactly how Codeman behaved before the local-
|
||||
echo overlay existed for touch devices — normal, not degraded, for a
|
||||
keyboard-and-mouse user.
|
||||
keyboard-and-mouse user. (Since moved to `TerminalTile`, terminal-tile.js,
|
||||
which has gained three pieces of the primary pane: hollow-buffer wheel
|
||||
paging (#555) and the desktop click report for a CLI with
|
||||
`cliMouseTracking` on, both through the primary pane's gates aimed at the
|
||||
tile, and its own keyCode-229 soft-keyboard controller
|
||||
(terminal-keycode229-recovery.js: the #441 next-keydown drain and #541's
|
||||
edit-based diff, so an Android autocorrect is not sent twice). The 1180px
|
||||
width gate is all that keeps a phone out, and a wide Android tablet clears
|
||||
it. See that file's fileoverview.)
|
||||
|
||||
If this asymmetry actually bothers you in daily use, promoting Pane B to full
|
||||
parity is a scoped v2 (extract the shared logic already once you have two
|
||||
|
||||
@@ -82,6 +82,7 @@ This is exactly how `command-palette` already behaves: it is a full registry ent
|
||||
|
||||
- The server strips mouse-tracking DECSETs for `claude`, `codex`, and `gemini` (`isAltScreenStripMode`, `src/session.ts:179`), which is why plain drag-select works in those tabs even though the TUI has mouse tracking on.
|
||||
- `shell`, `opencode`, and `antigravity` keep mouse reporting, so xterm requires `Shift`+drag to force a selection there. Worth one line in the docs, it is not a code change.
|
||||
⚠️ **Corrected 2026-09-16:** `opencode` no longer keeps mouse reporting in the browser. Its TUI enables tracking DECSETs, tmux `mouse off` passes them through to the tmux client, and xterm then reported DRAGS to the TUI instead of selecting — so `Shift`+drag was the only way to select, and a plain drag silently copied nothing (measured 62 `none` / 18 `any` over 16s; 5/5 dead drags while `any`). The server now strips those DECSETs (`isMuxMouseStripMode`), so a plain drag selects in opencode. `shell` and `antigravity` are unchanged.
|
||||
- Touch devices deliberately disable selection entirely (`body.touch-device .terminal-container .xterm{user-select:none !important}`, `styles.css:3196`), and phones have no Ctrl key. This feature is desktop and hardware-keyboard only, with no mobile regression surface.
|
||||
|
||||
### 2.6 Helpers that already exist and should be reused
|
||||
@@ -245,7 +246,7 @@ The shortcut overlay (`Ctrl+?`) and App Settings -> Shortcuts are registry-drive
|
||||
| Whitespace-only or empty selection | `getSelection()` empty string is treated as "no selection", so Ctrl+C still interrupts |
|
||||
| macOS Cmd+C | registry treats ctrl/meta as interchangeable, so with a selection it takes our path (same visible result as today's native copy), without one it falls through |
|
||||
| Chrome/Firefox `Ctrl+Shift+C` is the devtools inspect chord | browser-level and may still toggle devtools, our copy runs regardless. Document as a caveat, `Ctrl+C` is the primary path |
|
||||
| Selection in a tab whose TUI owns the mouse (`shell`/`opencode`/`antigravity`) | unchanged, `Shift`+drag selects, then Ctrl+C copies |
|
||||
| Selection in a tab whose TUI owns the mouse (`shell`/`antigravity`; `opencode` left this list on 2026-09-16 — its DECSETs are stripped now) | unchanged, `Shift`+drag selects, then Ctrl+C copies |
|
||||
| Web tab (iframe dashboard) focused | xterm handler never runs, browser-native copy inside the iframe |
|
||||
| Teammate/subagent terminals (`panels-ui.js:2268`, `onData` wired) | same limitation exists there, out of scope for this PR (section 8) |
|
||||
|
||||
@@ -281,7 +282,7 @@ Against a throwaway session on the live instance (`curl -sk https://localhost:30
|
||||
3. Type a few characters with local echo on (phone or `localEchoEnabled` forced), press Ctrl+C with no selection, confirm buffered text plus interrupt behave as before.
|
||||
4. Uncheck the shortcut in App Settings -> Shortcuts, confirm Ctrl+C always interrupts even with a selection.
|
||||
5. Rebind it, confirm the new chord copies and Ctrl+C reverts to pure interrupt.
|
||||
6. Repeat 1 and 2 in an `opencode` or `shell` tab using Shift+drag to select.
|
||||
6. Repeat 1 and 2 in a `shell` or `antigravity` tab using Shift+drag to select (`opencode` selects with a plain drag since 2026-09-16).
|
||||
7. Load over plain HTTP (`--host` LAN or `http://127.0.0.1:<port>`) and confirm the `execCommand` fallback copies and focus returns to the terminal.
|
||||
8. Mobile smoke: confirm nothing changed (selection is CSS-disabled, no Ctrl key).
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Tile Grid: Design Spec
|
||||
|
||||
**Status**: PR 1 (tile foundation) implemented on `feat/terminal-tile`; PR 2 (the grid) implemented on `feat/tile-grid`, both local only. Builds on `docs/split-pane-sessions-plan.md`; the split pane stays.
|
||||
**Status**: Merged for the 1.40.0 release as #560 (the TerminalTile foundation) and #561 (the grid). Where the "As built" section below differs from this spec, As built is authoritative. Builds on `docs/split-pane-sessions-plan.md`; the split pane stays.
|
||||
**Author**: Claude (planning session with the maintainer), 2026-10-06
|
||||
**Branches**: PR 1 `feat/terminal-tile`, PR 2 `feat/tile-grid` stacked on it (worktrees `claudeman-tiles`, `claudeman-tilegrid`)
|
||||
**Branches**: developed as PR 1 `feat/terminal-tile` and PR 2 `feat/tile-grid` stacked on it, both merged
|
||||
**Scope**: v1 is fully designed here; follow-ups are named at the end and explicitly deferred.
|
||||
|
||||
## As built: where PR 2 differs from this spec
|
||||
@@ -20,14 +20,22 @@ or settled a question the spec left open. The invariants as built are in
|
||||
- **`Ctrl+Shift+G` follows `showTileGridButton`** (decided by the owner, decision 6): with
|
||||
the setting off the toggle chord is inert. A grid opened another
|
||||
way (Ctrl/Cmd+click, a dropped tab, "Open group as tiles") keeps all its chords.
|
||||
- **The Tiles button ships ON** (owner, 1.36.0 beta): `showTileGridButton` defaults to on
|
||||
everywhere but handhelds (their defaults object keeps it off) and, since the 1.40.0 final
|
||||
checkup, devices whose primary pointer is coarse (touch tablets, opt-in there), so the
|
||||
chord is live by default too. An absent key resolves through the device defaults in both the button
|
||||
(settings-ui.js) and the chord (`tileShortcutFor`), so they cannot disagree.
|
||||
- **Dividers are grid tracks.** Each gap between columns and rows is its own 6px track (the
|
||||
grid gap is 0) and every tile and every empty slot is placed explicitly in its cell
|
||||
(`grid.cells`, see "Tiles move"). Fractions reset when the column or row count changes.
|
||||
- **Zoom follows tmux.** Moving focus to another tile restores the grid; an automatic zoom
|
||||
(window too small for the minimum tile) follows focus instead.
|
||||
- **Tile loads are bounded** (`boundedLoad`), carry a fetch deadline covering the body (Pane
|
||||
B too), and a refresh clears the screen at its turn in the queue, so a waiting tile keeps
|
||||
its last frame.
|
||||
B too), and a refresh fetches at its turn in the queue: the tile keeps its last frame
|
||||
through its wait and its own round trip, and is reset with the queued in-stream `\x1bc`
|
||||
only once the capture is in hand, right before the replay (never xterm's `clear()` before
|
||||
the fetch). A failed, aborted or empty fetch writes nothing and resets nothing: the tile
|
||||
keeps its last frame and every held live frame.
|
||||
- **4009 lands on the Attach overlay**, and 4003/4004/4010 remove the tile.
|
||||
- **Tile header buttons are 26px targets with 16 to 19px glyphs** (owner feedback: the
|
||||
first build's 12px glyphs read as tiny next to the name), the size of the app header's own
|
||||
@@ -37,20 +45,28 @@ or settled a question the spec left open. The invariants as built are in
|
||||
`Right-click`) and `Arrows` translated. Every string has its own entry or pattern; refreshes
|
||||
compare with the last English value, not the translated DOM.
|
||||
- **The Tiles button opens the grid at once** (owner decision 8, with the count of
|
||||
decision 10): a click (and `Ctrl+Shift+G`, the same `toggleTileGrid`) opens the remembered
|
||||
count of tiles (default 6, at most what the window fits). `tileGridOpenSet`
|
||||
(constants.js) picks the grid this tab last had, else an open split's two sessions, else
|
||||
the open sessions in tab order, the active one always included and focused, and
|
||||
`tileGridSetForCount` trims it (from the end, the session to focus kept) or fills it
|
||||
(from tab order) to the count. A remembered grid comes back with its tiles first, in
|
||||
their cells, then sessions in tab order, to the count in total: the count is a shape
|
||||
change under the cell model's rule (`reformTileCells`: the tiles keep their row and
|
||||
column when all fit, else they pack in reading order) and the added tiles fill the empty
|
||||
cells first. This supersedes decision 8's "exactly the stored set" (owner answer). A
|
||||
remembered grid still wins over an open split: the split closes and its sessions are not
|
||||
seeded first. A page-load restore brings back exactly the stored grid, whatever the
|
||||
count. Ctrl/Cmd+click on a tab with the grid closed opens the count in total, that
|
||||
session among them and focused (owner answer: N, not N+1).
|
||||
decision 10 and the layout memory of decision 11): a click (and `Ctrl+Shift+G`, the same
|
||||
`toggleTileGrid`) brings back the grid this browser last had EXACTLY as the user left
|
||||
it: which session sits in which cell, holes included, its tile count, divider sizes,
|
||||
focus and a zoom the user chose (`restoreTileGridCells`, constants.js). It is never
|
||||
filled to the remembered count and never trimmed to the window (a window too small
|
||||
for it shows the focused tile alone until it fits, the arrangement kept). A session
|
||||
that no longer exists frees its cell, which the ranking fills. Only with nothing
|
||||
stored, or none of its sessions left, does `tileGridOpenSet` (constants.js) take an
|
||||
open split's two sessions, else the open sessions as `rankTileSessions` orders them
|
||||
(owner request: "prefer to load in tiles that are working and then the most recent,
|
||||
so the oldest don't get opened"): WORKING first (the most recently started turn
|
||||
first, keyed off `lastSubmitAt` only), then the ones NEEDING INPUT (the red and yellow
|
||||
tab alerts), then the rest by most recent activity, tab order breaking ties; the
|
||||
active one always included and focused, and `tileGridSetForCount` trims it (from the
|
||||
end, the session to focus kept) or fills it (from the ranking) to the remembered count
|
||||
(default 6, at most what the window fits). The states and stamps are the home
|
||||
screens' own (`_mobileOverviewState`, `sessionActivityAnchor`). A remembered grid still
|
||||
wins over an open split: the split closes and its sessions are not seeded first. A
|
||||
page-load restore brings back the same grid as the toggle. Ctrl/Cmd+click on a tab
|
||||
with the grid closed opens what the toggle would with that session among the tiles and
|
||||
focused, never past the count (owner answer: N, not N+1): it joins the first empty cell
|
||||
while the grid holds fewer than the count, else it takes the last tile's place.
|
||||
- **A hover card on the Tiles button says it** (owner feedback: "give me the hover info
|
||||
to right click over the tile button to adjust it"). It replaces the button's native title:
|
||||
"Tiles · N" (the remembered count, live), what a click does (open or close the grid),
|
||||
@@ -72,9 +88,10 @@ or settled a question the spec left open. The invariants as built are in
|
||||
back on the Tiles button, Tab, a click elsewhere and the keyboard leaving it for another
|
||||
element close it (the single view a close starts focuses its terminal when its replay
|
||||
lands; a menu left open behind that would send its keys there). A pick is remembered per
|
||||
device in `codeman:tile-count` (`codeman:tile-grid` stays ids only) and opens that many
|
||||
tiles; with the grid open it re-forms it (`_reformTileGrid`): the focused tile always
|
||||
stays, the others leave from the end or join from tab order, filling empty cells first,
|
||||
device in `codeman:tile-count` and opens that many tiles (a stored grid re-formed to
|
||||
it, its tiles first in their cells); with the grid open it re-forms it
|
||||
(`_reformTileGrid`): the focused tile always stays, the others leave from the end or
|
||||
join from the ranking, filling empty cells first,
|
||||
every joining tile mounted and laid out before any connects (one fit, one PTY resize
|
||||
each), and a zoom the user chose ends. The other ways in (Ctrl/Cmd+click, a dragged tab,
|
||||
"Open group as tiles", Run) still add up to the cap of 6.
|
||||
@@ -89,7 +106,10 @@ or settled a question the spec left open. The invariants as built are in
|
||||
`test/header-icon-hover.test.ts`.
|
||||
- **The grid opens and closes with a short animation, on by default** (owner request:
|
||||
"when clicking on the tile button first make this animation nicer"). It is the grid's
|
||||
own, not an `entrance-animations.js` theme (those are off by default). Opening, each tile
|
||||
own `settle` style, the default of App Settings → Animations → Tile Animations, which
|
||||
switches on other styles (`fly` out of the tabs, `deal` from the Tiles button, `crt`,
|
||||
`beam`, ...; docs/architecture-invariants.md#entrance-animations).
|
||||
Opening, each tile
|
||||
fades and settles in (opacity, translateY 6px and scale .97), 180 ms, 24 ms apart in
|
||||
reading order (`--tile-enter-index`): the last of six is done at 300 ms; a tile added
|
||||
later enters the same way. Its terminal stays transparent (`.tile--revealing`) until the
|
||||
@@ -211,8 +231,10 @@ no `+`, owner decision 9).
|
||||
|
||||
## Non-goals (v1)
|
||||
|
||||
- Phones and tablets. The grid is desktop-only, gated at 1180 px like the
|
||||
split (`SPLIT_PANE_MIN_WIDTH`) and the home rail (`HOME_SESSIONS_MIN_WIDTH`).
|
||||
- Phones. The grid is gated on width alone at 1180 px like the split
|
||||
(`SPLIT_PANE_MIN_WIDTH`) and the home rail (`HOME_SESSIONS_MIN_WIDTH`); a
|
||||
wide tablet, or a large foldable unfolded in landscape, can reach it (see the
|
||||
keyboard exception below).
|
||||
- More than 9 tiles.
|
||||
- WebGL rendering inside tiles (see "Rendering" below).
|
||||
- Full parity with the main terminal's touch and IME features: local-echo
|
||||
@@ -220,7 +242,11 @@ no `+`, owner decision 9).
|
||||
mouse-wheel forwarding to Claude's fullscreen renderer, the "Load full
|
||||
history" banner. These exist for touch devices or rare cases; a desktop
|
||||
keyboard user types straight into xterm, which is how Codeman behaved before
|
||||
those features existed.
|
||||
those features existed. (One exception, since the 1180 px gate is width
|
||||
only and a wide Android tablet clears it: every tile wires the main
|
||||
terminal's keyCode-229 soft-keyboard controller, terminal-keycode229-recovery.js,
|
||||
so an Android autocorrect is sent as an edit rather than a duplicated line,
|
||||
#541, and a character committed with Enter is not lost, #441.)
|
||||
- Server-side persistence of grids (named presets per owner).
|
||||
- Pop-out windows (`/session/:id`, solo mode) showing a grid.
|
||||
|
||||
@@ -375,16 +401,34 @@ the harness/model request; see "As built")
|
||||
|
||||
### Persistence
|
||||
|
||||
Decided: per device, restored on reload. Stored in localStorage key
|
||||
`codeman:tile-grid`:
|
||||
Decided: per device (per browser), restored on reload when it was open, and by
|
||||
the Tiles toggle however it was closed (decision 11). Stored in localStorage key `codeman:tile-grid`, never on the
|
||||
server:
|
||||
|
||||
```json
|
||||
{ "v": 1, "open": true, "ids": ["…", "…"], "focused": "…", "zoomed": null,
|
||||
"colFr": [1, 1, 1], "rowFr": [1, 1] }
|
||||
{ "v": 1, "open": true, "ids": ["…", null, "…"], "count": 3, "focused": "…",
|
||||
"zoomed": null, "colFr": [1, 1, 1], "rowFr": [1, 1] }
|
||||
```
|
||||
|
||||
Ids only, never content. A pure sanitizer drops unknown, deleted, detached and
|
||||
duplicate ids on load. Never restored in a solo window.
|
||||
Session ids and the layout, never content. `ids` are the CELLS in reading order,
|
||||
`null` for an empty one. `count` is how many tiles the user's own last change
|
||||
left (open, add, remove by hand, a count picked): a session that goes away by
|
||||
itself (deleted, popped out, its socket refused) does not lower it, so the next
|
||||
time the grid opens the ranking fills that place, while a hole the user made
|
||||
stays. It is written on every change (a move, a divider drag at pointer-up, a
|
||||
tile added or removed, a count picked, a focus, a zoom) and kept, as
|
||||
`open: false`, however the grid closes: the toggle, a non-tiled tab,
|
||||
`leaveTiles` or a `#session=` link (which flips `open` only, so a gone id still
|
||||
frees its cell), Home, the width gate, the last tile, "Open group as tiles",
|
||||
closing or killing sessions. Nothing is written while a stored grid is being
|
||||
put back, so a half-built grid never overwrites it.
|
||||
|
||||
A pure sanitizer drops unknown, deleted, detached and duplicate ids on load,
|
||||
reports the cells their sessions freed (`freed`), and derives `count` for a
|
||||
value written before it existed (the number of sessions the cells name); the
|
||||
old packed `ids` (no nulls) read as cells with no hole, and anything that is not
|
||||
a v1 object is ignored. The format stays `v: 1`, so an older build still reads
|
||||
a newer value (it ignores `count`). Never read or written in a solo window.
|
||||
|
||||
The restore runs INSIDE `handleInit`, in place of its initial
|
||||
`selectSession(restoreId, { auto: true })` (the non-`keepTerminal` branch), not
|
||||
@@ -395,10 +439,22 @@ the main terminal never loads on that page load. A later `handleInit` (SSE
|
||||
reconnect after a server restart, the `keepTerminal` branch) reconciles ids
|
||||
against the live list without rebuilding tiles that are still alive.
|
||||
|
||||
A cell freed since the grid was stored is filled during that restore, from a
|
||||
ranking that knows each session's status and stamps (the init payload) but not
|
||||
yet its pending approvals: `seedApprovals` asks the server for them
|
||||
asynchronously, and the restore has run by the time they land. So on a reload a
|
||||
session waiting on a permission dialog or an unseen finished turn ranks with the
|
||||
quiet ones for that one fill (working sessions still rank first). Accepted: a
|
||||
fill held back for the approvals would open fewer tiles, which can be another
|
||||
shape, and then reshape the grid and move the user's tiles a second after the
|
||||
reload; so approvals that land later never re-form a restored grid. The Tiles
|
||||
toggle, run once the page has loaded, ranks with them.
|
||||
|
||||
### Gating
|
||||
|
||||
- Setting `showTileGridButton`, per device (in `displayKeys`, stripped from the
|
||||
settings PUT, NOT in `SettingsUpdateSchema`), default OFF. Independent of
|
||||
settings PUT, NOT in `SettingsUpdateSchema`), default ON on desktop and OFF on
|
||||
handhelds (specified OFF; superseded, see "As built"). Independent of
|
||||
`showSplitButton`, which is unchanged; a desk can show both buttons.
|
||||
- Hidden below 1180 px by both a JS width check with a `matchMedia` listener and
|
||||
a CSS `@media (max-width: 1179px)` backstop, exactly like the split button.
|
||||
@@ -800,7 +856,8 @@ Separate follow-up PRs worth doing (see "Follow-ups").
|
||||
open, and an open menu owns the Escape (it closes alone and the keyboard goes
|
||||
back to the Tiles button, like the tab-group menu).
|
||||
- **User text** (names) via `textContent` / attributes, never `innerHTML`.
|
||||
- **No secrets in localStorage**: the stored grid holds ids only.
|
||||
- **No secrets in localStorage**: the stored grid holds session ids and its
|
||||
layout only, never content.
|
||||
- **Memory**: everything a tile creates is released in `destroy()`.
|
||||
|
||||
## Delivery: two PRs
|
||||
@@ -993,8 +1050,17 @@ exits green. Use the browser runner for those files and read the file count.
|
||||
viewer keeps a stale width and renders garbled output (#464).
|
||||
3. WebSocket backpressure (`bufferedAmount` threshold, drop and send `{t:'r'}`
|
||||
on drain) for grids over slow links.
|
||||
4. Tile parity extras: mouse-wheel forwarding for Claude's fullscreen renderer,
|
||||
a "Load full history" action inside a tile.
|
||||
4. Tile parity extras: a "Load full history" action inside a tile. (Done
|
||||
since: a tile pages a hollow buffer's CLI transcript with PageUp/PageDown,
|
||||
the primary pane's #555 route, hand-reports a plain click while its session
|
||||
has `cliMouseTracking` on, and forwards the wheel to Claude's fullscreen
|
||||
renderer as SGR wheel reports from its own cells
|
||||
(`TerminalTile._maybeForwardWheelToCli`, encoding shared with the primary
|
||||
pane via `CodemanTerminalInput.sgrWheelReports`), all through the primary
|
||||
pane's gates aimed at the tile. Before that, a fullscreen Claude tile left
|
||||
the wheel to xterm, which scrolled only stale replayed frames. Shift+wheel
|
||||
scrolls the tile's local scrollback itself (`_maybeScrollLocalOnShift`),
|
||||
since xterm turns it into a horizontal no-op off macOS.)
|
||||
5. WebGL in tiles, after measuring the DOM renderer with nine busy tiles.
|
||||
6. Named grid presets, possibly per owner on the server.
|
||||
7. The end state: the main terminal becomes a 1x1 grid of `TerminalTile`,
|
||||
@@ -1033,7 +1099,8 @@ exits green. Use the browser runner for those files and read the file count.
|
||||
is on right-click of the button (its title says so, as do the wiki and the
|
||||
Help modal). Superseded in part by decision 10: right-click is now the count
|
||||
menu, and a remembered grid is filled to the count instead of opening
|
||||
exactly as stored.
|
||||
exactly as stored; decision 11 then restored "exactly as stored" and put a
|
||||
ranking in place of the tab order.
|
||||
9. **No + in the tile header.** Decided by the owner ("remove the + button from
|
||||
these views"): the header is `● name ……… ⋯ ⤢ ×`. The + menu and its "New
|
||||
session in this case" went with it. Tiles are added from the Tiles button
|
||||
@@ -1046,12 +1113,32 @@ exits green. Use the browser runner for those files and read the file count.
|
||||
right-click menu offers 2, 4 and 6, remembered per device; the session
|
||||
picker is gone, and decision 8's "picker on right-click" is superseded. The
|
||||
owner's answers on the details: the count wins over a remembered grid's
|
||||
size (its tiles first, in their cells, holes filled first, then tab order);
|
||||
size (its tiles first, in their cells, holes filled first, then tab order;
|
||||
superseded by decision 11: a click brings the remembered grid back as it
|
||||
was, and only a count picked in the menu re-forms it);
|
||||
Ctrl/Cmd+click with the grid closed opens the count in total, that session
|
||||
focused; shrinking keeps the focused tile; only the toggle animates the
|
||||
close; a remembered count larger than the window stays checked but greyed
|
||||
and a click opens what fits; the close keeps its dimmed still until the
|
||||
single view has painted (at most 700 ms); paced connect is in.
|
||||
11. **The grid keeps the layout the user arranged, and a fresh one ranks by
|
||||
work.** Decided by the owner ("when I hit the tiles button, it should prefer
|
||||
to load in tiles that are working and then the most recent working, so the
|
||||
oldest dont get opened ... when I moved around and modified it, save it per
|
||||
browser the layout, so when I turn tiles off and on, always keep what the
|
||||
last setting was, if there was no setting before take the working ones, that
|
||||
ones needs input and then the most recent ones in order"). The layout
|
||||
(cells and holes, tile count, divider sizes, focus, a zoom the user chose)
|
||||
is saved per browser on every change and comes back exactly from the toggle,
|
||||
however the grid closed, and from a reload when the grid was open (a grid
|
||||
closed before the reload stays remembered for the toggle; the page shows the
|
||||
single view); it is never filled to the remembered count nor trimmed to the
|
||||
window. A session gone since frees its cell for the
|
||||
ranking; with none left, the grid opens from the ranking (`rankTileSessions`:
|
||||
working, then needing input, then most recent), which also fills every place
|
||||
the grid fills on its own (a count picked in the menu, a freed cell, an open
|
||||
split's fill). Supersedes decision 10's "the count wins over a remembered
|
||||
grid's size"; the count menu itself, its counts and its other answers stay.
|
||||
|
||||
## Code anchors
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ Claude Code (**v2.1.80+**; prod box runs **2.1.177**) pipes a JSON blob to a con
|
||||
|
||||
The same stdin object also carries `model.display_name`, `context_window.{used_percentage, total_input_tokens, total_output_tokens, …}`, `cost.total_cost_usd`, `effort.level`, etc. The shipped feature uses **model + token totals + context %** to build the in-terminal footer (so the statusline stays useful even though we own it). The endpoint also broadcasts `contextUsedPercentage`/`costUsd`/`modelDisplayName` alongside the limits for future chip tooltips.
|
||||
|
||||
Since Claude Code v2.1.251 the payload also carries a `prompt_cache` object for the main conversation: `warm`, `ttl` (`5m` or `1h`), `expires_at` (epoch seconds), `recache_tokens_if_cold`, `misses`, `expected_rebuilds`, `hit_ratio`, `last_miss_at` and `last_miss_cause`. `StatusTelemetrySchema` lists every documented scalar field null-tolerant (several are documented as possibly null, and the object gains fields across CLI versions, so a strict shape would 400 the post and blank the footer); `parsePromptCache()` normalizes only the subset Codeman stores. The footer appends `cache:until HH:MM` while warm or `cache:cold` otherwise, and Claude re-runs the statusline when `expires_at` passes, so the cold flip arrives without a turn. The Session Options readout adds the hit rate, the last miss's causes, and a `Context compacted at HH:MM` note after a compaction or a tool-result clearing (the first warm report whose `recache_tokens_if_cold` is null after one that carried it; `expected_rebuilds` rises only at the next request, so it is not read; never raised as an alert). The last report is restored on a Codeman restart and the readout is time-aware, so a value whose expiry has passed shows as cold rather than stale-warm.
|
||||
|
||||
### Alternatives considered & rejected
|
||||
|
||||
| Source | Why not |
|
||||
|
||||
@@ -57,8 +57,10 @@ These may change in a **MINOR** (or even PATCH) release without a MAJOR bump:
|
||||
programmatically is not supported (there is no stable library entry point).
|
||||
3. **Experimental / opt-in features**, regardless of the app's version:
|
||||
Gesture Control (beta), Agent Teams
|
||||
(`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`), and anything labeled experimental
|
||||
in the UI or docs. These may change or be removed at any time.
|
||||
(`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`), the native-wrapper window bridge
|
||||
(`window.CodemanHost.openWindow` / `closeWindow` / `focusWindow`), and
|
||||
anything labeled experimental in the UI or docs. These may change or be
|
||||
removed at any time.
|
||||
|
||||
## Deprecation policy
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ output. The other CLIs expose no equivalent.
|
||||
| Respawn cycling and unattended runs | Yes | Yes |
|
||||
| Cron jobs | Yes | Yes |
|
||||
| Docker cases, remote SSH cases | Yes | Yes |
|
||||
| Precise idle detection | Yes | Codex: same screen check, via its own prompt and working line. DeepSeek: reports its state itself. Others: output stabilization, coarser |
|
||||
| Precise idle detection | Yes | Codex, Pi, OpenCode, OMP and Gemini: same screen check, via their own prompt and working line. DeepSeek: reports its state itself. Others: output stabilization, coarser |
|
||||
| Auto-resume when a usage limit resets | Yes | No |
|
||||
| Plan usage chip | Yes | No |
|
||||
| Approvals Inbox | Yes | DeepSeek yes; others no |
|
||||
@@ -121,10 +121,24 @@ Renders its own TUI, so Codeman treats readiness as output stabilization rather
|
||||
watching for a prompt marker. Requires tmux, with no direct-PTY fallback, because its
|
||||
environment is injected through socket-scoped `tmux setenv` rather than the command line.
|
||||
|
||||
Working and idle come from the screen: while a turn runs, OpenCode draws a small spinner at
|
||||
the start of its footer (`⬝■■■■■■⬝ esc interrupt`), and Codeman reads that to tell a working
|
||||
session from an idle one. A pending permission prompt shows as idle, since it is waiting on
|
||||
you. Before 1.40.0 an OpenCode session that had run a tool showed as working for good.
|
||||
|
||||
Integration detail: [`docs/opencode-integration.md`](https://github.com/Ark0N/Codeman/blob/master/docs/opencode-integration.md).
|
||||
|
||||
### Codex
|
||||
|
||||
App Settings has synced **Default Codex model** and **Default Codex reasoning effort**
|
||||
controls. Enter a model ID supported by your Codex provider; available reasoning levels
|
||||
depend on the model and CLI version. Empty defaults use Codex's own configuration.
|
||||
The defaults apply to local Codex sessions started from the Run menu, from Resume, and through
|
||||
`POST /api/sessions` or `/api/quick-start`; scheduled (cron) jobs do not use them.
|
||||
Explicit `codexConfig.model` / `codexConfig.reasoningEffort` values take precedence.
|
||||
Custom model endpoints, Docker containers and remote host command overrides keep their own settings.
|
||||
Changing a default affects new sessions and does not edit Codex configuration files.
|
||||
|
||||
Two behaviours that are deliberate and worth knowing:
|
||||
|
||||
- **Predictive echo instead of buffered echo.** Codex's composer reacts to every keystroke,
|
||||
@@ -148,6 +162,11 @@ needs `GOOGLE_CLOUD_PROJECT`, `GOOGLE_APPLICATION_CREDENTIALS`, and
|
||||
`GOOGLE_GENAI_USE_VERTEXAI`. That is the loosest allowlist entry in Codeman and it affects
|
||||
only the CLI you spawned yourself.
|
||||
|
||||
Working and idle come from the screen: while a turn runs, Gemini CLI draws a spinner line
|
||||
(`⠦ Thinking... (esc to cancel, 6s)`) above its composer, and Codeman reads that. A tool
|
||||
confirmation that waits for you shows as idle. Before 1.40.0 a Gemini session showed as
|
||||
working for good after its first turn.
|
||||
|
||||
### Antigravity
|
||||
|
||||
Google's successor to the consumer Gemini CLI, invoked as `agy`. It keeps all of its state
|
||||
@@ -169,6 +188,10 @@ Pi needs the opposite instincts from every other CLI here.
|
||||
`HF_TOKEN`, and so on) share no common prefix, and the environment allowlist is global
|
||||
rather than per mode, so admitting them for Pi would widen the allowlist for every mode at
|
||||
once. They stay out.
|
||||
- **Work detection reads Pi's composer rule.** Pi has no prompt glyph; while a turn runs it
|
||||
puts a spinner into the rule above the composer (`── ⠏ Working ───`), and Codeman reads
|
||||
that to tell working from idle. Before 1.40.0 a Pi session that had started a turn showed
|
||||
as working for good.
|
||||
|
||||
Guide: [`docs/pi-integration.md`](https://github.com/Ark0N/Codeman/blob/master/docs/pi-integration.md).
|
||||
|
||||
@@ -222,7 +245,9 @@ documented default approval mode is `yolo`, so an OMP pane auto-approves tool us
|
||||
flag from Codeman; change that in OMP's own config, not here.
|
||||
|
||||
OMP conversations appear in Past Sessions and can be resumed, and a respawn continues the
|
||||
same conversation with `--continue`.
|
||||
same conversation with `--continue`. Codeman tells working from idle by reading OMP's status
|
||||
bar, where a spinner and the elapsed time replace the `π` while a turn runs. Before 1.40.0
|
||||
an OMP session that had started a turn showed as working for good.
|
||||
|
||||
Guide: [`docs/omp-integration.md`](https://github.com/Ark0N/Codeman/blob/master/docs/omp-integration.md).
|
||||
|
||||
|
||||
@@ -43,8 +43,8 @@ npm run lint
|
||||
npm run format:check
|
||||
npm run check:frontend-syntax
|
||||
npm run check:browser-excludes
|
||||
npm test -- test/<file>.test.ts # one file, the normal way
|
||||
npm run test:ci # the full CI sweep
|
||||
npm test # the gate, exactly what CI runs
|
||||
npm test -- test/<file>.test.ts # one file
|
||||
```
|
||||
|
||||
`npm install` installs a `pre-push` git hook that runs the static checks above (about 10-40s,
|
||||
@@ -53,13 +53,18 @@ something other than the checked-out HEAD, or when the tree has uncommitted chan
|
||||
checks would read. Skip it once with `CODEMAN_SKIP_PREPUSH=1 git push`; a
|
||||
`pre-push` hook of your own is never overwritten.
|
||||
|
||||
**Never run bare `npm test`.** The default configuration includes browser-driven Playwright
|
||||
suites that need a live server, Chromium, and environment-specific baselines; they hang or
|
||||
fail on a normal machine. `test:ci` is the honest "run everything".
|
||||
`npm test` runs the same suite CI runs, so a green run locally means a green run there. It
|
||||
leaves out three suites that cannot pass on an arbitrary machine, each with its own command:
|
||||
`npm run test:browser` (Playwright, Chromium and a live server), `npm run test:mobile` (the
|
||||
same plus environment-specific screenshot baselines) and `npm run test:perf` (wall-clock
|
||||
benchmarks for an otherwise idle machine). Expect those to fail where the machine cannot
|
||||
provide what they need; that means "not runnable here", not a regression.
|
||||
|
||||
Tests are tmux-safe by design: under vitest the tmux layer becomes an in-memory mock, so
|
||||
tests cannot touch real sessions. If you add a test that binds a port, pick a unique one at
|
||||
3150 or above, and never 3000.
|
||||
tests cannot touch real sessions. If you add a test that binds a port, bind port 0
|
||||
(`new WebServer(0, …)` + `server.boundPort`, or `listen({ port: 0 })` + `address().port`),
|
||||
or use `app.inject()` when no socket is needed. Mobile tests call `createTestServer()` and
|
||||
read `server.boundPort`. Never 3000.
|
||||
|
||||
## Finding your way around
|
||||
|
||||
|
||||
@@ -15,7 +15,8 @@ Codeman-side configuration:
|
||||
- Per-case toggles (Agent Teams, 1M Opus context).
|
||||
- Where it runs, if it is not the local filesystem: see [Location overlays](#location-overlays).
|
||||
|
||||
Three ways to get one, all under **+** next to the case picker:
|
||||
Three ways to get one, all under **New or link a case…** at the bottom of the case picker
|
||||
(the case dropdown in the bottom toolbar; on a phone, the case sheet's **Create New Case**):
|
||||
|
||||
| How | Result |
|
||||
| ----------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
|
||||
@@ -4,8 +4,8 @@ Saved, named jobs that start a session and send it a prompt on a schedule. Cron
|
||||
sessions: *every weekday at 03:00, open a Claude session in `~/proj` and tell it to update
|
||||
dependencies and open a PR.*
|
||||
|
||||
The ⏰ **Cron** header button is opt-in. Turn it on in
|
||||
**App Settings → Header & Panels**.
|
||||
The ⏰ **Cron** button in the bottom toolbar is opt-in. Turn it on under
|
||||
**App Settings → Header & Panels → Scheduling**.
|
||||
|
||||
## Creating a job
|
||||
|
||||
@@ -96,11 +96,19 @@ The skip policy has the details you would want it to have:
|
||||
|
||||
Every fire is recorded per job, with a status:
|
||||
|
||||
| Status | Meaning |
|
||||
| --------- | -------------------------------------------------------------------- |
|
||||
| `created` | The run started and a session was created. |
|
||||
| `skipped` | The concurrency policy blocked it. Not counted as a run. |
|
||||
| `failed` | The prompt could not be resolved, or the working directory was gone. |
|
||||
| Status | Meaning |
|
||||
| ----------------- | ----------------------------------------------------------------- |
|
||||
| `created` | The run record was created; the session has not started yet. |
|
||||
| `session_started` | The session started; prompt delivery is still pending. |
|
||||
| `prompt_sent` | The prompt was sent to the session. |
|
||||
| `skipped` | The concurrency policy blocked it. Not counted as a run. |
|
||||
| `failed` | Prompt resolution, session launch, or prompt delivery failed. |
|
||||
|
||||
History records whether the session started and the prompt was delivered, **not whether
|
||||
the agent's task succeeded**. `prompt_sent` is not a task-completion signal.
|
||||
If the session is closed during the readiness wait or the server restarts before
|
||||
delivery, a run can remain `session_started` indefinitely with `finishedAt: null`;
|
||||
clients must not poll forever waiting for a terminal status.
|
||||
|
||||
The schedule is advanced **before** the session launches, so a slow start cannot cause the
|
||||
same job to re-trigger.
|
||||
|
||||
@@ -4,25 +4,34 @@ Everything the dashboard does is HTTP, so an agent can do it too. This page is f
|
||||
that makes Codeman interesting: **Claude Code running inside a Codeman session, spawning and
|
||||
supervising other sessions.**
|
||||
|
||||
Two routes. Start with the skill.
|
||||
Three routes. Start with the skill, whichever CLI the agent is. Where the skill does not
|
||||
reach (a pi or shell session), use the `codeman agent` commands. Raw HTTP is there for
|
||||
everything else.
|
||||
|
||||
## The agent skill
|
||||
|
||||
A Claude Code skill that teaches the agent the whole API, so you ask in plain English
|
||||
instead of pasting endpoint documentation into prompts.
|
||||
A skill in the `SKILL.md` format that Claude Code, Codex, Gemini CLI, OpenCode, Grok, OMP
|
||||
and most other agent CLIs read. It teaches the agent the whole API, so you ask in plain
|
||||
English instead of pasting endpoint documentation into prompts.
|
||||
|
||||
### Install it
|
||||
|
||||
| How | Command | Scope |
|
||||
| ------------ | ----------------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | Global, any skills-aware agent. |
|
||||
| Skills CLI | `npx skills add Ark0N/Codeman --skill codeman -g` | Global, any skills-aware agent. The way to give it to pi. |
|
||||
| Claude Code plugin | `/plugin marketplace add Ark0N/Codeman`, then `/plugin install codeman@codeman` | Global, through Claude Code's plugin manager. `/plugin update codeman` follows releases. Pick this or `codeman skill install`, not both, or the skill is listed twice (`codeman` and `codeman:codeman`). |
|
||||
| Bundled CLI | `codeman skill install` | Global, at `~/.claude/skills/codeman`. |
|
||||
| Bundled CLI | `codeman skill install --case <name>` | One case. |
|
||||
| Web UI | **App Settings → Agents & CLIs → Claude → Agent Skill** | Injects into each case when a Claude session is created. Off by default. |
|
||||
| Bundled CLI | `codeman skill install --case <name> [--mode <mode>]` | One case. `--mode codex` (or any other run mode) writes it where that CLI looks for skills. |
|
||||
| Web UI | **App Settings → Agents & CLIs → All agent CLIs → Codeman Agent Skill** | Injects into each case when a session is created, where that session's CLI looks: `.claude/skills/` for Claude Code, `.agents/skills/` for Codex, Gemini CLI, OpenCode, Antigravity, Grok, DeepSeek and OMP. Not pi: a project skill makes pi ask to trust the folder at startup. Off by default. |
|
||||
|
||||
`codeman skill uninstall [--case <name>]` reverses the CLI installs, and never touches a
|
||||
`skills/codeman` you wrote yourself.
|
||||
`codeman skill uninstall [--case <name>]` reverses the CLI installs (with `--case`, every
|
||||
Codeman-managed copy in that case), and never touches a `skills/codeman` you wrote yourself.
|
||||
|
||||
Two things to know when the agent is **Codex**: its default sandbox blocks network access
|
||||
even to this machine, so the skill needs **Bypass approvals and sandbox** (App Settings,
|
||||
Codex); and Codex 0.162 runs its commands in a shared background process, whose Codeman
|
||||
variables can belong to the session that started it. The skill checks for both and says so
|
||||
instead of acting.
|
||||
|
||||
### Then just ask
|
||||
|
||||
@@ -59,6 +68,82 @@ DeepSeek Harness workers the same way it drives Claude ones (`spawn_workers alph
|
||||
beta:deepseek` is a mixed fleet in one call), since those are the two modes with real
|
||||
completion signals.
|
||||
|
||||
## The `codeman agent` commands
|
||||
|
||||
The skill drives the API with `curl` and `jq`. Where it does not reach (a pi or shell
|
||||
session, a machine without `jq`), the agent runs in the same environment, so `codeman agent`
|
||||
packages the same verbs as shell commands. It is a thin client over the endpoints in
|
||||
[the manual path](#the-manual-path), so auth and ownership apply unchanged, and it refuses to
|
||||
act outside a Codeman session. One line in a case's `AGENTS.md` is enough: *"other sessions:
|
||||
`codeman agent --help`"*.
|
||||
|
||||
```bash
|
||||
codeman agent ls # sessions; * marks this one
|
||||
SID=$(codeman agent spawn scratch-1 --mode claude) # quick-start + wait for the composer where the mode has a ready mark
|
||||
codeman agent send "$SID" 'review src/, then say DONE' --until stop,exit --timeout 300000
|
||||
codeman agent read "$SID" # last answer (as the server reads it for that mode)
|
||||
codeman agent read "$SID" --tail 3000 # terminal tail, ANSI stripped (every mode)
|
||||
codeman agent send "$SID" 'run the tests, then print WORKDONE followed by _4711' # hook-less modes: the marker in halves …
|
||||
codeman agent wait "$SID" --match WORKDONE_4711 # … and the wait on the joined form
|
||||
codeman agent interrupt "$SID" # a bare ESC, conversation intact
|
||||
codeman agent rm "$SID" # any session except this one
|
||||
```
|
||||
|
||||
- **Ids** may be the 8-character form `ls` prints. Anything shorter refuses, and so does an
|
||||
ambiguous prefix.
|
||||
- **`send`** takes ONE quoted argument of printable text and presses Enter. A prompt that
|
||||
starts with `-` goes after `--`: `codeman agent send "$SID" -- "- fix the bug"`.
|
||||
- **Markers** follow [the split-marker trick](#the-split-marker-trick): the echo of your own
|
||||
prompt is output too, so ask for the marker in halves and wait on the joined form.
|
||||
- **Exit codes** are the same for every verb: `0` done, `1` error, `2` timeout, `3` the
|
||||
worker exited, `4` refused. `--json` prints the response's `data`.
|
||||
|
||||
## The MCP server
|
||||
|
||||
`codeman mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server, so any MCP
|
||||
client (Claude Code, Claude Desktop, Codex, Gemini CLI, Cursor) can drive Codeman, from
|
||||
inside a Codeman session or from an assistant on your desktop. It is a client of the same
|
||||
HTTP API, with seven tools: `list_sessions`, `start_session`, `send_prompt`,
|
||||
`wait_for_session`, `read_output`, `interrupt_session` and `delete_session`.
|
||||
|
||||
```bash
|
||||
# Claude Code
|
||||
claude mcp add codeman -e CODEMAN_API_URL=https://127.0.0.1:3000 -- codeman mcp
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"codeman": {
|
||||
"command": "codeman",
|
||||
"args": ["mcp"],
|
||||
"env": { "CODEMAN_API_URL": "https://127.0.0.1:3000" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
# Codex (~/.codex/config.toml): raise the 60 s default tool timeout for long waits
|
||||
[mcp_servers.codeman]
|
||||
command = "codeman"
|
||||
args = ["mcp"]
|
||||
env = { CODEMAN_API_URL = "https://127.0.0.1:3000" }
|
||||
env_vars = ["CODEMAN_MUX", "CODEMAN_SESSION_ID"] # Codex passes MCP servers a minimal env; these let it know the Codeman session it runs in
|
||||
tool_timeout_sec = 120
|
||||
```
|
||||
|
||||
The JSON form is what Claude Desktop, Cursor and Gemini CLI take. Add `CODEMAN_PASSWORD` to
|
||||
`env` when the server has a password.
|
||||
|
||||
- **It never guesses a server.** Without `CODEMAN_API_URL` (or `--url`) every call says how
|
||||
to configure it.
|
||||
- **Only its own sessions.** Prompting, interrupting and deleting are limited to sessions it
|
||||
started; listing, reading and waiting work on everything. `codeman mcp
|
||||
--allow-any-session` lifts that, for an assistant that should drive your existing tabs.
|
||||
- **Waits are short by default** (45 s, at most 600 s), so they fit a client's tool
|
||||
timeout. A `timed_out` answer means call again.
|
||||
|
||||
## The manual path
|
||||
|
||||
The same operations as raw HTTP, for a CI bot, a shell script, or an agent without skill
|
||||
@@ -189,7 +274,7 @@ followed by a wait races, and reports the previous turn's state.
|
||||
## Lineage
|
||||
|
||||
A create request can name the session that spawned it, through a body field or a header, and
|
||||
the dashboard then draws a lineage arc from parent to child. The skill sets it automatically.
|
||||
the dashboard then draws a lineage line from parent to child. The skill sets it automatically.
|
||||
|
||||
It is resolved rather than trusted: an unresolvable parent is dropped silently rather than
|
||||
failing the spawn, because a cosmetic field must never break a worker.
|
||||
|
||||
@@ -92,6 +92,32 @@ Roughly 235 handlers across 26 route modules. By domain:
|
||||
|
||||
Each route module documents its own endpoints in its file header.
|
||||
|
||||
## Cron jobs
|
||||
|
||||
Saved scheduled jobs are distinct from the legacy `/api/scheduled` loops. Their
|
||||
versioned endpoints are:
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/cron/jobs` | List jobs |
|
||||
| POST | `/api/v1/cron/jobs` | Create a job |
|
||||
| GET | `/api/v1/cron/jobs/:id` | Read a job |
|
||||
| PUT | `/api/v1/cron/jobs/:id` | Update a job (partial body) |
|
||||
| DELETE | `/api/v1/cron/jobs/:id` | Delete a job |
|
||||
| PUT | `/api/v1/cron/jobs/:id/enabled` | Enable/disable with `{ enabled: boolean }` |
|
||||
| POST | `/api/v1/cron/jobs/:id/run` | Run now, without changing the schedule |
|
||||
| GET | `/api/v1/cron/jobs/:id/runs` | Read a job's run history |
|
||||
| GET | `/api/v1/cron/runs` | Read all accessible run history |
|
||||
|
||||
Responses use the envelope above: job lists/history have arrays in `data`, a
|
||||
single-job GET has the job itself, create/update/enable have `{ job }`, delete has
|
||||
`{}`, and Run Now has `{ run, activeAgents }`. Prompt delivery is asynchronous;
|
||||
`session_started` and `prompt_sent` describe launch/delivery, not task success.
|
||||
|
||||
The [cron API reference](https://github.com/Ark0N/Codeman/blob/master/docs/api-reference.md#cron-jobs)
|
||||
lists all request and response fields, validation, and ownership restrictions.
|
||||
[Creating a job](Cron-Jobs) covers the UI and schedule semantics.
|
||||
|
||||
## Long-polling instead of polling
|
||||
|
||||
Three calls block until something happens, so an agent driving Codeman from a shell can wait
|
||||
|
||||
@@ -62,7 +62,9 @@ codeman web # then open http://localhost:3000
|
||||
| Page | What it answers |
|
||||
| ------------------------------------------ | ---------------------------------------------------------- |
|
||||
| [The Dashboard](The-Dashboard) | What is the UI telling me? |
|
||||
| [Tile Grid](Tile-Grid) | How do I watch and drive several sessions side by side? |
|
||||
| [Agent CLIs](Agent-CLIs) | Which agent should this session run, and how do I set it up? |
|
||||
| [Custom Model Endpoints](Custom-Model-Endpoints) | How do I point a session at my own OpenAI-compatible endpoint? |
|
||||
| [Working With Files](Working-With-Files) | How do I read, edit, and attach files? |
|
||||
| [Input And Voice](Input-And-Voice) | How do I talk to an agent, including by voice? |
|
||||
| [Mobile Guide](Mobile-Guide) | How well does this work on a phone? |
|
||||
|
||||
@@ -99,6 +99,14 @@ limit-paused. Without that, the next cycle would fire `/clear` and wipe the conv
|
||||
are waiting to resume. This is the single most useful setting for overnight runs on a
|
||||
subscription plan.
|
||||
|
||||
## The prompt cache readout
|
||||
|
||||
**Claude only.** On the Respawn tab, above the loop controls.
|
||||
|
||||
Claude Code bills a turn against the cached conversation while that cache is warm, and lets the cache expire after a fixed idle time: one hour on a subscription within plan usage, five minutes on an API key, a cloud provider or extra-usage credits. The first turn after a longer break re-processes the whole context at the cache-write rate, which is why coming back to a big session after lunch costs more than the turns around it.
|
||||
|
||||
Claude Code 2.1.251 and newer reports the cache state on the statusline after every response, and Codeman's statusline exporter keeps it per session. The row shows **Warm until HH:MM** with the lifetime and the tokens that would be re-cached if it went cold, or **Cold** with the size of the re-cache the next turn pays. When Claude reports them it also shows the session's cache hit rate and the cause of the last cache miss (for example `ttl_expired_1h` or `tools_changed`), so a surprise miss has a reason next to it. If the conversation is compacted while it stays warm (Claude Code now does this on its own on large idle sessions, a manual `/compact` does it too, and so does a clearing of old tool results), the row notes **Context compacted at HH:MM** until the next turn: Claude Code reports no re-cache size until then. None of this raises an alert. The row refreshes live and flips to cold on its own when the lifetime passes, and the last state is kept across a Codeman restart so it is not blank until the session's next turn. Sessions without a statusline of their own also get a short `cache:until HH:MM` or `cache:cold` group in the terminal footer. The readout rides the plan usage chip's telemetry collection, which is on by default on desktop.
|
||||
|
||||
## The plan usage chip
|
||||
|
||||
**Claude only.** A header chip showing live subscription usage, on by default on desktop and
|
||||
|
||||
@@ -66,7 +66,7 @@ autocorrect: Enter adds a new line, and only Send delivers the text, as one past
|
||||
by Enter, so your line breaks reach the agent intact. Anything already typed on the terminal
|
||||
prompt moves into the editor when it opens. Drafts are kept per session and in memory only,
|
||||
so switching tabs keeps them and a page reload forgets them; a dot on the key shows a draft
|
||||
is parked. The editor's Image button attaches photos and puts their paths into the draft.
|
||||
is parked. The editor's Image button attaches photos or videos and puts their paths into the draft.
|
||||
Destructive commands need a double press, so you cannot fire `/clear` with a stray thumb. On
|
||||
Codex sessions the bar also shows `⇧←` and `⇧→`, the Shift-modified arrows Codex binds to
|
||||
editing the last queued message and walking the prompt stack.
|
||||
@@ -100,13 +100,37 @@ looks exactly like a dead button.
|
||||
On phones this button replaces the desktop's **Run Shell** control; starting a shell moved
|
||||
into the Run dropdown.
|
||||
|
||||
## The Attach button
|
||||
|
||||
The toolbar's **Attach** button (the picture icon beside the mic) is the keyboard-down way to
|
||||
hand the agent a photo or a video. One tap opens the camera and photo library sheet, nothing
|
||||
else: no editor, no keyboard. The chosen files upload and their paths land on the prompt, so
|
||||
you then tap the terminal, write the rest of your message and press Enter. Videos (mp4, webm,
|
||||
mov, m4v, ogv) upload as recorded, up to 1 GB each by default
|
||||
(`CODEMAN_MAX_PASTE_VIDEO_BYTES` on the server changes it), so a long 4K clip takes a moment
|
||||
on the way up.
|
||||
|
||||
If the keyboard was up when you tapped Attach, iOS closes it to show the photo sheet and does
|
||||
not bring it back, so the tap on the terminal is how you get it again. That is the system's
|
||||
behaviour around its own picker rather than a Codeman setting.
|
||||
|
||||
The paths go onto the prompt as unsent text, exactly like something you typed, which means
|
||||
they travel with it. Tap **Compose** afterwards and the editor opens holding the paths *and*
|
||||
anything you had already typed, so you can write in front of a path, fix a word, and Send.
|
||||
**Use terminal keyboard** hands a single-line message back the other way, onto the prompt,
|
||||
so neither surface holds a half of your message. A multi-line message cannot make that trip
|
||||
(the prompt is a single line), so it stays parked as a draft and the dot on the Compose key
|
||||
shows it is waiting. The Compose editor's own Image button remains for the times you are
|
||||
already writing in the editor.
|
||||
|
||||
## Tapping, links and copying
|
||||
|
||||
- **Tap a link** in terminal output and it opens in a new tab. Same for a link in an agent's
|
||||
answer in the response viewer — it opens a tab rather than navigating the dashboard away,
|
||||
which on a phone would unload the whole session view.
|
||||
- **Tap a file path** an agent printed and the file-preview overlay opens; a log path opens the
|
||||
log viewer. Works in scrolled-up transcript too.
|
||||
- **Tap a file path** an agent printed and the file-preview overlay opens (Markdown rendered,
|
||||
HTML as a page); a log or other plain-text path opens the log viewer. Works in scrolled-up
|
||||
transcript too.
|
||||
- A tap on the prose *beside* a link still places the cursor as usual, and a tap on a dialog's
|
||||
numbered choice still answers the dialog even when the row contains a path — the dialog wins,
|
||||
because on a phone it is the only interaction that matters.
|
||||
@@ -158,7 +182,7 @@ enough to fix a typo an agent introduced while you are away from your desk.
|
||||
enforces it.
|
||||
- The Approvals bell. Phones get the NEEDS YOU strips on the home screen instead.
|
||||
- The desktop home tab rail, which needs a wide window.
|
||||
- Lineage arcs, which are a desktop overlay.
|
||||
- Lineage lines, which are a desktop overlay.
|
||||
|
||||
## Gotchas
|
||||
|
||||
|
||||
@@ -63,12 +63,19 @@ Ultracode Windows, Cron.
|
||||
|
||||
**Bottom bar** (below the chips): **Git status** shows a small indicator at the right of the
|
||||
bottom bar, off by default and per device. It reads `● N` uncommitted files, `↑ N` commits not
|
||||
pushed, `⚠ N` merge conflicts, or `✓` when everything is committed and pushed. Click it for the
|
||||
Git window; see [Working With Files](Working-With-Files#git-changes). **Git status: group files
|
||||
pushed, `⚠ N` merge conflicts, `? N` repositories git could not read, or `✓` when everything is
|
||||
committed and pushed. Click it for the Git window; see
|
||||
[Working With Files](Working-With-Files#git-changes). **Git status: group files
|
||||
by folder** (per device, on by default) shows changed files under collapsed folders in that
|
||||
window; off lists every file by its full path.
|
||||
window; off lists every file by its full path. **Git status: max repositories** (per device,
|
||||
1 to 50, default 12) is how many repositories the window lists when a session's folder holds
|
||||
several projects. **Git status: git timeout** (per device, 5 to 120 seconds, default 30) is how
|
||||
long one git command may run before that repository is reported as unreadable; raise it for
|
||||
repositories on a slow network share.
|
||||
|
||||
Most default to off. The stock desktop header is system stats, File Viewer, and the gear.
|
||||
Most default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
|
||||
**Header Stats Style** picks how the system stats and plan usage are drawn: *Compact*
|
||||
(default; two pills with a ring beside every value), *Tiles* (label over value with a bar underneath) or *As before* (the bars and the `5H · 7D` chip). Desktop only, per device.
|
||||
New header controls never appear on phones. Split is desktop-only regardless of this
|
||||
setting — the button and the feature both stay off below a ~1180px viewport, where two
|
||||
resizable panes plus their divider have nowhere to go. **Tiles** is desktop-only the same
|
||||
@@ -83,18 +90,31 @@ every session or only the active tab.
|
||||
| Setting | Notes |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------- |
|
||||
| Skin | Theme palettes, light ones included. Applied before first paint, so no flash of the wrong theme. |
|
||||
| Entrance Animations | Per-surface animation styles for tabs, terminals, windows, and lineage lines. All default to the legacy no-animation behaviour. |
|
||||
| Display Name | Your name in the UI. Cosmetic only; it never renames the package, CLI, API, or storage. |
|
||||
| Interface Language | English or Simplified Chinese. Per device. |
|
||||
| Session List Layout | Header tab strip (default), a collapsible left sidebar, or the sidebar with detailed rows. See [The Dashboard](The-Dashboard#session-list-layout). |
|
||||
| Tab Orientation | Keeps the header list but turns the strip vertical beside the terminal, resizable, with detailed rows by default. Desktop and tablet only. |
|
||||
| Vertical Rail Order | *By activity* (default) sorts the rail the way the home screens are sorted; *Manual* keeps your tab order and drag-reordering. |
|
||||
| Tab Layout | *Classic* (default): the single list as before. *By state*: a row each for needs you, waiting, working and idle, sections in the rail and sidebar. *By case*: one box per case. *Ledger*: an aligned column grid. See [The Dashboard](The-Dashboard#tab-layouts). |
|
||||
| State Order | For *By state*: needs you on top (default) or at the bottom, right above the terminal. |
|
||||
| Vertical Rail Order | *By activity* (default) sorts the rail the way the home screens are sorted; *Manual* keeps your tab order and drag-reordering. With *By state* or *By case* it orders the rows inside each section. |
|
||||
| Tall Tabs | Taller tab strip. |
|
||||
| CLI Logos on Tabs | Each agent tab, and its row on the desktop home rail, shows the CLI's logo before the name. Off hides those logos on this device; the status dot and the shell's SH badge stay, and tiles, split headers and the Run menus keep their logos. On by default. |
|
||||
| Pop-out Button on Tabs | Adds the detach control to tabs, with a per-tab override. |
|
||||
| Spawn Lineage Lines | Arcs from a parent tab to sessions it spawned. Desktop only, on by default. |
|
||||
| Spawn Lineage Lines | Lines from each tab to the sessions it spawned; the selected tab's family is drawn thicker. Desktop only, on by default. |
|
||||
| Auto-name Sessions | Titles a new tab after its first prompt, keeping the case prefix (`w3-myapp: fix the login redirect`). Synced, off by default. See [The Dashboard](The-Dashboard#automatic-session-names). |
|
||||
| Spawned Tabs Follow Their Parent | A session started by another one (an agent's worker, a `parentSessionId` spawn) follows its parent's tab into its group and moves with it until you move it by hand; the row menu then says where it sits and offers *Follow parent again*. Off, it starts right after its parent and stays put. Decided when the tab is created, so flipping it leaves existing tabs alone. Synced, off by default. |
|
||||
| Overview Home Screen | The phone home screen. On by default. |
|
||||
|
||||
### Animations
|
||||
|
||||
All per device, all off by default, applied as you pick them.
|
||||
|
||||
| Setting | Notes |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------- |
|
||||
| Entrance Theme | One look for how new tabs, terminal panes, agent windows and their lines arrive (Terminal, Beam down, Launch, Soft focus, Quiet, Playful). Off by default. |
|
||||
| Tile Animations | How tiles arrive when the tile grid opens and leave when it closes: fly out of their tabs, dealt from the Tiles button, CRT, beam down, cascade, pop or soft; each screen then plays the theme's terminal animation. Off by default (the grid's quick fade); picking a theme presets it. |
|
||||
| Animation Lab | Opens the per-surface lab (the same as `?animlab=1`): every style side by side, with replay, stagger and speed. Closes settings first. |
|
||||
|
||||
### Models
|
||||
|
||||
Claude model cards, the 1M context window switch, the thinking effort segment and the
|
||||
@@ -126,16 +146,22 @@ instead of its native cloud backend. See [Custom Model Endpoints](Custom-Model-E
|
||||
| Allowed Tools | The list used by the explicit mode. |
|
||||
| Ralph / Todo Tracker | Enables the Ralph loop surfaces. |
|
||||
| Agent Teams | Experimental teams. Also needs the CLI's own environment flag. |
|
||||
| Codeman Agent Skill | Injects the agent skill into new Claude sessions per case. Off by default. See [Driving Codeman From An Agent](Driving-Codeman-From-An-Agent). |
|
||||
| Codeman Agent Skill | Under **All agent CLIs**. Injects the agent skill into each new session's case, where that session's CLI looks for skills (every CLI except Pi and a plain shell). Off by default. See [Driving Codeman From An Agent](Driving-Codeman-From-An-Agent). |
|
||||
| Remote auto-reconnect | Reattaches dropped remote SSH sessions. On by default. |
|
||||
| Nice priority / value | Runs agent processes at a lower CPU priority. |
|
||||
| Bypass approvals and sandbox | Pi's project trust. Read [Agent CLIs](Agent-CLIs) before enabling. |
|
||||
| Default Codex model | Model for new local Codex sessions; empty uses Codex's own config. Letters, digits, `.` `_` `-` `/` only. |
|
||||
| Default Codex reasoning effort | Reasoning level for new local Codex sessions; empty uses Codex's own config. |
|
||||
| Bypass approvals and sandbox | Starts new Codex sessions with `--dangerously-bypass-approvals-and-sandbox`. Read [Agent CLIs](Agent-CLIs) before enabling. |
|
||||
| Animated status effects | Cosmetic. |
|
||||
| MCP server sync | Copies the MCP servers each installed, enabled CLI (Claude, Codex, Gemini, OpenCode, Antigravity) has into the others' own config files. Synced, off by default, admin only in multi-user mode. Turn it on and save, then **Preview** shows what would change and **Sync now** applies it. It only adds missing servers, keeps the previous file as `.codeman-bak`, and leaves a file that receives env values or headers readable by you only. A config dir moved by `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `XDG_CONFIG_HOME` or `GEMINI_CLI_HOME` in Codeman's own environment is followed. |
|
||||
| MCP server sync | Copies the MCP servers each installed, enabled CLI (Claude, Codex, Gemini, OpenCode, Antigravity) and GitHub Copilot CLI has into the others' own config files. Synced, off by default, admin only in multi-user mode. Turn it on and **Apply** or **Save** (Apply keeps Settings open), then **Preview** shows what would change and **Sync now** applies it. It only adds missing servers, keeps the previous file as `.codeman-bak`, and leaves a file that receives env values or headers readable by you only. A config dir moved by `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `XDG_CONFIG_HOME`, `GEMINI_CLI_HOME` or `COPILOT_HOME` in Codeman's own environment is followed. |
|
||||
|
||||
### Notifications
|
||||
|
||||
Master toggle, browser notifications, push subscription, audio alerts, the idle
|
||||
Master toggle, browser notifications, push subscription, audio alerts, how long a
|
||||
corner toast stays on screen (**Toast display time**, 1 to 300 seconds, default 3) and
|
||||
how long a desktop notification stays up before Codeman closes it (**Browser
|
||||
notification display time**, default 8; both per device, and your OS may close a
|
||||
desktop notification sooner), the idle
|
||||
threshold that decides when a quiet session counts as needing you, and the server-wide
|
||||
webhook (ntfy, Slack, Discord or generic JSON; admins only in multi-user mode). See
|
||||
[Notifications And Approvals](Notifications-And-Approvals).
|
||||
@@ -154,7 +180,7 @@ Rebinding for the shortcut registry. See [Keyboard Shortcuts](Keyboard-Shortcuts
|
||||
### System
|
||||
|
||||
`CLAUDE.md` template for new cases, default working directory, the image watcher, and
|
||||
Cloudflare tunnel controls including the tunnel and upload URLs. The **Diagnostics** group runs
|
||||
Cloudflare tunnel controls including the tunnel URL. The **Diagnostics** group runs
|
||||
`codeman doctor` on the server and lists the agent CLIs, tmux, Node and the optional office
|
||||
tools with their versions and install hints (admin only in multi-user mode). In multi-user
|
||||
mode, the **Users** administration entry is injected here.
|
||||
@@ -191,6 +217,8 @@ Some things are configured before the server starts, not in the UI:
|
||||
| `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` | Acknowledges exposing the server with no password. |
|
||||
| `CODEMAN_BASE_URL` | Mounts Codeman under a sub-path behind a reverse proxy that forwards the prefix unchanged. See [Remote Access](Remote-Access). |
|
||||
| `CODEMAN_MAX_DOWNLOAD_BYTES` | Cap on raw file bodies and downloads. 2 GB by default, `0` for none. |
|
||||
| `CODEMAN_MAX_PASTE_IMAGE_BYTES` | Cap on one pasted, dropped or attached image. 50 MB by default. |
|
||||
| `CODEMAN_MAX_PASTE_VIDEO_BYTES` | Cap on one attached video (phone Attach, drop). 1 GB by default; videos stream to disk, so this bounds disk use, not memory. |
|
||||
| `CODEMAN_MAX_REMOTE_FILE_SSH` | Concurrent ssh reads for files in remote cases. 4 by default. |
|
||||
| `CODEMAN_PATH_PROBE_TIMEOUT_MS` | How long a linked case's folder may take to answer before it is shown as unreachable. 1500 ms by default; raise it for a slow but healthy mount. |
|
||||
| `CODEMAN_PATH_PROBE_MAX_STALLED` | Unanswered folder checks allowed to pile up before new ones are refused. 2 by default: one below the threadpool size minus one, so it follows `UV_THREADPOOL_SIZE` (4 unless set), and it is never allowed above that ceiling. A check you start by opening one case or session may use the one slot left above it. |
|
||||
|
||||
@@ -6,7 +6,7 @@ Most of Codeman's UI is **opt-in**. A stock install shows a deliberately small h
|
||||
feature you read about here may simply not be on screen yet. Where that is the case, this
|
||||
page says so and names the setting.
|
||||
|
||||

|
||||

|
||||
|
||||
## Layout
|
||||
|
||||
@@ -15,7 +15,7 @@ page says so and names the setting.
|
||||
| **Header, left** | The "C" logo (goes home) and the session list, unless you moved it to the sidebar. |
|
||||
| **Header, right** | Status chips and panel buttons, most of them off by default. |
|
||||
| **Center** | The terminal for the active session, or the home screen when nothing is selected. |
|
||||
| **Bottom toolbar** | Run, Stop, Run Shell, the case picker, and the instance counters. |
|
||||
| **Bottom toolbar** | Run, Stop, Run Shell, the case picker, and the instance counter. |
|
||||
| **Overlays** | Panels and modals: Respawn, Cron, Subagents, File Viewer, Settings. |
|
||||
|
||||
## Session list layout
|
||||
@@ -27,18 +27,56 @@ Session List Layout** can move it into a vertical sidebar on the left instead, a
|
||||
|
||||
| Layout | Behaviour |
|
||||
| -------------------- | --------------------------------------------------------------------------------- |
|
||||
| **Header tab strip** | The default. Wraps to a second row on desktop, scrolls sideways on a phone. |
|
||||
| **Header tab strip** | The default. One list in tab order unless you pick another [Tab layout](#tab-layouts); it scrolls sideways on a phone. |
|
||||
| **Left sidebar** | A vertical list with a filter box and a live session count. `Alt+B` collapses it to a narrow rail that keeps the status dots and task badges visible. On a phone it is an off-canvas drawer rather than a docked rail. A detailed variant adds the home screen's per-session line (`created 3d ago · working 12m`) and a status pill. |
|
||||
| **Vertical rail** | The strip turned vertical beside the terminal, resizable, with detailed rows by default. **Vertical Rail Order** sorts it by activity (blocked on you first, then longest running, then most recently quiet), the same order as the home screens; pick *Manual* to get your own order and drag-reordering back. **Tab groups:** pick *Move to new group* from a row's ⋯ menu (or Shift+F10 on it) to make the first one; a group header's menu (right-click, Shift+F10 or its ⋯ glyph) renames it (also F2), reorders or deletes it, rows move between groups from their own menu or by dragging with a mouse or pen, and a collapsed group stays collapsed on that device. Desktop and tablet only. |
|
||||
| **Vertical rail** | The strip turned vertical beside the terminal, resizable, with detailed rows by default. **Vertical Rail Order** sorts it by activity (blocked on you first, then longest running, then most recently quiet), the same order as the home screens; pick *Manual* to get your own order and drag-reordering back. **Tab groups:** pick *Move to new group* from a row's ⋯ menu (or Shift+F10 on it) to make the first one; a group header's menu (right-click, Shift+F10 or its ⋯ glyph) renames it (also F2), reorders or deletes it, rows move between groups from their own menu or by dragging with a mouse or pen, and a collapsed group stays collapsed on that device. **Search sessions** at the top of the rail narrows it to the tabs whose name matches (a web tab by its title), across every group, collapsed ones included, without changing the groups or the order; a tab with an alert stays visible even when its name does not match; Escape or × clears it, and it is never saved. **Focus:** *Add to Focus* in a row's ⋯ menu (right-click on a web tab) pins a shortcut to that tab in a **Focus** section at the top of the rail, with or without groups; the tab itself stays where it is. Click a shortcut to switch to its tab, right-click it (or press the menu key) for *Remove from Focus*. Focus follows you across devices; whether it is collapsed is kept per device. Desktop and tablet only. |
|
||||
|
||||
It is the same list either way, just re-hosted: tab order, drag-to-reorder, the `Alt+1`
|
||||
to `Alt+9` numbers and every status colour below behave identically in both. The setting is
|
||||
per device, so a sidebar on your desktop does not force one onto your phone.
|
||||
|
||||
## Tab layouts
|
||||
|
||||
**App Settings → Appearance → Tabs → Tab Layout** picks how the tabs are arranged. Per device.
|
||||
|
||||
| Layout | What it does |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------ |
|
||||
| **By state** | Groups the tabs by what each session needs from you (below). |
|
||||
| **By case** | One box per case, labelled with the case and its tab count. Inside a box, `w75-api-gateway` reads just `w75`. A case with one tab gets a box with a colour swatch. |
|
||||
| **Ledger** | The same list on an aligned column grid: equal cells, monospace names, a coloured bar on the left of each cell instead of the dot (yellow waiting, red needs you). Desktop header only. |
|
||||
| **Classic** (default) | The single list in tab order, as before. |
|
||||
|
||||
**By state** groups the tabs like this, most urgent on top:
|
||||
|
||||
| Group | Who is in it |
|
||||
| ------------- | ----------------------------------------------------------------------------------- |
|
||||
| **Needs you** | Red: a question or permission prompt is blocking the agent. A failed session too. |
|
||||
| **Waiting** | Yellow: the agent finished its turn and is waiting for your next prompt. |
|
||||
| **Working** | A turn is running. |
|
||||
| **Idle** | Everything quiet, including ended sessions, agents that exited inside their pane, and web tabs. |
|
||||
|
||||
In the header each group is a row with its name and count on the left (Idle, the quiet
|
||||
default, carries no label); a group with more tabs than fit on one line continues on the
|
||||
next line. **State Order → Needs you at the
|
||||
bottom** turns the rows the other way up, so the needs-you row sits right above the
|
||||
terminal. Empty groups are not shown. These are the same states the phone overview and the
|
||||
desktop home rail use, and tabs move between groups on their own as their state changes.
|
||||
|
||||
Both groupings also apply to the vertical rail and the left sidebar, as labelled sections.
|
||||
Inside a group or a box tabs keep your tab order (on a rail sorted *By activity*, the
|
||||
activity order), and the `Alt+1` to `Alt+9` numbers never change. Dragging reorders tabs
|
||||
within a group or box. On a phone the strip stays a single scrolling row in group order,
|
||||
without labels or boxes. If you have named tab groups in the vertical rail, those take
|
||||
precedence there.
|
||||
|
||||
## Session tabs
|
||||
|
||||
One tab per session, in your order, and that order syncs across your devices.
|
||||
|
||||
An agent tab shows its CLI's logo before the name, and a shell tab an `SH` badge. **CLI Logos
|
||||
on Tabs** (App Settings → Appearance → Tabs) hides the logos on that device; the tile and split
|
||||
headers and the Run menus keep theirs.
|
||||
|
||||
**Status is carried by the dot and the tab's own styling:**
|
||||
|
||||
| Look | Meaning |
|
||||
@@ -84,13 +122,18 @@ title is derived locally from the prompt's first sentence; no text leaves the ma
|
||||
On phones the strip scrolls horizontally instead of wrapping, and the active tab is always
|
||||
scrolled into view. It is not reordered to the front, so the `Alt+N` numbering stays stable.
|
||||
|
||||
### Lineage arcs
|
||||
### Lineage lines
|
||||
|
||||
When one session spawns another (an agent starting a worker through the API), Codeman draws
|
||||
a coloured arc under the strip connecting parent to child, with one colour per child. It is
|
||||
how a fan-out of eight workers stays readable.
|
||||
lines from the parent to each child, in the parent's colour, routed through the gaps between
|
||||
tab rows so they never cover a tab or the terminal. Every family is always shown; selecting
|
||||
a tab draws its own family thicker and brighter. A dashed branch means that child is
|
||||
working. It is how a fan-out of eight workers stays readable.
|
||||
|
||||
Desktop only, and on by default. Turn it off in **App Settings → Appearance**. Arcs are
|
||||
While any tab has spawned another, the strip keeps a little extra room between rows for the
|
||||
lines, so switching tabs never changes the header height.
|
||||
|
||||
Desktop only, and on by default. Turn it off in **App Settings → Appearance**. Lines are
|
||||
skipped for tabs scrolled out of the strip.
|
||||
|
||||
## Header controls
|
||||
@@ -102,7 +145,7 @@ The right side of the header. Almost all of these are off until you enable them
|
||||
| ---------------------- | ------------------ | ------------------------------------------------------------------------------- |
|
||||
| Connection dot | Always on | SSE connection health. Green is connected. |
|
||||
| Font size `-` / `+` | Always on | `Ctrl +` / `Ctrl -` do the same. |
|
||||
| CPU / MEM bars | On | Server resource use. |
|
||||
| CPU / MEM | On | Server resource use. Drawn as a compact pill by default; see Header Stats Style below. |
|
||||
| File Viewer | On | Toggles the file browser panel. |
|
||||
| Settings gear | Always on | App Settings. |
|
||||
| Plan usage chip | On, desktop only | Live Claude subscription usage. Claude-only, and needs its telemetry exporter, which the same setting installs. |
|
||||
@@ -118,10 +161,23 @@ The right side of the header. Almost all of these are off until you enable them
|
||||
| Cron ⏰ | Off | Scheduled jobs. |
|
||||
| Multi-monitor | Off, macOS | Opens a window spanning every display. |
|
||||
| Split | Off, desktop only | View a second session beside the active one, with a draggable divider. |
|
||||
| Tiles | Off, desktop only | Up to six live sessions side by side. See [Tile Grid](Tile-Grid). |
|
||||
| Tiles | On, desktop only | Up to six live sessions side by side. See [Tile Grid](Tile-Grid). |
|
||||
| Tunnel indicator | When a tunnel runs | Cloudflare tunnel status. |
|
||||
| Admin panel | Multi-user only | User administration. |
|
||||
|
||||
### Header Stats Style
|
||||
|
||||
The connection readout, CPU, MEM and the plan usage windows can be drawn three ways
|
||||
(**App Settings → Header & Panels → Header Stats Style**, per device, desktop only):
|
||||
|
||||
| Style | Look |
|
||||
| -------------- | -------------------------------------------------------------------------------------- |
|
||||
| **Tiles** | One small tile each (`WS live`, `CPU 22%`, `MEM 14.4G`, `5H 28%`, `7D 35%`): label over value, a thin bar underneath, no icons. |
|
||||
| **Compact** | The default. Two slim pills, `WS · CPU · MEM` and the plan windows, with a small ring beside every value. Hands the tabs back the most room. |
|
||||
| **As before** | The bars and the `5H · 7D` chip, exactly as they were. |
|
||||
|
||||
Hiding System Stats or Plan Usage still hides them in every style.
|
||||
|
||||
New header controls never appear on phones. Phone layout is deliberately minimal and is
|
||||
covered in [Mobile Guide](Mobile-Guide).
|
||||
|
||||
@@ -158,15 +214,26 @@ TUIs render correctly.
|
||||
Worth knowing:
|
||||
|
||||
- **Scrollback.** Agent/TUI sessions pull their entire tmux scrollback on first open.
|
||||
A fullscreen Claude tab keeps its history inside Claude, so switching back to it
|
||||
reloads only the current screen, which keeps tab switches fast.
|
||||
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
|
||||
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
|
||||
history; press **Load full history** to pull the rest explicitly. Automatic output
|
||||
history; press **Load full history** to pull the rest explicitly. That notice only
|
||||
appears once you scroll to the top, leaves when you scroll back down, and stays away
|
||||
for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen
|
||||
Claude) never show it, since there is nothing more to load. Automatic output
|
||||
recovery stays within the bounded browser buffer.
|
||||
- **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent
|
||||
Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in
|
||||
`~/.claude/settings.json`), so the wheel scrolls the conversation rather than the terminal.
|
||||
Claude's default inline view keeps its history in the terminal and scrolls locally. `Shift+Wheel` is
|
||||
always local scrollback. Other CLIs scroll locally.
|
||||
always local scrollback. OpenCode's wheel and swipes page its own conversation
|
||||
(PageUp/PageDown), and so do newer Codex versions, which draw on the alternate screen
|
||||
and leave the terminal no history of its own (an older Codex that draws inline keeps
|
||||
its history in the terminal and scrolls locally). The first small movement of a
|
||||
gesture pages at once, then one page per half screen of travel; one finger on the
|
||||
screen is one gesture however slowly it moves. In a grid tile or the split view's
|
||||
second pane the wheel pages too. Other CLIs scroll locally.
|
||||
- **Selection copy.** `Ctrl+C` copies when text is selected and interrupts when it is not.
|
||||
`Ctrl+Shift+C` always copies.
|
||||
- **Selecting where the CLI owns the mouse.** `Shift+drag` starts a selection even in a pane
|
||||
@@ -200,7 +267,7 @@ Two extras depending on the device:
|
||||
| Respawn | Session Options | [Keeping Agents Running](Keeping-Agents-Running) |
|
||||
| Ralph | Session Options | [Autonomous Loops](Autonomous-Loops) |
|
||||
| Orchestrator | Toolbar | [Autonomous Loops](Autonomous-Loops) |
|
||||
| Cron | Header ⏰ (opt-in) | [Cron Jobs](Cron-Jobs) |
|
||||
| Cron | Bottom toolbar ⏰ (opt-in) | [Cron Jobs](Cron-Jobs) |
|
||||
| Subagents | Automatic while agents run | [Watching Agents Work](Watching-Agents-Work) |
|
||||
| Ultracode | Header (opt-in) | [Watching Agents Work](Watching-Agents-Work) |
|
||||
| File Viewer | Header | [Working With Files](Working-With-Files) |
|
||||
|
||||
@@ -9,29 +9,39 @@ never offered in a popped-out session window.
|
||||
|
||||
## Turning it on
|
||||
|
||||
**App Settings → Header & Panels → Tiles.** This is a per-device setting, off by default,
|
||||
so turning it on at your desk never puts the button on your phone. It shows a **Tiles**
|
||||
button in the header, beside Split, and enables `Ctrl+Shift+G`.
|
||||
**App Settings → Header & Panels → Tiles.** This is a per-device setting, on by default
|
||||
on desktops and laptops and off on phones and tablets, and the button only appears in a
|
||||
window at least 1180px wide.
|
||||
It shows a **Tiles** button in the header, beside Split, and enables `Ctrl+Shift+G`.
|
||||
|
||||
## Opening a grid
|
||||
|
||||
- **Tiles button**: one click shows the tiles straight away, as many as you last chose
|
||||
(six until you choose; fewer if the window is too small or you have fewer sessions open).
|
||||
You get the grid you last had, its tiles where they were, topped up with your open
|
||||
sessions in tab order; if there is none, an open split's two first; otherwise your open
|
||||
sessions in tab order, with the session you are on focused. With the grid open, the same
|
||||
button closes it.
|
||||
- **Tiles button**: one click shows the tiles straight away. If you have used the grid in
|
||||
this browser before, you get it back exactly as you left it: the same sessions in the
|
||||
same places, an empty place where you left one, the same number of tiles, your column
|
||||
widths and row heights, the tile you were in, and a zoomed tile still zoomed. A session
|
||||
closed since frees its place, which is filled the way a new grid is filled (below).
|
||||
Otherwise, or when none of those sessions is left, you get as many tiles as you last
|
||||
chose (six until you choose; fewer if the window is too small or you have fewer sessions
|
||||
open): an open split's two first; otherwise the sessions that are working (the most
|
||||
recently started first), then the ones waiting on you (red and yellow tabs), then the
|
||||
rest, the most recently used first, so the oldest are the ones left out. The session you
|
||||
are on always comes along and is focused. With the grid open, the same button closes it.
|
||||
- **Rest the pointer on the Tiles button** (or tab to it) for a short card that shows the
|
||||
count it opens and what a click and a right-click do.
|
||||
count you chose and what a click and a right-click do.
|
||||
- **Right-click the Tiles button** (or press `Shift+F10` on it) to choose how many tiles:
|
||||
**2**, **4** or **6**, each drawn as its layout. Your choice is remembered on this device
|
||||
and is what the next click opens. With the grid open, picking a count re-forms it: the
|
||||
tile you are in always stays, extra tiles leave from the end, new ones join from your tab
|
||||
order. A count the window is too small for is greyed out, with the reason.
|
||||
**2**, **4** or **6**, each drawn as its layout. Your choice is remembered in this
|
||||
browser. Picking a count opens the grid with that many tiles (the grid you left, its
|
||||
tiles in their places, new ones in the empty places first), and it is what a click opens
|
||||
when there is no grid to bring back. With the grid open, picking a count re-forms it: the
|
||||
tile you are in always stays, extra tiles leave from the end, new ones join working ones
|
||||
first, then the ones waiting on you, then the most recent. A count the window is too
|
||||
small for is greyed out, with the reason.
|
||||
- **`Ctrl+Shift+G`**: exactly what a click on the Tiles button does.
|
||||
- **`Ctrl`+click (or `Cmd`+click) a tab**: adds that session to the grid and focuses it. With
|
||||
the grid closed it opens what the Tiles button would show, with that session among them
|
||||
(still the count you chose in total). On macOS use
|
||||
the grid closed it opens what the Tiles button would show with that session added: in the
|
||||
empty place while the grid has fewer tiles than the count you chose, else in place of the
|
||||
last tile (never more than the count). On macOS use
|
||||
`Cmd`: `Ctrl`+click there opens the tab's rename instead.
|
||||
- **Drag a tab onto a tile** to replace that tile with it (the replaced session keeps
|
||||
running), or onto an empty slot to add it. Dragging a session that is already tiled onto
|
||||
@@ -58,7 +68,7 @@ Each tile has a small header: `● [logo] name · model ......... ⋯ ⤢ ×`
|
||||
| `●` | The session's state: working, idle, waiting on you, needs you (red, and the tile's border pulses), error, ended. Hover the header for how long. |
|
||||
| logo | Which agent runs in the tile (Claude Code, Codex, DeepSeek, Shell, ...). Hover it for the agent and the model by name. |
|
||||
| name | Double-click to rename the session. |
|
||||
| model | The model the session runs, when Codeman knows it: what the agent itself reports (it follows a `/model` switch), else the model its own config pins (DeepSeek's route, shown "from config"), else the model it was started with. Nothing when unknown. |
|
||||
| model | The model the session runs, when Codeman knows it: what the agent itself reports (it follows a `/model` switch), else the model its own config pins (DeepSeek's route, shown "from config"), else the model it was started with. Nothing when unknown. OpenCode shows the model and its provider together (`Big Pickle OpenCode Zen`), exactly as its own composer does. |
|
||||
| `⋯` | The session menu: options, open in a new window, close the session. |
|
||||
| `⤢` | Zoom: the tile fills the grid; press it again (or `Alt+Shift+Enter`) to get the grid back. |
|
||||
| `×` | Remove the tile. The session keeps running; close it from `⋯` if you want it gone. |
|
||||
@@ -88,7 +98,8 @@ keeps the focus.
|
||||
|
||||
A moved tile takes the size of the place it lands in: column widths and row heights stay
|
||||
where you dragged the dividers. Tiles do not move while one is zoomed. Where everything is,
|
||||
the empty slot included, is saved with the grid and comes back on reload.
|
||||
the empty slot included, is saved with the grid and comes back when you turn the grid off
|
||||
and on, and on a page reload while the grid is open.
|
||||
|
||||
Closing a tile leaves its place empty when the grid keeps its shape (six tiles to five), and a
|
||||
new tile takes the first empty place. When the number of tiles changes the grid's shape (four
|
||||
@@ -121,8 +132,18 @@ session finder) shows that session on its own, the normal single view. The grid
|
||||
remembered: the Tiles button or `Ctrl+Shift+G` brings it straight back. Going Home does the
|
||||
same. Narrowing the window below the desktop width also returns to the single view.
|
||||
|
||||
The grid is saved on this device and comes back when you reload the page, with its focus,
|
||||
zoom and column widths. A session that was closed in the meantime is simply left out.
|
||||
The grid is saved in this browser every time you change it (moving, resizing, adding or
|
||||
removing a tile, changing the count, focusing or zooming a tile), and never sent to the
|
||||
server. However you leave it (the Tiles button, another tab, Home, a link, closing its last
|
||||
tile or session), the Tiles button brings it back as it was. A page reload brings it back
|
||||
when the grid was open; after you left it, a reload shows the single view and the Tiles
|
||||
button still brings the grid back. A session that was closed or popped out into its own
|
||||
window in the meantime frees its place for another one, picked the way a new grid picks
|
||||
them; the place stays empty only when no other session is left. Right after a page reload
|
||||
the page does not know yet which sessions are waiting for your answer, so that pick goes by
|
||||
which sessions are working and which you used last. If the window has become too small for
|
||||
all the tiles, the tile you were in fills the grid until the window is wide enough again,
|
||||
and the rest of the layout is kept.
|
||||
|
||||
Split shows the same logo, name and model above both of its panes.
|
||||
|
||||
|
||||
@@ -22,13 +22,18 @@ transcript: what it was asked to do, what it is doing, and what it returned.
|
||||
This is the feature that makes a fan-out legible. Without it, a lead session that spawned
|
||||
eight workers looks like a stalled terminal for several minutes.
|
||||
|
||||
## Session lineage arcs
|
||||
## Session lineage lines
|
||||
|
||||
The tab strip draws a coloured arc from a parent tab to any tab it spawned, one colour per
|
||||
child. That covers the other direction of fan-out: not subagents inside one session, but
|
||||
whole sessions started by an agent through the API.
|
||||
The tab strip draws lines from every tab to the tabs it spawned. That covers the other
|
||||
direction of fan-out: not subagents inside one session, but whole sessions started by an
|
||||
agent through the API.
|
||||
|
||||
Desktop only, on by default, and toggled in **App Settings → Appearance**. Arcs are skipped
|
||||
The lines form one tree per spawning tab, in that tab's colour, and run only through the
|
||||
gaps between tab rows, so they never cover a tab name or the terminal. Select a tab and its
|
||||
family (the tabs it spawned, or its parent and siblings) is drawn thicker and brighter. A
|
||||
dashed branch means that child is working.
|
||||
|
||||
Desktop only, on by default, and toggled in **App Settings → Appearance**. Lines are skipped
|
||||
for tabs scrolled out of view.
|
||||
|
||||
See [Driving Codeman From An Agent](Driving-Codeman-From-An-Agent) for the spawning side.
|
||||
@@ -42,7 +47,8 @@ in the CLI's own environment:
|
||||
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
|
||||
```
|
||||
|
||||
and turn the per-case **Agent Teams** toggle on in the case settings gear.
|
||||
and turn the per-case **Agent Teams** toggle on under **Case settings…** at the bottom of the case
|
||||
picker (the gear beside the case button on a phone).
|
||||
|
||||
Codeman watches the team directory and matches teammates to the session leading them.
|
||||
Teammates are in-process threads rather than separate CLI processes, so they show up as
|
||||
|
||||
@@ -14,9 +14,10 @@ It renders what it can:
|
||||
| Kind | Behaviour |
|
||||
| ------------------------ | ------------------------------------------------------------------------- |
|
||||
| Text and code | Plain preview with Lines (line numbers) and Wrap toggles in the header. Long files are truncated in plain preview. |
|
||||
| Markdown | Rendered by default: headings, tables, code blocks with copy buttons, images and links relative to the file (root-relative ones resolve from the workspace root, as on GitHub). Opened from an attachment card, where the file's folder is unknown, relative images show their alt text and relative links show as plain text. The MD pill in the header flips to source. |
|
||||
| Markdown | Rendered by default: headings, tables, code blocks with copy buttons, images and links relative to the file (root-relative ones resolve from the workspace root, as on GitHub). Links to another heading of the same file (`[Install](#installation)`) scroll to it, with GitHub's heading names (lower-case, punctuation dropped, repeats numbered `-1`, `-2`), and never leave the page. Opened from an attachment card, where the file's folder is unknown, relative images show their alt text and relative links show as plain text. The MD pill in the header flips to source. |
|
||||
| Images | Inline. |
|
||||
| Audio and video | Inline with a working scrub bar, because range requests are supported. |
|
||||
| Spreadsheets (`.xlsx`) | Read-only grid, parsed in your browser (never on the server), up to 10 MB. `.xls` and `.ods` are download only. |
|
||||
| PDF and Office documents | Converted for preview when a converter is available. |
|
||||
| Anything else | Download. |
|
||||
|
||||
@@ -86,9 +87,10 @@ File paths in a session are links. That works in two places:
|
||||
render as underlined monospace links.
|
||||
|
||||
Clicking one opens it in the preview: images and PDFs render, video and audio play with a
|
||||
working scrub bar, documents convert, text shows inline and Markdown renders. The exception is
|
||||
a text or Markdown file inside the workspace clicked in the terminal: that opens in the tail
|
||||
viewer instead, which follows a file that is still being written.
|
||||
working scrub bar, documents convert, text shows inline, Markdown renders and HTML opens as a
|
||||
page. The exception is a plain text file (a log, `.txt`, `.json`, code) inside the workspace
|
||||
clicked in the terminal: that opens in the tail viewer instead, which follows a file that is
|
||||
still being written. A Markdown file always opens rendered, wherever you click it.
|
||||
|
||||
Paths **outside** the session's workspace work too, which matters because that is where most
|
||||
of an agent's output lands: a screenshot in `/tmp`, a capture in its own scratchpad, a file in
|
||||
@@ -100,8 +102,24 @@ Outside the workspace the allowlist is images, video, audio, PDF, Office documen
|
||||
files, where "text" is the same list the viewer will let you edit: code, config, logs, csv,
|
||||
markdown. The reasoning is that a session can already `cat` any of those, so the file suffix
|
||||
was never what kept anything secret; the path guard is. Types outside the list (`.svg`,
|
||||
`.bmp`) say so rather than failing silently, and `.html` previews as source rather than being
|
||||
rendered, so nothing served this way can execute in the page.
|
||||
`.bmp`) say so rather than failing silently.
|
||||
|
||||
An `.html` file opens as a rendered page by default, with its relative CSS, scripts, images and
|
||||
data files. The page is served from a separate `/html-view/...` address in a sandbox with no
|
||||
origin of its own, so its scripts can never read Codeman's page, cookies or API.
|
||||
|
||||
By the project owner's decision, a rendered page has the same network access as a file you open
|
||||
from disk in your browser. It **can** load scripts, styles, fonts, images and media from
|
||||
anywhere on the internet (a dashboard that pulls Chart.js from a CDN works), send requests to
|
||||
any host, and read the files in its own folder. It **cannot** act as Codeman: it has no access
|
||||
to Codeman's page, cookies or API, and no access to any folder other than its own. Since a page
|
||||
can send what it can read to any host, open HTML only from sources you trust, as you would on
|
||||
your own desktop. The **Page**
|
||||
pill in the viewer header switches to the source view (where **Edit** works as for any text
|
||||
file), and the viewer falls back to source on its own when a page cannot be rendered: a remote
|
||||
(SSH) case, an HTML file inside a hidden folder, or one sitting directly in a broad folder such
|
||||
as your home folder or `/tmp` (the page may read the files in its own folder tree, so move it
|
||||
into a folder of its own). The raw file routes still serve HTML as a download only.
|
||||
|
||||
Text previews are capped at the first 500 lines, fetched as a partial read, so clicking a
|
||||
one-gigabyte log does not try to paint one.
|
||||
@@ -154,9 +172,13 @@ expose everyone.
|
||||
|
||||
Paste from the clipboard or drag and drop straight onto the terminal. The image is written
|
||||
where the agent can read it and the reference is inserted into your prompt. On a phone, the
|
||||
image key in the keyboard bar opens the camera or photo library.
|
||||
toolbar's Attach button opens the camera or photo library, videos included, and puts the path
|
||||
on your prompt, where it behaves like text you typed; the Image button inside the Compose
|
||||
editor does the same into the editor. Dropping a video onto the terminal works the same way.
|
||||
|
||||
HEIC images from an iPhone are converted to JPEG on the way in.
|
||||
Videos (mp4, webm, mov, m4v, ogv) are stored as recorded, up to 1 GB each by default
|
||||
(`CODEMAN_MAX_PASTE_VIDEO_BYTES`); they stream to disk rather than through server memory.
|
||||
|
||||
## Generated artifacts
|
||||
|
||||
@@ -168,7 +190,7 @@ surface as an artifact attachment rather than a path you have to go and find.
|
||||
Agents often leave work uncommitted or unpushed. Turn on **App Settings → Header & Panels →
|
||||
Bottom bar → Git status** (per device, off by default) and the right of the bottom bar shows
|
||||
the active session's repository: `● 3` uncommitted files, `↑ 2` commits not pushed, `⚠` merge
|
||||
conflicts, `✓` when everything is committed and pushed.
|
||||
conflicts, `? 1` a repository git could not read, `✓` when everything is committed and pushed.
|
||||
|
||||
Click it for a draggable window, in the style of the File Viewer:
|
||||
|
||||
@@ -187,7 +209,10 @@ Click it for a draggable window, in the style of the File Viewer:
|
||||
**Open file** jumps to the File Viewer; **Back** returns to the list. A binary file shows a
|
||||
note instead, and a diff over 400 KB is cut short.
|
||||
- A session folder that holds several projects gets one collapsible section per repository
|
||||
found up to two levels down. They all start collapsed (each summary line shows its branch and
|
||||
found up to two levels down (up to **Git status: max repositories**, 12 by default; the window says
|
||||
when there are more). A repository git could not read, typically a timeout on a slow network
|
||||
share, is listed with the reason and counted as `? N` in the bottom-bar indicator, never silently
|
||||
left out; the **git timeout** setting raises how long it waits. They all start collapsed (each summary line shows its branch and
|
||||
what is outstanding), and the ones you open stay open when the window refreshes; an unrelated repository above the workspace (a dotfiles repo
|
||||
in your home folder) is ignored.
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.35.0",
|
||||
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"version": "1.41.1",
|
||||
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
|
||||
"mcpName": "io.github.Ark0N/codeman",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@@ -42,7 +43,7 @@
|
||||
"check:lockfile": "node scripts/check-lockfile-sync.mjs",
|
||||
"check:plugin": "node scripts/sync-plugin.mjs --check && claude plugin validate --strict plugins/codeman && claude plugin validate --strict .claude-plugin/marketplace.json",
|
||||
"knip": "npx --yes knip@latest --config config/knip.json",
|
||||
"release": "changeset publish"
|
||||
"release": "node scripts/npm-release.mjs"
|
||||
},
|
||||
"prettier": {
|
||||
"singleQuote": true,
|
||||
@@ -129,6 +130,8 @@
|
||||
"agent-browser": "^0.6.0",
|
||||
"esbuild": "^0.27.3",
|
||||
"eslint": "^9.0.0",
|
||||
"exceljs": "4.4.0",
|
||||
"fflate": "0.8.3",
|
||||
"pixelmatch": "^6.0.0",
|
||||
"playwright": "^1.58.0",
|
||||
"pngjs": "^7.0.0",
|
||||
@@ -169,7 +172,7 @@
|
||||
"bugs": {
|
||||
"url": "https://github.com/Ark0N/Codeman/issues"
|
||||
},
|
||||
"homepage": "https://github.com/Ark0N/Codeman#readme",
|
||||
"homepage": "https://getcodeman.com",
|
||||
"files": [
|
||||
"dist",
|
||||
"scripts/postinstall.js",
|
||||
|
||||
@@ -133,6 +133,13 @@ its CSP for WebAssembly). Deploy = copy the bundle into Codeman's
|
||||
drop point. Pinch the panel again to move it anywhere. It stays inside the
|
||||
camera-owning page, so the hand keeps control (the old `window.app.detachSession`
|
||||
`window.open` was a one-way trip). A small twitch-and-release cancels.
|
||||
- **Tiles** (tile grid open): pinch anywhere on a tile and carry it onto
|
||||
another tile (the two trade places) or an empty cell (it moves there). A
|
||||
session tab carried onto a tile or an empty cell joins the grid there. With
|
||||
**Detach Tiles** on (App Settings, per device, off by default) a tile let go
|
||||
outside the grid opens as a window of its own, which needs the site's pop-ups
|
||||
allowed (a hand is no click). The moves are tile-grid.js's own
|
||||
(`tileDropTargetAt` / `dropOnTileTarget` / `detachTileAtPoint`).
|
||||
- **Run / Run Shell** — pinch over the **Run** (`#runBtn`) or **Run Shell**
|
||||
(`.btn-shell`) toolbar button and release in place to fire it; drifting too
|
||||
far first cancels the tap. The button list is `CLICK_SELECTOR` in `entry.ts`.
|
||||
|
||||
@@ -27,6 +27,14 @@
|
||||
// • Button "tap" — pinch over a toolbar button (Run / Run Shell) and release
|
||||
// in place → fires the button's real click handler. Drift too far first and
|
||||
// it's treated as a stray move, not a tap.
|
||||
// • Tile "grab-to-move": with the tile grid open, pinch anywhere on a tile
|
||||
// and carry it onto another tile (the two trade places) or an empty cell
|
||||
// (it moves there). With Detach Tiles on (App Settings, per device, off by
|
||||
// default) a tile let go OUTSIDE the grid opens as a window of its own.
|
||||
// A session TAB carried onto a tile or an empty cell joins the grid there,
|
||||
// as a mouse-dragged tab does. Every move goes through app.js's own paths
|
||||
// (tile-grid.js tileDropTargetAt / dropOnTileTarget / detachTileAtPoint), so
|
||||
// the hand and the mouse can never disagree about what a drop does.
|
||||
//
|
||||
// Why in-page floats, not OS-window detach (decided 2026-06-08, see
|
||||
// docs/MULTIMONITOR_DESIGN.md): the hand only exists in the one page that owns
|
||||
@@ -52,11 +60,22 @@ declare global {
|
||||
saveSubagentWindowStates?: () => void;
|
||||
subagentWindowZIndex?: number;
|
||||
ultracodeWindowZIndex?: number;
|
||||
// The tile grid (tile-grid.js). All optional: an older dashboard without
|
||||
// them simply has no tile verbs for the hand.
|
||||
tileAtPoint?: (x: number, y: number) => string | null;
|
||||
canGrabTile?: (id: string) => boolean;
|
||||
tileDropTargetAt?: (x: number, y: number, draggedId: string) => TileTarget | null;
|
||||
dropOnTileTarget?: (draggedId: string, target: TileTarget) => boolean;
|
||||
isOverTileGrid?: (x: number, y: number) => boolean;
|
||||
tileDetachEnabled?: () => boolean;
|
||||
detachTileAtPoint?: (id: string, x: number, y: number, at?: { offsetX: number; offsetY: number }) => boolean;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const TAB_SELECTOR = '.session-tab';
|
||||
/** A tile of the open tile grid (tile-grid.js), keyed by `data-session-id`. */
|
||||
const TILE_SELECTOR = '#tileGrid .tile';
|
||||
/** An in-page floating session panel this layer spawned — re-grabbable to move. */
|
||||
const PANEL_SELECTOR = '.cg-float';
|
||||
/** The dashboard's own floating agent windows (subagent runs + ultracode run and
|
||||
@@ -81,11 +100,20 @@ const FLOAT_H = 420;
|
||||
const DETACH_PULL_PX = 70;
|
||||
/** If a button-pinch drifts more than this, it's a stray move, not a tap. */
|
||||
const TAP_CANCEL_PX = 45;
|
||||
/** How far (px) a grabbed tile must travel before it targets anything: a pinch
|
||||
* that barely moves is a stray one, and the tile stays where it is. */
|
||||
const TILE_MOVE_PX = 40;
|
||||
/** The width (px) of the small copy of a grabbed tile that follows the hand. */
|
||||
const TILE_GHOST_W = 280;
|
||||
|
||||
/** First letter colours: cyan left, violet right; green while pinching. */
|
||||
const handColor = (handedness: string, pinching: boolean): string =>
|
||||
pinching ? '#4ade80' : handedness === 'Right' ? '#a78bfa' : '#38bdf8';
|
||||
|
||||
/** Where a session carried by the hand would land in the tile grid: another
|
||||
* tile, or an empty cell (tile-grid.js tileDropTargetAt). */
|
||||
type TileTarget = { kind: 'tile'; id: string; el: HTMLElement } | { kind: 'cell'; cell: number; el: HTMLElement };
|
||||
|
||||
/** A floating in-page session panel (an iframe of `/session/:id`) the hand can
|
||||
* place and re-grab. Stays in this page's DOM, so it never leaves hand reach. */
|
||||
interface FloatingPanel {
|
||||
@@ -107,6 +135,29 @@ type Grab =
|
||||
oy: number;
|
||||
/** Pulled past the float-out threshold at least once. */
|
||||
armed: boolean;
|
||||
/** With the tile grid open: the tile or empty cell it would join (highlighted). */
|
||||
target: TileTarget | null;
|
||||
}
|
||||
| {
|
||||
/** A tile of the open grid, carried to another cell or (Detach Tiles)
|
||||
* out of the grid. The tile itself never moves until the drop: it dims
|
||||
* (`tile--dragging`, the mouse drag's own class) and a small copy of
|
||||
* it follows the hand. */
|
||||
kind: 'tile';
|
||||
id: string;
|
||||
el: HTMLElement;
|
||||
ghost: HTMLElement;
|
||||
/** Where in the tile the hand closed, so a pop-out window lands under it. */
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
ox: number;
|
||||
oy: number;
|
||||
/** Travelled past TILE_MOVE_PX at least once. */
|
||||
armed: boolean;
|
||||
/** The tile or empty cell it would drop onto (highlighted). */
|
||||
target: TileTarget | null;
|
||||
/** Outside the grid with Detach Tiles on: letting go opens a window. */
|
||||
out: boolean;
|
||||
}
|
||||
| {
|
||||
kind: 'panel';
|
||||
@@ -224,7 +275,7 @@ class GestureBridge {
|
||||
await this.gc.start();
|
||||
this.running = true;
|
||||
this.button.classList.add('on');
|
||||
this.status.textContent = 'on — pinch a tab, window, or button';
|
||||
this.status.textContent = 'on: pinch a tab, tile, window, or button';
|
||||
} catch (err) {
|
||||
// Surface the *real* cause: MediaPipe/Emscripten can throw a non-Error
|
||||
// (number/string), so `(err as Error).message` was logging "undefined".
|
||||
@@ -295,6 +346,35 @@ class GestureBridge {
|
||||
return;
|
||||
}
|
||||
|
||||
// A tile of the open tile grid → carry it to another cell, or (Detach
|
||||
// Tiles) out of the grid. Anywhere on the tile: the hand is choosing the
|
||||
// whole tile, as with the agent windows. A tile that can do neither (alone
|
||||
// or zoomed, Detach Tiles off) is left alone, so the pinch falls through.
|
||||
const tileId = window.app?.tileAtPoint?.(x, y) ?? null;
|
||||
const tileEl = tileId ? this.hitClosest(x, y, TILE_SELECTOR) : null;
|
||||
if (tileId && tileEl && window.app?.canGrabTile?.(tileId)) {
|
||||
const rect = tileEl.getBoundingClientRect();
|
||||
const ghost = this.tileGhost(tileEl, rect);
|
||||
document.body.append(ghost);
|
||||
tileEl.classList.add('tile--dragging');
|
||||
this.grabs.set(hand, {
|
||||
kind: 'tile',
|
||||
id: tileId,
|
||||
el: tileEl,
|
||||
ghost,
|
||||
offsetX: Math.max(0, Math.min(x - rect.left, rect.width)),
|
||||
offsetY: Math.max(0, Math.min(y - rect.top, rect.height)),
|
||||
ox: x,
|
||||
oy: y,
|
||||
armed: false,
|
||||
target: null,
|
||||
out: false,
|
||||
});
|
||||
this.positionGhost(ghost, x, y);
|
||||
this.status.textContent = 'moving tile';
|
||||
return;
|
||||
}
|
||||
|
||||
// A session tab → grab-and-pull-out into a floating panel (ghost follows).
|
||||
const tab = this.hitClosest(x, y, TAB_SELECTOR);
|
||||
const id = tab?.dataset.id;
|
||||
@@ -308,7 +388,7 @@ class GestureBridge {
|
||||
document.body.append(ghost);
|
||||
|
||||
tab.classList.add('cg-grabbed');
|
||||
this.grabs.set(hand, { kind: 'tab', id, tab, ghost, ox: x, oy: y, armed: false });
|
||||
this.grabs.set(hand, { kind: 'tab', id, tab, ghost, ox: x, oy: y, armed: false, target: null });
|
||||
this.positionGhost(ghost, x, y);
|
||||
return;
|
||||
}
|
||||
@@ -325,13 +405,42 @@ class GestureBridge {
|
||||
|
||||
private onDrag(hand: string, x: number, y: number): void {
|
||||
const grab = this.grabs.get(hand);
|
||||
if (grab?.kind === 'tile') {
|
||||
this.positionGhost(grab.ghost, x, y);
|
||||
if (!grab.armed && Math.hypot(x - grab.ox, y - grab.oy) >= TILE_MOVE_PX) grab.armed = true;
|
||||
if (!grab.armed) return;
|
||||
const app = window.app;
|
||||
const target = app?.tileDropTargetAt?.(x, y, grab.id) ?? null;
|
||||
this.setTileTarget(grab, target);
|
||||
const out = !target && !!app?.tileDetachEnabled?.() && !app?.isOverTileGrid?.(x, y);
|
||||
grab.out = out;
|
||||
grab.ghost.classList.toggle('cg-armed', !!target);
|
||||
grab.ghost.classList.toggle('cg-out', out);
|
||||
this.status.textContent = target
|
||||
? target.kind === 'tile'
|
||||
? 'release to swap tiles'
|
||||
: 'release to move the tile here'
|
||||
: out
|
||||
? 'release to open in a new window'
|
||||
: 'moving tile';
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === 'tab') {
|
||||
this.positionGhost(grab.ghost, x, y);
|
||||
const pulled = Math.hypot(x - grab.ox, y - grab.oy) >= DETACH_PULL_PX;
|
||||
if (pulled !== grab.armed) {
|
||||
// The tile grid open: a tile or an empty cell under the hand takes the
|
||||
// tab there, as a mouse-dragged tab does.
|
||||
const target = pulled ? (window.app?.tileDropTargetAt?.(x, y, grab.id) ?? null) : null;
|
||||
const targetChanged = (target?.el ?? null) !== (grab.target?.el ?? null);
|
||||
this.setTileTarget(grab, target);
|
||||
if (pulled !== grab.armed || targetChanged) {
|
||||
grab.armed = pulled;
|
||||
grab.ghost.classList.toggle('cg-armed', pulled);
|
||||
this.status.textContent = pulled ? 'release to float out' : 'on — pinch a tab';
|
||||
this.status.textContent = target
|
||||
? 'release to tile it here'
|
||||
: pulled
|
||||
? 'release to float out'
|
||||
: 'on — pinch a tab';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -354,17 +463,44 @@ class GestureBridge {
|
||||
if (tap && Math.hypot(x - tap.ox, y - tap.oy) > TAP_CANCEL_PX) {
|
||||
tap.el.classList.remove('cg-tap-armed');
|
||||
this.taps.delete(hand);
|
||||
this.status.textContent = 'on — pinch a tab, window, or button';
|
||||
this.status.textContent = 'on: pinch a tab, tile, window, or button';
|
||||
}
|
||||
}
|
||||
|
||||
private onDrop(hand: string, x: number, y: number): void {
|
||||
const grab = this.grabs.get(hand);
|
||||
if (grab?.kind === 'tile') {
|
||||
this.grabs.delete(hand);
|
||||
grab.ghost.remove();
|
||||
grab.el.classList.remove('tile--dragging');
|
||||
this.setTileTarget(grab, null);
|
||||
const app = window.app;
|
||||
if (!grab.armed) {
|
||||
this.flash('cancelled');
|
||||
return;
|
||||
}
|
||||
// Asked again at the drop: the grid may have changed since the last frame.
|
||||
const target = app?.tileDropTargetAt?.(x, y, grab.id) ?? null;
|
||||
if (target) {
|
||||
this.flash(app?.dropOnTileTarget?.(grab.id, target) ? 'moved tile' : 'cancelled');
|
||||
} else if (grab.out && !app?.isOverTileGrid?.(x, y)) {
|
||||
// A window opened with no click behind it is what popup blockers stop:
|
||||
// detachSession then says so in a toast and the tile stays.
|
||||
const opened = app?.detachTileAtPoint?.(grab.id, x, y, { offsetX: grab.offsetX, offsetY: grab.offsetY });
|
||||
this.flash(opened ? 'opened in a new window' : 'pop-out blocked: allow popups for this site');
|
||||
} else {
|
||||
this.flash('cancelled');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (grab?.kind === 'tab') {
|
||||
this.grabs.delete(hand);
|
||||
grab.ghost.remove();
|
||||
grab.tab.classList.remove('cg-grabbed');
|
||||
if (grab.armed) this.floatPanel(grab.id, x, y);
|
||||
this.setTileTarget(grab, null);
|
||||
const target = grab.armed ? (window.app?.tileDropTargetAt?.(x, y, grab.id) ?? null) : null;
|
||||
if (target) this.flash(window.app?.dropOnTileTarget?.(grab.id, target) ? 'tiled' : 'cancelled');
|
||||
else if (grab.armed) this.floatPanel(grab.id, x, y);
|
||||
else this.flash('cancelled');
|
||||
return;
|
||||
}
|
||||
@@ -505,6 +641,33 @@ class GestureBridge {
|
||||
ghost.style.top = `${y}px`;
|
||||
}
|
||||
|
||||
/** A small copy of a tile to follow the hand: its header (a copy: no
|
||||
* listeners come along) over an empty body, in the tile's proportions. */
|
||||
private tileGhost(tileEl: HTMLElement, rect: DOMRect): HTMLElement {
|
||||
const ghost = el('div', 'cg-ghost cg-tile-ghost');
|
||||
const width = Math.min(TILE_GHOST_W, rect.width);
|
||||
ghost.style.width = `${width}px`;
|
||||
ghost.style.height = `${Math.max(48, Math.round((width * rect.height) / Math.max(1, rect.width)))}px`;
|
||||
const header = tileEl.querySelector('.tile-header');
|
||||
if (header) {
|
||||
const copy = header.cloneNode(true) as HTMLElement;
|
||||
copy.removeAttribute('draggable');
|
||||
ghost.append(copy);
|
||||
}
|
||||
ghost.append(el('div', 'cg-tile-ghost-body'));
|
||||
return ghost;
|
||||
}
|
||||
|
||||
/** Highlights the tile or empty cell a carried session would drop onto
|
||||
* (the mouse drag's own `tile--drop-target`), clearing the last one. */
|
||||
private setTileTarget(grab: { target: TileTarget | null }, target: TileTarget | null): void {
|
||||
if (grab.target?.el !== target?.el) {
|
||||
grab.target?.el.classList.remove('tile--drop-target');
|
||||
target?.el.classList.add('tile--drop-target');
|
||||
}
|
||||
grab.target = target;
|
||||
}
|
||||
|
||||
private cancelAllGrabs(): void {
|
||||
// Floats themselves persist (they're placed windows) — only release any
|
||||
// in-progress grab cleanly, restoring a moved panel's interactivity.
|
||||
@@ -512,6 +675,11 @@ class GestureBridge {
|
||||
if (grab.kind === 'tab') {
|
||||
grab.ghost.remove();
|
||||
grab.tab.classList.remove('cg-grabbed');
|
||||
this.setTileTarget(grab, null);
|
||||
} else if (grab.kind === 'tile') {
|
||||
grab.ghost.remove();
|
||||
grab.el.classList.remove('tile--dragging');
|
||||
this.setTileTarget(grab, null);
|
||||
} else if (grab.kind === 'panel') {
|
||||
grab.panel.el.style.pointerEvents = '';
|
||||
grab.panel.el.classList.remove('cg-float-grabbed', 'cg-redock');
|
||||
@@ -525,6 +693,7 @@ class GestureBridge {
|
||||
document
|
||||
.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed, .cg-win-grabbed`)
|
||||
.forEach((t) => t.classList.remove('cg-grabbed', 'cg-tap-armed', 'cg-win-grabbed'));
|
||||
document.querySelectorAll(`${TILE_SELECTOR}.tile--dragging`).forEach((t) => t.classList.remove('tile--dragging'));
|
||||
}
|
||||
|
||||
private onStatus(fps: number, hands: HandState[]): void {
|
||||
@@ -607,6 +776,13 @@ function injectStyles(): void {
|
||||
outline: 2px solid #38bdf8; outline-offset: -2px;
|
||||
}
|
||||
.cg-ghost.cg-armed { outline-color: #4ade80; box-shadow: 0 8px 28px rgba(74,222,128,.5); }
|
||||
.cg-ghost.cg-out { outline-color: #fbbf24; box-shadow: 0 8px 28px rgba(251,191,36,.5); }
|
||||
.cg-tile-ghost {
|
||||
display: flex; flex-direction: column; overflow: hidden; transform: translate(-50%, -20%) scale(1);
|
||||
background: var(--term-bg, #161b23); border: 1px solid var(--border-color, #333);
|
||||
}
|
||||
.cg-tile-ghost > .tile-header { flex: 0 0 auto; }
|
||||
.cg-tile-ghost-body { flex: 1 1 auto; opacity: .5; }
|
||||
.cg-dock {
|
||||
position: fixed; right: 12px; bottom: 156px; z-index: ${Z + 3};
|
||||
display: flex; align-items: center; gap: 8px; font: 12px/1 system-ui, sans-serif;
|
||||
|
||||
@@ -1,5 +1,51 @@
|
||||
# xterm-zerolag-input
|
||||
|
||||
## 0.4.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 87f1c9c: ### Thanks
|
||||
- @Randalix for `codeman agent` (#557), the session verbs (`ls`, `spawn`, `send`, `wait`, `read`, `interrupt`, `rm`) for agents in every CLI mode, and for moving every test server onto an ephemeral port (#570), which finishes #440. Thanks also for reporting and fixing git's clone errors on non-English hosts (#568, shipped as #572 with your commit).
|
||||
- @opticon454 for five PRs: MCP server sync for GitHub Copilot CLI (#581), an Apply button that saves Settings without closing them (#565), configurable toast and browser-notification display times (#564), in-document links in rendered markdown that scroll to their heading (#563), and npm-based CLI installs that work when the system npm prefix is root-owned (#562).
|
||||
- @JDProfresh for three PRs: pasted and uploaded files moving into a hidden, self-ignoring `.codeman-uploads/` folder (#574, after your #553 proposal), local echo that keeps painting on phones when the view sits above the bottom (#576), and upload failures that say why they failed (#578).
|
||||
- @aakhter for session search on the vertical tab rail (#580), built on the sidebar's existing filter instead of a second one, and for keeping alerted tabs visible during a search.
|
||||
|
||||

|
||||
|
||||
**Tile Animations (#571).** The tile grid from 1.40.0 can now open with a show. App Settings has a new **Animations** section (right after Appearance) that holds every animation setting: the Entrance Theme (moved out of Appearance), the new **Tile Animations** row, and a button that opens the animation lab. Tile styles: **CRT** (each tile switches on as a hot line in a diagonal wave, and switches off to a line and a dot), **Fly from tab** (each tile grows out of its session tab and flies back into it), **Deal** (dealt out of the Tiles button like cards), **Beam down**, **Cascade**, **Pop**, **Soft** and **None**. A styled tile plays in two beats: the frame enters in the tile style, then its screen powers on in the terminal style of your Entrance Theme. Picking a theme presets a matching tile style, and a new **Launch** theme flies the tiles out of their tabs. Off by default (the grid keeps its quick fade), per device, nothing moves under reduced motion, and the animations never cost an extra PTY resize. The terminal pane's Boot entrance style is gone; a saved Boot falls back to off.
|
||||
|
||||
**Tiles open the sessions you care about, and keep your layout.** With no grid arranged yet, the Tiles button (or `Ctrl+Shift+G`) now fills the grid with the sessions that are working first (most recently started first), then the ones waiting on you (a permission prompt or a finished turn you have not seen), then the most recently used, instead of the tabs in strip order, which opened the oldest ones. The session you are on is still always included. Once you arrange a grid (which session sits where, empty cells, the tile count, divider sizes, the focused and zoomed tile), that layout is remembered in this browser and the Tiles button brings it back exactly, however the grid was closed, and so does a reload while it was open. A session that has gone since frees its place, which the same ranking fills. A grid larger than the window opens in full with the focused tile zoomed, instead of being trimmed (and losing the rest of your layout).
|
||||
|
||||
**The wheel scrolls Claude inside a tile (#577).** In a tile or the split's second pane, a Claude session on its fullscreen renderer now scrolls its own conversation with the mouse wheel, exactly like the main terminal: the wheel goes to Claude as mouse reports, aimed at that tile's session and computed from the tile's own screen. Before, the wheel did nothing or scrolled the stale frames left over from loading the tile. Shift+wheel (scroll local history) works in every tile on Windows and Linux too; it was dead there.
|
||||
|
||||
**`codeman agent`: session verbs for every CLI (#557).** Agents in any mode (Codex, OpenCode, Gemini, Pi and the rest, not just Claude) can now drive other Codeman sessions from the command line: `codeman agent ls | spawn | send | wait | read | interrupt | rm`. It is a thin client over the existing session API: every call names the session that made it, `wait` blocks on a signal (`--until stop,exit`) or a literal output marker (`--match`), and exit codes say what happened (`0` ok, `1` error, `2` timeout, `3` exited, `4` refused). Ids shorter than 8 characters are refused, so a stray `rm 9` can never pick a session at random, and `rm` never deletes the session it runs in. See the README section "`codeman agent`" and the wiki page Driving Codeman From An Agent. This is phase 1 of #445.
|
||||
|
||||
**Settings: Apply (#565).** Next to Save, an Apply button saves the same way but keeps Settings open. Switching on MCP server sync makes its Preview and Sync usable straight away, and CLI management's add, enable and disable work without closing and reopening Settings.
|
||||
|
||||
**MCP server sync reaches GitHub Copilot CLI (#581).** With MCP server sync on (App Settings, off by default), Copilot CLI's `~/.copilot/mcp-config.json` now takes part like the agent CLIs' own files: its servers are copied to the others and theirs to it, additively, with the previous file kept as `.codeman-bak`. Copilot joins only when it is installed or already has that file, a server switched off in Copilot is never copied, and `COPILOT_HOME` is followed. Copilot is a sync target only, not a new run mode.
|
||||
|
||||
**Notifications stay up longer if you want (#564).** Settings → Notifications has a Toast display time and a Browser notification display time (1 second to 5 minutes, per device; the defaults stay 3 s and 8 s).
|
||||
|
||||
**CLI logos on tabs can be switched off (#569).** App Settings → Appearance → Tabs → **CLI Logos on Tabs** hides the agent logo on every tab surface (header strip, rails, sidebar, phone chips, the desktop home list) on this device. On by default. Tile headers, split pane headers and the Run menus keep their logos.
|
||||
|
||||
**Search sessions on the vertical rail (#580).** The vertical tab rail has a **Search sessions** box at the top: type part of a name and the rail narrows to the tabs that match (a web tab by its title), across every group, collapsed ones included, without touching your groups, their collapse or the tab order. A tab with an alert stays visible even when its name does not match, so a prompt waiting on you is never filtered away. Escape or × clears it, you can still drag a found tab into a group, and nothing is saved. The sidebar's filter box shares the same filter: a tab with an alert stays visible there too, and in the by-case tab layout a case with no match now hides.
|
||||
|
||||
**Closing a tab is instant.** Closing a session used to take half a second or more before the tab went away. The tab, tile or split pane now goes (and the next session is selected) the moment you click, while the server shuts the session down in the background, and the server side is faster too (about 450 ms down to 200-260 ms for a Claude session): it no longer sleeps fixed intervals, no longer freezes for about 70 ms per close on a synchronous tmux call, and scans for a session's subagents once instead of once per subagent. If the server refuses the close, the tab comes back where it was with the error. This also fixes a bug where a failed close still said "Session closed" while the session kept running.
|
||||
|
||||
**Fixes.**
|
||||
- **Clone errors on non-English hosts (#572, from #568).** Cloning a repository as a case now classifies a failed clone correctly whatever the host's language: a missing branch or tag is "does not exist on the remote" (400) and a missing repository is a 404, instead of a generic 422 with git's German (or any other) error text. Git runs with `LC_ALL=C` for clones and repo status, so the repo status card's error text is English on every host as well.
|
||||
- **Links within a markdown file (#563).** A link to another heading of the same document (`[Install](#installation)`) in the File Viewer or Response Viewer scrolls to that heading instead of doing nothing. Headings get GitHub-style slugs, repeated titles are numbered, and non-ASCII headings work.
|
||||
- **npm CLI installs on a root-owned prefix (#562).** Installing an npm-based CLI from Settings (DeepSeek's `dsh`, pi, ...) no longer fails with EACCES when the system node keeps its global prefix under `/usr`: the install goes to `~/.local`, where Codeman already looks for CLIs. A prefix you set yourself, or one you can write to, is left alone, including when Codeman runs under `npm run`.
|
||||
- **Uploads go to a hidden `.codeman-uploads/` folder (#574).** Images you paste or upload into a prompt are saved in `<workspace>/.codeman-uploads/` instead of `.claude-images/`. The folder ignores itself in git (it carries a `.gitignore` of `*`), stays hidden in the Files panel, and is cleaned up as before: files older than 7 days in an hourly sweep, and the folder when the last session in that workspace closes. The old `.claude-images/` folder gets nothing new and is still swept and removed during 1.41.x. An upload to a remote (SSH) session is now refused with a clear message, since the file would land on the Codeman host where the remote agent cannot read it.
|
||||
- **Typing on a phone after a tab switch (#576, fixes #575).** With local echo on (the default on touch devices), text typed while the terminal sat above the bottom was buffered but never painted, so the keyboard looked dead. The view sits there after every tab switch and after the keyboard closes. The overlay now paints whenever the prompt row is on screen, and hides only when you scroll the prompt out of view.
|
||||
- **Upload failures say why (#578).** When a prompt image upload fails, the toast shows the server's reason (for example a rate limit) instead of only "1 failed".
|
||||
- **The npm page shows the English README.** npmjs.com had been rendering the Chinese README, because npm picks the package's readme from an unsorted file match at publish time. The publish now moves `README.zh-CN.md` aside while it runs (the file and every link to it stay as they are), and the package description and homepage say what Codeman is and point at getcodeman.com.
|
||||
- **New cases ask for clickable file paths.** The CLAUDE.md generated into a new case asks the agent to report every file it created as a full absolute path, which Codeman turns into a link that opens the File Viewer, and mentions the codeman skill for starting and managing worker sessions.
|
||||
|
||||
**For contributors (#570).** Every in-process test server binds an ephemeral port, the mobile suite included, and the port guard now also refuses raw listeners on a fixed port, so two test runs on one machine never collide.
|
||||
|
||||
**Fixes applied while landing.** zh-CN translations for the two new notification display-time settings and for the new Animations section. A session whose name matches an interface word ("Lab", "New session") is no longer translated in the tab strip when the interface is in Chinese. Plus test and doc cleanups left over from review.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -537,7 +537,7 @@ While flushed text exists the prompt column is locked, so a full-screen redraw c
|
||||
|
||||
### Scroll awareness
|
||||
|
||||
The overlay hides when the viewport is scrolled up (`viewportY !== baseY`) and re-renders, debounced, when you scroll back to the bottom.
|
||||
The overlay hides while the cursor row is scrolled out of the viewport and re-renders, debounced, when it scrolls back into view. A viewport parked a few rows above the bottom keeps painting as long as the cursor row is on screen. A buffer that reports no `cursorY` keeps the bottom-only rule.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "xterm-zerolag-input",
|
||||
"version": "0.4.0",
|
||||
"version": "0.4.1",
|
||||
"description": "Instant keystroke feedback overlay for xterm.js: Mosh-inspired local echo that removes perceived input latency over SSH, tunnels and other high-RTT connections",
|
||||
"type": "module",
|
||||
"main": "dist/index.cjs",
|
||||
|
||||
@@ -72,3 +72,20 @@ export function readTextAfterPrompt(terminal: XtermTerminal, prompt: PromptPosit
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the row the overlay draws on (the cursor row) is inside the viewport. A bare
|
||||
* `viewportY === baseY` test is wrong for a host that parks the viewport a few rows above
|
||||
* the bottom with the prompt still on screen; a buffer without `cursorY` keeps that rule.
|
||||
*/
|
||||
export function promptRowInViewport(terminal: XtermTerminal): boolean {
|
||||
try {
|
||||
const buf = terminal.buffer.active;
|
||||
if (buf.viewportY === buf.baseY) return true;
|
||||
if (typeof buf.cursorY !== 'number') return false;
|
||||
const cursorRow = buf.baseY + buf.cursorY;
|
||||
return cursorRow >= buf.viewportY && cursorRow < buf.viewportY + terminal.rows;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
FontStyle,
|
||||
} from './types.js';
|
||||
import { getCellDimensions } from './cell-dimensions.js';
|
||||
import { findPrompt, readTextAfterPrompt } from './prompt-finder.js';
|
||||
import { findPrompt, readTextAfterPrompt, promptRowInViewport } from './prompt-finder.js';
|
||||
import { renderOverlay, charCellWidth } from './overlay-renderer.js';
|
||||
|
||||
const DEFAULT_PROMPT: PromptFinder = { type: 'character', char: '>', offset: 2 };
|
||||
@@ -122,11 +122,10 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
// Cache font properties
|
||||
this._cacheFont();
|
||||
|
||||
// Scroll detection: hide overlay when scrolled away from bottom
|
||||
// Scroll detection: hide the overlay while the cursor row is scrolled out of view
|
||||
this._scrollHandler = () => {
|
||||
try {
|
||||
const buf = this._terminal!.buffer.active;
|
||||
if (buf.viewportY !== buf.baseY) {
|
||||
if (!promptRowInViewport(this._terminal!)) {
|
||||
this._overlay!.style.display = 'none';
|
||||
if (this._scrollTimer) {
|
||||
clearTimeout(this._scrollTimer);
|
||||
@@ -565,8 +564,8 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
try {
|
||||
const buf = this._terminal.buffer.active;
|
||||
|
||||
// Hide overlay when scrolled up — prompt is at bottom, not in viewport
|
||||
if (buf.viewportY !== buf.baseY) {
|
||||
// Hide the overlay while the cursor row is scrolled out of view
|
||||
if (!promptRowInViewport(this._terminal)) {
|
||||
this._overlay.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createMockTerminal } from './helpers.js';
|
||||
import { findPrompt, readTextAfterPrompt } from '../src/prompt-finder.js';
|
||||
import { promptRowInViewport, findPrompt, readTextAfterPrompt } from '../src/prompt-finder.js';
|
||||
import type { XtermTerminal, PromptFinder } from '../src/types.js';
|
||||
|
||||
function term(lines: string[]) {
|
||||
@@ -156,3 +156,28 @@ describe('readTextAfterPrompt', () => {
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
describe('promptRowInViewport', () => {
|
||||
const term = (viewportY: number, baseY: number, cursorY: number | undefined, rows = 24) =>
|
||||
({ rows, buffer: { active: { viewportY, baseY, cursorY, getLine: () => undefined } } }) as never;
|
||||
|
||||
it('is true at the bottom regardless of the cursor', () => {
|
||||
expect(promptRowInViewport(term(10, 10, undefined))).toBe(true);
|
||||
});
|
||||
|
||||
it('is true for a viewport parked above the bottom while the cursor row is on screen', () => {
|
||||
// scrollToLastNonEmptyLine() parks rows - 2 above the last non-empty row
|
||||
expect(promptRowInViewport(term(0, 16, 5))).toBe(true);
|
||||
// cursor exactly on the last visible row
|
||||
expect(promptRowInViewport(term(0, 23, 0))).toBe(true);
|
||||
});
|
||||
|
||||
it('is false once the cursor row is scrolled out of the viewport', () => {
|
||||
expect(promptRowInViewport(term(0, 24, 0))).toBe(false); // one past the last row
|
||||
expect(promptRowInViewport(term(0, 200, 3))).toBe(false); // deep in history
|
||||
});
|
||||
|
||||
it('keeps the bottom-only rule when the buffer has no cursorY', () => {
|
||||
expect(promptRowInViewport(term(0, 1, undefined))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -725,3 +725,34 @@ describe('ZerolagInputAddon', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('viewport scrolled away from the bottom', () => {
|
||||
function parked(viewportY: number, baseY: number, cursorY: number, rows = 24) {
|
||||
const mock = createMockTerminal({ buffer: { lines: ['$ '], viewportY, baseY, cursorY }, rows });
|
||||
const addon = new ZerolagInputAddon({ prompt: { type: 'character', char: '$', offset: 2 } });
|
||||
mock.terminal.loadAddon(addon);
|
||||
cleanups.push(() => {
|
||||
addon.dispose();
|
||||
mock.cleanup();
|
||||
});
|
||||
const overlay = mock.terminal.element.querySelector('.xterm-screen')!.lastElementChild as HTMLDivElement;
|
||||
return { addon, mock, overlay };
|
||||
}
|
||||
|
||||
it('still paints with the viewport parked above the bottom while the cursor row is on screen', () => {
|
||||
// The host parks the viewport to keep trailing blank rows out of view; the
|
||||
// prompt and cursor are still visible, so the user's text must be too.
|
||||
const { addon, overlay } = parked(0, 1, 0);
|
||||
addon.appendText('abc');
|
||||
expect(addon.pendingText).toBe('abc');
|
||||
expect(overlay.style.display).not.toBe('none');
|
||||
expect(overlay.textContent).toContain('abc');
|
||||
});
|
||||
|
||||
it('hides once the cursor row is scrolled out of the viewport, even over a stale prompt glyph', () => {
|
||||
const { addon, overlay } = parked(0, 30, 0);
|
||||
addon.appendText('abc');
|
||||
expect(addon.pendingText).toBe('abc');
|
||||
expect(overlay.style.display).toBe('none');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "codeman",
|
||||
"description": "Drive Codeman, the self-hosted session manager for AI coding agents, from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts only inside a Codeman-managed session.",
|
||||
"version": "1.35.0",
|
||||
"version": "1.41.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
---
|
||||
name: codeman
|
||||
description: >-
|
||||
Drive Codeman, the session manager this agent is running inside, over its HTTP API:
|
||||
list sessions, start worker sessions, send them prompts, block until they finish
|
||||
(wait / wait-output / send-and-wait), read their output, and clean up; where
|
||||
available, message claude workers directly (Claude Code cross-session messaging).
|
||||
Use when asked to orchestrate or parallelize work across Codeman sessions, watch
|
||||
Drive Codeman, the session manager this agent is running inside, over its HTTP API,
|
||||
from any agent CLI (Claude Code, Codex, Gemini CLI, OpenCode, Antigravity, Grok
|
||||
Build, DeepSeek Harness, OMP): list sessions, start worker sessions in any installed
|
||||
CLI, send them prompts, block until they finish (wait / wait-output / send-and-wait),
|
||||
read their output, and clean up; where available, message claude workers directly
|
||||
(Claude Code cross-session messaging). Use when asked to orchestrate or parallelize
|
||||
work across Codeman sessions, get a second opinion from another CLI or model, watch
|
||||
another session, or start and manage workers. Only usable inside a Codeman-managed
|
||||
session (CODEMAN_MUX=1); refuse to act otherwise.
|
||||
---
|
||||
@@ -29,11 +31,31 @@ worked multi-worker flows in [reference/recipes.md](reference/recipes.md), endpo
|
||||
tables and a symptom gallery in [reference/endpoints.md](reference/endpoints.md), and
|
||||
direct messaging to claude workers in [reference/messaging.md](reference/messaging.md).
|
||||
|
||||
This skill works the same whichever CLI you are: Codeman puts it where each CLI looks
|
||||
for skills (`.claude/skills/` for Claude Code, `.agents/skills/` for Codex, Gemini CLI,
|
||||
OpenCode, Antigravity, Grok, DeepSeek and OMP). A **pi** or **shell** worker never gets
|
||||
it, but has the same environment: tell it *"other sessions: `codeman agent --help`"*.
|
||||
That bundled CLI (`ls`, `spawn`, `send`, `wait`, `read`, `interrupt`, `rm`) is the same
|
||||
verbs over the same endpoints, with the guards below (no control bytes, no self-delete,
|
||||
no guessed URL) enforced in code, and it is also your own way through when this
|
||||
machine has no `jq` for the preamble below.
|
||||
|
||||
## 0. Guard and bootstrap
|
||||
|
||||
If `CODEMAN_MUX` is not `1`, **stop and say so**. Do not guess an API URL; a server
|
||||
you are not part of is not yours to drive.
|
||||
|
||||
Two failures come from your CLI, not from Codeman: name them to the user instead of
|
||||
retrying.
|
||||
|
||||
- **Every call fails at once with "couldn't connect" or "connection refused".** Your
|
||||
CLI's sandbox blocks network access, even to this machine. Codex's default sandbox
|
||||
does; it needs **Bypass approvals and sandbox** (Codeman App Settings, Codex).
|
||||
- **`"${CURL[@]}" -o /dev/null -w '%{http_code}' "$API/api/v1/sessions/$SELF"` prints
|
||||
`404`.** The commands you run do not carry this session's environment: Codex can run them in a shared background
|
||||
process another session started, so `$CODEMAN_SESSION_ID` (and with it `$SELF` and
|
||||
the delete guard) is that session's. Delete nothing; tell the user.
|
||||
|
||||
⚠️ **Your shell state does not survive between tool calls.** Each Bash call starts a
|
||||
fresh shell, so `$API`, `$SELF`, the `CURL` array and `delete_session` are all gone by
|
||||
the next call, and `$$` is a different pid. **The filesystem does survive**, so write
|
||||
@@ -41,8 +63,9 @@ the preamble to a file once and source it afterwards, rather than re-pasting a
|
||||
hundred-odd lines at the top of every call (a half-re-pasted preamble used to be the
|
||||
single most likely way to break a run).
|
||||
|
||||
**Codeman seeds the preamble file for you** when it spawns a claude session (server
|
||||
1.18.3+), so the bootstrap is usually nothing at all: these are the two lines every
|
||||
**Codeman seeds the preamble file for you** when it spawns your session (claude since
|
||||
server 1.18.3, the other CLIs since this skill reached them), so the bootstrap is
|
||||
usually nothing at all: these are the two lines every
|
||||
later call opens with, and your first REAL call performs them anyway:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* Extracted from the package.json one-liner for readability and debuggability.
|
||||
*
|
||||
* Steps:
|
||||
* 0. Preflight: the build-time packages resolve (nothing is touched before it)
|
||||
* 1. TypeScript compilation
|
||||
* 2. Copy static assets (web/public, templates)
|
||||
* 3. Build vendor xterm bundles
|
||||
@@ -13,6 +14,7 @@
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { createRequire } from 'module';
|
||||
import { appendFileSync, readFileSync, writeFileSync, renameSync } from 'fs';
|
||||
import { createHash } from 'crypto';
|
||||
import { fileURLToPath } from 'url';
|
||||
@@ -25,6 +27,31 @@ function run(label, cmd) {
|
||||
execSync(cmd, { stdio: 'inherit', cwd: ROOT, shell: true });
|
||||
}
|
||||
|
||||
// 0. Preflight: resolve the build-time packages the asset stage reads only AFTER it has
|
||||
// deleted dist/web/public (step 2), before anything is touched. A tree whose node_modules
|
||||
// predate them (a deploy that pulled but never ran `npm install`) used to fail mid-build
|
||||
// with dist/web/public already wiped, so the running server kept serving an index.html
|
||||
// whose hashed assets were gone. Keep the list in step with every require.resolve in
|
||||
// scripts/prepare-spreadsheet-assets.mjs (test/spreadsheet-assets.test.ts checks it).
|
||||
// Only specifiers that resolve without an exports map in the way: a subpath of a package
|
||||
// that has one (@xterm/*) can throw ERR_PACKAGE_PATH_NOT_EXPORTED while installed.
|
||||
// A hand-run of the asset stage alone (past a blocked tsc) skips this check.
|
||||
const BUILD_TIME_MODULES = ['exceljs/dist/exceljs.min.js', 'fflate'];
|
||||
const requireFromBuild = createRequire(import.meta.url);
|
||||
const missingModules = BUILD_TIME_MODULES.filter((specifier) => {
|
||||
try {
|
||||
requireFromBuild.resolve(specifier);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (missingModules.length > 0) {
|
||||
console.error(`[build] missing build dependency: ${missingModules.join(', ')}`);
|
||||
console.error('[build] run `npm install` first, then `npm run build` again. Nothing was built or deleted.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 1. TypeScript compilation
|
||||
run('tsc', 'tsc');
|
||||
run('chmod dist/index.js', 'chmod +x dist/index.js');
|
||||
@@ -49,6 +76,9 @@ run('xterm-addon-serialize', 'npx esbuild node_modules/@xterm/addon-serialize/li
|
||||
run('xterm-addon-webgl', 'cp node_modules/@xterm/addon-webgl/lib/addon-webgl.js dist/web/public/vendor/xterm-addon-webgl.min.js');
|
||||
run('xterm-addon-unicode11', 'npx esbuild node_modules/@xterm/addon-unicode11/lib/addon-unicode11.js --minify --outfile=dist/web/public/vendor/xterm-addon-unicode11.min.js');
|
||||
run('xterm-zerolag-input', 'npx esbuild packages/xterm-zerolag-input/src/zerolag-input-addon.ts --bundle --minify --format=iife --global-name=XtermZerolagInput --outfile=dist/web/public/vendor/xterm-zerolag-input.js');
|
||||
// XLSX preview parser bundles: loaded only inside spreadsheet-preview-worker.js,
|
||||
// never by the page (see scripts/prepare-spreadsheet-assets.mjs).
|
||||
run('spreadsheet preview vendors', 'node scripts/prepare-spreadsheet-assets.mjs dist/web/public/vendor');
|
||||
|
||||
// Append global aliases so app.js can use `new LocalEchoOverlay(terminal)`
|
||||
appendFileSync(
|
||||
@@ -129,6 +159,7 @@ console.log('\n[build] content-hash cache busting');
|
||||
'api-client.js',
|
||||
'subagent-windows.js',
|
||||
'image-input.js',
|
||||
'spreadsheet-preview.js',
|
||||
'vendor/xterm-zerolag-input.js',
|
||||
'vendor/xterm-predictive-echo.js',
|
||||
];
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { dirname, extname, join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
@@ -9,6 +10,10 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const publicRoot = resolve(repoRoot, 'src/web/public');
|
||||
const prettierBin = resolve(repoRoot, 'node_modules/.bin/prettier');
|
||||
const checkedExtensions = new Set(['.js', '.css', '.html', '.json']);
|
||||
// Combined budget for the two XLSX-preview vendor bundles (exceljs + fflate).
|
||||
// They load only inside the spreadsheet worker, but a dependency bump that
|
||||
// balloons them should be a deliberate decision, not a silent one.
|
||||
const SPREADSHEET_VENDOR_MAX_BYTES = 1_100_000;
|
||||
|
||||
function collectTextAssets(dir) {
|
||||
const files = [];
|
||||
@@ -35,6 +40,39 @@ function findNullByte(buffer) {
|
||||
const files = collectTextAssets(publicRoot);
|
||||
const failures = [];
|
||||
|
||||
// The spreadsheet worker is a stable (unhashed) URL, cache-busted by the
|
||||
// SPREADSHEET_ASSET_VERSION token in spreadsheet-preview.js. That token must be
|
||||
// the content hash of everything the worker loads, or a deploy can pair a new
|
||||
// worker with a stale cached core/vendor file (static assets are cached 1y).
|
||||
const spreadsheetWorker = join(publicRoot, 'spreadsheet-preview-worker.js');
|
||||
const spreadsheetCore = join(publicRoot, 'spreadsheet-xlsx-core.js');
|
||||
const spreadsheetEntry = join(publicRoot, 'spreadsheet-preview.js');
|
||||
const spreadsheetVendors = [join(publicRoot, 'vendor', 'exceljs.min.js'), join(publicRoot, 'vendor', 'fflate.min.js')];
|
||||
|
||||
if ([spreadsheetWorker, spreadsheetCore, spreadsheetEntry, ...spreadsheetVendors].every(existsSync)) {
|
||||
const vendorBytes = spreadsheetVendors.reduce((total, file) => total + readFileSync(file).length, 0);
|
||||
if (vendorBytes > SPREADSHEET_VENDOR_MAX_BYTES) {
|
||||
failures.push(`Spreadsheet vendor bundles exceed ${SPREADSHEET_VENDOR_MAX_BYTES} bytes (${vendorBytes} bytes)`);
|
||||
}
|
||||
|
||||
const expectedVersion = createHash('sha256')
|
||||
.update(readFileSync(spreadsheetWorker))
|
||||
.update(readFileSync(spreadsheetCore))
|
||||
.update(readFileSync(spreadsheetVendors[0]))
|
||||
.update(readFileSync(spreadsheetVendors[1]))
|
||||
.digest('hex')
|
||||
.slice(0, 12);
|
||||
const entrySource = readFileSync(spreadsheetEntry, 'utf8');
|
||||
const actualVersion = entrySource.match(/const SPREADSHEET_ASSET_VERSION = '([a-f0-9]+)'/)?.[1];
|
||||
if (actualVersion !== expectedVersion) {
|
||||
failures.push(
|
||||
`SPREADSHEET_ASSET_VERSION mismatch: expected ${expectedVersion}, found ${actualVersion || 'missing'}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
failures.push('Spreadsheet preview assets are missing; run `node scripts/prepare-spreadsheet-assets.mjs`');
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const rel = relative(repoRoot, file);
|
||||
const data = readFileSync(file);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @fileoverview `npm run release`: `changeset publish` with `README.zh-CN.md` moved aside.
|
||||
*
|
||||
* npmjs.com renders the package's top-level `readme`, and npm picks it at publish time:
|
||||
* @npmcli/package-json's normalize globs `{README,README.*}` in the package root UNSORTED and
|
||||
* keeps the first `.md` it sees. With `README.zh-CN.md` next to `README.md` that was the
|
||||
* Chinese one on this machine and on CI, so npmjs.com showed the Chinese README for months.
|
||||
* `files` cannot help: npm-packlist always includes every root `README.*`.
|
||||
*
|
||||
* Renaming the file would break every link to it, so for the length of the publish only it
|
||||
* moves to a name npm does not treat as a readme (a leading dot), and is put back afterwards,
|
||||
* whatever the publish did. The move happens HERE, inside the publish command, never as a
|
||||
* step before `changesets/action` in release.yml: that action also runs the version path and
|
||||
* commits the working tree into its version PR, which would commit the deletion.
|
||||
*
|
||||
* A previous run killed between the move and the restore leaves the aside copy behind; the
|
||||
* next run puts it back first. `xterm-zerolag-input` (packages/) has only a README.md.
|
||||
*
|
||||
* node scripts/npm-release.mjs what the Release workflow runs (via `npm run release`)
|
||||
*/
|
||||
import { existsSync, renameSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const HIDDEN_README = 'README.zh-CN.md';
|
||||
export const ASIDE_NAME = '.README.zh-CN.md.release-aside';
|
||||
|
||||
/**
|
||||
* Runs `publish` with `HIDDEN_README` moved aside in `root`, restoring it afterwards, also
|
||||
* when `publish` fails or throws. Returns the exit code `publish` returned.
|
||||
*
|
||||
* @param {{ root: string, publish: () => number, log?: (msg: string) => void }} opts
|
||||
* @returns {number}
|
||||
*/
|
||||
export function publishWithReadmeAside({ root, publish, log = (msg) => console.log(msg) }) {
|
||||
const original = join(root, HIDDEN_README);
|
||||
const aside = join(root, ASIDE_NAME);
|
||||
if (existsSync(aside) && !existsSync(original)) {
|
||||
renameSync(aside, original);
|
||||
log(`npm-release: restored ${HIDDEN_README} left aside by an earlier run`);
|
||||
}
|
||||
const moved = existsSync(original);
|
||||
if (moved) {
|
||||
renameSync(original, aside);
|
||||
log(`npm-release: ${HIDDEN_README} moved aside so npm picks README.md as the readme`);
|
||||
}
|
||||
try {
|
||||
return publish();
|
||||
} finally {
|
||||
if (moved) {
|
||||
renameSync(aside, original);
|
||||
log(`npm-release: ${HIDDEN_README} restored`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function runChangesetPublish() {
|
||||
const result = spawnSync('changeset', ['publish'], { stdio: 'inherit', shell: process.platform === 'win32' });
|
||||
if (result.error) {
|
||||
console.error(`npm-release: could not run changeset publish: ${result.error.message}`);
|
||||
return 1;
|
||||
}
|
||||
return result.status ?? 1;
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
const root = join(fileURLToPath(new URL('.', import.meta.url)), '..');
|
||||
process.exitCode = publishWithReadmeAside({ root, publish: runChangesetPublish });
|
||||
}
|
||||
@@ -341,6 +341,22 @@ if (isGlobalInstall) {
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// 4a. Copy the XLSX preview's browser bundles (exceljs, fflate) into
|
||||
// src/web/public/vendor/ for dev mode. The build does the same into dist/.
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
if (!isGlobalInstall) {
|
||||
try {
|
||||
execSync(`node "${join(import.meta.dirname, 'prepare-spreadsheet-assets.mjs')}"`, { stdio: 'pipe' });
|
||||
console.log(colors.green('✓ Spreadsheet preview vendor files prepared'));
|
||||
} catch (err) {
|
||||
hasWarnings = true;
|
||||
console.log(colors.yellow('⚠ Failed to prepare spreadsheet preview vendor files'));
|
||||
console.log(colors.dim(` ${err.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// 4b. Fetch gesture-overlay runtime assets (MediaPipe wasm + model) for dev mode
|
||||
// (src/web/public/gesture/). Opt-in feature (CODEMAN_GESTURE=1); non-fatal.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Copy the XLSX preview's browser bundles (exceljs, fflate) into a public vendor
|
||||
* dir. Run by postinstall for dev (src/web/public/vendor, gitignored) and by
|
||||
* build.mjs for prod (dist/web/public/vendor). Both packages are pinned exactly
|
||||
* in package.json, and check-public-assets.mjs hashes the output into
|
||||
* SPREADSHEET_ASSET_VERSION (the worker's cache-bust token), so a version bump
|
||||
* that changes the bytes fails that check until the token is refreshed.
|
||||
* Source-map comments are stripped: the maps are not shipped.
|
||||
*/
|
||||
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const outputDir = resolve(process.argv[2] || join(import.meta.dirname, '..', 'src', 'web', 'public', 'vendor'));
|
||||
const excelSource = require.resolve('exceljs/dist/exceljs.min.js');
|
||||
const fflateSource = join(dirname(require.resolve('fflate')), '..', 'umd', 'index.js');
|
||||
|
||||
function copyBrowserBundle(source, outputName) {
|
||||
const content = readFileSync(source, 'utf8').replace(/\n?\/\/# sourceMappingURL=.*(?:\n|$)/g, '\n');
|
||||
if (/sourceMappingURL/.test(content)) {
|
||||
throw new Error(`Failed to strip sourceMappingURL from ${outputName}`);
|
||||
}
|
||||
writeFileSync(join(outputDir, outputName), content, 'utf8');
|
||||
}
|
||||
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
copyBrowserBundle(excelSource, 'exceljs.min.js');
|
||||
copyBrowserBundle(fflateSource, 'fflate.min.js');
|
||||
@@ -29,6 +29,9 @@ const SOURCE = 'skills/codeman';
|
||||
const PLUGIN_DIR = `plugins/${PLUGIN_NAME}`;
|
||||
const MIRROR = `${PLUGIN_DIR}/skills/codeman`;
|
||||
const MANIFESTS = [`${PLUGIN_DIR}/.claude-plugin/plugin.json`, '.claude-plugin/marketplace.json'];
|
||||
// The MCP registry manifest for `codeman mcp` (published with `mcp-publisher` from its
|
||||
// directory): the server and its npm package both carry the release version.
|
||||
const MCP_REGISTRY_MANIFEST = 'config/mcp-registry/server.json';
|
||||
|
||||
const check = process.argv.includes('--check');
|
||||
const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
|
||||
@@ -78,6 +81,21 @@ for (const file of MANIFESTS) {
|
||||
if (changed && !check) writeFileSync(file, JSON.stringify(json, null, 2) + '\n');
|
||||
}
|
||||
|
||||
// 3. The MCP registry manifest.
|
||||
{
|
||||
const json = JSON.parse(readFileSync(MCP_REGISTRY_MANIFEST, 'utf8'));
|
||||
const targets = [json, ...(json.packages ?? []).filter((p) => p.registryType === 'npm')];
|
||||
let changed = false;
|
||||
for (const target of targets) {
|
||||
if (target.version !== version) {
|
||||
drift.push(`${MCP_REGISTRY_MANIFEST}: ${target.version} -> ${version}`);
|
||||
target.version = version;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed && !check) writeFileSync(MCP_REGISTRY_MANIFEST, JSON.stringify(json, null, 2) + '\n');
|
||||
}
|
||||
|
||||
if (drift.length === 0) {
|
||||
console.log(`plugin in step: mirror identical, manifests at ${version}`);
|
||||
} else if (check) {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
---
|
||||
name: codeman
|
||||
description: >-
|
||||
Drive Codeman, the session manager this agent is running inside, over its HTTP API:
|
||||
list sessions, start worker sessions, send them prompts, block until they finish
|
||||
(wait / wait-output / send-and-wait), read their output, and clean up; where
|
||||
available, message claude workers directly (Claude Code cross-session messaging).
|
||||
Use when asked to orchestrate or parallelize work across Codeman sessions, watch
|
||||
Drive Codeman, the session manager this agent is running inside, over its HTTP API,
|
||||
from any agent CLI (Claude Code, Codex, Gemini CLI, OpenCode, Antigravity, Grok
|
||||
Build, DeepSeek Harness, OMP): list sessions, start worker sessions in any installed
|
||||
CLI, send them prompts, block until they finish (wait / wait-output / send-and-wait),
|
||||
read their output, and clean up; where available, message claude workers directly
|
||||
(Claude Code cross-session messaging). Use when asked to orchestrate or parallelize
|
||||
work across Codeman sessions, get a second opinion from another CLI or model, watch
|
||||
another session, or start and manage workers. Only usable inside a Codeman-managed
|
||||
session (CODEMAN_MUX=1); refuse to act otherwise.
|
||||
---
|
||||
@@ -29,11 +31,31 @@ worked multi-worker flows in [reference/recipes.md](reference/recipes.md), endpo
|
||||
tables and a symptom gallery in [reference/endpoints.md](reference/endpoints.md), and
|
||||
direct messaging to claude workers in [reference/messaging.md](reference/messaging.md).
|
||||
|
||||
This skill works the same whichever CLI you are: Codeman puts it where each CLI looks
|
||||
for skills (`.claude/skills/` for Claude Code, `.agents/skills/` for Codex, Gemini CLI,
|
||||
OpenCode, Antigravity, Grok, DeepSeek and OMP). A **pi** or **shell** worker never gets
|
||||
it, but has the same environment: tell it *"other sessions: `codeman agent --help`"*.
|
||||
That bundled CLI (`ls`, `spawn`, `send`, `wait`, `read`, `interrupt`, `rm`) is the same
|
||||
verbs over the same endpoints, with the guards below (no control bytes, no self-delete,
|
||||
no guessed URL) enforced in code, and it is also your own way through when this
|
||||
machine has no `jq` for the preamble below.
|
||||
|
||||
## 0. Guard and bootstrap
|
||||
|
||||
If `CODEMAN_MUX` is not `1`, **stop and say so**. Do not guess an API URL; a server
|
||||
you are not part of is not yours to drive.
|
||||
|
||||
Two failures come from your CLI, not from Codeman: name them to the user instead of
|
||||
retrying.
|
||||
|
||||
- **Every call fails at once with "couldn't connect" or "connection refused".** Your
|
||||
CLI's sandbox blocks network access, even to this machine. Codex's default sandbox
|
||||
does; it needs **Bypass approvals and sandbox** (Codeman App Settings, Codex).
|
||||
- **`"${CURL[@]}" -o /dev/null -w '%{http_code}' "$API/api/v1/sessions/$SELF"` prints
|
||||
`404`.** The commands you run do not carry this session's environment: Codex can run them in a shared background
|
||||
process another session started, so `$CODEMAN_SESSION_ID` (and with it `$SELF` and
|
||||
the delete guard) is that session's. Delete nothing; tell the user.
|
||||
|
||||
⚠️ **Your shell state does not survive between tool calls.** Each Bash call starts a
|
||||
fresh shell, so `$API`, `$SELF`, the `CURL` array and `delete_session` are all gone by
|
||||
the next call, and `$$` is a different pid. **The filesystem does survive**, so write
|
||||
@@ -41,8 +63,9 @@ the preamble to a file once and source it afterwards, rather than re-pasting a
|
||||
hundred-odd lines at the top of every call (a half-re-pasted preamble used to be the
|
||||
single most likely way to break a run).
|
||||
|
||||
**Codeman seeds the preamble file for you** when it spawns a claude session (server
|
||||
1.18.3+), so the bootstrap is usually nothing at all: these are the two lines every
|
||||
**Codeman seeds the preamble file for you** when it spawns your session (claude since
|
||||
server 1.18.3, the other CLIs since this skill reached them), so the bootstrap is
|
||||
usually nothing at all: these are the two lines every
|
||||
later call opens with, and your first REAL call performs them anyway:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { basename, extname, isAbsolute } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, extname, isAbsolute, join } from 'node:path';
|
||||
import { isBlockedAttachmentPath, isUnderTree, loadAttachmentGuardConfig } from './config/attachment-guard.js';
|
||||
import { EDITABLE_EXTENSIONS } from './config/file-editing.js';
|
||||
import { validateSessionFilePath } from './web/route-helpers.js';
|
||||
@@ -53,15 +54,20 @@ export const AUDIO_ATTACHMENT_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
*/
|
||||
export const TEXT_ATTACHMENT_EXTENSIONS: ReadonlySet<string> = EDITABLE_EXTENSIONS;
|
||||
|
||||
/**
|
||||
* Document types an attachment card previews. Also the list `codeman attach`'s
|
||||
* error text names, so the help cannot drift from what is accepted. `xlsx` is
|
||||
* previewed client-side (spreadsheet-preview-worker.js) and served raw like the rest.
|
||||
*/
|
||||
export const DOCUMENT_ATTACHMENT_EXTENSIONS: readonly string[] = Object.freeze(['pdf', 'docx', 'pptx', 'xlsx']);
|
||||
|
||||
const SUPPORTED_ATTACHMENT_EXTENSIONS = new Set([
|
||||
'png',
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'gif',
|
||||
'webp',
|
||||
'pdf',
|
||||
'docx',
|
||||
'pptx',
|
||||
...DOCUMENT_ATTACHMENT_EXTENSIONS,
|
||||
'md',
|
||||
'txt',
|
||||
...VIDEO_ATTACHMENT_EXTENSIONS,
|
||||
@@ -143,6 +149,11 @@ class AttachmentRegistry {
|
||||
|
||||
export const attachmentRegistry = new AttachmentRegistry();
|
||||
|
||||
/** Every extension {@link isSupportedAttachmentExtension} accepts (lowercase, no dot). */
|
||||
export function supportedAttachmentExtensions(): string[] {
|
||||
return [...SUPPORTED_ATTACHMENT_EXTENSIONS];
|
||||
}
|
||||
|
||||
export function isSupportedAttachmentExtension(extension: string): boolean {
|
||||
return SUPPORTED_ATTACHMENT_EXTENSIONS.has(extension.toLowerCase().replace(/^\./, ''));
|
||||
}
|
||||
@@ -154,6 +165,7 @@ export function getAttachmentType(extension: string): AttachmentDetectedType {
|
||||
if (AUDIO_ATTACHMENT_EXTENSIONS.has(normalized)) return 'audio';
|
||||
if (normalized === 'pdf') return 'pdf';
|
||||
if (normalized === 'pptx') return 'presentation';
|
||||
if (normalized === 'xlsx') return 'spreadsheet';
|
||||
if (normalized === 'md') return 'markdown';
|
||||
// Everything else in the text family reads as text, including code and
|
||||
// config: the card and the preview both treat it as a plain-text file.
|
||||
@@ -324,13 +336,19 @@ export async function registerExternalAttachment(
|
||||
requestedPath: string,
|
||||
options: RegisterExternalAttachmentOptions = {}
|
||||
): Promise<AttachmentRegistrationResult> {
|
||||
if (!requestedPath || !isAbsolute(requestedPath)) {
|
||||
// `~/…` is the home of the session's HOST: expanded here for a local session,
|
||||
// and by the probe on the remote host for a remote one (`buildRemoteProbeCommand`),
|
||||
// whose home this server does not know. A clicked terminal link sends it as is
|
||||
// (Claude Code echoes attachments as `~/…`). Every guard below runs on the
|
||||
// resolved absolute path either way.
|
||||
const homeRelative = typeof requestedPath === 'string' && requestedPath.startsWith('~/');
|
||||
if (!requestedPath || (!isAbsolute(requestedPath) && !homeRelative)) {
|
||||
throw new AttachmentRegistrationError('Attachment path must be an absolute local path');
|
||||
}
|
||||
|
||||
const resolved = await (options.remote
|
||||
? resolveRemoteAttachment(requestedPath, options.remote, options.sessionWorkingDir, options.remoteProbes)
|
||||
: resolveLocalAttachment(requestedPath));
|
||||
: resolveLocalAttachment(homeRelative ? join(homedir(), requestedPath.slice(2)) : requestedPath));
|
||||
|
||||
// COD-53: enforce the active attachment-guard policy on the symlink-resolved
|
||||
// path before doing anything else.
|
||||
|
||||
@@ -0,0 +1,985 @@
|
||||
/**
|
||||
* @fileoverview `codeman agent …` — session-to-session verbs for the agent running
|
||||
* inside a Codeman session, in every CLI mode.
|
||||
*
|
||||
* A thin HTTP client over endpoints that already exist (`quick-start`, `input`,
|
||||
* `wait`, `wait-output`, `last-response`, `terminal`, `DELETE sessions/:id`). It
|
||||
* invents no route and no transport: everything goes through `CODEMAN_API_URL`, so
|
||||
* auth, ownership and the per-session waiter cap apply unchanged. The behaviour is
|
||||
* the packaged agent skill's (`skills/codeman`), ported from shell prose into code
|
||||
* with tests, so a `codex`/`opencode`/`pi` agent — which never gets the claude-only
|
||||
* preamble — has the same verbs from one line in its AGENTS.md.
|
||||
*
|
||||
* Invariants (each asserted in `test/cli-agent.test.ts`):
|
||||
* 1. Refuses outside a Codeman session (`CODEMAN_MUX=1` + `CODEMAN_API_URL`); it
|
||||
* never guesses a URL — a server you are not part of is not yours to drive.
|
||||
* 2. `send` transmits printable text plus `\r` only. ESC exists solely as
|
||||
* `interrupt`, which never appends `\r`. A stray control byte is a dead session
|
||||
* in the fullscreen TUIs (opencode's `Ctrl+C` is `app_exit`).
|
||||
* 3. `rm` fails closed: empty id, a short self id, or a prefix match in EITHER
|
||||
* direction refuses. Ids appear in full and 8-char form, so equality alone
|
||||
* misses a real combination — and the miss deletes the caller.
|
||||
* 4. An id shorter than 8 characters refuses (exit 4) before any request, on every
|
||||
* verb. `9` would resolve to whichever session is alone with that first
|
||||
* character, the user's own interactive tab included.
|
||||
*
|
||||
* Commands live here as functions returning an exit code, not calling
|
||||
* `process.exit`, so the whole surface is unit-testable against a fake server.
|
||||
*
|
||||
* @module cli-agent
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import type { Command } from 'commander';
|
||||
import {
|
||||
basicAuthHeader,
|
||||
credentialsFrom,
|
||||
readCodemanEnvFile,
|
||||
type CodemanCredentials,
|
||||
} from './codeman-credentials.js';
|
||||
import { getCli } from './config/cli-registry/registry.js';
|
||||
import { GLYPH, palette, table } from './cli-style.js';
|
||||
import { getErrorMessage } from './types.js';
|
||||
import { stripAnsi as stripAnsiSequences } from './utils/regex-patterns.js';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Context and guard
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AgentContext {
|
||||
/** Base URL of the Codeman server, from `CODEMAN_API_URL`. */
|
||||
apiUrl: string;
|
||||
/** This session's id, from `CODEMAN_SESSION_ID`. */
|
||||
selfId: string;
|
||||
/** Basic-auth credentials, when the server has a password. */
|
||||
auth?: CodemanCredentials;
|
||||
}
|
||||
|
||||
/** Thrown when the process is not inside a Codeman-managed session. */
|
||||
export class AgentGuardError extends Error {}
|
||||
|
||||
/** Exit codes shared by every verb; a shell agent can branch on them. */
|
||||
export const EXIT = {
|
||||
ok: 0,
|
||||
error: 1,
|
||||
timeout: 2,
|
||||
dead: 3,
|
||||
refused: 4,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Resolve the context from the environment, or throw `AgentGuardError`.
|
||||
*
|
||||
* Credentials in the order every client of the API uses (`credentialsFrom`, shared
|
||||
* with `codeman attach` and the TUI): each field from the environment (a session
|
||||
* inherits the server's), then the data dir's `.env`. No password means the server
|
||||
* is open (single-user) — or it is not, and the 401 says so.
|
||||
*/
|
||||
export function resolveAgentContext(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
envFile: () => Record<string, string> = readCodemanEnvFile
|
||||
): AgentContext {
|
||||
if (env.CODEMAN_MUX !== '1') {
|
||||
throw new AgentGuardError('Not inside a Codeman-managed session (CODEMAN_MUX is not 1); refusing to act.');
|
||||
}
|
||||
const apiUrl = env.CODEMAN_API_URL?.trim();
|
||||
if (!apiUrl) {
|
||||
throw new AgentGuardError('CODEMAN_API_URL is not set; refusing to guess a server.');
|
||||
}
|
||||
const selfId = env.CODEMAN_SESSION_ID?.trim();
|
||||
if (!selfId) {
|
||||
throw new AgentGuardError('CODEMAN_SESSION_ID is not set; cannot tell which session is me.');
|
||||
}
|
||||
const credentials = credentialsFrom(env, envFile());
|
||||
return { apiUrl, selfId, auth: credentials.password ? credentials : undefined };
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Pure helpers (the invariants)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Is `id` this session? Prefix in BOTH directions, because ids appear in full and
|
||||
* in 8-char form (mux names, UI surfaces, Docker's truncated `$SELF`). A self id
|
||||
* shorter than 8 characters cannot prove anything and is treated as "maybe me".
|
||||
*/
|
||||
export function isSelfSession(selfId: string, id: string): boolean {
|
||||
if (!id || selfId.length < 8) return true;
|
||||
return id.startsWith(selfId) || selfId.startsWith(id);
|
||||
}
|
||||
|
||||
/** Why `rm` refuses, or `undefined` when the delete may go ahead. */
|
||||
export function deleteRefusal(selfId: string, id: string): string | undefined {
|
||||
if (!id) return 'refusing: empty session id';
|
||||
if (selfId.length < 8) return 'refusing: own session id unset or too short to prove this is not me';
|
||||
if (isSelfSession(selfId, id)) return `refusing: ${id} is me`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The prompt `send` was given, which must be ONE argument. Joining several with spaces
|
||||
* would turn an unquoted `$(cat notes.txt)`, which the shell splits on every newline,
|
||||
* back into a single line, so the multi-line refusal below would never see it.
|
||||
*/
|
||||
export function sendPromptFromArgs(words: readonly string[]): { text: string } | { error: string } {
|
||||
if (words.length === 1) return { text: words[0] };
|
||||
return {
|
||||
error: `refusing: the prompt must be ONE argument, got ${words.length} — quote it (\`send <id> "…"\`; a prompt that starts with "-" goes after --: \`send <id> -- "- fix the bug"\`)`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Why `send` refuses this text, or `undefined` when it is printable. The composer
|
||||
* takes one line; the server strips `\r`/`\n` but everything else below 0x20 (and
|
||||
* DEL) reaches the pane as a keypress. None of that is a prompt.
|
||||
*/
|
||||
export function inputRefusal(text: string): string | undefined {
|
||||
if (text.length === 0) return 'refusing: empty input (use `interrupt` for ESC, `send <id> ""` is never a prompt)';
|
||||
// The composer is one line: the server strips newlines, which silently joins the
|
||||
// lines into one prompt, and a tab reaches the pane as a keypress (claude: mode toggle).
|
||||
if (/[\n\r\t]/.test(text)) {
|
||||
return 'refusing: input must be a single line (the composer strips newlines and would join your lines) — join them yourself, or write a file into the workspace and send its path';
|
||||
}
|
||||
// C0, DEL and C1 (U+0080–U+009F: an 8-bit CSI is still a CSI to a terminal).
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const control = text.match(/[\x00-\x1f\x7f-\x9f]/);
|
||||
if (control) {
|
||||
const code = control[0].charCodeAt(0).toString(16).padStart(2, '0');
|
||||
return `refusing: input contains control byte 0x${code}; send transmits printable text only (ESC is \`interrupt\`)`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Body for `POST /sessions/:id/input` on the send path: text plus `\r` unless the
|
||||
* caller asked to type without submitting. Never anything else.
|
||||
*/
|
||||
export function buildSendBody(
|
||||
text: string,
|
||||
options: { enter: boolean; clientId: string; seq: number; wait?: string | true; waitTimeout?: number }
|
||||
): Record<string, unknown> {
|
||||
const body: Record<string, unknown> = {
|
||||
input: options.enter ? `${text}\r` : text,
|
||||
useMux: true,
|
||||
clientId: options.clientId,
|
||||
seq: options.seq,
|
||||
};
|
||||
if (options.wait !== undefined) body.wait = options.wait;
|
||||
if (options.waitTimeout !== undefined) body.waitTimeout = options.waitTimeout;
|
||||
return body;
|
||||
}
|
||||
|
||||
/** Body for the interrupt path: a bare ESC, and nothing appended — ever. */
|
||||
export function buildInterruptBody(clientId: string, seq: number): Record<string, unknown> {
|
||||
return { input: '\u001b', useMux: true, clientId, seq };
|
||||
}
|
||||
|
||||
/** `clientId` for this caller: fixed per sending session, so `seq` stays monotonic. */
|
||||
export function defaultClientId(selfId: string, suffix = ''): string {
|
||||
return `codeman-agent-cli-${selfId.slice(0, 8)}${suffix ? `-${suffix}` : ''}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip a terminal buffer for humans: the shared ANSI strip (CSI, OSC such as window
|
||||
* titles, keypad modes) plus the charset designators (`ESC ( B`) it leaves in.
|
||||
*/
|
||||
export function stripAnsi(text: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return stripAnsiSequences(text).replace(/\x1b[()][AB0]/g, '');
|
||||
}
|
||||
|
||||
/** Parse a positive-integer option (`--timeout` ms, `--tail` bytes); the server rejects anything else. */
|
||||
export function parsePositiveInt(raw: string | undefined, fallback: number, flag = '--timeout'): number {
|
||||
if (raw === undefined) return fallback;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
throw new Error(`${flag} must be a positive integer, got "${raw}"`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exit code for a wait result: matched or a signal → ok, `exit` or `ended` → dead,
|
||||
* timeout → timeout. `ended` is checked BEFORE the happy paths: a worker that dies
|
||||
* during `--until stop` comes back as `ended:true, signal:null` (the registry only
|
||||
* satisfies waiters that listed `exit`, then cancels the rest), and a `--match` on
|
||||
* a dead worker as `ended:true, matched:false` — both are "dead", never "done".
|
||||
*/
|
||||
export function waitExitCode(wait: WaitResult | undefined): number {
|
||||
if (!wait) return EXIT.error;
|
||||
if (wait.signal === 'exit' || wait.ended) return EXIT.dead;
|
||||
if (wait.timedOut) return EXIT.timeout;
|
||||
if (wait.matched === false) return EXIT.timeout;
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// HTTP
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ApiEnvelope<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
errorCode?: string;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = unknown> {
|
||||
status: number;
|
||||
/** Parsed envelope, or `undefined` when the body was not JSON (auth guards answer in plain text). */
|
||||
json?: ApiEnvelope<T>;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface WaitResult {
|
||||
/** The signal that fired, or null when the wait ended without one. */
|
||||
signal?: string | null;
|
||||
timedOut?: boolean;
|
||||
/** The session went away (deleted / torn down / the write failed) before the wait resolved. */
|
||||
ended?: boolean;
|
||||
timeoutMs?: number;
|
||||
until?: string[];
|
||||
matched?: boolean;
|
||||
match?: string;
|
||||
snippet?: string;
|
||||
immediate?: boolean;
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
method: 'GET' | 'POST' | 'DELETE';
|
||||
path: string;
|
||||
query?: Record<string, string | number | boolean | undefined>;
|
||||
body?: Record<string, unknown>;
|
||||
headers?: Record<string, string>;
|
||||
/** Socket timeout; long-polls pass their own timeout plus headroom. */
|
||||
timeoutMs?: number;
|
||||
/** Aborts the request (an MCP client cancelling a long wait); the promise rejects. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export type ApiRequest = (ctx: AgentContext, options: RequestOptions) => Promise<ApiResponse>;
|
||||
|
||||
/** Every request carries these; they are ignored on endpoints that do not read them. */
|
||||
export function baseHeaders(ctx: AgentContext): Record<string, string> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
// Tags sessions this caller spawns as its children (lineage in the web UI).
|
||||
// Cosmetic, never fails a call. NOT X-Codeman-Agent-Origin: that one marks a case
|
||||
// directory as deletable agent scratch, so it rides only the spawn request that
|
||||
// may create one (see agentSpawn), never anything else. Absent for a caller outside
|
||||
// any session (`codeman mcp` launched by a desktop MCP client), which has no self.
|
||||
if (ctx.selfId) headers['X-Codeman-Parent-Session'] = ctx.selfId;
|
||||
const authorization = ctx.auth ? basicAuthHeader(ctx.auth) : undefined;
|
||||
if (authorization) headers.Authorization = authorization;
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** The real transport. `rejectUnauthorized:false` because the HTTPS install uses a self-signed cert. */
|
||||
export const httpRequest: ApiRequest = (ctx, options) => {
|
||||
const url = new URL(options.path, ctx.apiUrl);
|
||||
for (const [key, value] of Object.entries(options.query ?? {})) {
|
||||
if (value !== undefined) url.searchParams.set(key, String(value));
|
||||
}
|
||||
const bodyText = options.body === undefined ? undefined : JSON.stringify(options.body);
|
||||
const headers: Record<string, string | number> = { ...baseHeaders(ctx), ...(options.headers ?? {}) };
|
||||
if (bodyText !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
headers['Content-Length'] = Buffer.byteLength(bodyText);
|
||||
}
|
||||
const transport = url.protocol === 'https:' ? https : http;
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = transport.request(
|
||||
{
|
||||
protocol: url.protocol,
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
method: options.method,
|
||||
path: `${url.pathname}${url.search}`,
|
||||
rejectUnauthorized: false,
|
||||
headers,
|
||||
timeout: options.timeoutMs ?? 30_000,
|
||||
signal: options.signal,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
// A connection dropped mid-body emits 'error' and never 'end'; without this the
|
||||
// promise never settles (and a long-lived `codeman mcp` never answers the call).
|
||||
res.on('error', reject);
|
||||
res.on('end', () => {
|
||||
const text = Buffer.concat(chunks).toString('utf-8');
|
||||
let json: ApiEnvelope | undefined;
|
||||
try {
|
||||
json = JSON.parse(text) as ApiEnvelope;
|
||||
} catch {
|
||||
json = undefined;
|
||||
}
|
||||
resolve({ status: res.statusCode ?? 0, json, text });
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on('timeout', () => req.destroy(new Error(`request timed out after ${options.timeoutMs ?? 30_000} ms`)));
|
||||
req.on('error', reject);
|
||||
if (bodyText !== undefined) req.write(bodyText);
|
||||
req.end();
|
||||
});
|
||||
};
|
||||
|
||||
/** One line describing a failed response, for humans. Plain-text guards (401/403/429) have no envelope. */
|
||||
export function describeFailure(res: ApiResponse): string {
|
||||
if (res.json && !res.json.success) {
|
||||
return `${res.json.errorCode ?? 'ERROR'}: ${res.json.error ?? 'request failed'} (HTTP ${res.status})`;
|
||||
}
|
||||
const text = res.text.trim().split('\n')[0] ?? '';
|
||||
if (res.status === 401)
|
||||
return `HTTP 401 ${text}: the server wants a password (CODEMAN_PASSWORD, or the data dir's .env)`;
|
||||
return `HTTP ${res.status}${text ? ` ${text}` : ''}`;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Commands
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AgentIo {
|
||||
out: (line: string) => void;
|
||||
err: (line: string) => void;
|
||||
}
|
||||
|
||||
export interface AgentDeps {
|
||||
ctx: AgentContext;
|
||||
request: ApiRequest;
|
||||
io: AgentIo;
|
||||
json: boolean;
|
||||
/** Clock for `seq`; injectable so tests are deterministic. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
/** Print `data` as JSON (the `--json` path) — always the envelope's `data`, never a reshaped copy. */
|
||||
function emitJson(deps: AgentDeps, data: unknown): void {
|
||||
deps.io.out(JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
function fail(deps: AgentDeps, message: string, code: number = EXIT.error): number {
|
||||
if (deps.json) {
|
||||
deps.io.out(JSON.stringify({ success: false, error: message }));
|
||||
} else {
|
||||
deps.io.err(palette.err(`${GLYPH.fail} ${message}`));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
interface SessionRow {
|
||||
id: string;
|
||||
name?: string;
|
||||
mode?: string;
|
||||
status?: string;
|
||||
workingDir?: string;
|
||||
pid?: number | null;
|
||||
parentSessionId?: string | null;
|
||||
}
|
||||
|
||||
/** A full session id (the only form the routes accept); `ls` prints the 8-char prefix. */
|
||||
const FULL_ID_LENGTH = 36;
|
||||
|
||||
/**
|
||||
* Shortest prefix that may name a session: the 8-char form `ls` prints, and the floor
|
||||
* the server's own resolver uses (`PARENT_SESSION_ID_MIN_PREFIX`, route-helpers.ts).
|
||||
*/
|
||||
export const MIN_ID_PREFIX_LENGTH = 8;
|
||||
|
||||
/**
|
||||
* Turn the id a human typed into the one the routes accept. `ls` prints 8-char
|
||||
* prefixes and the routes answer 404 to those (measured live), so anything shorter
|
||||
* than a full id resolves through the session list; an ambiguous prefix refuses
|
||||
* rather than picking one. Below 8 characters it refuses before the list: "unique"
|
||||
* means nothing for `9` — it names whatever session happens to be alone with that
|
||||
* first character, and `rm`/`send` would act on it.
|
||||
*/
|
||||
export async function resolveSessionId(
|
||||
deps: AgentDeps,
|
||||
id: string
|
||||
): Promise<{ id: string } | { error: string; code: number }> {
|
||||
if (!id) return { error: 'refusing: empty session id', code: EXIT.refused };
|
||||
if (id.length < MIN_ID_PREFIX_LENGTH) {
|
||||
return {
|
||||
error: `refusing: "${id}" is shorter than ${MIN_ID_PREFIX_LENGTH} characters — use the 8-character id \`agent ls\` prints, or the full id`,
|
||||
code: EXIT.refused,
|
||||
};
|
||||
}
|
||||
if (id.length >= FULL_ID_LENGTH) return { id };
|
||||
const res = await deps.request(deps.ctx, { method: 'GET', path: '/api/v1/sessions' });
|
||||
if (!res.json?.success) return { error: describeFailure(res), code: EXIT.error };
|
||||
const matches = ((res.json.data as SessionRow[] | undefined) ?? []).filter((s) => s.id.startsWith(id));
|
||||
if (matches.length === 1) return { id: matches[0].id };
|
||||
if (matches.length === 0) return { error: `no session starts with "${id}" (see \`agent ls\`)`, code: EXIT.error };
|
||||
return { error: `"${id}" is ambiguous: ${matches.map((s) => s.id.slice(0, 13)).join(', ')}`, code: EXIT.error };
|
||||
}
|
||||
|
||||
/** `agent ls` — every session the caller can see, self marked. */
|
||||
export async function agentLs(deps: AgentDeps): Promise<number> {
|
||||
const res = await deps.request(deps.ctx, { method: 'GET', path: '/api/v1/sessions' });
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
const sessions = (res.json.data as SessionRow[] | undefined) ?? [];
|
||||
if (deps.json) {
|
||||
emitJson(
|
||||
deps,
|
||||
sessions.map((s) => ({ ...s, self: isSelfSession(deps.ctx.selfId, s.id) }))
|
||||
);
|
||||
return EXIT.ok;
|
||||
}
|
||||
if (sessions.length === 0) {
|
||||
deps.io.out(palette.muted('(no sessions)'));
|
||||
return EXIT.ok;
|
||||
}
|
||||
const rows = sessions.map((s) => [
|
||||
isSelfSession(deps.ctx.selfId, s.id) ? '*' : ' ',
|
||||
s.id.slice(0, 8),
|
||||
s.mode ?? '?',
|
||||
s.status ?? '?',
|
||||
s.name || s.workingDir || '',
|
||||
]);
|
||||
deps.io.out(table([[' ', 'ID', 'MODE', 'STATUS', 'NAME'], ...rows], { gap: 2 }));
|
||||
deps.io.out(
|
||||
palette.muted(`* = this session (${deps.ctx.selfId.slice(0, 8)}). status is a UI hint, never a sync signal.`)
|
||||
);
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
export interface SpawnOptions {
|
||||
caseName: string;
|
||||
mode: string;
|
||||
name?: string;
|
||||
/** Wait for the composer before returning, where the registry gives the mode a ready mark. */
|
||||
ready: boolean;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent-scratch label for a case directory a spawn CREATES (the server applies it only
|
||||
* when quick-start makes the directory). The Add Case UI offers a recursive delete for
|
||||
* such directories, so this header must never ride any other request: mislabelling a
|
||||
* real repo there is the one failure in this area that costs actual work.
|
||||
*/
|
||||
export const AGENT_ORIGIN_HEADER = { 'X-Codeman-Agent-Origin': 'codeman-agent-cli' } as const;
|
||||
|
||||
/**
|
||||
* What the mode's TUI draws once its composer can take a prompt, from the CLI registry
|
||||
* (`capabilities.composerReadyMark`); undefined means the mode has no readiness wait.
|
||||
*/
|
||||
export function composerReadyMark(mode: string): string | undefined {
|
||||
return getCli(mode)?.capabilities.composerReadyMark;
|
||||
}
|
||||
/** `agent spawn` — quick-start with lineage, then the readiness ladder where the mode has one. */
|
||||
export async function agentSpawn(deps: AgentDeps, options: SpawnOptions): Promise<number> {
|
||||
const body: Record<string, unknown> = {
|
||||
caseName: options.caseName,
|
||||
mode: options.mode,
|
||||
parentSessionId: deps.ctx.selfId,
|
||||
};
|
||||
if (options.name) body.sessionName = options.name;
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/quick-start',
|
||||
body,
|
||||
headers: { ...AGENT_ORIGIN_HEADER },
|
||||
});
|
||||
const data = res.json?.data as { sessionId?: string; caseName?: string; casePath?: string } | undefined;
|
||||
if (!res.json?.success || !data?.sessionId) return fail(deps, describeFailure(res));
|
||||
const sid = data.sessionId;
|
||||
|
||||
let ready: boolean | undefined;
|
||||
let readinessError: string | undefined;
|
||||
let dead = false;
|
||||
const mark = composerReadyMark(options.mode);
|
||||
if (options.ready && mark) {
|
||||
const wait = await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(sid)}/wait-output`,
|
||||
query: { match: mark, from: 'buffer', timeout: options.timeoutMs },
|
||||
timeoutMs: options.timeoutMs + 10_000,
|
||||
});
|
||||
// A failed readiness call (waiter cap, 400, network) is its own error, not "the
|
||||
// composer never showed up": report the real reason instead of the trust-dialog hint.
|
||||
if (!wait.json?.success) readinessError = describeFailure(wait);
|
||||
else {
|
||||
const result = (wait.json.data as { wait?: WaitResult } | undefined)?.wait;
|
||||
// A worker that died while we waited is exit 3 like every other wait, not a
|
||||
// "composer not seen" timeout that sends the caller looking for a dialog.
|
||||
dead = waitExitCode(result) === EXIT.dead;
|
||||
ready = !dead && Boolean(result?.matched);
|
||||
}
|
||||
}
|
||||
|
||||
if (deps.json) {
|
||||
emitJson(deps, { ...data, ready, readinessError });
|
||||
} else {
|
||||
// Human lines go to stderr so `SID=$(codeman agent spawn …)` captures the id alone.
|
||||
const say = (line: string) => deps.io.err(line);
|
||||
say(palette.ok(`${GLYPH.ok} spawned ${sid} (${options.mode}, case ${data.caseName ?? options.caseName})`));
|
||||
if (ready === true) say(palette.muted(' composer up: the worker can take a prompt'));
|
||||
if (dead) say(palette.err(`${GLYPH.fail} the worker exited during the readiness wait`));
|
||||
if (ready === false && !dead) {
|
||||
say(
|
||||
palette.warn(
|
||||
`${GLYPH.warn} composer not seen within ${options.timeoutMs} ms — read \`agent read ${sid.slice(0, 8)} --tail 2000\` before sending (a startup dialog?)`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (readinessError) say(palette.err(`${GLYPH.fail} readiness check failed: ${readinessError}`));
|
||||
if (ready === undefined && !readinessError && options.ready) {
|
||||
say(
|
||||
palette.muted(
|
||||
` ${options.mode} has no readiness mark; give it a moment, then use --match markers to synchronize`
|
||||
)
|
||||
);
|
||||
}
|
||||
deps.io.out(sid);
|
||||
}
|
||||
if (readinessError) return EXIT.error;
|
||||
if (dead) return EXIT.dead;
|
||||
return ready === false ? EXIT.timeout : EXIT.ok;
|
||||
}
|
||||
|
||||
export interface SendOptions {
|
||||
id: string;
|
||||
text: string;
|
||||
enter: boolean;
|
||||
/** `undefined` = fire-and-forget; `true` = default signal set; string = comma list. */
|
||||
wait?: string | true;
|
||||
timeoutMs?: number;
|
||||
clientId?: string;
|
||||
seq?: number;
|
||||
}
|
||||
|
||||
/** `agent send` — printable text plus `\r`, exactly-once, optionally blocking on end of turn. */
|
||||
export async function agentSend(deps: AgentDeps, options: SendOptions): Promise<number> {
|
||||
if (isSelfSession(deps.ctx.selfId, options.id)) {
|
||||
return fail(deps, `refusing: ${options.id} is me — typing into my own composer is not a message`, EXIT.refused);
|
||||
}
|
||||
const refusal = inputRefusal(options.text);
|
||||
if (refusal) return fail(deps, refusal, EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const body = buildSendBody(options.text, {
|
||||
enter: options.enter,
|
||||
clientId: options.clientId ?? defaultClientId(deps.ctx.selfId),
|
||||
seq: options.seq ?? (deps.now ?? Date.now)(),
|
||||
wait: options.wait,
|
||||
waitTimeout: options.wait !== undefined ? options.timeoutMs : undefined,
|
||||
});
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}/input`,
|
||||
body,
|
||||
timeoutMs: (options.timeoutMs ?? 60_000) + 10_000,
|
||||
});
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
const data = res.json.data as
|
||||
| { delivered?: boolean; duplicate?: boolean; buffered?: boolean; dropped?: boolean; wait?: WaitResult }
|
||||
| undefined;
|
||||
if (deps.json) emitJson(deps, data ?? {});
|
||||
// Fire-and-forget to a remote session whose host is asleep (wake-on-LAN): the server
|
||||
// holds the chunk and types it once the pane is back (`buffered`), or the chunk was
|
||||
// over the wake buffer's cap and is gone (`dropped`). The seq is spent either way,
|
||||
// so a retry needs a new one (the default, the clock, gives it that).
|
||||
if (data?.dropped) {
|
||||
if (!deps.json) {
|
||||
deps.io.err(
|
||||
palette.err(
|
||||
`${GLYPH.fail} dropped: ${target.id}'s host is waking and its input buffer is full — nothing will be typed; send again once it is back`
|
||||
)
|
||||
);
|
||||
}
|
||||
return EXIT.error;
|
||||
}
|
||||
// `delivered:false` without `duplicate` is the route's "the bytes went nowhere":
|
||||
// the PTY exited or send-keys hit a dead pane. The field exists so a client does not
|
||||
// say "wait longer" when the truth is "restart the worker" — so it is a failure here.
|
||||
if (data?.delivered === false && !data.duplicate) {
|
||||
if (!deps.json) {
|
||||
deps.io.err(
|
||||
palette.err(`${GLYPH.fail} not delivered: ${target.id} has no live worker (pane exited) — restart it`)
|
||||
);
|
||||
}
|
||||
return EXIT.dead;
|
||||
}
|
||||
if (!deps.json) {
|
||||
const noEnter = options.enter ? '' : ' (no Enter)';
|
||||
if (data?.duplicate) {
|
||||
deps.io.out(palette.warn(`${GLYPH.warn} duplicate (clientId/seq already applied): nothing typed`));
|
||||
} else if (data?.buffered) {
|
||||
deps.io.out(
|
||||
palette.ok(
|
||||
`${GLYPH.ok} buffered for ${target.id}${noEnter}: its host is asleep; Codeman is waking it and types this once the pane is back`
|
||||
)
|
||||
);
|
||||
} else if (data?.delivered === true) {
|
||||
deps.io.out(palette.ok(`${GLYPH.ok} delivered to ${target.id}${noEnter}`));
|
||||
} else {
|
||||
// Fire-and-forget answers before the write, so there is no delivery report here.
|
||||
deps.io.out(palette.ok(`${GLYPH.ok} accepted for ${target.id}${noEnter} (no delivery report without --wait)`));
|
||||
}
|
||||
if (data?.wait) deps.io.out(describeWait(data.wait));
|
||||
}
|
||||
if (options.wait === undefined) return EXIT.ok;
|
||||
return waitExitCode(data?.wait);
|
||||
}
|
||||
|
||||
function describeWait(wait: WaitResult): string {
|
||||
if (wait.signal === 'exit') return palette.err(`${GLYPH.fail} the session exited`);
|
||||
if (wait.ended) {
|
||||
return palette.err(
|
||||
`${GLYPH.fail} the wait ended without an answer: the session went away (dead worker, deleted, or nothing was written)`
|
||||
);
|
||||
}
|
||||
// A timeout is a 200 with `timedOut`, an answer rather than a failure: exit 2 says it,
|
||||
// so the line stays neutral instead of looking like an error to whoever reads the log.
|
||||
if (wait.timedOut) return palette.muted(`timed out after ${wait.timeoutMs ?? '?'} ms (exit 2)`);
|
||||
if (wait.matched !== undefined) {
|
||||
return wait.matched
|
||||
? palette.ok(`${GLYPH.ok} matched "${wait.match}"${wait.snippet ? `: ${wait.snippet}` : ''}`)
|
||||
: palette.muted('not matched (exit 2)');
|
||||
}
|
||||
return palette.ok(
|
||||
`${GLYPH.ok} signal: ${wait.signal}${wait.immediate ? ' (immediate: current state, not a transition)' : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
export interface WaitOptions {
|
||||
id: string;
|
||||
until?: string;
|
||||
match?: string;
|
||||
from?: 'buffer' | 'now';
|
||||
fresh?: boolean;
|
||||
nocase?: boolean;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
/** `agent wait` — a signal (`--until`) or a literal output marker (`--match`). */
|
||||
export async function agentWait(deps: AgentDeps, options: WaitOptions): Promise<number> {
|
||||
if (options.until && options.match)
|
||||
return fail(deps, 'use either --until <signals> or --match <marker>, not both', EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const sid = encodeURIComponent(target.id);
|
||||
const res = options.match
|
||||
? await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${sid}/wait-output`,
|
||||
query: {
|
||||
match: options.match,
|
||||
from: options.from ?? 'buffer',
|
||||
nocase: options.nocase ? 1 : undefined,
|
||||
timeout: options.timeoutMs,
|
||||
},
|
||||
timeoutMs: options.timeoutMs + 10_000,
|
||||
})
|
||||
: await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${sid}/wait`,
|
||||
query: { until: options.until, fresh: options.fresh ? 1 : undefined, timeout: options.timeoutMs },
|
||||
timeoutMs: options.timeoutMs + 10_000,
|
||||
});
|
||||
// A 400 here is the server saying "this mode has no such signal" (until=stop on an
|
||||
// external CLI). Passed through, never papered over: the marker path is the answer.
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
const data = res.json.data as { wait?: WaitResult; status?: string; limitPaused?: boolean } | undefined;
|
||||
if (deps.json) {
|
||||
emitJson(deps, data ?? {});
|
||||
} else if (data?.wait) {
|
||||
deps.io.out(describeWait(data.wait));
|
||||
if (data.limitPaused)
|
||||
deps.io.out(palette.warn(`${GLYPH.warn} session is paused on a usage limit; a timeout is expected`));
|
||||
}
|
||||
return waitExitCode(data?.wait);
|
||||
}
|
||||
|
||||
export interface ReadOptions {
|
||||
id: string;
|
||||
/** Bytes of raw terminal to fetch; ANSI is stripped for humans. */
|
||||
tail?: number;
|
||||
/** Whole conversation (`context=full`) instead of the last assistant message. */
|
||||
full?: boolean;
|
||||
}
|
||||
|
||||
/** `agent read` — the last answer (the route picks the transcript reader or the pane segmenter) or a terminal tail. */
|
||||
export async function agentRead(deps: AgentDeps, options: ReadOptions): Promise<number> {
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const sid = encodeURIComponent(target.id);
|
||||
if (options.tail !== undefined) {
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${sid}/terminal`,
|
||||
query: { tail: options.tail },
|
||||
});
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
const buffer = (res.json.data as { terminalBuffer?: string } | undefined)?.terminalBuffer ?? '';
|
||||
if (deps.json) emitJson(deps, res.json.data);
|
||||
else deps.io.out(stripAnsi(buffer));
|
||||
return EXIT.ok;
|
||||
}
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${sid}/last-response`,
|
||||
query: { context: options.full ? 'full' : undefined },
|
||||
});
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
const data = res.json.data as
|
||||
| { text?: string; timestamp?: string; messages?: Array<{ role: string; text: string }> }
|
||||
| undefined;
|
||||
if (deps.json) {
|
||||
emitJson(deps, data ?? {});
|
||||
return EXIT.ok;
|
||||
}
|
||||
if (options.full && data?.messages) {
|
||||
for (const m of data.messages) deps.io.out(`${palette.emph(m.role)}: ${m.text}`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
const text = data?.text ?? '';
|
||||
if (!text) {
|
||||
deps.io.err(
|
||||
palette.muted('(empty: nothing answered yet, or nothing the server could segment as an answer; try --tail 3000)')
|
||||
);
|
||||
return EXIT.ok;
|
||||
}
|
||||
deps.io.out(text);
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
/** `agent interrupt` — a bare ESC keypress, no Enter, conversation intact. */
|
||||
export async function agentInterrupt(deps: AgentDeps, options: { id: string }): Promise<number> {
|
||||
if (isSelfSession(deps.ctx.selfId, options.id)) return fail(deps, `refusing: ${options.id} is me`, EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const body = buildInterruptBody(defaultClientId(deps.ctx.selfId, 'interrupt'), (deps.now ?? Date.now)());
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}/input`,
|
||||
body,
|
||||
});
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
if (deps.json) emitJson(deps, res.json.data ?? {});
|
||||
else
|
||||
deps.io.out(
|
||||
palette.ok(
|
||||
`${GLYPH.ok} ESC sent to ${target.id} — one Esc does not always land; read the tail before the next prompt`
|
||||
)
|
||||
);
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
/** `agent rm` — delete a session that is provably not this one. */
|
||||
export async function agentRm(deps: AgentDeps, options: { id: string }): Promise<number> {
|
||||
const refusal = deleteRefusal(deps.ctx.selfId, options.id);
|
||||
if (refusal) return fail(deps, refusal, EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
// The guard again on the RESOLVED id: a prefix that is not me can still resolve
|
||||
// to me only if the list is lying, but a delete is the one call worth the paranoia.
|
||||
const resolvedRefusal = deleteRefusal(deps.ctx.selfId, target.id);
|
||||
if (resolvedRefusal) return fail(deps, resolvedRefusal, EXIT.refused);
|
||||
const res = await deps.request(deps.ctx, {
|
||||
method: 'DELETE',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}`,
|
||||
});
|
||||
if (!res.json?.success) return fail(deps, describeFailure(res));
|
||||
if (deps.json) emitJson(deps, res.json.data ?? {});
|
||||
else deps.io.out(palette.ok(`${GLYPH.ok} deleted ${target.id} (its case directory stays on disk)`));
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Commander wiring
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_WAIT_MS = 60_000;
|
||||
|
||||
/** Build deps from the live environment; the guard's message is the only thing a non-session caller sees. */
|
||||
function liveDeps(json: boolean): AgentDeps | undefined {
|
||||
try {
|
||||
return {
|
||||
ctx: resolveAgentContext(),
|
||||
request: httpRequest,
|
||||
json,
|
||||
io: { out: (line) => console.log(line), err: (line) => console.error(line) },
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof AgentGuardError) {
|
||||
console.error(palette.err(`${GLYPH.fail} ${err.message}`));
|
||||
return undefined;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Run a verb with the live transport and turn its exit code into the process exit. */
|
||||
async function run(json: boolean, verb: (deps: AgentDeps) => Promise<number>): Promise<void> {
|
||||
const deps = liveDeps(json);
|
||||
if (!deps) {
|
||||
process.exitCode = EXIT.refused;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
process.exitCode = await verb(deps);
|
||||
} catch (err) {
|
||||
console.error(palette.err(`${GLYPH.fail} ${getErrorMessage(err)}`));
|
||||
process.exitCode = EXIT.error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Register `codeman agent …` on the program. */
|
||||
export function registerAgentCommands(program: Command): Command {
|
||||
const agent = program
|
||||
.command('agent')
|
||||
.description('Talk to other sessions from inside one (any CLI mode): list, spawn, send, wait, read, interrupt, rm');
|
||||
|
||||
agent
|
||||
.command('ls')
|
||||
.alias('list')
|
||||
.description('List sessions; * marks this one')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((options: { json?: boolean }) => run(Boolean(options.json), agentLs));
|
||||
|
||||
agent
|
||||
.command('spawn <case>')
|
||||
.description(
|
||||
'Start a worker session in a case (created if missing) and wait for its composer where the mode draws one'
|
||||
)
|
||||
.option('-m, --mode <mode>', 'Run mode id, as the Run menu names it', 'claude')
|
||||
.option('-n, --name <name>', 'Session name shown in the UI')
|
||||
.option('--no-ready', 'Return as soon as the session exists, without the readiness wait')
|
||||
.option('-t, --timeout <ms>', 'Readiness budget in ms', String(DEFAULT_WAIT_MS))
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action(
|
||||
(caseName: string, options: { mode: string; name?: string; ready: boolean; timeout?: string; json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) =>
|
||||
agentSpawn(deps, {
|
||||
caseName,
|
||||
mode: options.mode,
|
||||
name: options.name,
|
||||
ready: options.ready,
|
||||
timeoutMs: parsePositiveInt(options.timeout, DEFAULT_WAIT_MS),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('send <id> <text...>')
|
||||
.description(
|
||||
'Type a prompt into another session and press Enter (ONE quoted argument, printable text only; a prompt that starts with "-" goes after --: send <id> -- "- fix the bug")'
|
||||
)
|
||||
.option('-w, --wait', 'Block until end of turn (the default signal set; see --until)')
|
||||
.option('-u, --until <signals>', 'Signals to wait for, comma list such as stop,exit (implies --wait)')
|
||||
.option('-t, --timeout <ms>', 'Wait budget in ms (with --wait)', String(DEFAULT_WAIT_MS))
|
||||
.option('--no-enter', 'Type the text without submitting it')
|
||||
.option('--client-id <id>', 'Exactly-once tag (default: one per calling session)')
|
||||
.option(
|
||||
'--seq <n>',
|
||||
'Sequence number for the tag (default: the current epoch ms). Must stay monotonic per client id: a reused or lower value is a silent duplicate, nothing is typed'
|
||||
)
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action(
|
||||
(
|
||||
id: string,
|
||||
words: string[],
|
||||
options: {
|
||||
wait?: boolean;
|
||||
until?: string;
|
||||
timeout?: string;
|
||||
enter: boolean;
|
||||
clientId?: string;
|
||||
seq?: string;
|
||||
json?: boolean;
|
||||
}
|
||||
) =>
|
||||
run(Boolean(options.json), (deps) => {
|
||||
const prompt = sendPromptFromArgs(words);
|
||||
if ('error' in prompt) return Promise.resolve(fail(deps, prompt.error, EXIT.refused));
|
||||
return agentSend(deps, {
|
||||
id,
|
||||
text: prompt.text,
|
||||
enter: options.enter,
|
||||
wait: options.until ?? (options.wait ? true : undefined),
|
||||
timeoutMs: parsePositiveInt(options.timeout, DEFAULT_WAIT_MS),
|
||||
clientId: options.clientId,
|
||||
seq: options.seq === undefined ? undefined : parsePositiveInt(options.seq, 1, '--seq'),
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
agent
|
||||
.command('wait <id>')
|
||||
.description(
|
||||
'Block until a signal (--until) or an output marker (--match) — timeout exits 2, a dead worker exits 3'
|
||||
)
|
||||
.option(
|
||||
'-u, --until <signals>',
|
||||
'Comma list: stop,idle,exit,working,blocked (stop/blocked need hook signals for the session; where there are none the server answers 400, passed through)'
|
||||
)
|
||||
.option(
|
||||
'-m, --match <marker>',
|
||||
'Literal substring to wait for in the output (ANSI-stripped, no regex). The echo of your own prompt is output too, so never put the marker verbatim in the prompt: ask for it in halves ("print WORKDONE followed by _4711") and wait on the joined form (WORKDONE_4711)'
|
||||
)
|
||||
.option('--from <where>', 'buffer (scan existing output first, the default) or now', 'buffer')
|
||||
.option('--nocase', 'Case-insensitive --match')
|
||||
.option('--fresh', 'Require an actual transition (--until only)')
|
||||
.option('-t, --timeout <ms>', 'Budget in ms', String(DEFAULT_WAIT_MS))
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action(
|
||||
(
|
||||
id: string,
|
||||
options: {
|
||||
until?: string;
|
||||
match?: string;
|
||||
from: string;
|
||||
nocase?: boolean;
|
||||
fresh?: boolean;
|
||||
timeout?: string;
|
||||
json?: boolean;
|
||||
}
|
||||
) =>
|
||||
run(Boolean(options.json), (deps) =>
|
||||
agentWait(deps, {
|
||||
id,
|
||||
until: options.until,
|
||||
match: options.match,
|
||||
from: options.from === 'now' ? 'now' : 'buffer',
|
||||
nocase: options.nocase,
|
||||
fresh: options.fresh,
|
||||
timeoutMs: parsePositiveInt(options.timeout, DEFAULT_WAIT_MS),
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('read <id>')
|
||||
.description("Print a session's last answer (as the server reads it for that mode) or, with --tail, its terminal")
|
||||
.option('--tail <bytes>', 'Raw terminal tail in bytes, ANSI stripped (works in every mode)')
|
||||
.option('--full', 'The whole conversation instead of the last assistant message')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { tail?: string; full?: boolean; json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) =>
|
||||
agentRead(deps, {
|
||||
id,
|
||||
tail: options.tail === undefined ? undefined : parsePositiveInt(options.tail, 3000, '--tail'),
|
||||
full: options.full,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('interrupt <id>')
|
||||
.description('Send a bare ESC to stop the current turn (the conversation survives; deleting would not)')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) => agentInterrupt(deps, { id }))
|
||||
);
|
||||
|
||||
agent
|
||||
.command('rm <id>')
|
||||
.description('Delete any session except this one (refuses your own id)')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { json?: boolean }) => run(Boolean(options.json), (deps) => agentRm(deps, { id })));
|
||||
|
||||
return agent;
|
||||
}
|
||||
@@ -15,15 +15,27 @@ import { existsSync, readFileSync } from 'node:fs';
|
||||
import { isAbsolute, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { dataPath } from './config/instance.js';
|
||||
import { readCodemanCredentials } from './codeman-credentials.js';
|
||||
import { casePath } from './config/cases-dir.js';
|
||||
import { assertValidBasePath } from './config/base-path.js';
|
||||
import { installAgentSkillInto, removeAgentSkillFrom, type AgentSkillApplyResult } from './hooks-config.js';
|
||||
import {
|
||||
agentSkillDir,
|
||||
agentSkillDirFor,
|
||||
CLAUDE_AGENT_SKILL_DIR,
|
||||
installAgentSkillInto,
|
||||
removeAgentSkillFrom,
|
||||
type AgentSkillApplyResult,
|
||||
} from './hooks-config.js';
|
||||
import type { AgentSkillDir } from './config/cli-registry/types.js';
|
||||
import { getCli, listClis } from './config/cli-registry/registry.js';
|
||||
import { registerAgentCommands } from './cli-agent.js';
|
||||
import { resolveMcpConfig, runMcpStdio } from './mcp-server.js';
|
||||
import { getSessionManager } from './session-manager.js';
|
||||
import { getTaskQueue } from './task-queue.js';
|
||||
import { getRalphLoop } from './ralph-loop.js';
|
||||
import { getStore } from './state-store.js';
|
||||
import { getErrorMessage } from './types.js';
|
||||
import { isSupportedAttachmentExtension } from './attachment-registry.js';
|
||||
import { DOCUMENT_ATTACHMENT_EXTENSIONS, isSupportedAttachmentExtension } from './attachment-registry.js';
|
||||
import { daemonStatus, startDaemon, stopDaemon, type WebLaunchOptions } from './daemon-control.js';
|
||||
import { installService, serviceStatus, uninstallService } from './service-installer.js';
|
||||
import { isLoopbackBindHost, isUnauthenticatedNetworkAcknowledged } from './web/network-auth-policy.js';
|
||||
@@ -42,32 +54,8 @@ function makeAttachmentMagicLink(filePath: string): string {
|
||||
return `codeman://attach?path=${encodeURIComponent(filePath)}`;
|
||||
}
|
||||
|
||||
function readCodemanEnv(): Record<string, string> {
|
||||
const envPath = dataPath('.env');
|
||||
try {
|
||||
const text = readFileSync(envPath, 'utf-8');
|
||||
const result: Record<string, string> = {};
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
||||
if (!match) continue;
|
||||
let value = match[2].trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
result[match[1]] = value;
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function postAttachment(apiUrl: string, sessionId: string, filePath: string): Promise<boolean> {
|
||||
const envFile = readCodemanEnv();
|
||||
const username = process.env.CODEMAN_USERNAME || envFile.CODEMAN_USERNAME || 'admin';
|
||||
const password = process.env.CODEMAN_PASSWORD || envFile.CODEMAN_PASSWORD;
|
||||
const { username, password } = readCodemanCredentials();
|
||||
const url = new URL(`/api/sessions/${encodeURIComponent(sessionId)}/attachments`, apiUrl);
|
||||
const body = JSON.stringify({ path: filePath });
|
||||
const transport = url.protocol === 'https:' ? https : http;
|
||||
@@ -111,7 +99,11 @@ program
|
||||
.action(async (filePath, options) => {
|
||||
const extension = String(filePath).split('.').pop()?.toLowerCase() || '';
|
||||
if (!isAbsolute(filePath) || !isSupportedAttachmentExtension(extension)) {
|
||||
console.error(palette.err('✗ attach requires an absolute path to a png, pdf, docx, pptx, md, or txt file'));
|
||||
console.error(
|
||||
palette.err(
|
||||
`✗ attach requires an absolute path to an image (png, jpg, gif, webp), document (${DOCUMENT_ATTACHMENT_EXTENSIONS.join(', ')}), audio, video, md, txt or other text file`
|
||||
)
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -158,7 +150,8 @@ export function resolveCliCasePath(name: string): string {
|
||||
/**
|
||||
* Resolve where `skill install` / `skill uninstall` operate. Global is
|
||||
* `~/.claude/skills/codeman` (Claude Code's user-scope skill dir, read by every new
|
||||
* session); `--case <name>` targets `<case>/.claude/skills/codeman`, resolved through
|
||||
* session); `--case <name>` targets `<case>/<skillDir>/codeman` for the given skills
|
||||
* directory (default: Claude Code's, `<case>/.claude/skills/codeman`), resolved through
|
||||
* `resolveCliCasePath()` above. The web server's automatic per-case injection
|
||||
* (`agentSkillEnabled`) covers multi-user spaces; this CLI is a local operator tool
|
||||
* and stays single-user.
|
||||
@@ -169,17 +162,18 @@ export function resolveCliCasePath(name: string): string {
|
||||
*/
|
||||
export function resolveSkillTargetPath(options: {
|
||||
case?: string;
|
||||
skillDir?: AgentSkillDir;
|
||||
}): { target: string; missingCase?: undefined } | { target?: undefined; missingCase: string } {
|
||||
if (options.case) {
|
||||
const casePath = resolveCliCasePath(options.case);
|
||||
if (!existsSync(casePath)) return { missingCase: casePath };
|
||||
return { target: join(casePath, '.claude', 'skills', 'codeman') };
|
||||
return { target: agentSkillDirFor(casePath, options.skillDir ?? CLAUDE_AGENT_SKILL_DIR) };
|
||||
}
|
||||
return { target: join(homedir(), '.claude', 'skills', 'codeman') };
|
||||
}
|
||||
|
||||
/** Exit-owning wrapper around `resolveSkillTargetPath()` for the two commands below. */
|
||||
function resolveSkillTarget(options: { case?: string }): string {
|
||||
function resolveSkillTarget(options: { case?: string; skillDir?: AgentSkillDir }): string {
|
||||
const resolved = resolveSkillTargetPath(options);
|
||||
if (resolved.missingCase !== undefined) {
|
||||
console.error(palette.err(`✗ Case not found: ${resolved.missingCase}`));
|
||||
@@ -188,8 +182,44 @@ function resolveSkillTarget(options: { case?: string }): string {
|
||||
return resolved.target;
|
||||
}
|
||||
|
||||
/** Print an AgentSkillApplyResult for humans; exit non-zero when nothing was done. */
|
||||
function reportSkillResult(result: AgentSkillApplyResult, target: string): void {
|
||||
/**
|
||||
* The skills directory `skill install --mode <mode>` writes into, or why it cannot: a
|
||||
* mode the registry gives no skill, or a user-level install for a CLI other than Claude
|
||||
* Code (each CLI keeps its user-level skills somewhere else, and `npx skills add`
|
||||
* already knows every one of those places).
|
||||
*/
|
||||
export function resolveSkillInstallDir(options: {
|
||||
mode?: string;
|
||||
case?: string;
|
||||
}): { skillDir: AgentSkillDir; error?: undefined } | { skillDir?: undefined; error: string } {
|
||||
const mode = options.mode ?? 'claude';
|
||||
const cli = getCli(mode);
|
||||
if (!cli) return { error: `Unknown mode: ${mode}` };
|
||||
const skillDir = agentSkillDir(cli.capabilities);
|
||||
if (!skillDir) return { error: `Mode ${mode} takes no Codeman agent skill` };
|
||||
if (!options.case && skillDir !== CLAUDE_AGENT_SKILL_DIR) {
|
||||
return {
|
||||
error: `A user-level install for ${mode} goes through the skills installer: npx skills add Ark0N/Codeman --skill codeman -g (or pass --case <name>)`,
|
||||
};
|
||||
}
|
||||
return { skillDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every distinct skills directory the registry can inject into, so
|
||||
* `skill uninstall --case` removes whatever any CLI's session left there.
|
||||
*/
|
||||
export function registryAgentSkillDirs(): AgentSkillDir[] {
|
||||
const dirs = new Set<AgentSkillDir>();
|
||||
for (const cli of listClis()) {
|
||||
const dir = agentSkillDir(cli.capabilities);
|
||||
if (dir) dirs.add(dir);
|
||||
}
|
||||
return [...dirs];
|
||||
}
|
||||
|
||||
/** An AgentSkillApplyResult in words, and whether it counts as success. */
|
||||
function describeSkillResult(result: AgentSkillApplyResult, target: string): { ok: boolean; text: string } {
|
||||
const messages: Record<AgentSkillApplyResult, { ok: boolean; text: string }> = {
|
||||
installed: { ok: true, text: `Agent skill installed: ${target}` },
|
||||
refreshed: { ok: true, text: `Agent skill refreshed (was stale): ${target}` },
|
||||
@@ -205,7 +235,12 @@ function reportSkillResult(result: AgentSkillApplyResult, target: string): void
|
||||
text: `${target} (or its parent) is a symlink, refusing to write through it.`,
|
||||
},
|
||||
};
|
||||
const message = messages[result];
|
||||
return messages[result];
|
||||
}
|
||||
|
||||
/** Print an AgentSkillApplyResult for humans; exit non-zero when nothing was done. */
|
||||
function reportSkillResult(result: AgentSkillApplyResult, target: string): void {
|
||||
const message = describeSkillResult(result, target);
|
||||
if (message.ok) {
|
||||
console.log(palette.ok(`✓ ${message.text}`));
|
||||
} else {
|
||||
@@ -223,9 +258,19 @@ skillCmd
|
||||
.description('Install the agent skill globally (~/.claude/skills/codeman) or into one case')
|
||||
.option('-g, --global', 'Install into ~/.claude/skills/codeman, picked up by every new session (the default)')
|
||||
.option('-c, --case <name>', 'Install into <case>/.claude/skills/codeman instead (linked cases resolve too)')
|
||||
.action(async (options: { global?: boolean; case?: string }) => {
|
||||
.option(
|
||||
'-m, --mode <mode>',
|
||||
'With --case: install where that run mode looks for skills (codex: <case>/.agents/skills/codeman)',
|
||||
'claude'
|
||||
)
|
||||
.action(async (options: { global?: boolean; case?: string; mode?: string }) => {
|
||||
try {
|
||||
const target = resolveSkillTarget(options);
|
||||
const resolved = resolveSkillInstallDir(options);
|
||||
if (resolved.error !== undefined) {
|
||||
console.error(palette.err(`✗ ${resolved.error}`));
|
||||
process.exit(1);
|
||||
}
|
||||
const target = resolveSkillTarget({ case: options.case, skillDir: resolved.skillDir });
|
||||
reportSkillResult(await installAgentSkillInto(target), target);
|
||||
} catch (err) {
|
||||
console.error(palette.err(`✗ Failed to install agent skill: ${getErrorMessage(err)}`));
|
||||
@@ -235,19 +280,70 @@ skillCmd
|
||||
|
||||
skillCmd
|
||||
.command('uninstall')
|
||||
.description('Remove a Codeman-managed agent skill copy (never touches a user-authored one)')
|
||||
.description('Remove Codeman-managed agent skill copies (never touches a user-authored one)')
|
||||
.option('-g, --global', 'Remove from ~/.claude/skills/codeman (the default)')
|
||||
.option('-c, --case <name>', 'Remove from <case>/.claude/skills/codeman instead (linked cases resolve too)')
|
||||
.option(
|
||||
'-c, --case <name>',
|
||||
"Remove every Codeman-managed copy from that case instead, whichever CLI's directory it is in (linked cases resolve too)"
|
||||
)
|
||||
.action(async (options: { global?: boolean; case?: string }) => {
|
||||
try {
|
||||
const target = resolveSkillTarget(options);
|
||||
reportSkillResult(await removeAgentSkillFrom(target), target);
|
||||
if (!options.case) {
|
||||
const target = resolveSkillTarget(options);
|
||||
reportSkillResult(await removeAgentSkillFrom(target), target);
|
||||
return;
|
||||
}
|
||||
let failed = false;
|
||||
let removedAny = false;
|
||||
for (const skillDir of registryAgentSkillDirs()) {
|
||||
const target = resolveSkillTarget({ case: options.case, skillDir });
|
||||
const result = await removeAgentSkillFrom(target);
|
||||
if (result === 'absent') continue;
|
||||
if (result === 'symlink') {
|
||||
// A shared-skills layout (`.agents/skills -> ../.claude/skills`) is deliberate:
|
||||
// skip it rather than fail the whole sweep.
|
||||
console.log(palette.warn(`- Skipped ${target}: it (or its parent) is a symlink, so it was not touched`));
|
||||
continue;
|
||||
}
|
||||
removedAny = true;
|
||||
const message = describeSkillResult(result, target);
|
||||
if (message.ok) console.log(palette.ok(`✓ ${message.text}`));
|
||||
else {
|
||||
console.error(palette.err(`✗ ${message.text}`));
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
if (!removedAny) console.log(palette.ok(`✓ No Codeman-managed agent skill in case ${options.case}`));
|
||||
if (failed) process.exit(1);
|
||||
} catch (err) {
|
||||
console.error(palette.err(`✗ Failed to remove agent skill: ${getErrorMessage(err)}`));
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
// ============ Agent Commands (session-to-session, any CLI mode) ============
|
||||
|
||||
registerAgentCommands(program);
|
||||
|
||||
// ============ MCP server (any MCP client drives Codeman) ============
|
||||
|
||||
program
|
||||
.command('mcp')
|
||||
.description(
|
||||
'Run a Model Context Protocol server on stdio, so MCP clients (Claude Code, Claude Desktop, Codex, Gemini CLI, Cursor, ...) can start, prompt, wait on, read and delete Codeman sessions'
|
||||
)
|
||||
.option('--url <url>', 'Codeman server URL (default: $CODEMAN_API_URL; never guessed)')
|
||||
.option(
|
||||
'--allow-any-session',
|
||||
'Let the tools prompt, interrupt and delete sessions this server did not start (default: only its own)'
|
||||
)
|
||||
.action(async (options: { url?: string; allowAnySession?: boolean }) => {
|
||||
await runMcpStdio(
|
||||
resolveMcpConfig({ url: options.url, allowAnySession: options.allowAnySession, version: pkg.version })
|
||||
);
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// ============ Session Commands ============
|
||||
|
||||
const sessionCmd = program.command('session').alias('s').description('Manage Claude sessions');
|
||||
@@ -637,9 +733,7 @@ function probeWebServerAt(base: string): Promise<WebServerProbe | null> {
|
||||
} catch {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const envFile = readCodemanEnv();
|
||||
const username = process.env.CODEMAN_USERNAME || envFile.CODEMAN_USERNAME || 'admin';
|
||||
const password = process.env.CODEMAN_PASSWORD || envFile.CODEMAN_PASSWORD;
|
||||
const { username, password } = readCodemanCredentials();
|
||||
const transport = url.protocol === 'https:' ? https : http;
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
if (password) {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @fileoverview Credentials for a client of this Codeman instance's own API.
|
||||
*
|
||||
* Env first, the data dir's `.env` as the fallback — the hand-authored file
|
||||
* `codeman attach`, `codeman tui` and `codeman agent` all read. One reader, so the
|
||||
* three clients cannot drift on quoting, comments or the default username.
|
||||
*
|
||||
* @module codeman-credentials
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dataPath } from './config/instance.js';
|
||||
|
||||
export interface CodemanCredentials {
|
||||
username: string;
|
||||
/** Absent when no password is configured (or only the server's environment has it). */
|
||||
password?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `KEY=value` env file: blank lines and `#` comments skipped, an `export `
|
||||
* prefix tolerated (the file is hand-authored, often sourced by a shell too), one
|
||||
* layer of matching quotes stripped, anything that is not an assignment ignored.
|
||||
*/
|
||||
export function parseEnvFile(text: string): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const match = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
|
||||
if (!match) continue;
|
||||
let value = match[2].trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
result[match[1]] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The data dir's `.env`, parsed. Absent or unreadable means `{}`. */
|
||||
export function readCodemanEnvFile(envFilePath: string = dataPath('.env')): Record<string, string> {
|
||||
try {
|
||||
return parseEnvFile(readFileSync(envFilePath, 'utf-8'));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lookup order every client uses, per field: the environment, then the `.env`
|
||||
* file, then (username only) `admin`. Pure, so a caller with its own environment
|
||||
* object (`codeman agent`'s guard takes one for testability) gets the same answer.
|
||||
*/
|
||||
export function credentialsFrom(env: NodeJS.ProcessEnv, fileEnv: Record<string, string>): CodemanCredentials {
|
||||
const username = env.CODEMAN_USERNAME || fileEnv.CODEMAN_USERNAME || 'admin';
|
||||
const password = env.CODEMAN_PASSWORD || fileEnv.CODEMAN_PASSWORD;
|
||||
return password ? { username, password } : { username };
|
||||
}
|
||||
|
||||
/**
|
||||
* Credentials for the API. No password means no auth is configured, or the user has
|
||||
* it only in the server's environment, in which case the API answers 401.
|
||||
*/
|
||||
export function readCodemanCredentials(
|
||||
envFilePath: string = dataPath('.env'),
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): CodemanCredentials {
|
||||
return credentialsFrom(env, readCodemanEnvFile(envFilePath));
|
||||
}
|
||||
|
||||
/** `Authorization` header value, or undefined when there is no password to send. */
|
||||
export function basicAuthHeader(credentials: CodemanCredentials): string | undefined {
|
||||
if (!credentials.password) return undefined;
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
@@ -113,6 +113,16 @@ export const FILE_PEEK_BYTES = 8 * 1024 - 1; // 8KB (inclusive end offset)
|
||||
*/
|
||||
export const MAX_PASTE_IMAGE_BYTES = parseInt(process.env.CODEMAN_MAX_PASTE_IMAGE_BYTES || '') || 50 * 1024 * 1024; // 50MB
|
||||
|
||||
/**
|
||||
* Maximum size (bytes) of a single video uploaded via POST
|
||||
* /api/sessions/:id/paste-image?kind=video (the phone toolbar's Attach button
|
||||
* offers the camera roll's videos beside its photos). Videos stream to disk
|
||||
* rather than through memory, so this is a disk-fill sanity bound, not a memory
|
||||
* bound: a minute of 4K60 from an iPhone is about 400MB, so the image cap would
|
||||
* refuse most clips. Override: CODEMAN_MAX_PASTE_VIDEO_BYTES (bytes)
|
||||
*/
|
||||
export const MAX_PASTE_VIDEO_BYTES = parseInt(process.env.CODEMAN_MAX_PASTE_VIDEO_BYTES || '') || 1024 * 1024 * 1024; // 1GB
|
||||
|
||||
// ============================================================================
|
||||
// File Download Limits
|
||||
// ============================================================================
|
||||
|
||||
@@ -15,7 +15,10 @@
|
||||
import { z } from 'zod';
|
||||
import { compileVersionRegex, countCaptureGroups, TOKEN_PATTERNS } from './patterns.js';
|
||||
import { isKnownLauncherProfile, isKnownSetenvProfile } from './profiles.js';
|
||||
import type { McpConfigFormat, ModelConfigResolverName } from './types.js';
|
||||
import type { AgentSkillDir, LaunchDefaultSettingKey, McpConfigFormat, ModelConfigResolverName } from './types.js';
|
||||
|
||||
/** `capabilities.agentSkillDir`: every value must stay a fixed, relative, `..`-free path. */
|
||||
export const AGENT_SKILL_DIRS = ['.claude/skills', '.agents/skills'] as const satisfies readonly AgentSkillDir[];
|
||||
|
||||
/** A bare CLI id: lowercase, starts with a letter, at most 24 chars. Also used as a CSS/URL token. */
|
||||
const cliId = z
|
||||
@@ -289,11 +292,15 @@ const capabilitiesSchema = z
|
||||
requiresMux: z.boolean(),
|
||||
hooks: z.enum(['none', 'always', 'supervised']),
|
||||
transcript: z.enum(['claude-jsonl', 'codex-rollout', 'deepseek-zstd', 'omp-jsonl', 'none']),
|
||||
altScreen: z.enum(['strip-full', 'strip-mux-only', 'preserve']),
|
||||
altScreen: z.enum(['strip-full', 'strip-mux-only', 'strip-mux-and-mouse', 'preserve']),
|
||||
echo: echoSchema,
|
||||
wheelForward: z
|
||||
.object({ mode: z.enum(['never', 'version-gated']), minVersion: z.string().max(20).optional() })
|
||||
.strict(),
|
||||
// Whether a hollow pane's wheel/touch scroll may be turned into PageUp/PageDown for
|
||||
// the CLI to page its own transcript. Distinct from wheelForward (SGR reports).
|
||||
// Optional: absent means no paging, the safe default for an unmeasured CLI.
|
||||
transcriptPageKeys: z.boolean().optional(),
|
||||
keyboardAccessory: z.enum(['agent', 'shell']),
|
||||
privilegedCommandGate: z.boolean(),
|
||||
startMode: z.enum(['interactive', 'shell']),
|
||||
@@ -302,6 +309,9 @@ const capabilitiesSchema = z
|
||||
respawn: z.boolean(),
|
||||
effort: z.boolean(),
|
||||
agentSkillInjection: z.boolean(),
|
||||
// A closed list on purpose: it decides where the server WRITES, and this file is
|
||||
// user-editable, so it can never be a free path (`..`, absolute).
|
||||
agentSkillDir: z.enum(AGENT_SKILL_DIRS).optional(),
|
||||
statusLineTelemetry: z.boolean(),
|
||||
// How many columns this CLI indents its transcript body by, so a copy can take
|
||||
// that much off the clipboard. Bounded, because it is the whole strip: a copy
|
||||
@@ -320,6 +330,8 @@ const capabilitiesSchema = z
|
||||
// A declared width cannot do either. Absent means no strip, so a CLI whose
|
||||
// transcript layout nobody has measured is never touched.
|
||||
transcriptGutter: z.number().int().min(1).max(8).optional(),
|
||||
// Literal text matched by a `wait-output` long-poll, never compiled as a regex.
|
||||
composerReadyMark: z.string().min(1).max(64).optional(),
|
||||
workDetect: z
|
||||
.object({
|
||||
promptGlyph: z.string().min(1).max(8),
|
||||
@@ -385,8 +397,10 @@ const capabilitiesSchema = z
|
||||
)
|
||||
.optional(),
|
||||
// Bounded hard, like watchingLines: every row it adds is one more row the agent
|
||||
// itself may be able to write.
|
||||
screenLines: z.number().int().min(1).max(4).optional(),
|
||||
// itself may be able to write. 8 is the reader's own cap (readScreenModel); a
|
||||
// window taller than the CLI's footer needs a pattern only that CLI's chrome can
|
||||
// satisfy at its position, as opencode's does by taking the LAST composer row.
|
||||
screenLines: z.number().int().min(1).max(8).optional(),
|
||||
// Single tokens, bounded: each is compared against one captured field.
|
||||
rejectWords: z.array(z.string().min(1).max(40).regex(/^\S+$/)).max(32).optional(),
|
||||
// A NAMED reader (src/model-config-resolvers.ts), never code in config.
|
||||
@@ -407,6 +421,17 @@ const capabilitiesSchema = z
|
||||
'rejectWords has nothing to filter without a screenLine'
|
||||
)
|
||||
.optional(),
|
||||
// Launch param -> synced App Settings key. The values are a closed enum, like
|
||||
// configResolver: a clis.json override names one of the settings this build knows
|
||||
// how to validate, never an arbitrary key. Params are checked against the declared
|
||||
// ones in the superRefine below.
|
||||
launchDefaults: z
|
||||
.record(
|
||||
z.string(),
|
||||
z.enum(['codexModel', 'codexReasoningEffort'] as const satisfies readonly LaunchDefaultSettingKey[])
|
||||
)
|
||||
.refine((v) => Object.keys(v).length >= 1 && Object.keys(v).length <= 8, 'launchDefaults takes 1 to 8 params')
|
||||
.optional(),
|
||||
privilegedParams: z
|
||||
.array(
|
||||
z
|
||||
@@ -428,6 +453,9 @@ const capabilitiesSchema = z
|
||||
.object({
|
||||
// Home-relative, no traversal: sync writes to this path.
|
||||
path: mcpRelativePath,
|
||||
// Home-relative fallback used when `path` is absent. Same no-traversal rule as `path`:
|
||||
// sync reads it and, when it parses as plain JSON, writes to it.
|
||||
altPath: mcpRelativePath.optional(),
|
||||
// Every value must be a known McpConfigFormat (types.ts); mcp-sync.ts's dialect table is
|
||||
// keyed by the same type, so an adapter-less format fails to compile there.
|
||||
format: z.enum([
|
||||
@@ -436,6 +464,7 @@ const capabilitiesSchema = z
|
||||
'codex-toml',
|
||||
'opencode-json',
|
||||
'antigravity-json',
|
||||
'copilot-json',
|
||||
] as const satisfies readonly McpConfigFormat[]),
|
||||
// The env var the CLI reads to move the file, and the path under it (same no-traversal
|
||||
// rule: sync writes there too). Resolved from the server env at call time, never here.
|
||||
@@ -625,6 +654,30 @@ export const CliEntrySchema = z
|
||||
}
|
||||
});
|
||||
|
||||
// Same silent-no-op class again: a launch default for a param the entry never declared
|
||||
// would be filled into the config object and then read by nothing. And without a
|
||||
// `legacyConfigField` the entry's params are read off the request body itself, where a
|
||||
// filled `model` would be a different field (claude's per-session one), so refuse it.
|
||||
const { launchDefaults } = entry.capabilities;
|
||||
if (launchDefaults !== undefined) {
|
||||
if (entry.launch.legacyConfigField === undefined) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: 'launchDefaults needs launch.legacyConfigField to fill',
|
||||
path: ['capabilities', 'launchDefaults'],
|
||||
});
|
||||
}
|
||||
for (const param of Object.keys(launchDefaults)) {
|
||||
if (!declaredParams.has(param)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `launchDefaults param "${param}" is not a declared launch param`,
|
||||
path: ['capabilities', 'launchDefaults', param],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { setenvProfile } = entry.env;
|
||||
if (setenvProfile !== undefined && !isKnownSetenvProfile(setenvProfile)) {
|
||||
ctx.addIssue({
|
||||
|
||||
@@ -76,6 +76,21 @@ function agentDefaults(): Pick<
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent skill in `<workspace>/.agents/skills/codeman`, the one project skills
|
||||
* directory every CLI that spreads this scans. Measured per CLI on
|
||||
* 2026-10-11 against the installed builds or their source: codex 0.162 (every dir from
|
||||
* the git root down to cwd), gemini (cwd only, behind folder trust, which `--skip-trust`
|
||||
* already answers), opencode 1.3 (cwd up to the worktree), agy 1.3.2 (its `.agents/`
|
||||
* customization root), grok 1.0.5 (each tier from cwd up to the repo root), dsh 0.1.1
|
||||
* (the git root, else cwd) and omp (cwd up to the git root). Claude Code does NOT read
|
||||
* `.agents/skills`, so a case shared with a claude session lists each skill once there.
|
||||
*/
|
||||
const AGENTS_DIR_SKILL: Pick<CliEntry['capabilities'], 'agentSkillInjection' | 'agentSkillDir'> = {
|
||||
agentSkillInjection: true,
|
||||
agentSkillDir: '.agents/skills',
|
||||
};
|
||||
|
||||
// `accent` on every entry below (except SHELL, which the frontend renders no
|
||||
// distinct color for) is measured from the actual `.btn-toolbar.btn-run.mode-<id>`
|
||||
// CSS rule's `border-color` on the OG skin (styles.css) — the single cleanest
|
||||
@@ -218,6 +233,9 @@ const CLAUDE: CliEntry = {
|
||||
// in them, so a copy can drop two and paste flush. Claude and codex are the only
|
||||
// entries that declare this, because theirs are the only gutters that have been measured.
|
||||
transcriptGutter: 2,
|
||||
// The composer's own hint text (`⏵⏵ … (shift+tab to cycle)`), not `❯`, which the
|
||||
// trust dialog's selected row also carries. Measured by the agent skill's spawn_worker.
|
||||
composerReadyMark: 'shift+tab',
|
||||
// The historical hard-coded pair, now stated as data. `workingLine` matches both the
|
||||
// `✻ Actualizing… (39s · ↓ 2.0k tokens)` status line and the bare `esc to interrupt`
|
||||
// footer, because tmux repaints partially and only one of the two may land in a chunk.
|
||||
@@ -267,6 +285,10 @@ const CLAUDE: CliEntry = {
|
||||
// Declared-for-later: the live rule (`_shouldForwardWheelToApp`, terminal-ui.js) is this version
|
||||
// AND the server-published `cliMouseTracking` flag (#498), so wiring this field up needs both.
|
||||
wheelForward: { mode: 'version-gated', minVersion: '2.1.187' },
|
||||
// A repaint-mode Claude pane keeps no local history, so when the wheel is not
|
||||
// forwarded (older CLI, inline renderer, the local-scrollback opt-out) a scroll is
|
||||
// turned into PageUp/PageDown, which Claude pages its transcript on (#205).
|
||||
transcriptPageKeys: true,
|
||||
keyboardAccessory: 'agent',
|
||||
privilegedCommandGate: false,
|
||||
startMode: 'interactive',
|
||||
@@ -275,6 +297,7 @@ const CLAUDE: CliEntry = {
|
||||
respawn: true,
|
||||
effort: true,
|
||||
agentSkillInjection: true,
|
||||
agentSkillDir: '.claude/skills',
|
||||
statusLineTelemetry: true,
|
||||
model: { source: 'claude-settings-file' },
|
||||
privilegedParams: [],
|
||||
@@ -491,11 +514,55 @@ const OPENCODE: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
altScreen: 'strip-mux-only',
|
||||
...AGENTS_DIR_SKILL,
|
||||
altScreen: 'strip-mux-and-mouse',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' }, predictProfile: undefined },
|
||||
// Pages its own transcript on PageUp/PageDown (`messages_page_up/down`) and ignores
|
||||
// SGR wheel reports, and its TUI runs on the alternate screen (1.18.31: tmux
|
||||
// `alternate_on=1`, `history_size=0`), so a pane keeps no local history and the
|
||||
// wheel is turned into page keys or it does nothing at all (#555).
|
||||
transcriptPageKeys: true,
|
||||
// Measured on a live opencode 1.3.0 pane (capture-pane every 250-300 ms through real
|
||||
// turns at 40, 60, 120 and 200 columns, plus the raw PTY stream, 2026-10-09). Every
|
||||
// composer row starts with a `┃` bar, and the submitted prompt lands in the transcript
|
||||
// with the same bar, so a turn's first repaint arms the idle confirmation and tmux's
|
||||
// reattach repaint does the same for a restored pane. While a turn runs the footer row
|
||||
// starts with an 8-cell knight-rider spinner, `⬝■■■■■■⬝ esc interrupt`, redrawn about
|
||||
// every 40 ms (never a 2.5 s gap mid-turn, so silence cannot end one early); at rest the
|
||||
// row holds only the key hints and nothing on screen draws a `⬝`/`■` run, the wide
|
||||
// layout's sidebar included. The working line is the spinner run, not the label: tmux
|
||||
// ships `esc` and `interrupt` as separate words joined by cursor moves, and below about
|
||||
// 45 columns the footer wraps the label itself. A pending permission prompt replaces
|
||||
// the composer and stops the spinner, so it reads as idle (waiting on the user).
|
||||
// ⚠️ Without this entry an opencode session latched `busy` after any turn that ran a
|
||||
// tool: the braille spinner on a running tool row trips SPINNER_PATTERN, and opencode
|
||||
// never draws Claude's `❯`, the fallback that would have armed the idle check. The
|
||||
// last `┃` row on screen is the composer's agent/model row (or the permission box's
|
||||
// closing bar), never the prompt text, so the submit verifier stands down.
|
||||
workDetect: {
|
||||
promptGlyph: '┃',
|
||||
workingLine: '[⬝■]{8}',
|
||||
},
|
||||
// The composer's agent row, measured on live opencode 1.3.0 panes (home screen and in
|
||||
// session, at 40, 60, 120 and 200 columns, 2026-10-09): `┃ Build Big Pickle OpenCode
|
||||
// Zen`, directly above the box's bottom edge `╹▀▀▀`. opencode renders it as the agent,
|
||||
// then the model's name, then the provider's name (then `· <variant>` when the model
|
||||
// has one), and only colour tells model from provider, so the field is all of it: what
|
||||
// opencode itself shows, owner's choice. A double space ends it, which is where the
|
||||
// 200-column layout's sidebar shares the row. The lookahead takes the LAST such row in
|
||||
// the window, so nothing the agent prints higher up can stand in for it; below the
|
||||
// composer there is only opencode's own chrome (key hints, a tip, the cwd/version
|
||||
// row), which is why the window can be 8 rows: the home screen puts up to 5 of those
|
||||
// rows under it. A permission prompt or shell mode hides the row, and the last model
|
||||
// is kept. `No provider ` is opencode's placeholder before a provider is connected.
|
||||
modelDetect: {
|
||||
screenLine: String.raw`┃ {2}[^\s·]+ {2}(?!No provider )([^ \n](?:[^ \n]| (?! ))*)(?: {2}.*)?\n *╹(?![\s\S]*\n *╹)`,
|
||||
screenLines: 8,
|
||||
},
|
||||
// opencode's global config dir is xdg-basedir's `$XDG_CONFIG_HOME/opencode`.
|
||||
mcpConfig: {
|
||||
path: '.config/opencode/opencode.json',
|
||||
altPath: '.config/opencode/opencode.jsonc',
|
||||
format: 'opencode-json',
|
||||
relocation: { envVar: 'XDG_CONFIG_HOME', path: 'opencode/opencode.json' },
|
||||
},
|
||||
@@ -587,6 +654,7 @@ const CODEX: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
...AGENTS_DIR_SKILL,
|
||||
// Codex draws `› Ask Codex to do anything` on its composer row and
|
||||
// `Working (2m 49s • esc to interrupt)` above it while a turn runs. It animates no
|
||||
// braille spinner, and it never prints `esc to interrupt` at rest, so that phrase
|
||||
@@ -598,10 +666,15 @@ const CODEX: CliEntry = {
|
||||
// Measured against a live codex-cli 0.154.0 pane on 2026-09-22: the row appears when
|
||||
// the terminal starts, follows the composer down as the conversation grows, and is
|
||||
// gone after `/stop`.
|
||||
// ⚠️ Codex 0.162.0 (measured 2026-10-09) draws a hint row under the status line at
|
||||
// rest (` ← for agents · ? for shortcuts`) and drops it while a prompt is typed, so
|
||||
// the chip is FOURTH from the bottom at rest and third while typing. A three-row
|
||||
// window never saw it at rest, which is exactly when the idle probe reads it, so a
|
||||
// session waiting on its terminal read as plainly idle. Four rows cover both.
|
||||
// ⚠️ This entry CANNOT promise what Claude's does, and the difference is Codex's
|
||||
// layout rather than its pattern. The third row from the bottom is the chip only
|
||||
// layout rather than its pattern. The fourth row from the bottom is the chip only
|
||||
// while a terminal runs; with none running it is the last row of the transcript,
|
||||
// which the agent writes. Matching the complete row raises the bar — an assistant
|
||||
// which the agent writes (and while a prompt is typed, the last two). Matching the complete row raises the bar — an assistant
|
||||
// message has to end with this exact line, to the character — but nothing here makes
|
||||
// forging it impossible, so do not read the Claude comment above as applying here.
|
||||
// What contains it is that codex declares `hooks: 'none'`: no hook event from a codex
|
||||
@@ -620,18 +693,37 @@ const CODEX: CliEntry = {
|
||||
promptGlyph: '›',
|
||||
workingLine: '[Ee]sc to interrupt',
|
||||
watchingLine: String.raw`^\s{0,4}(\d+ background terminals?) running · /ps to view · /stop to close$`,
|
||||
watchingLines: 3,
|
||||
watchingLines: 4,
|
||||
},
|
||||
// The footer under the composer, measured on a live 0.147.0 pane:
|
||||
// ` gpt-5.6-terra default · ~/codeman-cases/th-scratch` (model, reasoning effort,
|
||||
// cwd). It is the pane's LAST row, below the composer, so the transcript never
|
||||
// reaches it, and the effort word right after the model is codex's own format: an
|
||||
// open slash-command popup or a bare line of prose does not have that shape. A
|
||||
// footer without an effort word (a model with no reasoning setting) is not read,
|
||||
// and the session keeps its last known or launch model.
|
||||
// cwd). It sits below the composer, so the transcript never reaches it, and the
|
||||
// effort word right after the model is codex's own format: an open slash-command
|
||||
// popup or a bare line of prose does not have that shape. A footer without an effort
|
||||
// word (a model with no reasoning setting) is not read, and the session keeps its
|
||||
// last known or launch model.
|
||||
// The effort words are built from CODEX_REASONING_EFFORTS, the same list the
|
||||
// `reasoningEffort` launch param above admits, plus `default` (what codex prints when
|
||||
// no effort is configured). A hand-kept copy once left out `ultra`, so a session at
|
||||
// that level never named its model. Every word is plain letters, so the join adds no
|
||||
// quantifier and only a few characters to the 200-character compileVersionRegex cap.
|
||||
// ⚠️ It is not always the LAST row. 0.162.0 (measured 2026-10-09) adds a hint row
|
||||
// under it at rest, ` ← for agents · ? for shortcuts` or ` ? for shortcuts`, and
|
||||
// drops it again while a prompt is being typed. With a one-row window the footer was
|
||||
// never seen and every codex tile showed no model. So the window is two rows and the
|
||||
// footer is either the last one or followed by exactly one more two-space-indented
|
||||
// row. The `$` (no `m` flag: the end of the window) is what keeps the guard the
|
||||
// one-row rule had: with the footer hidden, the last two rows are a transcript line
|
||||
// and the `›` composer, and a forged footer-shaped transcript line is not followed by
|
||||
// an indented row, so it is not read.
|
||||
modelDetect: {
|
||||
screenLine: String.raw`^ {2}([A-Za-z0-9][\w.:/@+-]{0,79}) (?:none|minimal|low|medium|high|xhigh|max|default) · `,
|
||||
screenLine: String.raw`(?:^|\n) {2}([A-Za-z0-9][\w.:/@+-]{0,79}) (?:${[...CODEX_REASONING_EFFORTS, 'default'].join('|')}) · [^\n]*(?:\n {2}[^\n]*)?$`,
|
||||
screenLines: 2,
|
||||
},
|
||||
// App Settings → Codex model / reasoning effort (synced), filled into a LOCAL launch's
|
||||
// codexConfig wherever the caller left the field unset. Launch-only: nothing writes
|
||||
// codex's own config.toml. Read by applyLaunchDefaults() in src/web/launch-defaults.ts.
|
||||
launchDefaults: { model: 'codexModel', reasoningEffort: 'codexReasoningEffort' },
|
||||
// Two columns, like claude's, measured on a live 0.154.0 answer: the `•`/`›`/`⚠`
|
||||
// markers sit in the gutter, prose continuations sit at 2, and a nested YAML block
|
||||
// the model wrote rendered at 2/4/6/8 for its own 0/2/4/6. Replayed at 100, 120,
|
||||
@@ -642,6 +734,11 @@ const CODEX: CliEntry = {
|
||||
altScreen: 'strip-full',
|
||||
echo: { policy: 'predict', anchor: { kind: 'cursor' }, predictProfile: 'codex' },
|
||||
wheelForward: { mode: 'never' }, // #227: codex ignores SGR wheel reports, never forward
|
||||
// ...but it DOES page its transcript on PageUp/PageDown. Measured on 0.157.1 (local,
|
||||
// alternate screen inside tmux, so xterm holds no history) and 0.160 (remote): PageUp
|
||||
// moved the visible transcript while SGR wheel reports and local scrolling did nothing.
|
||||
// This is the page-key fallback for a hollow pane, not wheel forwarding.
|
||||
transcriptPageKeys: true,
|
||||
maxFrameBytes: 32 * 1024,
|
||||
// codex's own bare-spawn default (no config sent) is already safe (no bypass flag), so
|
||||
// the multi-user clamp only needs to force an EXPLICITLY-SENT bypass back off.
|
||||
@@ -752,8 +849,31 @@ const GEMINI: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
...AGENTS_DIR_SKILL,
|
||||
altScreen: 'strip-full',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' } },
|
||||
// Measured on a live Gemini CLI 0.63.0 pane (capture-pane every 300 ms through real
|
||||
// turns with a shell call at 40, 120 and 200 columns, YOLO and default approval mode,
|
||||
// plus the raw PTY stream, 2026-10-09). The TUI repaints its whole bottom region on
|
||||
// every frame, composer included, and the composer sits between a `▄` bar and a `▀`
|
||||
// bar; the submitted prompt is echoed between the same bars. So the `▀` bar arms the
|
||||
// idle confirmation (every repaint and tmux's reattach repaint carry it), and it is the
|
||||
// glyph rather than the composer's prompt character, which follows the approval mode
|
||||
// (`*` in YOLO) and whose `>` also starts the echoed prompt. While a turn runs a line
|
||||
// `⠦ Thinking... (esc to cancel, 6s)` animates about every 80 ms (largest gap mid-turn:
|
||||
// 214 ms); the label can be any loading phrase, so the working line is the
|
||||
// `(esc to cancel, <n>` suffix, or a spinner frame opening a line where a long phrase
|
||||
// pushed that suffix onto the next one. At rest nothing on screen matches either. A tool
|
||||
// confirmation (default mode) replaces the composer and stops the spinner, and the pane
|
||||
// goes silent, so it reads as idle (waiting on the user).
|
||||
// ⚠️ Without this entry a gemini session latched `busy` after its first turn: the braille
|
||||
// spinner trips SPINNER_PATTERN, and gemini never draws Claude's `❯`, the fallback that
|
||||
// would have armed the idle check. A line starting with `▀` is a bar, never prompt text,
|
||||
// so the submit verifier stands down.
|
||||
workDetect: {
|
||||
promptGlyph: '▀',
|
||||
workingLine: String.raw`\(esc to cancel, \d|(?:^|\n) ?[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] `,
|
||||
},
|
||||
// gemini's builder defaults an ABSENT approvalMode to 'yolo', so the clamp must
|
||||
// MATERIALIZE a config (not just touch an already-sent one) or a non-granted owner who
|
||||
// sends no geminiConfig at all would still get yolo for free.
|
||||
@@ -838,6 +958,7 @@ const ANTIGRAVITY: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
...AGENTS_DIR_SKILL,
|
||||
altScreen: 'strip-mux-only',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' } },
|
||||
// Like codex: an ABSENT config already defaults safe (no bypass flag), so only a
|
||||
@@ -933,8 +1054,44 @@ const PI: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
// No agent skill (agentSkillInjection stays false): any project-level `.agents/skills`
|
||||
// or `.pi/skills` makes pi ask "Trust project folder?" at startup
|
||||
// (hasTrustRequiringProjectResources, pi 1.1.0), which would stall a spawned worker on
|
||||
// a dialog. pi reads the user-level `~/.agents/skills` without that prompt, so a pi
|
||||
// user installs it there (`npx skills add Ark0N/Codeman --skill codeman -g`).
|
||||
altScreen: 'preserve', // pi's TUI renders into the main screen with terminal-owned scrollback
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' } },
|
||||
// Measured on a live pi 1.1.0 pane (capture-pane every 250 ms through a turn,
|
||||
// 2026-10-09): pi has no composer glyph. Its composer sits between two `─` rules, and
|
||||
// while a turn runs it embeds its status in the TOP rule as `── ⠏ Working ───…`, the
|
||||
// braille frame animating every ~80 ms; at rest both rules are plain `─`. So the rule
|
||||
// is the glyph that arms the idle confirmation, and a spinner frame inside it is the
|
||||
// working line (the frame, not the word: an extension can replace "Working").
|
||||
// ⚠️ Without this entry a pi session never left `busy` once marked working: the
|
||||
// braille spinner trips SPINNER_PATTERN, and pi never draws Claude's `❯`, the
|
||||
// fallback that would have armed the idle check. The rules carry no prompt text, so
|
||||
// the submit verifier reading them stands down instead of re-pressing Enter.
|
||||
workDetect: {
|
||||
promptGlyph: '─',
|
||||
workingLine: '── [⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] ',
|
||||
},
|
||||
// pi's footer stats row, read from pi 1.1.0's footer code (0.84.4's is the same) and
|
||||
// measured live as `0.8%/253k (auto) qwen3.8-27b-pi • xhigh`: usage and
|
||||
// context on the left, then at least two spaces and `[(provider) ]<model>` followed
|
||||
// by ` • <thinking>` for a reasoning model and ` → <routed model>` when routed. Only
|
||||
// the last two rows are read, which sit below the composer where the transcript never
|
||||
// reaches (an extension's status row may sit under the stats row), and the context
|
||||
// field (`12.3%/253k`, `?/128k`) picks the stats row out of them.
|
||||
// ⚠️ A narrow pane truncates the right side with NO ellipsis, leaving exactly two
|
||||
// spaces of padding. So a model with nothing after it is read only with 3+ spaces in
|
||||
// front; with two, only when a following ` •`/` →` proves the name is whole (the
|
||||
// bullet only ever follows a complete name, even when the cut lands right after it).
|
||||
// A cut name is never shown. `no-model` is pi's placeholder when none is selected.
|
||||
modelDetect: {
|
||||
screenLine: String.raw`[%?]/[\d.]+[kKM]?(?: \(auto\))?(?: • xp)? {2}(?: +|(?=(?:\(\S{1,40}\) )?\S{1,80} [•→]))(?:\([\w.@-]{1,40}\) )?([A-Za-z0-9][\w.:/@+-]{0,79})(?= [•→]|\n|$)`,
|
||||
screenLines: 2,
|
||||
rejectWords: ['no-model'],
|
||||
},
|
||||
// pi's absent-config default is an interactive trust PROMPT the session user could
|
||||
// just answer "yes" to, so omitting --approve is not itself a clamp — MATERIALIZE
|
||||
// approveProjectTrust:false so buildPiCommand emits --no-approve outright.
|
||||
@@ -1052,8 +1209,10 @@ const GROK: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
// Fullscreen alt-screen TUI with mouse support — same shape as opencode/antigravity:
|
||||
// only the tmux-attach-time smcup strip, not Ink's full erase-scrollback+DECSET strip.
|
||||
...AGENTS_DIR_SKILL,
|
||||
// Fullscreen alt-screen TUI with mouse support, same strip as antigravity until measured
|
||||
// (opencode's mouse strip is #443): only the tmux-attach-time smcup strip, not Ink's full
|
||||
// erase-scrollback+DECSET strip.
|
||||
altScreen: 'strip-mux-only',
|
||||
// Buffer-policy fallthrough default, unmeasured against an authenticated grok composer
|
||||
// (the existing hedge, preserved verbatim) — same as gemini/antigravity/pi.
|
||||
@@ -1223,10 +1382,13 @@ const DEEPSEEK: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
...AGENTS_DIR_SKILL,
|
||||
// Definitive rather than inferred: the harness TUI reports idle/working/blocked to a
|
||||
// supervisor and Codeman is that supervisor. 'supervised' rather than 'always' because
|
||||
// the session can disarm the bridge, and docker/remote cannot reach it at all.
|
||||
hooks: 'supervised',
|
||||
// dsh's composer glyph, drawn once the harness TUI can take a prompt.
|
||||
composerReadyMark: '❯',
|
||||
transcript: 'deepseek-zstd',
|
||||
altScreen: 'strip-mux-only',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' } },
|
||||
@@ -1386,13 +1548,28 @@ const OMP: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
// Fullscreen alt-screen TUI, same shape as opencode/antigravity/grok: only the
|
||||
...AGENTS_DIR_SKILL,
|
||||
// Fullscreen alt-screen TUI, same shape as antigravity/grok: only the
|
||||
// tmux-attach-time smcup strip, not Ink's full erase-scrollback+DECSET strip.
|
||||
altScreen: 'strip-mux-only',
|
||||
// Codeman reads omp's own `~/.omp/agent/sessions/**/*.jsonl` host-side, which is what
|
||||
// makes an omp conversation survive a full session kill.
|
||||
transcript: 'omp-jsonl',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'cursor' } },
|
||||
// Measured on live omp 18.8.6 and 18.0.11 panes (2026-10-09, a turn held open against
|
||||
// an endpoint that never answers): the input row is `╰─ <text>`, redrawn when a turn
|
||||
// ends, at launch and on reattach. While a turn runs the status bar's leading `π`
|
||||
// becomes a braille spinner plus the elapsed time (` ⠼ 14s > ⬢ model > 📁 ~/dir ▶──`;
|
||||
// 18.0.11 pads it with two spaces, past a minute it reads `1m`), and a `⎋ Working…`
|
||||
// row appears above it. At rest the bar starts ` π > `.
|
||||
// ⚠️ Without this entry an omp session never left `busy` once marked working, like pi:
|
||||
// the spinner trips SPINNER_PATTERN and omp never draws Claude's `❯` after setup.
|
||||
// The glyph also switches the submit verifier on for omp. A prompt sent mid-turn goes
|
||||
// to omp's `Steering` queue and clears the input row, so the verifier stands down.
|
||||
workDetect: {
|
||||
promptGlyph: '╰─',
|
||||
workingLine: '[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] [0-9hms ]+> |⎋ Working',
|
||||
},
|
||||
// No permission prompts and no bypass flag, so nothing config-shaped to clamp — the
|
||||
// whole privileged surface here is env-shaped.
|
||||
privilegedParams: [],
|
||||
|
||||
@@ -69,6 +69,14 @@ export type Cond =
|
||||
*/
|
||||
export type QuoteStyle = 'auto' | 'bare' | 'double' | 'single';
|
||||
|
||||
/**
|
||||
* Workspace-relative directories an agent CLI scans for project skills. A closed list
|
||||
* rather than a free path: the value decides where the server WRITES, and
|
||||
* `~/.codeman/clis.json` can set it, so it must never be able to name `..` or an
|
||||
* absolute path.
|
||||
*/
|
||||
export type AgentSkillDir = '.claude/skills' | '.agents/skills';
|
||||
|
||||
/** One argv element. */
|
||||
export type ArgSpec =
|
||||
/** A bare literal word, e.g. the base binary or codex's `resume` subcommand. */
|
||||
@@ -96,8 +104,22 @@ export type NewlineSequence = 'line-feed' | 'esc-enter';
|
||||
/** The config readers `capabilities.modelDetect.configResolver` may name (src/model-config-resolvers.ts). */
|
||||
export type ModelConfigResolverName = 'deepseek-route';
|
||||
|
||||
/**
|
||||
* The synced App Settings keys `capabilities.launchDefaults` may name (src/web/launch-defaults.ts).
|
||||
* A closed list rather than any settings key, so a clis.json override cannot feed an
|
||||
* arbitrary setting onto a command line; each name must also be a `SettingsUpdateSchema`
|
||||
* key, which the resolver's typing enforces.
|
||||
*/
|
||||
export type LaunchDefaultSettingKey = 'codexModel' | 'codexReasoningEffort';
|
||||
|
||||
/** The MCP config dialects `src/mcp-sync.ts` has an adapter for. */
|
||||
export type McpConfigFormat = 'claude-json' | 'gemini-json' | 'codex-toml' | 'opencode-json' | 'antigravity-json';
|
||||
export type McpConfigFormat =
|
||||
| 'claude-json'
|
||||
| 'gemini-json'
|
||||
| 'codex-toml'
|
||||
| 'opencode-json'
|
||||
| 'antigravity-json'
|
||||
| 'copilot-json';
|
||||
|
||||
export interface CliLaunch {
|
||||
params: Record<string, ParamSpec>;
|
||||
@@ -365,8 +387,8 @@ export interface CliCapabilities {
|
||||
/**
|
||||
* How many rows at the FOOT of the screen that row can appear in, counting non-blank
|
||||
* rows only. Claude writes its chip on the last row and keeps the default; Codex pins
|
||||
* its own above the composer, which puts it third from the bottom, so it declares
|
||||
* more. Keep each number as small as that CLI's layout allows: every extra row is
|
||||
* its own above the composer, which puts it third or fourth from the bottom (its hint
|
||||
* row comes and goes), so it declares more. Keep each number as small as that CLI's layout allows: every extra row is
|
||||
* another row an agent might be able to write, and the label is what silences an
|
||||
* alert. See `watchingLabel()` in `session-activity.ts`.
|
||||
*/
|
||||
@@ -408,6 +430,17 @@ export interface CliCapabilities {
|
||||
* Absent means no strip at all, the same fail-safe direction `workDetect` takes.
|
||||
*/
|
||||
transcriptGutter?: number;
|
||||
/**
|
||||
* Literal text the TUI draws once its composer can take a prompt — what `codeman agent
|
||||
* spawn` waits for (a `wait-output` match) before it calls a worker ready.
|
||||
*
|
||||
* Deliberately NOT `workDetect.promptGlyph`: claude's `❯` also marks the selected row
|
||||
* of its workspace-trust dialog, which is exactly the screen a readiness wait must not
|
||||
* mistake for a composer, so claude declares its composer's own hint text instead.
|
||||
* Absent means no readiness wait: a spawn returns as soon as the session exists, and
|
||||
* the caller synchronizes on `wait-output` markers.
|
||||
*/
|
||||
composerReadyMark?: string;
|
||||
/** No direct-PTY fallback: the CLI must run inside tmux (secrets ride tmux setenv). */
|
||||
requiresMux: boolean;
|
||||
/**
|
||||
@@ -439,11 +472,40 @@ export interface CliCapabilities {
|
||||
*/
|
||||
transcript: 'claude-jsonl' | 'codex-rollout' | 'deepseek-zstd' | 'omp-jsonl' | 'none';
|
||||
/**
|
||||
* 'strip-full' — alt-screen + erase-scrollback + mouse DECSETs stripped (Ink TUIs).
|
||||
* 'strip-mux-only' — only tmux's own attach-time smcup (the safe default).
|
||||
* 'preserve' — leave everything (a direct-PTY shell running vim/less/htop).
|
||||
* What the server strips from this CLI's output stream before the browser sees it.
|
||||
* The value encodes three independent choices (predicates in session.ts):
|
||||
*
|
||||
* | value | alt-screen toggles | `3J` (erase scrollback) | mouse DECSETs |
|
||||
* |-----------------------|---------------------|-------------------------|---------------------|
|
||||
* | `strip-full` | stripped | stripped | stripped |
|
||||
* | `strip-mux-and-mouse` | stripped under tmux | kept | stripped under tmux |
|
||||
* | `strip-mux-only` | stripped under tmux | kept | kept |
|
||||
* | `preserve` | stripped under tmux | kept | kept |
|
||||
*
|
||||
* `strip-full` is `isAltScreenStripMode`; `strip-mux-and-mouse` is `isMuxMouseStripMode`;
|
||||
* every other value takes `isMuxAltScreenOnlyStripMode`, so at runtime `preserve` and
|
||||
* `strip-mux-only` are the same row — `preserve` only says what such a CLI's pane
|
||||
* holds (terminal-owned scrollback: a shell, pi), not a different strip.
|
||||
*
|
||||
* - alt-screen: the tmux CLIENT emits `smcup` as its first bytes at attach, parking
|
||||
* xterm in the scrollback-less alternate buffer; a pane program's own toggles never
|
||||
* reach the client (tmux repaints instead). "Under tmux" means `useMux`: on a
|
||||
* direct-PTY fallback the `?1049h` is the program's own and must stay.
|
||||
* - `3J`: a user's `clear` is a deliberate scrollback wipe; only an Ink TUI's
|
||||
* redraw-driven `3J` (strip-full) is noise.
|
||||
* - mouse DECSETs: stripping them keeps a drag a local selection instead of a report
|
||||
* to the TUI. The browser then hand-encodes clicks (`_sendSyntheticSgrTap`), gated
|
||||
* on the `cliMouseTracking` the server records as it strips. Kept where a program's
|
||||
* own mouse support must work in the pane (htop/vim in a shell).
|
||||
*
|
||||
* Stock CLIs: `strip-full` = claude, codex, gemini (Ink TUIs); `strip-mux-and-mouse` =
|
||||
* opencode (a full-screen TUI that enables tracking itself); `strip-mux-only` =
|
||||
* antigravity, grok, deepseek, omp; `preserve` = shell, pi.
|
||||
*
|
||||
* A fourth combination is the point to split this into flags; three is still cheaper
|
||||
* as an enum.
|
||||
*/
|
||||
altScreen: 'strip-full' | 'strip-mux-only' | 'preserve';
|
||||
altScreen: 'strip-full' | 'strip-mux-only' | 'strip-mux-and-mouse' | 'preserve';
|
||||
echo: {
|
||||
policy: 'buffer' | 'predict' | 'off';
|
||||
/** How the local-echo overlay locates the composer row. */
|
||||
@@ -453,6 +515,20 @@ export interface CliCapabilities {
|
||||
};
|
||||
/** Forwarding the wheel to the CLI's own transcript. 'never' keeps local scrollback. */
|
||||
wheelForward: { mode: 'never' | 'version-gated'; minVersion?: string };
|
||||
/**
|
||||
* The CLI pages its OWN transcript on PageUp/PageDown, so a wheel or touch scroll over
|
||||
* a pane with no local history can be turned into those keys instead of doing nothing
|
||||
* (`_maybePageCliTranscript` in terminal-ui.js). Read by the frontend through
|
||||
* `window.__codemanTranscriptPageKeys`, which the server builds from this field.
|
||||
*
|
||||
* ⚠ NOT wheel forwarding. `wheelForward` above sends SGR mouse wheel REPORTS; this sends
|
||||
* plain keys, and only when the local buffer is hollow (normal buffer, `baseY === 0`).
|
||||
* A CLI can ignore one and honour the other: codex ignores SGR wheel reports (so its
|
||||
* `wheelForward` stays 'never') yet pages on PageUp/PageDown.
|
||||
*
|
||||
* Absent means no paging, so a CLI nobody has measured keeps plain local scrolling.
|
||||
*/
|
||||
transcriptPageKeys?: boolean;
|
||||
keyboardAccessory: 'agent' | 'shell';
|
||||
/** Multi-user: this CLI is a raw shell, so its commands need the privileged gate. */
|
||||
privilegedCommandGate: boolean;
|
||||
@@ -461,7 +537,20 @@ export interface CliCapabilities {
|
||||
ralph: boolean;
|
||||
respawn: boolean;
|
||||
effort: boolean;
|
||||
/**
|
||||
* Codeman may write its agent skill (`skills/codeman`) into this CLI's workspace and
|
||||
* seed its per-session preamble (behind the synced `agentSkillEnabled` setting,
|
||||
* add-only, marker-owned). Where it lands comes from `agentSkillDir` below.
|
||||
*/
|
||||
agentSkillInjection: boolean;
|
||||
/**
|
||||
* The workspace-relative directory this CLI scans for project skills, so the skill
|
||||
* lands at `<workspace>/<agentSkillDir>/codeman/SKILL.md` where the CLI discovers it.
|
||||
* Measured per CLI. Absent with `agentSkillInjection: true` means Claude Code's
|
||||
* `.claude/skills`, which is what the boolean meant before this field existed, so a
|
||||
* `~/.codeman/clis.json` written against the old schema keeps its behaviour.
|
||||
*/
|
||||
agentSkillDir?: AgentSkillDir;
|
||||
statusLineTelemetry: boolean;
|
||||
/** Where a model override is delivered. Claude uniquely writes settings.local.json. */
|
||||
model: { source: 'flag' | 'claude-settings-file' | 'none'; param?: string };
|
||||
@@ -500,6 +589,20 @@ export interface CliCapabilities {
|
||||
rejectWords?: string[];
|
||||
configResolver?: ModelConfigResolverName;
|
||||
};
|
||||
/**
|
||||
* Synced App Settings that seed this CLI's launch params when the caller left them unset,
|
||||
* keyed by LAUNCH PARAM name (`{ model: 'codexModel' }`), never the legacy wire name; the
|
||||
* resolver translates through `launch.legacyConfigAliases` like every other `param`.
|
||||
*
|
||||
* Filled into the entry's `launch.legacyConfigField` object at create time by
|
||||
* `applyLaunchDefaults()` (src/web/launch-defaults.ts), which re-validates each value
|
||||
* with `SettingsUpdateSchema` and never overwrites a value the caller sent. Which
|
||||
* launches get it is the CALLER's decision (local ones only: never remote, Docker or a
|
||||
* custom model endpoint). `schema.ts` refuses an undeclared param, and an entry without
|
||||
* a `legacyConfigField`, whose params would otherwise be read off the request body itself.
|
||||
* Absent = no launch defaults.
|
||||
*/
|
||||
launchDefaults?: Record<string, LaunchDefaultSettingKey>;
|
||||
/**
|
||||
* Params a non-granted multi-user owner may not set freely, and what they are forced to.
|
||||
* Data-driven so a CUSTOM CLI's bypass flag is clampable exactly like codex's.
|
||||
@@ -576,7 +679,12 @@ export interface CliCapabilities {
|
||||
* reported `skipped` rather than written somewhere the CLI never reads. Absent = the file
|
||||
* only follows `$HOME`.
|
||||
*/
|
||||
mcpConfig?: { path: string; format: McpConfigFormat; relocation?: { envVar: string; path: string } };
|
||||
mcpConfig?: {
|
||||
path: string;
|
||||
altPath?: string;
|
||||
format: McpConfigFormat;
|
||||
relocation?: { envVar: string; path: string };
|
||||
};
|
||||
/**
|
||||
* How this CLI is pointed at a user-supplied custom OpenAI-compatible
|
||||
* endpoint (local, e.g. llama.cpp, or cloud, e.g. Azure AI Foundry) — the
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* @fileoverview Folder listings for the file-preview folder grid.
|
||||
*
|
||||
* A folder the user opens (a clicked folder path, or "Folder" in the file
|
||||
* preview) is resolved, checked against the same attachment guard a single file
|
||||
* goes through, and GRANTED an id. The grid then asks for files by
|
||||
* `folderId + file name` only, so browser requests never carry arbitrary paths —
|
||||
* the rule the attachment routes follow for single files.
|
||||
*
|
||||
* Grants live in their own small registry, not in the attachment registry: that one
|
||||
* is capped at 200 records per session, and a folder of 300 renders would evict the
|
||||
* session's real attachments.
|
||||
*
|
||||
* Listings contain non-hidden subfolders and files whose type the preview supports
|
||||
* (`isSupportedAttachmentExtension`), newest first, capped at
|
||||
* {@link MAX_FOLDER_ENTRIES}. Local folders are read with `fs`; a remote (SSH) case's
|
||||
* folder is listed on its host in one ssh round trip (`remoteListFolder`).
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { extname, isAbsolute, join, posix } from 'node:path';
|
||||
import {
|
||||
getAttachmentType,
|
||||
isSupportedAttachmentExtension,
|
||||
supportedAttachmentExtensions,
|
||||
} from './attachment-registry.js';
|
||||
import { isBlockedAttachmentPath, isUnderTree, loadAttachmentGuardConfig } from './config/attachment-guard.js';
|
||||
import { isMultiUserMode, userSpacePath } from './config/multiuser.js';
|
||||
import { remoteListFolder, RemoteFileAccessError, type RemoteFolderEntry } from './remote-files.js';
|
||||
import type { AttachmentDetectedType, AuthUser } from './types.js';
|
||||
import type { SessionRemote } from './types/session.js';
|
||||
import { describeUnknownPath, probePathKind } from './utils/bounded-path-probe.js';
|
||||
import { validateSessionFilePath } from './web/route-helpers.js';
|
||||
|
||||
/** Most entries (files + subfolders) one listing returns. */
|
||||
export const MAX_FOLDER_ENTRIES = 1000;
|
||||
|
||||
/** Folder grants kept per session; the oldest is dropped beyond this. */
|
||||
const MAX_FOLDER_GRANTS_PER_SESSION = 32;
|
||||
|
||||
export interface FolderFileEntry {
|
||||
name: string;
|
||||
extension: string;
|
||||
attachmentType: AttachmentDetectedType;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
}
|
||||
|
||||
export interface FolderListing {
|
||||
folderId: string;
|
||||
/** The folder with symlinks resolved (on the session's host). */
|
||||
path: string;
|
||||
files: FolderFileEntry[];
|
||||
/** Non-hidden subfolder names, sorted. */
|
||||
folders: string[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export class FolderListingError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly statusCode: number = 400
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
interface FolderGrant {
|
||||
folderId: string;
|
||||
dir: string;
|
||||
}
|
||||
|
||||
class FolderGrants {
|
||||
private bySession = new Map<string, Map<string, FolderGrant>>();
|
||||
|
||||
grant(sessionId: string, dir: string): string {
|
||||
let grants = this.bySession.get(sessionId);
|
||||
if (!grants) {
|
||||
grants = new Map();
|
||||
this.bySession.set(sessionId, grants);
|
||||
}
|
||||
for (const existing of grants.values()) {
|
||||
if (existing.dir === dir) {
|
||||
// Refresh its position so an often-used folder is the last to be dropped.
|
||||
grants.delete(existing.folderId);
|
||||
grants.set(existing.folderId, existing);
|
||||
return existing.folderId;
|
||||
}
|
||||
}
|
||||
const folderId = `fld_${randomUUID()}`;
|
||||
grants.set(folderId, { folderId, dir });
|
||||
while (grants.size > MAX_FOLDER_GRANTS_PER_SESSION) {
|
||||
const oldest = grants.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
grants.delete(oldest);
|
||||
}
|
||||
return folderId;
|
||||
}
|
||||
|
||||
get(sessionId: string, folderId: string): FolderGrant | undefined {
|
||||
return this.bySession.get(sessionId)?.get(folderId);
|
||||
}
|
||||
|
||||
clearSession(sessionId: string): void {
|
||||
this.bySession.delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
export const folderGrants = new FolderGrants();
|
||||
|
||||
/**
|
||||
* A file name inside a granted folder, or null when it is not one: no path
|
||||
* separator, not hidden (which also rules out `.`/`..`; the listing leaves hidden
|
||||
* entries out, so the routes do too), no NUL, and a type the preview supports.
|
||||
*/
|
||||
export function validFolderFileName(name: unknown): string | null {
|
||||
if (typeof name !== 'string' || !name || name.length > 255) return null;
|
||||
if (name.startsWith('.') || name.includes('/') || name.includes('\\') || name.includes('\0')) return null;
|
||||
const extension = extname(name).toLowerCase().replace(/^\./, '');
|
||||
return isSupportedAttachmentExtension(extension) ? name : null;
|
||||
}
|
||||
|
||||
/** Where a granted folder's file lives (on the session's host). */
|
||||
export function folderFilePath(dir: string, name: string): string {
|
||||
return posix.join(dir, name);
|
||||
}
|
||||
|
||||
interface ListFolderOptions {
|
||||
sessionWorkingDir?: string;
|
||||
remote?: SessionRemote;
|
||||
/** The requesting identity; in multi-user mode a regular user is held to {@link folderAllowedForUser}. */
|
||||
user?: AuthUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-user rule for folder grants, the same one the filesystem path picker follows:
|
||||
* a regular user reaches only their own space (`userSpacePath`) or the session's
|
||||
* `workingDir`. User spaces live inside `homedir()`, so without it a user could list
|
||||
* and read another user's space. Always true in single-user mode and for admins; a
|
||||
* remote session's folders are on its host, where only the `workingDir` applies.
|
||||
*
|
||||
* @param path Already resolved (realpath on the session's host).
|
||||
*/
|
||||
export function folderAllowedForUser(
|
||||
path: string,
|
||||
user: AuthUser | undefined,
|
||||
scope: { workingDir?: string; remote?: SessionRemote }
|
||||
): boolean {
|
||||
if (!isMultiUserMode()) return true;
|
||||
if (!user) return false;
|
||||
if (user.role === 'admin') return true;
|
||||
if (scope.remote) return !!scope.workingDir && isUnderTree(path, scope.workingDir);
|
||||
return [userSpacePath(user.username), scope.workingDir].some(
|
||||
(root) => !!root && !!validateSessionFilePath(root, path)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve, guard, list and grant a folder for `sessionId`.
|
||||
*
|
||||
* A local folder is probed bounded first (`probePathKind`): one on a network mount
|
||||
* that stopped answering must not freeze the server, and "did not answer" is never
|
||||
* reported as "not found". The guard runs on the resolved folder before it is read.
|
||||
*
|
||||
* @param requestedPath Absolute, or `~/…` (the home of the session's host).
|
||||
* @throws FolderListingError 400 not absolute / not a folder, 403 blocked or outside the
|
||||
* user's space, 404 missing, 502 remote unreachable, 503 local folder not answering.
|
||||
*/
|
||||
export async function listFolder(
|
||||
sessionId: string,
|
||||
requestedPath: string,
|
||||
options: ListFolderOptions = {}
|
||||
): Promise<FolderListing> {
|
||||
const homeRelative = typeof requestedPath === 'string' && (requestedPath === '~' || requestedPath.startsWith('~/'));
|
||||
if (!requestedPath || typeof requestedPath !== 'string' || (!isAbsolute(requestedPath) && !homeRelative)) {
|
||||
throw new FolderListingError('Folder path must be absolute');
|
||||
}
|
||||
|
||||
const guard = await loadAttachmentGuardConfig();
|
||||
const workingDir = options.sessionWorkingDir;
|
||||
const assertAllowed = (dir: string): void => {
|
||||
const confined = !guard.confineToWorkspace
|
||||
? true
|
||||
: options.remote
|
||||
? !!workingDir && isUnderTree(dir, workingDir)
|
||||
: !!workingDir && !!validateSessionFilePath(workingDir, dir);
|
||||
if (!confined || isBlockedAttachmentPath(dir, guard.blockedTrees)) {
|
||||
throw new FolderListingError('Access to this folder is blocked', 403);
|
||||
}
|
||||
if (!folderAllowedForUser(dir, options.user, { workingDir, remote: options.remote })) {
|
||||
throw new FolderListingError('Folder is outside your space', 403);
|
||||
}
|
||||
};
|
||||
|
||||
let dir: string;
|
||||
let entries: RemoteFolderEntry[];
|
||||
let truncated = false;
|
||||
if (options.remote) {
|
||||
const remotePath = requestedPath === '~' ? '~/' : requestedPath;
|
||||
let listing;
|
||||
try {
|
||||
listing = await remoteListFolder(options.remote, remotePath, supportedAttachmentExtensions(), MAX_FOLDER_ENTRIES);
|
||||
} catch (err) {
|
||||
throw new FolderListingError(err instanceof RemoteFileAccessError ? err.message : 'remote host unreachable', 502);
|
||||
}
|
||||
if (!listing) throw new FolderListingError('Folder not found', 404);
|
||||
if (listing === 'not-a-folder') throw new FolderListingError('Not a folder');
|
||||
({ dir, entries, truncated } = listing);
|
||||
// One ssh call lists and resolves together, so the guard can only run after it;
|
||||
// nothing of a refused listing leaves this function.
|
||||
assertAllowed(dir);
|
||||
} else {
|
||||
const expanded = homeRelative ? join(homedir(), requestedPath.slice(2)) : requestedPath;
|
||||
const kind = await probePathKind(expanded, { pastCap: true });
|
||||
if (kind === 'unknown') {
|
||||
throw new FolderListingError(describeUnknownPath('Folder', expanded, { pastCap: true }), 503);
|
||||
}
|
||||
if (kind === 'absent') throw new FolderListingError('Folder not found', 404);
|
||||
if (kind !== 'directory') throw new FolderListingError('Not a folder');
|
||||
try {
|
||||
dir = await fs.realpath(expanded);
|
||||
} catch {
|
||||
throw new FolderListingError('Folder not found', 404);
|
||||
}
|
||||
assertAllowed(dir);
|
||||
({ entries, truncated } = await listLocalFolder(dir));
|
||||
}
|
||||
|
||||
const files: FolderFileEntry[] = [];
|
||||
const folders: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith('.')) continue;
|
||||
// A secret that happens to sit in an open folder stays out of the grid too.
|
||||
if (isBlockedAttachmentPath(folderFilePath(dir, entry.name), guard.blockedTrees)) continue;
|
||||
if (entry.kind === 'directory') {
|
||||
folders.push(entry.name);
|
||||
continue;
|
||||
}
|
||||
const extension = extname(entry.name).toLowerCase().replace(/^\./, '');
|
||||
if (!isSupportedAttachmentExtension(extension)) continue;
|
||||
files.push({
|
||||
name: entry.name,
|
||||
extension,
|
||||
attachmentType: getAttachmentType(extension),
|
||||
size: entry.size,
|
||||
mtimeMs: entry.mtimeMs,
|
||||
});
|
||||
}
|
||||
files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name));
|
||||
folders.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
return { folderId: folderGrants.grant(sessionId, dir), path: dir, files, folders, truncated };
|
||||
}
|
||||
|
||||
/** Local counterpart of the remote listing script: subfolders + supported files, stat'ed through symlinks. */
|
||||
async function listLocalFolder(dir: string): Promise<{ entries: RemoteFolderEntry[]; truncated: boolean }> {
|
||||
const dirents = await fs.readdir(dir, { withFileTypes: true });
|
||||
const entries: RemoteFolderEntry[] = [];
|
||||
let truncated = false;
|
||||
for (const dirent of dirents) {
|
||||
if (dirent.name.startsWith('.')) continue;
|
||||
if (entries.length >= MAX_FOLDER_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
const extension = extname(dirent.name).toLowerCase().replace(/^\./, '');
|
||||
const maybeFile = isSupportedAttachmentExtension(extension);
|
||||
if (!dirent.isDirectory() && !maybeFile && !dirent.isSymbolicLink()) continue;
|
||||
let stat;
|
||||
try {
|
||||
stat = await fs.stat(join(dir, dirent.name));
|
||||
} catch {
|
||||
continue; // dangling symlink, or gone since readdir
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
entries.push({ kind: 'directory', name: dirent.name, size: 0, mtimeMs: 0 });
|
||||
} else if (stat.isFile() && maybeFile) {
|
||||
entries.push({ kind: 'file', name: dirent.name, size: stat.size, mtimeMs: stat.mtimeMs });
|
||||
}
|
||||
}
|
||||
return { entries, truncated };
|
||||
}
|
||||
@@ -495,6 +495,10 @@ export function gitNonInteractiveEnv(base: NodeJS.ProcessEnv = process.env): Nod
|
||||
SSH_ASKPASS_REQUIRE: 'never',
|
||||
DISPLAY: '',
|
||||
GCM_INTERACTIVE: 'never',
|
||||
// classifyGitFailure() matches git's ENGLISH stderr; a German or French locale would
|
||||
// turn a missing ref into a generic FAILED (422 instead of 400).
|
||||
LC_ALL: 'C',
|
||||
LANG: 'C',
|
||||
GIT_SSH_COMMAND:
|
||||
base.GIT_SSH_COMMAND || 'ssh -oBatchMode=yes -oStrictHostKeyChecking=accept-new -oConnectTimeout=10',
|
||||
};
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
* subfolder reports its whole enclosing repo; a nested repo below it is just an untracked folder
|
||||
* to the outer one, and is not scanned;
|
||||
* - NOT inside one (a folder that holds several projects): every repository found up to two levels
|
||||
* DOWN (`MAX_REPOS` of them, skipping dot-folders, `node_modules` and the like, never following
|
||||
* symlinks), each reported separately;
|
||||
* DOWN (the caller's `maxRepos` of them, `MAX_REPOS` by default, skipping dot-folders, `node_modules`
|
||||
* and the like, never following symlinks), each reported separately;
|
||||
* - a repository that merely sits ABOVE the workspace and is the home folder or higher (a dotfiles
|
||||
* repo in `$HOME`, or `/`) is ignored: its dirty files are not this session's work.
|
||||
*
|
||||
@@ -52,7 +52,10 @@ import { gitNonInteractiveEnv, redactGitCredentials } from './git-clone.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const GIT_TIMEOUT_MS = 10_000;
|
||||
/** How long one git command may run, unless the caller passes `timeoutMs` (a slow network share needs more). */
|
||||
export const DEFAULT_GIT_TIMEOUT_MS = 30_000;
|
||||
export const MIN_GIT_TIMEOUT_MS = 5_000;
|
||||
export const MAX_GIT_TIMEOUT_MS = 120_000;
|
||||
/** `git status` on a huge tree can print a lot; a bound on what we will hold. */
|
||||
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
/** Max file rows returned. The counts stay exact. */
|
||||
@@ -258,9 +261,9 @@ export function parseCommitLog(text: string): GitCommitEntry[] {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Runs `git <args>` in `cwd` and returns stdout. Injected so the cache and error paths test without git. */
|
||||
export type GitRunner = (cwd: string, args: string[]) => Promise<string>;
|
||||
export type GitRunner = (cwd: string, args: string[], opts?: { timeoutMs?: number }) => Promise<string>;
|
||||
|
||||
export const runGit: GitRunner = async (cwd, args) => {
|
||||
export const runGit: GitRunner = async (cwd, args, opts) => {
|
||||
const { stdout } = await execFileAsync(
|
||||
'git',
|
||||
// --no-optional-locks: never touch the index just to look. core.fsmonitor=false: do not start or
|
||||
@@ -269,7 +272,7 @@ export const runGit: GitRunner = async (cwd, args) => {
|
||||
['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'log.showSignature=false', ...args],
|
||||
{
|
||||
cwd,
|
||||
timeout: GIT_TIMEOUT_MS,
|
||||
timeout: opts?.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS,
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
env: { ...gitNonInteractiveEnv(), LC_ALL: 'C', LANG: 'C', GIT_OPTIONAL_LOCKS: '0' },
|
||||
}
|
||||
@@ -288,17 +291,14 @@ function describeFailure(err: unknown): { notARepo: boolean; message: string } {
|
||||
return { notARepo: false, message: redactGitCredentials(text).slice(0, 300) };
|
||||
}
|
||||
|
||||
async function collect(cwd: string, git: GitRunner): Promise<GitWorkspaceStatus> {
|
||||
async function collect(cwd: string, git: GitRunner, timeoutMs?: number): Promise<GitWorkspaceStatus> {
|
||||
let statusText: string;
|
||||
try {
|
||||
statusText = await git(cwd, [
|
||||
'status',
|
||||
'--porcelain=v2',
|
||||
'--branch',
|
||||
'-z',
|
||||
'--untracked-files=normal',
|
||||
'--ignore-submodules=dirty',
|
||||
]);
|
||||
statusText = await git(
|
||||
cwd,
|
||||
['status', '--porcelain=v2', '--branch', '-z', '--untracked-files=normal', '--ignore-submodules=dirty'],
|
||||
{ timeoutMs }
|
||||
);
|
||||
} catch (err) {
|
||||
const f = describeFailure(err);
|
||||
return f.notARepo ? emptyStatus('not-a-repo') : emptyStatus('error', { error: f.message });
|
||||
@@ -307,7 +307,7 @@ async function collect(cwd: string, git: GitRunner): Promise<GitWorkspaceStatus>
|
||||
|
||||
const safe = async (args: string[]): Promise<string> => {
|
||||
try {
|
||||
return await git(cwd, args);
|
||||
return await git(cwd, args, { timeoutMs });
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
@@ -415,10 +415,12 @@ async function singleFlight<T>(
|
||||
*/
|
||||
export async function getGitWorkspaceStatus(
|
||||
cwd: string,
|
||||
opts: { git?: GitRunner; now?: () => number; fresh?: boolean } = {}
|
||||
opts: { git?: GitRunner; now?: () => number; fresh?: boolean; timeoutMs?: number } = {}
|
||||
): Promise<GitWorkspaceStatus> {
|
||||
const git = opts.git ?? runGit;
|
||||
return singleFlight(cache, cwd, { now: opts.now ?? Date.now, fresh: opts.fresh }, () => collect(cwd, git));
|
||||
return singleFlight(cache, cwd, { now: opts.now ?? Date.now, fresh: opts.fresh }, () =>
|
||||
collect(cwd, git, opts.timeoutMs)
|
||||
);
|
||||
}
|
||||
|
||||
type RepoToplevel = { state: 'ok'; root: string } | { state: 'not-a-repo' } | { state: 'error'; error: string };
|
||||
@@ -427,12 +429,12 @@ const toplevelCache = new Map<string, CacheEntry<RepoToplevel>>();
|
||||
/** The root of the repository enclosing `cwd` (git walks up), from one cheap `rev-parse`. Cached like the status. */
|
||||
function enclosingRepoRoot(
|
||||
cwd: string,
|
||||
opts: { git?: GitRunner; now?: () => number; fresh?: boolean }
|
||||
opts: { git?: GitRunner; now?: () => number; fresh?: boolean; timeoutMs?: number }
|
||||
): Promise<RepoToplevel> {
|
||||
const git = opts.git ?? runGit;
|
||||
return singleFlight(toplevelCache, cwd, { now: opts.now ?? Date.now, fresh: opts.fresh }, async () => {
|
||||
try {
|
||||
const root = (await git(cwd, ['rev-parse', '--show-toplevel'])).trim();
|
||||
const root = (await git(cwd, ['rev-parse', '--show-toplevel'], { timeoutMs: opts.timeoutMs })).trim();
|
||||
return root ? { state: 'ok', root } : { state: 'not-a-repo' };
|
||||
} catch (err) {
|
||||
const f = describeFailure(err);
|
||||
@@ -451,6 +453,16 @@ const DISCOVERY_MAX_DEPTH = 2;
|
||||
const DISCOVERY_MAX_ENTRIES = 300;
|
||||
/** Repositories reported for one workspace. */
|
||||
export const MAX_REPOS = 12;
|
||||
/** The most repositories a caller may ask for: each one costs several git processes per poll. */
|
||||
export const MAX_REPOS_LIMIT = 50;
|
||||
|
||||
/** `value` as a whole number within [min, max], else `fallback`. For options that arrive as untrusted query strings. */
|
||||
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
// An empty string is "not given", not 0 (Number('') is 0, which would clamp to the minimum).
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, Math.trunc(n)));
|
||||
}
|
||||
/** The list of repositories under a folder changes rarely, so it is re-scanned far less often than status. */
|
||||
const DISCOVERY_TTL_MS = 30_000;
|
||||
/** Folders that are never worth descending into when looking for projects. */
|
||||
@@ -472,8 +484,10 @@ export interface GitWorkspaceOverview {
|
||||
reason?: 'remote' | 'docker';
|
||||
error?: string;
|
||||
repos: GitRepoEntry[];
|
||||
/** More than `MAX_REPOS` repositories were found; only the first are reported. */
|
||||
/** More than `repoLimit` repositories were found; only the first are reported. */
|
||||
reposTruncated: boolean;
|
||||
/** The most repositories this overview would list (the caller's setting, or `MAX_REPOS`). */
|
||||
repoLimit?: number;
|
||||
checkedAt: number;
|
||||
}
|
||||
|
||||
@@ -553,7 +567,8 @@ async function readDirBounded(dir: string): Promise<import('node:fs').Dirent[] |
|
||||
/** Repositories up to `DISCOVERY_MAX_DEPTH` levels below `cwd`, nearest and alphabetical first. Never follows symlinks. */
|
||||
export async function discoverChildRepos(
|
||||
cwd: string,
|
||||
excludeRealRoots: string[] = []
|
||||
excludeRealRoots: string[] = [],
|
||||
maxRepos: number = MAX_REPOS
|
||||
): Promise<{ dirs: string[]; truncated: boolean }> {
|
||||
const found: string[] = [];
|
||||
let level = [cwd];
|
||||
@@ -576,7 +591,7 @@ export async function discoverChildRepos(
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
return { dirs: found.slice(0, MAX_REPOS), truncated: found.length > MAX_REPOS };
|
||||
return { dirs: found.slice(0, maxRepos), truncated: found.length > maxRepos };
|
||||
}
|
||||
|
||||
const discoveryCache = new Map<string, { at: number; value: { dirs: string[]; truncated: boolean } }>();
|
||||
@@ -602,13 +617,28 @@ export interface GitOverviewOptions {
|
||||
home?: string;
|
||||
/** Docker case workspaces (host paths): repositories at or inside these are never inspected. */
|
||||
dockerWorkspaces?: string[];
|
||||
/** How many repositories to report below a folder that is not itself a repository (1 to `MAX_REPOS_LIMIT`, default `MAX_REPOS`). */
|
||||
maxRepos?: number;
|
||||
/** How long one git command may run, in ms (`MIN_GIT_TIMEOUT_MS` to `MAX_GIT_TIMEOUT_MS`, default `DEFAULT_GIT_TIMEOUT_MS`). */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
/** The repository limit and git timeout an overview was computed with, from untrusted options. */
|
||||
export function resolveOverviewLimits(opts: { maxRepos?: unknown; timeoutMs?: unknown }): {
|
||||
maxRepos: number;
|
||||
timeoutMs: number;
|
||||
} {
|
||||
return {
|
||||
maxRepos: clampInt(opts.maxRepos, 1, MAX_REPOS_LIMIT, MAX_REPOS),
|
||||
timeoutMs: clampInt(opts.timeoutMs, MIN_GIT_TIMEOUT_MS, MAX_GIT_TIMEOUT_MS, DEFAULT_GIT_TIMEOUT_MS),
|
||||
};
|
||||
}
|
||||
|
||||
type WorkspaceRepos =
|
||||
| { kind: 'docker' }
|
||||
| { kind: 'error'; error: string }
|
||||
| { kind: 'enclosing'; root: string }
|
||||
| { kind: 'children'; dirs: string[]; truncated: boolean };
|
||||
| { kind: 'children'; dirs: string[]; truncated: boolean; limit: number };
|
||||
|
||||
/**
|
||||
* WHICH repositories belong to the workspace (the module header has the rules), without a full
|
||||
@@ -617,6 +647,7 @@ type WorkspaceRepos =
|
||||
*/
|
||||
async function resolveWorkspaceRepos(cwd: string, opts: GitOverviewOptions): Promise<WorkspaceRepos> {
|
||||
const now = opts.now ?? Date.now;
|
||||
const { maxRepos, timeoutMs } = resolveOverviewLimits(opts);
|
||||
const dockerRoots = await realAll(opts.dockerWorkspaces ?? []);
|
||||
// Checked BEFORE any git runs: git walks up from cwd, and a repository the container can write to
|
||||
// could carry config (a clean filter) that runs on the host.
|
||||
@@ -624,7 +655,7 @@ async function resolveWorkspaceRepos(cwd: string, opts: GitOverviewOptions): Pro
|
||||
// The enclosing repository is identified before its full status runs, so an unrelated one above the
|
||||
// workspace (a dotfiles repo in $HOME) costs one rev-parse, and its status failing cannot hide the
|
||||
// repositories below.
|
||||
const top = await enclosingRepoRoot(cwd, opts);
|
||||
const top = await enclosingRepoRoot(cwd, { ...opts, timeoutMs });
|
||||
if (top.state === 'error') return { kind: 'error', error: top.error };
|
||||
if (top.state === 'ok') {
|
||||
if (await isInsideAny(top.root, dockerRoots)) return { kind: 'docker' };
|
||||
@@ -633,18 +664,20 @@ async function resolveWorkspaceRepos(cwd: string, opts: GitOverviewOptions): Pro
|
||||
}
|
||||
|
||||
// Not inside a repository of this workspace: look below for projects.
|
||||
const hit = discoveryCache.get(cwd);
|
||||
// Keyed by the limit too: a list cut at 12 must not answer a request for 30.
|
||||
const discoveryKey = `${cwd}\0${maxRepos}`;
|
||||
const hit = discoveryCache.get(discoveryKey);
|
||||
let found: { dirs: string[]; truncated: boolean };
|
||||
if (!opts.fresh && hit && now() - hit.at < DISCOVERY_TTL_MS) found = hit.value;
|
||||
else {
|
||||
found = await discoverChildRepos(cwd, dockerRoots);
|
||||
discoveryCache.set(cwd, { at: now(), value: found });
|
||||
found = await discoverChildRepos(cwd, dockerRoots, maxRepos);
|
||||
discoveryCache.set(discoveryKey, { at: now(), value: found });
|
||||
if (discoveryCache.size > CACHE_MAX_ENTRIES) discoveryCache.delete(discoveryCache.keys().next().value as string);
|
||||
}
|
||||
// The cached list can predate a Docker case linked since: filter it against the roots as they are NOW.
|
||||
const dirs: string[] = [];
|
||||
for (const dir of found.dirs) if (!(await isInsideAny(dir, dockerRoots))) dirs.push(dir);
|
||||
return { kind: 'children', dirs, truncated: found.truncated };
|
||||
return { kind: 'children', dirs, truncated: found.truncated, limit: maxRepos };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -659,7 +692,7 @@ export async function getGitWorkspaceOverview(
|
||||
if (where.kind === 'docker') return emptyOverview('unsupported', { reason: 'docker' });
|
||||
if (where.kind === 'error') return emptyOverview('error', { error: where.error });
|
||||
if (where.kind === 'enclosing') {
|
||||
const primary = await getGitWorkspaceStatus(cwd, opts);
|
||||
const primary = await getGitWorkspaceStatus(cwd, { ...opts, timeoutMs: resolveOverviewLimits(opts).timeoutMs });
|
||||
if (primary.state === 'error') return emptyOverview('error', { error: primary.error });
|
||||
if (primary.state !== 'ok') return emptyOverview('not-a-repo');
|
||||
const root = primary.repoRoot ?? where.root;
|
||||
@@ -671,14 +704,21 @@ export async function getGitWorkspaceOverview(
|
||||
};
|
||||
}
|
||||
|
||||
const statuses = await mapLimited(where.dirs, STATUS_CONCURRENCY, (dir) => getGitWorkspaceStatus(dir, opts));
|
||||
const timeoutMs = resolveOverviewLimits(opts).timeoutMs;
|
||||
const statuses = await mapLimited(where.dirs, STATUS_CONCURRENCY, (dir) =>
|
||||
getGitWorkspaceStatus(dir, { ...opts, timeoutMs })
|
||||
);
|
||||
const repos: GitRepoEntry[] = [];
|
||||
where.dirs.forEach((dir, i) => {
|
||||
const status = statuses[i];
|
||||
if (status.state === 'ok') repos.push({ name: basename(dir), path: relative(cwd, dir), status });
|
||||
// A repository git could not read (a timeout on a slow share, a broken worktree) stays in the
|
||||
// list with its error, so it is visible that something is not being reported; only a folder
|
||||
// that turned out not to be a repository after all is left out.
|
||||
if (status.state === 'ok' || status.state === 'error')
|
||||
repos.push({ name: basename(dir), path: relative(cwd, dir), status });
|
||||
});
|
||||
if (!repos.length) return emptyOverview('not-a-repo');
|
||||
return { state: 'ok', repos, reposTruncated: where.truncated, checkedAt: Date.now() };
|
||||
return { state: 'ok', repos, reposTruncated: where.truncated, repoLimit: where.limit, checkedAt: Date.now() };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -726,7 +766,7 @@ export function isSafeRepoRelativePath(p: string): boolean {
|
||||
export async function getGitFileDiff(
|
||||
repoRoot: string,
|
||||
file: { path: string; origPath?: string; kind: GitFileKind },
|
||||
opts: { git?: GitRunner } = {}
|
||||
opts: { git?: GitRunner; timeoutMs?: number } = {}
|
||||
): Promise<GitFileDiff> {
|
||||
if (!isSafeRepoRelativePath(file.path) || (file.origPath && !isSafeRepoRelativePath(file.origPath))) {
|
||||
throw new Error('Invalid path');
|
||||
@@ -742,7 +782,7 @@ export async function getGitFileDiff(
|
||||
let out: string;
|
||||
let cutShort = false;
|
||||
try {
|
||||
out = await git(repoRoot, args);
|
||||
out = await git(repoRoot, args, { timeoutMs: opts.timeoutMs });
|
||||
} catch (err) {
|
||||
const e = err as { code?: unknown; stdout?: unknown };
|
||||
// `--no-index` exits 1 when the files differ, which is the normal case for it.
|
||||
|
||||
@@ -36,6 +36,7 @@ import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import type { HookEventType } from './types.js';
|
||||
import type { AgentSkillDir, CliCapabilities } from './config/cli-registry/types.js';
|
||||
import { HOOK_TIMEOUT_SECONDS } from './config/auth-config.js';
|
||||
import { dataPath } from './config/instance.js';
|
||||
import { readJsonConfig, SETTINGS_PATH } from './web/route-helpers.js';
|
||||
@@ -1228,8 +1229,8 @@ interface AgentSkillFile {
|
||||
*/
|
||||
async function readAgentSkillSource(): Promise<AgentSkillFile[]> {
|
||||
const src = agentSkillSourceDir();
|
||||
const skill = await readFile(join(src, 'SKILL.md'), 'utf-8');
|
||||
const files: AgentSkillFile[] = [{ relPath: 'SKILL.md', content: `${skill.trimEnd()}\n\n${AGENT_SKILL_MARKER}\n` }];
|
||||
const skillMd = await readFile(join(src, 'SKILL.md'), 'utf-8');
|
||||
const files: AgentSkillFile[] = [{ relPath: 'SKILL.md', content: `${skillMd.trimEnd()}\n\n${AGENT_SKILL_MARKER}\n` }];
|
||||
let referenceNames: string[] = [];
|
||||
try {
|
||||
referenceNames = (await readdir(join(src, 'reference'))).filter((name) => name.endsWith('.md')).sort();
|
||||
@@ -1285,7 +1286,8 @@ export type AgentSkillApplyResult =
|
||||
|
||||
/**
|
||||
* Install or refresh the Codeman agent skill into `skillDir` (a `.../codeman`
|
||||
* directory, e.g. `<case>/.claude/skills/codeman` or `~/.claude/skills/codeman`).
|
||||
* directory, e.g. `<case>/.claude/skills/codeman`, `~/.claude/skills/codeman` or
|
||||
* `<case>/.agents/skills/codeman`).
|
||||
*
|
||||
* Refuses two shapes rather than writing through them:
|
||||
* - a SYMLINK at the skill dir or its `skills/` parent: this repo's own dogfooding
|
||||
@@ -1336,16 +1338,20 @@ export async function installAgentSkillInto(skillDir: string): Promise<AgentSkil
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed a claude session's agent preamble file (`$XDG_CACHE_HOME/codeman-agent-<id>.sh`,
|
||||
* Seed a session's agent preamble file (`$XDG_CACHE_HOME/codeman-agent-<id>.sh`,
|
||||
* default `~/.cache/`) from the packaged `skills/codeman/preamble.sh`, so the agent
|
||||
* skill's §0 bootstrap collapses to a two-line loader instead of a ~150-line block the
|
||||
* model has to type out (measured live: that paste alone cost a spawn run ~47 s of
|
||||
* generation time). The path formula must match the skill's
|
||||
* `${XDG_CACHE_HOME:-$HOME/.cache}` exactly; sessions inherit the server's env, so
|
||||
* reading the server's own XDG_CACHE_HOME keeps the two in agreement (`||` mirrors the
|
||||
* shell's `:-`, treating empty as unset). Callers gate to LOCAL claude sessions (a
|
||||
* remote or in-container HOME is not this filesystem) and treat it as best-effort: the
|
||||
* skill's §0 fallback block self-heals a missing or stale file.
|
||||
* shell's `:-`, treating empty as unset). Callers gate to LOCAL sessions whose CLI gets
|
||||
* the skill (`agentSkillDir()` non-null, any CLI: the preamble is bash + curl + jq, nothing
|
||||
* claude-specific; a remote or in-container HOME is not this filesystem) and treat it as
|
||||
* best-effort: the skill's §0 fallback block self-heals a missing or stale file. Codex
|
||||
* caveat: codex 0.162 runs tool commands in a shared app-server daemon whose
|
||||
* `CODEMAN_SESSION_ID` is the starting session's, so its loader looks for that session's
|
||||
* file and its self id is wrong; the skill tells the agent how to notice.
|
||||
*/
|
||||
export async function seedAgentSessionPreamble(sessionId: string): Promise<void> {
|
||||
const content = await readFile(join(agentSkillSourceDir(), 'preamble.sh'), 'utf-8');
|
||||
@@ -1478,31 +1484,59 @@ export async function removeAgentSkillFrom(skillDir: string): Promise<AgentSkill
|
||||
}
|
||||
await rmdir(join(skillDir, 'reference')).catch(() => {}); // fails when non-empty, fine
|
||||
await rmdir(skillDir).catch(() => {});
|
||||
await rmdir(dirname(skillDir)).catch(() => {}); // prune `.claude/skills` if now empty
|
||||
await rmdir(dirname(skillDir)).catch(() => {}); // prune `.claude/skills` (or the CLI's own dir) if now empty
|
||||
return 'removed';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or remove the Codeman agent skill in `<case>/.claude/skills/codeman`,
|
||||
* mirroring `applyStatusLineConfig`'s shape. Gated by the synced `agentSkillEnabled`
|
||||
* app setting (default OFF); callers gate on Claude mode, since the skill is discovered
|
||||
* via `.claude/skills/`, which only Claude Code reads.
|
||||
* Claude Code's project skills directory, and the meaning `agentSkillInjection: true`
|
||||
* had before `capabilities.agentSkillDir` existed.
|
||||
*/
|
||||
export const CLAUDE_AGENT_SKILL_DIR: AgentSkillDir = '.claude/skills';
|
||||
|
||||
/**
|
||||
* The workspace-relative skills directory this CLI scans, i.e. where its sessions get
|
||||
* the skill, or `null` when they get none. Pure registry data, so no call site
|
||||
* branches on a CLI id.
|
||||
*/
|
||||
export function agentSkillDir(
|
||||
capabilities: Pick<CliCapabilities, 'agentSkillInjection' | 'agentSkillDir'> | undefined
|
||||
): AgentSkillDir | null {
|
||||
if (!capabilities?.agentSkillInjection) return null;
|
||||
return capabilities.agentSkillDir ?? CLAUDE_AGENT_SKILL_DIR;
|
||||
}
|
||||
|
||||
/** `<casePath>/<dir>/codeman`, the directory the skill's SKILL.md lives in. */
|
||||
export function agentSkillDirFor(casePath: string, dir: AgentSkillDir): string {
|
||||
return join(casePath, dir, 'codeman');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or remove the Codeman agent skill in `<case>/<dir>/codeman`, where `dir` is the
|
||||
* skills directory the session's CLI scans (default: Claude Code's `.claude/skills`;
|
||||
* callers resolve it with `agentSkillDir()`), mirroring `applyStatusLineConfig`'s
|
||||
* shape. Gated by the synced `agentSkillEnabled` app setting (default OFF).
|
||||
*
|
||||
* Call-site policy is ADD-ONLY on session create (callers pass `enabled: true` or
|
||||
* skip the call), for the statusLine reason: sessions in a repo share one `.claude/`
|
||||
* dir, so a single create while the setting is off must not yank the skill out from
|
||||
* skip the call), for the statusLine reason: sessions in a repo share one workspace,
|
||||
* so a single create while the setting is off must not yank the skill out from
|
||||
* under other live sessions.
|
||||
*
|
||||
* ⚠️ Consequence: turning `agentSkillEnabled` OFF sweeps nothing. There is deliberately
|
||||
* no server-side toggle-off sweep (it would have to walk every case, including ones
|
||||
* with live sessions, and would hit exactly the shared-`.claude/` hazard above), so
|
||||
* with live sessions, and would hit exactly the shared-workspace hazard above), so
|
||||
* already-injected copies stay on disk until removed per case with
|
||||
* `codeman skill uninstall --case <name>`. The `enabled: false` branch here backs that
|
||||
* CLI and the tests; it has no server call site. Keep the README's Agent Skill note in
|
||||
* sync if this ever changes.
|
||||
* `codeman skill uninstall --case <name>`, which removes the Codeman-managed copy from
|
||||
* every skills directory the registry could have written. The `enabled: false` branch
|
||||
* here backs that CLI and the tests; it has no server call site. Keep the README's
|
||||
* Agent Skill note in sync if this ever changes.
|
||||
*/
|
||||
export async function applyAgentSkill(casePath: string, enabled: boolean): Promise<AgentSkillApplyResult> {
|
||||
const skillDir = join(casePath, '.claude', 'skills', 'codeman');
|
||||
export async function applyAgentSkill(
|
||||
casePath: string,
|
||||
enabled: boolean,
|
||||
dir: AgentSkillDir = CLAUDE_AGENT_SKILL_DIR
|
||||
): Promise<AgentSkillApplyResult> {
|
||||
const skillDir = agentSkillDirFor(casePath, dir);
|
||||
return enabled ? installAgentSkillInto(skillDir) : removeAgentSkillFrom(skillDir);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* @fileoverview Capability tokens for rendering a local HTML file.
|
||||
*
|
||||
* `file-raw` never serves HTML as HTML: a page rendered from Codeman's own origin
|
||||
* could read the Codeman document and drive the agent-spawning API. So an HTML
|
||||
* file is rendered from `/html-view/:cap/*` instead, with a `Content-Security-
|
||||
* Policy: sandbox` header that puts the document in an OPAQUE origin no matter how
|
||||
* it is opened (iframe or top-level tab). That opaque origin is also why the route
|
||||
* cannot authenticate on the session cookie: its subresource requests are
|
||||
* cross-site, so the `SameSite=lax` cookie is never attached (the same reason the
|
||||
* web-tab proxy uses capabilities, see webview-capabilities.ts).
|
||||
*
|
||||
* A capability is minted by an authenticated `POST /api/sessions/:id/html-view` and
|
||||
* grants exactly one thing: GET access to the files in ONE directory (the HTML
|
||||
* file's own), so a page's relative `style.css` / `chart.js` / images resolve.
|
||||
*
|
||||
* - 192 bits of `randomBytes` entropy, base64url.
|
||||
* - Held in memory only. A restart invalidates every outstanding capability.
|
||||
* - Rolling TTL, revoked on logout, admin logout and user deletion (`revokeOwner`).
|
||||
*/
|
||||
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { StaleExpirationMap } from './utils/index.js';
|
||||
import { MAX_WEBVIEW_CAPABILITIES, WEBVIEW_CAPABILITY_TTL_MS } from './config/webview-limits.js';
|
||||
|
||||
/** URL prefix the rendered files are served under. */
|
||||
export const HTML_VIEW_PREFIX = '/html-view';
|
||||
|
||||
export interface HtmlViewCapabilityRecord {
|
||||
/** Realpath of the directory the capability serves. */
|
||||
rootDir: string;
|
||||
/** Username that minted it (multi-user); undefined in single-user mode. */
|
||||
owner?: string;
|
||||
/**
|
||||
* Whether the directory lies outside the minting session's workspace (admitted
|
||||
* under the attachment guard). Recorded so the serving route can refuse it the
|
||||
* moment workspace confinement is switched on, as the attachment routes do.
|
||||
*/
|
||||
outsideWorkspace: boolean;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export class HtmlViewCapabilityStore {
|
||||
private readonly capabilities: StaleExpirationMap<string, HtmlViewCapabilityRecord>;
|
||||
/** Reverse index so re-opening a page reuses its capability instead of leaking one per click. */
|
||||
private readonly byRoot = new Map<string, string>();
|
||||
|
||||
constructor(ttlMs: number = WEBVIEW_CAPABILITY_TTL_MS) {
|
||||
this.capabilities = new StaleExpirationMap<string, HtmlViewCapabilityRecord>({
|
||||
ttlMs,
|
||||
refreshOnGet: true,
|
||||
onExpire: (token, record) => {
|
||||
const key = rootKey(record.rootDir, record.owner, record.outsideWorkspace);
|
||||
if (this.byRoot.get(key) === token) this.byRoot.delete(key);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Mint (or reuse) a capability for a directory. Returns the token. */
|
||||
mint(rootDir: string, owner?: string, outsideWorkspace = false): string {
|
||||
// The flag is part of the key: an out-of-workspace mint must never reuse a
|
||||
// capability recorded as in-workspace, which confinement would not stop.
|
||||
const key = rootKey(rootDir, owner, outsideWorkspace);
|
||||
const existing = this.byRoot.get(key);
|
||||
if (existing && this.capabilities.get(existing)) return existing;
|
||||
if (existing) this.byRoot.delete(key);
|
||||
|
||||
if (this.capabilities.size >= MAX_WEBVIEW_CAPABILITIES) this.capabilities.cleanup();
|
||||
|
||||
const token = randomBytes(24).toString('base64url');
|
||||
this.capabilities.set(token, { rootDir, owner, outsideWorkspace, createdAt: Date.now() });
|
||||
this.byRoot.set(key, token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Resolve a capability, refreshing its TTL. Returns undefined when unknown or expired. */
|
||||
resolve(token: string): HtmlViewCapabilityRecord | undefined {
|
||||
if (!token) return undefined;
|
||||
return this.capabilities.get(token);
|
||||
}
|
||||
|
||||
/** Revoke every capability bound to an identity (logout, admin logout, user deletion). */
|
||||
revokeOwner(owner: string | undefined): number {
|
||||
let revoked = 0;
|
||||
for (const [key, token] of [...this.byRoot]) {
|
||||
const record = this.capabilities.peek(token);
|
||||
if (!record || record.owner === owner) {
|
||||
this.capabilities.delete(token);
|
||||
this.byRoot.delete(key);
|
||||
if (record) revoked++;
|
||||
}
|
||||
}
|
||||
return revoked;
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.capabilities.size;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.capabilities.dispose();
|
||||
this.byRoot.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function rootKey(rootDir: string, owner: string | undefined, outsideWorkspace: boolean): string {
|
||||
return `${owner ?? ''}\0${outsideWorkspace ? 'out' : 'in'}\0${rootDir}`;
|
||||
}
|
||||
|
||||
/** The capability token in an `/html-view/<cap>/...` path, or null. */
|
||||
export function capabilityFromHtmlViewPath(pathname: string): string | null {
|
||||
if (typeof pathname !== 'string') return null;
|
||||
const prefix = `${HTML_VIEW_PREFIX}/`;
|
||||
if (!pathname.startsWith(prefix)) return null;
|
||||
const rest = pathname.slice(prefix.length);
|
||||
const slash = rest.indexOf('/');
|
||||
const cap = slash === -1 ? rest : rest.slice(0, slash);
|
||||
return /^[A-Za-z0-9_-]{16,128}$/.test(cap) ? cap : null;
|
||||
}
|
||||
|
||||
/** Process-wide store, shared by the routes and the auth middleware (see webviewCapabilities). */
|
||||
export const htmlViewCapabilities = new HtmlViewCapabilityStore();
|
||||
@@ -14,6 +14,7 @@ import { basename, extname, relative } from 'node:path';
|
||||
import { statSync } from 'node:fs';
|
||||
import type { AttachmentDetectedEvent, AttachmentDetectedType, ImageDetectedEvent } from './types.js';
|
||||
import { KeyedDebouncer } from './utils/index.js';
|
||||
import { UPLOAD_DIR_NAMES } from './web/paste-image-gc.js';
|
||||
|
||||
// ========== Types ==========
|
||||
|
||||
@@ -157,12 +158,15 @@ export class ImageWatcher extends EventEmitter {
|
||||
// Watch all subdirectories (images may be saved in src/, assets/, etc.)
|
||||
// Ignore common heavy directories for performance
|
||||
ignored: (path: string) => {
|
||||
// Skip node_modules, .git, and other heavy directories
|
||||
// Skip node_modules, .git, and other heavy directories, and Codeman's
|
||||
// own upload folders: a pdf the user handed to the agent is not a file
|
||||
// the agent produced.
|
||||
if (
|
||||
path.includes('/node_modules/') ||
|
||||
path.includes('/.git/') ||
|
||||
path.includes('/dist/') ||
|
||||
path.includes('/.next/')
|
||||
path.includes('/.next/') ||
|
||||
UPLOAD_DIR_NAMES.some((name) => path.includes(`/${name}/`))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* @fileoverview MCP sync targets that are not Codeman run modes.
|
||||
*
|
||||
* `mcpSyncTargets()` (routes/mcp-sync-routes.ts) takes the registry's enabled CLIs that declare an
|
||||
* `mcpConfig`. Some tools read an MCP server list worth keeping in step with the others but are not
|
||||
* something Codeman launches, so they have no registry entry (and no id to branch on): GitHub
|
||||
* Copilot CLI is the first. They are plain data here, take part only when installed or when their
|
||||
* config file already exists (an absent tool is reported `absent`, never created), and sort after
|
||||
* the registry CLIs, so when two definitions of a name differ the registry CLI's is the one copied.
|
||||
*
|
||||
* @module mcp-sync-targets
|
||||
*/
|
||||
|
||||
import { accessSync, constants as fsConstants } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { delimiter, join } from 'node:path';
|
||||
import type { McpConfigFormat } from './config/cli-registry/types.js';
|
||||
import type { McpSyncTarget } from './mcp-sync.js';
|
||||
|
||||
export interface McpSyncOnlyTool {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Home-relative default location of the MCP config file. */
|
||||
path: string;
|
||||
format: McpConfigFormat;
|
||||
/** The env var the tool reads to move its home, and the file under it. */
|
||||
relocation?: { envVar: string; path: string };
|
||||
/** The executable whose presence on this machine means the tool is installed. */
|
||||
binary: string;
|
||||
}
|
||||
|
||||
export const MCP_SYNC_ONLY_TOOLS: readonly McpSyncOnlyTool[] = [
|
||||
{
|
||||
id: 'copilot',
|
||||
label: 'GitHub Copilot CLI',
|
||||
path: '.copilot/mcp-config.json',
|
||||
format: 'copilot-json',
|
||||
// COPILOT_HOME replaces ~/.copilot (checked: `COPILOT_HOME=<dir> copilot mcp list` reads <dir>).
|
||||
relocation: { envVar: 'COPILOT_HOME', path: 'mcp-config.json' },
|
||||
binary: 'copilot',
|
||||
},
|
||||
];
|
||||
|
||||
/** `name` is an executable file in the server's PATH, `~/.local/bin` or `/usr/local/bin`. */
|
||||
export function binaryOnPath(name: string, env: Record<string, string | undefined> = process.env): boolean {
|
||||
const dirs = [
|
||||
...(env.PATH ?? '').split(delimiter).filter(Boolean),
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
];
|
||||
return dirs.some((dir) => {
|
||||
try {
|
||||
accessSync(join(dir, name), fsConstants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The sync-only tools as sync targets, skipping any id the registry already provides. */
|
||||
export function mcpSyncOnlyTargets(
|
||||
taken: ReadonlySet<string>,
|
||||
isInstalled: (binary: string) => boolean = binaryOnPath
|
||||
): McpSyncTarget[] {
|
||||
return MCP_SYNC_ONLY_TOOLS.filter((t) => !taken.has(t.id)).map((t) => ({
|
||||
id: t.id,
|
||||
label: t.label,
|
||||
path: t.path,
|
||||
format: t.format,
|
||||
...(t.relocation ? { relocation: t.relocation } : {}),
|
||||
installed: isInstalled(t.binary),
|
||||
}));
|
||||
}
|
||||
@@ -12,7 +12,8 @@
|
||||
* does not understand) is never rewritten and nothing is ever removed. Same name with a
|
||||
* different definition is reported as a conflict and left alone.
|
||||
* - A server the user has switched off in its own CLI (codex `enabled = false`, opencode
|
||||
* `enabled: false`, antigravity `disabled: true`) is not propagated: copying it would
|
||||
* `enabled: false`, antigravity `disabled: true`, Copilot's `disabledMcpServers` in its
|
||||
* `settings.json`) is not propagated: copying it would
|
||||
* switch it on in every other CLI.
|
||||
* - A file that does not parse (e.g. opencode JSONC with comments, a TOML file with a
|
||||
* duplicate table) is never written, and a write is only made after the NEW text has been
|
||||
@@ -39,7 +40,7 @@
|
||||
import { promises as fs } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, isAbsolute, join } from 'node:path';
|
||||
import { basename, dirname, isAbsolute, join } from 'node:path';
|
||||
import { parse as parseToml, TomlError } from 'smol-toml';
|
||||
import type { McpConfigFormat } from './config/cli-registry/types.js';
|
||||
import type { McpSyncResult, McpSyncTargetResult } from './types/mcp-sync.js';
|
||||
@@ -65,6 +66,11 @@ export interface McpSyncTarget {
|
||||
label: string;
|
||||
/** Home-relative default location of the config file. */
|
||||
path: string;
|
||||
/**
|
||||
* Home-relative fallback file used when `path` is absent: read, and written in place when it
|
||||
* parses (a JSONC file with comments fails the parse and is never written).
|
||||
*/
|
||||
altPath?: string;
|
||||
format: McpFormat;
|
||||
/** The env var the CLI reads to move the file, and the path under it (`mcpConfig.relocation`). */
|
||||
relocation?: { envVar: string; path: string };
|
||||
@@ -196,11 +202,12 @@ function toClaude(s: McpServer): Record<string, unknown> {
|
||||
function fromGemini(raw: unknown): McpServer | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
// `httpUrl` is the legacy streamable-http key; `url` + `type` is what `gemini mcp add` writes
|
||||
// today, and a bare `url` with no type is the legacy SSE form.
|
||||
// today. A bare `url` with no type used to be the legacy SSE form, but gemini-cli v0.63.0 tries
|
||||
// it as streamable HTTP first (and logs `httpUrl` as deprecated), so map it to 'http'.
|
||||
if (typeof raw.httpUrl === 'string')
|
||||
return clean({ transport: 'http', url: raw.httpUrl, headers: strMap(raw.headers) });
|
||||
if (typeof raw.url === 'string') {
|
||||
return clean({ transport: raw.type === 'http' ? 'http' : 'sse', url: raw.url, headers: strMap(raw.headers) });
|
||||
return clean({ transport: raw.type === 'sse' ? 'sse' : 'http', url: raw.url, headers: strMap(raw.headers) });
|
||||
}
|
||||
if (typeof raw.command === 'string') {
|
||||
return clean({
|
||||
@@ -254,7 +261,7 @@ function toAntigravity(s: McpServer): Record<string, unknown> | null {
|
||||
|
||||
function fromOpencode(raw: unknown): McpServer | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const disabled = raw.enabled === false;
|
||||
const disabled = raw.enabled === false || raw.disabled === true;
|
||||
if (raw.type === 'remote' && typeof raw.url === 'string') {
|
||||
return clean({ transport: 'http', url: raw.url, headers: strMap(raw.headers), disabled });
|
||||
}
|
||||
@@ -284,21 +291,58 @@ function toOpencode(s: McpServer): Record<string, unknown> {
|
||||
return { type: 'remote', url: s.url, ...(s.headers ? { headers: s.headers } : {}), enabled: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub Copilot CLI (`copilot mcp add`): `~/.copilot/mcp-config.json`, `mcpServers`. A stdio server is
|
||||
* `type: "local"`; every entry carries `tools` (`["*"]` = all). Whether a server is switched off is NOT in
|
||||
* this file: `copilot mcp disable` records the name in `settings.json` beside it (`disabledMcpServers`).
|
||||
*/
|
||||
function fromCopilot(raw: unknown): McpServer | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
if ((raw.type === 'http' || raw.type === 'sse') && typeof raw.url === 'string') {
|
||||
return clean({ transport: raw.type, url: raw.url, headers: strMap(raw.headers) });
|
||||
}
|
||||
if ((raw.type === undefined || raw.type === 'local' || raw.type === 'stdio') && typeof raw.command === 'string') {
|
||||
return clean({ transport: 'stdio', command: raw.command, args: strArr(raw.args), env: strMap(raw.env) });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toCopilot(s: McpServer): Record<string, unknown> {
|
||||
if (s.transport === 'stdio') {
|
||||
return { tools: ['*'], type: 'local', command: s.command, args: s.args ?? [], ...(s.env ? { env: s.env } : {}) };
|
||||
}
|
||||
return { tools: ['*'], type: s.transport, url: s.url, ...(s.headers ? { headers: s.headers } : {}) };
|
||||
}
|
||||
|
||||
interface JsonDialect {
|
||||
/** Key holding the server table. */
|
||||
key: string;
|
||||
/** Servers also read from under `key.nestedKey` (OpenCode V2 nests them under `mcp.servers`). */
|
||||
nestedKey?: string;
|
||||
from(raw: unknown): McpServer | null;
|
||||
to(s: McpServer): Record<string, unknown> | null;
|
||||
/** Top-level keys to seed when creating the file from nothing. */
|
||||
seed?: Record<string, unknown>;
|
||||
/**
|
||||
* A file beside the config that lists the names of servers the user switched off (the switch is
|
||||
* not stored on the server entry). Read, never written.
|
||||
*/
|
||||
disabledIn?: { file: string; key: string };
|
||||
}
|
||||
|
||||
const JSON_DIALECTS: Record<Exclude<McpFormat, 'codex-toml'>, JsonDialect> = {
|
||||
'claude-json': { key: 'mcpServers', from: fromClaude, to: toClaude },
|
||||
'gemini-json': { key: 'mcpServers', from: fromGemini, to: toGemini },
|
||||
'antigravity-json': { key: 'mcpServers', from: fromAntigravity, to: toAntigravity },
|
||||
'copilot-json': {
|
||||
key: 'mcpServers',
|
||||
from: fromCopilot,
|
||||
to: toCopilot,
|
||||
disabledIn: { file: 'settings.json', key: 'disabledMcpServers' },
|
||||
},
|
||||
'opencode-json': {
|
||||
key: 'mcp',
|
||||
nestedKey: 'servers',
|
||||
from: fromOpencode,
|
||||
to: toOpencode,
|
||||
seed: { $schema: 'https://opencode.ai/config.json' },
|
||||
@@ -370,7 +414,17 @@ function mcpTable(format: McpFormat, text: string | null): Record<string, unknow
|
||||
const table = doc[dialect.key];
|
||||
if (table === undefined) return dict<unknown>();
|
||||
if (!isRecord(table)) throw new McpConfigError(`"${dialect.key}" is not an object`);
|
||||
return table;
|
||||
if (!dialect.nestedKey) return table;
|
||||
const nested = table[dialect.nestedKey];
|
||||
// OpenCode reads `mcp.servers` as a V1 server named "servers" when it carries a V1 `type`.
|
||||
if (nested === undefined || (isRecord(nested) && (nested.type === 'local' || nested.type === 'remote'))) return table;
|
||||
if (!isRecord(nested)) throw new McpConfigError(`"${dialect.key}.${dialect.nestedKey}" is not an object`);
|
||||
// Merge the direct (V1) table with the nested (V2) one. Like OpenCode, the native V2 entry wins a
|
||||
// name collision; sync never writes a name already defined, so this does not affect the read-back.
|
||||
const merged = dict<unknown>();
|
||||
for (const k of safeKeys(table)) if (k !== dialect.nestedKey) merged[k] = table[k];
|
||||
for (const k of safeKeys(nested)) merged[k] = nested[k];
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Parse a config file's text (null = file absent). Throws if it cannot be read safely. */
|
||||
@@ -558,6 +612,56 @@ function resolveFile(
|
||||
return { file: join(dir, rel.path) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The alternate config file for a target (`McpSyncTarget.altPath`), honouring the same relocation
|
||||
* as the primary file: the alt lives in the same directory, so the relocated path is the primary's
|
||||
* directory plus the alt filename. Once chosen it is read and written exactly like the primary; a
|
||||
* JSONC file with comments fails the parse guard and is never written.
|
||||
*/
|
||||
function resolveAltFile(
|
||||
t: McpSyncTarget,
|
||||
altPath: string,
|
||||
home: string,
|
||||
env: Record<string, string | undefined>
|
||||
): { file: string; skip?: string } {
|
||||
const rel = t.relocation;
|
||||
const dir = rel ? env[rel.envVar] : undefined;
|
||||
if (!rel || dir === undefined || dir === '') return { file: join(home, altPath) };
|
||||
if (!isAbsolute(dir)) {
|
||||
return {
|
||||
file: `$${rel.envVar}/…`,
|
||||
skip: `${rel.envVar} is set to a relative path, so the alt file cannot be located safely`,
|
||||
};
|
||||
}
|
||||
return { file: join(dir, dirname(rel.path), basename(altPath)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the servers a CLI keeps switched off in a companion file (`JsonDialect.disabledIn`) as
|
||||
* disabled, so they are not copied. If that file cannot be read as intended the target is
|
||||
* reported unreadable rather than guessing: a guess could switch a server on everywhere.
|
||||
*/
|
||||
async function applyCompanionDisabled(format: McpFormat, file: string, servers: McpServerMap): Promise<void> {
|
||||
if (format === 'codex-toml') return;
|
||||
const companion = JSON_DIALECTS[format].disabledIn;
|
||||
if (!companion) return;
|
||||
const text = await readText(join(dirname(file), companion.file));
|
||||
if (text === null || !text.trim()) return;
|
||||
let doc: unknown;
|
||||
try {
|
||||
doc = JSON.parse(text);
|
||||
} catch {
|
||||
throw new McpConfigError(
|
||||
`${companion.file} next to the config is not valid JSON, so which servers are switched off is unknown`
|
||||
);
|
||||
}
|
||||
const list = isRecord(doc) ? doc[companion.key] : undefined;
|
||||
if (list === undefined) return;
|
||||
const names = strArr(list);
|
||||
if (!names) throw new McpConfigError(`"${companion.key}" in ${companion.file} is not a list of names`);
|
||||
for (const n of names) if (n in servers) servers[n] = { ...servers[n], disabled: true };
|
||||
}
|
||||
|
||||
let applying = false;
|
||||
|
||||
/**
|
||||
@@ -606,11 +710,21 @@ async function run(targets: McpSyncTarget[], opts: McpSyncOptions, unsupported:
|
||||
for (const s of state) {
|
||||
if (s.res.status !== 'ok') continue;
|
||||
try {
|
||||
// A config kept under an alternate name (OpenCode's opencode.jsonc) is read when the primary
|
||||
// file is absent, so its servers are synced rather than silently treated as "not installed".
|
||||
if (s.t.altPath && !(await exists(s.file))) {
|
||||
const alt = resolveAltFile(s.t, s.t.altPath, home, env);
|
||||
if (!alt.skip && (await exists(alt.file))) {
|
||||
s.file = alt.file;
|
||||
s.res.file = alt.file;
|
||||
}
|
||||
}
|
||||
if (!s.t.installed && !(await exists(s.file))) {
|
||||
s.res.status = 'absent';
|
||||
continue;
|
||||
}
|
||||
const parsed = parseConfig(s.t.format, await readText(s.file));
|
||||
await applyCompanionDisabled(s.t.format, s.file, parsed.servers);
|
||||
s.servers = parsed.servers;
|
||||
s.names = parsed.names;
|
||||
s.res.servers = [...parsed.names];
|
||||
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
SessionRemote,
|
||||
SessionDocker,
|
||||
PaneExit,
|
||||
StatusLineExporter,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
@@ -57,6 +58,8 @@ export interface MuxSession {
|
||||
respawnConfig?: PersistedRespawnConfig;
|
||||
/** Whether Ralph / Todo tracking is enabled */
|
||||
ralphEnabled?: boolean;
|
||||
/** Whether the current launch carries the statusLine exporter; set on every create and respawn. */
|
||||
statusLine?: StatusLineExporter;
|
||||
/**
|
||||
* This record was rebuilt from the tmux socket rather than from Codeman's own
|
||||
* bookkeeping, so everything on it but the name and the pid is a guess. Its
|
||||
@@ -189,6 +192,21 @@ export interface PaneCaptureOptions {
|
||||
fullHistory?: boolean;
|
||||
/** Bound the full-history capture to this many scrollback lines (`-S -<N>`). */
|
||||
historyLimitLines?: number;
|
||||
/**
|
||||
* Full-history only: scrollback rows read from somewhere other than this pane
|
||||
* (raw `capture-pane -p -e -J` text, oldest first). The pane then contributes
|
||||
* only its visible frame and caret, and its own history is not read. A remote
|
||||
* session's real history lives in the REMOTE tmux (`remote-pane-history.ts`).
|
||||
*/
|
||||
scrollbackOverride?: string;
|
||||
/**
|
||||
* With `scrollbackOverride`: the screen rows of the pane that history came
|
||||
* from, read right after it. The frame this pane captures later can have
|
||||
* scrolled past some of them, or show only part of a taller screen, so the
|
||||
* rows above where the frame's top overlaps them are kept between the
|
||||
* scrollback and the frame (`joinScrollbackAndFrame`).
|
||||
*/
|
||||
scrollbackOverrideScreen?: string;
|
||||
/**
|
||||
* Byte cap the consumer will keep from the capture. Sizes the child-process
|
||||
* stdout buffer (with slack) so multi-MB scrollback dumps aren't killed by
|
||||
@@ -204,6 +222,24 @@ export interface PaneCaptureOptions {
|
||||
* rendering it needs the real height to know the frame fits.
|
||||
*/
|
||||
capturedGeometry?: { cols: number; rows: number };
|
||||
/**
|
||||
* Filled in by the implementation with the number of rows the pane holds in
|
||||
* scrollback ABOVE the visible frame (tmux `#{history_size}`), read in the
|
||||
* same query as the geometry. 0 means a full-history capture can return
|
||||
* nothing beyond the visible frame: a pane in the alternate screen (a
|
||||
* fullscreen CLI that keeps its transcript itself) never accumulates any.
|
||||
* A full-history capture bounded by `historyLimitLines` below this depth
|
||||
* left older lines behind in the multiplexer, which the caller must report
|
||||
* as recoverable. Absent when the pane could not be queried.
|
||||
*/
|
||||
capturedHistoryLines?: number;
|
||||
/**
|
||||
* Filled in by the implementation with whether the pane was in the alternate
|
||||
* screen at capture time, when it can tell. tmux keeps no history for such a
|
||||
* pane (a nested tmux client puts it there), so a full-history capture of it
|
||||
* holds one screen plus whatever the pane held before.
|
||||
*/
|
||||
capturedAlternateOn?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -135,6 +135,10 @@ export function buildRemoteFileCommand(remote: SessionRemote, shellCommand: stri
|
||||
* `echo` (which land before the script runs) from the records without any "last N
|
||||
* lines" guesswork. `realPath` is the last field, so a `|` in a path still parses.
|
||||
*
|
||||
* A path starting with `~/` is taken relative to the remote user's `$HOME`: this
|
||||
* server does not know that home, and a clicked `~/…` link means the host the
|
||||
* session runs on. The record's `realPath` is absolute, as for any other path.
|
||||
*
|
||||
* Symlink resolution is portable AND fails closed. `readlink -f` where available
|
||||
* (Linux, macOS >= 12.3); otherwise the fallback canonicalizes the directory chain
|
||||
* with `cd -P`/`pwd -P` and then follows the LAST component with plain `readlink`
|
||||
@@ -166,6 +170,8 @@ export function buildRemoteProbeCommand(paths: readonly string[]): string {
|
||||
'probe() {',
|
||||
' i=$1',
|
||||
' p=$2',
|
||||
// `~/…` from a clicked link: THIS host's home (assignment, so no word splitting).
|
||||
" case $p in '~/'*) p=$HOME/${p#??} ;; esac",
|
||||
` if [ ! -e "$p" ]; then printf '%s|${NOT_FOUND_MARKER}\\0' "$i"; return; fi`,
|
||||
` r=$(readlink -f "$p" 2>/dev/null) || r=$(resolve_last "$p") || { printf '%s|${UNRESOLVABLE_MARKER}\\0' "$i"; return; }`,
|
||||
` [ -n "$r" ] || { printf '%s|${UNRESOLVABLE_MARKER}\\0' "$i"; return; }`,
|
||||
@@ -269,6 +275,126 @@ export async function remoteProbePaths(
|
||||
return results;
|
||||
}
|
||||
|
||||
/** One entry of a remote folder listing: a file (with size/mtime) or a subfolder. */
|
||||
export interface RemoteFolderEntry {
|
||||
kind: 'file' | 'directory';
|
||||
name: string;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
}
|
||||
|
||||
/** A remote folder listing; `dir` is the folder with symlinks resolved on the remote host. */
|
||||
export interface RemoteFolderListing {
|
||||
dir: string;
|
||||
entries: RemoteFolderEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* List one remote folder in a SINGLE ssh round trip: its canonical path, then every
|
||||
* non-hidden subfolder and every regular file (symlinks followed) whose name ends in
|
||||
* one of `extensions` (any case), up to `maxEntries`.
|
||||
*
|
||||
* Same output discipline as {@link buildRemoteProbeCommand}: a lone NUL first (so rc
|
||||
* chatter before it is discarded), then NUL-terminated records — `E|n` (no such
|
||||
* folder), `E|x` (cannot be canonicalized), `D|<dir>`, `d|0|0|<name>`,
|
||||
* `f|<size>|<mtime>|<name>`, and `T|` when the cap cut the listing. The name is the
|
||||
* last field, so a `|` in it still parses, and NUL is the one byte a filename cannot
|
||||
* hold. A leading `~/` is the remote user's `$HOME`, as in the probe.
|
||||
*/
|
||||
export function buildRemoteFolderListCommand(dir: string, extensions: readonly string[], maxEntries: number): string {
|
||||
// `[pP][nN][gG]`: any case, as the local listing compares lowercased (`shot.Png`).
|
||||
const patterns = [...new Set(extensions.map((ext) => ext.toLowerCase()))]
|
||||
.map((ext) => `*.${ext.replace(/[a-z]/g, (c) => `[${c}${c.toUpperCase()}]`)}`)
|
||||
.join('|');
|
||||
const script = [
|
||||
`d=${shellescape(dir)}`,
|
||||
"case $d in '~/'*) d=$HOME/${d#??} ;; esac",
|
||||
"printf '\\0'",
|
||||
'[ -d "$d" ] || { [ -e "$d" ] && printf \'E|f\\0\' || printf \'E|n\\0\'; exit 0; }',
|
||||
'r=$(cd -P "$d" 2>/dev/null && pwd -P) || { printf \'E|x\\0\'; exit 0; }',
|
||||
'printf \'D|%s\\0\' "$r"',
|
||||
'n=0',
|
||||
'for f in "$r"/*; do',
|
||||
' [ -e "$f" ] || continue',
|
||||
` [ "$n" -lt ${Math.max(1, Math.floor(maxEntries))} ] || { printf 'T|\\0'; break; }`,
|
||||
' b=${f##*/}',
|
||||
' if [ -d "$f" ]; then n=$((n + 1)); printf \'d|0|0|%s\\0\' "$b"; continue; fi',
|
||||
' [ -f "$f" ] || continue',
|
||||
` case $b in ${patterns || '*.__none__'}) ;; *) continue ;; esac`,
|
||||
" sm=$(stat -L -c '%s %Y' \"$f\" 2>/dev/null || stat -L -f '%z %m' \"$f\" 2>/dev/null) || sm='0 0'",
|
||||
' n=$((n + 1))',
|
||||
' printf \'f|%s|%s|%s\\0\' "${sm% *}" "${sm#* }" "$b"',
|
||||
'done',
|
||||
].join('\n');
|
||||
// ⚠️ sshd runs the command in the remote user's LOGIN shell, rc aliases included.
|
||||
// On Hufflepuff `cd` is an alias that echoes the new directory (`$(cd -P "$d" &&
|
||||
// pwd -P)` came back as two lines, then zsh aborted on the glob: "no matches found:
|
||||
// /x\n/x/*"), so no folder listing worked over ssh. An explicit `sh` reads no rc
|
||||
// file — the same wrapper the transcript read uses.
|
||||
return `sh -c ${shellescape(script)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse {@link buildRemoteFolderListCommand} output: null when nothing exists there
|
||||
* (or it cannot be resolved), `'not-a-folder'` when it is a file.
|
||||
*/
|
||||
export function parseRemoteFolderListOutput(stdout: string): RemoteFolderListing | 'not-a-folder' | null {
|
||||
const records = stdout.split('\0').slice(1);
|
||||
let dir: string | null = null;
|
||||
let truncated = false;
|
||||
const entries: RemoteFolderEntry[] = [];
|
||||
for (const record of records) {
|
||||
if (record === 'E|f') return 'not-a-folder';
|
||||
if (record.startsWith('E|')) return null;
|
||||
if (record.startsWith('D|')) {
|
||||
dir = record.slice(2);
|
||||
continue;
|
||||
}
|
||||
if (record === 'T|') {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
const match = /^([fd])\|(\d*)\|(\d*)\|([\s\S]+)$/.exec(record);
|
||||
if (!match) continue;
|
||||
const size = Number.parseInt(match[2], 10);
|
||||
const mtime = Number.parseInt(match[3], 10);
|
||||
entries.push({
|
||||
kind: match[1] === 'd' ? 'directory' : 'file',
|
||||
name: match[4],
|
||||
size: Number.isFinite(size) && size > 0 ? size : 0,
|
||||
mtimeMs: Number.isFinite(mtime) && mtime > 0 ? mtime * 1000 : 0,
|
||||
});
|
||||
}
|
||||
if (!dir) {
|
||||
throw new RemoteFileAccessError('remote host returned no usable folder listing');
|
||||
}
|
||||
return { dir, entries, truncated };
|
||||
}
|
||||
|
||||
/** List a remote folder (see {@link buildRemoteFolderListCommand}). */
|
||||
export async function remoteListFolder(
|
||||
remote: SessionRemote,
|
||||
dir: string,
|
||||
extensions: readonly string[],
|
||||
maxEntries: number
|
||||
): Promise<RemoteFolderListing | 'not-a-folder' | null> {
|
||||
assertNotUnderTest();
|
||||
const command = buildRemoteFileCommand(remote, buildRemoteFolderListCommand(dir, extensions, maxEntries));
|
||||
let stdout: string;
|
||||
try {
|
||||
const result = await runWithRemoteSshLimit(() =>
|
||||
execAsync(command, { timeout: REMOTE_PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 })
|
||||
);
|
||||
stdout = result.stdout;
|
||||
} catch (err) {
|
||||
throw new RemoteFileAccessError(
|
||||
`remote host ${remote.label || remote.host} unreachable: ${describeExecError(err)}`
|
||||
);
|
||||
}
|
||||
return parseRemoteFolderListOutput(stdout);
|
||||
}
|
||||
|
||||
/** Read a whole remote file into memory, capped by `maxBytes`. */
|
||||
export async function remoteReadFile(remote: SessionRemote, remotePath: string, maxBytes: number): Promise<Buffer> {
|
||||
assertNotUnderTest();
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* @fileoverview Scrollback of a remote SSH session, read from the REMOTE tmux.
|
||||
*
|
||||
* A remote session's local pane runs `ssh -t … tmux new-session -A` (or `attach`),
|
||||
* so the local tmux only ever sees what the remote tmux CLIENT draws: full-screen
|
||||
* repaints, not scrolling output. The local pane therefore keeps a fraction of the
|
||||
* history (measured: 48 of 279 lines while output streamed, none after a reattach),
|
||||
* while the remote pane, where the shell really runs, keeps all of it. A full-history
|
||||
* load of a remote session reads the scrollback from there instead, and the caller
|
||||
* splices it above the LOCAL visible frame (`PaneCaptureOptions.scrollbackOverride`):
|
||||
* the local pane is what the live stream keeps drawing into, so its frame and caret
|
||||
* position are the ones the browser must end up with.
|
||||
*
|
||||
* ONE ssh round trip reads the remote pane's scrollback rows (`capture-pane -S -<N>
|
||||
* -E -1`), its `#{history_size}` and its screen. The size is load-bearing: with no
|
||||
* history at all, tmux clamps `-E -1` to the first VISIBLE row and would return it
|
||||
* as history. The screen closes the seam between the remote read and the local
|
||||
* frame, which is read only after the round trip: rows that scrolled in between,
|
||||
* and the top of a remote screen taller than the local pane, are on that screen
|
||||
* alone, and the caller keeps the screen rows above where the local frame overlaps
|
||||
* it (`joinScrollbackAndFrame`).
|
||||
*
|
||||
* ⚠️ The three reads are ONE tmux command list (`a \; b \; c`), not three tmux
|
||||
* runs. tmux runs a client's command list back to back without reading pane output
|
||||
* in between, so the history ends exactly where the screen begins. As separate runs
|
||||
* the shell kept writing between them, and the rows that scrolled in those
|
||||
* milliseconds were in neither capture (measured on a busy pane: every read lost
|
||||
* rows). This rests on how tmux's command queue behaves, not on a documented
|
||||
* guarantee. tmux output cannot carry the NUL markers, so a random marker line
|
||||
* printed by `display-message` separates the history from the size and screen.
|
||||
* tmux before 3.2 prints no newline after `capture-pane -p`, so the marker can be
|
||||
* glued onto an unterminated last history row; the parser accepts it there too.
|
||||
*
|
||||
* Bounded and fail-soft. Any failure (unreachable host, auth, missing session, odd
|
||||
* output) returns null and the caller keeps the local capture, so a remote load is
|
||||
* never worse than before. A transport failure also starts a short per-host back-off,
|
||||
* so a host that is asleep costs one timeout, not one per tab switch. The child runs
|
||||
* under the shared remote-ssh limiter (`remote-ssh-limiter.ts`) like every other
|
||||
* short-lived remote ssh, but gives up on a slot it waited too long for (`maxWaitMs`,
|
||||
* enforced in the queue), and the connection options come from
|
||||
* `buildSshConnectionArgs()`.
|
||||
*
|
||||
* How much history exists is the REMOTE tmux's `history-limit` (2000 lines unless
|
||||
* the remote user's tmux.conf raises it); the launch command does not set it.
|
||||
*/
|
||||
|
||||
import { exec } from 'node:child_process';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import type { SessionRemote } from './types/session.js';
|
||||
import { buildSshConnectionArgs, classifyRemoteAliveExit, remoteSshTarget, shellescape } from './remote-hosts.js';
|
||||
import { RemoteSshSlotTimeoutError, runWithRemoteSshLimit } from './remote-ssh-limiter.js';
|
||||
import { remoteTmuxLocation } from './tmux-manager.js';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Bound on the whole round trip. A full load waits on it, so it is far below the
|
||||
* 10 s `ConnectTimeout` the shared ssh options carry: past this the local capture
|
||||
* is the better answer.
|
||||
*/
|
||||
const REMOTE_HISTORY_TIMEOUT_MS = 5_000;
|
||||
|
||||
/**
|
||||
* Longest a load waits for a slot in the shared ssh pool, which file previews and
|
||||
* attachment probes (20 s each) also hold. Past it the local capture is used.
|
||||
*/
|
||||
const REMOTE_HISTORY_SLOT_WAIT_MS = 1_500;
|
||||
|
||||
/** After a failed read, skip that host for this long and use the local capture. */
|
||||
const REMOTE_HISTORY_BACKOFF_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Headroom over the remote `tail -c` bound for what it does not cover: the two NUL
|
||||
* markers and anything a login banner or rc file prints before the script.
|
||||
*/
|
||||
const REMOTE_HISTORY_SLACK_BYTES = 64 * 1024;
|
||||
|
||||
/**
|
||||
* Added to the configured byte cap for the remote `tail -c` bound. That bound
|
||||
* covers the whole tmux output, and the marker, the size and the screen come last
|
||||
* (a wide, tall screen of colored rows runs to a few hundred KB); without this, a
|
||||
* small cap would cut into the screen and lose the read. The route trims what it
|
||||
* returns to the configured cap anyway, keeping the newest bytes.
|
||||
*/
|
||||
const REMOTE_SCREEN_ALLOWANCE_BYTES = 1024 * 1024;
|
||||
|
||||
/** The remote `tail -c` bound for a configured byte cap; 0 (unbounded) stays 0. */
|
||||
export function remoteTailBytes(maxBytes: number): number {
|
||||
return maxBytes > 0 ? Math.trunc(maxBytes) + REMOTE_SCREEN_ALLOWANCE_BYTES : 0;
|
||||
}
|
||||
|
||||
/** Read ceiling when the configured byte cap is 0 (unbounded) and no `tail -c` runs. */
|
||||
const UNBOUNDED_READ_MAX_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Host id → time the back-off ends. Keyed by HOST, so a sleeping host with five
|
||||
* sessions costs one timeout, and the map is bounded by the configured hosts.
|
||||
*/
|
||||
const backoffUntil = new Map<string, number>();
|
||||
|
||||
/**
|
||||
* A fresh marker line for one read. Random, so no row the pane really holds can be
|
||||
* taken for it.
|
||||
*/
|
||||
export function newScrollbackMarker(): string {
|
||||
return `codeman-history-${randomBytes(8).toString('hex')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote shell script. It prints a NUL, the tmux output, then a second NUL:
|
||||
* the first separates a login banner or an rc-file `echo` printed before the
|
||||
* script runs without guessing (the same marker `buildRemoteProbeCommand` uses),
|
||||
* and both are printed whether or not tmux succeeds, so their presence says the
|
||||
* script ran on the host. The tmux output is the history rows, `marker`, the
|
||||
* history size, then the screen rows.
|
||||
*/
|
||||
export function buildRemoteScrollbackScript(
|
||||
socket: string,
|
||||
sessionName: string,
|
||||
historyLines: number,
|
||||
tailBytes: number,
|
||||
marker: string
|
||||
): string {
|
||||
// `=name:` is an EXACT session match, then its active pane. A bare name is
|
||||
// read as a pane index or window name first, so a discovered session named
|
||||
// `0` would capture some other session's pane.
|
||||
const target = shellescape(`=${sessionName}:`);
|
||||
const lines = Math.max(1, Math.trunc(historyLines));
|
||||
// The newest rows are the ones worth keeping, so the byte bound is applied on
|
||||
// the remote side (`tail -c`) rather than by killing the read at maxBuffer.
|
||||
// It covers the whole tmux output, history first, so with the screen
|
||||
// allowance in `remoteTailBytes()` a cut lands in the history. 0 means
|
||||
// unbounded, as in the route.
|
||||
const bound = tailBytes > 0 ? ` | tail -c ${Math.trunc(tailBytes)}` : '';
|
||||
// ONE tmux command list, so no pane output is read between the history and
|
||||
// the screen (see the @fileoverview). `\;` reaches tmux as a lone `;`.
|
||||
return (
|
||||
`printf '\\0'; tmux -L ${shellescape(socket)} ` +
|
||||
`capture-pane -p -e -J -S -${lines} -E -1 -t ${target} \\; ` +
|
||||
`display-message -p -t ${target} ${shellescape(marker)} \\; ` +
|
||||
`display-message -p -t ${target} '#{history_size}' \\; ` +
|
||||
`capture-pane -p -e -J -t ${target}${bound}; printf '\\0'`
|
||||
);
|
||||
}
|
||||
|
||||
/** The full ssh command line for {@link buildRemoteScrollbackScript}. */
|
||||
export function buildRemoteScrollbackCommand(
|
||||
remote: SessionRemote,
|
||||
sessionId: string,
|
||||
historyLines: number,
|
||||
tailBytes: number,
|
||||
marker: string
|
||||
): string {
|
||||
const { socket, sessionName } = remoteTmuxLocation(remote, sessionId);
|
||||
const script = buildRemoteScrollbackScript(socket, sessionName, historyLines, tailBytes, marker);
|
||||
// `exec` so a timeout kill reaches ssh itself, not only the local `sh -c`.
|
||||
return ['exec', ...buildSshConnectionArgs(remote), remoteSshTarget(remote), shellescape(script)].join(' ');
|
||||
}
|
||||
|
||||
/** What one round trip read from the remote pane: its scrollback rows, then its screen. */
|
||||
export interface RemoteScrollback {
|
||||
/** History rows above the screen, oldest first; '' when the pane has none. */
|
||||
scrollback: string;
|
||||
/** The screen's rows, read in the same tmux command list, so they begin where the scrollback ends. */
|
||||
screen: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The scrollback and screen rows from the script's stdout, or null when the
|
||||
* output is not the script's or tmux printed nothing usable (no such session,
|
||||
* or a byte cap so small it cut into the screen). The marker may end an
|
||||
* unterminated history row (tmux before 3.2); when the output reached
|
||||
* `tailBytes`, the history's partial first row is dropped.
|
||||
*/
|
||||
export function parseRemoteScrollbackOutput(
|
||||
stdout: string,
|
||||
marker: string,
|
||||
tailBytes: number
|
||||
): RemoteScrollback | null {
|
||||
const start = stdout.indexOf('\0');
|
||||
if (start === -1) return null;
|
||||
const end = stdout.indexOf('\0', start + 1);
|
||||
if (end === -1) return null;
|
||||
// The marker ends a row, after the history's last row. Usually it is a row of
|
||||
// its own, but tmux before 3.2 prints no newline after `capture-pane -p`, so
|
||||
// when the history ends inside a wrapped line (`-J` leaves it unterminated)
|
||||
// the marker is glued onto that row. It is random per read, so no row the
|
||||
// pane really holds ends with it.
|
||||
const markerRow = `${marker}\n`;
|
||||
const raw = stdout.slice(start + 1, end);
|
||||
const at = raw.indexOf(markerRow);
|
||||
if (at === -1) return null;
|
||||
const sizeStart = at + markerRow.length;
|
||||
const sizeEnd = raw.indexOf('\n', sizeStart);
|
||||
if (sizeEnd === -1) return null;
|
||||
const sizeText = raw.slice(sizeStart, sizeEnd).trim();
|
||||
if (!/^\d+$/.test(sizeText)) return null;
|
||||
const screen = raw.slice(sizeEnd + 1);
|
||||
// With no history at all, tmux clamps `-E -1` to the first visible row.
|
||||
if (Number(sizeText) === 0) return { scrollback: '', screen };
|
||||
// A tail -c cut lands in the history (the bound leaves room for the rest),
|
||||
// mid-row and possibly mid-escape, so the first, partial row is dropped. A
|
||||
// cut exactly on the marker row leaves no history at all.
|
||||
let scrollback = raw.slice(0, at);
|
||||
if (tailBytes > 0 && Buffer.byteLength(raw, 'utf-8') >= tailBytes) {
|
||||
const newline = scrollback.indexOf('\n');
|
||||
scrollback = newline === -1 ? '' : scrollback.slice(newline + 1);
|
||||
}
|
||||
if (scrollback !== '' && !scrollback.endsWith('\n')) scrollback += '\n';
|
||||
return { scrollback, screen };
|
||||
}
|
||||
|
||||
/** Runs the ssh command line and resolves its stdout; rejects like `exec` does. */
|
||||
export type RemoteScrollbackRunner = (command: string, opts: { timeout: number; maxBuffer: number }) => Promise<string>;
|
||||
|
||||
const execRunner: RemoteScrollbackRunner = async (command, opts) =>
|
||||
(await execAsync(command, { encoding: 'utf-8', ...opts })).stdout;
|
||||
|
||||
/**
|
||||
* Read a remote session's scrollback from the remote tmux, or null to keep the
|
||||
* local capture. Never throws.
|
||||
*
|
||||
* Only a TRANSPORT failure backs the host off (ssh's own exit 255, a timeout, a
|
||||
* spawn error, output that is not the script's): those say the host is
|
||||
* unreachable for every session on it. A remote command failing (a session
|
||||
* that is gone: tmux answers nothing between the NULs, and the closing `printf`
|
||||
* hides its exit status) is about this session only, so it returns
|
||||
* null and the next session on that host still tries. Same split as
|
||||
* `classifyRemoteAliveExit()`.
|
||||
*
|
||||
* `run` is a test seam: without it nothing runs under vitest, as in
|
||||
* remote-files.ts / remote-hosts.ts.
|
||||
*/
|
||||
export async function fetchRemoteScrollback(
|
||||
remote: SessionRemote,
|
||||
sessionId: string,
|
||||
historyLines: number,
|
||||
maxBytes: number,
|
||||
run?: RemoteScrollbackRunner
|
||||
): Promise<RemoteScrollback | null> {
|
||||
if (!run && process.env.VITEST) return null;
|
||||
const runner = run ?? execRunner;
|
||||
const until = backoffUntil.get(remote.hostId);
|
||||
if (until !== undefined) {
|
||||
if (Date.now() < until) return null;
|
||||
backoffUntil.delete(remote.hostId);
|
||||
}
|
||||
const marker = newScrollbackMarker();
|
||||
const tailBytes = remoteTailBytes(maxBytes);
|
||||
const command = buildRemoteScrollbackCommand(remote, sessionId, historyLines, tailBytes, marker);
|
||||
try {
|
||||
const stdout = await runWithRemoteSshLimit(
|
||||
() =>
|
||||
runner(command, {
|
||||
timeout: REMOTE_HISTORY_TIMEOUT_MS,
|
||||
maxBuffer: (tailBytes > 0 ? tailBytes : UNBOUNDED_READ_MAX_BYTES) + REMOTE_HISTORY_SLACK_BYTES,
|
||||
}),
|
||||
// The pool is shared with 20 s file probes; past this the local capture
|
||||
// is the better answer than waiting behind them.
|
||||
{ maxWaitMs: REMOTE_HISTORY_SLOT_WAIT_MS }
|
||||
);
|
||||
const parsed = parseRemoteScrollbackOutput(stdout, marker, tailBytes);
|
||||
if (parsed === null) {
|
||||
// Both NULs arrived, so the script ran on the host and only tmux had
|
||||
// nothing to say: no such session. The script's last command is the
|
||||
// closing `printf`, so this comes back as exit 0 rather than tmux's
|
||||
// exit 1, and it is about this session alone. Output without the NULs
|
||||
// is not the script's at all, which says the host is not answering as
|
||||
// expected.
|
||||
const parts = stdout.split('\0');
|
||||
const ranOnHost = parts.length >= 3;
|
||||
if (!ranOnHost) backoffUntil.set(remote.hostId, Date.now() + REMOTE_HISTORY_BACKOFF_MS);
|
||||
// tmux printed something, but not the marker, size and screen in order.
|
||||
const unreadable = ranOnHost && parts[1] !== '';
|
||||
const what = !ranOnHost
|
||||
? 'unexpected output'
|
||||
: unreadable
|
||||
? 'unreadable remote tmux output'
|
||||
: 'no such remote tmux session';
|
||||
console.warn(`[remote-history] ${remote.label}: ${what}; using the local capture`);
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
// A busy pool says nothing about the host.
|
||||
if (err instanceof RemoteSshSlotTimeoutError) return null;
|
||||
const e = err as { killed?: boolean; code?: unknown };
|
||||
const code = typeof e.code === 'number' ? e.code : null;
|
||||
const transport = classifyRemoteAliveExit(code, e.killed === true) === undefined;
|
||||
if (transport) backoffUntil.set(remote.hostId, Date.now() + REMOTE_HISTORY_BACKOFF_MS);
|
||||
const reason = e.killed ? 'timed out' : code !== null ? `exit ${code}` : 'failed';
|
||||
console.warn(`[remote-history] ${remote.label}: remote scrollback read ${reason}; using the local capture`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Test hook: forget every host back-off. */
|
||||
export function resetRemoteScrollbackBackoff(): void {
|
||||
backoffUntil.clear();
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
/**
|
||||
* @fileoverview Global concurrency limiter for the short-lived `ssh` children that
|
||||
* remote-case file access spawns (`src/remote-files.ts`: the realpath+stat probe and
|
||||
* the buffered text read).
|
||||
* the buffered text read). A remote session's full-history load reads its scrollback
|
||||
* from the remote tmux through the same pool (`src/remote-pane-history.ts`), with a
|
||||
* bounded wait (`maxWaitMs`) because it has the local capture to fall back on.
|
||||
*
|
||||
* Two paths can fan those out without a human behind each one:
|
||||
*
|
||||
@@ -60,12 +62,35 @@ export function getRemoteSshLimit(): number {
|
||||
return MAX_CONCURRENT_REMOTE_SSH;
|
||||
}
|
||||
|
||||
function acquire(): Promise<void> {
|
||||
/** Thrown by {@link runWithRemoteSshLimit} when `maxWaitMs` passed before a slot freed up. */
|
||||
export class RemoteSshSlotTimeoutError extends Error {
|
||||
constructor(maxWaitMs: number) {
|
||||
super(`No remote ssh slot within ${maxWaitMs} ms`);
|
||||
this.name = 'RemoteSshSlotTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
function acquire(maxWaitMs?: number): Promise<void> {
|
||||
if (active < MAX_CONCURRENT_REMOTE_SSH) {
|
||||
active++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise<void>((resolve) => waiters.push(resolve));
|
||||
if (maxWaitMs === undefined) return new Promise<void>((resolve) => waiters.push(resolve));
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const waiter = () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
// A timed-out waiter leaves the queue and is never handed a slot, so it
|
||||
// owns nothing to give back: `active` is untouched on this path.
|
||||
const timer = setTimeout(() => {
|
||||
const index = waiters.indexOf(waiter);
|
||||
if (index === -1) return; // already handed a slot by release()
|
||||
waiters.splice(index, 1);
|
||||
reject(new RemoteSshSlotTimeoutError(maxWaitMs));
|
||||
}, maxWaitMs);
|
||||
waiters.push(waiter);
|
||||
});
|
||||
}
|
||||
|
||||
function release(): void {
|
||||
@@ -78,9 +103,14 @@ function release(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Run `task` once an ssh slot is free, releasing the slot afterward. */
|
||||
export async function runWithRemoteSshLimit<T>(task: () => Promise<T>): Promise<T> {
|
||||
await acquire();
|
||||
/**
|
||||
* Run `task` once an ssh slot is free, releasing the slot afterward. With
|
||||
* `maxWaitMs`, give up instead (rejecting with {@link RemoteSshSlotTimeoutError},
|
||||
* `task` never runs) when no slot frees up in time: for a caller that has a
|
||||
* cheaper answer than waiting behind the queue.
|
||||
*/
|
||||
export async function runWithRemoteSshLimit<T>(task: () => Promise<T>, opts: { maxWaitMs?: number } = {}): Promise<T> {
|
||||
await acquire(opts.maxWaitMs);
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
|
||||