@cortex-agent/server 2026.10.15-2 → 2026.10.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -31
- package/defaults/board/board.css +140 -62
- package/defaults/board/scaffold.html +36 -13
- package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
- package/defaults/plugins/cortex-system/plugin.json +2 -2
- package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
- package/dist/agent-adapter/claude/adapter.d.ts +2 -5
- package/dist/agent-adapter/claude/adapter.js +6 -5
- package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
- package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
- package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
- package/dist/agent-adapter/claude/cache-refresh.js +145 -0
- package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
- package/dist/agent-adapter/claude/cache-touch.js +75 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
- package/dist/agent-adapter/claude/event-parser.js +33 -17
- package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
- package/dist/agent-adapter/claude/event-translator.js +2 -0
- package/dist/agent-adapter/claude/session-options.d.ts +0 -4
- package/dist/agent-adapter/claude/session-options.js +0 -9
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +2 -5
- package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
- package/dist/agent-adapter/claude/transcript-clear.js +217 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
- package/dist/agent-adapter/claude/turn-machine.js +21 -68
- package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
- package/dist/agent-adapter/claude/window-warmup.js +38 -0
- package/dist/agent-adapter/continuation-phase.js +3 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
- package/dist/agent-adapter/pi/event-parser.js +43 -27
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
- package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
- package/dist/agent-adapter/pi/pi-session.js +15 -0
- package/dist/agent-adapter/pi/session-options.d.ts +2 -6
- package/dist/agent-adapter/pi/session-options.js +2 -11
- package/dist/agent-adapter/run-events.d.ts +10 -0
- package/dist/agent-adapter/run-events.js +2 -0
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/client-bundle/manifest.json +1 -1
- package/dist/core/locales/en.d.ts +1 -0
- package/dist/core/locales/slices/commands.d.ts +1 -0
- package/dist/core/locales/slices/commands.js +2 -0
- package/dist/core/settings-spec.d.ts +25 -0
- package/dist/core/settings-spec.js +34 -0
- package/dist/domain/agents/engine-selection.js +1 -1
- package/dist/domain/agents/subagent/registry.d.ts +2 -0
- package/dist/domain/agents/subagent/registry.js +8 -0
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/browser/broker.d.ts +99 -0
- package/dist/domain/browser/broker.js +487 -0
- package/dist/domain/costs/claude-account.js +21 -0
- package/dist/domain/costs/rate-limit-throttle.js +3 -1
- package/dist/domain/costs/reset-account.d.ts +2 -0
- package/dist/domain/costs/usage-service.d.ts +1 -1
- package/dist/domain/costs/usage-service.js +20 -7
- package/dist/domain/mcp/tools/ui-file.js +1 -1
- package/dist/domain/remote/device-browser.js +1 -1
- package/dist/domain/remote/device-chrome-commands.js +2 -0
- package/dist/domain/remote/device-port.js +2 -2
- package/dist/domain/runs/builders.d.ts +2 -2
- package/dist/domain/runs/builders.js +2 -3
- package/dist/domain/runs/engine-spec.d.ts +5 -0
- package/dist/domain/runs/engine-spec.js +1 -2
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-lifecycle.d.ts +0 -4
- package/dist/domain/sessions/session-lifecycle.js +1 -1
- package/dist/domain/system/own-bin-path.d.ts +13 -0
- package/dist/domain/system/own-bin-path.js +36 -0
- package/dist/domain/system/terminal-cli/index.d.ts +58 -0
- package/dist/domain/system/terminal-cli/index.js +100 -0
- package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
- package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
- package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
- package/dist/domain/system/terminal-cli/registrar.js +1 -0
- package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
- package/dist/domain/system/terminal-cli/shims.js +108 -0
- package/dist/domain/system/terminal-cli/state.d.ts +7 -0
- package/dist/domain/system/terminal-cli/state.js +36 -0
- package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
- package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
- package/dist/domain/tui-session/tui-session-service.js +1 -1
- package/dist/domain/tui-session/types.d.ts +1 -1
- package/dist/domain/ui-service/app-router.d.ts +17 -6
- package/dist/domain/ui-service/app-router.js +3 -1
- package/dist/domain/ui-service/assistant-snapshots.js +2 -0
- package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
- package/dist/domain/ui-service/inline-media-types.js +1 -0
- package/dist/domain/ui-service/input-schemas.d.ts +17 -17
- package/dist/domain/ui-service/input-schemas.js +9 -9
- package/dist/domain/ui-service/mutate/models.d.ts +3 -0
- package/dist/domain/ui-service/mutate/models.js +21 -2
- package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
- package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
- package/dist/domain/ui-service/mutate/sessions.js +1 -4
- package/dist/domain/ui-service/query/sessions.js +1 -1
- package/dist/domain/ui-service/types.d.ts +8 -10
- package/dist/domain/ui-service/ui-service.d.ts +9 -6
- package/dist/domain/ui-service/ui-service.js +4 -1
- package/dist/entry/app.js +23 -0
- package/dist/entry/browser-cli.d.ts +39 -0
- package/dist/entry/browser-cli.js +317 -0
- package/dist/entry/cli-help.d.ts +1 -0
- package/dist/entry/cli-help.js +30 -0
- package/dist/entry/cli.js +2 -0
- package/dist/entry/daemon.js +2 -0
- package/dist/entry/path-cli.d.ts +4 -0
- package/dist/entry/path-cli.js +65 -0
- package/dist/entry/shutdown.js +7 -0
- package/dist/entry/start-ui-http.js +8 -0
- package/dist/entry/ui-service-wiring.js +2 -0
- package/dist/events/event-types.d.ts +2 -1
- package/dist/orchestration/agent-runner.d.ts +2 -2
- package/dist/orchestration/agent-runner.js +6 -6
- package/dist/orchestration/browser-webhook.d.ts +11 -0
- package/dist/orchestration/browser-webhook.js +28 -0
- package/dist/orchestration/cache-keep-warm.d.ts +77 -0
- package/dist/orchestration/cache-keep-warm.js +213 -0
- package/dist/orchestration/claude-window-warmup.d.ts +40 -0
- package/dist/orchestration/claude-window-warmup.js +126 -0
- package/dist/orchestration/conversation-request.d.ts +4 -7
- package/dist/orchestration/conversation-request.js +1 -2
- package/dist/orchestration/delta-coalescer.d.ts +4 -2
- package/dist/orchestration/delta-coalescer.js +5 -5
- package/dist/orchestration/edit-retry.js +3 -6
- package/dist/orchestration/inline-media-eager.d.ts +13 -0
- package/dist/orchestration/inline-media-eager.js +58 -0
- package/dist/orchestration/inline-media.d.ts +22 -0
- package/dist/orchestration/inline-media.js +151 -0
- package/dist/orchestration/interactions/ask-user-resume.js +3 -7
- package/dist/orchestration/routing/commands/usage-format.js +3 -0
- package/dist/orchestration/routing/webhook.js +4 -0
- package/dist/orchestration/session-compact.js +5 -7
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/transcript-sink.d.ts +6 -0
- package/dist/orchestration/transcript-sink.js +21 -2
- package/dist/orchestration/turn/turn-prep.d.ts +0 -8
- package/dist/orchestration/turn/turn-prep.js +0 -51
- package/dist/orchestration/turn/turn.js +4 -0
- package/dist/platform/adapters/tui/ports.d.ts +1 -1
- package/dist/platform/adapters/tui/tui-transcript.js +2 -0
- package/dist/platform/browser/agent-browser.d.ts +50 -0
- package/dist/platform/browser/agent-browser.js +165 -0
- package/dist/platform/browser/managed-browser.d.ts +1 -11
- package/dist/platform/browser/managed-browser.js +4 -12
- package/dist/platform/ui-http/browser-stream.d.ts +110 -0
- package/dist/platform/ui-http/browser-stream.js +447 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
- package/dist/platform/ui-http/ui-http-server.js +23 -6
- package/dist/store/conversation-history-reader.js +8 -0
- package/dist/store/conversation-history-repo.d.ts +8 -1
- package/dist/store/conversation-history-repo.js +5 -0
- package/dist/store/session-registry-journal.d.ts +0 -8
- package/dist/store/session-registry-journal.js +5 -17
- package/dist/store/session-registry-repo.d.ts +2 -3
- package/dist/store/session-registry-repo.js +0 -2
- package/package.json +4 -2
- package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
- package/web/dist/assets/index-CaSZPg_H.css +1 -0
- package/web/dist/assets/index-CzOR7Edh.js +522 -0
- package/web/dist/assets/{index-DaViXAg-.js → index-cIGFv27z.js} +1 -1
- package/web/dist/index.html +3 -2
- package/web/dist/theme.css +6 -0
- package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
- package/dist/agent-adapter/browser-mcp-server.js +0 -28
- package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
- package/dist/agent-adapter/claude/browser-mcp.js +0 -10
- package/web/dist/assets/index-Cgx3gdHV.css +0 -1
- package/web/dist/assets/index-CpZWBVHr.js +0 -494
|
@@ -4,12 +4,12 @@ description: "Open and keep a board: the live HTML status page the Web UI shows
|
|
|
4
4
|
allowed-tools: Read, Edit, Write, Bash, mcp__cortex-core__board_open, mcp__cortex-core__send_decision, mcp__cortex-core__current_time, mcp__cortex-core__cortex_context
|
|
5
5
|
metadata:
|
|
6
6
|
author: "Cortex"
|
|
7
|
-
version: "1.
|
|
7
|
+
version: "1.5.1"
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
# Board
|
|
11
11
|
|
|
12
|
-
A board is one HTML page per long task, shown in the Web UI beside the conversation and on the phone. The app draws a live strip above the page by itself:
|
|
12
|
+
A board is one HTML page per long task, shown in the Web UI beside the conversation and on the phone. The app names the board and draws a live strip above the page by itself: every bound session's status, questions waiting for the user, and the decision stream from `send_decision`. You write the page body: what the task is, where it stands, what comes next, and what needs the user. Someone glancing at it for five seconds should know whether things are on track.
|
|
13
13
|
|
|
14
14
|
## When to open one
|
|
15
15
|
|
|
@@ -37,11 +37,14 @@ A session is bound to at most one board. The tool returns the board directory; l
|
|
|
37
37
|
|
|
38
38
|
## Writing the page
|
|
39
39
|
|
|
40
|
-
- **Open with the head
|
|
40
|
+
- **Open with the head**: title, an overall state chip, and a one-line `.lead` saying where things stand. Keep the lead current; it is what the user reads first.
|
|
41
41
|
- **Replace the scaffold's examples** with real content on the first fill, and delete sections that do not apply.
|
|
42
|
-
- **Use the preset classes** below. They follow the user's theme (light/dark, palette, accent) without any work from you. When
|
|
43
|
-
- **Images** go in `assets/` and are referenced relatively: `<img src="assets/loss.png" alt="loss curve">`. The app inlines
|
|
42
|
+
- **Use the preset classes** below. They follow the user's theme (light/dark, palette, accent) without any work from you. The page reads as one document: each `card` is a section under its `h` heading, set apart by space rather than a box, and only a `callout` is boxed, for something the user has to act on. When the classes do not fit, write your own HTML, inline SVG charts, or a little inline `style`, and take colours from theme variables (`var(--proto-accent)`, `var(--proto-muted)`, …) rather than fixed values so the page still reads in dark mode.
|
|
43
|
+
- **Images** go in `assets/` and are referenced relatively: `<img src="assets/loss.png" alt="loss curve">`. A click opens any board image full size in the app's viewer, so a thumbnail need not be readable at board size; put a set of screenshots or plots in a `gallery`. The app inlines each image up to 2 MB, so resize or compress larger screenshots; a larger one shows as a dashed box that still opens on click. Wrap an image in `<a data-open="…">` to open something else instead.
|
|
44
|
+
- **Videos**: `<video src="assets/rollout.mp4" poster="assets/rollout.jpg" controls></video>`. Up to 2 MB plays in place; a larger one shows as a play tile (its `poster` frame, if any) that plays it in the app's viewer.
|
|
45
|
+
- **Formulas**: `<span class="tex">\mathcal{L} = \lVert x - \hat{x} \rVert^2</span>` inline, `<div class="tex">…</div>` on a line of its own. Write the TeX as text, with `<` as `<`; the app renders it with KaTeX, as in the chat. Do not use `$…$`: nothing on a board reads it.
|
|
44
46
|
- **Outputs**: put a file the user should open into the board's `assets/` and link it with `<a data-open="assets/report.md">report.md</a>`; a click opens it in the app. `data-open` only reaches files inside the board directory, so name anything elsewhere as path text without a link: `<code>experiments/run-12/metrics.json</code>`. Ordinary `https://` links open in the browser.
|
|
47
|
+
- **Type**: everything is in the app's face; the mono face (`code`, `pre`, `mono`, a row's `.id`) is only for code, paths, ids and hashes, never for names, times, numbers or labels. Headings and table headers are in sentence case, not capitals.
|
|
45
48
|
- **Keep it static.** The page runs in a sandbox; scripts are not needed for anything the presets do.
|
|
46
49
|
- **Decisions**: record them with `send_decision`; the strip shows them. On the page, keep at most a short "key decisions" row list.
|
|
47
50
|
- Write in the user's language.
|
|
@@ -49,16 +52,16 @@ A session is bound to at most one board. The tool returns the board directory; l
|
|
|
49
52
|
|
|
50
53
|
### States
|
|
51
54
|
|
|
52
|
-
One vocabulary across `chip`, `step`, `meter i`, `legend .sw` and `ic
|
|
55
|
+
One vocabulary across `chip`, `step`, `meter i`, `legend .sw` and `ic`. It is the app's own status-dot language:
|
|
53
56
|
|
|
54
57
|
| modifier | meaning | look |
|
|
55
58
|
|---|---|---|
|
|
56
|
-
| `ok` | done | success green |
|
|
57
|
-
| `run` | in progress | accent |
|
|
58
|
-
| `ask` | waiting on the user (a question, a review, a go/no-go) |
|
|
59
|
-
| `wait` | blocked on a machine or someone else: queue, GPU, rate limit, external review | hollow
|
|
59
|
+
| `ok` | done | success green; a check in a step |
|
|
60
|
+
| `run` | in progress | accent, with a soft halo |
|
|
61
|
+
| `ask` | waiting on the user (a question, a review, a go/no-go) | amber; nothing else on the page is amber |
|
|
62
|
+
| `wait` | blocked on a machine or someone else: queue, GPU, rate limit, external review | hollow ring |
|
|
60
63
|
| `bad` | failed, unexpected, risk | danger red |
|
|
61
|
-
| none | not started | gray |
|
|
64
|
+
| none | not started | faint gray |
|
|
62
65
|
|
|
63
66
|
Use `ask` only for things truly waiting on the user, so the amber stays meaningful.
|
|
64
67
|
|
|
@@ -66,21 +69,26 @@ Use `ask` only for things truly waiting on the user, so the amber stays meaningf
|
|
|
66
69
|
|
|
67
70
|
| class | use | shape |
|
|
68
71
|
|---|---|---|
|
|
69
|
-
| `stack` | vertical spacing between
|
|
70
|
-
| `card` | a
|
|
71
|
-
| `
|
|
72
|
-
| `
|
|
73
|
-
| `
|
|
72
|
+
| `stack` | vertical spacing between sections | `<div class="stack">…cards…</div>` |
|
|
73
|
+
| `card` | a section of the page, one topic each: plain, no box | `<div class="card">…</div>` |
|
|
74
|
+
| `callout` | the one boxed panel, for something the user has to act on; `callout ask` tints it amber | `<div class="card callout ask"><div class="h">Needs you</div>…</div>` |
|
|
75
|
+
| `grid`, `grid wide-left` | sections side by side (auto columns; `wide-left` is 1.3 : 1) | `<div class="grid wide-left"><div class="card">…</div><div class="stack">…</div></div>` |
|
|
76
|
+
| `h`, `.n` | section heading, optional count or note in a quieter tone | `<div class="h">Acceptance <span class="n">3 / 11</span></div>` |
|
|
77
|
+
| `kicker`, `.meta` | optional muted line above the title: scope, with the updated time on the right | `<div class="kicker">Project · scope<span class="meta">updated MM-DD HH:MM</span></div>` |
|
|
78
|
+
| `head`, `.meta` | title line with the overall state; `.meta` (right-aligned) when there is no kicker | `<div class="head"><h1>Title</h1><span class="chip run">in progress</span></div>` |
|
|
74
79
|
| `lead` | the one-line status under the head; `<b>` for the key fact | `<div class="lead"><b>Stage B merged.</b> C waits for a GPU.</div>` |
|
|
75
|
-
| `chip` + state | a state label | `<span class="chip wait">waiting</span>` |
|
|
80
|
+
| `chip` + state | a state label: a status dot and a word | `<span class="chip wait">waiting</span>` |
|
|
76
81
|
| `meter`, `legend .sw` | progress, one `<i>` per unit | `<div class="meter"><i class="ok"></i><i class="run"></i><i></i></div>` and `<div class="legend"><span><span class="sw ok"></span>done 1</span></div>` |
|
|
77
|
-
| `steps` > `step` + state |
|
|
78
|
-
| `rows` > `row` | lists of acceptance criteria, checkpoints, decisions, risks, outputs: `.id
|
|
82
|
+
| `steps` > `step` + state | stages, as rows in two columns: the step's state draws its icon column, `.top` (`.k` name + chip), `.t` what it delivers, `.m` a fact | `<div class="step run"><div class="top"><span class="k">C</span><span class="chip run">running</span></div><div class="t">…</div><div class="m">2 / 5</div></div>` |
|
|
83
|
+
| `rows` > `row` | lists of acceptance criteria, checkpoints, decisions, risks, outputs: `.id` (mono), `.body` (with `.sub` second line), `.end` right-aligned meta | `<div class="row"><span class="ic ok">✓</span><span class="id">A-2</span><span class="body">…<span class="sub">…</span></span><span class="end">4a85587c</span></div>` |
|
|
79
84
|
| `ic` + state, `ic risk`, `ic todo` | the icon at the start of a row; you choose the glyph (✓ ◐ ● ◌ ▲ ○) | `<span class="ic risk">▲</span>` |
|
|
80
|
-
| `tl` | a timeline
|
|
81
|
-
| `
|
|
85
|
+
| `tl` | a timeline section: each row starts with `.when` | `<div class="card tl"><div class="rows"><div class="row"><span class="when">MM-DD HH:MM</span><span class="chip ok">done</span><span class="body">…</span></div></div></div>` |
|
|
86
|
+
| `gallery` > `figure` | same-size thumbnails of images or videos, each with an optional `figcaption`; `style="--b-thumb:240px"` sets the minimum column width (default 160px) | `<div class="gallery"><figure><img src="assets/a.png" alt="…"><figcaption>run-12 · loss</figcaption></figure>…</div>` |
|
|
87
|
+
| `tex` on a `span` / `div` | a formula, inline or on its own line | `<span class="tex">\alpha_t</span>`, `<div class="tex">\frac{a}{b}</div>` |
|
|
88
|
+
| `tbl`, `num` | a table in a wrapper that scrolls sideways instead of squeezing: headers and `num` cells stay on one line, so wrap any table wider than a phone in it; `num` right-aligns a numeric `th`/`td` | `<div class="tbl"><table><tr><th>Run</th><th class="num">Success</th></tr><tr><td>run-12</td><td class="num">0.84</td></tr></table></div>` |
|
|
89
|
+
| `mono`, `muted`, `faint`, `code` | the code face (code only) and text tones; inline code | `<span class="muted">…</span>`, `<code>path</code>` |
|
|
82
90
|
|
|
83
|
-
Plain `p`, `ul`, `table` and `
|
|
91
|
+
Plain `p`, `ul`, `table`, `img`, `figure` and `pre` are styled to match; `pre` (a log tail, a command) scrolls in place rather than widening the page. The scaffold written by `board_open` has a working example of each component.
|
|
84
92
|
|
|
85
93
|
## When to update
|
|
86
94
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "cortex-system",
|
|
4
|
-
"version": "0.
|
|
5
|
-
"description": "Cortex system skill bundle — approval / client-manage / project-init / schedule / user-learn."
|
|
4
|
+
"version": "0.7.0",
|
|
5
|
+
"description": "Cortex system skill bundle — approval / browser / client-manage / project-init / schedule / user-learn."
|
|
6
6
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: browser
|
|
3
|
+
description: "Use whenever a task needs a real web browser: verifying or inspecting a web UI (a dev server, a Cortex page, a deployed site), taking a screenshot of a page, reading a page that needs JavaScript or a login, clicking through or operating a website, filling in forms, or checking what a user sees on their own machine. Drive it with the `cortex-browser` CLI."
|
|
4
|
+
metadata:
|
|
5
|
+
author: "Cortex"
|
|
6
|
+
version: "1.1.1"
|
|
7
|
+
date: "2026-10-19"
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Browser
|
|
11
|
+
|
|
12
|
+
`cortex-browser` is agent-browser attached to a Chrome that Cortex manages. Every session (and
|
|
13
|
+
every worker or subagent) gets its own tab, kept between turns. After 10 minutes without a
|
|
14
|
+
`cortex-browser` call the tab is closed, and the next call starts on a blank page, so reopen the URL
|
|
15
|
+
you need. Logins live in the browser profile, not the tab, and survive that and later sessions.
|
|
16
|
+
|
|
17
|
+
## Commands
|
|
18
|
+
|
|
19
|
+
Everything except `--device` is passed to agent-browser. Its full, version-matched guide is one
|
|
20
|
+
command away; read it before anything beyond open/snapshot/click rather than guessing flags:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cortex-browser skills get core # workflow and common commands
|
|
24
|
+
cortex-browser skills get core --full # every command and option
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The guide is written for plain `agent-browser`: run its examples as `cortex-browser`, and skip its
|
|
28
|
+
advice on `--session`, `--cdp`, `connect` and launching browsers, which Cortex handles.
|
|
29
|
+
|
|
30
|
+
The usual loop: `cortex-browser open <url>`, then `cortex-browser snapshot -i` to list interactive
|
|
31
|
+
elements as refs (`@e1`, `@e2` …), then `click @e2` / `fill @e3 "text"`. Snapshot again after the
|
|
32
|
+
page changes: refs from an old snapshot go stale.
|
|
33
|
+
|
|
34
|
+
## Which machine
|
|
35
|
+
|
|
36
|
+
- Default is `server`, the Chrome on the Cortex server. There, `localhost` means the server.
|
|
37
|
+
- `--device <name>` uses the Chrome on a connected device instead (its `localhost`, its network,
|
|
38
|
+
its logins), and sticks for the rest of the session. Use it when the user asks for their machine
|
|
39
|
+
or when the page only exists there.
|
|
40
|
+
- Commands still run on the server, so screenshots and other files land on the server either way.
|
|
41
|
+
|
|
42
|
+
When `cortex-browser` exits non-zero (device offline, Chrome failed to start, unknown device), the
|
|
43
|
+
message says why and what to do.
|
|
44
|
+
|
|
45
|
+
## Showing the user
|
|
46
|
+
|
|
47
|
+
`cortex-browser screenshot ./page.png` (relative paths resolve against your working directory;
|
|
48
|
+
`--full` for the whole page), then send it with `send_file`. The user can also watch the browser
|
|
49
|
+
live in the **Agent browser** tab of the Cortex app.
|
|
50
|
+
|
|
51
|
+
## Logins, captchas, 2FA
|
|
52
|
+
|
|
53
|
+
Don't try to get around them. Ask the user to open the **Agent browser** tab, press **Take over**,
|
|
54
|
+
finish the login, and press **Hand back**, then end your turn. When they reply, carry on in the same
|
|
55
|
+
tab. While they are in control, `cortex-browser` refuses with "the user is controlling this
|
|
56
|
+
browser": wait for them rather than retrying.
|
|
@@ -31,11 +31,8 @@ export interface ClaudeSpawnCompatibility {
|
|
|
31
31
|
mcpConfigPaths: string[];
|
|
32
32
|
mcpToolAllowlist: string[] | null;
|
|
33
33
|
supplementalMcpConfigIdentity: string | null;
|
|
34
|
-
/**
|
|
35
|
-
*
|
|
36
|
-
browserMcpConfigIdentity: string | null;
|
|
37
|
-
/** `--disable-slash-commands`. Part of the identity for the same reason as the browser: the skill
|
|
38
|
-
* surface is fixed at spawn, so two agents that differ only here must not share a process. */
|
|
34
|
+
/** `--disable-slash-commands`. Part of the identity because the skill surface is fixed at spawn,
|
|
35
|
+
* so two agents that differ only here must not share a process. */
|
|
39
36
|
disableSkills: boolean;
|
|
40
37
|
/** `--setting-sources`. Null = the CLI's own default set; `[]` = load none. Both are decided at
|
|
41
38
|
* spawn and cannot be re-pointed afterwards. */
|
|
@@ -8,6 +8,7 @@ import { IDLE_SESSION_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
|
|
|
8
8
|
import { claudeRouteIdentity } from './spawn-args.js';
|
|
9
9
|
import { claudeProcessLaunch, launchFromSpec, sessionOptionsFromSpec, } from './session-options.js';
|
|
10
10
|
import { computeTranscriptPath, readRestoredSessionCost, resolveResumeAgainstTranscript } from './transcript-path.js';
|
|
11
|
+
import { clearToolResultsForColdResume } from './transcript-clear.js';
|
|
11
12
|
import { buildPrompt, clearActivePlanFile, createStreamDeltaState, } from './event-parser.js';
|
|
12
13
|
import { BgTaskTracker } from './bg-task-tracker.js';
|
|
13
14
|
import { ClaudeTurnMachine } from './turn-machine.js';
|
|
@@ -44,7 +45,6 @@ function compatibilityFromOptions(options) {
|
|
|
44
45
|
mcpConfigPaths: cloneTextArray(options.mcpConfigPaths),
|
|
45
46
|
mcpToolAllowlist: optionalTextArray(options.mcpToolAllowlist),
|
|
46
47
|
supplementalMcpConfigIdentity: options.supplementalMcpConfigIdentity ?? null,
|
|
47
|
-
browserMcpConfigIdentity: options.browserMcpConfigIdentity ?? null,
|
|
48
48
|
disableSkills: options.disableSkills === true,
|
|
49
49
|
settingSources: optionalTextArray(options.settingSources),
|
|
50
50
|
};
|
|
@@ -66,7 +66,6 @@ export function claudeCompatibilityIdentity(compatibility) {
|
|
|
66
66
|
['tools', compatibility.tools],
|
|
67
67
|
['pluginCapabilityFingerprint', compatibility.pluginCapabilityFingerprint],
|
|
68
68
|
['supplementalMcpConfigIdentity', compatibility.supplementalMcpConfigIdentity],
|
|
69
|
-
['browserMcpConfigIdentity', compatibility.browserMcpConfigIdentity],
|
|
70
69
|
['disableSkills', compatibility.disableSkills],
|
|
71
70
|
['pluginDirs', compatibility.pluginDirs],
|
|
72
71
|
['mcpConfigPaths', compatibility.mcpConfigPaths],
|
|
@@ -178,12 +177,14 @@ class ClaudeSession {
|
|
|
178
177
|
}
|
|
179
178
|
spawnProcess() {
|
|
180
179
|
this.validateSupplementalMcpConfig();
|
|
180
|
+
const { cwd, processSpawner, cliPath } = this.options;
|
|
181
|
+
const transcriptPath = computeTranscriptPath(cwd, this.sessionId);
|
|
182
|
+
if (this.needsResume)
|
|
183
|
+
clearToolResultsForColdResume(transcriptPath, this.sessionId);
|
|
181
184
|
const { args, env } = claudeProcessLaunch({
|
|
182
185
|
channel: this.channel, sessionId: this.sessionId, needsResume: this.needsResume, options: this.options,
|
|
183
186
|
});
|
|
184
|
-
const
|
|
185
|
-
const restoredCost = this.needsResume
|
|
186
|
-
? readRestoredSessionCost(computeTranscriptPath(cwd, this.sessionId), this.sessionId) : 0;
|
|
187
|
+
const restoredCost = this.needsResume ? readRestoredSessionCost(transcriptPath, this.sessionId) : 0;
|
|
187
188
|
this.turns.resetCostBaseline(restoredCost);
|
|
188
189
|
log.info(`Spawning persistent process: ${this.sessionId.substring(0, 8)} ${this.needsResume ? `(resume, restored cost $${restoredCost.toFixed(2)})` : '(new)'}`);
|
|
189
190
|
const spawned = spawnClaudeProcess(processSpawner, args, { cwd, env }, cliPath);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ToolUseSubagent } from '../normalize/event-types.js';
|
|
2
|
+
import type { PendingTurn } from './turn-machine.js';
|
|
3
|
+
import { type StreamDeltaState } from './event-parser.js';
|
|
4
|
+
/** Complete blocks share turn accounting, but thinking never enters the answer/text callbacks. */
|
|
5
|
+
export declare function handleAssistantBlocks(turn: PendingTurn, data: any, state: StreamDeltaState, sessionId: string, subagent?: ToolUseSubagent): void;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createLogger } from '../../core/log.js';
|
|
2
|
+
import { getSettings } from '../../core/settings.js';
|
|
3
|
+
import { isPlanFilePath, setActivePlanFile, takeTextBlockId, takeThinkingBlockId, } from './event-parser.js';
|
|
4
|
+
const log = createLogger('claude-bridge');
|
|
5
|
+
function handleToolBlock(turn, block, sessionId, subagent) {
|
|
6
|
+
if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
|
|
7
|
+
turn.planFilePath = block.input.file_path;
|
|
8
|
+
setActivePlanFile(sessionId, block.input.file_path);
|
|
9
|
+
}
|
|
10
|
+
if (block.name === 'EnterPlanMode')
|
|
11
|
+
turn.enteredPlanMode = true;
|
|
12
|
+
if (block.name === 'ExitPlanMode')
|
|
13
|
+
turn.exitedPlanMode = true;
|
|
14
|
+
try {
|
|
15
|
+
turn.onToolUse?.(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '', subagent);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
log.warn('onToolUse threw:', error.message);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function handleTextBlock(turn, data, block, state, subagent) {
|
|
22
|
+
if (!block.text)
|
|
23
|
+
return;
|
|
24
|
+
const model = typeof data.message?.model === 'string' ? data.message.model : null;
|
|
25
|
+
// Child prose is complete and attributed, never the parent's answer or streamed text cursor.
|
|
26
|
+
if (subagent) {
|
|
27
|
+
turn.onAssistantMessage?.(block.text, undefined, model, subagent);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
turn.finalOutput = block.text;
|
|
31
|
+
if (block.text.length > (turn.longestOutput?.length || 0))
|
|
32
|
+
turn.longestOutput = block.text;
|
|
33
|
+
const blockId = takeTextBlockId(state) ?? undefined;
|
|
34
|
+
const streamedModel = state.messageId === data.message?.id ? state.model : null;
|
|
35
|
+
turn.onAssistantMessage?.(block.text, blockId, model ?? streamedModel);
|
|
36
|
+
}
|
|
37
|
+
function handleThinkingBlock(turn, block, state, subagent) {
|
|
38
|
+
if (subagent)
|
|
39
|
+
return;
|
|
40
|
+
// Consume even suppressed/empty blocks so a later complete event cannot adopt a stale id.
|
|
41
|
+
const blockId = takeThinkingBlockId(state) ?? undefined;
|
|
42
|
+
if (!getSettings().showThinking || typeof block.thinking !== 'string' || !block.thinking)
|
|
43
|
+
return;
|
|
44
|
+
turn.onAssistantThinking?.(block.thinking, blockId);
|
|
45
|
+
}
|
|
46
|
+
/** Complete blocks share turn accounting, but thinking never enters the answer/text callbacks. */
|
|
47
|
+
export function handleAssistantBlocks(turn, data, state, sessionId, subagent) {
|
|
48
|
+
if (subagent)
|
|
49
|
+
turn.subagentTurnCount += 1;
|
|
50
|
+
else
|
|
51
|
+
turn.turnCount += 1;
|
|
52
|
+
const handlers = {
|
|
53
|
+
tool_use: block => handleToolBlock(turn, block, sessionId, subagent),
|
|
54
|
+
text: block => handleTextBlock(turn, data, block, state, subagent),
|
|
55
|
+
thinking: block => handleThinkingBlock(turn, block, state, subagent),
|
|
56
|
+
};
|
|
57
|
+
for (const block of (data.message?.content || []))
|
|
58
|
+
handlers[block.type]?.(block);
|
|
59
|
+
if (!subagent)
|
|
60
|
+
turn.onProgress?.({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
|
|
61
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Readable, Writable } from 'node:stream';
|
|
2
|
+
import type { EngineSpec } from '../types.js';
|
|
3
|
+
export declare const CACHE_REFRESH_PROMPT = "[Cortex cache refresh] Reply with exactly: ok";
|
|
4
|
+
export declare const CACHE_REFRESH_TIMEOUT_MS = 90000;
|
|
5
|
+
export interface CacheRefreshLaunch {
|
|
6
|
+
command: string;
|
|
7
|
+
args: string[];
|
|
8
|
+
env: NodeJS.ProcessEnv;
|
|
9
|
+
cwd: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
transcriptPath: string;
|
|
12
|
+
}
|
|
13
|
+
export interface CacheRefreshUsage {
|
|
14
|
+
inputTokens: number;
|
|
15
|
+
outputTokens: number;
|
|
16
|
+
cacheReadTokens: number;
|
|
17
|
+
cacheWriteTokens: number;
|
|
18
|
+
}
|
|
19
|
+
export interface CacheRefreshResult {
|
|
20
|
+
usage: CacheRefreshUsage;
|
|
21
|
+
model: string | null;
|
|
22
|
+
/** This one request: the fork's total minus the history total it restored. */
|
|
23
|
+
costUsd: number;
|
|
24
|
+
durationMs: number;
|
|
25
|
+
}
|
|
26
|
+
/** The slice of a child process the refresh drives; `child_process.spawn` returns one. */
|
|
27
|
+
export interface CacheRefreshChild {
|
|
28
|
+
stdin: Writable | null;
|
|
29
|
+
stdout: Readable | null;
|
|
30
|
+
stderr: Readable | null;
|
|
31
|
+
exitCode: number | null;
|
|
32
|
+
signalCode: NodeJS.Signals | null;
|
|
33
|
+
kill(signal?: NodeJS.Signals): boolean;
|
|
34
|
+
on(event: 'error', listener: (error: Error) => void): this;
|
|
35
|
+
on(event: 'close', listener: (code: number | null) => void): this;
|
|
36
|
+
}
|
|
37
|
+
export type CacheRefreshSpawn = (command: string, args: string[], options: {
|
|
38
|
+
cwd: string;
|
|
39
|
+
env: NodeJS.ProcessEnv;
|
|
40
|
+
}) => CacheRefreshChild;
|
|
41
|
+
export interface CacheRefreshDeps {
|
|
42
|
+
spawn?: CacheRefreshSpawn;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
now?: () => number;
|
|
45
|
+
}
|
|
46
|
+
/** The launch's session identity (`--session-id X` or `--resume X`) turned into a one-turn fork of
|
|
47
|
+
* X that persists nothing. Throws when the argv does not name X. */
|
|
48
|
+
export declare function forkRefreshArgs(args: readonly string[], sessionId: string): string[];
|
|
49
|
+
/**
|
|
50
|
+
* The fork's command line: the launch the session's next turn would spawn, resumed, without
|
|
51
|
+
* hooks. Hooks run Cortex scripts against the session's identity and add nothing to the cached
|
|
52
|
+
* prefix, which is the system prompt, the tools and the transcript.
|
|
53
|
+
*/
|
|
54
|
+
export declare function cacheRefreshLaunch(spec: EngineSpec): CacheRefreshLaunch;
|
|
55
|
+
/** A resumed fork's `total_cost_usd` carries the session's restored history; this is the rest. */
|
|
56
|
+
export declare function refreshCost(totalCostUsd: unknown, restoredUsd: number): number;
|
|
57
|
+
/** Run one refresh fork to its result. */
|
|
58
|
+
export declare function runCacheRefresh(launch: CacheRefreshLaunch, deps?: CacheRefreshDeps): Promise<CacheRefreshResult>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { claudeProcessLaunch, launchFromSpec } from './session-options.js';
|
|
4
|
+
import { computeTranscriptPath, readRestoredSessionCost } from './transcript-path.js';
|
|
5
|
+
// A keep-warm refresh: one request on a fork of an idle session, so the session's one-hour prompt
|
|
6
|
+
// cache is read (which restarts its clock) without the session's own transcript changing. The fork
|
|
7
|
+
// resumes the transcript, sends one short message, persists nothing, and is gone after its result.
|
|
8
|
+
export const CACHE_REFRESH_PROMPT = '[Cortex cache refresh] Reply with exactly: ok';
|
|
9
|
+
export const CACHE_REFRESH_TIMEOUT_MS = 90_000;
|
|
10
|
+
/** How long a fork may take to exit once its stdin closes, before it is killed. */
|
|
11
|
+
const EXIT_GRACE_MS = 10_000;
|
|
12
|
+
const FORK_FLAGS = ['--fork-session', '--no-session-persistence', '--max-turns', '1'];
|
|
13
|
+
/** The launch's session identity (`--session-id X` or `--resume X`) turned into a one-turn fork of
|
|
14
|
+
* X that persists nothing. Throws when the argv does not name X. */
|
|
15
|
+
export function forkRefreshArgs(args, sessionId) {
|
|
16
|
+
const at = args.findIndex((arg, i) => (arg === '--session-id' || arg === '--resume') && args[i + 1] === sessionId);
|
|
17
|
+
if (at === -1)
|
|
18
|
+
throw new Error(`launch does not name session ${sessionId}`);
|
|
19
|
+
return [...args.slice(0, at), '--resume', sessionId, ...FORK_FLAGS, ...args.slice(at + 2)];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The fork's command line: the launch the session's next turn would spawn, resumed, without
|
|
23
|
+
* hooks. Hooks run Cortex scripts against the session's identity and add nothing to the cached
|
|
24
|
+
* prefix, which is the system prompt, the tools and the transcript.
|
|
25
|
+
*/
|
|
26
|
+
export function cacheRefreshLaunch(spec) {
|
|
27
|
+
const sessionId = spec.resume.backendSessionId;
|
|
28
|
+
if (!sessionId)
|
|
29
|
+
throw new Error('cache refresh needs a backend session to resume');
|
|
30
|
+
const launch = launchFromSpec(spec);
|
|
31
|
+
const options = { ...launch.options, disableHooks: true };
|
|
32
|
+
const { args, env } = claudeProcessLaunch({
|
|
33
|
+
channel: launch.channel, sessionId, needsResume: true, options,
|
|
34
|
+
});
|
|
35
|
+
return {
|
|
36
|
+
command: options.cliPath ?? 'claude',
|
|
37
|
+
args: forkRefreshArgs(args, sessionId),
|
|
38
|
+
env,
|
|
39
|
+
cwd: options.cwd,
|
|
40
|
+
sessionId,
|
|
41
|
+
transcriptPath: computeTranscriptPath(options.cwd, sessionId),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** A resumed fork's `total_cost_usd` carries the session's restored history; this is the rest. */
|
|
45
|
+
export function refreshCost(totalCostUsd, restoredUsd) {
|
|
46
|
+
if (typeof totalCostUsd !== 'number' || !Number.isFinite(totalCostUsd))
|
|
47
|
+
return 0;
|
|
48
|
+
return Math.max(0, totalCostUsd - restoredUsd);
|
|
49
|
+
}
|
|
50
|
+
function tokens(value) {
|
|
51
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
52
|
+
}
|
|
53
|
+
function usageOf(usage) {
|
|
54
|
+
return {
|
|
55
|
+
inputTokens: tokens(usage?.input_tokens),
|
|
56
|
+
outputTokens: tokens(usage?.output_tokens),
|
|
57
|
+
cacheReadTokens: tokens(usage?.cache_read_input_tokens),
|
|
58
|
+
cacheWriteTokens: tokens(usage?.cache_creation_input_tokens),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function parseRecord(line) {
|
|
62
|
+
try {
|
|
63
|
+
const record = JSON.parse(line);
|
|
64
|
+
return record && typeof record === 'object' ? record : null;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Once the result is in, close stdin so the CLI exits; kill it if it lingers. */
|
|
71
|
+
function release(child) {
|
|
72
|
+
child.stdin?.end();
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
75
|
+
child.kill('SIGKILL');
|
|
76
|
+
}, EXIT_GRACE_MS);
|
|
77
|
+
timer.unref?.();
|
|
78
|
+
child.on('close', () => clearTimeout(timer));
|
|
79
|
+
}
|
|
80
|
+
/** The fork's `result` record and the model that answered, or a rejection on timeout, a spawn
|
|
81
|
+
* error, or an exit before the result. A timeout kills the fork. */
|
|
82
|
+
function readForkResult(child, timeoutMs) {
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
let model = null;
|
|
85
|
+
let stderr = '';
|
|
86
|
+
let done = false;
|
|
87
|
+
const finish = (error, result) => {
|
|
88
|
+
if (done)
|
|
89
|
+
return;
|
|
90
|
+
done = true;
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
if (error)
|
|
93
|
+
reject(error);
|
|
94
|
+
else
|
|
95
|
+
resolve({ result: result, model });
|
|
96
|
+
};
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
child.kill();
|
|
99
|
+
finish(new Error(`no result within ${timeoutMs}ms`));
|
|
100
|
+
}, timeoutMs);
|
|
101
|
+
createInterface({ input: child.stdout }).on('line', (line) => {
|
|
102
|
+
const record = parseRecord(line);
|
|
103
|
+
if (record?.type === 'assistant')
|
|
104
|
+
model ??= record.message?.model ?? null;
|
|
105
|
+
if (record?.type === 'result')
|
|
106
|
+
finish(null, record);
|
|
107
|
+
});
|
|
108
|
+
child.stderr?.on('data', (data) => { stderr = (stderr + String(data)).slice(-500); });
|
|
109
|
+
child.on('error', (error) => finish(error));
|
|
110
|
+
child.on('close', (code) => finish(new Error(`exited ${code} before a result: ${stderr.trim()}`)));
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
function checkResult(result) {
|
|
114
|
+
// `--max-turns 1` ends a reply that reached for a tool as an error, but its request still ran.
|
|
115
|
+
if (result.is_error !== true || result.subtype === 'error_max_turns')
|
|
116
|
+
return;
|
|
117
|
+
throw new Error(`refresh failed: ${String(result.result ?? result.subtype).slice(0, 300)}`);
|
|
118
|
+
}
|
|
119
|
+
function writePrompt(child) {
|
|
120
|
+
// A fork that dies at once fails the write with EPIPE; its exit already rejects the refresh.
|
|
121
|
+
child.stdin.on('error', () => { });
|
|
122
|
+
const message = { type: 'user', message: { role: 'user', content: CACHE_REFRESH_PROMPT } };
|
|
123
|
+
child.stdin.write(JSON.stringify(message) + '\n');
|
|
124
|
+
}
|
|
125
|
+
/** Run one refresh fork to its result. */
|
|
126
|
+
export async function runCacheRefresh(launch, deps = {}) {
|
|
127
|
+
const now = deps.now ?? Date.now;
|
|
128
|
+
const restoredUsd = readRestoredSessionCost(launch.transcriptPath, launch.sessionId);
|
|
129
|
+
const started = now();
|
|
130
|
+
const child = (deps.spawn ?? defaultSpawn)(launch.command, launch.args, { cwd: launch.cwd, env: launch.env });
|
|
131
|
+
const output = readForkResult(child, deps.timeoutMs ?? CACHE_REFRESH_TIMEOUT_MS);
|
|
132
|
+
writePrompt(child);
|
|
133
|
+
const { result, model } = await output;
|
|
134
|
+
release(child);
|
|
135
|
+
checkResult(result);
|
|
136
|
+
return {
|
|
137
|
+
usage: usageOf(result.usage),
|
|
138
|
+
model,
|
|
139
|
+
costUsd: refreshCost(result.total_cost_usd, restoredUsd),
|
|
140
|
+
durationMs: now() - started,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function defaultSpawn(command, args, options) {
|
|
144
|
+
return spawn(command, args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
145
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare function noteCacheRefresh(backendSessionId: string, at?: number): void;
|
|
2
|
+
/**
|
|
3
|
+
* When the session last talked to the model: the newest timestamped record in its transcript.
|
|
4
|
+
* Not the file's mtime — the CLI appends untimestamped `last-prompt`/`cost-state` entries when its
|
|
5
|
+
* process exits, which for an idle-closed session is an hour after the last request. Falls back to
|
|
6
|
+
* the mtime when the tail holds no timestamped record. Null when the transcript is missing.
|
|
7
|
+
*/
|
|
8
|
+
export declare function lastModelActivity(transcriptPath: string): number | null;
|
|
9
|
+
/** When the session's prompt cache was last read or written: its last model activity or a later
|
|
10
|
+
* keep-warm refresh. Null when neither is known. */
|
|
11
|
+
export declare function lastCacheTouch(transcriptPath: string, backendSessionId: string): number | null;
|
|
12
|
+
export declare function resetCacheTouches(): void;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
+
const TAIL_BYTES = 512 * 1024;
|
|
3
|
+
// A keep-warm refresh reads the cached prefix through a fork that never writes the transcript, so
|
|
4
|
+
// the transcript alone says the cache went cold earlier than it did. In memory only: a restart
|
|
5
|
+
// loses it, and the worst case is one cold-resume clearing that a warm cache did not need.
|
|
6
|
+
const refreshedAt = new Map();
|
|
7
|
+
export function noteCacheRefresh(backendSessionId, at = Date.now()) {
|
|
8
|
+
refreshedAt.set(backendSessionId, at);
|
|
9
|
+
}
|
|
10
|
+
function lastTimestampIn(text) {
|
|
11
|
+
const lines = text.split('\n');
|
|
12
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
13
|
+
const line = lines[i];
|
|
14
|
+
if (!line.includes('"timestamp"'))
|
|
15
|
+
continue;
|
|
16
|
+
try {
|
|
17
|
+
const record = JSON.parse(line);
|
|
18
|
+
if (typeof record.timestamp !== 'string')
|
|
19
|
+
continue;
|
|
20
|
+
// The CLI writes these itself (interrupts, local errors) without calling the model.
|
|
21
|
+
if (record.message?.model === '<synthetic>')
|
|
22
|
+
continue;
|
|
23
|
+
const at = Date.parse(record.timestamp);
|
|
24
|
+
if (Number.isFinite(at))
|
|
25
|
+
return at;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* When the session last talked to the model: the newest timestamped record in its transcript.
|
|
35
|
+
* Not the file's mtime — the CLI appends untimestamped `last-prompt`/`cost-state` entries when its
|
|
36
|
+
* process exits, which for an idle-closed session is an hour after the last request. Falls back to
|
|
37
|
+
* the mtime when the tail holds no timestamped record. Null when the transcript is missing.
|
|
38
|
+
*/
|
|
39
|
+
export function lastModelActivity(transcriptPath) {
|
|
40
|
+
let fd;
|
|
41
|
+
try {
|
|
42
|
+
fd = openSync(transcriptPath, 'r');
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const stat = fstatSync(fd);
|
|
49
|
+
const start = Math.max(0, stat.size - TAIL_BYTES);
|
|
50
|
+
const buf = Buffer.alloc(stat.size - start);
|
|
51
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
52
|
+
let text = buf.toString('utf8');
|
|
53
|
+
if (start > 0)
|
|
54
|
+
text = text.slice(text.indexOf('\n') + 1);
|
|
55
|
+
return lastTimestampIn(text) ?? stat.mtimeMs;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
closeSync(fd);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** When the session's prompt cache was last read or written: its last model activity or a later
|
|
65
|
+
* keep-warm refresh. Null when neither is known. */
|
|
66
|
+
export function lastCacheTouch(transcriptPath, backendSessionId) {
|
|
67
|
+
const activity = lastModelActivity(transcriptPath);
|
|
68
|
+
const refreshed = refreshedAt.get(backendSessionId) ?? null;
|
|
69
|
+
if (activity === null)
|
|
70
|
+
return refreshed;
|
|
71
|
+
return refreshed === null ? activity : Math.max(activity, refreshed);
|
|
72
|
+
}
|
|
73
|
+
export function resetCacheTouches() {
|
|
74
|
+
refreshedAt.clear();
|
|
75
|
+
}
|
|
@@ -14,13 +14,17 @@ export interface StreamDeltaState {
|
|
|
14
14
|
model: string | null;
|
|
15
15
|
/** blockId of the text block currently open, awaiting its complete `assistant` event. */
|
|
16
16
|
textBlockId: string | null;
|
|
17
|
+
/** Independent cursor for complete thinking summaries. */
|
|
18
|
+
thinkingBlockId: string | null;
|
|
17
19
|
}
|
|
18
20
|
export declare function createStreamDeltaState(): StreamDeltaState;
|
|
19
|
-
|
|
20
|
-
export declare function parseStreamEvent(data: any, state: StreamDeltaState): {
|
|
21
|
+
export type StreamDelta = {
|
|
21
22
|
text: string;
|
|
22
23
|
blockId: string;
|
|
23
|
-
|
|
24
|
+
kind?: 'thinking';
|
|
25
|
+
};
|
|
26
|
+
/** Translate a partial stdout event while advancing only its own block cursor. */
|
|
27
|
+
export declare function parseStreamEvent(data: any, state: StreamDeltaState): StreamDelta | null;
|
|
24
28
|
/**
|
|
25
29
|
* Consume the blockId of the streamed text block that the complete `assistant` event now being
|
|
26
30
|
* handled belongs to. Returns null when nothing streamed (kill switch, older CLI, thinking-only
|
|
@@ -30,6 +34,7 @@ export declare function parseStreamEvent(data: any, state: StreamDeltaState): {
|
|
|
30
34
|
* can never re-adopt a stale id.
|
|
31
35
|
*/
|
|
32
36
|
export declare function takeTextBlockId(state: StreamDeltaState): string | null;
|
|
37
|
+
export declare function takeThinkingBlockId(state: StreamDeltaState): string | null;
|
|
33
38
|
export declare function formatAssistantEvent(data: any): string | null;
|
|
34
39
|
export declare function formatUserEvent(data: any): string | null;
|
|
35
40
|
export declare function formatResultEvent(data: any): string;
|