@sayknow-cli/coding-agent 0.7.12 → 0.7.14

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/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.7.14] - 2026-11-02
6
+
7
+ ### Changed
8
+
9
+ - Inside a tool loop, auto-compaction no longer fires at a lowered `compaction.thresholdTokens` on large-window models. A configured threshold (e.g. 150K on a 1M-token model) now applies at answer boundaries (end of a run, before the next prompt); mid-run, compaction waits until the default ceiling (300K) or the model's usable window, whichever is lower. Models whose usable window is at or below the ceiling still compact mid-run at the configured threshold.
10
+ - Threshold compaction after a finished answer (`stop` with no tool calls) no longer prompts an extra continuation turn. A continuation is still sent when the answer was cut off (for example `length`).
11
+
12
+ ### Fixed
13
+
14
+ - After compaction, the active SKC workflow skill (`ultragoal`, `deep-interview`, `ralplan`, `team`) gets its instructions back automatically, so the agent no longer re-reads `SKILL.md` after every compaction. The instructions are restored only for a skill invoked on the current branch and only when they are not already in context.
15
+ - The Telegram daemon no longer logs a warning every few seconds when the bot token is rejected (`getChat` 401). It retries the paired-chat privacy check with exponential backoff (15s up to 10 minutes) and logs each distinct failure once.
16
+ - `ask` no longer crashes with `theme.checkbox` undefined in headless and SDK runs.
17
+ - macOS: coordinator MCP `skc_coordinator_read_artifact` works on macOS. It previously refused every artifact because identity checks needed `/proc`; it now resolves the opened handle through `/dev/fd` and verifies the device and inode.
18
+ - macOS: reusing an existing session import returns the same canonical path (`/private/var/...`) as a fresh import.
19
+
20
+ ## [0.7.13] - 2026-10-26
21
+
22
+ ### Fixed
23
+
24
+ - A transient failure (e.g. `The socket connection was closed unexpectedly`) that cut off a tool call before it ran no longer ends the step with only a failed tool row. When the attempt streamed no answer text, automatic retry, `/retry`, and restart resume drop the cut-off call with its placeholder error result and ask the same model again; the call is never executed or replayed. When answer text was already shown, the step still stops, and a warning now says it was not resumed automatically.
25
+
5
26
  ## [0.7.12] - 2026-10-24
6
27
 
7
28
  ### Added
