chatccc 0.2.305 → 0.2.307

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,7 @@ ChatCCC 把本地 AI 编程工具接入即时通讯软件。你可以在手机
23
23
  - **微信接入更轻**:不用创建飞书应用,启动后扫码即可在微信私聊里使用。
24
24
  - **多 Agent 切换**:`/new` 使用默认 Agent,也可以用 `/new claude`、`/new cursor`、`/new codex`、`/new ccc`、`/new dsh` 指定工具。
25
25
  - **群里能跑 git**:`/git status`、`/git pull`、`/git log` 会在当前会话工作目录执行,并把输出发回聊天窗口。
26
- - **飞书混合附件不丢失**:同一条富文本中的文字、图片、视频和文件按顺序传给 Agent;视频保留原附件下载信息,不把封面误当成原视频。附件信息不完整时会明确提示。视频和文件仍由 Agent 按需下载处理,不代表模型原生支持视频输入。
26
+ - **飞书混合附件不丢失**:同一条富文本中的标题、文字、图片、视频和文件传给 Agent,兼容正文为空但标题和顶层 `files` 有内容的组合消息;保留正文顺序,顶层附件按原顺序补在正文后,并按文件 key 避免与内联附件重复。正文为空时兼容 `content_v2`,无法识别的富文本给出明确提示,不再静默忽略。视频保留原附件下载信息,不把封面误当成原视频。附件信息不完整时会明确提示。视频和文件仍由 Agent 按需下载处理,不代表模型原生支持视频输入。
27
27
 
28
28
  ## 飞书和微信的差异
29
29
 
@@ -165,7 +165,7 @@ Web UI 支持新建、恢复、重命名和删除多会话,多个会话可以
165
165
 
166
166
  图片会转换成模型可见的原生视觉输入。Web 支持选择、粘贴和拖拽 PNG/JPEG/WebP/GIF;CLI 可用 `--image` 或交互命令 `/image`。每条消息最多 10 张、单图最大 20 MiB、图片合计最大 24 MiB,单边最多 8192 像素;超限时提示分图或缩小,保留原图细节。附件复制到 `~/.deepccc/attachments/<session-id>/`,聊天历史只保存引用,raw 日志过滤图片编码。删除 Web 会话时附件一并清理。
167
167
 
168
- 默认由当前模型直接看图。若主模型不支持视觉,可在 API 设置中指定 `visionModel`(如 `deepseek-flash`),或设置 `DEEPCCC_VISION_MODEL` / CLI `--vision-model`;该模型使用同一 API 协议、Base URL 和 Key,先分析图片,再由主模型结合观察继续任务。界面及 JSONL 会显示实际图片模型和模式。未配置图片模型的 `deepseek-v4-pro` 收图会明确报错;其他兼容模型需服务端支持图像,接口错误不会降级成“假装看过”。官方 DeepSeek 端点的旧 Flash 名称仅在视觉请求中映射到当前 `deepseek-flash`,自定义网关保留用户配置的名称。
168
+ 识图模型未配置或为空白时,跟随当前会话实际主模型,包括 CLI --model 的覆盖值;子代理没有显式识图配置时跟随自身实际主模型,显式配置则继续继承。若主模型不支持视觉,可在 API 设置中指定 `visionModel`(如 `deepseek-flash`),或设置 `DEEPCCC_VISION_MODEL` / CLI `--vision-model`;该模型使用同一 API 协议、Base URL 和 Key,先分析图片,再由主模型结合观察继续任务。界面及 JSONL 会显示实际图片模型和模式。未配置图片模型的 `deepseek-v4-pro` 收图会明确报错;其他兼容模型需服务端支持图像,接口错误不会降级成“假装看过”。官方 DeepSeek 端点的旧 Flash 名称仅在视觉请求中映射到当前 `deepseek-flash`,自定义网关保留用户配置的名称。
169
169
 
170
170
  Agent 可用 `read_image` 查看本地截图、图表或工具产物,并通过 `question` 指定需要观察的细节;`present_file` 用于把图片展示给用户。后续追问会按预算重新加载近期图片;较早图片保留路径供 `read_image` 重新查看。独立图片模型的观察按原文问题、模型、端点与图片内容哈希缓存;细节追问可重新调用 `read_image`。压缩后的摘要应保留重要图片引用,缺失或损坏图片会明确报错。本版本支持图片输入,不包含音频、视频或 PDF 原生输入。
171
171
 
