@ccx-agent/opencode-ccx 0.5.0 → 0.7.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.
package/README.md CHANGED
@@ -340,6 +340,16 @@ Example:
340
340
  "explore_min_queries": 3,
341
341
  "coordinator_enabled": false,
342
342
  "allow_subagent_delegation": false,
343
+ "agents": {
344
+ "verification": {
345
+ "model": "anthropic/claude-sonnet-4-5",
346
+ "temperature": 0
347
+ },
348
+ "explore": {
349
+ "model": "openai/gpt-5-mini",
350
+ "temperature": 0.4
351
+ }
352
+ },
343
353
  "context_bundle": {
344
354
  "enabled": true,
345
355
  "include_cwd": true,
@@ -387,6 +397,10 @@ Example:
387
397
  | `subagent_orchestration.explore_min_queries` | `number` | `3` | Escalate to `ccx-explore` when directed lookup likely needs more than this query count |
388
398
  | `subagent_orchestration.coordinator_enabled` | `boolean` | `false` | Register and advertise `ccx-coordinator` subagent |
389
399
  | `subagent_orchestration.allow_subagent_delegation` | `boolean` | `false` | Permit subagents to delegate further. When `false`, runtime recursion guard blocks nested `task` delegation from `ccx-*` subagents unless explicit delegation-approval metadata is present |
400
+ | `subagent_orchestration.agents.<name>.model` | `string` | unset | Override a registered ccx subagent model using OpenCode's `provider/model` format, e.g. `anthropic/claude-sonnet-4-5` |
401
+ | `subagent_orchestration.agents.<name>.variant` | `string` | unset | Default model variant for that subagent when using its configured model |
402
+ | `subagent_orchestration.agents.<name>.temperature` | `number` | unset | Override that subagent's temperature; must be non-negative |
403
+ | `subagent_orchestration.agents.<name>.top_p` | `number` | unset | Override that subagent's top-p sampling value; must be between 0 and 1 |
390
404
  | `subagent_orchestration.context_bundle.enabled` | `boolean` | `true` | Inject a shared context bundle (cwd, git snapshot, recently changed files) into `task` tool args before execution |
391
405
  | `subagent_orchestration.context_bundle.include_cwd` | `boolean` | `true` | Include the working directory in the injected bundle |
392
406
  | `subagent_orchestration.context_bundle.include_git` | `boolean` | `true` | Include the per-session git snapshot in the injected bundle |
@@ -55,6 +55,12 @@ export declare const configSchema: z.ZodObject<{
55
55
  explore_min_queries: z.ZodDefault<z.ZodInt>;
56
56
  coordinator_enabled: z.ZodDefault<z.ZodBoolean>;
57
57
  allow_subagent_delegation: z.ZodDefault<z.ZodBoolean>;
58
+ agents: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
59
+ model: z.ZodOptional<z.ZodString>;
60
+ variant: z.ZodOptional<z.ZodString>;
61
+ temperature: z.ZodOptional<z.ZodNumber>;
62
+ top_p: z.ZodOptional<z.ZodNumber>;
63
+ }, z.core.$strip>>>;
58
64
  context_bundle: z.ZodDefault<z.ZodObject<{
59
65
  enabled: z.ZodDefault<z.ZodBoolean>;
60
66
  include_cwd: z.ZodDefault<z.ZodBoolean>;
@@ -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
@@ -21577,7 +21577,7 @@ function finalize(ctx, schema) {
21577
21577
  result.$schema = "http://json-schema.org/draft-07/schema#";
21578
21578
  } else if (ctx.target === "draft-04") {
21579
21579
  result.$schema = "http://json-schema.org/draft-04/schema#";
21580
- } else if (ctx.target === "openapi-3.0") {} else {}
21580
+ } else if (ctx.target === "openapi-3.0") {}
21581
21581
  if (ctx.external?.uri) {
21582
21582
  const id = ctx.external.registry.get(schema)?.id;
21583
21583
  if (!id)
@@ -21825,7 +21825,7 @@ var literalProcessor = (schema, ctx, json, _params) => {
21825
21825
  if (val === undefined) {
21826
21826
  if (ctx.unrepresentable === "throw") {
21827
21827
  throw new Error("Literal `undefined` cannot be represented in JSON Schema");
21828
- } else {}
21828
+ }
21829
21829
  } else if (typeof val === "bigint") {
21830
21830
  if (ctx.unrepresentable === "throw") {
21831
21831
  throw new Error("BigInt literals cannot be represented in JSON Schema");
@@ -24231,10 +24231,17 @@ var sessionWorkflowsSchema = exports_external.object({
24231
24231
  full_context_command: exports_external.string().min(1).nullable().default(null),
24232
24232
  status_command: exports_external.string().min(1).nullable().default(null)
24233
24233
  });
24234
+ var subagentModelConfigSchema = exports_external.object({
24235
+ model: exports_external.string().min(1).optional(),
24236
+ variant: exports_external.string().min(1).optional(),
24237
+ temperature: exports_external.number().finite().min(0).optional(),
24238
+ top_p: exports_external.number().finite().min(0).max(1).optional()
24239
+ });
24234
24240
  var subagentOrchestrationSchema = exports_external.object({
24235
24241
  explore_min_queries: exports_external.int().positive().default(3),
24236
24242
  coordinator_enabled: exports_external.boolean().default(false),
24237
24243
  allow_subagent_delegation: exports_external.boolean().default(false),
24244
+ agents: exports_external.record(exports_external.string().min(1), subagentModelConfigSchema).default({}),
24238
24245
  context_bundle: contextBundleSchema.default({
24239
24246
  enabled: true,
24240
24247
  include_cwd: true,
@@ -24302,6 +24309,7 @@ var configSchema = exports_external.object({
24302
24309
  explore_min_queries: 3,
24303
24310
  coordinator_enabled: false,
24304
24311
  allow_subagent_delegation: false,
24312
+ agents: {},
24305
24313
  context_bundle: {
24306
24314
  enabled: true,
24307
24315
  include_cwd: true,
@@ -24408,26 +24416,6 @@ function resolveAgentNameDerivedDefaults(config2) {
24408
24416
  };
24409
24417
  }
24410
24418
 
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
24419
  // src/hooks/chat-params.ts
24432
24420
  function createChatParamsHook() {
24433
24421
  return async (input, output) => {
@@ -24629,6 +24617,7 @@ function getDoingTasksSection() {
24629
24617
  `Do not offer time estimates or forecasts for task duration. Concentrate on the steps required, not on how long they might take.`,
24630
24618
  `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
24619
  `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.`,
24620
+ `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
24621
  codeStyleSubitems,
24633
24622
  `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
24623
  `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 +24770,7 @@ function getUsingToolsSection(toolNames) {
24781
24770
  `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
24771
  dedicatedToolSubitems,
24783
24772
  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.`
24773
+ `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
24774
  ];
24786
24775
  return ["# Using your tools", prependBullets(items)].join(`
24787
24776
  `);
@@ -24869,7 +24858,7 @@ async function composeSystemPrompt(options) {
24869
24858
 
24870
24859
  // src/agents/explore.ts
24871
24860
  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.
24861
+ 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
24862
 
24874
24863
  === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
24875
24864
  This task is strictly observational. The following actions are absolutely forbidden:
@@ -24906,7 +24895,7 @@ Fulfill the search task with precision and present a clear summary of what you f
24906
24895
  }
24907
24896
  var EXPLORE_AGENT_DEFINITION = {
24908
24897
  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.',
24898
+ 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
24899
  getSystemPrompt: getExploreAgentPrompt,
24911
24900
  disallowedTools: ["Edit", "Write"],
24912
24901
  readOnly: true
@@ -24914,7 +24903,7 @@ var EXPLORE_AGENT_DEFINITION = {
24914
24903
 
24915
24904
  // src/agents/plan.ts
24916
24905
  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.
24906
+ 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
24907
 
24919
24908
  === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
24920
24909
  This is an observation-only planning assignment. The following are strictly forbidden:
@@ -24968,7 +24957,7 @@ REMEMBER: Your scope is investigation and planning only. You lack the ability to
24968
24957
  }
24969
24958
  var PLAN_AGENT_DEFINITION = {
24970
24959
  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.",
24960
+ 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
24961
  getSystemPrompt: getPlanAgentPrompt,
24973
24962
  disallowedTools: ["Edit", "Write"],
24974
24963
  readOnly: true
@@ -24996,7 +24985,7 @@ ${SHARED_GUIDELINES}`;
24996
24985
  }
24997
24986
  var GENERAL_PURPOSE_AGENT_DEFINITION = {
24998
24987
  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.",
24988
+ 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
24989
  getSystemPrompt: getGeneralPurposeAgentPrompt
25001
24990
  };
25002
24991
 
@@ -25014,7 +25003,7 @@ The following are absolutely forbidden:
25014
25003
 
25015
25004
  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
25005
 
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.
25006
+ 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
25007
 
25019
25008
  Execute verification directly in this session. Delegate again only when the caller explicitly asks for delegation or your instructions explicitly permit it.
25020
25009
 
@@ -25126,7 +25115,7 @@ Use the literal string \`VERDICT: \` followed by exactly one of \`PASS\`, \`FAIL
25126
25115
  }
25127
25116
  var VERIFICATION_AGENT_DEFINITION = {
25128
25117
  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.",
25118
+ 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
25119
  getSystemPrompt: getVerificationAgentPrompt,
25131
25120
  disallowedTools: ["Edit", "Write"],
25132
25121
  readOnly: true
@@ -25282,8 +25271,9 @@ When a worker reports failure:
25282
25271
 
25283
25272
  ## Tool Surface (Enforced)
25284
25273
 
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.
25274
+ - Your tool surface is intentionally narrow: use the \`task\` tool to delegate work.
25286
25275
  - Do not execute implementation tools directly (Bash/Read/Edit/Write/Glob/Grep/etc.) from coordinator mode.
25276
+ - 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
25277
 
25288
25278
  Your operating loop is: comprehend -> decompose -> delegate -> digest -> delegate next phase -> verify -> report.`;
25289
25279
  }
@@ -25291,7 +25281,7 @@ var COORDINATOR_AGENT_DEFINITION = {
25291
25281
  name: "coordinator",
25292
25282
  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
25283
  getSystemPrompt: getCoordinatorAgentPrompt,
25294
- allowedTools: ["task", "question"]
25284
+ allowedTools: ["task"]
25295
25285
  };
25296
25286
 
25297
25287
  // src/hooks/config-handler.ts
@@ -25323,6 +25313,12 @@ function buildToolRestrictions(def) {
25323
25313
  }
25324
25314
  return tools;
25325
25315
  }
25316
+ function buildSubagentModelSettings(config2, def) {
25317
+ const settings = config2.subagent_orchestration.agents[def.name];
25318
+ if (!settings)
25319
+ return {};
25320
+ return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined));
25321
+ }
25326
25322
  function buildSubagentGuidance(config2) {
25327
25323
  const exploreMinQueries = config2.subagent_orchestration.explore_min_queries;
25328
25324
  const spotCheckMinCommands = config2.verification.spot_check_min_commands;
@@ -25417,7 +25413,8 @@ function createConfigHook(config2, directory) {
25417
25413
  description: def.description,
25418
25414
  mode: "subagent",
25419
25415
  prompt: def.getSystemPrompt(),
25420
- tools: buildToolRestrictions(def)
25416
+ tools: buildToolRestrictions(def),
25417
+ ...buildSubagentModelSettings(config2, def)
25421
25418
  };
25422
25419
  }
25423
25420
  input.agent = {
@@ -25433,6 +25430,9 @@ function createConfigHook(config2, directory) {
25433
25430
 
25434
25431
  // src/hooks/context-bundle.ts
25435
25432
  import { execFile as execFile2 } from "child_process";
25433
+ import { existsSync as existsSync3 } from "fs";
25434
+ import { readdir, stat as fsStat } from "fs/promises";
25435
+ import { join as join3 } from "path";
25436
25436
  import { promisify as promisify2 } from "util";
25437
25437
 
25438
25438
  // src/hooks/git-context.ts
@@ -25440,6 +25440,7 @@ import { execFile } from "child_process";
25440
25440
  import { promisify } from "util";
25441
25441
  var execFileAsync = promisify(execFile);
25442
25442
  var MAX_STATUS_CHARS = 2000;
25443
+ var SNAPSHOT_TTL_MS = 15000;
25443
25444
  var snapshotBySession = new Map;
25444
25445
  function isRecord(value) {
25445
25446
  return typeof value === "object" && value !== null;
@@ -25465,13 +25466,33 @@ async function resolveDefaultBranch(cwd) {
25465
25466
  return "main";
25466
25467
  }
25467
25468
  }
25468
- function getGitSnapshotSection(sessionID) {
25469
- const snapshot = snapshotBySession.get(sessionID);
25470
- if (!snapshot)
25469
+ async function captureSnapshot(cwd) {
25470
+ try {
25471
+ const [branch, mainBranch, statusRaw, recentCommits] = await Promise.all([
25472
+ runGit(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]),
25473
+ resolveDefaultBranch(cwd),
25474
+ runGit(cwd, ["--no-optional-locks", "status", "--short"]),
25475
+ runGit(cwd, ["--no-optional-locks", "log", "--oneline", "-n", "5"])
25476
+ ]);
25477
+ const status = statusRaw.length > MAX_STATUS_CHARS ? `${statusRaw.slice(0, MAX_STATUS_CHARS)}
25478
+ ... (truncated because it exceeds 2k characters)` : statusRaw;
25479
+ return {
25480
+ branch,
25481
+ mainBranch,
25482
+ status,
25483
+ recentCommits,
25484
+ capturedAt: Date.now()
25485
+ };
25486
+ } catch {
25471
25487
  return null;
25488
+ }
25489
+ }
25490
+ function formatSnapshot(snapshot) {
25491
+ const ageSeconds = Math.max(0, Math.round((Date.now() - snapshot.capturedAt) / 1000));
25492
+ const freshnessNote = ageSeconds <= 30 ? "Fresh snapshot." : `Snapshot captured ${ageSeconds}s ago \u2014 may be slightly stale.`;
25472
25493
  return [
25473
25494
  "# Git Context",
25474
- "This is a snapshot at the start of the session and may be stale now.",
25495
+ freshnessNote,
25475
25496
  `Current branch: ${snapshot.branch}`,
25476
25497
  `Main branch: ${snapshot.mainBranch}`,
25477
25498
  `Status:
@@ -25482,6 +25503,22 @@ ${snapshot.recentCommits || "(none)"}`
25482
25503
 
25483
25504
  `);
25484
25505
  }
25506
+ function getGitSnapshotSection(sessionID) {
25507
+ const snapshot = snapshotBySession.get(sessionID);
25508
+ if (!snapshot)
25509
+ return null;
25510
+ return formatSnapshot(snapshot);
25511
+ }
25512
+ async function refreshGitSnapshot(sessionID, cwd) {
25513
+ const existing = snapshotBySession.get(sessionID);
25514
+ if (existing && Date.now() - existing.capturedAt < SNAPSHOT_TTL_MS) {
25515
+ return;
25516
+ }
25517
+ const refreshed = await captureSnapshot(cwd);
25518
+ if (refreshed) {
25519
+ snapshotBySession.set(sessionID, refreshed);
25520
+ }
25521
+ }
25485
25522
  function createGitContextHook(directory) {
25486
25523
  return async (input, _output) => {
25487
25524
  if (!isRecord(input))
@@ -25492,32 +25529,98 @@ function createGitContextHook(directory) {
25492
25529
  const sessionID = typeof rawEvent.sessionID === "string" ? rawEvent.sessionID : typeof rawEvent.sessionId === "string" ? rawEvent.sessionId : undefined;
25493
25530
  if (!sessionID || snapshotBySession.has(sessionID))
25494
25531
  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 {}
25532
+ const snapshot = await captureSnapshot(directory);
25533
+ if (snapshot) {
25534
+ snapshotBySession.set(sessionID, snapshot);
25535
+ }
25511
25536
  };
25512
25537
  }
25513
25538
 
25539
+ // src/hooks/verification-reminder.ts
25540
+ var sessionStateById = new Map;
25541
+ var EDIT_TOOL_NAMES = new Set(["edit", "write"]);
25542
+ var TASK_TOOL_NAMES = new Set(["task", "taskcreate", "task_create"]);
25543
+ function isRecord2(value) {
25544
+ return typeof value === "object" && value !== null;
25545
+ }
25546
+ function getSessionState(sessionID) {
25547
+ const existing = sessionStateById.get(sessionID);
25548
+ if (existing) {
25549
+ return existing;
25550
+ }
25551
+ const created = {
25552
+ editedFiles: new Set,
25553
+ verificationTriggered: false
25554
+ };
25555
+ sessionStateById.set(sessionID, created);
25556
+ return created;
25557
+ }
25558
+ function getFilePath(value) {
25559
+ if (!isRecord2(value)) {
25560
+ return;
25561
+ }
25562
+ const candidates = [value.filePath, value.path, value.filename];
25563
+ return candidates.find((candidate) => typeof candidate === "string");
25564
+ }
25565
+ function createVerificationReminder(config2) {
25566
+ return async (input, _output) => {
25567
+ if (!config2.verification.enforce_contract || !config2.verification.auto_remind || !isRecord2(input)) {
25568
+ return;
25569
+ }
25570
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25571
+ const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : undefined;
25572
+ if (!sessionID || !toolName) {
25573
+ return;
25574
+ }
25575
+ if (TASK_TOOL_NAMES.has(toolName)) {
25576
+ const rawArgs = isRecord2(input.args) ? input.args : {};
25577
+ const subagentType = typeof rawArgs.subagent_type === "string" ? rawArgs.subagent_type.toLowerCase() : typeof rawArgs.subagentType === "string" ? rawArgs.subagentType.toLowerCase() : "";
25578
+ const verificationSubagent = `${config2.agent_name}-verification`;
25579
+ if (subagentType === verificationSubagent || subagentType === "verification") {
25580
+ getSessionState(sessionID).verificationTriggered = true;
25581
+ }
25582
+ return;
25583
+ }
25584
+ if (!EDIT_TOOL_NAMES.has(toolName)) {
25585
+ return;
25586
+ }
25587
+ const filePath = getFilePath(input.args);
25588
+ if (!filePath) {
25589
+ return;
25590
+ }
25591
+ const state = getSessionState(sessionID);
25592
+ state.editedFiles.add(filePath);
25593
+ };
25594
+ }
25595
+ function getVerificationState(sessionID) {
25596
+ const state = getSessionState(sessionID);
25597
+ return {
25598
+ editedFilesCount: state.editedFiles.size,
25599
+ verificationTriggered: state.verificationTriggered
25600
+ };
25601
+ }
25602
+ function listEditedFiles(sessionID, limit = 20) {
25603
+ const state = getSessionState(sessionID);
25604
+ return [...state.editedFiles].slice(-limit);
25605
+ }
25606
+ function requiresVerification(sessionID, minFileEdits) {
25607
+ const state = getSessionState(sessionID);
25608
+ return state.editedFiles.size >= minFileEdits && !state.verificationTriggered;
25609
+ }
25610
+
25514
25611
  // src/hooks/context-bundle.ts
25515
25612
  var execFileAsync2 = promisify2(execFile2);
25516
- var TASK_TOOL_NAMES = new Set(["task"]);
25613
+ var TASK_TOOL_NAMES2 = new Set(["task"]);
25517
25614
  var BUNDLE_MARKER_BEGIN = "<ccx-context-bundle>";
25518
25615
  var BUNDLE_MARKER_END = "</ccx-context-bundle>";
25519
25616
  var MAX_LIST_CHARS = 1500;
25520
- function isRecord2(value) {
25617
+ var RECENT_FILES_CACHE_TTL_MS = 30000;
25618
+ var EDITED_FILES_IN_BUNDLE = 10;
25619
+ var NON_GIT_SCAN_DEPTH = 3;
25620
+ var NON_GIT_MAX_FILES_EXAMINED = 2000;
25621
+ var NON_GIT_STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
25622
+ var recentFilesCache = new Map;
25623
+ function isRecord3(value) {
25521
25624
  return typeof value === "object" && value !== null;
25522
25625
  }
25523
25626
  function pickPromptFieldName(args2) {
@@ -25527,34 +25630,134 @@ function pickPromptFieldName(args2) {
25527
25630
  }
25528
25631
  return null;
25529
25632
  }
25530
- async function listRecentFiles(cwd, max) {
25531
- if (max <= 0)
25532
- return "";
25633
+ function isGitRepo(cwd) {
25634
+ try {
25635
+ return existsSync3(join3(cwd, ".git"));
25636
+ } catch {
25637
+ return false;
25638
+ }
25639
+ }
25640
+ async function listRecentFilesViaGit(cwd, max) {
25533
25641
  try {
25534
25642
  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(`
25643
+ return stdout.split(`
25536
25644
  `).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
25645
  } catch {
25646
+ return [];
25647
+ }
25648
+ }
25649
+ async function listRecentFilesFallback(cwd, max) {
25650
+ const ignoredDirs = new Set([
25651
+ "node_modules",
25652
+ ".git",
25653
+ ".hg",
25654
+ ".svn",
25655
+ "dist",
25656
+ "build",
25657
+ "out",
25658
+ "target",
25659
+ ".next",
25660
+ ".nuxt",
25661
+ "__pycache__",
25662
+ ".pytest_cache",
25663
+ ".mypy_cache",
25664
+ ".venv",
25665
+ "venv",
25666
+ ".idea",
25667
+ ".vscode",
25668
+ "coverage",
25669
+ ".cache"
25670
+ ]);
25671
+ const collected = [];
25672
+ const cutoff = Date.now() - NON_GIT_STALE_THRESHOLD_MS;
25673
+ async function walk(dir, depth) {
25674
+ if (depth > NON_GIT_SCAN_DEPTH)
25675
+ return;
25676
+ if (collected.length > NON_GIT_MAX_FILES_EXAMINED)
25677
+ return;
25678
+ let entries;
25679
+ try {
25680
+ entries = await readdir(dir, { withFileTypes: true });
25681
+ } catch {
25682
+ return;
25683
+ }
25684
+ for (const entry of entries) {
25685
+ if (collected.length > NON_GIT_MAX_FILES_EXAMINED)
25686
+ return;
25687
+ if (entry.name.startsWith(".") && entry.name !== "." && entry.name !== "..") {
25688
+ if (ignoredDirs.has(entry.name))
25689
+ continue;
25690
+ }
25691
+ if (ignoredDirs.has(entry.name))
25692
+ continue;
25693
+ const fullPath = join3(dir, entry.name);
25694
+ if (entry.isDirectory()) {
25695
+ await walk(fullPath, depth + 1);
25696
+ continue;
25697
+ }
25698
+ if (!entry.isFile())
25699
+ continue;
25700
+ try {
25701
+ const info = await fsStat(fullPath);
25702
+ if (info.mtimeMs < cutoff)
25703
+ continue;
25704
+ collected.push({ path: fullPath, mtimeMs: info.mtimeMs });
25705
+ } catch {
25706
+ continue;
25707
+ }
25708
+ }
25709
+ }
25710
+ await walk(cwd, 0);
25711
+ collected.sort((a, b) => b.mtimeMs - a.mtimeMs);
25712
+ const cwdPrefix = cwd.endsWith("/") ? cwd : `${cwd}/`;
25713
+ return collected.slice(0, max).map((entry) => entry.path.startsWith(cwdPrefix) ? entry.path.slice(cwdPrefix.length) : entry.path);
25714
+ }
25715
+ async function listRecentFiles(cwd, max) {
25716
+ if (max <= 0)
25544
25717
  return "";
25718
+ const cacheKey = `${cwd}:${max}`;
25719
+ const cached2 = recentFilesCache.get(cacheKey);
25720
+ if (cached2 && cached2.expiresAt > Date.now()) {
25721
+ return cached2.value;
25545
25722
  }
25723
+ const files = isGitRepo(cwd) ? await listRecentFilesViaGit(cwd, max) : await listRecentFilesFallback(cwd, max);
25724
+ const joined = files.join(`
25725
+ `);
25726
+ const value = joined.length > MAX_LIST_CHARS ? `${joined.slice(0, MAX_LIST_CHARS)}
25727
+ ... (truncated)` : joined;
25728
+ recentFilesCache.set(cacheKey, {
25729
+ value,
25730
+ expiresAt: Date.now() + RECENT_FILES_CACHE_TTL_MS
25731
+ });
25732
+ if (recentFilesCache.size > 64) {
25733
+ const oldestKey = recentFilesCache.keys().next().value;
25734
+ if (oldestKey !== undefined)
25735
+ recentFilesCache.delete(oldestKey);
25736
+ }
25737
+ return value;
25738
+ }
25739
+ function formatSessionEditedFiles(sessionID, limit) {
25740
+ if (!sessionID)
25741
+ return null;
25742
+ const files = listEditedFiles(sessionID, limit);
25743
+ if (files.length === 0)
25744
+ return null;
25745
+ const header = `# Parent session context
25746
+
25747
+ Files edited in this session (${files.length} total): ${files.join(", ")}`;
25748
+ return header;
25546
25749
  }
25547
25750
  function createContextBundleHook(args2) {
25548
25751
  const { config: config2, directory } = args2;
25549
25752
  return async (input, output) => {
25550
25753
  if (!config2.subagent_orchestration.context_bundle.enabled)
25551
25754
  return;
25552
- if (!isRecord2(input) || !isRecord2(output))
25755
+ if (!isRecord3(input) || !isRecord3(output))
25553
25756
  return;
25554
25757
  const toolName = typeof input.tool === "string" ? input.tool.toLowerCase() : "";
25555
- if (!TASK_TOOL_NAMES.has(toolName))
25758
+ if (!TASK_TOOL_NAMES2.has(toolName))
25556
25759
  return;
25557
- if (!isRecord2(output.args))
25760
+ if (!isRecord3(output.args))
25558
25761
  return;
25559
25762
  const promptKey = pickPromptFieldName(output.args);
25560
25763
  if (!promptKey)
@@ -25564,11 +25767,14 @@ function createContextBundleHook(args2) {
25564
25767
  return;
25565
25768
  const bundleParts = [];
25566
25769
  const bundleConfig = config2.subagent_orchestration.context_bundle;
25770
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25567
25771
  if (bundleConfig.include_cwd) {
25568
25772
  bundleParts.push(`Working directory: ${directory}`);
25569
25773
  }
25570
25774
  if (bundleConfig.include_git) {
25571
- const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
25775
+ if (sessionID) {
25776
+ await refreshGitSnapshot(sessionID, directory);
25777
+ }
25572
25778
  const gitSection = sessionID ? getGitSnapshotSection(sessionID) : null;
25573
25779
  if (gitSection) {
25574
25780
  bundleParts.push(gitSection);
@@ -25581,6 +25787,10 @@ function createContextBundleHook(args2) {
25581
25787
  ${recent}`);
25582
25788
  }
25583
25789
  }
25790
+ const editedSummary = formatSessionEditedFiles(sessionID, EDITED_FILES_IN_BUNDLE);
25791
+ if (editedSummary) {
25792
+ bundleParts.push(editedSummary);
25793
+ }
25584
25794
  if (bundleParts.length === 0)
25585
25795
  return;
25586
25796
  const bundle = [
@@ -25594,26 +25804,27 @@ ${recent}`);
25594
25804
  output.args[promptKey] = `${bundle}
25595
25805
 
25596
25806
  ${original}`;
25597
- const metadata = isRecord2(output.metadata) ? output.metadata : {};
25807
+ const metadata = isRecord3(output.metadata) ? output.metadata : {};
25598
25808
  metadata.contextBundle = {
25599
25809
  injected: true,
25600
25810
  tool: toolName,
25601
25811
  promptField: promptKey,
25602
- sections: bundleParts.length
25812
+ sections: bundleParts.length,
25813
+ nonGitFallback: !isGitRepo(directory)
25603
25814
  };
25604
25815
  output.metadata = metadata;
25605
25816
  };
25606
25817
  }
25607
25818
 
25608
25819
  // src/prompts/project-instructions.ts
25609
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
25820
+ import { existsSync as existsSync4, readFileSync as readFileSync2, statSync } from "fs";
25610
25821
  import { homedir as homedir2 } from "os";
25611
- import { dirname, isAbsolute, join as join3, resolve, sep } from "path";
25822
+ import { dirname, isAbsolute, join as join4, resolve, sep } from "path";
25612
25823
  var GLOBAL_DIR_RELATIVE = [".config", "opencode", "ccx"];
25613
25824
  var GLOBAL_FILENAMES = ["CCX.md", "instructions.md", "CLAUDE.md"];
25614
25825
  function safeReadText(filePath) {
25615
25826
  try {
25616
- if (!existsSync3(filePath))
25827
+ if (!existsSync4(filePath))
25617
25828
  return null;
25618
25829
  const stat = statSync(filePath);
25619
25830
  if (!stat.isFile())
@@ -25658,7 +25869,7 @@ function collectProjectInstructions(directory, filenames, maxDepth) {
25658
25869
  dirs.reverse();
25659
25870
  for (const dir of dirs) {
25660
25871
  for (const name of filenames) {
25661
- const candidate = join3(dir, name);
25872
+ const candidate = join4(dir, name);
25662
25873
  const resolved = resolve(candidate);
25663
25874
  if (seen.has(resolved))
25664
25875
  continue;
@@ -25675,11 +25886,11 @@ function collectGlobalInstructions() {
25675
25886
  const home = getHome();
25676
25887
  if (!home)
25677
25888
  return [];
25678
- const globalDir = join3(home, ...GLOBAL_DIR_RELATIVE);
25889
+ const globalDir = join4(home, ...GLOBAL_DIR_RELATIVE);
25679
25890
  const found = [];
25680
25891
  const seen = new Set;
25681
25892
  for (const name of GLOBAL_FILENAMES) {
25682
- const candidate = join3(globalDir, name);
25893
+ const candidate = join4(globalDir, name);
25683
25894
  const resolved = resolve(candidate);
25684
25895
  if (seen.has(resolved))
25685
25896
  continue;
@@ -25690,7 +25901,7 @@ function collectGlobalInstructions() {
25690
25901
  found.push({ path: resolved, origin: "global", content });
25691
25902
  }
25692
25903
  if (found.length === 0) {
25693
- const flat = join3(home, ".config", "opencode", "ccx.md");
25904
+ const flat = join4(home, ".config", "opencode", "ccx.md");
25694
25905
  const resolved = resolve(flat);
25695
25906
  if (!seen.has(resolved)) {
25696
25907
  const content = safeReadText(resolved);
@@ -25767,78 +25978,6 @@ ${body}`
25767
25978
  };
25768
25979
  }
25769
25980
 
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
25981
  // src/hooks/dynamic-system-prompt.ts
25843
25982
  function createDynamicSystemPrompt(config2, directory) {
25844
25983
  const instructionBundle = loadInstructionBundle(config2, directory);
@@ -25916,8 +26055,8 @@ Do NOT report completion to the user without going through this gate.`;
25916
26055
  }
25917
26056
 
25918
26057
  // src/hooks/environment-context.ts
25919
- import { existsSync as existsSync4 } from "fs";
25920
- import { join as join4 } from "path";
26058
+ import { existsSync as existsSync5 } from "fs";
26059
+ import { join as join5 } from "path";
25921
26060
  var environmentBySession = new Map;
25922
26061
  function isRecord4(value) {
25923
26062
  return typeof value === "object" && value !== null;
@@ -25935,7 +26074,7 @@ function createEnvironmentContext(directory) {
25935
26074
  const sessionID = typeof event.sessionID === "string" ? event.sessionID : typeof event.sessionId === "string" ? event.sessionId : undefined;
25936
26075
  const environment = {
25937
26076
  cwd: directory,
25938
- isGit: existsSync4(join4(directory, ".git")),
26077
+ isGit: existsSync5(join5(directory, ".git")),
25939
26078
  platform: process.platform,
25940
26079
  shell: process.env.SHELL ?? "unknown"
25941
26080
  };
@@ -26086,6 +26225,37 @@ function createMessageTransformHook() {
26086
26225
  };
26087
26226
  }
26088
26227
 
26228
+ // src/hooks/session-agent.ts
26229
+ var MAX_SESSIONS_TRACKED = 256;
26230
+ var sessionAgentById = new Map;
26231
+ function touch(sessionID, agent) {
26232
+ if (sessionAgentById.has(sessionID)) {
26233
+ sessionAgentById.delete(sessionID);
26234
+ }
26235
+ sessionAgentById.set(sessionID, agent);
26236
+ if (sessionAgentById.size > MAX_SESSIONS_TRACKED) {
26237
+ const oldestKey = sessionAgentById.keys().next().value;
26238
+ if (oldestKey !== undefined) {
26239
+ sessionAgentById.delete(oldestKey);
26240
+ }
26241
+ }
26242
+ }
26243
+ function recordSessionAgent(sessionID, agent) {
26244
+ if (!sessionID || !agent)
26245
+ return;
26246
+ touch(sessionID, agent);
26247
+ }
26248
+ function getSessionAgent(sessionID) {
26249
+ return sessionAgentById.get(sessionID);
26250
+ }
26251
+ function createSessionAgentTracker() {
26252
+ return async (input, _output) => {
26253
+ if (!input?.sessionID || !input.agent)
26254
+ return;
26255
+ recordSessionAgent(input.sessionID, input.agent);
26256
+ };
26257
+ }
26258
+
26089
26259
  // src/hooks/bash-analyzer.ts
26090
26260
  var import_bash_parser = __toESM(require_src(), 1);
26091
26261
  var WRAPPER_COMMANDS = new Set([
@@ -26509,6 +26679,26 @@ function analyzeBashCommand(source, options = {}) {
26509
26679
  }
26510
26680
  return dedupe(findings);
26511
26681
  }
26682
+ function extractCommandNames(source) {
26683
+ const trimmed = source.trim();
26684
+ if (!trimmed)
26685
+ return [];
26686
+ let commands = [];
26687
+ try {
26688
+ const ast = import_bash_parser.default(trimmed);
26689
+ commands = collectCommands(ast);
26690
+ } catch {
26691
+ commands = fallbackTokenize(trimmed);
26692
+ }
26693
+ const names = [];
26694
+ for (const cmd of commands) {
26695
+ const inner = unwrapWrapper(cmd);
26696
+ if (inner.name) {
26697
+ names.push(inner.name.toLowerCase());
26698
+ }
26699
+ }
26700
+ return names;
26701
+ }
26512
26702
  function fallbackTokenize(source) {
26513
26703
  const statements = source.split(/[;&|]{1,2}/);
26514
26704
  const out = [];
@@ -26544,6 +26734,240 @@ function pickHighestFinding(findings) {
26544
26734
  var TASK_LAUNCH_TOOL_NAMES = new Set(["task"]);
26545
26735
  var BASH_TOOL_NAMES = new Set(["bash", "shell", "sh", "exec"]);
26546
26736
  var SQL_TOOL_NAMES = new Set(["sql", "query", "db", "database"]);
26737
+ var ALL_AGENT_DEFS = [
26738
+ EXPLORE_AGENT_DEFINITION,
26739
+ PLAN_AGENT_DEFINITION,
26740
+ GENERAL_PURPOSE_AGENT_DEFINITION,
26741
+ VERIFICATION_AGENT_DEFINITION,
26742
+ COORDINATOR_AGENT_DEFINITION
26743
+ ];
26744
+ var READ_ONLY_BASH_COMMANDS = new Set([
26745
+ "ls",
26746
+ "pwd",
26747
+ "cd",
26748
+ "echo",
26749
+ "printf",
26750
+ "true",
26751
+ "false",
26752
+ "test",
26753
+ "[",
26754
+ "cat",
26755
+ "head",
26756
+ "tail",
26757
+ "less",
26758
+ "more",
26759
+ "bat",
26760
+ "grep",
26761
+ "egrep",
26762
+ "fgrep",
26763
+ "rg",
26764
+ "ripgrep",
26765
+ "ag",
26766
+ "find",
26767
+ "fd",
26768
+ "locate",
26769
+ "which",
26770
+ "whereis",
26771
+ "type",
26772
+ "command",
26773
+ "stat",
26774
+ "file",
26775
+ "du",
26776
+ "df",
26777
+ "wc",
26778
+ "nl",
26779
+ "sort",
26780
+ "uniq",
26781
+ "tr",
26782
+ "cut",
26783
+ "awk",
26784
+ "sed",
26785
+ "jq",
26786
+ "yq",
26787
+ "date",
26788
+ "hostname",
26789
+ "whoami",
26790
+ "id",
26791
+ "uname",
26792
+ "uptime",
26793
+ "git",
26794
+ "hg",
26795
+ "svn",
26796
+ "node",
26797
+ "python",
26798
+ "python3",
26799
+ "ruby",
26800
+ "perl",
26801
+ "npm",
26802
+ "pnpm",
26803
+ "yarn",
26804
+ "bun",
26805
+ "go",
26806
+ "cargo",
26807
+ "rustc",
26808
+ "tsc",
26809
+ "eslint",
26810
+ "prettier",
26811
+ "mypy",
26812
+ "ruff",
26813
+ "pylint",
26814
+ "flake8",
26815
+ "pytest",
26816
+ "jest",
26817
+ "vitest",
26818
+ "mocha",
26819
+ "curl",
26820
+ "wget",
26821
+ "nc",
26822
+ "ping",
26823
+ "dig",
26824
+ "nslookup",
26825
+ "host",
26826
+ "env",
26827
+ "printenv",
26828
+ "basename",
26829
+ "dirname",
26830
+ "readlink",
26831
+ "realpath",
26832
+ "diff",
26833
+ "comm",
26834
+ "cmp",
26835
+ "xxd",
26836
+ "od",
26837
+ "hexdump",
26838
+ "make",
26839
+ "cmake",
26840
+ "ninja",
26841
+ "docker",
26842
+ "kubectl",
26843
+ "helm",
26844
+ "ps",
26845
+ "top",
26846
+ "htop",
26847
+ "tree"
26848
+ ]);
26849
+ var DESTRUCTIVE_SUBCOMMANDS = {
26850
+ git: new Set([
26851
+ "add",
26852
+ "commit",
26853
+ "push",
26854
+ "pull",
26855
+ "merge",
26856
+ "rebase",
26857
+ "cherry-pick",
26858
+ "reset",
26859
+ "revert",
26860
+ "restore",
26861
+ "checkout",
26862
+ "switch",
26863
+ "branch",
26864
+ "tag",
26865
+ "stash",
26866
+ "clean",
26867
+ "gc",
26868
+ "filter-branch",
26869
+ "filter-repo",
26870
+ "rm",
26871
+ "mv",
26872
+ "config",
26873
+ "init",
26874
+ "clone",
26875
+ "remote"
26876
+ ]),
26877
+ npm: new Set(["install", "i", "uninstall", "remove", "rm", "publish", "link", "unlink", "run", "exec"]),
26878
+ pnpm: new Set(["install", "i", "add", "remove", "rm", "publish", "link", "unlink", "run", "exec", "dlx"]),
26879
+ yarn: new Set(["add", "remove", "install", "publish", "link", "unlink", "dlx"]),
26880
+ bun: new Set(["install", "add", "remove", "publish", "link", "unlink", "run", "x"]),
26881
+ cargo: new Set(["install", "uninstall", "publish", "run", "new", "init", "add", "remove"]),
26882
+ go: new Set(["install", "get", "mod", "run", "build"]),
26883
+ make: new Set(["install", "uninstall", "clean", "distclean"]),
26884
+ docker: new Set([
26885
+ "run",
26886
+ "create",
26887
+ "start",
26888
+ "stop",
26889
+ "kill",
26890
+ "rm",
26891
+ "rmi",
26892
+ "build",
26893
+ "push",
26894
+ "pull",
26895
+ "commit",
26896
+ "exec",
26897
+ "prune",
26898
+ "system",
26899
+ "volume",
26900
+ "network"
26901
+ ]),
26902
+ kubectl: new Set(["apply", "create", "delete", "edit", "patch", "replace", "scale", "rollout", "exec", "cp"]),
26903
+ helm: new Set(["install", "uninstall", "upgrade", "rollback", "delete"])
26904
+ };
26905
+ var ALLOWED_WRITE_PATH_PREFIXES = ["/tmp/", "/var/tmp/", "/private/tmp/"];
26906
+ function isRecord5(value) {
26907
+ return typeof value === "object" && value !== null;
26908
+ }
26909
+ function getReadOnlyAgentNames(agentName) {
26910
+ const out = new Set;
26911
+ for (const def of ALL_AGENT_DEFS) {
26912
+ if (def.readOnly) {
26913
+ out.add(`${agentName}-${def.name}`);
26914
+ }
26915
+ }
26916
+ return out;
26917
+ }
26918
+ function findReadOnlyViolations(bashSource) {
26919
+ const violations = [];
26920
+ const trimmed = bashSource.trim();
26921
+ if (!trimmed)
26922
+ return violations;
26923
+ const commandNames = extractCommandNames(trimmed);
26924
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
26925
+ for (const name of commandNames) {
26926
+ if (!READ_ONLY_BASH_COMMANDS.has(name)) {
26927
+ violations.push({
26928
+ reason: `command "${name}" is not in the read-only allowlist`,
26929
+ command: name
26930
+ });
26931
+ }
26932
+ }
26933
+ const inspectedIndices = new Set;
26934
+ for (let i = 0;i < tokens.length; i += 1) {
26935
+ const tokenLower = tokens[i].toLowerCase();
26936
+ const destructive = DESTRUCTIVE_SUBCOMMANDS[tokenLower];
26937
+ if (!destructive)
26938
+ continue;
26939
+ if (inspectedIndices.has(i))
26940
+ continue;
26941
+ let subIndex = i + 1;
26942
+ while (subIndex < tokens.length && tokens[subIndex].startsWith("-")) {
26943
+ subIndex += 1;
26944
+ }
26945
+ if (subIndex >= tokens.length)
26946
+ continue;
26947
+ const sub = tokens[subIndex].toLowerCase();
26948
+ inspectedIndices.add(subIndex);
26949
+ if (destructive.has(sub)) {
26950
+ violations.push({
26951
+ reason: `"${tokenLower} ${sub}" is a destructive subcommand`,
26952
+ command: `${tokenLower} ${sub}`
26953
+ });
26954
+ }
26955
+ }
26956
+ const redirectMatches = trimmed.matchAll(/(?:^|\s)(?:\d*>{1,2}|&>|>&)\s*([^\s;|&<>()]+)/g);
26957
+ for (const match of redirectMatches) {
26958
+ const target = match[1];
26959
+ if (!target || target === "/dev/null" || target === "&1" || target === "&2")
26960
+ continue;
26961
+ const isAllowed = ALLOWED_WRITE_PATH_PREFIXES.some((prefix) => target.startsWith(prefix)) || target.startsWith("$TMPDIR/") || target === "$TMPDIR";
26962
+ if (!isAllowed) {
26963
+ violations.push({
26964
+ reason: `redirection target "${target}" must be inside /tmp, /var/tmp, or $TMPDIR`,
26965
+ command: match[0].trim()
26966
+ });
26967
+ }
26968
+ }
26969
+ return violations;
26970
+ }
26547
26971
  function isGuardedSubagentName(value, agentName) {
26548
26972
  const prefix = `${agentName}-`;
26549
26973
  return typeof value === "string" && value.startsWith(prefix) && value !== `${agentName}-coordinator`;
@@ -26565,9 +26989,6 @@ function hasExplicitDelegationApproval(value) {
26565
26989
  return false;
26566
26990
  return metadata.subagentDelegation === true || metadata.subagentDelegation === "approved" || metadata.allow_subagent_delegation === true || metadata.allowSubagentDelegation === true || metadata.ccx_subagent_delegation === true || metadata.ccxSubagentDelegation === true;
26567
26991
  }
26568
- function isRecord5(value) {
26569
- return typeof value === "object" && value !== null;
26570
- }
26571
26992
  function collectBashSource(args2) {
26572
26993
  if (args2 === null || args2 === undefined)
26573
26994
  return [];
@@ -26616,15 +27037,16 @@ function formatWarning(level, toolName, finding) {
26616
27037
  return `${lead} (${finding.name}): ${finding.message}. Command: ${finding.command}`;
26617
27038
  }
26618
27039
  function createRiskGuard(config2) {
27040
+ const readOnlyAgentNames = getReadOnlyAgentNames(config2.agent_name);
26619
27041
  return async (input, output) => {
26620
27042
  if (!isRecord5(output)) {
26621
27043
  return;
26622
27044
  }
26623
27045
  const toolName = isRecord5(input) && typeof input.tool === "string" ? input.tool.toLowerCase() : "";
27046
+ const sessionID = isRecord5(input) && typeof input.sessionID === "string" ? input.sessionID : undefined;
27047
+ const directAgent = isRecord5(input) && typeof input.agent === "string" ? input.agent : undefined;
27048
+ const currentAgent = directAgent ?? (sessionID ? getSessionAgent(sessionID) : undefined);
26624
27049
  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
27050
  const approved = hasExplicitDelegationApproval(input) || hasExplicitDelegationApproval(output.args);
26629
27051
  if (isGuardedSubagentName(currentAgent, config2.agent_name) && !approved) {
26630
27052
  output.blocked = true;
@@ -26641,6 +27063,27 @@ function createRiskGuard(config2) {
26641
27063
  return;
26642
27064
  }
26643
27065
  }
27066
+ if (typeof currentAgent === "string" && readOnlyAgentNames.has(currentAgent) && BASH_TOOL_NAMES.has(toolName)) {
27067
+ const bashSources2 = collectBashSource(output.args);
27068
+ const allViolations = [];
27069
+ for (const source of bashSources2) {
27070
+ allViolations.push(...findReadOnlyViolations(source));
27071
+ }
27072
+ if (allViolations.length > 0) {
27073
+ output.blocked = true;
27074
+ const first = allViolations[0];
27075
+ output.warning = `Read-only agent "${currentAgent}" attempted a mutating shell operation: ${first.reason}. If this is intentional, run it from a non-readOnly agent.`;
27076
+ const metadata2 = isRecord5(output.metadata) ? output.metadata : {};
27077
+ metadata2.readOnlyAgentGuard = {
27078
+ flagged: true,
27079
+ blocked: true,
27080
+ agent: currentAgent,
27081
+ violations: allViolations
27082
+ };
27083
+ output.metadata = metadata2;
27084
+ return;
27085
+ }
27086
+ }
26644
27087
  const astEnabled = config2.risk_guard.ast_analysis;
26645
27088
  const bashSources = BASH_TOOL_NAMES.has(toolName) ? collectBashSource(output.args) : SQL_TOOL_NAMES.has(toolName) ? collectBashSource(output.args) : collectAllText(output.args);
26646
27089
  const analyzerOptions = {
@@ -27783,7 +28226,7 @@ function createPluginInterface(args2) {
27783
28226
  const environmentContext = createEnvironmentContext(ctx.directory);
27784
28227
  const gitContext = createGitContextHook(ctx.directory);
27785
28228
  const dynamicSystemPrompt = createDynamicSystemPrompt(config2, ctx.directory);
27786
- const chatMessageHook = createChatMessageHook(config2);
28229
+ const sessionAgentTracker = createSessionAgentTracker();
27787
28230
  const sessionWorkflows = createSessionWorkflowsHook({ config: config2, client: ctx.client });
27788
28231
  const chatParamsHook = createChatParamsHook();
27789
28232
  const compactionHook = createCompactionHook(config2);
@@ -27810,7 +28253,7 @@ function createPluginInterface(args2) {
27810
28253
  }
27811
28254
  },
27812
28255
  "chat.message": async (input, output) => {
27813
- await chatMessageHook(input, output);
28256
+ await sessionAgentTracker(input, output);
27814
28257
  await sessionWorkflows(input, output);
27815
28258
  if (input.sessionID) {
27816
28259
  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.7.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 {};