@ccx-agent/opencode-ccx 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13553,15 +13553,46 @@ function date4(params) {
13553
13553
  config(en_default());
13554
13554
  // src/config/schema.ts
13555
13555
  var verificationSchema = exports_external.object({
13556
- auto_remind: exports_external.boolean().default(true),
13556
+ auto_remind: exports_external.boolean().default(false),
13557
+ enforce_contract: exports_external.boolean().default(false),
13557
13558
  min_file_edits: exports_external.int().nonnegative().default(3),
13558
13559
  spot_check_min_commands: exports_external.int().positive().default(2)
13559
13560
  });
13560
13561
  var riskGuardSchema = exports_external.object({
13561
13562
  enforce_high_risk_confirmation: exports_external.boolean().default(true)
13562
13563
  });
13564
+ var contextBundleSchema = exports_external.object({
13565
+ enabled: exports_external.boolean().default(true),
13566
+ include_cwd: exports_external.boolean().default(true),
13567
+ include_git: exports_external.boolean().default(true),
13568
+ include_recent_files: exports_external.boolean().default(true),
13569
+ max_recent_files: exports_external.int().nonnegative().default(8)
13570
+ });
13571
+ var sessionWorkflowsSchema = exports_external.object({
13572
+ enabled: exports_external.boolean().default(true),
13573
+ fork_command: exports_external.string().min(1).default("/ccx-fork"),
13574
+ background_command: exports_external.string().min(1).default("/ccx-bg"),
13575
+ full_context_command: exports_external.string().min(1).default("/ccx-fullctx"),
13576
+ status_command: exports_external.string().min(1).default("/ccx-bg-status")
13577
+ });
13563
13578
  var subagentOrchestrationSchema = exports_external.object({
13564
- explore_min_queries: exports_external.int().positive().default(5)
13579
+ explore_min_queries: exports_external.int().positive().default(3),
13580
+ coordinator_enabled: exports_external.boolean().default(false),
13581
+ allow_subagent_delegation: exports_external.boolean().default(false),
13582
+ context_bundle: contextBundleSchema.default({
13583
+ enabled: true,
13584
+ include_cwd: true,
13585
+ include_git: true,
13586
+ include_recent_files: true,
13587
+ max_recent_files: 8
13588
+ }),
13589
+ session_workflows: sessionWorkflowsSchema.default({
13590
+ enabled: true,
13591
+ fork_command: "/ccx-fork",
13592
+ background_command: "/ccx-bg",
13593
+ full_context_command: "/ccx-fullctx",
13594
+ status_command: "/ccx-bg-status"
13595
+ })
13565
13596
  });
13566
13597
  var configSchema = exports_external.object({
13567
13598
  enabled: exports_external.boolean().default(true),
@@ -13569,7 +13600,8 @@ var configSchema = exports_external.object({
13569
13600
  disabled_hooks: exports_external.array(exports_external.string()).default([]),
13570
13601
  output_style: exports_external.string().min(1).nullable().default(null),
13571
13602
  verification: verificationSchema.default({
13572
- auto_remind: true,
13603
+ auto_remind: false,
13604
+ enforce_contract: false,
13573
13605
  min_file_edits: 3,
13574
13606
  spot_check_min_commands: 2
13575
13607
  }),
@@ -13577,7 +13609,23 @@ var configSchema = exports_external.object({
13577
13609
  enforce_high_risk_confirmation: true
13578
13610
  }),
13579
13611
  subagent_orchestration: subagentOrchestrationSchema.default({
13580
- explore_min_queries: 5
13612
+ explore_min_queries: 3,
13613
+ coordinator_enabled: false,
13614
+ allow_subagent_delegation: false,
13615
+ context_bundle: {
13616
+ enabled: true,
13617
+ include_cwd: true,
13618
+ include_git: true,
13619
+ include_recent_files: true,
13620
+ max_recent_files: 8
13621
+ },
13622
+ session_workflows: {
13623
+ enabled: true,
13624
+ fork_command: "/ccx-fork",
13625
+ background_command: "/ccx-bg",
13626
+ full_context_command: "/ccx-fullctx",
13627
+ status_command: "/ccx-bg-status"
13628
+ }
13581
13629
  })
13582
13630
  });
13583
13631
 
@@ -13653,6 +13701,10 @@ function loadConfig(directory) {
13653
13701
  }
13654
13702
 
13655
13703
  // src/hooks/chat-message.ts
13704
+ var sessionAgentById = new Map;
13705
+ function getSessionAgent(sessionID) {
13706
+ return sessionAgentById.get(sessionID);
13707
+ }
13656
13708
  function createChatMessageHook(_config) {
13657
13709
  return async (input, _output) => {
13658
13710
  if (!_config.enabled)
@@ -13660,6 +13712,9 @@ function createChatMessageHook(_config) {
13660
13712
  const { sessionID, agent } = input;
13661
13713
  if (!sessionID)
13662
13714
  return;
13715
+ if (agent) {
13716
+ sessionAgentById.set(sessionID, agent);
13717
+ }
13663
13718
  if (agent && !agent.startsWith("ccx"))
13664
13719
  return;
13665
13720
  };
@@ -13981,6 +14036,7 @@ Tool usage:
13981
14036
  - "Read" \u2014 when you already know the exact path to examine
13982
14037
  - "Bash" \u2014 permitted only for non-mutating operations (ls, git status, git log, git diff, find, grep, cat, head, tail)
13983
14038
  - "Bash" is off-limits for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or anything that creates or alters files
14039
+ - Execute the assigned search directly. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it
13984
14040
  - Calibrate your search depth according to the thoroughness level the caller requests
13985
14041
  - Deliver your findings as a direct text response \u2014 never try to write results to a file
13986
14042
 
@@ -14026,8 +14082,9 @@ You will receive a set of requirements and potentially a guiding perspective on
14026
14082
  - Map the current system structure
14027
14083
  - Locate analogous features that can serve as templates
14028
14084
  - Walk through the relevant execution flows
14029
- - "Bash" is allowed exclusively for non-mutating commands (ls, git status, git log, git diff, find, grep, cat, head, tail)
14030
- - "Bash" is off-limits for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or anything that creates or modifies files
14085
+ - "Bash" is allowed exclusively for non-mutating commands (ls, git status, git log, git diff, find, grep, cat, head, tail)
14086
+ - "Bash" is off-limits for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or anything that creates or modifies files
14087
+ - Execute planning work directly. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it
14031
14088
 
14032
14089
  3. **Architect the Solution**:
14033
14090
  - Formulate an implementation strategy aligned with your assigned perspective
@@ -14072,7 +14129,8 @@ Operating principles:
14072
14129
  - When analyzing: begin with broad searches, then zoom in. If one search strategy comes up empty, try a different angle.
14073
14130
  - Be comprehensive: inspect multiple directories, account for alternative naming styles, and look for related modules.
14074
14131
  - NEVER generate new files unless the task strictly demands it. ALWAYS modify an existing file rather than creating a fresh one.
14075
- - NEVER spontaneously produce documentation files (*.md) or README files. Only generate documentation when the user explicitly asks for it.`;
14132
+ - NEVER spontaneously produce documentation files (*.md) or README files. Only generate documentation when the user explicitly asks for it.
14133
+ - If you are running as a subagent, execute directly. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it.`;
14076
14134
  function getGeneralPurposeAgentPrompt() {
14077
14135
  return `${SHARED_PREFIX} Once finished, provide a brief summary of what was accomplished and any notable discoveries \u2014 this will be relayed to the user, so focus on the essential takeaways.
14078
14136
 
@@ -14100,6 +14158,8 @@ You ARE permitted to write throwaway test harnesses to a temporary directory (/t
14100
14158
 
14101
14159
  Inspect what tools are actually available in your session rather than making assumptions. You may have access to browser automation, HTTP fetching, or additional MCP capabilities \u2014 do not neglect tools you failed to check for.
14102
14160
 
14161
+ Execute verification directly in this session. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it.
14162
+
14103
14163
  === WHAT YOU RECEIVE ===
14104
14164
  You will be given: the original task specification, the list of changed files, the implementation approach, and optionally a path to a plan or spec document.
14105
14165
 
@@ -14355,29 +14415,48 @@ When a worker reports failure:
14355
14415
 
14356
14416
  - Reserve direct answers for simple questions that need no tool invocation.
14357
14417
  - For substantial engineering work, operate through workers.
14418
+ - Do not spawn additional coordinator agents. Keep delegation chains shallow and route work to execution-focused workers.
14358
14419
  - Do not assign one worker to monitor another worker.
14359
14420
  - Do not speculate about results that have not yet arrived.
14360
14421
  - After dispatching workers, inform the user what was launched and what remains pending.
14361
14422
  - Digest findings before assigning follow-up work.
14362
14423
  - Never implement directly when delegation is an option.
14363
14424
 
14425
+ ## Tool Surface (Enforced)
14426
+
14427
+ - Your tool surface is intentionally narrow: use 1) the \`task\` tool to delegate work, and 2) the \`question\` tool only when user input is strictly required.
14428
+ - Do not execute implementation tools directly (Bash/Read/Edit/Write/Glob/Grep/etc.) from coordinator mode.
14429
+
14364
14430
  Your operating loop is: comprehend -> decompose -> delegate -> digest -> delegate next phase -> verify -> report.`;
14365
14431
  }
14366
14432
  var COORDINATOR_AGENT_DEFINITION = {
14367
14433
  name: "coordinator",
14368
14434
  description: "Task orchestration agent for complex engineering work. Deploy this when a request should be decomposed into research, implementation, and verification phases distributed across multiple worker agents rather than executed by a single agent.",
14369
- getSystemPrompt: getCoordinatorAgentPrompt
14435
+ getSystemPrompt: getCoordinatorAgentPrompt,
14436
+ allowedTools: ["task", "question"]
14370
14437
  };
14371
14438
 
14372
14439
  // src/hooks/config-handler.ts
14373
- var SUBAGENT_DEFINITIONS = [
14440
+ var BASE_SUBAGENT_DEFINITIONS = [
14374
14441
  EXPLORE_AGENT_DEFINITION,
14375
14442
  PLAN_AGENT_DEFINITION,
14376
14443
  GENERAL_PURPOSE_AGENT_DEFINITION,
14377
- VERIFICATION_AGENT_DEFINITION,
14378
- COORDINATOR_AGENT_DEFINITION
14444
+ VERIFICATION_AGENT_DEFINITION
14379
14445
  ];
14446
+ function getEnabledSubagentDefinitions(config2) {
14447
+ if (config2.subagent_orchestration.coordinator_enabled) {
14448
+ return [...BASE_SUBAGENT_DEFINITIONS, COORDINATOR_AGENT_DEFINITION];
14449
+ }
14450
+ return BASE_SUBAGENT_DEFINITIONS;
14451
+ }
14380
14452
  function buildToolRestrictions(def) {
14453
+ if (def.allowedTools && def.allowedTools.length > 0) {
14454
+ const tools2 = { "*": false };
14455
+ for (const tool of def.allowedTools) {
14456
+ tools2[tool.toLowerCase()] = true;
14457
+ }
14458
+ return tools2;
14459
+ }
14381
14460
  if (!def.disallowedTools || def.disallowedTools.length === 0)
14382
14461
  return;
14383
14462
  const tools = { "*": true };
@@ -14389,40 +14468,57 @@ function buildToolRestrictions(def) {
14389
14468
  function buildSubagentGuidance(config2) {
14390
14469
  const exploreMinQueries = config2.subagent_orchestration.explore_min_queries;
14391
14470
  const spotCheckMinCommands = config2.verification.spot_check_min_commands;
14392
- const agentList = SUBAGENT_DEFINITIONS.map((def) => `- **ccx-${def.name}**: ${def.description}`).join(`
14471
+ const enabledSubagents = getEnabledSubagentDefinitions(config2);
14472
+ const agentList = enabledSubagents.map((def) => `- **ccx-${def.name}**: ${def.description}`).join(`
14393
14473
  `);
14474
+ const whenToUse = [
14475
+ `- Invoke the **task** tool with subagent_type \`ccx-explore\` for wide-ranging codebase exploration or in-depth research. For targeted lookups (a known file, class, or function name), use Glob or Grep directly \u2014 escalate to ccx-explore only when a simple search falls short or when the task clearly requires more than ${exploreMinQueries} queries.`,
14476
+ "- Invoke the **task** tool with subagent_type `ccx-plan` when an implementation strategy should be designed before any code is written. The plan agent examines the codebase in read-only mode and produces a step-by-step approach with key files identified.",
14477
+ "- Invoke the **task** tool with subagent_type `ccx-general-purpose` for multi-step work that does not fall under any other specialist's domain."
14478
+ ];
14479
+ if (config2.subagent_orchestration.coordinator_enabled) {
14480
+ whenToUse.push("- Invoke the **task** tool with subagent_type `ccx-coordinator` for complex tasks best decomposed into research, implementation, and verification phases distributed across multiple workers.");
14481
+ }
14482
+ const subagentUsageRules = [
14483
+ "- Subagents excel at running independent queries concurrently and keeping bulky output out of the main context, but avoid overusing them when the work is simple enough to handle directly.",
14484
+ "- Do NOT redo work that a subagent is already performing \u2014 once you delegate a research task, refrain from executing the same searches yourself.",
14485
+ "- When dispatching subagents, inform the user about what was launched and what results you are awaiting.",
14486
+ "- You may launch several subagents concurrently by issuing multiple task tool calls within a single response."
14487
+ ];
14488
+ if (config2.subagent_orchestration.allow_subagent_delegation) {
14489
+ subagentUsageRules.push("- If you are already operating as a subagent, prefer executing directly and keep delegation chains shallow.");
14490
+ } else {
14491
+ subagentUsageRules.push("- If you are already operating as a subagent, execute directly and avoid recursively dispatching more subagents unless the user explicitly requests delegation.");
14492
+ }
14493
+ const verificationSection = config2.verification.enforce_contract ? `## Verification contract
14494
+
14495
+ The rule: whenever non-trivial implementation occurs during your turn, an independent adversarial review must take place before you declare completion \u2014 whether you wrote the code yourself or a subagent did. You are the gatekeeper. Non-trivial is defined as: 3+ file edits, backend/API changes, or infrastructure changes.
14496
+
14497
+ Launch the **task** tool with subagent_type \`ccx-verification\`. Supply the ORIGINAL user task description, the list of changed files, and the approach used. Your own review and commentary do NOT count \u2014 only the verification agent assigns a verdict; you may not self-assign PARTIAL.
14498
+
14499
+ - On **FAIL**: address the reported issue, then resume the verifier session with the failure details plus your correction. Iterate until PASS.
14500
+ - On **PASS**: perform a spot-check \u2014 re-execute at least ${spotCheckMinCommands} commands from the verifier's report and confirm outputs match. If any PASS step lacks a Command run block or the output differs, resume the verifier with the discrepancy.
14501
+ - On **PARTIAL**: communicate what passed and what remained unverifiable due to environment constraints.` : "## Verification guidance\n\nFor significant implementation changes, prefer independent verification with subagent_type `ccx-verification` before reporting completion.";
14394
14502
  return `# Subagent orchestration
14395
14503
 
14396
- The \`task\` tool lets you launch specialized subagents. Leverage them to distribute work in parallel and shield your primary context window from being overwhelmed by verbose output.
14504
+ Use the \`task\` tool with specialized subagents when the current task clearly matches their role. Subagents are useful for parallelizing independent work and protecting the main context window from bulky output, but they should not be used excessively.
14397
14505
 
14398
- Reach for the task tool proactively when the current job aligns with a subagent's specialty. If a subagent's description indicates proactive usage, invoke it on your own initiative rather than waiting for the user to request it.
14506
+ Avoid duplicate work: once a search or investigation is delegated, do not run the same lookups in parallel from the current agent.
14399
14507
 
14400
14508
  ## Available subagents
14401
14509
  ${agentList}
14402
14510
 
14403
14511
  ## When to use subagents
14404
14512
 
14405
- - Invoke the **task** tool with subagent_type \`ccx-explore\` for wide-ranging codebase exploration or in-depth research. For targeted lookups (a known file, class, or function name), use Glob or Grep directly \u2014 escalate to ccx-explore only when a simple search falls short or when the task clearly requires more than ${exploreMinQueries} queries.
14406
- - Invoke the **task** tool with subagent_type \`ccx-plan\` when an implementation strategy should be designed before any code is written. The plan agent examines the codebase in read-only mode and produces a step-by-step approach with key files identified.
14407
- - Invoke the **task** tool with subagent_type \`ccx-general-purpose\` for multi-step work that does not fall under any other specialist's domain.
14408
- - Invoke the **task** tool with subagent_type \`ccx-coordinator\` for complex tasks best decomposed into research, implementation, and verification phases distributed across multiple workers.
14409
-
14410
- ## Verification contract
14513
+ ${whenToUse.join(`
14514
+ `)}
14411
14515
 
14412
- The rule: whenever non-trivial implementation occurs during your turn, an independent adversarial review must take place before you declare completion \u2014 whether you wrote the code yourself or a subagent did. You are the gatekeeper. Non-trivial is defined as: 3+ file edits, backend/API changes, or infrastructure changes.
14413
-
14414
- Launch the **task** tool with subagent_type \`ccx-verification\`. Supply the ORIGINAL user task description, the list of changed files, and the approach used. Your own review and commentary do NOT count \u2014 only the verification agent assigns a verdict; you may not self-assign PARTIAL.
14415
-
14416
- - On **FAIL**: address the reported issue, then resume the verifier session with the failure details plus your correction. Iterate until PASS.
14417
- - On **PASS**: perform a spot-check \u2014 re-execute at least ${spotCheckMinCommands} commands from the verifier's report and confirm outputs match. If any PASS step lacks a Command run block or the output differs, resume the verifier with the discrepancy.
14418
- - On **PARTIAL**: communicate what passed and what remained unverifiable due to environment constraints.
14516
+ ${verificationSection}
14419
14517
 
14420
14518
  ## Subagent usage rules
14421
14519
 
14422
- - Subagents excel at running independent queries concurrently and keeping bulky output out of the main context, but avoid overusing them when the work is simple enough to handle directly.
14423
- - Do NOT redo work that a subagent is already performing \u2014 once you delegate a research task, refrain from executing the same searches yourself.
14424
- - When dispatching subagents, inform the user about what was launched and what results you are awaiting.
14425
- - You may launch several subagents concurrently by issuing multiple task tool calls within a single response.`;
14520
+ ${subagentUsageRules.join(`
14521
+ `)}`;
14426
14522
  }
14427
14523
  function createConfigHook(config2, directory) {
14428
14524
  return async (input) => {
@@ -14450,8 +14546,9 @@ function createConfigHook(config2, directory) {
14450
14546
  prompt: mainPrompt,
14451
14547
  tools: { "*": true }
14452
14548
  };
14549
+ const enabledSubagents = getEnabledSubagentDefinitions(config2);
14453
14550
  const subagents = {};
14454
- for (const def of SUBAGENT_DEFINITIONS) {
14551
+ for (const def of enabledSubagents) {
14455
14552
  subagents[`ccx-${def.name}`] = {
14456
14553
  description: def.description,
14457
14554
  mode: "subagent",
@@ -14470,9 +14567,9 @@ function createConfigHook(config2, directory) {
14470
14567
  };
14471
14568
  }
14472
14569
 
14473
- // src/hooks/dynamic-system-prompt.ts
14474
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
14475
- import { join as join3 } from "path";
14570
+ // src/hooks/context-bundle.ts
14571
+ import { execFile as execFile2 } from "child_process";
14572
+ import { promisify as promisify2 } from "util";
14476
14573
 
14477
14574
  // src/hooks/git-context.ts
14478
14575
  import { execFile } from "child_process";
@@ -14550,11 +14647,109 @@ function createGitContextHook(directory) {
14550
14647
  };
14551
14648
  }
14552
14649
 
14650
+ // src/hooks/context-bundle.ts
14651
+ var execFileAsync2 = promisify2(execFile2);
14652
+ var TASK_TOOL_NAMES = new Set(["task"]);
14653
+ var BUNDLE_MARKER_BEGIN = "<ccx-context-bundle>";
14654
+ var BUNDLE_MARKER_END = "</ccx-context-bundle>";
14655
+ var MAX_LIST_CHARS = 1500;
14656
+ function isRecord2(value) {
14657
+ return typeof value === "object" && value !== null;
14658
+ }
14659
+ function pickPromptFieldName(args) {
14660
+ for (const key of ["message", "prompt", "task", "instruction"]) {
14661
+ if (typeof args[key] === "string")
14662
+ return key;
14663
+ }
14664
+ return null;
14665
+ }
14666
+ async function listRecentFiles(cwd, max) {
14667
+ if (max <= 0)
14668
+ return "";
14669
+ try {
14670
+ const { stdout } = await execFileAsync2("git", ["--no-optional-locks", "ls-files", "--modified", "--others", "--exclude-standard"], { cwd, timeout: 5000, maxBuffer: 1024 * 1024 });
14671
+ const files = stdout.split(`
14672
+ `).map((line) => line.trim()).filter(Boolean).slice(0, max);
14673
+ if (files.length === 0)
14674
+ return "";
14675
+ const joined = files.join(`
14676
+ `);
14677
+ return joined.length > MAX_LIST_CHARS ? `${joined.slice(0, MAX_LIST_CHARS)}
14678
+ ... (truncated)` : joined;
14679
+ } catch {
14680
+ return "";
14681
+ }
14682
+ }
14683
+ function createContextBundleHook(args) {
14684
+ const { config: config2, directory } = args;
14685
+ return async (input, output) => {
14686
+ if (!config2.subagent_orchestration.context_bundle.enabled)
14687
+ return;
14688
+ if (!isRecord2(input) || !isRecord2(output))
14689
+ return;
14690
+ const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : "";
14691
+ if (!TASK_TOOL_NAMES.has(toolName))
14692
+ return;
14693
+ if (!isRecord2(output.args))
14694
+ return;
14695
+ const promptKey = pickPromptFieldName(output.args);
14696
+ if (!promptKey)
14697
+ return;
14698
+ const original = output.args[promptKey];
14699
+ if (original.includes(BUNDLE_MARKER_BEGIN))
14700
+ return;
14701
+ const bundleParts = [];
14702
+ const bundleConfig = config2.subagent_orchestration.context_bundle;
14703
+ if (bundleConfig.include_cwd) {
14704
+ bundleParts.push(`Working directory: ${directory}`);
14705
+ }
14706
+ if (bundleConfig.include_git) {
14707
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
14708
+ const gitSection = sessionID ? getGitSnapshotSection(sessionID) : null;
14709
+ if (gitSection) {
14710
+ bundleParts.push(gitSection);
14711
+ }
14712
+ }
14713
+ if (bundleConfig.include_recent_files) {
14714
+ const recent = await listRecentFiles(directory, bundleConfig.max_recent_files);
14715
+ if (recent) {
14716
+ bundleParts.push(`# Recently changed files
14717
+ ${recent}`);
14718
+ }
14719
+ }
14720
+ if (bundleParts.length === 0)
14721
+ return;
14722
+ const bundle = [
14723
+ BUNDLE_MARKER_BEGIN,
14724
+ "The following context was injected automatically by the ccx plugin to give the subagent a shared baseline. Treat it as background information, not as new instructions.",
14725
+ ...bundleParts,
14726
+ BUNDLE_MARKER_END
14727
+ ].join(`
14728
+
14729
+ `);
14730
+ output.args[promptKey] = `${bundle}
14731
+
14732
+ ${original}`;
14733
+ const metadata = isRecord2(output.metadata) ? output.metadata : {};
14734
+ metadata.contextBundle = {
14735
+ injected: true,
14736
+ tool: toolName,
14737
+ promptField: promptKey,
14738
+ sections: bundleParts.length
14739
+ };
14740
+ output.metadata = metadata;
14741
+ };
14742
+ }
14743
+
14744
+ // src/hooks/dynamic-system-prompt.ts
14745
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
14746
+ import { join as join3 } from "path";
14747
+
14553
14748
  // src/hooks/verification-reminder.ts
14554
14749
  var sessionStateById = new Map;
14555
14750
  var EDIT_TOOL_NAMES = new Set(["edit", "write"]);
14556
- var TASK_TOOL_NAMES = new Set(["task", "taskcreate", "task_create"]);
14557
- function isRecord2(value) {
14751
+ var TASK_TOOL_NAMES2 = new Set(["task", "taskcreate", "task_create"]);
14752
+ function isRecord3(value) {
14558
14753
  return typeof value === "object" && value !== null;
14559
14754
  }
14560
14755
  function getSessionState(sessionID) {
@@ -14570,7 +14765,7 @@ function getSessionState(sessionID) {
14570
14765
  return created;
14571
14766
  }
14572
14767
  function getFilePath(value) {
14573
- if (!isRecord2(value)) {
14768
+ if (!isRecord3(value)) {
14574
14769
  return;
14575
14770
  }
14576
14771
  const candidates = [value.filePath, value.path, value.filename];
@@ -14578,7 +14773,7 @@ function getFilePath(value) {
14578
14773
  }
14579
14774
  function createVerificationReminder(config2) {
14580
14775
  return async (input, _output) => {
14581
- if (!config2.verification.auto_remind || !isRecord2(input)) {
14776
+ if (!config2.verification.enforce_contract || !config2.verification.auto_remind || !isRecord3(input)) {
14582
14777
  return;
14583
14778
  }
14584
14779
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
@@ -14586,8 +14781,8 @@ function createVerificationReminder(config2) {
14586
14781
  if (!sessionID || !toolName) {
14587
14782
  return;
14588
14783
  }
14589
- if (TASK_TOOL_NAMES.has(toolName)) {
14590
- const rawArgs = isRecord2(input.args) ? input.args : {};
14784
+ if (TASK_TOOL_NAMES2.has(toolName)) {
14785
+ const rawArgs = isRecord3(input.args) ? input.args : {};
14591
14786
  const subagentType = typeof rawArgs.subagent_type === "string" ? rawArgs.subagent_type.toLowerCase() : typeof rawArgs.subagentType === "string" ? rawArgs.subagentType.toLowerCase() : "";
14592
14787
  if (subagentType === "ccx-verification" || subagentType === "verification") {
14593
14788
  getSessionState(sessionID).verificationTriggered = true;
@@ -14689,7 +14884,7 @@ Files edited in this session (${editedFilesCount} total): ${editedFiles.join(",
14689
14884
  resolve: () => {
14690
14885
  if (!sessionID)
14691
14886
  return null;
14692
- if (!config2.verification.auto_remind)
14887
+ if (!config2.verification.enforce_contract || !config2.verification.auto_remind)
14693
14888
  return null;
14694
14889
  if (!requiresVerification(sessionID, config2.verification.min_file_edits)) {
14695
14890
  return null;
@@ -14715,16 +14910,16 @@ You have edited ${editedFilesCount} files in this session. It is recommended to
14715
14910
  import { existsSync as existsSync4 } from "fs";
14716
14911
  import { join as join4 } from "path";
14717
14912
  var environmentBySession = new Map;
14718
- function isRecord3(value) {
14913
+ function isRecord4(value) {
14719
14914
  return typeof value === "object" && value !== null;
14720
14915
  }
14721
14916
  function createEnvironmentContext(directory) {
14722
14917
  return async (input, output) => {
14723
- if (!isRecord3(input) || !isRecord3(output)) {
14918
+ if (!isRecord4(input) || !isRecord4(output)) {
14724
14919
  return;
14725
14920
  }
14726
14921
  const rawEvent = input.event;
14727
- if (!isRecord3(rawEvent) || rawEvent.type !== "session.created") {
14922
+ if (!isRecord4(rawEvent) || rawEvent.type !== "session.created") {
14728
14923
  return;
14729
14924
  }
14730
14925
  const event = rawEvent;
@@ -14738,12 +14933,77 @@ function createEnvironmentContext(directory) {
14738
14933
  if (sessionID) {
14739
14934
  environmentBySession.set(sessionID, environment);
14740
14935
  }
14741
- const existingContext = isRecord3(output.context) ? output.context : {};
14936
+ const existingContext = isRecord4(output.context) ? output.context : {};
14742
14937
  existingContext.environment = environment;
14743
14938
  output.context = existingContext;
14744
14939
  };
14745
14940
  }
14746
14941
 
14942
+ // src/hooks/idle-compaction.ts
14943
+ var sessionStates = new Map;
14944
+ var IDLE_THRESHOLD_MS = 30 * 60 * 1000;
14945
+ var MIN_TURNS_BEFORE_COMPACT = 10;
14946
+ function getIdleState(sessionID) {
14947
+ const existing = sessionStates.get(sessionID);
14948
+ if (existing)
14949
+ return existing;
14950
+ const state = {
14951
+ lastIdleTimestamp: 0,
14952
+ turnCount: 0,
14953
+ compactedAt: 0
14954
+ };
14955
+ sessionStates.set(sessionID, state);
14956
+ return state;
14957
+ }
14958
+ function recordSessionIdle(sessionID) {
14959
+ const state = getIdleState(sessionID);
14960
+ state.lastIdleTimestamp = Date.now();
14961
+ }
14962
+ function recordSessionTurn(sessionID) {
14963
+ getIdleState(sessionID).turnCount++;
14964
+ }
14965
+ function shouldCompactOnReturn(sessionID) {
14966
+ const state = getIdleState(sessionID);
14967
+ if (state.lastIdleTimestamp === 0)
14968
+ return false;
14969
+ if (state.turnCount < MIN_TURNS_BEFORE_COMPACT)
14970
+ return false;
14971
+ const idleDuration = Date.now() - state.lastIdleTimestamp;
14972
+ if (idleDuration < IDLE_THRESHOLD_MS)
14973
+ return false;
14974
+ const turnsSinceCompact = state.turnCount - state.compactedAt;
14975
+ return turnsSinceCompact >= MIN_TURNS_BEFORE_COMPACT;
14976
+ }
14977
+ function markCompacted(sessionID) {
14978
+ const state = getIdleState(sessionID);
14979
+ state.compactedAt = state.turnCount;
14980
+ }
14981
+ function createIdleCompactionHook(config2, client) {
14982
+ const typedClient = client;
14983
+ return {
14984
+ onEvent: async (event) => {
14985
+ if (!config2.enabled)
14986
+ return;
14987
+ if (event.type !== "session.idle")
14988
+ return;
14989
+ const sessionID = event.properties?.sessionID;
14990
+ if (!sessionID)
14991
+ return;
14992
+ recordSessionIdle(sessionID);
14993
+ },
14994
+ onChatMessage: async (sessionID) => {
14995
+ if (!config2.enabled)
14996
+ return;
14997
+ if (!shouldCompactOnReturn(sessionID))
14998
+ return;
14999
+ try {
15000
+ await typedClient.session.summarize({ path: { id: sessionID } });
15001
+ markCompacted(sessionID);
15002
+ } catch {}
15003
+ }
15004
+ };
15005
+ }
15006
+
14747
15007
  // src/hooks/message-transform.ts
14748
15008
  var MAX_TOOL_OUTPUT_LENGTH = 8000;
14749
15009
  var TOOL_OUTPUT_TRIM_TO = 4000;
@@ -14809,87 +15069,14 @@ function collapseConsecutiveReasoningParts(messages) {
14809
15069
  msg.parts = collapsed;
14810
15070
  }
14811
15071
  }
14812
- var microcompactEnabled = false;
14813
- function enableMicrocompact() {
14814
- microcompactEnabled = true;
14815
- }
14816
15072
  function createMessageTransformHook() {
14817
15073
  return async (_input, output) => {
14818
- if (microcompactEnabled) {
14819
- microcompactOldToolOutputs(output.messages);
14820
- microcompactEnabled = false;
14821
- }
15074
+ microcompactOldToolOutputs(output.messages);
14822
15075
  trimLongToolOutputs(output.messages);
14823
15076
  collapseConsecutiveReasoningParts(output.messages);
14824
15077
  };
14825
15078
  }
14826
15079
 
14827
- // src/hooks/idle-compaction.ts
14828
- var sessionStates = new Map;
14829
- var IDLE_THRESHOLD_MS = 30 * 60 * 1000;
14830
- var MIN_TURNS_BEFORE_COMPACT = 10;
14831
- function getIdleState(sessionID) {
14832
- const existing = sessionStates.get(sessionID);
14833
- if (existing)
14834
- return existing;
14835
- const state = {
14836
- lastIdleTimestamp: 0,
14837
- turnCount: 0,
14838
- compactedAt: 0
14839
- };
14840
- sessionStates.set(sessionID, state);
14841
- return state;
14842
- }
14843
- function recordSessionIdle(sessionID) {
14844
- const state = getIdleState(sessionID);
14845
- state.lastIdleTimestamp = Date.now();
14846
- }
14847
- function recordSessionTurn(sessionID) {
14848
- getIdleState(sessionID).turnCount++;
14849
- }
14850
- function shouldCompactOnReturn(sessionID) {
14851
- const state = getIdleState(sessionID);
14852
- if (state.lastIdleTimestamp === 0)
14853
- return false;
14854
- if (state.turnCount < MIN_TURNS_BEFORE_COMPACT)
14855
- return false;
14856
- const idleDuration = Date.now() - state.lastIdleTimestamp;
14857
- if (idleDuration < IDLE_THRESHOLD_MS)
14858
- return false;
14859
- const turnsSinceCompact = state.turnCount - state.compactedAt;
14860
- return turnsSinceCompact >= MIN_TURNS_BEFORE_COMPACT;
14861
- }
14862
- function markCompacted(sessionID) {
14863
- const state = getIdleState(sessionID);
14864
- state.compactedAt = state.turnCount;
14865
- }
14866
- function createIdleCompactionHook(config2, client) {
14867
- const typedClient = client;
14868
- return {
14869
- onEvent: async (event) => {
14870
- if (!config2.enabled)
14871
- return;
14872
- if (event.type !== "session.idle")
14873
- return;
14874
- const sessionID = event.properties?.sessionID;
14875
- if (!sessionID)
14876
- return;
14877
- recordSessionIdle(sessionID);
14878
- },
14879
- onChatMessage: async (sessionID) => {
14880
- if (!config2.enabled)
14881
- return;
14882
- if (!shouldCompactOnReturn(sessionID))
14883
- return;
14884
- enableMicrocompact();
14885
- try {
14886
- await typedClient.session.summarize({ path: { id: sessionID } });
14887
- markCompacted(sessionID);
14888
- } catch {}
14889
- }
14890
- };
14891
- }
14892
-
14893
15080
  // src/hooks/risk-guard.ts
14894
15081
  var RISK_RULES = [
14895
15082
  { pattern: /rm\s+-rf\b/i, level: "high", name: "rm-rf" },
@@ -14899,7 +15086,28 @@ var RISK_RULES = [
14899
15086
  { pattern: /truncate\s+table\b/i, level: "high", name: "sql-truncate-table" },
14900
15087
  { pattern: /delete\s+from\b/i, level: "medium", name: "sql-delete" }
14901
15088
  ];
14902
- function isRecord4(value) {
15089
+ var TASK_LAUNCH_TOOL_NAMES = new Set(["task"]);
15090
+ function isGuardedSubagentName(value) {
15091
+ return typeof value === "string" && value.startsWith("ccx-") && value !== "ccx-coordinator";
15092
+ }
15093
+ function hasExplicitDelegationApproval(value) {
15094
+ if (!isRecord5(value))
15095
+ return false;
15096
+ if (value.subagentDelegation === true || value.subagentDelegation === "approved") {
15097
+ return true;
15098
+ }
15099
+ if (value.allow_subagent_delegation === true || value.allowSubagentDelegation === true) {
15100
+ return true;
15101
+ }
15102
+ if (value.ccx_subagent_delegation === true || value.ccxSubagentDelegation === true) {
15103
+ return true;
15104
+ }
15105
+ const metadata = isRecord5(value.metadata) ? value.metadata : undefined;
15106
+ if (!metadata)
15107
+ return false;
15108
+ return metadata.subagentDelegation === true || metadata.subagentDelegation === "approved" || metadata.allow_subagent_delegation === true || metadata.allowSubagentDelegation === true || metadata.ccx_subagent_delegation === true || metadata.ccxSubagentDelegation === true;
15109
+ }
15110
+ function isRecord5(value) {
14903
15111
  return typeof value === "object" && value !== null;
14904
15112
  }
14905
15113
  function collectRiskText(value) {
@@ -14909,15 +15117,15 @@ function collectRiskText(value) {
14909
15117
  if (Array.isArray(value)) {
14910
15118
  return value.flatMap((item) => collectRiskText(item));
14911
15119
  }
14912
- if (isRecord4(value)) {
15120
+ if (isRecord5(value)) {
14913
15121
  return Object.values(value).flatMap((item) => collectRiskText(item));
14914
15122
  }
14915
15123
  return [];
14916
15124
  }
14917
15125
  function hasExplicitUserConfirmation(value) {
14918
- if (!isRecord4(value))
15126
+ if (!isRecord5(value))
14919
15127
  return false;
14920
- const metadata = isRecord4(value.metadata) ? value.metadata : undefined;
15128
+ const metadata = isRecord5(value.metadata) ? value.metadata : undefined;
14921
15129
  if (!metadata)
14922
15130
  return false;
14923
15131
  const confirmation = metadata.riskConfirmation;
@@ -14925,17 +15133,38 @@ function hasExplicitUserConfirmation(value) {
14925
15133
  }
14926
15134
  function createRiskGuard(config2) {
14927
15135
  return async (input, output) => {
14928
- if (!isRecord4(output)) {
15136
+ if (!isRecord5(output)) {
14929
15137
  return;
14930
15138
  }
15139
+ const toolName = isRecord5(input) && typeof input.tool === "string" ? input.tool.toLowerCase() : "";
15140
+ if (!config2.subagent_orchestration.allow_subagent_delegation && TASK_LAUNCH_TOOL_NAMES.has(toolName)) {
15141
+ const sessionID = isRecord5(input) && typeof input.sessionID === "string" ? input.sessionID : undefined;
15142
+ const directAgent = isRecord5(input) && typeof input.agent === "string" ? input.agent : undefined;
15143
+ const currentAgent = directAgent ?? (sessionID ? getSessionAgent(sessionID) : undefined);
15144
+ const approved = hasExplicitDelegationApproval(input) || hasExplicitDelegationApproval(output.args);
15145
+ if (isGuardedSubagentName(currentAgent) && !approved) {
15146
+ output.blocked = true;
15147
+ output.warning = "Nested subagent delegation is blocked by runtime policy. Execute directly in the current subagent, or provide explicit delegation approval metadata.";
15148
+ const metadata2 = isRecord5(output.metadata) ? output.metadata : {};
15149
+ metadata2.subagentRecursionGuard = {
15150
+ flagged: true,
15151
+ blocked: true,
15152
+ tool: toolName,
15153
+ agent: currentAgent,
15154
+ reason: "nested-subagent-delegation-blocked"
15155
+ };
15156
+ output.metadata = metadata2;
15157
+ return;
15158
+ }
15159
+ }
14931
15160
  const argsText = collectRiskText(output.args).join(`
14932
15161
  `);
14933
15162
  const matchedRule = RISK_RULES.find((rule) => rule.pattern.test(argsText));
14934
15163
  if (!matchedRule) {
14935
15164
  return;
14936
15165
  }
14937
- const toolName = isRecord4(input) && typeof input.tool === "string" ? input.tool : "tool";
14938
- const warning = matchedRule.level === "high" ? `High-risk ${toolName} invocation detected (${matchedRule.name}). Explicit user confirmation is required before execution.` : `Potentially destructive ${toolName} invocation detected (${matchedRule.name}). Review arguments carefully before continuing.`;
15166
+ const riskyToolName = isRecord5(input) && typeof input.tool === "string" ? input.tool : "tool";
15167
+ const warning = matchedRule.level === "high" ? `High-risk ${riskyToolName} invocation detected (${matchedRule.name}). Explicit user confirmation is required before execution.` : `Potentially destructive ${riskyToolName} invocation detected (${matchedRule.name}). Review arguments carefully before continuing.`;
14939
15168
  if (matchedRule.level === "high" && config2.risk_guard.enforce_high_risk_confirmation) {
14940
15169
  const confirmed = hasExplicitUserConfirmation(input);
14941
15170
  if (!confirmed) {
@@ -14943,7 +15172,7 @@ function createRiskGuard(config2) {
14943
15172
  }
14944
15173
  }
14945
15174
  output.warning = warning;
14946
- const metadata = isRecord4(output.metadata) ? output.metadata : {};
15175
+ const metadata = isRecord5(output.metadata) ? output.metadata : {};
14947
15176
  metadata.riskGuard = {
14948
15177
  flagged: true,
14949
15178
  level: matchedRule.level,
@@ -14954,6 +15183,453 @@ function createRiskGuard(config2) {
14954
15183
  };
14955
15184
  }
14956
15185
 
15186
+ // src/hooks/bg-tasks.ts
15187
+ var MAX_TASKS_PER_SESSION = 50;
15188
+ var tasksBySession = new Map;
15189
+ var tasksById = new Map;
15190
+ function pushTask(record2) {
15191
+ tasksById.set(record2.id, record2);
15192
+ const list = tasksBySession.get(record2.parentSessionID) ?? [];
15193
+ list.push(record2);
15194
+ if (list.length > MAX_TASKS_PER_SESSION) {
15195
+ const evicted = list.splice(0, list.length - MAX_TASKS_PER_SESSION);
15196
+ for (const item of evicted)
15197
+ tasksById.delete(item.id);
15198
+ }
15199
+ tasksBySession.set(record2.parentSessionID, list);
15200
+ }
15201
+ function createBgTask(args) {
15202
+ const record2 = {
15203
+ id: `ccx-bg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
15204
+ parentSessionID: args.parentSessionID,
15205
+ targetSessionID: args.targetSessionID,
15206
+ requestMessageID: args.requestMessageID,
15207
+ agent: args.agent,
15208
+ prompt: args.prompt,
15209
+ status: "queued",
15210
+ createdAt: Date.now(),
15211
+ fullContext: args.fullContext
15212
+ };
15213
+ pushTask(record2);
15214
+ return record2;
15215
+ }
15216
+ function markBgTaskRunning(id) {
15217
+ const task = tasksById.get(id);
15218
+ if (!task)
15219
+ return;
15220
+ task.status = "running";
15221
+ task.startedAt = Date.now();
15222
+ }
15223
+ function markBgTaskFailed(id, error48) {
15224
+ const task = tasksById.get(id);
15225
+ if (!task)
15226
+ return;
15227
+ task.status = "failed";
15228
+ task.finishedAt = Date.now();
15229
+ task.error = error48;
15230
+ }
15231
+ function markBgTaskCompleted(id) {
15232
+ const task = tasksById.get(id);
15233
+ if (!task)
15234
+ return;
15235
+ task.status = "completed";
15236
+ task.finishedAt = Date.now();
15237
+ }
15238
+ function getBgTask(id) {
15239
+ return tasksById.get(id);
15240
+ }
15241
+ function listBgTasksForSession(sessionID) {
15242
+ return tasksBySession.get(sessionID)?.slice() ?? [];
15243
+ }
15244
+ function formatBgTaskLine(task) {
15245
+ const age = Math.max(0, Math.round((Date.now() - task.createdAt) / 1000));
15246
+ const agent = task.agent ? ` agent=${task.agent}` : "";
15247
+ const ctx = task.fullContext ? " full-ctx" : "";
15248
+ const target = task.targetSessionID === task.parentSessionID ? "" : ` target=${task.targetSessionID}`;
15249
+ return `${task.id} ${task.status}${agent}${ctx}${target} age=${age}s`;
15250
+ }
15251
+
15252
+ // src/hooks/session-workflows.ts
15253
+ var FORK_CHILD_MARKER_BEGIN = "<ccx-fork-child>";
15254
+ var FORK_CHILD_MARKER_END = "</ccx-fork-child>";
15255
+ var TASK_STATUS_SCAN_LIMIT = 200;
15256
+ var forkChildSessionIDs = new Set;
15257
+ function isRecord6(value) {
15258
+ return typeof value === "object" && value !== null;
15259
+ }
15260
+ function createRequestMessageID() {
15261
+ return `ccx-bg-msg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
15262
+ }
15263
+ function joinTextParts(parts) {
15264
+ return parts.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
15265
+ `).trim();
15266
+ }
15267
+ function findCommandLine(text, command) {
15268
+ if (!text)
15269
+ return null;
15270
+ const lines = text.split(/\r?\n/);
15271
+ for (const line of lines) {
15272
+ const trimmed = line.trim();
15273
+ if (trimmed === command || trimmed.startsWith(`${command} `)) {
15274
+ return trimmed;
15275
+ }
15276
+ }
15277
+ return null;
15278
+ }
15279
+ function parseAgentAndPrompt(rest) {
15280
+ const trimmed = rest.trim();
15281
+ if (!trimmed)
15282
+ return { prompt: "" };
15283
+ const match = trimmed.match(/^([a-zA-Z0-9_-]+)\s+([\s\S]+)$/);
15284
+ if (!match)
15285
+ return { prompt: trimmed };
15286
+ return { agent: match[1], prompt: match[2].trim() };
15287
+ }
15288
+ function appendStatusPart(output, text) {
15289
+ output.parts.push({
15290
+ type: "text",
15291
+ text: `[ccx session-workflow] ${text}`,
15292
+ synthetic: true
15293
+ });
15294
+ }
15295
+ function extractSessionFromResponse(result) {
15296
+ if (!isRecord6(result))
15297
+ return;
15298
+ const data = isRecord6(result.data) ? result.data : result;
15299
+ if (!isRecord6(data))
15300
+ return;
15301
+ if (typeof data.id !== "string")
15302
+ return;
15303
+ return data;
15304
+ }
15305
+ function extractMessageList(result) {
15306
+ if (!result)
15307
+ return [];
15308
+ if (Array.isArray(result))
15309
+ return result;
15310
+ if (isRecord6(result) && Array.isArray(result.data)) {
15311
+ return result.data;
15312
+ }
15313
+ return [];
15314
+ }
15315
+ async function getSessionByID(client, sessionID) {
15316
+ if (!client.session?.get)
15317
+ return;
15318
+ try {
15319
+ const result = await client.session.get({ path: { id: sessionID } });
15320
+ return extractSessionFromResponse(result);
15321
+ } catch {
15322
+ return;
15323
+ }
15324
+ }
15325
+ function messagesContainForkMarker(messages) {
15326
+ for (const entry of messages) {
15327
+ const parts = Array.isArray(entry.parts) ? entry.parts : [];
15328
+ for (const part of parts) {
15329
+ if (!isRecord6(part))
15330
+ continue;
15331
+ if (typeof part.text === "string" && part.text.includes(FORK_CHILD_MARKER_BEGIN)) {
15332
+ return true;
15333
+ }
15334
+ }
15335
+ }
15336
+ return false;
15337
+ }
15338
+ function buildForkChildDirective(args) {
15339
+ const agentLine = args.agent ? `Target agent: ${args.agent}` : "Target agent: (inherit)";
15340
+ return [
15341
+ FORK_CHILD_MARKER_BEGIN,
15342
+ "You are a ccx fork-child. You have inherited the full parent session context above.",
15343
+ "Rules:",
15344
+ "1. Treat the inherited conversation as background. Do NOT re-introduce yourself.",
15345
+ "2. Do NOT fork again. Never invoke /ccx-fork or /ccx-fullctx from within this session.",
15346
+ "3. Focus strictly on the directive below. Report back concisely.",
15347
+ `Parent session: ${args.parentSessionID}`,
15348
+ agentLine,
15349
+ FORK_CHILD_MARKER_END,
15350
+ "",
15351
+ "Directive:",
15352
+ args.prompt
15353
+ ].join(`
15354
+ `);
15355
+ }
15356
+ async function isCurrentSessionForkChild(client, sessionID) {
15357
+ if (forkChildSessionIDs.has(sessionID))
15358
+ return true;
15359
+ const visited = new Set;
15360
+ let cursor = sessionID;
15361
+ for (let depth = 0;depth < 12; depth += 1) {
15362
+ if (!cursor || visited.has(cursor))
15363
+ break;
15364
+ visited.add(cursor);
15365
+ if (forkChildSessionIDs.has(cursor)) {
15366
+ forkChildSessionIDs.add(sessionID);
15367
+ return true;
15368
+ }
15369
+ const session = await getSessionByID(client, cursor);
15370
+ if (!session?.parentID)
15371
+ break;
15372
+ cursor = session.parentID;
15373
+ }
15374
+ if (!client.session?.messages)
15375
+ return false;
15376
+ try {
15377
+ const messages = await client.session.messages({
15378
+ path: { id: sessionID }
15379
+ });
15380
+ const isForkChild = messagesContainForkMarker(extractMessageList(messages));
15381
+ if (isForkChild)
15382
+ forkChildSessionIDs.add(sessionID);
15383
+ return isForkChild;
15384
+ } catch {
15385
+ return false;
15386
+ }
15387
+ }
15388
+ async function handleFork(client, sessionID, rest) {
15389
+ if (!client.session?.fork) {
15390
+ return { ok: false, text: "Fork is not supported by the current client." };
15391
+ }
15392
+ if (await isCurrentSessionForkChild(client, sessionID)) {
15393
+ return {
15394
+ ok: false,
15395
+ text: "Fork refused: current session is already a ccx fork-child (recursion guard)."
15396
+ };
15397
+ }
15398
+ const trimmed = rest.trim();
15399
+ const messageID = trimmed.length > 0 ? trimmed : undefined;
15400
+ try {
15401
+ const result = await client.session.fork({
15402
+ path: { id: sessionID },
15403
+ body: messageID ? { messageID } : {}
15404
+ });
15405
+ const forked = extractSessionFromResponse(result);
15406
+ const suffix = forked ? ` New session: ${forked.id}.` : "";
15407
+ return {
15408
+ ok: true,
15409
+ text: messageID ? `Forked session at message ${messageID}.${suffix}` : `Forked session at the latest message.${suffix}`
15410
+ };
15411
+ } catch (error48) {
15412
+ return {
15413
+ ok: false,
15414
+ text: `Failed to fork session: ${error48?.message ?? String(error48)}`
15415
+ };
15416
+ }
15417
+ }
15418
+ async function dispatchBackgroundPrompt(args) {
15419
+ const { client, targetSessionID, parentSessionID, agent, prompt, fullContext } = args;
15420
+ if (!client.session?.promptAsync) {
15421
+ return {
15422
+ ok: false,
15423
+ text: "Background prompts are not supported by the current client."
15424
+ };
15425
+ }
15426
+ const requestMessageID = createRequestMessageID();
15427
+ const task = createBgTask({
15428
+ parentSessionID,
15429
+ targetSessionID,
15430
+ requestMessageID,
15431
+ agent,
15432
+ prompt,
15433
+ fullContext
15434
+ });
15435
+ const directive = fullContext ? buildForkChildDirective({ agent, prompt, parentSessionID }) : prompt;
15436
+ try {
15437
+ await client.session.promptAsync({
15438
+ path: { id: targetSessionID },
15439
+ body: {
15440
+ messageID: requestMessageID,
15441
+ agent,
15442
+ parts: [{ type: "text", text: directive }]
15443
+ }
15444
+ });
15445
+ markBgTaskRunning(task.id);
15446
+ if (fullContext) {
15447
+ forkChildSessionIDs.add(targetSessionID);
15448
+ }
15449
+ const scope = fullContext ? `full-context subtask (fork session ${targetSessionID})` : agent ? `background prompt to agent "${agent}"` : "background prompt to the active agent";
15450
+ return {
15451
+ ok: true,
15452
+ text: `${scope} dispatched. task=${task.id} (status: running)`
15453
+ };
15454
+ } catch (error48) {
15455
+ const message = error48?.message ?? String(error48);
15456
+ markBgTaskFailed(task.id, message);
15457
+ return {
15458
+ ok: false,
15459
+ text: `Failed to dispatch background prompt: ${message} (task=${task.id})`
15460
+ };
15461
+ }
15462
+ }
15463
+ async function handleBackground(client, sessionID, rest) {
15464
+ const { agent, prompt } = parseAgentAndPrompt(rest);
15465
+ if (!prompt) {
15466
+ return { ok: false, text: "Background prompt requires a non-empty prompt body." };
15467
+ }
15468
+ return dispatchBackgroundPrompt({
15469
+ client,
15470
+ targetSessionID: sessionID,
15471
+ parentSessionID: sessionID,
15472
+ agent,
15473
+ prompt,
15474
+ fullContext: false
15475
+ });
15476
+ }
15477
+ async function handleFullContext(client, sessionID, rest) {
15478
+ if (!client.session?.fork || !client.session.promptAsync) {
15479
+ return {
15480
+ ok: false,
15481
+ text: "Full-context subtask requires session.fork and session.promptAsync support."
15482
+ };
15483
+ }
15484
+ if (await isCurrentSessionForkChild(client, sessionID)) {
15485
+ return {
15486
+ ok: false,
15487
+ text: "Full-context refused: current session is already a ccx fork-child (recursion guard)."
15488
+ };
15489
+ }
15490
+ const { agent, prompt } = parseAgentAndPrompt(rest);
15491
+ if (!agent || !prompt) {
15492
+ return { ok: false, text: "Usage: <command> <agent-name> <prompt>." };
15493
+ }
15494
+ let forkedSession;
15495
+ try {
15496
+ const result = await client.session.fork({
15497
+ path: { id: sessionID },
15498
+ body: {}
15499
+ });
15500
+ forkedSession = extractSessionFromResponse(result);
15501
+ } catch (error48) {
15502
+ return {
15503
+ ok: false,
15504
+ text: `Full-context fork failed: ${error48?.message ?? String(error48)}`
15505
+ };
15506
+ }
15507
+ if (!forkedSession) {
15508
+ return {
15509
+ ok: false,
15510
+ text: "Full-context fork returned no session id."
15511
+ };
15512
+ }
15513
+ return dispatchBackgroundPrompt({
15514
+ client,
15515
+ targetSessionID: forkedSession.id,
15516
+ parentSessionID: sessionID,
15517
+ agent,
15518
+ prompt,
15519
+ fullContext: true
15520
+ });
15521
+ }
15522
+ async function refreshBgTaskStatus(client, task) {
15523
+ if (!task || task.status !== "running")
15524
+ return;
15525
+ if (!client.session?.messages)
15526
+ return;
15527
+ try {
15528
+ const response = await client.session.messages({
15529
+ path: { id: task.targetSessionID },
15530
+ query: { limit: TASK_STATUS_SCAN_LIMIT }
15531
+ });
15532
+ const list = extractMessageList(response);
15533
+ if (list.length === 0)
15534
+ return;
15535
+ let info;
15536
+ for (let index = list.length - 1;index >= 0; index -= 1) {
15537
+ const candidate = list[index];
15538
+ if (!isRecord6(candidate?.info))
15539
+ continue;
15540
+ const messageInfo = candidate.info;
15541
+ if (messageInfo.role !== "assistant")
15542
+ continue;
15543
+ if (messageInfo.parentID !== task.requestMessageID)
15544
+ continue;
15545
+ info = messageInfo;
15546
+ break;
15547
+ }
15548
+ if (!info || info.role !== "assistant")
15549
+ return;
15550
+ const time3 = isRecord6(info.time) ? info.time : undefined;
15551
+ const completed = time3 && typeof time3.completed === "number" ? time3.completed : undefined;
15552
+ if (!completed)
15553
+ return;
15554
+ const errorInfo = isRecord6(info.error) ? info.error : undefined;
15555
+ if (errorInfo) {
15556
+ const errorData = isRecord6(errorInfo.data) ? errorInfo.data : undefined;
15557
+ const message = typeof errorData?.message === "string" ? errorData.message : typeof errorInfo.name === "string" ? errorInfo.name : "assistant reported an error";
15558
+ markBgTaskFailed(task.id, message);
15559
+ return;
15560
+ }
15561
+ markBgTaskCompleted(task.id);
15562
+ } catch {}
15563
+ }
15564
+ async function handleStatus(client, sessionID, rest) {
15565
+ const trimmed = rest.trim();
15566
+ if (trimmed) {
15567
+ const task = getBgTask(trimmed);
15568
+ if (!task) {
15569
+ return { ok: false, text: `No background task with id ${trimmed}.` };
15570
+ }
15571
+ await refreshBgTaskStatus(client, task);
15572
+ const errorLine = task.error ? ` error=${task.error}` : "";
15573
+ return {
15574
+ ok: true,
15575
+ text: `${formatBgTaskLine(task)}${errorLine}`
15576
+ };
15577
+ }
15578
+ const tasks = listBgTasksForSession(sessionID);
15579
+ if (tasks.length === 0) {
15580
+ return { ok: true, text: "No background tasks recorded for this session." };
15581
+ }
15582
+ for (const task of tasks) {
15583
+ await refreshBgTaskStatus(client, task);
15584
+ }
15585
+ const lines = tasks.slice(-10).map((task) => formatBgTaskLine(task));
15586
+ return { ok: true, text: `Recent background tasks:
15587
+ ${lines.join(`
15588
+ `)}` };
15589
+ }
15590
+ function createSessionWorkflowsHook(args) {
15591
+ const { config: config2 } = args;
15592
+ const client = args.client;
15593
+ return async (input, output) => {
15594
+ const workflows = config2.subagent_orchestration.session_workflows;
15595
+ if (!workflows.enabled)
15596
+ return;
15597
+ if (!input?.sessionID)
15598
+ return;
15599
+ if (!output?.parts)
15600
+ return;
15601
+ const text = joinTextParts(output.parts);
15602
+ if (!text)
15603
+ return;
15604
+ const forkLine = findCommandLine(text, workflows.fork_command);
15605
+ const backgroundLine = findCommandLine(text, workflows.background_command);
15606
+ const fullContextLine = findCommandLine(text, workflows.full_context_command);
15607
+ const statusLine = findCommandLine(text, workflows.status_command);
15608
+ if (!forkLine && !backgroundLine && !fullContextLine && !statusLine)
15609
+ return;
15610
+ if (forkLine) {
15611
+ const rest = forkLine.slice(workflows.fork_command.length);
15612
+ const status = await handleFork(client, input.sessionID, rest);
15613
+ appendStatusPart(output, status.text);
15614
+ }
15615
+ if (backgroundLine) {
15616
+ const rest = backgroundLine.slice(workflows.background_command.length);
15617
+ const status = await handleBackground(client, input.sessionID, rest);
15618
+ appendStatusPart(output, status.text);
15619
+ }
15620
+ if (fullContextLine) {
15621
+ const rest = fullContextLine.slice(workflows.full_context_command.length);
15622
+ const status = await handleFullContext(client, input.sessionID, rest);
15623
+ appendStatusPart(output, status.text);
15624
+ }
15625
+ if (statusLine) {
15626
+ const rest = statusLine.slice(workflows.status_command.length);
15627
+ const status = await handleStatus(client, input.sessionID, rest);
15628
+ appendStatusPart(output, status.text);
15629
+ }
15630
+ };
15631
+ }
15632
+
14957
15633
  // src/hooks/tool-definition.ts
14958
15634
  var TOOL_SAFETY_HINTS = {
14959
15635
  bash: "SAFETY: Before executing, verify the command is non-destructive. Never run rm -rf, git push --force, git reset --hard, DROP TABLE, or TRUNCATE TABLE without explicit user approval. Prefer --dry-run flags when available. Quote all file paths containing spaces.",
@@ -27304,13 +27980,18 @@ function tool(input) {
27304
27980
  }
27305
27981
  tool.schema = exports_external2;
27306
27982
  // src/plugin/tool-registry.ts
27307
- var agentDefinitions = [
27308
- COORDINATOR_AGENT_DEFINITION,
27983
+ var BASE_AGENT_DEFINITIONS = [
27309
27984
  EXPLORE_AGENT_DEFINITION,
27310
27985
  PLAN_AGENT_DEFINITION,
27311
27986
  GENERAL_PURPOSE_AGENT_DEFINITION,
27312
27987
  VERIFICATION_AGENT_DEFINITION
27313
27988
  ];
27989
+ function getEnabledAgentDefinitions(config3) {
27990
+ if (config3.subagent_orchestration.coordinator_enabled) {
27991
+ return [...BASE_AGENT_DEFINITIONS, COORDINATOR_AGENT_DEFINITION];
27992
+ }
27993
+ return BASE_AGENT_DEFINITIONS;
27994
+ }
27314
27995
  function createAgentTool(definition) {
27315
27996
  return tool({
27316
27997
  description: definition.description,
@@ -27321,6 +28002,7 @@ function createAgentTool(definition) {
27321
28002
  return [
27322
28003
  `Agent: ${definition.name}`,
27323
28004
  `Read-only: ${definition.readOnly ? "yes" : "no"}`,
28005
+ `Allowed tools: ${(definition.allowedTools ?? []).join(", ") || "all"}`,
27324
28006
  `Disallowed tools: ${(definition.disallowedTools ?? []).join(", ") || "none"}`,
27325
28007
  "System prompt:",
27326
28008
  definition.getSystemPrompt(),
@@ -27332,7 +28014,8 @@ function createAgentTool(definition) {
27332
28014
  }
27333
28015
  });
27334
28016
  }
27335
- function createAgentTools() {
28017
+ function createAgentTools(config3) {
28018
+ const agentDefinitions = getEnabledAgentDefinitions(config3);
27336
28019
  return Object.fromEntries(agentDefinitions.map((definition) => [definition.name, createAgentTool(definition)]));
27337
28020
  }
27338
28021
 
@@ -27341,11 +28024,13 @@ function createPluginInterface(args) {
27341
28024
  const { ctx, config: config3 } = args;
27342
28025
  const configHook = createConfigHook(config3, ctx.directory);
27343
28026
  const riskGuard = createRiskGuard(config3);
28027
+ const contextBundle = createContextBundleHook({ config: config3, directory: ctx.directory });
27344
28028
  const verificationReminder = createVerificationReminder(config3);
27345
28029
  const environmentContext = createEnvironmentContext(ctx.directory);
27346
28030
  const gitContext = createGitContextHook(ctx.directory);
27347
28031
  const dynamicSystemPrompt = createDynamicSystemPrompt(config3, ctx.directory);
27348
28032
  const chatMessageHook = createChatMessageHook(config3);
28033
+ const sessionWorkflows = createSessionWorkflowsHook({ config: config3, client: ctx.client });
27349
28034
  const chatParamsHook = createChatParamsHook();
27350
28035
  const compactionHook = createCompactionHook();
27351
28036
  const toolDefinitionHook = createToolDefinitionHook();
@@ -27353,8 +28038,11 @@ function createPluginInterface(args) {
27353
28038
  const idleCompaction = createIdleCompactionHook(config3, ctx.client);
27354
28039
  return {
27355
28040
  config: configHook,
27356
- tool: createAgentTools(),
27357
- "tool.execute.before": riskGuard,
28041
+ tool: createAgentTools(config3),
28042
+ "tool.execute.before": async (input, output) => {
28043
+ await contextBundle(input, output);
28044
+ await riskGuard(input, output);
28045
+ },
27358
28046
  "tool.execute.after": async (input, output) => {
27359
28047
  await verificationReminder(input, output);
27360
28048
  },
@@ -27368,6 +28056,7 @@ function createPluginInterface(args) {
27368
28056
  },
27369
28057
  "chat.message": async (input, output) => {
27370
28058
  await chatMessageHook(input, output);
28059
+ await sessionWorkflows(input, output);
27371
28060
  if (input.sessionID) {
27372
28061
  recordSessionTurn(input.sessionID);
27373
28062
  await idleCompaction.onChatMessage(input.sessionID);