@@ -197,6 +197,9 @@ Provider 发送 `max_tokens`,使用模型服务端默认值。可通过 `DEEPC
197
197
  API 拒绝(context length exceeded),实际窗口以模型与所用服务端为准(如 litellm 的
198
198
  `max_input_tokens`)。
199
199
 
200
+ 同一轮连续工具调用也有独立的结果重放预算。较早的简短成功回执、JSON 结果和错误信息,
201
+ 若比省略提示更短,会保留原结果;较大的结果仍按预算截断或省略,工具调用关联保持不变。
202
+
200
203
  `subModel` 是子模型(选填),默认 `""`(留空跟随主模型)。配置后,DeepCCC 内部的轻量
201
204
  环节——上下文压缩摘要生成、`task` 子代理任务——使用子模型执行,主对话仍用主模型。
202
205
  典型用法:主模型用 pro 承担复杂推理,子模型用 flash 做高频廉价的摘要与子任务。
@@ -354,6 +357,8 @@ deepccc-cli --dangerously-bypass-permissions
354
357
 
355
358
  持久化上下文达到常规 token 阈值或独立工具预算时,deepccc 会先按预算保留最近消息,再压缩较早内容;工具历史使用标准结构化 tool-call/tool-result 消息重放,不会把内部 `[工具记录]` 文本重复送回模型。若模型仍输出伪工具记录,系统会丢弃并重试一次;重复失败时安全终止,避免把未执行命令当成真实结果。超长历史消息、工具记录和压缩输入会被限长,一次压缩最多等待 5 分钟。
356
359
 
360
+ 持久化工具记录在总量受限时优先完整保留短参数和短结果,再分配长载荷预算,避免子代理句柄、路径或退出状态被长正文挤成无效 JSON。task、task_output 和 task_stop 在创建或查找任务前校验必需参数;错误的 raw 包装或缺失句柄会返回具体参数提示,不产生额外子任务。
361
+
357
362
  如果终端渲染出现异常,可以强制回退为纯文本流式输出:
358
363
 
359
364
  ```bash
@@ -460,6 +465,23 @@ deepccc 的内核主战场在 ChatCCC 仓库的 `deepccc-agent/` 子目录;本
460
465
 
461
466
  三个命令工具都支持独立 `cwd`、超时、取消、输出限长和运行中消息让位;返回非零退出码时不会直接被当成工具异常,模型可以读取结构化结果继续判断。Windows 下 `run_command` 会拒绝多行或嵌套同类引号的复杂 Python/Node 内联代码,并提示改用 `run_script`。
462
467
 
468
+ 命令工具及后台命令查询/终止会先检查必需的命名参数。误把参数放进 `raw`、传 JSON 字符串或缺少必需字段时,会在权限处理与进程操作前返回明确的入参错误;有效脚本里的 JSON 内容保持原样,不会被当作参数重新解析。
469
+
463
470
  ## License
464
471
 
465
472
  Apache-2.0
473
+ ### Per-invocation tool allowlist
474
+
475
+ For a bounded task, expose only the builtin tools it needs:
476
+
477
+ ```sh
478
+ deepccc-cli --stream-json --allowed-tools read_file,create_file,run_script --prompt "Read the specified files and save the result."
479
+ ```
480
+
481
+ The SDK equivalent is `new ChatSession(config, { allowedTools: ["read_file", "run_script"] })`.
482
+ Omitting the option keeps the existing full tool set; the SDK also accepts `[]` for no tools.
483
+ Unknown tool names are rejected before model generation. Automatic workspace navigation is skipped
484
+ when `workspace_map` is outside the allowlist, and child tasks inherit the same tool restriction.
485
+ The option applies to that invocation, so pass it again when resuming. Existing permission checks
486
+ still apply. This limits tool exposure and execution, not filesystem/network access inside an allowed
487
+ script or process tool; it is not a sandbox.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deepccc",
3
- "version": "0.2.29",
3
+ "version": "0.2.33",
4
4
  "description": "A lightweight coding agent with OpenAI-compatible and Anthropic Messages API support.",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -25,6 +25,7 @@ import { TerminalProgressRenderer } from "./progress/terminal-renderer.js";
25
25
  import { progressView } from "./progress/view.js";
26
26
  import { defaultLogDir, setupFileLogging } from "./file-log.js";
27
27
  import { AttachmentStore, buildAttachmentPrompt } from "./attachments.js";
