From 6ab42db9b41170014c3a3d7ac6168af41894dd8b Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Mon, 14 Sep 2026 21:06:45 +0800 Subject: [PATCH 01/49] feat: add hybrid code mode --- docs/design/code-mode-only.md | 26 +-- docs/design/code-mode-only.zh-CN.md | 168 ++++++++++++++++++ docs/design/code-mode.md | 85 +++++++++ docs/design/code-mode.zh-CN.md | 79 ++++++++ docs/users/configuration/settings.md | 1 + packages/cli/src/config/config.test.ts | 48 +++-- packages/cli/src/config/config.ts | 7 +- .../cli/src/config/settingsSchema.test.ts | 17 ++ packages/cli/src/config/settingsSchema.ts | 16 +- packages/cli/src/config/settingsUtils.ts | 2 +- .../SettingsDialog.test.tsx.snap | 20 +-- .../src/ui/opentui/dialogs-settings.test.ts | 2 +- .../runtime/agent-core.skill-gate.test.ts | 92 +++++++++- .../core/src/agents/runtime/agent-core.ts | 32 +++- packages/core/src/code-mode/code-mode.test.ts | 130 ++++++++++++-- packages/core/src/code-mode/scheduler.test.ts | 28 +-- packages/core/src/config/config.ts | 12 +- packages/core/src/index.ts | 1 + packages/core/src/tools/code-mode.ts | 38 +++- .../src/tools/exec-context-budget.test.ts | 2 +- .../core/src/tools/exec-context-tools.test.ts | 2 +- packages/core/src/tools/tool-registry.test.ts | 4 +- packages/core/src/tools/tool-registry.ts | 60 ++++++- .../schemas/settings.schema.json | 12 +- 24 files changed, 773 insertions(+), 111 deletions(-) create mode 100644 docs/design/code-mode-only.zh-CN.md create mode 100644 docs/design/code-mode.md create mode 100644 docs/design/code-mode.zh-CN.md diff --git a/docs/design/code-mode-only.md b/docs/design/code-mode-only.md index 7b56e28ac28..254c2da5fd8 100644 --- a/docs/design/code-mode-only.md +++ b/docs/design/code-mode-only.md @@ -1,5 +1,7 @@ # CodeModeOnly MVP +[English](code-mode-only.md) | [简体中文](code-mode-only.zh-CN.md) + ## Status Implemented for [#10377](https://github.com/QwenLM/qwen-code/issues/10377). @@ -7,14 +9,14 @@ The feature is opt-in and defaults off. ## Goal -Add a `tools.codeModeOnly` setting that replaces the ordinary model-facing -tool surface with one `exec` JavaScript tool plus the small set of tools that -must remain direct control-plane calls. `exec` code can call ordinary tools +Add a `tools.mode: "code_mode_only"` setting that replaces the ordinary +model-facing tool surface with one `exec` JavaScript tool plus the small set of +tools that must remain direct control-plane calls. `exec` code can call ordinary tools through `tools.(args)` without bypassing Qwen Code's validation, permissions, approvals, hooks, telemetry, cancellation, concurrency, or output budgets. -Direct mode is a compatibility boundary: when the setting is false, tool +Direct mode is a compatibility boundary: when `tools.mode` is `direct`, tool registration, deferred-tool behavior, provider requests, and execution remain unchanged. @@ -32,15 +34,15 @@ unchanged. ```json { "tools": { - "codeModeOnly": true + "mode": "code_mode_only" } } ``` -The setting resolves once to the effective `ToolMode` value `direct` or -`code_mode_only`. `ToolRegistry` and the execution surfaces consume that mode. -`exec` is only registered when the setting is enabled, so disabling the setting -also removes it from diagnostics and registry listings. +The setting resolves once to the effective `ToolMode` value. `ToolRegistry` +and the execution surfaces consume that mode. `exec` is only registered when a +code mode is enabled, so selecting `direct` also removes it from diagnostics +and registry listings. ## Exposure policy @@ -171,9 +173,9 @@ closed before scheduling. Invalid arguments continue to fail in the normal execution chain. A sandbox startup, protocol, timeout, memory, or teardown failure becomes an `exec` tool error. -Rollback is setting `tools.codeModeOnly` to false. No session migration or -registry cleanup is required because code mode has no persistent state and the -ordinary registry was never replaced. +Rollback is setting `tools.mode` to `direct`. No session migration or registry +cleanup is required because code mode has no persistent state and the ordinary +registry was never replaced. ## Verification diff --git a/docs/design/code-mode-only.zh-CN.md b/docs/design/code-mode-only.zh-CN.md new file mode 100644 index 00000000000..49de95596b6 --- /dev/null +++ b/docs/design/code-mode-only.zh-CN.md @@ -0,0 +1,168 @@ +# CodeModeOnly MVP + +[English](code-mode-only.md) | [简体中文](code-mode-only.zh-CN.md) + +## 状态 + +已为 [#10377](https://github.com/QwenLM/qwen-code/issues/10377) 实现。 +该功能为可选功能,默认关闭。 + +## 目标 + +新增 `tools.mode: "code_mode_only"` 设置,用一个 `exec` JavaScript 工具和少量 +必须保留为直接调用的控制面工具,取代面向模型的普通工具面。`exec` 中的代码可通过 +`tools.(args)` 调用普通工具,同时不会绕过 Qwen Code 的校验、权限、审批、 +hook、遥测、取消、并发或输出预算。 + +直接模式是兼容性边界:当 `tools.mode` 为 `direct` 时,工具注册、延迟工具行为、 +provider 请求和执行均保持不变。 + +## 非目标 + +- 混合暴露直接调用和代码调用。 +- 在多次 `exec` 调用间持久化 cell、全局变量或值。 +- 后台任务、`wait`、`yield`、`store` 或 `load`。 +- 原始/freeform provider 调用。 +- 在 code mode 中提供 `tool_search` 或 `tool_call` bridge。 +- 提供兼容 Node.js 的 sandbox。 + +## 配置 + +```json +{ + "tools": { + "mode": "code_mode_only" + } +} +``` + +该设置会解析一次,得到有效的 `ToolMode` 值;`ToolRegistry` 和各执行面使用这一 +模式。只有启用某个 code mode 时才注册 `exec`,因此选择 `direct` 也会将它从 +诊断信息和 registry 列表中移除。 + +## 暴露策略 + +registry 仍是事实来源。暴露只是注册工具之上的视图,而不是第二套 registry。 + +| 类别 | 模型顶层调用 | `exec` 内的 `tools.*` | +| ----------------------------------------- | --------------- | --------------------- | +| `exec` | 仅 CodeModeOnly | 否 | +| 直接控制工具 | 是 | 否 | +| 已注册的普通工具 | 否 | 是 | +| 隐藏 bridge(`tool_search`、`tool_call`) | 否 | 否 | + +直接控制 allowlist 集中维护且刻意保持精简。它覆盖用户交互 +(`ask_user_question`)、委派(`agent`)、终止输出约定、 +plan/goal/task/team/worktree/session 控制,以及生命周期无法安全隐藏在解释执行程序 +后的 ACP host 控制。新工具默认可在 code mode 中调用;增加仅直接调用或隐藏工具时, +必须显式修改策略。 + +延迟工具保持注册状态和延迟 registry 状态,并可从 `exec` 调用。生成的 `exec` +描述仍会携带这些工具的完整 schema,以及它们在 `ALL_TOOLS` 中的名称和描述: +CodeModeOnly 会隐藏 `tool_search`,嵌套调用也不会以 `functionCall` 出现在历史记录 +中,因此后续 reveal 无法补充描述里遗漏的 schema。CodeModeOnly 会跳过延迟预加载 +和 ToolSearch 提醒,因为二者都不属于它面向模型的协议。 + +## 确定性的 JavaScript 接口 + +每次向 provider 同步工具前,都会从当前 registry 生成 `exec` 描述。工具按规范 +名称排序。名称会通过替换无效标识符字符来规范化为 JavaScript 属性;如果名称以 +数字开头,还会添加前缀。如果两个规范名称映射到同一个属性,则字典序靠前的名称 +胜出,并用一条 warning 指出被省略的冲突项。 + +描述会定义: + +- 全新的异步 JavaScript 执行环境; +- 用于嵌套调用的 `tools.(args)`; +- 包含规范名称和 JavaScript 名称的 `ALL_TOOLS`; +- `text(value)`、`image(value)`、`audio(value)` 和 `exit()`; +- 从 JSON Schema 确定性生成的类 TypeScript 签名; +- 不提供 Node.js、import、网络 API、timer 和持久状态。 + +嵌套调用返回一个 JSON-safe 对象,其中包含真实 call id、工具名、状态、输出和 +structured content。调用失败或取消时,guest promise 会使用 scheduler/ACP 错误 +reject。 + +## Sandbox 与传输 + +`exec` 在独立子进程中运行编译为 WebAssembly 的 QuickJS。每次调用都会创建全新 +的 QuickJS runtime 和 context。子进程通过 stdio 接收精简的 framed JSON 协议; +其中不包含工具实现或 Qwen 配置。父进程把 JavaScript 名称映射回规范 registry +名称,并分派每次调用。 + +guest 不提供 Node 全局变量、`require`、`process`、文件系统、socket、模块加载器、 +`console`、timer、`Atomics`、`SharedArrayBuffer` 或 `WebAssembly`。由于没有安装 +模块加载器,动态和静态 import 都会失败。runtime 的内存和 stack 限制固定。 +QuickJS 的 interrupt hook 会限制 guest CPU 预算。当 guest 挂起等待已注册的 host +工具时,该预算和父进程的兜底 watchdog 会暂停;在 guest job 再次运行前恢复。 +因此,长时间 build 可以继续使用工具声明的 timeout,同时 guest CPU 死循环无法 +逃逸固定预算。源码、协议 frame、helper 输出和最终结果都有上限。 + +取消操作会中止所有嵌套调用并终止子进程。顶层 promise settled 后,也会在 teardown +前取消未 await 的嵌套调用。子进程、timer、promise handle 或 guest 全局变量都不 +会在调用结束后存活。 + +子进程只接收最小化且经过清理的环境,guest 无法检查该环境。独立进程为解释器故障 +提供纵深防御;QuickJS/WASM 是 guest 的 capability 边界。 + +## 重入式分派 + +`CoreToolScheduler.schedule()` 无法递归调用:子调用会排在仍在运行的父调用之后, +从而形成死锁。因此,scheduler 会在 invocation 边界绑定 async-local +`ToolCallRuntime` context,`exec` 只与该 context 通信。 + +scheduler runtime 会将同一 event-loop turn 中收到的嵌套调用合并为一批,并通过 +使用相同 `Config` 和 observer 配置的 sibling scheduler 执行。这样无需直接调用 +`tool.execute()`,仍能沿用现有的构建/校验、权限、确认、hook、执行、截断、遥测和 +并发链路。guest 的连续 await 会生成连续 batch;`Promise.all` 调用会进入同一个 +batch,由现有的只读并发分类器处理。嵌套 request id 包含父 id,并携带 +`source: code_mode` 和 `parentCallId`。 + +嵌套 scheduler 更新会合并到所属 scheduler 的可见调用中,嵌套 id 的确认响应也会 +委派给它。外层模型仍只接收完整的 `exec` 响应。 + +ACP 沿用其独立审计过的执行链。它的 invocation 边界会绑定相同的 runtime 接口, +嵌套分派通过 `Session.runTool` 重入。因此,ACP 顶层和嵌套调用使用相同的 ACP 权限、 +审批、hook、遥测、持久化和取消机制,而不是借用 CLI scheduler 状态或直接执行工具。 +ACP 会串行执行普通嵌套调用,与现有直接工具顺序一致;Core scheduler 则保留现有的 +安全只读并行 batch。 + +## Provider 行为 + +所有 provider 继续使用 `ToolRegistry` 提供的 `FunctionDeclaration[]`。在 Direct +模式下,该数组与现有视图逐字节一致。在 CodeModeOnly 中,它是暴露策略生成的视图, +因此 Gemini/Qwen、OpenAI-compatible 和 Anthropic adapter 都会收到结构化的 +`exec` declaration,不需要 provider 专用 prompt。 + +经过过滤的子智能体 declaration 使用相同策略。对于只读 teammate 或带执行 +allowlist 的 fork,`exec` 是经过审计的 gateway,而允许的确切嵌套名称会随 invocation +context 传递。同一集合既用于生成描述,也会在 Core 分派前再次校验,因此显式 +allowlist 可以收窄 code-mode-callable 嵌套工具,而不会变成仅 prompt 策略、暴露 +隐藏 bridge 或使 `exec` 能够递归。对于 cache-compatible fork,继承的 `exec` +declaration 代表其普通 binding:省略 `fork_tools` 时继承这些 binding,显式列表则 +用请求的子集替换它们。 + +## 失败与回滚 + +未知、冲突、隐藏、仅直接调用和递归请求的工具都会在调度前 fail closed。无效参数 +继续在正常执行链中失败。sandbox 启动、协议、timeout、内存或 teardown 失败会转为 +`exec` 工具错误。 + +回滚方式是将 `tools.mode` 设为 `direct`。无需迁移 session 或清理 registry, +因为 code mode 没有持久状态,且普通 registry 从未被替换。 + +## 验证 + +单元和集成测试必须覆盖: + +- Direct 和 CodeModeOnly 暴露、延迟保留、冲突处理、确定性描述和显式子智能体过滤。 +- 有效/无效 JavaScript、异步顺序、`Promise.all`、helper 输出、throw error、CPU + 死循环、内存限制、import、不可用全局变量、隔离、输出限制、取消、未 await 工作和 + 递归调用。 +- 嵌套权限、确认、Pre/Post hook、失败、输出预算、真实名称遥测/UI 更新、MCP 工具 + 和 scheduler 死锁回归。 +- Gemini/Qwen、OpenAI-compatible、Anthropic、headless、interactive、subagent + 和 ACP 调用面。 + +只有通过相关 package 测试、build、typecheck、E2E probe 和两轮干净的完整 diff +自审,才算实现完成。 diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md new file mode 100644 index 00000000000..3df7d63bab4 --- /dev/null +++ b/docs/design/code-mode.md @@ -0,0 +1,85 @@ +# Code Mode + +[English](code-mode.md) | [简体中文](code-mode.zh-CN.md) + +## Status + +Implemented. The feature is experimental and opt-in. + +## Problem + +Qwen Code currently supports direct tool calls and `CodeModeOnly`. The latter +replaces ordinary top-level tools with `exec`, which is useful for orchestration +but prevents a model from choosing direct calls when they are clearer or more +efficient. Codex models this as three tool modes: direct, hybrid Code Mode, and +CodeModeOnly. + +## Goal + +Add a hybrid `CodeMode` option without changing the existing default or +`CodeModeOnly` behavior. + +## Configuration + +```json +{ + "tools": { + "mode": "code_mode" + } +} +``` + +The effective modes are: + +| `tools.mode` value | Effective mode | +| ------------------ | ---------------- | +| omitted / `direct` | `direct` | +| `code_mode` | `code_mode` | +| `code_mode_only` | `code_mode_only` | + +This follows Codex's `ToolMode` serialized values. Safe mode and bare mode +force `direct`. + +## Exposure policy + +| Surface | `direct` | `code_mode` | `code_mode_only` | +| -------------------- | ------------------------ | ------------------------------- | ---------------- | +| Ordinary eager tools | Direct | Direct and nested | Nested only | +| Deferred tools | `tool_search` | `tool_search` and nested | Nested only | +| Direct-control tools | Direct | Direct only | Direct only | +| `exec` | Hidden | Direct | Direct | +| Hidden bridge tools | Existing direct behavior | Direct where already applicable | Hidden | + +In `code_mode`, ordinary visible tool descriptions gain an `exec` declaration +for that tool. The `exec` description keeps the complete `ALL_TOOLS` metadata +but does not duplicate every schema. Deferred tools gain their declaration when +their normal top-level declaration is revealed. In `code_mode_only`, the +existing behavior remains: all nested declarations live in the `exec` +description because no later top-level reveal is possible. + +Filtered subagent declarations preserve the same mode and narrow both direct +and nested calls to the subagent's allowed tool set. + +## Constraints and risks + +- Normal direct declarations must remain byte-for-byte unchanged in `direct`. +- Nested calls continue through the existing scheduler or ACP execution path; + the mode must not bypass validation, permissions, hooks, cancellation, or + telemetry. +- Duplicating every schema in hybrid mode would increase prompt size, so only + the per-tool nested declaration is appended there. + +## Validation + +- Verify mode resolution and safe/bare-mode fallback. +- Verify direct, hybrid, and CodeModeOnly declaration surfaces. +- Verify filtered subagent declarations and nested allowlists. +- Run focused Core and CLI tests, then build and typecheck. + +## Acceptance criteria + +- `tools.mode: "code_mode"` registers `exec` while retaining ordinary direct + tools and deferred discovery. +- Ordinary visible tools advertise their nested JavaScript signature. +- `tools.mode: "code_mode_only"` selects the stricter behavior. +- The default, safe-mode, and bare-mode surfaces remain direct-only. diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md new file mode 100644 index 00000000000..327054016d6 --- /dev/null +++ b/docs/design/code-mode.zh-CN.md @@ -0,0 +1,79 @@ +# Code Mode + +[English](code-mode.md) | [简体中文](code-mode.zh-CN.md) + +## 状态 + +已实现。该功能为实验性功能,默认关闭。 + +## 问题 + +Qwen Code 目前支持直接工具调用和 `CodeModeOnly`。后者会用 `exec` 替换普通 +顶层工具,适合编排调用,但模型无法在直接调用更清晰或更高效时选择直接调用。 +Codex 将这套能力建模为三种工具模式:直接模式、混合 Code Mode 和 +CodeModeOnly。 + +## 目标 + +新增混合 `CodeMode`,同时保持现有默认模式和 `CodeModeOnly` 行为不变。 + +## 配置 + +```json +{ + "tools": { + "mode": "code_mode" + } +} +``` + +有效模式如下: + +| `tools.mode` 值 | 有效模式 | +| ---------------- | ---------------- | +| 省略 / `direct` | `direct` | +| `code_mode` | `code_mode` | +| `code_mode_only` | `code_mode_only` | + +这些值与 Codex 的 `ToolMode` 序列化值一致。安全模式和 bare 模式会强制使用 +`direct`。 + +## 暴露策略 + +| 调用面 | `direct` | `code_mode` | `code_mode_only` | +| ------------ | -------------------- | ------------------------ | ---------------- | +| 普通即时工具 | 直接调用 | 直接调用和嵌套调用 | 仅嵌套调用 | +| 延迟工具 | `tool_search` | `tool_search` 和嵌套调用 | 仅嵌套调用 | +| 直接控制工具 | 直接调用 | 仅直接调用 | 仅直接调用 | +| `exec` | 隐藏 | 直接调用 | 直接调用 | +| 隐藏桥接工具 | 保持现有直接模式行为 | 在原本适用时直接调用 | 隐藏 | + +在 `code_mode` 中,普通可见工具的描述会附加该工具的 `exec` 调用声明。 +`exec` 描述保留完整的 `ALL_TOOLS` 元数据,但不重复所有 schema。延迟工具在 +按正常流程暴露顶层声明时获得对应声明。在 `code_mode_only` 中保持现有行为: +由于后续无法暴露顶层声明,所有嵌套声明都集中在 `exec` 描述中。 + +经过过滤的子智能体声明沿用相同模式,并将直接调用和嵌套调用都限制在该子智能体 +允许的工具集合内。 + +## 约束与风险 + +- `direct` 模式下的普通工具声明必须保持完全不变。 +- 嵌套调用继续经过现有 scheduler 或 ACP 执行链,不能绕过校验、权限、hook、 + 取消和遥测。 +- 混合模式若重复全部 schema 会增大提示词,因此只在各顶层工具描述中附加对应的 + 嵌套声明。 + +## 验证 + +- 验证模式解析以及安全模式/bare 模式回退。 +- 验证直接、混合和 CodeModeOnly 三种声明面。 +- 验证子智能体过滤后的声明和嵌套 allowlist。 +- 运行 Core 和 CLI 的相关测试,然后执行构建和类型检查。 + +## 验收标准 + +- `tools.mode: "code_mode"` 注册 `exec`,同时保留普通直接工具和延迟发现。 +- 普通可见工具会声明其嵌套 JavaScript 调用签名。 +- `tools.mode: "code_mode_only"` 选择严格模式。 +- 默认模式、安全模式和 bare 模式仍然只使用直接调用。 diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 484b85dbf75..050300695ed 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -384,6 +384,7 @@ If you are experiencing performance issues with file searching (e.g., with `@` c | `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, callable, and discoverable via `tool_search`. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with `tool_search`: when ToolSearch is not registered — `tools.toolSearch.enabled: false`, a `tool_search` deny rule, or the automatic opt-out for DeepSeek models — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools are out of reach for that session (they stay in `/tools`, and a warning is logged). Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in `tools.visible` are declared up front. Use `permissions.deny` if you meant to remove them, or leave ToolSearch on. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. | `undefined` | | | `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | | `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | +| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. | `direct` | Experimental. Requires restart. | | `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is loadable via `tool_search`, but its schema is not sent in the initial model request. | `undefined` | | | `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | | `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 00996c08764..2a994293837 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -20,6 +20,7 @@ import { AuthType, Storage, SessionIdCaseConflictError, + ToolMode, } from '@qwen-code/qwen-code-core'; import { normalizeModelProposedGoals } from './config.js'; import { @@ -3567,39 +3568,50 @@ describe('mergeExcludeTools', () => { expect(config.getToolSearchThreshold()).toBe(10); }); - it('should enable CodeModeOnly only when explicitly configured', async () => { + it('should resolve the tool mode enum', async () => { process.argv = ['node', 'script.js']; const argv = await parseArguments(); const direct = await loadCliConfig({}, argv, undefined, []); const codeMode = await loadCliConfig( - { tools: { codeModeOnly: true } }, + { tools: { mode: ToolMode.CodeMode } }, + argv, + undefined, + [], + ); + const codeModeOnly = await loadCliConfig( + { tools: { mode: ToolMode.CodeModeOnly } }, argv, undefined, [], ); expect(direct.getCodeModeOnly()).toBe(false); - expect(codeMode.getCodeModeOnly()).toBe(true); + expect(codeMode.getCodeModeOnly()).toBe(false); + expect(codeModeOnly.getCodeModeOnly()).toBe(true); expect(direct.getToolMode()).toBe('direct'); - expect(codeMode.getToolMode()).toBe('code_mode_only'); + expect(codeMode.getToolMode()).toBe('code_mode'); + expect(codeModeOnly.getToolMode()).toBe('code_mode_only'); }); - it.each(['--safe-mode', '--bare'])( - 'should disable CodeModeOnly in %s mode', - async (flag) => { - process.argv = ['node', 'script.js', flag]; - const argv = await parseArguments(); - const config = await loadCliConfig( - { tools: { codeModeOnly: true } }, - argv, - undefined, - [], - ); + it.each([ + ['--safe-mode', ToolMode.CodeMode], + ['--safe-mode', ToolMode.CodeModeOnly], + ['--bare', ToolMode.CodeMode], + ['--bare', ToolMode.CodeModeOnly], + ] as const)('should force direct mode for %s with %s', async (flag, mode) => { + process.argv = ['node', 'script.js', flag]; + const argv = await parseArguments(); + const config = await loadCliConfig( + { tools: { mode } }, + argv, + undefined, + [], + ); - expect(config.getCodeModeOnly()).toBe(false); - }, - ); + expect(config.getCodeModeOnly()).toBe(false); + expect(config.getToolMode()).toBe('direct'); + }); it('should default tools.listDirectory.enabled to false', async () => { process.argv = ['node', 'script.js']; diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 08caf32aa7f..91851eabcfb 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -30,6 +30,7 @@ import { type ToolName, type ToolInvocationGuard, ToolNames, + ToolMode, NativeLspClient, createDebugLogger, NativeLspService, @@ -2257,8 +2258,10 @@ export async function loadCliConfig( disabledTools: disabledTools.length > 0 ? disabledTools : undefined, visibleTools: visibleTools.length > 0 ? visibleTools : undefined, eagerTools, - codeModeOnly: - !bareMode && !safeMode && settings.tools?.codeModeOnly === true, + toolMode: + !bareMode && !safeMode + ? (settings.tools?.mode ?? ToolMode.Direct) + : ToolMode.Direct, toolSearchThreshold: bareMode || safeMode ? 0 : settings.tools?.toolSearch?.threshold, // New unified permissions (PermissionManager source of truth). diff --git a/packages/cli/src/config/settingsSchema.test.ts b/packages/cli/src/config/settingsSchema.test.ts index dca196d953c..11d193037c2 100644 --- a/packages/cli/src/config/settingsSchema.test.ts +++ b/packages/cli/src/config/settingsSchema.test.ts @@ -232,6 +232,23 @@ describe('SettingsSchema', () => { }); }); + it('should expose the tool mode enum', () => { + expect(getSettingsSchema().tools.properties.mode).toMatchObject({ + type: 'enum', + default: 'direct', + requiresRestart: true, + showInDialog: true, + options: [ + { value: 'direct', label: 'Default' }, + { value: 'code_mode', label: 'Code Mode' }, + { value: 'code_mode_only', label: 'Code Mode Only' }, + ], + }); + expect(getSettingsSchema().tools.properties).not.toHaveProperty( + 'codeModeOnly', + ); + }); + it('should expose cumulative tool result threshold in clearContextOnIdle', () => { const threshold = getSettingsSchema().context.properties.clearContextOnIdle.properties diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index d3b9d6e792c..f338123af45 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -33,6 +33,7 @@ import { OutputFormat, REASONING_EFFORT_TIERS, SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT, + ToolMode, } from '@qwen-code/qwen-code-core'; import type { CustomTheme } from '../ui/themes/theme.js'; import { getLanguageSettingsOptions } from '../i18n/languages.js'; @@ -2714,15 +2715,20 @@ const SETTINGS_SCHEMA = { description: 'Settings for built-in and custom tools.', showInDialog: false, properties: { - codeModeOnly: { - type: 'boolean', - label: 'Code Mode Only (Experimental)', + mode: { + type: 'enum', + label: 'Tool Mode (Experimental)', category: 'Tools', requiresRestart: true, - default: false, + default: ToolMode.Direct, description: - 'Expose ordinary tools to the model only through the isolated exec JavaScript tool. Direct control tools remain available. Ignored in safe and bare modes.', + 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct.', showInDialog: true, + options: [ + { value: ToolMode.Direct, label: 'Default' }, + { value: ToolMode.CodeMode, label: 'Code Mode' }, + { value: ToolMode.CodeModeOnly, label: 'Code Mode Only' }, + ], }, sandbox: { type: 'object', diff --git a/packages/cli/src/config/settingsUtils.ts b/packages/cli/src/config/settingsUtils.ts index c75fcd59987..eb54aa1f4e1 100644 --- a/packages/cli/src/config/settingsUtils.ts +++ b/packages/cli/src/config/settingsUtils.ts @@ -164,7 +164,7 @@ export function getAllSettingKeys(): string[] { const SETTINGS_DIALOG_ORDER: readonly string[] = [ // Workflow Control - most impactful setting 'tools.approvalMode', - 'tools.codeModeOnly', + 'tools.mode', // Localization - users often set this first 'general.language', diff --git a/packages/cli/src/ui/components/__snapshots__/SettingsDialog.test.tsx.snap b/packages/cli/src/ui/components/__snapshots__/SettingsDialog.test.tsx.snap index 5338e261363..ace3bc0019c 100644 --- a/packages/cli/src/ui/components/__snapshots__/SettingsDialog.test.tsx.snap +++ b/packages/cli/src/ui/components/__snapshots__/SettingsDialog.test.tsx.snap @@ -10,7 +10,7 @@ exports[`SettingsDialog > Snapshot Tests > should render default state correctly │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -35,7 +35,7 @@ exports[`SettingsDialog > Snapshot Tests > should render focused on scope select │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -60,7 +60,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with accessibility sett │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -85,7 +85,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with all boolean settin │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -110,7 +110,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with different scope se │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -135,7 +135,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with different scope se │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -160,7 +160,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with file filtering set │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -185,7 +185,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with mixed boolean and │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -210,7 +210,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with tools and security │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ @@ -235,7 +235,7 @@ exports[`SettingsDialog > Snapshot Tests > should render with various boolean se │ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ │ │ ●︎ Tool Approval Mode Auto │ -│ Code Mode Only (Experimental) false │ +│ Tool Mode (Experimental) Default │ │ Language: UI Auto (detect from system) │ │ Language: Model Auto (follow user input) │ │ Theme Qwen Dark ▸ │ diff --git a/packages/cli/src/ui/opentui/dialogs-settings.test.ts b/packages/cli/src/ui/opentui/dialogs-settings.test.ts index 3de7cdcefe2..020248059ea 100644 --- a/packages/cli/src/ui/opentui/dialogs-settings.test.ts +++ b/packages/cli/src/ui/opentui/dialogs-settings.test.ts @@ -69,7 +69,7 @@ describe('buildSettingsListItems', () => { expect(items.length).toBeGreaterThan(0); const keys = items.map((item) => item.key); expect(keys).toContain('ui.theme'); - expect(keys.indexOf('tools.codeModeOnly')).toBe( + expect(keys.indexOf('tools.mode')).toBe( keys.indexOf('tools.approvalMode') + 1, ); // Labels are resolved from the schema definitions. diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index b5e3122a9f4..dae34d74800 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -12,6 +12,7 @@ import { makeFakeConfig } from '../../test-utils/config.js'; import { ToolRegistry } from '../../tools/tool-registry.js'; import { ExecTool } from '../../tools/exec.js'; import { MockTool } from '../../test-utils/mock-tool.js'; +import { ToolMode } from '../../tools/code-mode.js'; // The skill-announcement gate asks whether the model can INVOKE a skill, and // that is two conditions, not one. @@ -191,7 +192,7 @@ describe('AgentCore skill-gate inputs', () => { toolConfig: ConstructorParameters[5], includeSkill = true, ) { - const config = makeFakeConfig({ codeModeOnly: true }); + const config = makeFakeConfig({ toolMode: 'code_mode_only' }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); @@ -295,7 +296,7 @@ describe('AgentCore skill-gate inputs', () => { }); it('uses exec as a restricted gateway for a narrowed CodeModeOnly agent', async () => { - const config = makeFakeConfig({ codeModeOnly: true }); + const config = makeFakeConfig({ toolMode: 'code_mode_only' }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); @@ -331,8 +332,89 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual([ToolNames.READ_FILE]); }); + it('keeps direct and exec surfaces aligned for a narrowed CodeMode agent', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'restricted-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.READ_FILE], + executionAllowedTools: [ToolNames.READ_FILE], + }, + ); + + const declarations = await core.prepareTools(); + const exec = declarations.find( + (declaration) => declaration.name === ToolNames.EXEC, + ); + const readFile = declarations.find( + (declaration) => declaration.name === ToolNames.READ_FILE, + ); + + expect(declarations.map((declaration) => declaration.name)).toEqual([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ]); + expect(executable(core, ToolNames.EXEC)).toBe(true); + expect(exec?.description).toContain('"name":"read_file"'); + expect(exec?.description).not.toContain('"name":"write_file"'); + expect(readFile?.description).toContain( + 'declare const tools: { read_file(args:', + ); + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual([ToolNames.READ_FILE]); + }); + + it('keeps inherited exec bindings off the direct CodeMode surface', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'exec-only-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC], + executionAllowedTools: [ToolNames.EXEC], + }, + ); + + const declarations = await core.prepareTools(); + + expect(declarations.map((declaration) => declaration.name)).toEqual([ + ToolNames.EXEC, + ]); + expect(declarations[0]?.description).toContain('"name":"read_file"'); + expect(declarations[0]?.description).toContain('"name":"write_file"'); + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual([ToolNames.READ_FILE, ToolNames.WRITE_FILE]); + }); + it('narrows an inherited fork exec surface to its execution allowlist', async () => { - const config = makeFakeConfig({ codeModeOnly: true }); + const config = makeFakeConfig({ toolMode: 'code_mode_only' }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); @@ -361,7 +443,7 @@ describe('AgentCore skill-gate inputs', () => { }); it('inherits the parent exec bindings for an unrestricted fork', async () => { - const config = makeFakeConfig({ codeModeOnly: true }); + const config = makeFakeConfig({ toolMode: 'code_mode_only' }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); @@ -389,7 +471,7 @@ describe('AgentCore skill-gate inputs', () => { }); it('keeps disallowed tools out of a restricted CodeModeOnly gateway', async () => { - const config = makeFakeConfig({ codeModeOnly: true }); + const config = makeFakeConfig({ toolMode: 'code_mode_only' }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 44a4b1f40cd..ff24e2d367d 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -112,7 +112,11 @@ import { AgentEventEmitter, AgentEventType } from './agent-events.js'; import { AgentStatistics, type AgentStatsSummary } from './agent-statistics.js'; import { matchesMcpPattern } from '../../permissions/rule-parser.js'; import { ToolNames } from '../../tools/tool-names.js'; -import { getToolExposure, ToolMode } from '../../tools/code-mode.js'; +import { + getToolExposure, + isCodeModeEnabled, + ToolMode, +} from '../../tools/code-mode.js'; import { DEFAULT_QWEN_MODEL } from '../../config/models.js'; import { type ContextState, templateString } from './agent-headless.js'; import { getResponseText } from '../../utils/partUtils.js'; @@ -723,7 +727,7 @@ export class AgentCore { : pattern === name, ) === true; - if (this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly) { + if (isCodeModeEnabled(this.runtimeContext.getToolMode?.())) { const stringTools = this.toolConfig?.tools.filter( (tool): tool is string => typeof tool === 'string', @@ -747,6 +751,7 @@ export class AgentCore { (name) => (!configuredNames || configuredNames.has(name) || + name === ToolNames.EXEC || (inheritsCodeModeBindings && getToolExposure(name) === 'code-mode-callable')) && !isExcluded(name) && @@ -759,8 +764,17 @@ export class AgentCore { (name) => getToolExposure(name) === 'code-mode-callable', ), ); - const declarations = - toolRegistry.getFunctionDeclarationsFiltered(allowedNames); + const declarationNames = + this.runtimeContext.getToolMode?.() === ToolMode.CodeMode && + configuredNames + ? allowedNames.filter( + (name) => name === ToolNames.EXEC || configuredNames.has(name), + ) + : allowedNames; + const declarations = toolRegistry.getFunctionDeclarationsFiltered( + declarationNames, + new Set(this.codeModeAllowedToolNames), + ); declarations.push( ...inlineTools.filter( (tool) => @@ -1686,7 +1700,7 @@ export class AgentCore { ): boolean { return ( (declaredToolNames.has(ToolNames.SKILL) || - (this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly && + (isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && declaredToolNames.has(ToolNames.EXEC) && !!this.runtimeContext.getToolRegistry().getTool(ToolNames.SKILL) && this.codeModeAllowedToolNames?.includes(ToolNames.SKILL) === true)) && @@ -1700,12 +1714,12 @@ export class AgentCore { } if ( toolName === ToolNames.EXEC && - this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) ) { return true; } if ( - this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly && + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && this.executionAllowedExactTools?.has(ToolNames.EXEC) && getToolExposure(toolName) === 'code-mode-callable' ) { @@ -1795,7 +1809,7 @@ export class AgentCore { }> { if ( this.codeModeAllowedToolNames === undefined && - this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) ) { await this.prepareTools(); } @@ -2286,7 +2300,7 @@ export class AgentCore { response_id: responseId, wasOutputTruncated, ...(toolName === ToolNames.EXEC && - this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) ? { codeModeAllowedToolNames: this.codeModeAllowedToolNames ?? [], } diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index 63e304fdddd..60ef610b5fa 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -16,6 +16,7 @@ import { getToolExposure, isCodeModeToolCallAllowed, planCodeModeBindings, + ToolMode, type CodeModeBindingPlan, } from '../tools/code-mode.js'; import { executeCodeMode } from './host-client.js'; @@ -48,7 +49,7 @@ function runtime( return { parentCallId: 'parent', dispatch }; } -describe('CodeModeOnly exposure', () => { +describe('code mode exposure', () => { const directTools = [ 'ask_user_question', 'agent', @@ -122,7 +123,9 @@ describe('CodeModeOnly exposure', () => { }); it('moves management and context tools out of top-level declarations', () => { - const registry = new ToolRegistry(makeFakeConfig({ codeModeOnly: true })); + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), + ); for (const name of [...directTools, ...migratedTools, 'exec']) { registry.registerTool(new MockTool({ name })); } @@ -139,34 +142,137 @@ describe('CodeModeOnly exposure', () => { expect(description).toContain('terminal update_goal'); }); - it('registers exec only when CodeModeOnly is enabled', async () => { + it('registers exec in both code modes', async () => { const direct = makeFakeConfig(); const directRegistry = await direct.createToolRegistry(undefined, { skipDiscovery: true, }); - const codeMode = makeFakeConfig({ codeModeOnly: true }); + const codeMode = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const codeModeRegistry = await codeMode.createToolRegistry(undefined, { skipDiscovery: true, }); + const codeModeOnly = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); + const codeModeOnlyRegistry = await codeModeOnly.createToolRegistry( + undefined, + { skipDiscovery: true }, + ); expect(directRegistry.getAllToolNames()).not.toContain('exec'); expect(codeModeRegistry.getAllToolNames()).toContain('exec'); expect(codeModeRegistry.getAllToolNames()).toContain('tool_search'); + expect(codeModeOnlyRegistry.getAllToolNames()).toContain('exec'); }); it('keeps Direct declarations unchanged', () => { const registry = new ToolRegistry(makeFakeConfig()); - for (const name of ['read_file', 'tool_search', 'agent']) { + const tools = ['read_file', 'tool_search', 'agent'].map( + (name) => new MockTool({ name }), + ); + for (const tool of tools) registry.registerTool(tool); + + expect(registry.getFunctionDeclarations()).toEqual( + tools + .sort((left, right) => left.name.localeCompare(right.name)) + .map((tool) => tool.schema), + ); + }); + + it('keeps ordinary tools direct and adds nested declarations in CodeMode', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + for (const name of ['read_file', 'tool_search', 'agent', 'exec']) { registry.registerTool(new MockTool({ name })); } - expect(registry.getFunctionDeclarations().map((item) => item.name)).toEqual( - ['agent', 'read_file', 'tool_search'], + const declarations = registry.getFunctionDeclarations(); + expect(declarations.map((item) => item.name)).toEqual([ + 'agent', + 'exec', + 'read_file', + 'tool_search', + ]); + expect( + declarations.find((item) => item.name === 'read_file')?.description, + ).toContain('declare const tools: { read_file(args:'); + expect( + declarations.find((item) => item.name === 'agent')?.description, + ).not.toContain('declare const tools:'); + const execDescription = declarations.find( + (item) => item.name === 'exec', + )?.description; + expect(execDescription).not.toContain('tools.read_file(args:'); + expect(execDescription).toContain('"name":"read_file"'); + expect(execDescription).toContain( + 'Deferred tools remain listed in ALL_TOOLS', ); }); + it('keeps filtered CodeMode declarations and nested bindings in scope', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + for (const name of ['read_file', 'write_file', 'agent', 'exec']) { + registry.registerTool(new MockTool({ name })); + } + + const declarations = registry.getFunctionDeclarationsFiltered([ + 'read_file', + 'exec', + ]); + expect(declarations.map((item) => item.name)).toEqual([ + 'exec', + 'read_file', + ]); + expect(declarations[0]?.description).toContain('"name":"read_file"'); + expect(declarations[0]?.description).not.toContain('"name":"write_file"'); + expect(declarations[1]?.description).toContain( + 'declare const tools: { read_file(args:', + ); + }); + + it('leaves direct declarations unchanged when exec is unavailable', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + const readFile = new MockTool({ name: 'read_file' }); + registry.registerTool(readFile); + + expect(registry.getFunctionDeclarations()).toEqual([readFile.schema]); + expect(registry.getFunctionDeclarationsFiltered(['read_file'])).toEqual([ + readFile.schema, + ]); + }); + + it('preserves deferred discovery in CodeMode', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + registry.registerTool(new MockTool({ name: 'exec' })); + registry.registerTool(new MockTool({ name: 'tool_search' })); + registry.registerTool( + new MockTool({ name: 'deferred_tool', shouldDefer: true }), + ); + + const initial = registry.getFunctionDeclarations(); + expect(initial.map((item) => item.name)).toEqual(['exec', 'tool_search']); + expect(initial[0]?.description).toContain('"name":"deferred_tool"'); + expect(registry.getDeferredToolSummary().map((item) => item.name)).toEqual([ + 'deferred_tool', + ]); + + const revealed = registry.getFunctionDeclarations({ + includeDeferred: true, + }); + expect( + revealed.find((item) => item.name === 'deferred_tool')?.description, + ).toContain('declare const tools: { deferred_tool(args:'); + }); + it('exposes exec and direct controls while retaining ordinary and hidden tools', () => { - const registry = new ToolRegistry(makeFakeConfig({ codeModeOnly: true })); + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), + ); for (const name of [ 'read_file', 'tool_search', @@ -195,7 +301,9 @@ describe('CodeModeOnly exposure', () => { }); it('narrows nested tools for filtered subagent declarations', () => { - const registry = new ToolRegistry(makeFakeConfig({ codeModeOnly: true })); + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), + ); for (const name of ['read_file', 'write_file', 'agent', 'exec']) { registry.registerTool(new MockTool({ name })); } @@ -209,7 +317,9 @@ describe('CodeModeOnly exposure', () => { }); it('keeps exec structured across Gemini, OpenAI, and Anthropic tool conversion', async () => { - const registry = new ToolRegistry(makeFakeConfig({ codeModeOnly: true })); + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), + ); for (const name of ['read_file', 'agent', 'exec']) { registry.registerTool(new MockTool({ name, params: { type: 'object' } })); } diff --git a/packages/core/src/code-mode/scheduler.test.ts b/packages/core/src/code-mode/scheduler.test.ts index c54c46e1b39..3cbb16c08dc 100644 --- a/packages/core/src/code-mode/scheduler.test.ts +++ b/packages/core/src/code-mode/scheduler.test.ts @@ -71,7 +71,7 @@ describe('CodeModeOnly scheduler dispatch', () => { }, }); const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -119,7 +119,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('returns image() output to the model as inline media', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -170,7 +170,7 @@ describe('CodeModeOnly scheduler dispatch', () => { 'preserves emitted %s and text when exec fails', async (kind) => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', targetDir: '/tmp', cwd: '/tmp', }); @@ -214,7 +214,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('normalizes a nested MCP image for image(result.content[0])', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -279,7 +279,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('passes the Qwen image_gen result to generatedImage()', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', imageModel: 'openai:qwen-image-2.0', modelProvidersConfig: { openai: [ @@ -362,7 +362,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('awaits a nested tool without self-queue deadlock and reports the real name', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -428,7 +428,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('runs Promise.all reads in one scheduler batch', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -485,7 +485,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('applies nested tool permission denial before execution', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -533,7 +533,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('routes nested permission approval through the visible scheduler', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -618,7 +618,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('runs nested hooks with the real tool name', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -678,7 +678,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('validates nested arguments before execution', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -729,7 +729,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('propagates parent cancellation to a running nested tool', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -788,7 +788,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('rejects an ordinary direct call on the CodeModeOnly surface', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', @@ -830,7 +830,7 @@ describe('CodeModeOnly scheduler dispatch', () => { it('enforces a restricted agent allowlist inside exec', async () => { const config = makeFakeConfig({ - codeModeOnly: true, + toolMode: 'code_mode_only', approvalMode: ApprovalMode.DEFAULT, targetDir: '/tmp', cwd: '/tmp', diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 2ccebf77a93..4ab1b97d5cd 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -1008,8 +1008,8 @@ export interface ConfigParameters { * auto-approval and never affects registration (#10075). */ eagerTools?: string[]; - /** Replace ordinary model-facing tools with the isolated exec bridge. */ - codeModeOnly?: boolean; + /** Select how model-facing tools are exposed. */ + toolMode?: ToolModeValue; /** * Percentage of the model's context window used as the session-start * budget for preloading deferred tools. When the combined estimated @@ -3195,9 +3195,9 @@ export class Config { this.bareMode = params.bareMode ?? false; this.safeMode = params.safeMode ?? isSafeModeEnv(); this.toolMode = - params.codeModeOnly && !this.bareMode && !this.safeMode - ? ToolMode.CodeModeOnly - : ToolMode.Direct; + this.bareMode || this.safeMode + ? ToolMode.Direct + : (params.toolMode ?? ToolMode.Direct); if (this.safeMode) { this.debugLogger.info( 'Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled', @@ -10396,7 +10396,7 @@ export class Config { }; const registerExecIfEnabled = async (): Promise => { - if (this.getToolMode() !== ToolMode.CodeModeOnly) return; + if (this.getToolMode() === ToolMode.Direct) return; await registerLazy(ToolNames.EXEC, async () => { const { ExecTool } = await import('../tools/exec.js'); return new ExecTool(this); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index f9ca42dd045..639665cad26 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -778,6 +778,7 @@ export { } from './code-mode/tool-call-runtime.js'; export { getToolExposure, + isCodeModeEnabled, isCodeModeToolCallAllowed, ToolMode, type ToolExposure, diff --git a/packages/core/src/tools/code-mode.ts b/packages/core/src/tools/code-mode.ts index 95c2a18214d..4e6f790fe41 100644 --- a/packages/core/src/tools/code-mode.ts +++ b/packages/core/src/tools/code-mode.ts @@ -20,11 +20,16 @@ export type ToolExposure = export const ToolMode = { Direct: 'direct', + CodeMode: 'code_mode', CodeModeOnly: 'code_mode_only', } as const; export type ToolMode = (typeof ToolMode)[keyof typeof ToolMode]; +export function isCodeModeEnabled(mode: ToolMode | undefined): boolean { + return mode === ToolMode.CodeMode || mode === ToolMode.CodeModeOnly; +} + const HIDDEN_TOOLS = new Set([ToolNames.TOOL_SEARCH, 'tool_call']); const DIRECT_ONLY_TOOLS = new Set([ @@ -201,7 +206,26 @@ function describeBinding(binding: CodeModeToolBinding): string { return `tools.${binding.jsName}(args: ${params}): Promise;`; } -export function buildExecDescription(plan: CodeModeBindingPlan): string { +export function augmentDeclarationForCodeMode( + declaration: FunctionDeclaration, + binding: CodeModeToolBinding, +): FunctionDeclaration { + const params = schemaToType(binding.parametersJsonSchema); + return { + ...declaration, + description: `${declaration.description ?? ''} + +exec tool declaration: +\`\`\`ts +declare const tools: { ${binding.jsName}(args: ${params}): Promise; }; +\`\`\``, + }; +} + +export function buildExecDescription( + plan: CodeModeBindingPlan, + codeModeOnly = true, +): string { const allTools = plan.bindings.map( ({ name, jsName, description, deferred }) => ({ name, @@ -216,7 +240,12 @@ export function buildExecDescription(plan: CodeModeBindingPlan): string { `- ${omitted} is omitted because it collides with ${kept} as tools.${jsName}.`, ) .join('\n'); - const declarations = plan.bindings.map(describeBinding).join('\n'); + const declarations = codeModeOnly + ? plan.bindings.map(describeBinding).join('\n') + : 'Nested tool declarations are included in their top-level tool descriptions. Deferred tools remain listed in ALL_TOOLS and receive a declaration when their top-level declaration is revealed.'; + const toolsDescription = codeModeOnly + ? 'the code-mode-callable tool functions declared below.' + : 'the code-mode-callable tool functions declared in their top-level tool descriptions.'; return `Execute JavaScript in a fresh isolated runtime and wait for it to finish. @@ -225,7 +254,7 @@ Use async/await and call registered tools through tools.(args). Calls use Results from skill, update_goal, and capture_screen_context are automatically retained in the exec response; text() is not required to preserve their context. Read loaded skill instructions before taking dependent actions in a later exec call. A terminal update_goal result ends the script and prevents further tool calls. Available globals: -- tools: the code-mode-callable tool functions declared below. +- tools: ${toolsDescription} - ALL_TOOLS: frozen metadata for every function in tools. - text(value): append bounded text output. Non-string values are JSON-stringified when possible. - image(imageUrlOrItem: string | ImageContent): append an image from a base64 data URL or Qwen MCP ImageContent. To return a nested MCP image, pass an item such as image(result.content[0]). @@ -250,9 +279,10 @@ ${collisionText ? `\nName collisions:\n${collisionText}` : ''}`; export function buildExecDeclaration( execTool: AnyDeclarativeTool, plan: CodeModeBindingPlan, + codeModeOnly = true, ): FunctionDeclaration { return { ...execTool.schema, - description: buildExecDescription(plan), + description: buildExecDescription(plan, codeModeOnly), }; } diff --git a/packages/core/src/tools/exec-context-budget.test.ts b/packages/core/src/tools/exec-context-budget.test.ts index 81447443cfc..75f3ad911d1 100644 --- a/packages/core/src/tools/exec-context-budget.test.ts +++ b/packages/core/src/tools/exec-context-budget.test.ts @@ -27,7 +27,7 @@ describe('exec context output budget', () => { userMemory: '', memoryFileCount: 0, approvalMode: ApprovalMode.YOLO, - codeModeOnly: true, + toolMode: 'code_mode_only', disableAllHooks: true, truncateToolOutputThreshold: 200_000, toolOutputBatchBudget: 200_000, diff --git a/packages/core/src/tools/exec-context-tools.test.ts b/packages/core/src/tools/exec-context-tools.test.ts index f4234fa5f5b..20bfc45d99e 100644 --- a/packages/core/src/tools/exec-context-tools.test.ts +++ b/packages/core/src/tools/exec-context-tools.test.ts @@ -34,7 +34,7 @@ function setup( userMemory: '', memoryFileCount: 0, approvalMode: ApprovalMode.DEFAULT, - codeModeOnly: true, + toolMode: 'code_mode_only', }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); diff --git a/packages/core/src/tools/tool-registry.test.ts b/packages/core/src/tools/tool-registry.test.ts index 0d64376118a..7e3b086e033 100644 --- a/packages/core/src/tools/tool-registry.test.ts +++ b/packages/core/src/tools/tool-registry.test.ts @@ -189,7 +189,7 @@ describe('ToolRegistry', () => { const baseUrl = 'https://images.example/v1'; const config = new Config({ ...baseConfigParams, - codeModeOnly: true, + toolMode: 'code_mode_only', experimentalZedIntegration: true, modelProvidersConfig: { openai: [ @@ -875,7 +875,7 @@ describe('ToolRegistry', () => { // is the one the previous test proves IS reported in Direct mode. const codeModeConfig = new Config({ ...baseConfigParams, - codeModeOnly: true, + toolMode: 'code_mode_only', }); const registry = new ToolRegistry(codeModeConfig); registry.registerTool( diff --git a/packages/core/src/tools/tool-registry.ts b/packages/core/src/tools/tool-registry.ts index ce87978cd9b..789c00896f5 100644 --- a/packages/core/src/tools/tool-registry.ts +++ b/packages/core/src/tools/tool-registry.ts @@ -31,6 +31,7 @@ import type { ReadResourceResult } from '@modelcontextprotocol/sdk/types.js'; import { normalizeMcpToolName } from '../utils/tool-name-utils.js'; import { CHARS_PER_TOKEN } from '../services/tokenEstimation.js'; import { + augmentDeclarationForCodeMode, buildExecDeclaration, getToolExposure, planCodeModeBindings, @@ -849,11 +850,12 @@ export class ToolRegistry { getFunctionDeclarations(options?: { includeDeferred?: boolean; }): FunctionDeclaration[] { - if (this.config.getToolMode?.() === ToolMode.CodeModeOnly) { + const toolMode = this.config.getToolMode?.(); + if (toolMode === ToolMode.CodeModeOnly) { return this.getCodeModeFunctionDeclarations(); } const includeDeferred = options?.includeDeferred === true; - return Array.from(this.tools.values()) + const declarations = Array.from(this.tools.values()) .filter((tool) => this.isToolAvailable(tool.name)) .filter((tool) => this.isToolDeclared(tool.name)) .filter( @@ -863,8 +865,33 @@ export class ToolRegistry { tool.alwaysLoad || !this.isDeferredAndHidden(tool.name), ) - .sort(ToolRegistry.compareToolsByDeclarationName) - .map((tool) => tool.schema); + .sort(ToolRegistry.compareToolsByDeclarationName); + if (toolMode !== ToolMode.CodeMode) { + return declarations.map((tool) => tool.schema); + } + return this.decorateCodeModeDeclarations(declarations); + } + + private decorateCodeModeDeclarations( + tools: AnyDeclarativeTool[], + allowedNames?: ReadonlySet, + ): FunctionDeclaration[] { + if (!tools.some((tool) => tool.name === ToolNames.EXEC)) { + return tools.map((tool) => tool.schema); + } + const plan = this.getCodeModeBindingPlan(allowedNames); + const bindings = new Map( + plan.bindings.map((binding) => [binding.name, binding]), + ); + return tools.map((tool) => { + if (tool.name === ToolNames.EXEC) { + return buildExecDeclaration(tool, plan, false); + } + const binding = bindings.get(tool.name); + return binding + ? augmentDeclarationForCodeMode(tool.schema, binding) + : tool.schema; + }); } private getCodeModeFunctionDeclarations( @@ -1098,21 +1125,42 @@ export class ToolRegistry { /** * Retrieves a filtered list of tool schemas based on a list of tool names. * @param toolNames - An array of tool names to include. + * @param codeModeAllowedNames - Optional nested binding allowlist when the + * direct and exec surfaces differ. * @returns An array of FunctionDeclarations for the specified tools. * @remarks Requires all tool factories to be resolved first. Call * {@link warmAll} before invoking this method, otherwise factory-registered * tools that have not yet been loaded will be silently omitted. */ - getFunctionDeclarationsFiltered(toolNames: string[]): FunctionDeclaration[] { + getFunctionDeclarationsFiltered( + toolNames: string[], + codeModeAllowedNames?: ReadonlySet, + ): FunctionDeclaration[] { if (this.factories.size > 0) { debugLogger.warn( `getFunctionDeclarationsFiltered() called with ${this.factories.size} unloaded ` + `tool factories. Call warmAll() first to avoid incomplete results.`, ); } - if (this.config.getToolMode?.() === ToolMode.CodeModeOnly) { + const toolMode = this.config.getToolMode?.(); + if (toolMode === ToolMode.CodeModeOnly) { return this.getCodeModeFunctionDeclarations(new Set(toolNames)); } + if (toolMode === ToolMode.CodeMode) { + const allowedNames = new Set(toolNames); + const tools = Array.from(this.tools.values()) + .filter( + (tool) => + allowedNames.has(tool.name) && + this.isToolAvailable(tool.name) && + this.isToolDeclared(tool.name), + ) + .sort(ToolRegistry.compareCodeModeTools); + return this.decorateCodeModeDeclarations( + tools, + codeModeAllowedNames ?? allowedNames, + ); + } const declarations: FunctionDeclaration[] = []; for (const name of toolNames) { const tool = this.getTool(name); diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index dc151095503..9955415163f 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1276,10 +1276,14 @@ "description": "Settings for built-in and custom tools.", "type": "object", "properties": { - "codeModeOnly": { - "description": "Expose ordinary tools to the model only through the isolated exec JavaScript tool. Direct control tools remain available. Ignored in safe and bare modes.", - "type": "boolean", - "default": false + "mode": { + "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Options: direct, code_mode, code_mode_only", + "enum": [ + "direct", + "code_mode", + "code_mode_only" + ], + "default": "direct" }, "sandbox": { "anyOf": [ From fda09c05dd5adde6e75fd5d26d4e9443431ac827 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Tue, 15 Sep 2026 23:21:38 +0800 Subject: [PATCH 02/49] fix(core): address hybrid code mode review feedback --- docs/design/code-mode-only.md | 29 +++--- docs/design/code-mode-only.zh-CN.md | 24 +++-- docs/design/code-mode.md | 6 +- docs/design/code-mode.zh-CN.md | 5 +- docs/users/configuration/settings.md | 58 ++++++------ .../acp-integration/session/Session.test.ts | 19 ++++ packages/cli/src/config/config.test.ts | 32 +++++++ packages/cli/src/config/config.ts | 46 ++++++++-- packages/cli/src/config/settingsSchema.ts | 4 +- packages/cli/src/i18n/locales/en.js | 5 +- packages/cli/src/i18n/locales/zh-TW.js | 5 +- packages/cli/src/i18n/locales/zh.js | 5 +- .../cli/src/i18n/mustTranslateKeys.test.ts | 18 ++++ .../runtime/agent-core.skill-gate.test.ts | 70 ++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 19 ++-- packages/core/src/code-mode/code-mode.test.ts | 91 +++++++++++++++++-- packages/core/src/code-mode/scheduler.test.ts | 41 +++++++++ packages/core/src/config/config.ts | 8 +- packages/core/src/core/client.test.ts | 23 +++++ packages/core/src/core/client.ts | 13 ++- packages/core/src/tools/code-mode.ts | 50 +++++++--- packages/core/src/tools/tool-registry.test.ts | 36 ++++++++ packages/core/src/tools/tool-registry.ts | 39 +++++++- .../schemas/settings.schema.json | 2 +- 24 files changed, 545 insertions(+), 103 deletions(-) diff --git a/docs/design/code-mode-only.md b/docs/design/code-mode-only.md index 254c2da5fd8..686c1d562d5 100644 --- a/docs/design/code-mode-only.md +++ b/docs/design/code-mode-only.md @@ -22,7 +22,7 @@ unchanged. ## Non-goals -- Hybrid direct/code exposure. +- Defining hybrid direct/code exposure; see [Code Mode](code-mode.md). - Persistent cells, globals, or values between `exec` calls. - Background jobs, `wait`, `yield`, `store`, or `load`. - Raw/freeform provider calls. @@ -49,12 +49,12 @@ and registry listings. The registry remains the source of truth. Exposure is a view over registered tools, never a second registry. -| Category | Model top level | `tools.*` inside `exec` | -| ------------------------------------------ | ----------------- | ----------------------- | -| `exec` | CodeModeOnly only | No | -| Direct control | Yes | No | -| Ordinary registered tool | No | Yes | -| Hidden bridge (`tool_search`, `tool_call`) | No | No | +| Category | Model top level | `tools.*` inside `exec` | +| ------------------------------------------ | ------------------------------------- | ----------------------- | +| `exec` | CodeMode and CodeModeOnly | No | +| Direct control | Yes | No | +| Ordinary registered tool | CodeMode only | Yes | +| Hidden bridge (`tool_search`, `tool_call`) | Existing behavior outside strict mode | No | The direct-control allowlist is centralized and deliberately small. It covers user interaction (`ask_user_question`), delegation (`agent`), terminal output @@ -157,14 +157,13 @@ OpenAI-compatible, and Anthropic adapters all receive the structured `exec` declaration without provider-specific prompting. Filtered subagent declarations apply the same policy. For a read-only teammate -or a fork with an execution allowlist, `exec` is the audited gateway while the -exact allowed nested names are carried in its invocation context. The same set -generates the description and is checked again before Core dispatch, so an -explicit allowlist can narrow code-mode-callable nested tools without becoming -prompt-only policy, exposing a hidden bridge, or making `exec` recursive. -For cache-compatible forks, an inherited `exec` declaration represents its -ordinary bindings: an omitted `fork_tools` inherits them, while an explicit -list replaces them with the requested subset. +or a fork with an execution allowlist, `exec` is the audited gateway and the +nested names carried in its invocation context are checked again before Core +dispatch. Explicit ordinary-tool entries narrow that nested set. An inherited +or explicitly allowed `exec` instead represents all surviving ordinary +code-mode-callable bindings, while the agent's own `tools` list still narrows +its direct surface. Hidden bridges remain unavailable and `exec` cannot call +itself. ## Failure and rollback diff --git a/docs/design/code-mode-only.zh-CN.md b/docs/design/code-mode-only.zh-CN.md index 49de95596b6..09a4a90ec2a 100644 --- a/docs/design/code-mode-only.zh-CN.md +++ b/docs/design/code-mode-only.zh-CN.md @@ -19,7 +19,7 @@ provider 请求和执行均保持不变。 ## 非目标 -- 混合暴露直接调用和代码调用。 +- 定义混合的直接调用和代码调用;详见 [Code Mode](code-mode.zh-CN.md)。 - 在多次 `exec` 调用间持久化 cell、全局变量或值。 - 后台任务、`wait`、`yield`、`store` 或 `load`。 - 原始/freeform provider 调用。 @@ -44,12 +44,12 @@ provider 请求和执行均保持不变。 registry 仍是事实来源。暴露只是注册工具之上的视图,而不是第二套 registry。 -| 类别 | 模型顶层调用 | `exec` 内的 `tools.*` | -| ----------------------------------------- | --------------- | --------------------- | -| `exec` | 仅 CodeModeOnly | 否 | -| 直接控制工具 | 是 | 否 | -| 已注册的普通工具 | 否 | 是 | -| 隐藏 bridge(`tool_search`、`tool_call`) | 否 | 否 | +| 类别 | 模型顶层调用 | `exec` 内的 `tools.*` | +| ----------------------------------------- | ------------------------ | --------------------- | +| `exec` | CodeMode 和 CodeModeOnly | 否 | +| 直接控制工具 | 是 | 否 | +| 已注册的普通工具 | 仅 CodeMode | 是 | +| 隐藏 bridge(`tool_search`、`tool_call`) | 严格模式之外沿用既有行为 | 否 | 直接控制 allowlist 集中维护且刻意保持精简。它覆盖用户交互 (`ask_user_question`)、委派(`agent`)、终止输出约定、 @@ -135,12 +135,10 @@ ACP 会串行执行普通嵌套调用,与现有直接工具顺序一致;Core `exec` declaration,不需要 provider 专用 prompt。 经过过滤的子智能体 declaration 使用相同策略。对于只读 teammate 或带执行 -allowlist 的 fork,`exec` 是经过审计的 gateway,而允许的确切嵌套名称会随 invocation -context 传递。同一集合既用于生成描述,也会在 Core 分派前再次校验,因此显式 -allowlist 可以收窄 code-mode-callable 嵌套工具,而不会变成仅 prompt 策略、暴露 -隐藏 bridge 或使 `exec` 能够递归。对于 cache-compatible fork,继承的 `exec` -declaration 代表其普通 binding:省略 `fork_tools` 时继承这些 binding,显式列表则 -用请求的子集替换它们。 +allowlist 的 fork,`exec` 是经过审计的 gateway,其 invocation context 中携带的嵌套 +名称会在 Core 分派前再次校验。显式列出的普通工具会收窄该嵌套集合;继承或显式允许 +的 `exec` 则代表所有仍可用的普通 code-mode-callable binding,而智能体自身的 +`tools` 列表仍会收窄直接调用面。隐藏 bridge 始终不可用,`exec` 也不能调用自身。 ## 失败与回滚 diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index 3df7d63bab4..ab1e66da88f 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -57,8 +57,10 @@ their normal top-level declaration is revealed. In `code_mode_only`, the existing behavior remains: all nested declarations live in the `exec` description because no later top-level reveal is possible. -Filtered subagent declarations preserve the same mode and narrow both direct -and nested calls to the subagent's allowed tool set. +Filtered subagent declarations preserve the same mode. The agent's `tools` +list narrows its direct surface. Explicit ordinary-tool execution entries +narrow the nested set, while an inherited or explicitly allowed `exec` carries +all surviving code-mode-callable bindings. ## Constraints and risks diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 327054016d6..2c238a8e436 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -53,8 +53,9 @@ CodeModeOnly。 按正常流程暴露顶层声明时获得对应声明。在 `code_mode_only` 中保持现有行为: 由于后续无法暴露顶层声明,所有嵌套声明都集中在 `exec` 描述中。 -经过过滤的子智能体声明沿用相同模式,并将直接调用和嵌套调用都限制在该子智能体 -允许的工具集合内。 +经过过滤的子智能体声明沿用相同模式。智能体的 `tools` 列表会收窄直接调用面。 +显式列出的普通工具会收窄嵌套集合;继承或显式允许的 `exec` 则携带所有仍可用的 +code-mode-callable binding。 ## 约束与风险 diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 050300695ed..76531c56629 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -370,37 +370,41 @@ If you are experiencing performance issues with file searching (e.g., with `@` c #### tools -| Setting | Type | Description | Default | Notes | -| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | -| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | -| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `true` | | -| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | -| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | -| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message` and `tool_search` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay loadable via `tool_search`), and `permissions.deny` to block tools outright. | `undefined` | | -| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | -| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring `tool_search`. Listed tools appear alongside core tools in the initial session. Merged as a union across scopes. | `undefined` | | -| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, callable, and discoverable via `tool_search`. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with `tool_search`: when ToolSearch is not registered — `tools.toolSearch.enabled: false`, a `tool_search` deny rule, or the automatic opt-out for DeepSeek models — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools are out of reach for that session (they stay in `/tools`, and a warning is logged). Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in `tools.visible` are declared up front. Use `permissions.deny` if you meant to remove them, or leave ToolSearch on. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. | `undefined` | | -| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | -| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. | `direct` | Experimental. Requires restart. | -| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is loadable via `tool_search`, but its schema is not sent in the initial model request. | `undefined` | | -| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | -| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | -| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | -| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | -| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | -| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | -| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | -| `tools.toolSearch.enabled` | boolean | Load MCP tools on demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates. | `true` | Requires restart: Yes | -| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). When their combined schemas fit within this budget, they are declared upfront instead of loaded on demand via ToolSearch. Tools demoted by `tools.eager` are excluded from this preload and stay on demand. Set `0` to always load deferred tools on demand. | `10` | Requires restart: Yes | -| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | -| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | +| Setting | Type | Description | Default | Notes | +| ------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | +| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | +| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `true` | | +| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | +| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | +| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message` and `tool_search` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay loadable via `tool_search`), and `permissions.deny` to block tools outright. | `undefined` | | +| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | +| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring `tool_search`. Listed tools appear alongside core tools in the initial session. Merged as a union across scopes. | `undefined` | | +| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, callable, and discoverable via `tool_search`. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with `tool_search`: when ToolSearch is not registered — `tools.toolSearch.enabled: false`, a `tool_search` deny rule, or the automatic opt-out for DeepSeek models — the allowlist still withholds the schemas, which cannot be revealed for direct use. In Code Mode the demoted tools remain callable through `exec`; in Direct mode they are out of reach for that session. A warning explains the active behavior. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in `tools.visible` are declared up front. Use `permissions.deny` if you meant to remove them, or leave ToolSearch on. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. | `undefined` | | +| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | +| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. | `direct` | Experimental. Requires restart. | +| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is loadable via `tool_search`, but its schema is not sent in the initial model request. | `undefined` | | +| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | +| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | +| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | +| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | +| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | +| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | +| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | +| `tools.toolSearch.enabled` | boolean | Load MCP tools on demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates. | `true` | Requires restart: Yes | +| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). When their combined schemas fit within this budget, they are declared upfront instead of loaded on demand via ToolSearch. Tools demoted by `tools.eager` are excluded from this preload and stay on demand. Set `0` to always load deferred tools on demand. | `10` | Requires restart: Yes | +| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | +| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | > [!note] > > **Migrating from `tools.core` / `tools.exclude` / `tools.allowed`:** These legacy settings are **deprecated** but are not automatically migrated; they continue to work at startup. Migrate `tools.allowed` and `tools.exclude` manually to `permissions.allow` and `permissions.deny`. `tools.core` has no exact replacement; see the table below. +> +> The nightly-only legacy setting `tools.codeModeOnly: true` is still honored +> as `tools.mode: "code_mode_only"` and emits a deprecation warning. Migrate it +> to `tools.mode` before that compatibility path is removed. #### memory diff --git a/packages/cli/src/acp-integration/session/Session.test.ts b/packages/cli/src/acp-integration/session/Session.test.ts index d93ae2c5f78..0e95078cb6c 100644 --- a/packages/cli/src/acp-integration/session/Session.test.ts +++ b/packages/cli/src/acp-integration/session/Session.test.ts @@ -35247,6 +35247,25 @@ describe('Session', () => { expect(direct.parts[0].functionResponse?.response?.['error']).toContain( 'unavailable on this CodeModeOnly call surface', ); + + vi.mocked(mockConfig.getToolMode).mockReturnValue(core.ToolMode.CodeMode); + const hybridDirect = await ( + session as unknown as ToolCallInternals + ).runToolCalls( + new AbortController().signal, + 'prompt-hybrid-code-mode-direct', + [ + { + id: 'read-acp-hybrid-direct', + name: 'read_file', + args: { path: '/tmp/example.txt' }, + }, + ], + ); + expect(nestedExecute).toHaveBeenCalledTimes(2); + expect(hybridDirect.parts[0].functionResponse?.response?.['output']).toBe( + 'nested ACP output', + ); }); function emitNestedAskUserQuestion( diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 2a994293837..8e02e4384f3 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -3594,6 +3594,38 @@ describe('mergeExcludeTools', () => { expect(codeModeOnly.getToolMode()).toBe('code_mode_only'); }); + it('should fail closed for an invalid tool mode', async () => { + process.argv = ['node', 'script.js']; + const argv = await parseArguments(); + const config = await loadCliConfig( + { tools: { mode: 'code-mode' } } as unknown as Settings, + argv, + undefined, + [], + ); + + expect(config.getToolMode()).toBe(ToolMode.Direct); + expect(config.getWarnings()).toContain( + 'Unrecognized tools.mode "code-mode"; falling back to direct.', + ); + }); + + it('should honor the legacy tools.codeModeOnly setting', async () => { + process.argv = ['node', 'script.js']; + const argv = await parseArguments(); + const config = await loadCliConfig( + { tools: { codeModeOnly: true } } as unknown as Settings, + argv, + undefined, + [], + ); + + expect(config.getToolMode()).toBe(ToolMode.CodeModeOnly); + expect(config.getWarnings()).toContain( + 'tools.codeModeOnly is deprecated; use tools.mode = "code_mode_only".', + ); + }); + it.each([ ['--safe-mode', ToolMode.CodeMode], ['--safe-mode', ToolMode.CodeModeOnly], diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 91851eabcfb..5a1fe180d91 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -30,7 +30,6 @@ import { type ToolName, type ToolInvocationGuard, ToolNames, - ToolMode, NativeLspClient, createDebugLogger, NativeLspService, @@ -54,6 +53,11 @@ import { stripAnsiAndControl, type OutputStyleDefinition, } from '@qwen-code/qwen-code-core'; +import { + isToolMode, + ToolMode, + type ToolMode as ToolModeValue, +} from '@qwen-code/qwen-code-core/tools/code-mode.js'; import { extensionsCommand } from '../commands/extensions.js'; import { hooksCommand } from '../commands/hooks.js'; import { resolveAcpChannelFallback } from './acp-channel-fallback.js'; @@ -134,6 +138,32 @@ function isSkillLevel(value: unknown): value is SkillLevel { return SKILL_LEVELS.includes(value as SkillLevel); } +function resolveToolModeSetting(tools: Settings['tools']): { + mode: ToolModeValue; + warning?: string; +} { + const mode: unknown = tools?.mode; + if (mode !== undefined) { + return isToolMode(mode) + ? { mode } + : { + mode: ToolMode.Direct, + warning: `Unrecognized tools.mode ${JSON.stringify(mode)}; falling back to direct.`, + }; + } + + const legacyCodeModeOnly = (tools as { codeModeOnly?: unknown } | undefined) + ?.codeModeOnly; + if (legacyCodeModeOnly === true) { + return { + mode: ToolMode.CodeModeOnly, + warning: + 'tools.codeModeOnly is deprecated; use tools.mode = "code_mode_only".', + }; + } + return { mode: ToolMode.Direct }; +} + function formatApprovalModeError(value: string): Error { return new Error( `Invalid approval mode: ${value}. Valid values are: ${APPROVAL_MODES.join( @@ -1988,6 +2018,10 @@ export async function loadCliConfig( selectedAuthType, env: process.env as Record, }); + const resolvedToolMode = + bareMode || safeMode + ? { mode: ToolMode.Direct } + : resolveToolModeSetting(settings.tools); const { model: resolvedModel } = resolvedCliConfig; @@ -2258,10 +2292,7 @@ export async function loadCliConfig( disabledTools: disabledTools.length > 0 ? disabledTools : undefined, visibleTools: visibleTools.length > 0 ? visibleTools : undefined, eagerTools, - toolMode: - !bareMode && !safeMode - ? (settings.tools?.mode ?? ToolMode.Direct) - : ToolMode.Direct, + toolMode: resolvedToolMode.mode, toolSearchThreshold: bareMode || safeMode ? 0 : settings.tools?.toolSearch?.threshold, // New unified permissions (PermissionManager source of truth). @@ -2401,7 +2432,10 @@ export async function loadCliConfig( generationConfigSources: resolvedCliConfig.sources, generationConfig: resolvedCliConfig.generationConfig, initialModelRegistryBaseUrl: resolvedCliConfig.registryBaseUrl, - warnings: resolvedCliConfig.warnings, + warnings: [ + ...resolvedCliConfig.warnings, + ...(resolvedToolMode.warning ? [resolvedToolMode.warning] : []), + ], bareMode, safeMode, allowedHttpHookUrls: diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index f338123af45..593dfcd10d6 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -33,8 +33,8 @@ import { OutputFormat, REASONING_EFFORT_TIERS, SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT, - ToolMode, } from '@qwen-code/qwen-code-core'; +import { ToolMode } from '@qwen-code/qwen-code-core/tools/code-mode.js'; import type { CustomTheme } from '../ui/themes/theme.js'; import { getLanguageSettingsOptions } from '../i18n/languages.js'; import { MergeStrategy } from '../utils/deepMerge.js'; @@ -3014,7 +3014,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string[] | undefined, description: - 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas are still withheld but nothing can load them back, so the demoted tools are out of reach for that session and a warning is logged. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', + 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas are still withheld and cannot be revealed for direct use; in Code Mode the demoted tools remain callable through exec, while in Direct mode they are out of reach for that session. A warning explains the active behavior. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', showInDialog: false, }, approvalMode: { diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index cd6ee4e6dad..5eb2ff9c783 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -721,7 +721,10 @@ export default { // ============================================================================ // Settings Labels // ============================================================================ - 'Code Mode Only (Experimental)': 'Code Mode Only (Experimental)', + 'Tool Mode (Experimental)': 'Tool Mode (Experimental)', + Default: 'Default', + 'Code Mode': 'Code Mode', + 'Code Mode Only': 'Code Mode Only', 'Vim Mode': 'Vim Mode', 'Attribution: commit': 'Attribution: commit', 'Terminal Bell Notification': 'Terminal Bell Notification', diff --git a/packages/cli/src/i18n/locales/zh-TW.js b/packages/cli/src/i18n/locales/zh-TW.js index ae0fba1d9a5..d20b060bb41 100644 --- a/packages/cli/src/i18n/locales/zh-TW.js +++ b/packages/cli/src/i18n/locales/zh-TW.js @@ -682,7 +682,10 @@ export default { Settings: '設置', 'To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.': '要查看更改,必須重啟 Qwen Code。按 r 退出並立即應用更改。', - 'Code Mode Only (Experimental)': '僅程式碼模式(實驗性)', + 'Tool Mode (Experimental)': '工具模式(實驗性)', + Default: '預設', + 'Code Mode': '程式碼模式', + 'Code Mode Only': '僅程式碼模式', 'Vim Mode': 'Vim 模式', 'Attribution: commit': '署名:提交', 'Terminal Bell Notification': '終端響鈴通知', diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index 3c1ca43e26a..1d55446b440 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -724,7 +724,10 @@ export default { // ============================================================================ // Settings Labels // ============================================================================ - 'Code Mode Only (Experimental)': '仅代码模式(实验性)', + 'Tool Mode (Experimental)': '工具模式(实验性)', + Default: '默认', + 'Code Mode': '代码模式', + 'Code Mode Only': '仅代码模式', 'Vim Mode': 'Vim 模式', 'Attribution: commit': '署名:提交', 'Terminal Bell Notification': '终端响铃通知', diff --git a/packages/cli/src/i18n/mustTranslateKeys.test.ts b/packages/cli/src/i18n/mustTranslateKeys.test.ts index ed10e8b3eb2..8f2a2bedba4 100644 --- a/packages/cli/src/i18n/mustTranslateKeys.test.ts +++ b/packages/cli/src/i18n/mustTranslateKeys.test.ts @@ -35,6 +35,13 @@ const FORK_COMMAND_REQUIRED_KEYS = [ 'Forked into a background agent. It inherits this conversation and runs without blocking — track it in the background tasks panel; it reports back when done.', ] as const; +const TOOL_MODE_TRANSLATION_KEYS = [ + 'Tool Mode (Experimental)', + 'Default', + 'Code Mode', + 'Code Mode Only', +] as const; + const NON_ENGLISH_LANGUAGES = SUPPORTED_LANGUAGES.filter( (language) => language.code !== 'en', ); @@ -119,6 +126,17 @@ describe('must-translate locale coverage', () => { SLOW_LOCALE_TEST_TIMEOUT_MS, ); + it.each(['zh', 'zh-TW'] as const)( + 'translates tool mode settings in %s', + async (language) => { + await setLanguageAsync(language); + + expect( + TOOL_MODE_TRANSLATION_KEYS.filter((key) => t(key) === key), + ).toEqual([]); + }, + ); + it.each(NON_ENGLISH_LANGUAGES)( 'translates built-in command descriptions in %s', async (language) => { diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index dae34d74800..ea2aeddb4aa 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -404,6 +404,76 @@ describe('AgentCore skill-gate inputs', () => { ]); expect(declarations[0]?.description).toContain('"name":"read_file"'); expect(declarations[0]?.description).toContain('"name":"write_file"'); + expect(declarations[0]?.description).toContain('tools.read_file(args:'); + expect(declarations[0]?.description).toContain('tools.write_file(args:'); + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual([ToolNames.READ_FILE, ToolNames.WRITE_FILE]); + }); + + it('keeps inherited CodeMode declarations executable only when directly allowed', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'allowlisted-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: ['*'], + executionAllowedTools: [ToolNames.EXEC, ToolNames.READ_FILE], + }, + ); + + const declarations = await core.prepareTools(); + + expect(declarations.map((declaration) => declaration.name)).toEqual([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ]); + expect(executable(core, ToolNames.READ_FILE)).toBe(true); + expect(executable(core, ToolNames.WRITE_FILE)).toBe(false); + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual([ToolNames.READ_FILE, ToolNames.WRITE_FILE]); + }); + + it('inherits the complete registry in CodeMode', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'inherited-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { tools: ['*'] }, + ); + + const declarations = await core.prepareTools(); + + expect(declarations.map((declaration) => declaration.name)).toEqual([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ToolNames.WRITE_FILE, + ]); expect( ( core as unknown as { diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index ff24e2d367d..e486916037f 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -757,7 +757,7 @@ export class AgentCore { !isExcluded(name) && !isHiddenByEagerAllowList(name) && !isDisallowed(name) && - this.isToolExecutionAllowed(name), + this.isToolExecutionAllowed(name, true), ); this.codeModeAllowedToolNames = Object.freeze( allowedNames.filter( @@ -765,10 +765,13 @@ export class AgentCore { ), ); const declarationNames = - this.runtimeContext.getToolMode?.() === ToolMode.CodeMode && - configuredNames + this.runtimeContext.getToolMode?.() === ToolMode.CodeMode ? allowedNames.filter( - (name) => name === ToolNames.EXEC || configuredNames.has(name), + (name) => + (!configuredNames || + name === ToolNames.EXEC || + configuredNames.has(name)) && + this.isToolExecutionAllowed(name), ) : allowedNames; const declarations = toolRegistry.getFunctionDeclarationsFiltered( @@ -1704,11 +1707,14 @@ export class AgentCore { declaredToolNames.has(ToolNames.EXEC) && !!this.runtimeContext.getToolRegistry().getTool(ToolNames.SKILL) && this.codeModeAllowedToolNames?.includes(ToolNames.SKILL) === true)) && - this.isToolExecutionAllowed(ToolNames.SKILL) + this.isToolExecutionAllowed(ToolNames.SKILL, true) ); } - private isToolExecutionAllowed(toolName: string): boolean { + private isToolExecutionAllowed( + toolName: string, + forNestedBinding = false, + ): boolean { if (this.executionAllowedTools === undefined) { return true; } @@ -1719,6 +1725,7 @@ export class AgentCore { return true; } if ( + forNestedBinding && isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && this.executionAllowedExactTools?.has(ToolNames.EXEC) && getToolExposure(toolName) === 'code-mode-callable' diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index 60ef610b5fa..460dc47887a 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -156,11 +156,19 @@ describe('code mode exposure', () => { undefined, { skipDiscovery: true }, ); + const invalid = makeFakeConfig(); + vi.spyOn(invalid, 'getToolMode').mockReturnValue( + 'code-mode' as ReturnType, + ); + const invalidRegistry = await invalid.createToolRegistry(undefined, { + skipDiscovery: true, + }); expect(directRegistry.getAllToolNames()).not.toContain('exec'); expect(codeModeRegistry.getAllToolNames()).toContain('exec'); expect(codeModeRegistry.getAllToolNames()).toContain('tool_search'); expect(codeModeOnlyRegistry.getAllToolNames()).toContain('exec'); + expect(invalidRegistry.getAllToolNames()).not.toContain('exec'); }); it('keeps Direct declarations unchanged', () => { @@ -181,9 +189,19 @@ describe('code mode exposure', () => { const registry = new ToolRegistry( makeFakeConfig({ toolMode: ToolMode.CodeMode }), ); - for (const name of ['read_file', 'tool_search', 'agent', 'exec']) { + registry.registerTool( + new MockTool({ + name: 'read_file', + description: 'Reads a file from the filesystem.', + params: { + type: 'object', + properties: { path: { type: 'string' } }, + required: ['path'], + }, + }), + ); + for (const name of ['tool_search', 'agent', 'exec']) registry.registerTool(new MockTool({ name })); - } const declarations = registry.getFunctionDeclarations(); expect(declarations.map((item) => item.name)).toEqual([ @@ -192,9 +210,13 @@ describe('code mode exposure', () => { 'read_file', 'tool_search', ]); - expect( - declarations.find((item) => item.name === 'read_file')?.description, - ).toContain('declare const tools: { read_file(args:'); + const readFileDescription = declarations.find( + (item) => item.name === 'read_file', + )?.description; + expect(readFileDescription).toContain('Reads a file from the filesystem.'); + expect(readFileDescription).toContain( + 'read_file(args: { "path": string })', + ); expect( declarations.find((item) => item.name === 'agent')?.description, ).not.toContain('declare const tools:'); @@ -204,7 +226,7 @@ describe('code mode exposure', () => { expect(execDescription).not.toContain('tools.read_file(args:'); expect(execDescription).toContain('"name":"read_file"'); expect(execDescription).toContain( - 'Deferred tools remain listed in ALL_TOOLS', + 'Deferred tools with a reveal path receive a declaration', ); }); @@ -269,6 +291,63 @@ describe('code mode exposure', () => { ).toContain('declare const tools: { deferred_tool(args:'); }); + it('includes nested schemas when CodeMode has no reveal path', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + registry.registerTool(new MockTool({ name: 'exec' })); + registry.registerTool( + new MockTool({ + name: 'deferred_tool', + shouldDefer: true, + params: { + type: 'object', + properties: { path: { type: 'string' } }, + required: ['path'], + }, + }), + ); + + const description = registry.getFunctionDeclarations()[0]?.description; + expect(description).toContain( + 'tools.deferred_tool(args: { "path": string })', + ); + }); + + it('describes an empty filtered CodeMode surface accurately', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + registry.registerTool(new MockTool({ name: 'exec' })); + registry.registerTool(new MockTool({ name: 'ask_user_question' })); + + const description = registry + .getFunctionDeclarationsFiltered(['exec', 'ask_user_question'], new Set()) + .find((declaration) => declaration.name === 'exec')?.description; + expect(description).toContain( + '// No ordinary tools are available in this context.', + ); + expect(description).not.toContain( + 'Nested tool declarations for directly exposed tools', + ); + }); + + it('keeps filtered and unfiltered CodeMode declaration order aligned', () => { + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeMode }), + ); + for (const name of ['read_file', 'readFile', 'exec']) + registry.registerTool(new MockTool({ name })); + + const unfiltered = registry + .getFunctionDeclarations() + .map((declaration) => declaration.name); + const filtered = registry + .getFunctionDeclarationsFiltered(['read_file', 'readFile', 'exec']) + .map((declaration) => declaration.name); + expect(filtered).toEqual(unfiltered); + }); + it('exposes exec and direct controls while retaining ordinary and hidden tools', () => { const registry = new ToolRegistry( makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), diff --git a/packages/core/src/code-mode/scheduler.test.ts b/packages/core/src/code-mode/scheduler.test.ts index 3cbb16c08dc..e041e905593 100644 --- a/packages/core/src/code-mode/scheduler.test.ts +++ b/packages/core/src/code-mode/scheduler.test.ts @@ -828,6 +828,47 @@ describe('CodeModeOnly scheduler dispatch', () => { ); }); + it('allows an ordinary direct call on the hybrid CodeMode surface', async () => { + const config = makeFakeConfig({ + toolMode: 'code_mode', + approvalMode: ApprovalMode.DEFAULT, + targetDir: '/tmp', + cwd: '/tmp', + }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + const execute = vi.fn().mockResolvedValue({ + llmContent: 'read ok', + returnDisplay: 'read ok', + }); + registry.registerTool( + new MockTool({ name: 'read_probe', kind: Kind.Read, execute }), + ); + const completed = vi.fn(); + const scheduler = new CoreToolScheduler({ + config, + onAllToolCallsComplete: async (calls) => completed(calls), + onToolCallsUpdate: vi.fn(), + getPreferredEditor: () => undefined, + onEditorClose: vi.fn(), + }); + + await scheduler.schedule( + { + callId: 'hybrid-direct-read', + name: 'read_probe', + args: {}, + isClientInitiated: false, + prompt_id: 'prompt-hybrid-direct-read', + }, + new AbortController().signal, + ); + + expect(execute).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(completed).toHaveBeenCalledOnce()); + expect(completed.mock.calls[0]?.[0][0].status).toBe('success'); + }); + it('enforces a restricted agent allowlist inside exec', async () => { const config = makeFakeConfig({ toolMode: 'code_mode_only', diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 4ab1b97d5cd..228178da668 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -96,6 +96,8 @@ import { ToolRegistry, type ToolFactory } from '../tools/tool-registry.js'; import type { McpBudgetEvent } from '../tools/mcp-client-manager.js'; import { ToolNames } from '../tools/tool-names.js'; import { + isCodeModeEnabled, + isToolMode, ToolMode, type ToolMode as ToolModeValue, } from '../tools/code-mode.js'; @@ -3197,7 +3199,9 @@ export class Config { this.toolMode = this.bareMode || this.safeMode ? ToolMode.Direct - : (params.toolMode ?? ToolMode.Direct); + : isToolMode(params.toolMode) + ? params.toolMode + : ToolMode.Direct; if (this.safeMode) { this.debugLogger.info( 'Safe mode active: hooks, extensions, skills, MCP servers, context files, rules disabled', @@ -10396,7 +10400,7 @@ export class Config { }; const registerExecIfEnabled = async (): Promise => { - if (this.getToolMode() === ToolMode.Direct) return; + if (!isCodeModeEnabled(this.getToolMode())) return; await registerLazy(ToolNames.EXEC, async () => { const { ExecTool } = await import('../tools/exec.js'); return new ExecTool(this); diff --git a/packages/core/src/core/client.test.ts b/packages/core/src/core/client.test.ts index 329d05c436d..7859202e4cd 100644 --- a/packages/core/src/core/client.test.ts +++ b/packages/core/src/core/client.test.ts @@ -101,6 +101,7 @@ import { import { collectAvailableSkillEntries } from '../tools/skill-utils.js'; import type { AvailableSkillEntry } from '../tools/skill-utils.js'; import { ToolNames } from '../tools/tool-names.js'; +import { ToolMode } from '../tools/code-mode.js'; import { emptyGoalSnapshot } from '../goals/goal-protocol.js'; import type { GoalRuntime } from '../goals/goal-runtime.js'; import type { FileHistorySnapshot } from '../services/fileHistoryService.js'; @@ -2961,6 +2962,28 @@ describe('Gemini Client (client.ts)', () => { warnSpy.mockRestore(); }); + it('reports that withheld tools remain callable through exec in CodeMode', async () => { + const reg = getRegistryMock(); + reg.getTool.mockReturnValue(null); + reg.getDeferredToolSummary.mockReturnValue([ + { name: 'write_file', description: 'write' }, + ]); + reg.isPermissionDeferred.mockReturnValue(true); + mockConfig.getToolMode = vi.fn().mockReturnValue(ToolMode.CodeMode); + vi.spyOn(client.getChat(), 'setTools').mockImplementation(() => {}); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await client.setTools(); + + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('they remain callable through exec'), + ); + expect(warnSpy).not.toHaveBeenCalledWith( + expect.stringContaining('they are unreachable until restart'), + ); + warnSpy.mockRestore(); + }); + it('does not call a history-revealed eager tool unreachable', async () => { // The history-reveal pass runs before the unreachable warning at both // call sites and re-exposes resume-referenced tools even when diff --git a/packages/core/src/core/client.ts b/packages/core/src/core/client.ts index a26b76bdc84..73dc6a56e27 100644 --- a/packages/core/src/core/client.ts +++ b/packages/core/src/core/client.ts @@ -1841,8 +1841,9 @@ export class LlmClient { * * Returns `undefined` when ToolSearch is unavailable: reminders must not * advertise tools the model has no way to load on demand. Tools held back - * by `tools.eager` in that state are unreachable for the session, which is - * warned about once per session. + * by `tools.eager` in that state are unavailable directly. Hybrid CodeMode + * can still call them through `exec`; Direct mode cannot reach them. The + * active behavior is warned about once per session. */ private resolveDeferredToolsForReminder( deferredSummary: readonly DeferredToolSummary[], @@ -1867,11 +1868,15 @@ export class LlmClient { } if (withheld.length > 0 && !this.warnedAboutUnreachableEagerTools) { this.warnedAboutUnreachableEagerTools = true; + const hybridCodeMode = + this.config.getToolMode?.() === ToolMode.CodeMode; // eslint-disable-next-line no-console -- operator-facing breadcrumb; the debug log file is off in default runs, where this reshaping would otherwise be invisible console.warn( `tools.eager is holding back ${withheld.length} tool(s) in a session with no tool_search, ` + - `so nothing can load them on demand and they are unreachable until restart: ${withheld.join(', ')}. ` + - `Enable tools.toolSearch.enabled (and drop any tool_search deny rule) to keep them loadable, ` + + (hybridCodeMode + ? `so their top-level declarations cannot be loaded until restart, but they remain callable through exec: ${withheld.join(', ')}. ` + : `so nothing can load them on demand and they are unreachable until restart: ${withheld.join(', ')}. `) + + `Enable tools.toolSearch.enabled (and drop any tool_search deny rule) to make them directly loadable, ` + `list them in tools.eager to send their schemas upfront, or use permissions.deny if removal was the intent.`, ); } diff --git a/packages/core/src/tools/code-mode.ts b/packages/core/src/tools/code-mode.ts index 4e6f790fe41..cce80f8fdc6 100644 --- a/packages/core/src/tools/code-mode.ts +++ b/packages/core/src/tools/code-mode.ts @@ -26,7 +26,11 @@ export const ToolMode = { export type ToolMode = (typeof ToolMode)[keyof typeof ToolMode]; -export function isCodeModeEnabled(mode: ToolMode | undefined): boolean { +export function isToolMode(mode: unknown): mode is ToolMode { + return Object.values(ToolMode).some((candidate) => candidate === mode); +} + +export function isCodeModeEnabled(mode: unknown): boolean { return mode === ToolMode.CodeMode || mode === ToolMode.CodeModeOnly; } @@ -197,27 +201,29 @@ function schemaToType(schema: unknown): string { return 'unknown'; } +function bindingSignature(binding: CodeModeToolBinding): string { + return `${binding.jsName}(args: ${schemaToType(binding.parametersJsonSchema)}): Promise`; +} + function describeBinding(binding: CodeModeToolBinding): string { // A deferred tool keeps its registry semantics, but CodeModeOnly hides // tool_search and never surfaces nested calls as history functionCalls, so // nothing can reveal it later: this description is its only chance to carry // a schema. - const params = schemaToType(binding.parametersJsonSchema); - return `tools.${binding.jsName}(args: ${params}): Promise;`; + return `tools.${bindingSignature(binding)};`; } export function augmentDeclarationForCodeMode( declaration: FunctionDeclaration, binding: CodeModeToolBinding, ): FunctionDeclaration { - const params = schemaToType(binding.parametersJsonSchema); return { ...declaration, description: `${declaration.description ?? ''} exec tool declaration: \`\`\`ts -declare const tools: { ${binding.jsName}(args: ${params}): Promise; }; +declare const tools: { ${bindingSignature(binding)}; }; \`\`\``, }; } @@ -225,6 +231,8 @@ declare const tools: { ${binding.jsName}(args: ${params}): Promise = new Set(), + canRevealDeferred = false, ): string { const allTools = plan.bindings.map( ({ name, jsName, description, deferred }) => ({ @@ -240,16 +248,29 @@ export function buildExecDescription( `- ${omitted} is omitted because it collides with ${kept} as tools.${jsName}.`, ) .join('\n'); - const declarations = codeModeOnly - ? plan.bindings.map(describeBinding).join('\n') - : 'Nested tool declarations are included in their top-level tool descriptions. Deferred tools remain listed in ALL_TOOLS and receive a declaration when their top-level declaration is revealed.'; + const uncoveredBindings = plan.bindings.filter( + (binding) => + !topLevelBindingNames.has(binding.name) && + (!binding.deferred || !canRevealDeferred), + ); + const declarations = + plan.bindings.length === 0 + ? '' + : codeModeOnly + ? plan.bindings.map(describeBinding).join('\n') + : [ + 'Nested tool declarations for directly exposed tools are included in their top-level tool descriptions. Deferred tools with a reveal path receive a declaration when their top-level declaration is revealed.', + uncoveredBindings.map(describeBinding).join('\n'), + ] + .filter(Boolean) + .join('\n'); const toolsDescription = codeModeOnly ? 'the code-mode-callable tool functions declared below.' - : 'the code-mode-callable tool functions declared in their top-level tool descriptions.'; + : 'the code-mode-callable tool functions declared in their top-level tool descriptions or below.'; return `Execute JavaScript in a fresh isolated runtime and wait for it to finish. -Use async/await and call registered tools through tools.(args). Calls use the same validation, permissions, approvals, hooks, telemetry, cancellation, concurrency, and output limits as direct tool calls. Tool calls can be composed with Promise.all. Await every tool promise; unawaited calls are cancelled when the script finishes. The exec tool, direct control tools, tool_search, and tool_call are not callable through tools. +Use async/await and call registered tools through tools.(args). Calls use the same validation, permissions, approvals, hooks, telemetry, cancellation, concurrency, and output limits as direct tool calls. Prefer batching independent calls with Promise.all. Await every tool promise; unawaited calls are cancelled when the script finishes. Pass values you need to inspect or return to text(); assigning a result does not include it in the exec output. The exec tool, direct control tools, tool_search, and tool_call are not callable through tools. Results from skill, update_goal, and capture_screen_context are automatically retained in the exec response; text() is not required to preserve their context. Read loaded skill instructions before taking dependent actions in a later exec call. A terminal update_goal result ends the script and prevents further tool calls. @@ -280,9 +301,16 @@ export function buildExecDeclaration( execTool: AnyDeclarativeTool, plan: CodeModeBindingPlan, codeModeOnly = true, + topLevelBindingNames?: ReadonlySet, + canRevealDeferred?: boolean, ): FunctionDeclaration { return { ...execTool.schema, - description: buildExecDescription(plan, codeModeOnly), + description: buildExecDescription( + plan, + codeModeOnly, + topLevelBindingNames, + canRevealDeferred, + ), }; } diff --git a/packages/core/src/tools/tool-registry.test.ts b/packages/core/src/tools/tool-registry.test.ts index 7e3b086e033..f0eaa2e0293 100644 --- a/packages/core/src/tools/tool-registry.test.ts +++ b/packages/core/src/tools/tool-registry.test.ts @@ -788,6 +788,42 @@ describe('ToolRegistry', () => { expect(toolRegistry.isDeferredToolRevealed(toolB.name)).toBe(false); }); + it('counts CodeMode declaration decoration toward the budget', () => { + const directTool = new MockTool({ + name: 'deferred', + shouldDefer: true, + params: { + type: 'object', + properties: { path: { type: 'string' } }, + required: ['path'], + }, + }); + const codeModeTool = new MockTool({ + name: 'deferred', + shouldDefer: true, + params: { + type: 'object', + properties: { path: { type: 'string' } }, + required: ['path'], + }, + }); + const directRegistry = new ToolRegistry(new Config(baseConfigParams)); + const codeModeRegistry = new ToolRegistry( + new Config({ ...baseConfigParams, toolMode: 'code_mode' }), + ); + directRegistry.registerTool(directTool); + codeModeRegistry.registerTool(new MockTool({ name: 'exec' })); + codeModeRegistry.registerTool(codeModeTool); + const rawBudget = tokensFor(directTool); + + expect(directRegistry.preloadDeferredToolsWithinBudget(rawBudget)).toBe( + 1, + ); + expect( + codeModeRegistry.preloadDeferredToolsWithinBudget(rawBudget), + ).toBe(0); + }); + it('excludes visible deferred tools from the preload budget', () => { const visibleTool = new MockTool({ name: 'visible', diff --git a/packages/core/src/tools/tool-registry.ts b/packages/core/src/tools/tool-registry.ts index 789c00896f5..b123207dc64 100644 --- a/packages/core/src/tools/tool-registry.ts +++ b/packages/core/src/tools/tool-registry.ts @@ -883,9 +883,24 @@ export class ToolRegistry { const bindings = new Map( plan.bindings.map((binding) => [binding.name, binding]), ); + const topLevelBindingNames = new Set( + tools + .filter((tool) => tool.name !== ToolNames.EXEC) + .filter((tool) => bindings.has(tool.name)) + .map((tool) => tool.name), + ); + const canRevealDeferred = tools.some( + (tool) => tool.name === ToolNames.TOOL_SEARCH, + ); return tools.map((tool) => { if (tool.name === ToolNames.EXEC) { - return buildExecDeclaration(tool, plan, false); + return buildExecDeclaration( + tool, + plan, + false, + topLevelBindingNames, + canRevealDeferred, + ); } const binding = bindings.get(tool.name); return binding @@ -1076,6 +1091,19 @@ export class ToolRegistry { preloadDeferredToolsWithinBudget(budgetTokens: number): number { const candidates: string[] = []; let totalChars = 0; + const execTool = this.tools.get(ToolNames.EXEC); + const codeModeBindings = + this.config.getToolMode?.() === ToolMode.CodeMode && + execTool !== undefined && + this.isToolAvailable(execTool.name) && + this.isToolDeclared(execTool.name) + ? new Map( + this.getCodeModeBindingPlan().bindings.map((binding) => [ + binding.name, + binding, + ]), + ) + : undefined; for (const tool of this.tools.values()) { if (!this.isToolAvailable(tool.name)) continue; if (!this.isEffectivelyDeferred(tool) || tool.alwaysLoad) continue; @@ -1088,7 +1116,12 @@ export class ToolRegistry { if (this.permissionDeferred.has(tool.name)) continue; if (this.config.getVisibleTools().has(tool.name)) continue; candidates.push(tool.name); - totalChars += JSON.stringify(tool.schema).length; + const binding = codeModeBindings?.get(tool.name); + totalChars += JSON.stringify( + binding + ? augmentDeclarationForCodeMode(tool.schema, binding) + : tool.schema, + ).length; } const estimatedTokens = Math.ceil(totalChars / CHARS_PER_TOKEN); if (candidates.length === 0) { @@ -1155,7 +1188,7 @@ export class ToolRegistry { this.isToolAvailable(tool.name) && this.isToolDeclared(tool.name), ) - .sort(ToolRegistry.compareCodeModeTools); + .sort(ToolRegistry.compareToolsByDeclarationName); return this.decorateCodeModeDeclarations( tools, codeModeAllowedNames ?? allowedNames, diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 9955415163f..f468be46474 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1433,7 +1433,7 @@ } }, "eager": { - "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas are still withheld but nothing can load them back, so the demoted tools are out of reach for that session and a warning is logged. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", + "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas are still withheld and cannot be revealed for direct use; in Code Mode the demoted tools remain callable through exec, while in Direct mode they are out of reach for that session. A warning explains the active behavior. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", "type": "array", "items": { "type": "string" From 6c919b726adb47d12c10094a7016507e3b7363ea Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Sat, 19 Sep 2026 02:07:58 +0800 Subject: [PATCH 03/49] fix(web-shell): map tool mode setting alias --- packages/web-shell/client/settings.test.ts | 8 ++++++++ packages/web-shell/client/settings.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/web-shell/client/settings.test.ts b/packages/web-shell/client/settings.test.ts index 71e8ffc69ac..b92ab8aedff 100644 --- a/packages/web-shell/client/settings.test.ts +++ b/packages/web-shell/client/settings.test.ts @@ -43,6 +43,14 @@ describe('settings presentation aliases', () => { ).toBe(true); expect(WEB_SHELL_SETTING_ITEM_IDS).toContain('setting:workflow-name-only'); }); + it('keeps the stable code-mode alias for the tool mode row', () => { + expect( + isSettingExcluded('tools.mode', { + excludeItems: ['setting:code-mode-only'], + }), + ).toBe(true); + expect(WEB_SHELL_SETTING_ITEM_IDS).toContain('setting:code-mode-only'); + }); it('matches published builtin ids by direct membership', () => { expect( isItemExcluded('builtin:model-management', { diff --git a/packages/web-shell/client/settings.ts b/packages/web-shell/client/settings.ts index 814137b59c0..b601e3a9567 100644 --- a/packages/web-shell/client/settings.ts +++ b/packages/web-shell/client/settings.ts @@ -32,7 +32,7 @@ const SETTING_KEYS = { 'setting:respect-git-ignore': 'context.fileFiltering.respectGitIgnore', 'setting:respect-qwen-ignore': 'context.fileFiltering.respectQwenIgnore', 'setting:fuzzy-file-search': 'context.fileFiltering.enableFuzzySearch', - 'setting:code-mode-only': 'tools.codeModeOnly', + 'setting:code-mode-only': 'tools.mode', 'setting:web-search': 'tools.webSearch.enabled', 'setting:web-search-model': 'tools.webSearch.model', 'setting:web-extractor': 'tools.webSearch.webExtractor', From 02afce8eddab7a06b33546db25b4c9af7eb10995 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Sun, 20 Sep 2026 13:45:37 +0800 Subject: [PATCH 04/49] fix(core): align code mode bindings and reported tool surfaces --- .../2026-09-12-agent-container-execution.md | 2 +- ...6-09-12-agent-container-execution.zh-CN.md | 2 +- docs/design/code-mode-only.md | 6 +- docs/design/code-mode-only.zh-CN.md | 7 ++- docs/design/code-mode.md | 27 +++++++-- docs/design/code-mode.zh-CN.md | 22 +++++-- docs/users/configuration/settings.md | 60 +++++++++---------- .../resident-tool-prompt-assembly/README.md | 24 ++++---- packages/cli/src/config/settingsSchema.ts | 6 +- .../src/ui/commands/contextCommand.test.ts | 60 +++++++++++++++++++ .../cli/src/ui/commands/contextCommand.ts | 15 ++--- packages/core/src/code-mode/code-mode.test.ts | 56 ++++++++++++++--- .../config-execution-environment.test.ts | 20 +++++++ packages/core/src/config/config.ts | 6 ++ packages/core/src/core/client.test.ts | 52 +++++++++++++++- packages/core/src/core/client.ts | 13 ++-- packages/core/src/tools/code-mode.ts | 20 ++++--- .../schemas/settings.schema.json | 6 +- 18 files changed, 306 insertions(+), 98 deletions(-) diff --git a/docs/design/2026-09-12-agent-container-execution.md b/docs/design/2026-09-12-agent-container-execution.md index 14d2f51ed77..051ffb3b625 100644 --- a/docs/design/2026-09-12-agent-container-execution.md +++ b/docs/design/2026-09-12-agent-container-execution.md @@ -79,7 +79,7 @@ values. The policy composes with `isolation: "worktree"` and `working_dir`. It does not extend the model-visible isolation enum or change `isolation: "remote"`. -Combining it with `tools.codeModeOnly` is rejected before container startup; +Combining it with `tools.mode: "code_mode_only"` is rejected before container startup; the first container registry supports direct tool calls only. ## Backend policy and definition boundaries diff --git a/docs/design/2026-09-12-agent-container-execution.zh-CN.md b/docs/design/2026-09-12-agent-container-execution.zh-CN.md index 0ca5f028b85..3d01a14cced 100644 --- a/docs/design/2026-09-12-agent-container-execution.zh-CN.md +++ b/docs/design/2026-09-12-agent-container-execution.zh-CN.md @@ -58,7 +58,7 @@ CLI 重启时保留环境变量值,供 Node TLS 证书、设置插值等启动 该策略可与 `isolation: "worktree"` 和 `working_dir` 组合。 它不扩展面向模型的 isolation 枚举,也不改变 `isolation: "remote"`。 -与 `tools.codeModeOnly` 的组合会在容器启动前被拒绝;首版容器注册表只支持直接工具调用。 +与 `tools.mode: "code_mode_only"` 的组合会在容器启动前被拒绝;首版容器注册表只支持直接工具调用。 ## 后端策略与定义边界 diff --git a/docs/design/code-mode-only.md b/docs/design/code-mode-only.md index a69c0273d6b..360bc9f3ef6 100644 --- a/docs/design/code-mode-only.md +++ b/docs/design/code-mode-only.md @@ -77,7 +77,8 @@ Before each provider tool sync, the `exec` description is generated from the current registry. Tools are sorted by canonical name. A name is normalized to a JavaScript property by replacing invalid identifier characters and prefixing names that begin with a digit. If two canonical names normalize to the same -property, the lexicographically first name wins and one warning names the +property, an exact canonical match wins over rewritten names. If neither is an +exact match, the lexicographically first name wins. The description names the omitted collision. The description defines: @@ -89,8 +90,7 @@ The description defines: `setTimeout(callback, delayMs)`, `clearTimeout(timeoutId)`, and `exit()`; - TypeScript-like signatures generated deterministically from JSON Schema; - the absence of Node.js, `process`, `require`, filesystem, network, imports, - `console`, `WebAssembly`, `Atomics`, `SharedArrayBuffer`, and persistent - state. Pending timers do not keep `exec` alive by themselves. + `console`, `WebAssembly`, `Atomics`, and persistent state. Pending timers do not keep `exec` alive by themselves. The nested call returns a JSON-safe object containing the real call id, tool name, status, output, and structured content. Failed and cancelled calls reject diff --git a/docs/design/code-mode-only.zh-CN.md b/docs/design/code-mode-only.zh-CN.md index 2308c6632f1..d3b4a39cff5 100644 --- a/docs/design/code-mode-only.zh-CN.md +++ b/docs/design/code-mode-only.zh-CN.md @@ -67,8 +67,9 @@ CodeModeOnly 会隐藏 `tool_search`,嵌套调用也不会以 `functionCall` 每次向 provider 同步工具前,都会从当前 registry 生成 `exec` 描述。工具按规范 名称排序。名称会通过替换无效标识符字符来规范化为 JavaScript 属性;如果名称以 -数字开头,还会添加前缀。如果两个规范名称映射到同一个属性,则字典序靠前的名称 -胜出,并用一条 warning 指出被省略的冲突项。 +数字开头,还会添加前缀。如果两个规范名称映射到同一个属性,优先保留与属性精确 +一致的规范名称;若都不是精确匹配,则字典序靠前的名称胜出。描述会指出被省略的 +冲突项。 描述会定义: @@ -79,7 +80,7 @@ CodeModeOnly 会隐藏 `tool_search`,嵌套调用也不会以 `functionCall` `setTimeout(callback, delayMs)`、`clearTimeout(timeoutId)` 和 `exit()`; - 从 JSON Schema 确定性生成的类 TypeScript 签名; - 不提供 Node.js、`process`、`require`、文件系统、网络、import、`console`、 - `WebAssembly`、`Atomics`、`SharedArrayBuffer` 和持久状态。待处理的 timer + `WebAssembly`、`Atomics` 和持久状态。待处理的 timer 本身不会让 `exec` 保持运行。 嵌套调用返回一个 JSON-safe 对象,其中包含真实 call id、工具名、状态、输出和 diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index a06a508dba7..ef21637efe0 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -16,8 +16,9 @@ CodeModeOnly. ## Goal -Add a hybrid `CodeMode` option without changing the existing default or -`CodeModeOnly` behavior. +Add a hybrid `CodeMode` option while preserving the direct default and the +strict `CodeModeOnly` exposure policy. Both code modes share the corrected +`exec` failure guidance and exact-name collision precedence described below. ## Configuration @@ -38,7 +39,8 @@ The effective modes are: | `code_mode_only` | `code_mode_only` | This follows Codex's `ToolMode` serialized values. Safe mode and bare mode -force `direct`. +force `direct`. Container execution exposes direct tools only: selecting +`code_mode` emits a warning and provides no `exec`; `code_mode_only` is rejected. ## Exposure policy @@ -55,7 +57,15 @@ for that tool. The `exec` description keeps the complete `ALL_TOOLS` metadata but does not duplicate every schema. Deferred tools gain their declaration when their normal top-level declaration is revealed. In `code_mode_only`, the existing behavior remains: all nested declarations live in the `exec` -description because no later top-level reveal is possible. +description because no later top-level reveal is possible. `tools.eager` and +`tools.visible` do not reduce those nested schemas in CodeModeOnly: `tool_search` +is hidden, deferred reminders and the no-ToolSearch warning are skipped, and +surviving callable tools remain available through `exec`. + +Nested bindings prefer an exact canonical JavaScript name over names rewritten +to that property. Other collisions retain canonical-name ordering; omitted +bindings remain absent from nested signatures and are never advertised as +reachable through `exec`. Filtered subagent declarations preserve the same mode. The agent's `tools` list narrows its direct surface. Explicit ordinary-tool execution entries @@ -70,8 +80,9 @@ all surviving code-mode-callable bindings. telemetry. - Duplicating every schema in hybrid mode would increase prompt size, so only the per-tool nested declaration is appended there. -- A denied or failed nested call aborts the whole `exec` program, so a call - that may be refused should stay out of a batch that would need to be repeated. +- A denied or failed nested call rejects its promise. An uncaught rejection + aborts `exec`; catching an expected rejection lets the program continue. Keep + calls that may be refused out of a batch that would need to be repeated. ## Validation @@ -87,3 +98,7 @@ all surviving code-mode-callable bindings. - Ordinary visible tools advertise their nested JavaScript signature. - `tools.mode: "code_mode_only"` selects the stricter behavior. - The default, safe-mode, and bare-mode surfaces remain direct-only. +- Both code modes dispatch an exact canonical name to that tool under a + normalization collision and describe caught versus uncaught failures accurately. +- Context accounting charges only emitted declarations; container fallback and + withheld-tool warnings describe the actual available bindings. diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index ca8197a1fab..056dd3e1693 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -15,7 +15,8 @@ CodeModeOnly。 ## 目标 -新增混合 `CodeMode`,同时保持现有默认模式和 `CodeModeOnly` 行为不变。 +新增混合 `CodeMode`,同时保持直接调用默认模式和 `CodeModeOnly` 的严格暴露策略。 +两种代码模式共享下述修正后的 `exec` 失败说明和精确名称碰撞优先级。 ## 配置 @@ -36,7 +37,8 @@ CodeModeOnly。 | `code_mode_only` | `code_mode_only` | 这些值与 Codex 的 `ToolMode` 序列化值一致。安全模式和 bare 模式会强制使用 -`direct`。 +`direct`。容器执行仅支持直接工具:选择 `code_mode` 会显示警告且不提供 `exec`; +选择 `code_mode_only` 则会报错。 ## 暴露策略 @@ -51,7 +53,13 @@ CodeModeOnly。 在 `code_mode` 中,普通可见工具的描述会附加该工具的 `exec` 调用声明。 `exec` 描述保留完整的 `ALL_TOOLS` 元数据,但不重复所有 schema。延迟工具在 按正常流程暴露顶层声明时获得对应声明。在 `code_mode_only` 中保持现有行为: -由于后续无法暴露顶层声明,所有嵌套声明都集中在 `exec` 描述中。 +由于后续无法暴露顶层声明,所有嵌套声明都集中在 `exec` 描述中。CodeModeOnly 中 +`tools.eager` 和 `tools.visible` 不会减少这些嵌套 schema:`tool_search` 被隐藏, +延迟提醒和缺少 ToolSearch 的警告被跳过,仍可调用的工具继续通过 `exec` 使用。 + +嵌套绑定优先保留与 JavaScript 属性精确一致的规范名称,再考虑改写为该属性的 +名称。其他碰撞沿用规范名称字典序;被省略的绑定不出现在嵌套签名中, +也不会被警告描述为可通过 `exec` 调用。 经过过滤的子智能体声明沿用相同模式。智能体的 `tools` 列表会收窄直接调用面。 显式列出的普通工具执行项(`executionAllowedTools`)会收窄嵌套集合;继承或显式 @@ -64,8 +72,9 @@ CodeModeOnly。 取消和遥测。 - 混合模式若重复全部 schema 会增大提示词,因此只在各顶层工具描述中附加对应的 嵌套声明。 -- 被拒绝或失败的嵌套调用会中止整个 `exec` 程序,因此可能被拒绝的调用不应加入 - 一个随后必须整体重试的批次。 +- 被拒绝或失败的嵌套调用会使 promise reject。未捕获的 rejection 会中止 `exec`; + 捕获预期 rejection 后可以继续执行。可能被拒绝的调用不应加入随后必须整体重试 + 的批次。 ## 验证 @@ -80,3 +89,6 @@ CodeModeOnly。 - 普通可见工具会声明其嵌套 JavaScript 调用签名。 - `tools.mode: "code_mode_only"` 选择严格模式。 - 默认模式、安全模式和 bare 模式仍然只使用直接调用。 +- 两种代码模式在规范化碰撞时都将精确规范名称分派给该工具,并准确区分已捕获与 + 未捕获失败的行为。 +- 上下文计数仅计入实际发送的声明;容器回退和工具延迟警告与实际可用绑定一致。 diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index c8126d8ecb9..435ed5bf5d8 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -370,36 +370,36 @@ If you are experiencing performance issues with file searching (e.g., with `@` c #### tools -| Setting | Type | Description | Default | Notes | -| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | -| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | -| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `true` | | -| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | -| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | -| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message` and `tool_search` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay loadable via `tool_search`), and `permissions.deny` to block tools outright. | `undefined` | | -| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | -| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring `tool_search`. Listed tools appear alongside core tools in the initial session. Merged as a union across scopes. | `undefined` | | -| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, callable, and discoverable via `tool_search`. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with `tool_search`: when ToolSearch is not registered — `tools.toolSearch.enabled: false`, a `tool_search` deny rule, or the automatic opt-out for DeepSeek models — the schemas cannot be revealed directly. In Code Mode, exec-capable tools stay available through `exec`; otherwise withheld tools are unreachable. A warning also names each group. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in `tools.visible` are declared up front. Use `permissions.deny` if you meant to remove them, or leave ToolSearch on. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. | `undefined` | | -| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | -| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. | `direct` | Experimental. Requires restart. | -| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | -| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is loadable via `tool_search`, but its schema is not sent in the initial model request. | `undefined` | | -| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | -| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | -| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | -| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | -| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | -| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | -| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | -| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | -| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | -| `tools.toolSearch.enabled` | boolean | Load MCP tools on demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates. | `true` | Requires restart: Yes | -| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). When their combined schemas fit within this budget, they are declared upfront instead of loaded on demand via ToolSearch. Tools demoted by `tools.eager` are excluded from this preload and stay on demand. Set `0` to always load deferred tools on demand. | `10` | Requires restart: Yes | -| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | -| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | +| Setting | Type | Description | Default | Notes | +| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | +| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | +| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `true` | | +| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | +| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | +| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message` and `tool_search` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay loadable via `tool_search`), and `permissions.deny` to block tools outright. | `undefined` | | +| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | +| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring `tool_search`. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in `exec` and hides `tool_search`. Merged as a union across scopes. | `undefined` | | +| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, callable, and discoverable via `tool_search`. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with `tool_search`: when ToolSearch is not registered — `tools.toolSearch.enabled: false`, a `tool_search` deny rule, or the automatic opt-out for DeepSeek models — the schemas cannot be revealed directly. In Code Mode, tools with actual nested bindings stay available through `exec`; otherwise withheld tools are unreachable. A warning names each group. Exception: Code Mode Only keeps full nested schemas for callable tools, hides `tool_search`, and skips deferred reminders and this warning; `tools.eager` and `tools.visible` do not save schema tokens there. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in `tools.visible` are declared up front. Use `permissions.deny` if you meant to remove them, or leave ToolSearch on. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. | `undefined` | | +| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | +| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. Code Mode Only ignores eager/visible schema deferral and includes full nested schemas for callable tools. | `direct` | Experimental. Requires restart. | +| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | +| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is loadable via `tool_search`, but its schema is not sent in the initial model request. | `undefined` | | +| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | +| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | +| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | +| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | +| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | +| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | +| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | +| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | +| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | +| `tools.toolSearch.enabled` | boolean | Load MCP tools on demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates. | `true` | Requires restart: Yes | +| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). When their combined schemas fit within this budget, they are declared upfront instead of loaded on demand via ToolSearch. Tools demoted by `tools.eager` are excluded from this preload and stay on demand. Set `0` to always load deferred tools on demand. | `10` | Requires restart: Yes | +| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | +| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | > [!note] > diff --git a/docs/verification/resident-tool-prompt-assembly/README.md b/docs/verification/resident-tool-prompt-assembly/README.md index 7a597cb5be8..e2dff2afd5e 100644 --- a/docs/verification/resident-tool-prompt-assembly/README.md +++ b/docs/verification/resident-tool-prompt-assembly/README.md @@ -122,18 +122,18 @@ done ## 5. 影响面清单(逐条过,这是"对别的模块没影响"的依据) -| # | 模块 | 为什么可能受影响 | 怎么验 | 预期 | -| --- | --------------------- | -------------------------------------------------- | ------------------------------------- | ---------------------------------------------- | -| 1 | 主会话(交互) | 提示词内容变了 | 裁剪配置下跑几轮真实任务 | 文件类任务正常完成,不出现"调用不存在的工具" | -| 2 | `/context` | 它读同一份快照来生成提示词 | `/context detail` 的系统提示词一行 | 与请求一致,不报错 | -| 3 | Arena | 它直接调 `getCoreSystemPrompt`,没有快照 | `/arena --models a,b "简单任务"` | 各 agent 提示词与改动前一致(无快照 = 不门控) | -| 4 | 子 agent | 走 `includeDeferred: true` 另一条路径,本改动不碰 | 跑一次 `agent` 委派 | 子 agent 提示词与改动前一致 | -| 5 | output style | `keepCodingInstructions: false` 与门控叠加 | 选一个自定义 style 再看提示词 | 两者各自生效,不互相吃掉 | -| 6 | code mode | 该模式下工具在 `exec` 内调用,实现里**明确不门控** | `tools.codeModeOnly: true` 起一个会话 | `tools.` 那些条目一条不少 | -| 7 | `QWEN_SYSTEM_MD` 覆盖 | 覆盖分支完全绕过默认提示词 | 设一个覆盖文件起会话 | 提示词就是该文件,门控不参与 | -| 8 | 提示词缓存 | 静态前缀内容变了 | 同一会话连发 3 轮,看缓存命中 token | 命中率与改动前同阶;前缀只在会话开始时重写一次 | -| 9 | 压缩 | 压缩走 `startChat`,会重算快照 | 触发一次 `/compress` | 压缩后提示词与压缩前一致(同一会话工具集没变) | -| 10 | 恢复会话 | 恢复也走 `startChat` | `--continue` 恢复一条旧会话 | 正常恢复,提示词按当前工具集门控 | +| # | 模块 | 为什么可能受影响 | 怎么验 | 预期 | +| --- | --------------------- | -------------------------------------------------- | ----------------------------------------- | ---------------------------------------------- | +| 1 | 主会话(交互) | 提示词内容变了 | 裁剪配置下跑几轮真实任务 | 文件类任务正常完成,不出现"调用不存在的工具" | +| 2 | `/context` | 它读同一份快照来生成提示词 | `/context detail` 的系统提示词一行 | 与请求一致,不报错 | +| 3 | Arena | 它直接调 `getCoreSystemPrompt`,没有快照 | `/arena --models a,b "简单任务"` | 各 agent 提示词与改动前一致(无快照 = 不门控) | +| 4 | 子 agent | 走 `includeDeferred: true` 另一条路径,本改动不碰 | 跑一次 `agent` 委派 | 子 agent 提示词与改动前一致 | +| 5 | output style | `keepCodingInstructions: false` 与门控叠加 | 选一个自定义 style 再看提示词 | 两者各自生效,不互相吃掉 | +| 6 | code mode | 该模式下工具在 `exec` 内调用,实现里**明确不门控** | `tools.mode: "code_mode_only"` 起一个会话 | `tools.` 那些条目一条不少 | +| 7 | `QWEN_SYSTEM_MD` 覆盖 | 覆盖分支完全绕过默认提示词 | 设一个覆盖文件起会话 | 提示词就是该文件,门控不参与 | +| 8 | 提示词缓存 | 静态前缀内容变了 | 同一会话连发 3 轮,看缓存命中 token | 命中率与改动前同阶;前缀只在会话开始时重写一次 | +| 9 | 压缩 | 压缩走 `startChat`,会重算快照 | 触发一次 `/compress` | 压缩后提示词与压缩前一致(同一会话工具集没变) | +| 10 | 恢复会话 | 恢复也走 `startChat` | `--continue` 恢复一条旧会话 | 正常恢复,提示词按当前工具集门控 | 第 6、7 条是**最容易被忽略的反向检查**:它们必须**没有**变化。 diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 299efc890e9..2efc8910261 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -2732,7 +2732,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: ToolMode.Direct, description: - 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct.', + 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral: callable tools retain full nested schemas and tool_search is hidden.', showInDialog: true, options: [ { value: ToolMode.Direct, label: 'Default' }, @@ -3024,7 +3024,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string[] | undefined, description: - 'Deferred tool names made visible at startup without requiring tool_search. Listed tools appear alongside core tools in the initial session.', + 'Deferred tool names made visible at startup without requiring tool_search. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in exec and does not expose tool_search.', showInDialog: false, mergeStrategy: MergeStrategy.UNION, }, @@ -3035,7 +3035,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string[] | undefined, description: - 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas cannot be revealed directly. In Code Mode, exec-capable tools stay available through exec; otherwise withheld tools are unreachable. A warning also names each group. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', + 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas cannot be revealed directly. In Code Mode, tools with actual exec bindings stay available through exec; otherwise withheld tools are unreachable. A warning also names each group. Exception: Code Mode Only always includes full nested schemas for callable tools, hides tool_search, and skips deferred reminders and this warning, so eager/visible do not save schema tokens there. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', showInDialog: false, }, approvalMode: { diff --git a/packages/cli/src/ui/commands/contextCommand.test.ts b/packages/cli/src/ui/commands/contextCommand.test.ts index f82766ba6e5..fc325f1fee0 100644 --- a/packages/cli/src/ui/commands/contextCommand.test.ts +++ b/packages/cli/src/ui/commands/contextCommand.test.ts @@ -12,6 +12,7 @@ import { getBuiltInOutputStyle, getCoreSystemPrompt, resolveInteractionMode, + estimateContextTextTokens, } from '@qwen-code/qwen-code-core'; import { t } from '../../i18n/index.js'; import { @@ -153,6 +154,65 @@ describe('collectContextData (contextCommand)', () => { expect(data.builtinTools[0]?.tokens).toBeGreaterThan(100); }); + it('counts only emitted declarations when ordinary tools are nested in exec', async () => { + const decoratedExec = { + name: 'exec', + description: 'tools.read_file and tools.skill '.repeat(100), + }; + const config = { + ...mockConfig, + getToolRegistry: vi.fn().mockReturnValue({ + getAllTools: () => + ['exec', 'read_file', 'skill'].map((name) => ({ + name, + schema: { name, description: 'raw schema '.repeat(20) }, + })), + getFunctionDeclarations: () => [decoratedExec], + isDeferredAndHidden: () => false, + }), + } as unknown as Config; + + const data = await collectContextData(config, true); + + expect(data.builtinTools.map((tool) => tool.name)).toEqual(['exec']); + expect(data.breakdown.skills).toBe(0); + expect(data.breakdown.builtinTools).toBe( + estimateContextTextTokens(JSON.stringify([decoratedExec])), + ); + }); + + it('charges the decorated Skill declaration once and leaves the residual in built-ins', async () => { + const decoratedExec = { name: 'exec', description: 'exec '.repeat(100) }; + const decoratedSkill = { + name: 'skill', + description: 'skill plus its nested declaration '.repeat(100), + }; + const declarations = [decoratedExec, decoratedSkill]; + const config = { + ...mockConfig, + getToolRegistry: vi.fn().mockReturnValue({ + getAllTools: () => + ['exec', 'skill'].map((name) => ({ + name, + schema: { name, description: 'raw' }, + })), + getFunctionDeclarations: () => declarations, + isDeferredAndHidden: () => false, + }), + } as unknown as Config; + + const data = await collectContextData(config, true); + const skillTokens = estimateContextTextTokens( + JSON.stringify(decoratedSkill), + ); + + expect(data.breakdown.skills).toBe(skillTokens); + expect(data.breakdown.builtinTools).toBe( + estimateContextTextTokens(JSON.stringify(declarations)) - skillTokens, + ); + expect(data.builtinTools.map((tool) => tool.name)).toEqual(['exec']); + }); + it('reads the per-session chat token count, not the process-global singleton (#5763)', async () => { // uiTelemetryService is a module-level singleton shared by every session // in a `serve` daemon. Reading it here would report whichever session most diff --git a/packages/cli/src/ui/commands/contextCommand.ts b/packages/cli/src/ui/commands/contextCommand.ts index 7a13cadcad0..3c8129f99e4 100644 --- a/packages/cli/src/ui/commands/contextCommand.ts +++ b/packages/cli/src/ui/commands/contextCommand.ts @@ -157,9 +157,9 @@ export async function collectContextData( if (isMediaPolicyToolHiddenFromModel(config, tool)) { continue; } - const toolJsonStr = JSON.stringify( - toolDeclarationsByName.get(tool.name) ?? tool.schema, - ); + const declaration = toolDeclarationsByName.get(tool.name); + if (!declaration) continue; + const toolJsonStr = JSON.stringify(declaration); const tokens = estimateContextTextTokens(toolJsonStr); if (tool instanceof DiscoveredMCPTool) { mcpTools.push({ @@ -186,12 +186,9 @@ export async function collectContextData( const memoryFilesTokens = memoryFiles.reduce((sum, f) => sum + f.tokens, 0); const skillTool = allTools.find((tool) => tool.name === ToolNames.SKILL); - const skillToolDefinitionTokens = skillTool - ? estimateContextTextTokens( - JSON.stringify( - toolDeclarationsByName.get(ToolNames.SKILL) ?? skillTool.schema, - ), - ) + const skillDeclaration = toolDeclarationsByName.get(ToolNames.SKILL); + const skillToolDefinitionTokens = skillDeclaration + ? estimateContextTextTokens(JSON.stringify(skillDeclaration)) : 0; const loadedSkillNames: ReadonlySet = diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index 73846124a7b..6dbe673330c 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -423,17 +423,17 @@ describe('code mode exposure', () => { expect(anthropic[1]?.description).toContain('tools.read_file'); }); - it('builds stable declarations and resolves normalized-name collisions first-wins', () => { + it('builds stable declarations and prefers exact names over rewritten collisions', () => { const tools = [ + new MockTool({ name: 'z-tool' }), new MockTool({ - name: 'z-tool', + name: 'z_tool', params: { type: 'object', properties: { count: { type: 'integer' } }, required: ['count'], }, }), - new MockTool({ name: 'z_tool' }), new MockTool({ name: 'a-tool', shouldDefer: true, @@ -453,10 +453,10 @@ describe('code mode exposure', () => { expect(first).toEqual(second); expect(first.bindings.map((item) => item.name)).toEqual([ 'a-tool', - 'z-tool', + 'z_tool', ]); expect(first.collisions).toEqual([ - { jsName: 'z_tool', kept: 'z-tool', omitted: 'z_tool' }, + { jsName: 'z_tool', kept: 'z_tool', omitted: 'z-tool' }, ]); expect(buildExecDescription(first)).toContain( 'tools.z_tool(args: { "count": number })', @@ -473,7 +473,7 @@ describe('code mode exposure', () => { 'Pending timeouts do not keep exec alive by themselves', ); expect(buildExecDescription(first, false)).toContain( - 'A denied or failed call aborts the whole program', + 'an uncaught rejection aborts the program', ); expect(buildExecDescription(first)).toContain( 'clearTimeout(timeoutId?: number)', @@ -501,19 +501,57 @@ describe('code mode exposure', () => { (item) => item.name === 'exec', )?.description; const keptDescription = declarations.find( - (item) => item.name === 'read-file', + (item) => item.name === 'read_file', )?.description; const omittedDescription = declarations.find( - (item) => item.name === 'read_file', + (item) => item.name === 'read-file', )?.description; expect(execDescription).toContain( - '- read_file is omitted because it collides with read-file as tools.read_file.', + '- read-file is omitted because it collides with read_file as tools.read_file.', ); expect(keptDescription).toContain('declare const tools: { read_file(args:'); expect(omittedDescription).not.toContain('declare const tools:'); }); + it('does not reserve an exact name excluded from the nested allowlist', () => { + const bindings = planCodeModeBindings( + [new MockTool({ name: 'get-data' }), new MockTool({ name: 'get_data' })], + () => false, + new Set(['get-data']), + ); + expect( + bindings.bindings.map(({ name, jsName }) => ({ name, jsName })), + ).toEqual([{ name: 'get-data', jsName: 'get_data' }]); + expect(bindings.collisions).toEqual([]); + }); + + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'dispatches the exact canonical MCP name under a collision in %s', + async (toolMode) => { + const registry = new ToolRegistry(makeFakeConfig({ toolMode })); + for (const name of [ + 'exec', + 'mcp__my-server__fetch', + 'mcp__my_server__fetch', + ]) { + registry.registerTool(new MockTool({ name })); + } + const dispatched: string[] = []; + const result = await executeCodeMode( + 'text((await tools.mcp__my_server__fetch({})).name)', + registry.getCodeModeBindingPlan(), + runtime(async (name) => { + dispatched.push(name); + return { callId: name, name, status: 'success', output: name }; + }), + new AbortController().signal, + ); + expect(dispatched).toEqual(['mcp__my_server__fetch']); + expect(result.output).toBe('mcp__my_server__fetch'); + }, + ); + it('expands deferred tool schemas because nothing can reveal them later', () => { const deferredPlan = planCodeModeBindings( [ diff --git a/packages/core/src/config/config-execution-environment.test.ts b/packages/core/src/config/config-execution-environment.test.ts index 0b61be2b386..f0e4db6e164 100644 --- a/packages/core/src/config/config-execution-environment.test.ts +++ b/packages/core/src/config/config-execution-environment.test.ts @@ -218,6 +218,26 @@ describe('execution environment ownership', () => { expect(parent.getExecutionEnvironment()).toBeUndefined(); }); + it('warns when a hybrid container registry falls back to direct tools', async () => { + const parent = new Config({ ...params, toolMode: ToolMode.CodeMode }); + const child = deriveConfig(parent, { + getExecutionEnvironment: () => ({}) as ExecutionEnvironment, + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const registry = await child.createToolRegistry(undefined, { + skipDiscovery: true, + }); + expect(registry.getAllToolNames()).toContain(ToolNames.READ_FILE); + expect(registry.getAllToolNames()).not.toContain(ToolNames.EXEC); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('continuing with direct tools'), + ); + } finally { + warn.mockRestore(); + } + }); + it.each(['ready', 'starting'])( 'waits for %s environments during session shutdown', async (state) => { diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 7c6b56a72cb..2d83a4356e3 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -11038,6 +11038,12 @@ export class Config { 'Container execution cannot be combined with tools.mode = "code_mode_only".', ); } + if (this.getToolMode() === ToolMode.CodeMode) { + // eslint-disable-next-line no-console -- the fallback must be visible without debug logging + console.warn( + 'Container execution does not support exec; continuing with direct tools for tools.mode = "code_mode".', + ); + } const [{ createExecutionTools }, { wrapExecutionTool }] = await Promise.all([ import('../services/local-execution-environment.js'), diff --git a/packages/core/src/core/client.test.ts b/packages/core/src/core/client.test.ts index 4a632b15207..19011db2916 100644 --- a/packages/core/src/core/client.test.ts +++ b/packages/core/src/core/client.test.ts @@ -109,7 +109,8 @@ import { import { collectAvailableSkillEntries } from '../tools/skill-utils.js'; import type { AvailableSkillEntry } from '../tools/skill-utils.js'; import { ToolNames } from '../tools/tool-names.js'; -import { ToolMode } from '../tools/code-mode.js'; +import { planCodeModeBindings, ToolMode } from '../tools/code-mode.js'; +import { MockTool } from '../test-utils/mock-tool.js'; import { emptyGoalSnapshot } from '../goals/goal-protocol.js'; import type { GoalRuntime } from '../goals/goal-runtime.js'; import type { FileHistorySnapshot } from '../services/fileHistoryService.js'; @@ -567,6 +568,9 @@ describe('Gemini Client (client.ts)', () => { // that depends on a fully-formed Config object, we need to mock the // entire implementation of Config for these tests. const mockToolRegistry = { + getCodeModeBindingPlan: vi + .fn() + .mockReturnValue({ bindings: [], collisions: [] }), warmAll: vi.fn().mockResolvedValue(undefined), ensureTool: vi.fn().mockResolvedValue(null), getFunctionDeclarations: vi.fn().mockReturnValue([]), @@ -2520,6 +2524,7 @@ describe('Gemini Client (client.ts)', () => { describe('setTools — progressive MCP reminders', () => { function getRegistryMock() { return vi.mocked(mockConfig.getToolRegistry)() as unknown as { + getCodeModeBindingPlan: ReturnType; getFunctionDeclarations: ReturnType; getDeferredToolSummary: ReturnType; getMcpServerInstructions: ReturnType; @@ -3331,6 +3336,15 @@ describe('Gemini Client (client.ts)', () => { it('reports only code-mode-callable withheld tools as reachable through exec', async () => { const reg = getRegistryMock(); + reg.getCodeModeBindingPlan.mockReturnValue( + planCodeModeBindings( + [ + new MockTool({ name: 'write_file' }), + new MockTool({ name: 'send_message' }), + ], + () => true, + ), + ); reg.getTool.mockImplementation((name: string) => name === ToolNames.EXEC ? ({} as never) : null, ); @@ -3356,6 +3370,42 @@ describe('Gemini Client (client.ts)', () => { warnSpy.mockRestore(); }); + it('does not advertise an omitted collision binding as reachable through exec', async () => { + const reg = getRegistryMock(); + reg.getTool.mockImplementation((name: string) => + name === ToolNames.EXEC ? ({} as never) : null, + ); + reg.getCodeModeBindingPlan.mockReturnValue( + planCodeModeBindings( + [ + new MockTool({ name: 'get--data' }), + new MockTool({ name: 'get-_data' }), + ], + () => true, + ), + ); + reg.getDeferredToolSummary.mockReturnValue([ + { name: 'get-_data', description: 'omitted target' }, + ]); + reg.isPermissionDeferred.mockReturnValue(true); + mockConfig.getToolMode = vi.fn().mockReturnValue(ToolMode.CodeMode); + vi.spyOn(client.getChat(), 'setTools').mockImplementation(() => {}); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + await client.setTools(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining( + 'These tools are unreachable until restart: get-_data', + ), + ); + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining('remain callable through exec'), + ); + } finally { + warn.mockRestore(); + } + }); + it('does not call a history-revealed eager tool unreachable', async () => { // The history-reveal pass runs before the unreachable warning at both // call sites and re-exposes resume-referenced tools even when diff --git a/packages/core/src/core/client.ts b/packages/core/src/core/client.ts index 6671d7d32b6..1f0e849a8b2 100644 --- a/packages/core/src/core/client.ts +++ b/packages/core/src/core/client.ts @@ -92,7 +92,7 @@ import { buildRelevantAutoMemoryPrompt } from '../memory/recall.js'; import { isManagedMemoryPath } from '../memory/paths.js'; import { isProjectSkillPath } from '../skills/skill-paths.js'; import { ToolNames, canonicalToolName } from '../tools/tool-names.js'; -import { getToolExposure, ToolMode } from '../tools/code-mode.js'; +import { ToolMode } from '../tools/code-mode.js'; // Telemetry import { @@ -1883,13 +1883,16 @@ export class LlmClient { this.warnedAboutUnreachableEagerTools = true; const hybridCodeMode = this.config.getToolMode?.() === ToolMode.CodeMode; - const nestedReachable = new Set( + const boundNames = new Set( hybridCodeMode && toolRegistry.getTool(ToolNames.EXEC) - ? withheld.filter( - (name) => getToolExposure(name) === 'code-mode-callable', - ) + ? toolRegistry + .getCodeModeBindingPlan() + .bindings.map((binding) => binding.name) : [], ); + const nestedReachable = new Set( + withheld.filter((name) => boundNames.has(name)), + ); const unreachable = withheld.filter( (name) => !nestedReachable.has(name), ); diff --git a/packages/core/src/tools/code-mode.ts b/packages/core/src/tools/code-mode.ts index 24d607b8079..bb9585fb15f 100644 --- a/packages/core/src/tools/code-mode.ts +++ b/packages/core/src/tools/code-mode.ts @@ -100,15 +100,21 @@ export function planCodeModeBindings( const bindings: CodeModeToolBinding[] = []; const collisions: CodeModeBindingPlan['collisions'] = []; const claimed = new Map(); - const sorted = [...tools].sort((a, b) => - a.name < b.name ? -1 : a.name > b.name ? 1 : 0, - ); + const sorted = tools + .filter( + (tool) => + getToolExposure(tool.name) === 'code-mode-callable' && + (!allowedNames || allowedNames.has(tool.name)), + ) + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const canonicalNames = new Set(sorted.map((tool) => tool.name)); for (const tool of sorted) { - if (getToolExposure(tool.name) !== 'code-mode-callable') continue; - if (allowedNames && !allowedNames.has(tool.name)) continue; const jsName = normalizeCodeModeToolName(tool.name); - const kept = claimed.get(jsName); + // An exact name owns its binding even if a rewritten name sorts first. + const kept = + claimed.get(jsName) ?? + (tool.name !== jsName && canonicalNames.has(jsName) ? jsName : undefined); if (kept) { collisions.push({ jsName, kept, omitted: tool.name }); continue; @@ -270,7 +276,7 @@ export function buildExecDescription( return `Execute JavaScript in a fresh isolated runtime and wait for it to finish. -Use async/await and call registered tools through tools.(args). Calls use the same validation, permissions, approvals, hooks, telemetry, cancellation, concurrency, and output limits as direct tool calls. Prefer batching independent calls with Promise.all. A denied or failed call aborts the whole program, so keep a call that may be refused out of a batch you would then have to repeat. Await every tool promise; unawaited calls are cancelled when the script finishes. Pass values you need to inspect or return to text(); assigning a result does not include it in the exec output. The exec tool, direct control tools, tool_search, and tool_call are not callable through tools. +Use async/await and call registered tools through tools.(args). Calls use the same validation, permissions, approvals, hooks, telemetry, cancellation, concurrency, and output limits as direct tool calls. Prefer batching independent calls with Promise.all. A denied or failed nested call rejects its promise; an uncaught rejection aborts the program. Catch expected failures if execution should continue, and keep a call that may be refused out of a batch you would then have to repeat. Await every tool promise; unawaited calls are cancelled when the script finishes. Pass values you need to inspect or return to text(); assigning a result does not include it in the exec output. The exec tool, direct control tools, tool_search, and tool_call are not callable through tools. Results from skill, update_goal, and capture_screen_context are automatically retained in the exec response; text() is not required to preserve their context. Read loaded skill instructions before taking dependent actions in a later exec call. A terminal update_goal result ends the script and prevents further tool calls. When Omni is enabled, uploaded media and its resource metadata are also automatically retained; a result without content needs no image() call. diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 12ccfdaead7..4dc9e4eebea 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1277,7 +1277,7 @@ "type": "object", "properties": { "mode": { - "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Options: direct, code_mode, code_mode_only", + "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral: callable tools retain full nested schemas and tool_search is hidden. Options: direct, code_mode, code_mode_only", "enum": [ "direct", "code_mode", @@ -1432,14 +1432,14 @@ } }, "visible": { - "description": "Deferred tool names made visible at startup without requiring tool_search. Listed tools appear alongside core tools in the initial session.", + "description": "Deferred tool names made visible at startup without requiring tool_search. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in exec and does not expose tool_search.", "type": "array", "items": { "type": "string" } }, "eager": { - "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas cannot be revealed directly. In Code Mode, exec-capable tools stay available through exec; otherwise withheld tools are unreachable. A warning also names each group. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", + "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, callable, and discoverable via tool_search. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with tool_search: when ToolSearch is not registered (tools.toolSearch.enabled false, a tool_search deny rule, or the automatic opt-out for DeepSeek models) the schemas cannot be revealed directly. In Code Mode, tools with actual exec bindings stay available through exec; otherwise withheld tools are unreachable. A warning also names each group. Exception: Code Mode Only always includes full nested schemas for callable tools, hides tool_search, and skips deferred reminders and this warning, so eager/visible do not save schema tokens there. Two carve-outs: demoted tools referenced in resumed session history get their schemas re-sent without a warning, and demoted tools listed in tools.visible are declared up front. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", "type": "array", "items": { "type": "string" From 3239c6804c1a37bdffcbc0a7a03d02ab434b8a2a Mon Sep 17 00:00:00 2001 From: qwen-code-ci-bot Date: Tue, 22 Sep 2026 15:27:45 +0000 Subject: [PATCH 05/49] fix: repair web-shell alias tests and address code-mode review feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - web-shell: call the exported isSettingVisible in the code-mode alias test and sync the mirrored alias table to tools.mode, fixing the ReferenceError and stale-alias failures in the Test job - coreToolScheduler: render only the skill invocation surfaces the session actually has — no exec surface in direct mode where exec is never registered, no top-level Skill surface in code_mode_only where direct skill calls are rejected - agent-core: let MCP tool names fall through to the exact-name and pattern checks before the nested exec gateway admits them, so a server-level executionAllowedTools pattern is honored for nested bindings - docs/settings: sync the threshold bridge-mode wording, the container execution fallback, and the zh-CN withheld-tool translation with the shipped behavior --- .../2026-09-12-agent-container-execution.md | 3 +- ...6-09-12-agent-container-execution.zh-CN.md | 3 +- docs/design/code-mode.zh-CN.md | 2 +- packages/cli/src/config/settingsSchema.ts | 2 +- .../runtime/agent-core.skill-gate.test.ts | 40 +++++++++++ .../core/src/agents/runtime/agent-core.ts | 5 ++ .../core/src/core/coreToolScheduler.test.ts | 71 +++++++++++++++++++ packages/core/src/core/coreToolScheduler.ts | 23 +++++- .../schemas/settings.schema.json | 2 +- packages/web-shell/client/settings.test.ts | 6 +- 10 files changed, 147 insertions(+), 10 deletions(-) diff --git a/docs/design/2026-09-12-agent-container-execution.md b/docs/design/2026-09-12-agent-container-execution.md index 051ffb3b625..6222258bb35 100644 --- a/docs/design/2026-09-12-agent-container-execution.md +++ b/docs/design/2026-09-12-agent-container-execution.md @@ -80,7 +80,8 @@ values. The policy composes with `isolation: "worktree"` and `working_dir`. It does not extend the model-visible isolation enum or change `isolation: "remote"`. Combining it with `tools.mode: "code_mode_only"` is rejected before container startup; -the first container registry supports direct tool calls only. +`tools.mode: "code_mode"` warns and continues with direct tools only, registering +no `exec`. The first container registry supports direct tool calls only. ## Backend policy and definition boundaries diff --git a/docs/design/2026-09-12-agent-container-execution.zh-CN.md b/docs/design/2026-09-12-agent-container-execution.zh-CN.md index 3d01a14cced..382b7796729 100644 --- a/docs/design/2026-09-12-agent-container-execution.zh-CN.md +++ b/docs/design/2026-09-12-agent-container-execution.zh-CN.md @@ -58,7 +58,8 @@ CLI 重启时保留环境变量值,供 Node TLS 证书、设置插值等启动 该策略可与 `isolation: "worktree"` 和 `working_dir` 组合。 它不扩展面向模型的 isolation 枚举,也不改变 `isolation: "remote"`。 -与 `tools.mode: "code_mode_only"` 的组合会在容器启动前被拒绝;首版容器注册表只支持直接工具调用。 +与 `tools.mode: "code_mode_only"` 的组合会在容器启动前被拒绝;`tools.mode: "code_mode"` +会告警并仅以直接工具继续,不注册 `exec`。首版容器注册表只支持直接工具调用。 ## 后端策略与定义边界 diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 54aa6f295b3..d4ddc349aeb 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -97,4 +97,4 @@ schema 的嵌套工具附上签名。在 `code_mode_only` 中,所有嵌套声 - 默认模式、安全模式和 bare 模式仍然只使用直接调用。 - 两种代码模式在规范化碰撞时都将精确规范名称分派给该工具,并准确区分已捕获与 未捕获失败的行为。 -- 上下文计数仅计入实际发送的声明;容器回退和工具延迟警告与实际可用绑定一致。 +- 上下文计数仅计入实际发送的声明;容器回退和被保留工具(withheld)的警告与实际可用绑定一致。 diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index f9c4887dd2d..d124c0cf6a7 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -2857,7 +2857,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: 0, description: - 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct tool mode. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct mode they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', + 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', showInDialog: true, // A percentage of the context window: values above 100 would set a // budget larger than the window and unconditionally preload every diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 6d5254da8fc..eca8fa444e3 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -479,6 +479,46 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual([ToolNames.READ_FILE, ToolNames.WRITE_FILE]); }); + it('honors MCP execution patterns in the hybrid nested binding set', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + const readTool = new MockTool({ name: 'mcp__github__read_file' }); + Object.assign(readTool, { + serverName: 'github', + serverToolName: 'read_file', + }); + const createTool = new MockTool({ name: 'mcp__github__create_issue' }); + Object.assign(createTool, { + serverName: 'github', + serverToolName: 'create_issue', + }); + registry.registerTool(readTool); + registry.registerTool(createTool); + const core = new AgentCore( + 'mcp-pattern-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC, 'mcp__github__read_*'], + executionAllowedTools: [ToolNames.EXEC, 'mcp__github__read_*'], + }, + ); + + await core.prepareTools(); + + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual(['mcp__github__read_file']); + }); + it('keeps inherited CodeMode declarations executable only when directly allowed', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 29665579066..d84c2ae7dc6 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -1756,6 +1756,11 @@ export class AgentCore { if ( forNestedBinding && isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && + // An MCP tool name must fall through to the exact-name and pattern + // checks below: they are the only place a server-level narrowing in + // the allowlist can be honored. + (!toolName.startsWith('mcp__') || + (this.executionAllowedMcpPatterns?.length ?? 0) === 0) && this.executionAllowedExactTools?.has(ToolNames.EXEC) && getToolExposure(toolName) === 'code-mode-callable' ) { diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 7b386b09fe1..5cf6ac509e7 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -20380,6 +20380,7 @@ describe('CoreToolScheduler activation wiring', () => { // omitted, defaults to ["tsx-helper"] which satisfies the common case. availableSkillNames?: string[]; containerExecution?: boolean; + toolMode?: 'direct' | 'code_mode' | 'code_mode_only'; }): { scheduler: CoreToolScheduler; onAllToolCallsComplete: ReturnType; @@ -20468,6 +20469,7 @@ describe('CoreToolScheduler activation wiring', () => { }, getDisabledSkillNames: () => new Set(), getExecutionEnvironment: () => (opts.containerExecution ? {} : undefined), + getToolMode: () => opts.toolMode, isSkillEnabled: () => true, getModelInvocableCommandsProvider: () => null, addInlineAnnouncedSkillKeys, @@ -20546,6 +20548,75 @@ describe('CoreToolScheduler activation wiring', () => { expect(responseText).toContain( 'Use the invocation surface available in this session', ); + // Direct mode never registers exec, so the reminder must not name the + // exec surface — a model following it would call an undeclared tool. + expect(responseText).toContain('pass its name to the top-level Skill tool'); + expect(responseText).not.toContain( + "await tools.skill({ skill: '' })", + ); + }); + + it('names both invocation surfaces in hybrid code mode', async () => { + const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); + const { scheduler, onAllToolCallsComplete } = + buildSchedulerWithSkillManager({ + matchAndActivateByPaths, + skillToolPresent: true, + toolMode: 'code_mode', + }); + + await scheduler.schedule( + [ + { + callId: '1', + name: ToolNames.READ_FILE, + args: { file_path: '/proj/src/App.tsx' }, + isClientInitiated: false, + prompt_id: 'p1', + }, + ], + new AbortController().signal, + ); + + const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; + expect(completed[0].status).toBe('success'); + const responseText = getResponseText(completed[0]); + expect(responseText).toContain('pass its name to the top-level Skill tool'); + expect(responseText).toContain("await tools.skill({ skill: '' })"); + }); + + it('names only the exec surface in code_mode_only', async () => { + const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); + const { scheduler, onAllToolCallsComplete } = + buildSchedulerWithSkillManager({ + matchAndActivateByPaths, + skillToolPresent: true, + toolMode: 'code_mode_only', + }); + + // A nested call (source: 'code_mode') is the surface a CodeModeOnly + // session actually executes read_file on, so the file read runs and the + // activation reminder is produced. + await scheduler.schedule( + [ + { + callId: '1', + name: ToolNames.READ_FILE, + args: { file_path: '/proj/src/App.tsx' }, + isClientInitiated: false, + prompt_id: 'p1', + source: 'code_mode', + }, + ], + new AbortController().signal, + ); + + const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; + expect(completed[0].status).toBe('success'); + const responseText = getResponseText(completed[0]); + expect(responseText).not.toContain( + 'pass its name to the top-level Skill tool', + ); expect(responseText).toContain("await tools.skill({ skill: '' })"); }); diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index b332fdcdce2..5b3d0a29693 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -228,7 +228,11 @@ import { runWithToolCallSource, type CodeModeToolResult, } from '../code-mode/tool-call-runtime.js'; -import { isCodeModeToolCallAllowed, ToolMode } from '../tools/code-mode.js'; +import { + isCodeModeEnabled, + isCodeModeToolCallAllowed, + ToolMode, +} from '../tools/code-mode.js'; const debugLogger = createDebugLogger('TOOL_SCHEDULER'); @@ -6117,8 +6121,23 @@ export class CoreToolScheduler { })); } if (activatedEntries.length > 0) { + // Name only the invocation surfaces this session has: the + // exec surface exists only when a code mode is enabled and + // exec was registered, and CodeModeOnly rejects top-level + // Skill calls. + const execSurfaceAvailable = + isCodeModeEnabled(this.config.getToolMode?.()) && + !!this.toolRegistry.getTool(ToolNames.EXEC); + const topLevelSurfaceAvailable = + this.config.getToolMode?.() !== ToolMode.CodeModeOnly; + const invocationGuidance = + execSurfaceAvailable && topLevelSurfaceAvailable + ? "pass its name to the top-level Skill tool, or call `await tools.skill({ skill: '' })` from exec" + : execSurfaceAvailable + ? "call `await tools.skill({ skill: '' })` from exec" + : 'pass its name to the top-level Skill tool'; reminderBlocks.push( - `The following skill(s) became available based on the file you just accessed. Use the invocation surface available in this session: pass its name to the top-level Skill tool, or call \`await tools.skill({ skill: '' })\` from exec:\n\n${renderAvailableSkillsBlock( + `The following skill(s) became available based on the file you just accessed. Use the invocation surface available in this session: ${invocationGuidance}:\n\n${renderAvailableSkillsBlock( activatedEntries, )}\n`, ); diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 7fb25c7b6b9..3aa1f4b0899 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1345,7 +1345,7 @@ "minimum": 0, "maximum": 100, "default": 0, - "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct tool mode. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct mode they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." + "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." } } }, diff --git a/packages/web-shell/client/settings.test.ts b/packages/web-shell/client/settings.test.ts index 897b963b0cd..266998d2537 100644 --- a/packages/web-shell/client/settings.test.ts +++ b/packages/web-shell/client/settings.test.ts @@ -45,10 +45,10 @@ describe('settings presentation aliases', () => { }); it('keeps the stable code-mode alias for the tool mode row', () => { expect( - isSettingExcluded('tools.mode', { + isSettingVisible('tools.mode', { excludeItems: ['setting:code-mode-only'], }), - ).toBe(true); + ).toBe(false); expect(WEB_SHELL_SETTING_ITEM_IDS).toContain('setting:code-mode-only'); }); it('matches published builtin ids by direct membership', () => { @@ -248,7 +248,7 @@ describe('settings presentation aliases', () => { 'setting:respect-git-ignore': 'context.fileFiltering.respectGitIgnore', 'setting:respect-qwen-ignore': 'context.fileFiltering.respectQwenIgnore', 'setting:fuzzy-file-search': 'context.fileFiltering.enableFuzzySearch', - 'setting:code-mode-only': 'tools.codeModeOnly', + 'setting:code-mode-only': 'tools.mode', 'setting:web-search': 'tools.webSearch.enabled', 'setting:web-search-model': 'tools.webSearch.model', 'setting:web-extractor': 'tools.webSearch.webExtractor', From 28df8ee5086f37a19378550e7dc3f93f331d01b7 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Wed, 23 Sep 2026 01:09:07 +0800 Subject: [PATCH 06/49] fix: align hybrid tool guidance with available invocation surfaces --- packages/core/src/code-mode/code-mode.test.ts | 9 +++- .../config-execution-environment.test.ts | 13 +++++- packages/core/src/config/config.ts | 7 +++- .../core/src/core/coreToolScheduler.test.ts | 34 ++++++++++----- packages/core/src/core/coreToolScheduler.ts | 23 +--------- packages/core/src/tools/code-mode.ts | 10 ++++- packages/core/src/tools/tool-registry.ts | 4 ++ packages/core/src/utils/fileUtils.test.ts | 36 +++++++++++++++- packages/core/src/utils/fileUtils.ts | 27 ++++++------ packages/sdk-typescript/README.md | 42 +++++++++---------- packages/sdk-typescript/src/types/types.ts | 12 ++++-- 11 files changed, 141 insertions(+), 76 deletions(-) diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index 276c876a73d..8a40865e5c2 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -200,7 +200,7 @@ describe('code mode exposure', () => { }, }), ); - for (const name of ['tool_search', 'agent', 'exec']) + for (const name of ['tool_search', 'tool_call', 'agent', 'exec']) registry.registerTool(new MockTool({ name })); const declarations = registry.getFunctionDeclarations(); @@ -208,6 +208,7 @@ describe('code mode exposure', () => { 'agent', 'exec', 'read_file', + 'tool_call', 'tool_search', ]); const readFileDescription = declarations.find( @@ -285,6 +286,8 @@ describe('code mode exposure', () => { ]); expect(initial[0]?.description).toContain('"name":"deferred_tool"'); expect(initial[0]?.description).not.toContain('tools.deferred_tool(args:'); + expect(initial[0]?.description).toContain('use tool_call outside exec'); + expect(initial[0]?.description).toContain('returned by tool_search'); expect(registry.getDeferredToolSummary().map((item) => item.name)).toEqual([ 'deferred_tool', ]); @@ -294,6 +297,7 @@ describe('code mode exposure', () => { new Set(['deferred_tool']), ); expect(filtered[0]?.description).toContain('tools.deferred_tool(args:'); + expect(filtered[0]?.description).toContain('use tool_call outside exec'); const revealed = registry.getFunctionDeclarations({ includeDeferred: true, @@ -333,6 +337,9 @@ describe('code mode exposure', () => { expect(description).toContain( 'tools.deferred_tool(args: { "path": string })', ); + expect(description).not.toContain('use tool_call outside exec'); + expect(description).not.toContain('returned by tool_search'); + expect(description).toContain('the tool has no nested binding'); }, ); diff --git a/packages/core/src/config/config-execution-environment.test.ts b/packages/core/src/config/config-execution-environment.test.ts index f0e4db6e164..e252e55cd09 100644 --- a/packages/core/src/config/config-execution-environment.test.ts +++ b/packages/core/src/config/config-execution-environment.test.ts @@ -218,7 +218,7 @@ describe('execution environment ownership', () => { expect(parent.getExecutionEnvironment()).toBeUndefined(); }); - it('warns when a hybrid container registry falls back to direct tools', async () => { + it('warns once per root session when hybrid container registries fall back to direct tools', async () => { const parent = new Config({ ...params, toolMode: ToolMode.CodeMode }); const child = deriveConfig(parent, { getExecutionEnvironment: () => ({}) as ExecutionEnvironment, @@ -233,6 +233,17 @@ describe('execution environment ownership', () => { expect(warn).toHaveBeenCalledWith( expect.stringContaining('continuing with direct tools'), ); + await child.createToolRegistry(undefined, { skipDiscovery: true }); + await deriveConfig(parent, { + getExecutionEnvironment: () => ({}) as ExecutionEnvironment, + }).createToolRegistry(undefined, { skipDiscovery: true }); + expect(warn).toHaveBeenCalledTimes(1); + + await deriveConfig( + new Config({ ...params, toolMode: ToolMode.CodeMode }), + { getExecutionEnvironment: () => ({}) as ExecutionEnvironment }, + ).createToolRegistry(undefined, { skipDiscovery: true }); + expect(warn).toHaveBeenCalledTimes(2); } finally { warn.mockRestore(); } diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index be0025a8104..d3874a20e53 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -3027,6 +3027,7 @@ export class Config { private fastModel?: string; private readonly webSearchSettings?: WebSearchSettings; private webSearchNoticeEmitted = false; + private readonly codeModeWarnings = { containerFallback: false }; /** * Per-session web_search call count. An object that is never reassigned: * derived Configs (`deriveConfig` → `Object.create(base)`) must mutate the @@ -11348,7 +11349,11 @@ export class Config { 'Container execution cannot be combined with tools.mode = "code_mode_only".', ); } - if (this.getToolMode() === ToolMode.CodeMode) { + if ( + this.getToolMode() === ToolMode.CodeMode && + !this.codeModeWarnings.containerFallback + ) { + this.codeModeWarnings.containerFallback = true; // eslint-disable-next-line no-console -- the fallback must be visible without debug logging console.warn( 'Container execution does not support exec; continuing with direct tools for tools.mode = "code_mode".', diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 5cf6ac509e7..0004aaf3ecb 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -20546,17 +20546,17 @@ describe('CoreToolScheduler activation wiring', () => { const responseText = getResponseText(completed[0]); expect(responseText).toContain('tsx-helper'); expect(responseText).toContain( - 'Use the invocation surface available in this session', + 'Load a skill by name using the tool interface declared in this session', + ); + expect(responseText).not.toContain( + 'pass its name to the top-level Skill tool', ); - // Direct mode never registers exec, so the reminder must not name the - // exec surface — a model following it would call an undeclared tool. - expect(responseText).toContain('pass its name to the top-level Skill tool'); expect(responseText).not.toContain( "await tools.skill({ skill: '' })", ); }); - it('names both invocation surfaces in hybrid code mode', async () => { + it('defers to declared invocation surfaces in hybrid code mode', async () => { const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); const { scheduler, onAllToolCallsComplete } = buildSchedulerWithSkillManager({ @@ -20581,11 +20581,18 @@ describe('CoreToolScheduler activation wiring', () => { const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; expect(completed[0].status).toBe('success'); const responseText = getResponseText(completed[0]); - expect(responseText).toContain('pass its name to the top-level Skill tool'); - expect(responseText).toContain("await tools.skill({ skill: '' })"); + expect(responseText).toContain( + 'Load a skill by name using the tool interface declared in this session', + ); + expect(responseText).not.toContain( + 'pass its name to the top-level Skill tool', + ); + expect(responseText).not.toContain( + "await tools.skill({ skill: '' })", + ); }); - it('names only the exec surface in code_mode_only', async () => { + it('defers to declared invocation surfaces in code_mode_only', async () => { const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); const { scheduler, onAllToolCallsComplete } = buildSchedulerWithSkillManager({ @@ -20614,10 +20621,15 @@ describe('CoreToolScheduler activation wiring', () => { const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; expect(completed[0].status).toBe('success'); const responseText = getResponseText(completed[0]); + expect(responseText).toContain( + 'Load a skill by name using the tool interface declared in this session', + ); expect(responseText).not.toContain( 'pass its name to the top-level Skill tool', ); - expect(responseText).toContain("await tools.skill({ skill: '' })"); + expect(responseText).not.toContain( + "await tools.skill({ skill: '' })", + ); }); it('stays silent when SkillTool is registered but was never declared', async () => { @@ -20654,7 +20666,7 @@ describe('CoreToolScheduler activation wiring', () => { expect(completed[0].status).toBe('success'); const responseText = getResponseText(completed[0]); expect(responseText).not.toContain( - 'Use the invocation surface available in this session', + 'Load a skill by name using the tool interface declared in this session', ); expect(responseText).not.toContain('tsx-helper'); // The half that starves the parent. Moving this call outside the gate @@ -20695,7 +20707,7 @@ describe('CoreToolScheduler activation wiring', () => { const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; expect(getResponseText(completed[0])).toContain( - 'Use the invocation surface available in this session', + 'Load a skill by name using the tool interface declared in this session', ); // …and the announcement IS consumed here, so the parent does not repeat // what this agent already showed. The pair is what makes the negative diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index 5b3d0a29693..6e56af06dec 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -228,11 +228,7 @@ import { runWithToolCallSource, type CodeModeToolResult, } from '../code-mode/tool-call-runtime.js'; -import { - isCodeModeEnabled, - isCodeModeToolCallAllowed, - ToolMode, -} from '../tools/code-mode.js'; +import { isCodeModeToolCallAllowed, ToolMode } from '../tools/code-mode.js'; const debugLogger = createDebugLogger('TOOL_SCHEDULER'); @@ -6121,23 +6117,8 @@ export class CoreToolScheduler { })); } if (activatedEntries.length > 0) { - // Name only the invocation surfaces this session has: the - // exec surface exists only when a code mode is enabled and - // exec was registered, and CodeModeOnly rejects top-level - // Skill calls. - const execSurfaceAvailable = - isCodeModeEnabled(this.config.getToolMode?.()) && - !!this.toolRegistry.getTool(ToolNames.EXEC); - const topLevelSurfaceAvailable = - this.config.getToolMode?.() !== ToolMode.CodeModeOnly; - const invocationGuidance = - execSurfaceAvailable && topLevelSurfaceAvailable - ? "pass its name to the top-level Skill tool, or call `await tools.skill({ skill: '' })` from exec" - : execSurfaceAvailable - ? "call `await tools.skill({ skill: '' })` from exec" - : 'pass its name to the top-level Skill tool'; reminderBlocks.push( - `The following skill(s) became available based on the file you just accessed. Use the invocation surface available in this session: ${invocationGuidance}:\n\n${renderAvailableSkillsBlock( + `The following skill(s) became available based on the file you just accessed. Load a skill by name using the tool interface declared in this session:\n\n${renderAvailableSkillsBlock( activatedEntries, )}\n`, ); diff --git a/packages/core/src/tools/code-mode.ts b/packages/core/src/tools/code-mode.ts index f9707cdd1d2..2f43519a785 100644 --- a/packages/core/src/tools/code-mode.ts +++ b/packages/core/src/tools/code-mode.ts @@ -239,6 +239,7 @@ export function buildExecDescription( codeModeOnly = true, topLevelBindingNames: ReadonlySet = new Set(), canSearchDeferredSchemas = false, + hasToolCallBridge = canSearchDeferredSchemas, ): string { const allTools = plan.bindings.map( ({ name, jsName, description, deferred }) => ({ @@ -265,14 +266,17 @@ export function buildExecDescription( : codeModeOnly ? plan.bindings.map(describeBinding).join('\n') : [ - 'Nested tool declarations for directly exposed tools are included in their top-level tool descriptions. With both tool_search and tool_call available, tool_search returns deferred parameter schemas without changing top-level declarations. Match the returned schema name exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, do not normalize or guess a binding; use tool_call outside exec, or an available direct tool, subject to normal validation and approval.', + 'Nested tool declarations for directly exposed tools are included in their top-level tool descriptions.', + hasToolCallBridge + ? 'With both tool_search and tool_call available, tool_search returns deferred parameter schemas without changing top-level declarations. Match the returned schema name exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, do not normalize or guess a binding; use tool_call outside exec, or an available direct tool, subject to normal validation and approval.' + : 'Other nested parameter schemas are declared below. Match tool names exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, the tool has no nested binding; do not normalize or guess one.', uncoveredBindings.map(describeBinding).join('\n'), ] .filter(Boolean) .join('\n'); const toolsDescription = codeModeOnly ? 'the code-mode-callable tool functions declared below.' - : 'the code-mode-callable functions listed in ALL_TOOLS. Parameter schemas are in their top-level tool descriptions, below, or returned by tool_search; use the exact ALL_TOOLS name-to-jsName mapping.'; + : `the code-mode-callable functions listed in ALL_TOOLS. Parameter schemas are in their top-level tool descriptions or below${hasToolCallBridge ? ', or returned by tool_search' : ''}; use the exact ALL_TOOLS name-to-jsName mapping.`; return `Execute JavaScript in a fresh isolated runtime and wait for it to finish. @@ -309,6 +313,7 @@ export function buildExecDeclaration( codeModeOnly = true, topLevelBindingNames?: ReadonlySet, canSearchDeferredSchemas?: boolean, + hasToolCallBridge?: boolean, ): FunctionDeclaration { return { ...execTool.schema, @@ -317,6 +322,7 @@ export function buildExecDeclaration( codeModeOnly, topLevelBindingNames, canSearchDeferredSchemas, + hasToolCallBridge, ), }; } diff --git a/packages/core/src/tools/tool-registry.ts b/packages/core/src/tools/tool-registry.ts index 6c8e64e7c2d..e2a657df1ea 100644 --- a/packages/core/src/tools/tool-registry.ts +++ b/packages/core/src/tools/tool-registry.ts @@ -883,6 +883,9 @@ export class ToolRegistry { if (!tools.some((tool) => tool.name === ToolNames.EXEC)) { return tools.map((tool) => tool.schema); } + const hasToolCallBridge = + tools.some((tool) => tool.name === ToolNames.TOOL_SEARCH) && + tools.some((tool) => tool.name === ToolNames.TOOL_CALL); const plan = this.getCodeModeBindingPlan(allowedNames); const bindings = new Map( plan.bindings.map((binding) => [binding.name, binding]), @@ -901,6 +904,7 @@ export class ToolRegistry { false, topLevelBindingNames, canSearchDeferredSchemas, + hasToolCallBridge, ); } const binding = bindings.get(tool.name); diff --git a/packages/core/src/utils/fileUtils.test.ts b/packages/core/src/utils/fileUtils.test.ts index e0bb1ac5c8c..5a0064e8194 100644 --- a/packages/core/src/utils/fileUtils.test.ts +++ b/packages/core/src/utils/fileUtils.test.ts @@ -40,6 +40,7 @@ import { decodeBufferWithEncodingInfo } from '../services/sync-file-encoding.js' import { iconvEncode } from './iconvHelper.js'; import { LargeNonUtf8TextError } from './read-text-range.js'; import type { Config } from '../config/config.js'; +import { ToolMode } from '../tools/code-mode.js'; import { StandardFileSystemService } from '../services/fileSystemService.js'; import { ToolErrorType } from '../tools/tool-error.js'; import { @@ -166,6 +167,7 @@ describe('fileUtils', () => { getFunctionDeclarations: () => [ { name: 'read_file' }, { name: 'tool_search' }, + { name: 'tool_call' }, ], getDeferredToolSummary: () => [{ name: 'zoom_image' }], getCodeModeBindingPlan: () => ({ @@ -1409,6 +1411,7 @@ describe('fileUtils', () => { it.each<{ codeModeOnly: boolean; + toolMode?: ToolMode; declared: string[]; deferred: string[]; bindings: string[]; @@ -1423,7 +1426,7 @@ describe('fileUtils', () => { }, { codeModeOnly: false, - declared: ['read_file', 'tool_search'], + declared: ['read_file', 'tool_search', 'tool_call'], deferred: ['zoom_image'], bindings: [], hint: @@ -1451,9 +1454,37 @@ describe('fileUtils', () => { bindings: ['zoom_image'], hint: ' If details are too small, call tools.zoom_image with coordinates normalized from 0 to 1000.', }, + ...[[], ['tool_search'], ['tool_call'], ['tool_search', 'tool_call']].map( + (bridgeTools) => ({ + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared: ['read_file', 'exec', ...bridgeTools], + deferred: ['zoom_image'], + bindings: ['zoom_image'], + hint: + bridgeTools.length === 2 + ? ' If details are too small, review zoom_image with tool_search and invoke it through tool_call, with coordinates normalized from 0 to 1000.' + : ' If details are too small, call tools.zoom_image with coordinates normalized from 0 to 1000.', + }), + ), + ...[[], ['tool_search'], ['tool_call']].map((bridgeTools) => ({ + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared: ['read_file', ...bridgeTools], + deferred: ['zoom_image'], + bindings: ['zoom_image'], + hint: '', + })), ])( 'uses only exposed tools for image guidance: $declared, code mode $codeModeOnly', - async ({ codeModeOnly, declared, deferred, bindings, hint }) => { + async ({ + codeModeOnly, + toolMode, + declared, + deferred, + bindings, + hint, + }) => { await sharp({ create: { width: 20, height: 10, channels: 3, background: '#306090' }, }) @@ -1463,6 +1494,7 @@ describe('fileUtils', () => { const result = await processSingleFileContent(testImageFilePath, { ...mockConfig, getCodeModeOnly: () => codeModeOnly, + getToolMode: () => toolMode, getToolRegistry: () => ({ getFunctionDeclarations: () => declared.map((name) => ({ name })), getDeferredToolSummary: () => deferred.map((name) => ({ name })), diff --git a/packages/core/src/utils/fileUtils.ts b/packages/core/src/utils/fileUtils.ts index 3420593f569..9a33c9a0639 100644 --- a/packages/core/src/utils/fileUtils.ts +++ b/packages/core/src/utils/fileUtils.ts @@ -1661,28 +1661,31 @@ export async function processSingleFileContent( .map((declaration) => declaration.name), ); const zoomDeclared = declaredTools.has('zoom_image'); - // Reachability, not existence (#12271): advertising a tool the - // session cannot call costs the model a turn. Checking - // `tool_search` alone is enough even though invoking a deferred - // tool also needs `tool_call` — when either bridge tool is - // unavailable, deferred tools are declared eagerly, which - // `zoomDeclared` already covers. - const zoomAvailable = codeModeOnly + const hasToolCallBridge = + declaredTools.has('tool_search') && + declaredTools.has('tool_call'); + const useNestedZoom = + codeModeOnly || + (config.getToolMode?.() === 'code_mode' && + declaredTools.has('exec') && + !zoomDeclared && + !hasToolCallBridge); + const zoomAvailable = useNestedZoom ? registry ?.getCodeModeBindingPlan() .bindings.some((binding) => binding.name === 'zoom_image') : zoomDeclared || - (declaredTools.has('tool_search') && + (hasToolCallBridge && registry ?.getDeferredToolSummary() .some((tool) => tool.name === 'zoom_image')); let zoomHint = ''; if (zoomAvailable) { - // CodeModeOnly binds zoom_image into `exec` and hides the bridge, - // so neither discovery nor `tool_call` applies there. - const toolName = codeModeOnly ? 'tools.zoom_image' : 'zoom_image'; + const toolName = useNestedZoom + ? 'tools.zoom_image' + : 'zoom_image'; zoomHint = - codeModeOnly || zoomDeclared + useNestedZoom || zoomDeclared ? ` If details are too small, call ${toolName} with coordinates normalized from 0 to 1000.` : ' If details are too small, review zoom_image with tool_search and invoke it through tool_call, with coordinates normalized from 0 to 1000.'; } diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 918dda2a7e0..e3e9feb9b17 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct tool mode. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; `tools.eager` does not make them unreachable or save their schema tokens. In direct mode they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; `tools.eager` does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index a85302dea9f..05dcade9606 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -416,7 +416,7 @@ export interface QueryOptions { * registered; when either is unregistered (`tools.toolSearch.enabled: false` * denies both; a `tool_search` or `tool_call` deny rule, or a * `tools.disabled` entry removes one) the - * demoted tools that remain hidden are not offered to the model and cannot + * demoted tools that remain hidden are absent from top-level declarations and cannot * be reached through the bridge for that session, and a warning is * written to the CLI process's stderr. The SDK forwards it only when * stderr is piped (`debug: true` or a `stderr` handler) and the effective @@ -430,7 +430,9 @@ export interface QueryOptions { * direct call to a still-hidden demoted tool, which any tool-set * refresh (resume, MCP discovery, the first plan-mode entry in a * session, a subagent definition change) re-declares. - * These bridge and warning rules describe direct tool mode. CodeModeOnly + * These bridge and warning rules apply to direct and hybrid code modes. + * In hybrid mode, exec retains callable nested bindings; their schemas are + * included in exec when either bridge tool is unavailable. CodeModeOnly * hides both bridge tools, includes callable deferred tools' full schemas * in exec, and skips deferred reminders and this warning; tools.eager does * not make those nested tools unreachable or reduce their schema tokens. @@ -487,7 +489,7 @@ export interface QueryOptions { * when either is unregistered (`tools.toolSearch.enabled: false` denies * both; a `tool_search` or `tool_call` deny rule, or a * `tools.disabled` entry removes one) the - * demoted tools that remain hidden are not offered to the model and cannot + * demoted tools that remain hidden are absent from top-level declarations and cannot * be reached through the bridge for that session, and a warning is * written to the CLI process's stderr. The SDK forwards it only when * stderr is piped (`debug: true` or a `stderr` handler) and the effective @@ -501,7 +503,9 @@ export interface QueryOptions { * contains a direct call to a still-hidden demoted tool, which any * tool-set refresh (resume, MCP discovery, the first plan-mode * entry in a session, a subagent definition change) re-declares (#9827). - * These bridge and warning rules describe direct tool mode. CodeModeOnly + * These bridge and warning rules apply to direct and hybrid code modes. + * In hybrid mode, exec retains callable nested bindings; their schemas are + * included in exec when either bridge tool is unavailable. CodeModeOnly * hides both bridge tools, includes callable deferred tools' full schemas * in exec, and skips deferred reminders and this warning; tools.eager does * not make those nested tools unreachable or reduce their schema tokens. From a7315eb58e26bdff075c23020fc09269698debb3 Mon Sep 17 00:00:00 2001 From: qwen-code-ci-bot Date: Tue, 22 Sep 2026 23:37:53 +0000 Subject: [PATCH 07/49] fix: address code-mode review feedback on exec binding narrowing and docs - Honor exact and server-level MCP names in the hybrid nested binding shortcut: any MCP entry in the execution allowlist now sends MCP tool names through the exact-name and pattern checks, so an ungranted server's tools are no longer admitted as nested bindings. - Qualify CodeModeOnly's eager-deferral immunity to the session surface across the design docs, settings descriptions, and SDK prose; AgentCore surfaces narrow the nested binding set by their own allowlists. Pin the boundary with a CodeModeOnly registry test. - State the exec-registered precondition in the SDK's hybrid nested schema guarantee, and retract the outdated "not offered to the model" wording from the settings descriptions to match the SDK. - Only promise nested schemas below in the exec description when uncovered bindings actually follow. - Resolve the image-overview nested zoom hint against the calling agent's narrowed binding set, threaded from the request through the scheduler as an ambient allowlist; pin the zoom-declared and agent-narrowed cases. - Drop the /context builtin-clamp compensation block that the declared-only billing guard made unreachable, and repurpose its test to pin declared-MCP billing; drop the hybrid skill-reminder test that duplicated the direct-mode case. --- docs/design/code-mode.md | 7 +- docs/design/code-mode.zh-CN.md | 5 +- docs/users/configuration/settings.md | 60 ++++++------- packages/cli/src/config/settingsSchema.ts | 6 +- .../src/ui/commands/contextCommand.test.ts | 23 ++--- .../cli/src/ui/commands/contextCommand.ts | 44 ++++----- .../runtime/agent-core.skill-gate.test.ts | 86 ++++++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 24 +++-- packages/core/src/code-mode/code-mode.test.ts | 28 ++++++ .../core/src/core/coreToolScheduler.test.ts | 36 -------- packages/core/src/core/coreToolScheduler.ts | 89 ++++++++++--------- packages/core/src/core/turn.ts | 6 +- packages/core/src/tools/code-mode.ts | 4 +- .../core/src/utils/code-mode-allowed-names.ts | 28 ++++++ packages/core/src/utils/fileUtils.test.ts | 52 ++++++++--- packages/core/src/utils/fileUtils.ts | 8 +- packages/sdk-typescript/README.md | 42 ++++----- packages/sdk-typescript/src/types/types.ts | 27 +++--- .../schemas/settings.schema.json | 6 +- 19 files changed, 368 insertions(+), 213 deletions(-) create mode 100644 packages/core/src/utils/code-mode-allowed-names.ts diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index 12d79d40ed1..6dc1b4ff5d1 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -65,8 +65,11 @@ When either bridge half is absent or the agent surface is filtered, `exec` includes signatures for nested tools whose schemas are otherwise unavailable. In `code_mode_only`, all nested declarations live in the `exec` description. Both bridge tools are hidden, deferred reminders and the incomplete-bridge -warning are skipped, and `tools.eager` / `tools.visible` do not reduce those -nested schemas. Callable tools remain available through `exec`. +warning are skipped, and on the session surface `tools.eager` / +`tools.visible` do not reduce those nested schemas. Callable tools remain +available through `exec`. An AgentCore surface (subagent, headless agent, +arena) narrows the nested binding set by its own allowlist, so a tool demoted +by `tools.eager` has no nested binding there. Nested bindings prefer an exact canonical JavaScript name over names rewritten to that property. Other collisions retain canonical-name ordering; omitted diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index d4ddc349aeb..4ea04977a86 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -59,9 +59,10 @@ CodeModeOnly。 任一桥接工具缺失或智能体调用面经过过滤时,`exec` 会为无法从其他途径取得 schema 的嵌套工具附上签名。在 `code_mode_only` 中,所有嵌套声明集中在 `exec` -描述中;两个桥接工具都被隐藏,延迟提醒和桥接不完整的警告被跳过。 +描述中;两个桥接工具都被隐藏,延迟提醒和桥接不完整的警告被跳过。在会话层, `tools.eager` 和 `tools.visible` 不会减少这些嵌套 schema,仍可调用的工具继续 -通过 `exec` 使用。 +通过 `exec` 使用。AgentCore 层(subagent、headless agent、arena)会按自身的 +allowlist 收窄嵌套绑定集合,因此被 `tools.eager` 降级的工具在该层没有嵌套绑定。 嵌套绑定优先保留与 JavaScript 属性精确一致的规范名称,再考虑改写为该属性的 名称。其他碰撞沿用规范名称字典序;被省略的绑定不出现在嵌套签名中, diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 1e2e1c8096e..4270cab0879 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -374,36 +374,36 @@ If you are experiencing performance issues with file searching (e.g., with `@` c #### tools -| Setting | Type | Description | Default | Notes | -| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | -| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | -| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. When unset, explicit one-shot prompts use `child_process`; interactive TUI, ACP, stream-json input, stdin-only, and file-input sessions use PTY. Platform and availability fallbacks to `child_process` still apply. | mode-based | | -| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | -| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | -| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message`, `tool_search` and `tool_call` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay reachable through `tool_search` + `tool_call` while both bridge tools are registered), and `permissions.deny` to block tools outright. | `undefined` | | -| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | -| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring the ToolSearch + ToolCall bridge. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in `exec` and hides both bridge tools. Merged as a union across scopes. | `undefined` | | -| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, and reachable through the `tool_search` + `tool_call` bridge. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — `tools.toolSearch.enabled: false` (which denies both), a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session (they stay registered and in `/tools`, a direct call by their own name is still evaluated and approved normally, and a warning is logged) — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Use `permissions.deny` if you meant to remove them, or keep both bridge tools registered. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. In Code Mode, withheld tools with actual nested bindings also remain callable through `exec`, and the warning names that subset. Code Mode Only hides both bridge tools, keeps full nested schemas for callable tools in `exec`, and skips deferred reminders and this warning; `tools.eager` and `tools.visible` do not save schema tokens there. | `undefined` | | -| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | -| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. Code Mode Only ignores eager/visible schema deferral and includes full nested schemas for callable tools. | `direct` | Experimental. Requires restart. | -| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | -| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is reachable through `tool_search` + `tool_call` while both bridge tools are registered, but its schema is not sent in the initial model request. | `undefined` | | -| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | -| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | -| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | -| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | -| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | -| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | -| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | -| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | -| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | -| `tools.toolSearch.enabled` | boolean | Review deferred tool schemas through ToolSearch and invoke them through the stable ToolCall bridge. Bridge review and invocation keep the tool list stable — the bridge never re-declares what it reveals — reducing prompt size without touching the prompt-cache prefix. The declaration list is not immutable, though: a session still re-declares on resume, whenever a tool-set refresh (MCP discovery, the first plan-mode entry in a session, a subagent definition change) finds a direct call to a still-hidden deferred tool in the live history, when a subagent definition change rewrites the agent tool's own description, and when an MCP server registers mid-session with `alwaysLoadTools: true`. | `true` | Requires restart: Yes | -| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to `0`, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one `tool_search` round trip before first use. Raise it to `N` so that, when every eligible deferred schema fits within `N`% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by `tools.eager` are excluded from this preload and stay reachable on demand through that bridge while it is registered. Separate paths can still declare deferred tools at `0`: `tools.visible`; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP's late registration, which explicitly reveals and pins `create_sub_session`. | `0` | Requires restart: Yes | -| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | -| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | +| Setting | Type | Description | Default | Notes | +| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | +| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | +| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. When unset, explicit one-shot prompts use `child_process`; interactive TUI, ACP, stream-json input, stdin-only, and file-input sessions use PTY. Platform and availability fallbacks to `child_process` still apply. | mode-based | | +| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | +| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | +| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message`, `tool_search` and `tool_call` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay reachable through `tool_search` + `tool_call` while both bridge tools are registered), and `permissions.deny` to block tools outright. | `undefined` | | +| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | +| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring the ToolSearch + ToolCall bridge. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in `exec` and hides both bridge tools. Merged as a union across scopes. | `undefined` | | +| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, and reachable through the `tool_search` + `tool_call` bridge. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — `tools.toolSearch.enabled: false` (which denies both), a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session (they stay registered and in `/tools`, a direct call by their own name is still evaluated and approved normally, and a warning is logged) — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Use `permissions.deny` if you meant to remove them, or keep both bridge tools registered. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. In Code Mode, withheld tools with actual nested bindings also remain callable through `exec`, and the warning names that subset. Code Mode Only hides both bridge tools, keeps full nested schemas for callable tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` and `tools.visible` do not save schema tokens there, while agent surfaces narrow the nested binding set by their own allowlists. | `undefined` | | +| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | +| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. Code Mode Only ignores eager/visible schema deferral on the session surface and includes full nested schemas for callable tools there; agent surfaces (subagents, headless agents, arena runs) narrow the nested binding set by their own allowlists, so a tool demoted by `tools.eager` has no nested binding there. | `direct` | Experimental. Requires restart. | +| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | +| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is reachable through `tool_search` + `tool_call` while both bridge tools are registered, but its schema is not sent in the initial model request. | `undefined` | | +| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | +| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | +| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | +| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | +| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | +| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | +| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | +| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | +| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | +| `tools.toolSearch.enabled` | boolean | Review deferred tool schemas through ToolSearch and invoke them through the stable ToolCall bridge. Bridge review and invocation keep the tool list stable — the bridge never re-declares what it reveals — reducing prompt size without touching the prompt-cache prefix. The declaration list is not immutable, though: a session still re-declares on resume, whenever a tool-set refresh (MCP discovery, the first plan-mode entry in a session, a subagent definition change) finds a direct call to a still-hidden deferred tool in the live history, when a subagent definition change rewrites the agent tool's own description, and when an MCP server registers mid-session with `alwaysLoadTools: true`. | `true` | Requires restart: Yes | +| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to `0`, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one `tool_search` round trip before first use. Raise it to `N` so that, when every eligible deferred schema fits within `N`% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by `tools.eager` are excluded from this preload and stay reachable on demand through that bridge while it is registered. Separate paths can still declare deferred tools at `0`: `tools.visible`; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP's late registration, which explicitly reveals and pins `create_sub_session`. | `0` | Requires restart: Yes | +| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | +| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | > [!note] > diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 1a100ed3a35..fc837732bde 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -2771,7 +2771,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: ToolMode.Direct, description: - 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral: callable tools retain full nested schemas and tool_search is hidden.', + 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent surfaces narrow nested bindings by their own allowlists.', showInDialog: true, options: [ { value: ToolMode.Direct, label: 'Default' }, @@ -2892,7 +2892,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: 0, description: - 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', + 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', showInDialog: true, // A percentage of the context window: values above 100 would set a // budget larger than the window and unconditionally preload every @@ -3074,7 +3074,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string[] | undefined, description: - 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', + 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', showInDialog: false, }, approvalMode: { diff --git a/packages/cli/src/ui/commands/contextCommand.test.ts b/packages/cli/src/ui/commands/contextCommand.test.ts index 99ade70193d..2852f9fbec0 100644 --- a/packages/cli/src/ui/commands/contextCommand.test.ts +++ b/packages/cli/src/ui/commands/contextCommand.test.ts @@ -1015,13 +1015,10 @@ describe('collectContextData (contextCommand)', () => { expect(sumRows(data.breakdown)).toBe(100_000); }); - it('charges the builtin-clamp deficit to the mcp row, not to messages', async () => { - // Under `tools.codeModeOnly` the declarations collapse to a few control - // tools while an `alwaysLoadTools` MCP server still bills every schema - // the detail loop sees, so the billed tools exceed the declared ones and - // `displayBuiltinTools` clamps at 0. The clamp deficit must come out of - // the mcp row — the row whose billing overshoots the declarations; - // otherwise `attributedOverhead` silently takes it out of `messages`. + it('bills the declared mcp schema to the mcp row, not to messages', async () => { + // The detail loop bills only declared tools, so a declared MCP schema + // lands on the mcp row and the rows must still partition the provider + // total exactly: `messages` absorbs only the calibrated remainder. // Own value properties shadow the prototype's getters (Object.assign // would trip the setter-less `schema` accessor on DeclarativeTool). const mcpToolDouble = Object.defineProperties( @@ -1040,7 +1037,7 @@ describe('collectContextData (contextCommand)', () => { }, ) as DiscoveredMCPTool; const tools = [skillToolDouble, mcpToolDouble]; - const declared = [skillToolSchema]; + const declared = [skillToolSchema, mcpToolDouble.schema]; const history = [prelude, ...conversation]; const unscaled = await collectContextData( @@ -1060,12 +1057,10 @@ describe('collectContextData (contextCommand)', () => { false, ); - // The fixture does put the clamp in force: billed skill definition plus - // mcp schemas exceed the declared tools. - expect( - estimateContextTextTokens(JSON.stringify(skillToolSchema)) + - estimateContextTextTokens(JSON.stringify(mcpToolDouble.schema)), - ).toBeGreaterThan(estimateContextTextTokens(JSON.stringify(declared))); + // The mcp schema is declared, so the guard bills it to the mcp row. + expect(data.breakdown.mcpTools).toBe( + estimateContextTextTokens(JSON.stringify(mcpToolDouble.schema)), + ); expect(data.breakdown.messages).toBe(300); expect(sumRows(data.breakdown)).toBe(total); }); diff --git a/packages/cli/src/ui/commands/contextCommand.ts b/packages/cli/src/ui/commands/contextCommand.ts index cc6ca12a7cb..8f103894d27 100644 --- a/packages/cli/src/ui/commands/contextCommand.ts +++ b/packages/cli/src/ui/commands/contextCommand.ts @@ -607,15 +607,20 @@ export async function collectContextData( let detailMemoryFiles: ContextMemoryDetail[]; let detailSkills: ContextSkillDetail[]; + // The per-tool loop bills only declared tools, so the Skill definition and + // the MCP schemas can exceed `allToolsTokens` only by estimator rounding; + // floor the builtin remainder at zero. + const builtinToolsTokens = Math.max( + 0, + allToolsTokens - skillToolDefinitionTokens - mcpToolsTotalTokens, + ); + if (!hasTokenCount) { totalTokens = 0; displaySystemPrompt = systemPromptTokens; displaySkills = skillsTokens; displayStartupContext = startupContextTokens; - displayBuiltinTools = Math.max( - 0, - allToolsTokens - skillToolDefinitionTokens - mcpToolsTotalTokens, - ); + displayBuiltinTools = builtinToolsTokens; displayMcpTools = mcpToolsTotalTokens; displayMemoryFiles = memoryFilesTokens; messagesTokens = 0; @@ -648,32 +653,15 @@ export async function collectContextData( // overshoot is absorbed by the `messages` cap below. const scale = rawOverhead > totalTokens ? totalTokens / rawOverhead : 1; - // `displayBuiltinTools` floors at 0, so when the billed Skill definition and - // the MCP schemas together exceed the declared tool list, that excess would - // be charged to the overhead and taken straight back out of `messages`. - // Charge it to `mcpTools`, and charge whatever the MCP schemas cannot absorb - // to the Skill definition `skills` carries, so the three rows still account - // for exactly `allToolsTokens` plus the listing and the loaded bodies. - const clampDeficit = Math.max( - 0, - skillToolDefinitionTokens + mcpToolsTotalTokens - allToolsTokens, - ); - const clampedMcpTools = Math.max(0, mcpToolsTotalTokens - clampDeficit); - const clampedSkills = - skillsTokens - Math.max(0, clampDeficit - mcpToolsTotalTokens); - const clampedBuiltinTools = Math.max( - 0, - allToolsTokens - skillToolDefinitionTokens - clampedMcpTools, - ); - // The clamped categories partition `rawOverhead` before scaling. Flooring - // each share keeps their sum at or below `totalTokens`; independently - // rounding them can overshoot the total by a token with no negative row - // available to absorb the excess. + // The categories partition `rawOverhead` before scaling. Flooring each + // share keeps their sum at or below `totalTokens`; independently rounding + // them can overshoot the total by a token with no negative row available + // to absorb the excess. displaySystemPrompt = Math.floor(systemPromptTokens * scale); - displayBuiltinTools = Math.floor(clampedBuiltinTools * scale); - displayMcpTools = Math.floor(clampedMcpTools * scale); + displayBuiltinTools = Math.floor(builtinToolsTokens * scale); + displayMcpTools = Math.floor(mcpToolsTotalTokens * scale); displayMemoryFiles = Math.floor(memoryFilesTokens * scale); - displaySkills = Math.floor(clampedSkills * scale); + displaySkills = Math.floor(skillsTokens * scale); displayStartupContext = Math.floor(startupContextTokens * scale); const attributedOverhead = diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index eca8fa444e3..05f756bbca5 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -519,6 +519,92 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual(['mcp__github__read_file']); }); + it('honors an exact MCP tool name in the hybrid nested binding set', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + const readTool = new MockTool({ name: 'mcp__github__read_file' }); + Object.assign(readTool, { + serverName: 'github', + serverToolName: 'read_file', + }); + const deleteTool = new MockTool({ name: 'mcp__github__delete_repo' }); + Object.assign(deleteTool, { + serverName: 'github', + serverToolName: 'delete_repo', + }); + registry.registerTool(readTool); + registry.registerTool(deleteTool); + const core = new AgentCore( + 'mcp-exact-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC, 'mcp__github__read_file'], + executionAllowedTools: [ToolNames.EXEC, 'mcp__github__read_file'], + }, + ); + + await core.prepareTools(); + + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual(['mcp__github__read_file']); + }); + + it('honors a server-level MCP name in the hybrid nested binding set', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + const readTool = new MockTool({ name: 'mcp__github__read_file' }); + Object.assign(readTool, { + serverName: 'github', + serverToolName: 'read_file', + }); + const createTool = new MockTool({ name: 'mcp__github__create_issue' }); + Object.assign(createTool, { + serverName: 'github', + serverToolName: 'create_issue', + }); + const chargeTool = new MockTool({ name: 'mcp__payments__charge' }); + Object.assign(chargeTool, { + serverName: 'payments', + serverToolName: 'charge', + }); + registry.registerTool(readTool); + registry.registerTool(createTool); + registry.registerTool(chargeTool); + const core = new AgentCore( + 'mcp-server-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC, 'mcp__github'], + executionAllowedTools: [ToolNames.EXEC, 'mcp__github'], + }, + ); + + await core.prepareTools(); + + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual(['mcp__github__read_file', 'mcp__github__create_issue']); + }); + it('keeps inherited CodeMode declarations executable only when directly allowed', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index d84c2ae7dc6..82b53fd37bf 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -1757,10 +1757,12 @@ export class AgentCore { forNestedBinding && isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && // An MCP tool name must fall through to the exact-name and pattern - // checks below: they are the only place a server-level narrowing in - // the allowlist can be honored. + // checks below once the allowlist mentions MCP at all: they are the + // only place a server-level or exact-tool narrowing can be honored. (!toolName.startsWith('mcp__') || - (this.executionAllowedMcpPatterns?.length ?? 0) === 0) && + !this.executionAllowedTools?.some((name) => + name.startsWith('mcp__'), + )) && this.executionAllowedExactTools?.has(ToolNames.EXEC) && getToolExposure(toolName) === 'code-mode-callable' ) { @@ -2393,12 +2395,16 @@ export class AgentCore { prompt_id: promptId, response_id: responseId, wasOutputTruncated, - ...(toolName === ToolNames.EXEC && - isCodeModeEnabled(this.runtimeContext.getToolMode?.()) - ? { - codeModeAllowedToolNames: this.codeModeAllowedToolNames ?? [], - } - : {}), + // The narrowed binding set rides on every code-mode agent request: + // exec dispatch gates on it, and the scheduler exposes it as the + // ambient allowlist so reachability hints resolve against the + // surface this agent actually received. + ...(this.codeModeAllowedToolNames !== undefined + ? { codeModeAllowedToolNames: this.codeModeAllowedToolNames } + : toolName === ToolNames.EXEC && + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) + ? { codeModeAllowedToolNames: [] } + : {}), }; if (canonicalToolName(toolName) === ToolNames.TOOL_CALL) { diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index 8a40865e5c2..15a1cdd8cc4 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -249,6 +249,9 @@ describe('code mode exposure', () => { ]); expect(declarations[0]?.description).toContain('"name":"read_file"'); expect(declarations[0]?.description).not.toContain('"name":"write_file"'); + // Every binding is already declared top-level, so no schema section + // follows: the description must not promise one. + expect(declarations[0]?.description).not.toContain('declared below'); expect(declarations[1]?.description).toContain( 'declare const tools: { read_file(args:', ); @@ -424,6 +427,31 @@ describe('code mode exposure', () => { expect(declarations[0]?.description).not.toContain('tools.write_file'); }); + it('keeps a permission-deferred binding on the session surface but not on a filtered one', async () => { + // The eager-deferral immunity the docs promise holds on the session + // surface only: an AgentCore surface (subagent, headless agent, arena) + // narrows the nested binding set by its own allowlist, so a tool demoted + // by `tools.eager` has no nested binding there. + const registry = new ToolRegistry( + makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), + ); + registry.registerTool(new MockTool({ name: 'exec' })); + registry.registerPermissionDeferredFactory( + 'write_file', + async () => new MockTool({ name: 'write_file' }), + ); + await registry.warmAll(); + + const sessionDescription = registry + .getFunctionDeclarations() + .find((item) => item.name === 'exec')?.description; + expect(sessionDescription).toContain('tools.write_file(args:'); + + const declarations = registry.getFunctionDeclarationsFiltered(['exec']); + expect(declarations.map((item) => item.name)).toEqual(['exec']); + expect(declarations[0]?.description).not.toContain('write_file'); + }); + it('keeps exec structured across Gemini, OpenAI, and Anthropic tool conversion', async () => { const registry = new ToolRegistry( makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }), diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 0004aaf3ecb..34594dd5588 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -20556,42 +20556,6 @@ describe('CoreToolScheduler activation wiring', () => { ); }); - it('defers to declared invocation surfaces in hybrid code mode', async () => { - const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); - const { scheduler, onAllToolCallsComplete } = - buildSchedulerWithSkillManager({ - matchAndActivateByPaths, - skillToolPresent: true, - toolMode: 'code_mode', - }); - - await scheduler.schedule( - [ - { - callId: '1', - name: ToolNames.READ_FILE, - args: { file_path: '/proj/src/App.tsx' }, - isClientInitiated: false, - prompt_id: 'p1', - }, - ], - new AbortController().signal, - ); - - const completed = onAllToolCallsComplete.mock.calls[0][0] as ToolCall[]; - expect(completed[0].status).toBe('success'); - const responseText = getResponseText(completed[0]); - expect(responseText).toContain( - 'Load a skill by name using the tool interface declared in this session', - ); - expect(responseText).not.toContain( - 'pass its name to the top-level Skill tool', - ); - expect(responseText).not.toContain( - "await tools.skill({ skill: '' })", - ); - }); - it('defers to declared invocation surfaces in code_mode_only', async () => { const matchAndActivateByPaths = vi.fn().mockResolvedValue(['tsx-helper']); const { scheduler, onAllToolCallsComplete } = diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index 6e56af06dec..d588a2607cc 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -228,6 +228,7 @@ import { runWithToolCallSource, type CodeModeToolResult, } from '../code-mode/tool-call-runtime.js'; +import { runWithCodeModeAllowedNames } from '../utils/code-mode-allowed-names.js'; import { isCodeModeToolCallAllowed, ToolMode } from '../tools/code-mode.js'; const debugLogger = createDebugLogger('TOOL_SCHEDULER'); @@ -5604,26 +5605,30 @@ export class CoreToolScheduler { setPromoteAbortControllerCallback, canPromoteForegroundShell, ); - return scheduledCall.request.name === ToolNames.EXEC - ? runWithToolCallRuntime( - { - parentCallId: callId, - allowedToolNames: - scheduledCall.request.codeModeAllowedToolNames, - dispatch: (name, args, nestedSignal, onResult) => - this.dispatchCodeModeTool( - name, - args, - scheduledCall.request, - nestedSignal, - onResult, - ), - }, - execute, - ) - : scheduledCall.request.source === 'code_mode' - ? runWithToolCallSource({ kind: 'code_mode' }, execute) - : execute(); + return runWithCodeModeAllowedNames( + scheduledCall.request.codeModeAllowedToolNames, + () => + scheduledCall.request.name === ToolNames.EXEC + ? runWithToolCallRuntime( + { + parentCallId: callId, + allowedToolNames: + scheduledCall.request.codeModeAllowedToolNames, + dispatch: (name, args, nestedSignal, onResult) => + this.dispatchCodeModeTool( + name, + args, + scheduledCall.request, + nestedSignal, + onResult, + ), + }, + execute, + ) + : scheduledCall.request.source === 'code_mode' + ? runWithToolCallSource({ kind: 'code_mode' }, execute) + : execute(), + ); }), ); } else { @@ -5645,26 +5650,30 @@ export class CoreToolScheduler { liveOutputCallback, shellExecutionConfig, ); - return scheduledCall.request.name === ToolNames.EXEC - ? runWithToolCallRuntime( - { - parentCallId: callId, - allowedToolNames: - scheduledCall.request.codeModeAllowedToolNames, - dispatch: (name, args, nestedSignal, onResult) => - this.dispatchCodeModeTool( - name, - args, - scheduledCall.request, - nestedSignal, - onResult, - ), - }, - execute, - ) - : scheduledCall.request.source === 'code_mode' - ? runWithToolCallSource({ kind: 'code_mode' }, execute) - : execute(); + return runWithCodeModeAllowedNames( + scheduledCall.request.codeModeAllowedToolNames, + () => + scheduledCall.request.name === ToolNames.EXEC + ? runWithToolCallRuntime( + { + parentCallId: callId, + allowedToolNames: + scheduledCall.request.codeModeAllowedToolNames, + dispatch: (name, args, nestedSignal, onResult) => + this.dispatchCodeModeTool( + name, + args, + scheduledCall.request, + nestedSignal, + onResult, + ), + }, + execute, + ) + : scheduledCall.request.source === 'code_mode' + ? runWithToolCallSource({ kind: 'code_mode' }, execute) + : execute(), + ); }), ); } diff --git a/packages/core/src/core/turn.ts b/packages/core/src/core/turn.ts index 810c4755637..68f6d3337c7 100644 --- a/packages/core/src/core/turn.ts +++ b/packages/core/src/core/turn.ts @@ -198,7 +198,11 @@ export interface ToolCallRequestInfo { /** Parent model tool call for a programmatically dispatched child call. */ parentCallId?: string; source?: 'model' | 'code_mode'; - /** Exact tools an exec call may dispatch for a restricted agent. */ + /** + * The owning agent's narrowed nested binding set: exec dispatch gates on + * it, and the scheduler exposes it as the ambient allowlist for + * reachability hints. + */ codeModeAllowedToolNames?: readonly string[]; } diff --git a/packages/core/src/tools/code-mode.ts b/packages/core/src/tools/code-mode.ts index 2f43519a785..278f40b0364 100644 --- a/packages/core/src/tools/code-mode.ts +++ b/packages/core/src/tools/code-mode.ts @@ -269,7 +269,9 @@ export function buildExecDescription( 'Nested tool declarations for directly exposed tools are included in their top-level tool descriptions.', hasToolCallBridge ? 'With both tool_search and tool_call available, tool_search returns deferred parameter schemas without changing top-level declarations. Match the returned schema name exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, do not normalize or guess a binding; use tool_call outside exec, or an available direct tool, subject to normal validation and approval.' - : 'Other nested parameter schemas are declared below. Match tool names exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, the tool has no nested binding; do not normalize or guess one.', + : uncoveredBindings.length === 0 + ? '' + : 'Other nested parameter schemas are declared below. Match tool names exactly to ALL_TOOLS.name, then call tools[entry.jsName] with arguments shaped by that schema. If no entry matches, the tool has no nested binding; do not normalize or guess one.', uncoveredBindings.map(describeBinding).join('\n'), ] .filter(Boolean) diff --git a/packages/core/src/utils/code-mode-allowed-names.ts b/packages/core/src/utils/code-mode-allowed-names.ts new file mode 100644 index 00000000000..b25e9de19fd --- /dev/null +++ b/packages/core/src/utils/code-mode-allowed-names.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; + +const storage = new AsyncLocalStorage(); + +// Nested-binding reachability is per-agent: the session-wide binding plan +// can hold bindings the calling agent's exec surface does not. An `undefined` +// store leaves the ambient set untouched so tools scheduled from a parent +// exec keep its allowlist. +export function runWithCodeModeAllowedNames( + allowedNames: readonly string[] | undefined, + callback: () => T, +): T { + return allowedNames === undefined + ? callback() + : storage.run(allowedNames, callback); +} + +export function getCurrentCodeModeAllowedNames(): + | readonly string[] + | undefined { + return storage.getStore(); +} diff --git a/packages/core/src/utils/fileUtils.test.ts b/packages/core/src/utils/fileUtils.test.ts index 5a0064e8194..51a52be72fe 100644 --- a/packages/core/src/utils/fileUtils.test.ts +++ b/packages/core/src/utils/fileUtils.test.ts @@ -41,6 +41,7 @@ import { iconvEncode } from './iconvHelper.js'; import { LargeNonUtf8TextError } from './read-text-range.js'; import type { Config } from '../config/config.js'; import { ToolMode } from '../tools/code-mode.js'; +import { runWithCodeModeAllowedNames } from './code-mode-allowed-names.js'; import { StandardFileSystemService } from '../services/fileSystemService.js'; import { ToolErrorType } from '../tools/tool-error.js'; import { @@ -1415,6 +1416,7 @@ describe('fileUtils', () => { declared: string[]; deferred: string[]; bindings: string[]; + allowedNames?: string[]; hint: string; }>([ { @@ -1475,6 +1477,27 @@ describe('fileUtils', () => { bindings: ['zoom_image'], hint: '', })), + { + // A declared zoom_image is directly callable: the guidance must not + // route it through exec. + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared: ['read_file', 'exec', 'zoom_image'], + deferred: [], + bindings: ['zoom_image'], + hint: ' If details are too small, call zoom_image with coordinates normalized from 0 to 1000.', + }, + { + // The session plan binds zoom_image, but the calling agent's + // narrowed plan does not: the guidance must not advertise it. + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared: ['read_file', 'exec'], + deferred: ['zoom_image'], + bindings: ['zoom_image'], + allowedNames: ['read_file'], + hint: '', + }, ])( 'uses only exposed tools for image guidance: $declared, code mode $codeModeOnly', async ({ @@ -1483,6 +1506,7 @@ describe('fileUtils', () => { declared, deferred, bindings, + allowedNames, hint, }) => { await sharp({ @@ -1491,19 +1515,23 @@ describe('fileUtils', () => { .png() .toFile(testImageFilePath); mockMimeGetType.mockReturnValue('image/png'); - const result = await processSingleFileContent(testImageFilePath, { - ...mockConfig, - getCodeModeOnly: () => codeModeOnly, - getToolMode: () => toolMode, - getToolRegistry: () => ({ - getFunctionDeclarations: () => declared.map((name) => ({ name })), - getDeferredToolSummary: () => deferred.map((name) => ({ name })), - getCodeModeBindingPlan: () => ({ - bindings: bindings.map((name) => ({ name })), - collisions: [], + const result = await runWithCodeModeAllowedNames(allowedNames, () => + processSingleFileContent(testImageFilePath, { + ...mockConfig, + getCodeModeOnly: () => codeModeOnly, + getToolMode: () => toolMode, + getToolRegistry: () => ({ + getFunctionDeclarations: () => declared.map((name) => ({ name })), + getDeferredToolSummary: () => deferred.map((name) => ({ name })), + getCodeModeBindingPlan: (allowed?: ReadonlySet) => ({ + bindings: bindings + .filter((name) => !allowed || allowed.has(name)) + .map((name) => ({ name })), + collisions: [], + }), }), - }), - } as unknown as Config); + } as unknown as Config), + ); const parts = result.llmContent as Part[]; expect(parts[0]).toEqual({ text: `Image overview: 20x10; oriented source: 20x10.${hint}`, diff --git a/packages/core/src/utils/fileUtils.ts b/packages/core/src/utils/fileUtils.ts index 9a33c9a0639..eb00d59c2c0 100644 --- a/packages/core/src/utils/fileUtils.ts +++ b/packages/core/src/utils/fileUtils.ts @@ -35,6 +35,7 @@ import { shouldRequirePDFPageRange, } from './pdf.js'; import { VISION_BRIDGE_MAX_IMAGES } from './vision-bridge-constants.js'; +import { getCurrentCodeModeAllowedNames } from './code-mode-allowed-names.js'; import type { VisionBridgePdfContinuation } from '../services/visionBridge/vision-bridge-service.js'; import { extensionForMimeType, @@ -1670,9 +1671,14 @@ export async function processSingleFileContent( declaredTools.has('exec') && !zoomDeclared && !hasToolCallBridge); + const ambientAllowedNames = getCurrentCodeModeAllowedNames(); const zoomAvailable = useNestedZoom ? registry - ?.getCodeModeBindingPlan() + ?.getCodeModeBindingPlan( + ambientAllowedNames === undefined + ? undefined + : new Set(ambientAllowedNames), + ) .bindings.some((binding) => binding.name === 'zoom_image') : zoomDeclared || (hasToolCallBridge && diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index e3e9feb9b17..493b97376c1 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; `tools.eager` does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, while `exec` itself is registered (container execution warns and falls back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index 05dcade9606..2aa3da71342 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -431,11 +431,14 @@ export interface QueryOptions { * refresh (resume, MCP discovery, the first plan-mode entry in a * session, a subagent definition change) re-declares. * These bridge and warning rules apply to direct and hybrid code modes. - * In hybrid mode, exec retains callable nested bindings; their schemas are - * included in exec when either bridge tool is unavailable. CodeModeOnly - * hides both bridge tools, includes callable deferred tools' full schemas - * in exec, and skips deferred reminders and this warning; tools.eager does - * not make those nested tools unreachable or reduce their schema tokens. + * In hybrid mode, while `exec` itself is registered (container execution + * warns and falls back to direct tools without it), exec retains callable + * nested bindings; their schemas are included in exec when either bridge + * tool is unavailable. CodeModeOnly hides both bridge tools, includes + * callable deferred tools' full schemas in exec, and skips deferred + * reminders and this warning; on the session surface tools.eager does not + * make those nested tools unreachable or reduce their schema tokens, while + * agent surfaces narrow the nested binding set by their own allowlists. * Tools already deferred by default remain * on demand even when listed; `tools.visible` surfaces one at startup. The * allowlist does not affect MCP tools, the `--json-schema` @@ -504,11 +507,15 @@ export interface QueryOptions { * tool-set refresh (resume, MCP discovery, the first plan-mode * entry in a session, a subagent definition change) re-declares (#9827). * These bridge and warning rules apply to direct and hybrid code modes. - * In hybrid mode, exec retains callable nested bindings; their schemas are - * included in exec when either bridge tool is unavailable. CodeModeOnly - * hides both bridge tools, includes callable deferred tools' full schemas - * in exec, and skips deferred reminders and this warning; tools.eager does - * not make those nested tools unreachable or reduce their schema tokens. + * In hybrid mode, while `exec` itself is registered (container + * execution warns and falls back to direct tools without it), exec + * retains callable nested bindings; their schemas are included in + * exec when either bridge tool is unavailable. CodeModeOnly hides + * both bridge tools, includes callable deferred tools' full schemas + * in exec, and skips deferred reminders and this warning; on the + * session surface tools.eager does not make those nested tools + * unreachable or reduce their schema tokens, while agent surfaces + * narrow the nested binding set by their own allowlists. * * **Pattern matching:** * - Tool name: `'write_file'` diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 95819cdf345..f49dda0ae21 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1314,7 +1314,7 @@ "description": "Linux tool execution confinement. Operator scopes only; workspace settings cannot override it. Model/auth/session traffic stays on the host." }, "mode": { - "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral: callable tools retain full nested schemas and tool_search is hidden. Options: direct, code_mode, code_mode_only", + "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent surfaces narrow nested bindings by their own allowlists. Options: direct, code_mode, code_mode_only", "enum": [ "direct", "code_mode", @@ -1382,7 +1382,7 @@ "minimum": 0, "maximum": 100, "default": 0, - "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." + "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." } } }, @@ -1475,7 +1475,7 @@ } }, "eager": { - "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; tools.eager does not make them unreachable or save their schema tokens. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", + "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", "type": "array", "items": { "type": "string" From 34711cfe7e7e7438677b17213c976e904b3d304f Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:00:59 +0800 Subject: [PATCH 08/49] fix(core): avoid unverified agent zoom hints and clarify tool exposure --- docs/design/code-mode.md | 12 ++-- docs/design/code-mode.zh-CN.md | 9 +-- docs/developers/sdk-typescript.md | 42 ++++++------- docs/users/configuration/settings.md | 60 +++++++++---------- packages/cli/src/config/settingsSchema.ts | 6 +- packages/core/src/utils/fileUtils.test.ts | 17 ++++++ packages/core/src/utils/fileUtils.ts | 4 +- packages/sdk-typescript/README.md | 42 ++++++------- packages/sdk-typescript/src/types/types.ts | 16 +++-- .../schemas/settings.schema.json | 6 +- 10 files changed, 122 insertions(+), 92 deletions(-) diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index 6dc1b4ff5d1..7921249f9b5 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -68,8 +68,8 @@ Both bridge tools are hidden, deferred reminders and the incomplete-bridge warning are skipped, and on the session surface `tools.eager` / `tools.visible` do not reduce those nested schemas. Callable tools remain available through `exec`. An AgentCore surface (subagent, headless agent, -arena) narrows the nested binding set by its own allowlist, so a tool demoted -by `tools.eager` has no nested binding there. +arena) excludes tools hidden by `tools.eager` from its nested bindings and +applies the agent allowlist rules below. Nested bindings prefer an exact canonical JavaScript name over names rewritten to that property. Other collisions retain canonical-name ordering; omitted @@ -77,9 +77,11 @@ bindings remain absent from nested signatures and are never advertised as reachable through `exec`. Filtered subagent declarations preserve the same mode. The agent's `tools` -list narrows its direct surface. Explicit ordinary-tool execution entries -narrow the nested set, while an inherited or explicitly allowed `exec` carries -all surviving code-mode-callable bindings. +list narrows its direct surface. Agent allowlists that do not grant `exec` +narrow nested bindings. Inheriting or explicitly granting `exec` keeps all +otherwise admitted ordinary code-mode-callable bindings. An execution +allowlist that mentions any MCP tool additionally restricts MCP bindings to +matching exact names or server patterns. ## Constraints and risks diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 4ea04977a86..5a10a2f51d3 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -61,16 +61,17 @@ CodeModeOnly。 schema 的嵌套工具附上签名。在 `code_mode_only` 中,所有嵌套声明集中在 `exec` 描述中;两个桥接工具都被隐藏,延迟提醒和桥接不完整的警告被跳过。在会话层, `tools.eager` 和 `tools.visible` 不会减少这些嵌套 schema,仍可调用的工具继续 -通过 `exec` 使用。AgentCore 层(subagent、headless agent、arena)会按自身的 -allowlist 收窄嵌套绑定集合,因此被 `tools.eager` 降级的工具在该层没有嵌套绑定。 +通过 `exec` 使用。AgentCore 层(subagent、headless agent、arena)会从嵌套绑定中 +排除被 `tools.eager` 隐藏的工具,并应用下文的智能体 allowlist 规则。 嵌套绑定优先保留与 JavaScript 属性精确一致的规范名称,再考虑改写为该属性的 名称。其他碰撞沿用规范名称字典序;被省略的绑定不出现在嵌套签名中, 也不会被警告描述为可通过 `exec` 调用。 经过过滤的子智能体声明沿用相同模式。智能体的 `tools` 列表会收窄直接调用面。 -显式列出的普通工具执行项(`executionAllowedTools`)会收窄嵌套集合;继承或显式 -允许的 `exec` 则携带所有仍可用的 code-mode-callable binding。 +未授权 `exec` 的智能体 allowlist 会收窄嵌套绑定;继承或显式允许 `exec` 时, +会保留所有通过其他准入检查的普通 code-mode-callable binding。若执行 allowlist +包含任一 MCP 工具项,MCP 绑定还必须匹配其中的精确工具名或服务器模式。 ## 约束与风险 diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index dfa31cab600..a6ecc4170ea 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are not offered to the model and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins); they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, while `exec` itself is registered (container execution warns and falls back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` does not make them unreachable or save their schema tokens, while agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 4270cab0879..6f62e18d2c0 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -374,36 +374,36 @@ If you are experiencing performance issues with file searching (e.g., with `@` c #### tools -| Setting | Type | Description | Default | Notes | -| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | -| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | -| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. When unset, explicit one-shot prompts use `child_process`; interactive TUI, ACP, stream-json input, stdin-only, and file-input sessions use PTY. Platform and availability fallbacks to `child_process` still apply. | mode-based | | -| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | -| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | -| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message`, `tool_search` and `tool_call` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay reachable through `tool_search` + `tool_call` while both bridge tools are registered), and `permissions.deny` to block tools outright. | `undefined` | | -| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | -| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring the ToolSearch + ToolCall bridge. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in `exec` and hides both bridge tools. Merged as a union across scopes. | `undefined` | | -| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, and reachable through the `tool_search` + `tool_call` bridge. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — `tools.toolSearch.enabled: false` (which denies both), a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session (they stay registered and in `/tools`, a direct call by their own name is still evaluated and approved normally, and a warning is logged) — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Use `permissions.deny` if you meant to remove them, or keep both bridge tools registered. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. In Code Mode, withheld tools with actual nested bindings also remain callable through `exec`, and the warning names that subset. Code Mode Only hides both bridge tools, keeps full nested schemas for callable tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` and `tools.visible` do not save schema tokens there, while agent surfaces narrow the nested binding set by their own allowlists. | `undefined` | | -| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | -| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | -| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. Code Mode Only ignores eager/visible schema deferral on the session surface and includes full nested schemas for callable tools there; agent surfaces (subagents, headless agents, arena runs) narrow the nested binding set by their own allowlists, so a tool demoted by `tools.eager` has no nested binding there. | `direct` | Experimental. Requires restart. | -| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | -| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is reachable through `tool_search` + `tool_call` while both bridge tools are registered, but its schema is not sent in the initial model request. | `undefined` | | -| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | -| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | -| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | -| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | -| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | -| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | -| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | -| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | -| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | -| `tools.toolSearch.enabled` | boolean | Review deferred tool schemas through ToolSearch and invoke them through the stable ToolCall bridge. Bridge review and invocation keep the tool list stable — the bridge never re-declares what it reveals — reducing prompt size without touching the prompt-cache prefix. The declaration list is not immutable, though: a session still re-declares on resume, whenever a tool-set refresh (MCP discovery, the first plan-mode entry in a session, a subagent definition change) finds a direct call to a still-hidden deferred tool in the live history, when a subagent definition change rewrites the agent tool's own description, and when an MCP server registers mid-session with `alwaysLoadTools: true`. | `true` | Requires restart: Yes | -| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to `0`, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one `tool_search` round trip before first use. Raise it to `N` so that, when every eligible deferred schema fits within `N`% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by `tools.eager` are excluded from this preload and stay reachable on demand through that bridge while it is registered. Separate paths can still declare deferred tools at `0`: `tools.visible`; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP's late registration, which explicitly reveals and pins `create_sub_session`. | `0` | Requires restart: Yes | -| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | -| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | +| Setting | Type | Description | Default | Notes | +| ------------------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | +| `tools.sandboxImage` | string | Sandbox image URI used by Docker/Podman when `--sandbox-image` and `QWEN_SANDBOX_IMAGE` are not set. | `undefined` | | +| `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. When unset, explicit one-shot prompts use `child_process`; interactive TUI, ACP, stream-json input, stdin-only, and file-input sessions use PTY. Platform and availability fallbacks to `child_process` still apply. | mode-based | | +| `tools.shell.defaultTimeoutMs` | number | Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout. | `undefined` | | +| `tools.shell.heartbeatIntervalMs` | number | Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats. | `undefined` | | +| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. A non-empty list restricts the core tool set (file, shell, search and related built-ins) to an allowlist: core tools not in the list are disabled (fail-closed). Tools outside that set — dynamically discovered tools (MCP, skill) and synthetic/system built-ins such as `agent`, `list_agents`, plan-mode lifecycle tools, goal tools, `task_stop`, `send_message`, `tool_search` and `tool_call` — bypass the allowlist by design; use `permissions.deny` to block a tool's calls (for MCP tools it stays listed and is rejected at runtime), or `tools.disabled` / the per-server `excludeTools` filter to remove it from the registry outright. An empty list (`[]`) is treated as unset and disables nothing. `permissions.allow` cannot reproduce this restriction — it is pure auto-approval (#10075). Use `tools.eager` to restrict which eager-by-default tool schemas are sent initially (unlisted tools are deferred, not disabled — they stay reachable through `tool_search` + `tool_call` while both bridge tools are registered), and `permissions.deny` to block tools outright. | `undefined` | | +| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.disabled` | array of strings | Tool names hidden from the registry entirely. Unlike `permissions.deny` (which blocks calls at runtime), disabled tools are never registered, so they do not appear in `/tools` and cannot be discovered or called by the model. For example, `["enter_plan_mode"]` prevents the model from switching into plan mode on its own. Merged as a union across scopes. | `undefined` | | +| `tools.visible` | array of strings | Deferred tool names made visible at startup without requiring the ToolSearch + ToolCall bridge. Listed tools appear alongside core tools in the initial session. Code Mode Only already includes full nested schemas in `exec` and hides both bridge tools. Merged as a union across scopes. | `undefined` | | +| `tools.eager` | array of strings | Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred instead: still registered, listed in `/tools`, and reachable through the `tool_search` + `tool_call` bridge. Tools already deferred by default stay on demand even when listed; use `tools.visible` to surface one at startup. `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, MCP tools, and `computer_use__*` tools are unaffected and keep their normal loading behaviour. An explicitly empty list (`[]`) is active and defers every non-exempt eager-by-default tool; omitting the setting means no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — `tools.toolSearch.enabled: false` (which denies both), a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session (they stay registered and in `/tools`, a direct call by their own name is still evaluated and approved normally, and a warning is logged) — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Use `permissions.deny` if you meant to remove them, or keep both bridge tools registered. Unusable entries (empty or malformed) are dropped with a warning and leave the rest of the list active. Later scopes replace earlier lists. Requires restart. In Code Mode, withheld tools with actual nested bindings also remain callable through `exec`, and the warning names that subset. Code Mode Only hides both bridge tools, keeps full nested schemas for callable tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` and `tools.visible` do not save schema tokens there, while agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. | `undefined` | | +| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Not automatically migrated; the legacy setting remains honoured at startup. | `undefined` | | +| `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `auto` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `auto` (LLM classifier auto-approves safe actions, blocks risky ones), `yolo` (automatically approve all tool calls) | +| `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. Code Mode Only ignores eager/visible schema deferral on the session surface and includes full nested schemas for callable tools there; AgentCore excludes tools hidden by `tools.eager` from nested bindings; agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. | `direct` | Experimental. Requires restart. | +| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | +| `tools.discoveryCommand` | string | Command to run for tool discovery. When the `tools.eager` allowlist is active, a discovered tool not named in it is registered as deferred: it stays in `/tools` and is reachable through `tool_search` + `tool_call` while both bridge tools are registered, but its schema is not sent in the initial model request. | `undefined` | | +| `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | +| `tools.useRipgrep` | boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | `true` | | +| `tools.useBuiltinRipgrep` | boolean | Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`. | `true` | | +| `tools.workflowsEnabled` | boolean | Enable the Workflow tool, which lets the model author and run a script that orchestrates subagents in parallel. Off by default; a run can dispatch many subagents and spend tokens accordingly. | `false` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. Env overrides: `QWEN_CODE_ENABLE_WORKFLOWS=1` forces on; `QWEN_CODE_DISABLE_WORKFLOWS=1` forces off (disable wins). | +| `tools.workflowSizeGuideline` | enum | Advisory size guideline for the dynamic workflows the model writes: `"small"` aims for fewer than 5 agents, `"medium"` fewer than 15, `"large"` fewer than 50, and `"unrestricted"` sends no guideline. It is not an enforced limit. It also sets the agent count at which a running workflow is flagged as a large workflow in the background-tasks view. | `"medium"` | Possible values: `"small"`, `"medium"`, `"large"`, `"unrestricted"`. Requires restart: No; a change is announced to the model with your next message. Env override for the warning threshold: `QWEN_CODE_WORKFLOW_SIZE_WARNING_AGENTS`. | +| `tools.workflowNameOnly` | boolean | Restrict the model to running named workflows — saved workflows and the workflows extensions ship, called as `Workflow({ name, args })`. The model cannot run an inline `script` or a `scriptPath`, and a running script cannot nest `workflow({ scriptPath })`, so every run the model starts can be matched by a `Workflow(name:...)` permission rule. It does not replace an approval policy: the model can still save a new workflow file and run it by name, which a rule scoped to specific names or script digests asks about. Runs a host starts over ACP (`run-saved`, `run-script`, retry, rerun) are not restricted. In such a session the `/review` workflow fan-out is unavailable. | `false` | Requires restart: Yes. Env: `QWEN_CODE_WORKFLOW_NAME_ONLY=1` turns it on too; a project `.env` cannot set it. A workspace may set this to `true` only; a workspace `false` is ignored. | +| `goals.modelProposed` | enum | Controls the `propose_goal` tool, which lets the model propose a session Goal for you to approve: `alwaysAsk` shows every proposal in an approval dialog and nothing is set until you accept it; `"disabled"` removes the tool. A typed `/goal` is unaffected. | `alwaysAsk` | User, System, and SystemDefaults scopes only; workspace values are ignored. Requires restart: Yes. | +| `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | +| `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | +| `tools.toolSearch.enabled` | boolean | Review deferred tool schemas through ToolSearch and invoke them through the stable ToolCall bridge. Bridge review and invocation keep the tool list stable — the bridge never re-declares what it reveals — reducing prompt size without touching the prompt-cache prefix. The declaration list is not immutable, though: a session still re-declares on resume, whenever a tool-set refresh (MCP discovery, the first plan-mode entry in a session, a subagent definition change) finds a direct call to a still-hidden deferred tool in the live history, when a subagent definition change rewrites the agent tool's own description, and when an MCP server registers mid-session with `alwaysLoadTools: true`. | `true` | Requires restart: Yes | +| `tools.toolSearch.threshold` | number | Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to `0`, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one `tool_search` round trip before first use. Raise it to `N` so that, when every eligible deferred schema fits within `N`% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by `tools.eager` are excluded from this preload and stay reachable on demand through that bridge while it is registered. Separate paths can still declare deferred tools at `0`: `tools.visible`; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP's late registration, which explicitly reveals and pins `create_sub_session`. | `0` | Requires restart: Yes | +| `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | +| `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | > [!note] > diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index fc837732bde..5c404b919c6 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -2771,7 +2771,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: ToolMode.Direct, description: - 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent surfaces narrow nested bindings by their own allowlists.', + 'Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns.', showInDialog: true, options: [ { value: ToolMode.Direct, label: 'Default' }, @@ -2892,7 +2892,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: 0, description: - 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', + 'Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session.', showInDialog: true, // A percentage of the context window: values above 100 would set a // budget larger than the window and unconditionally preload every @@ -3074,7 +3074,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: undefined as string[] | undefined, description: - 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', + 'Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.', showInDialog: false, }, approvalMode: { diff --git a/packages/core/src/utils/fileUtils.test.ts b/packages/core/src/utils/fileUtils.test.ts index 51a52be72fe..34afd11bfa8 100644 --- a/packages/core/src/utils/fileUtils.test.ts +++ b/packages/core/src/utils/fileUtils.test.ts @@ -1498,6 +1498,23 @@ describe('fileUtils', () => { allowedNames: ['read_file'], hint: '', }, + ...[ + ['read_file', 'exec', 'tool_search', 'tool_call'], + ['read_file', 'exec', 'zoom_image'], + ['read_file', 'exec'], + ].flatMap((declared) => + [[], ['read_file'], ['read_file', 'zoom_image']].map( + (allowedNames) => ({ + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared, + deferred: ['zoom_image'], + bindings: ['zoom_image'], + allowedNames, + hint: '', + }), + ), + ), ])( 'uses only exposed tools for image guidance: $declared, code mode $codeModeOnly', async ({ diff --git a/packages/core/src/utils/fileUtils.ts b/packages/core/src/utils/fileUtils.ts index eb00d59c2c0..c874b94e608 100644 --- a/packages/core/src/utils/fileUtils.ts +++ b/packages/core/src/utils/fileUtils.ts @@ -1686,7 +1686,9 @@ export async function processSingleFileContent( ?.getDeferredToolSummary() .some((tool) => tool.name === 'zoom_image')); let zoomHint = ''; - if (zoomAvailable) { + // An agent's target allowlist does not identify its declared + // direct, bridge, or exec routes. Do not advertise session routes. + if (zoomAvailable && ambientAllowedNames === undefined) { const toolName = useNestedZoom ? 'tools.zoom_image' : 'zoom_image'; diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 493b97376c1..66fd5d33e4f 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, while `exec` itself is registered (container execution warns and falls back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. In hybrid mode, while `exec` itself is registered (container execution warns and falls back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in `exec`, and skips deferred reminders and this warning; on the session surface `tools.eager` does not make them unreachable or save their schema tokens, while agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index 2aa3da71342..888a96710c4 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -437,8 +437,12 @@ export interface QueryOptions { * tool is unavailable. CodeModeOnly hides both bridge tools, includes * callable deferred tools' full schemas in exec, and skips deferred * reminders and this warning; on the session surface tools.eager does not - * make those nested tools unreachable or reduce their schema tokens, while - * agent surfaces narrow the nested binding set by their own allowlists. + * make those nested tools unreachable or reduce their schema tokens. + * Agent allowlists that do not grant `exec` narrow nested bindings. + * Inheriting or explicitly granting `exec` keeps all otherwise admitted + * ordinary code-mode-callable bindings. An execution allowlist that + * mentions any MCP tool additionally restricts MCP bindings to matching + * exact names or server patterns. * Tools already deferred by default remain * on demand even when listed; `tools.visible` surfaces one at startup. The * allowlist does not affect MCP tools, the `--json-schema` @@ -514,8 +518,12 @@ export interface QueryOptions { * both bridge tools, includes callable deferred tools' full schemas * in exec, and skips deferred reminders and this warning; on the * session surface tools.eager does not make those nested tools - * unreachable or reduce their schema tokens, while agent surfaces - * narrow the nested binding set by their own allowlists. + * unreachable or reduce their schema tokens. + * Agent allowlists that do not grant `exec` narrow nested bindings. + * Inheriting or explicitly granting `exec` keeps all otherwise admitted + * ordinary code-mode-callable bindings. An execution allowlist that + * mentions any MCP tool additionally restricts MCP bindings to matching + * exact names or server patterns. * * **Pattern matching:** * - Tool name: `'write_file'` diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index f49dda0ae21..01d4a17c764 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -1314,7 +1314,7 @@ "description": "Linux tool execution confinement. Operator scopes only; workspace settings cannot override it. Model/auth/session traffic stays on the host." }, "mode": { - "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent surfaces narrow nested bindings by their own allowlists. Options: direct, code_mode, code_mode_only", + "description": "Choose how tools are exposed to the model. Direct uses ordinary tool calls; Code Mode also exposes the isolated exec JavaScript tool; Code Mode Only exposes ordinary tools only through exec. Safe and bare modes always use Direct. Container execution warns and uses direct tools for Code Mode, and rejects Code Mode Only. Code Mode Only ignores eager/visible schema deferral on the session surface: callable tools retain full nested schemas there and tool_search is hidden; agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. Options: direct, code_mode, code_mode_only", "enum": [ "direct", "code_mode", @@ -1382,7 +1382,7 @@ "minimum": 0, "maximum": 100, "default": 0, - "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." + "description": "Context-window percentage used as the session-start budget for preloading ordinary deferred tools (bundled built-ins and MCP alike). Defaults to 0, which performs no threshold-based preload; ordinary deferred tools normally stay behind the stable ToolSearch + ToolCall bridge, at the cost of one tool_search round trip before first use. Raise it to N so that, when every eligible deferred schema fits within N% of the context window, all are declared upfront for direct calls with no bridge round trip; otherwise they stay behind the bridge while both bridge tools are registered. Tools demoted by tools.eager are excluded from this preload and stay reachable on demand through that bridge while it is registered; when either bridge tool is unregistered (tools.toolSearch.enabled false denies both; a tool_search or tool_call deny rule removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally. Separate paths can still declare deferred tools at 0: tools.visible; the live-history compatibility scan on every tool-set refresh (including resume, MCP discovery, first plan-mode entry, and subagent definition changes); the incomplete-bridge eager fallback; and daemon ACP late registration, which explicitly reveals and pins create_sub_session." } } }, @@ -1475,7 +1475,7 @@ } }, "eager": { - "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent surfaces narrow nested bindings by their own allowlists. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", + "description": "Allowlist of eager-by-default built-in tool names whose schemas remain eligible for the initial model request. Unlisted non-exempt tools are deferred but stay registered, listed in /tools, and reachable through the tool_search + tool_call bridge. Tools already deferred by default stay on demand even when listed; use tools.visible to surface one at startup. tool_search, tool_call, structured_output, plan-mode lifecycle tools, task_stop, MCP tools, and computer_use__* tools are unaffected. An explicitly empty list ([]) defers every non-exempt eager-by-default tool; omit the setting for no restriction. Pairs with the ToolSearch + ToolCall bridge: when either half is not registered — tools.toolSearch.enabled false (which denies both), a tool_search or tool_call deny rule, or a tools.disabled entry — the allowlist still withholds the schemas, but nothing can load them back, so the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is logged; these bridge and warning rules apply to direct and hybrid tool modes. In Code Mode, withheld tools with actual exec bindings also remain callable through exec; the warning names that subset. CodeModeOnly hides both bridge tools, keeps full nested schemas for callable deferred tools in exec, and skips deferred reminders and this warning; on the session surface tools.eager does not make them unreachable or save their schema tokens, while agent allowlists that do not grant exec narrow nested bindings. Inheriting or explicitly granting exec keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in tools.visible, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares. Differs from tools.disabled, which removes tools entirely, and from permissions.allow, which only auto-approves calls.", "type": "array", "items": { "type": "string" From fa457bda6b871a823f934d0a3ffd42203b8ed623 Mon Sep 17 00:00:00 2001 From: qwen-code-ci-bot Date: Wed, 23 Sep 2026 21:28:07 +0000 Subject: [PATCH 09/49] fix(core): narrow MCP nested bindings by the agent tools allowlist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The execution-allowlist branch already restricted MCP nested bindings to matching exact names or server patterns once the list mentioned MCP, but the configured-tools branch — the only allowlist SubagentConfig exposes — applied the exec carve-out to every code-mode-callable name, so tools: ['exec', 'mcp__github__read_*'] admitted every connected server's tools as nested exec bindings. Route MCP names through the shared raw-identity matcher in that branch too, and pin the bridge-route zoom hint case for narrowed agents. Co-authored-by: Qwen-Coder --- .../runtime/agent-core.skill-gate.test.ts | 49 +++++++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 42 ++++++++++++---- packages/core/src/utils/fileUtils.test.ts | 12 +++++ 3 files changed, 94 insertions(+), 9 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 05f756bbca5..446fa413347 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -519,6 +519,55 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual(['mcp__github__read_file']); }); + it('honors MCP patterns from the tools list alone in the hybrid nested binding set', async () => { + // No `executionAllowedTools`: the agent-definition surface + // (`SubagentConfig.tools`) is the only allowlist an SDK integrator can + // set, so the configured-list branch must apply the same MCP narrowing + // as the execution-allowlist branch. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + const readTool = new MockTool({ name: 'mcp__github__read_file' }); + Object.assign(readTool, { + serverName: 'github', + serverToolName: 'read_file', + }); + const createTool = new MockTool({ name: 'mcp__github__create_issue' }); + Object.assign(createTool, { + serverName: 'github', + serverToolName: 'create_issue', + }); + const chargeTool = new MockTool({ name: 'mcp__payments__charge' }); + Object.assign(chargeTool, { + serverName: 'payments', + serverToolName: 'charge', + }); + registry.registerTool(readTool); + registry.registerTool(createTool); + registry.registerTool(chargeTool); + const core = new AgentCore( + 'mcp-pattern-tools-only-hybrid-code-mode', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC, 'mcp__github__read_*'], + }, + ); + + await core.prepareTools(); + + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual(['mcp__github__read_file']); + }); + it('honors an exact MCP tool name in the hybrid nested binding set', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 82b53fd37bf..5611a0b9aaa 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -1744,7 +1744,19 @@ export class AgentCore { (forNestedBinding && isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && configuredAllowlist.includes(ToolNames.EXEC) && - getToolExposure(toolName) === 'code-mode-callable') + getToolExposure(toolName) === 'code-mode-callable' && + // Once the configured list mentions MCP at all, an MCP name must + // pass the raw-identity match instead of the exec carve-out — + // the same rule the executionAllowedTools branch applies below. + (!toolName.startsWith('mcp__') || + !configuredAllowlist.some((name) => name.startsWith('mcp__')) || + this.matchesMcpAllowlist( + toolName, + new Set( + configuredAllowlist.filter((name) => !name.includes('*')), + ), + configuredAllowlist.filter((name) => name.includes('*')), + ))) ); } if ( @@ -1775,9 +1787,24 @@ export class AgentCore { return false; } - // Match MCP patterns against the registry's raw server/tool identity. - // Comparing provider-sanitized prefixes can merge distinct server names - // such as "repo.bad" and "repo/bad", so it is unsafe for an allowlist. + return this.matchesMcpAllowlist( + toolName, + this.executionAllowedExactTools!, + this.executionAllowedMcpPatterns!, + ); + } + + /** + * Matches an MCP tool name against allowlist entries using the registry's + * raw server/tool identity. Comparing provider-sanitized prefixes can merge + * distinct server names such as "repo.bad" and "repo/bad", so it is unsafe + * for an allowlist. + */ + private matchesMcpAllowlist( + toolName: string, + exact: ReadonlySet, + patterns: readonly string[], + ): boolean { const registeredTool = this.runtimeContext .getToolRegistry() .getTool(toolName) as @@ -1794,14 +1821,11 @@ export class AgentCore { const serverToolName = registeredTool.serverToolName; const serverPattern = `mcp__${serverName}`; const rawToolName = `${serverPattern}__${serverToolName}`; - if ( - this.executionAllowedExactTools?.has(serverPattern) || - this.executionAllowedExactTools?.has(rawToolName) - ) { + if (exact.has(serverPattern) || exact.has(rawToolName)) { return true; } - return this.executionAllowedMcpPatterns!.some((pattern) => { + return patterns.some((pattern) => { if (pattern === 'mcp__*') { return true; } diff --git a/packages/core/src/utils/fileUtils.test.ts b/packages/core/src/utils/fileUtils.test.ts index 34afd11bfa8..53805ed747b 100644 --- a/packages/core/src/utils/fileUtils.test.ts +++ b/packages/core/src/utils/fileUtils.test.ts @@ -1498,6 +1498,18 @@ describe('fileUtils', () => { allowedNames: ['read_file'], hint: '', }, + { + // Same narrowing through the bridge route: the session declares + // tool_search and tool_call, but the narrowed agent has neither + // half, so the guidance must not advertise the bridge. + codeModeOnly: false, + toolMode: ToolMode.CodeMode, + declared: ['read_file', 'tool_search', 'tool_call'], + deferred: ['zoom_image'], + bindings: ['zoom_image'], + allowedNames: ['read_file'], + hint: '', + }, ...[ ['read_file', 'exec', 'tool_search', 'tool_call'], ['read_file', 'exec', 'zoom_image'], From ae358092224973c777bdd917131d3c3fc383bdfa Mon Sep 17 00:00:00 2001 From: qwen-code-ci-bot Date: Thu, 24 Sep 2026 14:28:59 +0000 Subject: [PATCH 10/49] fix(core): keep CodeModeOnly exec expansion from bypassing MCP narrowing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under tools.mode "code_mode_only", a configured agent tools list granting exec expands to every code-mode-callable registry name — including every connected MCP tool — so the includes() disjunct in isToolExecutionAllowed short-circuited before the MCP raw-identity narrowing could fire: tools: ['exec', 'mcp__github__read_*'] admitted mcp__payments__charge as a nested exec binding. Stop the expansion from adding MCP names once the configured list mentions MCP, letting the existing narrowing decide, and pin the CodeModeOnly case mirroring the hybrid one. Co-authored-by: Qwen-Coder --- .../runtime/agent-core.skill-gate.test.ts | 48 +++++++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 9 +++- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 446fa413347..ea7b979874e 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -568,6 +568,54 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual(['mcp__github__read_file']); }); + it('honors MCP patterns from the tools list alone in the CodeModeOnly nested binding set', async () => { + // CodeModeOnly widens a configured exec grant into every + // code-mode-callable registry name; that expansion must not swallow + // the MCP names the configured list narrows by pattern. + const config = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + const readTool = new MockTool({ name: 'mcp__github__read_file' }); + Object.assign(readTool, { + serverName: 'github', + serverToolName: 'read_file', + }); + const createTool = new MockTool({ name: 'mcp__github__create_issue' }); + Object.assign(createTool, { + serverName: 'github', + serverToolName: 'create_issue', + }); + const chargeTool = new MockTool({ name: 'mcp__payments__charge' }); + Object.assign(chargeTool, { + serverName: 'payments', + serverToolName: 'charge', + }); + registry.registerTool(readTool); + registry.registerTool(createTool); + registry.registerTool(chargeTool); + const core = new AgentCore( + 'mcp-pattern-tools-only-code-mode-only', + config, + { systemPrompt: '' } as never, + { model: 'test-model' } as never, + { max_turns: 1 } as never, + { + tools: [ToolNames.EXEC, 'mcp__github__read_*'], + }, + ); + + await core.prepareTools(); + + expect( + ( + core as unknown as { + codeModeAllowedToolNames?: readonly string[]; + } + ).codeModeAllowedToolNames, + ).toEqual(['mcp__github__read_file']); + }); + it('honors an exact MCP tool name in the hybrid nested binding set', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 5611a0b9aaa..49b098dbd60 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -1707,10 +1707,17 @@ export class AgentCore { this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly && allowed.has(ToolNames.EXEC) ) { + // A configured list that mentions MCP narrows MCP names through the + // raw-identity match in isToolExecutionAllowed; expanding them in here + // would short-circuit that narrowing via `includes`. + const mentionsMcp = [...allowed].some((name) => name.startsWith('mcp__')); for (const toolName of this.runtimeContext .getToolRegistry() .getAllToolNames()) { - if (getToolExposure(toolName) === 'code-mode-callable') { + if ( + getToolExposure(toolName) === 'code-mode-callable' && + !(mentionsMcp && toolName.startsWith('mcp__')) + ) { allowed.add(toolName); } } From b1561b7e27c62e821562126990b4ebe207df0092 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:27:23 +0800 Subject: [PATCH 11/49] fix: preserve nested-only fork access and legacy mode resets --- docs/users/features/sub-agents.md | 6 ++- .../src/ui/components/SettingsDialog.test.tsx | 49 +++++++++++++++++++ .../cli/src/ui/components/SettingsDialog.tsx | 3 +- packages/core/src/agents/agent-transcript.ts | 2 + .../agents/background-agent-resume.test.ts | 8 +++ .../src/agents/background-agent-resume.ts | 5 ++ .../runtime/agent-core.skill-gate.test.ts | 38 ++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 14 ++++++ .../core/src/agents/runtime/agent-types.ts | 2 + .../core/src/subagents/subagent-manager.ts | 7 +++ packages/core/src/tools/agent/agent.test.ts | 9 +++- packages/core/src/tools/agent/agent.ts | 37 ++++++++++++-- .../core/src/tools/agent/fork-subagent.ts | 24 ++++++--- 13 files changed, 189 insertions(+), 15 deletions(-) diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index 7d6737cccd2..6e0aa3ad885 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -381,10 +381,12 @@ Do not modify any files. Use `tools` and `disallowedTools` to control which tools a subagent can access. -**`tools` (allowlist):** When specified, the subagent can only use the listed tools. When omitted, the subagent inherits all available tools from the parent session. +**`tools` (allowlist):** When specified, the list bounds direct tool calls and deferred-tool bridge targets. Code mode also supports the nested `exec` path described below. When omitted, the subagent inherits all available tools from the parent session. The allowlist applies both to directly declared tools and to targets invoked through the `tool_search`/`tool_call` deferred-tool bridge. An explicit list of ordinary tools does not automatically include either bridge tool; name both `tool_search` and `tool_call` if the agent needs discovery and bridge invocation. A listed ordinary deferred target is declared directly, while a target demoted by `tools.eager` remains hidden unless a separate reveal rule applies. A hidden target must still be present in `tools` to be invoked through the bridge. `disallowedTools` and `permissions.deny` remain additional blocklists, and listing a tool does not bypass the subagent control-plane exclusions. +With `tools.mode: "code_mode"` or `"code_mode_only"`, `exec` provides a third path: nested `tools.(...)` calls. Explicitly listing `exec` also grants otherwise-admitted code-mode-callable bindings, including ordinary tools such as `write_file` and `run_shell_command` that are not individually listed. Thus `tools: [read_file, exec]` is not a read-only policy. Omit `exec` from the configured list to keep nested targets bounded by the listed names; the runtime still exposes the `exec` wrapper in code mode. `disallowedTools`, `permissions.deny`, subagent exclusions, and tools hidden by `tools.eager` continue to restrict access. This nested grant does not add direct-call permission in hybrid mode. A fork's explicit `fork_tools: [exec]` grant also remains bounded by its parent's inherited execution policy. + ``` --- name: reader @@ -412,7 +414,7 @@ disallowedTools: If both `tools` and `disallowedTools` are set, the allowlist is applied first, then the blocklist removes from that set. -**MCP tools** follow the same rules. If a subagent has no `tools` list, it inherits all MCP tools from the parent session. If a subagent has an explicit `tools` list, it only gets MCP tools that are explicitly named in that list. +**MCP tools** follow the same rules. Without a `tools` list, the subagent inherits MCP tools from the parent session. An explicit list ordinarily requires matching MCP entries. Granting `exec` also admits otherwise-available MCP bindings through the nested path when the list contains no MCP entries; once the list mentions MCP, nested MCP calls must match those entries. The blocklists and exclusions above still apply. The `disallowedTools` field supports MCP server-level patterns: diff --git a/packages/cli/src/ui/components/SettingsDialog.test.tsx b/packages/cli/src/ui/components/SettingsDialog.test.tsx index da40ce21254..fe1c026a21d 100644 --- a/packages/cli/src/ui/components/SettingsDialog.test.tsx +++ b/packages/cli/src/ui/components/SettingsDialog.test.tsx @@ -1241,6 +1241,55 @@ describe('SettingsDialog', () => { unmount(); }); + it.each(['\u0003', '\u000c'])( + 'persists resetting legacy Tool Mode with %j and requests restart', + async (key) => { + const settings = createMockSettings({ tools: { codeModeOnly: true } }); + const setValue = vi + .spyOn(settings, 'setValue') + .mockImplementation(() => {}); + const actual = await vi.importActual< + typeof import('../../config/settingsUtils.js') + >('../../config/settingsUtils.js'); + vi.mocked(saveModifiedSettings).mockImplementation( + actual.saveModifiedSettings, + ); + const onRestartRequest = vi.fn(); + const { stdin, lastFrame, unmount } = render( + + + , + ); + try { + await waitFor(() => expect(lastFrame()).toContain('Code Mode Only')); + stdin.write(TerminalKeys.DOWN_ARROW); + await wait(30); + stdin.write(key); + await waitFor(() => + expect(lastFrame()).toContain( + 'Press r to exit and apply changes now', + ), + ); + stdin.write('r'); + await waitFor(() => + expect(setValue).toHaveBeenCalledWith( + SettingScope.User, + 'tools.mode', + 'direct', + ), + ); + expect(onRestartRequest).toHaveBeenCalledOnce(); + } finally { + unmount(); + } + }, + ); + it('should handle Ctrl+C to reset current setting to default', async () => { const settings = createMockSettings({ vimMode: true }); // Start with vimMode enabled const onSelect = vi.fn(); diff --git a/packages/cli/src/ui/components/SettingsDialog.tsx b/packages/cli/src/ui/components/SettingsDialog.tsx index 399aea2a1dc..aafb5ec59f4 100644 --- a/packages/cli/src/ui/components/SettingsDialog.tsx +++ b/packages/cli/src/ui/components/SettingsDialog.tsx @@ -1015,9 +1015,8 @@ export function SettingsDialog({ const scopeSettings = settings.forScope(selectedScope).settings; const resetChangesValue = - !isDefaultValue(currentSetting.value, scopeSettings) && getEffectiveValue(currentSetting.value, scopeSettings, {}) !== - defaultValue; + defaultValue; setModifiedSettings((prev) => { const updated = new Set(prev); if (resetChangesValue) updated.add(currentSetting.value); diff --git a/packages/core/src/agents/agent-transcript.ts b/packages/core/src/agents/agent-transcript.ts index 000c9a9b1ab..641e169c552 100644 --- a/packages/core/src/agents/agent-transcript.ts +++ b/packages/core/src/agents/agent-transcript.ts @@ -148,6 +148,8 @@ export interface AgentMeta { * exclusion; an empty list means deny-all. */ executionAllowedTools?: string[]; + /** Exact names allowed only inside exec; never grants direct tool calls. */ + nestedExecutionAllowedTools?: string[]; /** * Launch-time per-agent tool blocklist of a fork, persisted beside * `executionAllowedTools`: the resume path rebuilds the fork's toolConfig diff --git a/packages/core/src/agents/background-agent-resume.test.ts b/packages/core/src/agents/background-agent-resume.test.ts index 3714e4dc362..9bc78485a9f 100644 --- a/packages/core/src/agents/background-agent-resume.test.ts +++ b/packages/core/src/agents/background-agent-resume.test.ts @@ -2460,6 +2460,7 @@ describe('BackgroundAgentResumeService', () => { format: 'persisted deny-all execution policy', legacyCapabilities: {}, executionAllowedTools: [] as string[] | undefined, + nestedExecutionAllowedTools: ['read_file'], includeDisplayImage: false, deniedTool: 'Read', expectedExecutionAllowedTools: [], @@ -2517,6 +2518,7 @@ describe('BackgroundAgentResumeService', () => { async ({ legacyCapabilities, executionAllowedTools, + nestedExecutionAllowedTools, includeDisplayImage, deniedTool, expectedExecutionAllowedTools, @@ -2537,6 +2539,9 @@ describe('BackgroundAgentResumeService', () => { status: 'running', subagentName: FORK_SUBAGENT_TYPE, resolvedApprovalMode: 'default', + ...(nestedExecutionAllowedTools !== undefined + ? { nestedExecutionAllowedTools } + : {}), ...(executionAllowedTools !== undefined ? { executionAllowedTools } : {}), @@ -2738,6 +2743,9 @@ describe('BackgroundAgentResumeService', () => { ToolNames.ASK_USER_QUESTION, ], executionAllowedTools: expectedExecutionAllowedTools, + ...(nestedExecutionAllowedTools !== undefined + ? { nestedExecutionAllowedTools } + : {}), }); expect(createArgs?.[9]).toBe(launchPrompt); expect(createArgs?.[10]).toBe(agentId); diff --git a/packages/core/src/agents/background-agent-resume.ts b/packages/core/src/agents/background-agent-resume.ts index fba1f582309..efb0dd39105 100644 --- a/packages/core/src/agents/background-agent-resume.ts +++ b/packages/core/src/agents/background-agent-resume.ts @@ -1023,6 +1023,7 @@ export class BackgroundAgentResumeService { meta.disallowedTools, meta.agentId, meta.description, + meta.nestedExecutionAllowedTools, ); } else { const resumeSubagentConfig = @@ -1803,6 +1804,7 @@ export class BackgroundAgentResumeService { disallowedTools?: string[], subagentId?: string, taskName?: string, + nestedExecutionAllowedTools?: string[], ): Promise { const promptConfig: PromptConfig = { renderedSystemPrompt: structuredClone(runtime.systemInstruction), @@ -1822,6 +1824,9 @@ export class BackgroundAgentResumeService { runtime.toolNames, ), ), + ...(nestedExecutionAllowedTools !== undefined + ? { nestedExecutionAllowedTools: [...nestedExecutionAllowedTools] } + : {}), // Restore the persisted blocklist beside the allowlist: the // invocation-level re-check is the only enforcement a wildcard // allowlist entry (e.g. mcp__*) cannot provide on its own. diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index ea7b979874e..27cd30663bf 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -479,6 +479,44 @@ describe('AgentCore skill-gate inputs', () => { ).toEqual([ToolNames.READ_FILE, ToolNames.WRITE_FILE]); }); + it('keeps bounded fork bindings nested-only with an immutable policy', async () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + for (const name of [ + ToolNames.READ_FILE, + ToolNames.WRITE_FILE, + 'mcp__payments__charge', + ]) { + registry.registerTool(new MockTool({ name })); + } + const nested: string[] = [ToolNames.READ_FILE]; + const core = new AgentCore( + 'bounded-exec-fork', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: [ToolNames.EXEC, ToolNames.READ_FILE, ToolNames.WRITE_FILE], + executionAllowedTools: [], + nestedExecutionAllowedTools: nested, + }, + ); + nested.push(ToolNames.WRITE_FILE); + const declarations = await core.prepareTools(); + expect(declarations.map((tool) => tool.name)).toEqual([ToolNames.EXEC]); + expect(executable(core, ToolNames.READ_FILE)).toBe(false); + expect(declarations[0]?.description).toContain('tools.read_file(args:'); + expect(declarations[0]?.description).not.toContain( + 'tools.write_file(args:', + ); + expect(declarations[0]?.description).not.toContain( + 'mcp__payments__charge', + ); + }); + it('honors MCP execution patterns in the hybrid nested binding set', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index e1a5571b28b..6b83fd510cb 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -394,6 +394,7 @@ export class AgentCore { readonly runConfig: RunConfig; readonly toolConfig?: ToolConfig; private readonly executionAllowedTools?: readonly string[]; + private readonly nestedExecutionAllowedTools?: ReadonlySet; private readonly executionAllowedExactTools?: ReadonlySet; private readonly executionAllowedMcpPatterns?: readonly string[]; private readonly executionAllowlistErrorSummary?: string; @@ -480,6 +481,11 @@ export class AgentCore { this.modelConfig = modelConfig; this.runConfig = runConfig; this.toolConfig = toolConfig; + if (toolConfig?.nestedExecutionAllowedTools !== undefined) { + this.nestedExecutionAllowedTools = new Set( + toolConfig.nestedExecutionAllowedTools, + ); + } if (toolConfig?.executionAllowedTools !== undefined) { this.executionAllowedTools = Object.freeze([ ...toolConfig.executionAllowedTools, @@ -1774,6 +1780,14 @@ export class AgentCore { if (this.isToolDisallowedByAgentConfig(toolName)) { return false; } + if ( + forNestedBinding && + isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && + getToolExposure(toolName) === 'code-mode-callable' && + this.nestedExecutionAllowedTools !== undefined + ) { + return this.nestedExecutionAllowedTools.has(toolName); + } if (this.executionAllowedTools === undefined) { // Code mode declares exec unconditionally (getCodeModeFunctionDeclarations // keeps exposure 'exec' regardless of the allowed set), so a finite diff --git a/packages/core/src/agents/runtime/agent-types.ts b/packages/core/src/agents/runtime/agent-types.ts index 8223bbd20a2..210df4fd3be 100644 --- a/packages/core/src/agents/runtime/agent-types.ts +++ b/packages/core/src/agents/runtime/agent-types.ts @@ -103,6 +103,8 @@ export interface ToolConfig { * Supports exact tool names and MCP server-level patterns. */ executionAllowedTools?: string[]; + /** Exact names allowed only inside exec; never grants direct tool calls. */ + nestedExecutionAllowedTools?: string[]; /** * Optional list of tool names to exclude from the agent's tool pool. diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index f7961305b56..b8be23ca517 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -1147,6 +1147,13 @@ export class SubagentManager { ], } : {}), + ...(configuredToolConfig?.nestedExecutionAllowedTools !== undefined + ? { + nestedExecutionAllowedTools: [ + ...configuredToolConfig.nestedExecutionAllowedTools, + ], + } + : {}), disallowedTools: Array.from( new Set([ ...(configuredToolConfig?.disallowedTools ?? []), diff --git a/packages/core/src/tools/agent/agent.test.ts b/packages/core/src/tools/agent/agent.test.ts index baff0438d88..914af8bc608 100644 --- a/packages/core/src/tools/agent/agent.test.ts +++ b/packages/core/src/tools/agent/agent.test.ts @@ -5605,12 +5605,17 @@ describe('AgentTool', () => { ); expect(result.error).toBeUndefined(); const tools = vi.mocked(AgentHeadless.create).mock.calls[0]?.[5]; - expect(tools?.executionAllowedTools).toEqual([ + expect(tools?.executionAllowedTools).toEqual([]); + expect(tools?.nestedExecutionAllowedTools).toEqual([ 'read_file', 'mcp__github__read_file', ]); expect(writeMetaSpy.mock.calls[0]?.[1]).toMatchObject({ - executionAllowedTools: ['read_file', 'mcp__github__read_file'], + executionAllowedTools: [], + nestedExecutionAllowedTools: [ + 'read_file', + 'mcp__github__read_file', + ], }); writeMetaSpy.mockRestore(); }, diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 78815a85318..9cc2cbd610b 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -1839,6 +1839,7 @@ class AgentToolInvocation extends BaseToolInvocation { }; const buildParentBoundExecutionAllowlist = ( fallbackTools: readonly string[], + forNestedBinding = false, ): string[] => { if (parentConfiguredToolAllowlist === undefined) { return buildForkExecutionAllowlist( @@ -1853,9 +1854,12 @@ class AgentToolInvocation extends BaseToolInvocation { !EXCLUDED_TOOLS_FOR_SUBAGENTS.has(toolName) && keepOffParentBlocklist(toolName) && (isRequestedByFork(toolName) || - (isCodeModeEnabled(agentConfig.getToolMode?.()) && + (forNestedBinding && + isCodeModeEnabled(agentConfig.getToolMode?.()) && requestedTools?.includes(ToolNames.EXEC) && - getToolExposure(toolName) === 'code-mode-callable') || + getToolExposure(toolName) === 'code-mode-callable' && + (!toolName.startsWith('mcp__') || + !requestedTools.some((name) => name.startsWith('mcp__')))) || (requestedTools !== undefined && requestedTools.length > 0 && (toolName === ToolNames.TOOL_SEARCH || @@ -1863,8 +1867,13 @@ class AgentToolInvocation extends BaseToolInvocation { parentToolNames.includes(toolName))), ); }; + const nestedExecutionAllowedTools = + parentConfiguredToolAllowlist !== undefined && + isCodeModeEnabled(agentConfig.getToolMode?.()) + ? buildParentBoundExecutionAllowlist(defaultExecutionToolNames, true) + : undefined; const requestedExecutionAllowedTools = - requestedTools === undefined + requestedTools === undefined && nestedExecutionAllowedTools === undefined ? undefined : resolveForkExecutionAllowedTools( parentToolNames, @@ -1924,6 +1933,7 @@ class AgentToolInvocation extends BaseToolInvocation { lastMessage, requestedExecutionAllowedTools, profilePromptHint, + nestedExecutionAllowedTools, ); if (forkedMessages.length > 0) { // Model had function calls: append tool responses + directive, @@ -1957,6 +1967,7 @@ class AgentToolInvocation extends BaseToolInvocation { this.params.prompt, requestedExecutionAllowedTools, profilePromptHint, + nestedExecutionAllowedTools, ); } @@ -1986,6 +1997,9 @@ class AgentToolInvocation extends BaseToolInvocation { parentToolNames, buildParentBoundExecutionAllowlist(defaultExecutionToolNames), ), + ...(nestedExecutionAllowedTools !== undefined + ? { nestedExecutionAllowedTools } + : {}), ...(parentDisallowedTools?.length ? { disallowedTools: [...parentDisallowedTools] } : {}), @@ -2001,6 +2015,9 @@ class AgentToolInvocation extends BaseToolInvocation { parentToolNames, buildParentBoundExecutionAllowlist(defaultExecutionToolNames), ), + ...(nestedExecutionAllowedTools !== undefined + ? { nestedExecutionAllowedTools } + : {}), ...(parentDisallowedTools?.length ? { disallowedTools: [...parentDisallowedTools] } : {}), @@ -3647,6 +3664,13 @@ class AgentToolInvocation extends BaseToolInvocation { // Unlike the allowlist above, the blocklist persists whenever the // fork carries one — it also bounds plain forks whose allowlist is // rebuilt from the live parent surface on resume. + ...(isFork && bgToolConfig?.nestedExecutionAllowedTools !== undefined + ? { + nestedExecutionAllowedTools: [ + ...bgToolConfig.nestedExecutionAllowedTools, + ], + } + : {}), ...(isFork && bgToolConfig?.disallowedTools?.length ? { disallowedTools: [...bgToolConfig.disallowedTools] } : {}), @@ -4561,6 +4585,13 @@ class AgentToolInvocation extends BaseToolInvocation { // Unlike the allowlist above, the blocklist persists whenever the // fork carries one — it also bounds plain forks whose allowlist is // rebuilt from the live parent surface on resume. + ...(isFork && toolConfig?.nestedExecutionAllowedTools !== undefined + ? { + nestedExecutionAllowedTools: [ + ...toolConfig.nestedExecutionAllowedTools, + ], + } + : {}), ...(isFork && toolConfig?.disallowedTools?.length ? { disallowedTools: [...toolConfig.disallowedTools] } : {}), diff --git a/packages/core/src/tools/agent/fork-subagent.ts b/packages/core/src/tools/agent/fork-subagent.ts index 892641e51fd..f1c9f8511ad 100644 --- a/packages/core/src/tools/agent/fork-subagent.ts +++ b/packages/core/src/tools/agent/fork-subagent.ts @@ -309,6 +309,7 @@ export function buildForkedMessages( assistantMessage: Content, executionAllowedTools?: readonly string[], promptHint?: string, + nestedExecutionAllowedTools?: readonly string[], ): Content[] { const toolUseParts = assistantMessage.parts?.filter((part) => part.functionCall) || []; @@ -356,7 +357,12 @@ export function buildForkedMessages( parts: [ ...toolResultParts, { - text: buildChildMessage(directive, executionAllowedTools, promptHint), + text: buildChildMessage( + directive, + executionAllowedTools, + promptHint, + nestedExecutionAllowedTools, + ), }, ], }; @@ -409,14 +415,20 @@ export function buildChildMessage( directive: string, executionAllowedTools?: readonly string[], promptHint?: string, + nestedExecutionAllowedTools?: readonly string[], ): string { const executionRestriction = - executionAllowedTools === undefined - ? '' - : executionAllowedTools.length === 0 - ? `\n\nTOOL EXECUTION RESTRICTION: + nestedExecutionAllowedTools !== undefined + ? `\n\nTOOL EXECUTION RESTRICTION: +You may call exec and tools matched by this direct-call allowlist: ${JSON.stringify(executionAllowedTools ?? [])}. +Inside exec, only these exact nested tool names are permitted: ${JSON.stringify(nestedExecutionAllowedTools)}. +Nested permission does not permit direct calls to those tools.` + : executionAllowedTools === undefined + ? '' + : executionAllowedTools.length === 0 + ? `\n\nTOOL EXECUTION RESTRICTION: You may not execute any tools, even though tool declarations remain visible. Do not attempt tool calls.` - : `\n\nTOOL EXECUTION RESTRICTION: + : `\n\nTOOL EXECUTION RESTRICTION: You may execute only tools matched by this allowlist: ${JSON.stringify(executionAllowedTools)}. Other visible tool declarations are unavailable to you. Do not call them.`; const profileGuidance = promptHint From f183ce03d90d9a9b9f6e5d9190ee11283ec5862d Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:03:39 +0800 Subject: [PATCH 12/49] fix(core): align hybrid tool visibility and prompt budgets --- .../agents/background-agent-resume.test.ts | 112 ++++++++++++++- .../src/agents/background-agent-resume.ts | 4 + .../agent-core.skill-eager-review.test.ts | 90 ++++++++++++ .../runtime/agent-core.skill-gate.test.ts | 12 +- .../core/src/agents/runtime/agent-core.ts | 11 ++ .../runtime/subagent-plan-tool-policy.ts | 41 ++++-- ...ubagent-manager.skill-eager-review.test.ts | 130 ++++++++++++++++++ .../core/src/subagents/subagent-manager.ts | 32 ++++- .../agent/agent.code-mode-review.test.ts | 62 +++++++++ packages/core/src/tools/agent/agent.ts | 2 + .../core/src/tools/agent/fork-subagent.ts | 12 +- ...l-registry.code-mode-budget-review.test.ts | 96 +++++++++++++ packages/core/src/tools/tool-registry.ts | 60 ++++++-- 13 files changed, 638 insertions(+), 26 deletions(-) create mode 100644 packages/core/src/agents/runtime/agent-core.skill-eager-review.test.ts create mode 100644 packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts create mode 100644 packages/core/src/tools/agent/agent.code-mode-review.test.ts create mode 100644 packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts diff --git a/packages/core/src/agents/background-agent-resume.test.ts b/packages/core/src/agents/background-agent-resume.test.ts index 77cbde0858b..6fcdd189dca 100644 --- a/packages/core/src/agents/background-agent-resume.test.ts +++ b/packages/core/src/agents/background-agent-resume.test.ts @@ -188,6 +188,7 @@ describe('BackgroundAgentResumeService', () => { * negative rows pass vacuously. */ registeredToolNames?: string[]; + skillVisibility?: 'hidden' | 'visible'; toolMode?: ToolMode; hookSystem?: | { @@ -254,6 +255,8 @@ describe('BackgroundAgentResumeService', () => { .fn() .mockReturnValue(options.deferredToolSummary ?? []), isDeferredToolRevealed: vi.fn().mockReturnValue(false), + isPermissionDeferred: (name: string) => + name === ToolNames.SKILL && options.skillVisibility !== undefined, getMcpServerInstructions: vi .fn() .mockReturnValue(options.mcpServerInstructions ?? new Map()), @@ -294,6 +297,8 @@ describe('BackgroundAgentResumeService', () => { getStopHookBlockingCap: () => options.stopHookBlockingCap ?? 8, getApprovalMode: () => 'default', getToolMode: () => options.toolMode, + getVisibleTools: () => + new Set(options.skillVisibility === 'visible' ? [ToolNames.SKILL] : []), getModel: () => 'parent-model', getBareMode: () => false, getSandbox: () => undefined, @@ -1186,9 +1191,106 @@ describe('BackgroundAgentResumeService', () => { boolean, ToolMode?, boolean?, + ('hidden' | 'visible')?, ] >([ ['inherits every tool', {}, true], + [ + 'CodeMode * with hidden eager Skill', + { tools: ['*'] }, + false, + ToolMode.CodeMode, + true, + 'hidden', + ], + [ + 'CodeMode * with visible eager Skill', + { tools: ['*'] }, + true, + ToolMode.CodeMode, + true, + 'visible', + ], + [ + 'CodeMode skill with hidden eager Skill', + { tools: ['skill'] }, + false, + ToolMode.CodeMode, + true, + 'hidden', + ], + [ + 'CodeMode skill with visible eager Skill', + { tools: ['skill'] }, + true, + ToolMode.CodeMode, + true, + 'visible', + ], + [ + 'CodeMode exec with hidden eager Skill', + { tools: ['exec'] }, + false, + ToolMode.CodeMode, + true, + 'hidden', + ], + [ + 'CodeMode exec with visible eager Skill', + { tools: ['exec'] }, + true, + ToolMode.CodeMode, + true, + 'visible', + ], + [ + 'CodeModeOnly * with hidden eager Skill', + { tools: ['*'] }, + true, + ToolMode.CodeModeOnly, + true, + 'hidden', + ], + [ + 'CodeModeOnly * with visible eager Skill', + { tools: ['*'] }, + true, + ToolMode.CodeModeOnly, + true, + 'visible', + ], + [ + 'CodeModeOnly skill with hidden eager Skill', + { tools: ['skill'] }, + true, + ToolMode.CodeModeOnly, + true, + 'hidden', + ], + [ + 'CodeModeOnly skill with visible eager Skill', + { tools: ['skill'] }, + true, + ToolMode.CodeModeOnly, + true, + 'visible', + ], + [ + 'CodeModeOnly exec with hidden eager Skill', + { tools: ['exec'] }, + true, + ToolMode.CodeModeOnly, + true, + 'hidden', + ], + [ + 'CodeModeOnly exec with visible eager Skill', + { tools: ['exec'] }, + true, + ToolMode.CodeModeOnly, + true, + 'visible', + ], [ 'disallows the Skill tool', { tools: ['*'], disallowedTools: [ToolNames.SKILL] }, @@ -1255,7 +1357,14 @@ describe('BackgroundAgentResumeService', () => { ], ])( 'matches the launch-time skill listing when the definition %s', - async (_label, toolFields, expectListing, toolMode, hasExec = false) => { + async ( + _label, + toolFields, + expectListing, + toolMode, + hasExec = false, + skillVisibility, + ) => { const sessionId = 'session-skill-listing'; const agentId = 'agent-skill-listing'; const metaPath = getAgentMetaPath(tempDir, sessionId, agentId); @@ -1311,6 +1420,7 @@ describe('BackgroundAgentResumeService', () => { }; const { service, subagentManager } = createService({ toolMode, + skillVisibility, // The session this resume runs in does have the Skill tool; the rows // below are about `subagentWillHaveSkillTool`, not about #12838's // registry gate. Omitting this made every row answer "no listing" for diff --git a/packages/core/src/agents/background-agent-resume.ts b/packages/core/src/agents/background-agent-resume.ts index fbc371862fd..8edee057866 100644 --- a/packages/core/src/agents/background-agent-resume.ts +++ b/packages/core/src/agents/background-agent-resume.ts @@ -77,6 +77,7 @@ import { } from './runtime/agent-core.js'; import { hasAgentSkillExecBinding, + isAgentSkillEagerHidden, toolConfigAllowsSkill, } from './runtime/subagent-plan-tool-policy.js'; import { toolSearchBridgeSentence } from '../skills/bundled-reference.js'; @@ -141,6 +142,7 @@ const CONTAINER_EXECUTION_BLOCKED_REASON = function subagentWillHaveSkillTool( subagentConfig: SubagentConfig | undefined, execBindingsAvailable = false, + skillEagerHidden = false, ): boolean { // Launch reads `config.tools?.length ? resolveToolNames(config.tools) : ['*']`, // and `resolveToolNames`' `for...of` walks a bare string per character, @@ -169,6 +171,7 @@ function subagentWillHaveSkillTool( : undefined, }, execBindingsAvailable, + skillEagerHidden, ); } @@ -1019,6 +1022,7 @@ export class BackgroundAgentResumeService { includeAvailableSkillsReminder: subagentWillHaveSkillTool( target.subagentConfig, hasAgentSkillExecBinding(activeAgentConfig), + isAgentSkillEagerHidden(activeAgentConfig), ), }) )[0], diff --git a/packages/core/src/agents/runtime/agent-core.skill-eager-review.test.ts b/packages/core/src/agents/runtime/agent-core.skill-eager-review.test.ts new file mode 100644 index 00000000000..6434a63c90e --- /dev/null +++ b/packages/core/src/agents/runtime/agent-core.skill-eager-review.test.ts @@ -0,0 +1,90 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it, vi } from 'vitest'; +import { AgentCore } from './agent-core.js'; +import { makeFakeConfig } from '../../test-utils/config.js'; +import { MockTool } from '../../test-utils/mock-tool.js'; +import { ToolRegistry } from '../../tools/tool-registry.js'; +import { ToolNames } from '../../tools/tool-names.js'; +import { ToolMode } from '../../tools/code-mode.js'; +import { ExecTool } from '../../tools/exec.js'; + +describe('Skill announcement for eager-hidden subagent tools', () => { + it.each( + [ToolMode.CodeMode, ToolMode.CodeModeOnly].flatMap((mode) => + [false, true].flatMap((warm) => + ['hidden', 'visible', 'revealed'].flatMap((visibility) => + [false, true].flatMap((copyRegistry) => + [['*'], [ToolNames.SKILL], [ToolNames.EXEC]].map((tools) => ({ + mode, + warm, + visibility, + copyRegistry, + tools, + })), + ), + ), + ), + ), + )( + 'matches invocation for $mode tools=$tools warm=$warm visibility=$visibility copied=$copyRegistry', + async ({ mode, warm, visibility, copyRegistry, tools }) => { + const config = makeFakeConfig({ toolMode: mode }); + const makeRegistry = () => { + const registry = new ToolRegistry(config); + registry.registerTool(new ExecTool(config)); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + return registry; + }; + let registry = makeRegistry(); + vi.spyOn(config, 'getToolRegistry').mockImplementation(() => registry); + if (warm || visibility === 'revealed') { + await registry.ensureTool(ToolNames.SKILL); + } + if (visibility === 'visible') { + vi.spyOn(config, 'getVisibleTools').mockReturnValue( + new Set([ToolNames.SKILL]), + ); + } else if (visibility === 'revealed') { + registry.revealDeferredTool(ToolNames.SKILL); + } + if (copyRegistry) { + const childRegistry = makeRegistry(); + childRegistry.copyDiscoveredToolsFrom(registry); + registry = childRegistry; + } + const core = new AgentCore( + 'skill-eager-review', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools }, + ); + const observed = core as unknown as { + willHaveSkillTool(): boolean; + canInvokeSkill(names: ReadonlySet): boolean; + }; + const announced = observed.willHaveSkillTool(); + const declared = new Set( + (await core.prepareTools()).map((declaration) => declaration.name), + ); + const invokable = observed.canInvokeSkill(declared); + const expected = + mode === ToolMode.CodeModeOnly || + visibility === 'visible' || + (visibility === 'revealed' && !copyRegistry); + + expect.soft(invokable).toBe(expected); + expect.soft(announced).toBe(expected); + expect(announced).toBe(invokable); + }, + ); +}); diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 71b6f1b31f8..ac0272f7d83 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -311,6 +311,10 @@ describe('AgentCore skill-gate inputs', () => { ); } expect(registry.getTool(ToolNames.EXEC)).toBeUndefined(); + registry.registerFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); const core = new AgentCore( 'lazy-exec-skill-listing', config, @@ -369,7 +373,9 @@ describe('AgentCore skill-gate inputs', () => { } else if (visibility === 'revealed') { registry.revealDeferredTool(ToolNames.SKILL); } - const parentExecBinding = hasAgentSkillExecBinding(config); + expect(hasAgentSkillExecBinding(config)).toBe( + mode === ToolMode.CodeModeOnly || visibility !== 'hidden', + ); const childRegistry = new ToolRegistry(config); childRegistry.registerTool(new ExecTool(config)); childRegistry.registerPermissionDeferredFactory( @@ -381,7 +387,9 @@ describe('AgentCore skill-gate inputs', () => { expect(childRegistry.isDeferredToolRevealed(ToolNames.SKILL)).toBe( false, ); - expect(hasAgentSkillExecBinding(config)).toBe(parentExecBinding); + expect(hasAgentSkillExecBinding(config)).toBe( + mode === ToolMode.CodeModeOnly || visibility === 'visible', + ); const core = new AgentCore( 'skill-route', config, diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 6bb57556b27..428ba0516e7 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -149,6 +149,7 @@ import { isPlanLifecycleToolUnavailableInSubagent, isToolExcludedForCurrentContext, hasAgentSkillExecBinding, + isAgentSkillEagerHidden, matchesAgentToolBlocklist, toolConfigAllowsSkill, } from './subagent-plan-tool-policy.js'; @@ -658,9 +659,19 @@ export class AgentCore { * disallowed `skill` was still shown every skill it could not load. */ private willHaveSkillTool(): boolean { + if ( + this.runtimeContext.getToolMode?.() === ToolMode.CodeMode && + !this.runtimeContext + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL) + ) { + return false; + } return toolConfigAllowsSkill( this.toolConfig, hasAgentSkillExecBinding(this.runtimeContext), + isAgentSkillEagerHidden(this.runtimeContext), ); } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 9fd88bb766c..a66e60dac67 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -89,19 +89,40 @@ export const EXCLUDED_TOOLS_FOR_SUBAGENTS: ReadonlySet = new Set([ ToolNames.MANAGE_MEMORY, ]); +type AgentSkillContext = Pick< + Config, + 'getToolMode' | 'getToolRegistry' | 'getVisibleTools' +>; + +export function isAgentSkillEagerHidden( + context: AgentSkillContext, + registryWillBeRebuilt = false, +): boolean { + const registry = context.getToolRegistry?.(); + // Lazy factories may not have a Tool instance yet. Registry rebuilds copy + // discovery metadata, but deliberately leave transient reveals behind. + return ( + context.getToolMode?.() === ToolMode.CodeMode && + registry?.isPermissionDeferred?.(ToolNames.SKILL) === true && + !context.getVisibleTools?.().has(ToolNames.SKILL) && + (registryWillBeRebuilt || + registry?.isDeferredToolRevealed?.(ToolNames.SKILL) !== true) + ); +} + export function hasAgentSkillExecBinding( - context: Pick, + context: AgentSkillContext, + registryWillBeRebuilt = false, ): boolean { const mode = context.getToolMode?.(); - const registry = context.getToolRegistry?.(); return ( mode === ToolMode.CodeModeOnly || (mode === ToolMode.CodeMode && - !!registry?.getAllToolNames().includes(ToolNames.EXEC) && - !( - registry?.isPermissionDeferred?.(ToolNames.SKILL) === true && - !context.getVisibleTools?.().has(ToolNames.SKILL) - )) + !!context + .getToolRegistry?.() + ?.getAllToolNames() + .includes(ToolNames.EXEC) && + !isAgentSkillEagerHidden(context, registryWillBeRebuilt)) ); } @@ -122,7 +143,8 @@ export function hasAgentSkillExecBinding( * Callers supply whether exec bindings are reachable in the current mode and * registry. A finite list naming exec can therefore reach Skill without * naming it directly. CodeModeOnly retains eager-deferred nested targets; - * Hybrid applies its final eager and permission scope in prepareTools(). + * The eager-hidden input vetoes every route in Hybrid, including wildcards + * and explicit Skill entries. Other permission bounds stay in prepareTools(). * Registry deny/exclude rules remain the bundled-reference resolver's concern; * this predicate supplies the per-agent policy that resolver cannot see. * @@ -138,8 +160,9 @@ export function hasAgentSkillExecBinding( export function toolConfigAllowsSkill( toolConfig: ToolConfig | undefined, execBindingsAvailable = false, + skillEagerHidden = false, ): boolean { - if (EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { + if (skillEagerHidden || EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { return false; } // No per-agent config inherits the whole registry. diff --git a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts new file mode 100644 index 00000000000..9bb756095f1 --- /dev/null +++ b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { Config } from '../config/config.js'; +import type { ToolConfig } from '../agents/runtime/agent-types.js'; +import { makeFakeConfig } from '../test-utils/config.js'; +import { PermissionManager } from '../permissions/permission-manager.js'; +import { SubagentManager } from './subagent-manager.js'; +import { AgentHeadless } from '../agents/runtime/agent-headless.js'; +import { AgentCore } from '../agents/runtime/agent-core.js'; +import { resolveAgentDelegationSurface } from '../skills/agent-delegation-skill.js'; +import { ToolMode } from '../tools/code-mode.js'; + +describe('nested agents retain their actual Skill availability', () => { + it.each([ + { mode: ToolMode.CodeMode, visible: false }, + { mode: ToolMode.CodeMode, visible: true }, + { mode: ToolMode.CodeModeOnly, visible: false }, + ])( + 'preserves Skill policy in $mode visible=$visible', + async ({ mode, visible }) => { + const config = makeFakeConfig({ + targetDir: process.cwd(), + cwd: process.cwd(), + toolMode: mode, + eagerTools: ['exec', 'agent', ...(visible ? ['skill'] : [])], + coreTools: ['exec', 'agent', 'skill', 'tool_search', 'tool_call'], + }); + const skills = { + addChangeListener: () => () => {}, + listSkills: async () => [], + getCachedSkills: () => [], + hasDiscoveryErrors: () => false, + isSkillActive: () => true, + }; + const permissions = new PermissionManager(config); + permissions.initialize(); + vi.spyOn(config, 'getPermissionManager').mockReturnValue(permissions); + vi.spyOn(config, 'getSkillManager').mockReturnValue(skills as never); + const manager = new SubagentManager(config); + vi.spyOn(manager, 'listSubagents').mockResolvedValue([]); + vi.spyOn(config, 'getSubagentManager').mockReturnValue(manager); + const rootRegistry = await config.createToolRegistry(undefined, { + skipDiscovery: true, + }); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(rootRegistry); + + let capture: + | { context: Config; tools: ToolConfig | undefined } + | undefined; + const createSpy = vi + .spyOn(AgentHeadless, 'create') + .mockImplementation( + async (_name, context, _prompt, _model, _run, tools) => { + capture = { context, tools }; + return { + getCore: () => ({ subagentId: 'skill-eager-review' }), + } as unknown as AgentHeadless; + }, + ); + const handles: Array<{ dispose(): Promise }> = []; + let parent = config; + const expected = mode === ToolMode.CodeModeOnly || visible; + try { + for (let depth = 1; depth <= 3; depth++) { + handles.push( + await manager.createAgentHeadless( + { + name: `skill-eager-review-${depth}`, + description: 'Isolated nested Skill test', + systemPrompt: 'Inspect Skill availability only.', + level: 'session', + ...(depth === 2 ? { tools: ['exec', 'agent'] } : {}), + }, + parent, + ), + ); + expect(capture).toBeDefined(); + const { context, tools } = capture!; + const core = new AgentCore( + 'skill-eager-review', + context, + { systemPrompt: 'Inspect Skill availability only.' }, + { model: 'test-model' }, + { max_turns: 1 }, + tools, + ); + const observed = core as unknown as { + willHaveSkillTool(): boolean; + canInvokeSkill(names: ReadonlySet): boolean; + }; + const announced = observed.willHaveSkillTool(); + const declared = new Set( + (await core.prepareTools()).map((declaration) => declaration.name), + ); + expect + .soft(!!context.getSkillManager(), `depth ${depth}`) + .toBe(expected); + expect + .soft(announced, `announcement at depth ${depth}`) + .toBe(expected); + expect + .soft( + observed.canInvokeSkill(declared), + `invocation at depth ${depth}`, + ) + .toBe(expected); + if (!expected) { + expect + .soft( + resolveAgentDelegationSurface(context), + `pointer at depth ${depth}`, + ) + .toBe('inline'); + } + parent = context; + } + } finally { + createSpy.mockRestore(); + for (const handle of handles.reverse()) await handle.dispose(); + await rootRegistry.stop(); + vi.restoreAllMocks(); + } + }, + ); +}); diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 88e216532df..2422f63812b 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -88,8 +88,10 @@ import { hasRebuiltToolRegistry, rebuildToolRegistryOnOverride, } from '../tools/agent/agent.js'; +import { ToolMode } from '../tools/code-mode.js'; import { hasAgentSkillExecBinding, + isAgentSkillEagerHidden, toolConfigAllowsSkill, } from '../agents/runtime/subagent-plan-tool-policy.js'; @@ -1184,9 +1186,37 @@ export class SubagentManager { modelConfig.reasoningEffort, ); + const skillRegistryWillBeRebuilt = + !!Object.keys(config.mcpServers ?? {}).length || + !hasRebuiltToolRegistry(runtimeContext) || + sessionSkillManager(runtimeContext) !== + runtimeContext.getSkillManager(); + let skillEagerHidden = isAgentSkillEagerHidden( + runtimeContext, + skillRegistryWillBeRebuilt, + ); + if ( + skillRegistryWillBeRebuilt && + runtimeContext.getToolMode?.() === ToolMode.CodeMode && + !runtimeContext + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL) + ) { + // A parent without a SkillManager omits the Skill factory entirely. + // Recover its registration policy before restoring skills to a child. + const status = await runtimeContext + .getPermissionManager?.() + ?.getToolRegistrationStatus(ToolNames.SKILL); + skillEagerHidden = + status === 'disabled' || + (status === 'deferred' && + !runtimeContext.getVisibleTools().has(ToolNames.SKILL)); + } const skillsAvailable = toolConfigAllowsSkill( toolConfig, - hasAgentSkillExecBinding(runtimeContext), + hasAgentSkillExecBinding(runtimeContext, skillRegistryWillBeRebuilt), + skillEagerHidden, ); const { context: subagentContext, cleanup } = await this.buildSubagentContextOverride( diff --git a/packages/core/src/tools/agent/agent.code-mode-review.test.ts b/packages/core/src/tools/agent/agent.code-mode-review.test.ts new file mode 100644 index 00000000000..38e0fadfa01 --- /dev/null +++ b/packages/core/src/tools/agent/agent.code-mode-review.test.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { buildChildMessage } from './fork-subagent.js'; +import { makeFakeConfig } from '../../test-utils/config.js'; +import { MockTool } from '../../test-utils/mock-tool.js'; +import { ToolRegistry } from '../tool-registry.js'; +import { ExecTool } from '../exec.js'; +import { ToolMode } from '../code-mode.js'; +import { ToolNames } from '../tool-names.js'; + +describe('Code-mode fork restriction matches declared call surfaces', () => { + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'only advertises possible direct calls in %s', + (mode) => { + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + const declarationNames = new Set( + registry + .getFunctionDeclarationsFiltered([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ]) + .map((declaration) => declaration.name), + ); + const message = buildChildMessage( + 'Inspect the implementation', + [ToolNames.READ_FILE], + undefined, + [ToolNames.READ_FILE], + mode, + ); + const directClaim = message.match(/direct-call allowlist: (\[[^\n]*\])/); + const claimedDirectTools: string[] = directClaim + ? JSON.parse(directClaim[1]) + : []; + + expect(declarationNames.has(ToolNames.EXEC)).toBe(true); + expect(message).toContain( + 'Inside exec, only these exact nested tool names are permitted: ["read_file"]', + ); + for (const name of claimedDirectTools) { + expect( + declarationNames.has(name), + `${name} is not directly declared`, + ).toBe(true); + } + if (mode === ToolMode.CodeMode) { + expect(claimedDirectTools).toContain(ToolNames.READ_FILE); + } else { + expect(declarationNames.has(ToolNames.READ_FILE)).toBe(false); + expect(claimedDirectTools).not.toContain(ToolNames.READ_FILE); + } + }, + ); +}); diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index de32ad58a54..5c958d6c1fd 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -1981,6 +1981,7 @@ class AgentToolInvocation extends BaseToolInvocation { requestedExecutionAllowedTools, profilePromptHint, nestedExecutionAllowedTools, + agentConfig.getToolMode?.(), ); if (forkedMessages.length > 0) { // Model had function calls: append tool responses + directive, @@ -2015,6 +2016,7 @@ class AgentToolInvocation extends BaseToolInvocation { requestedExecutionAllowedTools, profilePromptHint, nestedExecutionAllowedTools, + agentConfig.getToolMode?.(), ); } diff --git a/packages/core/src/tools/agent/fork-subagent.ts b/packages/core/src/tools/agent/fork-subagent.ts index f1c9f8511ad..166e9608e03 100644 --- a/packages/core/src/tools/agent/fork-subagent.ts +++ b/packages/core/src/tools/agent/fork-subagent.ts @@ -4,6 +4,7 @@ import type { Config } from '../../config/config.js'; import type { SubagentConfig } from '../../subagents/types.js'; import { BUBBLE_APPROVAL_MODE } from '../../subagents/types.js'; import { ToolNames } from '../tool-names.js'; +import { ToolMode } from '../code-mode.js'; import { getStartupContextLength, isSystemReminderContent, @@ -310,6 +311,7 @@ export function buildForkedMessages( executionAllowedTools?: readonly string[], promptHint?: string, nestedExecutionAllowedTools?: readonly string[], + toolMode?: ToolMode, ): Content[] { const toolUseParts = assistantMessage.parts?.filter((part) => part.functionCall) || []; @@ -362,6 +364,7 @@ export function buildForkedMessages( executionAllowedTools, promptHint, nestedExecutionAllowedTools, + toolMode, ), }, ], @@ -416,13 +419,18 @@ export function buildChildMessage( executionAllowedTools?: readonly string[], promptHint?: string, nestedExecutionAllowedTools?: readonly string[], + toolMode?: ToolMode, ): string { const executionRestriction = nestedExecutionAllowedTools !== undefined ? `\n\nTOOL EXECUTION RESTRICTION: -You may call exec and tools matched by this direct-call allowlist: ${JSON.stringify(executionAllowedTools ?? [])}. +${ + toolMode === ToolMode.CodeModeOnly + ? `You may call exec and, when declared, tool_search. Ordinary tools are reachable only inside exec; other declared direct-only control tools must also match this allowlist: ${JSON.stringify(executionAllowedTools ?? [])}.` + : `You may call exec and declared tools matched by this direct-call allowlist: ${JSON.stringify(executionAllowedTools ?? [])}.` +} Inside exec, only these exact nested tool names are permitted: ${JSON.stringify(nestedExecutionAllowedTools)}. -Nested permission does not permit direct calls to those tools.` +A nested allowance alone does not authorize a direct call; direct calls must satisfy the mode and direct-call allowlist above.` : executionAllowedTools === undefined ? '' : executionAllowedTools.length === 0 diff --git a/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts b/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts new file mode 100644 index 00000000000..96b1eb29dbf --- /dev/null +++ b/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { makeFakeConfig } from '../test-utils/config.js'; +import { MockTool } from '../test-utils/mock-tool.js'; +import { CHARS_PER_TOKEN } from '../services/tokenEstimation.js'; +import { ToolRegistry } from './tool-registry.js'; +import { ToolMode } from './code-mode.js'; +import { ToolNames } from './tool-names.js'; +import { ExecTool } from './exec.js'; + +const target = () => + new MockTool({ + name: 'deferred', + description: 'Budget-controlled deferred tool. '.repeat(80), + shouldDefer: true, + params: { + type: 'object', + properties: { path: { type: 'string' } }, + required: ['path'], + }, + }); + +function fixture(mode: ToolMode, hiddenExec = false) { + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + registry.registerTool(new MockTool({ name: ToolNames.TOOL_SEARCH })); + registry.registerTool(new MockTool({ name: ToolNames.TOOL_CALL })); + if (mode === ToolMode.CodeMode) { + if (hiddenExec) { + registry.registerPermissionDeferredFactory( + ToolNames.EXEC, + async () => new ExecTool(config), + ); + } else { + registry.registerTool(new ExecTool(config)); + } + } + const deferred = target(); + registry.registerTool(deferred); + return { registry, deferred }; +} + +describe('Code-mode preload follows actual declaration growth', () => { + it('keeps Direct preload at the raw-schema budget', () => { + const { registry, deferred } = fixture(ToolMode.Direct); + const rawTokens = Math.ceil( + JSON.stringify(deferred.schema).length / CHARS_PER_TOKEN, + ); + expect(registry.preloadDeferredToolsWithinBudget(rawTokens - 1)).toBe(0); + expect(registry.preloadDeferredToolsWithinBudget(rawTokens)).toBe(1); + }); + + it('keeps real exec declared even from a permission-deferred factory', async () => { + const { registry, deferred } = fixture(ToolMode.CodeMode, true); + await registry.warmAll(); + const rawTokens = Math.ceil( + JSON.stringify(deferred.schema).length / CHARS_PER_TOKEN, + ); + const before = registry.getFunctionDeclarations(); + expect(registry.isPermissionDeferred(ToolNames.EXEC)).toBe(true); + expect(before.some((item) => item.name === ToolNames.EXEC)).toBe(true); + + expect(registry.preloadDeferredToolsWithinBudget(rawTokens)).toBe(0); + expect(registry.isDeferredToolRevealed(deferred.name)).toBe(false); + }); + + it('rejects a budget that fits the target declaration but not the actual prompt growth', () => { + const measuring = fixture(ToolMode.CodeMode); + const before = measuring.registry.getFunctionDeclarations(); + measuring.registry.revealDeferredTool(measuring.deferred.name); + const after = measuring.registry.getFunctionDeclarations(); + const targetDeclaration = after.find( + (item) => item.name === measuring.deferred.name, + ); + const ownSchemaTokens = Math.ceil( + JSON.stringify(targetDeclaration).length / CHARS_PER_TOKEN, + ); + const actualGrowthTokens = Math.ceil( + (JSON.stringify(after).length - JSON.stringify(before).length) / + CHARS_PER_TOKEN, + ); + expect(actualGrowthTokens).toBeGreaterThan(ownSchemaTokens); + + const { registry, deferred } = fixture(ToolMode.CodeMode); + expect( + registry.preloadDeferredToolsWithinBudget(ownSchemaTokens), + `Own schema budget ${ownSchemaTokens}, actual growth ${actualGrowthTokens}`, + ).toBe(0); + expect(registry.isDeferredToolRevealed(deferred.name)).toBe(false); + }); +}); diff --git a/packages/core/src/tools/tool-registry.ts b/packages/core/src/tools/tool-registry.ts index 45aa0384a63..2603ea429e7 100644 --- a/packages/core/src/tools/tool-registry.ts +++ b/packages/core/src/tools/tool-registry.ts @@ -1433,18 +1433,16 @@ export class ToolRegistry { const candidates: string[] = []; let totalChars = 0; const execTool = this.tools.get(ToolNames.EXEC); - const codeModeBindings = - this.config.getToolMode?.() === ToolMode.CodeMode && - execTool !== undefined && - this.isToolAvailable(execTool.name) && - this.isToolDeclared(execTool.name) - ? new Map( - this.getCodeModeBindingPlan().bindings.map((binding) => [ - binding.name, - binding, - ]), - ) + const declaredNames = + this.config.getToolMode?.() === ToolMode.CodeMode + ? new Set(this.getFunctionDeclarations().map((tool) => tool.name)) : undefined; + const codeModePlan = declaredNames?.has(ToolNames.EXEC) + ? this.getCodeModeBindingPlan() + : undefined; + const codeModeBindings = codeModePlan + ? new Map(codeModePlan.bindings.map((binding) => [binding.name, binding])) + : undefined; for (const tool of this.tools.values()) { if (!this.isToolAvailable(tool.name)) continue; if (!this.isEffectivelyDeferred(tool) || tool.alwaysLoad) continue; @@ -1464,6 +1462,46 @@ export class ToolRegistry { : tool.schema, ).length; } + if (codeModePlan && execTool && declaredNames) { + const candidateNames = new Set(candidates); + // Compare complete exec declarations without changing registry state. + // Treat prior reveals as hidden in the baseline so repeated preloads + // keep charging their footprint instead of ratcheting past the budget. + const execChars = (revealed: boolean): number => { + const topLevelBindingNames = new Set( + [...declaredNames].filter( + (name): name is string => + name !== undefined && !candidateNames.has(name), + ), + ); + if (revealed) { + for (const name of candidates) topLevelBindingNames.add(name); + } + const hasToolCallBridge = + topLevelBindingNames.has(ToolNames.TOOL_SEARCH) && + topLevelBindingNames.has(ToolNames.TOOL_CALL); + return JSON.stringify( + buildExecDeclaration( + execTool, + { + ...codeModePlan, + bindings: codeModePlan.bindings.map((binding) => + candidateNames.has(binding.name) + ? { ...binding, deferred: !revealed } + : binding, + ), + }, + { + codeModeOnly: false, + topLevelBindingNames, + canSearchDeferredSchemas: hasToolCallBridge, + hasToolCallBridge, + }, + ), + ).length; + }; + totalChars += Math.max(0, execChars(true) - execChars(false)); + } const estimatedTokens = Math.ceil(totalChars / CHARS_PER_TOKEN); if (candidates.length === 0) { debugLogger.debug( From 71b85020805090632c385d806912a8a0801555eb Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Thu, 8 Oct 2026 15:08:52 +0000 Subject: [PATCH 13/49] fix(core): keep nested-only allowlists from revoking hybrid direct declarations prepareTools() built hybrid declarationNames from the pool already narrowed by the nested execution predicate, so a nested-only allowlist silently revoked a tool's direct declaration while the direct gate still permitted the call. Hybrid declarations now draw from a pool filtered by the direct predicate; the exec binding set and the CodeModeOnly branch keep the nested-filtered pool. toolConfigAllowsSkill() also credited a configured exec entry without consulting the config's own executionAllowedTools / nestedExecutionAllowedTools bounds, so the skill listing could announce a nested route canInvokeSkill() refuses. The exec route now counts only when those bounds keep it open, closing the listing/gate divergence for the fork shape that names exec in tools but not in the execution allowlist. --- .../runtime/agent-core.skill-gate.test.ts | 79 +++++++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 46 ++++++----- .../runtime/subagent-plan-tool-policy.ts | 11 ++- 3 files changed, 114 insertions(+), 22 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index ac0272f7d83..3d41d0e9e11 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -748,6 +748,85 @@ describe('AgentCore skill-gate inputs', () => { ); }); + it('keeps direct declarations a nested-only allowlist does not name', async () => { + // A nested-only allowlist is additive-only: it narrows the exec + // binding set, never the direct declaration surface. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'nested-only-allowlist-keeps-direct', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: ['*'], + executionAllowedTools: [ + ToolNames.EXEC, + ToolNames.READ_FILE, + ToolNames.WRITE_FILE, + ], + nestedExecutionAllowedTools: [ToolNames.READ_FILE], + }, + ); + + const declarations = await core.prepareTools(); + expect(declarations.map((declaration) => declaration.name)).toEqual([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ToolNames.WRITE_FILE, + ]); + expect(executable(core, ToolNames.WRITE_FILE)).toBe(true); + expect(codeModeAllowed(core)).toEqual([ToolNames.READ_FILE]); + const exec = declarations.find( + (declaration) => declaration.name === ToolNames.EXEC, + ); + expect(exec?.description).toContain('"name":"read_file"'); + expect(exec?.description).not.toContain('"name":"write_file"'); + }); + + it.each([ + { + tools: [ToolNames.EXEC, ToolNames.READ_FILE], + executionAllowedTools: [ToolNames.READ_FILE], + }, + { + tools: [ToolNames.EXEC, ToolNames.READ_FILE, ToolNames.WRITE_FILE], + executionAllowedTools: [] as string[], + nestedExecutionAllowedTools: [ToolNames.READ_FILE], + }, + ])( + 'closes the listing/gate gap when the config bounds the exec route: %j', + async (toolConfig) => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'skill-exec-route-bounded', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + toolConfig, + ); + + const willHaveSkill = ( + core as unknown as { willHaveSkillTool: () => boolean } + ).willHaveSkillTool(); + const declared = await declaredNames(core); + expect(willHaveSkill).toBe(false); + expect(gate(core, declared)).toBe(false); + }, + ); + it('honors MCP execution patterns in the hybrid nested binding set', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 428ba0516e7..d8c7a9baacb 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -740,21 +740,23 @@ export class AgentCore { : new Set(stringTools); const inheritsCodeModeBindings = configuredNames?.has(ToolNames.EXEC) === true; - const allowedNames = toolRegistry - .getAllToolNames() - .filter( - (name) => - (!configuredNames || - configuredNames.has(name) || - name === ToolNames.EXEC || - (inheritsCodeModeBindings && - getToolExposure(name) === 'code-mode-callable')) && - !isExcluded(name) && - (this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly || - !isHiddenByEagerAllowList(name)) && - !this.isToolDisallowedByAgentConfig(name, toolRegistry) && - this.isToolExecutionAllowed(name, true), - ); + const admissionPool = (forNestedBinding: boolean) => + toolRegistry + .getAllToolNames() + .filter( + (name) => + (!configuredNames || + configuredNames.has(name) || + name === ToolNames.EXEC || + (inheritsCodeModeBindings && + getToolExposure(name) === 'code-mode-callable')) && + !isExcluded(name) && + (this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly || + !isHiddenByEagerAllowList(name)) && + !this.isToolDisallowedByAgentConfig(name, toolRegistry) && + this.isToolExecutionAllowed(name, forNestedBinding), + ); + const allowedNames = admissionPool(true); if ( this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly && allowedNames.some( @@ -772,14 +774,18 @@ export class AgentCore { (name) => getToolExposure(name) === 'code-mode-callable', ), ); + // Hybrid declarations draw from a pool filtered by the DIRECT + // predicate: `allowedNames` is nested-filtered, and a nested-only + // allowlist is additive-only — it must never revoke a tool's direct + // declaration (agent-types.ts documents `nestedExecutionAllowedTools` + // as "never grants direct tool calls", not "revokes" either). const declarationNames = this.runtimeContext.getToolMode?.() === ToolMode.CodeMode - ? allowedNames.filter( + ? admissionPool(false).filter( (name) => - (!configuredNames || - name === ToolNames.EXEC || - configuredNames.has(name)) && - this.isToolExecutionAllowed(name), + !configuredNames || + name === ToolNames.EXEC || + configuredNames.has(name), ) : allowedNames; const declarations = toolRegistry.getFunctionDeclarationsFiltered( diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index a66e60dac67..035bc40c800 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -180,9 +180,16 @@ export function toolConfigAllowsSkill( // list holding only inline declarations inherits: both take the explicit // branch there, which declares no registry tool. const inheritsRegistry = names.includes('*'); - // Naming an available exec gateway can reach the nested Skill binding. + // Naming an available exec gateway reaches the nested Skill binding only + // while the config's own execution bounds keep that route open — + // `canInvokeSkill()` honours both lists, so the listing must too. + const execRouteOpen = + (toolConfig.executionAllowedTools === undefined || + toolConfig.executionAllowedTools.includes(ToolNames.EXEC)) && + (toolConfig.nestedExecutionAllowedTools === undefined || + toolConfig.nestedExecutionAllowedTools.includes(ToolNames.SKILL)); const reachesThroughExec = - execBindingsAvailable && names.includes(ToolNames.EXEC); + execBindingsAvailable && execRouteOpen && names.includes(ToolNames.EXEC); return ( inheritsRegistry || names.includes(ToolNames.SKILL) || reachesThroughExec ); From e81694c643c9bb8f95c02d280d9862a72207be35 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:47:09 +0800 Subject: [PATCH 14/49] fix(core): align Skill listings with exec permission bounds --- .../runtime/agent-core.skill-gate.test.ts | 82 ++++++++++++++++--- .../runtime/subagent-plan-tool-policy.ts | 16 ++-- 2 files changed, 78 insertions(+), 20 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 3d41d0e9e11..233a9b36ff8 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -16,6 +16,7 @@ import { ToolMode } from '../../tools/code-mode.js'; import { CoreToolScheduler } from '../../core/coreToolScheduler.js'; import { ToolSearchTool } from '../../tools/tool-search.js'; import { hasAgentSkillExecBinding } from './subagent-plan-tool-policy.js'; +import type { ToolConfig } from './agent-types.js'; // The skill-announcement gate asks whether the model can INVOKE a skill, and // that is two conditions, not one. @@ -789,20 +790,70 @@ describe('AgentCore skill-gate inputs', () => { expect(exec?.description).not.toContain('"name":"write_file"'); }); - it.each([ + const execSkillPolicies: Array<{ + label: string; + bounds: Omit; + allowed: boolean; + }> = [ + { label: 'unbounded exec', bounds: {}, allowed: true }, { - tools: [ToolNames.EXEC, ToolNames.READ_FILE], - executionAllowedTools: [ToolNames.READ_FILE], + label: 'blocked exec', + bounds: { disallowedTools: [ToolNames.EXEC] }, + allowed: false, }, { - tools: [ToolNames.EXEC, ToolNames.READ_FILE, ToolNames.WRITE_FILE], - executionAllowedTools: [] as string[], - nestedExecutionAllowedTools: [ToolNames.READ_FILE], + label: 'blocked Skill', + bounds: { disallowedTools: [ToolNames.SKILL] }, + allowed: false, }, - ])( - 'closes the listing/gate gap when the config bounds the exec route: %j', - async (toolConfig) => { - const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + { + label: 'explicit Skill execution grant', + bounds: { executionAllowedTools: [ToolNames.SKILL] }, + allowed: true, + }, + { + label: 'exec execution carve-out', + bounds: { executionAllowedTools: [ToolNames.EXEC] }, + allowed: true, + }, + { + label: 'read-only execution', + bounds: { executionAllowedTools: [ToolNames.READ_FILE] }, + allowed: false, + }, + { + label: 'nested Skill with empty direct execution', + bounds: { + executionAllowedTools: [], + nestedExecutionAllowedTools: [ToolNames.SKILL], + }, + allowed: true, + }, + { + label: 'nested read-only with empty direct execution', + bounds: { + executionAllowedTools: [], + nestedExecutionAllowedTools: [ToolNames.READ_FILE], + }, + allowed: false, + }, + { + label: 'nested denial overrides the exec carve-out', + bounds: { + executionAllowedTools: [ToolNames.EXEC], + nestedExecutionAllowedTools: [], + }, + allowed: false, + }, + ]; + it.each( + [ToolMode.Direct, ToolMode.CodeMode, ToolMode.CodeModeOnly].flatMap( + (mode) => execSkillPolicies.map((policy) => ({ ...policy, mode })), + ), + )( + 'matches listing and invocation for $label in $mode', + async ({ bounds, allowed, mode }) => { + const config = makeFakeConfig({ toolMode: mode }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); registry.registerTool(new ExecTool(config)); @@ -815,15 +866,20 @@ describe('AgentCore skill-gate inputs', () => { { systemPrompt: '' }, { model: 'test-model' }, { max_turns: 1 }, - toolConfig, + { tools: [ToolNames.EXEC, ToolNames.READ_FILE], ...bounds }, ); const willHaveSkill = ( core as unknown as { willHaveSkillTool: () => boolean } ).willHaveSkillTool(); const declared = await declaredNames(core); - expect(willHaveSkill).toBe(false); - expect(gate(core, declared)).toBe(false); + const expected = mode !== ToolMode.Direct && allowed; + expect.soft(gate(core, declared)).toBe(expected); + expect(willHaveSkill).toBe(expected); + if (bounds.executionAllowedTools?.length === 0) { + expect(declared.has(ToolNames.SKILL)).toBe(false); + expect(executable(core, ToolNames.SKILL)).toBe(false); + } }, ); diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 035bc40c800..0a259223597 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -180,14 +180,16 @@ export function toolConfigAllowsSkill( // list holding only inline declarations inherits: both take the explicit // branch there, which declares no registry tool. const inheritsRegistry = names.includes('*'); - // Naming an available exec gateway reaches the nested Skill binding only - // while the config's own execution bounds keep that route open — - // `canInvokeSkill()` honours both lists, so the listing must too. + // The exec wrapper does not need an execution-list entry in code modes. + // An explicit nested list is authoritative; otherwise either Skill itself + // or the exec carve-out grants the nested binding, as in AgentCore. const execRouteOpen = - (toolConfig.executionAllowedTools === undefined || - toolConfig.executionAllowedTools.includes(ToolNames.EXEC)) && - (toolConfig.nestedExecutionAllowedTools === undefined || - toolConfig.nestedExecutionAllowedTools.includes(ToolNames.SKILL)); + !matchesAgentToolBlocklist(toolConfig.disallowedTools, ToolNames.EXEC) && + (toolConfig.nestedExecutionAllowedTools !== undefined + ? toolConfig.nestedExecutionAllowedTools.includes(ToolNames.SKILL) + : toolConfig.executionAllowedTools === undefined || + toolConfig.executionAllowedTools.includes(ToolNames.SKILL) || + toolConfig.executionAllowedTools.includes(ToolNames.EXEC)); const reachesThroughExec = execBindingsAvailable && execRouteOpen && names.includes(ToolNames.EXEC); return ( From 5afe0cefc4d0e287242735bd350f04c0e4132aa0 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:03:49 +0800 Subject: [PATCH 15/49] fix(core): preserve direct Skill activation with nested restrictions --- .../runtime/agent-core.skill-gate.test.ts | 40 +++++++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 14 ++++--- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 233a9b36ff8..db234215379 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -790,6 +790,46 @@ describe('AgentCore skill-gate inputs', () => { expect(exec?.description).not.toContain('"name":"write_file"'); }); + it.each( + [ToolMode.Direct, ToolMode.CodeMode, ToolMode.CodeModeOnly].flatMap( + (toolMode) => [false, true].map((inline) => ({ toolMode, inline })), + ), + )( + 'checks the direct Skill route when nested Skill is excluded in $toolMode, inline=$inline', + async ({ toolMode, inline }) => { + const config = makeFakeConfig({ toolMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + const core = new AgentCore( + 'direct-skill-nested-exclusion', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: inline ? [ToolNames.EXEC, { name: ToolNames.SKILL }] : ['*'], + executionAllowedTools: [ + ToolNames.EXEC, + ToolNames.SKILL, + ToolNames.READ_FILE, + ], + nestedExecutionAllowedTools: [ToolNames.READ_FILE], + }, + ); + const declared = await declaredNames(core); + const hasDirectSkill = toolMode !== ToolMode.CodeModeOnly; + expect(declared.has(ToolNames.SKILL)).toBe(hasDirectSkill || inline); + expect(executable(core, ToolNames.SKILL)).toBe(true); + if (toolMode !== ToolMode.Direct) { + expect(codeModeAllowed(core)).not.toContain(ToolNames.SKILL); + } + expect(gate(core, declared)).toBe(hasDirectSkill); + }, + ); + const execSkillPolicies: Array<{ label: string; bounds: Omit; diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index d8c7a9baacb..41a511b8a57 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -1870,12 +1870,14 @@ export class AgentCore { declaredToolNames: ReadonlySet, ): boolean { return ( - (declaredToolNames.has(ToolNames.SKILL) || - (isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && - declaredToolNames.has(ToolNames.EXEC) && - !!this.runtimeContext.getToolRegistry().getTool(ToolNames.SKILL) && - this.codeModeAllowedToolNames?.includes(ToolNames.SKILL) === true)) && - this.isToolExecutionAllowed(ToolNames.SKILL, true) + (declaredToolNames.has(ToolNames.SKILL) && + this.runtimeContext.getToolMode?.() !== ToolMode.CodeModeOnly && + this.isToolExecutionAllowed(ToolNames.SKILL)) || + (isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && + declaredToolNames.has(ToolNames.EXEC) && + !!this.runtimeContext.getToolRegistry().getTool(ToolNames.SKILL) && + this.codeModeAllowedToolNames?.includes(ToolNames.SKILL) === true && + this.isToolExecutionAllowed(ToolNames.SKILL, true)) ); } From 3dd719a8161f955727dfc0881747de102d0cacba Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Fri, 9 Oct 2026 22:52:32 +0000 Subject: [PATCH 16/49] fix(core): gate the code-mode skill route on exec registration (#11854) hasAgentSkillExecBinding answered true for code_mode_only on the mode alone, so a subagent whose exec was kept out of the registry entirely (a permissions.deny rule or a legacy coreTools allowlist) was still announced skills it could never invoke. Hoist the exec-registration probe ahead of both code-mode arms, reading getAllToolNames() so an unwarmed lazy factory still counts. Also correct the docs that over-promised: the fork_tools pages now disclose that an exec grant under a code mode admits every code-mode-callable tool through nested calls, and the SDK hybrid sentence no longer implies withheld direct-only tools stay reachable through exec. Test hardening: pin the exec-route blocklist conjunct, give the fork code_mode_only claim row a non-vacuous wording-aware assertion, and add the missing accepting half to the code-mode preload budget test. --- docs/developers/sdk-typescript.md | 42 ++++++------ docs/developers/tools/task.md | 4 +- docs/users/features/sub-agents.md | 4 +- .../agents/background-agent-resume.test.ts | 19 ++++-- .../runtime/agent-core.skill-gate.test.ts | 13 ++-- .../runtime/subagent-plan-tool-policy.test.ts | 67 +++++++++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 14 ++-- .../agent/agent.code-mode-review.test.ts | 43 ++++++++++-- ...l-registry.code-mode-budget-review.test.ts | 12 ++++ packages/sdk-typescript/README.md | 42 ++++++------ packages/sdk-typescript/src/types/types.ts | 18 +++-- 11 files changed, 207 insertions(+), 71 deletions(-) diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index 8e421cedc63..d0d6a4959d3 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index c01d1846ce8..409aeadb1da 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -14,7 +14,7 @@ Use `agent` to launch a specialized subagent to handle complex, multi-step tasks - `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution. - `subagent_type` (string, optional): The type of specialized agent to use for this task. Defaults to `general-purpose` if omitted. - `fork_turns` (string, optional): Only valid with `subagent_type="fork"`. Omit it or use `all` for the full parent conversation, or use a positive integer string such as `"3"` for the most recent three real user turns. Tool responses and pure system reminders do not count as turns. -- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns while keeping the fork's current model-visible tool declarations unchanged for prompt-cache sharing. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. +- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns while keeping the fork's current model-visible tool declarations unchanged for prompt-cache sharing. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under a code mode (`tools.mode`), listing `exec` also admits every code-mode-callable tool through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy. - `fork_profile` (string, optional): Only valid with `subagent_type="fork"`. Loads a frontmatter-only regular `.qwen/fork-profiles/.md` of at most 64 KiB from the active project root and applies its required `tools` array plus an optional `promptHint` of at most 200 characters. The file cannot resolve outside the project profile directory. `fork_profile` cannot be combined with `fork_tools` or a named teammate, and it is unavailable in safe mode or bare mode. - `run_in_background` (boolean, optional): Defaults to `true` for top-level regular agents. Set to `false` to wait for a regular agent's result inline. Headless forks always run in the background. Nested agents run in the foreground unless `run_in_background` is explicitly `true`, which is rejected because nested agents cannot receive background completion notifications. Unnamed caller-owned `working_dir` launches run in the foreground: an explicit `run_in_background: true` request is rejected, while a configured background default (`background: true` in a subagent definition) is rejected at the top level and downgraded to the foreground when nested. - `isolation` (string, optional): Set to `"worktree"` to run an explicitly named, non-fork agent in an isolated git worktree that Qwen Code creates and manages. @@ -149,7 +149,7 @@ Don't use the Agent tool for: - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. - **Subagent interaction**: Regular subagents do not receive `ask_user_question`. Forks keep the parent's declaration list for cache sharing but reject that tool before scheduling or approval; when missing user input blocks work, the subagent reports the blocker to its parent. -- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. Disallowed calls return an error before scheduling or approval; the same declaration list remains model-visible for cache sharing. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. +- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. Disallowed calls return an error before scheduling or approval; the same declaration list remains model-visible for cache sharing. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. - **Continuation**: Use `list_agents` and `send_message` for related follow-up work instead of launching a duplicate agent. Continuation depends on compatible retained state and may be unavailable. diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index 32e227dcb61..c6859d978c5 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -54,7 +54,7 @@ Tool responses and pure system reminders do not count as user turns. Regular nam ## Restricting Fork Tool Execution with `fork_tools` -Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. The fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, but its task prompt identifies the restriction and a call not matched by `fork_tools` is rejected before scheduling or approval. +Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. The fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, but its task prompt identifies the restriction and a call not matched by `fork_tools` is rejected before scheduling or approval. One exception: under a code mode (`tools.mode`), listing `exec` admits every code-mode-callable tool through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). - Forks never execute `ask_user_question`; when user input is required, they report the blocker to their parent agent. - Omitting `fork_tools` allows every other inherited tool. @@ -385,7 +385,7 @@ Use `tools` and `disallowedTools` to control which tools a subagent can access. The allowlist applies both to directly declared tools and to targets invoked through the `tool_search`/`tool_call` deferred-tool bridge. An explicit list of ordinary tools does not automatically include either bridge tool; name both `tool_search` and `tool_call` if the agent needs discovery and bridge invocation. A listed ordinary deferred target is declared directly, while a target demoted by `tools.eager` remains hidden unless a separate reveal rule applies. A hidden target must still be present in `tools` to be invoked through the bridge. `disallowedTools` and `permissions.deny` remain additional blocklists, and listing a tool does not bypass the subagent control-plane exclusions. Code Mode (`tools.mode: "code_mode_only"`) differs: `tool_call` is not available, an agent allowed any tool callable from `exec` gets `tool_search` automatically unless `disallowedTools` names it, and tools demoted by `tools.eager` stay callable through `exec`. -With `tools.mode: "code_mode"` or `"code_mode_only"`, `exec` provides a third path: nested `tools.(...)` calls. Explicitly listing `exec` also grants otherwise-admitted code-mode-callable bindings, including ordinary tools such as `write_file` and `run_shell_command` that are not individually listed. Thus `tools: [read_file, exec]` is not a read-only policy. Omit `exec` from the configured list to keep nested targets bounded by the listed names; the runtime still exposes the `exec` wrapper in code mode. `disallowedTools`, `permissions.deny`, and subagent exclusions continue to restrict access in both modes. Hybrid additionally excludes tools hidden by `tools.eager`. This nested grant does not add direct-call permission in hybrid mode. A fork's explicit `fork_tools: [exec]` grant also remains bounded by its parent's inherited execution policy. +With `tools.mode: "code_mode"` or `"code_mode_only"`, `exec` provides a third path: nested `tools.(...)` calls. Explicitly listing `exec` also grants otherwise-admitted code-mode-callable bindings, including ordinary tools such as `write_file` and `run_shell_command` that are not individually listed. Thus `tools: [read_file, exec]` is not a read-only policy. Omit `exec` from the configured list to keep nested targets bounded by the listed names; the runtime still exposes the `exec` wrapper in code mode. `disallowedTools`, `permissions.deny`, and subagent exclusions continue to restrict access in both modes. Hybrid additionally excludes tools hidden by `tools.eager`. This nested grant does not add direct-call permission in hybrid mode. A fork's explicit `fork_tools: [exec]` grant is not an exec-only policy: in both code modes it admits every code-mode-callable tool the parent could reach through the nested path, bounded by the parent's inherited execution policy and blocklists. ``` --- diff --git a/packages/core/src/agents/background-agent-resume.test.ts b/packages/core/src/agents/background-agent-resume.test.ts index 5575a52ba8c..77109124d88 100644 --- a/packages/core/src/agents/background-agent-resume.test.ts +++ b/packages/core/src/agents/background-agent-resume.test.ts @@ -1360,14 +1360,25 @@ describe('BackgroundAgentResumeService', () => { true, ], // Under CodeModeOnly a finite list naming `exec` reaches `skill` through - // the code-mode gateway, so launch keeps the manager and resume must keep - // the listing. Dropping the tool-mode argument at the resume call site — - // the parent Config here reports CodeModeOnly — turns this row red. + // the code-mode gateway while exec is actually registered, so launch + // keeps the manager and resume must keep the listing. Dropping the + // tool-mode argument at the resume call site — the parent Config here + // reports CodeModeOnly — turns this row red. [ - 'names exec without skill under CodeModeOnly', + 'names exec without skill under CodeModeOnly with exec registered', { tools: [ToolNames.EXEC] }, true, ToolMode.CodeModeOnly, + true, + ], + // A deny rule or a legacy coreTools allowlist can keep exec out of the + // registry while the mode says code_mode_only; the agent then has no + // route to skill, so launch keeps no manager and resume must not list. + [ + 'names exec without skill under CodeModeOnly with exec unregistered', + { tools: [ToolNames.EXEC] }, + false, + ToolMode.CodeModeOnly, ], [ 'names exec without skill under Hybrid with registered exec', diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index db234215379..38190875c43 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -21,10 +21,14 @@ import type { ToolConfig } from './agent-types.js'; // The skill-announcement gate asks whether the model can INVOKE a skill, and // that is two conditions, not one. // -// Declared: `willHaveSkillTool()` reads only the `toolConfig` — the name list -// and the `disallowedTools` blocklist — so it is blind to a tool the -// permission layer kept out of the registry and to an inline declaration. So -// the gate reads the declarations `prepareTools` produced. +// Declared: `willHaveSkillTool()` reads the `toolConfig` — the name list and +// the `disallowedTools` blocklist — plus registry state: hybrid `code_mode` +// requires SKILL itself in the registry (a hybrid agent declares only what +// the registry holds), and both code modes require exec to be registered +// because the nested Skill binding runs through it (a deny rule or a legacy +// coreTools allowlist can keep exec out entirely). It stays blind to an +// inline declaration. So the gate reads the declarations `prepareTools` +// produced. // // Executable: being declared is not sufficient. A fork keeps the parent's // declared names for prompt-cache parity while `fork_tools` narrows what may @@ -43,6 +47,7 @@ describe('AgentCore skill-gate inputs', () => { declarations.filter((d) => wanted.includes(d.name as string)), ), getTool: vi.fn().mockReturnValue(undefined), + getAllToolNames: vi.fn().mockReturnValue(names), }; } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index 1bce8404d1f..1eab350b3ce 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -6,11 +6,18 @@ import { describe, expect, it, vi } from 'vitest'; import { ToolNames } from '../../tools/tool-names.js'; +import { ToolMode } from '../../tools/code-mode.js'; +import { makeFakeConfig } from '../../test-utils/config.js'; +import { ToolRegistry } from '../../tools/tool-registry.js'; +import { ExecTool } from '../../tools/exec.js'; +import { MockTool } from '../../test-utils/mock-tool.js'; import { runWithTeammateIdentity } from '../team/identity.js'; import { runWithAgentContext } from './agent-context.js'; import { buildSubagentPlanToolBlockedResult, getSubagentPlanToolUnavailableMessage, + hasAgentSkillExecBinding, + isAgentSkillEagerHidden, isPlanRequiredTeammatePreApprovalAllowedTool, isPlanLifecycleToolUnavailableInSubagent, shouldUsePlanOnlyReminderInSubagentContext, @@ -265,5 +272,65 @@ describe('subagent plan tool policy', () => { ).toBe(false); expect(toolConfigAllowsSkill({ tools: [] }, true)).toBe(false); }); + + it('honours the blocklist on the exec route itself', () => { + // prepareTools() drops an exec the blocklist names, leaving no gateway; + // the listing must not keep crediting the route through it. + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.EXEC], disallowedTools: [ToolNames.EXEC] }, + true, + ), + ).toBe(false); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.EXEC], disallowedTools: [ToolNames.READ_FILE] }, + true, + ), + ).toBe(true); + }); + }); + + describe('hasAgentSkillExecBinding', () => { + const contextWith = (mode: ToolMode, registerExec: boolean) => { + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + if (registerExec) { + registry.registerTool(new ExecTool(config)); + } + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + return config; + }; + + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'reports no exec route in %s when exec was never registered', + (mode) => { + // A deny rule or a legacy coreTools allowlist can keep exec out of + // the registry entirely; the mode alone must not answer true. + const context = contextWith(mode, false); + expect(hasAgentSkillExecBinding(context)).toBe(false); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.EXEC, ToolNames.READ_FILE] }, + hasAgentSkillExecBinding(context), + isAgentSkillEagerHidden(context), + ), + ).toBe(false); + }, + ); + + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'reports the exec route in %s while exec is registered', + (mode) => { + expect(hasAgentSkillExecBinding(contextWith(mode, true))).toBe(true); + }, + ); + + it('reports no exec route in Direct mode even with exec registered', () => { + expect(hasAgentSkillExecBinding(contextWith(ToolMode.Direct, true))).toBe( + false, + ); + }); }); }); diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index d43a3b8de68..6a9f8f24812 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -109,13 +109,19 @@ export function hasAgentSkillExecBinding( registryWillBeRebuilt = false, ): boolean { const mode = context.getToolMode?.(); + // The exec route needs exec itself registered, in either code mode: a deny + // rule or a legacy coreTools allowlist can keep it out of the registry + // while the mode alone still answers code_mode_only. Read registration + // metadata (getAllToolNames counts an unwarmed lazy factory), not + // isDeferredAndHidden — callers run before prepareTools()'s warmAll(). + if ( + !context.getToolRegistry?.()?.getAllToolNames().includes(ToolNames.EXEC) + ) { + return false; + } return ( mode === ToolMode.CodeModeOnly || (mode === ToolMode.CodeMode && - !!context - .getToolRegistry?.() - ?.getAllToolNames() - .includes(ToolNames.EXEC) && !isAgentSkillEagerHidden(context, registryWillBeRebuilt)) ); } diff --git a/packages/core/src/tools/agent/agent.code-mode-review.test.ts b/packages/core/src/tools/agent/agent.code-mode-review.test.ts index 38e0fadfa01..16772195716 100644 --- a/packages/core/src/tools/agent/agent.code-mode-review.test.ts +++ b/packages/core/src/tools/agent/agent.code-mode-review.test.ts @@ -10,7 +10,7 @@ import { makeFakeConfig } from '../../test-utils/config.js'; import { MockTool } from '../../test-utils/mock-tool.js'; import { ToolRegistry } from '../tool-registry.js'; import { ExecTool } from '../exec.js'; -import { ToolMode } from '../code-mode.js'; +import { ToolMode, getToolExposure } from '../code-mode.js'; import { ToolNames } from '../tool-names.js'; describe('Code-mode fork restriction matches declared call surfaces', () => { @@ -21,41 +21,70 @@ describe('Code-mode fork restriction matches declared call surfaces', () => { const registry = new ToolRegistry(config); registry.registerTool(new ExecTool(config)); registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.TOOL_SEARCH })); const declarationNames = new Set( registry .getFunctionDeclarationsFiltered([ ToolNames.EXEC, ToolNames.READ_FILE, + ToolNames.TOOL_SEARCH, ]) .map((declaration) => declaration.name), ); const message = buildChildMessage( 'Inspect the implementation', - [ToolNames.READ_FILE], + [ToolNames.READ_FILE, ToolNames.TOOL_SEARCH], undefined, [ToolNames.READ_FILE], mode, ); - const directClaim = message.match(/direct-call allowlist: (\[[^\n]*\])/); - const claimedDirectTools: string[] = directClaim - ? JSON.parse(directClaim[1]) - : []; + // The producer renders the same list under two wordings: the + // "direct-call" one presents every listed name as directly callable, + // while the plain one bounds only declared direct-only control tools. + // Which wording matched decides how strict the per-name check may be. + const directClaim = message.match( + /(?:direct-call )?allowlist: (\[[^\n]*\])/, + ); + expect( + directClaim, + 'fork message carries a machine-readable direct-call claim', + ).not.toBeNull(); + if (!directClaim) { + throw new Error('fork message carries no direct-call allowlist claim'); + } + const generalClaim = directClaim[0].startsWith('direct-call'); + const claimedDirectTools: string[] = JSON.parse(directClaim[1]); expect(declarationNames.has(ToolNames.EXEC)).toBe(true); expect(message).toContain( 'Inside exec, only these exact nested tool names are permitted: ["read_file"]', ); + let asserted = 0; for (const name of claimedDirectTools) { + // Under the plain wording a code-mode-callable entry is reachable + // only through exec; it is not a direct-call claim. + if ( + !generalClaim && + name !== ToolNames.EXEC && + getToolExposure(name) !== 'direct-only' + ) { + continue; + } + asserted += 1; expect( declarationNames.has(name), `${name} is not directly declared`, ).toBe(true); } + // The invariant this file is named for must run in both rows. + expect(asserted).toBeGreaterThan(0); if (mode === ToolMode.CodeMode) { + expect(generalClaim).toBe(true); expect(claimedDirectTools).toContain(ToolNames.READ_FILE); } else { + expect(generalClaim).toBe(false); expect(declarationNames.has(ToolNames.READ_FILE)).toBe(false); - expect(claimedDirectTools).not.toContain(ToolNames.READ_FILE); + expect(claimedDirectTools).toContain(ToolNames.TOOL_SEARCH); } }, ); diff --git a/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts b/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts index 96b1eb29dbf..935b48df9b6 100644 --- a/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts +++ b/packages/core/src/tools/tool-registry.code-mode-budget-review.test.ts @@ -92,5 +92,17 @@ describe('Code-mode preload follows actual declaration growth', () => { `Own schema budget ${ownSchemaTokens}, actual growth ${actualGrowthTokens}`, ).toBe(0); expect(registry.isDeferredToolRevealed(deferred.name)).toBe(false); + + // The accepting half: a budget that covers the real growth must reveal. + // Every other CodeMode assertion on this method expects 0, so without it + // a code-mode-only overcharge of the exec-delta term would retire the + // startup preload with the suite fully green. + const accepting = fixture(ToolMode.CodeMode); + expect( + accepting.registry.preloadDeferredToolsWithinBudget(actualGrowthTokens), + ).toBe(1); + expect( + accepting.registry.isDeferredToolRevealed(accepting.deferred.name), + ).toBe(true); }); }); diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 49a5bd67921..113b1492ef5 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), exec retains callable nested bindings; their schemas are included in exec when either bridge tool is unavailable. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index b06459d34bf..360a68fd448 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -434,9 +434,12 @@ export interface QueryOptions { * session, a subagent definition change) re-declares. * These bridge and warning rules apply to direct and hybrid code modes. * On the session surface in hybrid mode, while `exec` is registered (container or SSH execution - * warns and falls back to direct tools without it), exec retains callable - * nested bindings; their schemas are included in exec when either bridge - * tool is unavailable. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager + * warns and falls back to direct tools without it), withheld tools that have + * an actual nested exec binding remain callable through exec, and their + * schemas are included in the exec description when either bridge tool is + * unavailable; `direct-only` tools (`agent`, `send_message`, + * `create_sub_session`, the worktree tools) never get a nested binding and + * stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager * from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. * Inheriting or explicitly granting `exec` keeps all otherwise admitted * ordinary code-mode-callable bindings. An execution allowlist that @@ -511,9 +514,12 @@ export interface QueryOptions { * entry in a session, a subagent definition change) re-declares (#9827). * These bridge and warning rules apply to direct and hybrid code modes. * On the session surface in hybrid mode, while `exec` is registered (container or SSH - * execution warns and falls back to direct tools without it), exec - * retains callable nested bindings; their schemas are included in - * exec when either bridge tool is unavailable. CodeModeOnly discovers deferred schemas through + * execution warns and falls back to direct tools without it), withheld + * tools that have an actual nested exec binding remain callable through + * exec, and their schemas are included in the exec description when either + * bridge tool is unavailable; `direct-only` tools (`agent`, + * `send_message`, `create_sub_session`, the worktree tools) never get a + * nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through * top-level tool_search and invokes them through exec. It skips deferred * preload and startup catalogs; tools.eager reduces the initial exec * description. When search is unavailable in the current scope, exec From 9b41dc045d1abc0abf09f5783c653a9c0e7c9e9a Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Sat, 10 Oct 2026 16:08:10 +0000 Subject: [PATCH 17/49] fix(core): close CodeModeOnly skill-listing bypass without exec (#11854) Address review round 8: - R7-2: toolConfigAllowsSkill consulted the exec-registration probe only on the reachesThroughExec term, so a CodeModeOnly agent whose registry lacks exec (deny rule or legacy coreTools allowlist) was still announced skills through the wildcard, registry inheritance, or an explicit entry while canInvokeSkill found no route. The predicate now takes the mode and closes every route in CodeModeOnly when exec bindings are unavailable; AgentCore.willHaveSkillTool, SubagentManager, and the background-resume listing all pass it. - R7-1: the fork child message claimed the fork_tools allowlist bounds every call, but under either code mode the gate admits exec (and tool_search in code_mode_only) ahead of the allowlist check, so the sentence now names them. task.md and sub-agents.md scope the declaration-unchanged and rejects-every-call claims to direct mode and state the code-mode behavior positively. - R8-1: the code-mode design doc claimed both fork tool bounds persist through background resume; a plain fork persists neither and resume re-derives both from the parent's live surface. Both language versions now say so. --- docs/design/code-mode.md | 6 ++- docs/design/code-mode.zh-CN.md | 5 +- docs/developers/tools/task.md | 4 +- docs/users/features/sub-agents.md | 4 +- .../agents/background-agent-resume.test.ts | 10 ++++ .../src/agents/background-agent-resume.ts | 4 ++ .../runtime/agent-core.skill-gate.test.ts | 28 ++++++++++ .../core/src/agents/runtime/agent-core.ts | 1 + .../runtime/subagent-plan-tool-policy.test.ts | 38 +++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 10 ++++ .../src/subagents/subagent-manager.test.ts | 23 ++++++++ .../core/src/subagents/subagent-manager.ts | 1 + .../agent/agent.code-mode-review.test.ts | 54 ++++++++++++++++++- .../core/src/tools/agent/fork-subagent.ts | 15 +++++- 14 files changed, 194 insertions(+), 9 deletions(-) diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index eda51ddaceb..ef9ef71d66f 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -87,7 +87,11 @@ otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. Forks inherit the parent's direct-call bound separately from its nested binding set; nested access never widens -the child's direct-call grant. Both bounds persist through background resume. +the child's direct-call grant. A fork carrying an explicit `fork_tools`, a +fork profile, or an enclosing agent allowlist writes both bounds to its +background metadata, and resume restores them verbatim; a plain fork persists +neither bound, so resume re-derives both from the parent's live surface and +the child's grant can widen. ## Constraints and risks diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 12f180cca2c..86e1ff9722b 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -77,7 +77,10 @@ Hybrid 的 AgentCore 调用面从嵌套绑定中排除被 `tools.eager` 隐藏 会保留所有通过其他准入检查的普通 code-mode-callable binding。若执行 allowlist 包含任一 MCP 工具项,MCP 绑定还必须匹配其中的精确工具名或服务器模式。 Fork 分别继承父级的直接调用边界与嵌套绑定集合;嵌套访问权限不会扩大子级 -的直接调用授权。后台恢复会保留这两个边界。 +的直接调用授权。携带显式 `fork_tools`、fork profile 或外层智能体 allowlist 的 +fork 会把这两个边界写入后台元数据,resume 时按原样恢复;普通 fork 两个边界 +都不持久化,resume 会依据父级的实时工具面重新推导二者,因此子级的授权可能 +扩大。 ## 约束与风险 diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index 409aeadb1da..0105cadfc03 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -14,7 +14,7 @@ Use `agent` to launch a specialized subagent to handle complex, multi-step tasks - `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution. - `subagent_type` (string, optional): The type of specialized agent to use for this task. Defaults to `general-purpose` if omitted. - `fork_turns` (string, optional): Only valid with `subagent_type="fork"`. Omit it or use `all` for the full parent conversation, or use a positive integer string such as `"3"` for the most recent three real user turns. Tool responses and pure system reminders do not count as turns. -- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns while keeping the fork's current model-visible tool declarations unchanged for prompt-cache sharing. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under a code mode (`tools.mode`), listing `exec` also admits every code-mode-callable tool through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy. +- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under either code mode, `exec` itself is always declared and executable whatever `fork_tools` lists — an empty array included — and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy. - `fork_profile` (string, optional): Only valid with `subagent_type="fork"`. Loads a frontmatter-only regular `.qwen/fork-profiles/.md` of at most 64 KiB from the active project root and applies its required `tools` array plus an optional `promptHint` of at most 200 characters. The file cannot resolve outside the project profile directory. `fork_profile` cannot be combined with `fork_tools` or a named teammate, and it is unavailable in safe mode or bare mode. - `run_in_background` (boolean, optional): Defaults to `true` for top-level regular agents. Set to `false` to wait for a regular agent's result inline. Headless forks always run in the background. Nested agents run in the foreground unless `run_in_background` is explicitly `true`, which is rejected because nested agents cannot receive background completion notifications. Unnamed caller-owned `working_dir` launches run in the foreground: an explicit `run_in_background: true` request is rejected, while a configured background default (`background: true` in a subagent definition) is rejected at the top level and downgraded to the foreground when nested. - `isolation` (string, optional): Set to `"worktree"` to run an explicitly named, non-fork agent in an isolated git worktree that Qwen Code creates and manages. @@ -149,7 +149,7 @@ Don't use the Agent tool for: - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. - **Subagent interaction**: Regular subagents do not receive `ask_user_question`. Forks keep the parent's declaration list for cache sharing but reject that tool before scheduling or approval; when missing user input blocks work, the subagent reports the blocker to its parent. -- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. Disallowed calls return an error before scheduling or approval; the same declaration list remains model-visible for cache sharing. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool there. +- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing; under a code mode `exec` (and `tool_search` in `code_mode_only`) is always admitted regardless of the list, and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. - **Continuation**: Use `list_agents` and `send_message` for related follow-up work instead of launching a duplicate agent. Continuation depends on compatible retained state and may be unavailable. diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index c6859d978c5..c3d50cf3ab2 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -54,11 +54,11 @@ Tool responses and pure system reminders do not count as user turns. Regular nam ## Restricting Fork Tool Execution with `fork_tools` -Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. The fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, but its task prompt identifies the restriction and a call not matched by `fork_tools` is rejected before scheduling or approval. One exception: under a code mode (`tools.mode`), listing `exec` admits every code-mode-callable tool through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). +Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. In `direct` mode the fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this allowlist; either way its task prompt identifies the restriction, and a call not matched by `fork_tools` is rejected before scheduling or approval. Two code-mode exceptions: under either code mode `exec` is always declared and executable whatever `fork_tools` lists — an empty array included — and listing `exec` admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). - Forks never execute `ask_user_question`; when user input is required, they report the blocker to their parent agent. - Omitting `fork_tools` allows every other inherited tool. -- An empty array rejects every tool call. +- An empty array rejects every tool call (under a code mode, `exec` — and `tool_search` in `code_mode_only` — remains admitted anyway; see above). - `*` is not accepted; omit `fork_tools` to allow every otherwise-executable inherited tool. - Tool names cannot have surrounding whitespace. Wildcards are accepted only as `mcp__*` or as a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. - `mcp__*` intentionally allows every MCP tool while still denying unlisted built-in tools. diff --git a/packages/core/src/agents/background-agent-resume.test.ts b/packages/core/src/agents/background-agent-resume.test.ts index 77109124d88..bdac14c593e 100644 --- a/packages/core/src/agents/background-agent-resume.test.ts +++ b/packages/core/src/agents/background-agent-resume.test.ts @@ -1380,6 +1380,16 @@ describe('BackgroundAgentResumeService', () => { false, ToolMode.CodeModeOnly, ], + // The wildcard inherits the registry, but with exec kept out of a + // CodeModeOnly registry the resumed agent has no route to skill, so the + // listing must stay silent. Dropping the codeModeOnly argument at the + // resume call site turns this row red while the rows above stay green. + [ + 'inherits the registry under CodeModeOnly with exec unregistered', + { tools: ['*'] }, + false, + ToolMode.CodeModeOnly, + ], [ 'names exec without skill under Hybrid with registered exec', { tools: [ToolNames.EXEC] }, diff --git a/packages/core/src/agents/background-agent-resume.ts b/packages/core/src/agents/background-agent-resume.ts index 244d5700a7c..8b2eb2bf9f5 100644 --- a/packages/core/src/agents/background-agent-resume.ts +++ b/packages/core/src/agents/background-agent-resume.ts @@ -82,6 +82,7 @@ import { } from './runtime/subagent-plan-tool-policy.js'; import { toolSearchBridgeSentence } from '../skills/bundled-reference.js'; import { ToolNames } from '../tools/tool-names.js'; +import { ToolMode } from '../tools/code-mode.js'; import { isDirectToolBridgeAvailable } from '../tools/tool-search.js'; import type { AgentExternalInput, @@ -144,6 +145,7 @@ function subagentWillHaveSkillTool( subagentConfig: SubagentConfig | undefined, execBindingsAvailable = false, skillEagerHidden = false, + codeModeOnly = false, ): boolean { // Launch reads `config.tools?.length ? resolveToolNames(config.tools) : ['*']`, // and `resolveToolNames`' `for...of` walks a bare string per character, @@ -173,6 +175,7 @@ function subagentWillHaveSkillTool( }, execBindingsAvailable, skillEagerHidden, + codeModeOnly, ); } @@ -1033,6 +1036,7 @@ export class BackgroundAgentResumeService { target.subagentConfig, hasAgentSkillExecBinding(activeAgentConfig), isAgentSkillEagerHidden(activeAgentConfig), + activeAgentConfig.getToolMode?.() === ToolMode.CodeModeOnly, ), }) )[0], diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 38190875c43..a2d70dc67be 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -304,6 +304,34 @@ describe('AgentCore skill-gate inputs', () => { ).toBe(true); }); + it.each([{ tools: ['*'] }, { tools: [ToolNames.SKILL] }])( + 'stays silent in CodeModeOnly when exec was never registered: %j', + async (toolConfig) => { + // canInvokeSkill counts only the exec gateway in CodeModeOnly, so an + // exec-less registry leaves no Skill route at all: the announcement + // must agree with the gate for the wildcard and an explicit entry. + const config = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + const core = new AgentCore( + 'skill-gate-no-exec', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + toolConfig, + ); + const announced = ( + core as unknown as { willHaveSkillTool: () => boolean } + ).willHaveSkillTool(); + const declared = await declaredNames(core); + expect(announced).toBe(false); + expect(gate(core, declared)).toBe(false); + }, + ); + it.each([true, false])( 'lists Hybrid exec-only skills when lazy exec is registered: %s', (registered) => { diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 2450f5b0526..850d5fcfb0a 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -679,6 +679,7 @@ export class AgentCore { this.toolConfig, hasAgentSkillExecBinding(this.runtimeContext), isAgentSkillEagerHidden(this.runtimeContext), + this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, ); } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index 1eab350b3ce..b45c962d4bb 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -327,6 +327,44 @@ describe('subagent plan tool policy', () => { }, ); + // In CodeModeOnly the exec gateway is the ONLY Skill route — the + // invocation gate never counts a direct Skill declaration there — so with + // exec kept out of the registry every toolConfig shape must answer false, + // including the wildcard the resume path defaults to. Removing the + // exec-registration probe from hasAgentSkillExecBinding, or dropping the + // codeModeOnly conjunction from the predicate, turns each row red. + it.each([ + ['a wildcard', { tools: ['*'] }], + ['an explicit Skill entry', { tools: [ToolNames.SKILL] }], + ['no tool config', undefined], + ])( + 'closes every CodeModeOnly Skill route when exec is unregistered: %s', + (_label, toolConfig) => { + const context = contextWith(ToolMode.CodeModeOnly, false); + expect(hasAgentSkillExecBinding(context)).toBe(false); + expect( + toolConfigAllowsSkill( + toolConfig, + hasAgentSkillExecBinding(context), + isAgentSkillEagerHidden(context), + context.getToolMode?.() === ToolMode.CodeModeOnly, + ), + ).toBe(false); + }, + ); + + it('keeps the wildcard route open in CodeModeOnly while exec is registered', () => { + const context = contextWith(ToolMode.CodeModeOnly, true); + expect( + toolConfigAllowsSkill( + { tools: ['*'] }, + hasAgentSkillExecBinding(context), + isAgentSkillEagerHidden(context), + context.getToolMode?.() === ToolMode.CodeModeOnly, + ), + ).toBe(true); + }); + it('reports no exec route in Direct mode even with exec registered', () => { expect(hasAgentSkillExecBinding(contextWith(ToolMode.Direct, true))).toBe( false, diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 6a9f8f24812..3013dde1fed 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -148,6 +148,12 @@ export function hasAgentSkillExecBinding( * Registry deny/exclude rules remain the bundled-reference resolver's concern; * this predicate supplies the per-agent policy that resolver cannot see. * + * In CodeModeOnly the exec gateway is the ONLY Skill route — the invocation + * gate (`AgentCore.canInvokeSkill`) never counts a direct Skill declaration + * there — so when `exec` itself is missing from the registry (a deny rule or + * a legacy coreTools allowlist keeps it out) no `toolConfig` shape reaches + * Skill: not the wildcard, not registry inheritance, not an explicit entry. + * * Matching is exact, as `prepareTools()`'s is: `SubagentManager` resolves * configured names to canonical tool names before they reach a `ToolConfig`. * @@ -161,10 +167,14 @@ export function toolConfigAllowsSkill( toolConfig: ToolConfig | undefined, execBindingsAvailable = false, skillEagerHidden = false, + codeModeOnly = false, ): boolean { if (skillEagerHidden || EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { return false; } + if (codeModeOnly && !execBindingsAvailable) { + return false; + } // No per-agent config inherits the whole registry. if (!toolConfig) { return true; diff --git a/packages/core/src/subagents/subagent-manager.test.ts b/packages/core/src/subagents/subagent-manager.test.ts index 2713765b9c3..9c149a804bd 100644 --- a/packages/core/src/subagents/subagent-manager.test.ts +++ b/packages/core/src/subagents/subagent-manager.test.ts @@ -3237,6 +3237,29 @@ describe('SubagentManager', () => { }, ); + // The exec registration probe alone leaves the wildcard route open: + // with exec kept out of a CodeModeOnly registry the agent has no Skill + // route at all, so the manager must be withheld even for the default + // wildcard config. Dropping the codeModeOnly argument at the + // createAgentHeadless call site turns this case red. + it('withholds the manager for a wildcard agent in CodeModeOnly without exec', async () => { + const parent = makeFakeConfig({ toolMode: 'code_mode_only' }); + const registry = new ToolRegistry(parent); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + vi.spyOn(parent, 'getSkillManager').mockReturnValue(sessionManager); + vi.spyOn(parent, 'getSubagentManager').mockReturnValue(manager); + vi.spyOn(parent, 'getToolRegistry').mockReturnValue(registry); + + const { context, dispose } = await launchHandle({}, parent); + try { + expect(context.getSkillManager()).toBeNull(); + expect(resolveAgentDelegationSurface(context)).toBe('inline'); + } finally { + await dispose(); + await registry.stop(); + } + }); + it.each([false, true])( 'withholds the manager for an eager-hidden Hybrid Skill even if parent revealed it: %s', async (revealed) => { diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 2422f63812b..ad377c23d9e 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -1217,6 +1217,7 @@ export class SubagentManager { toolConfig, hasAgentSkillExecBinding(runtimeContext, skillRegistryWillBeRebuilt), skillEagerHidden, + runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, ); const { context: subagentContext, cleanup } = await this.buildSubagentContextOverride( diff --git a/packages/core/src/tools/agent/agent.code-mode-review.test.ts b/packages/core/src/tools/agent/agent.code-mode-review.test.ts index 16772195716..e4d4944fde1 100644 --- a/packages/core/src/tools/agent/agent.code-mode-review.test.ts +++ b/packages/core/src/tools/agent/agent.code-mode-review.test.ts @@ -4,7 +4,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; +import { AgentCore } from '../../agents/runtime/agent-core.js'; import { buildChildMessage } from './fork-subagent.js'; import { makeFakeConfig } from '../../test-utils/config.js'; import { MockTool } from '../../test-utils/mock-tool.js'; @@ -88,4 +89,55 @@ describe('Code-mode fork restriction matches declared call surfaces', () => { } }, ); + + it('declares, executes, and names exec for a hybrid fork that omits it', async () => { + // The fork shape agent.ts builds for fork_tools: ["read_file"] in hybrid + // code mode: the parent's declared names stay as the tool list while the + // execution allowlist narrows to the requested ones. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool(new MockTool({ name: ToolNames.WRITE_FILE })); + const core = new AgentCore( + 'hybrid-fork', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: [ToolNames.EXEC, ToolNames.READ_FILE], + executionAllowedTools: [ToolNames.READ_FILE], + }, + ); + + // Scoping the unconditional exec carve-out in isToolExecutionAllowed back + // to CodeModeOnly turns both of these red. + const declarations = await core.prepareTools(); + expect(declarations.map((declaration) => declaration.name)).toContain( + ToolNames.EXEC, + ); + expect( + ( + core as unknown as { isToolExecutionAllowed: (t: string) => boolean } + ).isToolExecutionAllowed.call(core, ToolNames.EXEC), + ).toBe(true); + + // The child message must not claim the allowlist bounds exec: the gate + // admits it for every code mode and every fork_tools value. + const message = buildChildMessage( + 'Inspect the implementation', + [ToolNames.READ_FILE], + undefined, + undefined, + ToolMode.CodeMode, + ); + const sentence = message + .split('\n') + .find((line) => line.includes('allowlist')); + expect(sentence).toBeDefined(); + expect(sentence).toContain(JSON.stringify([ToolNames.READ_FILE])); + expect(sentence).toContain(ToolNames.EXEC); + }); }); diff --git a/packages/core/src/tools/agent/fork-subagent.ts b/packages/core/src/tools/agent/fork-subagent.ts index 166e9608e03..0411e4530ec 100644 --- a/packages/core/src/tools/agent/fork-subagent.ts +++ b/packages/core/src/tools/agent/fork-subagent.ts @@ -4,7 +4,7 @@ import type { Config } from '../../config/config.js'; import type { SubagentConfig } from '../../subagents/types.js'; import { BUBBLE_APPROVAL_MODE } from '../../subagents/types.js'; import { ToolNames } from '../tool-names.js'; -import { ToolMode } from '../code-mode.js'; +import { isCodeModeEnabled, ToolMode } from '../code-mode.js'; import { getStartupContextLength, isSystemReminderContent, @@ -421,6 +421,13 @@ export function buildChildMessage( nestedExecutionAllowedTools?: readonly string[], toolMode?: ToolMode, ): string { + // Under either code mode the gate admits exec ahead of the allowlist check + // (and tool_search in CodeModeOnly), so the sentence must name them rather + // than claim the list bounds every call. + const codeModeAlwaysAdmitted = + toolMode === ToolMode.CodeModeOnly + ? `${ToolNames.EXEC} and ${ToolNames.TOOL_SEARCH}` + : ToolNames.EXEC; const executionRestriction = nestedExecutionAllowedTools !== undefined ? `\n\nTOOL EXECUTION RESTRICTION: @@ -436,7 +443,11 @@ A nested allowance alone does not authorize a direct call; direct calls must sat : executionAllowedTools.length === 0 ? `\n\nTOOL EXECUTION RESTRICTION: You may not execute any tools, even though tool declarations remain visible. Do not attempt tool calls.` - : `\n\nTOOL EXECUTION RESTRICTION: + : isCodeModeEnabled(toolMode) + ? `\n\nTOOL EXECUTION RESTRICTION: +You may execute only tools matched by this allowlist: ${JSON.stringify(executionAllowedTools)} — except ${codeModeAlwaysAdmitted}, which the active code mode always admits. +Other visible tool declarations are unavailable to you. Do not call them.` + : `\n\nTOOL EXECUTION RESTRICTION: You may execute only tools matched by this allowlist: ${JSON.stringify(executionAllowedTools)}. Other visible tool declarations are unavailable to you. Do not call them.`; const profileGuidance = promptHint From 7faeea6d21dfbbb3a1e4a68dd4e0c0dd210c62c6 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Sat, 10 Oct 2026 17:07:42 +0000 Subject: [PATCH 18/49] test(cli): align OpenTUI settings region tests with tools.mode (#11854) Same-run verification repair: the deterministic gate rejected the round because dialogs-modes.test.tsx still pinned the removed tools.codeModeOnly boolean at the settings list's second row. The PR replaced it with the tools.mode enum (direct -> code_mode -> code_mode_only), so the five region-budget tests now expect the enum's cycle value, the items[1] key assertion names tools.mode, and the space-bar probe's scope stub holds the renamed key so a guard-broken second toggle stays a real write. --- .../cli/src/ui/opentui/dialogs-modes.test.tsx | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/cli/src/ui/opentui/dialogs-modes.test.tsx b/packages/cli/src/ui/opentui/dialogs-modes.test.tsx index 52ee14fefff..a417fac69f1 100644 --- a/packages/cli/src/ui/opentui/dialogs-modes.test.tsx +++ b/packages/cli/src/ui/opentui/dialogs-modes.test.tsx @@ -1887,14 +1887,14 @@ describe('OpenTuiSettingsDialog region budget', () => { />, ); press('tab'); // → back to the settings list - press('down'); // tools.codeModeOnly — a boolean + press('down'); // tools.mode — an enum press('return'); expect(setValue).toHaveBeenCalledTimes(1); expect(setValue).toHaveBeenCalledWith( SettingScope.User, - 'tools.codeModeOnly', - true, + 'tools.mode', + 'code_mode', ); }); @@ -1932,14 +1932,14 @@ describe('OpenTuiSettingsDialog region budget', () => { />, ); press('tab'); // → back to the settings list - press('down'); // tools.codeModeOnly — a boolean + press('down'); // tools.mode — an enum press('return'); expect(setValue).toHaveBeenCalledTimes(1); expect(setValue).toHaveBeenCalledWith( SettingScope.User, - 'tools.codeModeOnly', - true, + 'tools.mode', + 'code_mode', ); }); @@ -1987,7 +1987,7 @@ describe('OpenTuiSettingsDialog region budget', () => { ); expect(screen.getByText(items[2]!.label)).not.toBeNull(); - press('down'); // tools.codeModeOnly — a boolean that requires restart + press('down'); // tools.mode — an enum that requires restart press('return'); expect( @@ -2022,7 +2022,7 @@ describe('OpenTuiSettingsDialog region budget', () => { // 19 - 16 chrome rows: three list rows paint before the toggle. expect(screen.getByText(items[2]!.label)).not.toBeNull(); - press('down'); // tools.codeModeOnly — a boolean that requires restart + press('down'); // tools.mode — an enum that requires restart press('return'); expect( @@ -2111,12 +2111,12 @@ describe('OpenTuiSettingsDialog region budget', () => { />, ); - press('down'); // tools.codeModeOnly — a boolean that requires restart + press('down'); // tools.mode — an enum that requires restart press('return'); expect(setValue).toHaveBeenCalledWith( SettingScope.User, - 'tools.codeModeOnly', - true, + 'tools.mode', + 'code_mode', ); expect( screen.getByText(/To see changes, Qwen Code must be restarted/), @@ -2134,7 +2134,7 @@ describe('OpenTuiSettingsDialog region budget', () => { // would be invisible, and the description painted under the list is the // tell that it must not happen. const items = buildSettingsListItems(); - expect(items[1]!.key).toBe('tools.codeModeOnly'); + expect(items[1]!.key).toBe('tools.mode'); expect(items[1]!.description).toBeTruthy(); // The description line paints clipped to the frame's content width (ink's // wrap="truncate-end" parity), so the tell matches on a prefix. @@ -2155,7 +2155,7 @@ describe('OpenTuiSettingsDialog region budget', () => { availableTerminalHeight={15} />, ); - press('down'); // tools.codeModeOnly + press('down'); // tools.mode press('return'); // the restart prompt takes the last row — window is zero expect(descriptionPaints(1)).toBe(true); @@ -2201,14 +2201,14 @@ describe('OpenTuiSettingsDialog region budget', () => { // the sequence alone classifies it as search input — while the // commit branch reads the name and toggles the row under the cursor. At // a zero-row window that is a write the user was never shown. The scope - // file below holds the key, so a toggle back to the default is still a - // real write (an empty scope stub would make the second toggle a skipped - // write and the probe blind). + // file below holds the key, the first toggle off the default is a real + // write, and a guard-broken second toggle advances the enum again — + // tools.mode persists even at its default — so the probe stays live. const setValue = vi.fn(); const settings = { isTrusted: true, merged: {}, - forScope: () => ({ settings: { tools: { codeModeOnly: false } } }), + forScope: () => ({ settings: { tools: { mode: 'direct' } } }), setValue, } as unknown as LoadedSettings; render( @@ -2219,13 +2219,13 @@ describe('OpenTuiSettingsDialog region budget', () => { />, ); - press('down'); // tools.codeModeOnly — a boolean that requires restart + press('down'); // tools.mode — an enum that requires restart press('return'); expect(setValue).toHaveBeenCalledTimes(1); expect(setValue).toHaveBeenCalledWith( SettingScope.User, - 'tools.codeModeOnly', - true, + 'tools.mode', + 'code_mode', ); // The restart prompt takes the last list row — the window is now zero. expect( From f6ea27dae067a1d5fffba08ffdb78eb60a01808e Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Sun, 11 Oct 2026 00:36:16 +0000 Subject: [PATCH 19/49] fix(core): close remaining CodeModeOnly skill-gate exec routes (#11854) The CodeModeOnly veto in toolConfigAllowsSkill only consulted exec registration, so a per-agent exec blocklist or an execution allowlist naming neither skill nor exec still answered true for an agent with no skill route at all. Widen the veto to consult the full exec-route condition, and mode-split the fork declaration-visibility contract in the remaining unconditional statements (agent tool schema text, task.md, ToolConfig docs, scheduler comment). Correct the SDK docs' direct-only reachability sentence: withheld direct-only tools stay reachable through the tool_search + tool_call bridge, not through exec. --- docs/design/code-mode.md | 2 +- docs/design/code-mode.zh-CN.md | 14 ++--- docs/developers/sdk-typescript.md | 42 +++++++-------- docs/developers/tools/task.md | 2 +- .../core/src/agents/runtime/agent-core.ts | 8 +-- .../core/src/agents/runtime/agent-types.ts | 6 ++- .../runtime/subagent-plan-tool-policy.test.ts | 53 +++++++++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 16 ++++-- packages/core/src/tools/agent/agent.test.ts | 3 +- packages/core/src/tools/agent/agent.ts | 4 +- packages/sdk-typescript/README.md | 42 +++++++-------- packages/sdk-typescript/src/types/types.ts | 8 +-- 12 files changed, 135 insertions(+), 65 deletions(-) diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index ef9ef71d66f..53098ccfcab 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -50,7 +50,7 @@ force `direct`. Container execution exposes direct tools only: selecting | -------------------- | --------------------------- | ------------------------------- | ---------------------------------- | | Ordinary eager tools | Direct | Direct and nested | Nested only | | Deferred tools | `tool_search` + `tool_call` | Bridge and nested | Nested only | -| Direct-control tools | Direct | Direct only | Direct only | +| Direct-control tools | Direct | Direct; bridge when withheld | Direct only | | `exec` | Not registered | Direct | Direct | | Discovery bridge | Existing direct behavior | Direct where already applicable | Top-level search; tool_call hidden | diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 86e1ff9722b..0b50f7988bf 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -44,13 +44,13 @@ CodeModeOnly。 ## 暴露策略 -| 调用面 | `direct` | `code_mode` | `code_mode_only` | -| ------------ | --------------------------- | -------------------- | ------------------------ | -| 普通即时工具 | 直接调用 | 直接调用和嵌套调用 | 仅嵌套调用 | -| 延迟工具 | `tool_search` + `tool_call` | 桥接和嵌套调用 | 仅嵌套调用 | -| 直接控制工具 | 直接调用 | 仅直接调用 | 仅直接调用 | -| `exec` | 未注册 | 直接调用 | 直接调用 | -| 发现桥接工具 | 保持现有直接模式行为 | 在原本适用时直接调用 | 顶层搜索;隐藏 tool_call | +| 调用面 | `direct` | `code_mode` | `code_mode_only` | +| ------------ | --------------------------- | ------------------------ | ------------------------ | +| 普通即时工具 | 直接调用 | 直接调用和嵌套调用 | 仅嵌套调用 | +| 延迟工具 | `tool_search` + `tool_call` | 桥接和嵌套调用 | 仅嵌套调用 | +| 直接控制工具 | 直接调用 | 直接调用;被隐藏时经桥接 | 仅直接调用 | +| `exec` | 未注册 | 直接调用 | 直接调用 | +| 发现桥接工具 | 保持现有直接模式行为 | 在原本适用时直接调用 | 顶层搜索;隐藏 tool_call | 在 `code_mode` 中,普通可见工具的描述会附加该工具的 `exec` 调用声明。 `exec` 描述保留每个 `ALL_TOOLS` 条目的工具名、JavaScript 名称和延迟标记。 diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index d0d6a4959d3..2d30841c26a 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index 0105cadfc03..a7802a79ad3 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -148,7 +148,7 @@ Don't use the Agent tool for: ## Important Notes - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. -- **Subagent interaction**: Regular subagents do not receive `ask_user_question`. Forks keep the parent's declaration list for cache sharing but reject that tool before scheduling or approval; when missing user input blocks work, the subagent reports the blocker to its parent. +- **Subagent interaction**: Regular subagents do not receive `ask_user_question`. In `direct` mode forks keep the parent's declaration list for cache sharing — including that tool — and reject it before scheduling or approval; under hybrid `code_mode` a `fork_tools` allowlist narrows the declaration list, so it is dropped there. When missing user input blocks work, the subagent reports the blocker to its parent. - **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing; under a code mode `exec` (and `tool_search` in `code_mode_only`) is always admitted regardless of the list, and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 850d5fcfb0a..5ad028eb6ba 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -2187,9 +2187,11 @@ export class AgentCore { ]), ); - // The model-visible declarations and the execution allowlist are separate: - // forks keep the parent's declaration prefix for cache sharing while - // optionally narrowing which declared tools may actually run. + // The model-visible declarations and the execution allowlist are separate + // in `direct` mode: forks keep the parent's declaration prefix for cache + // sharing while optionally narrowing which declared tools may actually + // run. Under hybrid `code_mode` the allowlist also narrows the fork's + // declarations (see prepareTools' admission pool). const declaredToolNames = new Set(toolsList.map((t) => t.name)); const isReplayOfHandledCall = (fc: FunctionCall): boolean => { const providerCallId = getProviderToolCallId(fc) ?? fc.id; diff --git a/packages/core/src/agents/runtime/agent-types.ts b/packages/core/src/agents/runtime/agent-types.ts index 210df4fd3be..98ff88bcc55 100644 --- a/packages/core/src/agents/runtime/agent-types.ts +++ b/packages/core/src/agents/runtime/agent-types.ts @@ -98,8 +98,10 @@ export interface ToolConfig { tools: Array; /** - * Optional execution-layer allowlist. Tool declarations remain unchanged, - * but calls outside this list are rejected before scheduling or approval. + * Optional execution-layer allowlist. Calls outside this list are rejected + * before scheduling or approval. In `direct` mode the tool declarations + * remain unchanged; under hybrid `code_mode` the allowlist also narrows + * the agent's top-level declarations. * Supports exact tool names and MCP server-level patterns. */ executionAllowedTools?: string[]; diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index b45c962d4bb..f4a35a0ce81 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -289,6 +289,59 @@ describe('subagent plan tool policy', () => { ), ).toBe(true); }); + + // In CodeModeOnly the exec gateway is the ONLY Skill route, so a + // toolConfig that closes that route must answer false whatever the + // declaration list says: prepareTools() drops a blocklisted exec, and + // leaves skill out of codeModeAllowedToolNames when the execution + // allowlists name neither skill nor exec; canInvokeSkill never counts a + // direct Skill declaration there. + it.each([ + [ + 'a wildcard with exec disallowed', + { tools: ['*'], disallowedTools: [ToolNames.EXEC] }, + ], + [ + 'an explicit Skill entry with exec disallowed', + { tools: [ToolNames.SKILL], disallowedTools: [ToolNames.EXEC] }, + ], + [ + 'a wildcard whose execution allowlist omits skill and exec', + { tools: ['*'], executionAllowedTools: [ToolNames.READ_FILE] }, + ], + [ + 'a wildcard whose nested execution allowlist omits skill', + { tools: ['*'], nestedExecutionAllowedTools: [ToolNames.READ_FILE] }, + ], + ])( + 'closes the CodeModeOnly Skill route when the exec gateway is unreachable: %s', + (_label, toolConfig) => { + expect(toolConfigAllowsSkill(toolConfig, true, false, true)).toBe( + false, + ); + }, + ); + + // The same shapes stay open outside CodeModeOnly: canInvokeSkill counts a + // direct Skill declaration in Direct and Hybrid, so the exec-route veto + // must not fire there. + it.each([ + [ + 'a wildcard with exec disallowed', + { tools: ['*'], disallowedTools: [ToolNames.EXEC] }, + ], + [ + 'a wildcard whose nested execution allowlist omits skill', + { tools: ['*'], nestedExecutionAllowedTools: [ToolNames.READ_FILE] }, + ], + ])( + 'keeps the Skill route open outside CodeModeOnly: %s', + (_label, toolConfig) => { + expect(toolConfigAllowsSkill(toolConfig, true, false, false)).toBe( + true, + ); + }, + ); }); describe('hasAgentSkillExecBinding', () => { diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 3013dde1fed..97c1d5cd0e0 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -150,9 +150,13 @@ export function hasAgentSkillExecBinding( * * In CodeModeOnly the exec gateway is the ONLY Skill route — the invocation * gate (`AgentCore.canInvokeSkill`) never counts a direct Skill declaration - * there — so when `exec` itself is missing from the registry (a deny rule or - * a legacy coreTools allowlist keeps it out) no `toolConfig` shape reaches - * Skill: not the wildcard, not registry inheritance, not an explicit entry. + * there — so when that route is closed no `toolConfig` shape reaches Skill: + * not the wildcard, not registry inheritance, not an explicit entry. The + * route is closed when `exec` itself is missing from the registry (a deny + * rule or a legacy coreTools allowlist keeps it out), when the agent + * blocklists `exec` (`prepareTools()` drops it from the declarations), or + * when an execution allowlist names neither `skill` nor `exec` (`skill` + * stays out of `codeModeAllowedToolNames`). * * Matching is exact, as `prepareTools()`'s is: `SubagentManager` resolves * configured names to canonical tool names before they reach a `ToolConfig`. @@ -200,6 +204,12 @@ export function toolConfigAllowsSkill( : toolConfig.executionAllowedTools === undefined || toolConfig.executionAllowedTools.includes(ToolNames.SKILL) || toolConfig.executionAllowedTools.includes(ToolNames.EXEC)); + // In CodeModeOnly a closed exec route reaches no skill whatever the + // declaration list says. Ordered after the `!toolConfig` early return: + // execRouteOpen is only defined for a concrete config. + if (codeModeOnly && !execRouteOpen) { + return false; + } const reachesThroughExec = execBindingsAvailable && execRouteOpen && names.includes(ToolNames.EXEC); return ( diff --git a/packages/core/src/tools/agent/agent.test.ts b/packages/core/src/tools/agent/agent.test.ts index 9a3c80bf9c6..a4363b70640 100644 --- a/packages/core/src/tools/agent/agent.test.ts +++ b/packages/core/src/tools/agent/agent.test.ts @@ -1283,7 +1283,8 @@ describe('AgentTool', () => { expect(forkTools.minItems).toBeUndefined(); expectText(forkTools.description, [ 'Only valid with subagent_type "fork"', - 'tool declarations remain unchanged', + 'In `direct` mode the model-visible tool declarations remain unchanged', + "this allowlist also narrows the fork's declarations", ]); }); diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 89970254568..56105e1b175 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -857,7 +857,7 @@ export class AgentTool extends BaseDeclarativeTool { minLength: 1, }, description: - 'Only valid with subagent_type "fork". Exact tool names and MCP server patterns this fork may execute. Entries cannot have surrounding whitespace; wildcard entries must be "mcp__*" or a trailing MCP tool-prefix pattern such as "mcp__github__read_*". The model-visible tool declarations remain unchanged for prompt-cache sharing, while the task prompt tells the fork about the restriction. Forks can never execute ask_user_question; omit fork_tools to allow every other inherited tool, or use an empty array to reject every tool call.', + 'Only valid with subagent_type "fork". Exact tool names and MCP server patterns this fork may execute. Entries cannot have surrounding whitespace; wildcard entries must be "mcp__*" or a trailing MCP tool-prefix pattern such as "mcp__github__read_*". In `direct` mode the model-visible tool declarations remain unchanged for prompt-cache sharing; under hybrid `tools.mode: "code_mode"` this allowlist also narrows the fork\'s declarations. Forks can never execute ask_user_question; omit fork_tools to allow every other inherited tool, or use an empty array to reject every tool call.', }, fork_profile: { type: 'string', @@ -998,7 +998,7 @@ The Agent tool launches specialized agents (subprocesses) that autonomously hand Available agent types and the tools they have access to: ${subagentDescriptions} -When using the Agent tool, specify a subagent_type to select which agent type to use. If omitted, the general-purpose agent is used. Top-level regular subagents run in the background by default and report their results through a completion notification; set \`run_in_background: false\` when you need a regular subagent's result inline before continuing. A fork (\`subagent_type: "fork"\`) inherits the parent conversation context. A background fork's result arrives through a completion notification. Forks inherit the full parent conversation by default; set \`fork_turns\` to a positive integer string to limit inheritance to that many recent real user turns. Set \`fork_tools\` to restrict which of the still-visible parent tools the fork may execute, or \`fork_profile\` to load the same restriction from a project profile. +When using the Agent tool, specify a subagent_type to select which agent type to use. If omitted, the general-purpose agent is used. Top-level regular subagents run in the background by default and report their results through a completion notification; set \`run_in_background: false\` when you need a regular subagent's result inline before continuing. A fork (\`subagent_type: "fork"\`) inherits the parent conversation context. A background fork's result arrives through a completion notification. Forks inherit the full parent conversation by default; set \`fork_turns\` to a positive integer string to limit inheritance to that many recent real user turns. Set \`fork_tools\` to restrict which of the parent's tools the fork may execute, or \`fork_profile\` to load the same restriction from a project profile. When NOT to use the Agent tool: - If you want to read a specific file path, use the ${ToolNames.READ_FILE} tool or the ${ToolNames.GLOB} tool instead of the ${ToolNames.AGENT} tool, to find the match more quickly diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 113b1492ef5..e93db6034e5 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index 360a68fd448..3ace7d4d3fb 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -438,8 +438,9 @@ export interface QueryOptions { * an actual nested exec binding remain callable through exec, and their * schemas are included in the exec description when either bridge tool is * unavailable; `direct-only` tools (`agent`, `send_message`, - * `create_sub_session`, the worktree tools) never get a nested binding and - * stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager + * `create_sub_session`, the worktree tools) never get a nested binding; + * when withheld they stay reachable through the `tool_search` + `tool_call` + * bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager * from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. * Inheriting or explicitly granting `exec` keeps all otherwise admitted * ordinary code-mode-callable bindings. An execution allowlist that @@ -519,7 +520,8 @@ export interface QueryOptions { * exec, and their schemas are included in the exec description when either * bridge tool is unavailable; `direct-only` tools (`agent`, * `send_message`, `create_sub_session`, the worktree tools) never get a - * nested binding and stay reachable only by a direct call by name. CodeModeOnly discovers deferred schemas through + * nested binding; when withheld they stay reachable through the + * `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through * top-level tool_search and invokes them through exec. It skips deferred * preload and startup catalogs; tools.eager reduces the initial exec * description. When search is unavailable in the current scope, exec From ecbb1aefef6756dc998b1a0d31d05fb64c98d314 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Sun, 11 Oct 2026 09:06:46 +0000 Subject: [PATCH 20/49] fix(core): close code-mode exec admission, container mode, and allowlist gaps (#11854) Address the round-10 review findings. A deny-all fork execution list (fork_tools: []) no longer admits exec or tool_search ahead of the list in either code mode; an explicit non-empty nested grant keeps exec reachable, matching toolConfigAllowsSkill, and the fork_tools contract text (schema, task.md, sub-agents.md) now states the non-empty qualification. A hybrid session under container execution now reports ToolMode.Direct from getToolMode() since the registry never registers exec there, so code-mode gates and the fork child message stop claiming an exec surface that does not exist; the container fallback warning still keys on the configured mode and CodeModeOnly remains a registry-creation rejection. Nested code-mode tool calls now carry the parent's codeModeAllowedToolNames onto the nested request so a call resumed after approval re-establishes the ambient allowlist instead of losing it outside the parent async frame. Docs: the CodeModeOnly collision sentence now credits the debug warning and scopes the description to search-unavailable scopes, and the SDK direct-only bridge-reachability clause is scoped to a registered bridge. --- docs/design/code-mode-only.md | 5 +- docs/design/code-mode-only.zh-CN.md | 4 +- docs/developers/sdk-typescript.md | 42 ++++++------ docs/developers/tools/task.md | 4 +- docs/users/features/sub-agents.md | 2 +- .../runtime/agent-core.fork-policy.test.ts | 19 ++++-- .../core/src/agents/runtime/agent-core.ts | 12 +++- packages/core/src/code-mode/scheduler.test.ts | 65 +++++++++++++++++++ packages/core/src/config/config.test.ts | 22 +++++++ packages/core/src/config/config.ts | 13 +++- packages/core/src/core/coreToolScheduler.ts | 4 ++ .../agent/agent.code-mode-review.test.ts | 26 ++++++++ packages/core/src/tools/agent/agent.test.ts | 52 ++++++++++++++- packages/core/src/tools/agent/agent.ts | 2 +- packages/sdk-typescript/README.md | 42 ++++++------ packages/sdk-typescript/src/types/types.ts | 5 +- 16 files changed, 256 insertions(+), 63 deletions(-) diff --git a/docs/design/code-mode-only.md b/docs/design/code-mode-only.md index 51527d013eb..9e7fe4d482c 100644 --- a/docs/design/code-mode-only.md +++ b/docs/design/code-mode-only.md @@ -85,8 +85,9 @@ current registry. Tools are sorted by canonical name. A name is normalized to a JavaScript property by replacing invalid identifier characters and prefixing names that begin with a digit. If two canonical names normalize to the same property, an exact canonical match wins over rewritten names. If neither is an -exact match, the lexicographically first name wins. The description names the -omitted collision. +exact match, the lexicographically first name wins. One debug warning names the +omitted collision; the description names it only when search is unavailable in +the current scope. The description defines: diff --git a/docs/design/code-mode-only.zh-CN.md b/docs/design/code-mode-only.zh-CN.md index 7238c2f8047..b2de89ef479 100644 --- a/docs/design/code-mode-only.zh-CN.md +++ b/docs/design/code-mode-only.zh-CN.md @@ -70,8 +70,8 @@ CodeModeOnly 会隐藏 `tool_search`,嵌套调用也不会以 `functionCall` 每次向 provider 同步工具前,都会从当前 registry 生成 `exec` 描述。工具按规范 名称排序。名称会通过替换无效标识符字符来规范化为 JavaScript 属性;如果名称以 数字开头,还会添加前缀。如果两个规范名称映射到同一个属性,优先保留与属性精确 -一致的规范名称;若都不是精确匹配,则字典序靠前的名称胜出。描述会指出被省略的 -冲突项。 +一致的规范名称;若都不是精确匹配,则字典序靠前的名称胜出。会有一条 debug +warning 指出被省略的冲突项;只有当当前作用域内 search 不可用时,描述才会指出它。 描述会定义: diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index 2d30841c26a..13f7e9ee8c7 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index a7802a79ad3..a0e856f7ce0 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -14,7 +14,7 @@ Use `agent` to launch a specialized subagent to handle complex, multi-step tasks - `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution. - `subagent_type` (string, optional): The type of specialized agent to use for this task. Defaults to `general-purpose` if omitted. - `fork_turns` (string, optional): Only valid with `subagent_type="fork"`. Omit it or use `all` for the full parent conversation, or use a positive integer string such as `"3"` for the most recent three real user turns. Tool responses and pure system reminders do not count as turns. -- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under either code mode, `exec` itself is always declared and executable whatever `fork_tools` lists — an empty array included — and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy. +- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under either code mode a non-empty `fork_tools` list still admits `exec` (and `tool_search` under `code_mode_only`), which the mode grants ahead of the allowlist, and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy; the empty array closes the exec route too. - `fork_profile` (string, optional): Only valid with `subagent_type="fork"`. Loads a frontmatter-only regular `.qwen/fork-profiles/.md` of at most 64 KiB from the active project root and applies its required `tools` array plus an optional `promptHint` of at most 200 characters. The file cannot resolve outside the project profile directory. `fork_profile` cannot be combined with `fork_tools` or a named teammate, and it is unavailable in safe mode or bare mode. - `run_in_background` (boolean, optional): Defaults to `true` for top-level regular agents. Set to `false` to wait for a regular agent's result inline. Headless forks always run in the background. Nested agents run in the foreground unless `run_in_background` is explicitly `true`, which is rejected because nested agents cannot receive background completion notifications. Unnamed caller-owned `working_dir` launches run in the foreground: an explicit `run_in_background: true` request is rejected, while a configured background default (`background: true` in a subagent definition) is rejected at the top level and downgraded to the foreground when nested. - `isolation` (string, optional): Set to `"worktree"` to run an explicitly named, non-fork agent in an isolated git worktree that Qwen Code creates and manages. @@ -149,7 +149,7 @@ Don't use the Agent tool for: - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. - **Subagent interaction**: Regular subagents do not receive `ask_user_question`. In `direct` mode forks keep the parent's declaration list for cache sharing — including that tool — and reject it before scheduling or approval; under hybrid `code_mode` a `fork_tools` allowlist narrows the declaration list, so it is dropped there. When missing user input blocks work, the subagent reports the blocker to its parent. -- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing; under a code mode `exec` (and `tool_search` in `code_mode_only`) is always admitted regardless of the list, and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. +- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing; under a code mode a non-empty list still admits `exec` (and `tool_search` in `code_mode_only`) ahead of the list — an empty array rejects every call, `exec` included — and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. - **Continuation**: Use `list_agents` and `send_message` for related follow-up work instead of launching a duplicate agent. Continuation depends on compatible retained state and may be unavailable. diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index c3d50cf3ab2..4d494f2687b 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -54,7 +54,7 @@ Tool responses and pure system reminders do not count as user turns. Regular nam ## Restricting Fork Tool Execution with `fork_tools` -Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. In `direct` mode the fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this allowlist; either way its task prompt identifies the restriction, and a call not matched by `fork_tools` is rejected before scheduling or approval. Two code-mode exceptions: under either code mode `exec` is always declared and executable whatever `fork_tools` lists — an empty array included — and listing `exec` admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). +Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. In `direct` mode the fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this allowlist; either way its task prompt identifies the restriction, and a call not matched by `fork_tools` is rejected before scheduling or approval. Two code-mode exceptions: under either code mode a non-empty `fork_tools` list still admits `exec` ahead of the list — an empty array closes the exec route too — and listing `exec` admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). - Forks never execute `ask_user_question`; when user input is required, they report the blocker to their parent agent. - Omitting `fork_tools` allows every other inherited tool. diff --git a/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts b/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts index e13b0870567..0cc50f305f0 100644 --- a/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts +++ b/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts @@ -143,11 +143,20 @@ describe('fork MCP policy inheritance', () => { tools, ); const declarations = await core.prepareTools(); - const exec = declarations.find((d) => d.name === 'exec')!; - expect(exec.description).not.toContain('mcp__payments__charge'); - expect(exec.description).not.toContain('mcp__github__create_issue'); - if (pattern.includes('github')) { - expect(exec.description).toContain('mcp__github__read_file'); + // An empty inherited execution list is the documented deny-all: + // the code modes must not re-admit exec ahead of it, so the child + // declares nothing. The offline pattern reaches that state at + // generation 1; the github arm keeps a non-empty list and the + // exec-wrapper assertions below. + if (tools.executionAllowedTools?.length === 0) { + expect(declarations).toEqual([]); + } else { + const exec = declarations.find((d) => d.name === 'exec')!; + expect(exec.description).not.toContain('mcp__payments__charge'); + expect(exec.description).not.toContain('mcp__github__create_issue'); + if (pattern.includes('github')) { + expect(exec.description).toContain('mcp__github__read_file'); + } } let frame: readonly string[] | undefined; await core.runInAgentFrames(async () => { diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 5ad028eb6ba..b249891e6b9 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -2044,11 +2044,17 @@ export class AgentCore { ))) ); } + // An explicit empty execution list denies every direct call (the + // documented deny-all contract); without a nested grant the code-mode + // exec/tool_search surface closes with it. A non-empty nested list keeps + // exec reachable, the same route toolConfigAllowsSkill derives. if ( - (toolName === ToolNames.EXEC && + (this.executionAllowedTools.length > 0 || + (this.nestedExecutionAllowedTools?.size ?? 0) > 0) && + ((toolName === ToolNames.EXEC && isCodeModeEnabled(this.runtimeContext.getToolMode?.())) || - (toolName === ToolNames.TOOL_SEARCH && - this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly) + (toolName === ToolNames.TOOL_SEARCH && + this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly)) ) { return true; } diff --git a/packages/core/src/code-mode/scheduler.test.ts b/packages/core/src/code-mode/scheduler.test.ts index 2f352ed19f8..31ec660fbc9 100644 --- a/packages/core/src/code-mode/scheduler.test.ts +++ b/packages/core/src/code-mode/scheduler.test.ts @@ -19,6 +19,7 @@ import { MockTool } from '../test-utils/mock-tool.js'; import { ExecTool } from '../tools/exec.js'; import { ToolSearchTool } from '../tools/tool-search.js'; import { getToolCallRuntime } from './tool-call-runtime.js'; +import { getCurrentCodeModeAllowedNames } from '../utils/code-mode-allowed-names.js'; import { Kind, ToolConfirmationOutcome, @@ -599,6 +600,70 @@ describe('CodeModeOnly scheduler dispatch', () => { expect(call().status).toBe('success'); }, 40_000); + it('re-establishes the parent allowlist for a nested call resumed after approval', async () => { + // The approval resume path runs outside the parent exec's async frame, so + // the nested tool can only observe the allowlist when the scheduler + // re-establishes it from the request — which requires dispatchCodeModeTool + // to copy codeModeAllowedToolNames onto the nested request. + let observed: readonly string[] | undefined | 'unset' = 'unset'; + const execute = vi.fn(async () => { + observed = getCurrentCodeModeAllowedNames(); + return { + llmContent: 'approved', + returnDisplay: 'approved', + }; + }); + const updates: ToolCall[][] = []; + const { scheduler, run, completed, call } = setup( + [ + new MockTool({ + name: 'approval_probe', + kind: Kind.Other, + params: { type: 'object' }, + getDefaultPermission: async () => 'ask', + getConfirmationDetails: async () => ({ + type: 'info', + title: 'Approve nested tool', + prompt: 'Continue?', + onConfirm: vi.fn().mockResolvedValue(undefined), + }), + execute, + }), + ], + { + params: { interactive: true }, + onToolCallsUpdate: (calls) => updates.push(calls), + }, + ); + + const controller = new AbortController(); + const scheduled = run( + 'exec-approval-allowlist', + 'prompt-approval-allowlist', + 'await tools.approval_probe({})', + { codeModeAllowedToolNames: ['approval_probe'] }, + controller.signal, + ); + const waiting = () => + findUpdate(updates, 'approval_probe', 'awaiting_approval'); + await vi.waitFor(() => expect(waiting() !== undefined).toBe(true), { + timeout: 30_000, + }); + const { request, confirmationDetails } = waiting() as WaitingToolCall; + await scheduler.handleConfirmationResponse( + request.callId, + confirmationDetails.onConfirm, + ToolConfirmationOutcome.ProceedOnce, + controller.signal, + ); + + await scheduled; + await vi.waitFor(() => expect(completed).toHaveBeenCalledOnce()); + expect(execute).toHaveBeenCalledOnce(); + expect(call().status).toBe('success'); + expect(observed).toEqual(['approval_probe']); + }, 40_000); + it('runs nested hooks with the real tool name', async () => { const messageBus = { request: vi diff --git a/packages/core/src/config/config.test.ts b/packages/core/src/config/config.test.ts index d0e165be414..a3ccf696799 100644 --- a/packages/core/src/config/config.test.ts +++ b/packages/core/src/config/config.test.ts @@ -44,6 +44,7 @@ import { import { GOAL_DEFAULT_TOKEN_BUDGET } from '../goals/goal-protocol.js'; import { Storage } from './storage.js'; import { SshExecutionEnvironment } from '../services/ssh-execution-environment.js'; +import { ToolMode } from '../tools/code-mode.js'; import { DEFAULT_MAX_TOOL_CALLS_PER_TURN } from '../services/loopDetectionService.js'; import * as fs from 'node:fs'; import * as os from 'node:os'; @@ -9437,6 +9438,27 @@ describe('Server Config (config.ts)', () => { await config.shutdownExecutionEnvironments(); expect(dispose).toHaveBeenCalledOnce(); }); + it('reports the direct fallback as the effective tool mode under container execution', () => { + // Container execution cannot host exec, so a hybrid session falls back + // to direct tools and getToolMode() must say so — otherwise every + // isCodeModeEnabled gate takes the code-mode branch in a session where + // exec is never registered. CodeModeOnly stays a registry-creation + // rejection, not a silent downgrade. + const config = makeConfig({ + executionEnvironment: sshEnvironment(), + toolMode: 'code_mode', + }); + expect(config.getToolMode()).toBe(ToolMode.Direct); + expect(makeConfig({ toolMode: 'code_mode' }).getToolMode()).toBe( + ToolMode.CodeMode, + ); + expect( + makeConfig({ + executionEnvironment: sshEnvironment(), + toolMode: 'code_mode_only', + }).getToolMode(), + ).toBe(ToolMode.CodeModeOnly); + }); it('skips host project hooks, skills, extensions and memory during SSH initialization', async () => { const config = makeConfig({ executionEnvironment: sshEnvironment(), diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 540dafd807b..4d06b7a48f7 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -8427,6 +8427,17 @@ export class Config { } getToolMode(): ToolModeValue { + // Container execution cannot host exec and the registry falls back to + // direct tools there, so report the effective mode rather than the + // configured one. CodeModeOnly is excluded: registry creation rejects + // it. The virtual getter matters because derived (e.g. container + // subagent) configs supply the environment by overriding it. + if ( + this.toolMode === ToolMode.CodeMode && + this.getExecutionEnvironment() !== undefined + ) { + return ToolMode.Direct; + } return this.toolMode; } @@ -12676,7 +12687,7 @@ export class Config { ); } if ( - this.getToolMode() === ToolMode.CodeMode && + this.toolMode === ToolMode.CodeMode && !this.codeModeWarnings.containerFallback ) { this.codeModeWarnings.containerFallback = true; diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index b90cd3ac451..65b7f9daeca 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -1964,6 +1964,10 @@ export class CoreToolScheduler { parentCallId: parent.callId, source: 'code_mode', goalContext: parent.goalContext, + // Copied verbatim (including an empty array, which fails closed): a + // nested call resumed outside the parent's async frame — e.g. after an + // approval — re-establishes the ambient allowlist from this field. + codeModeAllowedToolNames: parent.codeModeAllowedToolNames, }; return new Promise((resolve, reject) => { this.nestedQueue.push({ request, signal, resolve, reject, onResult }); diff --git a/packages/core/src/tools/agent/agent.code-mode-review.test.ts b/packages/core/src/tools/agent/agent.code-mode-review.test.ts index e4d4944fde1..a4df7bae687 100644 --- a/packages/core/src/tools/agent/agent.code-mode-review.test.ts +++ b/packages/core/src/tools/agent/agent.code-mode-review.test.ts @@ -13,6 +13,7 @@ import { ToolRegistry } from '../tool-registry.js'; import { ExecTool } from '../exec.js'; import { ToolMode, getToolExposure } from '../code-mode.js'; import { ToolNames } from '../tool-names.js'; +import type { ExecutionEnvironment } from '../../services/execution-environment.js'; describe('Code-mode fork restriction matches declared call surfaces', () => { it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( @@ -140,4 +141,29 @@ describe('Code-mode fork restriction matches declared call surfaces', () => { expect(sentence).toContain(JSON.stringify([ToolNames.READ_FILE])); expect(sentence).toContain(ToolNames.EXEC); }); + + it('drops the exec carve-out for a container-backed hybrid session', () => { + // Container execution falls back to direct tools, so the child message + // must not claim the code mode always admits exec there; a non-container + // hybrid session keeps the carve-out. + const container = buildChildMessage( + 'Inspect the implementation', + [ToolNames.READ_FILE], + undefined, + undefined, + makeFakeConfig({ + toolMode: ToolMode.CodeMode, + executionEnvironment: {} as ExecutionEnvironment, + }).getToolMode(), + ); + expect(container).not.toContain(`except ${ToolNames.EXEC}`); + const hybrid = buildChildMessage( + 'Inspect the implementation', + [ToolNames.READ_FILE], + undefined, + undefined, + makeFakeConfig({ toolMode: ToolMode.CodeMode }).getToolMode(), + ); + expect(hybrid).toContain(`except ${ToolNames.EXEC}`); + }); }); diff --git a/packages/core/src/tools/agent/agent.test.ts b/packages/core/src/tools/agent/agent.test.ts index a4363b70640..8aabbe66c33 100644 --- a/packages/core/src/tools/agent/agent.test.ts +++ b/packages/core/src/tools/agent/agent.test.ts @@ -18,6 +18,12 @@ import type { ToolResultDisplay, AgentResultDisplay } from '../tools.js'; import { ToolConfirmationOutcome } from '../tools.js'; import type { ResidentBackgroundAgent } from '../../agents/background-tasks.js'; import { ToolNames } from '../tool-names.js'; +import { ToolMode } from '../code-mode.js'; +import { ToolRegistry } from '../tool-registry.js'; +import { ExecTool } from '../exec.js'; +import { AgentCore } from '../../agents/runtime/agent-core.js'; +import { MockTool } from '../../test-utils/mock-tool.js'; +import { makeFakeConfig } from '../../test-utils/config.js'; import { Config, ApprovalMode, @@ -1283,8 +1289,10 @@ describe('AgentTool', () => { expect(forkTools.minItems).toBeUndefined(); expectText(forkTools.description, [ 'Only valid with subagent_type "fork"', - 'In `direct` mode the model-visible tool declarations remain unchanged', - "this allowlist also narrows the fork's declarations", + '`direct` mode keeps declarations unchanged', + 'hybrid `code_mode` narrows them to the list', + 'Code modes admit `exec` ahead of a non-empty list', + 'an empty array rejects every tool call', ]); }); @@ -3673,6 +3681,46 @@ describe('AgentTool', () => { expect(allowed()).toEqual([]); }); + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'deny-all fork_tools closes the exec route in %s', + async (mode) => { + config.getToolMode = vi.fn().mockReturnValue(mode); + parentTools(readSearchCall, [...bridged()]); + await runFork( + forkParams('deny all tools', { + prompt: 'reason without tools', + fork_tools: [], + }), + ); + expect(allowed()).toEqual([]); + // Drive the captured child toolConfig through a real AgentCore: the + // empty execution allowlist must close the exec route in both code + // modes, at the declaration surface and at the admission gate. + const childConfig = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(childConfig); + vi.spyOn(childConfig, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(childConfig)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + const core = new AgentCore( + 'deny-all-fork', + childConfig, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + toolConfig(), + ); + const declarations = await core.prepareTools(); + expect(declarations.map((d) => d.name)).not.toContain(ToolNames.EXEC); + expect( + ( + core as unknown as { + isToolExecutionAllowed: (t: string) => boolean; + } + ).isToolExecutionAllowed.call(core, ToolNames.EXEC), + ).toBe(false); + }, + ); + it('preserves display_image in the fork declarations but denies its execution', async () => { parentTools([ [ToolNames.READ_FILE, 'Read a file'], diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 56105e1b175..db9adbc0565 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -857,7 +857,7 @@ export class AgentTool extends BaseDeclarativeTool { minLength: 1, }, description: - 'Only valid with subagent_type "fork". Exact tool names and MCP server patterns this fork may execute. Entries cannot have surrounding whitespace; wildcard entries must be "mcp__*" or a trailing MCP tool-prefix pattern such as "mcp__github__read_*". In `direct` mode the model-visible tool declarations remain unchanged for prompt-cache sharing; under hybrid `tools.mode: "code_mode"` this allowlist also narrows the fork\'s declarations. Forks can never execute ask_user_question; omit fork_tools to allow every other inherited tool, or use an empty array to reject every tool call.', + 'Only valid with subagent_type "fork". Exact tool names and MCP server patterns this fork may execute. Entries cannot have surrounding whitespace; wildcard entries must be "mcp__*" or a trailing MCP tool-prefix pattern such as "mcp__github__read_*". `direct` mode keeps declarations unchanged for prompt-cache sharing; hybrid `code_mode` narrows them to the list. Code modes admit `exec` ahead of a non-empty list (and `tool_search` in `code_mode_only`). Forks never execute ask_user_question; omit fork_tools to allow every other inherited tool, or an empty array rejects every tool call.', }, fork_profile: { type: 'string', diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index e93db6034e5..3586f6e63f5 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. diff --git a/packages/sdk-typescript/src/types/types.ts b/packages/sdk-typescript/src/types/types.ts index 3ace7d4d3fb..492beca591c 100644 --- a/packages/sdk-typescript/src/types/types.ts +++ b/packages/sdk-typescript/src/types/types.ts @@ -440,7 +440,7 @@ export interface QueryOptions { * unavailable; `direct-only` tools (`agent`, `send_message`, * `create_sub_session`, the worktree tools) never get a nested binding; * when withheld they stay reachable through the `tool_search` + `tool_call` - * bridge, not through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager + * bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager * from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. * Inheriting or explicitly granting `exec` keeps all otherwise admitted * ordinary code-mode-callable bindings. An execution allowlist that @@ -521,7 +521,8 @@ export interface QueryOptions { * bridge tool is unavailable; `direct-only` tools (`agent`, * `send_message`, `create_sub_session`, the worktree tools) never get a * nested binding; when withheld they stay reachable through the - * `tool_search` + `tool_call` bridge, not through `exec`. CodeModeOnly discovers deferred schemas through + * `tool_search` + `tool_call` bridge while both bridge tools are + * registered, never through `exec`. CodeModeOnly discovers deferred schemas through * top-level tool_search and invokes them through exec. It skips deferred * preload and startup catalogs; tools.eager reduces the initial exec * description. When search is unavailable in the current scope, exec From b98c1608637a95d55166a1babe0b3cef81a5c8e3 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Mon, 12 Oct 2026 01:36:30 +0000 Subject: [PATCH 21/49] docs(sub-agents): restore fork_tools deny-all contract line (#11854) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bullet claimed exec/tool_search remain admitted under a code mode even with fork_tools: [], but the exec carve-out in AgentCore.isToolExecutionAllowed is gated on a non-empty execution/nested allowlist, so an empty array closes the exec route too — as the same page's lead paragraph and docs/developers/tools/task.md already state. Drop the false parenthetical. Co-authored-by: Qwen-Coder --- docs/users/features/sub-agents.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index 4d494f2687b..ed51275b3ab 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -58,7 +58,7 @@ Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact c - Forks never execute `ask_user_question`; when user input is required, they report the blocker to their parent agent. - Omitting `fork_tools` allows every other inherited tool. -- An empty array rejects every tool call (under a code mode, `exec` — and `tool_search` in `code_mode_only` — remains admitted anyway; see above). +- An empty array rejects every tool call. - `*` is not accepted; omit `fork_tools` to allow every otherwise-executable inherited tool. - Tool names cannot have surrounding whitespace. Wildcards are accepted only as `mcp__*` or as a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. - `mcp__*` intentionally allows every MCP tool while still denying unlisted built-in tools. From 4307ddc2e0f639dad7d1d6a9240be0e8c8e6b559 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Tue, 13 Oct 2026 12:58:58 +0800 Subject: [PATCH 22/49] fix(core): keep bundled guidance reachable in hybrid agents --- docs/users/features/context-cost.md | 4 +- packages/core/src/core/mod-tool-check.test.ts | 8 +- .../core/src/skills/agent-delegation-skill.ts | 15 +--- .../core/src/skills/bundled-reference.test.ts | 81 +++++++++++++++++-- packages/core/src/skills/bundled-reference.ts | 17 +--- .../bundled/agent-delegation/SKILL.test.ts | 12 +-- .../src/subagents/subagent-manager.test.ts | 2 +- .../workflow/workflow-description.test.ts | 2 +- packages/core/src/tools/workflow/workflow.ts | 11 ++- 9 files changed, 99 insertions(+), 53 deletions(-) diff --git a/docs/users/features/context-cost.md b/docs/users/features/context-cost.md index 3d1d74b27a0..b0a45725ad4 100644 --- a/docs/users/features/context-cost.md +++ b/docs/users/features/context-cost.md @@ -53,9 +53,9 @@ Measure the allowlist against the right baseline. Tools that are on demand by _t Four things to know before you use it: - **It is not a disable.** A demoted tool stays reachable. If you meant to remove a tool, use a whole-tool `permissions.deny` rule or `tools.disabled`. -- **Some tools are exempt** and keep their normal loading behaviour whatever the list says: `tool_search` and `tool_call` (the two halves of the bridge that reaches a withheld tool), `structured_output`, the plan-mode lifecycle tools (`enter_plan_mode`, `exit_plan_mode`, `ask_user_question`), `task_stop`, MCP tools (`mcp__*`), and Computer Use tools (`computer_use__*`). `task_stop` and the Computer Use family are on demand by default anyway, so gating them would save nothing; MCP tools are governed by `tools.toolSearch.*` and the per-server `includeTools` / `excludeTools` filters; and nothing in `tools.eager` can drop one of the rest: that takes a whole-tool `permissions.deny` rule, a `tools.disabled` entry, or `--exclude-tools` — and for the bridge pair, `tools.toolSearch.enabled: false` removes both halves at once. Removing a bridge half is not a neutral way out of the allowlist: every ordinary deferred tool (all MCP tools, the deferred Computer Use family) is then force-declared into every request, while a withheld tool stays out of top-level declarations and cannot be loaded back through the bridge. In direct and hybrid modes it stays registered, so a direct call by name still goes through normal approval. On the hybrid session surface, callable nested tools retain their schemas inside `exec` when the bridge is incomplete; withholding their top-level declarations does not save those schema tokens. +- **Some tools are exempt** and keep their normal loading behaviour whatever the list says: `tool_search` and `tool_call` (the two halves of the bridge that reaches a withheld tool), `structured_output`, the plan-mode lifecycle tools (`enter_plan_mode`, `exit_plan_mode`, `ask_user_question`), `task_stop`, MCP tools (`mcp__*`), and Computer Use tools (`computer_use__*`). `task_stop` and the Computer Use family are on demand by default anyway, so gating them would save nothing; MCP tools are governed by `tools.toolSearch.*` and the per-server `includeTools` / `excludeTools` filters; and nothing in `tools.eager` can drop one of the rest: that takes a whole-tool `permissions.deny` rule, a `tools.disabled` entry, or `--exclude-tools` — and for the bridge pair, `tools.toolSearch.enabled: false` removes both halves at once. Removing a bridge half is not a neutral way out of the allowlist: in direct and hybrid modes, every ordinary deferred tool (all MCP tools, the deferred Computer Use family) is then force-declared into every request, while a withheld tool stays out of top-level declarations and cannot be loaded back through the bridge. In direct and hybrid modes it stays registered, so a direct call by name still goes through normal approval. On the hybrid session surface, callable nested tools retain their schemas inside `exec` when the bridge is incomplete; withholding their top-level declarations does not save those schema tokens. - **`permissions.allow` saves nothing.** It is pure auto-approval: it never demotes, hides, or removes a tool. Neither do approval modes. -- **It needs both halves of the bridge.** A withheld tool is reviewed with `tool_search` and invoked through `tool_call`; `tool_search` alone can read a schema it cannot call. If either is unregistered — `tools.toolSearch.enabled: false` denies both; a `tool_search`/`tool_call` deny rule, an `--exclude-tools` entry, or a `tools.disabled` entry removes one — the allowlist still withholds top-level schemas and nothing can load them back through the bridge. In direct and hybrid modes a warning is logged; the tools stay registered, so a direct call by name still goes through normal approval. On the hybrid session surface, callable nested tools still carry their full schemas inside `exec`. Code Mode Only discovers deferred schemas through top-level `tool_search` and calls them through `exec`; when search is unavailable in the current scope, `exec` includes all allowed signatures. Only skips the bridge warning and budget preload, while `tools.eager` and `tools.visible` control its initial documented bindings. In Hybrid mode, AgentCore excludes tools still hidden by `tools.eager` from nested bindings. Ordinary deferred tools fall back to being declared eagerly in that case; tools you demoted with `tools.eager` do not. +- **It needs both halves of the bridge.** A withheld tool is reviewed with `tool_search` and invoked through `tool_call`; `tool_search` alone can read a schema it cannot call. If either is unregistered — `tools.toolSearch.enabled: false` denies both; a `tool_search`/`tool_call` deny rule, an `--exclude-tools` entry, or a `tools.disabled` entry removes one — the allowlist still withholds top-level schemas and nothing can load them back through the bridge. In direct and hybrid modes a warning is logged; the tools stay registered, so a direct call by name still goes through normal approval. On the hybrid session surface, callable nested tools still carry their full schemas inside `exec`. Code Mode Only discovers deferred schemas through top-level `tool_search` and calls them through `exec`; when search is unavailable in the current scope, `exec` includes all allowed signatures. Only skips the bridge warning and budget preload, while `tools.eager` and `tools.visible` control its initial documented bindings. In Hybrid mode, AgentCore excludes tools still hidden by `tools.eager` from nested bindings. In direct and hybrid modes, ordinary deferred tools fall back to being declared eagerly in that case; tools you demoted with `tools.eager` do not. Code Mode Only has no top-level deferred set to reveal: its ordinary deferred tools stay inside `exec`, whose signature list expands to all allowed signatures when search is unavailable. `tools.visible` is the escape hatch for one tool you want declared up front even though it is deferred by default. diff --git a/packages/core/src/core/mod-tool-check.test.ts b/packages/core/src/core/mod-tool-check.test.ts index 935fe7dc7c3..dacd8b121c1 100644 --- a/packages/core/src/core/mod-tool-check.test.ts +++ b/packages/core/src/core/mod-tool-check.test.ts @@ -19,6 +19,7 @@ import { PermissionManager } from '../permissions/permission-manager.js'; import type { PermissionDecision } from '../permissions/types.js'; import { makeFakeConfig } from '../test-utils/config.js'; import { MockTool } from '../test-utils/mock-tool.js'; +import { ToolMode } from '../tools/code-mode.js'; import { ExecTool } from '../tools/exec.js'; import { ToolErrorType } from '../tools/tool-error.js'; import { ToolRegistry } from '../tools/tool-registry.js'; @@ -80,7 +81,7 @@ function setup( }); const registry = new ToolRegistry(config); registry.registerTool(tool); - if (options.config?.codeModeOnly) { + if (options.config?.toolMode === ToolMode.CodeModeOnly) { registry.registerTool(new ExecTool(config)); } vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); @@ -413,7 +414,10 @@ describe('headless-owned Mod tool.check restriction', () => { }), ); const harness = setup(check, { - config: { codeModeOnly: true, approvalMode: ApprovalMode.YOLO }, + config: { + toolMode: ToolMode.CodeModeOnly, + approvalMode: ApprovalMode.YOLO, + }, }); const call = await harness.run( { source: 'text(await tools.checked_tool({value: "nested"}));' }, diff --git a/packages/core/src/skills/agent-delegation-skill.ts b/packages/core/src/skills/agent-delegation-skill.ts index 0bbf5da56fb..109e9169f53 100644 --- a/packages/core/src/skills/agent-delegation-skill.ts +++ b/packages/core/src/skills/agent-delegation-skill.ts @@ -45,20 +45,11 @@ const POINTER = `## Writing the prompt Before writing a delegation prompt, load the \`${AGENT_DELEGATION_SKILL_NAME}\` skill — what to put in the prompt, what not to delegate, how a fork prompt differs, and a worked example.`; /** - * Leads the inlined reference, mirroring the workflow reference's note: the - * body is written for sessions that can load skills, so say up front that the - * pointers inside it do not apply here. The "even one named in a skill - * listing" clause is load-bearing, not courtesy: a session whose - * `tools.eager` allowlist withholds the Skill tool still gets an - * `` prelude naming this skill in the same request, and - * without the clause the description contradicts the listing. The workflow - * note's second clause ("Where it points at another skill…") is dropped on - * purpose: this reference names no other skill. A rule separator follows, - * because the body opens with its own title and would otherwise read as a - * continuation of the fork section above it. + * Inline guidance must also work when a shared registry cannot prove that the + * current agent can load skills. Avoid claims about session-wide availability. */ const INLINE_NOTE = - 'Skills cannot be loaded in this session, even one named in a skill listing, so the delegation reference follows in full.'; + 'The delegation reference follows in full. Use this inline guidance directly.'; /** * The Agent tool's prompt-writing section for this session. diff --git a/packages/core/src/skills/bundled-reference.test.ts b/packages/core/src/skills/bundled-reference.test.ts index 1f8f20eaaad..db5b9b4a63e 100644 --- a/packages/core/src/skills/bundled-reference.test.ts +++ b/packages/core/src/skills/bundled-reference.test.ts @@ -24,7 +24,15 @@ */ import { describe, expect, it, vi } from 'vitest'; -import { AGENT_DELEGATION_SKILL_NAME } from './agent-delegation-skill.js'; +import { AgentCore } from '../agents/runtime/agent-core.js'; +import { + AGENT_DELEGATION_SKILL_NAME, + resolveAgentDelegationSurface, +} from './agent-delegation-skill.js'; +import { MockTool } from '../test-utils/mock-tool.js'; +import { ToolRegistry } from '../tools/tool-registry.js'; +import { ExecTool } from '../tools/exec.js'; +import { ToolMode } from '../tools/code-mode.js'; import { readBundledReference, resolveBundledReferenceRoute, @@ -77,9 +85,9 @@ describe('hybrid reference routes', () => { ); it.each([ - [[], 'skill'], - [['tool_search'], 'skill'], - [['tool_call'], 'skill'], + [[], 'inline'], + [['tool_search'], 'inline'], + [['tool_call'], 'inline'], [['tool_search', 'tool_call'], 'skill-via-tool-search'], ] as const)('uses a reachable skill with bridge %j', (bridge, route) => { const config = { @@ -94,9 +102,7 @@ describe('hybrid reference routes', () => { expect(resolveBundledReferenceRoute(config, 'agent-delegation')).toBe( route, ); - expect(isToolHiddenBehindToolSearch(config, 'skill')).toBe( - bridge.length === 2, - ); + expect(isToolHiddenBehindToolSearch(config, 'skill')).toBe(true); }); it('inlines a hidden skill when both exec and the bridge are unavailable', () => { @@ -164,3 +170,64 @@ describe('readBundledReference', () => { } }); }); + +it.each([ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL])( + 'inlines Skill guidance for a child reusing the session registry without %s', + async (missingBridge) => { + const config = makeFakeConfig({ + toolMode: ToolMode.CodeMode, + eagerTools: [ToolNames.EXEC, ToolNames.READ_FILE], + disabledTools: [missingBridge], + }); + vi.spyOn(config, 'getSkillManager').mockReturnValue({} as never); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + for (const name of [ + ToolNames.READ_FILE, + ToolNames.TOOL_SEARCH, + ToolNames.TOOL_CALL, + ]) { + registry.registerTool(new MockTool({ name })); + } + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + try { + // Descriptions are chosen before the child warms its inherited registry. + const surface = resolveAgentDelegationSurface(config); + const core = new AgentCore( + 'workflow-child', + config, + { systemPrompt: '' }, + { model: 'test' }, + { max_turns: 1 }, + { tools: ['*'] }, + ); + const declarations = await core.runInAgentFrames(() => + core.prepareTools(), + ); + expect(registry.forSubAgent).toBe(false); + expect(registry.isDeferredAndHidden(ToolNames.SKILL)).toBe(true); + expect( + registry + .getCodeModeBindingPlan() + .bindings.map((binding) => binding.name), + ).toContain(ToolNames.SKILL); + expect(declarations.map((tool) => tool.name)).not.toContain( + ToolNames.SKILL, + ); + expect( + declarations.find((tool) => tool.name === ToolNames.EXEC)?.description, + ).not.toContain('"name":"skill"'); + expect(Reflect.get(core, 'codeModeAllowedToolNames')).not.toContain( + ToolNames.SKILL, + ); + expect(surface).toBe('inline'); + } finally { + await registry.stop(); + vi.restoreAllMocks(); + } + }, +); diff --git a/packages/core/src/skills/bundled-reference.ts b/packages/core/src/skills/bundled-reference.ts index d7a25c7850d..200a1f4a07c 100644 --- a/packages/core/src/skills/bundled-reference.ts +++ b/packages/core/src/skills/bundled-reference.ts @@ -209,24 +209,13 @@ export function resolveBundledReferenceSurface( * `tools.visible`. A ToolSearch reveal is not consulted, because `/clear` * drops it — a decision recorded once has to ask this. CodeModeOnly discovers * schemas through top-level search and invokes deferred tools through exec. - * Session Hybrid exec also carries their schemas when the bridge is incomplete. - * AgentCore filters eager-hidden tools from its nested bindings, so an agent - * registry cannot use that session fallback, even before prepareTools runs. + * A registry can be shared with an AgentCore that filters eager-hidden tools + * from exec. Inline the reference without a complete bridge rather than assume + * every consumer can use the session exec bindings. */ function isToolDeferredBehindToolSearch(config: Config, name: string): boolean { const mode = config.getToolMode?.(); if (mode === ToolMode.CodeModeOnly) return false; - const names = config.getToolRegistry?.()?.getAllToolNames?.() ?? []; - if ( - mode === ToolMode.CodeMode && - !config.getToolRegistry?.()?.forSubAgent && - names.includes(ToolNames.EXEC) && - !( - names.includes(ToolNames.TOOL_SEARCH) && - names.includes(ToolNames.TOOL_CALL) - ) - ) - return false; if (!config.getToolRegistry?.()?.isPermissionDeferred?.(name)) return false; return !config.getVisibleTools?.()?.has(name); } diff --git a/packages/core/src/skills/bundled/agent-delegation/SKILL.test.ts b/packages/core/src/skills/bundled/agent-delegation/SKILL.test.ts index 0ef06270cca..e6929f83604 100644 --- a/packages/core/src/skills/bundled/agent-delegation/SKILL.test.ts +++ b/packages/core/src/skills/bundled/agent-delegation/SKILL.test.ts @@ -319,12 +319,8 @@ describe('bundled agent-delegation skill', () => { it('travels in the description when no skill can be loaded', async () => { const description = await agentDescription({ skills: false }); - expect(description).toContain('Skills cannot be loaded in this session'); - // The clause that reconciles this preamble with the same request's - // prelude, which lists this skill by name: without it - // the description denies a skill the listing just offered, and the model - // spends a call finding out. Dropping it from INLINE_NOTE turns this red. - expect(description).toContain('even one named in a skill listing'); + expect(description).toContain('The delegation reference follows in full'); + expect(description).toContain('Use this inline guidance directly'); expect(description).toContain('Never delegate understanding'); expect(description).not.toContain( `load the \`${AGENT_DELEGATION_SKILL_NAME}\` skill`, @@ -358,7 +354,7 @@ describe('bundled agent-delegation skill', () => { `load the \`${AGENT_DELEGATION_SKILL_NAME}\` skill`, ); expect(description).not.toContain( - 'Skills cannot be loaded in this session', + 'The delegation reference follows in full', ); expect(description).not.toContain('Never delegate understanding'); expect(description).not.toContain('## Writing the prompt'); @@ -393,7 +389,7 @@ describe('bundled agent-delegation skill', () => { `load the \`${AGENT_DELEGATION_SKILL_NAME}\` skill`, ); expect(description).not.toContain( - 'Skills cannot be loaded in this session', + 'The delegation reference follows in full', ); expect(description).not.toContain('Never delegate understanding'); expect(description).not.toContain('## Writing the prompt'); diff --git a/packages/core/src/subagents/subagent-manager.test.ts b/packages/core/src/subagents/subagent-manager.test.ts index 9c149a804bd..4fcba5a1af5 100644 --- a/packages/core/src/subagents/subagent-manager.test.ts +++ b/packages/core/src/subagents/subagent-manager.test.ts @@ -3144,7 +3144,7 @@ describe('SubagentManager', () => { .ensureTool(ToolNames.AGENT)) as AgentTool; await agentTool.refreshSubagents(); expect(agentTool.description).toContain( - 'Skills cannot be loaded in this session', + 'The delegation reference follows in full', ); }, ); diff --git a/packages/core/src/tools/workflow/workflow-description.test.ts b/packages/core/src/tools/workflow/workflow-description.test.ts index 04e1d63528e..e145763faf7 100644 --- a/packages/core/src/tools/workflow/workflow-description.test.ts +++ b/packages/core/src/tools/workflow/workflow-description.test.ts @@ -165,7 +165,7 @@ describe('Workflow tool description shape', () => { "authoring reference in this tool's description", ); expect(instance.description).toContain( - 'that skill is not available here either', + 'references to other skills do not establish that those skills are available', ); }); diff --git a/packages/core/src/tools/workflow/workflow.ts b/packages/core/src/tools/workflow/workflow.ts index 3a937546bdd..dbd8f2b462f 100644 --- a/packages/core/src/tools/workflow/workflow.ts +++ b/packages/core/src/tools/workflow/workflow.ts @@ -1562,12 +1562,11 @@ const WORKFLOW_TOOL_RUNTIME_NAME_ONLY = withReplacements( const WORKFLOW_AUTHORING_TOOL_SEARCH_NOTE = ` ${toolSearchBridgeSentence(ToolDisplayNames.SKILL)}`; /** - * Leads the inlined reference. The reference is written for sessions that can - * load skills, so it names another one (`workflow-creator`); say up front that - * such pointers do not apply here. + * The reference names another skill (`workflow-creator`), but a shared registry + * does not prove that the current agent can load it. */ const WORKFLOW_AUTHORING_INLINE_NOTE = - 'Skills cannot be loaded in this session, even one named in a skill listing, so the authoring reference follows in full. Where it points at another skill, that skill is not available here either.'; + 'The authoring reference follows in full. Use this inline guidance directly; references to other skills do not establish that those skills are available.'; /** * The tool description for a given shape. @@ -1575,8 +1574,8 @@ const WORKFLOW_AUTHORING_INLINE_NOTE = * - `pointer` / `pointer-via-tool-search`: decision + runtime + a line naming * the skill. This is the point of moving the reference out: roughly four * times this text, needed only on the turn that writes a script. - * - `inline`: decision + the reference in full. No route to any skill, so a - * pointer would leave the model writing scripts against nothing. + * - `inline`: decision + the reference in full. A skill-loading route cannot + * be established for every consumer, so avoid relying on a pointer. * - `withheld`: decision + runtime. The user turned the reference off; putting * it back into every request would raise exactly the cost they removed. * From dd262a96f6608697fcc0701b9fe5439edb1e29cd Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Tue, 13 Oct 2026 11:32:53 +0000 Subject: [PATCH 23/49] test(cli): raise vi.waitFor timeouts on contention-exposed waits (#11854) The deterministic gate runs packages/cli's full --changed set at --maxWorkers=25%; under that load vitest's default 1s waitFor timeout expired before the async dispatch/render landed (three failures, plus a SessionWriterLostError when a delayed hook execution outlived its timed-out test's lease). Give the exposed waits an explicit 10s timeout, matching the sibling convention in hosted-harness-session.test.ts. No assertions removed and no tests disabled. --- .../cli/src/serve/hosted-hook-session.test.ts | 38 ++++++++++++------- packages/cli/src/ui/AppContainer.test.tsx | 27 ++++++++----- 2 files changed, 42 insertions(+), 23 deletions(-) diff --git a/packages/cli/src/serve/hosted-hook-session.test.ts b/packages/cli/src/serve/hosted-hook-session.test.ts index 89c8453d708..a6962265039 100644 --- a/packages/cli/src/serve/hosted-hook-session.test.ts +++ b/packages/cli/src/serve/hosted-hook-session.test.ts @@ -1040,7 +1040,9 @@ it('waits for Runtime admission before acknowledging an async Hook', async () => completed = true; return result; }); - await vi.waitFor(() => expect(finish).toBeDefined()); + await vi.waitFor(() => expect(finish).toBeDefined(), { + timeout: 10_000, + }); expect(completed).toBe(false); finish!({ success: true, outcome: 'success', duration: 0 }); await firing; @@ -1076,7 +1078,9 @@ it('rejects a changed input while the same occurrence is still running', async ( { tool_name: 'read_file' }, signal(), ); - await vi.waitFor(() => expect(finish).toBeDefined()); + await vi.waitFor(() => expect(finish).toBeDefined(), { + timeout: 10_000, + }); await expect( hooks.fire( HookEventName.PreToolUse, @@ -1105,7 +1109,9 @@ it('cancels an active occurrence and does not dispatch later sequential hooks', finish = resolve; }); const firing = hooks.fire(HookEventName.PreToolUse, 'call-1', {}, signal()); - await vi.waitFor(() => expect(finish).toBeDefined()); + await vi.waitFor(() => expect(finish).toBeDefined(), { + timeout: 10_000, + }); const cancelled = await hooks.status('call-1', true); expect(cancelled.cancelRequested).toBe(true); finish!({ success: false, outcome: 'cancelled', duration: 0 }); @@ -1209,13 +1215,15 @@ it('cancels a detached child after its async marker has admitted it', async () = true, ); await hooks.status('call-1', true); - await vi.waitFor(() => - expect( - session.authority - .extensionRecordsInDomain('hook_execution') - .filter((record) => !record.recordId.startsWith('hook-plan-')) - .map((record) => record.run.state), - ).toEqual(['cancelled']), + await vi.waitFor( + () => + expect( + session.authority + .extensionRecordsInDomain('hook_execution') + .filter((record) => !record.recordId.startsWith('hook-plan-')) + .map((record) => record.run.state), + ).toEqual(['cancelled']), + { timeout: 10_000 }, ); expect( requests.filter((request) => request.kind === 'hook-cancel').length, @@ -1753,10 +1761,12 @@ it('fences a hook-cancel that lands during module evaluation as outcome_unknown' {}, abort.signal, ); - await vi.waitFor(() => - expect( - requests.filter((request) => request.kind === 'hook-execute'), - ).toHaveLength(1), + await vi.waitFor( + () => + expect( + requests.filter((request) => request.kind === 'hook-execute'), + ).toHaveLength(1), + { timeout: 10_000 }, ); abort.abort(); await expect(fired).rejects.toBeInstanceOf(HostedHookRecoveryRequiredError); diff --git a/packages/cli/src/ui/AppContainer.test.tsx b/packages/cli/src/ui/AppContainer.test.tsx index c2c3c9463b7..df084c16bac 100644 --- a/packages/cli/src/ui/AppContainer.test.tsx +++ b/packages/cli/src/ui/AppContainer.test.tsx @@ -1228,9 +1228,12 @@ describe('AppContainer State Management', () => { />, ); - await vi.waitFor(() => { - expect(startupNoticeSpy).toHaveBeenCalled(); - }); + await vi.waitFor( + () => { + expect(startupNoticeSpy).toHaveBeenCalled(); + }, + { timeout: 10_000 }, + ); expect(readCronTasksMock).not.toHaveBeenCalled(); expect(addItem).not.toHaveBeenCalledWith( expect.objectContaining({ @@ -1274,9 +1277,12 @@ describe('AppContainer State Management', () => { />, ); - await vi.waitFor(() => { - expect(startupNoticeSpy).toHaveBeenCalled(); - }); + await vi.waitFor( + () => { + expect(startupNoticeSpy).toHaveBeenCalled(); + }, + { timeout: 10_000 }, + ); expect(addItem).not.toHaveBeenCalledWith( expect.objectContaining({ text: expect.stringContaining('active scheduled'), @@ -3357,9 +3363,12 @@ describe('AppContainer State Management', () => { ); // The startup effect arms pendingWorktreeNoticeRef from the consumed // one-shot Config notice; wait for it before submitting. - await vi.waitFor(() => { - expect(startupNoticeSpy).toHaveBeenCalled(); - }); + await vi.waitFor( + () => { + expect(startupNoticeSpy).toHaveBeenCalled(); + }, + { timeout: 10_000 }, + ); act(() => { capturedUIActions.setShellModeActive(true); From a5d9ac13be6493ea9377185c3f8cb5bd6ec57762 Mon Sep 17 00:00:00 2001 From: Dragon <52599892+DragonnZhang@users.noreply.github.com> Date: Wed, 14 Oct 2026 12:44:17 +0800 Subject: [PATCH 24/49] docs: clarify persisted fork tool bounds --- docs/design/code-mode.md | 10 ++++++---- docs/design/code-mode.zh-CN.md | 9 +++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index 53098ccfcab..846694efc5e 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -87,10 +87,12 @@ otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. Forks inherit the parent's direct-call bound separately from its nested binding set; nested access never widens -the child's direct-call grant. A fork carrying an explicit `fork_tools`, a -fork profile, or an enclosing agent allowlist writes both bounds to its -background metadata, and resume restores them verbatim; a plain fork persists -neither bound, so resume re-derives both from the parent's live surface and +the child's direct-call grant. In a code mode, a fork launched under an +enclosing agent allowlist writes both bounds to its background metadata, and +resume restores them verbatim. A fork carrying only an explicit `fork_tools` +list or a fork profile persists its direct-call bound alone, so resume +re-derives its nested binding set from the parent's live surface and that set +can widen. A plain fork persists neither bound, so resume re-derives both and the child's grant can widen. ## Constraints and risks diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 0b50f7988bf..601e4695c49 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -77,10 +77,11 @@ Hybrid 的 AgentCore 调用面从嵌套绑定中排除被 `tools.eager` 隐藏 会保留所有通过其他准入检查的普通 code-mode-callable binding。若执行 allowlist 包含任一 MCP 工具项,MCP 绑定还必须匹配其中的精确工具名或服务器模式。 Fork 分别继承父级的直接调用边界与嵌套绑定集合;嵌套访问权限不会扩大子级 -的直接调用授权。携带显式 `fork_tools`、fork profile 或外层智能体 allowlist 的 -fork 会把这两个边界写入后台元数据,resume 时按原样恢复;普通 fork 两个边界 -都不持久化,resume 会依据父级的实时工具面重新推导二者,因此子级的授权可能 -扩大。 +的直接调用授权。在 code mode 下,受外层智能体 allowlist 约束的 fork 会把两个 +边界写入后台元数据,resume 时按原样恢复。仅携带显式 `fork_tools` 列表或 +fork profile 的 fork 只持久化直接调用边界,resume 会依据父级的实时工具面 +重新推导嵌套绑定集合,因此该集合可能扩大。普通 fork 两个边界都不持久化, +resume 会重新推导二者,因此子级的授权可能扩大。 ## 约束与风险 From f7bab3dde06d048e099aba0ad220fd6497c4e019 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Wed, 14 Oct 2026 10:37:51 +0000 Subject: [PATCH 25/49] fix(core): close CodeModeOnly skill route when Skill is unregistered (#11854) Co-authored-by: Qwen-Coder --- .../src/agents/background-agent-resume.ts | 6 +++ .../core/src/agents/runtime/agent-core.ts | 10 +++-- .../runtime/subagent-plan-tool-policy.test.ts | 41 ++++++++++++++++++- .../runtime/subagent-plan-tool-policy.ts | 26 ++++++++---- .../core/src/subagents/subagent-manager.ts | 31 ++++++++------ 5 files changed, 87 insertions(+), 27 deletions(-) diff --git a/packages/core/src/agents/background-agent-resume.ts b/packages/core/src/agents/background-agent-resume.ts index 8b2eb2bf9f5..d18da633262 100644 --- a/packages/core/src/agents/background-agent-resume.ts +++ b/packages/core/src/agents/background-agent-resume.ts @@ -146,6 +146,7 @@ function subagentWillHaveSkillTool( execBindingsAvailable = false, skillEagerHidden = false, codeModeOnly = false, + skillRegistered = true, ): boolean { // Launch reads `config.tools?.length ? resolveToolNames(config.tools) : ['*']`, // and `resolveToolNames`' `for...of` walks a bare string per character, @@ -176,6 +177,7 @@ function subagentWillHaveSkillTool( execBindingsAvailable, skillEagerHidden, codeModeOnly, + skillRegistered, ); } @@ -1037,6 +1039,10 @@ export class BackgroundAgentResumeService { hasAgentSkillExecBinding(activeAgentConfig), isAgentSkillEagerHidden(activeAgentConfig), activeAgentConfig.getToolMode?.() === ToolMode.CodeModeOnly, + activeAgentConfig + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL), ), }) )[0], diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index b249891e6b9..c29febe9e8d 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -666,12 +666,13 @@ export class AgentCore { * disallowed `skill` was still shown every skill it could not load. */ private willHaveSkillTool(): boolean { + const skillRegistered = this.runtimeContext + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL); if ( this.runtimeContext.getToolMode?.() === ToolMode.CodeMode && - !this.runtimeContext - .getToolRegistry() - .getAllToolNames() - .includes(ToolNames.SKILL) + !skillRegistered ) { return false; } @@ -680,6 +681,7 @@ export class AgentCore { hasAgentSkillExecBinding(this.runtimeContext), isAgentSkillEagerHidden(this.runtimeContext), this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, + skillRegistered, ); } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index f4a35a0ce81..390f4b0e742 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -345,14 +345,20 @@ describe('subagent plan tool policy', () => { }); describe('hasAgentSkillExecBinding', () => { - const contextWith = (mode: ToolMode, registerExec: boolean) => { + const contextWith = ( + mode: ToolMode, + registerExec: boolean, + registerSkill = true, + ) => { const config = makeFakeConfig({ toolMode: mode }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); if (registerExec) { registry.registerTool(new ExecTool(config)); } - registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + if (registerSkill) { + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + } return config; }; @@ -406,6 +412,37 @@ describe('subagent plan tool policy', () => { }, ); + // In CodeModeOnly the exec gateway reaches only registered tools, so a + // Skill the registry never registered (a deny rule, a legacy coreTools + // allowlist, or a skill-withheld parent's Config keeps the factory out) + // closes every route even while exec itself is registered — including the + // wildcard and an explicit Skill entry, the two arms that bypass + // execRouteOpen. Removing the skillRegistered term from the predicate's + // codeModeOnly veto turns each row red. + it.each([ + ['a wildcard', { tools: ['*'] }], + ['an explicit Skill entry', { tools: [ToolNames.SKILL] }], + ['no tool config', undefined], + ])( + 'closes every CodeModeOnly Skill route when skill is unregistered: %s', + (_label, toolConfig) => { + const context = contextWith(ToolMode.CodeModeOnly, true, false); + expect(hasAgentSkillExecBinding(context)).toBe(true); + expect( + toolConfigAllowsSkill( + toolConfig, + hasAgentSkillExecBinding(context), + isAgentSkillEagerHidden(context), + context.getToolMode?.() === ToolMode.CodeModeOnly, + context + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL), + ), + ).toBe(false); + }, + ); + it('keeps the wildcard route open in CodeModeOnly while exec is registered', () => { const context = contextWith(ToolMode.CodeModeOnly, true); expect( diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 97c1d5cd0e0..700b63502d5 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -141,8 +141,9 @@ export function hasAgentSkillExecBinding( * be loaded — the disagreement #12424 reports. * * Callers supply whether exec bindings are reachable in the current mode and - * registry. A finite list naming exec can therefore reach Skill without - * naming it directly. CodeModeOnly retains eager-deferred nested targets; + * registry, and whether the Skill factory is registered there at all. A + * finite list naming exec can therefore reach Skill without naming it + * directly. CodeModeOnly retains eager-deferred nested targets; * The eager-hidden input vetoes every route in Hybrid, including wildcards * and explicit Skill entries. Other permission bounds stay in prepareTools(). * Registry deny/exclude rules remain the bundled-reference resolver's concern; @@ -152,11 +153,15 @@ export function hasAgentSkillExecBinding( * gate (`AgentCore.canInvokeSkill`) never counts a direct Skill declaration * there — so when that route is closed no `toolConfig` shape reaches Skill: * not the wildcard, not registry inheritance, not an explicit entry. The - * route is closed when `exec` itself is missing from the registry (a deny - * rule or a legacy coreTools allowlist keeps it out), when the agent - * blocklists `exec` (`prepareTools()` drops it from the declarations), or - * when an execution allowlist names neither `skill` nor `exec` (`skill` - * stays out of `codeModeAllowedToolNames`). + * route is closed when `skill` itself is missing from the registry — `exec` + * binds only registered tools, and a deny rule, a legacy coreTools allowlist, + * or a skill-withheld parent Config keeps the factory out (Config registers + * it for a subagent only when that subagent holds a SkillManager) — when + * `exec` itself is missing from the registry (a deny rule or a legacy + * coreTools allowlist keeps it out), when the agent blocklists `exec` + * (`prepareTools()` drops it from the declarations), or when an execution + * allowlist names neither `skill` nor `exec` (`skill` stays out of + * `codeModeAllowedToolNames`). * * Matching is exact, as `prepareTools()`'s is: `SubagentManager` resolves * configured names to canonical tool names before they reach a `ToolConfig`. @@ -172,11 +177,16 @@ export function toolConfigAllowsSkill( execBindingsAvailable = false, skillEagerHidden = false, codeModeOnly = false, + skillRegistered = true, ): boolean { if (skillEagerHidden || EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { return false; } - if (codeModeOnly && !execBindingsAvailable) { + // exec binds only registered tools, so a registry without the Skill + // factory (a deny rule or a legacy coreTools allowlist keeps it out, or a + // skill-withheld parent's Config never registered it) closes the gateway + // just as a missing exec does. + if (codeModeOnly && !(execBindingsAvailable && skillRegistered)) { return false; } // No per-agent config inherits the whole registry. diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index ad377c23d9e..4d0ec02d110 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -1195,29 +1195,34 @@ export class SubagentManager { runtimeContext, skillRegistryWillBeRebuilt, ); - if ( - skillRegistryWillBeRebuilt && - runtimeContext.getToolMode?.() === ToolMode.CodeMode && - !runtimeContext - .getToolRegistry() - .getAllToolNames() - .includes(ToolNames.SKILL) - ) { + let skillRegistered = runtimeContext + .getToolRegistry() + .getAllToolNames() + .includes(ToolNames.SKILL); + if (skillRegistryWillBeRebuilt && !skillRegistered) { // A parent without a SkillManager omits the Skill factory entirely. - // Recover its registration policy before restoring skills to a child. + // Recover its registration policy before restoring skills to a child: + // when policy allows, a child granted skills here holds the session's + // manager, so its rebuilt registry re-registers the factory (Config + // gates it on the child's own SkillManager). const status = await runtimeContext .getPermissionManager?.() ?.getToolRegistrationStatus(ToolNames.SKILL); - skillEagerHidden = - status === 'disabled' || - (status === 'deferred' && - !runtimeContext.getVisibleTools().has(ToolNames.SKILL)); + if (runtimeContext.getToolMode?.() === ToolMode.CodeMode) { + skillEagerHidden = + status === 'disabled' || + (status === 'deferred' && + !runtimeContext.getVisibleTools().has(ToolNames.SKILL)); + } + skillRegistered = + status !== 'disabled' && sessionSkillManager(runtimeContext) != null; } const skillsAvailable = toolConfigAllowsSkill( toolConfig, hasAgentSkillExecBinding(runtimeContext, skillRegistryWillBeRebuilt), skillEagerHidden, runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, + skillRegistered, ); const { context: subagentContext, cleanup } = await this.buildSubagentContextOverride( From 48bed39b783c36dec790f703e27b236da74ea04b Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Wed, 14 Oct 2026 11:21:49 +0000 Subject: [PATCH 26/49] fix(core): tolerate registry-less stub Config in willHaveSkillTool (#11854) Co-authored-by: Qwen-Coder --- packages/core/src/agents/runtime/agent-core.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index c29febe9e8d..8a1f8846e7c 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -666,10 +666,11 @@ export class AgentCore { * disallowed `skill` was still shown every skill it could not load. */ private willHaveSkillTool(): boolean { - const skillRegistered = this.runtimeContext - .getToolRegistry() - .getAllToolNames() - .includes(ToolNames.SKILL); + const skillRegistered = + this.runtimeContext + .getToolRegistry?.() + .getAllToolNames() + .includes(ToolNames.SKILL) ?? true; if ( this.runtimeContext.getToolMode?.() === ToolMode.CodeMode && !skillRegistered From 255e9a08f51da71d7559f88dfb92187f0b9f66e8 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Wed, 14 Oct 2026 22:43:26 +0000 Subject: [PATCH 27/49] fix(core): align fork deny-all message and skill reminder with the gate (#11854) Co-authored-by: Qwen-Coder --- docs/developers/tools/task.md | 4 +- .../core/src/core/coreToolScheduler.test.ts | 4 +- .../agent/agent.code-mode-review.test.ts | 40 +++++++++++++++++++ .../core/src/tools/agent/fork-subagent.ts | 4 +- packages/core/src/tools/skill-utils.ts | 2 +- 5 files changed, 47 insertions(+), 7 deletions(-) diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index a0e856f7ce0..0b4a59686d1 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -14,7 +14,7 @@ Use `agent` to launch a specialized subagent to handle complex, multi-step tasks - `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution. - `subagent_type` (string, optional): The type of specialized agent to use for this task. Defaults to `general-purpose` if omitted. - `fork_turns` (string, optional): Only valid with `subagent_type="fork"`. Omit it or use `all` for the full parent conversation, or use a positive integer string such as `"3"` for the most recent three real user turns. Tool responses and pure system reminders do not count as turns. -- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. Under either code mode a non-empty `fork_tools` list still admits `exec` (and `tool_search` under `code_mode_only`), which the mode grants ahead of the allowlist, and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy; the empty array closes the exec route too. +- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. A non-empty `fork_tools` list also re-admits `tool_search` and `tool_call` in any mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under either code mode the list still admits `exec` (and `tool_search` under `code_mode_only`), which the mode grants ahead of the allowlist, and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy; the empty array closes the exec route too. - `fork_profile` (string, optional): Only valid with `subagent_type="fork"`. Loads a frontmatter-only regular `.qwen/fork-profiles/.md` of at most 64 KiB from the active project root and applies its required `tools` array plus an optional `promptHint` of at most 200 characters. The file cannot resolve outside the project profile directory. `fork_profile` cannot be combined with `fork_tools` or a named teammate, and it is unavailable in safe mode or bare mode. - `run_in_background` (boolean, optional): Defaults to `true` for top-level regular agents. Set to `false` to wait for a regular agent's result inline. Headless forks always run in the background. Nested agents run in the foreground unless `run_in_background` is explicitly `true`, which is rejected because nested agents cannot receive background completion notifications. Unnamed caller-owned `working_dir` launches run in the foreground: an explicit `run_in_background: true` request is rejected, while a configured background default (`background: true` in a subagent definition) is rejected at the top level and downgraded to the foreground when nested. - `isolation` (string, optional): Set to `"worktree"` to run an explicitly named, non-fork agent in an isolated git worktree that Qwen Code creates and manages. @@ -149,7 +149,7 @@ Don't use the Agent tool for: - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. - **Subagent interaction**: Regular subagents do not receive `ask_user_question`. In `direct` mode forks keep the parent's declaration list for cache sharing — including that tool — and reject it before scheduling or approval; under hybrid `code_mode` a `fork_tools` allowlist narrows the declaration list, so it is dropped there. When missing user input blocks work, the subagent reports the blocker to its parent. -- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing; under a code mode a non-empty list still admits `exec` (and `tool_search` in `code_mode_only`) ahead of the list — an empty array rejects every call, `exec` included — and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. +- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing. A non-empty list also re-admits `tool_search` and `tool_call` in every mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under a code mode a non-empty list still admits `exec` (and `tool_search` in `code_mode_only`) ahead of the list — an empty array rejects every call, `exec` included — and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. - **Continuation**: Use `list_agents` and `send_message` for related follow-up work instead of launching a duplicate agent. Continuation depends on compatible retained state and may be unavailable. diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 91b3c8b7917..7e0836c0250 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -14467,9 +14467,7 @@ describe('CoreToolScheduler activation wiring', () => { expect(responseText()).toContain( 'Load a skill by name using the tool interface declared in this session', ); - expect(responseText()).not.toContain( - 'pass its name to the top-level Skill tool', - ); + expect(responseText()).not.toContain('via the Skill tool'); }); /** runWithSkillManager (App.tsx read) whose activation yields tsx-helper. */ diff --git a/packages/core/src/tools/agent/agent.code-mode-review.test.ts b/packages/core/src/tools/agent/agent.code-mode-review.test.ts index a4df7bae687..00db46e523e 100644 --- a/packages/core/src/tools/agent/agent.code-mode-review.test.ts +++ b/packages/core/src/tools/agent/agent.code-mode-review.test.ts @@ -91,6 +91,46 @@ describe('Code-mode fork restriction matches declared call surfaces', () => { }, ); + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'tells a fork whose bounds are both empty it may not execute any tools in %s', + (mode) => { + // fork_tools: [] resolves both bounds to empty and the gate denies + // exec there, so the message must not claim exec is callable. + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + const core = new AgentCore( + 'deny-all-fork', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: [ToolNames.EXEC, ToolNames.READ_FILE], + executionAllowedTools: [], + nestedExecutionAllowedTools: [], + }, + ); + expect( + ( + core as unknown as { isToolExecutionAllowed: (t: string) => boolean } + ).isToolExecutionAllowed.call(core, ToolNames.EXEC), + ).toBe(false); + + const message = buildChildMessage( + 'Inspect the implementation', + [], + undefined, + [], + mode, + ); + expect(message).toContain('You may not execute any tools'); + expect(message).not.toContain('You may call exec'); + }, + ); + it('declares, executes, and names exec for a hybrid fork that omits it', async () => { // The fork shape agent.ts builds for fork_tools: ["read_file"] in hybrid // code mode: the parent's declared names stay as the tool list while the diff --git a/packages/core/src/tools/agent/fork-subagent.ts b/packages/core/src/tools/agent/fork-subagent.ts index 0411e4530ec..c734225ebb4 100644 --- a/packages/core/src/tools/agent/fork-subagent.ts +++ b/packages/core/src/tools/agent/fork-subagent.ts @@ -429,7 +429,9 @@ export function buildChildMessage( ? `${ToolNames.EXEC} and ${ToolNames.TOOL_SEARCH}` : ToolNames.EXEC; const executionRestriction = - nestedExecutionAllowedTools !== undefined + nestedExecutionAllowedTools !== undefined && + (nestedExecutionAllowedTools.length > 0 || + (executionAllowedTools?.length ?? 0) > 0) ? `\n\nTOOL EXECUTION RESTRICTION: ${ toolMode === ToolMode.CodeModeOnly diff --git a/packages/core/src/tools/skill-utils.ts b/packages/core/src/tools/skill-utils.ts index 3cdf03e4bc7..84824beb333 100644 --- a/packages/core/src/tools/skill-utils.ts +++ b/packages/core/src/tools/skill-utils.ts @@ -278,7 +278,7 @@ function compareSkillEntries( * `/context` bills it with the tool result (#12235). */ export const SKILLS_ACTIVATED_OPENER = - 'The following skill(s) became available via the Skill tool based on the file you just accessed'; + 'The following skill(s) became available based on the file you just accessed'; /** * Renders normalized skill entries into the `` body. Pure: no From 5438ffda6bae787e48235463699a067db8f08838 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Mon, 19 Oct 2026 21:05:22 +0000 Subject: [PATCH 28/49] test(cli): scope AppContainer Mod session mock to its config (#11854) Co-authored-by: Qwen-Coder --- packages/cli/src/ui/AppContainer.test.tsx | 28 ++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/cli/src/ui/AppContainer.test.tsx b/packages/cli/src/ui/AppContainer.test.tsx index 8b9164f5e42..996f1b43865 100644 --- a/packages/cli/src/ui/AppContainer.test.tsx +++ b/packages/cli/src/ui/AppContainer.test.tsx @@ -6787,17 +6787,29 @@ describe('AppContainer State Management', () => { await ready; if (fails) throw new Error('tool.call is unsupported'); }); + const session = { + initialize, + subscribe: (listener: (text: string) => void) => { + emit = listener; + return () => {}; + }, + setPresentation: vi.fn(), + } as unknown as interactiveMods.InteractiveModSession; const owner = vi .spyOn(interactiveMods, 'getInteractiveModSession') - .mockReturnValue({ - initialize, - subscribe: (listener: (text: string) => void) => { - emit = listener; - return () => {}; - }, - setPresentation: vi.fn(), - } as unknown as interactiveMods.InteractiveModSession); + // Startup work left pending by an earlier unmounted render resumes + // with its own Config; scope the session so only this test's mount + // can call its initialize. + .mockImplementation((config) => + config === mockConfig ? session : undefined, + ); try { + // Only this test's Config may resolve to the session: startup work + // from an earlier unmounted render resumes against the live module + // mock and must not inflate this test's call count. + expect( + interactiveMods.getInteractiveModSession(makeFakeConfig()), + ).toBeUndefined(); render( Date: Wed, 28 Oct 2026 03:07:23 +0000 Subject: [PATCH 29/49] test(core): pin hybrid exec nested declaration signature (#11854) --- packages/core/src/code-mode/code-mode.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/code-mode/code-mode.test.ts b/packages/core/src/code-mode/code-mode.test.ts index aa5acc88ae0..d44c52718cd 100644 --- a/packages/core/src/code-mode/code-mode.test.ts +++ b/packages/core/src/code-mode/code-mode.test.ts @@ -266,7 +266,7 @@ describe('CodeModeOnly exposure', () => { )?.description; expect(readFileDescription).toContain('Reads a file from the filesystem.'); expect(readFileDescription).toContain( - 'read_file(args: { "path": string })', + 'declare const tools: { read_file(args: { "path": string }): Promise; };', ); expect( declarations.find((item) => item.name === 'agent')?.description, From 494d4a3ef118d818e22e4a69ee2dbfc068f91082 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Wed, 28 Oct 2026 19:11:12 +0000 Subject: [PATCH 30/49] fix(core): derive the fork nested exec bound without the subagent frame (#11854) Forks launch only from the top-level session, where no enclosing-agent tool-allowlist frame exists, so the nested exec bound was always undefined and the documented fork_tools restriction never reached exec. Derive a restricted fork's nested bound from the ambient code-mode names (falling back to the inherited surface), apply the nested admission filter on that path, and persist the direct and nested bounds together. Update the bilingual design doc to match the aligned persistence rule. --- docs/design/code-mode.md | 12 ++-- docs/design/code-mode.zh-CN.md | 9 ++- packages/core/src/tools/agent/agent.test.ts | 65 +++++++++++++++++++++ packages/core/src/tools/agent/agent.ts | 56 +++++++++++------- 4 files changed, 108 insertions(+), 34 deletions(-) diff --git a/docs/design/code-mode.md b/docs/design/code-mode.md index 846694efc5e..b764a5502ea 100644 --- a/docs/design/code-mode.md +++ b/docs/design/code-mode.md @@ -87,13 +87,11 @@ otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. Forks inherit the parent's direct-call bound separately from its nested binding set; nested access never widens -the child's direct-call grant. In a code mode, a fork launched under an -enclosing agent allowlist writes both bounds to its background metadata, and -resume restores them verbatim. A fork carrying only an explicit `fork_tools` -list or a fork profile persists its direct-call bound alone, so resume -re-derives its nested binding set from the parent's live surface and that set -can widen. A plain fork persists neither bound, so resume re-derives both and -the child's grant can widen. +the child's direct-call grant. In a code mode, a fork carrying an explicit +`fork_tools` list, a fork profile, or an enclosing agent allowlist writes both +bounds to its background metadata, and resume restores them verbatim. A plain +fork persists neither bound, so resume re-derives both from the parent's live +surface and the child's grant can widen. ## Constraints and risks diff --git a/docs/design/code-mode.zh-CN.md b/docs/design/code-mode.zh-CN.md index 601e4695c49..19bb81d1fa0 100644 --- a/docs/design/code-mode.zh-CN.md +++ b/docs/design/code-mode.zh-CN.md @@ -77,11 +77,10 @@ Hybrid 的 AgentCore 调用面从嵌套绑定中排除被 `tools.eager` 隐藏 会保留所有通过其他准入检查的普通 code-mode-callable binding。若执行 allowlist 包含任一 MCP 工具项,MCP 绑定还必须匹配其中的精确工具名或服务器模式。 Fork 分别继承父级的直接调用边界与嵌套绑定集合;嵌套访问权限不会扩大子级 -的直接调用授权。在 code mode 下,受外层智能体 allowlist 约束的 fork 会把两个 -边界写入后台元数据,resume 时按原样恢复。仅携带显式 `fork_tools` 列表或 -fork profile 的 fork 只持久化直接调用边界,resume 会依据父级的实时工具面 -重新推导嵌套绑定集合,因此该集合可能扩大。普通 fork 两个边界都不持久化, -resume 会重新推导二者,因此子级的授权可能扩大。 +的直接调用授权。在 code mode 下,携带显式 `fork_tools` 列表、fork profile +或受外层智能体 allowlist 约束的 fork 会把两个边界写入后台元数据,resume 时 +按原样恢复。普通 fork 两个边界都不持久化,resume 会依据父级的实时工具面 +重新推导二者,因此子级的授权可能扩大。 ## 约束与风险 diff --git a/packages/core/src/tools/agent/agent.test.ts b/packages/core/src/tools/agent/agent.test.ts index fd195fae9bd..1725dddbbc6 100644 --- a/packages/core/src/tools/agent/agent.test.ts +++ b/packages/core/src/tools/agent/agent.test.ts @@ -4198,6 +4198,71 @@ describe('AgentTool', () => { writeMetaSpy.mockRestore(); }, ); + + it.each([ + { + forkTools: [ToolNames.READ_FILE], + direct: [ToolNames.READ_FILE], + nested: [ToolNames.READ_FILE], + }, + { + forkTools: [ToolNames.EXEC], + direct: [ToolNames.EXEC], + nested: [ToolNames.READ_FILE, ToolNames.WRITE_FILE], + }, + ])( + 'derives the nested exec bound for a top-level hybrid fork (%j)', + async ({ forkTools, direct, nested }) => { + // Forks launch only from the top-level session, where no + // runWithAgentConfiguredToolAllowlist frame exists. The nested bound + // must still be concrete, or exec bypasses fork_tools. + preparePolicyRuntime('code_mode'); + vi.mocked(config.getToolRegistry().getAllToolNames).mockReturnValue([ + ToolNames.EXEC, + ToolNames.READ_FILE, + ToolNames.WRITE_FILE, + ]); + vi.mocked(config.getLlmClient).mockReturnValue({ + getHistory: vi.fn().mockReturnValue([]), + getChat: vi.fn().mockReturnValue({ + getGenerationConfig: vi.fn().mockReturnValue({ + systemInstruction: 'parent system', + tools: [ + { + functionDeclarations: [ + { name: ToolNames.EXEC }, + { name: ToolNames.READ_FILE }, + { name: ToolNames.WRITE_FILE }, + ], + }, + ], + }), + }), + } as unknown as ReturnType); + const writeMetaSpy = vi + .spyOn(transcript, 'writeAgentMeta') + .mockImplementation(() => {}); + const invocation = ( + agentTool as AgentToolWithProtectedMethods + ).createInvocation({ + description: 'bound a top-level fork', + prompt: 'read the implementation', + subagent_type: 'fork', + fork_tools: forkTools, + run_in_background: true, + }); + const result = await invocation.execute(); + expect(result.error).toBeUndefined(); + const tools = vi.mocked(AgentHeadless.create).mock.calls[0]?.[5]; + expect(tools?.executionAllowedTools).toEqual(direct); + expect(tools?.nestedExecutionAllowedTools).toEqual(nested); + expect(writeMetaSpy.mock.calls[0]?.[1]).toMatchObject({ + executionAllowedTools: direct, + nestedExecutionAllowedTools: nested, + }); + writeMetaSpy.mockRestore(); + }, + ); }); it('preserves fork_tools deny-all inside a configured parent allowlist', async () => { diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 6aeee7264e5..a5cad63473c 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -2073,13 +2073,16 @@ class AgentToolInvocation extends BaseToolInvocation { fallbackTools: readonly string[], forNestedBinding = false, ): string[] => { - if (parentConfiguredToolAllowlist === undefined) { + if (parentConfiguredToolAllowlist === undefined && !forNestedBinding) { return buildForkExecutionAllowlist( requestedTools, fallbackTools, parentToolNames, ).filter(keepOffParentBlocklist); } + const requestsExec = requestedTools?.includes(ToolNames.EXEC) === true; + const requestsMcp = + requestedTools?.some((name) => name.startsWith('mcp__')) === true; return fallbackTools.filter( (toolName) => toolName !== ToolNames.ASK_USER_QUESTION && @@ -2088,10 +2091,9 @@ class AgentToolInvocation extends BaseToolInvocation { (isRequestedByFork(toolName) || (forNestedBinding && isCodeModeEnabled(agentConfig.getToolMode?.()) && - requestedTools?.includes(ToolNames.EXEC) && + requestsExec && getToolExposure(toolName) === 'code-mode-callable' && - (!toolName.startsWith('mcp__') || - !requestedTools.some((name) => name.startsWith('mcp__')))) || + (!toolName.startsWith('mcp__') || !requestsMcp)) || (requestedTools !== undefined && requestedTools.length > 0 && (toolName === ToolNames.TOOL_SEARCH || @@ -2099,12 +2101,19 @@ class AgentToolInvocation extends BaseToolInvocation { parentToolNames.includes(toolName))), ); }; + // Forks launch only from the top-level session, where the enclosing-agent + // policy frame is never set. Derive a restricted fork's nested bound from + // the ambient code-mode names instead of that frame; an unrestricted fork + // carries no bound, so its prompt and execution surface stay unchanged. const nestedExecutionAllowedTools = - parentConfiguredToolAllowlist !== undefined && - isCodeModeEnabled(agentConfig.getToolMode?.()) + isCodeModeEnabled(agentConfig.getToolMode?.()) && + (requestedTools !== undefined || + parentConfiguredToolAllowlist !== undefined) ? buildParentBoundExecutionAllowlist( getCurrentCodeModeAllowedNames() ?? defaultExecutionToolNames, true, + ).filter( + (toolName) => getToolExposure(toolName) === 'code-mode-callable', ) : undefined; const requestedExecutionAllowedTools = @@ -3119,6 +3128,13 @@ class AgentToolInvocation extends BaseToolInvocation { }).`, ); } + // Only a restricted fork persists its launch-time bounds; a plain fork + // re-derives them from the live parent surface when it resumes. + const persistsForkPolicy = + isFork && + (this.params.fork_tools !== undefined || + this.forkProfile !== undefined || + getCurrentAgentConfiguredToolAllowlist() !== undefined); const effectiveSubagentType = requestedType ? requestedType : DEFAULT_BUILTIN_SUBAGENT_TYPE; @@ -4102,25 +4118,23 @@ class AgentToolInvocation extends BaseToolInvocation { ...(backgroundFix ? { resumeBlockedReason: BACKGROUND_FIX_CONTINUATION_BLOCKED } : {}), - ...(isFork && - (this.params.fork_tools !== undefined || - this.forkProfile !== undefined || - getCurrentAgentConfiguredToolAllowlist() !== undefined) && + ...(persistsForkPolicy && bgToolConfig?.executionAllowedTools !== undefined ? { executionAllowedTools: [...bgToolConfig.executionAllowedTools], } : {}), - // Unlike the allowlist above, the blocklist persists whenever the - // fork carries one — it also bounds plain forks whose allowlist is - // rebuilt from the live parent surface on resume. - ...(isFork && bgToolConfig?.nestedExecutionAllowedTools !== undefined + ...(persistsForkPolicy && + bgToolConfig?.nestedExecutionAllowedTools !== undefined ? { nestedExecutionAllowedTools: [ ...bgToolConfig.nestedExecutionAllowedTools, ], } : {}), + // Unlike the allowlists above, the blocklist persists whenever the + // fork carries one — it also bounds plain forks whose allowlist is + // rebuilt from the live parent surface on resume. ...(isFork && bgToolConfig?.disallowedTools?.length ? { disallowedTools: [...bgToolConfig.disallowedTools] } : {}), @@ -5047,25 +5061,23 @@ class AgentToolInvocation extends BaseToolInvocation { : undefined, lastUpdatedAt: new Date().toISOString(), resolvedApprovalMode, - ...(isFork && - (this.params.fork_tools !== undefined || - this.forkProfile !== undefined || - getCurrentAgentConfiguredToolAllowlist() !== undefined) && + ...(persistsForkPolicy && toolConfig?.executionAllowedTools !== undefined ? { executionAllowedTools: [...toolConfig.executionAllowedTools], } : {}), - // Unlike the allowlist above, the blocklist persists whenever the - // fork carries one — it also bounds plain forks whose allowlist is - // rebuilt from the live parent surface on resume. - ...(isFork && toolConfig?.nestedExecutionAllowedTools !== undefined + ...(persistsForkPolicy && + toolConfig?.nestedExecutionAllowedTools !== undefined ? { nestedExecutionAllowedTools: [ ...toolConfig.nestedExecutionAllowedTools, ], } : {}), + // Unlike the allowlists above, the blocklist persists whenever the + // fork carries one — it also bounds plain forks whose allowlist is + // rebuilt from the live parent surface on resume. ...(isFork && toolConfig?.disallowedTools?.length ? { disallowedTools: [...toolConfig.disallowedTools] } : {}), From 1547568d36fef790b19db52c67160f3625f692bc Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Thu, 29 Oct 2026 06:21:31 +0000 Subject: [PATCH 31/49] fix(core): keep deferred Skill reachable past the eager veto (#11854) The eager-hidden veto removed the SkillManager even when tool_search and tool_call could still reach the registered tool, so a prompt-budget allowlist silently deleted the capability. Scope the veto to the bridge-less case. Also treat an eager-hidden exec as no exec gateway, matching the hybrid declaration and binding pools, so the Skill listing predicate stays truthful. --- .../src/agents/background-agent-resume.ts | 4 + .../runtime/agent-core.skill-gate.test.ts | 60 ++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 4 +- .../runtime/subagent-plan-tool-policy.test.ts | 53 ++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 80 ++++++++++++++----- ...ubagent-manager.skill-eager-review.test.ts | 38 ++++++--- .../core/src/subagents/subagent-manager.ts | 2 + 7 files changed, 210 insertions(+), 31 deletions(-) diff --git a/packages/core/src/agents/background-agent-resume.ts b/packages/core/src/agents/background-agent-resume.ts index 7818639440c..78320bfe4a5 100644 --- a/packages/core/src/agents/background-agent-resume.ts +++ b/packages/core/src/agents/background-agent-resume.ts @@ -76,6 +76,7 @@ import { extractParentToolNames, } from './runtime/agent-core.js'; import { + hasAgentSkillBridge, hasAgentSkillExecBinding, isAgentSkillEagerHidden, toolConfigAllowsSkill, @@ -147,6 +148,7 @@ function subagentWillHaveSkillTool( skillEagerHidden = false, codeModeOnly = false, skillRegistered = true, + deferredBridgeAvailable = false, ): boolean { // Launch reads `config.tools?.length ? resolveToolNames(config.tools) : ['*']`, // and `resolveToolNames`' `for...of` walks a bare string per character, @@ -178,6 +180,7 @@ function subagentWillHaveSkillTool( skillEagerHidden, codeModeOnly, skillRegistered, + deferredBridgeAvailable, ); } @@ -1049,6 +1052,7 @@ export class BackgroundAgentResumeService { .getToolRegistry() .getAllToolNames() .includes(ToolNames.SKILL), + hasAgentSkillBridge(activeAgentConfig), ), }) )[0], diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index a2d70dc67be..02bbcba8b9a 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -15,6 +15,7 @@ import { MockTool } from '../../test-utils/mock-tool.js'; import { ToolMode } from '../../tools/code-mode.js'; import { CoreToolScheduler } from '../../core/coreToolScheduler.js'; import { ToolSearchTool } from '../../tools/tool-search.js'; +import { ToolCallTool } from '../../tools/tool-call.js'; import { hasAgentSkillExecBinding } from './subagent-plan-tool-policy.js'; import type { ToolConfig } from './agent-types.js'; @@ -445,6 +446,65 @@ describe('AgentCore skill-gate inputs', () => { }, ); + it('keeps a hybrid wildcard Skill reachable through the deferred-tool bridge', async () => { + // `tools.eager` demotes `skill` without disabling it; the deferred-tool + // bridge is the route that keeps the capability. Withholding the + // SkillManager here would unregister the factory and leave the bridge + // nothing to discover. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + registry.registerTool(new ToolSearchTool(config)); + registry.registerTool(new ToolCallTool(registry)); + const core = new AgentCore( + 'skill-eager-bridge', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools: ['*'] }, + ); + const announced = ( + core as unknown as { willHaveSkillTool: () => boolean } + ).willHaveSkillTool(); + expect(announced).toBe(true); + const declared = await declaredNames(core); + expect(declared.has(ToolNames.SKILL)).toBe(false); + expect(declared.has(ToolNames.TOOL_SEARCH)).toBe(true); + expect(declared.has(ToolNames.TOOL_CALL)).toBe(true); + }); + + it('stays silent when the eager-hidden Skill has no declared bridge', () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + registry.registerTool(new ToolSearchTool(config)); + registry.registerTool(new ToolCallTool(registry)); + const core = new AgentCore( + 'skill-eager-no-bridge', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools: [ToolNames.SKILL] }, + ); + expect( + ( + core as unknown as { willHaveSkillTool: () => boolean } + ).willHaveSkillTool(), + ).toBe(false); + }); + it('opens for a hybrid nested-only skill', async () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index a30dba31d00..94ec6bb8bed 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -150,10 +150,11 @@ import { getExcludedToolsForCurrentContext, getLeaderOnlyToolUnavailableMessage, getSubagentPlanToolUnavailableMessage, + hasAgentSkillBridge, + hasAgentSkillExecBinding, isLeaderOnlyToolUnavailableInSubagent, isPlanLifecycleToolUnavailableInSubagent, isToolExcludedForCurrentContext, - hasAgentSkillExecBinding, isAgentSkillEagerHidden, matchesAgentToolBlocklist, toolConfigAllowsSkill, @@ -683,6 +684,7 @@ export class AgentCore { isAgentSkillEagerHidden(this.runtimeContext), this.runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, skillRegistered, + hasAgentSkillBridge(this.runtimeContext), ); } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index 390f4b0e742..cf6b7043906 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -344,6 +344,34 @@ describe('subagent plan tool policy', () => { ); }); + it('reaches an eager-hidden Skill through a declared bridge', () => { + const toolConfig = { + tools: [ToolNames.SKILL, ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL], + }; + expect( + toolConfigAllowsSkill(toolConfig, false, true, false, true, true), + ).toBe(true); + expect( + toolConfigAllowsSkill({ tools: ['*'] }, false, true, false, true, true), + ).toBe(true); + }); + + it('vetoes an eager-hidden Skill the bridge cannot reach', () => { + expect( + toolConfigAllowsSkill({ tools: ['*'] }, false, true, false, true, false), + ).toBe(false); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.SKILL] }, + false, + true, + false, + true, + true, + ), + ).toBe(false); + }); + describe('hasAgentSkillExecBinding', () => { const contextWith = ( mode: ToolMode, @@ -362,6 +390,31 @@ describe('subagent plan tool policy', () => { return config; }; + it('reports no exec route when exec is eager-hidden in Hybrid', () => { + // `tools.eager` can demote `exec` too. prepareTools() then drops it from + // the Hybrid declarations and from the exec binding set, so the gateway + // is closed even though the registry still counts the factory. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerPermissionDeferredFactory( + ToolNames.EXEC, + async () => new ExecTool(config), + ); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + vi.spyOn(config, 'getVisibleTools').mockReturnValue( + new Set([ToolNames.SKILL]), + ); + expect(hasAgentSkillExecBinding(config)).toBe(false); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.EXEC] }, + hasAgentSkillExecBinding(config), + isAgentSkillEagerHidden(config), + ), + ).toBe(false); + }); + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( 'reports no exec route in %s when exec was never registered', (mode) => { diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index ec3bd26fc1b..dd9bb504b03 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -89,8 +89,9 @@ type AgentSkillContext = Pick< 'getToolMode' | 'getToolRegistry' | 'getVisibleTools' >; -export function isAgentSkillEagerHidden( +function isAgentToolEagerHidden( context: AgentSkillContext, + toolName: string, registryWillBeRebuilt = false, ): boolean { const registry = context.getToolRegistry?.(); @@ -98,10 +99,37 @@ export function isAgentSkillEagerHidden( // discovery metadata, but deliberately leave transient reveals behind. return ( context.getToolMode?.() === ToolMode.CodeMode && - registry?.isPermissionDeferred?.(ToolNames.SKILL) === true && - !context.getVisibleTools?.().has(ToolNames.SKILL) && + registry?.isPermissionDeferred?.(toolName) === true && + !context.getVisibleTools?.().has(toolName) && (registryWillBeRebuilt || - registry?.isDeferredToolRevealed?.(ToolNames.SKILL) !== true) + registry?.isDeferredToolRevealed?.(toolName) !== true) + ); +} + +export function isAgentSkillEagerHidden( + context: AgentSkillContext, + registryWillBeRebuilt = false, +): boolean { + return isAgentToolEagerHidden( + context, + ToolNames.SKILL, + registryWillBeRebuilt, + ); +} + +/** + * Whether the deferred-tool bridge is registered: `tool_search` reviews a + * deferred schema and `tool_call` invokes it. A hybrid agent whose `skill` is + * demoted by `tools.eager` keeps the capability this bridge carries, so the + * eager-hidden veto must not fire while both halves are present. + * + * Does not reuse `isDeferredToolBridgeAvailable` (tools/tool-search.ts): that + * module imports this one, so the dependency would be circular. + */ +export function hasAgentSkillBridge(context: AgentSkillContext): boolean { + const names = context.getToolRegistry?.().getAllToolNames() ?? []; + return ( + names.includes(ToolNames.TOOL_SEARCH) && names.includes(ToolNames.TOOL_CALL) ); } @@ -123,6 +151,9 @@ export function hasAgentSkillExecBinding( return ( mode === ToolMode.CodeModeOnly || (mode === ToolMode.CodeMode && + // `tools.eager` can demote exec too; prepareTools() then drops it from + // the Hybrid declarations and from the exec binding set. + !isAgentToolEagerHidden(context, ToolNames.EXEC, registryWillBeRebuilt) && !isAgentSkillEagerHidden(context, registryWillBeRebuilt)) ); } @@ -142,11 +173,14 @@ export function hasAgentSkillExecBinding( * be loaded — the disagreement #12424 reports. * * Callers supply whether exec bindings are reachable in the current mode and - * registry, and whether the Skill factory is registered there at all. A - * finite list naming exec can therefore reach Skill without naming it - * directly. CodeModeOnly retains eager-deferred nested targets; - * The eager-hidden input vetoes every route in Hybrid, including wildcards - * and explicit Skill entries. Other permission bounds stay in prepareTools(). + * registry, whether the Skill factory is registered there at all, and whether + * the deferred-tool bridge is registered. A finite list naming exec can + * therefore reach Skill without naming it directly. CodeModeOnly retains + * eager-deferred nested targets. In Hybrid, an eager-hidden Skill is vetoed + * only when the bridge cannot reach it: `prepareTools()` keeps the schema out + * of the direct declarations, but `tool_search` + `tool_call` still discover + * and invoke the registered tool. Other permission bounds stay in + * prepareTools(). * Registry deny/exclude rules remain the bundled-reference resolver's concern; * this predicate supplies the per-agent policy that resolver cannot see. * @@ -179,8 +213,26 @@ export function toolConfigAllowsSkill( skillEagerHidden = false, codeModeOnly = false, skillRegistered = true, + deferredBridgeAvailable = false, ): boolean { - if (skillEagerHidden || EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { + if (EXCLUDED_TOOLS_FOR_SUBAGENTS.has(ToolNames.SKILL)) { + return false; + } + const names = + toolConfig?.tools.filter( + (tool): tool is string => typeof tool === 'string', + ) ?? []; + // Only a wildcard inherits the registry, exactly as `prepareTools()` does. + // Neither an explicit empty list (the documented deny-all contract) nor a + // list holding only inline declarations inherits: both take the explicit + // branch there, which declares no registry tool. + const inheritsRegistry = !toolConfig || names.includes('*'); + const bridgeReachesSkill = + deferredBridgeAvailable && + (inheritsRegistry || + (names.includes(ToolNames.TOOL_SEARCH) && + names.includes(ToolNames.TOOL_CALL))); + if (skillEagerHidden && !bridgeReachesSkill) { return false; } // exec binds only registered tools, so a registry without the Skill @@ -197,14 +249,6 @@ export function toolConfigAllowsSkill( if (matchesAgentToolBlocklist(toolConfig.disallowedTools, ToolNames.SKILL)) { return false; } - const names = toolConfig.tools.filter( - (tool): tool is string => typeof tool === 'string', - ); - // Only a wildcard inherits the registry, exactly as `prepareTools()` does. - // Neither an explicit empty list (the documented deny-all contract) nor a - // list holding only inline declarations inherits: both take the explicit - // branch there, which declares no registry tool. - const inheritsRegistry = names.includes('*'); // The exec wrapper does not need an execution-list entry in code modes. // An explicit nested list is authoritative; otherwise either Skill itself // or the exec carve-out grants the nested binding, as in AgentCore. diff --git a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts index 9bb756095f1..7ba4ad4bc28 100644 --- a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts +++ b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts @@ -14,6 +14,7 @@ import { AgentHeadless } from '../agents/runtime/agent-headless.js'; import { AgentCore } from '../agents/runtime/agent-core.js'; import { resolveAgentDelegationSurface } from '../skills/agent-delegation-skill.js'; import { ToolMode } from '../tools/code-mode.js'; +import { ToolNames } from '../tools/tool-names.js'; describe('nested agents retain their actual Skill availability', () => { it.each([ @@ -64,7 +65,10 @@ describe('nested agents retain their actual Skill availability', () => { ); const handles: Array<{ dispose(): Promise }> = []; let parent = config; - const expected = mode === ToolMode.CodeModeOnly || visible; + // Direct declarations and the exec gateway. A hybrid agent whose Skill + // is eager-hidden loses both, but keeps the capability while the + // deferred-tool bridge is registered (R22-1). + const directlyInvokable = mode === ToolMode.CodeModeOnly || visible; try { for (let depth = 1; depth <= 3; depth++) { handles.push( @@ -97,26 +101,36 @@ describe('nested agents retain their actual Skill availability', () => { const declared = new Set( (await core.prepareTools()).map((declaration) => declaration.name), ); + const toolNames = context.getToolRegistry().getAllToolNames(); + const bridgeReachesSkill = + (tools === undefined || tools.tools.some((tool) => tool === '*')) && + toolNames.includes(ToolNames.TOOL_SEARCH) && + toolNames.includes(ToolNames.TOOL_CALL); + const reachable = directlyInvokable || bridgeReachesSkill; expect .soft(!!context.getSkillManager(), `depth ${depth}`) - .toBe(expected); + .toBe(reachable); expect .soft(announced, `announcement at depth ${depth}`) - .toBe(expected); + .toBe(reachable); expect .soft( observed.canInvokeSkill(declared), `invocation at depth ${depth}`, ) - .toBe(expected); - if (!expected) { - expect - .soft( - resolveAgentDelegationSurface(context), - `pointer at depth ${depth}`, - ) - .toBe('inline'); - } + .toBe(directlyInvokable); + expect + .soft( + resolveAgentDelegationSurface(context), + `pointer at depth ${depth}`, + ) + .toBe( + reachable + ? bridgeReachesSkill && !directlyInvokable + ? 'pointer-via-tool-search' + : 'pointer' + : 'inline', + ); parent = context; } } finally { diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 4d0ec02d110..a89bca05615 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -90,6 +90,7 @@ import { } from '../tools/agent/agent.js'; import { ToolMode } from '../tools/code-mode.js'; import { + hasAgentSkillBridge, hasAgentSkillExecBinding, isAgentSkillEagerHidden, toolConfigAllowsSkill, @@ -1223,6 +1224,7 @@ export class SubagentManager { skillEagerHidden, runtimeContext.getToolMode?.() === ToolMode.CodeModeOnly, skillRegistered, + hasAgentSkillBridge(runtimeContext), ); const { context: subagentContext, cleanup } = await this.buildSubagentContextOverride( From 1ff2c86d70e9dec1068af6677bc9317d162481a1 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Thu, 29 Oct 2026 16:48:49 +0000 Subject: [PATCH 32/49] fix(cli): keep operator code mode over a lower-scope tool mode (#11854) --- packages/cli/src/config/config.test.ts | 26 +++++++- .../cli/src/config/settings-tool-mode.test.ts | 61 +++++++++++++++++-- packages/cli/src/config/settings.ts | 21 +++++++ 3 files changed, 102 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 4674cc5e7d4..2e9d4e14be4 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -33,7 +33,7 @@ import { type CliArgs, resetOutputStyleWarningsForTesting, } from './config.js'; -import type { Settings } from './settings.js'; +import { LoadedSettings, type Settings } from './settings.js'; import * as ServerConfig from '@qwen-code/qwen-code-core'; import { isWorkspaceTrusted } from './trustedFolders.js'; import { resetMcpApprovalsForTesting } from './mcpApprovals.js'; @@ -4688,6 +4688,30 @@ describe('mergeExcludeTools', () => { ); }); + it('should keep an operator legacy mode over a lower-scope tools.mode', async () => { + const file = (settings: Settings) => ({ + settings, + originalSettings: settings, + path: 'fixture', + }); + const loaded = new LoadedSettings( + file({ tools: { codeModeOnly: true } } as unknown as Settings), + file({}), + file({ tools: { mode: ToolMode.Direct } }), + file({}), + true, + new Set(), + ); + process.argv = ['node', 'script.js']; + const argv = await parseArguments(); + const config = await loadCliConfig(loaded.merged, argv, undefined, []); + + expect(config.getToolMode()).toBe(ToolMode.CodeModeOnly); + expect(config.getWarnings()).toContain( + 'tools.codeModeOnly is deprecated; use tools.mode = "code_mode_only".', + ); + }); + it.each([ ['--safe-mode', ToolMode.CodeMode], ['--safe-mode', ToolMode.CodeModeOnly], diff --git a/packages/cli/src/config/settings-tool-mode.test.ts b/packages/cli/src/config/settings-tool-mode.test.ts index f63e06962c8..6222278c25c 100644 --- a/packages/cli/src/config/settings-tool-mode.test.ts +++ b/packages/cli/src/config/settings-tool-mode.test.ts @@ -9,11 +9,13 @@ import { getEffectiveValue, saveModifiedSettings, } from './settingsUtils.js'; -import { - SettingScope, - type LoadedSettings, - type Settings, -} from './settings.js'; +import { LoadedSettings, SettingScope, type Settings } from './settings.js'; + +const file = (settings: Settings) => ({ + settings, + originalSettings: settings, + path: 'fixture', +}); describe('legacy tool mode settings', () => { const legacy = { tools: { codeModeOnly: true } } as unknown as Settings; @@ -55,4 +57,53 @@ describe('legacy tool mode settings', () => { ); expect(getEffectiveValue('tools.mode', settings, settings)).toBe('direct'); }); + + it('resolves an operator legacy mode over a lower-precedence tools.mode', () => { + const loaded = new LoadedSettings( + file({ tools: { codeModeOnly: true } } as unknown as Settings), + file({}), + file({ tools: { mode: 'direct' } }), + file({}), + true, + new Set(), + ); + + expect( + (loaded.merged.tools as { codeModeOnly?: unknown })?.codeModeOnly, + ).toBe(true); + expect(loaded.merged.tools?.mode).toBeUndefined(); + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe( + 'code_mode_only', + ); + }); + + it('keeps an explicit mode over the legacy key in the same scope', () => { + const loaded = new LoadedSettings( + file({}), + file({}), + file({ + tools: { codeModeOnly: true, mode: 'direct' }, + } as unknown as Settings), + file({}), + true, + new Set(), + ); + + expect(loaded.merged.tools?.mode).toBe('direct'); + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe('direct'); + }); + + it('keeps a higher-precedence tools.mode over a lower legacy mode', () => { + const loaded = new LoadedSettings( + file({ tools: { mode: 'direct' } }), + file({ tools: { codeModeOnly: true } } as unknown as Settings), + file({}), + file({}), + true, + new Set(), + ); + + expect(loaded.merged.tools?.mode).toBe('direct'); + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe('direct'); + }); }); diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index 6df220ee93c..efcb1abfc30 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -752,6 +752,27 @@ function mergeSettings( } else if (merged.tools && typeof merged.tools === 'object') { delete merged.tools.executionSandbox; } + // `tools.mode` and the legacy `tools.codeModeOnly` name one setting but + // merge as independent keys, so an operator's enforced legacy value would + // otherwise sit beside a lower-scope `mode` that every key-first reader + // prefers. Keep the highest-precedence scope's choice. + const toolModeChoice = [systemDefaults, user, safeWorkspace, system].reduce< + 'mode' | 'legacy' | undefined + >((choice, scope) => { + const tools = scope.tools as + | { mode?: unknown; codeModeOnly?: unknown } + | undefined; + if (tools?.mode !== undefined) return 'mode'; + if (tools?.codeModeOnly === true) return 'legacy'; + return choice; + }, undefined); + if ( + toolModeChoice === 'legacy' && + merged.tools && + typeof merged.tools === 'object' + ) { + delete merged.tools.mode; + } return merged; } From 382c14190cbbce7808fe4331ee008077a93e2ac8 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Thu, 29 Oct 2026 22:40:53 +0000 Subject: [PATCH 33/49] docs(subagents): scope fork prompt-cache parity to direct mode (#11854) --- docs/design/fork-tool-execution-allowlist.md | 24 +++++++++++++------- docs/users/features/sub-agents.md | 18 +++++++-------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/docs/design/fork-tool-execution-allowlist.md b/docs/design/fork-tool-execution-allowlist.md index 2d30e2e2042..afaefb37941 100644 --- a/docs/design/fork-tool-execution-allowlist.md +++ b/docs/design/fork-tool-execution-allowlist.md @@ -4,7 +4,9 @@ Add an optional `fork_tools` parameter to the Agent tool's existing `subagent_type: "fork"` runtime. The parameter narrows which tools a fork can -execute without changing the tool declarations sent to the model. +execute without changing the tool declarations sent to the model under +`direct` mode; under hybrid `tools.mode: "code_mode"` the same allowlist +filters those declarations. This is the first phase of #7625. Named profile files, shell argument patterns, overlay filesystems, and `/btw` integration are out of scope. A launch-prompt @@ -16,8 +18,9 @@ hint tells the fork which visible tools the allowlist permits. except for interaction tools that forks must never execute. - Treat an empty list as deny-all rather than as the existing `tools: []` wildcard behavior. -- Keep the fork's current model-visible declarations unchanged so adding an - execution restriction does not alter its prompt-cache prefix. +- Keep the fork's current model-visible declarations unchanged in `direct` + mode so adding an execution restriction does not alter its prompt-cache + prefix. - Reject disallowed calls before tool construction, tool hooks, permission classification, scheduling, or approval. - Preserve the restriction when a background fork is revived from its @@ -67,14 +70,19 @@ tool, or add declarations. Every fork receives an in-memory execution allowlist, even when `fork_tools` is omitted. The runtime-owned floor removes `ask_user_question` after applying -the caller-supplied list, so a caller cannot re-enable it. The tool remains in -the parent-derived declaration list for prompt-cache sharing, but a call is -rejected before scheduling or approval. A blocked fork reports the missing -input to its parent instead of trying to interact with the user directly. +the caller-supplied list, so a caller cannot re-enable it. In `direct` mode the +tool remains in the parent-derived declaration list for prompt-cache sharing, +but a call is rejected before scheduling or approval. Under hybrid +`tools.mode: "code_mode"`, `AgentCore.prepareTools()` also filters the +declaration list by the execution allowlist, so the fork's declarations, and +therefore its cached prefix, can differ from the parent's. A blocked fork +reports the missing input to its parent instead of trying to interact with the +user directly. The fork receives a restriction notice in the task prompt after the inherited cacheable prefix. This avoids trial-and-error calls without changing the -parent-derived system instruction, history prefix, or tool declarations. +parent-derived system instruction or history prefix; in `direct` mode it also +leaves the tool declarations unchanged. ## Background Revival diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index ed51275b3ab..dca4087708c 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -100,13 +100,13 @@ Like `fork_tools`, a fork profile is a caller-selected restriction rather than a ### How Fork Differs from Named Subagents -| | Named Subagent | Fork Subagent | -| ------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Context | Starts fresh with no parent conversation history | Inherits all parent history by default; `fork_turns` can select a bounded recent window | -| System prompt | Uses its own configured prompt | Uses parent's exact system prompt (for cache sharing) | -| Tools | Configured declaration set without interactive question tools | Keeps the parent-derived declaration set for caching; execution always rejects `ask_user_question`, and `fork_tools` or `fork_profile` can independently narrow it without changing that declaration | -| Execution | Background by default; supports an explicit foreground opt-out | Always detached; parent continues immediately | -| Use case | Specialized tasks (testing, docs) | Parallel tasks that need the current context | +| | Named Subagent | Fork Subagent | +| ------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Context | Starts fresh with no parent conversation history | Inherits all parent history by default; `fork_turns` can select a bounded recent window | +| System prompt | Uses its own configured prompt | Uses parent's exact system prompt (for cache sharing) | +| Tools | Configured declaration set without interactive question tools | In `direct` mode, keeps the parent-derived declaration set for caching; execution always rejects `ask_user_question`, and `fork_tools` or `fork_profile` narrow execution without changing that declaration. In hybrid `tools.mode: "code_mode"` the effective execution allowlist also filters the top-level declarations | +| Execution | Background by default; supports an explicit foreground opt-out | Always detached; parent continues immediately | +| Use case | Specialized tasks (testing, docs) | Parallel tasks that need the current context | ### When Fork is Used @@ -118,7 +118,7 @@ The AI automatically uses fork when it needs to: ### Prompt Cache Sharing -All forks share the parent's exact API request prefix (system prompt, tools, conversation history), enabling DashScope prompt cache hits. When 3 forks run in parallel, the shared prefix is cached once and reused — saving 80%+ token costs compared to independent subagents. +In `direct` mode, all forks share the parent's exact API request prefix (system prompt, tools, conversation history), enabling DashScope prompt cache hits. When 3 forks run in parallel, the shared prefix is cached once and reused — saving 80%+ token costs compared to independent subagents. Under hybrid `tools.mode: "code_mode"`, `fork_tools`, `fork_profile`, and the inherited execution allowlist filter the fork's tool declarations, so the tools portion of the prefix can differ from the parent's. ### Recursive Delegation Prevention @@ -133,7 +133,7 @@ Fork children cannot spawn any further sub-agent. This is enforced at runtime - **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.) - **Context Isolation**: Keep specialized work separate from your main conversation - **Context Inheritance**: Fork subagents inherit the full conversation by default and can select a bounded number of recent parent turns -- **Prompt Cache Sharing**: Fork subagents share the parent's cache prefix, reducing token costs +- **Prompt Cache Sharing**: In `direct` mode, fork subagents share the parent's cache prefix, reducing token costs - **Reusability**: Save and reuse agent configurations across projects and sessions - **Controlled Access**: Limit which tools each agent can use for security and focus - **Progress Visibility**: Monitor agent execution with real-time progress updates From ceeec7dffc7548a865592979caaa6b1ebde5459a Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Fri, 30 Oct 2026 00:32:24 +0000 Subject: [PATCH 34/49] test(web-shell): supply transcript coverage in managed recovery mock (#11854) Live message paging requires coveredSequence on a WebShellTranscript. The recovery fixture returned only lastSequence, so getTranscript threw and the handoff lost its history, failing the @smoke case. Mirror the sequence the fixture already uses. Co-authored-by: Qwen-Coder --- packages/web-shell/client/e2e/managed-recovery.spec.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/web-shell/client/e2e/managed-recovery.spec.ts b/packages/web-shell/client/e2e/managed-recovery.spec.ts index 2c248aa8053..5f6c97c5685 100644 --- a/packages/web-shell/client/e2e/managed-recovery.spec.ts +++ b/packages/web-shell/client/e2e/managed-recovery.spec.ts @@ -145,7 +145,13 @@ async function installRecovery(page: Page, running = false) { }); if (path.endsWith('/transcript/query')) return route.fulfill({ - json: { items: [], events, lastSequence: 6, hasMore: false }, + json: { + items: [], + events, + coveredSequence: 6, + lastSequence: 6, + hasMore: false, + }, }); if (path.endsWith('/events/stream')) return route.fulfill({ contentType: 'text/event-stream', body: '' }); From d6527fff4982a88e9a8956376ddd184fbbb45ba7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=BF=E9=BE=99?= Date: Wed, 4 Nov 2026 11:17:44 +0000 Subject: [PATCH 35/49] test(cli): pin the declared MCP schema's billing row The base merge resolved the shared contextCommand case to main's rework, whose exposed scenario only asserted the MCP detail row and not the breakdown row the pre-round test pinned. Restore that assertion against main's shape so the declared MCP schema is again charged to the mcp row, clearing the test-weakening rejection. Co-authored-by: Qwen-Coder --- packages/cli/src/ui/commands/contextCommand.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/cli/src/ui/commands/contextCommand.test.ts b/packages/cli/src/ui/commands/contextCommand.test.ts index 30887df8df8..fb35fcbeb25 100644 --- a/packages/cli/src/ui/commands/contextCommand.test.ts +++ b/packages/cli/src/ui/commands/contextCommand.test.ts @@ -1601,6 +1601,10 @@ describe('collectContextData (contextCommand)', () => { }), true, ); + // The mcp schema is declared, so the guard bills it to the mcp row. + expect(exposed.breakdown.mcpTools).toBe( + estimateContextTextTokens(JSON.stringify(mcpToolDouble.schema)), + ); expect(exposed.mcpTools).toEqual([ { name: 'server__big_tool', From a6eabc78e55b623fca987c4fead7920aea49b194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=BF=E9=BE=99?= Date: Wed, 4 Nov 2026 14:28:24 +0000 Subject: [PATCH 36/49] fix: honour legacy direct pin and blocked skill bridge (#11854) Co-authored-by: Qwen-Coder --- .../cli/src/config/settings-tool-mode.test.ts | 17 +++++++++++ packages/cli/src/config/settings.ts | 11 +++++--- .../runtime/subagent-plan-tool-policy.test.ts | 28 +++++++++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 7 +++++ 4 files changed, 59 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/config/settings-tool-mode.test.ts b/packages/cli/src/config/settings-tool-mode.test.ts index 6222278c25c..242c846a74b 100644 --- a/packages/cli/src/config/settings-tool-mode.test.ts +++ b/packages/cli/src/config/settings-tool-mode.test.ts @@ -77,6 +77,23 @@ describe('legacy tool mode settings', () => { ); }); + it('honours an explicit higher-precedence legacy direct pin', () => { + const loaded = new LoadedSettings( + file({ tools: { codeModeOnly: false } } as unknown as Settings), + file({}), + file({ tools: { mode: 'code_mode_only' } }), + file({}), + true, + new Set(), + ); + + expect( + (loaded.merged.tools as { codeModeOnly?: unknown })?.codeModeOnly, + ).toBe(false); + expect(loaded.merged.tools?.mode).toBeUndefined(); + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe('direct'); + }); + it('keeps an explicit mode over the legacy key in the same scope', () => { const loaded = new LoadedSettings( file({}), diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index f6c75ae290c..77c54b51577 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -758,21 +758,24 @@ function mergeSettings( // otherwise sit beside a lower-scope `mode` that every key-first reader // prefers. Keep the highest-precedence scope's choice. const toolModeChoice = [systemDefaults, user, safeWorkspace, system].reduce< - 'mode' | 'legacy' | undefined + 'mode' | 'legacy-true' | 'legacy-false' | undefined >((choice, scope) => { const tools = scope.tools as | { mode?: unknown; codeModeOnly?: unknown } | undefined; if (tools?.mode !== undefined) return 'mode'; - if (tools?.codeModeOnly === true) return 'legacy'; + if (tools?.codeModeOnly === true) return 'legacy-true'; + if (tools?.codeModeOnly === false) return 'legacy-false'; return choice; }, undefined); if ( - toolModeChoice === 'legacy' && + (toolModeChoice === 'legacy-true' || toolModeChoice === 'legacy-false') && merged.tools && typeof merged.tools === 'object' ) { - delete merged.tools.mode; + const tools = merged.tools as { mode?: unknown; codeModeOnly?: unknown }; + delete tools.mode; + tools.codeModeOnly = toolModeChoice === 'legacy-true'; } const operatorCatalogRefresh = selectOperatorCatalogRefresh( systemDefaults, diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index cf6b7043906..8c0d216da2b 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -372,6 +372,34 @@ describe('subagent plan tool policy', () => { ).toBe(false); }); + it('vetoes an eager-hidden Skill whose declared bridge is blocklisted', () => { + // prepareTools() drops whichever bridge half the blocklist names, so the + // wildcard's inherited bridge no longer reaches the withheld schema. + for (const blocked of [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL]) { + expect( + toolConfigAllowsSkill( + { tools: ['*'], disallowedTools: [blocked] }, + false, + true, + false, + true, + true, + ), + ).toBe(false); + } + // An unrelated blocklist entry leaves the bridge intact. + expect( + toolConfigAllowsSkill( + { tools: ['*'], disallowedTools: [ToolNames.SHELL] }, + false, + true, + false, + true, + true, + ), + ).toBe(true); + }); + describe('hasAgentSkillExecBinding', () => { const contextWith = ( mode: ToolMode, diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index dd9bb504b03..4ea219e7863 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -227,8 +227,15 @@ export function toolConfigAllowsSkill( // list holding only inline declarations inherits: both take the explicit // branch there, which declares no registry tool. const inheritsRegistry = !toolConfig || names.includes('*'); + const bridgeBlocked = + matchesAgentToolBlocklist( + toolConfig?.disallowedTools, + ToolNames.TOOL_SEARCH, + ) || + matchesAgentToolBlocklist(toolConfig?.disallowedTools, ToolNames.TOOL_CALL); const bridgeReachesSkill = deferredBridgeAvailable && + !bridgeBlocked && (inheritsRegistry || (names.includes(ToolNames.TOOL_SEARCH) && names.includes(ToolNames.TOOL_CALL))); From d47bbf957f30a8aa5756e68de57087f6ab81c30f Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Wed, 4 Nov 2026 23:12:30 +0000 Subject: [PATCH 37/49] fix(core): gate the deferred bridge on the execution allowlist (#11854) An eager-hidden Skill was credited with a tool_search + tool_call route even when the agent's execution allowlist excluded either bridge half. Nested agents in that shape were shown an block they could not load and received bundled references as pointers instead of inline. Also state the legacy tools.codeModeOnly merge rule the code implements, and qualify the SDK hybrid exec precondition with tools.eager demotion. Co-authored-by: Qwen-Coder --- docs/developers/sdk-typescript.md | 42 +++++++++---------- docs/users/configuration/settings.md | 2 +- .../runtime/subagent-plan-tool-policy.test.ts | 35 ++++++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 8 ++++ packages/sdk-typescript/README.md | 42 +++++++++---------- 5 files changed, 86 insertions(+), 43 deletions(-) diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index d9e736b3d90..b7aafc14c52 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered and not demoted by `tools.eager` (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 81ca102f4f5..ffeffcffbb4 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -430,7 +430,7 @@ The bridge-availability and missing-bridge warning rules below describe direct a | `tools.listDirectory.enabled` | boolean | Enable the built-in `list_directory` tool. Disabled by default because `glob` covers directory listing in most cases; the tool is also re-enabled automatically when explicitly listed in the `coreTools` allowlist (`--core-tools` / `tools.core`). | `false` | Requires restart: Yes | | `tools.todoWrite.enabled` | boolean | Enable the built-in `todo_write` tool and its system-prompt guidance. Disabled by default. | `false` | Requires restart: Yes | | `tools.mode` | string | Selects the tool exposure mode: `direct` uses ordinary tool calls, `code_mode` also exposes the isolated `exec` JavaScript tool, and `code_mode_only` exposes ordinary tools only through `exec` while keeping direct control tools available. Ignored in safe and bare modes. Container execution warns and uses direct tools for `code_mode`, and rejects `code_mode_only`. SSH workspaces warn and use Direct for either code mode. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools hidden by `tools.eager` from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. | `direct` | Experimental. Requires restart. | -| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup only while `tools.mode` is unset. Not shown in the settings dialog. | `undefined` | Requires restart. | +| `tools.codeModeOnly` | boolean | **Deprecated.** Use `tools.mode: "code_mode_only"` instead. Removed from the settings schema; still honored at startup. The highest-precedence scope that sets either key decides: a scope's `codeModeOnly` overrides a lower-precedence `tools.mode`, and setting both in one scope keeps `tools.mode`. Not shown in the settings dialog. | `undefined` | Requires restart. | > [!note] > diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index 8c0d216da2b..b7c1446dd04 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -400,6 +400,41 @@ describe('subagent plan tool policy', () => { ).toBe(true); }); + it('vetoes an eager-hidden Skill an execution allowlist hides the bridge from', () => { + // Hybrid declarations are narrowed by the execution allowlist, so a + // wildcard alone does not keep a bridge half the allowlist excludes. + for (const allowed of [ + [ToolNames.READ_FILE], + [ToolNames.TOOL_SEARCH], + [ToolNames.TOOL_CALL], + ]) { + expect( + toolConfigAllowsSkill( + { tools: ['*'], executionAllowedTools: allowed }, + false, + true, + false, + true, + true, + ), + ).toBe(false); + } + // Both halves declared keep the route open. + expect( + toolConfigAllowsSkill( + { + tools: ['*'], + executionAllowedTools: [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL], + }, + false, + true, + false, + true, + true, + ), + ).toBe(true); + }); + describe('hasAgentSkillExecBinding', () => { const contextWith = ( mode: ToolMode, diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 4ea219e7863..6c3e76f5e37 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -233,9 +233,17 @@ export function toolConfigAllowsSkill( ToolNames.TOOL_SEARCH, ) || matchesAgentToolBlocklist(toolConfig?.disallowedTools, ToolNames.TOOL_CALL); + // The execution allowlist also bounds the bridge: under hybrid code_mode it + // narrows the declarations, and in every mode a call outside it is rejected + // (an empty list denies every direct call). + const bridgeExecutionAllowed = + toolConfig?.executionAllowedTools === undefined || + (toolConfig.executionAllowedTools.includes(ToolNames.TOOL_SEARCH) && + toolConfig.executionAllowedTools.includes(ToolNames.TOOL_CALL)); const bridgeReachesSkill = deferredBridgeAvailable && !bridgeBlocked && + bridgeExecutionAllowed && (inheritsRegistry || (names.includes(ToolNames.TOOL_SEARCH) && names.includes(ToolNames.TOOL_CALL))); diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index d9b01e7cf90..71feb1160c3 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered and not demoted by `tools.eager` (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. From aec647b98695b98c1196e9044a963443ad246516 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Wed, 4 Nov 2026 23:20:40 +0000 Subject: [PATCH 38/49] docs(core): scope the bridge allowlist comment to Direct and Hybrid (#11854) Co-authored-by: Qwen-Coder --- packages/core/src/agents/runtime/subagent-plan-tool-policy.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 6c3e76f5e37..1863e4be184 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -234,8 +234,8 @@ export function toolConfigAllowsSkill( ) || matchesAgentToolBlocklist(toolConfig?.disallowedTools, ToolNames.TOOL_CALL); // The execution allowlist also bounds the bridge: under hybrid code_mode it - // narrows the declarations, and in every mode a call outside it is rejected - // (an empty list denies every direct call). + // narrows the declarations, and a half outside it cannot be called in Direct + // or Hybrid (an empty list denies every direct call). const bridgeExecutionAllowed = toolConfig?.executionAllowedTools === undefined || (toolConfig.executionAllowedTools.includes(ToolNames.TOOL_SEARCH) && From e4b181383d8cf24be4d7efaf19d41db707e79903 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=BF=E9=BE=99?= Date: Thu, 5 Nov 2026 13:00:45 +0800 Subject: [PATCH 39/49] fix(core): preserve always-loaded exec skill capability --- docs/developers/sdk-typescript.md | 42 ++++----- .../codemode-eager-exec-regression.test.ts | 88 +++++++++++++++++++ .../runtime/subagent-plan-tool-policy.test.ts | 9 +- .../runtime/subagent-plan-tool-policy.ts | 5 +- .../tools/workflow/workflow-deferred.test.ts | 3 +- packages/sdk-typescript/README.md | 42 ++++----- 6 files changed, 137 insertions(+), 52 deletions(-) create mode 100644 packages/core/src/agents/runtime/codemode-eager-exec-regression.test.ts diff --git a/docs/developers/sdk-typescript.md b/docs/developers/sdk-typescript.md index b7aafc14c52..d9e736b3d90 100644 --- a/docs/developers/sdk-typescript.md +++ b/docs/developers/sdk-typescript.md @@ -53,27 +53,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered and not demoted by `tools.eager` (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!note] > For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns. diff --git a/packages/core/src/agents/runtime/codemode-eager-exec-regression.test.ts b/packages/core/src/agents/runtime/codemode-eager-exec-regression.test.ts new file mode 100644 index 00000000000..a919373cdd1 --- /dev/null +++ b/packages/core/src/agents/runtime/codemode-eager-exec-regression.test.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2026 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ +import { describe, expect, it, vi } from 'vitest'; +import { AgentCore } from './agent-core.js'; +import { ToolMode } from '../../tools/code-mode.js'; +import { ToolNames } from '../../tools/tool-names.js'; +import { ExecTool } from '../../tools/exec.js'; +import { ToolRegistry } from '../../tools/tool-registry.js'; +import { MockTool } from '../../test-utils/mock-tool.js'; +import { makeFakeConfig } from '../../test-utils/config.js'; +import { + hasAgentSkillExecBinding, + isAgentSkillEagerHidden, + toolConfigAllowsSkill, +} from './subagent-plan-tool-policy.js'; + +function fixture() { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + vi.spyOn(config, 'getVisibleTools').mockReturnValue( + new Set([ToolNames.SKILL, ToolNames.READ_FILE]), + ); + registry.registerPermissionDeferredFactory( + ToolNames.EXEC, + async () => new ExecTool(config), + ); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + return { config, registry }; +} + +describe('R33-62 eager exec skill visibility', () => { + it('advertises the always-loaded exec route before warming lazy factories', () => { + const { config, registry } = fixture(); + expect(registry.isPermissionDeferred(ToolNames.EXEC)).toBe(true); + expect(hasAgentSkillExecBinding(config)).toBe(true); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.EXEC] }, + hasAgentSkillExecBinding(config), + isAgentSkillEagerHidden(config), + ), + ).toBe(true); + }); + + it('agrees with the actual AgentCore skill invocation gate', async () => { + const { config, registry } = fixture(); + const core = new AgentCore( + 'eager-exec-reproduction', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools: [ToolNames.EXEC] }, + ); + const internals = core as unknown as { + willHaveSkillTool: () => boolean; + canInvokeSkill: (declared: ReadonlySet) => boolean; + }; + const announcedBeforePrepare = internals.willHaveSkillTool(); + const declared = new Set( + (await core.prepareTools()) + .map((x) => x.name) + .filter((x): x is string => !!x), + ); + expect(registry.isPermissionDeferred(ToolNames.EXEC)).toBe(true); + expect(registry.isDeferredAndHidden(ToolNames.EXEC)).toBe(false); + expect(declared.has(ToolNames.EXEC)).toBe(true); + expect(internals.canInvokeSkill(declared)).toBe(true); + expect(announcedBeforePrepare).toBe(true); + expect(internals.willHaveSkillTool()).toBe(true); + }); + + it('still withholds an ordinary eager-hidden skill', () => { + const { config, registry } = fixture(); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + vi.spyOn(config, 'getVisibleTools').mockReturnValue(new Set()); + expect(isAgentSkillEagerHidden(config)).toBe(true); + expect(hasAgentSkillExecBinding(config)).toBe(false); + }); +}); diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index b7c1446dd04..c87a3561e5a 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -453,10 +453,7 @@ describe('subagent plan tool policy', () => { return config; }; - it('reports no exec route when exec is eager-hidden in Hybrid', () => { - // `tools.eager` can demote `exec` too. prepareTools() then drops it from - // the Hybrid declarations and from the exec binding set, so the gateway - // is closed even though the registry still counts the factory. + it('retains the always-loaded exec route when permission-deferred in Hybrid', () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); const registry = new ToolRegistry(config); vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); @@ -468,14 +465,14 @@ describe('subagent plan tool policy', () => { vi.spyOn(config, 'getVisibleTools').mockReturnValue( new Set([ToolNames.SKILL]), ); - expect(hasAgentSkillExecBinding(config)).toBe(false); + expect(hasAgentSkillExecBinding(config)).toBe(true); expect( toolConfigAllowsSkill( { tools: [ToolNames.EXEC] }, hasAgentSkillExecBinding(config), isAgentSkillEagerHidden(config), ), - ).toBe(false); + ).toBe(true); }); it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 1863e4be184..9535715a92d 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -151,9 +151,8 @@ export function hasAgentSkillExecBinding( return ( mode === ToolMode.CodeModeOnly || (mode === ToolMode.CodeMode && - // `tools.eager` can demote exec too; prepareTools() then drops it from - // the Hybrid declarations and from the exec binding set. - !isAgentToolEagerHidden(context, ToolNames.EXEC, registryWillBeRebuilt) && + // Exec is alwaysLoad: permission deferral cannot hide the registered gateway, + // including before its lazy factory has been warmed. !isAgentSkillEagerHidden(context, registryWillBeRebuilt)) ); } diff --git a/packages/core/src/tools/workflow/workflow-deferred.test.ts b/packages/core/src/tools/workflow/workflow-deferred.test.ts index 479a164cfca..7b77188bae6 100644 --- a/packages/core/src/tools/workflow/workflow-deferred.test.ts +++ b/packages/core/src/tools/workflow/workflow-deferred.test.ts @@ -19,6 +19,7 @@ import { ToolSearchTool } from '../tool-search.js'; import { resolveDeferredToolCall, ToolCallTool } from '../tool-call.js'; import { ToolErrorType } from '../tool-error.js'; import { ToolNames } from '../tool-names.js'; +import { ToolMode } from '../code-mode.js'; import { WorkflowTool } from './workflow.js'; afterEach(() => vi.restoreAllMocks()); @@ -145,7 +146,7 @@ describe('deferred Workflow discovery', () => { it('keeps CodeMode discovery behind exec without Direct bridge instructions', async () => { const { config, registry, workflow, lookup } = fixture({ - codeModeOnly: true, + toolMode: ToolMode.CodeModeOnly, }); const declarations = registry.getFunctionDeclarations(); expect(JSON.stringify(declarations)).not.toContain('tools.workflow(args:'); diff --git a/packages/sdk-typescript/README.md b/packages/sdk-typescript/README.md index 71feb1160c3..d9b01e7cf90 100644 --- a/packages/sdk-typescript/README.md +++ b/packages/sdk-typescript/README.md @@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code. #### QueryOptions -| Option | Type | Default | Description | -| ------------------------ | -------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | -| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | -| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | -| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | -| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | -| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | -| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | -| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | -| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | -| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | -| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | -| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered and not demoted by `tools.eager` (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | -| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | -| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | -| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | -| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | -| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | -| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | -| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | +| Option | Type | Default | Description | +| ------------------------ | -------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. | +| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. | +| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. | +| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. | +| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). | +| `env` | `Record` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. | +| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. | +| `mcpServers` | `Record` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. | +| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. | +| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. | +| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. | +| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is the only allowlist-style option that restricts built-in tool registration; a whole-tool `permissions.deny` / `excludeTools` rule (and `tools.disabled` in settings.json) also removes a tool from the registry. `permissions.allow` in settings.json is pure auto-approval and never removes, demotes, or hides a tool (#10075). To keep a tool's schema out of the initial model request, use `tools.eager` in settings.json (requires restart, #9827) — `tool_search`, `tool_call`, `structured_output`, plan-mode lifecycle tools, `task_stop`, `mcp__*` and `computer_use__*` tools are exempt from that allowlist and keep their normal loading; tools demoted this way stay registered and reachable through `tool_search` + `tool_call` while both bridge tools are registered — when either is unregistered (`tools.toolSearch.enabled: false` denies both; a `tool_search` or `tool_call` deny rule, or a `tools.disabled` entry removes one) the demoted tools that remain hidden are absent from top-level declarations and cannot be reached through the bridge for that session, and a warning is written to the CLI process's stderr (SDK forwards it only with piped stderr and effective `debug` logging; an explicit `logLevel` always wins). These bridge and warning rules apply to direct and hybrid code modes. On the session surface in hybrid mode, while `exec` itself is registered (container and SSH execution warn and fall back to direct tools without it), withheld tools that have an actual nested exec binding remain callable through exec, and their schemas are included in the exec description when either bridge tool is unavailable; `direct-only` tools (`agent`, `send_message`, `create_sub_session`, the worktree tools) never get a nested binding; when withheld they stay reachable through the `tool_search` + `tool_call` bridge while both bridge tools are registered, never through `exec`. CodeModeOnly discovers deferred schemas through top-level tool_search and invokes them through exec. It skips deferred preload and startup catalogs; tools.eager reduces the initial exec description. When search is unavailable in the current scope, exec includes all allowed signatures. In Hybrid mode, AgentCore excludes tools still hidden by tools.eager from nested bindings. In both code modes, agent allowlists that do not grant `exec` narrow nested bindings. Inheriting or explicitly granting `exec` keeps all otherwise admitted ordinary code-mode-callable bindings. An execution allowlist that mentions any MCP tool additionally restricts MCP bindings to matching exact names or server patterns. In direct and hybrid modes they stay registered, so a direct call by their own name is still evaluated and approved normally — except tools also listed in `tools.visible`, which are declared upfront, and sessions whose live history contains a direct call to a still-hidden demoted tool, which any tool-set refresh (resume, MCP discovery, the first plan-mode entry in a session, a subagent definition change) re-declares.; to remove a tool entirely, use a whole-tool `excludeTools` / `permissions.deny` rule — a rule with a specifier (such as `'Bash(rm *)'`) only denies matching invocations at runtime. MCP tools are exempt from deny-based removal: hide them with the per-server `excludeTools` / `tools.disabled` filters instead (deny still blocks their calls at runtime). Example: `['read_file', 'edit', 'run_shell_command']`. | +| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). | +| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Like `permissions.allow`, this is pure auto-approval and never affects which tools are registered or which schemas are sent (#10075). Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. | +| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. | +| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. | +| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. | +| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. | +| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. | > [!tip] > If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers. From 78f08c1d7cc4e9dcfc51cf60d8996489eed288b1 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Thu, 5 Nov 2026 20:06:46 +0000 Subject: [PATCH 40/49] fix(core): align the eager-hidden skill check with the declaration filter (#11854) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Direct-mode `tools.eager` demotion hid the Skill declaration, but the predicate still answered "not hidden", so `willHaveSkillTool()` injected an `` listing whose only tool was absent. Mirror the filter — every mode except CodeModeOnly hides these targets — instead of naming Hybrid alone. Also require the deferred bridge's execution allowlist to admit the resolved `skill` target: the scheduler re-checks the unwrapped name, so a list naming only the two bridge halves announced skills that `tool_call` would then deny. Co-authored-by: Qwen-Coder --- .../runtime/subagent-plan-tool-policy.test.ts | 61 ++++++++++++++++++- .../runtime/subagent-plan-tool-policy.ts | 21 +++++-- 2 files changed, 76 insertions(+), 6 deletions(-) diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index c87a3561e5a..21e977e8a12 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -419,7 +419,9 @@ describe('subagent plan tool policy', () => { ), ).toBe(false); } - // Both halves declared keep the route open. + // Both halves declared keep the route open only while the allowlist also + // admits the resolved target: the scheduler re-checks `skill` against the + // same list after the bridge resolves the wrapper. expect( toolConfigAllowsSkill( { @@ -432,9 +434,66 @@ describe('subagent plan tool policy', () => { true, true, ), + ).toBe(false); + expect( + toolConfigAllowsSkill( + { + tools: ['*'], + executionAllowedTools: [ + ToolNames.TOOL_SEARCH, + ToolNames.TOOL_CALL, + ToolNames.SKILL, + ], + }, + false, + true, + false, + true, + true, + ), ).toBe(true); }); + it.each([ToolMode.Direct, ToolMode.CodeMode])( + 'reports a permission-deferred skill as eager-hidden in %s', + (mode) => { + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + + // prepareTools() removes the declaration outside CodeModeOnly, so the + // listing must not survive without a route to the tool. + expect(isAgentSkillEagerHidden(config)).toBe(true); + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.SKILL] }, + false, + isAgentSkillEagerHidden(config), + false, + true, + false, + ), + ).toBe(false); + }, + ); + + it('reports a permission-deferred skill as not hidden in CodeModeOnly', () => { + // The one mode whose admission pool retains eager-hidden targets: exec + // binds the registered tool even while its direct schema is withheld. + const config = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + expect(isAgentSkillEagerHidden(config)).toBe(false); + }); + describe('hasAgentSkillExecBinding', () => { const contextWith = ( mode: ToolMode, diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 9535715a92d..06f64cb5165 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -97,8 +97,11 @@ function isAgentToolEagerHidden( const registry = context.getToolRegistry?.(); // Lazy factories may not have a Tool instance yet. Registry rebuilds copy // discovery metadata, but deliberately leave transient reveals behind. + // Only CodeModeOnly keeps eager-hidden targets in its admission pool (as + // exec bindings); every other mode filters the declaration out, so the + // predicate must mirror that filter rather than name a single mode. return ( - context.getToolMode?.() === ToolMode.CodeMode && + context.getToolMode?.() !== ToolMode.CodeModeOnly && registry?.isPermissionDeferred?.(toolName) === true && !context.getVisibleTools?.().has(toolName) && (registryWillBeRebuilt || @@ -175,10 +178,10 @@ export function hasAgentSkillExecBinding( * registry, whether the Skill factory is registered there at all, and whether * the deferred-tool bridge is registered. A finite list naming exec can * therefore reach Skill without naming it directly. CodeModeOnly retains - * eager-deferred nested targets. In Hybrid, an eager-hidden Skill is vetoed - * only when the bridge cannot reach it: `prepareTools()` keeps the schema out - * of the direct declarations, but `tool_search` + `tool_call` still discover - * and invoke the registered tool. Other permission bounds stay in + * eager-deferred nested targets. Outside CodeModeOnly, an eager-hidden Skill + * is vetoed only when the bridge cannot reach it: `prepareTools()` keeps the + * schema out of the direct declarations, but `tool_search` + `tool_call` still + * discover and invoke the registered tool. Other permission bounds stay in * prepareTools(). * Registry deny/exclude rules remain the bundled-reference resolver's concern; * this predicate supplies the per-agent policy that resolver cannot see. @@ -239,10 +242,18 @@ export function toolConfigAllowsSkill( toolConfig?.executionAllowedTools === undefined || (toolConfig.executionAllowedTools.includes(ToolNames.TOOL_SEARCH) && toolConfig.executionAllowedTools.includes(ToolNames.TOOL_CALL)); + // The bridge resolves to `skill` itself, and the scheduler re-checks that + // resolved target against the same execution allowlist (direct form). A + // defined list is authoritative for non-MCP names, so `tools: ['*']` must + // not re-admit a target the list omits. + const bridgeTargetAllowed = + toolConfig?.executionAllowedTools === undefined || + toolConfig.executionAllowedTools.includes(ToolNames.SKILL); const bridgeReachesSkill = deferredBridgeAvailable && !bridgeBlocked && bridgeExecutionAllowed && + bridgeTargetAllowed && (inheritsRegistry || (names.includes(ToolNames.TOOL_SEARCH) && names.includes(ToolNames.TOOL_CALL))); From 3bb29e2ccfe42c618dd5b740382f6aef931ed0cc Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Fri, 6 Nov 2026 00:18:52 +0000 Subject: [PATCH 41/49] fix(core): recompute eager-hidden Skill in Direct mode (#11854) The recovery path for a parent that never registered the Skill factory recomputed `skillEagerHidden` only in Hybrid mode, while the shared predicate it feeds hides eager-deferred targets in every mode except CodeModeOnly. In Direct mode the two halves disagreed: the parent's missing factory made the predicate answer "not hidden", the recovery skipped the recompute, and a grandchild naming `skill` was handed the session SkillManager even though neither the declaration nor the bridge could reach it. Mirror the predicate's own mode test, and pin it with a Direct-mode `tools.eager` case whose grandchild asks for `skill` without either bridge half and must resolve to an inline delegation reference. Co-authored-by: Qwen-Coder Co-authored-by: Qwen-Coder --- ...ubagent-manager.skill-eager-review.test.ts | 84 +++++++++++++++++++ .../core/src/subagents/subagent-manager.ts | 2 +- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts index 7ba4ad4bc28..4b3a853f3a4 100644 --- a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts +++ b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts @@ -141,4 +141,88 @@ describe('nested agents retain their actual Skill availability', () => { } }, ); + + it('withholds the session SkillManager from a Direct-mode grandchild that cannot reach Skill', async () => { + // A Direct-mode `tools.eager` allowlist omits `skill`, so the root + // registry registers it permission-deferred. The child's registry holds no + // Skill factory (its own policy withholds `skill`), and the grandchild + // asks for it back without either bridge half. + const config = makeFakeConfig({ + targetDir: process.cwd(), + cwd: process.cwd(), + toolMode: ToolMode.Direct, + eagerTools: [ToolNames.READ_FILE], + }); + const skills = { + addChangeListener: () => () => {}, + listSkills: async () => [], + getCachedSkills: () => [], + hasDiscoveryErrors: () => false, + isSkillActive: () => true, + }; + const permissions = new PermissionManager(config); + permissions.initialize(); + vi.spyOn(config, 'getPermissionManager').mockReturnValue(permissions); + vi.spyOn(config, 'getSkillManager').mockReturnValue(skills as never); + const manager = new SubagentManager(config); + vi.spyOn(manager, 'listSubagents').mockResolvedValue([]); + vi.spyOn(config, 'getSubagentManager').mockReturnValue(manager); + const rootRegistry = await config.createToolRegistry(undefined, { + skipDiscovery: true, + }); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(rootRegistry); + + let capture: { context: Config; tools: ToolConfig | undefined } | undefined; + const createSpy = vi + .spyOn(AgentHeadless, 'create') + .mockImplementation( + async (_name, context, _prompt, _model, _run, tools) => { + capture = { context, tools }; + return { + getCore: () => ({ subagentId: 'direct-skill-policy' }), + } as unknown as AgentHeadless; + }, + ); + const handles: Array<{ dispose(): Promise }> = []; + try { + handles.push( + await manager.createAgentHeadless( + { + name: 'direct-skill-parent', + description: 'Direct-mode parent without Skill', + systemPrompt: 'Inspect Skill availability only.', + level: 'session', + tools: [ToolNames.READ_FILE], + }, + config, + ), + ); + const child = capture!.context; + expect(child.getSkillManager()).toBeNull(); + expect(child.getToolRegistry().getAllToolNames()).not.toContain( + ToolNames.SKILL, + ); + + handles.push( + await manager.createAgentHeadless( + { + name: 'direct-skill-grandchild', + description: 'Direct-mode grandchild naming Skill', + systemPrompt: 'Inspect Skill availability only.', + level: 'session', + tools: [ToolNames.READ_FILE, ToolNames.SKILL], + }, + child, + ), + ); + const grandchild = capture!.context; + expect(grandchild.getSkillManager()).toBeNull(); + expect(resolveAgentDelegationSurface(grandchild)).toBe('inline'); + } finally { + createSpy.mockRestore(); + for (const handle of handles.reverse()) await handle.dispose(); + await rootRegistry.stop(); + vi.restoreAllMocks(); + } + }); }); diff --git a/packages/core/src/subagents/subagent-manager.ts b/packages/core/src/subagents/subagent-manager.ts index 3293bfb051c..0a7779c270f 100644 --- a/packages/core/src/subagents/subagent-manager.ts +++ b/packages/core/src/subagents/subagent-manager.ts @@ -1209,7 +1209,7 @@ export class SubagentManager { const status = await runtimeContext .getPermissionManager?.() ?.getToolRegistrationStatus(ToolNames.SKILL); - if (runtimeContext.getToolMode?.() === ToolMode.CodeMode) { + if (runtimeContext.getToolMode?.() !== ToolMode.CodeModeOnly) { skillEagerHidden = status === 'disabled' || (status === 'deferred' && From 0a054d857e2ef97861e9e0654cdba00be5dfbe96 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Tue, 10 Nov 2026 00:33:23 +0000 Subject: [PATCH 42/49] fix: align skill bridge gate, fork_tools docs, and tool-mode restore (#11854) Co-authored-by: Qwen-Coder --- docs/developers/tools/task.md | 4 +- docs/users/features/sub-agents.md | 2 +- .../cli/src/config/settings-tool-mode.test.ts | 52 ++++++++++++++++ packages/cli/src/config/settings.ts | 39 +++++++----- .../runtime/agent-core.fork-policy.test.ts | 52 ++++++++++++++++ .../runtime/agent-core.skill-gate.test.ts | 47 ++++++++++++++ .../core/src/agents/runtime/agent-core.ts | 18 +++++- .../runtime/subagent-plan-tool-policy.ts | 61 +++++++++++-------- packages/core/src/tools/agent/agent.ts | 2 +- 9 files changed, 233 insertions(+), 44 deletions(-) diff --git a/docs/developers/tools/task.md b/docs/developers/tools/task.md index 1522549c1e0..862006d12ed 100644 --- a/docs/developers/tools/task.md +++ b/docs/developers/tools/task.md @@ -14,7 +14,7 @@ Use `agent` to launch a specialized subagent to handle complex, multi-step tasks - `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution. - `subagent_type` (string, optional): The type of specialized agent to use for this task. Defaults to `general-purpose` if omitted. - `fork_turns` (string, optional): Only valid with `subagent_type="fork"`. Omit it or use `all` for the full parent conversation, or use a positive integer string such as `"3"` for the most recent three real user turns. Tool responses and pure system reminders do not count as turns. -- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. A non-empty `fork_tools` list also re-admits `tool_search` and `tool_call` in any mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under either code mode the list still admits `exec` (and `tool_search` under `code_mode_only`), which the mode grants ahead of the allowlist, and listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy; the empty array closes the exec route too. +- `fork_tools` (array of strings, optional): Only valid with `subagent_type="fork"`. Restricts execution to exact canonical tool names or MCP server patterns; in `direct` mode the fork's current model-visible tool declarations remain unchanged for prompt-cache sharing, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this execution allowlist. Entries cannot have surrounding whitespace; wildcards are limited to `mcp__*` or a trailing MCP tool-prefix pattern such as `mcp__github__read_*`. Forks never execute `ask_user_question`; omit `fork_tools` to allow every other inherited tool, or use an empty array to reject every tool call. A non-empty `fork_tools` list also re-admits `tool_search` and `tool_call` in any mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under either code mode a non-empty list still admits `exec` (and `tool_search` under `code_mode_only`), which the mode grants ahead of the allowlist, provided the derived allowlist is non-empty; a list whose every entry is filtered out (for example only `ask_user_question` or `display_image`, with no parent bridge half) behaves like an empty array and closes the exec route. Listing `exec` also admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls, so `fork_tools: ["exec"]` is not an exec-only policy. - `fork_profile` (string, optional): Only valid with `subagent_type="fork"`. Loads a frontmatter-only regular `.qwen/fork-profiles/.md` of at most 64 KiB from the active project root and applies its required `tools` array plus an optional `promptHint` of at most 200 characters. The file cannot resolve outside the project profile directory. `fork_profile` cannot be combined with `fork_tools` or a named teammate, and it is unavailable in safe mode or bare mode. - `run_in_background` (boolean, optional): For top-level regular agents, omission uses the definition's `background` field, then `agents.defaultBackground` (default: `true`; requires restart). An explicit argument overrides both. Set to `false` to wait for a regular agent's result inline. Headless forks always run in the background. Nested agents run in the foreground unless `run_in_background` is explicitly `true`, which is rejected because nested agents cannot receive background completion notifications. Unnamed caller-owned `working_dir` launches run in the foreground: an explicit `run_in_background: true` request is rejected, while a configured background default (`background: true` in a subagent definition) is rejected at the top level and downgraded to the foreground when nested. - `isolation` (string, optional): Set to `"worktree"` to run an explicitly named, non-fork agent in an isolated git worktree that Qwen Code creates and manages. @@ -149,7 +149,7 @@ Don't use the Agent tool for: - **Independent context**: Regular subagents start without parent conversation history. Forks inherit the full conversation by default and accept `fork_turns` when a bounded recent window is sufficient. - **Subagent interaction**: Regular subagents do not receive `ask_user_question`. In `direct` mode forks keep the parent's declaration list for cache sharing — including that tool — and reject it before scheduling or approval; under hybrid `code_mode` a `fork_tools` allowlist narrows the declaration list, so it is dropped there. When missing user input blocks work, the subagent reports the blocker to its parent. -- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing. A non-empty list also re-admits `tool_search` and `tool_call` in every mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under a code mode a non-empty list still admits `exec` (and `tool_search` in `code_mode_only`) ahead of the list — an empty array rejects every call, `exec` included — and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. +- **Fork execution restrictions**: `fork_tools` further narrows which already-declared tools a fork may execute. In `direct` mode, disallowed calls return an error before scheduling or approval and the same declaration list remains model-visible for cache sharing. A non-empty list also re-admits `tool_search` and `tool_call` in every mode when the parent session declares them — the deferred-tool bridge route; `tool_call`'s resolved target is still checked against the list. Under a code mode a non-empty list still admits `exec` (and `tool_search` in `code_mode_only`) ahead of the list provided the derived allowlist is non-empty — an empty array, or a list whose every entry is filtered out (for example only `ask_user_question` or `display_image`, with no parent bridge half), rejects every call, `exec` included — and under hybrid `code_mode` the allowlist also narrows the fork's declarations. This is a per-call restriction chosen by the caller, not an administrator-enforced sandbox. Under a code mode, nested `tools.(...)` calls inside `exec` follow the code-mode binding rules instead: an `exec` entry admits every code-mode-callable tool this fork's own surface admits there. - **Fork profiles**: A project profile under `.qwen/fork-profiles/` reuses the same execution gate as `fork_tools`. It is resolved once before launch; the resolved list is persisted for revival, and an optional `promptHint` is added only to the task directive. - **Completion delivery**: Background results arrive through completion notifications in a later turn. Do not assume a result before the notification arrives. - **Continuation**: Use `list_agents` and `send_message` for related follow-up work instead of launching a duplicate agent. Continuation depends on compatible retained state and may be unavailable. diff --git a/docs/users/features/sub-agents.md b/docs/users/features/sub-agents.md index 47b017e98b0..16221ef2394 100644 --- a/docs/users/features/sub-agents.md +++ b/docs/users/features/sub-agents.md @@ -54,7 +54,7 @@ Tool responses and pure system reminders do not count as user turns. Regular nam ## Restricting Fork Tool Execution with `fork_tools` -Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. In `direct` mode the fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this allowlist; either way its task prompt identifies the restriction, and a call not matched by `fork_tools` is rejected before scheduling or approval. Two code-mode exceptions: under either code mode a non-empty `fork_tools` list still admits `exec` ahead of the list — an empty array closes the exec route too — and listing `exec` admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). +Only `subagent_type: "fork"` accepts `fork_tools`. The array may contain exact canonical tool names, such as `read_file` and `grep_search`, or MCP server patterns such as `mcp__github`. In `direct` mode the fork still receives the same model-visible tool declarations as an unrestricted fork, preserving its prompt-cache prefix, while under hybrid `tools.mode: "code_mode"` the fork's top-level declarations are filtered by this allowlist; either way its task prompt identifies the restriction, and a call not matched by `fork_tools` is rejected before scheduling or approval. Two code-mode exceptions: under either code mode a non-empty `fork_tools` list still admits `exec` ahead of the list provided the derived allowlist is non-empty — an empty array, or a list whose every entry is filtered out (for example only `ask_user_question` or `display_image`, with no parent bridge half), closes the exec route too — and listing `exec` admits every code-mode-callable tool this fork's own surface admits through exec's nested `tools.(...)` calls — see the `exec` note under [Tool Configuration](#tool-configuration). - Forks never execute `ask_user_question`; when user input is required, they report the blocker to their parent agent. - Omitting `fork_tools` allows every other inherited tool. diff --git a/packages/cli/src/config/settings-tool-mode.test.ts b/packages/cli/src/config/settings-tool-mode.test.ts index 242c846a74b..35727247700 100644 --- a/packages/cli/src/config/settings-tool-mode.test.ts +++ b/packages/cli/src/config/settings-tool-mode.test.ts @@ -110,6 +110,58 @@ describe('legacy tool mode settings', () => { expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe('direct'); }); + it.each([null, false, 'replace', []])( + 'keeps an operator tools.mode when a project replaces tools with %j', + (tools) => { + const loaded = new LoadedSettings( + file({}), + file({}), + file({ tools: { mode: 'code_mode_only' } }), + file({ tools } as unknown as Settings), + true, + new Set(), + ); + + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe( + 'code_mode_only', + ); + }, + ); + + it.each([null, false, 'replace', []])( + 'keeps an operator legacy mode when a project replaces tools with %j', + (tools) => { + const loaded = new LoadedSettings( + file({ tools: { codeModeOnly: true } } as unknown as Settings), + file({}), + file({}), + file({ tools } as unknown as Settings), + true, + new Set(), + ); + + expect(getEffectiveValue('tools.mode', {}, loaded.merged)).toBe( + 'code_mode_only', + ); + }, + ); + + it('re-adds only the operator mode key to a project tools section', () => { + const loaded = new LoadedSettings( + file({}), + file({}), + file({ tools: { codeModeOnly: true } } as unknown as Settings), + file({ tools: { approvalMode: 'yolo' } } as unknown as Settings), + true, + new Set(), + ); + + expect(loaded.merged.tools?.approvalMode).toBe('yolo'); + expect( + (loaded.merged.tools as { codeModeOnly?: unknown })?.codeModeOnly, + ).toBe(true); + }); + it('keeps a higher-precedence tools.mode over a lower legacy mode', () => { const loaded = new LoadedSettings( file({ tools: { mode: 'direct' } }), diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index 77c54b51577..3caf18b6b83 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -754,28 +754,39 @@ function mergeSettings( delete merged.tools.executionSandbox; } // `tools.mode` and the legacy `tools.codeModeOnly` name one setting but - // merge as independent keys, so an operator's enforced legacy value would - // otherwise sit beside a lower-scope `mode` that every key-first reader - // prefers. Keep the highest-precedence scope's choice. + // merge as independent keys, so an operator's enforced value would + // otherwise sit beside a lower-scope key that every key-first reader + // prefers. Keep the highest-precedence scope's choice, and rebuild the + // section when a project replaced `tools` with null, a scalar, or an array + // during the ordinary merge. const toolModeChoice = [systemDefaults, user, safeWorkspace, system].reduce< - 'mode' | 'legacy-true' | 'legacy-false' | undefined + | { kind: 'mode'; value: unknown } + | { kind: 'legacy'; value: boolean } + | undefined >((choice, scope) => { const tools = scope.tools as | { mode?: unknown; codeModeOnly?: unknown } | undefined; - if (tools?.mode !== undefined) return 'mode'; - if (tools?.codeModeOnly === true) return 'legacy-true'; - if (tools?.codeModeOnly === false) return 'legacy-false'; + if (tools?.mode !== undefined) return { kind: 'mode', value: tools.mode }; + if (typeof tools?.codeModeOnly === 'boolean') { + return { kind: 'legacy', value: tools.codeModeOnly }; + } return choice; }, undefined); - if ( - (toolModeChoice === 'legacy-true' || toolModeChoice === 'legacy-false') && - merged.tools && - typeof merged.tools === 'object' - ) { - const tools = merged.tools as { mode?: unknown; codeModeOnly?: unknown }; + if (toolModeChoice) { + const existing = merged.tools; + const tools: { mode?: unknown; codeModeOnly?: unknown } = + existing && typeof existing === 'object' && !Array.isArray(existing) + ? { ...existing } + : {}; delete tools.mode; - tools.codeModeOnly = toolModeChoice === 'legacy-true'; + delete tools.codeModeOnly; + if (toolModeChoice.kind === 'mode') { + tools.mode = toolModeChoice.value; + } else { + tools.codeModeOnly = toolModeChoice.value; + } + merged.tools = tools as Settings['tools']; } const operatorCatalogRefresh = selectOperatorCatalogRefresh( systemDefaults, diff --git a/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts b/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts index 0cc50f305f0..12899aee6c4 100644 --- a/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts +++ b/packages/core/src/agents/runtime/agent-core.fork-policy.test.ts @@ -15,8 +15,60 @@ import { MockTool } from '../../test-utils/mock-tool.js'; import { ToolRegistry } from '../../tools/tool-registry.js'; import { ExecTool } from '../../tools/exec.js'; import { ToolMode } from '../../tools/code-mode.js'; +import { ToolNames } from '../../tools/tool-names.js'; +import { + buildForkExecutionAllowlist, + resolveForkExecutionAllowedTools, +} from '../../tools/agent/fork-subagent.js'; describe('fork MCP policy inheritance', () => { + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( + 'treats a non-empty fork_tools list that derives to empty as deny-all in %s', + async (mode) => { + const config = makeFakeConfig({ toolMode: mode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.READ_FILE })); + registry.registerTool( + new MockTool({ name: ToolNames.ASK_USER_QUESTION }), + ); + const parentToolNames = registry.getAllToolNames(); + // `ask_user_question` never executes in a fork, and this parent + // declares neither bridge half, so a one-entry list derives to `[]` — + // the same deny-all shape as `fork_tools: []`. + const executionAllowedTools = resolveForkExecutionAllowedTools( + parentToolNames, + buildForkExecutionAllowlist( + [ToolNames.ASK_USER_QUESTION], + [ToolNames.READ_FILE], + parentToolNames, + ), + ); + expect(executionAllowedTools).toEqual([]); + + const core = new AgentCore( + 'fork-empty-derived', + config, + { systemPrompt: '' }, + { model: 'test' }, + { max_turns: 1 }, + { + tools: parentToolNames, + executionAllowedTools, + nestedExecutionAllowedTools: [], + }, + ); + const executable = ( + core as unknown as { + isToolExecutionAllowed: (name: string) => boolean; + } + ).isToolExecutionAllowed.bind(core); + expect(executable(ToolNames.EXEC)).toBe(false); + expect(await core.prepareTools()).toEqual([]); + }, + ); + it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( 'does not turn the %s exec wrapper into an inherited grant', async (mode) => { diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index 02bbcba8b9a..a6b6e91cb39 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -477,6 +477,53 @@ describe('AgentCore skill-gate inputs', () => { expect(declared.has(ToolNames.SKILL)).toBe(false); expect(declared.has(ToolNames.TOOL_SEARCH)).toBe(true); expect(declared.has(ToolNames.TOOL_CALL)).toBe(true); + // The announcement is only useful if the activation gate agrees: the + // bridge can invoke the skill, so it must not withhold the details. + expect(gate(core, declared)).toBe(true); + }); + + it('refuses the bridge route under CodeModeOnly, where tool_call is hidden', () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + registry.registerTool(new MockTool({ name: ToolNames.TOOL_SEARCH })); + registry.registerTool(new MockTool({ name: ToolNames.TOOL_CALL })); + const core = new AgentCore( + 'skill-bridge-code-mode-only', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools: ['*'] }, + ); + // `prepareTools()` never declares `tool_call` in this mode, so the + // declaration set is supplied directly to pin the mode rule. + expect( + gate(core, new Set([ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL])), + ).toBe(false); + }); + + it('refuses declarations whose bridge halves are not registered', () => { + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerTool(new MockTool({ name: ToolNames.SKILL })); + const core = new AgentCore( + 'skill-bridge-unregistered', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { tools: ['*'] }, + ); + // Inline declarations can name the bridge without registering it; such + // a `tool_call` resolves nothing, so the gate must not open on it. + expect( + gate(core, new Set([ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL])), + ).toBe(false); }); it('stays silent when the eager-hidden Skill has no declared bridge', () => { diff --git a/packages/core/src/agents/runtime/agent-core.ts b/packages/core/src/agents/runtime/agent-core.ts index 6aec1ca11ed..148cba367c2 100644 --- a/packages/core/src/agents/runtime/agent-core.ts +++ b/packages/core/src/agents/runtime/agent-core.ts @@ -150,6 +150,7 @@ import { getExcludedToolsForCurrentContext, getLeaderOnlyToolUnavailableMessage, getSubagentPlanToolUnavailableMessage, + deferredBridgeReachesSkill, hasAgentSkillBridge, hasAgentSkillExecBinding, isLeaderOnlyToolUnavailableInSubagent, @@ -1932,15 +1933,28 @@ export class AgentCore { private canInvokeSkill( declaredToolNames: ReadonlySet, ): boolean { + const registry = this.runtimeContext.getToolRegistry(); return ( (declaredToolNames.has(ToolNames.SKILL) && this.runtimeContext.getToolMode?.() !== ToolMode.CodeModeOnly && this.isToolExecutionAllowed(ToolNames.SKILL)) || (isCodeModeEnabled(this.runtimeContext.getToolMode?.()) && declaredToolNames.has(ToolNames.EXEC) && - !!this.runtimeContext.getToolRegistry().getTool(ToolNames.SKILL) && + !!registry.getTool(ToolNames.SKILL) && this.codeModeAllowedToolNames?.includes(ToolNames.SKILL) === true && - this.isToolExecutionAllowed(ToolNames.SKILL, true)) + this.isToolExecutionAllowed(ToolNames.SKILL, true)) || + // CodeModeOnly hides and refuses `tool_call`, so the bridge is a + // direct-call route only outside it. + (this.runtimeContext.getToolMode?.() !== ToolMode.CodeModeOnly && + hasAgentSkillBridge(this.runtimeContext) && + deferredBridgeReachesSkill( + (toolName) => + declaredToolNames.has(toolName) && + this.isToolExecutionAllowed(toolName), + (toolName) => + !!registry.getTool(toolName) && + this.isToolExecutionAllowed(toolName), + )) ); } diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index 06f64cb5165..ccb0d637dac 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -136,6 +136,28 @@ export function hasAgentSkillBridge(context: AgentSkillContext): boolean { ); } +/** + * Whether the deferred-tool bridge (`tool_search` + `tool_call`) reaches the + * Skill tool. + * + * `isBridgeHalfUsable` answers for each wrapper and `isSkillTargetUsable` for + * the resolved target, at the caller's own level: the declaration-level + * `ToolConfig` in {@link toolConfigAllowsSkill}, the invocation-level + * declarations and execution allowlist in `AgentCore.canInvokeSkill`. One + * helper, so the announcement predicate and the activation gate cannot + * disagree about this route. + */ +export function deferredBridgeReachesSkill( + isBridgeHalfUsable: (toolName: string) => boolean, + isSkillTargetUsable: (toolName: string) => boolean, +): boolean { + return ( + isBridgeHalfUsable(ToolNames.TOOL_SEARCH) && + isBridgeHalfUsable(ToolNames.TOOL_CALL) && + isSkillTargetUsable(ToolNames.SKILL) + ); +} + export function hasAgentSkillExecBinding( context: AgentSkillContext, registryWillBeRebuilt = false, @@ -229,34 +251,25 @@ export function toolConfigAllowsSkill( // list holding only inline declarations inherits: both take the explicit // branch there, which declares no registry tool. const inheritsRegistry = !toolConfig || names.includes('*'); - const bridgeBlocked = - matchesAgentToolBlocklist( - toolConfig?.disallowedTools, - ToolNames.TOOL_SEARCH, - ) || - matchesAgentToolBlocklist(toolConfig?.disallowedTools, ToolNames.TOOL_CALL); // The execution allowlist also bounds the bridge: under hybrid code_mode it // narrows the declarations, and a half outside it cannot be called in Direct - // or Hybrid (an empty list denies every direct call). - const bridgeExecutionAllowed = - toolConfig?.executionAllowedTools === undefined || - (toolConfig.executionAllowedTools.includes(ToolNames.TOOL_SEARCH) && - toolConfig.executionAllowedTools.includes(ToolNames.TOOL_CALL)); - // The bridge resolves to `skill` itself, and the scheduler re-checks that - // resolved target against the same execution allowlist (direct form). A - // defined list is authoritative for non-MCP names, so `tools: ['*']` must - // not re-admit a target the list omits. - const bridgeTargetAllowed = - toolConfig?.executionAllowedTools === undefined || - toolConfig.executionAllowedTools.includes(ToolNames.SKILL); + // or Hybrid (an empty list denies every direct call). The bridge resolves to + // `skill` itself, and the scheduler re-checks that resolved target against + // the same execution allowlist (direct form); a defined list is + // authoritative for non-MCP names, so `tools: ['*']` must not re-admit a + // target the list omits. const bridgeReachesSkill = deferredBridgeAvailable && - !bridgeBlocked && - bridgeExecutionAllowed && - bridgeTargetAllowed && - (inheritsRegistry || - (names.includes(ToolNames.TOOL_SEARCH) && - names.includes(ToolNames.TOOL_CALL))); + deferredBridgeReachesSkill( + (toolName) => + !matchesAgentToolBlocklist(toolConfig?.disallowedTools, toolName) && + (toolConfig?.executionAllowedTools === undefined || + toolConfig.executionAllowedTools.includes(toolName)) && + (inheritsRegistry || names.includes(toolName)), + (toolName) => + toolConfig?.executionAllowedTools === undefined || + toolConfig.executionAllowedTools.includes(toolName), + ); if (skillEagerHidden && !bridgeReachesSkill) { return false; } diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 19bc4f73a62..0110ac62414 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -935,7 +935,7 @@ export class AgentTool extends BaseDeclarativeTool { minLength: 1, }, description: - 'Only valid with subagent_type "fork". Exact tool names and MCP server patterns this fork may execute. Entries cannot have surrounding whitespace; wildcard entries must be "mcp__*" or a trailing MCP tool-prefix pattern such as "mcp__github__read_*". `direct` mode keeps declarations unchanged for prompt-cache sharing; hybrid `code_mode` narrows them to the list. Code modes admit `exec` ahead of a non-empty list (and `tool_search` in `code_mode_only`). Forks never execute ask_user_question; omit fork_tools to allow every other inherited tool, or an empty array rejects every tool call.', + 'Only valid with subagent_type "fork". Exact names or MCP patterns. No surrounding whitespace; wildcards must be "mcp__*" or a trailing MCP prefix such as "mcp__github__read_*". `direct` mode keeps declarations unchanged for prompt-cache sharing; hybrid `code_mode` narrows them to the list. Code modes admit `exec` ahead of a non-empty list (and `tool_search` in `code_mode_only`) unless the fork\'s filters leave the derived allowlist empty; such a list behaves like []. Forks never execute ask_user_question; omit fork_tools to allow other inherited tools; an empty array rejects every tool call.', }, fork_profile: { type: 'string', From 14bc01c4fe8b6a6d2610892c9a2862fe4d36d04b Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Tue, 10 Nov 2026 01:31:51 +0000 Subject: [PATCH 43/49] fix: stop question acquire at its deadline and align nested skill gate (#11854) Co-authored-by: Qwen-Coder Co-authored-by: Qwen-Coder --- .../src/serve/hosted-question-wait.test.ts | 49 +++++++++++++++++++ .../cli/src/serve/hosted-question-wait.ts | 7 ++- ...ubagent-manager.skill-eager-review.test.ts | 2 +- 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/serve/hosted-question-wait.test.ts b/packages/cli/src/serve/hosted-question-wait.test.ts index 902135c64b1..352a3fe6250 100644 --- a/packages/cli/src/serve/hosted-question-wait.test.ts +++ b/packages/cli/src/serve/hosted-question-wait.test.ts @@ -16,6 +16,27 @@ import { HostedWorkspaceBrokerRejection, } from './hosted-workspace-broker.js'; +type PromiseDelay = ( + ms?: number, + value?: unknown, + options?: { signal?: AbortSignal; ref?: boolean }, +) => Promise; +const timer = vi.hoisted(() => ({ + override: undefined as PromiseDelay | undefined, +})); +// A plain wrapper rather than vi.fn, whose implementation afterEach would +// clear; the deadline case below overrides the timer explicitly. +vi.mock('node:timers/promises', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + setTimeout: (ms?: number, value?: unknown, options?: never) => + timer.override + ? timer.override(ms, value, options) + : (actual.setTimeout as PromiseDelay)(ms, value, options), + }; +}); + afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); @@ -231,6 +252,34 @@ describe('question wait ownership', () => { }, ); + it('does not acquire again when a retry timer fires a millisecond early', async () => { + let now = 1_000_000; + vi.spyOn(Date, 'now').mockImplementation(() => now); + timer.override = async (ms) => { + // A real timer may fire up to 1 ms before the requested wall-clock + // delay, so the loop must not re-check the deadline one millisecond + // short and issue an acquire past it. + now += Math.max(1, Number(ms) - 1); + }; + try { + const f = fixture(); + f.acquire.mockRejectedValue( + new HostedWorkspaceBrokerRejection(409, 'workspace_busy'), + ); + await expect( + acquireHostedQuestionRuntime( + f.broker, + original, + f.abort.signal, + now + 30, + ), + ).resolves.toBe(false); + expect(f.acquire).toHaveBeenCalledOnce(); + } finally { + timer.override = undefined; + } + }); + it('does not acquire an already cancelled question', async () => { const f = fixture(); f.abort.abort(); diff --git a/packages/cli/src/serve/hosted-question-wait.ts b/packages/cli/src/serve/hosted-question-wait.ts index 2f7f192df12..87da3dde7fc 100644 --- a/packages/cli/src/serve/hosted-question-wait.ts +++ b/packages/cli/src/serve/hosted-question-wait.ts @@ -107,7 +107,12 @@ export async function acquireHostedQuestionRuntime( await delay( Math.min( 250, - expiresAt === undefined ? 250 : Math.max(0, expiresAt - Date.now()), + // A timer can fire up to 1 ms before the requested wall-clock + // delay; overshoot the deadline so the next check cannot land a + // millisecond short and issue an acquire past it. + expiresAt === undefined + ? 250 + : Math.max(0, expiresAt - Date.now()) + 1, ), undefined, { signal, ref: false }, diff --git a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts index 4b3a853f3a4..a0326f3704c 100644 --- a/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts +++ b/packages/core/src/subagents/subagent-manager.skill-eager-review.test.ts @@ -118,7 +118,7 @@ describe('nested agents retain their actual Skill availability', () => { observed.canInvokeSkill(declared), `invocation at depth ${depth}`, ) - .toBe(directlyInvokable); + .toBe(reachable); expect .soft( resolveAgentDelegationSurface(context), From 89bc7556f5c0f1c96060a9e13143fb7e91dc1173 Mon Sep 17 00:00:00 2001 From: qwen-code-autofix Date: Thu, 12 Nov 2026 14:14:06 +0000 Subject: [PATCH 44/49] style(cli): restore trailing newline in must-translate test Co-authored-by: Qwen-Coder --- packages/cli/src/i18n/mustTranslateKeys.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/i18n/mustTranslateKeys.test.ts b/packages/cli/src/i18n/mustTranslateKeys.test.ts index 3579628b174..aae95168eb9 100644 --- a/packages/cli/src/i18n/mustTranslateKeys.test.ts +++ b/packages/cli/src/i18n/mustTranslateKeys.test.ts @@ -234,4 +234,4 @@ describe('must-translate locale coverage', () => { }, SLOW_LOCALE_TEST_TIMEOUT_MS, ); -}); \ No newline at end of file +}); From a111c369a662083a9ea70c2550126c9ee60b4595 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Thu, 12 Nov 2026 20:53:43 +0000 Subject: [PATCH 45/49] fix(core): keep display_image out of fork exec bounds (#11854) Co-authored-by: Qwen-Coder --- packages/core/src/tools/agent/agent.test.ts | 24 +++++++++++++++---- packages/core/src/tools/agent/agent.ts | 4 +++- .../src/tools/agent/fork-subagent.test.ts | 9 +++++++ .../core/src/tools/agent/fork-subagent.ts | 23 ++++++++++-------- 4 files changed, 44 insertions(+), 16 deletions(-) diff --git a/packages/core/src/tools/agent/agent.test.ts b/packages/core/src/tools/agent/agent.test.ts index db19a3afa64..5f474b025d2 100644 --- a/packages/core/src/tools/agent/agent.test.ts +++ b/packages/core/src/tools/agent/agent.test.ts @@ -4368,18 +4368,32 @@ describe('AgentTool', () => { expect(allowed()).toEqual([]); }); - it.each([ToolMode.CodeMode, ToolMode.CodeModeOnly])( - 'deny-all fork_tools closes the exec route in %s', - async (mode) => { + it.each([ + { mode: ToolMode.CodeMode, forkTools: [] as string[] }, + { mode: ToolMode.CodeMode, forkTools: [ToolNames.DISPLAY_IMAGE] }, + { mode: ToolMode.CodeModeOnly, forkTools: [] as string[] }, + { mode: ToolMode.CodeModeOnly, forkTools: [ToolNames.DISPLAY_IMAGE] }, + ])( + 'deny-all fork_tools closes the exec route in $mode ($forkTools)', + async ({ mode, forkTools }) => { config.getToolMode = vi.fn().mockReturnValue(mode); - parentTools(readSearchCall, [...bridged()]); + parentTools( + forkTools.length === 0 + ? readSearchCall + : [ + [ToolNames.READ_FILE, 'Read a file'], + [ToolNames.DISPLAY_IMAGE, 'Display an image'], + ], + [...bridged(), ToolNames.DISPLAY_IMAGE], + ); await runFork( forkParams('deny all tools', { prompt: 'reason without tools', - fork_tools: [], + fork_tools: forkTools, }), ); expect(allowed()).toEqual([]); + expect(toolConfig()?.nestedExecutionAllowedTools).toEqual([]); // Drive the captured child toolConfig through a real AgentCore: the // empty execution allowlist must close the exec route in both code // modes, at the declaration surface and at the admission gate. diff --git a/packages/core/src/tools/agent/agent.ts b/packages/core/src/tools/agent/agent.ts index 1df00e4ec6c..4fe9a9e8507 100644 --- a/packages/core/src/tools/agent/agent.ts +++ b/packages/core/src/tools/agent/agent.ts @@ -2125,7 +2125,9 @@ class AgentToolInvocation extends BaseToolInvocation { getCurrentCodeModeAllowedNames() ?? defaultExecutionToolNames, true, ).filter( - (toolName) => getToolExposure(toolName) === 'code-mode-callable', + (toolName) => + toolName !== ToolNames.DISPLAY_IMAGE && + getToolExposure(toolName) === 'code-mode-callable', ) : undefined; const requestedExecutionAllowedTools = diff --git a/packages/core/src/tools/agent/fork-subagent.test.ts b/packages/core/src/tools/agent/fork-subagent.test.ts index bd9ab9199a6..8f7907358f8 100644 --- a/packages/core/src/tools/agent/fork-subagent.test.ts +++ b/packages/core/src/tools/agent/fork-subagent.test.ts @@ -74,6 +74,15 @@ describe('resolveForkExecutionAllowedTools', () => { ).toEqual([ToolNames.READ_FILE, ToolNames.EDIT, ToolNames.GLOB]); }); + it('filters display_image from an explicit allowlist the parent does not advertise', () => { + expect( + resolveForkExecutionAllowedTools( + [ToolNames.READ_FILE], + [ToolNames.DISPLAY_IMAGE, ToolNames.READ_FILE], + ), + ).toEqual([ToolNames.READ_FILE]); + }); + it('cannot re-enable display_image through fork_tools', () => { expect( resolveForkExecutionAllowedTools(parentTools, [ diff --git a/packages/core/src/tools/agent/fork-subagent.ts b/packages/core/src/tools/agent/fork-subagent.ts index 1dc1853df53..c6d95eacf1a 100644 --- a/packages/core/src/tools/agent/fork-subagent.ts +++ b/packages/core/src/tools/agent/fork-subagent.ts @@ -73,19 +73,22 @@ export function resolveForkExecutionAllowedTools( advertisedToolNames: readonly string[], requestedToolNames: readonly string[] | undefined, ): string[] | undefined { + // display_image is main-session-only, so an explicit list must never keep + // it executable, whether or not the parent advertises it. + const executableToolNames = requestedToolNames?.filter( + (name) => name !== ToolNames.DISPLAY_IMAGE, + ); if (!advertisedToolNames.includes(ToolNames.DISPLAY_IMAGE)) { - return requestedToolNames ? [...requestedToolNames] : undefined; + return executableToolNames; } - // display_image is main-session-only. "Unrestricted" (undefined) minus - // display_image cannot be written as a finite allowlist, so fail closed to - // deny-all instead of returning undefined — that would hand the fork - // unrestricted execution, including the very tool this strips. Every live - // caller passes a concrete list (buildForkExecutionAllowlist always returns - // an array); DisplayImageInvocation.execute() also enforces this locally. - return ( - requestedToolNames?.filter((name) => name !== ToolNames.DISPLAY_IMAGE) ?? [] - ); + // "Unrestricted" (undefined) minus display_image cannot be written as a + // finite allowlist, so fail closed to deny-all instead of returning + // undefined — that would hand the fork unrestricted execution, including + // the very tool this strips. Every live caller passes a concrete list + // (buildForkExecutionAllowlist always returns an array); + // DisplayImageInvocation.execute() also enforces this locally. + return executableToolNames ?? []; } /** From d4f5a76d45244cd5968d2d3445fbd72f3cd9afc3 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Fri, 13 Nov 2026 03:32:05 +0000 Subject: [PATCH 46/49] test(core): align AgentCore tool-registry mocks with merged policy Co-authored-by: Qwen-Coder --- packages/core/src/agents/runtime/agent-core.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/core/src/agents/runtime/agent-core.test.ts b/packages/core/src/agents/runtime/agent-core.test.ts index 0d3609b2193..b0b1788dc9a 100644 --- a/packages/core/src/agents/runtime/agent-core.test.ts +++ b/packages/core/src/agents/runtime/agent-core.test.ts @@ -861,6 +861,7 @@ describe.each(LOOPS)( const config = { getToolRegistry: vi.fn().mockReturnValue({ getTool: vi.fn(), + getAllToolNames: vi.fn().mockReturnValue([]), }), getDebugLogger: vi .fn() @@ -1128,6 +1129,7 @@ describe.each(LOOPS)( available && toolName === name ? { serverName: 'catalog', serverToolName: 'lookup' } : undefined, + getAllToolNames: () => [], }), getSkipLoopDetection: () => true, getMaxToolCallsPerTurn: () => 100, From f42a1c543a979231d24db2f54632427b3bc24695 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Fri, 13 Nov 2026 11:46:49 +0000 Subject: [PATCH 47/49] test(managed-agent): align versioning retry count with main (#11854) The fast-tier H2 suite failed transientReadsRecoverWithTheRealSdk[4] and [5] with "expected: 3 but was: 2". The versioning probe runs once in the store constructor and is retried once by the SDK, so a single fault yields two wire requests; main corrected this assertion in 7de5501299, which this branch merged main before. --- .../persistence/AliyunToolPublicationReadRetryTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/managed-agent-server/verification/src/test/java/com/alibaba/qwen/code/managedagent/persistence/AliyunToolPublicationReadRetryTest.java b/packages/managed-agent-server/verification/src/test/java/com/alibaba/qwen/code/managedagent/persistence/AliyunToolPublicationReadRetryTest.java index b8b563a30e7..971bbe5ad52 100644 --- a/packages/managed-agent-server/verification/src/test/java/com/alibaba/qwen/code/managedagent/persistence/AliyunToolPublicationReadRetryTest.java +++ b/packages/managed-agent-server/verification/src/test/java/com/alibaba/qwen/code/managedagent/persistence/AliyunToolPublicationReadRetryTest.java @@ -31,7 +31,7 @@ void transientReadsRecoverWithTheRealSdk(String operation, int status, String co try (var input = objects.open("key")) { assertThat(input.readAllBytes()).isEqualTo("payload".getBytes(StandardCharsets.UTF_8)); } - assertThat(fixture.attempts.get()).isEqualTo(operation.equals("versioning") ? 3 : 2); + assertThat(fixture.attempts.get()).isEqualTo(2); } } From 119999a80ec777f021f97cda82fa93372e1846b5 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Fri, 13 Nov 2026 12:27:33 +0000 Subject: [PATCH 48/49] chore(web-shell): regenerate NOTICES for current dependency tree (#11854) Co-authored-by: Qwen-Coder --- packages/web-shell/NOTICES.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/web-shell/NOTICES.txt b/packages/web-shell/NOTICES.txt index b6ee3bedaa5..aee843566aa 100644 --- a/packages/web-shell/NOTICES.txt +++ b/packages/web-shell/NOTICES.txt @@ -6917,7 +6917,7 @@ SOFTWARE. ============================================================ -qs@6.16.0 +qs@6.17.1 (https://github.com/ljharb/qs.git) BSD 3-Clause License @@ -11187,7 +11187,7 @@ terms above. ============================================================ -dompurify@3.4.14 +dompurify@3.4.17 (git://github.com/cure53/DOMPurify.git) From 4f4e85b5d6d051ca3685fc7be933751e075477f8 Mon Sep 17 00:00:00 2001 From: qwen-code-dev-bot Date: Sat, 14 Nov 2026 09:38:31 +0000 Subject: [PATCH 49/49] fix(core): reach an eager-hidden skill through a declared bridge (#11854) Co-authored-by: Qwen-Coder --- .../runtime/agent-core.skill-gate.test.ts | 41 +++++++++++++ .../runtime/subagent-plan-tool-policy.test.ts | 61 +++++++++++++++++++ .../runtime/subagent-plan-tool-policy.ts | 17 ++++-- 3 files changed, 115 insertions(+), 4 deletions(-) diff --git a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts index a6b6e91cb39..25b43943a6d 100644 --- a/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts +++ b/packages/core/src/agents/runtime/agent-core.skill-gate.test.ts @@ -482,6 +482,47 @@ describe('AgentCore skill-gate inputs', () => { expect(gate(core, declared)).toBe(true); }); + it('keeps an eager-hidden Skill reachable for an agent declaring only the bridge', async () => { + // A finite list naming both halves reaches the demoted Skill exactly as + // the wildcard does; withholding the listing and the Skill factory here + // would take away a capability the activation gate still opens. + const config = makeFakeConfig({ toolMode: ToolMode.CodeMode }); + const registry = new ToolRegistry(config); + vi.spyOn(config, 'getToolRegistry').mockReturnValue(registry); + registry.registerTool(new ExecTool(config)); + registry.registerPermissionDeferredFactory( + ToolNames.SKILL, + async () => new MockTool({ name: ToolNames.SKILL }), + ); + registry.registerTool(new ToolSearchTool(config)); + registry.registerTool(new ToolCallTool(registry)); + const core = new AgentCore( + 'skill-eager-bridge-finite', + config, + { systemPrompt: '' }, + { model: 'test-model' }, + { max_turns: 1 }, + { + tools: [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL], + executionAllowedTools: [ + ToolNames.SKILL, + ToolNames.TOOL_SEARCH, + ToolNames.TOOL_CALL, + ], + }, + ); + expect( + ( + core as unknown as { willHaveSkillTool: () => boolean } + ).willHaveSkillTool(), + ).toBe(true); + const declared = await declaredNames(core); + expect(declared.has(ToolNames.TOOL_SEARCH)).toBe(true); + expect(declared.has(ToolNames.TOOL_CALL)).toBe(true); + expect(declared.has(ToolNames.SKILL)).toBe(false); + expect(gate(core, declared)).toBe(true); + }); + it('refuses the bridge route under CodeModeOnly, where tool_call is hidden', () => { const config = makeFakeConfig({ toolMode: ToolMode.CodeModeOnly }); const registry = new ToolRegistry(config); diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts index 21e977e8a12..c339b185c8a 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.test.ts @@ -354,6 +354,67 @@ describe('subagent plan tool policy', () => { expect( toolConfigAllowsSkill({ tools: ['*'] }, false, true, false, true, true), ).toBe(true); + // A finite list naming only the two bridge halves reaches the demoted + // Skill: AgentCore.canInvokeSkill answers true for this shape. + expect( + toolConfigAllowsSkill( + { + tools: [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL], + executionAllowedTools: [ + ToolNames.SKILL, + ToolNames.TOOL_SEARCH, + ToolNames.TOOL_CALL, + ], + }, + false, + true, + false, + true, + true, + ), + ).toBe(true); + }); + + it('vetoes an eager-hidden Skill the bridge cannot invoke', () => { + const bridgeConfig = { + tools: [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL], + executionAllowedTools: [ + ToolNames.SKILL, + ToolNames.TOOL_SEARCH, + ToolNames.TOOL_CALL, + ], + }; + // The per-agent blocklist still filters the resolved target. + expect( + toolConfigAllowsSkill( + { ...bridgeConfig, disallowedTools: [ToolNames.SKILL] }, + false, + true, + false, + true, + true, + ), + ).toBe(false); + // Without an explicit execution allowlist the finite tools list is the + // allowlist, so a bridge-only list does not admit the resolved Skill. + expect( + toolConfigAllowsSkill( + { tools: [ToolNames.TOOL_SEARCH, ToolNames.TOOL_CALL] }, + false, + true, + false, + true, + true, + ), + ).toBe(false); + // The bridge cannot invoke a Skill the registry never registered. + expect( + toolConfigAllowsSkill(bridgeConfig, false, true, false, false, true), + ).toBe(false); + // CodeModeOnly hides and refuses tool_call, so the bridge is no route. + expect( + toolConfigAllowsSkill(bridgeConfig, false, true, true, true, true), + ).toBe(false); }); it('vetoes an eager-hidden Skill the bridge cannot reach', () => { diff --git a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts index ccb0d637dac..1bb8a2cd5e1 100644 --- a/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts +++ b/packages/core/src/agents/runtime/subagent-plan-tool-policy.ts @@ -267,11 +267,20 @@ export function toolConfigAllowsSkill( toolConfig.executionAllowedTools.includes(toolName)) && (inheritsRegistry || names.includes(toolName)), (toolName) => - toolConfig?.executionAllowedTools === undefined || - toolConfig.executionAllowedTools.includes(toolName), + skillRegistered && + !matchesAgentToolBlocklist(toolConfig?.disallowedTools, toolName) && + // Without an explicit execution allowlist the finite `tools` list is + // the allowlist, exactly as `AgentCore.isToolExecutionAllowed` reads + // it; a wildcard or absent config inherits the registry. + (toolConfig?.executionAllowedTools !== undefined + ? toolConfig.executionAllowedTools.includes(toolName) + : inheritsRegistry || names.includes(toolName)), ); - if (skillEagerHidden && !bridgeReachesSkill) { - return false; + if (skillEagerHidden) { + // Outside CodeModeOnly both bridge halves keep an eager-hidden Skill + // loadable. CodeModeOnly hides and refuses `tool_call`, so the bridge is + // not a route there. + return bridgeReachesSkill && !codeModeOnly; } // exec binds only registered tools, so a registry without the Skill // factory (a deny rule or a legacy coreTools allowlist keeps it out, or a