@@ -345,6 +345,15 @@ export declare class TelegramNotificationDaemon {
345
345
  private readonly flatIdentitySent;
346
346
  /** Cached result of whether the paired chat is a private chat (flat-fallback gate). */
347
347
  private pairedChatPrivate;
348
+ /**
349
+ * Backoff for indeterminate privacy checks. A rejected bot token or a deleted
350
+ * chat fails the same way on every attempt; re-asking on every delivery tick
351
+ * flooded the log (one warning per 4s) and the Bot API. Retry with backoff and
352
+ * warn only when the failure changes.
353
+ */
354
+ private pairedChatPrivacyRetryAt;
355
+ private pairedChatPrivacyFailures;
356
+ private pairedChatPrivacyLastWarning;
348
357
  /** Bot username from getMe, cached once at owner startup for group/forum command targeting. */
349
358
  private botUsername;
350
359
  /** Sessions whose agent loop is currently busy (drives the typing indicator). */
@@ -526,6 +535,12 @@ export declare class TelegramNotificationDaemon {
526
535
  * later.
527
536
  */
528
537
  private resolvePairedChatPrivacy;
538
+ /**
539
+ * Fail closed for now and schedule the next check. A single failure retries on
540
+ * the next attempt (transient errors clear quickly); repeated failures back off
541
+ * exponentially. Warn once per distinct failure.
542
+ */
543
+ private deferPairedChatPrivacy;
529
544
  /** Keep existing outbound callers fail-closed for indeterminate privacy. */
530
545
  private pairedChatIsPrivate;
531
546
  /** Tell the user once (per daemon run) how to enable Threaded Mode. */
@@ -881,6 +881,15 @@ export declare class TelegramNotificationDaemon {
881
881
  private readonly flatIdentitySent;
882
882
  /** Cached result of whether the paired chat is a private chat (flat-fallback gate). */
883
883
  private pairedChatPrivate;
884
+ /**
885
+ * Backoff for indeterminate privacy checks. A rejected bot token or a deleted
886
+ * chat fails the same way on every attempt; re-asking on every delivery tick
887
+ * flooded the log (one warning per 4s) and the Bot API. Retry with backoff and
888
+ * warn only when the failure changes.
889
+ */
890
+ private pairedChatPrivacyRetryAt;
891
+ private pairedChatPrivacyFailures;
892
+ private pairedChatPrivacyLastWarning;
884
893
  /** Bot username from getMe, cached once at owner startup for group/forum command targeting. */
885
894
  private botUsername;
886
895
  /** Sessions whose agent loop is currently busy (drives the typing indicator). */
@@ -1091,6 +1100,12 @@ export declare class TelegramNotificationDaemon {
1091
1100
  * later.
1092
1101
  */
1093
1102
  private resolvePairedChatPrivacy;
1103
+ /**
1104
+ * Fail closed for now and schedule the next check. A single failure retries on
1105
+ * the next attempt (transient errors clear quickly); repeated failures back off
1106
+ * exponentially. Warn once per distinct failure.
1107
+ */
1108
+ private deferPairedChatPrivacy;
1094
1109
  /** Keep existing outbound callers fail-closed for indeterminate privacy. */
1095
1110
  private pairedChatIsPrivate;
1096
1111
  /** Tell the user once (per daemon run) how to enable Threaded Mode. */
@@ -1293,7 +1293,8 @@ export declare class AgentSession {
1293
1293
  * left by a non-graceful process exit after the user/custom/tool-result message
1294
1294
  * was persisted but before the agent emitted a terminal assistant response.
1295
1295
  * Removes only a failed/aborted assistant tail with no visible output or tool
1296
- * calls, then re-attempts with a fresh retry budget.
1296
+ * calls, or a failed tail whose cut-off tool calls never ran (with their placeholder
1297
+ * results), then re-attempts with a fresh retry budget.
1297
1298
  * @returns false when the agent is busy, no retryable tail exists, the tail shows
1298
1299
  * output or tool calls, a persisted recovery is unresolved, or the step dispatched
1299
1300
  * unobservable remote work; true when a retry/resume was scheduled.
@@ -40,6 +40,11 @@ export interface AutoResumeMarker {
40
40
  * recovery drops it and asks the same model again instead of stopping.
41
41
  */
42
42
  export declare function isThinkingOnlyFailure(message: AgentMessage | undefined): boolean;
43
+ /**
44
+ * The transcript before its trailing unexecuted tool-call failure, without the error
45
+ * placeholder results paired with its calls; undefined when the tail is anything else.
46
+ */
47
+ export declare function dropUnexecutedToolCallFailure(messages: readonly AgentMessage[]): AgentMessage[] | undefined;
43
48
  /**
44
49
  * Restart-safe means: an instance of a built-in read-only tool class (seen through
45
50
  * extension/hook interception wrappers) whose wire name is unique among the selected
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/coding-agent",
4
- "version": "0.7.12",
4
+ "version": "0.7.14",
5
5
  "description": "Sayknow-CLI CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -54,12 +54,12 @@
54
54
  "@agentclientprotocol/sdk": "1.3.0",
55
55
  "@babel/parser": "^7.29.3",
56
56
  "@mozilla/readability": "^0.6.0",
57
- "@sayknow-cli/stats": "0.7.12",
58
- "@sayknow-cli/agent-core": "0.7.12",
59
- "@sayknow-cli/ai": "0.7.12",
60
- "@sayknow-cli/natives": "0.7.12",
61
- "@sayknow-cli/tui": "0.7.12",
62
- "@sayknow-cli/utils": "0.7.12",
57
+ "@sayknow-cli/stats": "0.7.14",
58
+ "@sayknow-cli/agent-core": "0.7.14",
59
+ "@sayknow-cli/ai": "0.7.14",
60
+ "@sayknow-cli/natives": "0.7.14",
61
+ "@sayknow-cli/tui": "0.7.14",
62
+ "@sayknow-cli/utils": "0.7.14",
63
63
  "@puppeteer/browsers": "^2.13.0",
64
64
  "@types/turndown": "5.0.6",
65
65
  "@xterm/headless": "^6.0.0",
@@ -252,14 +252,14 @@ export async function safeOpenCoordinatorArtifact(
252
252
  if (typeof artifactPath !== "string" || artifactPath.trim().length === 0)
253
253
  throw new Error("coordinator_artifact_path_required");
254
254
  if (config.allowedRoots.length === 0) throw new Error("coordinator_artifact_roots_required");
255
- if (process.platform !== "linux") throw new Error("artifact_identity_unavailable");
255
+ if (process.platform !== "linux" && process.platform !== "darwin") throw new Error("artifact_identity_unavailable");
256
256
  const requested = path.resolve(artifactPath);
257
257
  await assertCoordinatorArtifactPath(config, requested);
258
258
  const handle = await fs.open(requested, nodeFs.constants.O_RDONLY | nodeFs.constants.O_NOFOLLOW);
259
259
  try {
260
260
  const opened = await handle.stat({ bigint: true });
261
261
  if (!opened.isFile()) throw new Error("artifact_identity_unavailable");
262
- const canonicalTarget = await fs.realpath(`/proc/self/fd/${handle.fd}`);
262
+ const canonicalTarget = await openedArtifactPath(handle, opened);
263
263
  const canonicalStateRoot = await realpathIfExists(config.stateRoot);
264
264
  const roots = await canonicalAllowedRoots(config);
265
265
  if (isInside(canonicalTarget, canonicalStateRoot)) throw new Error("coordinator_artifact_state_root_denied");
@@ -271,3 +271,14 @@ export async function safeOpenCoordinatorArtifact(
271
271
  throw error;
272
272
  }
273
273
  }
274
+
275
+ /** Canonical path of an opened artifact, derived from the handle rather than the racy requested pathname. */
276
+ async function openedArtifactPath(handle: fs.FileHandle, opened: nodeFs.BigIntStats): Promise<string> {
277
+ if (process.platform === "linux") return fs.realpath(`/proc/self/fd/${handle.fd}`);
278
+ // darwin has no /proc; Bun resolves /dev/fd/N via fcntl(F_GETPATH), which follows the opened inode.
279
+ const fdPath = `/dev/fd/${handle.fd}`;
280
+ const canonical = await fs.realpath(fdPath).catch(() => fdPath);
281
+ const named = canonical === fdPath ? null : await fs.lstat(canonical, { bigint: true }).catch(() => null);
282
+ if (!named || named.dev !== opened.dev || named.ino !== opened.ino) throw new Error("artifact_identity_unavailable");
283
+ return canonical;
284
+ }
@@ -20,7 +20,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
20
20
  "bridge.md": "# Bridge Protocol Reference (Experimental, Fail-Closed)\n\nBridge mode runs the coding agent as an experimental network control surface over\nHTTPS. The session-control surface is intentionally **fail-closed by default**\nwhile the bridge security model is hardened.\n\nDefault availability:\n\n- `GET /healthz` is available without auth and returns `{ \"status\": \"ok\" }`.\n- `GET /v1/help` is available without auth and reports the fail-closed endpoint\n matrix.\n- `POST /v1/handshake` remains authenticated, but the default response advertises\n no enabled session endpoints, no accepted capabilities, no accepted scopes, and\n no frame types.\n- `GET /v1/sessions/{session_id}/events` fails closed with\n `403 endpoint_disabled` after bearer auth succeeds.\n- `POST /v1/sessions/{session_id}/commands` fails closed with\n `403 endpoint_disabled` after bearer auth succeeds and before body parsing,\n command validation, scope checks, or dispatch.\n- `POST /v1/sessions/{session_id}/control:claim` and\n `POST /v1/sessions/{session_id}/control:disconnect` fail closed with\n `403 endpoint_disabled` after bearer auth succeeds.\n- `POST /v1/sessions/{session_id}/ui-responses/{correlation_id}` fails closed\n with `403 endpoint_disabled` after bearer auth succeeds and before body parsing\n or controller checks.\n- `POST /v1/sessions/{session_id}/host-tool-results/{correlation_id}` and\n `POST /v1/sessions/{session_id}/host-uri-results/{correlation_id}` fail closed\n with `403 endpoint_disabled` after bearer auth succeeds and before body parsing\n or host callback handling.\n\nThe implementation still contains the v1 protocol scaffolding and internal tests\nfor the previously enabled surface, but external clients must treat events,\ncommands, controller ownership, UI responses, host tool results, and host URI\nresults as unavailable unless a future release explicitly re-enables them.\n\nPrimary implementation:\n\n- `src/modes/bridge/bridge-mode.ts`\n- `src/modes/bridge/auth.ts`\n- `src/modes/bridge/event-stream.ts`\n- `src/modes/bridge/bridge-client-bridge.ts`\n- `src/modes/bridge/bridge-ui-context.ts`\n- `src/modes/shared/agent-wire/*` (protocol, scopes, handshake, command dispatch/validation, host bridges)\n- `packages/bridge-client/src/*`\n\n## Startup\n\n```bash\nskc --mode bridge [regular CLI options]\n```\n\nBehavior notes:\n\n- The bridge is served over **HTTPS only**. Startup refuses to bind without TLS\n configured (see Security and TLS). There is no unencrypted startup path.\n- `@file` CLI arguments are rejected in bridge mode (as in RPC mode).\n- Bridge mode reuses the RPC default-setting overrides and suppresses automatic\n session title generation.\n- One bridge process serves exactly **one live `AgentSession`**.\n- The default endpoint matrix disables session events, commands, controller\n ownership, UI responses, host tool results, and host URI results.\n\n### Configuration (environment variables)\n\nSee `docs/environment-variables.md` for the authoritative table. Summary:\n\n| Variable | Required | Default | Notes |\n| --- | --- | --- | --- |\n| `SKC_BRIDGE_TOKEN` | Yes | — | Bearer token for authenticated endpoints. **Secret — never commit.** |\n| `SKC_BRIDGE_TLS_CERT` | Yes | — | Path to the TLS certificate (PEM). |\n| `SKC_BRIDGE_TLS_KEY` | Yes | — | Path to the TLS private key (PEM). **Secret — never commit.** |\n| `SKC_BRIDGE_HOST` | No | `127.0.0.1` | Bind hostname. |\n| `SKC_BRIDGE_PORT` | No | `4077` | Bind port (1–65535). |\n| `SKC_BRIDGE_SCOPES` | No | `prompt` | Parsed for internal compatibility, but default session endpoints are fail-closed. |\n\n## Security and TLS\n\nThe bridge is a network control surface, so it is **secure-by-default**:\n\n- **TLS is mandatory for every bind, including loopback.** Startup fails closed\n with a clear error if `SKC_BRIDGE_TLS_CERT` and `SKC_BRIDGE_TLS_KEY` are not\n both set. There is no plaintext fallback and no insecure/trust-bypass switch.\n- **Bearer token is mandatory** for every endpoint except `GET /healthz` and\n `GET /v1/help`.\n- The TypeScript SDK refuses bearer-token clients over non-`https` URLs by\n default. It allows plaintext only for `localhost`, `127.0.0.1`, or `[::1]`\n when the caller explicitly passes the localhost/test opt-in.\n- Session endpoints fail closed by default even when bearer auth and scopes are\n otherwise valid.\n\n## Handshake\n\n```\nPOST /v1/handshake (authenticated)\n```\n\nThe client sends its supported protocol version range, requested capabilities,\nand requested scopes. Version mismatch returns `status: \"rejected\"`,\n`reason: \"incompatible_version\"`. Malformed request bodies return\n`400 invalid_request`.\n\nIn the default fail-closed configuration, a successful authenticated\nhandshake returns:\n\n- `protocol_version` — the server protocol version (`BRIDGE_PROTOCOL_VERSION`, `2`).\n- `session_id` — the single session id this bridge serves.\n- `accepted_capabilities` — empty.\n- `accepted_scopes` — empty.\n- `unsupported` — every requested capability.\n- `endpoints` — all session endpoint descriptors present but empty strings.\n- `frame_types` — empty.\n\n## Fail-Closed Endpoint Matrix\n\nThe disabled endpoint matrix is:\n\n| Surface | Endpoint(s) | Default |\n| --- | --- | --- |\n| Events | `GET /v1/sessions/{session_id}/events?last_seq=<n>` | Disabled |\n| Commands | `POST /v1/sessions/{session_id}/commands` | Disabled |\n| Control | `POST /v1/sessions/{session_id}/control:claim`, `POST /v1/sessions/{session_id}/control:disconnect` | Disabled |\n| UI responses | `POST /v1/sessions/{session_id}/ui-responses/{correlation_id}` | Disabled |\n| Host tool results | `POST /v1/sessions/{session_id}/host-tool-results/{correlation_id}` | Disabled |\n| Host URI results | `POST /v1/sessions/{session_id}/host-uri-results/{correlation_id}` | Disabled |\n\nAuthenticated requests to disabled endpoints return:\n\n```json\n{ \"error\": \"endpoint_disabled\", \"endpoint\": \"commands\" }\n```\n\nThe `endpoint` value is one of `events`, `commands`, `control`, `uiResponses`,\n`hostToolResults`, or `hostUriResults`.\n\n## Protocol Catalog Kept for Internal Compatibility\n\nThe bridge protocol module still defines the v1 command and scope catalog so\nexisting internal tests can validate the dormant implementation and future\nre-enable work has a stable baseline.\n\nWhen internally enabled for compatibility tests, event replay still uses `last_seq` and the bounded replay reset marker `replay_window_exceeded`; command and UI response retries still use `Idempotency-Key`. These mechanisms are dormant for default external bridge clients because the endpoint matrix rejects the endpoints before they reach replay, body parsing, idempotency, scope, or dispatch logic.\n\nWorkflow-gate responses are part of the UI-response surface, not the dormant command surface: when internally enabled, an answerer responds to `workflow_gate` frame `wg_...` by posting `{ \"gate_id\": \"wg_...\", \"answer\": ... }` to `POST /v1/sessions/{session_id}/ui-responses/{gate_id}`. Gate answers are authorized by bearer auth, the `control` scope on this (default-disabled) endpoint, and the currently claimed controller owner token. `X-SKC-Bridge-Owner-Token` must match the claimed controller token; mismatches return `403 not_controller` and do not resolve the gate. `Idempotency-Key` is optional and is also forwarded as `idempotency_key` when supplied by SDK helpers.\n\n### Scopes\n\nThe configurable scope set (`BRIDGE_COMMAND_SCOPES`) is:\n\n- `prompt`\n- `control`\n- `bash`\n- `export`\n- `session`\n- `model`\n- `message:read`\n- `host_tools`\n- `host_uri`\n- `admin`\n\nThe mandatory compliance floor (`MANDATORY_FLOOR_COMMAND_SCOPES`) remains\n`prompt` for the dormant command surface. Because commands are disabled by the\nendpoint matrix, the default handshake advertises no accepted scopes.\n\n### Command catalog and scope mapping\n\n| Command | Scope |\n| --- | --- |\n| `prompt` | `prompt` |\n| `steer` | `prompt` |\n| `follow_up` | `prompt` |\n| `abort` | `prompt` |\n| `abort_and_prompt` | `prompt` |\n| `new_session` | `session` |\n| `get_state` | `message:read` |\n| `set_todos` | `control` |\n| `set_host_tools` | `host_tools` |\n| `set_host_uri_schemes` | `host_uri` |\n| `get_pending_workflow_gates` | `message:read` |\n| `set_capabilities` | `control` |\n| `set_model` | `model` |\n| `set_default_model_selection` | `model` |\n| `cycle_model` | `model` |\n| `get_available_models` | `model` |\n| `set_thinking_level` | `model` |\n| `cycle_thinking_level` | `model` |\n| `set_steering_mode` | `control` |\n| `set_follow_up_mode` | `control` |\n| `set_interrupt_mode` | `control` |\n| `compact` | `control` |\n| `set_auto_compaction` | `control` |\n| `set_auto_retry` | `control` |\n| `abort_retry` | `control` |\n| `bash` | `bash` |\n| `abort_bash` | `bash` |\n| `get_session_stats` | `message:read` |\n| `export_html` | `export` |\n| `switch_session` | `session` |\n| `branch` | `session` |\n| `get_branch_messages` | `session` |\n| `get_last_assistant_text` | `message:read` |\n| `set_session_name` | `session` |\n| `handoff` | `admin` |\n| `get_messages` | `message:read` |\n| `get_login_providers` | `admin` |\n| `login` | `admin` |\n| `negotiate_unattended` | `control` |\n| `workflow_gate_response` | `control` |\n\n### Dormant capabilities and frame types\n\nThese names remain in the protocol code for future compatibility and internal\nconformance tests, but they are not advertised by the default fail-closed\nhandshake:\n\nCapabilities: `events`, `prompt`, `permission`, `elicitation`, `ui.declarative`,\n`host_tools`, `host_uri`, `workflow_gate`.\n\nFrame types: `ready`, `event`, `response`, `ui_request`, `permission_request`,\n`host_tool_call`, `host_uri_request`, `reset`, `workflow_gate`, `error`.\n\n## UI Capability Parity\n\nBridge UI parity remains **semantic, not pixel-perfect** when the dormant UI\nsurface is explicitly enabled for internal validation. Local-only UI capabilities\ncontinue to report typed unsupported results instead of silent defaults:\n\n- `ui.terminal_input`\n- `ui.widget.component`\n- `ui.footer.component`\n- `ui.header.component`\n- `ui.custom.component`\n- `ui.editor.get_text`\n- `ui.editor.component`\n- `ui.tools_expanded`\n- Theme switching is unsupported (`setTheme` returns `{ success: false }`).\n\n## SDK Usage\n\n`@sayknow-cli/bridge-client` exposes `BridgeClient` with handshake, command\nhelpers mirroring the full RPC command catalog, an `events()` async generator,\ncontroller/UI/host-callback helpers, and an idempotency-key helper. The bridge\nsession-control surface remains fail-closed by default, so against an\nunconfigured bridge those helpers should be expected to fail because the server\nendpoint matrix disables the corresponding session endpoints until they are\nexplicitly enabled.\n\n`BridgeClient.respondGate(sessionId, gateId, ownerToken, answer, options)` posts to the fail-closed UI-response endpoint and returns the gate resolution envelope emitted by the bridge. It deliberately does not send `workflow_gate_response` through `/commands`. Gate answers are authorized by bearer auth, the `control` scope on the (by-default-disabled) `ui-responses` endpoint, and the current controller owner token; unauthorized owner-token attempts return `403 not_controller` without resolving the gate.\n\n> Response typing: in this experimental version, `command()` and the typed\n> command helpers return `Promise<unknown>`. Callers narrow the response\n> themselves. Importing `@sayknow-cli/coding-agent` internal `rpc-types` into the\n> SDK is intentionally avoided to preserve the package boundary; stable shared\n> protocol response types are tracked as follow-up work.\n\n## Limitations\n\n- **Single session per process.** A bridge process serves exactly one live\n `AgentSession`. The `session_id` is present in every frame and endpoint for\n ordering and future additive multiplexing, but multi-session multiplexing is\n **not** implemented in v1.\n- Session events, commands, controller ownership, UI responses, host tool\n results, and host URI results are disabled by default.\n- Coarse per-token scopes only (no fine-grained per-command policy yet).\n- UI parity is semantic, not pixel-perfect (see UI Capability Parity).\n\n## Hermes/Claw orchestration layering\n\nFor Hermes/Claw-style orchestration, treat `skc` as an external runner. The orchestration agent should choose or create the repository checkout first, preferably a dedicated Git worktree for branch-local work, then launch or attach a leader session with `skc --tmux` from that directory. SKC is not embedded runtime injection into Hermes, Claw Code, or another coding tool.\n\nPublic orchestration boundaries:\n\n1. Choose the repo/worktree and branch that will own changes, logs, and review evidence.\n2. Start or attach the SKC leader with `skc --tmux` from that directory. If you want SKC to create the sibling worktree, use `skc --tmux --worktree <branch-like-name>`; the argument is a worktree/branch name, not a filesystem path.\n3. Submit the workflow appropriate to the task: `/skill:deep-interview` for requirements discovery, `/skill:ralplan` for plan consensus, and `skc ultragoal ...` for durable goal tracking through execution and verification.\n4. Use `skc team ...` only when coordinated parallel tmux workers help with implementation or verification; single-lane work should stay in the leader session.\n5. Collect the handoff state: whether the session stopped cleanly, changed files, commands/checks run, failures, unresolved risks, and evidence summaries.\n\nBridge mode remains the public remote-control protocol for an already-running SKC session, but the session-control endpoints are fail-closed by default. Keep lifecycle, worktree selection, and evidence policy above the bridge frames, and avoid documenting private deployment, routing, or credential internals. Introducing another authenticated remote-control protocol for the same purpose should require ADR-level rationale.\n\nThe same external-runner workflow is summarized in the README section [Using SKC with other coding agents](../README.md#using-skc-with-other-coding-agents).\n",
21
21
  "codebase-overview.md": "# Codebase Overview\n\nThis document maps the main parts of the `sayknow-cli` repository. The root README stays intentionally small; this file is the architecture-oriented companion.\n\n## Product shape\n\nSayknow-CLI (`skc`) is centered on `packages/coding-agent/`. The public workflow surface is intentionally fixed at four source-bundled skills and four public role subagents. Runtime state, specs, plans, goals, team state, and local overrides live under `.skc/`.\n\nDefault workflow skills are embedded from:\n\n```text\npackages/coding-agent/src/defaults/skc/skills/<name>/SKILL.md\n```\n\nPublic role subagent prompts are embedded from:\n\n```text\npackages/coding-agent/src/prompts/agents/<role>.md\n```\n\nThe runtime can still discover project/user overrides, but the bundled defaults are loaded from source so a missing project `.skc` directory does not remove the default workflow surface.\n\n## Packages\n\n### `packages/coding-agent/`\n\nMain `skc` CLI and product runtime.\n\n- `packages/coding-agent/package.json` exposes the `skc` binary at `src/cli.ts` and the SDK/barrel entrypoint at `src/index.ts`.\n- `packages/coding-agent/src/cli.ts` is the executable bootstrap. It registers CLI commands such as `setup`, `deep-interview`, `ralplan`, `ultragoal`, `team`, and the default launch path.\n- `packages/coding-agent/src/main.ts` adapts CLI options into session creation and dispatches interactive, print, and ACP modes; external machine clients use the SDK WebSocket interface.\n- `packages/coding-agent/src/sdk/session.ts` assembles settings, model registry, auth, workspace/context discovery, skills, rules, tools, system prompt, and the underlying `@sayknow-cli/agent-core` agent.\n- `packages/coding-agent/src/tools/index.ts` is the built-in tool registry for file/code/runtime tools such as read, bash, edit, AST tools, eval, find/search, LSP, browser, task/subagent, recipe, IRC, todo, web search, and write. Memory backends are private integrations, not public coding-harness tools.\n- `packages/coding-agent/src/defaults/skc-defaults.ts` embeds and installs the default workflow skills.\n- `packages/coding-agent/src/task/agents.ts` embeds bundled task-agent prompts. The public contract is `executor`, `architect`, `planner`, and `critic`; other bundled prompts are internal/runtime utilities.\n- `packages/coding-agent/src/coordinator/contract.ts` defines the transport-neutral third-party coordinator contract used by `skc mcp-serve coordinator`, `skc coordinator`, and `skc setup hermes`.\n- `packages/coding-agent/src/coordinator-mcp/server.ts` implements the outward MCP adapter for bot/coordinator integrations, including session start/register, turn state, question answering, status reports, and artifact reads.\n- `docs/external-control-readiness.md` classifies the public external-control surfaces: SDK WebSocket for live session control, Coordinator MCP for multi-session control planes, and ACP for editor/ACP clients. `docs/bot-integration.md` is the end-to-end guide for external controller authors.\n\n### `packages/ai/`\n\nProvider/model boundary for LLM access.\n\n- `packages/ai/src/index.ts` exports model registry/resolution, provider implementations, auth broker/gateway/storage, streaming, usage, retry/overflow utilities, OAuth, discovery, and validation helpers.\n- `packages/ai/src/types.ts` defines provider, model, context, message, tool, usage, reasoning, and stream-event contracts.\n- `packages/ai/src/stream.ts` dispatches model-driven streams to the right provider/API implementation and normalizes streaming events.\n- `packages/ai/src/model-manager.ts` merges static, cached, dynamic, and remote model sources.\n- `packages/ai/README.md` documents tool calling, partial streaming tool calls, thinking/reasoning, provider configuration, context handoff, and OAuth flows.\n\n### `packages/agent/`\n\nStateful agent runtime built on `@sayknow-cli/ai`.\n\n- `packages/agent/src/index.ts` exports the `Agent`, loop APIs, append-only context, compaction, telemetry, proxy utilities, thinking helpers, and shared types.\n- `packages/agent/src/agent-loop.ts` owns the turn loop: transform context, call the model stream, execute tool calls, append tool results, and emit lifecycle events.\n- `packages/agent/src/agent.ts` wraps the loop with mutable state, subscriptions, prompt/continue/abort APIs, queues, provider session state, telemetry, and state mutation helpers.\n- `packages/agent/src/types.ts` defines `AgentMessage`, `AgentTool`, loop config, event, and runtime state contracts.\n\n### `packages/tui/`\n\nTerminal UI framework used by the CLI.\n\n- `packages/tui/src/index.ts` exports components, keybindings, autocomplete, terminal abstractions, image support, TUI core, and utilities.\n- `packages/tui/src/tui.ts` manages component rendering, focus, overlays, terminal dimensions, diff state, and synchronized output.\n- `packages/tui/src/terminal.ts` abstracts terminal lifecycle, dimensions, cursor controls, title/progress, Kitty protocol state, and appearance notifications.\n- `packages/tui/README.md` documents the component model and built-in components such as text, input, editor, markdown, loaders, select/settings lists, spacer, image, box, and container.\n\n### `packages/natives/` and Rust crates\n\nNative helper layer exposed through N-API.\n\n- `packages/natives/package.json` exports `native/index.js` and generated TypeScript definitions.\n- `packages/natives/native/loader-state.js` resolves platform/CPU-specific native binaries and validates package/native version alignment.\n- `crates/pi-natives/src/lib.rs` is the N-API root for appearance, AST search/editing, clipboard, filesystem scan/cache, grep/glob, syntax highlighting, HTML-to-Markdown, keyboard parsing, process/PTY/shell support, SIXEL, code summarization, token counting, text measurement/wrapping/truncation, workspace scanning, power assertions, and isolation helpers.\n- `crates/pi-shell/src/lib.rs` exposes brush-based shell execution primitives used by the native shell adapter.\n- `crates/pi-shell/src/shell.rs` implements persistent and one-shot shell execution, streaming, environment handling, cancellation, and output minimizer telemetry.\n- `crates/pi-shell/src/fixup.rs` performs conservative AST-based bash command fixups.\n- `crates/pi-natives/src/pty.rs` implements interactive PTY sessions.\n\n### `packages/utils/`\n\nShared TypeScript utilities.\n\n- `packages/utils/src/index.ts` exports abortable/async helpers, color/env/dir utilities, fetch retry, formatting, frontmatter, glob helpers, JSON helpers, logging, MIME detection, prompt rendering, process-tree helpers, sanitization, streams, temp files, tab spacing, type guards, and executable lookup.\n- `packages/utils/src/ptree.ts` and `packages/utils/src/procmgr.ts` wrap native process helpers for ergonomic TypeScript use.\n\n### `packages/stats/`\n\nLocal observability dashboard for session and model usage.\n\n- `packages/stats/src/index.ts` exposes the `skc-stats` CLI entrypoint and exports aggregation/server APIs.\n- `packages/stats/src/aggregator.ts` parses session-derived request metrics and writes aggregated data through SQLite.\n- `packages/stats/src/server.ts` serves local dashboard API routes and static SPA assets.\n- `packages/stats/src/types.ts` and `packages/stats/src/shared-types.ts` define dashboard and aggregate metric shapes.\n\n### `packages/typescript-edit-benchmark/`\n\nPrivate benchmark package for TypeScript edit tasks.\n\n- `packages/typescript-edit-benchmark/package.json` exposes `typescript-edit-benchmark` and depends on the coding-agent, agent-core, ai, tui, utils, diff, prettier, and Babel tooling.\n- `packages/typescript-edit-benchmark/src/index.ts` is the benchmark CLI: it resolves fixtures, loads tasks, runs edit attempts, records progress, and writes reports/conversation dumps under `runs/`.\n\n## Python packages\n\n### External machine interfaces\n\nExternal machine clients use the SDK WebSocket interface documented in `docs/sdk.md`. Coordinator MCP supplies multi-session orchestration, while ACP remains the stdio editor protocol. The former Python RPC client and bot integration paths were removed with the RPC ingress mode.\n\n## Runtime flow\n\nA normal CLI session starts in `packages/coding-agent/src/cli.ts`, routes through command handling, then reaches `packages/coding-agent/src/main.ts`. `main.ts` converts CLI/runtime settings into `CreateAgentSessionOptions` and calls `createAgentSession()` in `packages/coding-agent/src/sdk/session.ts`.\n\nThe SDK builds the session context, loads the default skills, creates built-in tools, resolves model/auth state through `@sayknow-cli/ai`, constructs the system prompt, and instantiates `@sayknow-cli/agent-core`. The agent loop streams model events, executes tools, records tool results, and hands state back to the selected interactive TUI, print, or ACP mode while exposing external control through the SDK WebSocket interface.\n\n## Verification and gates\n\nPackage-local checks are defined in each `package.json`. For workflow-definition or default-surface changes, the focused gates are:\n\n```sh\nbun scripts/check-visible-definitions.ts\nbun scripts/verify-g002-gates.ts\nbun scripts/rebrand-inventory.ts --strict\nbun test packages/coding-agent/test/default-skc-definitions.test.ts\n```\n\nFor broader TypeScript verification, use the root script:\n\n```sh\nbun run check:ts\n```\n\nDo not use `tsc` or `npx tsc` directly in this repository.\n",
22
22
  "codegraph-custom-tool.md": "# CodeGraph as a custom tool\n\n[CodeGraph](https://github.com/colbymchenry/codegraph) is a local, language-agnostic\ncode knowledge graph for AI agents. It pre-indexes symbols, call edges, and\ndependencies in a project so an agent can answer structural questions (\"how does X\nwork\", \"who calls X\", \"what breaks if I change X\") in a few graph queries instead\nof crawling files with `search`/`read`.\n\nThis guide shows how to wire CodeGraph into SKC through the **custom-tool extension\npath** — no core changes, no built-in provider. SKC intentionally keeps third-party\nCLI integrations like this in the user/project extension layer rather than bundling\nthem, so you own the integration and its lifecycle.\n\n> CodeGraph integrates with other agents over MCP, but this guide wires it as a SKC\n> custom tool around CodeGraph's local **CLI** — it does not add an MCP server or a\n> built-in provider. For how SKC treats MCP servers in standalone sessions, see\n> [`standalone-mcp.md`](standalone-mcp.md).\n\n## 1. Install and index\n\n```bash\n# Install the CodeGraph CLI (or use the install script from CodeGraph's README).\nnpm i -g @colbymchenry/codegraph\n\n# Build the local index for a project.\ncd your-project\ncodegraph init\n```\n\n`codegraph init` creates a local `.codegraph/` directory. No data leaves your\nmachine — it is a local SQLite index.\n\n## 2. Add the custom tool\n\nSKC discovers custom tools from a `tools/` directory in its config dirs:\n\n- **Project-scoped**: `<project>/.skc/tools/`\n- **User-scoped (all projects)**: `~/.skc/agent/tools/`\n\nA `*.ts` tool file's default export is a factory `(pi) => CustomTool`. The factory\nreceives an API (`pi`) with members such as `exec`, `cwd`, `zod`, and `logger` — so\nthe tool needs no imports from SKC internals.\n\nSave the following as `.skc/tools/codegraph.ts` (project) or\n`~/.skc/agent/tools/codegraph.ts` (user):\n\n```typescript\n/**\n * CodeGraph custom tool for sayknow-cli (SKC).\n *\n * Wraps the local CodeGraph CLI (https://github.com/colbymchenry/codegraph) so the\n * agent can query a project's code knowledge graph instead of crawling files.\n *\n * It only runs CodeGraph's query-style (read-only) subcommands and never edits your\n * source files. It does not run indexing or sync commands. (CodeGraph maintains its\n * own local `.codegraph/` index via its own CLI; this tool only reads from it.)\n *\n * Prereqs: `npm i -g @colbymchenry/codegraph` and `codegraph init` in the project.\n */\nimport type { CustomToolFactory } from \"@sayknow-cli/coding-agent\"; // optional: editor types only\n\nconst CODEGRAPH_CLI = \"codegraph\";\nconst TIMEOUT_MS = 60_000;\nconst SEARCH_LIMIT_DEFAULT = 10;\nconst MAX = 100;\n\nconst codegraph: CustomToolFactory = (pi) => {\n\tconst z = pi.zod;\n\n\tconst parameters = z\n\t\t.object({\n\t\t\top: z\n\t\t\t\t.enum([\"explore\", \"search\", \"callers\", \"callees\", \"impact\", \"status\"])\n\t\t\t\t.describe(\n\t\t\t\t\t\"explore: context (relevant source + call paths) for a natural-language query — prefer for 'how does X work'; search: full-text symbol search (target=query); callers: who calls target; callees: what target calls; impact: blast radius of changing target; status: index health (no target).\",\n\t\t\t\t),\n\t\t\ttarget: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t\"For explore: a natural-language query or symbol(s). For callers/callees/impact: a symbol name. For search: the query. Omit for status.\",\n\t\t\t\t),\n\t\t\tlimit: z.number().int().min(1).max(MAX).optional().describe(`Max search results (default ${SEARCH_LIMIT_DEFAULT}).`),\n\t\t\tmaxFiles: z.number().int().min(1).max(MAX).optional().describe(\"For explore: cap files whose source is included.\"),\n\t\t})\n\t\t.strict();\n\n\ttype Params = import(\"zod/v4\").infer<typeof parameters>;\n\n\tfunction buildArgs(params: Params): string[] {\n\t\tif (params.op === \"status\") return [\"status\", pi.cwd, \"--json\"];\n\t\tconst target = params.target?.trim();\n\t\tif (!target) throw new Error(`codegraph ${params.op} requires a non-empty \"target\".`);\n\t\tif (params.op === \"search\") {\n\t\t\tconst limit = Math.min(params.limit ?? SEARCH_LIMIT_DEFAULT, MAX);\n\t\t\treturn [\"query\", target, \"--json\", \"--limit\", String(limit), \"--path\", pi.cwd];\n\t\t}\n\t\tif (params.op === \"explore\") {\n\t\t\tconst args = [\"explore\", target, \"--path\", pi.cwd];\n\t\t\tif (params.maxFiles !== undefined) args.push(\"--max-files\", String(params.maxFiles));\n\t\t\treturn args;\n\t\t}\n\t\treturn [params.op, target, \"--json\", \"--path\", pi.cwd];\n\t}\n\n\tfunction ref(r: { name: string; kind: string; filePath: string; startLine: number }): string {\n\t\treturn ` - ${r.name} (${r.kind}) — ${r.filePath}:${r.startLine}`;\n\t}\n\n\tfunction render(params: Params, stdout: string): string {\n\t\tif (params.op === \"explore\") return stdout.trim() || `No exploration results for \"${params.target?.trim() ?? \"\"}\".`;\n\t\tlet data: any;\n\t\ttry {\n\t\t\tdata = JSON.parse(stdout);\n\t\t} catch {\n\t\t\tthrow new Error(`codegraph ${params.op} returned unparseable output.`);\n\t\t}\n\t\tif (params.op === \"search\") {\n\t\t\tconst hits = data as Array<{ node: any }>;\n\t\t\tif (hits.length === 0) return `No symbols matched \"${params.target?.trim() ?? \"\"}\".`;\n\t\t\treturn [\n\t\t\t\t`${hits.length} symbol(s) matching \"${params.target?.trim() ?? \"\"}\":`,\n\t\t\t\t...hits.map(({ node }) => {\n\t\t\t\t\tconst exp = node.isExported ? \" [exported]\" : \"\";\n\t\t\t\t\tconst sig = node.signature ? ` ${node.signature}` : \"\";\n\t\t\t\t\treturn ` - ${node.name} (${node.kind})${sig}${exp} — ${node.filePath}:${node.startLine}`;\n\t\t\t\t}),\n\t\t\t].join(\"\\n\");\n\t\t}\n\t\tif (params.op === \"callers\") {\n\t\t\tconst list = data.callers ?? [];\n\t\t\treturn list.length === 0\n\t\t\t\t? `No callers found for \"${data.symbol}\".`\n\t\t\t\t: [`${list.length} caller(s) of \"${data.symbol}\":`, ...list.map(ref)].join(\"\\n\");\n\t\t}\n\t\tif (params.op === \"callees\") {\n\t\t\tconst list = data.callees ?? [];\n\t\t\treturn list.length === 0\n\t\t\t\t? `\"${data.symbol}\" has no recorded callees.`\n\t\t\t\t: [`${list.length} callee(s) of \"${data.symbol}\":`, ...list.map(ref)].join(\"\\n\");\n\t\t}\n\t\tif (params.op === \"impact\") {\n\t\t\tconst header = `Impact of changing \"${data.symbol}\" (depth ${data.depth}): ${data.nodeCount} node(s), ${data.edgeCount} edge(s) affected.`;\n\t\t\tconst list = data.affected ?? [];\n\t\t\treturn list.length === 0 ? header : [header, \"Affected:\", ...list.map(ref)].join(\"\\n\");\n\t\t}\n\t\t// status\n\t\tif (!data.initialized) return `CodeGraph is not initialized for ${data.projectPath}. Run \\`codegraph init\\`.`;\n\t\tconst lines = [\n\t\t\t`CodeGraph index for ${data.projectPath}:`,\n\t\t\t` files: ${data.fileCount}, nodes: ${data.nodeCount}, edges: ${data.edgeCount}`,\n\t\t];\n\t\tif (data.languages?.length) lines.push(` languages: ${data.languages.join(\", \")}`);\n\t\tconst p = data.pendingChanges;\n\t\tif (p && (p.added || p.modified || p.removed)) lines.push(` pending sync: +${p.added} ~${p.modified} -${p.removed}`);\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\treturn {\n\t\tname: \"codegraph\",\n\t\tlabel: \"CodeGraph\",\n\t\tdescription:\n\t\t\t\"Query the project's CodeGraph code knowledge graph (symbols, callers, callees, impact, and an 'explore' context query) via the local codegraph CLI. Read-only with respect to your source. Prefer over search/read for structural questions. Requires `codegraph init` to have been run in the project.\",\n\t\tparameters,\n\t\tstrict: true,\n\t\tasync execute(_id: string, params: Params, _onUpdate: unknown, _ctx: unknown, signal?: AbortSignal) {\n\t\t\tlet result: { stdout: string; stderr: string; code: number };\n\t\t\ttry {\n\t\t\t\tresult = await pi.exec(CODEGRAPH_CLI, buildArgs(params), { cwd: pi.cwd, signal, timeout: TIMEOUT_MS });\n\t\t\t} catch (e) {\n\t\t\t\tconst msg = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (/not found|enoent/i.test(msg)) {\n\t\t\t\t\tthrow new Error(\"The `codegraph` CLI is not installed. Install it: npm i -g @colbymchenry/codegraph\");\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst err = result.stderr.toLowerCase();\n\t\t\t\tif (err.includes(\"not initialized\") || err.includes(\".codegraph\") || err.includes(\"no index\")) {\n\t\t\t\t\tthrow new Error(\"CodeGraph is not initialized for this project. Run `codegraph init` in the project root.\");\n\t\t\t\t}\n\t\t\t\tthrow new Error(result.stderr.trim() || \"codegraph failed with no diagnostic output.\");\n\t\t\t}\n\t\t\treturn { content: [{ type: \"text\", text: render(params, result.stdout) }] };\n\t\t},\n\t};\n};\n\nexport default codegraph;\n```\n\nThe `import type` line is optional — it only provides editor types when SKC is\nresolvable from your tool file. It is erased at runtime, so the tool loads fine\nwithout it.\n\n## 3. Use it\n\nStart SKC in the project. The `codegraph` tool is now available to the model. Ask\na structural question and it will call the tool, for example:\n\n- `codegraph` with `{ \"op\": \"explore\", \"target\": \"how requests are routed\" }` can\n return relevant source plus graph context in one call.\n- `{ \"op\": \"callers\", \"target\": \"MyClass.handle\" }` lists callers.\n- `{ \"op\": \"impact\", \"target\": \"parseConfig\" }` shows what a change would affect.\n- `{ \"op\": \"status\" }` reports index health.\n\n## Operations\n\n| `op` | `target` | Description |\n| --- | --- | --- |\n| `explore` | natural-language query | Context query: relevant symbols' source plus graph context (CodeGraph's `explore`). `maxFiles` caps included source. |\n| `search` | query | Full-text symbol search (`limit`, default 10). |\n| `callers` | symbol | Functions/methods that call the symbol, including dynamic dispatch. |\n| `callees` | symbol | Functions/methods the symbol calls. |\n| `impact` | symbol | Blast radius of changing the symbol. |\n| `status` | — | Index health: file/node/edge counts, languages, pending sync. |\n\n## Notes\n\n- **Read-only with respect to your code.** The tool only runs CodeGraph's\n query-style subcommands; it never edits your files and does not run indexing or\n sync commands. CodeGraph maintains its own local `.codegraph/` index via its CLI.\n If results look stale or `status` reports pending changes, refresh the index with\n CodeGraph's CLI (e.g. `codegraph sync`) outside SKC.\n- **Safe argument handling.** The example spawns CodeGraph with argv arrays via\n `pi.exec` (no shell), `op` is constrained to a fixed enum, and numeric inputs are\n capped — there is no shell interpolation of model-provided values.\n- **Scope.** Use a project-scoped file to limit the tool to one repo, or a\n user-scoped file to make it available everywhere `codegraph init` has been run.\n- **Naming.** The tool registers as `codegraph`; rename it in the file if it\n collides with another tool in your setup.\n- **Fallback.** If the graph reports a symbol is missing, a file is flagged as\n pending sync, or you need a non-structural text search, refresh the CodeGraph\n index outside SKC or fall back to `read`/`search`.\n- For background on how SKC treats external tools and MCP servers in standalone\n sessions, see [`standalone-mcp.md`](standalone-mcp.md).\n",
23
- "compaction.md": "# Compaction and Branch Summaries\n\nCompaction and branch summaries are the two mechanisms that keep long sessions usable without losing prior work context.\n\n- **Compaction** rewrites old history into a summary on the current branch.\n- **Branch summary** captures abandoned branch context during `/tree` navigation.\n\nBoth are persisted as session entries and converted back into user-context messages when rebuilding LLM input.\n\n## Key implementation files\n\n- `packages/agent/src/compaction/compaction.ts` (context-full summarization and handoff generation)\n- `packages/agent/src/compaction/branch-summarization.ts`\n- `packages/agent/src/compaction/pruning.ts`\n- `packages/agent/src/compaction/utils.ts`\n- `packages/agent/src/compaction/openai.ts`\n- `packages/coding-agent/src/session/session-manager.ts`\n- `packages/coding-agent/src/session/agent-session.ts`\n- `packages/coding-agent/src/session/messages.ts`\n- `packages/coding-agent/src/extensibility/hooks/types.ts`\n- `packages/coding-agent/src/config/settings-schema.ts`\n\n## Session entry model\n\nCompaction and branch summaries are first-class session entries, not plain assistant/user messages.\n\n- `CompactionEntry`\n - `type: \"compaction\"`\n - `summary`, optional `shortSummary`\n - `firstKeptEntryId` (compaction boundary)\n - `tokensBefore`\n - optional `details`, `preserveData`, `fromExtension`\n- `BranchSummaryEntry`\n - `type: \"branch_summary\"`\n - `fromId`, `summary`\n - optional `details`, `fromExtension`\n\nWhen context is rebuilt (`buildSessionContext`):\n\n1. Latest compaction on the active path is converted to one `compactionSummary` message.\n2. Kept entries from `firstKeptEntryId` to the compaction point are re-included.\n3. Later entries on the path are appended.\n4. `branch_summary` entries are converted to `branchSummary` messages.\n5. `custom_message` entries are converted to `custom` messages.\n\nThose custom roles are then transformed into LLM-facing user messages in `convertToLlm()` using the static templates:\n\n- `packages/agent/src/compaction/prompts/compaction-summary-context.md`\n- `packages/agent/src/compaction/prompts/branch-summary-context.md`\n- `packages/agent/src/compaction/prompts/handoff-document.md`\n\n## Compaction pipeline\n\n### Triggers\n\nCompaction/context maintenance can run in four ways:\n\n1. **Manual context compaction**: `/compact [instructions]` calls `AgentSession.compact(...)`.\n2. **Automatic overflow recovery**: after a same-model assistant error that matches context overflow.\n3. **Automatic threshold maintenance**: after a successful turn when context exceeds the resolved threshold.\n4. **Idle maintenance**: `runIdleCompaction()` can invoke the same auto-maintenance path with reason `\"idle\"`.\n\n### Compaction shape (visual)\n\n```text\nBefore compaction:\n\n entry: 0 1 2 3 4 5 6 7 8 9\n ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬──────┐\n │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool │\n └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴──────┘\n └────────┬───────┘ └──────────────┬──────────────┘\n messagesToSummarize kept messages\n ↑\n firstKeptEntryId (entry 4)\n\nAfter compaction (new entry appended):\n\n entry: 0 1 2 3 4 5 6 7 8 9 10\n ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬──────┬─────┐\n │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool │ cmp │\n └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴──────┴─────┘\n └──────────┬──────┘ └──────────────────────┬───────────────────┘\n not sent to LLM sent to LLM\n ↑\n starts from firstKeptEntryId\n\nWhat the LLM sees:\n\n ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐\n │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │\n └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘\n ↑ ↑ └─────────────────┬────────────────┘\n prompt from cmp messages from firstKeptEntryId\n```\n\n### Overflow-retry vs threshold/idle maintenance\n\nThe automatic paths are intentionally different:\n\n- **Overflow recovery**\n - Trigger: current-model assistant error is detected as context overflow and the error is not older than the latest compaction.\n - The failing assistant error message is removed from active agent state before retry.\n - Context promotion is tried first; if a configured larger model is available, the agent switches model and retries without compacting.\n - If promotion is unavailable and compaction is enabled, context-full compaction runs with `reason: \"overflow\"` and `willRetry: true`; handoff strategy is not used for overflow.\n - On success, agent auto-continues (`agent.continue()`) after compaction.\n\n- **Threshold maintenance**\n - Trigger: successful, non-error assistant message whose adjusted context tokens exceed `resolveThresholdTokens(...)`.\n - Tool-output pruning can reduce the measured token count before threshold comparison.\n - Context promotion is tried before compaction.\n - If promotion is unavailable, auto maintenance runs with `reason: \"threshold\"` and `willRetry: false`.\n - With `compaction.strategy: \"handoff\"`, threshold maintenance starts a new handoff session instead of writing a compaction entry; if handoff returns no document without aborting, it falls back to context-full compaction.\n - On success, if `compaction.autoContinue !== false`, schedules an agent-authored developer auto-continue prompt from `prompts/system/auto-continue.md`.\n\n- **Idle maintenance**\n - Trigger: `runIdleCompaction()` when not streaming or already compacting.\n - Uses `reason: \"idle\"` and does not auto-continue afterward.\n\n### Pre-compaction pruning\n\nBefore compaction checks, tool-result pruning may run (`pruneToolOutputs`).\n\nDefault prune policy:\n\n- Protect newest `40_000` tool-output tokens.\n- Require at least `20_000` total estimated savings.\n- Never prune tool results from `skill` or `read`.\n\nPruned tool results are replaced with:\n\n- `[Output truncated - N tokens]`\n\nIf pruning changes entries, session storage is rewritten and agent message state is refreshed before compaction decisions.\n\n### Boundary and cut-point logic\n\n`prepareCompaction()` only considers entries since the last compaction entry (if any).\n\n1. Find previous compaction index.\n2. Compute `boundaryStart = prevCompactionIndex + 1`.\n3. Adapt `keepRecentTokens` using measured usage ratio when available.\n4. Run `findCutPoint()` over the boundary window.\n\nValid cut points include:\n\n- message entries with roles: `user`, `assistant`, `bashExecution`, `hookMessage`, `branchSummary`, `compactionSummary`\n- `custom_message` entries\n- `branch_summary` entries\n\nHard rule: never cut at `toolResult`.\n\nIf there are non-message metadata entries immediately before the cut point (`model_change`, `thinking_level_change`, labels, etc.), they are pulled into the kept region by moving cut index backward until a message or compaction boundary is hit.\n\n### Split-turn handling\n\nIf cut point is not at a user-turn start, compaction treats it as a split turn.\n\nTurn start detection treats these as user-turn boundaries:\n\n- `message.role === \"user\"`\n- `message.role === \"bashExecution\"`\n- `custom_message` entry\n- `branch_summary` entry\n\nSplit-turn compaction generates two summaries:\n\n1. History summary (`messagesToSummarize`)\n2. Turn-prefix summary (`turnPrefixMessages`)\n\nFinal stored summary is merged as:\n\n```markdown\n<history summary>\n\n---\n\n**Turn Context (split turn):**\n\n<turn prefix summary>\n```\n\n### Summary generation\n\n`compact(...)` builds summaries from serialized conversation text:\n\n1. Convert messages via `convertToLlm()`.\n2. Serialize with `serializeConversation()`.\n3. Wrap in `<conversation>...</conversation>`.\n4. Optionally include `<previous-summary>...</previous-summary>`.\n5. Optionally inject hook context as `<additional-context>` list.\n6. Execute summarization prompt with `SUMMARIZATION_SYSTEM_PROMPT`.\n\nPrompt selection:\n\n- first compaction: `compaction-summary.md`\n- iterative compaction with prior summary: `compaction-update-summary.md`\n- split-turn second pass: `compaction-turn-prefix.md`\n- short UI summary: `compaction-short-summary.md`\n- handoff document: `handoff-document.md` (used by `generateHandoff(...)`, not serialized compaction)\n\nRemote summarization modes:\n\n- If `compaction.remoteEndpoint` is set and remote compaction is enabled, local summary generation POSTs:\n - `{ systemPrompt, prompt }`\n- Expects JSON containing at least `{ summary }`.\n- For OpenAI/OpenAI code provider models, compaction first tries the provider-native `/responses/compact` endpoint when remote compaction is enabled. It preserves provider replacement history in `preserveData.openaiRemoteCompaction` and falls back to local summarization if that native request fails.\n\n### Handoff generation\n\n`packages/agent/src/compaction/compaction.ts` also exports `generateHandoff(...)`. Handoff generation uses the same `completeSimple(...)` oneshot style as summarization, but it preserves the live agent cache prefix by sending the active system prompt, tool array, and real LLM message history, then appending one agent-attributed `user` message containing the handoff prompt. It forces `toolChoice: \"none\"` and returns joined text blocks directly.\n\nHandoff does not write a `CompactionEntry`. `AgentSession.handoff()` owns the session transition: it starts a new session, injects the generated document as a visible `custom_message` with `customType: \"handoff\"`, and rebuilds agent messages from that new session.\n\n### File-operation context in summaries\n\nCompaction tracks cumulative file activity using assistant tool calls:\n\n- `read(path)` → read set\n- `write(path)` → modified set\n- `edit(path)` → modified set\n\nCumulative behavior:\n\n- Includes prior compaction details only when prior entry is pi-generated (`fromExtension !== true`).\n- In split turns, includes turn-prefix file ops too.\n- `readFiles` excludes files also modified.\n\nSummary text gets file tags appended via prompt template:\n\n```xml\n<read-files>\n...\n</read-files>\n<modified-files>\n...\n</modified-files>\n```\n\n### Persist and reload\n\nAfter summary generation (or hook-provided summary), agent session:\n\n1. Appends `CompactionEntry` with `appendCompaction(...)` for context-full maintenance; handoff strategy creates a new session and injects a handoff `custom_message` instead.\n2. Rebuilds display context from the active leaf via `buildDisplaySessionContext()`.\n3. Replaces live agent messages with rebuilt context.\n4. Emits `session_compact` hook event.\n\n## Branch summarization pipeline\n\nBranch summarization is tied to tree navigation, not token overflow.\n\n### Trigger\n\nDuring `navigateTree(...)`:\n\n1. Compute abandoned entries from old leaf to common ancestor using `collectEntriesForBranchSummary(...)`.\n2. If caller requested summary (`options.summarize`), generate summary before switching leaf.\n3. If summary exists, attach it at the navigation target using `branchWithSummary(...)`.\n\nOperationally this is commonly driven by `/tree` flow when `branchSummary.enabled` is enabled.\n\n### Branch switch shape (visual)\n\n```text\nTree before navigation:\n\n ┌─ B ─ C ─ D (old leaf, being abandoned)\n A ───┤\n └─ E ─ F (target)\n\nCommon ancestor: A\nEntries to summarize: B, C, D\n\nAfter navigation with summary:\n\n ┌─ B ─ C ─ D ─ [summary of B,C,D]\n A ───┤\n └─ E ─ F (new leaf)\n```\n\n### Preparation and token budget\n\n`generateBranchSummary(...)` computes budget as:\n\n- `tokenBudget = model.contextWindow - branchSummary.reserveTokens`\n\n`prepareBranchEntries(...)` then:\n\n1. First pass: collect cumulative file ops from all summarized entries, including prior pi-generated `branch_summary` details.\n2. Second pass: walk newest → oldest, adding messages until token budget is reached.\n3. Prefer preserving recent context.\n4. May still include large summary entries near budget edge for continuity.\n\nCompaction entries are included as messages (`compactionSummary`) during branch summarization input.\n\n### Summary generation and persistence\n\nBranch summarization:\n\n1. Converts and serializes selected messages.\n2. Wraps in `<conversation>`.\n3. Uses custom instructions if supplied, otherwise `branch-summary.md`.\n4. Calls summarization model with `SUMMARIZATION_SYSTEM_PROMPT`.\n5. Prepends `branch-summary-preamble.md`.\n6. Appends file-operation tags.\n\nResult is stored as `BranchSummaryEntry` with optional details (`readFiles`, `modifiedFiles`).\n\n## Extension and hook touchpoints\n\n### `session_before_compact`\n\nPre-compaction hook.\n\nCan:\n\n- cancel compaction (`{ cancel: true }`)\n- provide full custom compaction payload (`{ compaction: CompactionResult }`)\n\n### `session.compacting`\n\nPrompt/context customization hook for default compaction.\n\nCan return:\n\n- `prompt` (override base summary prompt)\n- `context` (extra context lines injected into `<additional-context>`)\n- `preserveData` (stored on compaction entry)\n\n### `session_compact`\n\nPost-compaction notification with saved `compactionEntry` and `fromExtension` flag.\n\n### `session_before_tree`\n\nRuns on tree navigation before default branch summary generation.\n\nCan:\n\n- cancel navigation\n- provide custom `{ summary: { summary, details } }` used when user requested summarization\n\n### `session_tree`\n\nPost-navigation event exposing new/old leaf and optional summary entry.\n\n## Runtime behavior and failure semantics\n\n- Manual compaction aborts current agent operation first.\n- `abortCompaction()` cancels both manual and auto-compaction controllers.\n- Auto compaction emits start/end session events for UI/state updates.\n- Auto compaction can try multiple model candidates and retry transient failures; long retry delays prefer the next candidate when one is available.\n- Overflow errors are excluded from generic retry path because they are handled by context promotion/compaction.\n- If auto-compaction fails:\n - overflow path emits `Context overflow recovery failed: ...`\n - threshold path emits `Auto-compaction failed: ...`\n- Branch summarization can be cancelled via abort signal (e.g., Escape), returning canceled/aborted navigation result.\n\n## Settings and defaults\n\nFrom `settings-schema.ts`:\n\n- `compaction.enabled` = `true`\n- `compaction.strategy` = `\"context-full\"` (`\"handoff\"` and `\"off\"` are also supported)\n- `compaction.reserveTokens` = `16384`\n- `compaction.keepRecentTokens` = `20000`\n- `compaction.autoContinue` = `true`\n- `compaction.remoteEnabled` = `true`\n- `compaction.remoteEndpoint` = `undefined`\n- `compaction.thresholdPercent` = `-1` and `compaction.thresholdTokens` = `-1`; when no positive override is set, the threshold is `contextWindow - max(15% of contextWindow, reserveTokens)`\n- `compaction.idleEnabled` = `true`\n- `branchSummary.enabled` = `false`\n- `branchSummary.reserveTokens` = `16384`\n\nThese values are consumed at runtime by `AgentSession` and compaction/branch summarization modules.\n",
23
+ "compaction.md": "# Compaction and Branch Summaries\n\nCompaction and branch summaries are the two mechanisms that keep long sessions usable without losing prior work context.\n\n- **Compaction** rewrites old history into a summary on the current branch.\n- **Branch summary** captures abandoned branch context during `/tree` navigation.\n\nBoth are persisted as session entries and converted back into user-context messages when rebuilding LLM input.\n\n## Key implementation files\n\n- `packages/agent/src/compaction/compaction.ts` (context-full summarization and handoff generation)\n- `packages/agent/src/compaction/branch-summarization.ts`\n- `packages/agent/src/compaction/pruning.ts`\n- `packages/agent/src/compaction/utils.ts`\n- `packages/agent/src/compaction/openai.ts`\n- `packages/coding-agent/src/session/session-manager.ts`\n- `packages/coding-agent/src/session/agent-session.ts`\n- `packages/coding-agent/src/session/messages.ts`\n- `packages/coding-agent/src/extensibility/hooks/types.ts`\n- `packages/coding-agent/src/config/settings-schema.ts`\n\n## Session entry model\n\nCompaction and branch summaries are first-class session entries, not plain assistant/user messages.\n\n- `CompactionEntry`\n - `type: \"compaction\"`\n - `summary`, optional `shortSummary`\n - `firstKeptEntryId` (compaction boundary)\n - `tokensBefore`\n - optional `details`, `preserveData`, `fromExtension`\n- `BranchSummaryEntry`\n - `type: \"branch_summary\"`\n - `fromId`, `summary`\n - optional `details`, `fromExtension`\n\nWhen context is rebuilt (`buildSessionContext`):\n\n1. Latest compaction on the active path is converted to one `compactionSummary` message.\n2. Kept entries from `firstKeptEntryId` to the compaction point are re-included.\n3. Later entries on the path are appended.\n4. `branch_summary` entries are converted to `branchSummary` messages.\n5. `custom_message` entries are converted to `custom` messages.\n\nThose custom roles are then transformed into LLM-facing user messages in `convertToLlm()` using the static templates:\n\n- `packages/agent/src/compaction/prompts/compaction-summary-context.md`\n- `packages/agent/src/compaction/prompts/branch-summary-context.md`\n- `packages/agent/src/compaction/prompts/handoff-document.md`\n\n## Compaction pipeline\n\n### Triggers\n\nCompaction/context maintenance can run in four ways:\n\n1. **Manual context compaction**: `/compact [instructions]` calls `AgentSession.compact(...)`.\n2. **Automatic overflow recovery**: after a same-model assistant error that matches context overflow.\n3. **Automatic threshold maintenance**: after a successful turn when context exceeds the resolved threshold.\n4. **Idle maintenance**: `runIdleCompaction()` can invoke the same auto-maintenance path with reason `\"idle\"`.\n\n### Compaction shape (visual)\n\n```text\nBefore compaction:\n\n entry: 0 1 2 3 4 5 6 7 8 9\n ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬──────┐\n │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool │\n └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴──────┘\n └────────┬───────┘ └──────────────┬──────────────┘\n messagesToSummarize kept messages\n ↑\n firstKeptEntryId (entry 4)\n\nAfter compaction (new entry appended):\n\n entry: 0 1 2 3 4 5 6 7 8 9 10\n ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬──────┬─────┐\n │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool │ cmp │\n └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴──────┴─────┘\n └──────────┬──────┘ └──────────────────────┬───────────────────┘\n not sent to LLM sent to LLM\n ↑\n starts from firstKeptEntryId\n\nWhat the LLM sees:\n\n ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐\n │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │\n └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘\n ↑ ↑ └─────────────────┬────────────────┘\n prompt from cmp messages from firstKeptEntryId\n```\n\n### Overflow-retry vs threshold/idle maintenance\n\nThe automatic paths are intentionally different:\n\n- **Overflow recovery**\n - Trigger: current-model assistant error is detected as context overflow and the error is not older than the latest compaction.\n - The failing assistant error message is removed from active agent state before retry.\n - Context promotion is tried first; if a configured larger model is available, the agent switches model and retries without compacting.\n - If promotion is unavailable and compaction is enabled, context-full compaction runs with `reason: \"overflow\"` and `willRetry: true`; handoff strategy is not used for overflow.\n - On success, agent auto-continues (`agent.continue()`) after compaction.\n\n- **Threshold maintenance**\n - Trigger: successful, non-error assistant message whose adjusted context tokens exceed `resolveThresholdTokens(...)`.\n - Tool-output pruning can reduce the measured token count before threshold comparison.\n - Context promotion is tried before compaction.\n - If promotion is unavailable, auto maintenance runs with `reason: \"threshold\"` and `willRetry: false`.\n - With `compaction.strategy: \"handoff\"`, threshold maintenance starts a new handoff session instead of writing a compaction entry; if handoff returns no document without aborting, it falls back to context-full compaction.\n - On success, if `compaction.autoContinue !== false` and the triggering answer was unfinished (it called tools or stopped for a reason other than `stop`), schedules an agent-authored developer auto-continue prompt from `prompts/system/auto-continue.md`. A finished answer is compacted without a continuation turn.\n\n- **Mid-run maintenance** (inside a tool loop)\n - Trigger: between tool-loop steps, against `resolveMidRunThresholdTokens(...)`. When the model's usable window (`contextWindow - reserve`) exceeds the default ceiling (300K), a lower configured threshold is deferred to the ceiling, so a 150K threshold on a 1M-token model compacts at answer boundaries instead of mid-task. Smaller windows use the configured threshold as-is.\n - The run ends with `stopReason: \"maintenance\"` and the session resumes it with `agent.continue()` on the rewritten context.\n - After a compaction, if an SKC workflow skill (`deep-interview`, `ralplan`, `ultragoal`, `team`) invoked on the current branch is active and its instructions are no longer in context, they are re-attached as a hidden `workflow-skill-context` message. The same restore runs before the next prompt after an answer-boundary compaction.\n\n- **Idle maintenance**\n - Trigger: `runIdleCompaction()` when not streaming or already compacting.\n - Uses `reason: \"idle\"` and does not auto-continue afterward.\n\n### Pre-compaction pruning\n\nBefore compaction checks, tool-result pruning may run (`pruneToolOutputs`).\n\nDefault prune policy:\n\n- Protect newest `40_000` tool-output tokens.\n- Require at least `20_000` total estimated savings.\n- Never prune tool results from `skill` or `read`.\n\nPruned tool results are replaced with:\n\n- `[Output truncated - N tokens]`\n\nIf pruning changes entries, session storage is rewritten and agent message state is refreshed before compaction decisions.\n\n### Boundary and cut-point logic\n\n`prepareCompaction()` only considers entries since the last compaction entry (if any).\n\n1. Find previous compaction index.\n2. Compute `boundaryStart = prevCompactionIndex + 1`.\n3. Adapt `keepRecentTokens` using measured usage ratio when available.\n4. Run `findCutPoint()` over the boundary window.\n\nValid cut points include:\n\n- message entries with roles: `user`, `assistant`, `bashExecution`, `hookMessage`, `branchSummary`, `compactionSummary`\n- `custom_message` entries\n- `branch_summary` entries\n\nHard rule: never cut at `toolResult`.\n\nIf there are non-message metadata entries immediately before the cut point (`model_change`, `thinking_level_change`, labels, etc.), they are pulled into the kept region by moving cut index backward until a message or compaction boundary is hit.\n\n### Split-turn handling\n\nIf cut point is not at a user-turn start, compaction treats it as a split turn.\n\nTurn start detection treats these as user-turn boundaries:\n\n- `message.role === \"user\"`\n- `message.role === \"bashExecution\"`\n- `custom_message` entry\n- `branch_summary` entry\n\nSplit-turn compaction generates two summaries:\n\n1. History summary (`messagesToSummarize`)\n2. Turn-prefix summary (`turnPrefixMessages`)\n\nFinal stored summary is merged as:\n\n```markdown\n<history summary>\n\n---\n\n**Turn Context (split turn):**\n\n<turn prefix summary>\n```\n\n### Summary generation\n\n`compact(...)` builds summaries from serialized conversation text:\n\n1. Convert messages via `convertToLlm()`.\n2. Serialize with `serializeConversation()`.\n3. Wrap in `<conversation>...</conversation>`.\n4. Optionally include `<previous-summary>...</previous-summary>`.\n5. Optionally inject hook context as `<additional-context>` list.\n6. Execute summarization prompt with `SUMMARIZATION_SYSTEM_PROMPT`.\n\nPrompt selection:\n\n- first compaction: `compaction-summary.md`\n- iterative compaction with prior summary: `compaction-update-summary.md`\n- split-turn second pass: `compaction-turn-prefix.md`\n- short UI summary: `compaction-short-summary.md`\n- handoff document: `handoff-document.md` (used by `generateHandoff(...)`, not serialized compaction)\n\nRemote summarization modes:\n\n- If `compaction.remoteEndpoint` is set and remote compaction is enabled, local summary generation POSTs:\n - `{ systemPrompt, prompt }`\n- Expects JSON containing at least `{ summary }`.\n- For OpenAI/OpenAI code provider models, compaction first tries the provider-native `/responses/compact` endpoint when remote compaction is enabled. It preserves provider replacement history in `preserveData.openaiRemoteCompaction` and falls back to local summarization if that native request fails.\n\n### Handoff generation\n\n`packages/agent/src/compaction/compaction.ts` also exports `generateHandoff(...)`. Handoff generation uses the same `completeSimple(...)` oneshot style as summarization, but it preserves the live agent cache prefix by sending the active system prompt, tool array, and real LLM message history, then appending one agent-attributed `user` message containing the handoff prompt. It forces `toolChoice: \"none\"` and returns joined text blocks directly.\n\nHandoff does not write a `CompactionEntry`. `AgentSession.handoff()` owns the session transition: it starts a new session, injects the generated document as a visible `custom_message` with `customType: \"handoff\"`, and rebuilds agent messages from that new session.\n\n### File-operation context in summaries\n\nCompaction tracks cumulative file activity using assistant tool calls:\n\n- `read(path)` → read set\n- `write(path)` → modified set\n- `edit(path)` → modified set\n\nCumulative behavior:\n\n- Includes prior compaction details only when prior entry is pi-generated (`fromExtension !== true`).\n- In split turns, includes turn-prefix file ops too.\n- `readFiles` excludes files also modified.\n\nSummary text gets file tags appended via prompt template:\n\n```xml\n<read-files>\n...\n</read-files>\n<modified-files>\n...\n</modified-files>\n```\n\n### Persist and reload\n\nAfter summary generation (or hook-provided summary), agent session:\n\n1. Appends `CompactionEntry` with `appendCompaction(...)` for context-full maintenance; handoff strategy creates a new session and injects a handoff `custom_message` instead.\n2. Rebuilds display context from the active leaf via `buildDisplaySessionContext()`.\n3. Replaces live agent messages with rebuilt context.\n4. Emits `session_compact` hook event.\n\n## Branch summarization pipeline\n\nBranch summarization is tied to tree navigation, not token overflow.\n\n### Trigger\n\nDuring `navigateTree(...)`:\n\n1. Compute abandoned entries from old leaf to common ancestor using `collectEntriesForBranchSummary(...)`.\n2. If caller requested summary (`options.summarize`), generate summary before switching leaf.\n3. If summary exists, attach it at the navigation target using `branchWithSummary(...)`.\n\nOperationally this is commonly driven by `/tree` flow when `branchSummary.enabled` is enabled.\n\n### Branch switch shape (visual)\n\n```text\nTree before navigation:\n\n ┌─ B ─ C ─ D (old leaf, being abandoned)\n A ───┤\n └─ E ─ F (target)\n\nCommon ancestor: A\nEntries to summarize: B, C, D\n\nAfter navigation with summary:\n\n ┌─ B ─ C ─ D ─ [summary of B,C,D]\n A ───┤\n └─ E ─ F (new leaf)\n```\n\n### Preparation and token budget\n\n`generateBranchSummary(...)` computes budget as:\n\n- `tokenBudget = model.contextWindow - branchSummary.reserveTokens`\n\n`prepareBranchEntries(...)` then:\n\n1. First pass: collect cumulative file ops from all summarized entries, including prior pi-generated `branch_summary` details.\n2. Second pass: walk newest → oldest, adding messages until token budget is reached.\n3. Prefer preserving recent context.\n4. May still include large summary entries near budget edge for continuity.\n\nCompaction entries are included as messages (`compactionSummary`) during branch summarization input.\n\n### Summary generation and persistence\n\nBranch summarization:\n\n1. Converts and serializes selected messages.\n2. Wraps in `<conversation>`.\n3. Uses custom instructions if supplied, otherwise `branch-summary.md`.\n4. Calls summarization model with `SUMMARIZATION_SYSTEM_PROMPT`.\n5. Prepends `branch-summary-preamble.md`.\n6. Appends file-operation tags.\n\nResult is stored as `BranchSummaryEntry` with optional details (`readFiles`, `modifiedFiles`).\n\n## Extension and hook touchpoints\n\n### `session_before_compact`\n\nPre-compaction hook.\n\nCan:\n\n- cancel compaction (`{ cancel: true }`)\n- provide full custom compaction payload (`{ compaction: CompactionResult }`)\n\n### `session.compacting`\n\nPrompt/context customization hook for default compaction.\n\nCan return:\n\n- `prompt` (override base summary prompt)\n- `context` (extra context lines injected into `<additional-context>`)\n- `preserveData` (stored on compaction entry)\n\n### `session_compact`\n\nPost-compaction notification with saved `compactionEntry` and `fromExtension` flag.\n\n### `session_before_tree`\n\nRuns on tree navigation before default branch summary generation.\n\nCan:\n\n- cancel navigation\n- provide custom `{ summary: { summary, details } }` used when user requested summarization\n\n### `session_tree`\n\nPost-navigation event exposing new/old leaf and optional summary entry.\n\n## Runtime behavior and failure semantics\n\n- Manual compaction aborts current agent operation first.\n- `abortCompaction()` cancels both manual and auto-compaction controllers.\n- Auto compaction emits start/end session events for UI/state updates.\n- Auto compaction can try multiple model candidates and retry transient failures; long retry delays prefer the next candidate when one is available.\n- Overflow errors are excluded from generic retry path because they are handled by context promotion/compaction.\n- If auto-compaction fails:\n - overflow path emits `Context overflow recovery failed: ...`\n - threshold path emits `Auto-compaction failed: ...`\n- Branch summarization can be cancelled via abort signal (e.g., Escape), returning canceled/aborted navigation result.\n\n## Settings and defaults\n\nFrom `settings-schema.ts`:\n\n- `compaction.enabled` = `true`\n- `compaction.strategy` = `\"context-full\"` (`\"handoff\"` and `\"off\"` are also supported)\n- `compaction.reserveTokens` = `16384`\n- `compaction.keepRecentTokens` = `20000`\n- `compaction.autoContinue` = `true`\n- `compaction.remoteEnabled` = `true`\n- `compaction.remoteEndpoint` = `undefined`\n- `compaction.thresholdPercent` = `-1` and `compaction.thresholdTokens` = `-1`; when no positive override is set, the threshold is `contextWindow - max(15% of contextWindow, reserveTokens)`\n- `compaction.idleEnabled` = `true`\n- `branchSummary.enabled` = `false`\n- `branchSummary.reserveTokens` = `16384`\n\nThese values are consumed at runtime by `AgentSession` and compaction/branch summarization modules.\n",
24
24
  "composer-codex-parity.md": "# Composer 2.5 Fast parity repro\n\nThis document records the one-command repros for the Composer 2.5 Fast stability work. Scope is SKC-local only: no OpenClaw reference, no Cursor live e2e, no upstream xAI/server change, and no Codex refactor. Codex is the baseline/report model only.\n\n## Focused discipline regression\n\n```sh\nbun test packages/ai/test/composer-discipline.test.ts\n```\n\nExpected contract:\n\n- `grok-build/grok-composer-2.5-fast` and other composer ids receive `COMPOSER_EDIT_DISCIPLINE_PROMPT` ahead of host/default system prompts on the `openai-completions`, `openai-responses`, and Cursor RPC prompt paths.\n- Non-composer models keep their system prompt payload unchanged.\n- The prompt explicitly covers adversarial shell file discovery, shell file reads, out-of-band shell writes, fabricated/stale anchors, malformed tool arguments, and contaminated bash command strings.\n\n## V3 mock P1 gate\n\n```sh\nbun packages/agent/bench/composer-stability-v3.ts --mock --seed 42 -n 5 --model grok-build/grok-composer-2.5-fast --baseline-model openai-codex/gpt-5.5:low\n```\n\nEquivalent package script:\n\n```sh\nbun run bench:composer-stability-v3\n```\n\nP1 passes when `candidateFailureCount <= baselineFailureCount` over the same deterministic scenario matrix. Mock mode is a smoke gate, not live parity proof.\n\n## V3 trace-backed gate\n\n```sh\nbun packages/agent/bench/composer-stability-v3.ts --trace --trace-file packages/agent/test/fixtures/composer-stability-v3/traces/parity.json\n```\n\nEquivalent package script:\n\n```sh\nbun run bench:composer-stability-v3:trace\n```\n\nTrace files can be JSON, JSON arrays, JSON `{ \"records\": [...] }`, or JSONL. Each record declares `scenarioId`, `modelRole` (`candidate` or `baseline`), `model`, `trial`, optional `expected`, and `events`. The classifier maps recorded tool behavior to failure classes:\n\n- `shell-read`\n- `shell-file-discovery`\n- `shell-write`\n- `contaminated-command`\n- `bad-anchor-unrecovered`\n- `malformed-tool-args-unrecovered`\n- `sanitize-replay-regression`\n- `wrong-file-edit`\n- `missing-tool-turn`\n- `timeout`\n\nTrace P1 is applicable only when both candidate and baseline records exist, and it can pass only with at least three comparable candidate/baseline scenario ids so a one-scenario smoke cannot fake parity. It reports `candidateFailureCount`, `baselineFailureCount`, `parityDelta`, per-scenario counts, and the trace artifact paths that were scored.\n\n## Optional live smoke\n\n```sh\nbun packages/agent/bench/composer-stability-v3.ts --live -n 3 --model grok-build/grok-composer-2.5-fast --baseline-model openai-codex/gpt-5.5:low\n```\n\nLive smoke is informational. Without `GROK_CLI_OAUTH_TOKEN` and Codex/OpenAI credentials, or without trace artifacts from a real capture, `--live` exits successfully with an explicit skip record and `p1.applicable=false`; it does not fake a P1 pass. Pass `--live --trace-dir <captured-traces>` to score real captured runs through the same trace classifier. Cursor live e2e is intentionally out of scope.\n\n## Broader local verification\n\n```sh\nbun test packages/agent/test/composer-stability-v3.test.ts packages/coding-agent/test/grok-cli-sanitize.test.ts packages/coding-agent/test/grok-build-stream.test.ts\nbun test packages/agent packages/ai\nbun scripts/verify-g002-gates.ts\n```\n\nUse `mise x bun@1.3.14 -- <command>` when `bun` is not on `PATH`.\n",
25
25
  "computer-use/README.md": "# Native computer-use tool\n\nStatus: **in progress (draft)** — coordinate contract + native `screenshot`\ncapture landed and verified; input primitives, kill-switch, and napi/TS surface\nto follow.\n\nA new, model-agnostic `computer` tool that lets any model drive the user's real\nmacOS desktop via the OpenAI computer-use action set. Built fresh (the\nopen-source `openai/codex` repo has no GUI computer-use source to copy; only the\npublic action *schema* is mirrored).\n\nThis feature was scoped through SKC's deep-interview (requirements) and ralplan\n(Planner/Architect/Critic consensus) workflows. The full deep-interview spec and\nthe consensus plan + ADR are the authoritative source of truth; this document is\nthe committed summary and roadmap.\n\n## Locked decisions (ADR summary)\n\n- **Target:** the user's real macOS desktop, OS-native control. v1 is macOS-only\n (Linux/Windows deferred behind the same tool schema).\n- **Driver:** any model via a generic structured tool-call interface — no\n provider-specific computer-use API.\n- **Action set:** the exact OpenAI computer-use primitives — `screenshot`,\n `click`, `double_click`, `move`, `drag`, `scroll`, `type`, `keypress`, `wait`.\n- **Implementation:** built fresh in the Rust `pi-natives` crate (napi),\n exposed through `packages/natives` to a new\n `packages/coding-agent/src/tools/computer.ts`, kept deliberately lower-level\n than the existing `browser` tool (coordinate/input primitives only, no web\n semantics).\n- **Coordinate contract:** a single normalized virtual display. The returned\n screenshot's pixel dimensions *are* the action coordinate space; Rust owns the\n transform to macOS logical points (Retina/HiDPI-safe) and display selection.\n- **Permissions:** macOS TCC (Accessibility + Screen Recording) auto-preflighted;\n on a missing grant, open the relevant Settings pane and return a clear\n \"grant then retry/relaunch\" error.\n- **Gating:** off by default; opt-in config flag (per session) plus a persistent\n always-on option.\n- **Safety:** no per-action approval (autonomous), **but** a daemon-enforced\n global kill-switch outside model control (global hotkey OR TUI stop key) that\n aborts queued actions, releases held keys/buttons, suspends further input, and\n snapshots the last screen. Reset is user-only, never via the model-facing tool.\n- **Architecture:** every primitive delegates to one central Rust\n `execute_action` state machine (preflight, validation, cancellation, audit,\n screenshot policy, release-all) so per-primitive methods cannot drift past the\n safety contract. The in-process supervisor sits behind a `SupervisorClient`\n boundary so an out-of-process daemon can replace it later without changing the\n napi surface.\n\n## Capture + coordinate contract (shipped)\n\n`crates/pi-natives/src/computer/coords.rs` implements the pure, framework-free\ncore: `NormalizedDisplay` maps a screenshot-space pixel `(x, y)` to a macOS\nlogical point via per-axis scale and the display's logical origin, rejecting\nout-of-bounds and non-finite inputs. It is unit-tested (scale 1.0/2.0,\nfractional and anisotropic scale, non-zero origins, edges, out-of-bounds,\ninvalid scale) and requires no display or granted permissions.\n\n`crates/pi-natives/src/computer/capture.rs` (macOS) implements the read-only\n`screenshot` primitive: it captures the primary display via CoreGraphics into a\nPNG and derives the `NormalizedDisplay` scale from captured physical pixels vs\nlogical bounds, surfacing a missing Screen Recording grant as\n`CaptureError::CaptureFailed` (never a silent black frame). Verified live: a\nreal, non-uniform primary-display capture decodes as a PNG with matching\ndimensions (`cargo test -p pi-natives --ignored captures_non_uniform_primary_display`).\n\n## Delivery roadmap\n\nDelivery ships a `screenshot`+`click`+`type` vertical slice first; the remaining\nsix primitives fast-follow; v1 acceptance = all nine primitives drive a real\nmacOS app end-to-end plus a kill-switch drill (per-primitive napi unit tests +\nmanual macOS E2E).\n\n| Slice | Scope | Status |\n|-------|-------|--------|\n| Coordinate contract + planning docs | `coords` module + unit tests + this doc | **done (this PR)** |\n| Native screen capture (`screenshot`) | `capture` module, primary display, PNG + scale | **done (this PR, verified live)** |\n| TCC preflight (`permissions`) | Accessibility + Screen Recording checks, Settings openers, fail-closed guards | **done (this PR, verified live)** |\n| napi screenshot binding (`computerScreenshot`) | napi → `packages/natives` → TS, verified live | **done (this PR)** |\n| Native input orchestration (`input`) | `InputController` click/double_click/move/drag/scroll/type/keypress + release_all over an `EventSink` | **done (this PR)** — logic unit-tested; **live cursor-move injection verified** (Accessibility granted) |\n| Central `execute_action` state machine | preflight + supervisor + cancellation + audit + release-all | planned |\n| Kill-switch supervisor + global-hotkey event-tap | `supervisor` (fail-closed `input_allowed`, user-only reset) + `hotkey` CGEventTap on a CFRunLoop thread | **done (this PR)** — supervisor unit-tested; **synthetic-hotkey latch verified live** |\n| Supervisor-gated `execute_action` + napi/TS `computer` tool | wire input through `input_allowed` + cancellation; `ComputerController` napi; `computer.ts` schema/gating/prompt/renderer | next |\n| Manual macOS E2E acceptance | TextEdit all-nine + kill-switch drill | planned (requires macOS hardware + granted TCC + human operator) |\n\nThe remaining input backend, kill-switch, napi/TS surface, and manual\nend-to-end acceptance still require injecting events into a live desktop and a\nhuman-operated drill, so they are tracked as follow-up work rather than landed\nin this draft.\n",
26
26
  "discord-onboarding.md": "# Discord notification onboarding\n\nThis is the managed Discord notification adapter. It is an SDK client: every\nlocal SKC session retains its own loopback SDK endpoint, while the daemon maps\nthat session to one Discord thread under a configured parent channel.\n\n## Prerequisites\n\nCreate a Discord application and bot through Discord's developer portal, install\nthe bot in the target guild, and create or select the parent channel that will\ncontain SKC session threads. Configure the bot with only the permissions it\nneeds in that channel:\n\n- View Channel\n- Send Messages\n- Create Public Threads\n- Send Messages in Threads\n- Manage Threads (needed to archive, unarchive, and lock session threads)\n- Read Message History\n\nEnable the Gateway intents required to receive the configured thread messages\nand interactions. Do not grant Administrator merely to make setup work. Keep\nthe bot and parent channel private to people permitted to see local session\nmetadata.\n\n## Configure the adapter\n\n`skc notify setup discord` is non-interactive. It requires these flags:\n\n- `--discord-bot-token`\n- `--discord-application-id`\n- `--discord-guild-id`\n- `--discord-parent-channel-id`\n\nIt also accepts `--redact`. Supply secret flag values from an approved local\nsecret mechanism rather than placing them in shell history, files committed to\nthe repository, chat transcripts, or screenshots. The setup command writes:\n\n- `notifications.enabled = true`\n- `notifications.discord.botToken`\n- `notifications.discord.applicationId`\n- `notifications.discord.guildId`\n- `notifications.discord.parentChannelId`\n- `notifications.redact = true` when requested\n\n`skc notify status` shows configured Discord identifiers and masks token values.\nIt must not be used as a way to recover a token.\n\n## Threads, resume, and replies\n\nA session gets one Discord thread. For a generic text-channel parent, the daemon\nfirst posts a nonce-bearing starter message and then uses Discord's **Start\nThread from Message** endpoint. It never sends the protocol-invalid nested\n`message` field to the **Start Thread without Message** endpoint. A notification\ncreates a durable local mapping before remote work begins; a retry first finds\nthe nonce-bearing starter message and attached thread, reconciling an uncertain\ncreate instead of intentionally creating a second thread. The nonce is only an\nopaque correlation marker and never contains credentials.\n\nWhen a session is archived, the daemon archives its thread. On resume it first\ntries to unarchive that thread. If Discord refuses unarchive, the daemon creates\na replacement thread and marks the old mapping superseded. Inbound events from a\nsuperseded thread, stale endpoint generation, unknown route, bot author, or\nmissing local endpoint fail closed and are not routed to a session.\n\nReply controls carry the session endpoint generation. Discord interaction IDs\nand event IDs are deduplicated locally. A reply is sent to the loopback SDK only;\nthe daemon never stores endpoint tokens or message bodies in its conversation\nstate.\n\n## Operational safety\n\nDiscord API permission failures, rate limits, disconnects, and uncertain creates\nmust be retried through the managed daemon's reconciliation path. Do not use a\nsecond bot process against the same managed state directory, manually edit\nconversation files, scrape a session terminal, expose the loopback endpoint, or\nturn Discord into a general remote shell.\n\nThe supported surface is notification delivery and replies to the SDK protocol.\nProvider registration, provider secrets in session state, and arbitrary remote\ncontrol are out of scope.\n\n## Verification boundary\n\nThe shipped acceptance coverage uses an injectable fake Discord provider. It\ncovers uncertain create reconciliation, durable restart behavior, archive/\nunarchive-or-replacement resume, stale/superseded inbound rejection, permission\nand rate-limit failure paths, and disconnect handling. It deliberately does not\nrequire live Discord credentials, a live guild, or live-provider end-to-end\ntests.\n",
@@ -840,6 +840,8 @@ export class TelegramBotTransport implements BotApi {
840
840
  }
841
841
 
842
842
  type PairedChatPrivacy = "private" | "non-private" | "indeterminate";
843
+ const PAIRED_CHAT_PRIVACY_RETRY_BASE_MS = 15_000;
844
+ const PAIRED_CHAT_PRIVACY_RETRY_MAX_MS = 10 * 60_000;
843
845
 
844
846
  export type TelegramUpdateOutcome = "consumed" | "retry";
845
847
 
@@ -1049,6 +1051,15 @@ export class TelegramNotificationDaemon {
1049
1051
  private readonly flatIdentitySent = new Set<string>();
1050
1052
  /** Cached result of whether the paired chat is a private chat (flat-fallback gate). */
1051
1053
  private pairedChatPrivate: boolean | undefined;
1054
+ /**
1055
+ * Backoff for indeterminate privacy checks. A rejected bot token or a deleted
1056
+ * chat fails the same way on every attempt; re-asking on every delivery tick
1057
+ * flooded the log (one warning per 4s) and the Bot API. Retry with backoff and
1058
+ * warn only when the failure changes.
1059
+ */
1060
+ private pairedChatPrivacyRetryAt = 0;
1061
+ private pairedChatPrivacyFailures = 0;
1062
+ private pairedChatPrivacyLastWarning: string | undefined;
1052
1063
  /** Bot username from getMe, cached once at owner startup for group/forum command targeting. */
1053
1064
  private botUsername: string | undefined;
1054
1065
  /** Sessions whose agent loop is currently busy (drives the typing indicator). */
@@ -2550,14 +2561,22 @@ export class TelegramNotificationDaemon {
2550
2561
  */
2551
2562
  private async resolvePairedChatPrivacy(): Promise<PairedChatPrivacy> {
2552
2563
  if (this.pairedChatPrivate !== undefined) return this.pairedChatPrivate ? "private" : "non-private";
2564
+ const now = this.opts.now?.() ?? Date.now();
2565
+ if (now < this.pairedChatPrivacyRetryAt) return "indeterminate";
2553
2566
  try {
2554
2567
  const res = (await this.botApi.call("getChat", { chat_id: this.opts.chatId })) as {
2555
2568
  ok?: unknown;
2569
+ error_code?: unknown;
2570
+ description?: unknown;
2556
2571
  result?: { type?: unknown };
2557
2572
  };
2558
2573
  if (res?.ok !== true) {
2559
- logger.warn("notifications: getChat privacy check indeterminate (non-success response)");
2560
- return "indeterminate";
2574
+ const code = typeof res?.error_code === "number" ? ` ${res.error_code}` : "";
2575
+ const description = typeof res?.description === "string" ? `: ${res.description}` : "";
2576
+ return this.deferPairedChatPrivacy(
2577
+ now,
2578
+ `notifications: getChat privacy check indeterminate (non-success response${code}${description})`,
2579
+ );
2561
2580
  }
2562
2581
  if (res.result?.type === "private") {
2563
2582
  this.pairedChatPrivate = true;
@@ -2567,12 +2586,35 @@ export class TelegramNotificationDaemon {
2567
2586
  this.pairedChatPrivate = false;
2568
2587
  return "non-private";
2569
2588
  }
2570
- logger.warn("notifications: getChat privacy check indeterminate (missing or invalid chat type)");
2571
- return "indeterminate";
2589
+ return this.deferPairedChatPrivacy(
2590
+ now,
2591
+ "notifications: getChat privacy check indeterminate (missing or invalid chat type)",
2592
+ );
2572
2593
  } catch {
2573
- logger.warn("notifications: getChat privacy check indeterminate (request failed)");
2574
- return "indeterminate";
2594
+ return this.deferPairedChatPrivacy(now, "notifications: getChat privacy check indeterminate (request failed)");
2595
+ }
2596
+ }
2597
+
2598
+ /**
2599
+ * Fail closed for now and schedule the next check. A single failure retries on
2600
+ * the next attempt (transient errors clear quickly); repeated failures back off
2601
+ * exponentially. Warn once per distinct failure.
2602
+ */
2603
+ private deferPairedChatPrivacy(now: number, warning: string | undefined): PairedChatPrivacy {
2604
+ this.pairedChatPrivacyFailures += 1;
2605
+ const delayMs =
2606
+ this.pairedChatPrivacyFailures < 2
2607
+ ? 0
2608
+ : Math.min(
2609
+ PAIRED_CHAT_PRIVACY_RETRY_MAX_MS,
2610
+ PAIRED_CHAT_PRIVACY_RETRY_BASE_MS * 2 ** (this.pairedChatPrivacyFailures - 2),
2611
+ );
2612
+ this.pairedChatPrivacyRetryAt = now + delayMs;
2613
+ if (warning && warning !== this.pairedChatPrivacyLastWarning) {
2614
+ this.pairedChatPrivacyLastWarning = warning;
2615
+ logger.warn(warning, { retryInMs: delayMs });
2575
2616
  }
2617
+ return "indeterminate";
2576
2618
  }
2577
2619
 
2578
2620
  /** Keep existing outbound callers fail-closed for indeterminate privacy. */
@@ -3595,6 +3595,8 @@ export class TelegramBotTransport implements BotApi {
3595
3595
  }
3596
3596
 
3597
3597
  type PairedChatPrivacy = "private" | "non-private" | "indeterminate";
3598
+ const PAIRED_CHAT_PRIVACY_RETRY_BASE_MS = 15_000;
3599
+ const PAIRED_CHAT_PRIVACY_RETRY_MAX_MS = 10 * 60_000;
3598
3600
 
3599
3601
  export type TelegramUpdateOutcome = "consumed" | "retry";
3600
3602
 
@@ -4200,6 +4202,15 @@ export class TelegramNotificationDaemon {
4200
4202
  private readonly flatIdentitySent = new Set<string>();
4201
4203
  /** Cached result of whether the paired chat is a private chat (flat-fallback gate). */
4202
4204
  private pairedChatPrivate: boolean | undefined;
4205
+ /**
4206
+ * Backoff for indeterminate privacy checks. A rejected bot token or a deleted
4207
+ * chat fails the same way on every attempt; re-asking on every delivery tick
4208
+ * flooded the log (one warning per 4s) and the Bot API. Retry with backoff and
4209
+ * warn only when the failure changes.
4210
+ */
4211
+ private pairedChatPrivacyRetryAt = 0;
4212
+ private pairedChatPrivacyFailures = 0;
4213
+ private pairedChatPrivacyLastWarning: string | undefined;
4203
4214
  /** Bot username from getMe, cached once at owner startup for group/forum command targeting. */
4204
4215
  private botUsername: string | undefined;
4205
4216
  /** Sessions whose agent loop is currently busy (drives the typing indicator). */
@@ -7859,15 +7870,23 @@ export class TelegramNotificationDaemon {
7859
7870
  */
7860
7871
  private async resolvePairedChatPrivacy(): Promise<PairedChatPrivacy> {
7861
7872
  if (this.pairedChatPrivate !== undefined) return this.pairedChatPrivate ? "private" : "non-private";
7873
+ const now = this.opts.now?.() ?? Date.now();
7874
+ if (now < this.pairedChatPrivacyRetryAt) return "indeterminate";
7862
7875
  try {
7863
7876
  const res = (await this.botApi.call("getChat", { chat_id: this.opts.chatId })) as {
7864
7877
  ok?: unknown;
7878
+ error_code?: unknown;
7879
+ description?: unknown;
7865
7880
  result?: { type?: unknown };
7866
7881
  };
7867
- if (res === undefined) return "indeterminate";
7882
+ if (res === undefined) return this.deferPairedChatPrivacy(now, undefined);
7868
7883
  if (res?.ok !== true) {
7869
- logger.warn("notifications: getChat privacy check indeterminate (non-success response)");
7870
- return "indeterminate";
7884
+ const code = typeof res?.error_code === "number" ? ` ${res.error_code}` : "";
7885
+ const description = typeof res?.description === "string" ? `: ${res.description}` : "";
7886
+ return this.deferPairedChatPrivacy(
7887
+ now,
7888
+ `notifications: getChat privacy check indeterminate (non-success response${code}${description})`,
7889
+ );
7871
7890
  }
7872
7891
  if (res.result?.type === "private") {
7873
7892
  this.pairedChatPrivate = true;
@@ -7877,12 +7896,35 @@ export class TelegramNotificationDaemon {
7877
7896
  this.pairedChatPrivate = false;
7878
7897
  return "non-private";
7879
7898
  }
7880
- logger.warn("notifications: getChat privacy check indeterminate (missing or invalid chat type)");
7881
- return "indeterminate";
7899
+ return this.deferPairedChatPrivacy(
7900
+ now,
7901
+ "notifications: getChat privacy check indeterminate (missing or invalid chat type)",
7902
+ );
7882
7903
  } catch {
7883
- logger.warn("notifications: getChat privacy check indeterminate (request failed)");
7884
- return "indeterminate";
7904
+ return this.deferPairedChatPrivacy(now, "notifications: getChat privacy check indeterminate (request failed)");
7905
+ }
7906
+ }
7907
+
7908
+ /**
7909
+ * Fail closed for now and schedule the next check. A single failure retries on
7910
+ * the next attempt (transient errors clear quickly); repeated failures back off
7911
+ * exponentially. Warn once per distinct failure.
7912
+ */
7913
+ private deferPairedChatPrivacy(now: number, warning: string | undefined): PairedChatPrivacy {
7914
+ this.pairedChatPrivacyFailures += 1;
7915
+ const delayMs =
7916
+ this.pairedChatPrivacyFailures < 2
7917
+ ? 0
7918
+ : Math.min(
7919
+ PAIRED_CHAT_PRIVACY_RETRY_MAX_MS,
7920
+ PAIRED_CHAT_PRIVACY_RETRY_BASE_MS * 2 ** (this.pairedChatPrivacyFailures - 2),
7921
+ );
7922
+ this.pairedChatPrivacyRetryAt = now + delayMs;
7923
+ if (warning && warning !== this.pairedChatPrivacyLastWarning) {
7924
+ this.pairedChatPrivacyLastWarning = warning;
7925
+ logger.warn(warning, { retryInMs: delayMs });
7885
7926
  }
7927
+ return "indeterminate";
7886
7928
  }
7887
7929
 
7888
7930
  /** Keep existing outbound callers fail-closed for indeterminate privacy. */
@@ -66,6 +66,7 @@ import {
66
66
  prepareCompaction,
67
67
  type RemoteCompactionFallbackHealthEvent,
68
68
  type RemoteCompactionFallbackHealthHooks,
69
+ resolveMidRunThresholdTokens,
69
70
  resolveThresholdTokens,
70
71
  type SummaryOptions,
71
72
  shouldCompact,
@@ -410,6 +411,7 @@ import {
410
411
  type AutoResumeMarker,
411
412
  type AutoResumeMode,
412
413
  type AutoResumeTrigger,
414
+ dropUnexecutedToolCallFailure,
413
415
  hasAutoResumeMarkerSinceLastUser,
414
416
  hasVisibleFailedPrefix,
415
417
  INTERRUPTED_TOOL_RESULT_TEXT,
@@ -1005,6 +1007,8 @@ function assistantMessageHasVisibleOrToolContent(message: AssistantMessage): boo
1005
1007
  /** Serializers with a verified projection of a failed plain-text assistant prefix. */
1006
1008
  const VISIBLE_CONTINUATION_APIS: ReadonlySet<string> = new Set(["openai-completions", "anthropic-messages"]);
1007
1009
  const RECOVERY_CHECKPOINT_CUSTOM_TYPE = "recovery_checkpoint";
1010
+ /** Re-attached workflow skill instructions after compaction summarized the original prompt away. */
1011
+ const WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE = "workflow-skill-context";
1008
1012
  const VISIBLE_CONTINUATION_PROMPT =
1009
1013
  "The connection was interrupted while you were answering. Your answer above is preserved exactly as the user saw it. Continue directly from where it stops: do not repeat any of it and do not redo completed work.";
1010
1014
 
@@ -1016,6 +1020,11 @@ function isTextVisibleTail(message: AssistantMessage): boolean {
1016
1020
  );
1017
1021
  }
1018
1022
 
1023
+ /** The model ended its turn normally with no pending tool calls: the answer is complete. */
1024
+ function isFinishedAnswer(message: AssistantMessage): boolean {
1025
+ return message.stopReason === "stop" && !message.content.some(block => block.type === "toolCall");
1026
+ }
1027
+
1019
1028
  function isLocalModelEndpoint(model: Model | undefined): boolean {
1020
1029
  if (!model) return false;
1021
1030
  if (model.provider === "ollama" || model.provider === "lm-studio" || model.provider === "llama.cpp") {
@@ -4193,7 +4202,22 @@ export class AgentSession {
4193
4202
  maintenanceGeneration !== undefined &&
4194
4203
  this.#promptGeneration === maintenanceGeneration
4195
4204
  ) {
4196
- this.#scheduleAgentContinue({ generation: maintenanceGeneration, skipCompactionCheck: true });
4205
+ // Compaction may have summarized away the active workflow's instructions;
4206
+ // re-attach them inside the tracked continuation (registered synchronously,
4207
+ // so the run never looks idle) before the loop's first model call.
4208
+ const invokedWorkflowSkills = outcome === "compacted" ? this.#invokedWorkflowSkillArgs() : undefined;
4209
+ this.#scheduleAgentContinue({
4210
+ generation: maintenanceGeneration,
4211
+ skipCompactionCheck: true,
4212
+ beforeContinue:
4213
+ invokedWorkflowSkills && invokedWorkflowSkills.size > 0
4214
+ ? async () => {
4215
+ const workflowSkillMessage =
4216
+ await this.#buildWorkflowSkillContextMessage(invokedWorkflowSkills);
4217
+ if (workflowSkillMessage) this.agent.steer(workflowSkillMessage);
4218
+ }
4219
+ : undefined,
4220
+ });
4197
4221
  }
4198
4222
  return;
4199
4223
  }
@@ -4403,6 +4427,8 @@ export class AgentSession {
4403
4427
  onError?: (error: unknown) => void;
4404
4428
  /** Run on the current model only: no managed chain, no fallback switch. */
4405
4429
  pinnedModel?: boolean;
4430
+ /** Runs inside the tracked task after the continue checks pass, before agent.continue. */
4431
+ beforeContinue?: () => Promise<void>;
4406
4432
  }): Promise<void> {
4407
4433
  const predecessorAgentEndHold = options?.suppressPredecessorAgentEnd
4408
4434
  ? this.#reserveDeferredAgentEndForContinuation()
@@ -4471,6 +4497,10 @@ export class AgentSession {
4471
4497
  skip("handoff_in_progress");
4472
4498
  return;
4473
4499
  }
4500
+ if (options?.beforeContinue) {
4501
+ await options.beforeContinue();
4502
+ if (!canContinue()) return;
4503
+ }
4474
4504
  const predecessorAgentEnd = this.#claimDeferredAgentEndForContinuation(predecessorAgentEndHold);
4475
4505
  const startsQueuedSuccessor =
4476
4506
  this.agent.state.messages.at(-1)?.role === "assistant" && this.agent.hasQueuedMessages();
@@ -7842,6 +7872,70 @@ export class AgentSession {
7842
7872
  return message;
7843
7873
  }
7844
7874
 
7875
+ /**
7876
+ * The active workflow skill's instructions, when compaction has summarized the
7877
+ * original skill prompt out of live context. A workflow (ralplan, ultragoal, ...)
7878
+ * spans many turns and follows its SKILL.md step by step; a summary of it is not
7879
+ * enough to keep following it, and the model otherwise re-reads the file.
7880
+ * Returns null while the skill prompt (or a restored copy) is still in context.
7881
+ */
7882
+ /**
7883
+ * Workflow skills this branch actually invoked, with their latest args. Sync and
7884
+ * in-memory so sessions that never ran a workflow skill pay no state-file IO.
7885
+ * A leftover state row from another session or an abandoned run must not inject
7886
+ * instructions, so only branch-invoked skills are restore candidates.
7887
+ */
7888
+ #invokedWorkflowSkillArgs(): Map<string, string> {
7889
+ const invoked = new Map<string, string>();
7890
+ for (const entry of this.sessionManager.getBranch()) {
7891
+ if (entry.type !== "custom_message" || entry.customType !== SKILL_PROMPT_MESSAGE_TYPE) continue;
7892
+ const details = entry.details as { name?: unknown; args?: unknown } | undefined;
7893
+ if (typeof details?.name !== "string" || !isCanonicalSkcWorkflowSkill(details.name)) continue;
7894
+ invoked.set(details.name, typeof details.args === "string" ? details.args : "");
7895
+ }
7896
+ return invoked;
7897
+ }
7898
+
7899
+ async #buildWorkflowSkillContextMessage(invoked: Map<string, string>): Promise<CustomMessage | null> {
7900
+ const sessionId = this.sessionManager.getSessionId();
7901
+ let activeSkill: string | undefined;
7902
+ try {
7903
+ const activeState = await readVisibleSkillActiveState(this.sessionManager.getCwd(), sessionId);
7904
+ activeSkill = activeState?.active_skills
7905
+ ?.filter(entry => entry.active !== false && entry.session_id === sessionId)
7906
+ .filter(entry => isCanonicalSkcWorkflowSkill(entry.skill))
7907
+ .sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""))[0]?.skill;
7908
+ } catch (error) {
7909
+ logger.warn("Failed to read workflow skill state for post-compaction restore", {
7910
+ error: error instanceof Error ? error.message : String(error),
7911
+ });
7912
+ return null;
7913
+ }
7914
+ if (!activeSkill || this.#isDisposed || this.sessionManager.getSessionId() !== sessionId) return null;
7915
+ const skillNameOf = (message: AgentMessage): string | undefined =>
7916
+ message.role === "custom" &&
7917
+ (message.customType === SKILL_PROMPT_MESSAGE_TYPE || message.customType === WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE)
7918
+ ? ((message.details as { name?: unknown } | undefined)?.name as string | undefined)
7919
+ : undefined;
7920
+ if (this.agent.state.messages.some(message => skillNameOf(message) === activeSkill)) return null;
7921
+ const skill = this.skills.find(candidate => candidate.name === activeSkill);
7922
+ const args = invoked.get(activeSkill);
7923
+ if (!skill || args === undefined) return null;
7924
+ const built = await buildSkillPromptMessage(skill, args, {
7925
+ cwd: this.sessionManager.getCwd(),
7926
+ sessionId,
7927
+ });
7928
+ return {
7929
+ role: "custom",
7930
+ customType: WORKFLOW_SKILL_CONTEXT_CUSTOM_TYPE,
7931
+ content: `The conversation was compacted. The active ${activeSkill} workflow's instructions are restored below; keep following them from the current step recorded in its state.\n\n${built.message}`,
7932
+ display: false,
7933
+ details: { name: activeSkill, args: args || undefined },
7934
+ attribution: "agent",
7935
+ timestamp: Date.now(),
7936
+ };
7937
+ }
7938
+
7845
7939
  /**
7846
7940
  * Clear the goal/plan static-once injection signatures so the next prompt
7847
7941
  * re-injects the active mode context once. MUST be called whenever the live
@@ -8538,6 +8632,12 @@ export class AgentSession {
8538
8632
  if (goalModeMessage) {
8539
8633
  messages.push(goalModeMessage);
8540
8634
  }
8635
+ const invokedWorkflowSkills = this.#invokedWorkflowSkillArgs();
8636
+ const workflowSkillMessage =
8637
+ invokedWorkflowSkills.size > 0 ? await this.#buildWorkflowSkillContextMessage(invokedWorkflowSkills) : null;
8638
+ if (workflowSkillMessage) {
8639
+ messages.push(workflowSkillMessage);
8640
+ }
8541
8641
  const volatileProjectContextMessage = await this.#buildVolatileProjectContextMessage();
8542
8642
  if (!this.#isLatestRetainedEphemeralCopy(volatileProjectContextMessage)) {
8543
8643
  messages.push(volatileProjectContextMessage);
@@ -12193,7 +12293,11 @@ export class AgentSession {
12193
12293
  // Try promotion first — if a larger model is available, switch instead of compacting
12194
12294
  const promoted = await this.#tryContextPromotion(assistantMessage);
12195
12295
  if (!promoted) {
12196
- await this.#runAutoCompaction("threshold", false);
12296
+ // A finished answer has nothing to resume; prompting the model to continue
12297
+ // would start an extra turn that can redo the work it just reported.
12298
+ await this.#runAutoCompaction("threshold", false, false, {
12299
+ promptContinuation: !isFinishedAnswer(assistantMessage),
12300
+ });
12197
12301
  }
12198
12302
  }
12199
12303
  return true;
@@ -12248,13 +12352,20 @@ export class AgentSession {
12248
12352
  // A compaction already in flight (overflow recovery, manual, idle) owns the
12249
12353
  // context; never double-compact underneath it.
12250
12354
  if (this.isCompacting) return "not-needed";
12355
+ // The configured threshold is enforced at answer boundaries; inside a run
12356
+ // only the ceiling/window limit applies, so work is not summarized away
12357
+ // and redone mid-task.
12358
+ const runSettings = {
12359
+ ...compactionSettings,
12360
+ thresholdTokens: resolveMidRunThresholdTokens(contextWindow, compactionSettings),
12361
+ };
12251
12362
 
12252
12363
  // Model maxTokens is a capability ceiling, not a per-turn reservation;
12253
12364
  // track actual context fullness (mirrors the agent_end / pre-prompt checks).
12254
12365
  const autoCompactionOutputReserveTokens = 0;
12255
12366
  const anchor = this.#findMidRunUsageAnchor(context.messages);
12256
12367
  let contextTokens = this.#estimateMidRunContextTokens(context.messages);
12257
- if (!shouldCompact(contextTokens, contextWindow, compactionSettings, autoCompactionOutputReserveTokens)) {
12368
+ if (!shouldCompact(contextTokens, contextWindow, runSettings, autoCompactionOutputReserveTokens)) {
12258
12369
  return "not-needed";
12259
12370
  }
12260
12371
  // Anti-loop (#1662): a given provider response anchors at most one
@@ -12287,7 +12398,7 @@ export class AgentSession {
12287
12398
  !shouldCompact(
12288
12399
  Math.max(0, contextTokens - pruneEstimate.tokensSaved),
12289
12400
  contextWindow,
12290
- compactionSettings,
12401
+ runSettings,
12291
12402
  autoCompactionOutputReserveTokens,
12292
12403
  )
12293
12404
  ) {
@@ -12295,7 +12406,7 @@ export class AgentSession {
12295
12406
  if (isAborted()) return "aborted";
12296
12407
  if (pruneResult) contextTokens = Math.max(0, contextTokens - pruneResult.tokensSaved);
12297
12408
  }
12298
- if (!shouldCompact(contextTokens, contextWindow, compactionSettings, autoCompactionOutputReserveTokens)) {
12409
+ if (!shouldCompact(contextTokens, contextWindow, runSettings, autoCompactionOutputReserveTokens)) {
12299
12410
  return pruneResult?.prunedCount ? "pruned" : "not-needed";
12300
12411
  }
12301
12412
 
@@ -13587,6 +13698,7 @@ export class AgentSession {
13587
13698
  deferred = false,
13588
13699
  options?: {
13589
13700
  continueAfterMaintenance?: boolean;
13701
+ promptContinuation?: boolean;
13590
13702
  deferHandoffMaintenance?: boolean;
13591
13703
  force?: boolean;
13592
13704
  signal?: AbortSignal;
@@ -13605,6 +13717,7 @@ export class AgentSession {
13605
13717
  deferred = false,
13606
13718
  options?: {
13607
13719
  continueAfterMaintenance?: boolean;
13720
+ promptContinuation?: boolean;
13608
13721
  deferHandoffMaintenance?: boolean;
13609
13722
  force?: boolean;
13610
13723
  signal?: AbortSignal;
@@ -13639,6 +13752,7 @@ export class AgentSession {
13639
13752
  let action: "context-full" | "handoff" =
13640
13753
  compactionSettings.strategy === "handoff" && reason !== "overflow" ? "handoff" : "context-full";
13641
13754
  const continueAfterMaintenance = options?.continueAfterMaintenance !== false;
13755
+ const promptContinuation = continueAfterMaintenance && options?.promptContinuation !== false;
13642
13756
  // Register the controller before the observable start event so an abort from
13643
13757
  // a local subscriber, extension, dispose, or caller signal owns this run.
13644
13758
  this.#autoCompactionAbortController?.abort();
@@ -13702,7 +13816,7 @@ export class AgentSession {
13702
13816
  willRetry: false,
13703
13817
  });
13704
13818
  if (autoCompactionSignal.aborted) return { kind: "aborted", source: "signal" };
13705
- if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
13819
+ if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
13706
13820
  this.#scheduleAutoContinuePrompt(generation);
13707
13821
  }
13708
13822
  if (autoCompactionSignal.aborted) return { kind: "aborted", source: "signal" };
@@ -13803,7 +13917,7 @@ export class AgentSession {
13803
13917
  onSkip: skipReason => this.#logCompactionContinuationSkipped("queued_continue", skipReason),
13804
13918
  onError: error => this.#logCompactionContinuationError("queued_continue", error),
13805
13919
  });
13806
- } else if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
13920
+ } else if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
13807
13921
  this.#scheduleAutoContinuePrompt(generation);
13808
13922
  }
13809
13923
  return { kind: "skipped" };
@@ -14047,7 +14161,7 @@ export class AgentSession {
14047
14161
  onSkip: reason => this.#logCompactionContinuationSkipped("queued_continue", reason),
14048
14162
  onError: error => this.#logCompactionContinuationError("queued_continue", error),
14049
14163
  });
14050
- } else if (continueAfterMaintenance && reason !== "idle" && compactionSettings.autoContinue !== false) {
14164
+ } else if (promptContinuation && reason !== "idle" && compactionSettings.autoContinue !== false) {
14051
14165
  this.#scheduleAutoContinuePrompt(generation);
14052
14166
  }
14053
14167
  return { kind: "compacted" };
@@ -14888,14 +15002,20 @@ export class AgentSession {
14888
15002
  // only reasoning holds no answer and its signed blocks cannot be replayed: it
14889
15003
  // is dropped and retried like a failure that showed nothing.
14890
15004
  const thinkingOnlyFailure = !managedOutcome && isThinkingOnlyFailure(message);
14891
- const visibleFailure =
14892
- !managedOutcome && !thinkingOnlyFailure && assistantMessageHasVisibleOrToolContent(message);
15005
+ // Tool calls cut off by the failure never ran (see #withoutUnexecutedToolCallFailure):
15006
+ // without answer text the attempt is dropped like a reasoning-only failure.
15007
+ const unexecutedToolCallFailure =
15008
+ !managedOutcome &&
15009
+ this.agent.state.messages.findLast(item => item.role === "assistant") === message &&
15010
+ this.#withoutUnexecutedToolCallFailure() !== undefined;
15011
+ const answerlessFailure = thinkingOnlyFailure || unexecutedToolCallFailure;
15012
+ const visibleFailure = !managedOutcome && !answerlessFailure && assistantMessageHasVisibleOrToolContent(message);
14893
15013
  const visibleContinuation = visibleFailure && this.#canContinueVisibleFailure(message);
14894
15014
  if (visibleFailure && !visibleContinuation) return false;
14895
15015
  // Bare defaults admit only clean canonical stream watchdog failures, plus a
14896
- // transient server failure that streamed only reasoning (e.g. an SSE
14897
- // overloaded_error after thinking_delta): the provider's own pre-content
14898
- // retry cannot cover it, and it has no answer to preserve. Completed tool
15016
+ // transient server failure that streamed only reasoning or never-run tool calls
15017
+ // (e.g. an SSE overloaded_error after thinking_delta): the provider's own
15018
+ // pre-content retry cannot cover it, and it has no answer to preserve. Completed tool
14899
15019
  // pairs and preserved visible output stay in the transcript and are never
14900
15020
  // re-executed; only hooks/commands/user shell/abort make the run unsafe.
14901
15021
  if (!managedFallback && !legacyRetryConfigured) {
@@ -14903,8 +15023,8 @@ export class AgentSession {
14903
15023
  !hasBareDefaultRetryDisqualifyingFacts(message) &&
14904
15024
  (classification === "transient" || classification === "first_event_timeout") &&
14905
15025
  BARE_DEFAULT_WATCHDOG_ERROR.test(message.errorMessage ?? "");
14906
- const bareThinkingOnly =
14907
- thinkingOnlyFailure &&
15026
+ const bareAnswerless =
15027
+ answerlessFailure &&
14908
15028
  classification === "transient" &&
14909
15029
  message.errorKind === undefined &&
14910
15030
  !BARE_DEFAULT_THROTTLE_ERROR.test(message.errorMessage ?? "") &&
@@ -14919,7 +15039,7 @@ export class AgentSession {
14919
15039
  classification === "transient" &&
14920
15040
  !hasBareDefaultRetryDisqualifyingFacts(message) &&
14921
15041
  isUnexpectedSocketCloseMessage(message.errorMessage ?? "");
14922
- if (!(bareWatchdog || bareThinkingOnly || bareSocketClose) || !this.#hasCleanContinuationSafety) {
15042
+ if (!(bareWatchdog || bareAnswerless || bareSocketClose) || !this.#hasCleanContinuationSafety) {
14923
15043
  return false;
14924
15044
  }
14925
15045
  }
@@ -15116,7 +15236,10 @@ export class AgentSession {
15116
15236
  // after the backoff instead (see below).
15117
15237
  if (!visibleContinuation) {
15118
15238
  const messages = this.agent.state.messages;
15119
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
15239
+ const withoutAttempt = unexecutedToolCallFailure ? this.#withoutUnexecutedToolCallFailure() : undefined;
15240
+ if (withoutAttempt) {
15241
+ this.agent.replaceMessages(withoutAttempt);
15242
+ } else if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
15120
15243
  this.agent.replaceMessages(messages.slice(0, -1));
15121
15244
  }
15122
15245
  }
@@ -15676,6 +15799,18 @@ export class AgentSession {
15676
15799
  logger.debug("auto_resume_paused", { trigger, reason: decision.reason });
15677
15800
  if (decision.reason === "already_resumed") {
15678
15801
  this.emitNotice("info", "Automatic resume was already used for this request.", "retry");
15802
+ } else if (
15803
+ trigger === "interrupted" &&
15804
+ decision.reason !== "disabled" &&
15805
+ decision.reason !== "not_interrupted" &&
15806
+ decision.reason !== "user_input_pending"
15807
+ ) {
15808
+ // Otherwise the step just stops: a failed tool-call tail renders only as a tool error.
15809
+ this.emitNotice(
15810
+ "warning",
15811
+ "The interrupted step was not resumed automatically. Send a message to continue.",
15812
+ "retry",
15813
+ );
15679
15814
  }
15680
15815
  return false;
15681
15816
  }
@@ -15719,10 +15854,14 @@ export class AgentSession {
15719
15854
  logger.warn("auto_resume_abandoned", { trigger, reason: "state changed while the marker was written" });
15720
15855
  return false;
15721
15856
  }
15722
- // A failed attempt that showed nothing, or only private reasoning, is not part of the
15723
- // answer; resending it only adds an empty assistant turn (the same rule manual retry applies).
15857
+ // A failed attempt that showed nothing, only private reasoning, or tool calls that
15858
+ // never ran is not part of the answer; resending it only adds an empty assistant
15859
+ // turn (the same rule manual retry applies).
15860
+ const withoutAttempt = this.#withoutUnexecutedToolCallFailure();
15724
15861
  const tailMessage = this.agent.state.messages.at(-1);
15725
- if (
15862
+ if (placeholders.length === 0 && withoutAttempt) {
15863
+ this.agent.replaceMessages(withoutAttempt);
15864
+ } else if (
15726
15865
  placeholders.length === 0 &&
15727
15866
  tailMessage?.role === "assistant" &&
15728
15867
  (tailMessage.stopReason === "error" || tailMessage.stopReason === "aborted") &&
@@ -15896,12 +16035,28 @@ export class AgentSession {
15896
16035
  );
15897
16036
  }
15898
16037
 
16038
+ /**
16039
+ * The transcript without a trailing failed attempt whose only public content is tool
16040
+ * calls cut off before they could run: the loop executes tools only after a completed
16041
+ * stream and pairs a failed stream's calls with placeholder results. Opaque transports
16042
+ * execute calls remotely, so their attempts are never dropped.
16043
+ */
16044
+ #withoutUnexecutedToolCallFailure(): AgentMessage[] | undefined {
16045
+ const messages = this.agent.state.messages;
16046
+ const failed = messages.findLast(message => message.role === "assistant");
16047
+ if (failed?.role !== "assistant" || failed.api === "cursor-agent" || this.model?.transport === "pi-native") {
16048
+ return undefined;
16049
+ }
16050
+ return dropUnexecutedToolCallFailure(messages);
16051
+ }
16052
+
15899
16053
  /**
15900
16054
  * Manually retry the last failed assistant turn, or resume an interrupted tail
15901
16055
  * left by a non-graceful process exit after the user/custom/tool-result message
15902
16056
  * was persisted but before the agent emitted a terminal assistant response.
15903
16057
  * Removes only a failed/aborted assistant tail with no visible output or tool
15904
- * calls, then re-attempts with a fresh retry budget.
16058
+ * calls, or a failed tail whose cut-off tool calls never ran (with their placeholder
16059
+ * results), then re-attempts with a fresh retry budget.
15905
16060
  * @returns false when the agent is busy, no retryable tail exists, the tail shows
15906
16061
  * output or tool calls, a persisted recovery is unresolved, or the step dispatched
15907
16062
  * unobservable remote work; true when a retry/resume was scheduled.
@@ -15919,7 +16074,9 @@ export class AgentSession {
15919
16074
  const lastMsg = messages[messages.length - 1];
15920
16075
  if (!lastMsg) return false;
15921
16076
 
15922
- if (lastMsg.role !== "assistant") {
16077
+ const withoutAttempt = this.#withoutUnexecutedToolCallFailure();
16078
+
16079
+ if (lastMsg.role !== "assistant" && !withoutAttempt) {
15923
16080
  if (!this.#isInterruptedRetryTail(lastMsg)) return false;
15924
16081
  this.#retryAttempt = 0;
15925
16082
  this.#endStepRecoveryBudget();
@@ -15927,15 +16084,21 @@ export class AgentSession {
15927
16084
  return true;
15928
16085
  }
15929
16086
 
15930
- const assistantMsg = lastMsg as AssistantMessage;
15931
- // Explicit retry does not establish the outcome of an interrupted operation
15932
- // and is never permission to erase a prefix already shown to the user. A failure
15933
- // that streamed only reasoning holds no answer and is dropped like an empty one.
15934
- if (!isThinkingOnlyFailure(assistantMsg) && assistantMessageHasVisibleOrToolContent(assistantMsg)) return false;
15935
- if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "aborted") return false;
16087
+ if (withoutAttempt) {
16088
+ // Cut-off tool calls that never ran are dropped with their placeholder results.
16089
+ this.agent.replaceMessages(withoutAttempt);
16090
+ } else {
16091
+ const assistantMsg = lastMsg as AssistantMessage;
16092
+ // Explicit retry does not establish the outcome of an interrupted operation
16093
+ // and is never permission to erase a prefix already shown to the user. A failure
16094
+ // that streamed only reasoning holds no answer and is dropped like an empty one.
16095
+ if (!isThinkingOnlyFailure(assistantMsg) && assistantMessageHasVisibleOrToolContent(assistantMsg))
16096
+ return false;
16097
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "aborted") return false;
15936
16098
 
15937
- // Remove the empty failed/aborted assistant message before re-attempting.
15938
- this.agent.replaceMessages(messages.slice(0, -1));
16099
+ // Remove the empty failed/aborted assistant message before re-attempting.
16100
+ this.agent.replaceMessages(messages.slice(0, -1));
16101
+ }
15939
16102
 
15940
16103
  // Reset retry budget for a fresh attempt: a manual retry is a new invocation.
15941
16104
  this.#retryAttempt = 0;
@@ -72,6 +72,38 @@ export function isThinkingOnlyFailure(message: AgentMessage | undefined): boolea
72
72
  return thinking;
73
73
  }
74
74
 
75
+ /**
76
+ * A failed attempt cut off before any answer text whose only public content is tool
77
+ * calls: the loop runs tools only after a stream completes, so these calls never ran
78
+ * and only got placeholder results. Like a reasoning-only failure it holds no answer;
79
+ * recovery drops it with those placeholders and asks the same model again.
80
+ */
81
+ function isUnexecutedToolCallFailure(message: AgentMessage): boolean {
82
+ if (message.role !== "assistant" || message.stopReason !== "error") return false;
83
+ let toolCall = false;
84
+ for (const block of message.content) {
85
+ if (block.type === "toolCall") toolCall = true;
86
+ else if (block.type === "text" && block.text.trim().length > 0) return false;
87
+ }
88
+ return toolCall;
89
+ }
90
+
91
+ /**
92
+ * The transcript before its trailing unexecuted tool-call failure, without the error
93
+ * placeholder results paired with its calls; undefined when the tail is anything else.
94
+ */
95
+ export function dropUnexecutedToolCallFailure(messages: readonly AgentMessage[]): AgentMessage[] | undefined {
96
+ const index = messages.findLastIndex(message => message.role === "assistant");
97
+ if (index === -1) return undefined;
98
+ const failed = messages[index];
99
+ if (failed.role !== "assistant" || !isUnexecutedToolCallFailure(failed)) return undefined;
100
+ const callIds = new Set(failed.content.flatMap(block => (block.type === "toolCall" ? [block.id] : [])));
101
+ for (const message of messages.slice(index + 1)) {
102
+ if (message.role !== "toolResult" || !message.isError || !callIds.has(message.toolCallId)) return undefined;
103
+ }
104
+ return messages.slice(0, index);
105
+ }
106
+
75
107
  /** Built-in tools whose execution has no side effects and may run again after a restart. */
76
108
  const RESTART_SAFE_TOOL_CLASSES = [ReadTool, SearchTool, FindTool, AstGrepTool, LocateTool] as const;
77
109
 
@@ -129,7 +161,8 @@ export function findInterruptedToolCalls(messages: readonly AgentMessage[]): Too
129
161
  * Tails that cannot be resumed safely: a failed step holding private signed reasoning
130
162
  * next to an answer or tool calls (possibly cut off mid-arguments), a call without an
131
163
  * id, or unanswered calls whose results could no longer be placed directly after their
132
- * assistant. A failure that streamed only reasoning is dropped before resuming instead.
164
+ * assistant. A failure that streamed only reasoning, or tool calls that never ran, is
165
+ * dropped before resuming instead.
133
166
  */
134
167
  function hasUnsafeAssistantTail(messages: readonly AgentMessage[]): boolean {
135
168
  const assistantIndex = messages.findLastIndex(message => message.role === "assistant");
@@ -194,14 +227,18 @@ export function resolveAutoResumePolicy(input: AutoResumePolicyInput): AutoResum
194
227
  if (input.userInputPending) return { type: "pause", reason: "user_input_pending" };
195
228
  if (!input.selectorAvailable) return { type: "pause", reason: "selector_unavailable" };
196
229
  if (!input.budgetAdmits) return { type: "pause", reason: "budget_exhausted" };
197
- if (hasUnsafeAssistantTail(input.messages)) return { type: "pause", reason: "unsafe_tail" };
198
- if (hasVisibleFailedPrefix(input.messages) && !input.prefixReplayable)
199
- return { type: "pause", reason: "unsafe_tail" };
200
- const tail = input.messages.at(-1);
230
+ // Tool calls cut off by the failure never ran: the attempt is dropped before resuming,
231
+ // so only the transcript before it is judged.
232
+ const withoutAttempt = dropUnexecutedToolCallFailure(input.messages);
233
+ const messages = withoutAttempt ?? input.messages;
234
+ if (hasUnsafeAssistantTail(messages)) return { type: "pause", reason: "unsafe_tail" };
235
+ if (hasVisibleFailedPrefix(messages) && !input.prefixReplayable) return { type: "pause", reason: "unsafe_tail" };
236
+ const tail = messages.at(-1);
201
237
  if (!tail) return { type: "pause", reason: "not_interrupted" };
202
- // Only a restart can find a user message whose request never settled.
238
+ // Only a restart can find a user message whose request never settled, unless the
239
+ // failed attempt answering it was just dropped.
203
240
  if (tail.role === "user") {
204
- return input.trigger === "restart"
241
+ return input.trigger === "restart" || withoutAttempt
205
242
  ? { type: "resume", mode: "full", interruptedCalls: [] }
206
243
  : { type: "pause", reason: "not_interrupted" };
207
244
  }
@@ -210,7 +247,7 @@ export function resolveAutoResumePolicy(input: AutoResumePolicyInput): AutoResum
210
247
  const settled = !tail.content.some(block => block.type === "toolCall");
211
248
  if (settled) return { type: "pause", reason: "not_interrupted" };
212
249
  }
213
- const interruptedCalls = findInterruptedToolCalls(input.messages);
250
+ const interruptedCalls = findInterruptedToolCalls(messages);
214
251
  if (interruptedCalls.length === 0) return { type: "resume", mode: "full", interruptedCalls };
215
252
  if (!input.selectedTools.some(tool => isRestartSafeTool(tool, input.selectedTools))) {
216
253
  return { type: "pause", reason: "no_restart_safe_tools" };
@@ -7,6 +7,7 @@ import * as path from "node:path";
7
7
  import { canContinuePersistedHistory } from "@sayknow-cli/agent-core";
8
8
  import { getAgentDir } from "@sayknow-cli/utils";
9
9
  import { withFileLock } from "../config/file-lock";
10
+ import { canonicalizeTrustedPath } from "../session/internal/managed-session-scope";
10
11
  import { type SessionDestinationInput, SessionManager } from "../session/session-manager";
11
12
  import { FileSessionStorage, type SessionStorageSnapshot } from "../session/session-storage";
12
13
  import { parseClaudeCodeTranscript, parseClaudeExport } from "./claude";
@@ -548,7 +549,8 @@ function findExistingWorkspaceImport(
548
549
  }
549
550
  return {
550
551
  targetSessionId: candidate.id,
551
- targetPath: candidate.path,
552
+ // Same canonical form SessionManager gives a freshly materialized import (macOS /var -> /private/var).
553
+ targetPath: canonicalizeTrustedPath(candidate.path),
552
554
  title:
553
555
  typeof header.title === "string" && header.title.trim()
554
556
  ? truncateText(header.title, MAX_TITLE_CHARS)
package/src/tools/ask.ts CHANGED
@@ -867,8 +867,11 @@ export class AskTool implements AgentTool<AskParametersSchema, AskToolDetails> {
867
867
  activeRemoteReceipt = undefined;
868
868
  if (receipt) await receipt.settle(settlement);
869
869
  };
870
- const checkedPrefix = `${theme.checkbox.checked} `;
871
- const uncheckedPrefix = `${theme.checkbox.unchecked} `;
870
+ // Headless/SDK sessions never initialize the TUI theme and never render
871
+ // checkbox-decorated labels, so any non-matching prefix is correct there.
872
+ const checkbox = theme?.checkbox ?? { checked: "[x]", unchecked: "[ ]" };
873
+ const checkedPrefix = `${checkbox.checked} `;
874
+ const uncheckedPrefix = `${checkbox.unchecked} `;
872
875
  /** The option a displayed label stands for, without checkbox, numbering, or recommendation decoration. */
873
876
  const semanticLabel = (label: string): string =>
874
877
  stripRecommendedSuffix(