28
+ import { normalizeAllowedTools } from "./tool-selection.js";
28
29
  function parsePositiveIntegerOption(name, value) {
29
30
  const parsed = Number(value);
30
31
  if (!Number.isInteger(parsed) || parsed <= 0) {
@@ -91,6 +92,13 @@ function parseArgs(argv = process.argv.slice(2)) {
91
92
  options.maxSteps = parsePositiveIntegerOption("--max-steps", next);
92
93
  i++;
93
94
  }
95
+ else if (arg === "--allowed-tools") {
96
+ if (next === undefined || next.startsWith("--")) {
97
+ throw new Error("--allowed-tools requires a comma-separated list of tool names");
98
+ }
99
+ options.allowedTools = normalizeAllowedTools(next.split(","));
100
+ i++;
101
+ }
94
102
  else if (arg === "--resume") {
95
103
  if (next !== undefined && !next.startsWith("--")) {
96
104
  resume = next;
@@ -151,6 +159,7 @@ function printHelp(appConfig) {
151
159
  " --api-key <key> API key",
152
160
  " --cwd <path> Working directory",
153
161
  " --max-steps <n> Optional tool-step limit. Omit for no step limit",
162
+ " --allowed-tools <names> Comma-separated builtin tool allowlist for this invocation",
154
163
  " --resume [id] Resume latest cwd session, or the explicit session id",
155
164
  " --list-sessions List saved sessions and exit",
156
165
  " --stream-json One-shot mode: write JSONL events to stdout",
@@ -297,6 +297,8 @@ export function serializeMessagesForSummary(messages) {
297
297
  function truncateMiddle(value, maxChars, marker) {
298
298
  if (value.length <= maxChars)
299
299
  return value;
300
+ if (maxChars <= marker.length + 2)
301
+ return value.slice(0, Math.max(0, maxChars));
300
302
  const available = Math.max(0, maxChars - marker.length - 2);
301
303
  const headChars = Math.ceil(available / 2);
302
304
  const tailChars = Math.floor(available / 2);
@@ -306,16 +308,31 @@ export const DEFAULT_PERSISTED_ASSISTANT_TEXT_CHARS = 32_000;
306
308
  export const DEFAULT_PERSISTED_TOOL_TRANSCRIPT_CHARS = 24_000;
307
309
  const ASSISTANT_TRUNCATED_MARKER = "...[助手回复已在上下文中截断]...";
308
310
  const TOOL_TRANSCRIPT_TRUNCATED_MARKER = "...[工具记录已截断]...";
311
+ /** Reserve short control records before sharing the remaining space with large payloads. */
312
+ function toolPayloadBudgets(lengths, maximum) {
313
+ const budgets = Array(lengths.length).fill(0);
314
+ const ordered = lengths.map((length, index) => ({ length, index }))
315
+ .sort((a, b) => a.length - b.length);
316
+ let remaining = Math.max(0, Math.floor(maximum));
317
+ for (let index = 0; index < ordered.length; index += 1) {
318
+ const entry = ordered[index];
319
+ const budget = Math.min(entry.length, Math.floor(remaining / (ordered.length - index)));
320
+ budgets[entry.index] = budget;
321
+ remaining -= budget;
322
+ }
323
+ return budgets;
324
+ }
309
325
  function truncateStructuredToolCalls(calls, maxChars) {
310
326
  const payloads = calls.flatMap((call) => [call.input ?? "", call.output ?? ""]).filter(Boolean);
311
327
  const total = payloads.reduce((sum, value) => sum + value.length, 0);
312
328
  if (total <= maxChars)
313
329
  return calls;
314
- const sharedBudget = Math.max(0, maxChars - payloads.length);
330
+ const budgets = toolPayloadBudgets(payloads.map(value => value.length), maxChars);
331
+ let payloadIndex = 0;
315
332
  const truncatePayload = (value) => {
316
333
  if (value === undefined || value.length === 0)
317
334
  return value;
318
- const budget = 1 + Math.floor(sharedBudget * value.length / Math.max(1, total));
335
+ const budget = budgets[payloadIndex++];
319
336
  return truncateMiddle(value, budget, TOOL_TRANSCRIPT_TRUNCATED_MARKER);
320
337
  };
321
338
  return calls.map((call) => ({
@@ -346,15 +363,10 @@ function truncatePersistedTimeline(entries) {
346
363
  const maxToolChars = DEFAULT_PERSISTED_TOOL_TRANSCRIPT_CHARS;
347
364
  const totalText = entries.reduce((sum, entry) => sum + (entry.type === "text" ? entry.text.length : 0), 0);
348
365
  const textPayloads = entries.filter((entry) => entry.type === "text" && entry.text.length > 0).length;
349
- const totalTool = entries.reduce((sum, entry) => {
350
- if (entry.type === "tool_use")
351
- return sum + (entry.input?.length ?? 0);
352
- if (entry.type === "tool_result")
353
- return sum + (entry.output?.length ?? 0);
354
- return sum;
355
- }, 0);
356
- const toolPayloads = entries.filter((entry) => (entry.type === "tool_use" && (entry.input?.length ?? 0) > 0)
357
- || (entry.type === "tool_result" && (entry.output?.length ?? 0) > 0)).length;
366
+ const toolPayloads = entries.flatMap(entry => entry.type === "tool_use" && entry.input
367
+ ? [entry.input] : entry.type === "tool_result" && entry.output ? [entry.output] : []);
368
+ const toolBudgets = toolPayloadBudgets(toolPayloads.map(value => value.length), maxToolChars);
369
+ let toolPayloadIndex = 0;
358
370
  const payloadBudget = (length, total, count, maximum) => {
359
371
  if (total <= maximum)
360
372
  return length;
@@ -374,11 +386,11 @@ function truncatePersistedTimeline(entries) {
374
386
  return { ...entry, text: truncatePayload(entry.text, budget, ASSISTANT_TRUNCATED_MARKER) };
375
387
  }
376
388
  if (entry.type === "tool_use" && entry.input !== undefined) {
377
- const budget = payloadBudget(entry.input.length, totalTool, toolPayloads, maxToolChars);
389
+ const budget = entry.input.length ? toolBudgets[toolPayloadIndex++] : 0;
378
390
  return { ...entry, input: truncatePayload(entry.input, budget, TOOL_TRANSCRIPT_TRUNCATED_MARKER) };
379
391
  }
380
392
  if (entry.type === "tool_result" && entry.output !== undefined) {
381
- const budget = payloadBudget(entry.output.length, totalTool, toolPayloads, maxToolChars);
393
+ const budget = entry.output.length ? toolBudgets[toolPayloadIndex++] : 0;
382
394
  return { ...entry, output: truncatePayload(entry.output, budget, TOOL_TRANSCRIPT_TRUNCATED_MARKER) };
383
395
  }
384
396
  return entry;
@@ -1449,6 +1449,7 @@ function startBackgroundTask(runTask, input, parentSignal) {
1449
1449
  return { taskId, running: true };
1450
1450
  }
1451
1451
  export async function taskOutputForTool(input) {
1452
+ requireCommandArguments("task_output", input, ["taskId"]);
1452
1453
  const entry = backgroundTasks.get(input.taskId);
1453
1454
  if (!entry)
1454
1455
  throw new Error(`未知的后台子代理:${input.taskId}`);
@@ -1456,6 +1457,7 @@ export async function taskOutputForTool(input) {
1456
1457
  return snapshotBackgroundTask(entry);
1457
1458
  }
1458
1459
  export async function taskStopForTool(input) {
1460
+ requireCommandArguments("task_stop", input, ["taskId"]);
1459
1461
  const entry = backgroundTasks.get(input.taskId);
1460
1462
  if (!entry)
1461
1463
  throw new Error(`未知的后台子代理:${input.taskId}`);
@@ -1474,6 +1476,15 @@ export function killAllBackgroundTasks() {
1474
1476
  }
1475
1477
  backgroundTasks.clear();
1476
1478
  }
1479
+ function requireCommandArguments(name, input, requiredStrings, allowEmpty = []) {
1480
+ const value = input && typeof input === "object" && !Array.isArray(input)
1481
+ ? input : undefined;
1482
+ if (!value || requiredStrings.some((key) => typeof value[key] !== "string"
1483
+ || (!allowEmpty.includes(key) && !value[key].trim()))) {
1484
+ throw new Error(`Invalid ${name} arguments: expected a structured object with string fields ${requiredStrings.join(", ")}. `
1485
+ + "Pass these named fields directly; do not wrap the arguments in raw or a JSON string.");
1486
+ }
1487
+ }
1477
1488
  export function createBuiltinFileTools(cwd, options = {}) {
1478
1489
  const gate = options.permissionGate;
1479
1490
  const runTask = options.runTask;
@@ -1601,6 +1612,7 @@ export function createBuiltinFileTools(cwd, options = {}) {
1601
1612
  required: ["executable"],
1602
1613
  }),
1603
1614
  execute: async (input, execOptions) => {
1615
+ requireCommandArguments("run_process", input, ["executable"]);
1604
1616
  const action = [input.executable, ...(input.args ?? [])].join(" ");
1605
1617
  await guard({
1606
1618
  tool: "run_process",
@@ -1631,6 +1643,10 @@ export function createBuiltinFileTools(cwd, options = {}) {
1631
1643
  required: ["language", "code"],
1632
1644
  }),
1633
1645
  execute: async (input, execOptions) => {
1646
+ requireCommandArguments("run_script", input, ["language", "code"], ["code"]);
1647
+ if (input.language !== "node" && input.language !== "python") {
1648
+ throw new Error("Invalid run_script arguments: language must be node or python.");
1649
+ }
1634
1650
  const runtime = input.executable?.trim() || input.language;
1635
1651
  await guard({
1636
1652
  tool: "run_script",
@@ -1654,6 +1670,7 @@ export function createBuiltinFileTools(cwd, options = {}) {
1654
1670
  required: ["command"],
1655
1671
  }),
1656
1672
  execute: async (input, execOptions) => {
1673
+ requireCommandArguments("run_command", input, ["command"]);
1657
1674
  await guard({
1658
1675
  tool: "run_command",
1659
1676
  action: input.command,
@@ -1674,7 +1691,10 @@ export function createBuiltinFileTools(cwd, options = {}) {
1674
1691
  },
1675
1692
  required: ["taskId"],
1676
1693
  }),
1677
- execute: (input) => commandOutputForTool(input.taskId, input, options.shouldYieldToInjection),
1694
+ execute: async (input) => {
1695
+ requireCommandArguments("command_output", input, ["taskId"]);
1696
+ return commandOutputForTool(input.taskId, input, options.shouldYieldToInjection);
1697
+ },
1678
1698
  }),
1679
1699
  command_kill: tool({
1680
1700
  description: "终止一个由 run_process、run_script 或 run_command 转入后台的进程。",
@@ -1686,7 +1706,10 @@ export function createBuiltinFileTools(cwd, options = {}) {
1686
1706
  },
1687
1707
  required: ["taskId"],
1688
1708
  }),
1689
- execute: (input) => commandKillForTool(input.taskId),
1709
+ execute: async (input) => {
1710
+ requireCommandArguments("command_kill", input, ["taskId"]);
1711
+ return commandKillForTool(input.taskId);
1712
+ },
1690
1713
  }),
1691
1714
  task: tool({
1692
1715
  description: `把独立子任务委派给子代理执行:子代理使用子模型、拥有独立上下文,不污染主对话上下文。可用 maxSteps 指定 ${MIN_TASK_MAX_STEPS}-${MAX_TASK_MAX_STEPS} 步预算。默认同步等待;runInBackground=true 时立即返回 taskId,之后用 task_output 查看或 task_stop 要求其停止调查并总结。子代理不能再次委派任务(禁止嵌套),结果会截断回传。`,
@@ -1710,6 +1733,7 @@ export function createBuiltinFileTools(cwd, options = {}) {
1710
1733
  required: ["description"],
1711
1734
  }),
1712
1735
  execute: async (input, execOptions) => {
1736
+ requireCommandArguments("task", input, ["description"]);
1713
1737
  if (!runTask) {
1714
1738
  throw new Error("task 工具不可用:当前环境未启用子代理执行器");
1715
1739
  }
@@ -15,6 +15,7 @@ import { createRawStreamLog, } from "./raw-stream-log.js";
15
15
  import { buildPersistedAssistantMessage, buildSummaryPrompt, BuiltinContextManager, defaultBuiltinSessionId, } from "./context.js";
16
16
  import { createBuiltinFileTools, MAX_TASK_MAX_STEPS, MAX_TASK_OUTPUT_CHARS, MIN_TASK_MAX_STEPS, TASK_STOP_ABORT_REASON, } from "./file-tools.js";
17
17
  import { PermissionGate } from "./permissions.js";
18
+ import { normalizeAllowedTools, selectAllowedTools } from "./tool-selection.js";
18
19
  import { hasMalformedToolProtocolText, TOOL_PROTOCOL_RECOVERY_PROMPT, } from "./tool-protocol.js";
19
20
  import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs, } from "./skills.js";
20
21
  import { applyPrivacy, applyPrivacyToJson } from "./privacy.js";
@@ -284,6 +285,7 @@ class InputInjectionInterrupt extends Error {
284
285
  }
285
286
  }
286
287
  export class ChatSession {
288
+ allowedTools;
287
289
  model;
288
290
  /** 子模型实例;未配置 subModel 时与主模型同一实例 */
289
291
  subModel;
@@ -293,6 +295,8 @@ export class ChatSession {
293
295
  modelId;
294
296
  subModelId;
295
297
  visionModelId;
298
+ /** Keep the optional override separate so each child can fall back to its own main model. */
299
+ configuredVisionModelId;
296
300
  imageRuntime;
297
301
  providerFactory;
298
302
  imageNotices = [];
@@ -370,7 +374,7 @@ export class ChatSession {
370
374
  apiKey: this.apiKey,
371
375
  baseURL: this.baseURL,
372
376
  model: this.subModelId || this.modelId,
373
- visionModel: this.visionModelId,
377
+ visionModel: this.configuredVisionModelId,
374
378
  effort: this.effort,
375
379
  maxOutputTokens: this.maxOutputTokens,
376
380
  }, {
@@ -381,6 +385,7 @@ export class ChatSession {
381
385
  maxSteps,
382
386
  compactionTimeoutMs: this.compactionTimeoutMs,
383
387
  skillsDirs: this.skillDirs.map((s) => s.dir),
388
+ allowedTools: this.allowedTools,
384
389
  });
385
390
  let full = "";
386
391
  for await (const event of child.chat(input.description, taskSignal)) {
@@ -416,7 +421,8 @@ export class ChatSession {
416
421
  const modelId = overrides.model ?? appConfig.model;
417
422
  this.modelId = modelId;
418
423
  this.subModelId = (overrides.subModel ?? appConfig.subModel ?? "").trim();
419
- this.visionModelId = (overrides.visionModel ?? appConfig.visionModel ?? "").trim();
424
+ this.configuredVisionModelId = (overrides.visionModel ?? appConfig.visionModel ?? "").trim();
425
+ this.visionModelId = this.configuredVisionModelId || modelId;
420
426
  this.provider = normalizeDeepCccProvider(overrides.provider ?? appConfig.provider);
421
427
  this.effort = (overrides.effort ?? appConfig.effort ?? "").trim();
422
428
  this.maxOutputTokens = normalizeMaxOutputTokens(overrides.maxOutputTokens ?? appConfig.maxOutputTokens);
@@ -439,6 +445,7 @@ export class ChatSession {
439
445
  // 子模型:留空时与主模型共用同一实例(行为与旧版完全一致,零开销)
440
446
  this.subModel = this.subModelId ? provider(this.subModelId) : this.model;
441
447
  this.cwd = options.cwd ?? process.cwd();
448
+ this.allowedTools = normalizeAllowedTools(options.allowedTools);
442
449
  this.maxSteps = normalizeMaxSteps(options.maxSteps);
443
450
  this.shouldYieldToInjection = options.shouldYieldToInjection;
444
451
  this.compactionTimeoutMs = Math.max(1, options.compactionTimeoutMs ?? DEFAULT_COMPACTION_TIMEOUT_MS);
@@ -522,6 +529,15 @@ export class ChatSession {
522
529
  const timeline = [];
523
530
  let toolContext = [];
524
531
  try {
532
+ // Validate/filter before compaction can contact a Provider. The same map
533
+ // controls both advertised definitions and SDK tool execution.
534
+ const tools = selectAllowedTools(createBuiltinFileTools(this.cwd, {
535
+ permissionGate: this.permissionGate,
536
+ runTask: this.runTask,
537
+ readImage: input => this.imageRuntime.readImage(input),
538
+ shouldYieldToInjection: this.shouldYieldToInjection,
539
+ gitCoAuthor: { ...appConfig.git.coAuthor, enabled: this.gitCoAuthorEnabled },
540
+ }), this.allowedTools);
525
541
  if (this.context.planCompaction()) {
526
542
  yield { type: "status", phase: "compacting" };
527
543
  const compactedMessages = await this.compactIfNeeded(signal);
@@ -554,7 +570,8 @@ export class ChatSession {
554
570
  const contextMessages = this.context.buildModelMessages();
555
571
  // Ephemeral navigation is refreshed from disk, not appended to persisted chat history.
556
572
  // A small budget keeps routine turns cheap; the tool remains available for any topic.
557
- if (needsWorkspaceOrientation(userMessage)) {
573
+ if ((this.allowedTools === undefined || this.allowedTools.includes("workspace_map"))
574
+ && needsWorkspaceOrientation(userMessage)) {
558
575
  try {
559
576
  const map = await buildWorkspaceMap(this.cwd, { query: userMessage.split("[User message]").pop(), maxChars: 3000, signal });
560
577
  contextMessages.splice(Math.max(0, contextMessages.length - 1), 0, {
@@ -592,16 +609,7 @@ export class ChatSession {
592
609
  const baseGenerationOptions = {
593
610
  model: this.model,
594
611
  system,
595
- tools: createBuiltinFileTools(this.cwd, {
596
- permissionGate: this.permissionGate,
597
- runTask: this.runTask,
598
- readImage: input => this.imageRuntime.readImage(input),
599
- shouldYieldToInjection: this.shouldYieldToInjection,
600
- gitCoAuthor: {
601
- ...appConfig.git.coAuthor,
602
- enabled: this.gitCoAuthorEnabled,
603
- },
604
- }),
612
+ tools,
605
613
  stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
606
614
  abortSignal: signal,
607
615
  prepareStep: async ({ messages, stepNumber }) => {
@@ -0,0 +1,19 @@
1
+ /** A per-invocation tool surface, not a filesystem/process sandbox. */
2
+ export function normalizeAllowedTools(value) {
3
+ if (value === undefined)
4
+ return undefined;
5
+ if (!Array.isArray(value) || value.some(name => typeof name !== "string" || !name.trim())) {
6
+ throw new Error("allowedTools must be an array of non-empty tool names");
7
+ }
8
+ return [...new Set(value.map(name => name.trim()))];
9
+ }
10
+ export function selectAllowedTools(tools, names) {
11
+ if (names === undefined)
12
+ return tools;
13
+ for (const name of names) {
14
+ if (!Object.prototype.hasOwnProperty.call(tools, name)) {
15
+ throw new Error(`Unknown allowed tool: ${name}`);
16
+ }
17
+ }
18
+ return Object.fromEntries(names.map(name => [name, tools[name]]));
19
+ }
@@ -72,7 +72,9 @@ export function compactToolLoopMessages(input, options = {}) {
72
72
  for (let index = prepared.length - keepRecent - 1; index >= 0; index -= 1) {
73
73
  const item = prepared[index];
74
74
  const delta = item.cappedSize - omittedSize;
75
- if (delta <= 0 || retainedToolChars + delta > maximum)
75
+ // A short status/error can cost less than the omission marker. Always
76
+ // restore such results: this retains evidence and reduces replay size.
77
+ if (delta > 0 && retainedToolChars + delta > maximum)
76
78
  continue;
77
79
  item.message.content[item.partIndex] = { ...item.part, output: item.capped };
78
80
  retainedToolChars += delta;
@@ -13,7 +13,8 @@ export async function formatMessageContent(message) {
13
13
  const contentStr = message.content ?? "{}";
14
14
  let content;
15
15
  try {
16
- content = JSON.parse(contentStr);
16
+ const parsed = JSON.parse(contentStr);
17
+ content = isPostRecord(parsed) ? parsed : {};
17
18
  }
18
19
  catch {
19
20
  // merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
@@ -32,7 +33,12 @@ export async function formatMessageContent(message) {
32
33
  return text.trim();
33
34
  }
34
35
  if (message.message_type === "post") {
35
- return formatPostContentWithAttachments(content, message.message_id);
36
+ const text = await formatPostContentWithAttachments(content, message.message_id);
37
+ if (text)
38
+ return text;
39
+ // Keep unsupported/empty rich posts visible instead of triggering the ingress empty-text drop.
40
+ console.warn(`[${ts()}] [POST] No readable content in rich-text message`);
41
+ return "[富文本消息暂无法解析,请将文字和附件分开发送]";
36
42
  }
37
43
  if (message.message_type === "image") {
38
44
  const imageKey = content.image_key;
@@ -69,35 +75,73 @@ export async function formatMessageContent(message) {
69
75
  return contentStr;
70
76
  }
71
77
  export function formatPostContent(content) {
72
- const paragraphs = getPostParagraphs(content);
73
- if (!Array.isArray(paragraphs))
74
- return "";
75
78
  const parts = [];
76
- for (const line of paragraphs) {
77
- if (!Array.isArray(line))
78
- continue;
79
- for (const elem of line) {
80
- const el = elem;
81
- if (!el || typeof el !== "object")
82
- continue;
83
- const text = formatPostTextElement(el);
84
- if (text)
85
- parts.push(text);
86
- }
79
+ for (const el of getPostElements(content)) {
80
+ const text = formatPostTextElement(el);
81
+ if (text)
82
+ parts.push(text);
87
83
  }
88
84
  return parts.join("\n").trim();
89
85
  }
90
- function getPostParagraphs(content) {
91
- const direct = content.content;
92
- if (Array.isArray(direct))
93
- return direct;
86
+ function isPostRecord(value) {
87
+ return value !== null && typeof value === "object" && !Array.isArray(value);
88
+ }
89
+ function getPostPayload(content) {
90
+ const hasFields = (value) => Array.isArray(value.content)
91
+ || Array.isArray(value.content_v2) || Array.isArray(value.files) || Boolean(attachmentString(value.title));
92
+ if (hasFields(content))
93
+ return content;
94
94
  for (const locale of ["zh_cn", "en_us", "ja_jp"]) {
95
95
  const localized = content[locale];
96
- if (localized && Array.isArray(localized.content)) {
97
- return localized.content;
98
- }
96
+ if (isPostRecord(localized) && hasFields(localized))
97
+ return localized;
99
98
  }
100
- return [];
99
+ return content;
100
+ }
101
+ /** Both formatters must preserve title-only/file-list posts as well as inline attachments. */
102
+ function getPostElements(content) {
103
+ const post = getPostPayload(content);
104
+ const flatten = (value) => Array.isArray(value)
105
+ ? value.flatMap(line => Array.isArray(line) ? line.filter(isPostRecord) : [])
106
+ : [];
107
+ const legacy = flatten(post.content);
108
+ // The API can return both versions; replaying both duplicates text and attachments.
109
+ const elements = legacy.length > 0 ? legacy : flatten(post.content_v2);
110
+ const files = Array.isArray(post.files) ? post.files.filter(isPostRecord) : [];
111
+ const filesByKey = new Map();
112
+ for (const file of files) {
113
+ const key = attachmentString(file.file_key);
114
+ if (key && !filesByKey.has(key))
115
+ filesByKey.set(key, file);
116
+ }
117
+ const seenFileKeys = new Set();
118
+ const result = elements.map(el => {
119
+ if (el.tag !== "file" && el.tag !== "media")
120
+ return el;
121
+ const key = attachmentString(el.file_key);
122
+ if (key)
123
+ seenFileKeys.add(key);
124
+ const metadata = filesByKey.get(key);
125
+ return metadata
126
+ ? { ...el, file_name: attachmentString(el.file_name) || attachmentString(metadata.file_name) }
127
+ : el;
128
+ });
129
+ const title = attachmentString(post.title);
130
+ const first = result[0];
131
+ const titleAlreadyInBody = first && (first.tag === "text" || first.tag === "p")
132
+ && attachmentString(first.text) === title;
133
+ if (title && !titleAlreadyInBody)
134
+ result.unshift({ tag: "text", text: title });
135
+ // Top-level files have no inline position; append in their original order.
136
+ for (const file of files) {
137
+ const key = attachmentString(file.file_key);
138
+ if (key && seenFileKeys.has(key))
139
+ continue;
140
+ if (key)
141
+ seenFileKeys.add(key);
142
+ result.push({ ...file, tag: "file" });
143
+ }
144
+ return result;
101
145
  }
102
146
  function attachmentString(value) {
103
147
  return typeof value === "string" ? value.trim() : "";
@@ -175,24 +219,14 @@ function getPostImageKey(el) {
175
219
  return undefined;
176
220
  }
177
221
  async function formatPostContentWithAttachments(content, messageId) {
178
- const paragraphs = getPostParagraphs(content);
179
- if (!Array.isArray(paragraphs))
180
- return "";
181
222
  const parts = [];
182
- for (const line of paragraphs) {
183
- if (!Array.isArray(line))
184
- continue;
185
- for (const elem of line) {
186
- const el = elem;
187
- if (!el || typeof el !== "object")
188
- continue;
189
- const text = formatPostTextElement(el, messageId);
190
- if (text)
191
- parts.push(text);
192
- const imageKey = getPostImageKey(el);
193
- if (imageKey) {
194
- parts.push(await formatPostImageElement(messageId, imageKey));
195
- }
223
+ for (const el of getPostElements(content)) {
224
+ const text = formatPostTextElement(el, messageId);
225
+ if (text)
226
+ parts.push(text);
227
+ const imageKey = getPostImageKey(el);
228
+ if (imageKey) {
229
+ parts.push(await formatPostImageElement(messageId, imageKey));
196
230
  }
197
231
  }
198
232
  return parts.join("\n").trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatccc",
3
- "version": "0.2.305",
3
+ "version": "0.2.307",
4
4
  "description": "Feishu bot bridge for Claude Code",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",