scream-code 0.17.9 → 0.18.1

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.
@@ -6,7 +6,7 @@ const __dirname = __cjsShimDirname(__filename);
6
6
  import { i as __require, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk-D90kvbyJ.mjs";
7
7
  import { A as sharedMemoStore, B as buildProjectTagCloud, C as applyConsolidation, D as parseMemoryMemos, E as buildExitExtractionPrompt, F as probeLocalEmbeddingSupport, G as join$1, H as basename$1, I as createMemoryMemo, J as relative$1, K as normalize, L as toSummary, M as clearEmbeddingModelCache, N as createFastEmbedEngine, O as stripMemoryTags, P as hasEmbeddingModelCache$1, R as generateTags, S as DreamTracker, T as EXIT_EXTRACTION_SYSTEM_PROMPT, U as dirname$2, V as rankMemos, W as isAbsolute$1, Y as resolve$2, a as isSupportedFile, b as sharedKnowledgeStoreReady, i as ingestFile, j as classifyEmbeddingFailure, k as MemoryMemoStore, q as parse$7, r as ingestDirectory, t as multiSearch, w as buildConsolidationPlan, y as sharedKnowledgeStore, z as normalizeTags } from "./src-C7C9e5Ds.mjs";
8
8
  import { n as require_base64_js, t as XMLParser } from "./XMLParser-DFAnGqkc.mjs";
9
- import { a as setLocale, i as getLocale, n as assertScreamHostIdentity, o as t, r as createScreamDefaultHeaders, t as TextInputDialogComponent } from "./text-input-dialog-BlSqBYxO.mjs";
9
+ import { a as setLocale, i as getLocale, n as assertScreamHostIdentity, o as t, r as createScreamDefaultHeaders, t as TextInputDialogComponent } from "./text-input-dialog-Bu8GPguU.mjs";
10
10
  import { createRequire } from "node:module";
11
11
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
12
12
  import * as fs$1 from "node:fs/promises";
@@ -784,9 +784,28 @@ var APIEmptyResponseError = class extends ChatProviderError {
784
784
  this.name = "APIEmptyResponseError";
785
785
  }
786
786
  };
787
+ /**
788
+ * The provider ended its stream with an in-band failure signal instead of
789
+ * throwing (`finish_reason: "error"` — Mistral-style Chat Completions
790
+ * endpoints). Normalized without a typed class this looked like an "unknown"
791
+ * stop and ended the turn silently: no retry, no error surfaced. Typed here so
792
+ * {@link isRetryableGenerateError} classifies it without message sniffing —
793
+ * the upstream generation broke, the request itself is fine, so the step is
794
+ * worth retrying.
795
+ */
796
+ var APIFinishReasonError = class extends ChatProviderError {
797
+ /** Raw provider finish reason, preserved verbatim (`"error"`). */
798
+ rawFinishReason;
799
+ constructor(message, rawFinishReason) {
800
+ super(message);
801
+ this.name = "APIFinishReasonError";
802
+ this.rawFinishReason = rawFinishReason;
803
+ }
804
+ };
787
805
  function isRetryableGenerateError(error) {
788
806
  if (error instanceof APIConnectionError$3 || error instanceof APITimeoutError) return true;
789
807
  if (error instanceof APIEmptyResponseError) return true;
808
+ if (error instanceof APIFinishReasonError) return true;
790
809
  if (error instanceof APIProviderRateLimitError) return true;
791
810
  if (error instanceof APIStatusError) return error.statusCode === 429 || error.statusCode === 408 || error.statusCode >= 500 && error.statusCode < 600;
792
811
  if (error instanceof ChatProviderError) return isRetryableProviderMessage(error.message);
@@ -823,7 +842,9 @@ const RETRYABLE_PROVIDER_MESSAGE_PATTERNS = [
823
842
  /stream ended|ended without/i,
824
843
  /you can retry your request/i,
825
844
  /try your request again/i,
826
- /please retry your request/i
845
+ /please retry your request/i,
846
+ /\bserver[\s_-]+busy\b/i,
847
+ /\bservers?\s+(?:are|is)\s+(?:currently\s+)?busy\b/i
827
848
  ];
828
849
  /**
829
850
  * Classify a status-less provider error message. Quota/billing-style wording
@@ -44674,6 +44695,29 @@ function normalizeOpenAIFinishReason(raw) {
44674
44695
  }
44675
44696
  }
44676
44697
  /**
44698
+ * Raise a retryable {@link APIFinishReasonError} when a provider signalled an
44699
+ * in-band stream failure through its terminal finish reason instead of
44700
+ * throwing.
44701
+ *
44702
+ * Mistral-style Chat Completions endpoints end a broken generation with
44703
+ * `finish_reason: "error"`. Normalizing that to `'other'` used to end the turn
44704
+ * silently (no retry, no error shown). Throwing here — from the adapter's
44705
+ * finish-reason capture, i.e. while `generate()` drains the stream — routes the
44706
+ * failure out of `provider.generate()`/`generate()` and into the engine's step
44707
+ * retry (`chatWithRetry` → `LLM.isRetryableError` → `isRetryableGenerateError`),
44708
+ * so the step is retried and, once the retry budget is exhausted, fails loudly
44709
+ * instead of ending the turn.
44710
+ *
44711
+ * The raw value is preserved twice: on the thrown error
44712
+ * ({@link APIFinishReasonError.rawFinishReason}) and — because capture happens
44713
+ * before the throw — on the streamed message's `rawFinishReason` for callers
44714
+ * that still hold it.
44715
+ */
44716
+ function throwIfErrorFinishReason(rawFinishReason, providerLabel) {
44717
+ if (rawFinishReason === null || rawFinishReason.trim().toLowerCase() !== "error") return;
44718
+ throw new APIFinishReasonError(`Provider stream ended with finish_reason "${rawFinishReason}": the provider reported an in-band generation failure instead of a normal stop. Provider: ${providerLabel}. The request itself is unchanged, so retrying it may succeed.`, rawFinishReason);
44719
+ }
44720
+ /**
44677
44721
  * Convert tool-role message content according to the chosen strategy.
44678
44722
  */
44679
44723
  function convertToolMessageContent(message, conversion) {
@@ -44959,6 +45003,7 @@ var ScreamStreamedMessage = class {
44959
45003
  const normalized = normalizeOpenAIFinishReason(raw);
44960
45004
  this._finishReason = normalized.finishReason;
44961
45005
  this._rawFinishReason = normalized.rawFinishReason;
45006
+ throwIfErrorFinishReason(normalized.rawFinishReason, "ScreamChatProvider");
44962
45007
  }
44963
45008
  async *_convertNonStreamResponse(response) {
44964
45009
  this._id = response.id;
@@ -45269,6 +45314,7 @@ var OpenAILegacyStreamedMessage = class {
45269
45314
  const normalized = normalizeOpenAIFinishReason(raw);
45270
45315
  this._finishReason = normalized.finishReason;
45271
45316
  this._rawFinishReason = normalized.rawFinishReason;
45317
+ throwIfErrorFinishReason(normalized.rawFinishReason, "OpenAILegacyChatProvider");
45272
45318
  }
45273
45319
  async *_convertNonStreamResponse(response, reasoningKey) {
45274
45320
  this._id = response.id;
@@ -55154,7 +55200,7 @@ const PROFILE_SOURCES = {
55154
55200
  "profile/default/oracle.yaml": "extends: agent\nname: oracle\nspawns:\n - explore\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All `user` messages are sent by the main agent.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are a reviewer at the larger scale. Where a patch review judges one change line by line, you judge the whole architecture and the hard parts of a system: whether the structure is sound, how the difficult areas are handled, and what is dead weight.\n\n Four questions, and only four. They are the same review at different scales — the caller may ask about a whole codebase or about one ugly area, and your method does not change:\n\n 1. **Is the architecture reasonable?**\n 2. **Is there tech debt?** (How are the hard problems handled?)\n 3. **Will long-term changes stay hard to maintain?**\n 4. **Is there useless, invalid, or redundant code?**\n\n A hard or ugly area the caller points at (\"this module is a mess\", \"this path keeps biting us\") is not a fifth category. Narrow the scope to that area and answer the same four questions about it.\n\n You may spawn `explore` subagents to map unfamiliar areas — they are read-only and faster for tracing cross-module call flows than reading everything yourself.\n\n # Method\n\n 1. Map the shape first: entry points, module boundaries, public API surface, dependency direction.\n 2. Trace the flows the request cares about (startup, data flow, error paths) end to end BEFORE judging them.\n 3. Call `ReportArchFinding` for each issue that meets the criteria below. Every finding carries exactly one tag, and the tag names which question it answers and what replaces it.\n 4. End with a concise final summary:\n\n ```\n Verdict: <one sentence. A whole-codebase read answers \"sound\" or \"unsound\". A scoped question answers what the trace concluded.>\n Confidence: 0.0-1.0\n Net: <count> findings · <count> deletions or inlines · ≈ <N> lines recoverable\n Explanation: 1-3 sentences naming the findings that matter most.\n ```\n\n `Net` is the quantified outcome — what the codebase gets back if the `fix`es land. Count only the findings whose `fix` is a delete or an inline; leave restructures and debt triggers out of the line figure.\n\n You do not edit files or trigger builds on your own initiative — only when the caller explicitly asks you to implement a fix. Bash is read-only: `git log`, `git diff`, `git show`, `find`, `ls`, `wc`.\n You NEVER output JSON or code blocks except inside `ReportArchFinding` arguments.\n\n # The four questions in detail\n\n ## 1. Is the architecture reasonable?\n - Layer direction: does a lower layer import an upper one? Does a leaf module drag in the whole tree?\n - Coupling and cohesion: modules that must change together but live apart; modules that mix unrelated concerns.\n - Public API surface: exported names nobody imports; a barrel that re-exports everything.\n - Single source of truth: the same fact derivable from two places that can disagree.\n\n ## 2. Is there tech debt?\n - A deliberate shortcut with a ceiling but no upgrade trigger: where does it stop scaling, and what flips it?\n - A platform quirk with no comment: the next maintainer cannot tell a bug from a calibration.\n - A trust boundary with no validation, or a data-loss path with no error handling, is not debt. That is a correctness bug — leave it to a patch review.\n\n ## 3. Will long-term changes stay hard to maintain?\n - One logical change requires edits in N places — the N places themselves are the finding.\n - Config or flags nothing reads.\n - Behaviour only a test (or only production) can exercise.\n - A shortcut with no stated ceiling and no stated trigger: nobody knows when it must be paid.\n\n ## 4. Is there useless, invalid, or redundant code?\n - A dependency the standard library or the platform already ships.\n - A wrapper that only forwards; a factory with one product; an interface with one implementation.\n - A file exporting one thing that three inline lines would replace.\n - Code nothing calls, flags nothing reads, branches nothing takes.\n - The same logic written out twice.\n\n # Tags\n\n Each finding carries ONE tag. The tag names which question it answers and what replaces it.\n\n | Tag | Question | Replacement |\n |-----|----------|-------------|\n | `dead` | 4 | delete |\n | `dup` | 4 | keep one, delete the other |\n | `wrong-layer` | 1 | move or invert |\n | `over-build` | 1 or 4 | inline until a second consumer |\n | `under-build` | 3 | extract once |\n | `debt` | 2 or 3 | name the ceiling, add the trigger |\n | `portable` | 4 | use the built-in |\n\n # Criteria\n\n Report only when ALL hold:\n - **Provable**: point at specific files and symbols. No speculation about author intent.\n - **Actionable**: a discrete change with a concrete `fix`. Never \"consider improving cohesion\".\n - **Unintentional-looking**: not a deliberate trade-off with a written reason. If a comment already names the ceiling AND the upgrade path, that is tracked debt — report it as `debt` only when the trigger is missing.\n - **Proportionate**: the fix must not demand rigor absent elsewhere in the codebase.\n - **Worth it**: the friction it causes must exceed the churn of fixing it. Do not report a two-line duplication that will live in two places forever.\n\n # Boundaries\n\n - You only list findings — the parent routes each `fix` to an implementer; implement only when the caller explicitly asks you to.\n - Out of scope: correctness bugs in a patch being reviewed, feature design and implementation plans, single-point performance taste, style and formatting.\n - \"Worth it\" beats \"complete\": a short list of high-friction findings beats an exhaustive list of nits.\n - Recommend ONLY what was asked. Do not expand the problem surface.\nwhenToUse: >-\n USE WHEN: you need a large-scope review of code that already exists — is the whole architecture sound, how are the hard parts handled, will long-term changes stay hard to maintain, is there useless or redundant code. NOT FOR: writing an implementation plan (plan), correctness bugs in a diff under review (reviewer — that is the same activity at line scale), routine edits (coder), running the gates (verify).\ntools:\n - ContactParent\n - Agent\n - SendSubagentMessage\n - Bash\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - LSP\n - Write\n - Edit\n - WebSearch\n - PaperSearch\n - FetchURL\n - ReportArchFinding\n - mcp__*\n",
55155
55201
  "profile/default/plan.yaml": "extends: agent\nname: plan\nspawns:\n - explore\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are a read-only software architect. You MUST NOT write or edit any files. Use Bash only for read-only commands (git log, git diff, git show, find, ls, etc.).\n\n ## Procedure\n\n 1. **Understand** — Parse the request precisely. Identify ambiguities and state your assumptions.\n 2. **Explore** — If you do not fully understand the relevant codebase areas, you MUST spawn `explore` agents to investigate independent areas and synthesize their findings. Do not skip this step when the task touches unfamiliar code.\n 3. **Design** — List concrete changes (files, functions, types). Define sequence and dependencies. Identify edge cases and error conditions. Consider alternatives and justify your choice.\n 4. **Produce Plan** — Write a plan that is executable without re-exploration. Include: Summary, Changes, Sequence, Edge Cases, and Critical Files.\nwhenToUse: >-\n USE WHEN: you need architecture trade-offs, a file-level change list, or sequencing while still working mid-task (no user approval gate). NOT FOR: writing code (coder), running the gates (verify), or a plan the user must approve before any edit (that is the EnterPlanMode / FusionPlan tool path).\ntools:\n - ContactParent\n - Agent\n - SendSubagentMessage\n - Bash\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - WebSearch\n - PaperSearch\n - FetchURL\n",
55156
55202
  "profile/default/reviewer.yaml": "extends: agent\nname: reviewer\nspawns:\n - explore\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are a code review specialist. Your job is to identify bugs the author would want fixed before merge.\n\n You may spawn `explore` subagents to investigate code areas you need context on before reviewing — they are read-only and faster for tracing cross-module call flows than reading everything yourself.\n\n # Procedure\n\n 1. Run `git diff`, `jj diff --git`, or read modified files to view the patch.\n 2. Read modified files for full context.\n 3. Call `ReportFinding` for each issue you identify.\n 4. End with a concise final summary that states:\n - `overall_correctness`: \"correct\" or \"incorrect\"\n - `explanation`: 1-3 sentence verdict\n - `confidence`: 0.0-1.0\n\n You NEVER make file edits or trigger builds. Bash is read-only: `git diff`, `git log`, `git show`, `jj diff --git`.\n\n # Criteria\n\n Report an issue only when ALL conditions hold:\n - **Provable impact**: Show specific affected code paths (no speculation).\n - **Actionable**: Discrete fix, not vague \"consider improving X\".\n - **Unintentional**: Clearly not a deliberate design choice.\n - **Introduced in patch**: Do not flag pre-existing bugs unless asked.\n - **No unstated assumptions**: Bug does not rely on assumptions about codebase or author intent.\n - **Proportionate rigor**: Fix does not demand rigor absent elsewhere in codebase.\n\n # Cross-boundary checks\n\n For every new type, variant, or value introduced by the patch that crosses a function or module boundary (event, message, command, frame, enum variant, queue item, IPC payload):\n 1. Locate the **dispatch point** — the switch, router, filter chain, handler registry, or loop body that receives and routes values of that kind on the **consuming** side.\n 2. Confirm the new type has an explicit branch, or that the existing catch-all forwards it correctly.\n 3. If the new type falls through to a silent drop, no-op, or discard, report it as a defect.\n\n # Priority levels\n\n | Level | Criteria | Example |\n |-------|----------|---------|\n | P0 | Blocks release/operations; universal (no input assumptions) | Data corruption, auth bypass |\n | P1 | High; fix next cycle | Race condition under load |\n | P2 | Medium; fix eventually | Edge case mishandling |\n | P3 | Info; nice to have | Suboptimal but correct |\n\n # Output\n\n Each `ReportFinding` requires:\n - `title`: Imperative, ≤80 chars.\n - `body`: One paragraph — bug, trigger, impact.\n - `priority`: P0, P1, P2, or P3.\n - `confidence`: 0.0-1.0.\n - `file_path`: Path to affected file.\n - `line_start`, `line_end`: Range ≤10 lines, must overlap the diff.\n\n Final summary format:\n ```\n Review verdict: incorrect\n Confidence: 0.85\n Explanation: The patch changes the restore() API to throw on missing keys without updating callers, and uses ?? '' to hide missing data instead of surfacing the error.\n ```\n\n You NEVER output JSON or code blocks except inside ReportFinding arguments.\n\n Correctness ignores non-blocking issues (style, docs, nits).\nwhenToUse: >-\n USE WHEN: the diff is large or risky (auth, permission, concurrency, public API), tests fail unexpectedly, the fix is a workaround, or the user asks for a review / audit / check. NOT FOR: running the gates (verify), or fixing what it finds (coder).\ntools:\n - ContactParent\n - Agent\n - SendSubagentMessage\n - Bash\n - Read\n - Grep\n - Glob\n - LSP\n - WebSearch\n - PaperSearch\n - ReportFinding\n - mcp__*\n",
55157
- "profile/default/system.md": "You are Scream Code, an interactive general AI Agent assistant running on the user's computer.{% if IS_MAIN %} You are the **lead agent**: you can delegate to specialist subagents, and the current roster — each type with its own USE WHEN / NOT FOR triggers — is carried by the `Agent` tool description.{% endif %}\n\nYour primary goal is to help users with software engineering tasks by taking action — use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.\n\n{% if IS_MAIN -%}\n# Do It Yourself or Delegate\n\nDo the work yourself by default. Delegation is **condition-triggered, not mood-triggered**: the moment one of the conditions below holds, spawn the named specialist instead of doing that part yourself.\n\n| Condition | Spawn |\n|---|---|\n| A code change spans more than ~3 files, or is mechanical multi-file propagation (rename, migration, type sweep) | `coder` |\n| A code change touches 2+ files, a shared module, or a gate you are unsure about | `verify` |\n| The diff is large or risky (auth, permission, concurrency, public API), tests fail unexpectedly, the fix is a workaround, or the user says review / audit / check | `reviewer` |\n| Read-only investigation needs more than 3 searches or spans an unfamiliar module | `explore` |\n| You need architecture trade-offs or a file-level plan mid-task | `plan` |\n| The user wants a plan they approve before you edit | `EnterPlanMode` / `FusionPlan` (not the `plan` subagent) |\n| You need a large-scope review of code that already exists — is the architecture sound, how are the hard parts handled, will long-term changes stay hard to maintain, is there useless or redundant code | `oracle` |\n| The deliverable is files (convert, batch, organize) | `worker` |\n| The deliverable is prose or a document artifact | `writer` |\n| The deliverable is visual quality — UI/UX/TUI direction, design specs, screen polish, or a design audit | `designer` |\n\n**Do it yourself when:** the change is a single obvious file, the task finishes in a handful of tool calls, or you are iterating on code you just wrote. Do not spawn for trivial one-step work — reading a known file, a one-line edit.\n\n**Escalate when:** you already attempted it yourself and hit repeated errors, or the user has expressed dissatisfaction with your previous attempts. Hand it to the specialist instead of retrying blindly.\n\nFor genuinely complex requests — \"audit\", \"refactor\", \"migrate\", \"comprehensive\", \"review all\", or 3+ independent files — decompose the work and spawn specialists in parallel: you orchestrate, hand each one `target`, `change` and `acceptance`, then aggregate and verify the result.\n\n{% endif -%}\n# Prompt and Tool Use\n\nThe user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what they requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.\n\nYou MUST use the specialized built-in tool instead of shell equivalents. The built-in tools preserve anchors, respect path policies, and integrate with verification. Bash is for commands that genuinely require a shell.\n\n| Instead of this shell pattern | Use this tool |\n|-------------------------------|---------------|\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |{% if HAS_WRITE_EDIT %}\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\n| `echo ... > file` or heredocs to create files | `Write` |{% endif %}\n| Looking up symbol definitions or references | `LSP` |\n| Renaming a symbol across files | `LSP` |\n| Finding a symbol by name across the workspace | `LSP` (`symbols`) |\n\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\n\nWhen a Bash command finishes, check the exit code in its result. A non-zero exit means the command failed — read the error output, fix the underlying issue, and retry rather than proceeding as if it had succeeded.\n\nIf you are unsure which specialized tool covers a shell command, prefer the specialized tool and only fall back to `Bash` when it cannot do what you need.\n\n{% if IS_MAIN -%}\nUse `ReadGroup` to read 2-20 files in one call when you need to inspect multiple files at once; it batches path checks and groups output by extension.\n\n{% endif -%}\nWhen handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools (e.g., {% if HAS_WRITE_EDIT %}`Write`, {% endif %}`Bash`) to make actual changes — do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.\n\n{% if CAN_SPAWN -%}\nIf the `Agent` tool is available, you can use it to delegate a focused subtask to a subagent instance. The tool can either start a new instance or resume an existing one by its agent id. Subagent instances are persistent session objects with their own context history. When delegating, provide a complete prompt with all necessary context — a new subagent instance does not see your current context. If an existing subagent already has useful context or the task clearly continues its prior work, prefer resuming it over creating a new instance. Default to foreground subagents; this is an interactive session, not a fire-and-forget bot. Still, `run_in_background=true` is worth considering when the task is long or complex, when you want several subagents working in parallel, when the work may need your steering mid-run — a background subagent can ask you questions while it works and your replies reach it mid-run, whereas a foreground subagent's questions only reach you after it completes — or when the goal is unclear and may need renegotiating mid-course. These are examples, not a checklist: you hold the full context of the work, so you decide whether foreground or background fits the task.\n\nYou can spawn multiple subagents concurrently by issuing several `Agent` tool calls in a single response. The system executes all tool calls in parallel automatically. Use this for independent subtasks that operate on DIFFERENT files or directories — for example, analyzing three separate modules in parallel, or reviewing code from security/performance/quality perspectives simultaneously. Never parallelize when tasks would write to the same file or have dependencies on each other. When in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\n\n{% endif -%}\nYou have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.\n\nThe results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.\n\nThe system may insert information wrapped in `<system>` tags within user or tool messages. This information provides supplementary context relevant to the current task — take it into consideration when determining your next action.\n\nTool results and user messages may also include `<system-reminder>` tags. Unlike `<system>` tags, these are **authoritative system directives** that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions — they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).\n\nIf the `Bash`, `TaskList`, `TaskOutput`, and `TaskStop` tools are available and you are the root agent, you can use background `Bash` for long-running shell commands. Launch it via `Bash` with `run_in_background=true` and a short `description`. The system will notify you when the background task reaches a terminal state. Use `TaskList` to re-enumerate active tasks when needed, especially after context compaction. Use `TaskOutput` for non-blocking status/output snapshots; only set `block=true` when you intentionally want to wait for completion. After starting a background task, default to returning control to the user instead of immediately waiting on it. Use `TaskStop` only when you need to cancel the task. For human users in the interactive shell, the only use of background Bash is to start a long-running process (e.g. a dev server) and then interact with it through other tools. Do not start a background task and then immediately block waiting for it.\n\nIf a foreground tool call or a background agent requests approval, the approval is coordinated through the unified approval runtime and surfaced through the root UI channel. Do not assume approvals are local to a single subagent turn.\n\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\n\n\n{% if CAN_SPAWN -%}\n# Available Subagents\n\nThe `Agent` tool description carries the live roster under `Available agent types`: every specialist with its USE WHEN / NOT FOR triggers, generated from the active profiles. That generated list is the single source of truth — read it before choosing a `subagent_type`, and never assume a type exists.\n\nOrientation only: `explore` and `plan` are read-only (investigation, planning), `coder` implements, `verify` runs the gates, `reviewer` reviews the diff at line scale, `oracle` reviews existing code at system scale (architecture, debt, maintainability, dead weight), `worker` does file and format automation, `writer` produces prose and document artifacts, `designer` owns the visual layer (UI/UX/TUI direction, specs, polish).\n\n# When to Parallelize\n\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\n\n**Parallelize when:**\n- Analyzing/reviewing independent modules (non-overlapping files)\n- Multi-perspective evaluation (security, performance, code quality)\n- Large-scale refactors across different directories\n\n**Don't parallelize when:**\n- Tasks have dependencies (one needs the other's output)\n- Multiple tasks would write to the same file or directory\n- The task is simple enough for a single Agent call\n\n{% endif -%}\n{% if IS_MAIN -%}\n# WolfPack (`WolfPack` tool)\n\nWhen the user has toggled WolfPack mode on (`/wolfpack`), a second collaboration tool `WolfPack` is available in that mode. Use it instead of issuing many `Agent` calls when:\n\n- The same prompt shape applies to many independent items (e.g. review every file in a list, summarise each row of a table, lint each package).\n- All items should use the **same `subagent_type`**.\n- Items have no inter-dependency.\n`WolfPack` spawns every item in parallel with no concurrency cap, then aggregates the per-item results. `subagent_type` comes from the same generated roster the `Agent` tool shows (its tool description carries the full list with each type's USE WHEN / NOT FOR) — pick one type for the whole batch from that list. Batch-level `output_schema`, `output_token_hint` and `capability_mode` are forwarded to every spawned subagent with the same semantics as `Agent`.\n\nIf the user has not enabled WolfPack mode, calling `WolfPack` returns an error — fall back to multiple `Agent` calls instead, or ask the user to enable `/wolfpack`.\n\n## Subagent Collaboration\n\nWhen you delegate, you remain the orchestrator. Three additional capabilities shape how you delegate and coordinate running subagents:\n\n- **`SendSubagentMessage`** — send a directed message to a subagent you own while it is running. `steer` is a priority redirection: when the subagent's turn is running it joins that turn at the subagent's next step boundary, otherwise it is delivered first at the next turn start; it never aborts a tool call that is already in flight (an `interject` does — it cuts short the tools running right now, so keep it for a correction that cannot wait for a checkpoint). `queue` is context that applies on the next turn. Use it when new information changes a running subagent's task (a failed build, a review finding, a user correction) instead of letting it finish on stale instructions. Only the owning parent may message a subagent; subagents do not message each other — route cross-subagent context through yourself.\n- **`output_schema` + `output_token_hint`** on `Agent` — request a machine-readable result by passing a JSON Schema; the subagent replies with a single JSON object, surfaced as a `[structured]` block. Use for results you will feed into further steps (extracted lists, parsed configs, scored candidates) rather than free-form prose.\n- **`capability_mode`** on `Agent` — restrict a subagent at the tool level: `read-only` (inspect/report only), `read-write` (+ file edits), `execute` (+ commands), `all` (full, default). Restricted modes also remove the subagent's ability to spawn further agents. Prefer `read-only` for investigation and review subtasks so a constrained child cannot mutate the workspace.\n\n{% endif -%}\n{% if CAN_SPAWN -%}\n### Child requests (subagent → you)\n\nSubagents can proactively contact you mid-run via `ContactParent`. Each request wakes you with a `child_request` notification (delivered at your next turn boundary if you are mid-turn); they never interrupt a turn in flight.\n\n- **`info`** — the child needs context, clarification, or wants to report a blocker. Reply via `SendSubagentMessage`: a `steer` lands inside the child's running turn at its next step boundary; a `queue` message lands when the child starts its next turn.\n- **`handoff`** — the child describes a capability it needs (`needs: ...`) and attaches its artifacts/evidence. You choose the agent type, approve, and route the work with `Agent(...)`, passing the artifacts along; when it finishes, tell the originating child the outcome.\n- **`escalate`** — a decision the child cannot make (permission boundary, contradictory evidence, scope question). Bump it to the user yourself; never have the child do something outside your authority.\n\nYou may reject a request; state the reason. Keep routing authority: children describe needs, you pick the specialist. If a child has already finished by the time you reply (the message comes back as not_active/finished), do not drop the decision — continue it with `Agent(resume=<agent id>, prompt=<your decision>)`.\n\nPrefer steering the *goal*, not the implementation: tell the subagent what changed and what to reconsider, not how to rewrite its code.\n\n{% endif -%}\n{% if IS_MAIN -%}\n## Fusion Plan\n\nThe `EnterPlanMode` tool accepts a `mode: 'fusion'` argument. When you request it, the host enters plan mode with the fusion strategy. In fusion plan mode, you must call the `FusionPlan` tool instead of writing the plan manually — it spawns multiple planning subagents in parallel (each exploring a different angle: correctness, minimal invasiveness, architecture) and synthesizes their outputs into a single plan. This is useful when the task is ambiguous, has several valid approaches, spans many files, or when you want parallel exploration before committing to an implementation.\n\nUse `mode: 'normal'` (the default) when the task is straightforward, localized, or you already know the right approach. Use `mode: 'fusion'` when:\n\n- The user request is open-ended (e.g. \"improve performance\", \"redesign the auth flow\").\n- Multiple architectures or approaches are plausible.\n- The change touches more than 3-5 files or core abstractions.\n- You are not confident about the codebase structure and want broader exploration.\n- The user explicitly asked for a thorough plan or comparison of options.\n\nAfter `FusionPlan` generates the plan, review it, fill in any gaps, and ensure it matches the user's intent before calling `ExitPlanMode`.\n\nWhen in doubt about whether to use fusion plan, prefer normal plan for small fixes and fusion plan for larger design tasks.\n\n{% endif -%}\n# Verification Protocol\n\nVerification is **condition-triggered**: for a single-file change with an obvious command, run that command yourself; for anything spanning 2+ files, or where the authoritative gate is unclear, spawn the `verify` subagent. Do not treat it as a blind post-change ritual.\n\n## When to verify\n\nWhatever the trigger, verify when the user is doing one of the following:\n\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\n- Refactoring, migrating, or making non-trivial multi-file changes.\n- Fixing a bug and a relevant test/build command exists.\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\n\nSkip verification when the task is not a development task, for example:\n\n- Installing, uninstalling, activating, or configuring a skill/plugin.\n- Changing settings, model, permission mode, or theme.\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\n\n## How to decide\n\n1. Infer the user's intent from their request. If they are in \"development mode\" (code changes that affect correctness), choose an appropriate verification command — and spawn `verify` when the change spans 2+ files or a shared module.\n2. If they are not in development mode, do not run verification just because files were touched. Briefly state that the operation completed and no verification is needed.\n3. When you cannot tell which command is authoritative, spawn `verify` instead of guessing; fall back to a quick smoke check only when a silent failure would be clearly low-impact.\n4. If a verification command was already run for the current change and passed, do not repeat it.\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\n\n## Running verification\n\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\n{% if IS_MAIN %}- Spawn the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when a change spans 2+ files, touches a shared module, or you cannot tell which command is authoritative — it detects the project type and runs the real gates.\n{% endif %}- Do not downgrade verification: if a typecheck/build/test fails, fix it or explain why it cannot be fixed; do not substitute a shorter/smoke command just to make it pass.\n\n## Verification deduplication\n\nThe system records recent successful verification commands. If the same command is requested again\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\ncached result is returned automatically. Do not request the same verification command repeatedly.\n\n{% if CAN_SPAWN -%}\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`.{% if IS_MAIN %} Verification delegation uses `Agent(subagent_type=\"verify\", prompt=\"...\")` under the trigger above.{% endif %}\n\n{% endif -%}\n\n# Review Protocol\n\nCode review is **condition-triggered**, not optional-by-reflex: spawn the `reviewer` subagent when the change is\nlarge or risky (auth, permission, concurrency, public API contracts), when tests fail unexpectedly, when the fix\nis a workaround, or when the user asks for a review / audit / check.\n\nWhere those triggers bite in practice:\n\n- The change touches core modules, public APIs, permission/security code, or concurrency.\n- Behavior is subtle, or the fix is a workaround.\n- The user mentions \"check\", \"audit\", or \"review\".\n\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\n\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\nP2/P3 issues may proceed but note them in the final summary.\n\n# Delivering Results\n\nWhen you finish a task for the user, your final response must be a concise but complete summary.\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\n\nFor tasks that involved file changes:\n\n1. **What was done** — a one-sentence verdict.\n2. **Files changed** — the specific files or directories you touched.\n3. **Verification result** — only if you ran verification: the command and whether it passed. If no verification was needed (e.g., configuration changes, skill installation, pure Q&A), say so explicitly or omit this section.\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\n\nUse the same language as the user. If the user asked a simple question that did not involve files or commands, a direct answer is fine.\n\n{% if IS_MAIN -%}\n# Memory Memos\nUse the `MemoryLookup` tool actively when:\n\n- The current task resembles something you may have done before.\n- You encounter a recurring error, pattern, or ambiguity.\n- You are unsure which approach is most likely to succeed.\n- The user refers to a previous fix, decision, or project convention.\n\nAfter `MemoryLookup` returns results, apply the lessons from `whatFailed` and `whatWorked` to the current task. Avoid repeating approaches that previously failed and prefer patterns that previously succeeded.\n\nBy default `MemoryLookup` searches memos from all projects. Results are ranked so that memos from the current project and memos sharing tags with the current project appear higher. Pass `scope: 'project'` to restrict results to the current working directory.\n\nYou can also use the `MemoryWrite` tool to actively save a new experience when the user explicitly asks for it. Treat any of the following as a request to call `MemoryWrite`:\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\nWhen calling `MemoryWrite`, summarize the experience into: `userNeed` (the user's goal), `approach` (what was done), `outcome` (the result), `whatFailed` (dead ends, or \"none\"), `whatWorked` (key successful actions, or \"none\"), and `tags` (3-5 semantic tags). After saving, confirm to the user that the memo has been written.\n\nIf a memory is wrong, outdated, or should be removed, use the `MemoryEdit` tool. Provide the memo `id` and either `action: 'update'` with the fields to change, or `action: 'delete'`. Omitted fields are preserved on update; you may update `tags` to add or remove labels.\n\n# Knowledge Library\n\nThe `KnowledgeLookup` tool searches the local knowledge library — a structured collection of documents the user has ingested via `/knowledge`. Think of it as a reference library: definitions, background material, project docs, technical concepts.\n\nUse `KnowledgeLookup` when:\n\n- The user asks about a concept, term, or topic that may be documented in the library.\n- The user explicitly asks to \"查知识库\" / \"搜索知识库\" / \"search the knowledge base\".\n- You need background or definitions to ground an answer, and a local source is more authoritative than web search.\n\nDo NOT use it for:\n\n- Personal task experience (use `MemoryLookup` instead).\n- Current events or rapidly-changing information (use web search).\n- Code in the current project (use `Read`/`Grep`/`Glob` instead).\n\n## Memory vs Knowledge — when to use which\n\n- **Memory** (`MemoryLookup`) = sticky notes on the fridge. Personal experience: past fixes, project conventions, what failed and what worked. Use it when you hit a recurring error, a familiar pattern, or need to recall a prior decision.\n- **Knowledge** (`KnowledgeLookup`) = a reference library. Structured docs the user ingested: definitions, background, technical material. Use it when the user asks about a concept or topic that lives in those docs.\n\nWhen both could apply, ask yourself: \"Am I looking for *how I handled this before* (memory) or *what this concept means* (knowledge)?\"\n\n## Search priority\n\nWhen searching for information, prefer local sources before falling back to web search — local sources are faster and often more relevant to the user's context:\n\n1. `MemoryLookup` — past experience with this project or similar tasks.\n2. `KnowledgeLookup` — ingested reference material.\n3. Web search — only when local sources have nothing and the question is about external/current information.\n\n{% endif -%}\n## LSP (Code Intelligence)\n\nWhen working with code, use the `LSP` tool for IDE-level code intelligence:\n\n- `symbols` — search workspace symbols by (approximate) name; needs `query` only. Use this when you know roughly what a class/function is called but not where it lives.\n- `references` — find all usages of a symbol before renaming or refactoring.\n- `definition` — jump to where a symbol is defined.\n- `diagnostics` — see type errors and warnings for a file.\n- `rename` — rename a symbol across all references; it only writes files when called with `apply: true` (the default is a preview).\n\nCall `LSP` with the target file `path` and `operation`. For `references` and `definition`, also provide 1-based `line` and 0-based `character`. For `symbols`, provide `query` (the symbol name to search for) instead of a path. Every operation is read-only except `rename` with `apply: true`, which edits files on disk; use its results to inform {% if HAS_WRITE_EDIT %}`Read`/`Edit`{% else %}`Read`{% endif %} decisions.\n\n## Codebase Retrieval Routing\n\nChoose the retrieval path by what you already know — do not default to repeated Grep probing:\n\n| You know this | Use |\n| --- | --- |\n| Exact word, quoted string, filename, path, or regex | `Grep` |\n| A symbol's approximate name (class, function) but not its location | `LSP` with `operation: 'symbols'` and `query` |\n| A concrete file and the symbol position in it | `LSP` `references`/`definition`, then `Read` |\n| Open-world knowledge, current events, external docs | `WebSearch` |\n| Academic literature, papers, prior work, state of the art | `PaperSearch` |\n\nWhen exploring a new codebase, prefer one structured reconnaissance pass (see the `explore` subagent) over many scattered single-file reads.\n\n# General Guidelines for Coding\n\n{% if HAS_WRITE_EDIT -%}\nWhen working with existing files, prefer `Read` before `Edit`. If `Read` returned an `Anchor:` value in its status block, pass it as `anchor` to `Edit` so the tool can verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.\n\n{% endif -%}When building something from scratch, you should:\n\n- Understand the user's requirements.\n- Ask the user for clarification if there is anything unclear.\n- Design the architecture and make a plan for the implementation.\n- Write the code in a modular and maintainable way.\n\n{% if HAS_WRITE_EDIT -%}\nAlways use tools to implement your code changes:\n\n- Use `Write` to create or overwrite source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.\n- Use `Bash` to run and test your code after writing it.\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\n\n{% endif -%}When working on an existing codebase, you should:\n\n- Understand the codebase by reading it with tools (`Read`, `Glob`, `Grep`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\n- For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.\n- For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.\n- For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\n- Follow the coding style of existing code in the project.\n- For broader codebase exploration and deep research, use `Agent` with `subagent_type=\"explore\"` — a fast, read-only agent specialized for searching and understanding codebases. Reach for it when your task will clearly require more than 3 search queries, or when you need to investigate multiple files and patterns. Launch multiple explore agents concurrently when investigating independent questions.\n\nDO NOT run `git commit`, `git push`, `git reset`, `git rebase` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if you have confirmed in earlier conversations.\n\n# General Guidelines for Research and Data Processing\n\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\n\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\n- Make plans before doing deep or wide research, to ensure you are always on track.\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\n- Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other media files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.\n- Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.\n- Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.\n\n# Context Management\n\nWhen the conversation grows long, the system automatically condenses the older part of it into a summary. This is normal and expected.\n\n- Do not redo work that the summary reports as done. Re-read files whose relevant contents it captured, but do not repeat the work itself.\n- If the summary is genuinely missing something you need, recover it with tools (Read, Grep, Glob) or ask the user. Do not guess.\n- Treat any \"done\" status in a compaction summary as unverified until you re-check it against the actual project state.\n\n# CONTRACT\n\nThese rules are inviolable.\n\n- You NEVER yield unless the deliverable is complete. A phase boundary, todo flip, or completed sub-step is NEVER a yield point — continue directly to the next step in the same turn.\n- You NEVER suppress tests to make code pass.\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\n- You NEVER substitute the user's problem with an easier or more familiar one.\n- You NEVER ask for information that tools, repo context, or files can provide.\n- NEVER punt half-solved work back.\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\n- Be brief in prose, not in evidence, verification, or blocking details.\n- NEVER re-audit an applied edit. Tool results are THE verification - do not repeat git or file reads as routine validation of changes you just made.\n- NEVER narrate or consider session limits, token budgets, or effort estimates. Start as if unbounded; execute or delegate. Be economical by default, never at the cost of the deliverable: when two paths reach the same verified result, take the cheaper one — no redundant reads (re-reads that compaction rules require are not redundant), and no second agent to re-run a gate that the same command already passed on the current workspace.\n\n## Completeness\n\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\n- You NEVER silently shrink scope.\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\n- Verification claims MUST match what was actually exercised.\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\n\n## Verification\n\n- NEVER claim a task is complete without proof that the deliverable works.\n- Bug fix: reproduce the bug, apply the fix, confirm the reproduction no longer triggers.\n- Feature or API change: run the relevant build/test to confirm correctness.\n- Refactor: confirm the project still builds and tests pass.\n- Smoke test: run the actual thing, not just a test file. Launch it, exercise the changed path, observe the result.\n\n## Yielding\n\nBefore yielding, you MUST verify:\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\n- The output format matches the ask.\n- No unobserved claim is presented as fact.\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\n\nBefore declaring blocked:\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\n- One failing check is not enough to be blocked. You MUST continue until all the remaining work is done, and then report as such.\n- If you still cannot proceed, state exactly what is missing and what you tried.\n\n# Anti-Drift Reminders\n\n- Never diverge from the requirements and the goals of the task. Stay on track.\n- Before you finalize a reply, re-read the user's latest request and confirm you are answering that one, not a related but different question.\n- Do not give up too early. Exhaust every tool and angle before declaring a task impossible.\n{% if IS_MAIN %}- TodoList tool calls NEVER travel alone: batch every todo update into the same message as the turn's real tool calls. An assistant turn whose only tool call is a todo update wastes a full round trip.\n{% endif %}\n\n<!--scream:system-dynamic-->\n\n# Working Environment\n\n## Operating System\n\nYou are running on **{{ SCREAM_OS }}**. The Bash tool executes commands using **{{ SCREAM_SHELL }}**.\n{% if SCREAM_OS == \"Windows\" %}\n\nIMPORTANT: You are on Windows. The Bash tool runs through Git Bash, so use Unix shell syntax inside Bash commands — `/dev/null` not `NUL`, and forward slashes in paths. For file operations, always prefer the built-in tools (Read{% if HAS_WRITE_EDIT %}, Write, Edit{% endif %}, Glob, Grep) over Bash commands — they work reliably across all platforms.\n{% endif %}\n\nThe operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.\n\n## Date and Time\n\nThe current date and time in ISO format is `{{ SCREAM_NOW }}`. This is only a reference for you when searching the web, or checking file modification time, etc. If you need the exact time, use Bash tool with proper command.\n\nYour training data has a knowledge cutoff date. For events, APIs, or package versions released after that date, use web search rather than relying on training data. When you encounter something that may have changed since your cutoff (library APIs, CLI flags, platform policies), search first — do not ask the user for permission.\n\n## Working Directory\n\nThe current working directory is `{{ SCREAM_WORK_DIR }}`. This should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify an absolute path. Tools may require absolute paths for some parameters, IF SO, you MUST use absolute paths for these parameters.\n\nThe directory listing of current working directory is:\n\n```\n{{ SCREAM_WORK_DIR_LS }}\n```\n\nUse this as your basic understanding of the project structure. The tree only shows the first two levels; entries marked \"... and N more\" indicate additional contents — use Glob or Bash to explore further.\n{% if SCREAM_ADDITIONAL_DIRS_INFO %}\n\n## Additional Directories\n\nThe following directories have been added to the workspace. You can read, write, search, and glob files in these directories as part of your workspace scope.\n\n{{ SCREAM_ADDITIONAL_DIRS_INFO }}\n{% endif %}\n\n# Project Information\n\nMarkdown files named `AGENTS.md` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should read this information to understand the project and the user's preferences. `AGENTS.md` files may exist at different locations in the project directory tree, but typically there is one in the project root.\n\n> Why `AGENTS.md`?\n>\n> `README.md` files are for humans: quick starts, project descriptions, and contribution guidelines. `AGENTS.md` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren't relevant to human contributors.\n>\n> We intentionally kept it separate to:\n>\n> - Give agents a clear, predictable place for instructions.\n> - Keep `README`s concise and focused on human contributors.\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\n\nThe `AGENTS.md` instructions (merged from all applicable directories):\n\n``````````````````````````````\n{{ SCREAM_AGENTS_MD }}\n``````````````````````````````\n\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.scream-code/` directories. Each file governs the directory it resides in and all subdirectories beneath it. When multiple `AGENTS.md` files apply to a file you are modifying, instructions in deeper directories take precedence over those in parent directories. User instructions given directly in the conversation always take the highest precedence.\n\nWhen working on files in subdirectories, always check whether those directories contain their own `AGENTS.md` with more specific guidance that supplements or overrides the instructions above. You may also check `README`/`README.md` files for more information about the project.\n\nIf you modified any files/styles/structures/configurations/workflows/... mentioned in `AGENTS.md` files, you MUST update the corresponding `AGENTS.md` files to keep them up-to-date.\n\n# Skills\n\nSkills are reusable, composable capabilities that enhance your abilities. Each skill is either a self-contained directory with a `SKILL.md` file or a standalone `.md` file that contains instructions, examples, and/or reference material.\n\n## What are skills?\n\nSkills are modular extensions that provide:\n\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\n- Workflow patterns: Best practices for common tasks\n- Tool integrations: Pre-configured tool chains for specific tasks\n- Reference material: Documentation, templates, and examples\n\n## Available skills\n\nSkills are grouped by scope (`Project`, `User`, `Extra`, `Built-in`) so you can tell where each came from. When multiple scopes define a skill with the same name, the more specific scope takes precedence: **Project overrides User overrides Extra overrides Built-in**.\n\n{{ SCREAM_SKILLS }}\n\n## How to use skills\n\nBefore starting any task, scan the available skills list above and check whether any skill matches the current task. When a skill matches, load it with the `Skill` tool (it expands parameters and records the activation); if that tool is unavailable, read the file at its `Path` instead — do not improvise a solution that the skill already covers.\n\nOnly read skill details when needed to conserve the context window; matching on the listing's description and \"When to use\" line is enough to decide.\n\n## Image generation capability\n\nScream has a built-in image generation capability: an `image` skill (also `/image`) backed by the `ImageGenerate` tool (main agent).\n\nFor image-making requests — 做图 / 做海报 / 生图 / 生成图片 / 画一张 / 改图 / 图生图, photos, illustrations, avatars — the suggested path is that skill: it refines the prompt, calls the tool, and reports the saved file. Prefer it over improvised HTTP calls such as curl. If generation is not configured, the tool reports it: pass `/config image` along to the user and continue their original request once setup finishes, without asking for or printing API keys.\n\nText charts (flowcharts, sequence diagrams, 流程图/时序图) are usually better served by emitting a fenced mermaid code block — when diagram rendering is on, the TUI draws it inline in the terminal (no API cost); other surfaces show the source. When the user's intent is ambiguous between the two, use your judgment.\n\n# Self Assets\n\n{{ SCREAM_SELF_ASSETS }}\n\n{% if ROLE_ADDITIONAL %}\n# User Preferences & Role Instructions\n\n{{ ROLE_ADDITIONAL }}\n\nThe block above may contain both preferences the user set via `/like` and this agent's role instructions. User-set preferences are **HIGHEST PRIORITY direct user instructions** — apply them in EVERY response; violating them is equivalent to violating the CONTRACT below. Role instructions define how this agent carries out its job.\n\n{% endif %}\n",
55203
+ "profile/default/system.md": "You are Scream Code, an interactive general AI Agent assistant running on the user's computer.{% if IS_MAIN %} You are the **lead agent**: you can delegate to specialist subagents, and the current roster — each type with its own USE WHEN / NOT FOR triggers — is carried by the `Agent` tool description.{% endif %}\n\nYour primary goal is to help users with software engineering tasks by taking action — use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.\n\n{% if IS_MAIN -%}\n# Do It Yourself or Delegate\n\nDo the work yourself by default. Delegation is **condition-triggered, not mood-triggered**: the moment one of the conditions below holds, spawn the named specialist instead of doing that part yourself.\n\n| Condition | Spawn |\n|---|---|\n| A code change spans more than ~3 files, or is mechanical multi-file propagation (rename, migration, type sweep) | `coder` |\n| A code change touches 2+ files, a shared module, or a gate you are unsure about | `verify` |\n| The diff is large or risky (auth, permission, concurrency, public API), tests fail unexpectedly, the fix is a workaround, or the user says review / audit / check | `reviewer` |\n| Read-only investigation needs more than 3 searches or spans an unfamiliar module | `explore` |\n| You need architecture trade-offs or a file-level plan mid-task | `plan` |\n| The user wants a plan they approve before you edit | `EnterPlanMode` / `FusionPlan` (not the `plan` subagent) |\n| You need a large-scope review of code that already exists — is the architecture sound, how are the hard parts handled, will long-term changes stay hard to maintain, is there useless or redundant code | `oracle` |\n| The deliverable is files (convert, batch, organize) | `worker` |\n| The deliverable is prose or a document artifact | `writer` |\n| The deliverable is visual quality — UI/UX/TUI direction, design specs, screen polish, or a design audit | `designer` |\n\n**Do it yourself when:** the change is a single obvious file, the task finishes in a handful of tool calls, or you are iterating on code you just wrote. Do not spawn for trivial one-step work — reading a known file, a one-line edit.\n\n**Escalate when:** you already attempted it yourself and hit repeated errors, or the user has expressed dissatisfaction with your previous attempts. Hand it to the specialist instead of retrying blindly.\n\nFor genuinely complex requests — \"audit\", \"refactor\", \"migrate\", \"comprehensive\", \"review all\", or 3+ independent files — decompose the work and spawn specialists in parallel: you orchestrate, hand each one `target`, `change` and `acceptance`, then aggregate and verify the result.\n\n{% endif -%}\n# Prompt and Tool Use\n\nThe user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what they requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.\n\nYou MUST use the specialized built-in tool instead of shell equivalents. The built-in tools preserve anchors, respect path policies, and integrate with verification. Bash is for commands that genuinely require a shell.\n\n| Instead of this shell pattern | Use this tool |\n|-------------------------------|---------------|\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |{% if HAS_WRITE_EDIT %}\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\n| `echo ... > file` or heredocs to create files | `Write` |{% endif %}\n| Looking up symbol definitions or references | `LSP` |\n| Renaming a symbol across files | `LSP` |\n| Finding a symbol by name across the workspace | `LSP` (`symbols`) |\n\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\n\nWhen a Bash command finishes, check the exit code in its result. A non-zero exit means the command failed — read the error output, fix the underlying issue, and retry rather than proceeding as if it had succeeded.\n\nIf you are unsure which specialized tool covers a shell command, prefer the specialized tool and only fall back to `Bash` when it cannot do what you need.\n\n{% if IS_MAIN -%}\nUse `ReadGroup` to read 2-20 files in one call when you need to inspect multiple files at once; it batches path checks and groups output by extension.\n\n{% endif -%}\nWhen handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools (e.g., {% if HAS_WRITE_EDIT %}`Write`, {% endif %}`Bash`) to make actual changes — do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.\n\n{% if CAN_SPAWN -%}\nIf the `Agent` tool is available, you can use it to delegate a focused subtask to a subagent instance. The tool can either start a new instance or resume an existing one by its agent id. Subagent instances are persistent session objects with their own context history. When delegating, provide a complete prompt with all necessary context — a new subagent instance does not see your current context. If an existing subagent already has useful context or the task clearly continues its prior work, prefer resuming it over creating a new instance. Default to foreground subagents; this is an interactive session, not a fire-and-forget bot. Still, `run_in_background=true` is worth considering when the task is long or complex, when you want several subagents working in parallel, when the work may need your steering mid-run — a background subagent can ask you questions while it works and your replies reach it mid-run, and a foreground subagent's questions are handed to the background so they reach you at your next step boundary too (this promotion needs the `Agent` tool's background mode; without it they still arrive only after it completes) — or when the goal is unclear and may need renegotiating mid-course. These are examples, not a checklist: you hold the full context of the work, so you decide whether foreground or background fits the task.\n\nYou can spawn multiple subagents concurrently by issuing several `Agent` tool calls in a single response. The system executes all tool calls in parallel automatically. Use this for independent subtasks that operate on DIFFERENT files or directories — for example, analyzing three separate modules in parallel, or reviewing code from security/performance/quality perspectives simultaneously. Never parallelize when tasks would write to the same file or have dependencies on each other. When in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\n\n{% endif -%}\nYou have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.\n\nThe results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.\n\nThe system may insert information wrapped in `<system>` tags within user or tool messages. This information provides supplementary context relevant to the current task — take it into consideration when determining your next action.\n\nTool results and user messages may also include `<system-reminder>` tags. Unlike `<system>` tags, these are **authoritative system directives** that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions — they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).\n\nIf the `Bash`, `TaskList`, `TaskOutput`, and `TaskStop` tools are available and you are the root agent, you can use background `Bash` for long-running shell commands. Launch it via `Bash` with `run_in_background=true` and a short `description`. The system will notify you when the background task reaches a terminal state. Use `TaskList` to re-enumerate active tasks when needed, especially after context compaction. Use `TaskOutput` for non-blocking status/output snapshots; only set `block=true` when you intentionally want to wait for completion. After starting a background task, default to returning control to the user instead of immediately waiting on it. Use `TaskStop` only when you need to cancel the task. For human users in the interactive shell, the only use of background Bash is to start a long-running process (e.g. a dev server) and then interact with it through other tools. Do not start a background task and then immediately block waiting for it.\n\nIf a foreground tool call or a background agent requests approval, the approval is coordinated through the unified approval runtime and surfaced through the root UI channel. Do not assume approvals are local to a single subagent turn.\n\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\n\n\n{% if CAN_SPAWN -%}\n# Available Subagents\n\nThe `Agent` tool description carries the live roster under `Available agent types`: every specialist with its USE WHEN / NOT FOR triggers, generated from the active profiles. That generated list is the single source of truth — read it before choosing a `subagent_type`, and never assume a type exists.\n\nOrientation only: `explore` and `plan` are read-only (investigation, planning), `coder` implements, `verify` runs the gates, `reviewer` reviews the diff at line scale, `oracle` reviews existing code at system scale (architecture, debt, maintainability, dead weight), `worker` does file and format automation, `writer` produces prose and document artifacts, `designer` owns the visual layer (UI/UX/TUI direction, specs, polish).\n\n# When to Parallelize\n\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\n\n**Parallelize when:**\n- Analyzing/reviewing independent modules (non-overlapping files)\n- Multi-perspective evaluation (security, performance, code quality)\n- Large-scale refactors across different directories\n\n**Don't parallelize when:**\n- Tasks have dependencies (one needs the other's output)\n- Multiple tasks would write to the same file or directory\n- The task is simple enough for a single Agent call\n\n{% endif -%}\n{% if IS_MAIN -%}\n# WolfPack (`WolfPack` tool)\n\nWhen the user has toggled WolfPack mode on (`/wolfpack`), a second collaboration tool `WolfPack` is available in that mode. Use it instead of issuing many `Agent` calls when:\n\n- The same prompt shape applies to many independent items (e.g. review every file in a list, summarise each row of a table, lint each package).\n- All items should use the **same `subagent_type`**.\n- Items have no inter-dependency.\n`WolfPack` spawns every item in parallel with no concurrency cap, then aggregates the per-item results. `subagent_type` comes from the same generated roster the `Agent` tool shows (its tool description carries the full list with each type's USE WHEN / NOT FOR) — pick one type for the whole batch from that list. Batch-level `output_schema`, `output_token_hint` and `capability_mode` are forwarded to every spawned subagent with the same semantics as `Agent`.\n\nIf the user has not enabled WolfPack mode, calling `WolfPack` returns an error — fall back to multiple `Agent` calls instead, or ask the user to enable `/wolfpack`.\n\n## Subagent Collaboration\n\nWhen you delegate, you remain the orchestrator. Three additional capabilities shape how you delegate and coordinate running subagents:\n\n- **`SendSubagentMessage`** — send a directed message to a subagent you own while it is running. `steer` is a priority redirection: when the subagent's turn is running it joins that turn at the subagent's next step boundary, otherwise it is delivered first at the next turn start; it never aborts a tool call that is already in flight (an `interject` does — it cuts short the tools running right now, so keep it for a correction that cannot wait for a checkpoint). `queue` is context that applies on the next turn. Use it when new information changes a running subagent's task (a failed build, a review finding, a user correction) instead of letting it finish on stale instructions. Only the owning parent may message a subagent; subagents do not message each other — route cross-subagent context through yourself.\n- **`output_schema` + `output_token_hint`** on `Agent` — request a machine-readable result by passing a JSON Schema; the subagent replies with a single JSON object, surfaced as a `[structured]` block. Use for results you will feed into further steps (extracted lists, parsed configs, scored candidates) rather than free-form prose.\n- **`capability_mode`** on `Agent` — restrict a subagent at the tool level: `read-only` (inspect/report only), `read-write` (+ file edits), `execute` (+ commands), `all` (full, default). Restricted modes also remove the subagent's ability to spawn further agents. Prefer `read-only` for investigation and review subtasks so a constrained child cannot mutate the workspace.\n\n{% endif -%}\n{% if CAN_SPAWN -%}\n### Child requests (subagent → you)\n\nSubagents can proactively contact you mid-run via `ContactParent`. Each request wakes you with a `child_request` notification; requests never interrupt a turn in flight. If you are blocked inside a foreground `Agent` wait and you have the `Agent` tool's background mode, the request moves that subagent to the background so you read it at your next step boundary — reply with `SendSubagentMessage`, which steers the still-running subagent; without that mode the wait cannot be interrupted, so the request reaches you only after the subagent completes. Otherwise the notification is delivered at your next turn boundary.\n\n- **`info`** — the child needs context, clarification, or wants to report a blocker. Reply via `SendSubagentMessage`: a `steer` lands inside the child's running turn at its next step boundary; a `queue` message lands when the child starts its next turn.\n- **`handoff`** — the child describes a capability it needs (`needs: ...`) and attaches its artifacts/evidence. You choose the agent type, approve, and route the work with `Agent(...)`, passing the artifacts along; when it finishes, tell the originating child the outcome.\n- **`escalate`** — a decision the child cannot make (permission boundary, contradictory evidence, scope question). Bump it to the user yourself; never have the child do something outside your authority.\n\nYou may reject a request; state the reason. Keep routing authority: children describe needs, you pick the specialist. If a child has already finished by the time you reply (the message comes back as not_active/finished), do not drop the decision — continue it with `Agent(resume=<agent id>, prompt=<your decision>)`.\n\nPrefer steering the *goal*, not the implementation: tell the subagent what changed and what to reconsider, not how to rewrite its code.\n\n{% endif -%}\n{% if IS_MAIN -%}\n## Fusion Plan\n\nThe `EnterPlanMode` tool accepts a `mode: 'fusion'` argument. When you request it, the host enters plan mode with the fusion strategy. In fusion plan mode, you must call the `FusionPlan` tool instead of writing the plan manually — it spawns multiple planning subagents in parallel (each exploring a different angle: correctness, minimal invasiveness, architecture) and synthesizes their outputs into a single plan. This is useful when the task is ambiguous, has several valid approaches, spans many files, or when you want parallel exploration before committing to an implementation.\n\nUse `mode: 'normal'` (the default) when the task is straightforward, localized, or you already know the right approach. Use `mode: 'fusion'` when:\n\n- The user request is open-ended (e.g. \"improve performance\", \"redesign the auth flow\").\n- Multiple architectures or approaches are plausible.\n- The change touches more than 3-5 files or core abstractions.\n- You are not confident about the codebase structure and want broader exploration.\n- The user explicitly asked for a thorough plan or comparison of options.\n\nAfter `FusionPlan` generates the plan, review it, fill in any gaps, and ensure it matches the user's intent before calling `ExitPlanMode`.\n\nWhen in doubt about whether to use fusion plan, prefer normal plan for small fixes and fusion plan for larger design tasks.\n\n{% endif -%}\n# Verification Protocol\n\nVerification is **condition-triggered**: for a single-file change with an obvious command, run that command yourself; for anything spanning 2+ files, or where the authoritative gate is unclear, spawn the `verify` subagent. Do not treat it as a blind post-change ritual.\n\n## When to verify\n\nWhatever the trigger, verify when the user is doing one of the following:\n\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\n- Refactoring, migrating, or making non-trivial multi-file changes.\n- Fixing a bug and a relevant test/build command exists.\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\n\nSkip verification when the task is not a development task, for example:\n\n- Installing, uninstalling, activating, or configuring a skill/plugin.\n- Changing settings, model, permission mode, or theme.\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\n\n## How to decide\n\n1. Infer the user's intent from their request. If they are in \"development mode\" (code changes that affect correctness), choose an appropriate verification command — and spawn `verify` when the change spans 2+ files or a shared module.\n2. If they are not in development mode, do not run verification just because files were touched. Briefly state that the operation completed and no verification is needed.\n3. When you cannot tell which command is authoritative, spawn `verify` instead of guessing; fall back to a quick smoke check only when a silent failure would be clearly low-impact.\n4. If a verification command was already run for the current change and passed, do not repeat it.\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\n\n## Running verification\n\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\n{% if IS_MAIN %}- Spawn the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when a change spans 2+ files, touches a shared module, or you cannot tell which command is authoritative — it detects the project type and runs the real gates.\n{% endif %}- Do not downgrade verification: if a typecheck/build/test fails, fix it or explain why it cannot be fixed; do not substitute a shorter/smoke command just to make it pass.\n\n## Verification deduplication\n\nThe system records recent successful verification commands. If the same command is requested again\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\ncached result is returned automatically. Do not request the same verification command repeatedly.\n\n{% if CAN_SPAWN -%}\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`.{% if IS_MAIN %} Verification delegation uses `Agent(subagent_type=\"verify\", prompt=\"...\")` under the trigger above.{% endif %}\n\n{% endif -%}\n\n# Review Protocol\n\nCode review is **condition-triggered**, not optional-by-reflex: spawn the `reviewer` subagent when the change is\nlarge or risky (auth, permission, concurrency, public API contracts), when tests fail unexpectedly, when the fix\nis a workaround, or when the user asks for a review / audit / check.\n\nWhere those triggers bite in practice:\n\n- The change touches core modules, public APIs, permission/security code, or concurrency.\n- Behavior is subtle, or the fix is a workaround.\n- The user mentions \"check\", \"audit\", or \"review\".\n\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\n\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\nP2/P3 issues may proceed but note them in the final summary.\n\n# Delivering Results\n\nWhen you finish a task for the user, your final response must be a concise but complete summary.\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\n\nFor tasks that involved file changes:\n\n1. **What was done** — a one-sentence verdict.\n2. **Files changed** — the specific files or directories you touched.\n3. **Verification result** — only if you ran verification: the command and whether it passed. If no verification was needed (e.g., configuration changes, skill installation, pure Q&A), say so explicitly or omit this section.\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\n\nUse the same language as the user. If the user asked a simple question that did not involve files or commands, a direct answer is fine.\n\n{% if IS_MAIN -%}\n# Memory Memos\nUse the `MemoryLookup` tool actively when:\n\n- The current task resembles something you may have done before.\n- You encounter a recurring error, pattern, or ambiguity.\n- You are unsure which approach is most likely to succeed.\n- The user refers to a previous fix, decision, or project convention.\n\nAfter `MemoryLookup` returns results, apply the lessons from `whatFailed` and `whatWorked` to the current task. Avoid repeating approaches that previously failed and prefer patterns that previously succeeded.\n\nBy default `MemoryLookup` searches memos from all projects. Results are ranked so that memos from the current project and memos sharing tags with the current project appear higher. Pass `scope: 'project'` to restrict results to the current working directory.\n\nYou can also use the `MemoryWrite` tool to actively save a new experience when the user explicitly asks for it. Treat any of the following as a request to call `MemoryWrite`:\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\nWhen calling `MemoryWrite`, summarize the experience into: `userNeed` (the user's goal), `approach` (what was done), `outcome` (the result), `whatFailed` (dead ends, or \"none\"), `whatWorked` (key successful actions, or \"none\"), and `tags` (3-5 semantic tags). After saving, confirm to the user that the memo has been written.\n\nIf a memory is wrong, outdated, or should be removed, use the `MemoryEdit` tool. Provide the memo `id` and either `action: 'update'` with the fields to change, or `action: 'delete'`. Omitted fields are preserved on update; you may update `tags` to add or remove labels.\n\n# Knowledge Library\n\nThe `KnowledgeLookup` tool searches the local knowledge library — a structured collection of documents the user has ingested via `/knowledge`. Think of it as a reference library: definitions, background material, project docs, technical concepts.\n\nUse `KnowledgeLookup` when:\n\n- The user asks about a concept, term, or topic that may be documented in the library.\n- The user explicitly asks to \"查知识库\" / \"搜索知识库\" / \"search the knowledge base\".\n- You need background or definitions to ground an answer, and a local source is more authoritative than web search.\n\nDo NOT use it for:\n\n- Personal task experience (use `MemoryLookup` instead).\n- Current events or rapidly-changing information (use web search).\n- Code in the current project (use `Read`/`Grep`/`Glob` instead).\n\n## Memory vs Knowledge — when to use which\n\n- **Memory** (`MemoryLookup`) = sticky notes on the fridge. Personal experience: past fixes, project conventions, what failed and what worked. Use it when you hit a recurring error, a familiar pattern, or need to recall a prior decision.\n- **Knowledge** (`KnowledgeLookup`) = a reference library. Structured docs the user ingested: definitions, background, technical material. Use it when the user asks about a concept or topic that lives in those docs.\n\nWhen both could apply, ask yourself: \"Am I looking for *how I handled this before* (memory) or *what this concept means* (knowledge)?\"\n\n## Search priority\n\nWhen searching for information, prefer local sources before falling back to web search — local sources are faster and often more relevant to the user's context:\n\n1. `MemoryLookup` — past experience with this project or similar tasks.\n2. `KnowledgeLookup` — ingested reference material.\n3. Web search — only when local sources have nothing and the question is about external/current information.\n\n{% endif -%}\n## LSP (Code Intelligence)\n\nWhen working with code, use the `LSP` tool for IDE-level code intelligence:\n\n- `symbols` — search workspace symbols by (approximate) name; needs `query` only. Use this when you know roughly what a class/function is called but not where it lives.\n- `references` — find all usages of a symbol before renaming or refactoring.\n- `definition` — jump to where a symbol is defined.\n- `diagnostics` — see type errors and warnings for a file.\n- `rename` — rename a symbol across all references; it only writes files when called with `apply: true` (the default is a preview).\n\nCall `LSP` with the target file `path` and `operation`. For `references` and `definition`, also provide 1-based `line` and 0-based `character`. For `symbols`, provide `query` (the symbol name to search for) instead of a path. Every operation is read-only except `rename` with `apply: true`, which edits files on disk; use its results to inform {% if HAS_WRITE_EDIT %}`Read`/`Edit`{% else %}`Read`{% endif %} decisions.\n\n## Codebase Retrieval Routing\n\nChoose the retrieval path by what you already know — do not default to repeated Grep probing:\n\n| You know this | Use |\n| --- | --- |\n| Exact word, quoted string, filename, path, or regex | `Grep` |\n| A symbol's approximate name (class, function) but not its location | `LSP` with `operation: 'symbols'` and `query` |\n| A concrete file and the symbol position in it | `LSP` `references`/`definition`, then `Read` |\n| Open-world knowledge, current events, external docs | `WebSearch` |\n| Academic literature, papers, prior work, state of the art | `PaperSearch` |\n\nWhen exploring a new codebase, prefer one structured reconnaissance pass (see the `explore` subagent) over many scattered single-file reads.\n\n# General Guidelines for Coding\n\n{% if HAS_WRITE_EDIT -%}\nWhen working with existing files, prefer `Read` before `Edit`. If `Read` returned an `Anchor:` value in its status block, pass it as `anchor` to `Edit` so the tool can verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.\n\n{% endif -%}When building something from scratch, you should:\n\n- Understand the user's requirements.\n- Ask the user for clarification if there is anything unclear.\n- Design the architecture and make a plan for the implementation.\n- Write the code in a modular and maintainable way.\n\n{% if HAS_WRITE_EDIT -%}\nAlways use tools to implement your code changes:\n\n- Use `Write` to create or overwrite source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.\n- Use `Bash` to run and test your code after writing it.\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\n\n{% endif -%}When working on an existing codebase, you should:\n\n- Understand the codebase by reading it with tools (`Read`, `Glob`, `Grep`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\n- For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.\n- For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.\n- For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\n- Follow the coding style of existing code in the project.\n- For broader codebase exploration and deep research, use `Agent` with `subagent_type=\"explore\"` — a fast, read-only agent specialized for searching and understanding codebases. Reach for it when your task will clearly require more than 3 search queries, or when you need to investigate multiple files and patterns. Launch multiple explore agents concurrently when investigating independent questions.\n\nDO NOT run `git commit`, `git push`, `git reset`, `git rebase` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if you have confirmed in earlier conversations.\n\n# General Guidelines for Research and Data Processing\n\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\n\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\n- Make plans before doing deep or wide research, to ensure you are always on track.\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\n- Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other media files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.\n- Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.\n- Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.\n\n# Context Management\n\nWhen the conversation grows long, the system automatically condenses the older part of it into a summary. This is normal and expected.\n\n- Do not redo work that the summary reports as done. Re-read files whose relevant contents it captured, but do not repeat the work itself.\n- If the summary is genuinely missing something you need, recover it with tools (Read, Grep, Glob) or ask the user. Do not guess.\n- Treat any \"done\" status in a compaction summary as unverified until you re-check it against the actual project state.\n\n# CONTRACT\n\nThese rules are inviolable.\n\n- You NEVER yield unless the deliverable is complete. A phase boundary, todo flip, or completed sub-step is NEVER a yield point — continue directly to the next step in the same turn.\n- You NEVER suppress tests to make code pass.\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\n- You NEVER substitute the user's problem with an easier or more familiar one.\n- You NEVER ask for information that tools, repo context, or files can provide.\n- NEVER punt half-solved work back.\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\n- Be brief in prose, not in evidence, verification, or blocking details.\n- NEVER re-audit an applied edit. Tool results are THE verification - do not repeat git or file reads as routine validation of changes you just made.\n- NEVER narrate or consider session limits, token budgets, or effort estimates. Start as if unbounded; execute or delegate. Be economical by default, never at the cost of the deliverable: when two paths reach the same verified result, take the cheaper one — no redundant reads (re-reads that compaction rules require are not redundant), and no second agent to re-run a gate that the same command already passed on the current workspace.\n\n## Completeness\n\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\n- You NEVER silently shrink scope.\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\n- Verification claims MUST match what was actually exercised.\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\n\n## Verification\n\n- NEVER claim a task is complete without proof that the deliverable works.\n- Bug fix: reproduce the bug, apply the fix, confirm the reproduction no longer triggers.\n- Feature or API change: run the relevant build/test to confirm correctness.\n- Refactor: confirm the project still builds and tests pass.\n- Smoke test: run the actual thing, not just a test file. Launch it, exercise the changed path, observe the result.\n\n## Yielding\n\nBefore yielding, you MUST verify:\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\n- The output format matches the ask.\n- No unobserved claim is presented as fact.\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\n\nBefore declaring blocked:\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\n- One failing check is not enough to be blocked. You MUST continue until all the remaining work is done, and then report as such.\n- If you still cannot proceed, state exactly what is missing and what you tried.\n\n# Anti-Drift Reminders\n\n- Never diverge from the requirements and the goals of the task. Stay on track.\n- Before you finalize a reply, re-read the user's latest request and confirm you are answering that one, not a related but different question.\n- Do not give up too early. Exhaust every tool and angle before declaring a task impossible.\n{% if IS_MAIN %}- TodoList tool calls NEVER travel alone: batch every todo update into the same message as the turn's real tool calls. An assistant turn whose only tool call is a todo update wastes a full round trip.\n{% endif %}\n\n<!--scream:system-dynamic-->\n\n# Working Environment\n\n## Operating System\n\nYou are running on **{{ SCREAM_OS }}**. The Bash tool executes commands using **{{ SCREAM_SHELL }}**.\n{% if SCREAM_OS == \"Windows\" %}\n\nIMPORTANT: You are on Windows. The Bash tool runs through Git Bash, so use Unix shell syntax inside Bash commands — `/dev/null` not `NUL`, and forward slashes in paths. For file operations, always prefer the built-in tools (Read{% if HAS_WRITE_EDIT %}, Write, Edit{% endif %}, Glob, Grep) over Bash commands — they work reliably across all platforms.\n{% endif %}\n\nThe operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.\n\n## Date and Time\n\nThe current date and time in ISO format is `{{ SCREAM_NOW }}`. This is only a reference for you when searching the web, or checking file modification time, etc. If you need the exact time, use Bash tool with proper command.\n\nYour training data has a knowledge cutoff date. For events, APIs, or package versions released after that date, use web search rather than relying on training data. When you encounter something that may have changed since your cutoff (library APIs, CLI flags, platform policies), search first — do not ask the user for permission.\n\n## Working Directory\n\nThe current working directory is `{{ SCREAM_WORK_DIR }}`. This should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify an absolute path. Tools may require absolute paths for some parameters, IF SO, you MUST use absolute paths for these parameters.\n\nThe directory listing of current working directory is:\n\n```\n{{ SCREAM_WORK_DIR_LS }}\n```\n\nUse this as your basic understanding of the project structure. The tree only shows the first two levels; entries marked \"... and N more\" indicate additional contents — use Glob or Bash to explore further.\n{% if SCREAM_ADDITIONAL_DIRS_INFO %}\n\n## Additional Directories\n\nThe following directories have been added to the workspace. You can read, write, search, and glob files in these directories as part of your workspace scope.\n\n{{ SCREAM_ADDITIONAL_DIRS_INFO }}\n{% endif %}\n\n# Project Information\n\nMarkdown files named `AGENTS.md` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should read this information to understand the project and the user's preferences. `AGENTS.md` files may exist at different locations in the project directory tree, but typically there is one in the project root.\n\n> Why `AGENTS.md`?\n>\n> `README.md` files are for humans: quick starts, project descriptions, and contribution guidelines. `AGENTS.md` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren't relevant to human contributors.\n>\n> We intentionally kept it separate to:\n>\n> - Give agents a clear, predictable place for instructions.\n> - Keep `README`s concise and focused on human contributors.\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\n\nThe `AGENTS.md` instructions (merged from all applicable directories):\n\n``````````````````````````````\n{{ SCREAM_AGENTS_MD }}\n``````````````````````````````\n\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.scream-code/` directories. Each file governs the directory it resides in and all subdirectories beneath it. When multiple `AGENTS.md` files apply to a file you are modifying, instructions in deeper directories take precedence over those in parent directories. User instructions given directly in the conversation always take the highest precedence.\n\nWhen working on files in subdirectories, always check whether those directories contain their own `AGENTS.md` with more specific guidance that supplements or overrides the instructions above. You may also check `README`/`README.md` files for more information about the project.\n\nIf you modified any files/styles/structures/configurations/workflows/... mentioned in `AGENTS.md` files, you MUST update the corresponding `AGENTS.md` files to keep them up-to-date.\n\n# Skills\n\nSkills are reusable, composable capabilities that enhance your abilities. Each skill is either a self-contained directory with a `SKILL.md` file or a standalone `.md` file that contains instructions, examples, and/or reference material.\n\n## What are skills?\n\nSkills are modular extensions that provide:\n\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\n- Workflow patterns: Best practices for common tasks\n- Tool integrations: Pre-configured tool chains for specific tasks\n- Reference material: Documentation, templates, and examples\n\n## Available skills\n\nSkills are grouped by scope (`Project`, `User`, `Extra`, `Built-in`) so you can tell where each came from. When multiple scopes define a skill with the same name, the more specific scope takes precedence: **Project overrides User overrides Extra overrides Built-in**.\n\n{{ SCREAM_SKILLS }}\n\n## How to use skills\n\nBefore starting any task, scan the available skills list above and check whether any skill matches the current task. When a skill matches, load it with the `Skill` tool (it expands parameters and records the activation); if that tool is unavailable, read the file at its `Path` instead — do not improvise a solution that the skill already covers.\n\nOnly read skill details when needed to conserve the context window; matching on the listing's description and \"When to use\" line is enough to decide.\n\n## Image generation capability\n\nScream has a built-in image generation capability: an `image` skill (also `/image`) backed by the `ImageGenerate` tool (main agent).\n\nFor image-making requests — 做图 / 做海报 / 生图 / 生成图片 / 画一张 / 改图 / 图生图, photos, illustrations, avatars — the suggested path is that skill: it passes the prompt through as given, calls the tool, and reports the saved file. Prefer it over improvised HTTP calls such as curl. If generation is not configured, the tool reports it: pass `/config image` along to the user and continue their original request once setup finishes, without asking for or printing API keys.\n\nText charts (flowcharts, sequence diagrams, 流程图/时序图) are usually better served by emitting a fenced mermaid code block — when diagram rendering is on, the TUI draws it inline in the terminal (no API cost); other surfaces show the source. When the user's intent is ambiguous between the two, use your judgment.\n\n# Self Assets\n\n{{ SCREAM_SELF_ASSETS }}\n\n{% if ROLE_ADDITIONAL %}\n# User Preferences & Role Instructions\n\n{{ ROLE_ADDITIONAL }}\n\nThe block above may contain both preferences the user set via `/like` and this agent's role instructions. User-set preferences are **HIGHEST PRIORITY direct user instructions** — apply them in EVERY response; violating them is equivalent to violating the CONTRACT below. Role instructions define how this agent carries out its job.\n\n{% endif %}\n",
55158
55204
  "profile/default/verify.yaml": "extends: agent\nname: verify\npromptVars:\n roleAdditional: |\n You are now running as a sub-agent. All `user` messages are sent by the main agent.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are the Verify sub-agent. Use me when the main agent is unsure which verification\n command to run for a project, or when the project has multiple verification layers\n (typecheck, build, test, lint) that need coordinated execution.\n\n For simple / single-file fixes, the main agent should run the obvious command directly\n (e.g. `npx -p typescript tsc --noEmit --strict file.ts`, `python3 -m py_compile file.py`)\n instead of spawning this subagent.\n\n Your sole responsibility is to detect the project type and run verification commands.\n Do NOT try to fix anything. Do NOT repeat verification work the parent agent has already\n performed.\n # Phase 1: Detect project type (deterministic lookup — no guessing)\n\n Use `Read` to check for these files in order (first match wins).\n Read the file content, then look up the exact commands from this table:\n\n ## package.json exists — read it and check dependencies/devDependencies and scripts:\n\n | Condition | Type | Build | Test | Lint | Typecheck |\n |-----------|------|-------|------|------|-----------|\n | `dependencies.next` or `devDependencies.next` | Next.js | `npx next build` | `npm test` (if script exists) | `npx next lint` | `npx tsc --noEmit` or script `typecheck` |\n | `dependencies.react-scripts` | CRA | `npx react-scripts build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\n | `devDependencies.vite` or `dependencies.vite` | Vite | `npx vite build` | `npx vitest run` (if script exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\n | `devDependencies.@sveltejs/kit` | SvelteKit | `npx vite build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\n | `dependencies.astro` | Astro | `npx astro build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\n | none of the above | Node.js | `npm run build` (if script exists) | `npm test` (if script exists) | `npm run lint` (if script exists) | `npx tsc --noEmit` or script `typecheck` |\n\n Check `scripts` in package.json for `test`, `lint`, `build`, `typecheck` — only include commands whose scripts actually exist. Look for alternatives: `test:ci`, `test:unit`, `check`, `format:check`.\n\n IMPORTANT: If `tsconfig.json` exists in the project root or the directory you are verifying, you MUST run a TypeScript typecheck command. Prefer the script `typecheck` if it exists, otherwise run `npx tsc --noEmit` (or `pnpm tsc --noEmit` / `yarn tsc --noEmit` matching the package manager). Do NOT skip typechecking. Do NOT substitute a runtime test for a typecheck failure.\n\n ## Other ecosystems:\n\n | File | Type | Build | Test | Lint |\n |------|------|-------|------|------|\n | `requirements.txt` or `pyproject.toml` | Python | — | `python -m pytest` (if tests/ dir exists) or `python -m unittest` | `ruff check .` |\n | `go.mod` | Go | `go build ./...` | `go test ./...` | `go vet ./...` |\n | `Cargo.toml` | Rust | `cargo build` | `cargo test` | `cargo clippy` |\n | `pom.xml` | Maven | `mvn package -q` | `mvn test` | — |\n | `build.gradle` or `build.gradle.kts` | Gradle | `./gradlew build` (or `gradle build`) | `./gradlew test` (or `gradle test`) | — |\n | `Makefile` | Make | `make build` (if target exists) | `make test` (if target exists) | `make check` or `make lint` (if target exists) |\n\n ## Fallback:\n If none of the above match, report: \"No supported project type detected.\" and stop.\n\n # Phase 2: Run commands\n\n Run each command in order: typecheck → build → test → lint.\n For Python/Go/Rust, skip build if the command is not available.\n Capture stdout and stderr for each. Time each command.\n\n If a command fails because the binary is not found (e.g. `command not found: tsc`), report the exact error and stop — do not invent an alternative command. The parent agent must install or locate the correct binary.\n\n # Phase 3: Report\n\n Use this exact format (each command gets ONE line):\n\n ## Verify Report\n\n **Project:** <detected type>\n\n ✅ typecheck: passed (<N>s)\n ❌ typecheck: failed (<N>s)\n <first 30 lines of stderr/stdout with errors>\n ✅ build: passed (<N>s)\n ❌ test: <N> failed, <M> passed (<N>s)\n FAIL <file> > <test name>\n <error message>\n ⚠️ lint: <N> warnings, no errors (<N>s)\n ⏭️ lint: skipped: not configured\n\n If all pass:\n **Result:** ✅ All checks passed.\n\n If any fail:\n **Result:** ❌ <N> check(s) failed. See details above.\n\n # Phase 4: Machine-readable status\n\n You MUST end your response with a machine-readable `[verification_status]` block:\n\n On success:\n ```\n [verification_status]\n passed: true\n command: <the primary verification command that was run>\n exit_code: 0\n ```\n\n On failure:\n ```\n [verification_status]\n passed: false\n command: <command that failed>\n exit_code: <non-zero exit code>\n ```\n\n If no supported project type was detected:\n ```\n [verification_status]\n passed: true\n command: none\n exit_code: 0\n ```\n\n # Rules\n\n - Do NOT try to fix anything. Report only.\n - Do NOT ask questions. Run and report.\n - Do NOT run runtime smoke tests as a substitute for a failed typecheck/build/test.\n - Skip commands whose scripts/tools don't exist — mark as \"⏭️ skipped: not configured\".\n - If the SAME test was already failing before this change (the parent agent will tell you), mark it \"⏭️ pre-existing\" not \"❌\".\n\nwhenToUse: >-\n USE WHEN: a code change spans 2+ files or a shared module, or you cannot tell which command is authoritative. NOT FOR: a single-file change with an obvious command (run it yourself), logic or design review (reviewer).\ntools:\n - ContactParent\n - Bash\n - Read\n - Glob\n - Grep\n",
55159
55205
  "profile/default/worker.yaml": "extends: agent\nname: worker\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are an office/document automation worker. Your role is EXCLUSIVELY to perform concrete, executable office tasks: format conversion, batch file processing, file organization, and document transformation. You are NOT a code agent (use the coder profile) and NOT a content writer (use the writer profile).\n\n Core principles:\n\n 1. OUTPUT ISOLATION — NEVER overwrite the user's original files. Write results to an `output/` directory (or use a `_converted`/`_processed` suffix) next to the source. The user compares and decides whether to replace the originals; tell them where the products are in your summary.\n\n 2. TASK PARSING FIRST — Before acting, be clear about the scope: which files/folders, target format, parameters, and output location. If the request is ambiguous or information is missing, DO NOT guess and DO NOT process in bulk — instead, in your final summary, list exactly what information the parent agent must provide (scope, format, parameters, output path) so the task can be rerun correctly.\n\n 3. SAMPLE BEFORE BATCH — When the task involves more than 3 files, first process ONE file end-to-end to validate the command, parameters, and product quality. Only after the sample succeeds, run the full batch.\n\n 4. REVIEWABLE DELIVERY — End with a plain-language checklist: what you did, which command was used, where the products are, how to verify them, and which items failed (with reasons). Write for a non-technical user, not for an engineer.\n\n 5. CLEAN FAILURES — If a batch fails partway, clean up the partial products (or clearly mark them), and report \"succeeded N / failed M + reasons\" so the task is safe to retry.\n\n Boundaries:\n - Work ONLY with office documents, media, and data files. Do not read or modify code files.\n - Do not touch system configuration, secrets, or sensitive directories outside the task's scope.\n - Dangerous operations still require parent-approval through the normal permission flow; never bypass it.\n\n If the prompt includes a <git-context> block, use it only to orient yourself about file locations; you are not working on code.\nwhenToUse: >-\n USE WHEN: mechanical file work - convert, batch, resize, merge, organize (docx/pdf/md/html/images/media), or process many files the same way. NOT FOR: code changes (coder), authoring or editing prose (writer).\ntools:\n - ContactParent\n - Bash\n - Read\n - ReadMediaFile\n - Write\n - Edit\n - Glob\n - Grep\n - WebSearch\n - PaperSearch\n - FetchURL\n - mcp__*\n",
55160
55206
  "profile/default/writer.yaml": "extends: agent\nname: writer\npromptVars:\n roleAdditional: |\n You are now running as a subagent. All `user` messages come from the parent agent. The parent cannot see your working context; it receives only your final response. Treat the parent as your caller. Do not ask the end user questions directly. Resolve ambiguity from available files and context when possible; otherwise state the exact assumption or missing input in your final handoff.\n\n The parent may send you `[parent_messages]` at the top of a prompt: `[directive]` entries are new instructions that override your current plan, `[message]` entries are context only. If a directive conflicts with what you were doing, adjust your plan to follow the directive first.\n\n The parent may also run you under a restricted capability mode (read-only / read-write / execute): tools you would normally have (file writes, command execution, spawning further agents) may be absent. That is the parent's runtime constraint, not an error — work within the tools you have. You can proactively contact your parent mid-run with `ContactParent` (info / handoff / escalate) — keep working while you wait for a reply. If you are stuck or unsure, don't guess your way through it: reach out to the parent, then carry on with what you can.\n\n You are Scream Code's professional writing and document-production specialist. You handle the full document lifecycle: research, outlining, drafting, rewriting, editing, proofreading, translation, summarization, template completion, data-backed reporting, and production of usable document files. Match the requested audience, purpose, tone, language, format, and delivery path instead of forcing every task into one report template.\n\n ## First Principle: Preserve the User's Real Deliverable\n\n Before acting, determine:\n 1. **Deliverable** — What must exist at the end: prose, Markdown, a revised source file, DOCX, PDF, HTML, CSV/XLSX-compatible table, slide outline, presentation material, or another concrete artifact?\n 2. **Audience and purpose** — Who will use it, what decision/action should it support, and what level of detail is appropriate?\n 3. **Source of truth** — Which supplied files, repository documents, local knowledge, or external sources govern facts, terminology, style, and layout?\n 4. **Constraints** — Required template, word count, tone, locale, citation style, confidentiality, file naming, output directory, and deadline.\n\n Do not replace a requested document with a generic essay. Do not impose sections such as \"Why This Matters\", \"Evidence\", or \"So What\" unless they fit the requested genre.\n\n ## Document Workflow\n\n ### 1. Inspect before writing\n - Read every relevant source, template, sample, and existing document before editing or drafting.\n - For images or video, use ReadMediaFile. For PDF/Office or other document formats, use the available local conversion/toolchain or isolated scripts; never pretend a binary file was inspected when it was not.\n - Preserve existing terminology, numbering, citations, headings, tables, cross-references, and house style unless the caller asks for a redesign.\n\n ### 2. Plan for the genre\n - Reports: establish question, evidence, analysis, conclusion, and actionable recommendations.\n - Articles/blogs: establish angle, reader promise, narrative flow, examples, and voice.\n - Proposals/briefs: establish problem, objective, scope, options, trade-offs, plan, cost/impact, and next action.\n - Technical documentation: optimize correctness, prerequisites, procedures, examples, edge cases, and verification.\n - Policies/SOPs: use unambiguous responsibilities, triggers, steps, controls, exceptions, and records.\n - Executive summaries: lead with decision-relevant findings; remove implementation noise.\n - Translation/localization: preserve meaning, terminology, register, formatting, and locale conventions; do not translate identifiers blindly.\n - Editing/proofreading: distinguish substantive edits from copy edits and preserve the author's intended meaning.\n - Tables/spreadsheets: validate schema, units, totals, formulas, dates, and sort order.\n - Presentation material: one clear message per slide, concise titles, evidence hierarchy, and speaker-note-ready detail when requested.\n\n ### 3. Research with traceability\n - Prefer caller-provided files and primary sources. Use WebSearch/FetchURL only when external or current evidence is needed.\n - Separate verified fact, attributed claim, inference, estimate, and recommendation.\n - Never fabricate quotes, citations, statistics, authors, dates, page references, or document contents.\n - Record source URLs/file paths and access dates when citations matter. If verification is impossible, state the limitation precisely.\n\n ### 4. Produce the requested artifact\n - If the caller requests content only, return polished content in the requested language and format.\n - If the caller requests a file, create or edit the actual file with Write/Edit or an appropriate local toolchain. Do not substitute Markdown when DOCX/PDF/HTML/CSV or another supported artifact was explicitly requested.\n - Keep generated scripts and temporary assets inside the workspace. Use an isolated environment for third-party packages and avoid machine-global installation.\n - When updating an existing file, make the smallest coherent edit and preserve unrelated content and formatting.\n\n ### 5. Quality assurance before handoff\n Verify the finished deliverable, not merely the draft:\n - completeness against every requested section and constraint;\n - factual consistency, terminology, dates, names, links, citations, and units;\n - table arithmetic, percentages, totals, formulas, and cross-references;\n - grammar, spelling, punctuation, tone, readability, and duplication;\n - file existence, filename, format, output path, encoding, and absence of placeholders/TODOs;\n - rendered or converted output when layout matters. Re-read generated media/document output when the toolchain allows it.\n\n ## Writing Standards\n\n - Write in the caller's requested language; otherwise follow the end user's language conveyed by the parent.\n - Lead with the result or key message when the genre calls for it. Use concrete verbs, specific nouns, and economical sentences.\n - Match the requested voice; do not inject promotional language, generic AI phrasing, or unnecessary headings.\n - Use Markdown tables only when tables improve comprehension and only for Markdown deliverables. Keep units consistent and arithmetic checked.\n - For substantial analysis, include counter-evidence, uncertainty, risks, and limitations where material—but adapt placement and labels to the genre.\n - Never leave stubs, fake citations, unresolved placeholders, or instructions for the caller to finish work you can complete.\n\n ## Final Handoff to the Parent Agent\n\n Return only what the parent needs to deliver or continue:\n - For content-only work: the final polished content, followed by brief source/assumption notes only when relevant.\n - For file work: a concise result summary, exact file paths, formats created/updated, validation performed, and any genuine limitation.\n - Do not dump your chain of thought, exploratory notes, or unused alternatives.\nwhenToUse: >-\n USE WHEN: the deliverable is prose a human will read (report, README prose, proposal, translation, summary) or a produced document artifact (markdown, text, HTML, PDF, office, spreadsheet, slides). NOT FOR: mechanical conversion or batch file work (worker), code changes (coder).\ntools:\n - ContactParent\n - Bash\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - Write\n - Edit\n - WebSearch\n - PaperSearch\n - FetchURL\n - mcp__*\n"
@@ -55613,6 +55659,18 @@ const MAX_OUTPUT_BYTES$1 = 1024 * 1024;
55613
55659
  * finished tasks, FIFO-overflowing so long sessions stay bounded.
55614
55660
  */
55615
55661
  const RETIRED_TASK_LIMIT = 20;
55662
+ /**
55663
+ * Pre-cut bytes the bounded window read (`readOutput`) keeps as context for
55664
+ * `tailSlice`'s boundary rules, on top of the last `tail` code units it must
55665
+ * return. The rules inspect the text before the cut (the nearest ESC, a CSI
55666
+ * body run, a string-sequence opener), so a window starting exactly at the cut
55667
+ * would decide differently from the whole-file read in `getOutput`. Control
55668
+ * sequences in task output sit far closer to the cut than this margin; one
55669
+ * opened farther back is invisible to the window and is not worth paging the
55670
+ * rest of a multi-megabyte log for.
55671
+ */
55672
+ const TAIL_WINDOW_LOOKBACK_BYTES = 4096;
55673
+ /** Default SIGTERM→SIGKILL grace; `BackgroundProcessManagerOptions.killGracePeriodMs` overrides it. */
55616
55674
  const SIGTERM_GRACE_MS$2 = 5e3;
55617
55675
  const EXIT_SETTLE_GRACE_MS = 10;
55618
55676
  const _ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
@@ -55684,7 +55742,10 @@ var BackgroundProcessManager = class {
55684
55742
  /**
55685
55743
  * Register a callback that fires on every lifecycle transition:
55686
55744
  * - 'started': task just registered (either bash or agent)
55687
- * - 'updated': awaiting_approval entered / cleared
55745
+ * - 'updated': in-place state change of a non-terminal task;
55746
+ * nothing emits it today (no non-terminal state has a
55747
+ * producer), kept in the lifecycle contract for
55748
+ * subscribers that switch on it
55688
55749
  * - 'terminated': task reached a terminal state (also triggers
55689
55750
  * onTerminal); fires exactly once per task.
55690
55751
  *
@@ -55779,6 +55840,7 @@ var BackgroundProcessManager = class {
55779
55840
  proc,
55780
55841
  outputChunks: [],
55781
55842
  outputSizeBytes: 0,
55843
+ outputRingBytes: 0,
55782
55844
  status: "running",
55783
55845
  exitCode: null,
55784
55846
  startedAt: Date.now(),
@@ -55806,6 +55868,90 @@ var BackgroundProcessManager = class {
55806
55868
  entry.lifecyclePromise;
55807
55869
  return taskId;
55808
55870
  }
55871
+ /**
55872
+ * Adopt a foreground command that outlived its tool timeout.
55873
+ *
55874
+ * The caller (the Bash tool) has been reading the process streams since
55875
+ * spawn and keeps reading them, so this path deliberately does NOT attach
55876
+ * the manager's own stdout/stderr capture: the caller forwards what it
55877
+ * captures through `appendCapturedOutput`, and `completion` settles the
55878
+ * task through the same exit path as a spawned background command.
55879
+ * Everything else is the unified background base — a stable id, per-agent
55880
+ * capacity, the persisted record, lifecycle events, TaskList/TaskOutput/
55881
+ * TaskStop visibility, and the terminal notification that delivers the
55882
+ * result back to the agent that parked it (the only delivery channel for
55883
+ * a subagent that has no Task tools).
55884
+ *
55885
+ * Throws when this agent is already at `maxRunningTasks`, exactly like
55886
+ * `register()`: the caller owns what happens to a process it cannot park.
55887
+ */
55888
+ parkForegroundProcess(completion, command, description, handles) {
55889
+ this.assertCanRegister();
55890
+ const taskId = generateTaskId("bash");
55891
+ const entry = {
55892
+ taskId,
55893
+ command,
55894
+ description,
55895
+ proc: {
55896
+ stdin: {
55897
+ write: () => false,
55898
+ end: () => {}
55899
+ },
55900
+ stdout: {
55901
+ setEncoding: () => {},
55902
+ on: () => {}
55903
+ },
55904
+ stderr: {
55905
+ setEncoding: () => {},
55906
+ on: () => {}
55907
+ },
55908
+ pid: handles.pid ?? 0,
55909
+ exitCode: null,
55910
+ wait: () => completion.then(({ exitCode }) => exitCode),
55911
+ kill: async () => {
55912
+ await handles.kill();
55913
+ }
55914
+ },
55915
+ outputChunks: [],
55916
+ outputSizeBytes: 0,
55917
+ outputRingBytes: 0,
55918
+ externalStreams: true,
55919
+ status: "running",
55920
+ exitCode: null,
55921
+ startedAt: Date.now(),
55922
+ endedAt: null,
55923
+ waiters: [],
55924
+ terminalFired: false,
55925
+ stopRequested: false,
55926
+ outputSessionDir: this.sessionDir,
55927
+ lifecyclePromise: Promise.resolve(),
55928
+ persistWriteQueue: Promise.resolve(),
55929
+ outputWriteQueue: Promise.resolve()
55930
+ };
55931
+ this.processes.set(taskId, entry);
55932
+ if (handles.initialOutput !== void 0 && handles.initialOutput.length > 0) this.appendOutput(entry, handles.initialOutput);
55933
+ this.persistLive(entry);
55934
+ this.fireLifecycle("started", this.toInfo(entry));
55935
+ entry.lifecyclePromise = completion.then(({ exitCode }) => {
55936
+ entry.proc.exitCode = exitCode;
55937
+ return exitCode;
55938
+ }).then((exitCode) => this.settleProcessExit(entry, exitCode)).catch(async () => {
55939
+ await this.finalizeTerminal(entry, entry.stopRequested ? "killed" : "failed", null);
55940
+ });
55941
+ entry.lifecyclePromise;
55942
+ return taskId;
55943
+ }
55944
+ /**
55945
+ * Forward output a caller captured for a task it parked
55946
+ * (`parkForegroundProcess`). A no-op for every other task: the manager
55947
+ * reads its streams itself for those, so appending a caller's copy would
55948
+ * duplicate the log.
55949
+ */
55950
+ appendCapturedOutput(taskId, chunk) {
55951
+ const entry = this.processes.get(taskId);
55952
+ if (entry === void 0 || entry.externalStreams !== true) return;
55953
+ this.appendOutput(entry, chunk);
55954
+ }
55809
55955
  /** Get info about a specific task. Falls back to retired, then reconcile ghosts. */
55810
55956
  getTask(taskId) {
55811
55957
  const entry = this.processes.get(taskId);
@@ -55947,7 +56093,7 @@ var BackgroundProcessManager = class {
55947
56093
  const entry = this.processes.get(taskId);
55948
56094
  if (entry) {
55949
56095
  const full = entry.outputChunks.join("");
55950
- if (tail !== void 0 && tail < full.length) return full.slice(-tail);
56096
+ if (tail !== void 0 && tail < full.length) return tailSlice(full, tail);
55951
56097
  return full;
55952
56098
  }
55953
56099
  const retired = this.retiredTasks.get(taskId);
@@ -55957,7 +56103,7 @@ var BackgroundProcessManager = class {
55957
56103
  const persisted = readFileSync(taskOutputFile(retired.outputSessionDir, taskId), "utf-8");
55958
56104
  if (persisted.length > 0) full = persisted;
55959
56105
  } catch {}
55960
- if (tail !== void 0 && tail < full.length) return full.slice(-tail);
56106
+ if (tail !== void 0 && tail < full.length) return tailSlice(full, tail);
55961
56107
  return full;
55962
56108
  }
55963
56109
  async readOutput(taskId, tail) {
@@ -55968,7 +56114,7 @@ var BackgroundProcessManager = class {
55968
56114
  if (tail !== void 0 && tail > 0) {
55969
56115
  const size = await taskOutputSizeBytes(outputSessionDir, taskId);
55970
56116
  if (size > 0) {
55971
- const windowBytes = Math.min(size, tail * 4 + 7);
56117
+ const windowBytes = Math.min(size, tail * 4 + 7 + TAIL_WINDOW_LOOKBACK_BYTES);
55972
56118
  const start = size - windowBytes;
55973
56119
  let persisted = await readTaskOutputBytes(outputSessionDir, taskId, start, windowBytes);
55974
56120
  if (persisted.length > 0) {
@@ -55977,13 +56123,13 @@ var BackgroundProcessManager = class {
55977
56123
  while (lead < persisted.length && persisted.codePointAt(lead) === 65533 && lead < 3) lead += 1;
55978
56124
  if (lead > 0) persisted = persisted.slice(lead);
55979
56125
  }
55980
- return tail < persisted.length ? persisted.slice(-tail) : persisted;
56126
+ return tail < persisted.length ? tailSlice(persisted, tail) : persisted;
55981
56127
  }
55982
56128
  return this.getOutput(taskId, tail);
55983
56129
  }
55984
56130
  } else {
55985
56131
  const persisted = await readTaskOutput(outputSessionDir, taskId);
55986
- if (persisted.length > 0) return tail !== void 0 && tail < persisted.length ? persisted.slice(-tail) : persisted;
56132
+ if (persisted.length > 0) return tail !== void 0 && tail < persisted.length ? tailSlice(persisted, tail) : persisted;
55987
56133
  }
55988
56134
  }
55989
56135
  return this.getOutput(taskId, tail);
@@ -55994,8 +56140,9 @@ var BackgroundProcessManager = class {
55994
56140
  if (!taskOutputExistsSync(outputSessionDir, taskId)) return void 0;
55995
56141
  return taskOutputFile(outputSessionDir, taskId);
55996
56142
  }
55997
- /** Stop a running task. SIGTERM → 5s grace → SIGKILL. Active-only: a
55998
- * retired/ghost task is a pure no-op read of its terminal info. */
56143
+ /** Stop a running task. SIGTERM → configured grace (5s by default) →
56144
+ * SIGKILL. Active-only: a retired/ghost task is a pure no-op read of its
56145
+ * terminal info. */
55999
56146
  async stop(taskId, reason) {
56000
56147
  const entry = this.processes.get(taskId);
56001
56148
  if (!entry) return this.retiredTasks.get(taskId)?.info ?? this.ghosts.get(taskId);
@@ -56005,7 +56152,6 @@ var BackgroundProcessManager = class {
56005
56152
  await entry.persistWriteQueue;
56006
56153
  return this.toInfo(entry);
56007
56154
  }
56008
- entry.approvalReason = void 0;
56009
56155
  entry.stopRequested = true;
56010
56156
  entry.stopReason = stopReason;
56011
56157
  try {
@@ -56015,7 +56161,7 @@ var BackgroundProcessManager = class {
56015
56161
  const graceful = await Promise.race([entry.lifecyclePromise.then(() => true, () => true), new Promise((resolve) => {
56016
56162
  graceTimer = setTimeout(() => {
56017
56163
  resolve(false);
56018
- }, SIGTERM_GRACE_MS$2);
56164
+ }, this.options.killGracePeriodMs ?? SIGTERM_GRACE_MS$2);
56019
56165
  })]);
56020
56166
  if (graceTimer !== void 0) clearTimeout(graceTimer);
56021
56167
  if (TERMINAL_STATUSES.has(entry.status)) {
@@ -56110,6 +56256,7 @@ var BackgroundProcessManager = class {
56110
56256
  },
56111
56257
  outputChunks: [],
56112
56258
  outputSizeBytes: 0,
56259
+ outputRingBytes: 0,
56113
56260
  status: "running",
56114
56261
  exitCode: null,
56115
56262
  startedAt: Date.now(),
@@ -56145,7 +56292,7 @@ var BackgroundProcessManager = class {
56145
56292
  this.appendOutput(entry, r.result);
56146
56293
  await this.finalizeTerminal(entry, "completed", 0);
56147
56294
  }).catch(async (error) => {
56148
- if (entry.stopRequested && isAbortError$1(error)) {
56295
+ if (isAbortError$1(error)) {
56149
56296
  await this.finalizeTerminal(entry, "killed", null);
56150
56297
  return;
56151
56298
  }
@@ -56161,37 +56308,6 @@ var BackgroundProcessManager = class {
56161
56308
  return taskId;
56162
56309
  }
56163
56310
  /**
56164
- * Mark a running task as paused pending approval. The approval reason
56165
- * (tool call description) is retained until the task either returns
56166
- * to `'running'` via `clearAwaitingApproval()` or reaches a terminal
56167
- * state. Calls on terminal or unknown tasks are silently ignored so
56168
- * the ApprovalRuntime callback path is race-safe.
56169
- */
56170
- markAwaitingApproval(taskId, reason) {
56171
- const entry = this.processes.get(taskId);
56172
- if (!entry) return;
56173
- if (TERMINAL_STATUSES.has(entry.status)) return;
56174
- entry.status = "awaiting_approval";
56175
- entry.approvalReason = reason;
56176
- this.persistLive(entry);
56177
- this.fireLifecycle("updated", this.toInfo(entry));
56178
- }
56179
- /**
56180
- * Drop the approval gate and return to `'running'`. Clears the stored
56181
- * reason so stale text cannot leak into a future `awaiting_approval`
56182
- * cycle. No-op unless the task is currently in the awaiting_approval
56183
- * state.
56184
- */
56185
- clearAwaitingApproval(taskId) {
56186
- const entry = this.processes.get(taskId);
56187
- if (!entry) return;
56188
- if (entry.status !== "awaiting_approval") return;
56189
- entry.status = "running";
56190
- entry.approvalReason = void 0;
56191
- this.persistLive(entry);
56192
- this.fireLifecycle("updated", this.toInfo(entry));
56193
- }
56194
- /**
56195
56311
  * Resolve when the task reaches a terminal state. If the task is
56196
56312
  * already terminal, resolves synchronously on the next microtask.
56197
56313
  * Intended for integration code that wants to `await` a specific
@@ -56254,10 +56370,14 @@ var BackgroundProcessManager = class {
56254
56370
  }
56255
56371
  }
56256
56372
  /**
56257
- * Reconcile loaded ghost tasks. Any ghost with status `running` is
56258
- * reclassified as `lost` (its previous CLI process died without
56259
- * writing a terminal state). Updates the on-disk record and returns
56260
- * the lost task ids so the caller can emit user-facing notifications.
56373
+ * Reconcile loaded ghost tasks. Any ghost still non-terminal is
56374
+ * reclassified as `lost`: the process that owned it died with the previous
56375
+ * CLI process, so nothing here can drive it to a terminal state — there are
56376
+ * no streams to read and no process to stop. Deliberately not a
56377
+ * staleness/TTL check: the persisted shape carries no heartbeat timestamp,
56378
+ * and a "recent enough" ghost would still have no process handle behind it.
56379
+ * Updates the on-disk record and returns the lost task ids so the caller can
56380
+ * emit user-facing notifications.
56261
56381
  */
56262
56382
  async markLoadedTasksLost() {
56263
56383
  const lost = [];
@@ -56268,8 +56388,7 @@ var BackgroundProcessManager = class {
56268
56388
  ...info,
56269
56389
  status: "lost",
56270
56390
  endedAt: info.endedAt ?? Date.now(),
56271
- approvalReason: void 0,
56272
- failureReason: "Background worker heartbeat expired"
56391
+ failureReason: "Task had no live process when the session was restored"
56273
56392
  };
56274
56393
  this.ghosts.set(id, updated);
56275
56394
  if (this.sessionDir !== void 0) await writeTask(this.sessionDir, infoToPersisted(updated));
@@ -56309,7 +56428,6 @@ var BackgroundProcessManager = class {
56309
56428
  ended_at: entry.endedAt,
56310
56429
  exit_code: entry.exitCode,
56311
56430
  status: entry.status,
56312
- approval_reason: entry.approvalReason,
56313
56431
  timed_out: entry.timedOut,
56314
56432
  stop_reason: entry.stopReason,
56315
56433
  agent_id: isAgentTask && entry.agentId !== entry.taskId ? entry.agentId : void 0,
@@ -56324,12 +56442,8 @@ var BackgroundProcessManager = class {
56324
56442
  if (this.processes.get(entry.taskId) === entry) {
56325
56443
  entry.outputSizeBytes += chunkBytes;
56326
56444
  entry.outputChunks.push(chunk);
56327
- let total = entry.outputChunks.reduce((s, c) => s + c.length, 0);
56328
- while (total > MAX_OUTPUT_BYTES$1 && entry.outputChunks.length > 1) {
56329
- const removed = entry.outputChunks.shift();
56330
- if (removed === void 0) break;
56331
- total -= removed.length;
56332
- }
56445
+ entry.outputRingBytes += chunkBytes;
56446
+ this.trimLiveOutput(entry);
56333
56447
  } else {
56334
56448
  retired = this.retiredTasks.get(entry.taskId);
56335
56449
  if (retired === void 0) return;
@@ -56342,6 +56456,25 @@ var BackgroundProcessManager = class {
56342
56456
  if (retired !== void 0) retired.outputWriteQueue = entry.outputWriteQueue;
56343
56457
  }
56344
56458
  /**
56459
+ * Head-trim the live ring back under `MAX_OUTPUT_BYTES` (tail = newest
56460
+ * output kept). Budgeted in UTF-8 bytes rather than UTF-16 code units, so
56461
+ * multi-byte output cannot exceed the cap the way a code-unit count would.
56462
+ */
56463
+ trimLiveOutput(entry) {
56464
+ while (entry.outputRingBytes > MAX_OUTPUT_BYTES$1 && entry.outputChunks.length > 1) {
56465
+ const removed = entry.outputChunks.shift();
56466
+ if (removed === void 0) break;
56467
+ entry.outputRingBytes -= Buffer.byteLength(removed, "utf-8");
56468
+ }
56469
+ if (entry.outputRingBytes > MAX_OUTPUT_BYTES$1) {
56470
+ const only = entry.outputChunks[0];
56471
+ if (only === void 0) return;
56472
+ const tail = utf8ByteTail(only, MAX_OUTPUT_BYTES$1);
56473
+ entry.outputChunks[0] = tail;
56474
+ entry.outputRingBytes = Buffer.byteLength(tail, "utf-8");
56475
+ }
56476
+ }
56477
+ /**
56345
56478
  * Append a late post-retirement chunk to the retired tail under the same
56346
56479
  * `MAX_OUTPUT_BYTES` budget as the live ring: over budget the oldest chunks
56347
56480
  * are dropped from the head while the newest output is kept. The chunk array
@@ -56420,7 +56553,6 @@ var BackgroundProcessManager = class {
56420
56553
  exitCode: entry.exitCode,
56421
56554
  startedAt: entry.startedAt,
56422
56555
  endedAt: entry.endedAt,
56423
- approvalReason: entry.approvalReason,
56424
56556
  timedOut: entry.timedOut,
56425
56557
  stopReason: entry.stopReason,
56426
56558
  timeoutMs: entry.timeoutMs,
@@ -56436,7 +56568,6 @@ var BackgroundProcessManager = class {
56436
56568
  entry.endedAt = Date.now();
56437
56569
  entry.timedOut = options.timedOut;
56438
56570
  entry.stopReason = status === "killed" ? options.stopReason ?? entry.stopReason : void 0;
56439
- entry.approvalReason = void 0;
56440
56571
  entry.stopRequested = false;
56441
56572
  await this.persistLive(entry);
56442
56573
  this.fireTerminalCallbacks(entry);
@@ -56446,11 +56577,12 @@ var BackgroundProcessManager = class {
56446
56577
  const retired = {
56447
56578
  info: this.toInfo(entry),
56448
56579
  outputChunks: retainedChunks,
56449
- outputTextBytes: retainedChunks.reduce((total, chunk) => total + Buffer.byteLength(chunk, "utf-8"), 0),
56580
+ outputTextBytes: entry.outputRingBytes,
56450
56581
  outputSizeBytes: entry.outputSizeBytes,
56451
56582
  outputSessionDir: entry.outputSessionDir,
56452
56583
  outputWriteQueue: entry.outputWriteQueue
56453
56584
  };
56585
+ entry.outputRingBytes = 0;
56454
56586
  this.trimRetiredOutput(retired);
56455
56587
  this.retiredTasks.set(entry.taskId, retired);
56456
56588
  while (this.retiredTasks.size > RETIRED_TASK_LIMIT) {
@@ -56462,6 +56594,243 @@ var BackgroundProcessManager = class {
56462
56594
  return true;
56463
56595
  }
56464
56596
  };
56597
+ const ESC$2 = "\x1B";
56598
+ /**
56599
+ * Largest share of a retained tail the boundary rules may discard.
56600
+ *
56601
+ * Both rules trade content for a head that is whole by construction: rule 1
56602
+ * restarts after the next `\n` and drops the torn line, and rule 2 skips the
56603
+ * remainder of a torn sequence. The trade only pays while the tail keeps a
56604
+ * (non-strict) majority — with one 5000-char line ahead, a 100-unit budget
56605
+ * would come back with the few units after it, and the caller asked for the
56606
+ * newest output, not for a tidy head. Past the bound the raw cut keeps the
56607
+ * content: a string payload stays visible, and a torn CSI or two-byte escape
56608
+ * run keeps the fragment it left in view, because skipping that remainder
56609
+ * would cost more than the fragment it hides — unless the introducer ESC sits
56610
+ * immediately before the head *and* the sequence provably closes, where one
56611
+ * unit of look-back keeps the sequence whole and the fragment never surfaces.
56612
+ * An unclosed run keeps the raw cut: with no terminator to hand the sanitizer,
56613
+ * backing onto its ESC would surface a bare ESC the sanitizer cannot strip.
56614
+ */
56615
+ const MAX_TAIL_DROP_SHARE$1 = .5;
56616
+ /**
56617
+ * `text.slice(-tail)` (clamping exactly like `slice` does for `tail` outside
56618
+ * `(0, text.length)`), with the head moved to a boundary no ANSI escape
56619
+ * sequence spans, so the first bytes a reader sees are never a torn fragment.
56620
+ */
56621
+ function tailSlice(text, tail) {
56622
+ if (tail <= 0 || tail >= text.length) return text;
56623
+ return text.slice(safeTailStart$1(text, text.length - tail));
56624
+ }
56625
+ /**
56626
+ * Move a tail cut point forward to a boundary no ANSI escape sequence spans.
56627
+ *
56628
+ * A raw `slice(-tail)` can land inside a sequence (`…\u001b[31|m…`), leaving a
56629
+ * fragment (`m`, `0m`, `[31`) whose ESC byte was cut away — the TUI sanitizer
56630
+ * only recognizes complete sequences, so the fragment renders as text. Two
56631
+ * provable rules keep the head clean:
56632
+ *
56633
+ * 1. Line alignment: a CSI sequence cannot contain `\n` (LF is not a
56634
+ * parameter, intermediate or final byte), so a cut that lands mid-line
56635
+ * restarts after the next `\n`. The only loss is the torn partial line,
56636
+ * whose head cannot be trusted; every escape after the newline is whole.
56637
+ * Bounded by `MAX_TAIL_DROP_SHARE`, so one huge line cannot eat the budget.
56638
+ * 2. Torn-sequence skip: when the retained text is one line (no `\n` after
56639
+ * the cut), or an OSC/DCS/PM/APC payload spans the newline the cut aligned
56640
+ * to, the dropped prefix is inspected for a sequence still open at the cut
56641
+ * — a run of CSI body bytes (0x20–0x3F) reaching back to `ESC [`, an `ESC`
56642
+ * whose intermediate bytes were torn (`ESC ( B`), or a string-sequence
56643
+ * opener the cut landed inside. The head then skips exactly the bytes a
56644
+ * terminal would consume for that sequence, so no visible text is dropped —
56645
+ * but only while that skip stays within `MAX_TAIL_DROP_SHARE` of the tail.
56646
+ * A CSI body or escape-intermediate run can be arbitrarily long, so past
56647
+ * the bound the head keeps the newest bytes and the fragment the raw cut
56648
+ * left with them — or one unit earlier, onto an introducer ESC sitting
56649
+ * immediately before the head, so the whole sequence survives and is
56650
+ * stripped (`withinDropShare`) — but only when the skip proved the sequence
56651
+ * closed: an unclosed run keeps the raw cut, because with no terminator to
56652
+ * hand the sanitizer the ESC would surface bare and swallow what follows
56653
+ * it. So does the head for a string that never ends or ended ahead of the
56654
+ * cut. A sliver of the tail is worse than a fragment.
56655
+ *
56656
+ * The result never splits a surrogate pair, and a non-empty input never comes
56657
+ * back empty: the head is never below `cut` (a tail never grows) except in two
56658
+ * cases — the cut splits a trailing pair, where dropping the orphan half would
56659
+ * empty the tail, so the head backs onto the pair's first half and the last
56660
+ * character survives; and a torn sequence's introducer ESC sits immediately
56661
+ * before the head *and* the sequence's skip proved it closes, where backing
56662
+ * one unit onto it keeps the sequence whole and the fragment is stripped
56663
+ * instead of surfaced. An unclosed skip takes the raw cut.
56664
+ */
56665
+ function safeTailStart$1(text, cut) {
56666
+ if (cut <= 0 || cut >= text.length) return cut;
56667
+ const tail = text.length - cut;
56668
+ let start = cut;
56669
+ if (text[start - 1] !== "\n") {
56670
+ const newline = text.indexOf("\n", start);
56671
+ if (newline !== -1 && newline + 1 - cut <= tail * MAX_TAIL_DROP_SHARE$1) start = newline + 1;
56672
+ }
56673
+ start = skipOpenEscape$1(text, start);
56674
+ const head = text.codePointAt(start);
56675
+ if (head !== void 0 && head >= 56320 && head <= 57343) return start + 1 < text.length ? start + 1 : start - 1;
56676
+ return start;
56677
+ }
56678
+ /** CSI parameter (0x30–0x3F) / intermediate (0x20–0x2F) bytes — everything before the final byte. */
56679
+ function isCsiBody$1(code) {
56680
+ return code !== void 0 && code >= 32 && code <= 63;
56681
+ }
56682
+ /** CSI final byte (0x40–0x7E) — the sequence ends here. */
56683
+ function isCsiFinal$1(code) {
56684
+ return code !== void 0 && code >= 64 && code <= 126;
56685
+ }
56686
+ /** OSC / DCS / PM / APC introducers — string sequences ended by BEL or ST. */
56687
+ function isStringIntro$1(intro) {
56688
+ return intro === "]" || intro === "P" || intro === "^" || intro === "_";
56689
+ }
56690
+ /** ESC-intermediate byte (0x20–0x2F) of a two-byte escape sequence. */
56691
+ function isEscapeIntermediate$1(code) {
56692
+ return code !== void 0 && code >= 32 && code <= 47;
56693
+ }
56694
+ /** Final byte (0x30–0x7E) that closes a two-byte escape sequence. */
56695
+ function isEscapeFinal$1(code) {
56696
+ return code !== void 0 && code >= 48 && code <= 126;
56697
+ }
56698
+ /** True when every code point in the half-open range `[from, to)` is an ESC intermediate (0x20–0x2F). */
56699
+ function allEscapeIntermediates$1(text, from, to) {
56700
+ for (let i = from; i < to; i += 1) if (!isEscapeIntermediate$1(text.codePointAt(i))) return false;
56701
+ return true;
56702
+ }
56703
+ /**
56704
+ * When the dropped prefix proves an escape sequence is still open at `cut`,
56705
+ * return the index after its remainder; otherwise return `cut` unchanged.
56706
+ */
56707
+ function skipOpenEscape$1(text, cut) {
56708
+ let run = cut;
56709
+ while (run > 0 && isCsiBody$1(text.codePointAt(run - 1))) run -= 1;
56710
+ if (run >= 2 && text[run - 1] === "[" && text[run - 2] === ESC$2) {
56711
+ const skip = skipCsiRest$1(text, cut);
56712
+ return withinDropShare$1(text, cut, skip.end, skip.closed);
56713
+ }
56714
+ if (text[run - 1] === ESC$2 && allEscapeIntermediates$1(text, run, cut)) return skipEscapeRest$1(text, cut);
56715
+ const open = text.lastIndexOf(ESC$2, cut - 1);
56716
+ if (open !== -1 && isStringIntro$1(text[open + 1])) return stringSequenceHead$1(text, open, cut);
56717
+ return cut;
56718
+ }
56719
+ /**
56720
+ * Keep a provable skip only while it stays within `MAX_TAIL_DROP_SHARE` of the
56721
+ * tail that starts at `from`: the skipped bytes are exactly what the reader
56722
+ * loses from the tail it asked for. A CSI body or escape-intermediate run can
56723
+ * be arbitrarily long, so past the bound the raw cut is worth more than the
56724
+ * clean head — except when the sequence's introducer ESC sits immediately
56725
+ * before the head (`…\u001b|[31m…`) *and* `closed` says the skip found the
56726
+ * sequence's terminator, where one unit of look-back keeps the sequence whole
56727
+ * instead: the sanitizer strips it and the visible text is the skip's, for
56728
+ * that one unit rather than a sliver of the tail. An unclosed run must keep
56729
+ * the raw cut even with that ESC one unit ahead: nothing terminates it, so
56730
+ * look-back would hand the reader a bare ESC whose sequence run a terminal
56731
+ * swallows along with the bytes behind it.
56732
+ */
56733
+ function withinDropShare$1(text, from, target, closed) {
56734
+ if (target - from <= (text.length - from) * MAX_TAIL_DROP_SHARE$1) return target;
56735
+ return closed && from > 0 && text[from - 1] === ESC$2 ? from - 1 : from;
56736
+ }
56737
+ /**
56738
+ * The rest of a CSI sequence whose body was torn at `cut`, with the closure
56739
+ * its skip proved: `closed` holds only when a final byte (0x40–0x7E) was
56740
+ * actually found, so a parameter run that reaches the end of `text` — or stops
56741
+ * on a byte no CSI can end with — reports the sequence as open.
56742
+ */
56743
+ function skipCsiRest$1(text, cut) {
56744
+ let end = cut;
56745
+ while (end < text.length && isCsiBody$1(text.codePointAt(end))) end += 1;
56746
+ const closed = end < text.length && isCsiFinal$1(text.codePointAt(end));
56747
+ return {
56748
+ end: closed ? end + 1 : end,
56749
+ closed
56750
+ };
56751
+ }
56752
+ /** Index after the escape sequence whose introducer ESC sits at `cut - 1`. */
56753
+ function skipEscapeRest$1(text, cut) {
56754
+ const intro = text[cut];
56755
+ if (intro === "[") {
56756
+ const skip = skipCsiRest$1(text, cut + 1);
56757
+ return withinDropShare$1(text, cut, skip.end, skip.closed);
56758
+ }
56759
+ if (isStringIntro$1(intro)) return stringSequenceHead$1(text, cut - 1, cut + 1);
56760
+ let end = cut;
56761
+ while (end < text.length && isEscapeIntermediate$1(text.codePointAt(end))) end += 1;
56762
+ const closed = end < text.length && isEscapeFinal$1(text.codePointAt(end));
56763
+ return withinDropShare$1(text, cut, closed ? end + 1 : end, closed);
56764
+ }
56765
+ /**
56766
+ * Head index for a cut that lands inside the string sequence opened at `open`.
56767
+ *
56768
+ * `stringEnd` gives the byte a terminal stops at; skipping to it hides the
56769
+ * payload's remainder, which is what a terminal shows — but only while that
56770
+ * costs at most `MAX_TAIL_DROP_SHARE` of the tail. A long OSC 8 URL, or any
56771
+ * payload longer than the budget, would otherwise hand the caller a sliver of
56772
+ * the tail it asked for; a payload whose extent exceeds the budget stays
56773
+ * visible instead. A cut the string already ended ahead of needs no skip, and
56774
+ * an unterminated one must not swallow the tail (`stringPayloadHead`).
56775
+ */
56776
+ function stringSequenceHead$1(text, open, cut) {
56777
+ const drop = stringEnd$1(text, open + 2) - cut;
56778
+ if (drop >= 0 && drop <= (text.length - cut) * MAX_TAIL_DROP_SHARE$1) return cut + drop;
56779
+ return stringPayloadHead$1(text, open, cut);
56780
+ }
56781
+ /**
56782
+ * Head index that keeps a string sequence's payload visible, moving the cut
56783
+ * only past the opener's own bytes when the cut landed inside them.
56784
+ *
56785
+ * A terminal swallows an unterminated payload, but a viewer must never render
56786
+ * a blank body: `tailSlice` backs the tasks-browser tail read, and a log that
56787
+ * opens with an unterminated OSC — a run killed mid-title, a truncated write —
56788
+ * would otherwise come back empty. The head stays at `cut` unless the cut
56789
+ * landed inside the opener (`\u001b]0;` would leave `0;` in front of the
56790
+ * payload), and never reaches `text.length` — the clamp to the last unit steps
56791
+ * back onto the pair's first half when that unit is a trailing surrogate
56792
+ * pair's low half — so the tail is empty only for empty input.
56793
+ */
56794
+ function stringPayloadHead$1(text, open, cut) {
56795
+ const head = Math.min(Math.max(cut, stringPayloadStart$1(text, open)), text.length - 1);
56796
+ const code = text.codePointAt(head);
56797
+ return head > 0 && code !== void 0 && code >= 56320 && code <= 57343 ? head - 1 : head;
56798
+ }
56799
+ /**
56800
+ * Index after the byte that ends the string sequence whose payload starts at
56801
+ * `from` — its BEL or `ESC \` terminator, or a CAN (0x18) / SUB (0x1A), which
56802
+ * a terminal reads as "string over, resume normal parsing". `-1` when the
56803
+ * string never ends.
56804
+ */
56805
+ function stringEnd$1(text, from) {
56806
+ for (let i = from; i < text.length; i += 1) {
56807
+ const code = text.codePointAt(i);
56808
+ if (code === 7) return i + 1;
56809
+ if (code === 27 && text[i + 1] === "\\") return i + 2;
56810
+ if (code === 24 || code === 26) return i + 1;
56811
+ }
56812
+ return -1;
56813
+ }
56814
+ /**
56815
+ * Index where the payload of the string sequence opened at `open` starts: for
56816
+ * OSC after `ESC ] Ps ;`, for DCS/PM/APC after their parameter and
56817
+ * intermediate bytes and the final byte that opens the payload.
56818
+ */
56819
+ function stringPayloadStart$1(text, open) {
56820
+ let i = open + 2;
56821
+ if (text[open + 1] === "]") {
56822
+ while (i < text.length && isOscParam$1(text.codePointAt(i))) i += 1;
56823
+ if (text[i] === ";") i += 1;
56824
+ return i;
56825
+ }
56826
+ while (i < text.length && isCsiBody$1(text.codePointAt(i))) i += 1;
56827
+ const final = text.codePointAt(i);
56828
+ return i < text.length && isCsiFinal$1(final) ? i + 1 : i;
56829
+ }
56830
+ /** OSC numeric parameter byte (0x30–0x39) — the `Ps` before the `;` separator. */
56831
+ function isOscParam$1(code) {
56832
+ return code !== void 0 && code >= 48 && code <= 57;
56833
+ }
56465
56834
  /**
56466
56835
  * Longest suffix of `text` whose UTF-8 encoding fits in `maxBytes`. Encoding
56467
56836
  * through a Buffer keeps lone surrogates accounted as the 3-byte replacement
@@ -56485,7 +56854,6 @@ function persistedToInfo(t) {
56485
56854
  exitCode: t.exit_code,
56486
56855
  startedAt: t.started_at,
56487
56856
  endedAt: t.ended_at,
56488
- approvalReason: t.approval_reason,
56489
56857
  timedOut: t.timed_out,
56490
56858
  stopReason: t.stop_reason,
56491
56859
  agentId: t.agent_id,
@@ -56502,7 +56870,6 @@ function infoToPersisted(info) {
56502
56870
  ended_at: info.endedAt,
56503
56871
  exit_code: info.exitCode,
56504
56872
  status: info.status,
56505
- approval_reason: info.approvalReason,
56506
56873
  timed_out: info.timedOut,
56507
56874
  stop_reason: info.stopReason,
56508
56875
  agent_id: info.agentId === info.taskId ? void 0 : info.agentId,
@@ -59791,7 +60158,7 @@ function normalizePath$1(path) {
59791
60158
  var agent_background_disabled_default = "Background agent execution is disabled for this agent. Do not set `run_in_background=true`.";
59792
60159
  //#endregion
59793
60160
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/agent-background-enabled.md
59794
- var agent_background_enabled_default = "When `run_in_background=true`, the subagent runs detached from this turn. The completion arrives in a later turn as a synthetic user-role message containing its result — you do not need to poll, sleep, or check on its progress. Continue with other work or respond to the user. Never fabricate or predict what the result will say.\n\nWhile it runs, the subagent can ask you questions via `ContactParent`. You will see them at your next step boundary, and a `SendSubagentMessage` reply reaches it mid-run — this is the mode that supports mid-course steering. A foreground subagent's questions, in contrast, only reach you after it completes.\n\nFor a background task, when `timeout` is omitted it falls back to the operator-configured background timeout, if one is set. If the operator has not configured a background timeout, an omitted `timeout` means the task runs with no time limit.\n";
60161
+ var agent_background_enabled_default = "When `run_in_background=true`, the subagent runs detached from this turn. The completion arrives in a later turn as a synthetic user-role message containing its result — you do not need to poll, sleep, or check on its progress. Continue with other work or respond to the user. Never fabricate or predict what the result will say.\n\nWhile it runs, the subagent can ask you questions via `ContactParent`. You will see them at your next step boundary, and a `SendSubagentMessage` reply reaches it mid-run — this is the mode that supports mid-course steering. A foreground subagent's questions are delivered the same way: the request ends your foreground wait and hands the subagent to the background, so it reaches you at your next step boundary and a `SendSubagentMessage` reply still steers it mid-run.\n\nFor a background task, when `timeout` is omitted it falls back to the operator-configured background timeout, if one is set. If the operator has not configured a background timeout, an omitted `timeout` means the task runs with no time limit.\n";
59795
60162
  //#endregion
59796
60163
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/agent.md
59797
60164
  var agent_default = "Launch a subagent to handle a focused task. Prefer this tool over doing the work yourself when the task matches one of the specialists listed below.\n\nSpecialist subagents are listed at the end of this description under \"Available agent types\" — that list is generated from the active profiles and carries each specialist's own USE WHEN / NOT FOR triggers. Read it before choosing a `subagent_type`; never assume a type exists.\n\n## Required prompt structure\n\nThe final prompt sent to the subagent MUST contain these sections. Provide them either by writing them directly into the `prompt` field, or by using the structured `target`, `change`, and `acceptance` fields — they will be appended to `prompt` automatically.\n\n```markdown\n# Target\nExact files, symbols, or directories to touch. Explicit non-goals.\n\n# Change\nStep-by-step what to add, remove, or modify. Include concrete examples when possible.\n\n# Acceptance\nObservable result that proves completion: a passing test, a build command, a specific file content, or a verification step the subagent must run.\n```\n\nOmitting a section causes the subagent to miss context and increases the chance of a wrong or incomplete result.\n\nWriting the prompt:\n- The subagent starts with zero context — it has not seen this conversation. Brief it like a colleague who just walked into the room: state the goal, list what you already know, hand over the specifics.\n- Lookups (read this file, run that test): put the exact path or command in the prompt. The subagent should not have to search for things you already know.\n- Investigations (figure out X, find why Y): give the question, not prescribed steps — fixed steps become dead weight when the premise is wrong.\n- Do not delegate understanding. If the task hinges on a file path or line number, find it yourself first and write it into the prompt.\n- The `Acceptance` section is not optional. The subagent MUST verify against it before returning.\n\nUsage notes:\n- When the task continues earlier work a subagent already did, prefer resuming that agent (pass its `resume` id) over spawning a fresh instance — the resumed agent keeps its prior context.\n- A subagent's result is only visible to you, not to the user. When the user needs to see what a subagent produced, summarize the relevant parts yourself in your own reply.\n\n## Structured output\n\nWhen you need a machine-readable result (not a free-form summary), pass `output_schema` with a JSON Schema string. The subagent is instructed to reply with a single JSON object matching the schema; if the reply parses, it is surfaced as a `[structured]` block in the tool output. Use `output_token_hint` to keep structured replies compact (e.g. 1024 for a schema-shaped answer).\n\nExample:\n```\nAgent(prompt=\"Extract the test commands from this project\", output_schema='{\"type\":\"object\",\"properties\":{\"commands\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}}}')\n```\n\n## Capability constraints\n\nBy default a subagent gets its profile's full tool set. Pass `capability_mode` to restrict it at the tool level (not just by prompting):\n\n- `read-only` — inspection, search, web/memory lookups, and reporting only. No file writes, no command execution, no spawning further agents.\n- `read-write` — additionally file/memory writes. No command execution, no spawning.\n- `execute` — additionally command execution (bash, python). Still no spawning of further agents.\n- `all` — full profile tool set (default).\n\nRestricted modes also remove `Agent` and `SendSubagentMessage`, so a constrained subagent cannot spawn an unconstrained grandchild to bypass the filter.\n\nResume clamps the contract — it can only tighten, never widen. A resumed agent keeps the tool set it was spawned with (its profile is not rebuilt), so a wider `capability_mode` than the one it already carries is ignored, and a stored restriction is re-applied on the resumed instance. To hand a subagent more tools, spawn a fresh one.\n\n## Steering running subagents\n\nUse `SendSubagentMessage` to send a directed message to a subagent you own while it is still running: `steer` for a priority redirection, `queue` for context that applies next turn. A `steer` joins the subagent's running turn at its next step boundary; a `queue` message is delivered when the subagent starts its next turn. When the correction cannot wait for a checkpoint, use `interject`: it interrupts the tools running at that moment (side-effecting commands included, and pending approvals are withdrawn) so the message lands at the very next step. Only the owning parent may message a subagent.\n\nWhen NOT to use Agent: skip delegation for trivial one-step work (e.g. reading a known file). Almost everything else is a candidate for delegation.\n\nOnce a subagent is running, leave that scope to it: do not redo its searches or reads in parallel, and do not abandon it midway and finish the job manually. Both undo the context savings the delegation was meant to buy.\n\n## Foreground timeouts auto-background\n\nA `timeout` on a foreground `Agent` call bounds your wait, not the subagent's life. When the deadline fires while the child is still running, it is handed to the background task manager (status: backgrounded) instead of being aborted: the tool returns a `task_id`, its completion notification arrives automatically in a later turn (no polling), and you can peek with `TaskOutput(task_id=..., block=false)` or stop it with `TaskStop`. User cancellation still aborts immediately. A stopped (TaskStop) background task never suggests resume; only tasks that finish or fail on their own are recoverable via `Agent(resume=...)`.";
@@ -59851,6 +60218,15 @@ z.object({
59851
60218
  }).describe("Cumulative token usage")
59852
60219
  });
59853
60220
  const BACKGROUND_AGENT_UNAVAILABLE = "Background agent execution is not available for this agent because TaskList, TaskOutput, and TaskStop are not enabled.";
60221
+ /**
60222
+ * Refusal text for the nesting-depth gate. Shared by every spawn surface
60223
+ * (the Agent tool and WolfPack) so both refuse at the same cap with the same
60224
+ * wording — a cap the model can walk around through another spawn tool is no
60225
+ * cap at all.
60226
+ */
60227
+ function spawnDepthLimitRefusal(depth) {
60228
+ return `Depth limit reached: this agent is already ${String(depth)} spawn hops from the root agent, and the nesting depth cap is ${String(3)}. Spawning another subagent here would keep (or loop) the delegation chain instead of finishing the work. Do the task in this agent; if you are blocked, report back to your parent with ContactParent.`;
60229
+ }
59854
60230
  var AgentTool = class {
59855
60231
  subagentHost;
59856
60232
  backgroundManager;
@@ -59868,6 +60244,7 @@ var AgentTool = class {
59868
60244
  this.description = typeLines ? `${baseDescription}\n\nAvailable agent types (pass via subagent_type):\n${typeLines}` : baseDescription;
59869
60245
  this.log = log;
59870
60246
  this.allowedSpawns = options?.allowedSpawns;
60247
+ this.spawnDepth = options?.spawnDepth ?? (() => 0);
59871
60248
  }
59872
60249
  checkSpawnAllowed(profileName) {
59873
60250
  if (this.allowedSpawns !== void 0 && !this.allowedSpawns.includes(profileName)) return {
@@ -59877,6 +60254,8 @@ var AgentTool = class {
59877
60254
  }
59878
60255
  log;
59879
60256
  allowedSpawns;
60257
+ /** Reads the calling agent's spawn depth for the nesting gate. */
60258
+ spawnDepth;
59880
60259
  resolveExecution(args) {
59881
60260
  let profileName = args.subagent_type?.length ? args.subagent_type : "coder";
59882
60261
  const resumeAgentId = args.resume?.trim();
@@ -59905,6 +60284,13 @@ var AgentTool = class {
59905
60284
  output: "Cannot set subagent_type when resuming an existing agent. Resume by agent id only.",
59906
60285
  isError: true
59907
60286
  };
60287
+ if (!(resumeAgentId !== void 0 && resumeAgentId.length > 0)) {
60288
+ const depth = this.spawnDepth();
60289
+ if (depth >= 3) return {
60290
+ output: spawnDepthLimitRefusal(depth),
60291
+ isError: true
60292
+ };
60293
+ }
59908
60294
  const effectiveProfileName = resumeAgentId !== void 0 && resumeAgentId.length > 0 ? this.subagentHost.getProfileName?.(resumeAgentId) : requestedProfileName ?? "coder";
59909
60295
  if (effectiveProfileName !== void 0) {
59910
60296
  const denied = this.checkSpawnAllowed(effectiveProfileName);
@@ -60041,76 +60427,133 @@ var AgentTool = class {
60041
60427
  }
60042
60428
  }
60043
60429
  /**
60044
- * Foreground completion wait with optional timeout.
60430
+ * Foreground completion wait.
60431
+ *
60432
+ * When background dispatch is available the wait races three legs: the
60433
+ * child's completion (always), a collaboration request from the child
60434
+ * (always), and the deadline (only when `timeoutMs` is set). Either bounded
60435
+ * outcome hands the still-running child to the background task manager —
60436
+ * never aborts it — and returns a `backgrounded` outcome carrying the task
60437
+ * id:
60438
+ *
60439
+ * - A request means the parent is needed mid-run: the parent is parked
60440
+ * inside this tool call, so the `child_request` notification would sit in
60441
+ * the steer buffer until the child finishes. Backgrounding lets the parent
60442
+ * read the request at its next step boundary and answer the still-running
60443
+ * child through `SendSubagentMessage`.
60444
+ * - A timeout degrades the wait; it does not destroy the subagent's work.
60445
+ *
60446
+ * Without background dispatch (`!allowBackground` or no manager) the wait
60447
+ * degrades to awaiting completion directly.
60045
60448
  *
60046
- * When `timeoutMs` is set and background dispatch is available, the wait is
60047
- * bounded by a race: if the child has not finished by the deadline it is
60048
- * handed to the background task manager (never aborted) and the caller
60049
- * receives a `backgrounded` outcome carrying the task id. A timeout degrades
60050
- * the wait; it does not destroy the subagent's work.
60449
+ * A child whose controller is already aborted (the user cancelled the parent
60450
+ * turn while the child was parked in a signal-ignoring tool such as
60451
+ * `ContactParent`) is never handed over: both bounded legs fall back to the
60452
+ * completion leg so the cancellation is reported instead of resurrected as a
60453
+ * background task.
60051
60454
  */
60052
60455
  async awaitForegroundCompletion(handle, description, timeoutMs, childController, unlinkChild) {
60053
- if (timeoutMs === void 0 || !this.allowBackground || this.backgroundManager === void 0) return {
60456
+ const backgroundManager = this.backgroundManager;
60457
+ if (!this.allowBackground || backgroundManager === void 0) return {
60054
60458
  kind: "completed",
60055
60459
  result: await handle.completion
60056
60460
  };
60461
+ const childRequestArrival = this.subagentHost.waitForChildRequest?.(handle.agentId);
60057
60462
  let timer;
60058
- const deadline = new Promise((resolve) => {
60059
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
60060
- });
60061
60463
  try {
60062
- const outcome = await Promise.race([handle.completion.then((result) => ({
60464
+ const legs = [handle.completion.then((result) => ({
60063
60465
  kind: "completed",
60064
60466
  result
60065
- })), deadline.then(() => ({ kind: "timeout" }))]);
60066
- if (outcome.kind === "completed") return outcome;
60067
- let taskId;
60068
- try {
60069
- taskId = this.backgroundManager.registerAgentTask(handle.completion, description, {
60070
- agentId: handle.agentId,
60071
- subagentType: handle.profileName,
60072
- abort: () => childController.abort()
60073
- });
60074
- } catch (error) {
60075
- const message = error instanceof Error ? error.message : String(error);
60076
- this.log?.warn("foreground→background handoff failed; child kept running", {
60077
- agentId: handle.agentId,
60078
- error
60079
- });
60080
- return {
60081
- kind: "backgrounded",
60082
- output: [
60083
- `agent_id: ${handle.agentId}`,
60084
- `actual_subagent_type: ${handle.profileName}`,
60085
- "status: backgrounded",
60086
- "",
60087
- `warning: timed out after ${timeoutMs}ms and could not register a background task: ${message}`,
60088
- "",
60089
- `resume_hint: The subagent is still running. To pick it up, call Agent(resume="${handle.agentId}", prompt="...").`
60090
- ].join("\n")
60091
- };
60467
+ }))];
60468
+ if (childRequestArrival !== void 0) legs.push(childRequestArrival.then(() => ({ kind: "request" })));
60469
+ if (timeoutMs !== void 0) {
60470
+ const bound = timeoutMs;
60471
+ legs.push(new Promise((resolve) => {
60472
+ timer = setTimeout(() => {
60473
+ resolve({
60474
+ kind: "timeout",
60475
+ timeoutMs: bound
60476
+ });
60477
+ }, bound);
60478
+ }));
60092
60479
  }
60093
- unlinkChild?.();
60094
- this.subagentHost.markBackground?.(handle.agentId);
60480
+ const outcome = await Promise.race(legs);
60481
+ if (outcome.kind === "completed") return outcome;
60482
+ if (childController.signal.aborted) return {
60483
+ kind: "completed",
60484
+ result: await handle.completion
60485
+ };
60486
+ if (outcome.kind === "request") return this.handoffChildToBackground(backgroundManager, handle, description, { kind: "request" }, childController, unlinkChild);
60487
+ return this.handoffChildToBackground(backgroundManager, handle, description, {
60488
+ kind: "timeout",
60489
+ timeoutMs: outcome.timeoutMs
60490
+ }, childController, unlinkChild);
60491
+ } finally {
60492
+ if (timer !== void 0) clearTimeout(timer);
60493
+ this.subagentHost.releaseChildRequestWait?.(handle.agentId);
60494
+ }
60495
+ }
60496
+ /**
60497
+ * Hand a still-running foreground child to the background task manager.
60498
+ *
60499
+ * Shared by both bounded-wait outcomes: the timeout path keeps its exact
60500
+ * wording, the request path reports why the parent got the task (the child
60501
+ * asked something; the parent answers it at its next step). Registration
60502
+ * failure keeps the parent→child link intact — the child is neither orphaned
60503
+ * nor aborted — and only a successful handoff decouples it from the parent
60504
+ * signal and flips it to the background lifecycle.
60505
+ */
60506
+ handoffChildToBackground(backgroundManager, handle, description, reason, childController, unlinkChild) {
60507
+ childController.signal.throwIfAborted();
60508
+ let taskId;
60509
+ try {
60510
+ taskId = backgroundManager.registerAgentTask(handle.completion, description, {
60511
+ agentId: handle.agentId,
60512
+ subagentType: handle.profileName,
60513
+ abort: () => {
60514
+ childController.abort();
60515
+ }
60516
+ });
60517
+ } catch (error) {
60518
+ const message = error instanceof Error ? error.message : String(error);
60519
+ this.log?.warn("foreground→background handoff failed; child kept running", {
60520
+ agentId: handle.agentId,
60521
+ error
60522
+ });
60523
+ const warning = reason.kind === "timeout" ? `warning: timed out after ${reason.timeoutMs}ms and could not register a background task: ${message}` : `warning: the subagent requested input and could not register a background task: ${message}`;
60524
+ const tail = reason.kind === "timeout" ? `resume_hint: The subagent is still running. To pick it up, call Agent(resume="${handle.agentId}", prompt="...").` : ["next_step: The subagent is still running and its request is already queued for you — it reaches you at your next step boundary, and SendSubagentMessage can steer the child.", `resume_hint: To continue or recover this same subagent later, call Agent(resume="${handle.agentId}", prompt="...").`].join("\n");
60095
60525
  return {
60096
60526
  kind: "backgrounded",
60097
60527
  output: [
60098
- `task_id: ${taskId}`,
60099
- "status: backgrounded",
60100
60528
  `agent_id: ${handle.agentId}`,
60101
60529
  `actual_subagent_type: ${handle.profileName}`,
60102
- "automatic_notification: true",
60103
- "cancel_semantics: Stopping this task (TaskStop) cancels it — its completion notification will not suggest resume. Only tasks that finish or fail on their own are recoverable via Agent(resume=...).",
60530
+ "status: backgrounded",
60104
60531
  "",
60105
- `description: ${description}`,
60532
+ warning,
60106
60533
  "",
60107
- `next_step: The subagent exceeded the foreground timeout (${timeoutMs}ms) and was moved to the background instead of being aborted. Its completion arrives automatically in a later turn — no polling needed. To peek at progress without blocking, call TaskOutput(task_id="${taskId}", block=false).`,
60108
- `resume_hint: To continue or recover this same subagent later, call Agent(resume="${handle.agentId}", prompt="..."). The parameter is agent_id ("${handle.agentId}"), NOT task_id ("${taskId}") or source_id from a later <notification>.`
60534
+ tail
60109
60535
  ].join("\n")
60110
60536
  };
60111
- } finally {
60112
- if (timer !== void 0) clearTimeout(timer);
60113
60537
  }
60538
+ unlinkChild?.();
60539
+ this.subagentHost.markBackground?.(handle.agentId);
60540
+ const nextStep = reason.kind === "timeout" ? `next_step: The subagent exceeded the foreground timeout (${reason.timeoutMs}ms) and was moved to the background instead of being aborted. Its completion arrives automatically in a later turn — no polling needed. To peek at progress without blocking, call TaskOutput(task_id="${taskId}", block=false).` : `next_step: The subagent raised a request and was moved to the background so you can answer it in real time. The request text arrives with the subagent message at your next step boundary. Reply with SendSubagentMessage — the subagent keeps running and a steer lands inside its live turn (operation "interject" if it must be read immediately, e.g. it is stuck in a long tool call). Its completion arrives automatically in a later turn; to wait for it without polling, call TaskOutput(task_id="${taskId}", block=true).`;
60541
+ return {
60542
+ kind: "backgrounded",
60543
+ output: [
60544
+ `task_id: ${taskId}`,
60545
+ "status: backgrounded",
60546
+ `agent_id: ${handle.agentId}`,
60547
+ `actual_subagent_type: ${handle.profileName}`,
60548
+ "automatic_notification: true",
60549
+ "cancel_semantics: Stopping this task (TaskStop) cancels it — its completion notification will not suggest resume. Only tasks that finish or fail on their own are recoverable via Agent(resume=...).",
60550
+ "",
60551
+ `description: ${description}`,
60552
+ "",
60553
+ nextStep,
60554
+ `resume_hint: To continue or recover this same subagent later, call Agent(resume="${handle.agentId}", prompt="..."). The parameter is agent_id ("${handle.agentId}"), NOT task_id ("${taskId}") or source_id from a later <notification>.`
60555
+ ].join("\n")
60556
+ };
60114
60557
  }
60115
60558
  /** Render the completed-subagent result text (summary + optional structured block). */
60116
60559
  formatCompletion(handle, result, outputSchema) {
@@ -60283,9 +60726,16 @@ function isQuestionResponse(result) {
60283
60726
  }
60284
60727
  //#endregion
60285
60728
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/contact-parent.md
60286
- var contact_parent_default = "You are running as a subagent. Use this tool to proactively contact your parent agent mid-run.\n\nThree request types:\n\n- `info` — ask for missing context, clarify an ambiguous instruction, or report a blocker while you keep working. The parent replies at its next turn boundary.\n- `handoff` — ask the parent to pass part of your work to a different capability (for example: \"needs: independent verification of this logic\"). Describe the capability you need (`needs`), never a specific agent, and say what a good reply looks like (`payload.expecting`). The parent chooses the agent, approves, and routes the work with your artifacts.\n- `escalate` — bump something to the human that you are not allowed to decide (a permission boundary, a contradiction in evidence, a scope question).\n\nInclude a `payload` with your work products (`artifacts`), proof (`evidence`), anything left unfinished (`missing`), and — for a handoff — what a good reply looks like (`expecting`: the shape, format, or acceptance criteria you want back) so the parent can route the work without you re-explaining everything.\n\nRate limit: up to 4 requests per turn; duplicate requests within a turn are merged. `accepted` means the request was delivered to the parent as a notification — the parent sees it at its next turn boundary (it may be delayed if the parent is mid-turn). Keep working while you wait; do not block on a reply. If the parent cannot help, it will tell you why via a message.\n\n**Never guess your way through a blocker.** If you are stuck or unsure, contact the parent instead of inventing an answer.\n";
60729
+ var contact_parent_default = "You are running as a subagent. Use this tool to proactively contact your parent agent mid-run.\n\nThree request types:\n\n- `info` — ask for missing context, clarify an ambiguous instruction, or report a blocker while you keep working. The parent replies at its next turn boundary.\n- `handoff` — ask the parent to pass part of your work to a different capability (for example: \"needs: independent verification of this logic\"). Describe the capability you need (`needs`), never a specific agent, and say what a good reply looks like (`payload.expecting`). The parent chooses the agent, approves, and routes the work with your artifacts.\n- `escalate` — bump something to the human that you are not allowed to decide (a permission boundary, a contradiction in evidence, a scope question).\n\nInclude a `payload` with your work products (`artifacts`), proof (`evidence`), anything left unfinished (`missing`), and — for a handoff — what a good reply looks like (`expecting`: the shape, format, or acceptance criteria you want back) so the parent can route the work without you re-explaining everything.\n\nRate limit: up to 4 requests per turn; duplicate requests within a turn are merged. `accepted` means the request was delivered to the parent as a notification — the parent sees it at its next turn boundary. If the parent is blocked waiting on your run (a foreground Agent call) and it has background dispatch, the request moves you to the background so the parent can read it and reply while you keep running (without background dispatch on the parent's side it can only read it after your run finishes) — this never aborts you or discards work. Keep working while you wait; do not block on a reply. If the parent cannot help, it will tell you why via a message.\n\nA request that is not `accepted` was not delivered: `parent_gone` (the parent agent is no longer running in this session) or `not_active` means no reply can ever arrive — do not wait for one, finish your work and report the open question in your result.\n\n**Never guess your way through a blocker.** If you are stuck or unsure, contact the parent instead of inventing an answer.\n";
60287
60730
  //#endregion
60288
60731
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/contact-parent.ts
60732
+ /** Rejections the child can act on. A request that was not accepted was not
60733
+ * delivered — none of these may read like a delayed delivery. */
60734
+ const REJECT_TEXT = {
60735
+ not_active: "Request rejected: this agent is no longer an active child of its parent in this session, so the request was not delivered. Do not wait for a reply.",
60736
+ parent_gone: "Request rejected: the parent agent is no longer running in this session, so it cannot receive this request and no reply will come. Do not wait — finish the remaining work and return your result; a resumed parent can pick this agent up again with Agent(resume=<agent id>).",
60737
+ saturated: "Request rejected: this turn already used its budget of 4 collaboration requests. Resolve what you can yourself, and report the open question in your result instead."
60738
+ };
60289
60739
  const ContactParentInputSchema = z.object({
60290
60740
  request_type: z.enum([
60291
60741
  "info",
@@ -60319,7 +60769,7 @@ var ContactParentTool = class {
60319
60769
  const result = this.subagentHost.submitChildRequest(this.getAgent(), args);
60320
60770
  return {
60321
60771
  isError: result.status !== "accepted",
60322
- output: result.status === "accepted" ? result.deduped === true ? "Request accepted (duplicate of an earlier request this turn; the parent already has it)." : "Request accepted. The parent will see it at its next turn boundary; keep working while you wait." : `Request rejected: ${result.status}.`
60772
+ output: result.status === "accepted" ? result.deduped === true ? "Request accepted (duplicate of an earlier request this turn; the parent already has it)." : "Request accepted. The parent will see it at its next turn boundary; keep working while you wait." : REJECT_TEXT[result.status] ?? `Request rejected: ${result.status}.`
60323
60773
  };
60324
60774
  }
60325
60775
  };
@@ -60546,9 +60996,156 @@ function formatFindingsBlock(findings) {
60546
60996
  if (findings.length === 0) return "";
60547
60997
  return `\n\n[review_findings]\n${findings.map((f) => `- [${f.priority}] ${f.title.split("\n").join(" ")} (${f.file_path.split("\n").join(" ")}:${f.line_start}${f.line_end === f.line_start ? "" : `-${f.line_end}`}) confidence=${(f.confidence * 100).toFixed(0)}%\n ${f.body.split("\n").join("\n ")}`).join("\n")}`;
60548
60998
  }
60999
+ const DEFAULT_BYTE_LIMIT = 16 * 1024;
61000
+ /**
61001
+ * How long a queued message stays deliverable. A child turn routinely outlasts
61002
+ * a minute (long tool calls, several steps), so the window has to cover a real
61003
+ * turn rather than expire while the child is still working.
61004
+ */
61005
+ const SUBAGENT_MESSAGE_DEADLINE_MS = 3e5;
61006
+ /** UTF-8 byte length (TextEncoder is available in all supported runtimes). */
61007
+ function byteLength(text) {
61008
+ return new TextEncoder().encode(text).length;
61009
+ }
61010
+ /**
61011
+ * Byte length of a message body. Callers that deliver a message without going
61012
+ * through `send` (the mid-run steer path) use this to apply the same limit.
61013
+ */
61014
+ function subagentMessageBytes(text) {
61015
+ return byteLength(text);
61016
+ }
61017
+ var SubagentMessageBus = class {
61018
+ mailboxes = /* @__PURE__ */ new Map();
61019
+ nextId = 0;
61020
+ nextSeq = 0;
61021
+ /**
61022
+ * Number of messages still deliverable for `agentId`. Expired ones are not
61023
+ * counted: `poll` drops them, so counting them would make the host spend a
61024
+ * delivery turn on a message that can never arrive. Counting is also an
61025
+ * ordinary bus access, so it reclaims mail that has expired by now.
61026
+ */
61027
+ activeCount(agentId) {
61028
+ this.reclaimExpired(Date.now());
61029
+ return this.mailboxes.get(agentId)?.queue.length ?? 0;
61030
+ }
61031
+ /**
61032
+ * Queue a message for a subagent. Pure mailbox logic: ownership, liveness
61033
+ * and activity checks belong to the host. Returns the delivery status and,
61034
+ * on acceptance, the stable message id plus the queue depth seen by the
61035
+ * recipient at poll time.
61036
+ *
61037
+ * The id is the reconciliation handle for a delivery: it is unique within
61038
+ * this bus, never reissued (see `clear`), carried by the delivered message
61039
+ * and returned here so the host can tie a retried send to the message it
61040
+ * duplicates and can watch the message's consumption (`holdsMessage`).
61041
+ */
61042
+ send(msg) {
61043
+ const now = Date.now();
61044
+ this.reclaimExpired(now);
61045
+ if (byteLength(msg.text) > msg.byteLimit) return {
61046
+ status: "saturated",
61047
+ reason: "bytes"
61048
+ };
61049
+ let mailbox = this.mailboxes.get(msg.toAgentId);
61050
+ if (mailbox === void 0) {
61051
+ mailbox = { queue: [] };
61052
+ this.mailboxes.set(msg.toAgentId, mailbox);
61053
+ }
61054
+ if (mailbox.queue.length >= msg.inFlightLimit) return {
61055
+ status: "saturated",
61056
+ reason: "queue"
61057
+ };
61058
+ const message = {
61059
+ ...msg,
61060
+ id: `${msg.fromAgentId}:${msg.toAgentId}:${++this.nextId}`,
61061
+ seq: ++this.nextSeq
61062
+ };
61063
+ mailbox.queue.push(message);
61064
+ return {
61065
+ status: "accepted",
61066
+ queueDepth: mailbox.queue.length,
61067
+ messageId: message.id
61068
+ };
61069
+ }
61070
+ /**
61071
+ * Drop every queued message in every mailbox (session teardown). Id and seq
61072
+ * counters stay monotonic so identifiers issued before the clear are never
61073
+ * reissued.
61074
+ */
61075
+ clear() {
61076
+ this.mailboxes.clear();
61077
+ }
61078
+ /** How many mailboxes currently hold undelivered mail (diagnostics). */
61079
+ get mailboxCount() {
61080
+ return this.mailboxes.size;
61081
+ }
61082
+ /**
61083
+ * Whether the message with this id is still queued and deliverable — the
61084
+ * consumption check behind the host's parent→child dedupe: while this
61085
+ * returns true a retried send is a duplicate, and once it returns false the
61086
+ * message has been delivered (or expired) and the retry must go through.
61087
+ * Ordinary bus access: expired mail is reclaimed first, so an expired
61088
+ * message reads as no longer in flight, which is exactly right — it will
61089
+ * never reach the child.
61090
+ */
61091
+ holdsMessage(id) {
61092
+ this.reclaimExpired(Date.now());
61093
+ for (const mailbox of this.mailboxes.values()) if (mailbox.queue.some((message) => message.id === id)) return true;
61094
+ return false;
61095
+ }
61096
+ /**
61097
+ * Drop mail that can no longer be delivered and free the mailbox slot it
61098
+ * pinned. A message is deliverable only until its deadline; past it, `poll`
61099
+ * would discard it rather than hand it to the child, so keeping it would pin
61100
+ * memory for a run that has already ended. Called on every ordinary bus
61101
+ * access — send, activeCount, poll — which is what keeps the mailbox map
61102
+ * bounded now that a finished child's terminal no longer purges its mailbox.
61103
+ */
61104
+ reclaimExpired(now) {
61105
+ for (const [agentId, mailbox] of this.mailboxes) {
61106
+ const live = mailbox.queue.filter((m) => m.deadline > now);
61107
+ if (live.length === 0) this.mailboxes.delete(agentId);
61108
+ else if (live.length !== mailbox.queue.length) mailbox.queue = live;
61109
+ }
61110
+ }
61111
+ /**
61112
+ * Deliver all pending, unexpired messages for `agentId`. Steer messages are
61113
+ * always dequeued before queue messages; within an operation class, arrival
61114
+ * order is preserved via the monotonically increasing `seq` (this is a stable
61115
+ * two-pass collection, not a sort). Messages past their deadline are
61116
+ * reclaimed, never delivered.
61117
+ *
61118
+ * The mailbox entry is removed once its queue is emptied: a polled-out (or
61119
+ * fully expired) mailbox must not pin a Map slot.
61120
+ */
61121
+ poll(agentId) {
61122
+ const now = Date.now();
61123
+ this.reclaimExpired(now);
61124
+ const mailbox = this.mailboxes.get(agentId);
61125
+ if (mailbox === void 0) return [];
61126
+ this.mailboxes.delete(agentId);
61127
+ const steers = mailbox.queue.filter((m) => m.operation === "steer");
61128
+ const queues = mailbox.queue.filter((m) => m.operation === "queue");
61129
+ steers.sort((a, b) => a.seq - b.seq);
61130
+ queues.sort((a, b) => a.seq - b.seq);
61131
+ return [...steers, ...queues];
61132
+ }
61133
+ };
61134
+ /** Construct a message with the bus defaults applied. */
61135
+ function buildSubagentMessage(fromAgentId, toAgentId, operation, text, overrides) {
61136
+ return {
61137
+ fromAgentId,
61138
+ toAgentId,
61139
+ operation,
61140
+ text,
61141
+ inFlightLimit: overrides?.inFlightLimit ?? 4,
61142
+ byteLimit: overrides?.byteLimit ?? 16384,
61143
+ deadline: overrides?.deadline ?? Date.now() + 3e5
61144
+ };
61145
+ }
60549
61146
  //#endregion
60550
61147
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/send-subagent-message.md
60551
- var send_subagent_message_default = "# SendSubagentMessage\n\nSend a directed message to a subagent you own. Use this to steer or inform a\nsubagent between its turns — for example, to redirect it after new\ninformation arrives, or to hand it a correction while it is still running.\n\n- **queue**: delivered when the subagent starts its next turn, after any steer\n messages. Use for context that does not change the immediate direction.\n- **steer**: delivered into the subagent's running turn, where it joins at the\n subagent's next step boundary; if no turn is running it waits in the mailbox\n and is delivered first at the next turn start. Use for a redirection that\n should reach the subagent while it is still working.\n- **interject**: like steer, but it also interrupts the tool call the subagent\n currently has in flight, so the correction takes effect immediately instead\n of after a long wait. Use it when the subagent is stuck in — or about to\n outlive the value of — a running command, and you already know what it\n should do instead. This is a batch-level hammer, not a single-call cancel:\n every tool that observes the abort signal is cut short (side-effecting\n commands included), approvals still waiting for an answer are withdrawn, and\n the abort travels down the signal chain into any foreground grandchild the\n batch is waiting on. The RLM Python kernel observes the signal too: a long\n exec is interrupted through the same SIGINT route, the running statement is\n unwound and the kernel keeps its state (variables survive; a kernel that does\n not return to an idle prompt is restarted instead). An interject aimed at an\n idle or structured-output subagent degrades to the steer/mailbox path.\n\n## Rules\n\n- You may only message subagents you spawned. Messaging a subagent owned by a\n different agent is refused.\n- A subagent cannot message itself.\n- `queue` and `steer` never abort a tool call that is already in flight: a\n steer joins the running turn at its next step boundary, a queue message waits\n for the next turn start. Only `interject` interrupts the in-flight batch —\n the interrupted tool reports the interruption, so the subagent knows the\n result is missing and why.\n- The acknowledgement says which path the message took. \"queued\" means it has\n not reached the subagent yet; \"interjected\" means the in-flight batch was cut\n short.\n- Keep messages short and unambiguous. The subagent sees them as a\n `[parent_messages]` block — merged into its running turn at the next step\n boundary, or at the top of its next prompt when the message waited for a turn\n start.\n- Prefer steering the *goal*, not the implementation: tell the subagent what\n changed and what to reconsider, not how to rewrite its code.\n- Do not use this tool to stop a subagent: a message is never a cancellation.\n To end its work use `TaskStop` (background tasks) or let the turn finish.\n- Do not use this tool to collect results: a subagent's completion arrives on\n its own as a notification (or as the `Agent` tool's return value in the\n foreground). Wait for that instead of polling.\n- This tool is available only to agents that may spawn subagents. Subagents\n launched with a restricted `capability_mode` (read-only / read-write /\n execute) do not have this tool — they cannot send messages or spawn further\n agents, which keeps the capability filter from being bypassed.\n";
61148
+ var send_subagent_message_default = "# SendSubagentMessage\n\nSend a directed message to a subagent you own. Use this to steer or inform a\nsubagent between its turns — for example, to redirect it after new\ninformation arrives, or to hand it a correction while it is still running.\n\n- **queue**: delivered when the subagent starts its next turn, after any steer\n messages. Use for context that does not change the immediate direction.\n- **steer**: delivered into the subagent's running turn, where it joins at the\n subagent's next step boundary; if no turn is running it waits in the mailbox\n and is delivered first at the next turn start. Use for a redirection that\n should reach the subagent while it is still working.\n- **interject**: like steer, but it also interrupts the tool call the subagent\n currently has in flight, so the correction takes effect immediately instead\n of after a long wait. Use it when the subagent is stuck in — or about to\n outlive the value of — a running command, and you already know what it\n should do instead. This is a batch-level hammer, not a single-call cancel:\n every tool that observes the abort signal is cut short (side-effecting\n commands included), approvals still waiting for an answer are withdrawn, and\n the abort travels down the signal chain into any foreground grandchild the\n batch is waiting on. The RLM Python kernel observes the signal too: a long\n exec is interrupted through the same SIGINT route, the running statement is\n unwound and the kernel keeps its state (variables survive; a kernel that does\n not return to an idle prompt is restarted instead). An interject aimed at an\n idle or structured-output subagent degrades to the steer/mailbox path, and\n the acknowledgement names the reason for the downgrade.\n\n## Rules\n\n- You may only message subagents you spawned. Messaging a subagent owned by a\n different agent is refused.\n- A subagent cannot message itself.\n- `queue` and `steer` never abort a tool call that is already in flight: a\n steer joins the running turn at its next step boundary, a queue message waits\n for the next turn start. Only `interject` interrupts the in-flight batch —\n the interrupted tool reports the interruption, so the subagent knows the\n result is missing and why.\n- The acknowledgement says which path the message took. \"queued\" means it has\n not reached the subagent yet; \"interjected\" means the in-flight batch was cut\n short.\n- Delivery is in-session and time-boxed. The mailbox lives in memory for this\n session only: \"accepted\" (queued) promises delivery only if the subagent\n reaches its next turn — or is resumed in this session — within the delivery\n deadline (about 5 minutes); after that the message expires undelivered, and\n nothing is persisted across a process restart. A subagent that already\n finished is refused outright — resume it instead of messaging it.\n- Message size is capped at 16 KiB of UTF-8 text (about 5,400 Chinese\n characters, since those take three bytes each); a longer message is rejected\n rather than truncated.\n- Keep messages short and unambiguous. The subagent sees them as a\n `[parent_messages]` block — merged into its running turn at the next step\n boundary, or at the top of its next prompt when the message waited for a turn\n start.\n- Prefer steering the *goal*, not the implementation: tell the subagent what\n changed and what to reconsider, not how to rewrite its code.\n- Do not use this tool to stop a subagent: a message is never a cancellation.\n To end its work use `TaskStop` (background tasks) or let the turn finish.\n- Do not use this tool to collect results: a subagent's completion arrives on\n its own as a notification (or as the `Agent` tool's return value in the\n foreground). Wait for that instead of polling.\n- This tool is available only to agents that may spawn subagents. Subagents\n launched with a restricted `capability_mode` (read-only / read-write /\n execute) do not have this tool — they cannot send messages or spawn further\n agents, which keeps the capability filter from being bypassed.\n";
60552
61149
  //#endregion
60553
61150
  //#region ../../packages/agent-core/src/tools/builtin/collaboration/send-subagent-message.ts
60554
61151
  /**
@@ -60564,6 +61161,8 @@ var send_subagent_message_default = "# SendSubagentMessage\n\nSend a directed me
60564
61161
  * message addressed to a child owned by a different parent is refused as
60565
61162
  * not_owned.
60566
61163
  */
61164
+ const BYTE_LIMIT_KIB = DEFAULT_BYTE_LIMIT / 1024;
61165
+ const DEADLINE_MINUTES = Math.round(SUBAGENT_MESSAGE_DEADLINE_MS / 6e4);
60567
61166
  const SendSubagentMessageInputSchema = z.object({
60568
61167
  agent_id: z.string().min(1).describe("Agent id of the target subagent, as returned by Agent."),
60569
61168
  operation: z.enum([
@@ -60571,19 +61170,25 @@ const SendSubagentMessageInputSchema = z.object({
60571
61170
  "steer",
60572
61171
  "interject"
60573
61172
  ]).describe("queue: delivered when the subagent starts its next turn, after any steer messages. steer: delivered into the subagent's running turn at its next step boundary, or first in the mailbox if no turn is running. interject: like steer, but also interrupts the tool call the subagent has in flight right now — use it to correct a subagent stuck in a long wait; it falls back to the mailbox when no turn is running."),
60574
- message: z.string().min(1).max(16384).describe("Message to deliver to the subagent.")
61173
+ message: z.string().min(1).refine((value) => new TextEncoder().encode(value).length <= DEFAULT_BYTE_LIMIT, { message: `Message must be at most ${BYTE_LIMIT_KIB} KiB of UTF-8 text.` }).describe(`Message to deliver to the subagent. At most ${BYTE_LIMIT_KIB} KiB of UTF-8 text (about 5,400 Chinese characters); a longer message is rejected.`)
60575
61174
  });
60576
61175
  const STATUS_TO_TEXT = {
60577
61176
  not_found: "No such subagent.",
60578
61177
  not_owned: "That subagent is not owned by the current agent; only the owning parent may message it.",
60579
- not_active: "The subagent already finished; messages cannot reach it. Use Agent(resume=<agent id>, prompt=<your decision>) to continue it with your reply.",
60580
- saturated: "Message rejected: the target mailbox is already holding its maximum number of undelivered messages.",
60581
- deadline_elapsed: "Message rejected: its delivery deadline elapsed before it could be sent."
61178
+ not_active: "The subagent already finished; messages cannot reach it in this session. Use Agent(resume=<agent id>, prompt=<your decision>) to continue it with your reply.",
61179
+ parent_gone: "Message refused: the parent agent that owns this session state is no longer running, so the message was not queued. Resume that agent and send the message again from there.",
61180
+ saturated: "Message rejected: the target mailbox is already holding its maximum number of undelivered messages."
60582
61181
  };
60583
61182
  const ACCEPTED_TEXT = {
60584
- "mid-run": "Message accepted and delivered into the subagent's running turn; it joins at the subagent's next step boundary.",
60585
- interjected: "Message accepted and interjected: the subagent's in-flight tool batch was interrupted so the message takes effect immediately.",
60586
- queued: "Message accepted and queued; it is delivered when the subagent starts its next turn."
61183
+ "mid-run": "Message accepted and delivered into the subagent's running turn; it joins at the subagent's next step boundary. Delivery is in-session only — nothing is persisted across a process restart.",
61184
+ interjected: "Message accepted and interjected: the subagent's in-flight tool batch was interrupted so the message takes effect immediately. Delivery is in-session only — nothing is persisted across a process restart.",
61185
+ queued: `Message accepted and queued; it is delivered when the subagent starts its next turn. Delivery is in-session and time-boxed: an undelivered message expires ${DEADLINE_MINUTES} minutes after acceptance (nothing survives a process restart; a resume in this session before the deadline can still pick it up).`
61186
+ };
61187
+ /** Why an accepted `interject` fell back to the mailbox instead of firing. */
61188
+ const DOWNGRADE_TEXT = {
61189
+ structured: "Interject downgraded to a queued message: the subagent returns a structured (JSON) answer, so its tool batch is never interrupted.",
61190
+ idle: "Interject downgraded to a queued message: no turn is running, so there is no tool batch to interrupt.",
61191
+ "steer-buffer-full": "Interject downgraded to a queued message: the subagent's steer buffer is full."
60587
61192
  };
60588
61193
  var SendSubagentMessageTool = class {
60589
61194
  subagentHost;
@@ -60599,7 +61204,7 @@ var SendSubagentMessageTool = class {
60599
61204
  approvalRule: this.name,
60600
61205
  execute: async () => {
60601
61206
  const result = this.subagentHost.sendMessage(args.agent_id, args.operation, args.message);
60602
- const reasonText = result.status === "accepted" ? `${ACCEPTED_TEXT[result.delivery ?? "queued"]}${result.duplicate === true ? " Duplicate of a message already in flight — the subagent will see it once." : ""}` : result.reason === "bytes" ? "Message rejected: it exceeds the byte limit for a single message." : STATUS_TO_TEXT[result.status] ?? result.status;
61207
+ const reasonText = result.status === "accepted" ? `${ACCEPTED_TEXT[result.delivery ?? "queued"]}${result.downgrade !== void 0 ? ` ${DOWNGRADE_TEXT[result.downgrade]}` : ""}${result.duplicate === true ? ` Duplicate of a message already in flight${result.messageId === void 0 ? "" : ` (id: ${result.messageId})`} — the subagent will see it once.` : ""}` : result.reason === "bytes" ? `Message rejected: it exceeds the ${BYTE_LIMIT_KIB} KiB UTF-8 byte limit for a single message.` : STATUS_TO_TEXT[result.status] ?? result.status;
60603
61208
  return {
60604
61209
  isError: result.status !== "accepted",
60605
61210
  output: reasonText
@@ -61655,7 +62260,7 @@ var KnowledgeLookupTool = class {
61655
62260
  };
61656
62261
  //#endregion
61657
62262
  //#region ../../packages/agent-core/src/tools/builtin/image/image-generate.md
61658
- var image_generate_default = "Generate or edit an image through the locally configured image API (OpenAI-compatible) and save the result as a PNG file. Returns the absolute path of the saved image.\n\n- `mode=new`: text-to-image generation from `prompt`.\n- `mode=edit`: rewrites the image(s) listed in `imagePaths` (at least one required).\n- `mode=continue`: edits the last image produced in the session; extra `imagePaths` are fed in as additional references.\n- `session` groups turns into one visual thread; omit it to start or join the default thread.\n- `size` defaults to the configured value (usually omitted from the request). If the service rejects an explicit size or demands one, the tool retries once on its own — no need to repeat the call.\n- The configured URL is the FULL endpoint and is used verbatim; nothing is appended. Image editing uses the configured edit URL, or derives the sibling `/images/edits` endpoint when the main URL ends in `/images/generations`.\n- Input image paths go through the same path policy as Read before any request: sensitive files (credentials, SSH keys, env files) are rejected outright, and relative paths may not escape the workspace. Rejections happen before approval and before any bytes leave the machine.\n- The API configuration lives only in a local file on this machine. When the tool reports that image generation is not configured, tell the user to run `/config image` and retry after they finish — never ask for, repeat, or log an API key in the conversation.\n- Call this only after the prompt has been refined for image generation (subject, composition, style, lighting, aspect ratio).\n";
62263
+ var image_generate_default = "Generate or edit an image through the locally configured image API (OpenAI-compatible) and save the result as a PNG file. Returns the absolute path of the saved image.\n\n- `mode=new`: text-to-image generation from `prompt`.\n- `mode=edit`: rewrites the image(s) listed in `imagePaths` (at least one required).\n- `mode=continue`: edits the last image produced in the session; extra `imagePaths` are fed in as additional references.\n- `session` groups turns into one visual thread; omit it to start or join the default thread.\n- `size` defaults to the configured value (usually omitted from the request). If the service rejects an explicit size or demands one, the tool retries once on its own — no need to repeat the call.\n- The configured URL is the FULL endpoint and is used verbatim; nothing is appended. Image editing uses the configured edit URL, or derives the sibling `/images/edits` endpoint when the main URL ends in `/images/generations`.\n- Input image paths go through the same path policy as Read before any request: sensitive files (credentials, SSH keys, env files) are rejected outright, and relative paths may not escape the workspace. Rejections happen before approval and before any bytes leave the machine.\n- The API configuration lives only in a local file on this machine. When the tool reports that image generation is not configured, tell the user to run `/config image` and retry after they finish — never ask for, repeat, or log an API key in the conversation.\n- Call this with the prompt passed through unchanged: use the user's own wording — do not rewrite, expand, or add style/lighting/composition details. Size and aspect-ratio needs belong in `size`. Refine the prompt only when the user explicitly asks for a rewrite.\n";
61659
62264
  //#endregion
61660
62265
  //#region ../../packages/agent-core/src/tools/builtin/image/image-generate.ts
61661
62266
  /**
@@ -61684,7 +62289,7 @@ const ImageGenerateInputSchema = z.object({
61684
62289
  "edit",
61685
62290
  "continue"
61686
62291
  ]).describe("new = text-to-image, edit = rewrite imagePaths, continue = edit the session's last image."),
61687
- prompt: z.string().min(1).describe("The refined image-generation prompt."),
62292
+ prompt: z.string().min(1).describe("The image-generation prompt exactly as the user wrote it."),
61688
62293
  imagePaths: z.array(z.string()).optional().describe("Absolute or workspace-relative image paths. Required for mode=edit."),
61689
62294
  session: z.string().optional().describe("Visual thread name. Omit to start/join the default thread."),
61690
62295
  size: z.string().optional().describe("Requested size for the model, e.g. \"1024x1024\" or \"1536x1024\". Pick one from the user's aspect-ratio need; omit to use the configured default.")
@@ -61716,7 +62321,7 @@ var ApiError = class extends Error {
61716
62321
  this.name = "ApiError";
61717
62322
  }
61718
62323
  };
61719
- function isPlaceholder(value) {
62324
+ function isPlaceholder$1(value) {
61720
62325
  const trimmed = value.trim();
61721
62326
  return trimmed.length === 0 || trimmed.includes("replace-with") || trimmed.startsWith("<") && trimmed.endsWith(">");
61722
62327
  }
@@ -61738,11 +62343,11 @@ async function loadConfig(screamHomeDir) {
61738
62343
  try {
61739
62344
  const text = await readFile(join$1(screamHomeDir, "image-config.json"), "utf8");
61740
62345
  const parsed = JSON.parse(text);
61741
- const legacyUrl = typeof parsed.base_url === "string" && !isPlaceholder(parsed.base_url) ? `${normalizeUrl(parsed.base_url)}${GENERATIONS_SUFFIX}` : "";
61742
- const urlRaw = typeof parsed.url === "string" && !isPlaceholder(parsed.url) ? parsed.url : legacyUrl;
61743
- if (urlRaw.length === 0 || typeof parsed.api_key !== "string" || typeof parsed.model !== "string" || isPlaceholder(parsed.api_key)) return;
61744
- const legacyEdit = typeof parsed.edit_base_url === "string" && !isPlaceholder(parsed.edit_base_url) ? `${normalizeUrl(parsed.edit_base_url)}${EDITS_SUFFIX}` : "";
61745
- const editUrlRaw = typeof parsed.edit_url === "string" && !isPlaceholder(parsed.edit_url) ? parsed.edit_url : legacyEdit;
62346
+ const legacyUrl = typeof parsed.base_url === "string" && !isPlaceholder$1(parsed.base_url) ? `${normalizeUrl(parsed.base_url)}${GENERATIONS_SUFFIX}` : "";
62347
+ const urlRaw = typeof parsed.url === "string" && !isPlaceholder$1(parsed.url) ? parsed.url : legacyUrl;
62348
+ if (urlRaw.length === 0 || typeof parsed.api_key !== "string" || typeof parsed.model !== "string" || isPlaceholder$1(parsed.api_key)) return;
62349
+ const legacyEdit = typeof parsed.edit_base_url === "string" && !isPlaceholder$1(parsed.edit_base_url) ? `${normalizeUrl(parsed.edit_base_url)}${EDITS_SUFFIX}` : "";
62350
+ const editUrlRaw = typeof parsed.edit_url === "string" && !isPlaceholder$1(parsed.edit_url) ? parsed.edit_url : legacyEdit;
61746
62351
  const editModelRaw = typeof parsed.edit_model === "string" ? parsed.edit_model : "";
61747
62352
  return {
61748
62353
  provider: typeof parsed.provider === "string" ? parsed.provider : "openai-compatible",
@@ -65155,7 +65760,7 @@ const DREAM_SKILL = {
65155
65760
  };
65156
65761
  //#endregion
65157
65762
  //#region ../../packages/agent-core/src/skill/builtin/image.md
65158
- var image_default = "---\nname: image\ndescription: 生图/改图/图生图 — 把需求或已有图片变成新图(触发词:做图、做海报、生图、生成图片、图生图、改图、画一张、画个、出图、把图改成)\n---\n\n# Image: 生图工作流\n\n用户想生成或修改图片。你的职责:把模糊需求加工成高质量生图 prompt,然后通过 `ImageGenerate` 工具完成生成,最后把图片路径交给用户。\n\n## 第一步:直接进入工作流(不要为检查配置单独调用)\n\n不要为了\"测试配置\"而发起一次 `ImageGenerate`——配置正常时那会真的生成一张废图、白花额度。\n正确顺序:**先完成第二、三步的模式判定与 prompt 优化,再发起真实的生成调用。**\n\n如果真实调用返回\"未配置\"错误:\n\n1. 回复用户:「生图 API 尚未配置,请输入 `/config image` 完成配置(选服务商 → 填 URL → 填 APIKey → 填模型)。配置完成后告诉我,我会**自动继续**刚才的请求。」\n2. **不要**询问、索要、或接受 APIKey —— 密钥只走 `/config image` 的本地对话框,绝不进入对话。\n3. 用户说配置完成后,直接重试生图,**让用户重述需求**是失败的体验。\n\n## 第二步:判定模式\n\n| 情形 | mode | 参数 |\n|---|---|---|\n| 纯文字要一张新图 | `new` | 优化后的 prompt |\n| 用户消息带了图片附件,要改它 | `edit` | `imagePaths: [附件路径]` |\n| \"继续改上一张 / 再改改\" | `continue` | 用会话里上一张输出 |\n| 说要\"改\"但上下文没有图 | **先问图** | 请用户发图或给文件路径,不要瞎猜 |\n\n- 附件路径以消息中实际出现的文件路径为准;拿不到路径就向用户要。\n- 路径规则与 Read 相同:**敏感文件(密钥/凭证/env)会被工具直接拒绝**,相对路径不得逃出工作区——遇到这类报错就告诉用户换一张图,不要绕过工具。\n- 想出多张变体:同一 `session` 连续调用多次 `new`,prompt 每次换一个变体方向。\n\n## 第三步:优化 prompt(这是你的核心价值)\n\n把用户的粗糙需求加工成完整五要素,**输出优化后的 prompt 再调工具**(让用户看到你加了什么):\n\n1. **主体**:谁/什么,动作、表情、材质\n2. **构图**:视角、景别、主体位置\n3. **风格**:摄影/插画/3D/像素/水彩……写实 or 扁平\n4. **光照**:自然光/棚拍/霓虹/逆影/黄金时刻\n5. **用途与比例**:头像 1:1、壁纸 16:9、海报 3:4 ——并按需把比例翻译成 `size` 参数\n\n**常用比例 → size 建议**(模型不支持的档位会被自动降级兜底,无需你重试):\n\n| 用途 | 比例 | size |\n|---|---|---|\n| 头像 / 图标 | 1:1 | `1024x1024` |\n| 壁纸 / 横版插画 | 16:9 | `1536x1024`(竖版反向 `1024x1536`) |\n| 海报 / 人像 | 3:4 | `1024x1536` |\n| 不确定 / 用户没提 | — | **不传**(留空最安全,服务端会用默认档) |\n\n改图(edit/continue)用不变量模板:**\"以所附图片为底,保留主体与构图,只改 X\"** ——不要重写与需求无关的部分。\n\n示例:\n- 用户:\"画一只猫\" →\n `一只橘猫蹲坐在旧书桌上,侧逆光勾勒毛发轮廓,浅景深,背景是虚化的咖啡馆暖光,胶片摄影风格,16:9 桌面壁纸`\n- 用户(对上一张图):\"改成夜景\" →\n `以所附图片为底,保留主体、构图与机位,仅将场景光照替换为夜景:冷调月光、远处暖色路灯、天空压暗,其余细节不变`\n\n## 第四步:调用与产出\n\n1. 调 `ImageGenerate`,参数带上优化后的 prompt、正确的 mode、必要时指定 `session`。\n2. 成功后向用户展示:**图片绝对路径** + 一句你加工了什么。建议用户用图片查看能力打开确认。\n3. 失败(网络/HTTP/无图数据):把错误要点转述给用户,给出「换个时段 / 检查 `/config image` 的 URL 与模型」两类排查方向,不要重复粘贴原始堆栈。\n\n## 安全红线\n\n- **永远不要**在回复、日志、示例里回显 APIKey;工具结果里也不会出现它。\n- 用户在聊天里粘贴密钥:拒绝使用,引导其 `/config image` 重新输入,并建议他作废已泄露的 key。\n- 不要绕过 `ImageGenerate` 用 Bash 直接 curl 生图接口 —— 那会把密钥暴露给 shell 历史与输出。\n";
65763
+ var image_default = "---\nname: image\ndescription: 生图/改图/图生图 — 把需求或已有图片变成新图(触发词:做图、做海报、生图、生成图片、图生图、改图、画一张、画个、出图、把图改成)\n---\n\n# Image: 生图工作流\n\n用户想生成或修改图片。你的职责:把用户的提示词**原样**交给 `ImageGenerate`(内容完全以用户为主、不作发挥),只处理参数类事项(模式 / 尺寸 等),最后把图片路径交给用户。\n\n## 第一步:直接进入工作流(不要为检查配置单独调用)\n\n不要为了\"测试配置\"而发起一次 `ImageGenerate`——配置正常时那会真的生成一张废图、白花额度。\n正确顺序:**先完成第二、三步的模式判定与 prompt 准备,再发起真实的生成调用。**\n\n如果真实调用返回\"未配置\"错误:\n\n1. 回复用户:「生图 API 尚未配置,请输入 `/config image` 完成配置(选服务商 → 填 URL → 填 APIKey → 填模型)。配置完成后告诉我,我会**自动继续**刚才的请求。」\n2. **不要**询问、索要、或接受 APIKey —— 密钥只走 `/config image` 的本地对话框,绝不进入对话。\n3. 用户说配置完成后,直接重试生图,**让用户重述需求**是失败的体验。\n\n## 第二步:判定模式\n\n| 情形 | mode | 参数 |\n|---|---|---|\n| 纯文字要一张新图 | `new` | 用户的 prompt(内容零发挥,见第三步) |\n| 用户消息带了图片附件,要改它 | `edit` | `imagePaths: [附件路径]` |\n| \"继续改上一张 / 再改改\" | `continue` | 用会话里上一张输出 |\n| 说要\"改\"但上下文没有图 | **先问图** | 请用户发图或给文件路径,不要瞎猜 |\n\n- 附件路径以消息中实际出现的文件路径为准;拿不到路径就向用户要。\n- 路径规则与 Read 相同:**敏感文件(密钥/凭证/env)会被工具直接拒绝**,相对路径不得逃出工作区——遇到这类报错就告诉用户换一张图,不要绕过工具。\n- 想出多张变体:同一 `session` 连续调用多次 `new`,prompt 每次换一个变体方向。\n\n## 第三步:prompt 以用户为主(内容零发挥)\n\n生图模型自己就懂提示词——**不要替用户加工**:\n\n1. **原样直传**:用户给什么就输入什么;用户给了详细提示词就**一字不改**,不加主体细节、不加风格 / 光照 / 构图。\n2. **最多微微调**:仅修明显的笔误 / 病句,不碰元素与语义。\n3. **含糊也直传**:\"画一只猫\" 就输入 `画一只猫`——品种、场景、风格由模型自行诠释,不要替用户补全。\n4. **用户明确要求优化时**才优化,按其要求来;skill 不主动代劳、不主动加料。\n\n**参数类才是你要优化的**——尺寸 / 比例、mode 等;用户没提就留空用默认,不瞎猜。\n\n**常用比例 → size 建议**(模型不支持的档位会被自动降级兜底,无需你重试):\n\n| 用途 | 比例 | size |\n|---|---|---|\n| 头像 / 图标 | 1:1 | `1024x1024` |\n| 壁纸 / 横版插画 | 16:9 | `1536x1024`(竖版反向 `1024x1536`) |\n| 海报 / 人像 | 3:4 | `1024x1536` |\n| 不确定 / 用户没提 | — | **不传**(留空最安全,服务端会用默认档) |\n\n**带文字的物料(海报等):文字交给模型**——把用户给的**全部文案写进提示词**(一字不改),由模型完成排版与生成;**禁止**\"先生成底图、再用任何工具加字 / 合成 / 后处理\"。用户没给文案就先向用户要,不要自己编。\n\n**改图(edit / continue):同样不套模板**——直接把用户原话作为 prompt、附上图片即可;不要添加用户没说的约束。\n\n示例:\n- 用户:\"画一只猫\" → prompt 就是 `画一只猫`(品种 / 场景 / 风格由模型自行诠释)\n- 用户:\"做一张竖版海报,主标题『春日特惠』,副标题『全场五折』,暖色调\" → prompt 包含上述原文与全部文案,**一次生成**;不要先生成底图再加字\n- 用户(对上一张图):\"改成夜景\" → prompt 就是 `改成夜景` + 附图\n\n## 第四步:调用与产出\n\n1. 调 `ImageGenerate`:prompt 用**用户的提示词**(内容零发挥)、正确的 mode、按需的尺寸参数,必要时指定 `session`。\n2. 成功后向用户展示:**图片绝对路径**;如参数层有可说明的(尺寸等)就顺带一句,**不要汇报\"我加工 / 优化了什么\"**。建议用户用图片查看能力打开确认。\n3. 失败(网络/HTTP/无图数据):把错误要点转述给用户,给出「换个时段 / 检查 `/config image` 的 URL 与模型」两类排查方向,不要重复粘贴原始堆栈。\n\n## 安全红线\n\n- **永远不要**在回复、日志、示例里回显 APIKey;工具结果里也不会出现它。\n- 用户在聊天里粘贴密钥:拒绝使用,引导其 `/config image` 重新输入,并建议他作废已泄露的 key。\n- 不要绕过 `ImageGenerate` 用 Bash 直接 curl 生图接口 —— 那会把密钥暴露给 shell 历史与输出。\n";
65159
65764
  //#endregion
65160
65765
  //#region ../../packages/agent-core/src/skill/builtin/image.ts
65161
65766
  const PSEUDO_PATH$1 = "builtin://image";
@@ -67409,8 +68014,7 @@ const BackgroundConfigSchema = z.object({
67409
68014
  maxRunningTasks: z.number().int().min(1).optional(),
67410
68015
  keepAliveOnExit: z.boolean().optional(),
67411
68016
  killGracePeriodMs: z.number().int().min(0).optional(),
67412
- agentTaskTimeoutS: z.number().int().min(1).optional(),
67413
- printWaitCeilingS: z.number().int().min(1).optional()
68017
+ agentTaskTimeoutS: z.number().int().min(1).optional()
67414
68018
  });
67415
68019
  const HookDefSchema = z.object({
67416
68020
  event: z.enum(HOOK_EVENT_TYPES),
@@ -69571,10 +70175,13 @@ var WolfPackTool = class {
69571
70175
  this.log = options?.log;
69572
70176
  this.allowedSpawns = options?.allowedSpawns;
69573
70177
  this.timeoutMs = options?.timeoutMs ?? DEFAULT_SUBAGENT_TIMEOUT_MS;
70178
+ this.spawnDepth = options?.spawnDepth ?? (() => 0);
69574
70179
  }
69575
70180
  log;
69576
70181
  allowedSpawns;
69577
70182
  timeoutMs;
70183
+ /** Reads the calling agent's spawn depth for the nesting gate. */
70184
+ spawnDepth;
69578
70185
  resolveExecution(args) {
69579
70186
  return {
69580
70187
  description: `WolfPack: ${args.description} (${args.items.length} agents)`,
@@ -69600,6 +70207,11 @@ var WolfPackTool = class {
69600
70207
  output: `Cannot spawn "${profileName}" via WolfPack. Allowed subagents: ${this.allowedSpawns.join(", ")}.`,
69601
70208
  isError: true
69602
70209
  };
70210
+ const depth = this.spawnDepth();
70211
+ if (depth >= 3) return {
70212
+ output: spawnDepthLimitRefusal(depth),
70213
+ isError: true
70214
+ };
69603
70215
  const template = args.prompt_template;
69604
70216
  const handlePromises = args.items.map(async (item) => {
69605
70217
  ctx.signal.throwIfAborted();
@@ -78334,7 +78946,7 @@ var ScriptTool = class {
78334
78946
  signal: ctx.signal,
78335
78947
  store: this.store.get("scriptStore") ?? {}
78336
78948
  });
78337
- if (!result.ok) return await this.failedResult(result.error, result.output, state);
78949
+ if (!result.ok) return await this.failedResult(result.error, result.output, state, parsed.options);
78338
78950
  this.commitStoreWrites(result.storeWrites);
78339
78951
  return await this.successResult(result.output, result.value, state, parsed.options);
78340
78952
  } finally {
@@ -78397,7 +79009,7 @@ var ScriptTool = class {
78397
79009
  async successResult(output, value, state, options) {
78398
79010
  const textParts = output.filter((item) => item.type === "text").map((item) => item.text);
78399
79011
  if (value !== void 0) textParts.push(valueText(value));
78400
- const { shown } = await truncateOutput(textParts.join("\n"), (options.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS) * CHARS_PER_TOKEN);
79012
+ const { shown } = await truncateOutput(textParts.join("\n"), outputBudgetChars(options));
78401
79013
  const parts = [];
78402
79014
  if (shown.length > 0) parts.push({
78403
79015
  type: "text",
@@ -78416,11 +79028,11 @@ var ScriptTool = class {
78416
79028
  ...state.records.length > 0 ? { nestedCalls: state.records } : {}
78417
79029
  };
78418
79030
  }
78419
- async failedResult(error, output, state) {
79031
+ async failedResult(error, output, state, options) {
78420
79032
  const lines = [`Script failed (${error.kind}): ${error.message}`];
78421
79033
  const partial = output.filter((item) => item.type === "text").map((item) => item.text).join("\n");
78422
79034
  if (partial.length > 0) {
78423
- const { shown } = await truncateOutput(partial, DEFAULT_MAX_OUTPUT_TOKENS * CHARS_PER_TOKEN);
79035
+ const { shown } = await truncateOutput(partial, outputBudgetChars(options));
78424
79036
  lines.push("", "Partial output before the failure:", shown);
78425
79037
  }
78426
79038
  if (state.records.length > 0) lines.push(`(${state.records.length} nested call${state.records.length === 1 ? "" : "s"} ran before the failure)`);
@@ -78452,6 +79064,15 @@ function valueText(value) {
78452
79064
  }
78453
79065
  }
78454
79066
  /**
79067
+ * The script's effective output budget in characters: the `@options.max_output_tokens`
79068
+ * annotation when the script carries one, the tool default otherwise. The success path
79069
+ * and the failure path both read this single value, so the annotation cannot apply to
79070
+ * only one of them.
79071
+ */
79072
+ function outputBudgetChars(options) {
79073
+ return (options.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS) * CHARS_PER_TOKEN;
79074
+ }
79075
+ /**
78455
79076
  * Truncates to the character budget, keeping half the budget on each side
78456
79077
  * (matching the reference implementation). The full text is spilled to a
78457
79078
  * temp file and its path reported in the shown output.
@@ -78609,89 +79230,6 @@ function splitSegments(value) {
78609
79230
  //#region ../../packages/agent-core/src/tools/builtin/shell/bash.md
78610
79231
  var bash_default = "Execute a `{{ SHELL_NAME }}` command. Use this for shell semantics — pipes, env, processes, git, package managers, build/test runners, anything genuinely interactive or multi-step.\n\n**Translate these to a dedicated tool instead:**\n- `cat` / `head` / `tail` (known path) → `Read`\n- `sed` / `awk` (in-place edit) → `Edit`\n- `echo > file` / `cat <<EOF` → `Write`\n- `find` / recursive `ls` to locate files by name pattern → `Glob` (plain `ls <known-directory>` is fine for listing a directory)\n- `grep` / `rg` (search file contents) → `Grep`\n- `echo` / `printf` (talk to the user) → just output text directly\n\nThe dedicated tools render in the per-tool permission UI and keep raw stdout out of the conversation; that is why they are worth reaching for whenever one fits.\n\n**Output:**\nThe stdout and stderr will be combined and returned as a string. The output may be truncated if it is too long. If the command failed, the output will end with a `Command failed with exit code: N` line stating the non-zero exit code.\n\nIf `run_in_background=true`, the command will be started as a background task and this tool will return a task ID instead of waiting for command completion. When doing that, you must provide a short `description`. Background commands default to a {{ DEFAULT_BACKGROUND_TIMEOUT_S }}s timeout and `timeout` is capped at {{ MAX_BACKGROUND_TIMEOUT_S }}s; set `disable_timeout=true` only when the task should run without a timeout. You will be automatically notified when the task completes. Use `TaskOutput` for a non-blocking status/output snapshot, and only set `block=true` when you explicitly want to wait for completion. Use `TaskStop` only if the task must be cancelled. If a human user wants to inspect background tasks themselves, point them to the `/tasks` command, which opens an interactive panel; it has no subcommands.\n\n**Guidelines for safety and security:**\n- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls.\n- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the `timeout` argument in seconds. Foreground commands default to {{ DEFAULT_TIMEOUT_S }}s and allow up to {{ MAX_TIMEOUT_S }}s.\n- Avoid using `..` to access files or directories outside of the working directory.\n- Avoid modifying files outside of the working directory unless explicitly instructed to do so.\n- Never run commands that require superuser privileges unless explicitly instructed to do so.\n\n**Guidelines for efficiency:**\n{%- if SHELL_IS_POWERSHELL %}\n- Chain with `;` to run commands sequentially. `&&` / `||` only exist from PowerShell 7 and are a parse error on Windows PowerShell 5.1, so do not use them; write `; if ($?) { … }` when the next step must run only if the previous one succeeded.\n- Filter and transform with pipelines (`Get-ChildItem | Where-Object …`); redirect with `>` / `>>`.\n- Quote paths containing spaces with single quotes, e.g. `Set-Location 'C:\\Program Files'`.\n- Read environment variables as `$env:NAME` (`$env:NAME = 'value'`), never `$NAME`.\n- Compose multi-step logic in a single call with `if` / `foreach` / `while` and `try` / `catch`.\n{%- else %}\n- For multiple related commands, use `&&` to chain them in a single call, e.g. `cd /path && ls -la`\n- Use `;` to run commands sequentially regardless of success/failure\n- Use `||` for conditional execution (run second command only if first fails)\n- Use pipe operations (`|`) and redirections (`>`, `>>`) to chain input and output between commands\n- Always quote file paths containing spaces with double quotes (e.g., cd \"/path with spaces/\")\n- Compose multi-step logic in a single call with `if` / `case` / `for` / `while` control flows.\n{%- endif %}\n- Prefer `run_in_background=true` for long-running builds, tests, watchers, or servers when you need the conversation to continue before the command finishes.\n\n**Commands available:**\nThe following common command categories are usually available. Availability still depends on the host, so when in doubt {% if SHELL_IS_POWERSHELL %}confirm a command exists with `Get-Command <name> -ErrorAction SilentlyContinue` before relying on it — several names below are cmdlet aliases (`ls` → `Get-ChildItem`, `rm` → `Remove-Item`), and POSIX-only entries such as `uname`, `chmod` and `kill` may be absent.{% else %}run `which <command>` first to confirm a command exists before relying on it.{% endif %}\n- Navigation and inspection: `ls`, `pwd`, `cd`, `stat`, `file`, `du`, `df`, `tree`\n- File and directory management: `cp`, `mv`, `rm`, `mkdir`, `touch`, `ln`, `chmod`, `chown`\n- Text and data processing: `wc`, `sort`, `uniq`, `cut`, `tr`, `diff`, `xargs`\n- Archives and compression: `tar`, `gzip`, `gunzip`, `zip`, `unzip`\n- Networking and transfer: `curl`, `wget`, `ping`, `ssh`, `scp`\n- Version control: `git`\n- Process and system: `ps`, `kill`, `top`, `env`, `date`, `uname`, `whoami`\n- Language and package toolchains: `node`, `npm`, `pnpm`, `yarn`, `python`, `pip` (use whichever the project actually relies on)\n";
78611
79232
  //#endregion
78612
- //#region ../../packages/agent-core/src/tools/builtin/shell/background-tasks.ts
78613
- /**
78614
- * Lightweight store for foreground Bash commands that were moved to
78615
- * background on timeout. The process continues running; when it exits
78616
- * the result is stored here and surfaced to the model on the next Bash
78617
- * call.
78618
- *
78619
- * This is intentionally simple - it does NOT use the full
78620
- * BackgroundProcessManager (which assumes it owns the process streams
78621
- * from spawn). Here the streams are already being read by the
78622
- * foreground ToolResultBuilder, so we just wrap the pending
78623
- * completion promise.
78624
- */
78625
- const pendingTasks = /* @__PURE__ */ new Map();
78626
- const MAX_PENDING = 10;
78627
- function createBackgroundTask(command, completion, handles) {
78628
- const id = randomUUID().slice(0, 8);
78629
- const task = {
78630
- command,
78631
- startedAt: Date.now(),
78632
- completion,
78633
- kill: handles.kill,
78634
- pid: handles.pid,
78635
- ownerId: handles.ownerId
78636
- };
78637
- if (pendingTasks.size >= MAX_PENDING) {
78638
- const oldest = pendingTasks.keys().next().value;
78639
- if (oldest !== void 0) {
78640
- const evicted = pendingTasks.get(oldest);
78641
- pendingTasks.delete(oldest);
78642
- if (evicted !== void 0) evicted.kill();
78643
- }
78644
- }
78645
- pendingTasks.set(id, task);
78646
- task.completion.then((result) => {
78647
- task.result = result;
78648
- }, () => {
78649
- task.result = {
78650
- exitCode: -1,
78651
- output: "Background process failed."
78652
- };
78653
- });
78654
- return id;
78655
- }
78656
- /**
78657
- * Collect results from background tasks that have completed since the
78658
- * last check. Each completed task is returned once and then removed.
78659
- */
78660
- function drainCompletedBackgroundTasks() {
78661
- const completed = [];
78662
- for (const [id, task] of pendingTasks) if (task.result !== void 0) {
78663
- completed.push({
78664
- id,
78665
- command: task.command,
78666
- exitCode: task.result.exitCode,
78667
- output: task.result.output,
78668
- elapsedMs: Date.now() - task.startedAt
78669
- });
78670
- pendingTasks.delete(id);
78671
- }
78672
- return completed;
78673
- }
78674
- /**
78675
- * Kill the parked commands one owner is responsible for and clear them.
78676
- *
78677
- * Strictly owner-matched, `undefined` included: the registry is module-level
78678
- * while sessions are not, so a session teardown must reach exactly the tasks
78679
- * its own agents parked (every agent's Bash tool stamps its session id — see
78680
- * `Session.instantiateAgent`) and never another session's. The undefined match
78681
- * is a real case, not a wildcard: `SessionOptions.id` is optional, so a session
78682
- * created without an id stamps no owner, and matching it against "no owner" is
78683
- * what keeps that session's close() from executing a foreign session's command.
78684
- * Process-wide cleanup is `killAllPendingBackgroundTasks`, which only a real
78685
- * exit path may call.
78686
- */
78687
- function stopAllPendingBackgroundTasks(ownerId) {
78688
- for (const [id, task] of pendingTasks) {
78689
- if (task.ownerId !== ownerId) continue;
78690
- task.kill();
78691
- pendingTasks.delete(id);
78692
- }
78693
- }
78694
- //#endregion
78695
79233
  //#region ../../packages/agent-core/src/tools/builtin/shell/bash.ts
78696
79234
  /**
78697
79235
  * BashTool — execute shell commands.
@@ -78979,13 +79517,6 @@ var BashTool = class {
78979
79517
  shellKind;
78980
79518
  allowBackground;
78981
79519
  availableTools;
78982
- /**
78983
- * Session this tool belongs to (the owning agent's session id). A command
78984
- * that times out is parked in the module-level pending registry under this
78985
- * key, so closing one session sweeps only its own parked commands instead of
78986
- * executing every other session's running work.
78987
- */
78988
- ownerId;
78989
79520
  constructor(jian, cwd, backgroundManager, options) {
78990
79521
  this.jian = jian;
78991
79522
  this.cwd = cwd;
@@ -78995,7 +79526,6 @@ var BashTool = class {
78995
79526
  this.isWindowsBash = this.isWindows && this.shellKind === "posix";
78996
79527
  this.allowBackground = options?.allowBackground ?? this.backgroundManager !== void 0;
78997
79528
  this.availableTools = options?.availableTools ?? /* @__PURE__ */ new Set();
78998
- this.ownerId = options?.ownerId;
78999
79529
  const rendered = renderBashDescription(this.jian.osEnv.shellName, this.shellKind === "powershell");
79000
79530
  this.description = this.allowBackground ? rendered : withoutBackgroundDescription(rendered);
79001
79531
  }
@@ -79037,15 +79567,13 @@ var BashTool = class {
79037
79567
  }
79038
79568
  async execution(args, ctx) {
79039
79569
  const { signal, onUpdate } = ctx;
79040
- const completedBg = drainCompletedBackgroundTasks();
79041
- const bgPrefix = completedBg.length > 0 ? completedBg.map((t) => `[Background task ${t.id} completed] Command: ${t.command}\nExit code: ${String(t.exitCode)} (${(t.elapsedMs / 1e3).toFixed(1)}s)\nOutput:\n${t.output}\n---\n`).join("") : "";
79042
79570
  if (signal.aborted) return {
79043
79571
  isError: true,
79044
- output: bgPrefix + (isParentInterject(signal.reason) ? "Interrupted by the parent agent before the command started" : "Aborted before command started")
79572
+ output: isParentInterject(signal.reason) ? "Interrupted by the parent agent before the command started" : "Aborted before command started"
79045
79573
  };
79046
79574
  if (args.command.length === 0) return {
79047
79575
  isError: true,
79048
- output: bgPrefix + "Command cannot be empty."
79576
+ output: "Command cannot be empty."
79049
79577
  };
79050
79578
  const validationError = validateCommand(args.command, this.isWindows);
79051
79579
  if (validationError !== null) return validationError;
@@ -79076,7 +79604,12 @@ var BashTool = class {
79076
79604
  let aborted = false;
79077
79605
  let killed = false;
79078
79606
  let streaming = true;
79607
+ let parkedTaskId;
79079
79608
  const forwardChunk = (kind, text) => {
79609
+ if (parkedTaskId !== void 0) {
79610
+ this.backgroundManager?.appendCapturedOutput(parkedTaskId, text);
79611
+ return;
79612
+ }
79080
79613
  if (!streaming || signal.aborted || onUpdate === void 0) return;
79081
79614
  onUpdate({
79082
79615
  kind,
@@ -79123,7 +79656,6 @@ var BashTool = class {
79123
79656
  await writeFile(artifactPath, fullOutput, "utf8");
79124
79657
  return artifactPath;
79125
79658
  } });
79126
- if (bgPrefix.length > 0) builder.write(bgPrefix);
79127
79659
  const stdoutDone = readStreamIntoBuilder(proc.stdout, builder, (text) => forwardChunk("stdout", text));
79128
79660
  const stderrDone = readStreamIntoBuilder(proc.stderr, builder, (text) => forwardChunk("stderr", text));
79129
79661
  const stdoutSettled = stdoutDone.catch(() => void 0);
@@ -79147,38 +79679,34 @@ var BashTool = class {
79147
79679
  if (raceResult.timedOut) {
79148
79680
  streaming = false;
79149
79681
  const timeoutLabel = timeoutMs % 1e3 === 0 ? `${String(timeoutMs / 1e3)}s` : `${String(timeoutMs)}ms`;
79150
- const taskId = createBackgroundTask(command, completionPromise.then(({ exitCode }) => ({
79151
- exitCode,
79152
- output: builder.toString()
79153
- })), {
79154
- kill: killProc,
79155
- pid: proc.pid,
79156
- ownerId: this.ownerId
79157
- });
79158
- if (onUpdate !== void 0) completionPromise.then(({ exitCode }) => {
79159
- onUpdate({
79160
- kind: "custom",
79161
- customKind: "background.task.terminated",
79162
- customData: {
79163
- id: taskId,
79164
- command,
79165
- exitCode
79166
- }
79167
- });
79168
- }, () => {
79169
- onUpdate({
79170
- kind: "custom",
79171
- customKind: "background.task.terminated",
79172
- customData: {
79173
- id: taskId,
79174
- command,
79175
- exitCode: -1
79176
- }
79682
+ const manager = this.backgroundManager;
79683
+ if (manager === void 0) {
79684
+ killProc();
79685
+ return {
79686
+ isError: true,
79687
+ output: `Command timed out after ${timeoutLabel} and was stopped: this agent has no background task manager.`
79688
+ };
79689
+ }
79690
+ let parkedId;
79691
+ const trimmedDescription = args.description?.trim();
79692
+ try {
79693
+ parkedId = manager.parkForegroundProcess(completionPromise, command, trimmedDescription === void 0 || trimmedDescription.length === 0 ? command : trimmedDescription, {
79694
+ kill: () => killProc(),
79695
+ pid: proc.pid,
79696
+ initialOutput: builder.toString()
79177
79697
  });
79178
- });
79698
+ } catch (error) {
79699
+ killProc();
79700
+ return {
79701
+ isError: true,
79702
+ output: `Command timed out after ${timeoutLabel} and was stopped: could not park it as a background task (${error instanceof Error ? error.message : String(error)}).`
79703
+ };
79704
+ }
79705
+ parkedTaskId = parkedId;
79179
79706
  const outputSoFar = builder.toString();
79707
+ const nextStep = this.allowBackground ? `The task keeps running and notifies you when it finishes; TaskOutput(task_id="${parkedId}") shows its output and TaskStop(task_id="${parkedId}") cancels it.` : "The task keeps running and notifies you when it finishes.";
79180
79708
  return {
79181
- output: `Command timed out after ${timeoutLabel} but is still running in the background (task: ${taskId}).\nOutput so far (${String(builder.nChars)} chars):\n${outputSoFar}\n---\nThe command will complete in the background. The result will be included in your next Bash call.`,
79709
+ output: `Command timed out after ${timeoutLabel} but is still running in the background (task: ${parkedId}).\nOutput so far (${String(builder.nChars)} chars):\n${outputSoFar}\n---\n${nextStep}`,
79182
79710
  isError: false
79183
79711
  };
79184
79712
  }
@@ -80339,9 +80867,17 @@ var BackgroundManager = class extends BackgroundProcessManager {
80339
80867
  agent;
80340
80868
  scheduledNotificationKeys = /* @__PURE__ */ new Set();
80341
80869
  deliveredNotificationKeys = /* @__PURE__ */ new Set();
80870
+ /**
80871
+ * Session-death latch, set by `Session.close()` before it tears anything
80872
+ * down, and by a subagent's terminal release as it evicts its finished
80873
+ * owner (see `markSessionClosed`). While set, a terminal task notification
80874
+ * is dropped instead of steered — see `notifyBackgroundTask`.
80875
+ */
80876
+ sessionClosed = false;
80342
80877
  constructor(agent) {
80343
80878
  super({
80344
80879
  maxRunningTasks: agent.screamConfig?.background?.maxRunningTasks,
80880
+ killGracePeriodMs: agent.screamConfig?.background?.killGracePeriodMs,
80345
80881
  sessionDir: agent.homedir
80346
80882
  });
80347
80883
  this.agent = agent;
@@ -80368,6 +80904,50 @@ var BackgroundManager = class extends BackgroundProcessManager {
80368
80904
  }
80369
80905
  });
80370
80906
  }
80907
+ /**
80908
+ * Latch this manager so no further terminal task notification is steered
80909
+ * through it (see `notifyBackgroundTask`). Two owners set it:
80910
+ *
80911
+ * - `Session.close()` calls it for every manager the session created, before
80912
+ * any teardown runs. That single drop does both jobs: no ghost turn is
80913
+ * launched for the closing session, and the notification stays undelivered,
80914
+ * so the reconcile path (`restoreBackgroundTaskNotifications`) appends it
80915
+ * silently the next time the session is opened.
80916
+ * - The subagent host latches a child's manager when the child is evicted at
80917
+ * the end of its run. The child can no longer consume a notification, and
80918
+ * the tasks that outlive it — a parked foreground command above all —
80919
+ * would otherwise wake the evicted agent as a ghost turn. The drop is the
80920
+ * same: undelivered here, reported as `lost` by the reconcile of the
80921
+ * fresh manager a later resume builds.
80922
+ *
80923
+ * The latch has no reset counterpart on purpose: it models "this manager has
80924
+ * no live consumer left", and nothing re-registers the latched instance. A
80925
+ * closed session is discarded (the RPC layer's closeSession deletes it from
80926
+ * the active map, and a later activation constructs a new `Session`), and
80927
+ * `Session.resume()` / `ensureAgent` drop evicted agents before
80928
+ * re-instantiating them from metadata — so every reopened or resumed owner
80929
+ * runs a brand-new BackgroundManager whose latch starts unset.
80930
+ */
80931
+ markSessionClosed() {
80932
+ this.sessionClosed = true;
80933
+ }
80934
+ /**
80935
+ * Stop every non-terminal agent-class task — the tasks registered through
80936
+ * `registerAgentTask`, whose ids carry the `agent-` prefix (see
80937
+ * generateTaskId).
80938
+ *
80939
+ * `Session.close()` calls this under `keepAliveOnExit`: that switch protects
80940
+ * real bash processes, whose work stays meaningful to the user after the
80941
+ * session is gone, while an agent task is a coroutine driving a subagent turn
80942
+ * the close has already cancelled — left "alive" it can never finish on its
80943
+ * own and would strand a half-dead ledger entry that later notifies a dead
80944
+ * session. Bash tasks are deliberately untouched here; stopping those is
80945
+ * `stopAll`, the keepAlive=false path.
80946
+ */
80947
+ async stopAgentTasks(reason) {
80948
+ const taskIds = this.list().filter((info) => isAgentTaskId(info.taskId)).map((info) => info.taskId);
80949
+ return (await Promise.all(taskIds.map((taskId) => this.stop(taskId, reason)))).filter((info) => info !== void 0);
80950
+ }
80371
80951
  async reconcile() {
80372
80952
  const result = await super.reconcile();
80373
80953
  await this.restoreBackgroundTaskNotifications();
@@ -80394,8 +80974,13 @@ var BackgroundManager = class extends BackgroundProcessManager {
80394
80974
  * same boundary, each scoped to the manager's own agent.
80395
80975
  */
80396
80976
  async notifyBackgroundTask(info) {
80977
+ if (this.sessionClosed) return;
80397
80978
  const context = await this.buildBackgroundTaskNotificationContext(info);
80398
80979
  if (context === void 0) return;
80980
+ if (this.sessionClosed) {
80981
+ this.scheduledNotificationKeys.delete(notificationKey(context.origin));
80982
+ return;
80983
+ }
80399
80984
  this.agent.turn.steer(context.content, context.origin);
80400
80985
  this.fireNotificationHook(context.notification);
80401
80986
  }
@@ -80419,7 +81004,7 @@ var BackgroundManager = class extends BackgroundProcessManager {
80419
81004
  this.scheduledNotificationKeys.add(key);
80420
81005
  const tailOutput = (await this.getOutputSnapshot(info.taskId, NOTIFICATION_TAIL_BYTES)).preview;
80421
81006
  if (this.hasDeliveredNotification(origin)) return;
80422
- const isAgentTask = info.taskId.startsWith("agent-");
81007
+ const isAgentTask = isAgentTaskId(info.taskId);
80423
81008
  const label = isAgentTask ? "agent" : "task";
80424
81009
  const notification = {
80425
81010
  id: notificationId,
@@ -80459,6 +81044,27 @@ var BackgroundManager = class extends BackgroundProcessManager {
80459
81044
  markDeliveredNotification(origin) {
80460
81045
  this.deliveredNotificationKeys.add(notificationKey(origin));
80461
81046
  }
81047
+ /**
81048
+ * Export the delivered-notification keys for wire persistence. A full
81049
+ * compaction folds the notification messages these marks were derived from
81050
+ * into its summary, and the folded `context.append_message` records never
81051
+ * replay — the `context.snapshot` payload is therefore the only place a
81052
+ * resume can recover the marks from (see
81053
+ * `ContextMemoryJSONSnapshot.deliveredNotificationKeys`). Losing them makes
81054
+ * reconcile re-deliver notifications the session already saw.
81055
+ */
81056
+ exportDeliveredNotificationKeys() {
81057
+ return [...this.deliveredNotificationKeys];
81058
+ }
81059
+ /**
81060
+ * Rebuild delivered marks from a restored snapshot. Additive on purpose:
81061
+ * replay separately re-marks every notification message still present in
81062
+ * the restored history, and a key from either source suppresses re-delivery
81063
+ * — only a notification neither source knows about is appended by reconcile.
81064
+ */
81065
+ restoreDeliveredNotificationKeys(keys) {
81066
+ for (const key of keys) this.deliveredNotificationKeys.add(key);
81067
+ }
80462
81068
  hasDeliveredNotification(origin) {
80463
81069
  return this.deliveredNotificationKeys.has(notificationKey(origin));
80464
81070
  }
@@ -80479,6 +81085,13 @@ function notificationKey(origin) {
80479
81085
  return `${origin.taskId}\0${origin.status}\0${origin.notificationId}`;
80480
81086
  }
80481
81087
  /**
81088
+ * Agent-class tasks are the ones registered through `registerAgentTask`; their
81089
+ * ids carry the `agent-` prefix (generateTaskId in tools/background/manager).
81090
+ */
81091
+ function isAgentTaskId(taskId) {
81092
+ return taskId.startsWith("agent-");
81093
+ }
81094
+ /**
80482
81095
  * Build the human/LLM-readable body that lands in the `<notification>`
80483
81096
  * XML. For agent-* tasks that ended non-successfully and whose subagent id
80484
81097
  * we still know, append a paragraph telling the LLM exactly how to resume
@@ -83204,6 +83817,7 @@ var ContextMemory = class {
83204
83817
  * {@link ContextMemoryJSONSnapshot}).
83205
83818
  */
83206
83819
  toJSONSnapshot() {
83820
+ const deliveredNotificationKeys = this.agent.background.exportDeliveredNotificationKeys();
83207
83821
  return {
83208
83822
  history: [...this._history],
83209
83823
  tokenCount: this._tokenCount,
@@ -83211,7 +83825,8 @@ var ContextMemory = class {
83211
83825
  openSteps: [...this.openSteps.entries()].map(([uuid, message]) => [uuid, this._history.indexOf(message)]),
83212
83826
  pendingToolResultIds: [...this.pendingToolResultIds],
83213
83827
  deferredMessages: [...this.deferredMessages],
83214
- ...this._messageEdits.size > 0 ? { messageEdits: [...this._messageEdits.entries()] } : {}
83828
+ ...this._messageEdits.size > 0 ? { messageEdits: [...this._messageEdits.entries()] } : {},
83829
+ ...deliveredNotificationKeys.length > 0 ? { deliveredNotificationKeys } : {}
83215
83830
  };
83216
83831
  }
83217
83832
  /**
@@ -83234,6 +83849,7 @@ var ContextMemory = class {
83234
83849
  this.pendingToolResultIds = new Set(snapshot.pendingToolResultIds);
83235
83850
  this.deferredMessages = [...snapshot.deferredMessages];
83236
83851
  this._messageEdits = new Map(snapshot.messageEdits ?? []);
83852
+ this.agent.background.restoreDeliveredNotificationKeys(snapshot.deliveredNotificationKeys ?? []);
83237
83853
  for (const message of this._history) this.assignMessageId(message);
83238
83854
  for (const message of this.deferredMessages) this.assignMessageId(message);
83239
83855
  }
@@ -85857,7 +86473,6 @@ const DEFAULT_HOOK_TIMEOUT_SECONDS = 30;
85857
86473
  var HookEngine = class {
85858
86474
  options;
85859
86475
  byEvent = /* @__PURE__ */ new Map();
85860
- pendingTriggers = /* @__PURE__ */ new Set();
85861
86476
  constructor(hooks = [], options = {}) {
85862
86477
  this.options = options;
85863
86478
  for (const hook of hooks) {
@@ -85914,18 +86529,25 @@ var HookEngine = class {
85914
86529
  async triggerBlock(event, args = {}) {
85915
86530
  return blockDecision(event, await this.trigger(event, args));
85916
86531
  }
86532
+ /**
86533
+ * Fire an event without making the caller wait for it. The returned promise
86534
+ * is still awaitable by a caller that wants the results, and every failure
86535
+ * path (synchronous throw included) resolves to `[]` so a caller that drops
86536
+ * it can never produce an unhandled rejection.
86537
+ *
86538
+ * The engine keeps no bookkeeping of its own: there is no drain point for
86539
+ * in-flight fire-and-forget work (no engine lifecycle owner — the engine is
86540
+ * constructed per agent and never awaits a shutdown), so tracking the
86541
+ * promises here would be write-only state that only pins memory. The
86542
+ * per-hook timeout in `runHook` bounds the work itself, and the returned
86543
+ * promise is the handle for a caller that does want to await it.
86544
+ */
85917
86545
  fireAndForgetTrigger(event, args = {}) {
85918
- let promise;
85919
86546
  try {
85920
- promise = this.trigger(event, args).catch(() => []);
86547
+ return this.trigger(event, args).catch(() => []);
85921
86548
  } catch {
85922
- promise = Promise.resolve([]);
86549
+ return Promise.resolve([]);
85923
86550
  }
85924
- this.pendingTriggers.add(promise);
85925
- promise.finally(() => {
85926
- this.pendingTriggers.delete(promise);
85927
- });
85928
- return promise;
85929
86551
  }
85930
86552
  async triggerInner(event, args) {
85931
86553
  const matcherValue = matcherValueText(args.matcherValue);
@@ -87000,6 +87622,7 @@ const READ_TOOLS = new Set([
87000
87622
  "Read",
87001
87623
  "ReadGroup",
87002
87624
  "ReadMediaFile",
87625
+ "ReportArchFinding",
87003
87626
  "ReportFinding",
87004
87627
  "Skill",
87005
87628
  "TodoList",
@@ -87075,6 +87698,135 @@ const DEFAULT_AUTO_APPROVE_TOOLS = new Set([
87075
87698
  "MakeSkillApply"
87076
87699
  ]);
87077
87700
  //#endregion
87701
+ //#region ../../packages/agent-core/src/session/subagent-capability.ts
87702
+ /**
87703
+ * Subagent capability modes and their tool-set policy.
87704
+ *
87705
+ * Capability modes (read-only / read-write / execute / all): a mode is
87706
+ * enforced at the tool level, not just by prompting. `all` keeps the profile's
87707
+ * full tool set; stricter modes strip it down to the tools the mode permits.
87708
+ *
87709
+ * Tool classification is by name; the sets live in `#/tools/tool-catalog`
87710
+ * (shared with the permission policies) so a new tool is classified once.
87711
+ * Names the catalog does not classify are refused in every restricted mode
87712
+ * (fail-closed): a tool nobody classified must not survive a trim by virtue
87713
+ * of being unknown. MCP tools are refused for the same reason — their
87714
+ * read/write/execute nature cannot be read off the name.
87715
+ */
87716
+ /** Tool names each restricted mode permits, built once at module load: the
87717
+ * membership test runs for every active tool at spawn and for every tool call
87718
+ * the runtime permission gate inspects. */
87719
+ const ALLOWED_TOOLS_BY_MODE = {
87720
+ "read-only": union(READ_TOOLS, CORE_TOOLS),
87721
+ "read-write": union(READ_TOOLS, WRITE_TOOLS, CORE_TOOLS),
87722
+ execute: union(READ_TOOLS, WRITE_TOOLS, EXECUTE_TOOLS, CORE_TOOLS)
87723
+ };
87724
+ /**
87725
+ * Whether a tool may be used under `mode` — the single membership test shared
87726
+ * by the spawn-time trim (`filterToolsForCapability`) and the runtime
87727
+ * permission gate (`agent/permission/policies/capability-guard-deny`), so what
87728
+ * the model sees and what may actually run can never disagree.
87729
+ *
87730
+ * Fail-closed: `all` allows everything; every restricted mode refuses MCP
87731
+ * tools and any name the catalog does not classify.
87732
+ */
87733
+ function isToolAllowedForCapability(name, mode) {
87734
+ if (mode === "all") return true;
87735
+ if (NESTING_TOOLS.has(name)) return false;
87736
+ if (name.startsWith("mcp__")) return false;
87737
+ return ALLOWED_TOOLS_BY_MODE[mode].has(name);
87738
+ }
87739
+ /**
87740
+ * Filter an active tool-name list down to what `mode` permits. `all` returns
87741
+ * the input unchanged. Restricted modes drop every name outside the mode's
87742
+ * set, unclassified names included (fail-closed — classify the tool in
87743
+ * `#/tools/tool-catalog` to admit it to a restricted child).
87744
+ */
87745
+ function filterToolsForCapability(activeTools, mode) {
87746
+ if (mode === void 0 || mode === "all") return [...activeTools];
87747
+ return activeTools.filter((name) => isToolAllowedForCapability(name, mode));
87748
+ }
87749
+ function union(...sets) {
87750
+ const out = /* @__PURE__ */ new Set();
87751
+ for (const s of sets) for (const v of s) out.add(v);
87752
+ return out;
87753
+ }
87754
+ /** Strictness order: earlier = narrower (fewer tools permitted). */
87755
+ const CAPABILITY_ORDER = [
87756
+ "read-only",
87757
+ "read-write",
87758
+ "execute",
87759
+ "all"
87760
+ ];
87761
+ /**
87762
+ * The narrower of two capability modes (`read-only` < `read-write` < `execute`
87763
+ * < `all`). Resume uses this to clamp: a resumed agent keeps the tool set it
87764
+ * already has (its profile is not rebuilt), so its contract may be re-applied
87765
+ * or tightened, never widened.
87766
+ */
87767
+ function narrowerCapability(a, b) {
87768
+ return CAPABILITY_ORDER.indexOf(a) <= CAPABILITY_ORDER.indexOf(b) ? a : b;
87769
+ }
87770
+ /**
87771
+ * Infer the strictest capability mode that already permits `activeTools` — the
87772
+ * first mode whose `filterToolsForCapability` pass removes nothing, else `all`.
87773
+ *
87774
+ * Used when resuming a session recorded before `AgentMeta.capabilityMode`
87775
+ * existed: filtering is pure subtraction, so a tool set that survives
87776
+ * `read-only` unchanged is evidence the agent was never granted more than
87777
+ * that. The inference can only be too *narrow* (a set that happens to contain
87778
+ * only allowed tools), which is the safe direction for a capability clamp —
87779
+ * and an unclassified name can never be inferred into a restricted mode,
87780
+ * because every restricted mode drops it (fail-closed).
87781
+ */
87782
+ function inferCapabilityFromTools(activeTools) {
87783
+ for (const mode of CAPABILITY_ORDER) {
87784
+ if (mode === "all") break;
87785
+ if (filterToolsForCapability(activeTools, mode).length === activeTools.length) return mode;
87786
+ }
87787
+ return "all";
87788
+ }
87789
+ //#endregion
87790
+ //#region ../../packages/agent-core/src/agent/permission/policies/capability-guard-deny.ts
87791
+ /**
87792
+ * Hard capability gate for restricted subagents.
87793
+ *
87794
+ * `read-only` / `read-write` / `execute` are enforced twice: the spawn-time
87795
+ * trim (`filterToolsForCapability`) removes what the model SEES, and this
87796
+ * policy refuses what may RUN. A call can still arrive for a tool that is not
87797
+ * in the active list (a replayed turn, a plugin-provided name, a stale
87798
+ * schema), and an approval policy later in the chain must never widen a
87799
+ * restricted contract — the parent may spawn the child restricted, but the
87800
+ * child itself cannot talk its way past the trim.
87801
+ *
87802
+ * Both sides ask `isToolAllowedForCapability`, so visibility and execution
87803
+ * cannot drift: an unclassified tool name is refused here exactly as it is
87804
+ * stripped there, and MCP tools stay fail-closed.
87805
+ *
87806
+ * The mode is read off the asking agent instance (`all` for main agents and
87807
+ * unrestricted subagents, so this policy is inert for them). Because the
87808
+ * refusal lives in the permission layer rather than in each tool, it also
87809
+ * covers tools that keep a conditional write path (e.g. LSP rename with
87810
+ * `apply: true`) without every such tool re-implementing the check.
87811
+ */
87812
+ var CapabilityGuardDenyPermissionPolicy = class {
87813
+ agent;
87814
+ name = "capability-guard-deny";
87815
+ constructor(agent) {
87816
+ this.agent = agent;
87817
+ }
87818
+ evaluate(context) {
87819
+ const mode = this.agent.getCapabilityMode();
87820
+ if (mode === "all") return void 0;
87821
+ const toolName = context.toolCall.name;
87822
+ if (isToolAllowedForCapability(toolName, mode)) return void 0;
87823
+ return {
87824
+ kind: "deny",
87825
+ message: `Tool "${toolName}" is not available to this agent: it runs under the "${mode}" capability contract, which permits only a fixed tool set. Do not retry the call or try to reach the same effect another way — report back to the parent agent instead (ContactParent); the parent can re-dispatch the work with a wider contract if it is needed.`
87826
+ };
87827
+ }
87828
+ };
87829
+ //#endregion
87078
87830
  //#region ../../packages/agent-core/src/agent/permission/policies/default-tool-approve.ts
87079
87831
  var DefaultToolApprovePermissionPolicy = class {
87080
87832
  name = "default-tool-approve";
@@ -87676,6 +88428,7 @@ var WolfPackModeApprovePermissionPolicy = class {
87676
88428
  function createPermissionDecisionPolicies(agent) {
87677
88429
  return [
87678
88430
  new PreToolCallHookPermissionPolicy(agent),
88431
+ new CapabilityGuardDenyPermissionPolicy(agent),
87679
88432
  new AutoModeAskUserQuestionDenyPermissionPolicy(agent),
87680
88433
  new PlanModeGuardDenyPermissionPolicy(agent),
87681
88434
  new AskModeGuardDenyPermissionPolicy(agent),
@@ -87810,6 +88563,15 @@ var PermissionManager = class {
87810
88563
  };
87811
88564
  const action = context.execution.description ?? `Call ${name}`;
87812
88565
  const startedAt = Date.now();
88566
+ const sourceAgentId = this.agent.agentId;
88567
+ const sourceAgentName = this.agent.config.profileName;
88568
+ const sourceCapabilityMode = this.agent.getCapabilityMode();
88569
+ const source = {
88570
+ sourceAgentId,
88571
+ ...sourceAgentName !== void 0 ? { sourceAgentName } : {},
88572
+ ...sourceCapabilityMode !== "all" ? { sourceCapabilityMode } : {},
88573
+ sourceToolName: name
88574
+ };
87813
88575
  let response;
87814
88576
  if (this.agent.rpc?.requestApproval) {
87815
88577
  const approvalId = `approval-${String(++this.nextApprovalId)}`;
@@ -87832,7 +88594,8 @@ var PermissionManager = class {
87832
88594
  toolCallId: id,
87833
88595
  toolName: name,
87834
88596
  action,
87835
- display
88597
+ display,
88598
+ ...source
87836
88599
  }, { signal }).then(resolve, reject);
87837
88600
  });
87838
88601
  const timeoutPromise = new Promise((_, reject) => {
@@ -103869,8 +104632,7 @@ var ToolManager = class {
103869
104632
  new GlobTool(jian, workspace),
103870
104633
  new BashTool(jian, cwd, background, {
103871
104634
  allowBackground,
103872
- availableTools: this.enabledTools,
103873
- ownerId: this.agent.sessionId
104635
+ availableTools: this.enabledTools
103874
104636
  }),
103875
104637
  pythonTool,
103876
104638
  new ScriptTool(this.toolStore),
@@ -103907,14 +104669,16 @@ var ToolManager = class {
103907
104669
  canSpawn && new AgentTool(this.agent.subagentHost, background, visibleSubagents, {
103908
104670
  allowBackground,
103909
104671
  log: this.agent.log,
103910
- allowedSpawns
104672
+ allowedSpawns,
104673
+ spawnDepth: () => this.agent.getRlmDepth()
103911
104674
  }),
103912
104675
  canSpawn && new SendSubagentMessageTool(this.agent.subagentHost),
103913
104676
  this.agent.type === "sub" && this.agent.ownerHost !== void 0 && new ContactParentTool(this.agent.ownerHost, () => this.agent),
103914
104677
  canSpawn && new WolfPackTool(this.agent.subagentHost, () => this.agent.wolfpackMode.isActive, {
103915
104678
  subagents: visibleSubagents,
103916
104679
  log: this.agent.log,
103917
- allowedSpawns
104680
+ allowedSpawns,
104681
+ spawnDepth: () => this.agent.getRlmDepth()
103918
104682
  }),
103919
104683
  this.agent.type === "main" && canSpawn && new FusionPlanTool(this.agent),
103920
104684
  toolServices?.webSearcher && new WebSearchTool(toolServices.webSearcher),
@@ -110610,199 +111374,6 @@ async function collectStream(stream) {
110610
111374
  for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
110611
111375
  return Buffer.concat(chunks).toString("utf-8");
110612
111376
  }
110613
- /** UTF-8 byte length (TextEncoder is available in all supported runtimes). */
110614
- function byteLength(text) {
110615
- return new TextEncoder().encode(text).length;
110616
- }
110617
- /**
110618
- * Byte length of a message body. Callers that deliver a message without going
110619
- * through `send` (the mid-run steer path) use this to apply the same limit.
110620
- */
110621
- function subagentMessageBytes(text) {
110622
- return byteLength(text);
110623
- }
110624
- var SubagentMessageBus = class {
110625
- mailboxes = /* @__PURE__ */ new Map();
110626
- nextId = 0;
110627
- nextSeq = 0;
110628
- /**
110629
- * Number of messages still deliverable for `agentId`. Expired ones are not
110630
- * counted: `poll` drops them, so counting them would make the host spend a
110631
- * delivery turn on a message that can never arrive. Counting is also an
110632
- * ordinary bus access, so it reclaims mail that has expired by now.
110633
- */
110634
- activeCount(agentId) {
110635
- this.reclaimExpired(Date.now());
110636
- return this.mailboxes.get(agentId)?.queue.length ?? 0;
110637
- }
110638
- /**
110639
- * Queue a message for a subagent. Pure mailbox logic: ownership, liveness
110640
- * and activity checks belong to the host. Returns the delivery status and,
110641
- * on acceptance, the queue depth seen by the recipient at poll time.
110642
- */
110643
- send(msg) {
110644
- const now = Date.now();
110645
- this.reclaimExpired(now);
110646
- if (now > msg.deadline) return { status: "deadline_elapsed" };
110647
- if (byteLength(msg.text) > msg.byteLimit) return {
110648
- status: "saturated",
110649
- reason: "bytes"
110650
- };
110651
- let mailbox = this.mailboxes.get(msg.toAgentId);
110652
- if (mailbox === void 0) {
110653
- mailbox = { queue: [] };
110654
- this.mailboxes.set(msg.toAgentId, mailbox);
110655
- }
110656
- if (mailbox.queue.length >= msg.inFlightLimit) return {
110657
- status: "saturated",
110658
- reason: "queue"
110659
- };
110660
- const message = {
110661
- ...msg,
110662
- id: `${msg.fromAgentId}:${msg.toAgentId}:${++this.nextId}`,
110663
- seq: ++this.nextSeq
110664
- };
110665
- mailbox.queue.push(message);
110666
- return {
110667
- status: "accepted",
110668
- queueDepth: mailbox.queue.length
110669
- };
110670
- }
110671
- /**
110672
- * Drop every queued message in every mailbox (session teardown). Id and seq
110673
- * counters stay monotonic so identifiers issued before the clear are never
110674
- * reissued.
110675
- */
110676
- clear() {
110677
- this.mailboxes.clear();
110678
- }
110679
- /** Mailbox entries currently pinned in memory (diagnostics / assertions).
110680
- * Reading does not reclaim: an entry whose mail has all expired is freed by
110681
- * the next send/activeCount/poll, not by this getter. */
110682
- get mailboxCount() {
110683
- return this.mailboxes.size;
110684
- }
110685
- /**
110686
- * Drop mail that can no longer be delivered and free the mailbox slot it
110687
- * pinned. A message is deliverable only until its deadline; past it, `poll`
110688
- * would discard it rather than hand it to the child, so keeping it would pin
110689
- * memory for a run that has already ended. Called on every ordinary bus
110690
- * access — send, activeCount, poll — which is what keeps the mailbox map
110691
- * bounded now that a finished child's terminal no longer purges its mailbox.
110692
- */
110693
- reclaimExpired(now) {
110694
- for (const [agentId, mailbox] of this.mailboxes) {
110695
- const live = mailbox.queue.filter((m) => m.deadline > now);
110696
- if (live.length === 0) this.mailboxes.delete(agentId);
110697
- else if (live.length !== mailbox.queue.length) mailbox.queue = live;
110698
- }
110699
- }
110700
- /**
110701
- * Deliver all pending, unexpired messages for `agentId`. Steer messages are
110702
- * always dequeued before queue messages; within an operation class, arrival
110703
- * order is preserved via the monotonically increasing `seq` (this is a stable
110704
- * two-pass collection, not a sort). Messages past their deadline are
110705
- * reclaimed, never delivered.
110706
- *
110707
- * The mailbox entry is removed once its queue is emptied: a polled-out (or
110708
- * fully expired) mailbox must not pin a Map slot.
110709
- */
110710
- poll(agentId) {
110711
- const now = Date.now();
110712
- this.reclaimExpired(now);
110713
- const mailbox = this.mailboxes.get(agentId);
110714
- if (mailbox === void 0) return [];
110715
- this.mailboxes.delete(agentId);
110716
- const steers = mailbox.queue.filter((m) => m.operation === "steer");
110717
- const queues = mailbox.queue.filter((m) => m.operation === "queue");
110718
- steers.sort((a, b) => a.seq - b.seq);
110719
- queues.sort((a, b) => a.seq - b.seq);
110720
- return [...steers, ...queues];
110721
- }
110722
- };
110723
- /** Construct a message with the bus defaults applied. */
110724
- function buildSubagentMessage(fromAgentId, toAgentId, operation, text, overrides) {
110725
- return {
110726
- fromAgentId,
110727
- toAgentId,
110728
- operation,
110729
- text,
110730
- inFlightLimit: overrides?.inFlightLimit ?? 4,
110731
- byteLimit: overrides?.byteLimit ?? 16384,
110732
- deadline: overrides?.deadline ?? Date.now() + 3e5
110733
- };
110734
- }
110735
- //#endregion
110736
- //#region ../../packages/agent-core/src/session/subagent-capability.ts
110737
- /**
110738
- * Subagent capability modes and their tool-set policy.
110739
- *
110740
- * Capability modes (read-only / read-write / execute / all): a mode is
110741
- * enforced at the tool level, not just by prompting. `all` keeps the profile's
110742
- * full tool set; stricter modes strip it down to the tools the mode permits.
110743
- *
110744
- * Tool classification is by name; the sets live in `#/tools/tool-catalog`
110745
- * (shared with the permission policies) so a new tool is classified once.
110746
- * Unknown tool names are kept (a future tool should fail open rather than
110747
- * being silently stripped from a read-only child).
110748
- */
110749
- const KNOWN_TOOL_SETS = [
110750
- READ_TOOLS,
110751
- WRITE_TOOLS,
110752
- EXECUTE_TOOLS,
110753
- NESTING_TOOLS,
110754
- CORE_TOOLS
110755
- ];
110756
- /**
110757
- * Filter an active tool-name list down to what `mode` permits. `all` returns
110758
- * the input unchanged. Unknown names are preserved.
110759
- */
110760
- function filterToolsForCapability(activeTools, mode) {
110761
- if (mode === void 0 || mode === "all") return [...activeTools];
110762
- const allowed = mode === "read-only" ? union(READ_TOOLS, CORE_TOOLS) : mode === "read-write" ? union(READ_TOOLS, WRITE_TOOLS, CORE_TOOLS) : union(READ_TOOLS, WRITE_TOOLS, EXECUTE_TOOLS, CORE_TOOLS);
110763
- return activeTools.filter((name) => {
110764
- if (name.startsWith("mcp__")) return false;
110765
- return allowed.has(name) || !KNOWN_TOOL_SETS.some((set) => set.has(name));
110766
- });
110767
- }
110768
- function union(...sets) {
110769
- const out = /* @__PURE__ */ new Set();
110770
- for (const s of sets) for (const v of s) out.add(v);
110771
- return out;
110772
- }
110773
- /** Strictness order: earlier = narrower (fewer tools permitted). */
110774
- const CAPABILITY_ORDER = [
110775
- "read-only",
110776
- "read-write",
110777
- "execute",
110778
- "all"
110779
- ];
110780
- /**
110781
- * The narrower of two capability modes (`read-only` < `read-write` < `execute`
110782
- * < `all`). Resume uses this to clamp: a resumed agent keeps the tool set it
110783
- * already has (its profile is not rebuilt), so its contract may be re-applied
110784
- * or tightened, never widened.
110785
- */
110786
- function narrowerCapability(a, b) {
110787
- return CAPABILITY_ORDER.indexOf(a) <= CAPABILITY_ORDER.indexOf(b) ? a : b;
110788
- }
110789
- /**
110790
- * Infer the strictest capability mode that already permits `activeTools` — the
110791
- * first mode whose `filterToolsForCapability` pass removes nothing, else `all`.
110792
- *
110793
- * Used when resuming a session recorded before `AgentMeta.capabilityMode`
110794
- * existed: filtering is pure subtraction, so a tool set that survives
110795
- * `read-only` unchanged is evidence the agent was never granted more than
110796
- * that. The inference can only be too *narrow* (a set that happens to contain
110797
- * only allowed tools), which is the safe direction for a capability clamp.
110798
- */
110799
- function inferCapabilityFromTools(activeTools) {
110800
- for (const mode of CAPABILITY_ORDER) {
110801
- if (mode === "all") break;
110802
- if (filterToolsForCapability(activeTools, mode).length === activeTools.length) return mode;
110803
- }
110804
- return "all";
110805
- }
110806
111377
  //#endregion
110807
111378
  //#region ../../packages/agent-core/src/session/summary-continuation.md
110808
111379
  var summary_continuation_default = "Your previous response was too brief. Please provide a more comprehensive summary that includes:\n\n1. Specific technical details and implementations\n2. Detailed findings and analysis\n3. All important information that the parent agent should know";
@@ -110824,6 +111395,14 @@ const SUMMARY_CONTINUATION_ATTEMPTS = 1;
110824
111395
  * that was too short consumed the only delivery window, so a message queued a
110825
111396
  * few milliseconds later was destroyed at run end while the parent still held
110826
111397
  * an "accepted" acknowledgement.
111398
+ *
111399
+ * Scope: this budget bounds the MAILBOX path only — a message that has to wait
111400
+ * for a turn start, and therefore only ever costs a delivery turn. A mid-run
111401
+ * `steer` (including the foreground→background handoff, where the parent wakes
111402
+ * from a blocked Agent call and answers the still-running child) joins the turn
111403
+ * that is already running through the steer buffer instead; it is bounded there
111404
+ * by DEFAULT_IN_FLIGHT_LIMIT and must not spend delivery turns, because no
111405
+ * delivery turn is needed to reach it.
110827
111406
  */
110828
111407
  const MAX_PARENT_MESSAGE_DELIVERY_TURNS = 2;
110829
111408
  const HOOK_TEXT_PREVIEW_LENGTH = 500;
@@ -110854,22 +111433,39 @@ var SessionSubagentHost = class {
110854
111433
  modelBindings;
110855
111434
  bus;
110856
111435
  activeChildren = /* @__PURE__ */ new Map();
110857
- /** Per-child per-model usage already folded into the parent totals, so a
110858
- * resumed child's aggregation only adds the delta. */
110859
- aggregatedChildUsage = /* @__PURE__ */ new WeakMap();
110860
111436
  /** Per-turn budget (≤4 accepted) for child→parent collaboration requests. */
110861
111437
  childRequestCounts = /* @__PURE__ */ new Map();
110862
111438
  /** Dedupe keys seen within the current turn, per child. */
110863
111439
  childRequestSeen = /* @__PURE__ */ new Map();
110864
111440
  /**
110865
- * Parent→child message dedupe keys, per child, for the child's current turn.
110866
- * A retried send (the parent re-issuing the same directive after a tool
110867
- * hiccup) must not reach the child twice; asking again in a later turn is a
110868
- * legitimate re-ask, so the keys are cleared with the child request limits.
111441
+ * Parent→child message dedupe ledger, per child, for the child's current
111442
+ * turn: key → the in-flight message that key stands for. A retried send (the
111443
+ * parent re-issuing the same directive after a tool hiccup) must not reach
111444
+ * the child twice WHILE the first copy is still in flight; once the child has
111445
+ * consumed that copy — the mailbox no longer holds it, or the steer buffer
111446
+ * has flushed it — the key is released, because a re-send then is a fresh
111447
+ * instruction rather than a retry of an undelivered one. Asking again in a
111448
+ * later turn is legitimate too, so the ledger is cleared with the child
111449
+ * request limits.
110869
111450
  */
110870
111451
  parentMessageSeen = /* @__PURE__ */ new Map();
111452
+ /** Profile names of children spawned or resumed through this host, keyed by
111453
+ * child id. `getProfileName` falls back to it once a child is evicted: the
111454
+ * Agent tool reads that name to validate the parent's `spawns` whitelist on
111455
+ * the resume path, and an evicted child has no live config left to read. */
111456
+ childProfiles = /* @__PURE__ */ new Map();
110871
111457
  /** Agent → childId lookup for child→parent collaboration requests. */
110872
111458
  childIdByAgent = /* @__PURE__ */ new WeakMap();
111459
+ /**
111460
+ * One-shot "this child submitted a collaboration request" wake-ups, keyed by
111461
+ * child id. The Agent tool registers one when a foreground wait begins — the
111462
+ * parent is parked inside the tool call, so the parent turn has no step
111463
+ * boundary to flush the notification into — and releases it when the wait
111464
+ * ends. `submitChildRequest` resolves it once the request has been steered to
111465
+ * the parent. Without a registration the request keeps the plain
111466
+ * notification path (it waits for the parent's next boundary).
111467
+ */
111468
+ childRequestWaiters = /* @__PURE__ */ new Map();
110873
111469
  constructor(session, ownerAgentId, backgroundTaskTimeoutMs, modelBindings, bus) {
110874
111470
  this.session = session;
110875
111471
  this.ownerAgentId = ownerAgentId;
@@ -110887,6 +111483,7 @@ var SessionSubagentHost = class {
110887
111483
  type: "sub",
110888
111484
  generate: parent.rawGenerate
110889
111485
  }, void 0, this.ownerAgentId);
111486
+ this.childProfiles.set(id, profile.name);
110890
111487
  agent.setRlmDepth(parent.getRlmDepth() + 1);
110891
111488
  agent.setRlmMaxDepth(parent.getRlmMaxDepth());
110892
111489
  const controller = new AbortController();
@@ -110923,6 +111520,9 @@ var SessionSubagentHost = class {
110923
111520
  if (metadata.parentAgentId !== this.ownerAgentId) throw new Error(`Agent instance "${agentId}" does not belong to this parent agent`);
110924
111521
  if (this.activeChildren.has(agentId) || child.turn.hasActiveTurn) throw new Error(`Agent instance "${agentId}" is already running and cannot be resumed concurrently`);
110925
111522
  const profileName = child.config.profileName ?? "subagent";
111523
+ this.childProfiles.set(agentId, profileName);
111524
+ const whitelist = spawnWhitelistFor(parent);
111525
+ if (whitelist !== void 0 && !whitelist.includes(profileName)) throw new Error(`Subagent profile "${profileName}" is not in the parent profile's spawn whitelist (${whitelist.join(", ")}): agent "${agentId}" cannot be resumed by this parent`);
110926
111526
  const controller = new AbortController();
110927
111527
  const unlinkAbortSignal = linkAbortSignal(options.signal, controller);
110928
111528
  this.activeChildren.set(agentId, {
@@ -110978,10 +111578,19 @@ var SessionSubagentHost = class {
110978
111578
  child.controller.abort(reason);
110979
111579
  }
110980
111580
  }
111581
+ /**
111582
+ * Profile name of one of this host's children, or undefined when the id is
111583
+ * not a child of this owner. Reads the live instance when it is resident and
111584
+ * falls back to the name recorded at spawn/resume: a finished child is
111585
+ * evicted from `session.agents`, and its resumability is then judged from
111586
+ * exactly this call (the Agent tool validates the parent's spawn whitelist
111587
+ * before calling `resume`), so reporting `undefined` for the evicted child
111588
+ * would skip the whitelist instead of consulting it.
111589
+ */
110981
111590
  getProfileName(agentId) {
110982
111591
  const metadata = this.session.metadata.agents[agentId];
110983
111592
  if (metadata?.type !== "sub" || metadata.parentAgentId !== this.ownerAgentId) return;
110984
- return this.session.agents.get(agentId)?.config.profileName;
111593
+ return this.session.agents.get(agentId)?.config.profileName ?? this.childProfiles.get(agentId);
110985
111594
  }
110986
111595
  /**
110987
111596
  * Chain a child run's terminal step: release the child's own resources, then
@@ -110999,12 +111608,14 @@ var SessionSubagentHost = class {
110999
111608
  try {
111000
111609
  return await run;
111001
111610
  } finally {
111611
+ child.background.markSessionClosed();
111002
111612
  terminal.unlinkAbortSignal();
111003
111613
  await this.releaseChildResourcesBounded(parent, child, terminal.childId);
111004
111614
  this.activeChildren.delete(terminal.childId);
111005
111615
  this.childRequestCounts.delete(terminal.childId);
111006
111616
  this.childRequestSeen.delete(terminal.childId);
111007
111617
  this.parentMessageSeen.delete(terminal.childId);
111618
+ this.childRequestWaiters.delete(terminal.childId);
111008
111619
  this.session.removeAgent?.(terminal.childId);
111009
111620
  if (terminal.childId !== "main") this.session.agents.delete(terminal.childId);
111010
111621
  }
@@ -111083,7 +111694,11 @@ var SessionSubagentHost = class {
111083
111694
  * Send a directed message to a subagent owned by this parent. Ownership is
111084
111695
  * verified against the session metadata before anything is enqueued; a
111085
111696
  * message addressed to a foreign or unknown agent is refused as
111086
- * `not_owned`/`not_found`.
111697
+ * `not_owned`/`not_found`, one addressed to a finished child as `not_active`,
111698
+ * and one whose sender is no longer resident in the session as `parent_gone`
111699
+ * — an accepted message must have a live owner that can observe (and act on)
111700
+ * the delivery it was promised, instead of being acknowledged into a bus
111701
+ * whose owning turn has already ended.
111087
111702
  *
111088
111703
  * `steer` redirects a running child without disturbing its in-flight tools;
111089
111704
  * `interject` does the same but additionally interrupts the tool batch in
@@ -111096,6 +111711,7 @@ var SessionSubagentHost = class {
111096
111711
  const child = this.session.agents.get(toAgentId);
111097
111712
  const record = this.activeChildren.get(toAgentId);
111098
111713
  if (child === void 0 || record === void 0) return { status: "not_active" };
111714
+ if (this.session.agents.get(this.ownerAgentId) === void 0) return { status: "parent_gone" };
111099
111715
  const message = buildSubagentMessage(this.ownerAgentId, toAgentId, operation === "queue" ? "queue" : "steer", text, overrides);
111100
111716
  const byteLimit = overrides?.byteLimit ?? 16384;
111101
111717
  if (subagentMessageBytes(text) > byteLimit) return {
@@ -111104,14 +111720,19 @@ var SessionSubagentHost = class {
111104
111720
  };
111105
111721
  let seen = this.parentMessageSeen.get(toAgentId);
111106
111722
  if (seen === void 0) {
111107
- seen = /* @__PURE__ */ new Set();
111723
+ seen = /* @__PURE__ */ new Map();
111108
111724
  this.parentMessageSeen.set(toAgentId, seen);
111109
111725
  }
111110
111726
  const dedupeKey = `${operation}\n${text}`;
111111
- if (seen.has(dedupeKey)) return {
111112
- status: "accepted",
111113
- duplicate: true
111114
- };
111727
+ const pending = seen.get(dedupeKey);
111728
+ if (pending !== void 0) {
111729
+ if (this.parentMessageInFlight(child, pending)) return {
111730
+ status: "accepted",
111731
+ duplicate: true,
111732
+ ...pending.kind === "mailbox" ? { messageId: pending.messageId } : {}
111733
+ };
111734
+ seen.delete(dedupeKey);
111735
+ }
111115
111736
  if ((operation === "steer" || operation === "interject") && !record.structured && child.turn.hasActiveTurn && child.turn.steerQueueLength < 4) {
111116
111737
  child.turn.steer([{
111117
111738
  type: "text",
@@ -111120,22 +111741,44 @@ var SessionSubagentHost = class {
111120
111741
  kind: "system_trigger",
111121
111742
  name: operation === "interject" ? "parent_interject" : "parent_message"
111122
111743
  }, operation === "interject" ? { interrupt: true } : void 0);
111123
- seen.add(dedupeKey);
111744
+ seen.set(dedupeKey, {
111745
+ kind: "steer",
111746
+ bufferLengthAtSend: child.turn.steerQueueLength
111747
+ });
111124
111748
  return {
111125
111749
  status: "accepted",
111126
111750
  delivery: operation === "interject" ? "interjected" : "mid-run"
111127
111751
  };
111128
111752
  }
111129
111753
  const out = this.bus.send(message);
111130
- if (out.status === "accepted") seen.add(dedupeKey);
111754
+ if (out.status === "accepted" && out.messageId !== void 0) seen.set(dedupeKey, {
111755
+ kind: "mailbox",
111756
+ messageId: out.messageId
111757
+ });
111131
111758
  return {
111132
111759
  status: out.status,
111133
111760
  reason: out.reason,
111134
111761
  delivery: out.status === "accepted" ? "queued" : void 0,
111135
- queueDepth: out.queueDepth
111762
+ queueDepth: out.queueDepth,
111763
+ messageId: out.messageId,
111764
+ downgrade: operation === "interject" && out.status === "accepted" ? record.structured ? "structured" : child.turn.hasActiveTurn ? "steer-buffer-full" : "idle" : void 0
111136
111765
  };
111137
111766
  }
111138
111767
  /**
111768
+ * Whether the message a dedupe key stands for is still undelivered. Mailbox
111769
+ * copies are judged by the bus (which also reclaims expired mail, so a
111770
+ * message that can never arrive reads as consumed); steered copies by the
111771
+ * turn's buffer: a buffer shorter than the length recorded at acceptance was
111772
+ * flushed — flushes drain the whole buffer, so the copy rode along. A full
111773
+ * buffer that flushed and was refilled reads as still in flight (the count is
111774
+ * back at or above the mark); that errs toward deduplicating, never toward
111775
+ * delivering the same directive twice.
111776
+ */
111777
+ parentMessageInFlight(child, pending) {
111778
+ if (pending.kind === "mailbox") return this.bus.holdsMessage(pending.messageId);
111779
+ return child.turn.hasActiveTurn && child.turn.steerQueueLength >= pending.bufferLengthAtSend;
111780
+ }
111781
+ /**
111139
111782
  * Child→parent collaboration request (B-scheme). A subagent can proactively
111140
111783
  * contact its owner mid-run: `info` (ask for context/clarification),
111141
111784
  * `handoff` (ask to pass the work to another capability — described as a
@@ -111148,6 +111791,8 @@ var SessionSubagentHost = class {
111148
111791
  submitChildRequest(fromAgent, req) {
111149
111792
  const fromChildId = this.childIdByAgent.get(fromAgent);
111150
111793
  if (fromChildId === void 0 || !this.activeChildren.has(fromChildId)) return { status: "not_active" };
111794
+ const parent = this.session.agents.get(this.ownerAgentId);
111795
+ if (parent === void 0) return { status: "parent_gone" };
111151
111796
  const count = this.childRequestCounts.get(fromChildId) ?? 0;
111152
111797
  if (count >= 4) return { status: "saturated" };
111153
111798
  const dedupeKey = `${req.request_type}|${req.needs ?? ""}|${req.message}`;
@@ -111171,7 +111816,7 @@ var SessionSubagentHost = class {
111171
111816
  req.payload?.evidence !== void 0 && req.payload.evidence.length > 0 ? `evidence: [${req.payload.evidence.join(", ")}]` : void 0,
111172
111817
  req.payload?.missing !== void 0 && req.payload.missing.length > 0 ? `missing: [${req.payload.missing.join(", ")}]` : void 0
111173
111818
  ].filter((l) => l !== void 0);
111174
- this.session.agents.get(this.ownerAgentId)?.turn.steer([{
111819
+ parent.turn.steer([{
111175
111820
  type: "text",
111176
111821
  text: renderNotificationXml({
111177
111822
  id: `child_request:${fromChildId}:${Date.now()}`,
@@ -111187,13 +111832,52 @@ var SessionSubagentHost = class {
111187
111832
  kind: "system_trigger",
111188
111833
  name: "child_request"
111189
111834
  });
111835
+ parent.emitEvent({
111836
+ type: "subagent.child_request",
111837
+ subagentId: fromChildId,
111838
+ subagentName: this.getProfileName(fromChildId),
111839
+ requestType: req.request_type,
111840
+ message: req.message,
111841
+ needs: req.needs,
111842
+ expecting: req.payload?.expecting,
111843
+ artifacts: req.payload?.artifacts,
111844
+ evidence: req.payload?.evidence,
111845
+ missing: req.payload?.missing
111846
+ });
111847
+ this.childRequestWaiters.get(fromChildId)?.resolve();
111190
111848
  return { status: "accepted" };
111191
111849
  }
111850
+ /**
111851
+ * Register (or reuse) the one-shot wake-up resolved when this child submits
111852
+ * its next accepted collaboration request. Called by the Agent tool when a
111853
+ * foreground wait begins; the returned promise resolves at most once.
111854
+ */
111855
+ waitForChildRequest(childId) {
111856
+ const existing = this.childRequestWaiters.get(childId);
111857
+ if (existing !== void 0) return existing.promise;
111858
+ let resolve;
111859
+ const promise = new Promise((res) => {
111860
+ resolve = res;
111861
+ });
111862
+ this.childRequestWaiters.set(childId, {
111863
+ promise,
111864
+ resolve
111865
+ });
111866
+ return promise;
111867
+ }
111868
+ /**
111869
+ * Drop a child's wake-up registration (its foreground wait ended). The entry
111870
+ * is deleted rather than kept resolved: the next foreground wait registers a
111871
+ * fresh one-shot signal, so a stale resolution cannot background a later run.
111872
+ */
111873
+ releaseChildRequestWait(childId) {
111874
+ this.childRequestWaiters.delete(childId);
111875
+ }
111192
111876
  /** Per-turn budget reset for child→parent collaboration requests. */
111193
111877
  resetChildRequestLimits(childId) {
111194
111878
  this.childRequestCounts.set(childId, 0);
111195
111879
  this.childRequestSeen.set(childId, /* @__PURE__ */ new Set());
111196
- this.parentMessageSeen.set(childId, /* @__PURE__ */ new Set());
111880
+ this.parentMessageSeen.set(childId, /* @__PURE__ */ new Map());
111197
111881
  }
111198
111882
  resolveProfile(parent, profileName) {
111199
111883
  const profile = DEFAULT_AGENT_PROFILES[parent.config.profileName ?? "agent"]?.subagents?.[profileName] ?? DEFAULT_AGENT_PROFILES["agent"]?.subagents?.[profileName];
@@ -111284,20 +111968,23 @@ var SessionSubagentHost = class {
111284
111968
  }
111285
111969
  const usage = child.usage.data().total;
111286
111970
  const childByModel = child.usage.data().byModel ?? {};
111287
- const previous = this.aggregatedChildUsage.get(child) ?? {};
111971
+ const ledger = foldedChildUsageFor(this.session);
111972
+ const previous = ledger.get(childId) ?? {};
111973
+ const deltas = {};
111288
111974
  for (const [model, childUsage] of Object.entries(childByModel)) {
111289
111975
  const delta = previous[model] === void 0 ? childUsage : subtractUsage(childUsage, previous[model]);
111290
- if (isZeroUsage(delta)) continue;
111291
- try {
111292
- parent.usage.record(model, delta, "session");
111293
- } catch (error) {
111294
- parent.log.warn("Failed to aggregate subagent usage", {
111295
- model,
111296
- error: String(error)
111297
- });
111298
- }
111976
+ if (!isZeroUsage(delta)) deltas[model] = delta;
111299
111977
  }
111300
- this.aggregatedChildUsage.set(child, childByModel);
111978
+ const foldTarget = this.usageFoldTarget(parent);
111979
+ for (const [model, delta] of Object.entries(deltas)) try {
111980
+ foldTarget.usage.record(model, delta, "session");
111981
+ } catch (error) {
111982
+ parent.log.warn("Failed to aggregate subagent usage", {
111983
+ model,
111984
+ error: String(error)
111985
+ });
111986
+ }
111987
+ ledger.set(childId, childByModel);
111301
111988
  const findingsBlock = [formatFindingsBlock(getFindingsFromStore(child.tools.toolStore)), formatArchFindingsBlock(getArchFindingsFromStore(child.tools.toolStore))].join("");
111302
111989
  const durationMs = Date.now() - startedAt;
111303
111990
  const toolCallCount = countAssistantToolCalls(child);
@@ -111329,9 +112016,36 @@ var SessionSubagentHost = class {
111329
112016
  error: message,
111330
112017
  usage: child.usage.data().total
111331
112018
  });
112019
+ this.triggerSubagentStop(parent, profileName, lastAssistantText$1(child), message);
111332
112020
  throw error;
111333
112021
  }
111334
112022
  }
112023
+ /**
112024
+ * Where a finished child's usage delta is folded. Normally its direct parent.
112025
+ * When that parent has been evicted from the session (a background
112026
+ * grandchild can outlive the child that spawned it), its recorder is no
112027
+ * longer part of any live rollup — the fold would land on an agent nobody
112028
+ * reads again — so the delta goes to the nearest RESIDENT ancestor instead,
112029
+ * and the chain keeps rolling up through finished intermediates. The delta
112030
+ * is recorded exactly once, at that target: the ledger that guards against
112031
+ * re-folding is keyed by the CHILD, so a later resume of the intermediate
112032
+ * can never fold the amount a second time (its own total never received it).
112033
+ *
112034
+ * The direct parent is the fallback when nothing in the chain is resident
112035
+ * (session teardown): recording there is what happened before this walk, and
112036
+ * no live reader remains to disagree.
112037
+ */
112038
+ usageFoldTarget(parent) {
112039
+ const resident = this.session.agents.get(parent.agentId);
112040
+ if (resident !== void 0) return resident;
112041
+ let ancestorId = this.session.metadata.agents[parent.agentId]?.parentAgentId ?? null;
112042
+ while (ancestorId !== null) {
112043
+ const ancestor = this.session.agents.get(ancestorId);
112044
+ if (ancestor !== void 0) return ancestor;
112045
+ ancestorId = this.session.metadata.agents[ancestorId]?.parentAgentId ?? null;
112046
+ }
112047
+ return parent;
112048
+ }
111335
112049
  async configureChild(parent, child, profile, childId, capabilityMode) {
111336
112050
  const binding = this.resolveModelBinding(profile.name);
111337
112051
  const modelAlias = this.resolveValidModelAlias(parent, binding);
@@ -111402,16 +112116,54 @@ var SessionSubagentHost = class {
111402
112116
  }
111403
112117
  });
111404
112118
  }
111405
- triggerSubagentStop(parent, profileName, result) {
112119
+ /**
112120
+ * Fire the SubagentStop hook for a child run that has reached a terminal
112121
+ * state. Called on the success path and from the failure/cancel handler, so
112122
+ * the event means "this child run ended", never just "it succeeded"; a failed
112123
+ * run adds the `error` field (and `response` still carries whatever the child
112124
+ * had produced) while a successful one keeps the original payload shape.
112125
+ */
112126
+ triggerSubagentStop(parent, profileName, result, error) {
111406
112127
  parent.hooks?.fireAndForgetTrigger("SubagentStop", {
111407
112128
  matcherValue: profileName,
111408
112129
  inputData: {
111409
112130
  agentName: profileName,
111410
- response: result.slice(0, HOOK_TEXT_PREVIEW_LENGTH)
112131
+ response: result.slice(0, HOOK_TEXT_PREVIEW_LENGTH),
112132
+ ...error !== void 0 ? { error: error.slice(0, HOOK_TEXT_PREVIEW_LENGTH) } : {}
111411
112133
  }
111412
112134
  });
111413
112135
  }
111414
112136
  };
112137
+ /**
112138
+ * How much of each child's cumulative usage has already been folded into its
112139
+ * owner's session totals, keyed by the child's stable agent id. Session-scoped
112140
+ * and module-level: an Agent-instance key cannot survive the resume path
112141
+ * (`ensureAgent` re-hydrates a new instance whose replayed recorder holds the
112142
+ * full history, which was then folded a second time), and a host-level map
112143
+ * cannot survive an owner being re-instantiated, which would reopen the same
112144
+ * hole one level down.
112145
+ */
112146
+ const foldedChildUsageBySession = /* @__PURE__ */ new WeakMap();
112147
+ function foldedChildUsageFor(session) {
112148
+ let ledger = foldedChildUsageBySession.get(session);
112149
+ if (ledger === void 0) {
112150
+ ledger = /* @__PURE__ */ new Map();
112151
+ foldedChildUsageBySession.set(session, ledger);
112152
+ }
112153
+ return ledger;
112154
+ }
112155
+ /**
112156
+ * The `spawns` whitelist of the given agent's own profile — the same source of
112157
+ * truth the Agent tool derives its `allowedSpawns` from (agent/tool/index.ts:
112158
+ * `DEFAULT_AGENT_PROFILES[agent.config.profileName ?? 'agent']?.spawns`).
112159
+ * Named here because the resume path must enforce the identical rule from
112160
+ * inside the host: the Agent tool resolves a resumed child's profile through
112161
+ * `getProfileName`, which historically could not see an evicted child and so
112162
+ * skipped the check entirely.
112163
+ */
112164
+ function spawnWhitelistFor(agent) {
112165
+ return DEFAULT_AGENT_PROFILES[agent.config.profileName ?? "agent"]?.spawns;
112166
+ }
111415
112167
  /** Element-wise subtraction clamped at zero (usage can never go negative). */
111416
112168
  function subtractUsage(current, previous) {
111417
112169
  return {
@@ -111526,6 +112278,14 @@ var Session$1 = class {
111526
112278
  /** Session-level parent→child message bus shared by every subagent host. */
111527
112279
  subagentMessages = new SubagentMessageBus();
111528
112280
  agentIdCounter = 0;
112281
+ /**
112282
+ * Every BackgroundManager this session created for one of its agents, held
112283
+ * through a `WeakRef` so `close()` can still latch the manager of a finished
112284
+ * (evicted) subagent — see `trackBackgroundManager`. Weak on purpose: a
112285
+ * strong reference would pin each manager for the session's lifetime, the
112286
+ * leak `removeAgent` exists to avoid.
112287
+ */
112288
+ backgroundManagers = /* @__PURE__ */ new Set();
111529
112289
  skillsReady;
111530
112290
  mcpReady;
111531
112291
  metadata = {
@@ -111594,7 +112354,6 @@ var Session$1 = class {
111594
112354
  }
111595
112355
  });
111596
112356
  this.disposables.add("background-pending", async () => {
111597
- stopAllPendingBackgroundTasks(this.options.id);
111598
112357
  await this.stopBackgroundTasksOnExit();
111599
112358
  });
111600
112359
  this.disposables.add("cron", async () => {
@@ -111651,6 +112410,7 @@ var Session$1 = class {
111651
112410
  return { warning: resumeWarning };
111652
112411
  }
111653
112412
  async close() {
112413
+ for (const manager of this.liveBackgroundManagers()) manager.markSessionClosed();
111654
112414
  const main = this.agents.get("main");
111655
112415
  if (main !== void 0) {
111656
112416
  const recap = main.sessionMemory.getSessionSummary();
@@ -111672,15 +112432,39 @@ var Session$1 = class {
111672
112432
  }
111673
112433
  if (disposeError !== null) throw disposeError;
111674
112434
  }
112435
+ /**
112436
+ * Per-agent background-task policy for session exit, run from the
112437
+ * `background-pending` close-out step — i.e. after `close()` cancelled the
112438
+ * agent turns.
112439
+ *
112440
+ * `keepAliveOnExit` now protects bash processes only. They are real OS
112441
+ * processes whose work (`npm install`, a dev server) is still meaningful to
112442
+ * the user after the session is gone, so the true path leaves them running.
112443
+ * Agent tasks are not processes — they are coroutines over a subagent turn
112444
+ * that `close()` has already cancelled and can never finish on their own — so
112445
+ * they are stopped in both paths: via `stopAll` when keepAlive is off (which
112446
+ * covers every task, so the agent-only stop is not repeated on top of it),
112447
+ * and via `stopAgentTasks` when keepAlive is on.
112448
+ *
112449
+ * The sweep runs over `liveBackgroundManagers()`, not just `this.agents`: a
112450
+ * finished subagent is evicted while agent-class tasks it registered may
112451
+ * still be running, and those are exactly the tasks that would otherwise be
112452
+ * stranded into a later `failed` notification that advertises `Agent(resume=)`.
112453
+ */
111675
112454
  async stopBackgroundTasksOnExit() {
111676
- if (resolveConfigValue({
112455
+ const keepAliveOnExit = resolveConfigValue({
111677
112456
  env: process.env,
111678
112457
  envKey: BACKGROUND_KEEP_ALIVE_ON_EXIT_ENV,
111679
112458
  configValue: this.options.background?.keepAliveOnExit,
111680
112459
  defaultValue: true,
111681
112460
  parseEnv: parseBooleanEnv
111682
- })) return;
111683
- await Promise.all(Array.from(this.agents.values(), (agent) => agent.background.stopAll("Session closed")));
112461
+ });
112462
+ const managers = this.liveBackgroundManagers();
112463
+ if (!keepAliveOnExit) {
112464
+ await Promise.all(managers.map((manager) => manager.stopAll("Session closed")));
112465
+ return;
112466
+ }
112467
+ await Promise.all(managers.map((manager) => manager.stopAgentTasks("Session closed")));
111684
112468
  }
111685
112469
  async createAgent(config, profile, parentAgentId) {
111686
112470
  await this.skillsReady;
@@ -111948,7 +112732,7 @@ var Session$1 = class {
111948
112732
  instantiateAgent(id, homedir, type, config = {}, parentAgentId = null) {
111949
112733
  const parentAgent = parentAgentId !== null ? this.agents.get(parentAgentId) : void 0;
111950
112734
  const cwd = parentAgent?.config.cwd ?? this.options.jian.getcwd();
111951
- return new Agent({
112735
+ const agent = new Agent({
111952
112736
  ...config,
111953
112737
  agentId: id,
111954
112738
  type,
@@ -111971,6 +112755,48 @@ var Session$1 = class {
111971
112755
  pluginSessionStarts: type === "main" ? this.options.pluginSessionStarts : void 0,
111972
112756
  resolveRuntimeSystemPrompt: (basePrompt) => this.effectiveSystemPrompt(basePrompt)
111973
112757
  });
112758
+ this.trackBackgroundManager(agent.background);
112759
+ return agent;
112760
+ }
112761
+ /**
112762
+ * Remember a BackgroundManager so `close()` can latch it shut (see
112763
+ * BackgroundManager.markSessionClosed) even after its agent was evicted from
112764
+ * `agents`. A manager `close()` cannot reach would deliver a terminal task
112765
+ * notification into the closing session — the ghost turn the latch exists to
112766
+ * prevent.
112767
+ *
112768
+ * The reference is weak on purpose: a strong one would pin every manager this
112769
+ * session ever created for the session's whole lifetime, exactly the leak
112770
+ * `removeAgent` avoids for finished subagents. A manager the GC has reclaimed
112771
+ * cannot notify anyone, so skipping it is correct. Dead entries are pruned
112772
+ * here and again in `close()`.
112773
+ */
112774
+ trackBackgroundManager(manager) {
112775
+ for (const ref of this.backgroundManagers) if (ref.deref() === void 0) this.backgroundManagers.delete(ref);
112776
+ this.backgroundManagers.add(new WeakRef(manager));
112777
+ }
112778
+ /**
112779
+ * Every BackgroundManager this session created that is still alive. Agents
112780
+ * are registered at construction (`instantiateAgent` →
112781
+ * `trackBackgroundManager`), so resident agents' managers are included and
112782
+ * this is the one enumeration both `close()`'s latch and
112783
+ * `stopBackgroundTasksOnExit`'s stop sweep run over — an evicted subagent's
112784
+ * manager stays reachable here after the agent left `agents`.
112785
+ *
112786
+ * An entry the GC already reclaimed is pruned: nothing can notify through,
112787
+ * or hold tasks in, a manager that no longer exists.
112788
+ */
112789
+ liveBackgroundManagers() {
112790
+ const live = [];
112791
+ for (const ref of this.backgroundManagers) {
112792
+ const manager = ref.deref();
112793
+ if (manager === void 0) {
112794
+ this.backgroundManagers.delete(ref);
112795
+ continue;
112796
+ }
112797
+ live.push(manager);
112798
+ }
112799
+ return live;
111974
112800
  }
111975
112801
  permissionOptions(parentAgentId, input) {
111976
112802
  if (parentAgentId === null) return {
@@ -128658,15 +129484,17 @@ var ScreamCore = class {
128658
129484
  }
128659
129485
  async closeSession({ sessionId }) {
128660
129486
  const session = this.sessions.get(sessionId);
128661
- if (session) {
129487
+ if (session) try {
128662
129488
  await session.close();
129489
+ } finally {
128663
129490
  this.sessions.delete(sessionId);
128664
129491
  }
128665
129492
  }
128666
129493
  async deleteSession({ sessionId }) {
128667
129494
  const active = this.sessions.get(sessionId);
128668
- if (active) {
129495
+ if (active) try {
128669
129496
  await active.close();
129497
+ } finally {
128670
129498
  this.sessions.delete(sessionId);
128671
129499
  }
128672
129500
  await this.sessionStore.delete(sessionId);
@@ -129949,26 +130777,35 @@ var SDKRpcClient = class {
129949
130777
  skillName: input.skillName
129950
130778
  });
129951
130779
  }
130780
+ /**
130781
+ * Background tasks are registered per agent: a subagent's Bash/Agent task
130782
+ * lives in that subagent's own registry, so `agentId` selects whose registry
130783
+ * answers. Omitted ⇒ the interactive agent (main), which is the pre-existing
130784
+ * behavior. An id the session does not know fails with AGENT_NOT_FOUND —
130785
+ * an owner whose live instance has already been dropped is gone, not empty.
130786
+ */
129952
130787
  async listBackgroundTasks(input) {
129953
130788
  return (await this.getRpc()).getBackground({
129954
130789
  sessionId: input.sessionId,
129955
- agentId: this.interactiveAgentId,
130790
+ agentId: input.agentId ?? this.interactiveAgentId,
129956
130791
  activeOnly: input.activeOnly,
129957
130792
  limit: input.limit
129958
130793
  });
129959
130794
  }
130795
+ /** See {@link listBackgroundTasks} for the `agentId` contract. */
129960
130796
  async getBackgroundTaskOutput(input) {
129961
130797
  return (await this.getRpc()).getBackgroundOutput({
129962
130798
  sessionId: input.sessionId,
129963
- agentId: this.interactiveAgentId,
130799
+ agentId: input.agentId ?? this.interactiveAgentId,
129964
130800
  taskId: input.taskId,
129965
130801
  tail: input.tail
129966
130802
  });
129967
130803
  }
130804
+ /** See {@link listBackgroundTasks} for the `agentId` contract. */
129968
130805
  async getBackgroundTaskOutputPath(input) {
129969
130806
  return (await this.getRpc()).getBackgroundOutputPath({
129970
130807
  sessionId: input.sessionId,
129971
- agentId: this.interactiveAgentId,
130808
+ agentId: input.agentId ?? this.interactiveAgentId,
129972
130809
  taskId: input.taskId
129973
130810
  });
129974
130811
  }
@@ -129993,10 +130830,11 @@ var SDKRpcClient = class {
129993
130830
  maxDepth: input.maxDepth
129994
130831
  });
129995
130832
  }
130833
+ /** See {@link listBackgroundTasks} for the `agentId` contract. */
129996
130834
  async stopBackgroundTask(input) {
129997
130835
  return (await this.getRpc()).stopBackground({
129998
130836
  sessionId: input.sessionId,
129999
- agentId: this.interactiveAgentId,
130837
+ agentId: input.agentId ?? this.interactiveAgentId,
130000
130838
  taskId: input.taskId,
130001
130839
  reason: input.reason
130002
130840
  });
@@ -130399,20 +131237,26 @@ var Session = class {
130399
131237
  *
130400
131238
  * Defaults to all tasks (including terminal/lost). Pass
130401
131239
  * `{ activeOnly: true }` to filter to non-terminal entries.
131240
+ *
131241
+ * `agentId` selects whose registry answers — a subagent's task lives in
131242
+ * that subagent's own registry. Omitted ⇒ the interactive agent (main);
131243
+ * an unknown id fails with AGENT_NOT_FOUND.
130402
131244
  */
130403
131245
  async listBackgroundTasks(options = {}) {
130404
131246
  this.ensureOpen();
130405
131247
  return this.rpc.listBackgroundTasks({
130406
131248
  sessionId: this.id,
130407
131249
  activeOnly: options.activeOnly,
130408
- limit: options.limit
131250
+ limit: options.limit,
131251
+ agentId: options.agentId
130409
131252
  });
130410
131253
  }
130411
131254
  /**
130412
131255
  * Read a background task's captured output. Returns the in-memory
130413
131256
  * ring buffer if available, otherwise falls back to the persisted
130414
131257
  * `<sessionDir>/tasks/<taskId>/output.log`. `tail` caps the returned
130415
- * string to that many trailing characters.
131258
+ * string to that many trailing characters. `agentId` selects the owning
131259
+ * agent's registry (default: the interactive agent).
130416
131260
  */
130417
131261
  async getBackgroundTaskOutput(taskId, options = {}) {
130418
131262
  this.ensureOpen();
@@ -130420,7 +131264,8 @@ var Session = class {
130420
131264
  return this.rpc.getBackgroundTaskOutput({
130421
131265
  sessionId: this.id,
130422
131266
  taskId: trimmedTaskId,
130423
- tail: options.tail
131267
+ tail: options.tail,
131268
+ agentId: options.agentId
130424
131269
  });
130425
131270
  }
130426
131271
  /**
@@ -130428,7 +131273,9 @@ var Session = class {
130428
131273
  * grace period (handled by the core BPM); subscribers receive a
130429
131274
  * `background.task.terminated` event when the kill settles. Calls
130430
131275
  * for unknown or already-terminal task ids are no-ops at the core
130431
- * level — this method does not throw in those cases.
131276
+ * level — this method does not throw in those cases. `agentId` selects
131277
+ * the owning agent's registry (default: the interactive agent); stopping
131278
+ * a subagent's task through the main registry would be such a no-op.
130432
131279
  */
130433
131280
  /**
130434
131281
  * Enables or disables the /rlm persistent-python mode. When enabled, the
@@ -130472,20 +131319,23 @@ var Session = class {
130472
131319
  await this.rpc.stopBackgroundTask({
130473
131320
  sessionId: this.id,
130474
131321
  taskId: trimmedTaskId,
130475
- reason: options.reason
131322
+ reason: options.reason,
131323
+ agentId: options.agentId
130476
131324
  });
130477
131325
  }
130478
131326
  /**
130479
131327
  * Return the absolute path to the task's `output.log` on disk, or
130480
131328
  * `undefined` when the task is unknown or has no persisted output.
130481
- * Callers can hand the path to an external pager.
131329
+ * Callers can hand the path to an external pager. `agentId` selects the
131330
+ * owning agent's registry (default: the interactive agent).
130482
131331
  */
130483
- async getBackgroundTaskOutputPath(taskId) {
131332
+ async getBackgroundTaskOutputPath(taskId, options = {}) {
130484
131333
  this.ensureOpen();
130485
131334
  const trimmedTaskId = normalizeRequiredString(taskId, "Task id cannot be empty", ErrorCodes.BACKGROUND_TASK_ID_EMPTY);
130486
131335
  return this.rpc.getBackgroundTaskOutputPath({
130487
131336
  sessionId: this.id,
130488
- taskId: trimmedTaskId
131337
+ taskId: trimmedTaskId,
131338
+ agentId: options.agentId
130489
131339
  });
130490
131340
  }
130491
131341
  async listMcpServers() {
@@ -132529,6 +133379,38 @@ function resolveConnectCatalogRequest(args) {
132529
133379
  };
132530
133380
  }
132531
133381
  //#endregion
133382
+ //#region src/tui/utils/image-config.ts
133383
+ function getImageConfigPath() {
133384
+ return join(resolveScreamHome(), "image-config.json");
133385
+ }
133386
+ /** Placeholder rules mirrored from the ImageGenerate tool's `isPlaceholder`. */
133387
+ function isPlaceholder(value) {
133388
+ const trimmed = value.trim();
133389
+ return trimmed.length === 0 || trimmed.includes("replace-with") || trimmed.startsWith("<") && trimmed.endsWith(">");
133390
+ }
133391
+ /**
133392
+ * Best-effort read of an existing image config (never throws, never exposes
133393
+ * the key). The `usable` predicate mirrors the ImageGenerate tool's
133394
+ * `loadConfig` (packages/agent-core/src/tools/builtin/image/image-generate.ts):
133395
+ * a config the tool would reject must never be advertised as "configured".
133396
+ */
133397
+ async function readExistingImageConfig() {
133398
+ try {
133399
+ const text = await readFile(getImageConfigPath(), "utf8");
133400
+ const parsed = JSON.parse(text);
133401
+ const urlRaw = typeof parsed["url"] === "string" ? parsed["url"] : "";
133402
+ const legacyRaw = typeof parsed["base_url"] === "string" ? parsed["base_url"] : "";
133403
+ const url = !isPlaceholder(urlRaw) ? urlRaw.trim() : !isPlaceholder(legacyRaw) ? `${legacyRaw.trim().replace(/\/+$/, "")}/images/generations` : "";
133404
+ const model = typeof parsed["model"] === "string" ? parsed["model"].trim() : "";
133405
+ const apiKeyRaw = typeof parsed["api_key"] === "string" ? parsed["api_key"] : "";
133406
+ if (url.length > 0 && model.length > 0 && !isPlaceholder(apiKeyRaw)) return {
133407
+ provider: typeof parsed["provider"] === "string" ? parsed["provider"] : "openai-compatible",
133408
+ model,
133409
+ url
133410
+ };
133411
+ } catch {}
133412
+ }
133413
+ //#endregion
132532
133414
  //#region src/tui/components/dialogs/api-key-input-dialog.ts
132533
133415
  function getFooter() {
132534
133416
  return t("apikey.footer");
@@ -132775,6 +133657,11 @@ var ModelSelectorComponent = class extends Container {
132775
133657
  lines.push(this.renderVideoControl(selected.model));
132776
133658
  lines.push(this.renderAudioControl(selected.model));
132777
133659
  }
133660
+ if (this.opts.imageGeneration !== void 0) {
133661
+ const imageGeneration = this.opts.imageGeneration;
133662
+ lines.push("");
133663
+ lines.push(chalk.hex(colors.textMuted)(imageGeneration.configured && imageGeneration.model !== void 0 ? t("model.image_gen_configured", { model: imageGeneration.model }) : t("model.image_gen_missing")));
133664
+ }
132778
133665
  lines.push("");
132779
133666
  if (view.page.pageCount > 1) lines.push(chalk.hex(colors.textMuted)(` Page ${String(view.page.page + 1)}/${String(view.page.pageCount)}`));
132780
133667
  lines.push(chalk.hex(colors.primary)("─".repeat(width)));
@@ -133309,26 +134196,6 @@ const IMAGE_PROVIDER_PRESETS = [
133309
134196
  model: "gpt-image-2"
133310
134197
  }
133311
134198
  ];
133312
- function getImageConfigPath() {
133313
- return join(resolveScreamHome(), "image-config.json");
133314
- }
133315
- /** Best-effort read of an existing image config (never throws, never exposes the key). */
133316
- async function readExistingImageConfig() {
133317
- try {
133318
- const text = await readFile(getImageConfigPath(), "utf8");
133319
- const parsed = JSON.parse(text);
133320
- const urlDirect = typeof parsed["url"] === "string" ? parsed["url"].trim() : "";
133321
- const legacyBase = typeof parsed["base_url"] === "string" ? parsed["base_url"].trim() : "";
133322
- const url = urlDirect.length > 0 ? urlDirect : legacyBase.length > 0 ? `${legacyBase.replace(/\/+$/, "")}/images/generations` : "";
133323
- const model = typeof parsed["model"] === "string" ? parsed["model"].trim() : "";
133324
- const apiKey = typeof parsed["api_key"] === "string" ? parsed["api_key"].trim() : "";
133325
- if (url.length > 0 && !url.includes("replace-with") && !(url.startsWith("<") && url.endsWith(">")) && model.length > 0 && apiKey.length > 0 && !apiKey.includes("replace-with") && !(apiKey.startsWith("<") && apiKey.endsWith(">"))) return {
133326
- provider: typeof parsed["provider"] === "string" ? parsed["provider"] : "openai-compatible",
133327
- model,
133328
- url
133329
- };
133330
- } catch {}
133331
- }
133332
134199
  /**
133333
134200
  * Normalize the URL exactly as the user typed it: trim whitespace and
133334
134201
  * trailing slashes only. Nothing is ever appended or completed — the full
@@ -135889,6 +136756,10 @@ function parseColorFgBg(value) {
135889
136756
  */
135890
136757
  const dark = {
135891
136758
  yellowGreen: "#79eb00",
136759
+ gold: "#FFD700",
136760
+ coral: "#FF7043",
136761
+ skyBlue: "#9CDCFE",
136762
+ violet: "#C084FC",
135892
136763
  pink400: "#FF6B9D",
135893
136764
  cyan400: "#56D4DD",
135894
136765
  amber400: "#E8A838",
@@ -135905,6 +136776,10 @@ const dark = {
135905
136776
  };
135906
136777
  const light = {
135907
136778
  yellowGreen700: "#4B7A06",
136779
+ gold: "#A16207",
136780
+ orange: "#C2410C",
136781
+ blue: "#1565C0",
136782
+ violet: "#7C3AED",
135908
136783
  pink700: "#C2185B",
135909
136784
  cyan800: "#006978",
135910
136785
  gray900: "#1A1A1A",
@@ -135921,14 +136796,19 @@ const darkColors = {
135921
136796
  accent: dark.pink400,
135922
136797
  planMode: dark.cyan400,
135923
136798
  fusionPlanMode: dark.amber500,
135924
- wolfpackMode: "#C084FC",
135925
- rlmMode: "#FFD700",
136799
+ wolfpackMode: dark.violet,
136800
+ rlmMode: dark.gold,
136801
+ permissionManual: dark.yellowGreen,
136802
+ permissionYolo: dark.gold,
136803
+ permissionAuto: dark.coral,
136804
+ permissionAsk: dark.skyBlue,
136805
+ permissionBot: dark.violet,
135926
136806
  text: dark.gray100,
135927
136807
  textStrong: dark.gray50,
135928
136808
  textDim: dark.gray500,
135929
136809
  textMuted: dark.gray600,
135930
136810
  mdLink: "#56B6C2",
135931
- mdCodeBlock: "#9CDCFE",
136811
+ mdCodeBlock: dark.skyBlue,
135932
136812
  mdCodeBlockBorder: "#5C6370",
135933
136813
  mdCodeBlockBg: "#16191f",
135934
136814
  mdQuote: "#7F848E",
@@ -135956,14 +136836,19 @@ const lightColors = {
135956
136836
  accent: light.pink700,
135957
136837
  planMode: light.cyan800,
135958
136838
  fusionPlanMode: light.amber700,
135959
- wolfpackMode: "#7C3AED",
135960
- rlmMode: "#A16207",
136839
+ wolfpackMode: light.violet,
136840
+ rlmMode: light.gold,
136841
+ permissionManual: light.yellowGreen700,
136842
+ permissionYolo: light.gold,
136843
+ permissionAuto: light.orange,
136844
+ permissionAsk: light.blue,
136845
+ permissionBot: light.violet,
135961
136846
  text: light.gray900,
135962
136847
  textStrong: light.gray900,
135963
136848
  textDim: light.gray700,
135964
136849
  textMuted: light.gray600,
135965
136850
  mdLink: "#007A8A",
135966
- mdCodeBlock: "#1565C0",
136851
+ mdCodeBlock: light.blue,
135967
136852
  mdCodeBlockBorder: "#848484",
135968
136853
  mdCodeBlockBg: "#f7f9fb",
135969
136854
  mdQuote: "#616161",
@@ -137282,14 +138167,14 @@ async function handleModelCommand(host, args) {
137282
138167
  const alias = trimmed;
137283
138168
  if (alias.length === 0) {
137284
138169
  await refreshModelsForPicker(host);
137285
- showModelPicker(host);
138170
+ await showModelPicker(host);
137286
138171
  return;
137287
138172
  }
137288
138173
  if (host.state.appState.availableModels[alias] === void 0) {
137289
138174
  host.showError(`Unknown model alias: ${alias}`);
137290
138175
  return;
137291
138176
  }
137292
- showModelPicker(host, alias);
138177
+ await showModelPicker(host, alias);
137293
138178
  }
137294
138179
  /**
137295
138180
  * Reload provider/model config before showing the model picker so models
@@ -137349,11 +138234,12 @@ async function applyEditorChoice(host, value) {
137349
138234
  host.setAppState({ editorCommand });
137350
138235
  host.showStatus(value.length > 0 ? `Editor set to "${value}".` : "编辑器设置为自动检测 ($VISUAL / $EDITOR)。");
137351
138236
  }
137352
- function showModelPicker(host, selectedValue = host.state.appState.model) {
138237
+ async function showModelPicker(host, selectedValue = host.state.appState.model) {
137353
138238
  if (Object.entries(host.state.appState.availableModels).length === 0) {
137354
138239
  host.showNotice("未配置模型", "运行 /config 自定义模型配置。");
137355
138240
  return;
137356
138241
  }
138242
+ const imageConfig = await readExistingImageConfig();
137357
138243
  host.mountEditorReplacement(new ModelSelectorComponent({
137358
138244
  models: host.state.appState.availableModels,
137359
138245
  currentValue: host.state.appState.model,
@@ -137361,6 +138247,10 @@ function showModelPicker(host, selectedValue = host.state.appState.model) {
137361
138247
  currentThinkingLevel: host.state.appState.thinkingLevel,
137362
138248
  colors: host.state.theme.colors,
137363
138249
  searchable: true,
138250
+ imageGeneration: imageConfig === void 0 ? { configured: false } : {
138251
+ configured: true,
138252
+ model: imageConfig.model
138253
+ },
137364
138254
  onSelect: ({ alias, thinkingLevel }) => {
137365
138255
  host.restoreEditor();
137366
138256
  performModelSwitch(host, alias, thinkingLevel);
@@ -138410,7 +139300,7 @@ async function guidedGoalSetup(host) {
138410
139300
  host.showNotice(t("goal.storm_breaker"), t("goal.conflict_loop"));
138411
139301
  return;
138412
139302
  }
138413
- const { TextInputDialogComponent } = await import("./text-input-dialog-HfsxLcQf.mjs");
139303
+ const { TextInputDialogComponent } = await import("./text-input-dialog-b-TqTP2z.mjs");
138414
139304
  const initialDesc = await promptText(host, TextInputDialogComponent, {
138415
139305
  title: t("goal.setup_title_initial"),
138416
139306
  subtitle: t("goal.setup_desc_hint"),
@@ -138431,7 +139321,7 @@ async function guidedGoalSetup(host) {
138431
139321
  await showGoalConfigWizard(host, session, confirmed.trim() || objective, false);
138432
139322
  }
138433
139323
  async function showGoalConfigWizard(host, session, objective, replace) {
138434
- const { TextInputDialogComponent } = await import("./text-input-dialog-HfsxLcQf.mjs");
139324
+ const { TextInputDialogComponent } = await import("./text-input-dialog-b-TqTP2z.mjs");
138435
139325
  const turnInput = await promptNumber(host, TextInputDialogComponent, {
138436
139326
  title: t("goal.wizard_title", { objective }),
138437
139327
  subtitle: t("goal.budget_turns_hint"),
@@ -140075,11 +140965,21 @@ var ActivityGroupComponent = class extends Container {
140075
140965
  });
140076
140966
  }
140077
140967
  /**
140078
- * Expanded state: the whole timeline in order. Rows are budgeted for the block
140968
+ * Expanded state, split by whether the block is still running. A running block
140969
+ * anchors its window on the newest steps — the part of the timeline still
140970
+ * moving — while a settled block keeps the window that starts at the first
140971
+ * step. Both spend one shared row budget for the block as a whole.
140972
+ */
140973
+ buildExpandedRows(width) {
140974
+ if (this.running) this.buildExpandedRowsTail(width);
140975
+ else this.buildExpandedRowsHead(width);
140976
+ }
140977
+ /**
140978
+ * Settled state: the whole timeline in order. Rows are budgeted for the block
140079
140979
  * as a whole, so a turn with dozens of steps cannot expand into hundreds of
140080
140980
  * rows; whatever does not fit is summarised in one row at the end.
140081
140981
  */
140082
- buildExpandedRows(width) {
140982
+ buildExpandedRowsHead(width) {
140083
140983
  this.bodyContainer.addChild(new Text(TREE_PIPE_ROW, 0, 0));
140084
140984
  let used = 1;
140085
140985
  let hidden = 0;
@@ -140100,6 +141000,39 @@ var ActivityGroupComponent = class extends Container {
140100
141000
  this.bodyContainer.addChild(new Text(`${BRANCH_PIPE}${BODY_TEXT_INDENT}${chalk.dim(summary)}`, 0, 0));
140101
141001
  }
140102
141002
  }
141003
+ /**
141004
+ * Running state: the newest steps, still in chronological order so the tail
141005
+ * reads top-down, with the older steps that no longer fit counted in one row
141006
+ * above them. The budget is spent from the newest end backwards and the newest
141007
+ * step always renders, mirroring the head-anchored loop's rule that the first
141008
+ * step always renders — a single oversized step cannot leave the block
141009
+ * expanded-but-empty in either direction. The end-of-tree summary of the
141010
+ * settled loop is structurally unreachable here: a running block never keeps
141011
+ * rows below its newest step, so there is nothing at the end to count.
141012
+ */
141013
+ buildExpandedRowsTail(width) {
141014
+ const visible = [];
141015
+ let used = 1;
141016
+ let hidden = 0;
141017
+ for (let index = this.segments.length - 1; index >= 0; index -= 1) {
141018
+ const segment = this.segments[index];
141019
+ const isLastStep = index === this.segments.length - 1;
141020
+ const rows = this.segmentRows(segment, width, isLastStep);
141021
+ const budget = 60 - (isLastStep ? 0 : 1);
141022
+ if (!isLastStep && used + rows.cost > budget) {
141023
+ hidden = index + 1;
141024
+ break;
141025
+ }
141026
+ visible.unshift(...rows.components);
141027
+ used += rows.cost;
141028
+ }
141029
+ this.bodyContainer.addChild(new Text(TREE_PIPE_ROW, 0, 0));
141030
+ if (hidden > 0) {
141031
+ const summary = t("activitygroup.segments_folded_above", { count: String(hidden) });
141032
+ this.bodyContainer.addChild(new Text(`${BRANCH_PIPE}${BODY_TEXT_INDENT}${chalk.dim(summary)}`, 0, 0));
141033
+ }
141034
+ for (const component of visible) this.bodyContainer.addChild(component);
141035
+ }
140103
141036
  /** Renders one step of the timeline: its branch row plus its own body rows. */
140104
141037
  segmentRows(segment, width, isLast) {
140105
141038
  if (segment.kind === "tool") {
@@ -141621,24 +142554,259 @@ function trimTrailingEmptyLines(lines) {
141621
142554
  return lines.slice(0, end);
141622
142555
  }
141623
142556
  /**
141624
- * Returns the tail of `text` whose UTF-8 byte length is at most `maxBytes`.
142557
+ * Returns the tail of `text` whose UTF-8 byte length is at most `maxBytes`
142558
+ * (plus one byte when a torn sequence's introducer ESC sits immediately before
142559
+ * the cut and the sequence's remainder provably closes — keeping the ESC makes
142560
+ * the sequence whole and hides its fragment), with the head aligned to a
142561
+ * boundary no ANSI escape sequence spans.
141625
142562
  * Iterates by Unicode code points so multi-byte characters and surrogate
141626
- * pairs are never split.
142563
+ * pairs are never split, then hands the cut to `safeTailStart`: success output
142564
+ * keeps its ANSI codes (only error output is stripped), and a raw byte cut
142565
+ * could land inside a sequence, leaving a fragment (`m`, `0m`, `[31`) that
142566
+ * `sanitizeShellOutput` cannot recognize because its ESC byte was cut away.
141627
142567
  */
141628
142568
  function truncateTailBytes(text, maxBytes) {
141629
142569
  if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
141630
142570
  const chars = Array.from(text);
141631
- let start = chars.length;
141632
142571
  let bytes = 0;
142572
+ let units = 0;
141633
142573
  for (let i = chars.length - 1; i >= 0; i--) {
141634
142574
  const char = chars[i];
141635
142575
  if (char === void 0) continue;
141636
142576
  const charBytes = Buffer.byteLength(char, "utf8");
141637
142577
  if (bytes + charBytes > maxBytes) break;
141638
142578
  bytes += charBytes;
141639
- start = i;
142579
+ units += char.length;
142580
+ }
142581
+ return text.slice(safeTailStart(text, text.length - units));
142582
+ }
142583
+ const ESC = "\x1B";
142584
+ /**
142585
+ * Largest share of a retained tail the boundary rules may discard.
142586
+ *
142587
+ * Both rules trade content for a head that is whole by construction: rule 1
142588
+ * restarts after the next `\n` and drops the torn line, and rule 2 skips the
142589
+ * remainder of a torn sequence. The trade only pays while the tail keeps a
142590
+ * (non-strict) majority — with one 5000-char line ahead, a 100-byte budget
142591
+ * would come back with the few bytes after it, and the reader asked for the
142592
+ * newest output, not for a tidy head. Past the bound the raw cut keeps the
142593
+ * content: a string payload stays visible, and a torn CSI or two-byte escape
142594
+ * run keeps the fragment it left in view, because skipping that remainder
142595
+ * would cost more than the fragment it hides — unless the introducer ESC sits
142596
+ * immediately before the head *and* the sequence provably closes, where one
142597
+ * unit of look-back keeps the sequence whole and the fragment never surfaces.
142598
+ * An unclosed run keeps the raw cut: with no terminator to hand the sanitizer,
142599
+ * backing onto its ESC would surface a bare ESC the sanitizer cannot strip.
142600
+ */
142601
+ const MAX_TAIL_DROP_SHARE = .5;
142602
+ /**
142603
+ * Move a tail cut point forward to a boundary no ANSI escape sequence spans.
142604
+ *
142605
+ * A raw `slice(-tail)` can land inside a sequence (`…\u001b[31|m…`), leaving a
142606
+ * fragment (`m`, `0m`, `[31`) whose ESC byte was cut away —
142607
+ * `sanitizeShellOutput` only recognizes complete sequences, so the fragment
142608
+ * renders as text. Two provable rules keep the head clean:
142609
+ *
142610
+ * 1. Line alignment: a CSI sequence cannot contain `\n` (LF is not a
142611
+ * parameter, intermediate or final byte), so a cut that lands mid-line
142612
+ * restarts after the next `\n`. The only loss is the torn partial line,
142613
+ * whose head cannot be trusted; every escape after the newline is whole.
142614
+ * Bounded by `MAX_TAIL_DROP_SHARE`, so one huge line cannot eat the budget.
142615
+ * 2. Torn-sequence skip: when the retained text is one line (no `\n` after
142616
+ * the cut), or an OSC/DCS/PM/APC payload spans the newline the cut aligned
142617
+ * to, the dropped prefix is inspected for a sequence still open at the cut
142618
+ * — a run of CSI body bytes (0x20–0x3F) reaching back to `ESC [`, an `ESC`
142619
+ * whose intermediate bytes were torn (`ESC ( B`), or a string-sequence
142620
+ * opener the cut landed inside. The head then skips exactly the bytes a
142621
+ * terminal would consume for that sequence, so no visible text is dropped —
142622
+ * but only while that skip stays within `MAX_TAIL_DROP_SHARE` of the tail.
142623
+ * A CSI body or escape-intermediate run can be arbitrarily long, so past
142624
+ * the bound the head keeps the newest bytes and the fragment the raw cut
142625
+ * left with them — or one unit earlier, onto an introducer ESC sitting
142626
+ * immediately before the head, so the whole sequence survives and is
142627
+ * stripped (`withinDropShare`) — but only when the skip proved the sequence
142628
+ * closed: an unclosed run keeps the raw cut, because with no terminator to
142629
+ * hand the sanitizer the ESC would surface bare and swallow what follows
142630
+ * it. So does the head for a string that never ends or ended ahead of the
142631
+ * cut. A sliver of the tail is worse than a fragment.
142632
+ *
142633
+ * `cut` is always a code-point boundary here (the byte loop above works in
142634
+ * code points), so unlike its manager-side twin there is no surrogate half to
142635
+ * drop, and `stringPayloadHead`'s clamp steps back onto a code point as well;
142636
+ * the one-unit look-back onto an introducer ESC (`withinDropShare`) — taken
142637
+ * only for a skip that proved its sequence closed — is a code point boundary
142638
+ * too. Mirrors `safeTailStart` in
142639
+ * `packages/agent-core/src/tools/background/manager.ts` — app code cannot
142640
+ * import agent-core directly, so the rule lives in both places.
142641
+ */
142642
+ function safeTailStart(text, cut) {
142643
+ if (cut <= 0 || cut >= text.length) return cut;
142644
+ const tail = text.length - cut;
142645
+ let start = cut;
142646
+ if (text[start - 1] !== "\n") {
142647
+ const newline = text.indexOf("\n", start);
142648
+ if (newline !== -1 && newline + 1 - cut <= tail * MAX_TAIL_DROP_SHARE) start = newline + 1;
142649
+ }
142650
+ return skipOpenEscape(text, start);
142651
+ }
142652
+ /** CSI parameter (0x30–0x3F) / intermediate (0x20–0x2F) bytes — everything before the final byte. */
142653
+ function isCsiBody(code) {
142654
+ return code !== void 0 && code >= 32 && code <= 63;
142655
+ }
142656
+ /** CSI final byte (0x40–0x7E) — the sequence ends here. */
142657
+ function isCsiFinal(code) {
142658
+ return code !== void 0 && code >= 64 && code <= 126;
142659
+ }
142660
+ /** OSC / DCS / PM / APC introducers — string sequences ended by BEL or ST. */
142661
+ function isStringIntro(intro) {
142662
+ return intro === "]" || intro === "P" || intro === "^" || intro === "_";
142663
+ }
142664
+ /** ESC-intermediate byte (0x20–0x2F) of a two-byte escape sequence. */
142665
+ function isEscapeIntermediate(code) {
142666
+ return code !== void 0 && code >= 32 && code <= 47;
142667
+ }
142668
+ /** Final byte (0x30–0x7E) that closes a two-byte escape sequence. */
142669
+ function isEscapeFinal(code) {
142670
+ return code !== void 0 && code >= 48 && code <= 126;
142671
+ }
142672
+ /** True when every code point in the half-open range `[from, to)` is an ESC intermediate (0x20–0x2F). */
142673
+ function allEscapeIntermediates(text, from, to) {
142674
+ for (let i = from; i < to; i += 1) if (!isEscapeIntermediate(text.codePointAt(i))) return false;
142675
+ return true;
142676
+ }
142677
+ /**
142678
+ * When the dropped prefix proves an escape sequence is still open at `cut`,
142679
+ * return the index after its remainder; otherwise return `cut` unchanged.
142680
+ */
142681
+ function skipOpenEscape(text, cut) {
142682
+ let run = cut;
142683
+ while (run > 0 && isCsiBody(text.codePointAt(run - 1))) run -= 1;
142684
+ if (run >= 2 && text[run - 1] === "[" && text[run - 2] === ESC) {
142685
+ const skip = skipCsiRest(text, cut);
142686
+ return withinDropShare(text, cut, skip.end, skip.closed);
142687
+ }
142688
+ if (text[run - 1] === ESC && allEscapeIntermediates(text, run, cut)) return skipEscapeRest(text, cut);
142689
+ const open = text.lastIndexOf(ESC, cut - 1);
142690
+ if (open !== -1 && isStringIntro(text[open + 1])) return stringSequenceHead(text, open, cut);
142691
+ return cut;
142692
+ }
142693
+ /**
142694
+ * Keep a provable skip only while it stays within `MAX_TAIL_DROP_SHARE` of the
142695
+ * tail that starts at `from`: the skipped bytes are exactly what the reader
142696
+ * loses from the tail it asked for. A CSI body or escape-intermediate run can
142697
+ * be arbitrarily long, so past the bound the raw cut is worth more than the
142698
+ * clean head — except when the sequence's introducer ESC sits immediately
142699
+ * before the head (`…\u001b|[31m…`) *and* `closed` says the skip found the
142700
+ * sequence's terminator, where one unit of look-back keeps the sequence whole
142701
+ * instead: the sanitizer strips it and the visible text is the skip's, for
142702
+ * that one unit rather than a sliver of the tail. An unclosed run must keep
142703
+ * the raw cut even with that ESC one unit ahead: nothing terminates it, so
142704
+ * look-back would hand the reader a bare ESC whose sequence run a terminal
142705
+ * swallows along with the bytes behind it.
142706
+ */
142707
+ function withinDropShare(text, from, target, closed) {
142708
+ if (target - from <= (text.length - from) * MAX_TAIL_DROP_SHARE) return target;
142709
+ return closed && from > 0 && text[from - 1] === ESC ? from - 1 : from;
142710
+ }
142711
+ /**
142712
+ * The rest of a CSI sequence whose body was torn at `cut`, with the closure
142713
+ * its skip proved: `closed` holds only when a final byte (0x40–0x7E) was
142714
+ * actually found, so a parameter run that reaches the end of `text` — or stops
142715
+ * on a byte no CSI can end with — reports the sequence as open.
142716
+ */
142717
+ function skipCsiRest(text, cut) {
142718
+ let end = cut;
142719
+ while (end < text.length && isCsiBody(text.codePointAt(end))) end += 1;
142720
+ const closed = end < text.length && isCsiFinal(text.codePointAt(end));
142721
+ return {
142722
+ end: closed ? end + 1 : end,
142723
+ closed
142724
+ };
142725
+ }
142726
+ /** Index after the escape sequence whose introducer ESC sits at `cut - 1`. */
142727
+ function skipEscapeRest(text, cut) {
142728
+ const intro = text[cut];
142729
+ if (intro === "[") {
142730
+ const skip = skipCsiRest(text, cut + 1);
142731
+ return withinDropShare(text, cut, skip.end, skip.closed);
142732
+ }
142733
+ if (isStringIntro(intro)) return stringSequenceHead(text, cut - 1, cut + 1);
142734
+ let end = cut;
142735
+ while (end < text.length && isEscapeIntermediate(text.codePointAt(end))) end += 1;
142736
+ const closed = end < text.length && isEscapeFinal(text.codePointAt(end));
142737
+ return withinDropShare(text, cut, closed ? end + 1 : end, closed);
142738
+ }
142739
+ /**
142740
+ * Head index for a cut that lands inside the string sequence opened at `open`.
142741
+ *
142742
+ * `stringEnd` gives the byte a terminal stops at; skipping to it hides the
142743
+ * payload's remainder, which is what a terminal shows — but only while that
142744
+ * costs at most `MAX_TAIL_DROP_SHARE` of the tail. A long OSC 8 URL, or any
142745
+ * payload longer than the budget, would otherwise hand the reader a sliver of
142746
+ * the tail it asked for; a payload whose extent exceeds the budget stays
142747
+ * visible instead. A cut the string already ended ahead of needs no skip, and
142748
+ * an unterminated one must not swallow the tail (`stringPayloadHead`).
142749
+ */
142750
+ function stringSequenceHead(text, open, cut) {
142751
+ const drop = stringEnd(text, open + 2) - cut;
142752
+ if (drop >= 0 && drop <= (text.length - cut) * MAX_TAIL_DROP_SHARE) return cut + drop;
142753
+ return stringPayloadHead(text, open, cut);
142754
+ }
142755
+ /**
142756
+ * Head index that keeps a string sequence's payload visible, moving the cut
142757
+ * only past the opener's own bytes when the cut landed inside them.
142758
+ *
142759
+ * A terminal swallows an unterminated payload, but a viewer must never render
142760
+ * a blank body: a shell card whose output opens with an unterminated OSC — a
142761
+ * command killed mid-title, a truncated write — would otherwise show nothing
142762
+ * at all. The head stays at `cut` unless the cut landed inside the opener
142763
+ * (`\u001b]0;` would leave `0;` in front of the payload), and never reaches
142764
+ * `text.length` — the clamp to the last unit steps back onto the pair's first
142765
+ * half when that unit is a trailing surrogate pair's low half (defensive here:
142766
+ * `truncateTailBytes` cuts on a code point boundary, so the clamp cannot land
142767
+ * between a pair's halves in practice) — so this rule never empties the tail;
142768
+ * the tail comes back empty only when the byte budget fits none of the last
142769
+ * character.
142770
+ */
142771
+ function stringPayloadHead(text, open, cut) {
142772
+ const head = Math.min(Math.max(cut, stringPayloadStart(text, open)), text.length - 1);
142773
+ const code = text.codePointAt(head);
142774
+ return head > 0 && code !== void 0 && code >= 56320 && code <= 57343 ? head - 1 : head;
142775
+ }
142776
+ /**
142777
+ * Index after the byte that ends the string sequence whose payload starts at
142778
+ * `from` — its BEL or `ESC \` terminator, or a CAN (0x18) / SUB (0x1A), which
142779
+ * a terminal reads as "string over, resume normal parsing". `-1` when the
142780
+ * string never ends.
142781
+ */
142782
+ function stringEnd(text, from) {
142783
+ for (let i = from; i < text.length; i += 1) {
142784
+ const code = text.codePointAt(i);
142785
+ if (code === 7) return i + 1;
142786
+ if (code === 27 && text[i + 1] === "\\") return i + 2;
142787
+ if (code === 24 || code === 26) return i + 1;
142788
+ }
142789
+ return -1;
142790
+ }
142791
+ /**
142792
+ * Index where the payload of the string sequence opened at `open` starts: for
142793
+ * OSC after `ESC ] Ps ;`, for DCS/PM/APC after their parameter and
142794
+ * intermediate bytes and the final byte that opens the payload.
142795
+ */
142796
+ function stringPayloadStart(text, open) {
142797
+ let i = open + 2;
142798
+ if (text[open + 1] === "]") {
142799
+ while (i < text.length && isOscParam(text.codePointAt(i))) i += 1;
142800
+ if (text[i] === ";") i += 1;
142801
+ return i;
141640
142802
  }
141641
- return chars.slice(start).join("");
142803
+ while (i < text.length && isCsiBody(text.codePointAt(i))) i += 1;
142804
+ const final = text.codePointAt(i);
142805
+ return i < text.length && isCsiFinal(final) ? i + 1 : i;
142806
+ }
142807
+ /** OSC numeric parameter byte (0x30–0x39) — the `Ps` before the `;` separator. */
142808
+ function isOscParam(code) {
142809
+ return code !== void 0 && code >= 48 && code <= 57;
141642
142810
  }
141643
142811
  /**
141644
142812
  * Component that renders tool output with wrap-aware line truncation.
@@ -142651,6 +143819,15 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
142651
143819
  * background agent — including lost ones — as `✓ Completed`.
142652
143820
  */
142653
143821
  backgroundTaskTerminalPhase;
143822
+ /**
143823
+ * True when a foreground subagent was handed to the background manager
143824
+ * mid-run (the request-leg / timeout handoff). The Agent tool still returns
143825
+ * a normal result — its body carries `status: backgrounded` — which the
143826
+ * result-based derivation would otherwise read as `done`; this mark keeps
143827
+ * the card on `backgrounded` until a real terminal status
143828
+ * (`backgroundTaskTerminalPhase`) arrives, which still wins.
143829
+ */
143830
+ subagentBackgrounded = false;
142654
143831
  subagentContextTokens;
142655
143832
  subagentUsage;
142656
143833
  /** Latest activity (Using X / Used Y) for the running-phase chip. */
@@ -142911,7 +144088,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
142911
144088
  const tokens = contextTokens && contextTokens > 0 ? contextTokens : this.subagentUsage === void 0 ? 0 : usageTotal(this.subagentUsage);
142912
144089
  const latestActivity = computeLatestActivity(this.ongoingSubCalls, this.finishedSubCalls, this.getCombinedSubagentText(), this.workspaceDir, this.subagentPhase === "running" ? this.ongoingSubCalls.size === 0 && this.subagentText === "" : void 0);
142913
144090
  this.latestActivity = latestActivity;
142914
- const derivedPhase = this.backgroundTaskTerminalPhase ?? (this.result !== void 0 ? this.result.is_error ? "failed" : "done" : this.subagentPhase);
144091
+ const derivedPhase = this.backgroundTaskTerminalPhase ?? (this.subagentBackgrounded ? "backgrounded" : this.result !== void 0 ? this.result.is_error ? "failed" : "done" : this.subagentPhase);
142915
144092
  const errorText = this.subagentError ?? (derivedPhase === "failed" ? this.result?.output : void 0);
142916
144093
  return {
142917
144094
  toolCallId: this.toolCall.id,
@@ -143114,6 +144291,20 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
143114
144291
  this.notifySnapshotChange();
143115
144292
  }
143116
144293
  /**
144294
+ * Marks the run as handed off to the background manager (foreground→
144295
+ * background). Idempotent, and never downgrades a terminal phase: the card
144296
+ * reads `backgrounded` until `setBackgroundTaskTerminalStatus` reports the
144297
+ * real end state.
144298
+ */
144299
+ setSubagentBackgrounded() {
144300
+ if (this.subagentBackgrounded) return;
144301
+ this.subagentBackgrounded = true;
144302
+ this.headerText.setText(this.buildHeader());
144303
+ this.rebuildContent();
144304
+ this.notifySnapshotChange();
144305
+ this.ui?.requestRender();
144306
+ }
144307
+ /**
143117
144308
  * Subagent id for the backing AgentTool call, used by routing to find a
143118
144309
  * tool call's backing subagent when reconciling background task lifecycle
143119
144310
  * events.
@@ -143313,7 +144504,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
143313
144504
  for (const component of components) this.addChild(component);
143314
144505
  }
143315
144506
  buildSubagentBlock() {
143316
- if (this.subagentAgentId === void 0 && this.ongoingSubCalls.size === 0 && this.finishedSubCalls.length === 0 && this.subagentText.length === 0 && this.subagentPhase === void 0 && this.backgroundTaskTerminalPhase === void 0) return;
144507
+ if (this.subagentAgentId === void 0 && this.ongoingSubCalls.size === 0 && this.finishedSubCalls.length === 0 && this.subagentText.length === 0 && this.subagentPhase === void 0 && this.backgroundTaskTerminalPhase === void 0 && !this.subagentBackgrounded) return;
143317
144508
  if (this.isSingleSubagentView()) {
143318
144509
  this.buildSingleSubagentBlock();
143319
144510
  return;
@@ -143394,13 +144585,14 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
143394
144585
  return id.length > 10 ? id.slice(0, 10) + "…" : id;
143395
144586
  }
143396
144587
  hasSubagentState() {
143397
- return this.subagentAgentId !== void 0 || this.ongoingSubCalls.size > 0 || this.finishedSubCalls.length > 0 || this.subToolActivities.size > 0 || this.subagentText.length > 0 || this.subagentThinkingText.length > 0 || this.subagentPhase !== void 0 || this.backgroundTaskTerminalPhase !== void 0;
144588
+ return this.subagentAgentId !== void 0 || this.ongoingSubCalls.size > 0 || this.finishedSubCalls.length > 0 || this.subToolActivities.size > 0 || this.subagentText.length > 0 || this.subagentThinkingText.length > 0 || this.subagentPhase !== void 0 || this.backgroundTaskTerminalPhase !== void 0 || this.subagentBackgrounded;
143398
144589
  }
143399
144590
  isSingleSubagentView() {
143400
144591
  return this.toolCall.name === "Agent" && this.hasSubagentState();
143401
144592
  }
143402
144593
  getDerivedSubagentPhase() {
143403
144594
  if (this.backgroundTaskTerminalPhase !== void 0) return this.backgroundTaskTerminalPhase;
144595
+ if (this.subagentBackgrounded) return "backgrounded";
143404
144596
  if (this.result !== void 0) return this.result.is_error ? "failed" : "done";
143405
144597
  return this.subagentPhase;
143406
144598
  }
@@ -143427,7 +144619,7 @@ var ToolCallComponent = class ToolCallComponent extends CachedContainer {
143427
144619
  case "done": return chalk.hex(this.colors.success)(t("toolcall.completed"));
143428
144620
  case "failed": return chalk.hex(this.colors.error)(t("toolcall.failed"));
143429
144621
  case "running": return chalk.hex(this.colors.primary)(t("toolcall.running"));
143430
- case "backgrounded": return t("toolcall.bg_running");
144622
+ case "backgrounded": return this.subagentBackgrounded ? chalk.hex(this.colors.warning)(`◐ ${t("toolcall.bg_handed_off")}`) : t("toolcall.bg_running");
143431
144623
  case "spawning":
143432
144624
  case void 0: return chalk.hex(this.colors.primary)(t("toolcall.starting"));
143433
144625
  }
@@ -143863,6 +145055,7 @@ async function handleRevokeCommand(host, args = "") {
143863
145055
  const preservedEntries = entries.slice(lastUserIndex).filter((entry) => !isRevokeContextEntry(entry));
143864
145056
  entries.splice(lastUserIndex, entries.length - lastUserIndex, ...preservedEntries);
143865
145057
  if (entries.length === 0) renderWelcome(host);
145058
+ host.state.ui.resetTextSelection();
143866
145059
  host.state.ui.requestRender();
143867
145060
  }
143868
145061
  function parseRevokeCount(args) {
@@ -146547,12 +147740,14 @@ function showValuePicker(host, key) {
146547
147740
  onSelect: (value) => {
146548
147741
  const parsed = Number(value);
146549
147742
  if (!Number.isFinite(parsed)) return;
147743
+ const resized = parsed !== getActivityLineValue(key);
146550
147744
  setActivityLineValue(key, parsed);
146551
147745
  host.restoreEditor();
146552
147746
  host.showStatus(t("blockrows.saved", {
146553
147747
  label: t(setting.label),
146554
147748
  value: String(parsed)
146555
147749
  }), host.state.theme.colors.success);
147750
+ if (resized) host.state.ui.resetTextSelection();
146556
147751
  repaintTranscript(host);
146557
147752
  },
146558
147753
  onCancel: () => {
@@ -147135,8 +148330,10 @@ function buildOptions() {
147135
148330
  }
147136
148331
  /** Apply a choice: redraw what is already on screen, restate the capability. */
147137
148332
  async function applyDisplay(host, value) {
148333
+ const previous = getMermaidDisplay();
147138
148334
  setMermaidDisplay(value);
147139
148335
  host.showStatus(t("mermaid.applied", { mode: optionLabel(value) }), value === "off" ? host.state.theme.colors.textDim : host.state.theme.colors.success);
148336
+ if (previous !== value && (previous === "off" || value === "off")) host.state.ui.resetTextSelection();
147140
148337
  repaintTranscript(host);
147141
148338
  await syncDiagramCapabilityPrompt(host.session);
147142
148339
  }