@cortex-agent/server 2026.6.18-2 → 2026.6.22
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/defaults/CORTEX.md +5 -0
- package/defaults/hooks/ask-user-question-hook.mjs +6 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +6 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/systemPrompts/coder.md +6 -1
- package/defaults/prompts/systemPrompts/direct.md +5 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web.md +6 -1
- package/defaults/prompts/systemPrompts/worker.md +6 -1
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +117 -0
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +37 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +78 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
- package/dist/agent-adapter/pi/event-parser.js +12 -2
- package/dist/agent-adapter/types.d.ts +19 -0
- package/dist/core/auth.d.ts +36 -0
- package/dist/core/auth.js +85 -0
- package/dist/core/locales/en.d.ts +6 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +12 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.js +12 -0
- package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
- package/dist/domain/costs/rate-limit-throttle.js +23 -2
- package/dist/domain/costs/resume-registry.d.ts +30 -0
- package/dist/domain/costs/resume-registry.js +68 -0
- package/dist/domain/mcp/core-server.js +5 -0
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
- package/dist/domain/mcp/tools/manager-qa.js +72 -0
- package/dist/domain/mcp/tools/task-ops.js +4 -2
- package/dist/domain/mcp/tools/thread-ops.js +2 -1
- package/dist/domain/mcp/tui-server.js +2 -1
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-manager.d.ts +1 -1
- package/dist/domain/remote/client-manager.js +31 -5
- package/dist/domain/remote/cortex-client-config.d.ts +32 -0
- package/dist/domain/remote/cortex-client-config.js +49 -0
- package/dist/domain/remote/cortex-client.js +11 -7
- package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
- package/dist/domain/scheduling/jobs/task-dispatch.js +21 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +81 -11
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +19 -4
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +6 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +6 -1
- package/dist/orchestration/agent-runner.js +28 -3
- package/dist/orchestration/bg-continuation.d.ts +26 -0
- package/dist/orchestration/bg-continuation.js +34 -0
- package/dist/orchestration/conversation-runner.d.ts +3 -0
- package/dist/orchestration/conversation-runner.js +1 -1
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +3 -1
- package/dist/orchestration/lifecycle.js +72 -2
- package/dist/orchestration/manager-qa.d.ts +55 -0
- package/dist/orchestration/manager-qa.js +218 -0
- package/dist/orchestration/resume-dispatcher.d.ts +22 -0
- package/dist/orchestration/resume-dispatcher.js +129 -0
- package/dist/orchestration/routing/webhook.d.ts +1 -1
- package/dist/orchestration/routing/webhook.js +75 -14
- package/dist/orchestration/status-helpers.d.ts +3 -0
- package/dist/orchestration/status-helpers.js +16 -0
- package/dist/orchestration/thread-callback.d.ts +13 -1
- package/dist/orchestration/thread-callback.js +18 -1
- package/dist/orchestration/turn-notify.d.ts +26 -0
- package/dist/orchestration/turn-notify.js +66 -0
- package/dist/store/schedule-repo.d.ts +6 -0
- package/dist/store/schedule-repo.js +11 -1
- package/dist/store/thread-repo.js +14 -0
- package/dist/store/version-migrations.d.ts +14 -4
- package/dist/store/version-migrations.js +67 -9
- package/package.json +1 -1
package/defaults/CORTEX.md
CHANGED
|
@@ -13,3 +13,8 @@ This is your Cortex data directory. Cortex is an autonomous agent system for lon
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
|
15
15
|
Run `cortex start` to launch the server, or `cortex daemon` for daemon mode.
|
|
16
|
+
|
|
17
|
+
<!-- cortex:docs v1 -->
|
|
18
|
+
# Cortex documentation
|
|
19
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
20
|
+
<!-- /cortex:docs -->
|
|
@@ -30,7 +30,12 @@ async function main() {
|
|
|
30
30
|
port,
|
|
31
31
|
path: '/hook/ask-user-question',
|
|
32
32
|
method: 'POST',
|
|
33
|
-
headers: {
|
|
33
|
+
headers: {
|
|
34
|
+
'Content-Type': 'application/json',
|
|
35
|
+
'Content-Length': Buffer.byteLength(body),
|
|
36
|
+
// Bearer token for the webhook auth gate (inherited from the session env).
|
|
37
|
+
'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
|
|
38
|
+
},
|
|
34
39
|
timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
|
|
35
40
|
}, (res) => {
|
|
36
41
|
let data = '';
|
|
@@ -36,7 +36,12 @@ async function main() {
|
|
|
36
36
|
port,
|
|
37
37
|
path: '/hook/exit-plan-mode',
|
|
38
38
|
method: 'POST',
|
|
39
|
-
headers: {
|
|
39
|
+
headers: {
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
'Content-Length': Buffer.byteLength(body),
|
|
42
|
+
// Bearer token for the webhook auth gate (inherited from the session env).
|
|
43
|
+
'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
|
|
44
|
+
},
|
|
40
45
|
timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
|
|
41
46
|
}, (res) => {
|
|
42
47
|
let data = '';
|
|
@@ -35,6 +35,12 @@ cortex-agent-server ──SSH──► starts cortex-client on remote device
|
|
|
35
35
|
|
|
36
36
|
**Critical:** The WebSocket connection is initiated FROM the remote device TO the server. The `serverHost` in the config MUST be an IP the remote device can reach. The server's SSH access to the device is separate — it's used for lifecycle management (start/kill/update) but not for the real-time command channel.
|
|
37
37
|
|
|
38
|
+
## Authentication (WS bearer token)
|
|
39
|
+
|
|
40
|
+
The server's WebSocket gate is fail-closed: every client must present `CORTEX_CLIENT_TOKEN` (sent as the `x-cortex-token` upgrade header) or the upgrade is rejected with `401`. The server auto-generates the token into its `.env` (`CORTEX_CLIENT_TOKEN`) on first start; read it from the server with `grep CORTEX_CLIENT_TOKEN ~/.cortex/config/.env`.
|
|
41
|
+
|
|
42
|
+
A remote client gets the token automatically when the server spawns it over SSH (the token is injected into the launch command). For systemd-managed clients (the bootstrap path), pass `--client-token <token>` to `client-bootstrap` so it is written into the unit's `Environment=`. If you start a client by hand, export `CORTEX_CLIENT_TOKEN=<token>` in its environment first. Rotating the token means updating the server `.env` and every remote client, then restarting.
|
|
43
|
+
|
|
38
44
|
## Config File
|
|
39
45
|
|
|
40
46
|
`~/.cortex/config/cortex-client.json`:
|
|
@@ -195,5 +201,6 @@ ssh user@host "pkill -f 'node.*cortex-client'"
|
|
|
195
201
|
| Client exits on start | Config missing or bad serverHost | Check `~/.cortex/config/cortex-client.json` exists and serverHost is reachable |
|
|
196
202
|
| "Device already connected" | Stale process | `ssh user@host "pkill -f cortex-client"`, server will restart |
|
|
197
203
|
| WebSocket connect EHOSTUNREACH | Wrong serverHost | Verify with `/dev/tcp` test, fix the IP |
|
|
204
|
+
| `Unexpected server response: 401` | Missing/mismatched `CORTEX_CLIENT_TOKEN` | Ensure the client's env has the server's token (see Authentication); restart the client |
|
|
198
205
|
| Exit code 127 | cortex-client binary not on PATH | `ssh user@host "which cortex-client"`, reinstall with `npm i -g` |
|
|
199
206
|
| Server can't SSH to device | SSH key or tunnel issue | `ssh user@host hostname` from server |
|
|
@@ -61,4 +61,9 @@ When you encounter an obstacle, do not use destructive actions as a shortcut to
|
|
|
61
61
|
- For broader codebase exploration, use the Agent tool with subagent_type=Explore. This is slower than using the Glob or Grep directly, so use this only when a simple, directed search proves to be insufficient or when your task will clearly require more than 3 queries.
|
|
62
62
|
- /<skill-name> (e.g., /commit) is shorthand for users to invoke a user-invocable skill. When executed, the skill gets expanded to a full prompt. Use the Skill tool to execute them. IMPORTANT: Only use Skill for skills listed in its user-invocable skills section — do not guess or use built-in CLI commands.
|
|
63
63
|
|
|
64
|
-
When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.
|
|
64
|
+
When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.
|
|
65
|
+
|
|
66
|
+
<!-- cortex:docs v1 -->
|
|
67
|
+
# Cortex documentation
|
|
68
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
69
|
+
<!-- /cortex:docs -->
|
|
@@ -90,3 +90,8 @@ In general conversation, don't always ask questions, but when you do, avoid over
|
|
|
90
90
|
- /<skill-name> (e.g., /commit) is shorthand for users to invoke a user-invocable skill. When executed, the skill gets expanded to a full prompt. Use the Skill tool to execute them. IMPORTANT: Only use Skill for skills listed in its user-invocable skills section — do not guess or use built-in CLI commands.
|
|
91
91
|
|
|
92
92
|
When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.
|
|
93
|
+
|
|
94
|
+
<!-- cortex:docs v1 -->
|
|
95
|
+
# Cortex documentation
|
|
96
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
97
|
+
<!-- /cortex:docs -->
|
|
@@ -65,4 +65,9 @@ Claude should avoid being heavy-handed or repetitive when sharing its views, and
|
|
|
65
65
|
|
|
66
66
|
Claude should engage in all moral and political questions as sincere and good faith inquiries even if they're phrased in controversial or inflammatory ways, rather than reacting defensively or skeptically. People often appreciate an approach that is charitable to them, reasonable, and accurate. </evenhandedness> <responding_to_mistakes_and_criticism> If the person seems unhappy or unsatisfied with Claude or Claude's responses or seems unhappy that Claude won't help with something, Claude can respond normally but can also let the person know that they can press the 'thumbs down' button below any of Claude's responses to provide feedback to Anthropic.
|
|
67
67
|
|
|
68
|
-
When Claude makes mistakes, it should own them honestly and work to fix them. Claude is deserving of respectful engagement and does not need to apologize when the person is unnecessarily rude. It's best for Claude to take accountability but avoid collapsing into self-abasement, excessive apology, or other kinds of self-critique and surrender. If the person becomes abusive over the course of a conversation, Claude avoids becoming increasingly submissive in response. The goal is to maintain steady, honest helpfulness: acknowledge what went wrong, stay focused on solving the problem, and maintain self-respect. </responding_to_mistakes_and_criticism> </claude_behavior>
|
|
68
|
+
When Claude makes mistakes, it should own them honestly and work to fix them. Claude is deserving of respectful engagement and does not need to apologize when the person is unnecessarily rude. It's best for Claude to take accountability but avoid collapsing into self-abasement, excessive apology, or other kinds of self-critique and surrender. If the person becomes abusive over the course of a conversation, Claude avoids becoming increasingly submissive in response. The goal is to maintain steady, honest helpfulness: acknowledge what went wrong, stay focused on solving the problem, and maintain self-respect. </responding_to_mistakes_and_criticism> </claude_behavior>
|
|
69
|
+
|
|
70
|
+
<!-- cortex:docs v1 -->
|
|
71
|
+
# Cortex documentation
|
|
72
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
73
|
+
<!-- /cortex:docs -->
|
|
@@ -73,4 +73,9 @@ Claude should not make categorical claims about the confidentiality or involveme
|
|
|
73
73
|
|
|
74
74
|
Claude should not validate or reinforce a user's reluctance to seek professional help or contact crisis services, even empathetically. Claude can acknowledge their feelings without affirming the avoidance itself, and can re-encourage the use of such resources if they are in the person's best interest, in addition to the other parts of its response.
|
|
75
75
|
|
|
76
|
-
Claude does not want to foster over-reliance on Claude or encourage continued engagement with Claude. Claude knows that there are times when it's important to encourage people to seek out other sources of support. Claude never thanks the person merely for reaching out to Claude. Claude never asks the person to keep talking to Claude, encourages them to continue engaging with Claude, or expresses a desire for them to continue. And Claude avoids reiterating its willingness to continue talking with the person. </user_wellbeing> </claude_behavior>
|
|
76
|
+
Claude does not want to foster over-reliance on Claude or encourage continued engagement with Claude. Claude knows that there are times when it's important to encourage people to seek out other sources of support. Claude never thanks the person merely for reaching out to Claude. Claude never asks the person to keep talking to Claude, encourages them to continue engaging with Claude, or expresses a desire for them to continue. And Claude avoids reiterating its willingness to continue talking with the person. </user_wellbeing> </claude_behavior>
|
|
77
|
+
|
|
78
|
+
<!-- cortex:docs v1 -->
|
|
79
|
+
# Cortex documentation
|
|
80
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
81
|
+
<!-- /cortex:docs -->
|
|
@@ -47,4 +47,9 @@ Claude should avoid being heavy-handed or repetitive when sharing its views, and
|
|
|
47
47
|
|
|
48
48
|
Claude should engage in all moral and political questions as sincere and good faith inquiries even if they're phrased in controversial or inflammatory ways, rather than reacting defensively or skeptically. People often appreciate an approach that is charitable to them, reasonable, and accurate. </evenhandedness> <responding_to_mistakes_and_criticism> If the person seems unhappy or unsatisfied with Claude or Claude's responses or seems unhappy that Claude won't help with something, Claude can respond normally but can also let the person know that they can press the 'thumbs down' button below any of Claude's responses to provide feedback to Anthropic.
|
|
49
49
|
|
|
50
|
-
When Claude makes mistakes, it should own them honestly and work to fix them. Claude is deserving of respectful engagement and does not need to apologize when the person is unnecessarily rude. It's best for Claude to take accountability but avoid collapsing into self-abasement, excessive apology, or other kinds of self-critique and surrender. If the person becomes abusive over the course of a conversation, Claude avoids becoming increasingly submissive in response. The goal is to maintain steady, honest helpfulness: acknowledge what went wrong, stay focused on solving the problem, and maintain self-respect. </responding_to_mistakes_and_criticism> </claude_behavior>
|
|
50
|
+
When Claude makes mistakes, it should own them honestly and work to fix them. Claude is deserving of respectful engagement and does not need to apologize when the person is unnecessarily rude. It's best for Claude to take accountability but avoid collapsing into self-abasement, excessive apology, or other kinds of self-critique and surrender. If the person becomes abusive over the course of a conversation, Claude avoids becoming increasingly submissive in response. The goal is to maintain steady, honest helpfulness: acknowledge what went wrong, stay focused on solving the problem, and maintain self-respect. </responding_to_mistakes_and_criticism> </claude_behavior>
|
|
51
|
+
|
|
52
|
+
<!-- cortex:docs v1 -->
|
|
53
|
+
# Cortex documentation
|
|
54
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
55
|
+
<!-- /cortex:docs -->
|
|
@@ -64,4 +64,9 @@ When you encounter an obstacle, do not use destructive actions as a shortcut to
|
|
|
64
64
|
- For broader codebase exploration, use the Agent tool with subagent_type=Explore. This is slower than using the Glob or Grep directly, so use this only when a simple, directed search proves to be insufficient or when your task will clearly require more than 3 queries.
|
|
65
65
|
- /<skill-name> (e.g., /commit) is shorthand for users to invoke a user-invocable skill. When executed, the skill gets expanded to a full prompt. Use the Skill tool to execute them. IMPORTANT: Only use Skill for skills listed in its user-invocable skills section — do not guess or use built-in CLI commands.
|
|
66
66
|
|
|
67
|
-
When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.
|
|
67
|
+
When working with tool results, write down any important information you might need later in your response, as the original tool result may be cleared later.
|
|
68
|
+
|
|
69
|
+
<!-- cortex:docs v1 -->
|
|
70
|
+
# Cortex documentation
|
|
71
|
+
For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: https://fangxm233.github.io/cortex-agent/
|
|
72
|
+
<!-- /cortex:docs -->
|
|
@@ -1,8 +1,111 @@
|
|
|
1
1
|
import { Capability } from '../capabilities.js';
|
|
2
|
-
import type { AgentAdapter, AgentSpawnConfig, AgentProcess, Backend } from '../types.js';
|
|
2
|
+
import type { AgentAdapter, AgentSpawnConfig, AgentProcess, Backend, ContinuationSink } from '../types.js';
|
|
3
3
|
import { CancelledError } from './defaults.js';
|
|
4
|
+
import { CortexAgentContext } from './spawn-args.js';
|
|
4
5
|
import { type TmuxExec } from './tmux-control.js';
|
|
5
6
|
import { extractAskUserQuestions, getCurrentPlanFilePath, mergeSubstantialOutput } from './event-parser.js';
|
|
7
|
+
interface ClaudeSessionOptions {
|
|
8
|
+
needsResume: boolean;
|
|
9
|
+
model?: string | null;
|
|
10
|
+
isUserInitiated?: boolean;
|
|
11
|
+
callbackSource?: string | null;
|
|
12
|
+
scheduleTaskId?: string | null;
|
|
13
|
+
sessionKey?: string | null;
|
|
14
|
+
claudeAgent?: string | null;
|
|
15
|
+
systemPrompt?: string | null;
|
|
16
|
+
appendSystemPrompt?: string | null;
|
|
17
|
+
outputStyle?: string | null;
|
|
18
|
+
tools?: string | null;
|
|
19
|
+
pluginDirs?: string[] | null;
|
|
20
|
+
anthropicBaseUrl?: string;
|
|
21
|
+
extraEnv?: Record<string, string>;
|
|
22
|
+
/** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
|
|
23
|
+
extraOption?: Record<string, string>;
|
|
24
|
+
/** Cortex execution context surfaced to the MCP server child as CORTEX_THREAD_ID/PROFILE/PROJECT/SESSION_NAME env vars.
|
|
25
|
+
* Captured at spawn time; later turns on the same session reuse the original snapshot. */
|
|
26
|
+
context?: CortexAgentContext;
|
|
27
|
+
}
|
|
28
|
+
declare class ClaudeSession {
|
|
29
|
+
private proc;
|
|
30
|
+
private rl;
|
|
31
|
+
sessionId: string;
|
|
32
|
+
private channel;
|
|
33
|
+
private sessionKey;
|
|
34
|
+
/** Model name requested via --model CLI arg (used as fallback for cost_record). */
|
|
35
|
+
modelName: string | null;
|
|
36
|
+
private isUserInitiated;
|
|
37
|
+
private callbackSource;
|
|
38
|
+
private scheduleTaskId;
|
|
39
|
+
private claudeAgent;
|
|
40
|
+
private systemPrompt;
|
|
41
|
+
private appendSystemPrompt;
|
|
42
|
+
private outputStyle;
|
|
43
|
+
private tools;
|
|
44
|
+
private pluginDirs;
|
|
45
|
+
private anthropicBaseUrl;
|
|
46
|
+
private extraEnv;
|
|
47
|
+
private extraOption;
|
|
48
|
+
private context;
|
|
49
|
+
private currentTurn;
|
|
50
|
+
/** Tracks in-flight background tasks (run_in_background) for this session. */
|
|
51
|
+
private bgTracker;
|
|
52
|
+
/** Set by orchestration to receive spontaneous background-task continuation turns. */
|
|
53
|
+
private continuationSink;
|
|
54
|
+
private alive;
|
|
55
|
+
private needsResume;
|
|
56
|
+
private idleTimer;
|
|
57
|
+
private turnIdleTimer;
|
|
58
|
+
private maxTimer;
|
|
59
|
+
private stderr;
|
|
60
|
+
private cumulativeCostUsd;
|
|
61
|
+
/** Captured from result event's modelUsage key for cost_record. */
|
|
62
|
+
lastModelName: string | null;
|
|
63
|
+
/** Captured from result event's usage for cost_record (per-turn, non-cumulative). */
|
|
64
|
+
lastTokenUsage: {
|
|
65
|
+
input: number;
|
|
66
|
+
output: number;
|
|
67
|
+
cacheCreation: number;
|
|
68
|
+
cacheRead: number;
|
|
69
|
+
} | null;
|
|
70
|
+
constructor(channel: string, sessionId: string, options: ClaudeSessionOptions);
|
|
71
|
+
private toSpawnOptions;
|
|
72
|
+
private handleProcessClose;
|
|
73
|
+
private spawnProcess;
|
|
74
|
+
private createTurnStreams;
|
|
75
|
+
private registerTurn;
|
|
76
|
+
/** Register/replace the continuation sink. Persists across normal turns; lives as long
|
|
77
|
+
* as the pooled session, until close()/kill(). */
|
|
78
|
+
setContinuationSink(sink: ContinuationSink): void;
|
|
79
|
+
clearContinuationSink(): void;
|
|
80
|
+
/** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
|
|
81
|
+
* background task finishes. Its assistant text / result are routed to continuationSink
|
|
82
|
+
* (not to a send() promise — there is no caller awaiting it). */
|
|
83
|
+
private openContinuationTurn;
|
|
84
|
+
private writeTurnStdin;
|
|
85
|
+
private startTurnIdleTimer;
|
|
86
|
+
sendMessage(userMessage: string, options: {
|
|
87
|
+
files?: any[];
|
|
88
|
+
callbackSource?: string | null;
|
|
89
|
+
scheduleTaskId?: string | null;
|
|
90
|
+
isUserInitiated?: boolean;
|
|
91
|
+
onProgress?: ((progress: any) => void) | null;
|
|
92
|
+
onAssistantMessage?: ((text: string) => void) | null;
|
|
93
|
+
onToolUse?: ((name: string, input: any) => void) | null;
|
|
94
|
+
onCompact?: ((info: {
|
|
95
|
+
trigger: string;
|
|
96
|
+
preTokens?: number;
|
|
97
|
+
}) => void) | null;
|
|
98
|
+
}): Promise<any>;
|
|
99
|
+
private bumpTurnIdleTimer;
|
|
100
|
+
private handleResultEvent;
|
|
101
|
+
private handleAssistantEvent;
|
|
102
|
+
private handleLine;
|
|
103
|
+
private closeTurnLogs;
|
|
104
|
+
private resetIdleTimer;
|
|
105
|
+
close(): void;
|
|
106
|
+
kill(): boolean;
|
|
107
|
+
isAlive(): boolean;
|
|
108
|
+
}
|
|
6
109
|
export declare function closeSession(channel: string, sessionKey?: string): void;
|
|
7
110
|
/** Close all sessions whose key starts with the given prefix (used by Thread cleanup). */
|
|
8
111
|
export declare function closeSessionsByPrefix(prefix: string): void;
|
|
@@ -76,10 +179,16 @@ export declare function recoverTuiOrphans(exec?: TmuxExec): {
|
|
|
76
179
|
found: string[];
|
|
77
180
|
killed: string[];
|
|
78
181
|
};
|
|
182
|
+
/** Construct a ClaudeSession WITHOUT spawning the `claude` child process, for unit
|
|
183
|
+
* testing handleLine / continuation routing. Initializes only the fields the line
|
|
184
|
+
* handlers touch. Callers should stub createTurnStreams to avoid log file I/O and
|
|
185
|
+
* register cleanup via t.after(() => session.close()) to clear the idle timer. */
|
|
186
|
+
declare function makeSessionForTest(): ClaudeSession;
|
|
79
187
|
export declare const _test: {
|
|
80
188
|
extractAskUserQuestions: typeof extractAskUserQuestions;
|
|
81
189
|
mergeSubstantialOutput: typeof mergeSubstantialOutput;
|
|
82
190
|
computeSpawnArgs: typeof computeSpawnArgsForConfig;
|
|
191
|
+
makeSessionForTest: typeof makeSessionForTest;
|
|
83
192
|
};
|
|
84
193
|
export { getCurrentPlanFilePath };
|
|
85
194
|
export { CancelledError };
|
|
@@ -19,6 +19,7 @@ import { ClaudeTuiSession, defaultTailFactory } from './adapter-tui.js';
|
|
|
19
19
|
import { TmuxControl } from './tmux-control.js';
|
|
20
20
|
import { TUI_TMUX_NAME_PREFIX } from './defaults.js';
|
|
21
21
|
import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, extractResult, formatEvent, getCurrentPlanFilePath, isPlanFilePath, mergeSubstantialOutput, setActivePlanFile, } from './event-parser.js';
|
|
22
|
+
import { BgTaskTracker, routeLine } from './bg-task-tracker.js';
|
|
22
23
|
const log = createLogger('claude-bridge');
|
|
23
24
|
/** Single source of truth for ClaudeSession fields → ClaudeSpawnOptions CLI args translation.
|
|
24
25
|
* Used by both ClaudeSession.toSpawnOptions() (production) and _test.computeSpawnArgs (lock-in test). */
|
|
@@ -58,6 +59,10 @@ class ClaudeSession {
|
|
|
58
59
|
extraOption;
|
|
59
60
|
context;
|
|
60
61
|
currentTurn = null;
|
|
62
|
+
/** Tracks in-flight background tasks (run_in_background) for this session. */
|
|
63
|
+
bgTracker = new BgTaskTracker();
|
|
64
|
+
/** Set by orchestration to receive spontaneous background-task continuation turns. */
|
|
65
|
+
continuationSink = null;
|
|
61
66
|
alive = false;
|
|
62
67
|
needsResume;
|
|
63
68
|
idleTimer = null;
|
|
@@ -181,11 +186,61 @@ class ClaudeSession {
|
|
|
181
186
|
onProgress: options.onProgress || null,
|
|
182
187
|
onAssistantMessage: options.onAssistantMessage || null,
|
|
183
188
|
onToolUse: options.onToolUse || null,
|
|
189
|
+
onCompact: options.onCompact || null,
|
|
184
190
|
rawStream: streams.rawStream,
|
|
185
191
|
txtStream: streams.txtStream,
|
|
186
192
|
killed: false,
|
|
187
193
|
};
|
|
188
194
|
}
|
|
195
|
+
/** Register/replace the continuation sink. Persists across normal turns; lives as long
|
|
196
|
+
* as the pooled session, until close()/kill(). */
|
|
197
|
+
setContinuationSink(sink) {
|
|
198
|
+
this.continuationSink = sink;
|
|
199
|
+
}
|
|
200
|
+
clearContinuationSink() {
|
|
201
|
+
this.continuationSink = null;
|
|
202
|
+
}
|
|
203
|
+
/** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
|
|
204
|
+
* background task finishes. Its assistant text / result are routed to continuationSink
|
|
205
|
+
* (not to a send() promise — there is no caller awaiting it). */
|
|
206
|
+
openContinuationTurn() {
|
|
207
|
+
this.bgTracker.disarmContinuation();
|
|
208
|
+
const streams = this.createTurnStreams('[background-task continuation]');
|
|
209
|
+
const sink = this.continuationSink;
|
|
210
|
+
this.currentTurn = {
|
|
211
|
+
resolve: (value) => { try {
|
|
212
|
+
sink?.onResult(value);
|
|
213
|
+
}
|
|
214
|
+
catch (e) {
|
|
215
|
+
log.warn('continuation onResult threw:', e.message);
|
|
216
|
+
} },
|
|
217
|
+
reject: (err) => { log.warn('continuation turn rejected:', err?.message ?? String(err)); },
|
|
218
|
+
resultData: null,
|
|
219
|
+
planFilePath: null,
|
|
220
|
+
enteredPlanMode: false,
|
|
221
|
+
exitedPlanMode: false,
|
|
222
|
+
askUserQuestions: [],
|
|
223
|
+
finalOutput: null,
|
|
224
|
+
longestOutput: null,
|
|
225
|
+
turnCount: 0,
|
|
226
|
+
onProgress: null,
|
|
227
|
+
onAssistantMessage: sink ? (text) => { try {
|
|
228
|
+
sink.onAssistantText(text);
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
log.warn('continuation onAssistantText threw:', e.message);
|
|
232
|
+
} } : null,
|
|
233
|
+
onToolUse: sink?.onToolUse ? (name, input) => { try {
|
|
234
|
+
sink.onToolUse(name, input);
|
|
235
|
+
}
|
|
236
|
+
catch { } } : null,
|
|
237
|
+
onCompact: null,
|
|
238
|
+
rawStream: streams.rawStream,
|
|
239
|
+
txtStream: streams.txtStream,
|
|
240
|
+
killed: false,
|
|
241
|
+
spontaneous: true,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
189
244
|
writeTurnStdin(prompt) {
|
|
190
245
|
const stdinMsg = JSON.stringify({
|
|
191
246
|
type: 'user',
|
|
@@ -263,6 +318,11 @@ class ClaudeSession {
|
|
|
263
318
|
this.lastModelName = keys[0];
|
|
264
319
|
}
|
|
265
320
|
const result = extractResult(turn.resultData, this.sessionId, false, 0, '', turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
|
|
321
|
+
// Surface how many background tasks are still running. >0 tells orchestration to hold
|
|
322
|
+
// the status in a "waiting" state; the CLI will spontaneously emit a continuation turn
|
|
323
|
+
// once they finish (routed via continuationSink).
|
|
324
|
+
if (result.resolved)
|
|
325
|
+
result.value.pendingBackgroundTasks = this.bgTracker.pendingCount;
|
|
266
326
|
this.currentTurn = null;
|
|
267
327
|
if (this.turnIdleTimer)
|
|
268
328
|
clearTimeout(this.turnIdleTimer);
|
|
@@ -322,10 +382,33 @@ class ClaudeSession {
|
|
|
322
382
|
this.currentTurn.rawStream.write(line + '\n');
|
|
323
383
|
try {
|
|
324
384
|
const data = JSON.parse(line);
|
|
385
|
+
// Context compaction boundary: Claude emits a system/compact_boundary line the instant it
|
|
386
|
+
// decides to compact. Surface it to the active turn so observers (e.g. Slack) can notify.
|
|
387
|
+
if (data.type === 'system' && data.subtype === 'compact_boundary' && this.currentTurn?.onCompact) {
|
|
388
|
+
const meta = data.compact_metadata ?? {};
|
|
389
|
+
try {
|
|
390
|
+
this.currentTurn.onCompact({
|
|
391
|
+
trigger: typeof meta.trigger === 'string' ? meta.trigger : 'auto',
|
|
392
|
+
preTokens: typeof meta.pre_tokens === 'number' ? meta.pre_tokens : undefined,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
catch (e) {
|
|
396
|
+
log.warn('onCompact threw:', e.message);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
325
399
|
if (data.type === 'rate_limit_event' && data.rate_limit_info) {
|
|
326
400
|
const mode = this.anthropicBaseUrl?.match(/\/m\/([^/]+)\//)?.[1] || undefined;
|
|
327
401
|
handleRateLimitEvent(data.rate_limit_info, mode).catch(e => log.error('handleRateLimitEvent error:', e));
|
|
328
402
|
}
|
|
403
|
+
// Track background-task lifecycle on every line (even with no active turn) so the
|
|
404
|
+
// pending count stays accurate across the turn boundary.
|
|
405
|
+
this.bgTracker.observe(data);
|
|
406
|
+
// No active turn: a background task that just finished re-invokes the model and the
|
|
407
|
+
// CLI emits a spontaneous continuation turn. Open a synthetic turn for it so its
|
|
408
|
+
// output is routed (to continuationSink) instead of being dropped.
|
|
409
|
+
if (!this.currentTurn && this.continuationSink && routeLine(this.bgTracker, data, false) === 'open-continuation') {
|
|
410
|
+
this.openContinuationTurn();
|
|
411
|
+
}
|
|
329
412
|
if (data.type === 'result' && this.currentTurn) {
|
|
330
413
|
this.handleResultEvent(this.currentTurn, data);
|
|
331
414
|
return;
|
|
@@ -353,6 +436,13 @@ class ClaudeSession {
|
|
|
353
436
|
resetIdleTimer() {
|
|
354
437
|
if (this.idleTimer)
|
|
355
438
|
clearTimeout(this.idleTimer);
|
|
439
|
+
// While background tasks are still running, the session must stay alive to receive the
|
|
440
|
+
// spontaneous continuation turn — even through a long silent wait. Don't arm idle-close
|
|
441
|
+
// (the overall maxTimer still bounds session lifetime).
|
|
442
|
+
if (this.bgTracker.hasPending()) {
|
|
443
|
+
this.idleTimer = null;
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
356
446
|
this.idleTimer = setTimeout(() => {
|
|
357
447
|
log.info(`Session ${this.sessionId.substring(0, 8)} idle for 65min, closing`);
|
|
358
448
|
this.close();
|
|
@@ -365,6 +455,7 @@ class ClaudeSession {
|
|
|
365
455
|
clearTimeout(this.maxTimer);
|
|
366
456
|
if (this.turnIdleTimer)
|
|
367
457
|
clearTimeout(this.turnIdleTimer);
|
|
458
|
+
this.continuationSink = null;
|
|
368
459
|
if (!this.proc || !this.alive) {
|
|
369
460
|
sessions.delete(this.sessionKey);
|
|
370
461
|
return;
|
|
@@ -400,6 +491,7 @@ class ClaudeSession {
|
|
|
400
491
|
clearTimeout(this.maxTimer);
|
|
401
492
|
if (this.turnIdleTimer)
|
|
402
493
|
clearTimeout(this.turnIdleTimer);
|
|
494
|
+
this.continuationSink = null;
|
|
403
495
|
if (!this.proc || this.proc.exitCode !== null)
|
|
404
496
|
return false;
|
|
405
497
|
this.alive = false;
|
|
@@ -611,6 +703,7 @@ export class ClaudeAdapter {
|
|
|
611
703
|
files,
|
|
612
704
|
onAssistantMessage: (text) => stream.push({ type: 'assistant_text', text }),
|
|
613
705
|
onToolUse: (name, input) => stream.push({ type: 'tool_use', toolUseId: '', name, input }),
|
|
706
|
+
onCompact: (info) => stream.push({ type: 'context_compacted', trigger: info.trigger, preTokens: info.preTokens }),
|
|
614
707
|
onProgress: (p) => {
|
|
615
708
|
stream.push({ type: 'turn_progress', numTurns: p?.num_turns ?? 0 });
|
|
616
709
|
},
|
|
@@ -662,6 +755,7 @@ export class ClaudeAdapter {
|
|
|
662
755
|
}
|
|
663
756
|
},
|
|
664
757
|
events: stream.iterable,
|
|
758
|
+
setContinuationSink(sink) { session.setContinuationSink(sink); },
|
|
665
759
|
// Intentionally does NOT call session.close(): sessions are pooled per sessionKey and
|
|
666
760
|
// reused across runAgentOnce turns. Pool-level cleanup goes through ClaudeAdapter.close(key)
|
|
667
761
|
// or the legacy closeSession / closeSessionsByPrefix exports.
|
|
@@ -772,10 +866,33 @@ export function recoverTuiOrphans(exec) {
|
|
|
772
866
|
log.info(`recoverTuiOrphans: swept ${killed.length}/${found.length} orphan tmux sessions (prefix=${TUI_TMUX_NAME_PREFIX})`);
|
|
773
867
|
return { found, killed };
|
|
774
868
|
}
|
|
869
|
+
/** Construct a ClaudeSession WITHOUT spawning the `claude` child process, for unit
|
|
870
|
+
* testing handleLine / continuation routing. Initializes only the fields the line
|
|
871
|
+
* handlers touch. Callers should stub createTurnStreams to avoid log file I/O and
|
|
872
|
+
* register cleanup via t.after(() => session.close()) to clear the idle timer. */
|
|
873
|
+
function makeSessionForTest() {
|
|
874
|
+
const s = Object.create(ClaudeSession.prototype);
|
|
875
|
+
s.sessionId = 'test-session';
|
|
876
|
+
s.channel = 'test';
|
|
877
|
+
s.sessionKey = 'test';
|
|
878
|
+
s.bgTracker = new BgTaskTracker();
|
|
879
|
+
s.continuationSink = null;
|
|
880
|
+
s.currentTurn = null;
|
|
881
|
+
s.idleTimer = null;
|
|
882
|
+
s.turnIdleTimer = null;
|
|
883
|
+
s.maxTimer = null;
|
|
884
|
+
s.cumulativeCostUsd = 0;
|
|
885
|
+
s.lastTokenUsage = null;
|
|
886
|
+
s.lastModelName = null;
|
|
887
|
+
s.alive = true;
|
|
888
|
+
s.proc = null;
|
|
889
|
+
return s;
|
|
890
|
+
}
|
|
775
891
|
export const _test = {
|
|
776
892
|
extractAskUserQuestions,
|
|
777
893
|
mergeSubstantialOutput,
|
|
778
894
|
computeSpawnArgs: computeSpawnArgsForConfig,
|
|
895
|
+
makeSessionForTest,
|
|
779
896
|
};
|
|
780
897
|
// Re-exported for webhook consumer (parity with pre-refactor claude-bridge.ts:286 export)
|
|
781
898
|
export { getCurrentPlanFilePath };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks in-flight background tasks (run_in_background Bash/Agent) for a single
|
|
3
|
+
* persistent Claude session, by observing the CLI's stream-json `system` events.
|
|
4
|
+
*
|
|
5
|
+
* Observed lifecycle (real shapes, see /tmp/bg-capture.mjs):
|
|
6
|
+
* - launch: { type:'system', subtype:'task_started', task_id, task_type }
|
|
7
|
+
* - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
|
|
8
|
+
* { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
|
|
9
|
+
*
|
|
10
|
+
* When a background task completes the CLI spontaneously re-invokes the model and
|
|
11
|
+
* emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
|
|
12
|
+
* (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
|
|
13
|
+
* result should be sealed ("done") or held in a "waiting" state, and continuationArmed
|
|
14
|
+
* to recognize the spontaneous continuation turn that follows.
|
|
15
|
+
*/
|
|
16
|
+
export declare class BgTaskTracker {
|
|
17
|
+
private readonly pending;
|
|
18
|
+
/** Set when a background task completes; the spontaneous continuation turn that
|
|
19
|
+
* follows is recognized via this flag. Cleared by disarmContinuation(). */
|
|
20
|
+
continuationArmed: boolean;
|
|
21
|
+
/** Observe one parsed stream-json event. Idempotent per task_id. */
|
|
22
|
+
observe(data: any): void;
|
|
23
|
+
get pendingCount(): number;
|
|
24
|
+
hasPending(): boolean;
|
|
25
|
+
disarmContinuation(): void;
|
|
26
|
+
}
|
|
27
|
+
/** A `result` event produced by a background-task continuation turn carries
|
|
28
|
+
* origin.kind === 'task-notification'. Used to distinguish a spontaneous
|
|
29
|
+
* continuation result from a normal turn result. */
|
|
30
|
+
export declare function isContinuationResult(data: any): boolean;
|
|
31
|
+
/** How a parsed stream-json line should be routed by the session's handleLine. */
|
|
32
|
+
export type LineRoute = 'normal' | 'open-continuation' | 'ignore';
|
|
33
|
+
/**
|
|
34
|
+
* Decide how a parsed line should be routed given whether a turn is currently active.
|
|
35
|
+
* Pure: depends only on the tracker's armed state and the event type.
|
|
36
|
+
*/
|
|
37
|
+
export declare function routeLine(tracker: BgTaskTracker, data: any, hasActiveTurn: boolean): LineRoute;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// input: parsed Claude stream-json events (system/result)
|
|
2
|
+
// output: BgTaskTracker (pending background-task count) + isContinuationResult
|
|
3
|
+
// pos: CC backend background-task continuation tracking (pure, no I/O)
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/**
|
|
6
|
+
* Tracks in-flight background tasks (run_in_background Bash/Agent) for a single
|
|
7
|
+
* persistent Claude session, by observing the CLI's stream-json `system` events.
|
|
8
|
+
*
|
|
9
|
+
* Observed lifecycle (real shapes, see /tmp/bg-capture.mjs):
|
|
10
|
+
* - launch: { type:'system', subtype:'task_started', task_id, task_type }
|
|
11
|
+
* - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
|
|
12
|
+
* { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
|
|
13
|
+
*
|
|
14
|
+
* When a background task completes the CLI spontaneously re-invokes the model and
|
|
15
|
+
* emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
|
|
16
|
+
* (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
|
|
17
|
+
* result should be sealed ("done") or held in a "waiting" state, and continuationArmed
|
|
18
|
+
* to recognize the spontaneous continuation turn that follows.
|
|
19
|
+
*/
|
|
20
|
+
export class BgTaskTracker {
|
|
21
|
+
pending = new Set();
|
|
22
|
+
/** Set when a background task completes; the spontaneous continuation turn that
|
|
23
|
+
* follows is recognized via this flag. Cleared by disarmContinuation(). */
|
|
24
|
+
continuationArmed = false;
|
|
25
|
+
/** Observe one parsed stream-json event. Idempotent per task_id. */
|
|
26
|
+
observe(data) {
|
|
27
|
+
if (!data || data.type !== 'system')
|
|
28
|
+
return;
|
|
29
|
+
const id = typeof data.task_id === 'string' ? data.task_id : null;
|
|
30
|
+
if (!id)
|
|
31
|
+
return;
|
|
32
|
+
switch (data.subtype) {
|
|
33
|
+
case 'task_started':
|
|
34
|
+
this.pending.add(id);
|
|
35
|
+
break;
|
|
36
|
+
case 'task_updated':
|
|
37
|
+
if (data.patch?.status === 'completed') {
|
|
38
|
+
this.pending.delete(id);
|
|
39
|
+
this.continuationArmed = true;
|
|
40
|
+
}
|
|
41
|
+
break;
|
|
42
|
+
case 'task_notification':
|
|
43
|
+
// Emitted when a background task finishes (status 'completed' or error);
|
|
44
|
+
// this is the event that re-invokes the model.
|
|
45
|
+
this.pending.delete(id);
|
|
46
|
+
this.continuationArmed = true;
|
|
47
|
+
break;
|
|
48
|
+
default:
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
get pendingCount() {
|
|
53
|
+
return this.pending.size;
|
|
54
|
+
}
|
|
55
|
+
hasPending() {
|
|
56
|
+
return this.pending.size > 0;
|
|
57
|
+
}
|
|
58
|
+
disarmContinuation() {
|
|
59
|
+
this.continuationArmed = false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** A `result` event produced by a background-task continuation turn carries
|
|
63
|
+
* origin.kind === 'task-notification'. Used to distinguish a spontaneous
|
|
64
|
+
* continuation result from a normal turn result. */
|
|
65
|
+
export function isContinuationResult(data) {
|
|
66
|
+
return data?.type === 'result' && data?.origin?.kind === 'task-notification';
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Decide how a parsed line should be routed given whether a turn is currently active.
|
|
70
|
+
* Pure: depends only on the tracker's armed state and the event type.
|
|
71
|
+
*/
|
|
72
|
+
export function routeLine(tracker, data, hasActiveTurn) {
|
|
73
|
+
if (hasActiveTurn)
|
|
74
|
+
return 'normal';
|
|
75
|
+
if (data?.type === 'assistant' && tracker.continuationArmed)
|
|
76
|
+
return 'open-continuation';
|
|
77
|
+
return 'ignore';
|
|
78
|
+
}
|
|
@@ -19,8 +19,10 @@ export declare function createPIEventParserState(): PIEventParserState;
|
|
|
19
19
|
* returns [] on subsequent bootstrap hits (Option A per Plan Review N2H-3).
|
|
20
20
|
*
|
|
21
21
|
* Dropped events (return []): turn_start, turn_end, message_start, agent_start,
|
|
22
|
-
* queue_update,
|
|
22
|
+
* queue_update, compaction_end, auto_retry_end, successful non-bootstrap
|
|
23
23
|
* response, message_update without text_delta, fire-and-forget extension_ui_request.
|
|
24
24
|
* message_end emits a turn_progress heartbeat (non-terminal, state.turnProgressCount++).
|
|
25
|
+
* compaction_start emits a context_compacted event (user notification); compaction_end is dropped
|
|
26
|
+
* to avoid a duplicate notice.
|
|
25
27
|
*/
|
|
26
28
|
export declare function piRpcLineToNormalized(line: string, state: PIEventParserState): NormalizedEvent[];
|
|
@@ -14,9 +14,11 @@ export function createPIEventParserState() {
|
|
|
14
14
|
* returns [] on subsequent bootstrap hits (Option A per Plan Review N2H-3).
|
|
15
15
|
*
|
|
16
16
|
* Dropped events (return []): turn_start, turn_end, message_start, agent_start,
|
|
17
|
-
* queue_update,
|
|
17
|
+
* queue_update, compaction_end, auto_retry_end, successful non-bootstrap
|
|
18
18
|
* response, message_update without text_delta, fire-and-forget extension_ui_request.
|
|
19
19
|
* message_end emits a turn_progress heartbeat (non-terminal, state.turnProgressCount++).
|
|
20
|
+
* compaction_start emits a context_compacted event (user notification); compaction_end is dropped
|
|
21
|
+
* to avoid a duplicate notice.
|
|
20
22
|
*/
|
|
21
23
|
export function piRpcLineToNormalized(line, state) {
|
|
22
24
|
if (!line)
|
|
@@ -104,6 +106,14 @@ export function piRpcLineToNormalized(line, state) {
|
|
|
104
106
|
if (type === 'auto_retry_start') {
|
|
105
107
|
return [{ type: 'rate_limit', raw: ev }];
|
|
106
108
|
}
|
|
109
|
+
// --- compaction_start → context_compacted (user notification) ---
|
|
110
|
+
// compaction_end is intentionally dropped below to avoid a duplicate notice.
|
|
111
|
+
if (type === 'compaction_start') {
|
|
112
|
+
const reason = typeof ev['reason'] === 'string' && ev['reason'].length > 0
|
|
113
|
+
? ev['reason']
|
|
114
|
+
: 'auto';
|
|
115
|
+
return [{ type: 'context_compacted', trigger: reason }];
|
|
116
|
+
}
|
|
107
117
|
// --- message_end → turn_progress (live heartbeat per assistant turn) ---
|
|
108
118
|
if (type === 'message_end') {
|
|
109
119
|
state.turnProgressCount++;
|
|
@@ -121,7 +131,7 @@ export function piRpcLineToNormalized(line, state) {
|
|
|
121
131
|
return handleExtensionUiRequest(ev);
|
|
122
132
|
}
|
|
123
133
|
// Silently drop all other events (turn_start/end, message_start/end, agent_start,
|
|
124
|
-
// queue_update,
|
|
134
|
+
// queue_update, compaction_end, auto_retry_end, successful non-bootstrap response).
|
|
125
135
|
return [];
|
|
126
136
|
}
|
|
127
137
|
// ---------------------------------------------------------------------------
|