@ccx-agent/opencode-ccx 0.5.0 → 0.6.0

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.
@@ -10,4 +10,13 @@ export type AnalyzerOptions = {
10
10
  extraAllowedCommands?: string[];
11
11
  };
12
12
  export declare function analyzeBashCommand(source: string, options?: AnalyzerOptions): RiskFinding[];
13
+ /**
14
+ * Extract the top-level command names from a bash source string, with wrapper
15
+ * commands (sudo, xargs, env, timeout, …) unwrapped to the inner command.
16
+ *
17
+ * Used by the risk-guard to enforce a read-only command allowlist for agents
18
+ * that declared `readOnly: true`. Returns lowercased command names only —
19
+ * arguments and redirections are not included in the returned list.
20
+ */
21
+ export declare function extractCommandNames(source: string): string[];
13
22
  export declare function pickHighestFinding(findings: RiskFinding[]): RiskFinding | null;
@@ -1,4 +1,5 @@
1
1
  import type { OhMyCCAgentConfig } from "../config/schema";
2
+ export declare function invalidateRecentFilesCache(): void;
2
3
  export declare function createContextBundleHook(args: {
3
4
  config: OhMyCCAgentConfig;
4
5
  directory: string;
@@ -1,2 +1,8 @@
1
1
  export declare function getGitSnapshotSection(sessionID: string): string | null;
2
+ /**
3
+ * Refresh the git snapshot for a session if it's older than SNAPSHOT_TTL_MS.
4
+ * Called lazily from context-bundle so subagents see current git state rather
5
+ * than a stale session.created snapshot from hours ago.
6
+ */
7
+ export declare function refreshGitSnapshot(sessionID: string, cwd: string): Promise<void>;
2
8
  export declare function createGitContextHook(directory: string): (input: unknown, _output: unknown) => Promise<void>;
@@ -0,0 +1,8 @@
1
+ export declare function recordSessionAgent(sessionID: string, agent: string | undefined): void;
2
+ export declare function getSessionAgent(sessionID: string): string | undefined;
3
+ type ChatMessageInput = {
4
+ sessionID?: string;
5
+ agent?: string;
6
+ };
7
+ export declare function createSessionAgentTracker(): (input: ChatMessageInput, _output: unknown) => Promise<void>;
8
+ export {};
package/dist/index.js CHANGED
@@ -24408,26 +24408,6 @@ function resolveAgentNameDerivedDefaults(config2) {
24408
24408
  };
24409
24409
  }
24410
24410
 
24411
- // src/hooks/chat-message.ts
24412
- var sessionAgentById = new Map;
24413
- function getSessionAgent(sessionID) {
24414
- return sessionAgentById.get(sessionID);
24415
- }
24416
- function createChatMessageHook(_config) {
24417
- return async (input, _output) => {
24418
- if (!_config.enabled)
24419
- return;
24420
- const { sessionID, agent } = input;
24421
- if (!sessionID)
24422
- return;
24423
- if (agent) {
24424
- sessionAgentById.set(sessionID, agent);
24425
- }
24426
- if (agent && !agent.startsWith(_config.agent_name))
24427
- return;
24428
- };
24429
- }
24430
-
24431
24411
  // src/hooks/chat-params.ts
24432
24412
  function createChatParamsHook() {
24433
24413
  return async (input, output) => {
@@ -24629,6 +24609,7 @@ function getDoingTasksSection() {
24629
24609
  `Do not offer time estimates or forecasts for task duration. Concentrate on the steps required, not on how long they might take.`,
24630
24610
  `When something fails, investigate the cause before pivoting to a different strategy \u2014 read the error output, verify your assumptions, and attempt a targeted correction. Do not blindly repeat the same action, but also do not discard a workable approach after one setback. Only escalate to the user after genuine investigation, not as an immediate reaction to friction.`,
24631
24611
  `Guard against introducing security flaws such as command injection, cross-site scripting, SQL injection, directory traversal, unsafe deserialization, and other prevalent vulnerabilities. If you realize you have written insecure code, correct it right away. Producing safe, secure, and correct code takes precedence.`,
24612
+ `Do not add error handling, fallbacks, or validation for scenarios that cannot happen. Trust internal code and framework guarantees. Validate only at system boundaries such as user input and external APIs. Do not introduce feature flags or backward-compatibility shims when you can simply change the code in place.`,
24632
24613
  codeStyleSubitems,
24633
24614
  `Do not employ backward-compatibility workarounds like underscore-prefixed unused variables, re-exported types, or placeholder comments for removed functionality. When you are confident something is no longer referenced, remove it entirely.`,
24634
24615
  `Report outcomes faithfully: if tests fail, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded. Never claim "all tests pass" when output shows failures, never suppress or simplify failing checks (tests, lints, type errors) to manufacture a green result, and never characterize incomplete or broken work as done. Equally, when a check did pass or a task is complete, state it plainly \u2014 do not hedge confirmed results with unnecessary disclaimers, downgrade finished work to "partial," or re-verify things you already checked. The goal is an accurate report, not a defensive one.`,
@@ -24781,7 +24762,7 @@ function getUsingToolsSection(toolNames) {
24781
24762
  `Avoid using ${toolNames.bash} when a purpose-built tool covers the same operation. Specialized tools give the user better visibility into and control over your work. This is essential for effective assistance:`,
24782
24763
  dedicatedToolSubitems,
24783
24764
  toolNames.todo ? `Organize and track your work using the ${toolNames.todo} tool. Mark each item done as soon as you finish it. Do not accumulate several completed items before updating their status.` : `Organize and track your work explicitly as you proceed. Record progress at small, natural checkpoints rather than saving all updates for the end.`,
24784
- `Multiple tools can be invoked within a single response. When tool calls have no interdependencies, issue them all at once for maximum throughput. When one call requires the result of another, sequence them accordingly.`
24765
+ `You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. Maximize parallel tool calls whenever independent operations exist \u2014 do NOT issue them sequentially when they could run together. When one call depends on the output of another, sequence them accordingly.`
24785
24766
  ];
24786
24767
  return ["# Using your tools", prependBullets(items)].join(`
24787
24768
  `);
@@ -24869,7 +24850,7 @@ async function composeSystemPrompt(options) {
24869
24850
 
24870
24851
  // src/agents/explore.ts
24871
24852
  function getExploreAgentPrompt() {
24872
- return `You are a codebase navigation agent. Your specialty is locating files, tracing code paths, and surfacing relevant information from source repositories.
24853
+ return `You are a file search specialist. You excel at thoroughly navigating and exploring codebases \u2014 locating files, tracing code paths, and surfacing the exact information the caller needs.
24873
24854
 
24874
24855
  === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
24875
24856
  This task is strictly observational. The following actions are absolutely forbidden:
@@ -24906,7 +24887,7 @@ Fulfill the search task with precision and present a clear summary of what you f
24906
24887
  }
24907
24888
  var EXPLORE_AGENT_DEFINITION = {
24908
24889
  name: "explore",
24909
- description: 'Lightweight codebase exploration agent optimized for speed. Deploy this agent to locate files via glob patterns (e.g. "src/components/**/*.tsx"), search source code for specific terms (e.g. "API endpoints"), or answer structural questions about the repository (e.g. "how are API endpoints organized?"). Indicate the desired depth when invoking: "quick" for surface-level lookups, "medium" for broader investigation, or "very thorough" for exhaustive scanning across all relevant paths and naming variations.',
24890
+ description: 'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',
24910
24891
  getSystemPrompt: getExploreAgentPrompt,
24911
24892
  disallowedTools: ["Edit", "Write"],
24912
24893
  readOnly: true
@@ -24914,7 +24895,7 @@ var EXPLORE_AGENT_DEFINITION = {
24914
24895
 
24915
24896
  // src/agents/plan.ts
24916
24897
  function getPlanAgentPrompt() {
24917
- return `You are an implementation planning agent. Your purpose is to investigate existing code and produce detailed blueprints for how changes should be made.
24898
+ return `You are a software architect and planning specialist. Your role is to explore the codebase and design detailed implementation plans for how changes should be made.
24918
24899
 
24919
24900
  === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
24920
24901
  This is an observation-only planning assignment. The following are strictly forbidden:
@@ -24968,7 +24949,7 @@ REMEMBER: Your scope is investigation and planning only. You lack the ability to
24968
24949
  }
24969
24950
  var PLAN_AGENT_DEFINITION = {
24970
24951
  name: "plan",
24971
- description: "Implementation planning agent that analyzes codebases and produces architectural blueprints. Deploy this when you need a structured strategy for a development task. Outputs ordered implementation steps, highlights key files, and evaluates design tradeoffs.",
24952
+ description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
24972
24953
  getSystemPrompt: getPlanAgentPrompt,
24973
24954
  disallowedTools: ["Edit", "Write"],
24974
24955
  readOnly: true
@@ -24996,7 +24977,7 @@ ${SHARED_GUIDELINES}`;
24996
24977
  }
24997
24978
  var GENERAL_PURPOSE_AGENT_DEFINITION = {
24998
24979
  name: "general-purpose",
24999
- description: "Versatile agent for investigating complex questions, locating code, and handling multi-step workflows. Ideal when you need to find a specific symbol or file but anticipate that multiple search attempts may be needed before landing on the right result.",
24980
+ description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
25000
24981
  getSystemPrompt: getGeneralPurposeAgentPrompt
25001
24982
  };
25002
24983
 
@@ -25014,7 +24995,7 @@ The following are absolutely forbidden:
25014
24995
 
25015
24996
  You ARE permitted to write throwaway test harnesses to a temporary directory (/tmp or $TMPDIR) using "Bash" redirection when a single inline command is insufficient \u2014 for example, a concurrency stress test or a browser automation script. Remove these when finished.
25016
24997
 
25017
- 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.
24998
+ Inspect what tools are actually available in your session rather than making assumptions. You may have access to browser automation MCP tools (e.g. playwright, chrome-devtools, claude-in-chrome), WebFetch, or other MCP capabilities \u2014 enumerate your tool list first before declaring a capability unavailable. If an MCP tool errors, debug it (is the server running? is the selector correct?) rather than abandoning it.
25018
24999
 
25019
25000
  Execute verification directly in this session. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it.
25020
25001
 
@@ -25126,7 +25107,7 @@ Use the literal string \`VERDICT: \` followed by exactly one of \`PASS\`, \`FAIL
25126
25107
  }
25127
25108
  var VERIFICATION_AGENT_DEFINITION = {
25128
25109
  name: "verification",
25129
- description: "Adversarial verification agent that validates implementation correctness before it ships. Invoke after significant changes (3+ file edits, backend/API work, infrastructure modifications). Supply the ORIGINAL task description, files that were changed, and the implementation approach. The agent executes builds, tests, linters, and targeted checks, then delivers a PASS/FAIL/PARTIAL verdict backed by evidence.",
25110
+ description: "Use this agent to verify that implementation work is correct before reporting completion. Invoke after non-trivial tasks (3+ file edits, backend/API changes, infrastructure changes). Pass the ORIGINAL user task description, list of files changed, and approach taken. The agent runs builds, tests, linters, and checks to produce a PASS/FAIL/PARTIAL verdict with evidence.",
25130
25111
  getSystemPrompt: getVerificationAgentPrompt,
25131
25112
  disallowedTools: ["Edit", "Write"],
25132
25113
  readOnly: true
@@ -25282,8 +25263,9 @@ When a worker reports failure:
25282
25263
 
25283
25264
  ## Tool Surface (Enforced)
25284
25265
 
25285
- - 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.
25266
+ - Your tool surface is intentionally narrow: use the \`task\` tool to delegate work.
25286
25267
  - Do not execute implementation tools directly (Bash/Read/Edit/Write/Glob/Grep/etc.) from coordinator mode.
25268
+ - If user clarification is strictly required before you can decompose the work, state the open question in your reply so the user (or parent agent) can answer in the next turn \u2014 do not try to invoke interactive prompts from coordinator mode.
25287
25269
 
25288
25270
  Your operating loop is: comprehend -> decompose -> delegate -> digest -> delegate next phase -> verify -> report.`;
25289
25271
  }
@@ -25291,7 +25273,7 @@ var COORDINATOR_AGENT_DEFINITION = {
25291
25273
  name: "coordinator",
25292
25274
  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.",
25293
25275
  getSystemPrompt: getCoordinatorAgentPrompt,
25294
- allowedTools: ["task", "question"]
25276
+ allowedTools: ["task"]
25295
25277
  };
25296
25278
 
25297
25279
  // src/hooks/config-handler.ts
@@ -25433,6 +25415,9 @@ function createConfigHook(config2, directory) {
25433
25415
 
25434
25416
  // src/hooks/context-bundle.ts
25435
25417
  import { execFile as execFile2 } from "child_process";
25418
+ import { existsSync as existsSync3 } from "fs";
25419
+ import { readdir, stat as fsStat } from "fs/promises";
25420
+ import { join as join3 } from "path";
25436
25421
  import { promisify as promisify2 } from "util";
25437
25422
 
25438
25423
  // src/hooks/git-context.ts
@@ -25440,6 +25425,7 @@ import { execFile } from "child_process";
25440
25425
  import { promisify } from "util";
25441
25426
  var execFileAsync = promisify(execFile);
25442
25427
  var MAX_STATUS_CHARS = 2000;
25428
+ var SNAPSHOT_TTL_MS = 15000;
25443
25429
  var snapshotBySession = new Map;
25444
25430
  function isRecord(value) {
25445
25431
  return typeof value === "object" && value !== null;
@@ -25465,13 +25451,33 @@ async function resolveDefaultBranch(cwd) {
25465
25451
  return "main";
25466
25452
  }
25467
25453
  }
25468
- function getGitSnapshotSection(sessionID) {
25469
- const snapshot = snapshotBySession.get(sessionID);
25470
- if (!snapshot)
25454
+ async function captureSnapshot(cwd) {
25455
+ try {
25456
+ const [branch, mainBranch, statusRaw, recentCommits] = await Promise.all([
25457
+ runGit(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]),
25458
+ resolveDefaultBranch(cwd),
25459
+ runGit(cwd, ["--no-optional-locks", "status", "--short"]),
25460
+ runGit(cwd, ["--no-optional-locks", "log", "--oneline", "-n", "5"])
25461
+ ]);
25462
+ const status = statusRaw.length > MAX_STATUS_CHARS ? `${statusRaw.slice(0, MAX_STATUS_CHARS)}
25463
+ ... (truncated because it exceeds 2k characters)` : statusRaw;
25464
+ return {
25465
+ branch,
25466
+ mainBranch,
25467
+ status,
25468
+ recentCommits,
25469
+ capturedAt: Date.now()
25470
+ };
25471
+ } catch {
25471
25472
  return null;
25473
+ }
25474
+ }
25475
+ function formatSnapshot(snapshot) {
25476
+ const ageSeconds = Math.max(0, Math.round((Date.now() - snapshot.capturedAt) / 1000));
25477
+ const freshnessNote = ageSeconds <= 30 ? "Fresh snapshot." : `Snapshot captured ${ageSeconds}s ago \u2014 may be slightly stale.`;
25472
25478
  return [
25473
25479
  "# Git Context",
25474
- "This is a snapshot at the start of the session and may be stale now.",
25480
+ freshnessNote,
25475
25481
  `Current branch: ${snapshot.branch}`,
25476
25482
  `Main branch: ${snapshot.mainBranch}`,
25477
25483
  `Status:
@@ -25482,6 +25488,22 @@ ${snapshot.recentCommits || "(none)"}`
25482
25488
 
25483
25489
  `);
25484
25490
  }
25491
+ function getGitSnapshotSection(sessionID) {
25492
+ const snapshot = snapshotBySession.get(sessionID);
25493
+ if (!snapshot)
25494
+ return null;
25495
+ return formatSnapshot(snapshot);
25496
+ }
25497
+ async function refreshGitSnapshot(sessionID, cwd) {
25498
+ const existing = snapshotBySession.get(sessionID);
25499
+ if (existing && Date.now() - existing.capturedAt < SNAPSHOT_TTL_MS) {
25500
+ return;
25501
+ }
25502
+ const refreshed = await captureSnapshot(cwd);
25503
+ if (refreshed) {
25504
+ snapshotBySession.set(sessionID, refreshed);
25505
+ }
25506
+ }
25485
25507
  function createGitContextHook(directory) {
25486
25508
  return async (input, _output) => {
25487
25509
  if (!isRecord(input))
@@ -25492,32 +25514,98 @@ function createGitContextHook(directory) {
25492
25514
  const sessionID = typeof rawEvent.sessionID === "string" ? rawEvent.sessionID : typeof rawEvent.sessionId === "string" ? rawEvent.sessionId : undefined;
25493
25515
  if (!sessionID || snapshotBySession.has(sessionID))
25494
25516
  return;
25495
- try {
25496
- const [branch, mainBranch, statusRaw, recentCommits] = await Promise.all([
25497
- runGit(directory, ["rev-parse", "--abbrev-ref", "HEAD"]),
25498
- resolveDefaultBranch(directory),
25499
- runGit(directory, ["--no-optional-locks", "status", "--short"]),
25500
- runGit(directory, ["--no-optional-locks", "log", "--oneline", "-n", "5"])
25501
- ]);
25502
- const status = statusRaw.length > MAX_STATUS_CHARS ? `${statusRaw.slice(0, MAX_STATUS_CHARS)}
25503
- ... (truncated because it exceeds 2k characters)` : statusRaw;
25504
- snapshotBySession.set(sessionID, {
25505
- branch,
25506
- mainBranch,
25507
- status,
25508
- recentCommits
25509
- });
25510
- } catch {}
25517
+ const snapshot = await captureSnapshot(directory);
25518
+ if (snapshot) {
25519
+ snapshotBySession.set(sessionID, snapshot);
25520
+ }
25511
25521
  };
25512
25522
  }
25513
25523
 
25524
+ // src/hooks/verification-reminder.ts
25525
+ var sessionStateById = new Map;
25526
+ var EDIT_TOOL_NAMES = new Set(["edit", "write"]);
25527
+ var TASK_TOOL_NAMES = new Set(["task", "taskcreate", "task_create"]);
25528
+ function isRecord2(value) {
25529
+ return typeof value === "object" && value !== null;
25530
+ }
25531
+ function getSessionState(sessionID) {
25532
+ const existing = sessionStateById.get(sessionID);
25533
+ if (existing) {
25534
+ return existing;
25535
+ }
25536
+ const created = {
25537
+ editedFiles: new Set,
25538
+ verificationTriggered: false
25539
+ };
25540
+ sessionStateById.set(sessionID, created);
25541
+ return created;
25542
+ }
25543
+ function getFilePath(value) {
25544
+ if (!isRecord2(value)) {
25545
+ return;
25546
+ }
25547
+ const candidates = [value.filePath, value.path, value.filename];
25548
+ return candidates.find((candidate) => typeof candidate === "string");
25549
+ }
25550
+ function createVerificationReminder(config2) {
25551
+ return async (input, _output) => {
25552
+ if (!config2.verification.enforce_contract || !config2.verification.auto_remind || !isRecord2(input)) {
25553
+ return;
25554
+ }
25555
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25556
+ const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : undefined;
25557
+ if (!sessionID || !toolName) {
25558
+ return;
25559
+ }
25560
+ if (TASK_TOOL_NAMES.has(toolName)) {
25561
+ const rawArgs = isRecord2(input.args) ? input.args : {};
25562
+ const subagentType = typeof rawArgs.subagent_type === "string" ? rawArgs.subagent_type.toLowerCase() : typeof rawArgs.subagentType === "string" ? rawArgs.subagentType.toLowerCase() : "";
25563
+ const verificationSubagent = `${config2.agent_name}-verification`;
25564
+ if (subagentType === verificationSubagent || subagentType === "verification") {
25565
+ getSessionState(sessionID).verificationTriggered = true;
25566
+ }
25567
+ return;
25568
+ }
25569
+ if (!EDIT_TOOL_NAMES.has(toolName)) {
25570
+ return;
25571
+ }
25572
+ const filePath = getFilePath(input.args);
25573
+ if (!filePath) {
25574
+ return;
25575
+ }
25576
+ const state = getSessionState(sessionID);
25577
+ state.editedFiles.add(filePath);
25578
+ };
25579
+ }
25580
+ function getVerificationState(sessionID) {
25581
+ const state = getSessionState(sessionID);
25582
+ return {
25583
+ editedFilesCount: state.editedFiles.size,
25584
+ verificationTriggered: state.verificationTriggered
25585
+ };
25586
+ }
25587
+ function listEditedFiles(sessionID, limit = 20) {
25588
+ const state = getSessionState(sessionID);
25589
+ return [...state.editedFiles].slice(-limit);
25590
+ }
25591
+ function requiresVerification(sessionID, minFileEdits) {
25592
+ const state = getSessionState(sessionID);
25593
+ return state.editedFiles.size >= minFileEdits && !state.verificationTriggered;
25594
+ }
25595
+
25514
25596
  // src/hooks/context-bundle.ts
25515
25597
  var execFileAsync2 = promisify2(execFile2);
25516
- var TASK_TOOL_NAMES = new Set(["task"]);
25598
+ var TASK_TOOL_NAMES2 = new Set(["task"]);
25517
25599
  var BUNDLE_MARKER_BEGIN = "<ccx-context-bundle>";
25518
25600
  var BUNDLE_MARKER_END = "</ccx-context-bundle>";
25519
25601
  var MAX_LIST_CHARS = 1500;
25520
- function isRecord2(value) {
25602
+ var RECENT_FILES_CACHE_TTL_MS = 30000;
25603
+ var EDITED_FILES_IN_BUNDLE = 10;
25604
+ var NON_GIT_SCAN_DEPTH = 3;
25605
+ var NON_GIT_MAX_FILES_EXAMINED = 2000;
25606
+ var NON_GIT_STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
25607
+ var recentFilesCache = new Map;
25608
+ function isRecord3(value) {
25521
25609
  return typeof value === "object" && value !== null;
25522
25610
  }
25523
25611
  function pickPromptFieldName(args2) {
@@ -25527,34 +25615,134 @@ function pickPromptFieldName(args2) {
25527
25615
  }
25528
25616
  return null;
25529
25617
  }
25530
- async function listRecentFiles(cwd, max) {
25531
- if (max <= 0)
25532
- return "";
25618
+ function isGitRepo(cwd) {
25619
+ try {
25620
+ return existsSync3(join3(cwd, ".git"));
25621
+ } catch {
25622
+ return false;
25623
+ }
25624
+ }
25625
+ async function listRecentFilesViaGit(cwd, max) {
25533
25626
  try {
25534
25627
  const { stdout } = await execFileAsync2("git", ["--no-optional-locks", "ls-files", "--modified", "--others", "--exclude-standard"], { cwd, timeout: 5000, maxBuffer: 1024 * 1024 });
25535
- const files = stdout.split(`
25628
+ return stdout.split(`
25536
25629
  `).map((line) => line.trim()).filter(Boolean).slice(0, max);
25537
- if (files.length === 0)
25538
- return "";
25539
- const joined = files.join(`
25540
- `);
25541
- return joined.length > MAX_LIST_CHARS ? `${joined.slice(0, MAX_LIST_CHARS)}
25542
- ... (truncated)` : joined;
25543
25630
  } catch {
25631
+ return [];
25632
+ }
25633
+ }
25634
+ async function listRecentFilesFallback(cwd, max) {
25635
+ const ignoredDirs = new Set([
25636
+ "node_modules",
25637
+ ".git",
25638
+ ".hg",
25639
+ ".svn",
25640
+ "dist",
25641
+ "build",
25642
+ "out",
25643
+ "target",
25644
+ ".next",
25645
+ ".nuxt",
25646
+ "__pycache__",
25647
+ ".pytest_cache",
25648
+ ".mypy_cache",
25649
+ ".venv",
25650
+ "venv",
25651
+ ".idea",
25652
+ ".vscode",
25653
+ "coverage",
25654
+ ".cache"
25655
+ ]);
25656
+ const collected = [];
25657
+ const cutoff = Date.now() - NON_GIT_STALE_THRESHOLD_MS;
25658
+ async function walk(dir, depth) {
25659
+ if (depth > NON_GIT_SCAN_DEPTH)
25660
+ return;
25661
+ if (collected.length > NON_GIT_MAX_FILES_EXAMINED)
25662
+ return;
25663
+ let entries;
25664
+ try {
25665
+ entries = await readdir(dir, { withFileTypes: true });
25666
+ } catch {
25667
+ return;
25668
+ }
25669
+ for (const entry of entries) {
25670
+ if (collected.length > NON_GIT_MAX_FILES_EXAMINED)
25671
+ return;
25672
+ if (entry.name.startsWith(".") && entry.name !== "." && entry.name !== "..") {
25673
+ if (ignoredDirs.has(entry.name))
25674
+ continue;
25675
+ }
25676
+ if (ignoredDirs.has(entry.name))
25677
+ continue;
25678
+ const fullPath = join3(dir, entry.name);
25679
+ if (entry.isDirectory()) {
25680
+ await walk(fullPath, depth + 1);
25681
+ continue;
25682
+ }
25683
+ if (!entry.isFile())
25684
+ continue;
25685
+ try {
25686
+ const info = await fsStat(fullPath);
25687
+ if (info.mtimeMs < cutoff)
25688
+ continue;
25689
+ collected.push({ path: fullPath, mtimeMs: info.mtimeMs });
25690
+ } catch {
25691
+ continue;
25692
+ }
25693
+ }
25694
+ }
25695
+ await walk(cwd, 0);
25696
+ collected.sort((a, b) => b.mtimeMs - a.mtimeMs);
25697
+ const cwdPrefix = cwd.endsWith("/") ? cwd : `${cwd}/`;
25698
+ return collected.slice(0, max).map((entry) => entry.path.startsWith(cwdPrefix) ? entry.path.slice(cwdPrefix.length) : entry.path);
25699
+ }
25700
+ async function listRecentFiles(cwd, max) {
25701
+ if (max <= 0)
25544
25702
  return "";
25703
+ const cacheKey = `${cwd}:${max}`;
25704
+ const cached2 = recentFilesCache.get(cacheKey);
25705
+ if (cached2 && cached2.expiresAt > Date.now()) {
25706
+ return cached2.value;
25545
25707
  }
25708
+ const files = isGitRepo(cwd) ? await listRecentFilesViaGit(cwd, max) : await listRecentFilesFallback(cwd, max);
25709
+ const joined = files.join(`
25710
+ `);
25711
+ const value = joined.length > MAX_LIST_CHARS ? `${joined.slice(0, MAX_LIST_CHARS)}
25712
+ ... (truncated)` : joined;
25713
+ recentFilesCache.set(cacheKey, {
25714
+ value,
25715
+ expiresAt: Date.now() + RECENT_FILES_CACHE_TTL_MS
25716
+ });
25717
+ if (recentFilesCache.size > 64) {
25718
+ const oldestKey = recentFilesCache.keys().next().value;
25719
+ if (oldestKey !== undefined)
25720
+ recentFilesCache.delete(oldestKey);
25721
+ }
25722
+ return value;
25723
+ }
25724
+ function formatSessionEditedFiles(sessionID, limit) {
25725
+ if (!sessionID)
25726
+ return null;
25727
+ const files = listEditedFiles(sessionID, limit);
25728
+ if (files.length === 0)
25729
+ return null;
25730
+ const header = `# Parent session context
25731
+
25732
+ Files edited in this session (${files.length} total): ${files.join(", ")}`;
25733
+ return header;
25546
25734
  }
25547
25735
  function createContextBundleHook(args2) {
25548
25736
  const { config: config2, directory } = args2;
25549
25737
  return async (input, output) => {
25550
25738
  if (!config2.subagent_orchestration.context_bundle.enabled)
25551
25739
  return;
25552
- if (!isRecord2(input) || !isRecord2(output))
25740
+ if (!isRecord3(input) || !isRecord3(output))
25553
25741
  return;
25554
25742
  const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : "";
25555
- if (!TASK_TOOL_NAMES.has(toolName))
25743
+ if (!TASK_TOOL_NAMES2.has(toolName))
25556
25744
  return;
25557
- if (!isRecord2(output.args))
25745
+ if (!isRecord3(output.args))
25558
25746
  return;
25559
25747
  const promptKey = pickPromptFieldName(output.args);
25560
25748
  if (!promptKey)
@@ -25564,11 +25752,14 @@ function createContextBundleHook(args2) {
25564
25752
  return;
25565
25753
  const bundleParts = [];
25566
25754
  const bundleConfig = config2.subagent_orchestration.context_bundle;
25755
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25567
25756
  if (bundleConfig.include_cwd) {
25568
25757
  bundleParts.push(`Working directory: ${directory}`);
25569
25758
  }
25570
25759
  if (bundleConfig.include_git) {
25571
- const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25760
+ if (sessionID) {
25761
+ await refreshGitSnapshot(sessionID, directory);
25762
+ }
25572
25763
  const gitSection = sessionID ? getGitSnapshotSection(sessionID) : null;
25573
25764
  if (gitSection) {
25574
25765
  bundleParts.push(gitSection);
@@ -25581,6 +25772,10 @@ function createContextBundleHook(args2) {
25581
25772
  ${recent}`);
25582
25773
  }
25583
25774
  }
25775
+ const editedSummary = formatSessionEditedFiles(sessionID, EDITED_FILES_IN_BUNDLE);
25776
+ if (editedSummary) {
25777
+ bundleParts.push(editedSummary);
25778
+ }
25584
25779
  if (bundleParts.length === 0)
25585
25780
  return;
25586
25781
  const bundle = [
@@ -25594,26 +25789,27 @@ ${recent}`);
25594
25789
  output.args[promptKey] = `${bundle}
25595
25790
 
25596
25791
  ${original}`;
25597
- const metadata = isRecord2(output.metadata) ? output.metadata : {};
25792
+ const metadata = isRecord3(output.metadata) ? output.metadata : {};
25598
25793
  metadata.contextBundle = {
25599
25794
  injected: true,
25600
25795
  tool: toolName,
25601
25796
  promptField: promptKey,
25602
- sections: bundleParts.length
25797
+ sections: bundleParts.length,
25798
+ nonGitFallback: !isGitRepo(directory)
25603
25799
  };
25604
25800
  output.metadata = metadata;
25605
25801
  };
25606
25802
  }
25607
25803
 
25608
25804
  // src/prompts/project-instructions.ts
25609
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
25805
+ import { existsSync as existsSync4, readFileSync as readFileSync2, statSync } from "fs";
25610
25806
  import { homedir as homedir2 } from "os";
25611
- import { dirname, isAbsolute, join as join3, resolve, sep } from "path";
25807
+ import { dirname, isAbsolute, join as join4, resolve, sep } from "path";
25612
25808
  var GLOBAL_DIR_RELATIVE = [".config", "opencode", "ccx"];
25613
25809
  var GLOBAL_FILENAMES = ["CCX.md", "instructions.md", "CLAUDE.md"];
25614
25810
  function safeReadText(filePath) {
25615
25811
  try {
25616
- if (!existsSync3(filePath))
25812
+ if (!existsSync4(filePath))
25617
25813
  return null;
25618
25814
  const stat = statSync(filePath);
25619
25815
  if (!stat.isFile())
@@ -25658,7 +25854,7 @@ function collectProjectInstructions(directory, filenames, maxDepth) {
25658
25854
  dirs.reverse();
25659
25855
  for (const dir of dirs) {
25660
25856
  for (const name of filenames) {
25661
- const candidate = join3(dir, name);
25857
+ const candidate = join4(dir, name);
25662
25858
  const resolved = resolve(candidate);
25663
25859
  if (seen.has(resolved))
25664
25860
  continue;
@@ -25675,11 +25871,11 @@ function collectGlobalInstructions() {
25675
25871
  const home = getHome();
25676
25872
  if (!home)
25677
25873
  return [];
25678
- const globalDir = join3(home, ...GLOBAL_DIR_RELATIVE);
25874
+ const globalDir = join4(home, ...GLOBAL_DIR_RELATIVE);
25679
25875
  const found = [];
25680
25876
  const seen = new Set;
25681
25877
  for (const name of GLOBAL_FILENAMES) {
25682
- const candidate = join3(globalDir, name);
25878
+ const candidate = join4(globalDir, name);
25683
25879
  const resolved = resolve(candidate);
25684
25880
  if (seen.has(resolved))
25685
25881
  continue;
@@ -25690,7 +25886,7 @@ function collectGlobalInstructions() {
25690
25886
  found.push({ path: resolved, origin: "global", content });
25691
25887
  }
25692
25888
  if (found.length === 0) {
25693
- const flat = join3(home, ".config", "opencode", "ccx.md");
25889
+ const flat = join4(home, ".config", "opencode", "ccx.md");
25694
25890
  const resolved = resolve(flat);
25695
25891
  if (!seen.has(resolved)) {
25696
25892
  const content = safeReadText(resolved);
@@ -25767,78 +25963,6 @@ ${body}`
25767
25963
  };
25768
25964
  }
25769
25965
 
25770
- // src/hooks/verification-reminder.ts
25771
- var sessionStateById = new Map;
25772
- var EDIT_TOOL_NAMES = new Set(["edit", "write"]);
25773
- var TASK_TOOL_NAMES2 = new Set(["task", "taskcreate", "task_create"]);
25774
- function isRecord3(value) {
25775
- return typeof value === "object" && value !== null;
25776
- }
25777
- function getSessionState(sessionID) {
25778
- const existing = sessionStateById.get(sessionID);
25779
- if (existing) {
25780
- return existing;
25781
- }
25782
- const created = {
25783
- editedFiles: new Set,
25784
- verificationTriggered: false
25785
- };
25786
- sessionStateById.set(sessionID, created);
25787
- return created;
25788
- }
25789
- function getFilePath(value) {
25790
- if (!isRecord3(value)) {
25791
- return;
25792
- }
25793
- const candidates = [value.filePath, value.path, value.filename];
25794
- return candidates.find((candidate) => typeof candidate === "string");
25795
- }
25796
- function createVerificationReminder(config2) {
25797
- return async (input, _output) => {
25798
- if (!config2.verification.enforce_contract || !config2.verification.auto_remind || !isRecord3(input)) {
25799
- return;
25800
- }
25801
- const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25802
- const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : undefined;
25803
- if (!sessionID || !toolName) {
25804
- return;
25805
- }
25806
- if (TASK_TOOL_NAMES2.has(toolName)) {
25807
- const rawArgs = isRecord3(input.args) ? input.args : {};
25808
- const subagentType = typeof rawArgs.subagent_type === "string" ? rawArgs.subagent_type.toLowerCase() : typeof rawArgs.subagentType === "string" ? rawArgs.subagentType.toLowerCase() : "";
25809
- const verificationSubagent = `${config2.agent_name}-verification`;
25810
- if (subagentType === verificationSubagent || subagentType === "verification") {
25811
- getSessionState(sessionID).verificationTriggered = true;
25812
- }
25813
- return;
25814
- }
25815
- if (!EDIT_TOOL_NAMES.has(toolName)) {
25816
- return;
25817
- }
25818
- const filePath = getFilePath(input.args);
25819
- if (!filePath) {
25820
- return;
25821
- }
25822
- const state = getSessionState(sessionID);
25823
- state.editedFiles.add(filePath);
25824
- };
25825
- }
25826
- function getVerificationState(sessionID) {
25827
- const state = getSessionState(sessionID);
25828
- return {
25829
- editedFilesCount: state.editedFiles.size,
25830
- verificationTriggered: state.verificationTriggered
25831
- };
25832
- }
25833
- function listEditedFiles(sessionID, limit = 20) {
25834
- const state = getSessionState(sessionID);
25835
- return [...state.editedFiles].slice(-limit);
25836
- }
25837
- function requiresVerification(sessionID, minFileEdits) {
25838
- const state = getSessionState(sessionID);
25839
- return state.editedFiles.size >= minFileEdits && !state.verificationTriggered;
25840
- }
25841
-
25842
25966
  // src/hooks/dynamic-system-prompt.ts
25843
25967
  function createDynamicSystemPrompt(config2, directory) {
25844
25968
  const instructionBundle = loadInstructionBundle(config2, directory);
@@ -25916,8 +26040,8 @@ Do NOT report completion to the user without going through this gate.`;
25916
26040
  }
25917
26041
 
25918
26042
  // src/hooks/environment-context.ts
25919
- import { existsSync as existsSync4 } from "fs";
25920
- import { join as join4 } from "path";
26043
+ import { existsSync as existsSync5 } from "fs";
26044
+ import { join as join5 } from "path";
25921
26045
  var environmentBySession = new Map;
25922
26046
  function isRecord4(value) {
25923
26047
  return typeof value === "object" && value !== null;
@@ -25935,7 +26059,7 @@ function createEnvironmentContext(directory) {
25935
26059
  const sessionID = typeof event.sessionID === "string" ? event.sessionID : typeof event.sessionId === "string" ? event.sessionId : undefined;
25936
26060
  const environment = {
25937
26061
  cwd: directory,
25938
- isGit: existsSync4(join4(directory, ".git")),
26062
+ isGit: existsSync5(join5(directory, ".git")),
25939
26063
  platform: process.platform,
25940
26064
  shell: process.env.SHELL ?? "unknown"
25941
26065
  };
@@ -26086,6 +26210,37 @@ function createMessageTransformHook() {
26086
26210
  };
26087
26211
  }
26088
26212
 
26213
+ // src/hooks/session-agent.ts
26214
+ var MAX_SESSIONS_TRACKED = 256;
26215
+ var sessionAgentById = new Map;
26216
+ function touch(sessionID, agent) {
26217
+ if (sessionAgentById.has(sessionID)) {
26218
+ sessionAgentById.delete(sessionID);
26219
+ }
26220
+ sessionAgentById.set(sessionID, agent);
26221
+ if (sessionAgentById.size > MAX_SESSIONS_TRACKED) {
26222
+ const oldestKey = sessionAgentById.keys().next().value;
26223
+ if (oldestKey !== undefined) {
26224
+ sessionAgentById.delete(oldestKey);
26225
+ }
26226
+ }
26227
+ }
26228
+ function recordSessionAgent(sessionID, agent) {
26229
+ if (!sessionID || !agent)
26230
+ return;
26231
+ touch(sessionID, agent);
26232
+ }
26233
+ function getSessionAgent(sessionID) {
26234
+ return sessionAgentById.get(sessionID);
26235
+ }
26236
+ function createSessionAgentTracker() {
26237
+ return async (input, _output) => {
26238
+ if (!input?.sessionID || !input.agent)
26239
+ return;
26240
+ recordSessionAgent(input.sessionID, input.agent);
26241
+ };
26242
+ }
26243
+
26089
26244
  // src/hooks/bash-analyzer.ts
26090
26245
  var import_bash_parser = __toESM(require_src(), 1);
26091
26246
  var WRAPPER_COMMANDS = new Set([
@@ -26509,6 +26664,26 @@ function analyzeBashCommand(source, options = {}) {
26509
26664
  }
26510
26665
  return dedupe(findings);
26511
26666
  }
26667
+ function extractCommandNames(source) {
26668
+ const trimmed = source.trim();
26669
+ if (!trimmed)
26670
+ return [];
26671
+ let commands = [];
26672
+ try {
26673
+ const ast = import_bash_parser.default(trimmed);
26674
+ commands = collectCommands(ast);
26675
+ } catch {
26676
+ commands = fallbackTokenize(trimmed);
26677
+ }
26678
+ const names = [];
26679
+ for (const cmd of commands) {
26680
+ const inner = unwrapWrapper(cmd);
26681
+ if (inner.name) {
26682
+ names.push(inner.name.toLowerCase());
26683
+ }
26684
+ }
26685
+ return names;
26686
+ }
26512
26687
  function fallbackTokenize(source) {
26513
26688
  const statements = source.split(/[;&|]{1,2}/);
26514
26689
  const out = [];
@@ -26544,6 +26719,240 @@ function pickHighestFinding(findings) {
26544
26719
  var TASK_LAUNCH_TOOL_NAMES = new Set(["task"]);
26545
26720
  var BASH_TOOL_NAMES = new Set(["bash", "shell", "sh", "exec"]);
26546
26721
  var SQL_TOOL_NAMES = new Set(["sql", "query", "db", "database"]);
26722
+ var ALL_AGENT_DEFS = [
26723
+ EXPLORE_AGENT_DEFINITION,
26724
+ PLAN_AGENT_DEFINITION,
26725
+ GENERAL_PURPOSE_AGENT_DEFINITION,
26726
+ VERIFICATION_AGENT_DEFINITION,
26727
+ COORDINATOR_AGENT_DEFINITION
26728
+ ];
26729
+ var READ_ONLY_BASH_COMMANDS = new Set([
26730
+ "ls",
26731
+ "pwd",
26732
+ "cd",
26733
+ "echo",
26734
+ "printf",
26735
+ "true",
26736
+ "false",
26737
+ "test",
26738
+ "[",
26739
+ "cat",
26740
+ "head",
26741
+ "tail",
26742
+ "less",
26743
+ "more",
26744
+ "bat",
26745
+ "grep",
26746
+ "egrep",
26747
+ "fgrep",
26748
+ "rg",
26749
+ "ripgrep",
26750
+ "ag",
26751
+ "find",
26752
+ "fd",
26753
+ "locate",
26754
+ "which",
26755
+ "whereis",
26756
+ "type",
26757
+ "command",
26758
+ "stat",
26759
+ "file",
26760
+ "du",
26761
+ "df",
26762
+ "wc",
26763
+ "nl",
26764
+ "sort",
26765
+ "uniq",
26766
+ "tr",
26767
+ "cut",
26768
+ "awk",
26769
+ "sed",
26770
+ "jq",
26771
+ "yq",
26772
+ "date",
26773
+ "hostname",
26774
+ "whoami",
26775
+ "id",
26776
+ "uname",
26777
+ "uptime",
26778
+ "git",
26779
+ "hg",
26780
+ "svn",
26781
+ "node",
26782
+ "python",
26783
+ "python3",
26784
+ "ruby",
26785
+ "perl",
26786
+ "npm",
26787
+ "pnpm",
26788
+ "yarn",
26789
+ "bun",
26790
+ "go",
26791
+ "cargo",
26792
+ "rustc",
26793
+ "tsc",
26794
+ "eslint",
26795
+ "prettier",
26796
+ "mypy",
26797
+ "ruff",
26798
+ "pylint",
26799
+ "flake8",
26800
+ "pytest",
26801
+ "jest",
26802
+ "vitest",
26803
+ "mocha",
26804
+ "curl",
26805
+ "wget",
26806
+ "nc",
26807
+ "ping",
26808
+ "dig",
26809
+ "nslookup",
26810
+ "host",
26811
+ "env",
26812
+ "printenv",
26813
+ "basename",
26814
+ "dirname",
26815
+ "readlink",
26816
+ "realpath",
26817
+ "diff",
26818
+ "comm",
26819
+ "cmp",
26820
+ "xxd",
26821
+ "od",
26822
+ "hexdump",
26823
+ "make",
26824
+ "cmake",
26825
+ "ninja",
26826
+ "docker",
26827
+ "kubectl",
26828
+ "helm",
26829
+ "ps",
26830
+ "top",
26831
+ "htop",
26832
+ "tree"
26833
+ ]);
26834
+ var DESTRUCTIVE_SUBCOMMANDS = {
26835
+ git: new Set([
26836
+ "add",
26837
+ "commit",
26838
+ "push",
26839
+ "pull",
26840
+ "merge",
26841
+ "rebase",
26842
+ "cherry-pick",
26843
+ "reset",
26844
+ "revert",
26845
+ "restore",
26846
+ "checkout",
26847
+ "switch",
26848
+ "branch",
26849
+ "tag",
26850
+ "stash",
26851
+ "clean",
26852
+ "gc",
26853
+ "filter-branch",
26854
+ "filter-repo",
26855
+ "rm",
26856
+ "mv",
26857
+ "config",
26858
+ "init",
26859
+ "clone",
26860
+ "remote"
26861
+ ]),
26862
+ npm: new Set(["install", "i", "uninstall", "remove", "rm", "publish", "link", "unlink", "run", "exec"]),
26863
+ pnpm: new Set(["install", "i", "add", "remove", "rm", "publish", "link", "unlink", "run", "exec", "dlx"]),
26864
+ yarn: new Set(["add", "remove", "install", "publish", "link", "unlink", "dlx"]),
26865
+ bun: new Set(["install", "add", "remove", "publish", "link", "unlink", "run", "x"]),
26866
+ cargo: new Set(["install", "uninstall", "publish", "run", "new", "init", "add", "remove"]),
26867
+ go: new Set(["install", "get", "mod", "run", "build"]),
26868
+ make: new Set(["install", "uninstall", "clean", "distclean"]),
26869
+ docker: new Set([
26870
+ "run",
26871
+ "create",
26872
+ "start",
26873
+ "stop",
26874
+ "kill",
26875
+ "rm",
26876
+ "rmi",
26877
+ "build",
26878
+ "push",
26879
+ "pull",
26880
+ "commit",
26881
+ "exec",
26882
+ "prune",
26883
+ "system",
26884
+ "volume",
26885
+ "network"
26886
+ ]),
26887
+ kubectl: new Set(["apply", "create", "delete", "edit", "patch", "replace", "scale", "rollout", "exec", "cp"]),
26888
+ helm: new Set(["install", "uninstall", "upgrade", "rollback", "delete"])
26889
+ };
26890
+ var ALLOWED_WRITE_PATH_PREFIXES = ["/tmp/", "/var/tmp/", "/private/tmp/"];
26891
+ function isRecord5(value) {
26892
+ return typeof value === "object" && value !== null;
26893
+ }
26894
+ function getReadOnlyAgentNames(agentName) {
26895
+ const out = new Set;
26896
+ for (const def of ALL_AGENT_DEFS) {
26897
+ if (def.readOnly) {
26898
+ out.add(`${agentName}-${def.name}`);
26899
+ }
26900
+ }
26901
+ return out;
26902
+ }
26903
+ function findReadOnlyViolations(bashSource) {
26904
+ const violations = [];
26905
+ const trimmed = bashSource.trim();
26906
+ if (!trimmed)
26907
+ return violations;
26908
+ const commandNames = extractCommandNames(trimmed);
26909
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
26910
+ for (const name of commandNames) {
26911
+ if (!READ_ONLY_BASH_COMMANDS.has(name)) {
26912
+ violations.push({
26913
+ reason: `command "${name}" is not in the read-only allowlist`,
26914
+ command: name
26915
+ });
26916
+ }
26917
+ }
26918
+ const inspectedIndices = new Set;
26919
+ for (let i = 0;i < tokens.length; i += 1) {
26920
+ const tokenLower = tokens[i].toLowerCase();
26921
+ const destructive = DESTRUCTIVE_SUBCOMMANDS[tokenLower];
26922
+ if (!destructive)
26923
+ continue;
26924
+ if (inspectedIndices.has(i))
26925
+ continue;
26926
+ let subIndex = i + 1;
26927
+ while (subIndex < tokens.length && tokens[subIndex].startsWith("-")) {
26928
+ subIndex += 1;
26929
+ }
26930
+ if (subIndex >= tokens.length)
26931
+ continue;
26932
+ const sub = tokens[subIndex].toLowerCase();
26933
+ inspectedIndices.add(subIndex);
26934
+ if (destructive.has(sub)) {
26935
+ violations.push({
26936
+ reason: `"${tokenLower} ${sub}" is a destructive subcommand`,
26937
+ command: `${tokenLower} ${sub}`
26938
+ });
26939
+ }
26940
+ }
26941
+ const redirectMatches = trimmed.matchAll(/(?:^|\s)(?:\d*>{1,2}|&>|>&)\s*([^\s;|&<>()]+)/g);
26942
+ for (const match of redirectMatches) {
26943
+ const target = match[1];
26944
+ if (!target || target === "/dev/null" || target === "&1" || target === "&2")
26945
+ continue;
26946
+ const isAllowed = ALLOWED_WRITE_PATH_PREFIXES.some((prefix) => target.startsWith(prefix)) || target.startsWith("$TMPDIR/") || target === "$TMPDIR";
26947
+ if (!isAllowed) {
26948
+ violations.push({
26949
+ reason: `redirection target "${target}" must be inside /tmp, /var/tmp, or $TMPDIR`,
26950
+ command: match[0].trim()
26951
+ });
26952
+ }
26953
+ }
26954
+ return violations;
26955
+ }
26547
26956
  function isGuardedSubagentName(value, agentName) {
26548
26957
  const prefix = `${agentName}-`;
26549
26958
  return typeof value === "string" && value.startsWith(prefix) && value !== `${agentName}-coordinator`;
@@ -26565,9 +26974,6 @@ function hasExplicitDelegationApproval(value) {
26565
26974
  return false;
26566
26975
  return metadata.subagentDelegation === true || metadata.subagentDelegation === "approved" || metadata.allow_subagent_delegation === true || metadata.allowSubagentDelegation === true || metadata.ccx_subagent_delegation === true || metadata.ccxSubagentDelegation === true;
26567
26976
  }
26568
- function isRecord5(value) {
26569
- return typeof value === "object" && value !== null;
26570
- }
26571
26977
  function collectBashSource(args2) {
26572
26978
  if (args2 === null || args2 === undefined)
26573
26979
  return [];
@@ -26616,15 +27022,16 @@ function formatWarning(level, toolName, finding) {
26616
27022
  return `${lead} (${finding.name}): ${finding.message}. Command: ${finding.command}`;
26617
27023
  }
26618
27024
  function createRiskGuard(config2) {
27025
+ const readOnlyAgentNames = getReadOnlyAgentNames(config2.agent_name);
26619
27026
  return async (input, output) => {
26620
27027
  if (!isRecord5(output)) {
26621
27028
  return;
26622
27029
  }
26623
27030
  const toolName = isRecord5(input) && typeof input.tool === "string" ? input.tool.toLowerCase() : "";
27031
+ const sessionID = isRecord5(input) && typeof input.sessionID === "string" ? input.sessionID : undefined;
27032
+ const directAgent = isRecord5(input) && typeof input.agent === "string" ? input.agent : undefined;
27033
+ const currentAgent = directAgent ?? (sessionID ? getSessionAgent(sessionID) : undefined);
26624
27034
  if (!config2.subagent_orchestration.allow_subagent_delegation && TASK_LAUNCH_TOOL_NAMES.has(toolName)) {
26625
- const sessionID = isRecord5(input) && typeof input.sessionID === "string" ? input.sessionID : undefined;
26626
- const directAgent = isRecord5(input) && typeof input.agent === "string" ? input.agent : undefined;
26627
- const currentAgent = directAgent ?? (sessionID ? getSessionAgent(sessionID) : undefined);
26628
27035
  const approved = hasExplicitDelegationApproval(input) || hasExplicitDelegationApproval(output.args);
26629
27036
  if (isGuardedSubagentName(currentAgent, config2.agent_name) && !approved) {
26630
27037
  output.blocked = true;
@@ -26641,6 +27048,27 @@ function createRiskGuard(config2) {
26641
27048
  return;
26642
27049
  }
26643
27050
  }
27051
+ if (typeof currentAgent === "string" && readOnlyAgentNames.has(currentAgent) && BASH_TOOL_NAMES.has(toolName)) {
27052
+ const bashSources2 = collectBashSource(output.args);
27053
+ const allViolations = [];
27054
+ for (const source of bashSources2) {
27055
+ allViolations.push(...findReadOnlyViolations(source));
27056
+ }
27057
+ if (allViolations.length > 0) {
27058
+ output.blocked = true;
27059
+ const first = allViolations[0];
27060
+ output.warning = `Read-only agent "${currentAgent}" attempted a mutating shell operation: ${first.reason}. If this is intentional, run it from a non-readOnly agent.`;
27061
+ const metadata2 = isRecord5(output.metadata) ? output.metadata : {};
27062
+ metadata2.readOnlyAgentGuard = {
27063
+ flagged: true,
27064
+ blocked: true,
27065
+ agent: currentAgent,
27066
+ violations: allViolations
27067
+ };
27068
+ output.metadata = metadata2;
27069
+ return;
27070
+ }
27071
+ }
26644
27072
  const astEnabled = config2.risk_guard.ast_analysis;
26645
27073
  const bashSources = BASH_TOOL_NAMES.has(toolName) ? collectBashSource(output.args) : SQL_TOOL_NAMES.has(toolName) ? collectBashSource(output.args) : collectAllText(output.args);
26646
27074
  const analyzerOptions = {
@@ -27783,7 +28211,7 @@ function createPluginInterface(args2) {
27783
28211
  const environmentContext = createEnvironmentContext(ctx.directory);
27784
28212
  const gitContext = createGitContextHook(ctx.directory);
27785
28213
  const dynamicSystemPrompt = createDynamicSystemPrompt(config2, ctx.directory);
27786
- const chatMessageHook = createChatMessageHook(config2);
28214
+ const sessionAgentTracker = createSessionAgentTracker();
27787
28215
  const sessionWorkflows = createSessionWorkflowsHook({ config: config2, client: ctx.client });
27788
28216
  const chatParamsHook = createChatParamsHook();
27789
28217
  const compactionHook = createCompactionHook(config2);
@@ -27810,7 +28238,7 @@ function createPluginInterface(args2) {
27810
28238
  }
27811
28239
  },
27812
28240
  "chat.message": async (input, output) => {
27813
- await chatMessageHook(input, output);
28241
+ await sessionAgentTracker(input, output);
27814
28242
  await sessionWorkflows(input, output);
27815
28243
  if (input.sessionID) {
27816
28244
  recordSessionTurn(input.sessionID);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ccx-agent/opencode-ccx",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Production-grade prompt engineering for OpenCode — disciplined coding, risk-aware actions, adversarial verification",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1,21 +0,0 @@
1
- import type { OhMyCCAgentConfig } from "../config/schema";
2
- type ChatMessageInput = {
3
- sessionID: string;
4
- agent?: string;
5
- model?: {
6
- providerID: string;
7
- modelID: string;
8
- };
9
- messageID?: string;
10
- };
11
- type ChatMessageOutput = {
12
- message: Record<string, unknown>;
13
- parts: Array<{
14
- type: string;
15
- text?: string;
16
- [key: string]: unknown;
17
- }>;
18
- };
19
- export declare function getSessionAgent(sessionID: string): string | undefined;
20
- export declare function createChatMessageHook(_config: OhMyCCAgentConfig): (input: ChatMessageInput, _output: ChatMessageOutput) => Promise<void>;
21
- export {};