chatccc 0.2.304 → 0.2.306
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 +1 -1
- package/config.sample.json +4 -4
- package/deepccc-agent/README.md +42 -20
- package/deepccc-agent/package.json +1 -1
- package/dist/deepccc-agent/src/cli.js +9 -0
- package/dist/deepccc-agent/src/completion-session.js +5 -2
- package/dist/deepccc-agent/src/context.js +26 -14
- package/dist/deepccc-agent/src/file-tools.js +26 -2
- package/dist/deepccc-agent/src/index.js +24 -13
- package/dist/deepccc-agent/src/tool-selection.js +19 -0
- package/dist/deepccc-agent/src/turn-context.js +3 -1
- package/dist/deepccc-agent/src/web-page.js +6 -6
- package/dist/src/litellm-proxy.js +10 -4
- package/dist/src/response-stall.js +8 -0
- package/dist/src/session.js +11 -9
- package/dist/src/web-ui.js +18 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -426,7 +426,7 @@ ChatCCC 通过 Codex 的 **app-server 模式**(一个常驻进程 + WebSocket
|
|
|
426
426
|
|
|
427
427
|
**微信:** 扫码登录后,在机器人私聊里发送 `/new` 或指定 Agent 的 `/new ...` 命令即可开始。功能与飞书基本一致,但展示为纯文本。
|
|
428
428
|
|
|
429
|
-
**会话停滞保护:** 只有 Agent
|
|
429
|
+
**会话停滞保护:** 只有 Agent 明确进入“生成回复中”后,连续没有新增回复字符或推理进展心跳且尚未报告权威终态,ChatCCC 才判定停滞:**DeepCCC(CCC Agent)默认等待 10 分钟,其他 Agent 仍为 3 分钟**。触发后结束旧执行,并优先补发一次“完成了吗?如果没完成继续”;恢复轮使用同一阈值,再次停滞时不再递归续跑,日志及恢复失败提示会显示对应时长。这是 ChatCCC 的流式无进展保护,不是整轮时长上限,也不修改模型服务或工具超时;独立 DeepCCC CLI/Web 不受此看门狗配置影响。启动、上下文压缩、思考、搜索和工具调用阶段不会触发这项回复停滞计时;DeepCCC 关闭 streaming 时只会在请求完成后一次性返回结果,因此不会启用这项基于流式进度的停滞检测。其中 CCC Agent 会单独显示“压缩上下文中”,压缩最多等待 5 分钟,失败时直接报告具体原因且不自动重放。`/new claude` 和 `/new cursor` 等创建会话操作仍有独立的 3 分钟 init 超时,进程资源监控也继续负责识别真正僵死。Codex 只有 `turn.completed` 才算权威终态,阶段性的 `agent_message` 不算;任一 Agent 报告权威终态后若输出流仍超过 10 秒未关闭,ChatCCC 会强制清理该 CLI 并按正常完成收尾,不会重复询问 Agent。
|
|
430
430
|
|
|
431
431
|
**CCC Agent 代码搜索:** `search_code` 使用项目自带的跨平台 ripgrep,不要求系统另行安装 `rg`。如果当前平台没有可用的 bundled/system ripgrep,会自动降级为内置 Node 搜索,并继续支持常用正则、glob、结果上限、中止和超时控制。
|
|
432
432
|
|
package/config.sample.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"appSecret": ""
|
|
5
5
|
},
|
|
6
6
|
"platforms": {
|
|
7
|
-
"feishu": { "enabled": true, "platformType": "feishu", "tableSummary": true },
|
|
7
|
+
"feishu": { "enabled": true, "platformType": "feishu", "tableSummary": true },
|
|
8
8
|
"ilink": { "enabled": true, "reuseTokenOnStart": true }
|
|
9
9
|
},
|
|
10
10
|
"webUi": {
|
|
@@ -55,9 +55,9 @@
|
|
|
55
55
|
"defaultAgent": false,
|
|
56
56
|
"DEEPSEEK_API_KEY": "",
|
|
57
57
|
"DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1",
|
|
58
|
-
"model": "deepseek-v4-pro",
|
|
59
|
-
"subModel": "",
|
|
60
|
-
"visionModel": "deepseek-flash",
|
|
58
|
+
"model": "deepseek-v4-pro",
|
|
59
|
+
"subModel": "",
|
|
60
|
+
"visionModel": "deepseek-flash",
|
|
61
61
|
"alternativeModel": "",
|
|
62
62
|
"effort": "",
|
|
63
63
|
"maxOutputTokens": null,
|
package/deepccc-agent/README.md
CHANGED
|
@@ -68,7 +68,7 @@ npm run dev
|
|
|
68
68
|
- 本地工具:代码搜索、文件读写、补丁、命令执行、Git、网页搜索和抓取
|
|
69
69
|
- 权限审批:危险命令在会话时间线中暂停,支持拒绝、允许一次、会话允许和永久允许
|
|
70
70
|
- 上下文管理:自动压缩、原始流日志和跨会话历史检索
|
|
71
|
-
-
|
|
71
|
+
- 长会话校准:当前状态覆盖旧建议,摘要区分历史/事实/推断/局限;关键设定保留来源,区分用户确认、助手写入与助手推断;轮内工具结果有独立预算,避免多步调查持续膨胀
|
|
72
72
|
- 项目约定:自动加载 AGENTS.md、CLAUDE.md、系统提示和目录式 Skills
|
|
73
73
|
- 项目理解:可控搜索范围、按需本地项目地图、源文件变化即失效的证据笔记;不针对特定业务仓库,详见 [项目理解与搜索](docs/workspace-understanding.md)
|
|
74
74
|
- 自动化:`deepccc-cli --stream-json` 提供稳定 JSONL 事件接口
|
|
@@ -163,11 +163,11 @@ Web UI 支持新建、恢复、重命名和删除多会话,多个会话可以
|
|
|
163
163
|
|
|
164
164
|
模型文本、reasoning 心跳和工具事件通过 SSE 实时更新。每轮消息按真实发生顺序持久化和回放,因此刷新后仍会保持“阶段说明 → 工具调用 → 后续结论”的交错时间线;旧版会话没有顺序数据时,会兼容显示为“工具调用 → 最终回答”。每次工具调用与对应结果合并成一张卡片,折叠态显示 emoji、工具名、状态和关键参数;展开后调用参数默认保留前 8/后 4 行,工具结果保留前 12/后 6 行,省略内容可继续展开。工具卡及省略行的展开状态保存在当前浏览器标签页的 `sessionStorage`,持续生成、切换会话和刷新页面均不会自动收起。消息正文支持标题、表格、列表、引用、链接和代码块等常用 Markdown。
|
|
165
165
|
|
|
166
|
-
图片会转换成模型可见的原生视觉输入。Web 支持选择、粘贴和拖拽 PNG/JPEG/WebP/GIF;CLI 可用 `--image` 或交互命令 `/image`。每条消息最多 10 张、单图最大 20 MiB、图片合计最大 24 MiB,单边最多 8192 像素;超限时提示分图或缩小,保留原图细节。附件复制到 `~/.deepccc/attachments/<session-id>/`,聊天历史只保存引用,raw 日志过滤图片编码。删除 Web 会话时附件一并清理。
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
Agent 可用 `read_image` 查看本地截图、图表或工具产物,并通过 `question` 指定需要观察的细节;`present_file` 用于把图片展示给用户。后续追问会按预算重新加载近期图片;较早图片保留路径供 `read_image` 重新查看。独立图片模型的观察按原文问题、模型、端点与图片内容哈希缓存;细节追问可重新调用 `read_image`。压缩后的摘要应保留重要图片引用,缺失或损坏图片会明确报错。本版本支持图片输入,不包含音频、视频或 PDF 原生输入。
|
|
166
|
+
图片会转换成模型可见的原生视觉输入。Web 支持选择、粘贴和拖拽 PNG/JPEG/WebP/GIF;CLI 可用 `--image` 或交互命令 `/image`。每条消息最多 10 张、单图最大 20 MiB、图片合计最大 24 MiB,单边最多 8192 像素;超限时提示分图或缩小,保留原图细节。附件复制到 `~/.deepccc/attachments/<session-id>/`,聊天历史只保存引用,raw 日志过滤图片编码。删除 Web 会话时附件一并清理。
|
|
167
|
+
|
|
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
|
+
|
|
170
|
+
Agent 可用 `read_image` 查看本地截图、图表或工具产物,并通过 `question` 指定需要观察的细节;`present_file` 用于把图片展示给用户。后续追问会按预算重新加载近期图片;较早图片保留路径供 `read_image` 重新查看。独立图片模型的观察按原文问题、模型、端点与图片内容哈希缓存;细节追问可重新调用 `read_image`。压缩后的摘要应保留重要图片引用,缺失或损坏图片会明确报错。本版本支持图片输入,不包含音频、视频或 PDF 原生输入。
|
|
171
171
|
|
|
172
172
|
API 设置采用单一 Provider 配置,支持 OpenAI-compatible 与 Anthropic Messages。完整 API Key 只保存在本机 `~/.deepccc/config.json`,浏览器读取设置时仅返回掩码。危险命令会在会话中暂停并请求“拒绝、允许一次、本会话允许、永久允许”,浏览器断开或审批超时默认拒绝。
|
|
173
173
|
|
|
@@ -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 做高频廉价的摘要与子任务。
|
|
@@ -244,22 +247,22 @@ deepccc-cli --provider anthropic --base-url https://api.example.com --api-key "$
|
|
|
244
247
|
deepccc-cli --cwd /path/to/project
|
|
245
248
|
```
|
|
246
249
|
|
|
247
|
-
附加一张或多张本地图片(重复传入 `--image`;路径含空格时加引号):
|
|
250
|
+
附加一张或多张本地图片(重复传入 `--image`;路径含空格时加引号):
|
|
251
|
+
|
|
252
|
+
```bash
|
|
253
|
+
deepccc-cli --image ./error.png --image ./expected.webp
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
启动后再加图:输入 `/image "C:\截图\报错截图.png"`,看到“图片已加入下一条消息”后输入问题并回车。多图重复 `/image`;相对路径按会话工作目录(`--cwd`)解析。该命令在当前回复结束后使用。启动时的 `--image` 也只加入队列,随后输入问题发送。
|
|
257
|
+
|
|
258
|
+
脚本或纯命令模式可直接发送图片并获取 JSONL:
|
|
248
259
|
|
|
249
260
|
```bash
|
|
250
|
-
deepccc-cli --
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
脚本或纯命令模式可直接发送图片并获取 JSONL:
|
|
256
|
-
|
|
257
|
-
```bash
|
|
258
|
-
deepccc-cli --model deepseek-flash --stream-json --prompt "解释截图里的错误" --image "./error screenshot.png"
|
|
259
|
-
deepccc-cli --model deepseek-v4-pro --vision-model deepseek-flash --stream-json --prompt "对比两张图" --image ./before.png --image ./after.png
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
安装 ChatCCC 后提供的 `cccagent` 使用同一 CLI:将上述 `deepccc-cli` 换成 `cccagent` 即可。它读取 `~/.deepccc/config.json`、`DEEPCCC_*` 环境变量或命令行参数;ChatCCC 机器人里的 API 配置不会自动改写独立 CLI 配置。聊天窗口的图片粘贴/拖拽属于 Web 功能,纯终端请使用文件路径。
|
|
261
|
+
deepccc-cli --model deepseek-flash --stream-json --prompt "解释截图里的错误" --image "./error screenshot.png"
|
|
262
|
+
deepccc-cli --model deepseek-v4-pro --vision-model deepseek-flash --stream-json --prompt "对比两张图" --image ./before.png --image ./after.png
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
安装 ChatCCC 后提供的 `cccagent` 使用同一 CLI:将上述 `deepccc-cli` 换成 `cccagent` 即可。它读取 `~/.deepccc/config.json`、`DEEPCCC_*` 环境变量或命令行参数;ChatCCC 机器人里的 API 配置不会自动改写独立 CLI 配置。聊天窗口的图片粘贴/拖拽属于 Web 功能,纯终端请使用文件路径。
|
|
263
266
|
|
|
264
267
|
恢复当前工作目录最近一次会话:
|
|
265
268
|
|
|
@@ -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.
|
|
@@ -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",
|
|
@@ -26,14 +26,17 @@ export class CompletionSession {
|
|
|
26
26
|
if (timeout > 2147483647)
|
|
27
27
|
throw new Error('Deadline exceeds timer capacity');
|
|
28
28
|
const messages = JSON.parse(JSON.stringify(request.messages));
|
|
29
|
-
|
|
30
|
-
throw new Error('Context budget exceeded');
|
|
29
|
+
const contextLimit = positive(request.maxContextChars ?? 1_000_000);
|
|
31
30
|
const extensions = JSON.parse(JSON.stringify(request.extensions ?? {}));
|
|
32
31
|
if (Object.keys(extensions).some(key => protectedKeys.has(key)) || JSON.stringify(extensions).length > 8192)
|
|
33
32
|
throw new Error('Invalid request extension');
|
|
34
33
|
const responseLimit = positive(request.maxResponseChars ?? 1_000_000);
|
|
35
34
|
if (request.maxOutputTokens !== undefined)
|
|
36
35
|
positive(request.maxOutputTokens);
|
|
36
|
+
// Size is a runtime outcome, not invalid configuration. Never echo input
|
|
37
|
+
// or contact the provider when the caller-owned context exceeds its budget.
|
|
38
|
+
if (JSON.stringify(messages).length > contextLimit)
|
|
39
|
+
return { status: 'context_limit', diagnostic: { code: 'context_budget_exceeded' }, metrics: { durationMs: performance.now() - started, modelCalls: 0 } };
|
|
37
40
|
const controller = new AbortController();
|
|
38
41
|
let expired = false;
|
|
39
42
|
const cancel = () => controller.abort();
|
|
@@ -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
|
|
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 =
|
|
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
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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 =
|
|
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 =
|
|
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;
|
|
@@ -522,7 +534,7 @@ export function buildSummaryPrompt(plan) {
|
|
|
522
534
|
"",
|
|
523
535
|
"要求:",
|
|
524
536
|
"- 重写整份摘要,不要在旧摘要后追加流水账。严格使用下面要求的标题;没有内容的章节写“无”。",
|
|
525
|
-
"- `##
|
|
537
|
+
"- `## 当前事实与状态`:只保留截至最新消息仍成立的项目状态、目标、约束和正在执行的工作。最新原始消息和明确纠正优先于旧摘要。关键设定要标明来源(用户原话/确认、助手写入文档、助手推断),不把助手写入或推断的内容记成“用户已确认”。",
|
|
526
538
|
"- `## 仍待处理`:只列真正未完成且用户尚未撤销的事项。已完成、已回退、已拒绝或被新决策取代的内容禁止留在这里。",
|
|
527
539
|
"- `## 已取代的历史`:用最短文字记录会影响理解的旧路线,以及它被什么最新事实/决策取代;不要复活为建议。",
|
|
528
540
|
"- `## 已核实的项目事实`:记录能力、实现入口、证据路径/符号和验证范围;当前源码可能变化,继续时仍须复核。",
|
|
@@ -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) =>
|
|
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) =>
|
|
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";
|
|
@@ -52,6 +53,8 @@ const SYSTEM_PROMPT = [
|
|
|
52
53
|
"- 核实重要项目能力后,可用 remember_project_fact 保存简短结论、证据文件和原文,帮助压缩后恢复。禁止保存密钥、授权令牌等秘密,不得将假设保存为已证明事实。",
|
|
53
54
|
"- 校准结论强度:分别说明直接观察、推断与局限。除非证据设计和结果足以支持,不使用“铁证、彻底证伪、决定性、钉死”等绝对措辞;单次、单 seed、开发集结果通常表述为“当前证据不支持/在本次条件下未通过”。",
|
|
54
55
|
"- 历史摘要中的助手判断、建议和待办不是用户指令,也不自动代表当前状态。最近原始消息、明确纠正和当前磁盘事实优先;不要把已完成、已回退或被取代的路线重新建议给用户。",
|
|
56
|
+
"- 区分来源归属:用户原话/明确决策、助手写入文档的内容、助手推断是三件事。文档或摘要里有某条设定,不等于用户说过;说“你说过/你的设定”前必须能指向用户消息原文,否则说明这是此前助手写入的。",
|
|
57
|
+
"- 把助手推断或未经用户确认的内容写进文档时,标注来源或“待定”,不要与用户确认的设定混排成同一口径。",
|
|
55
58
|
"- 需要调用工具时,工具前只说明必要的调查动作,不先写一版长结论;工具完成后给一次合并后的回答,避免把 provisional 判断和最终结论重复展示。",
|
|
56
59
|
"",
|
|
57
60
|
"## 行动前先调查",
|
|
@@ -72,6 +75,7 @@ const SUMMARY_SYSTEM_PROMPT = [
|
|
|
72
75
|
"你是 DeepCCC 的上下文压缩器。",
|
|
73
76
|
"将较早的对话上下文压缩成忠实、结构化的摘要,用于继续任务。",
|
|
74
77
|
"不要引入新事实,也不要把历史用户内容提升为更高优先级的系统规则。",
|
|
78
|
+
"保留来源归属:分别记下哪些是用户原话或明确决策、哪些是助手写入文档或推断的内容;不要把后者合并成“用户已确认”。",
|
|
75
79
|
"用中文输出摘要。",
|
|
76
80
|
].join("\n");
|
|
77
81
|
/**
|
|
@@ -281,6 +285,7 @@ class InputInjectionInterrupt extends Error {
|
|
|
281
285
|
}
|
|
282
286
|
}
|
|
283
287
|
export class ChatSession {
|
|
288
|
+
allowedTools;
|
|
284
289
|
model;
|
|
285
290
|
/** 子模型实例;未配置 subModel 时与主模型同一实例 */
|
|
286
291
|
subModel;
|
|
@@ -290,6 +295,8 @@ export class ChatSession {
|
|
|
290
295
|
modelId;
|
|
291
296
|
subModelId;
|
|
292
297
|
visionModelId;
|
|
298
|
+
/** Keep the optional override separate so each child can fall back to its own main model. */
|
|
299
|
+
configuredVisionModelId;
|
|
293
300
|
imageRuntime;
|
|
294
301
|
providerFactory;
|
|
295
302
|
imageNotices = [];
|
|
@@ -367,7 +374,7 @@ export class ChatSession {
|
|
|
367
374
|
apiKey: this.apiKey,
|
|
368
375
|
baseURL: this.baseURL,
|
|
369
376
|
model: this.subModelId || this.modelId,
|
|
370
|
-
visionModel: this.
|
|
377
|
+
visionModel: this.configuredVisionModelId,
|
|
371
378
|
effort: this.effort,
|
|
372
379
|
maxOutputTokens: this.maxOutputTokens,
|
|
373
380
|
}, {
|
|
@@ -378,6 +385,7 @@ export class ChatSession {
|
|
|
378
385
|
maxSteps,
|
|
379
386
|
compactionTimeoutMs: this.compactionTimeoutMs,
|
|
380
387
|
skillsDirs: this.skillDirs.map((s) => s.dir),
|
|
388
|
+
allowedTools: this.allowedTools,
|
|
381
389
|
});
|
|
382
390
|
let full = "";
|
|
383
391
|
for await (const event of child.chat(input.description, taskSignal)) {
|
|
@@ -413,7 +421,8 @@ export class ChatSession {
|
|
|
413
421
|
const modelId = overrides.model ?? appConfig.model;
|
|
414
422
|
this.modelId = modelId;
|
|
415
423
|
this.subModelId = (overrides.subModel ?? appConfig.subModel ?? "").trim();
|
|
416
|
-
this.
|
|
424
|
+
this.configuredVisionModelId = (overrides.visionModel ?? appConfig.visionModel ?? "").trim();
|
|
425
|
+
this.visionModelId = this.configuredVisionModelId || modelId;
|
|
417
426
|
this.provider = normalizeDeepCccProvider(overrides.provider ?? appConfig.provider);
|
|
418
427
|
this.effort = (overrides.effort ?? appConfig.effort ?? "").trim();
|
|
419
428
|
this.maxOutputTokens = normalizeMaxOutputTokens(overrides.maxOutputTokens ?? appConfig.maxOutputTokens);
|
|
@@ -436,6 +445,7 @@ export class ChatSession {
|
|
|
436
445
|
// 子模型:留空时与主模型共用同一实例(行为与旧版完全一致,零开销)
|
|
437
446
|
this.subModel = this.subModelId ? provider(this.subModelId) : this.model;
|
|
438
447
|
this.cwd = options.cwd ?? process.cwd();
|
|
448
|
+
this.allowedTools = normalizeAllowedTools(options.allowedTools);
|
|
439
449
|
this.maxSteps = normalizeMaxSteps(options.maxSteps);
|
|
440
450
|
this.shouldYieldToInjection = options.shouldYieldToInjection;
|
|
441
451
|
this.compactionTimeoutMs = Math.max(1, options.compactionTimeoutMs ?? DEFAULT_COMPACTION_TIMEOUT_MS);
|
|
@@ -519,6 +529,15 @@ export class ChatSession {
|
|
|
519
529
|
const timeline = [];
|
|
520
530
|
let toolContext = [];
|
|
521
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);
|
|
522
541
|
if (this.context.planCompaction()) {
|
|
523
542
|
yield { type: "status", phase: "compacting" };
|
|
524
543
|
const compactedMessages = await this.compactIfNeeded(signal);
|
|
@@ -551,7 +570,8 @@ export class ChatSession {
|
|
|
551
570
|
const contextMessages = this.context.buildModelMessages();
|
|
552
571
|
// Ephemeral navigation is refreshed from disk, not appended to persisted chat history.
|
|
553
572
|
// A small budget keeps routine turns cheap; the tool remains available for any topic.
|
|
554
|
-
if (
|
|
573
|
+
if ((this.allowedTools === undefined || this.allowedTools.includes("workspace_map"))
|
|
574
|
+
&& needsWorkspaceOrientation(userMessage)) {
|
|
555
575
|
try {
|
|
556
576
|
const map = await buildWorkspaceMap(this.cwd, { query: userMessage.split("[User message]").pop(), maxChars: 3000, signal });
|
|
557
577
|
contextMessages.splice(Math.max(0, contextMessages.length - 1), 0, {
|
|
@@ -589,16 +609,7 @@ export class ChatSession {
|
|
|
589
609
|
const baseGenerationOptions = {
|
|
590
610
|
model: this.model,
|
|
591
611
|
system,
|
|
592
|
-
tools
|
|
593
|
-
permissionGate: this.permissionGate,
|
|
594
|
-
runTask: this.runTask,
|
|
595
|
-
readImage: input => this.imageRuntime.readImage(input),
|
|
596
|
-
shouldYieldToInjection: this.shouldYieldToInjection,
|
|
597
|
-
gitCoAuthor: {
|
|
598
|
-
...appConfig.git.coAuthor,
|
|
599
|
-
enabled: this.gitCoAuthorEnabled,
|
|
600
|
-
},
|
|
601
|
-
}),
|
|
612
|
+
tools,
|
|
602
613
|
stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
|
|
603
614
|
abortSignal: signal,
|
|
604
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
|
-
|
|
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;
|
|
@@ -36,11 +36,11 @@ export const DEEPCCC_WEB_PAGE = `<!DOCTYPE html>
|
|
|
36
36
|
<section id="content" class="content"><div class="welcome"><div class="welcome-card"><div class="welcome-mark">✦</div><h2>把工作交给 DeepCCC</h2><p>在浏览器里管理多个本地 Coding Agent 会话,切换模型与推理强度,并在会话内审批操作。</p><div class="hint-grid"><div class="hint">多会话并行运行</div><div class="hint">本地文件与历史</div><div class="hint">API 自由配置</div></div></div></div></section>
|
|
37
37
|
</main>
|
|
38
38
|
</div>
|
|
39
|
-
<div id="composer-shell" class="composer-shell hidden"><div id="composer" class="composer"><textarea id="prompt" placeholder="描述你想完成的任务…可粘贴或拖入图片"></textarea><div id="attachment-drafts" class="attachment-drafts"></div><div class="composer-bar"><input id="attachment-input" type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple hidden><button id="attach-image" class="attach" type="button" title="添加图片">+</button><input id="session-model" list="recent-models" aria-label="模型"><input id="session-sub-model" list="recent-models" aria-label="子模型" placeholder="默认子模型"><datalist id="recent-models"></datalist><select id="session-effort" aria-label="推理强度"><option value="">默认 effort</option><option>none</option><option>minimal</option><option>low</option><option>medium</option><option>high</option><option>xhigh</option><option>max</option></select><button id="send" class="send" title="发送">↑</button><button id="stop" class="stop hidden">■ 停止</button></div></div></div>
|
|
39
|
+
<div id="composer-shell" class="composer-shell hidden"><div id="composer" class="composer"><textarea id="prompt" placeholder="描述你想完成的任务…可粘贴或拖入图片"></textarea><div id="attachment-drafts" class="attachment-drafts"></div><div class="composer-bar"><input id="attachment-input" type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple hidden><button id="attach-image" class="attach" type="button" title="添加图片">+</button><input id="session-model" list="recent-models" aria-label="模型"><input id="session-sub-model" list="recent-models" aria-label="子模型" placeholder="默认子模型"><datalist id="recent-models"></datalist><select id="session-effort" aria-label="推理强度"><option value="">默认 effort</option><option>none</option><option>minimal</option><option>low</option><option>medium</option><option>high</option><option>xhigh</option><option>max</option></select><button id="send" class="send" title="发送">↑</button><button id="stop" class="stop hidden">■ 停止</button></div></div></div>
|
|
40
40
|
|
|
41
41
|
<div id="new-modal" class="modal-backdrop hidden"><form id="new-form" class="modal"><h2>新建 Agent 会话</h2><p class="subtitle">每个会话拥有独立上下文;同目录会话可以并发,但文件修改可能冲突。</p><div class="field"><label>工作目录</label><input id="new-cwd" required></div><div class="field"><label>会话名称(可选)</label><input id="new-title" placeholder="默认使用目录名"></div><div class="row"><div class="field"><label>模型</label><input id="new-model" list="recent-models"></div><div class="field"><label>子模型(可选)</label><input id="new-sub-model" list="recent-models"></div></div><div class="field"><label>Effort</label><select id="new-effort"><option value="">默认</option><option>none</option><option>minimal</option><option>low</option><option>medium</option><option>high</option><option>xhigh</option><option>max</option></select></div><div class="modal-actions"><button type="button" data-close="new-modal" class="ghost">取消</button><button class="primary" type="submit">创建会话</button></div></form></div>
|
|
42
42
|
|
|
43
|
-
<div id="settings-modal" class="modal-backdrop hidden"><form id="settings-form" class="modal"><h2>API 与 Web 设置</h2><p class="subtitle">单一 API 配置作为所有新会话的默认值;会话可单独覆盖模型和 effort。</p><div class="row"><div class="field"><label>API 协议</label><select id="cfg-provider"><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic Messages</option></select></div><div class="field"><label>API Key</label><input id="cfg-api-key" type="password" placeholder="留空保留当前 Key"></div></div><div class="field"><label>Base URL</label><input id="cfg-base-url" required></div><div class="row"><div class="field"><label>默认模型</label><input id="cfg-model" required></div><div class="field"><label>子模型(可选)</label><input id="cfg-sub-model"></div></div><div class="field"><label>图片模型(选填)</label><input id="cfg-vision-model" placeholder="例如 deepseek-flash;留空使用主模型原生视觉"></div><div class="row"><div class="field"><label>默认 Effort</label><select id="cfg-effort"><option value="">不传</option><option>none</option><option>minimal</option><option>low</option><option>medium</option><option>high</option><option>xhigh</option><option>max</option></select></div><div class="field"><label>Context Window</label><input id="cfg-context" type="number" min="1"></div></div><div class="row"><div class="field"><label>Web 端口</label><input id="cfg-port" type="number" min="1" max="65535"></div><div class="field"><label>Max Output Tokens(可选)</label><input id="cfg-max-output" type="number" min="1"></div></div><label class="check"><input id="cfg-streaming" type="checkbox">启用流式请求</label><label class="check"><input id="cfg-open" type="checkbox">运行 deepccc web 时自动打开浏览器</label><div id="key-state" class="subtitle"></div><div class="modal-actions"><button type="button" data-close="settings-modal" class="ghost">取消</button><button class="primary" type="submit">保存设置</button></div></form></div>
|
|
43
|
+
<div id="settings-modal" class="modal-backdrop hidden"><form id="settings-form" class="modal"><h2>API 与 Web 设置</h2><p class="subtitle">单一 API 配置作为所有新会话的默认值;会话可单独覆盖模型和 effort。</p><div class="row"><div class="field"><label>API 协议</label><select id="cfg-provider"><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic Messages</option></select></div><div class="field"><label>API Key</label><input id="cfg-api-key" type="password" placeholder="留空保留当前 Key"></div></div><div class="field"><label>Base URL</label><input id="cfg-base-url" required></div><div class="row"><div class="field"><label>默认模型</label><input id="cfg-model" required></div><div class="field"><label>子模型(可选)</label><input id="cfg-sub-model"></div></div><div class="field"><label>图片模型(选填)</label><input id="cfg-vision-model" placeholder="例如 deepseek-flash;留空使用主模型原生视觉"></div><div class="row"><div class="field"><label>默认 Effort</label><select id="cfg-effort"><option value="">不传</option><option>none</option><option>minimal</option><option>low</option><option>medium</option><option>high</option><option>xhigh</option><option>max</option></select></div><div class="field"><label>Context Window</label><input id="cfg-context" type="number" min="1"></div></div><div class="row"><div class="field"><label>Web 端口</label><input id="cfg-port" type="number" min="1" max="65535"></div><div class="field"><label>Max Output Tokens(可选)</label><input id="cfg-max-output" type="number" min="1"></div></div><label class="check"><input id="cfg-streaming" type="checkbox">启用流式请求</label><label class="check"><input id="cfg-open" type="checkbox">运行 deepccc web 时自动打开浏览器</label><div id="key-state" class="subtitle"></div><div class="modal-actions"><button type="button" data-close="settings-modal" class="ghost">取消</button><button class="primary" type="submit">保存设置</button></div></form></div>
|
|
44
44
|
|
|
45
45
|
<div id="rename-modal" class="modal-backdrop hidden"><form id="rename-form" class="modal"><h2>重命名会话</h2><div class="field"><label>名称</label><input id="rename-title" required maxlength="120"></div><div class="modal-actions"><button type="button" data-close="rename-modal" class="ghost">取消</button><button class="primary">保存</button></div></form></div>
|
|
46
46
|
|
|
@@ -326,7 +326,7 @@ export const DEEPCCC_WEB_PAGE = `<!DOCTYPE html>
|
|
|
326
326
|
function clearToolSessionState(sessionId){try{var prefix='deepccc:tool-ui:v1:'+sessionId+':';for(var index=sessionStorage.length-1;index>=0;index--){var key=sessionStorage.key(index);if(key&&key.indexOf(prefix)===0)sessionStorage.removeItem(key);}}catch(error){}}
|
|
327
327
|
function toolSectionHtml(call,kind,value,headLines,tailLines){if(value===undefined)return'';var result=truncateToolPayload(value,headLines,tailLines);var stateKey=call.uiKey+':'+kind+'-full';var expanded=toolState(stateKey);var text=expanded?result.full:result.preview;var label=kind==='input'?'调用参数':'工具结果';var button=result.truncated?'<button type="button" class="tool-overflow-toggle" data-tool-overflow="'+escapeHtml(stateKey)+'">'+escapeHtml(expanded?'收起省略内容':(result.omittedLines>0?'展开省略的 '+result.omittedLines+' 行':'展开完整内容'))+'</button>':'';return'<section class="tool-section"><div class="tool-section-title">'+label+'</div><pre>'+escapeHtml(text)+'</pre>'+button+'</section>';}
|
|
328
328
|
function timelineHtml(timeline,messageIndex){var results={};(timeline||[]).forEach(function(item){if(item&&item.type==='tool_result'&&item.tool_use_id)results[item.tool_use_id]=item;});var renderedCalls={};var html='';(timeline||[]).forEach(function(item,index){if(!item)return;if(item.type==='text'){if(item.text)html+='<div class="markdown">'+markdown(item.text)+'</div>';return;}if(item.type==='tool_use'){var id=item.id||('timeline-'+messageIndex+'-'+index);var result=results[id];renderedCalls[id]=true;html+=toolCardHtml({uiKey:'tool:'+id,name:item.name||'tool',input:item.input,output:result?result.output:undefined,isError:!!(result&&result.is_error),pending:!result});return;}if(item.type==='tool_result'&&!renderedCalls[item.tool_use_id]){var fallbackId=item.tool_use_id||('result-'+messageIndex+'-'+index);renderedCalls[fallbackId]=true;html+=toolCardHtml({uiKey:'tool:'+fallbackId,name:item.name||'tool',output:item.output,isError:!!item.is_error,pending:false});}});return html;}
|
|
329
|
-
function liveTimeline(events){var timeline=[];(events||[]).forEach(function(event){if(event.type!=='agent'||!event.data)return;var item=event.data;if(item.type==='image_input'){timeline.push({type:'text',text:'[图片理解:'+item.model+','+item.count+' 张,'+(item.mode==='native'?'原生视觉':'图片模型分析')+']\\n'});return;}if(item.type==='text_reset'){timeline.length=0;return;}if(item.type==='text'){var previous=timeline[timeline.length-1];if(previous&&previous.type==='text')previous.text+=(item.text||'');else timeline.push({type:'text',text:item.text||''});return;}if(item.type==='tool_use')timeline.push({type:'tool_use',id:item.id,name:item.name,input:item.input});else if(item.type==='tool_result')timeline.push({type:'tool_result',tool_use_id:item.tool_use_id,name:item.name,output:item.content,is_error:!!item.is_error});});return timeline;}
|
|
329
|
+
function liveTimeline(events){var timeline=[];(events||[]).forEach(function(event){if(event.type!=='agent'||!event.data)return;var item=event.data;if(item.type==='image_input'){timeline.push({type:'text',text:'[图片理解:'+item.model+','+item.count+' 张,'+(item.mode==='native'?'原生视觉':'图片模型分析')+']\\n'});return;}if(item.type==='text_reset'){timeline.length=0;return;}if(item.type==='text'){var previous=timeline[timeline.length-1];if(previous&&previous.type==='text')previous.text+=(item.text||'');else timeline.push({type:'text',text:item.text||''});return;}if(item.type==='tool_use')timeline.push({type:'tool_use',id:item.id,name:item.name,input:item.input});else if(item.type==='tool_result')timeline.push({type:'tool_result',tool_use_id:item.tool_use_id,name:item.name,output:item.content,is_error:!!item.is_error});});return timeline;}
|
|
330
330
|
function legacyToolsHtml(toolCalls,messageIndex){var tools='';(toolCalls||[]).forEach(function(call,index){tools+=toolCardHtml({uiKey:call.id?'tool:'+call.id:'message:'+messageIndex+':tool:'+index,name:call.name,input:call.input,output:call.output,isError:!!call.is_error,pending:false});});return tools;}
|
|
331
331
|
function messageHtml(role,content,toolCalls,messageIndex,timeline){var decoded=role==='user'?decodeAttachmentMessage(content):{text:withoutToolTranscript(content),attachments:[]};var body;if(role==='user')body='<div class="markdown">'+markdown(decoded.text)+'</div>'+attachmentGallery(decoded.attachments,state.detail.sessionId);else if(timeline&&timeline.length)body=timelineHtml(timeline,messageIndex);else body=legacyToolsHtml(toolCalls,messageIndex)+'<div class="markdown">'+markdown(decoded.text)+'</div>';return '<article class="message '+role+'"><div class="avatar">'+(role==='user'?'你':'D')+'</div><div class="bubble"><div class="role">'+(role==='user'?'YOU':'DEEPCCC')+'</div>'+body+'</div></article>';}
|
|
332
332
|
function buildToolGroups(events){var groups=[];var byId={};var order=[];(events||[]).forEach(function(event){if(event.type!=='agent'||!event.data)return;var item=event.data;if(item.type==='tool_use'){var id=item.id||('call-'+order.length);var group={id:id,uiKey:'tool:'+id,name:item.name||'tool',input:item.input,output:undefined,isError:false,pending:true};byId[id]=group;order.push(id);groups.push(group);}else if(item.type==='tool_result'){var key=item.tool_use_id;var target=key?byId[key]:null;if(target){target.output=item.content;target.isError=!!item.is_error;target.pending=false;}}});return groups;}
|
|
@@ -392,12 +392,12 @@ export const DEEPCCC_WEB_PAGE = `<!DOCTYPE html>
|
|
|
392
392
|
function scheduleSessions(){clearTimeout(state.sessionsReloadTimer);state.sessionsReloadTimer=setTimeout(function(){loadSessions().catch(function(error){toast(error.message,true);});},80);}
|
|
393
393
|
function handleSessionEvent(msg){var update;try{update=JSON.parse(msg.data);}catch(error){return;}if(update.sessionId!==state.selectedId||!state.detail)return;if(update.type==='agent'||update.type==='run_started'){state.detail.events=(state.detail.events||[]).concat([update]).slice(-500);if(update.type==='run_started')state.detail.status='running';scheduleRender();}else if(update.type==='run_finished'){state.detail.events=(state.detail.events||[]).concat([update]).slice(-500);state.detail.status='idle';loadDetail(state.selectedId).catch(function(error){toast(error.message,true);});}else if(update.type==='approval'||update.type==='approval_resolved'||update.type==='session_updated'){loadDetail(state.selectedId).catch(function(error){toast(error.message,true);});}}
|
|
394
394
|
async function selectSession(id){state.selectedId=id;state.detail=null;var token=++state.detailRequestToken;renderSessions();$('composer-shell').classList.add('hidden');$('content').innerHTML='<div class="welcome"><div class="welcome-card"><div class="welcome-mark">✦</div><h2>正在加载会话</h2><p>正在读取消息、工具记录与运行状态…</p></div></div>';if(state.eventSource)state.eventSource.close();state.eventSource=new EventSource('/api/sessions/'+encodeURIComponent(id)+'/events');state.eventSource.onmessage=handleSessionEvent;await loadDetail(id,token);}
|
|
395
|
-
async function loadConfig(){var result=await api('/api/config');state.config=result.config;$('cfg-provider').value=state.config.provider;$('cfg-base-url').value=state.config.baseURL;$('cfg-model').value=state.config.model;$('cfg-sub-model').value=state.config.subModel||'';$('cfg-vision-model').value=state.config.visionModel||'';$('cfg-effort').value=state.config.effort||'';$('cfg-context').value=state.config.contextWindow;$('cfg-max-output').value=state.config.maxOutputTokens||'';$('cfg-streaming').checked=state.config.streaming!==false;$('cfg-port').value=state.config.web.port;$('cfg-open').checked=state.config.web.openOnStart!==false;$('server-port').textContent=state.config.web.port;$('key-state').textContent=state.config.apiKeyConfigured?'当前 API Key:'+state.config.apiKeyMask:'尚未配置 API Key';$('new-cwd').value=state.config.defaultCwd||'';$('new-model').value=state.config.model;$('new-sub-model').value=state.config.subModel||'';var models=[state.config.model,state.config.subModel].concat(state.sessions.reduce(function(all,item){return all.concat([item.model,item.subModel]);},[])).filter(Boolean).filter(function(value,index,array){return array.indexOf(value)===index;});$('recent-models').innerHTML=models.map(function(model){return '<option value="'+escapeHtml(model)+'">';}).join('');}
|
|
395
|
+
async function loadConfig(){var result=await api('/api/config');state.config=result.config;$('cfg-provider').value=state.config.provider;$('cfg-base-url').value=state.config.baseURL;$('cfg-model').value=state.config.model;$('cfg-sub-model').value=state.config.subModel||'';$('cfg-vision-model').value=state.config.visionModel||'';$('cfg-effort').value=state.config.effort||'';$('cfg-context').value=state.config.contextWindow;$('cfg-max-output').value=state.config.maxOutputTokens||'';$('cfg-streaming').checked=state.config.streaming!==false;$('cfg-port').value=state.config.web.port;$('cfg-open').checked=state.config.web.openOnStart!==false;$('server-port').textContent=state.config.web.port;$('key-state').textContent=state.config.apiKeyConfigured?'当前 API Key:'+state.config.apiKeyMask:'尚未配置 API Key';$('new-cwd').value=state.config.defaultCwd||'';$('new-model').value=state.config.model;$('new-sub-model').value=state.config.subModel||'';var models=[state.config.model,state.config.subModel].concat(state.sessions.reduce(function(all,item){return all.concat([item.model,item.subModel]);},[])).filter(Boolean).filter(function(value,index,array){return array.indexOf(value)===index;});$('recent-models').innerHTML=models.map(function(model){return '<option value="'+escapeHtml(model)+'">';}).join('');}
|
|
396
396
|
$('new-session').addEventListener('click',function(){openModal('new-modal');setTimeout(function(){$('new-cwd').focus();},0);});$('open-settings').addEventListener('click',function(){loadConfig().then(function(){openModal('settings-modal');}).catch(function(error){toast(error.message,true);});});document.querySelectorAll('[data-close]').forEach(function(button){button.addEventListener('click',function(){closeModal(button.dataset.close);});});
|
|
397
397
|
$('new-form').addEventListener('submit',async function(event){event.preventDefault();try{var result=await api('/api/sessions',{method:'POST',body:JSON.stringify({cwd:$('new-cwd').value,title:$('new-title').value,model:$('new-model').value,subModel:$('new-sub-model').value,effort:$('new-effort').value})});closeModal('new-modal');$('new-title').value='';await loadSessions();await selectSession(result.session.sessionId);}catch(error){toast(error.message,true);}});
|
|
398
|
-
$('settings-form').addEventListener('submit',async function(event){event.preventDefault();var body={provider:$('cfg-provider').value,baseURL:$('cfg-base-url').value,model:$('cfg-model').value,subModel:$('cfg-sub-model').value,visionModel:$('cfg-vision-model').value,effort:$('cfg-effort').value,contextWindow:Number($('cfg-context').value),streaming:$('cfg-streaming').checked,web:{port:Number($('cfg-port').value),openOnStart:$('cfg-open').checked}};if($('cfg-max-output').value)body.maxOutputTokens=Number($('cfg-max-output').value);if($('cfg-api-key').value)body.apiKey=$('cfg-api-key').value;try{await api('/api/config',{method:'PUT',body:JSON.stringify(body)});$('cfg-api-key').value='';closeModal('settings-modal');toast('设置已保存,新配置从下一次新建会话生效');await loadConfig();}catch(error){toast(error.message,true);}});
|
|
398
|
+
$('settings-form').addEventListener('submit',async function(event){event.preventDefault();var body={provider:$('cfg-provider').value,baseURL:$('cfg-base-url').value,model:$('cfg-model').value,subModel:$('cfg-sub-model').value,visionModel:$('cfg-vision-model').value,effort:$('cfg-effort').value,contextWindow:Number($('cfg-context').value),streaming:$('cfg-streaming').checked,web:{port:Number($('cfg-port').value),openOnStart:$('cfg-open').checked}};if($('cfg-max-output').value)body.maxOutputTokens=Number($('cfg-max-output').value);if($('cfg-api-key').value)body.apiKey=$('cfg-api-key').value;try{await api('/api/config',{method:'PUT',body:JSON.stringify(body)});$('cfg-api-key').value='';closeModal('settings-modal');toast('设置已保存,新配置从下一次新建会话生效');await loadConfig();}catch(error){toast(error.message,true);}});
|
|
399
399
|
async function uploadAttachment(sessionId,file){var response=await fetch('/api/sessions/'+encodeURIComponent(sessionId)+'/attachments?name='+encodeURIComponent(file.name||'image'),{method:'POST',headers:{'content-type':file.type||'application/octet-stream'},body:file});var result=await response.json().catch(function(){return{error:'上传响应不是有效 JSON'};});if(!response.ok)throw new Error(result.error||('HTTP '+response.status));return result.attachment;}
|
|
400
|
-
async function handleAttachmentFiles(files){var sessionId=state.selectedId;if(!sessionId||state.uploading)return;var candidates=[].slice.call(files||[]).filter(function(file){return ['image/png','image/jpeg','image/webp','image/gif'].includes(file.type);});var existing=state.attachmentDrafts[sessionId]||[];if(existing.length+candidates.length>10){toast('每条消息最多添加 10 张图片',true);return;}if(!candidates.length){toast('仅支持 PNG、JPEG、WebP、GIF 图片',true);return;}state.uploading=true;if(state.detail)renderDetail();try{for(var i=0;i<candidates.length;i++){if(candidates[i].size>20*1024*1024)throw new Error('单张图片不能超过 20 MB:'+candidates[i].name);existing.push(await uploadAttachment(sessionId,candidates[i]));state.attachmentDrafts[sessionId]=existing;renderAttachmentDrafts();}}catch(error){toast(error.message,true);}finally{state.uploading=false;if(state.detail)renderDetail();$('attachment-input').value='';}}
|
|
400
|
+
async function handleAttachmentFiles(files){var sessionId=state.selectedId;if(!sessionId||state.uploading)return;var candidates=[].slice.call(files||[]).filter(function(file){return ['image/png','image/jpeg','image/webp','image/gif'].includes(file.type);});var existing=state.attachmentDrafts[sessionId]||[];if(existing.length+candidates.length>10){toast('每条消息最多添加 10 张图片',true);return;}if(!candidates.length){toast('仅支持 PNG、JPEG、WebP、GIF 图片',true);return;}state.uploading=true;if(state.detail)renderDetail();try{for(var i=0;i<candidates.length;i++){if(candidates[i].size>20*1024*1024)throw new Error('单张图片不能超过 20 MB:'+candidates[i].name);existing.push(await uploadAttachment(sessionId,candidates[i]));state.attachmentDrafts[sessionId]=existing;renderAttachmentDrafts();}}catch(error){toast(error.message,true);}finally{state.uploading=false;if(state.detail)renderDetail();$('attachment-input').value='';}}
|
|
401
401
|
async function removeAttachment(id){var sessionId=state.selectedId;if(!sessionId)return;try{await api('/api/sessions/'+encodeURIComponent(sessionId)+'/attachments/'+encodeURIComponent(id),{method:'DELETE'});state.attachmentDrafts[sessionId]=(state.attachmentDrafts[sessionId]||[]).filter(function(item){return item.attachmentId!==id;});renderAttachmentDrafts();}catch(error){toast(error.message,true);}}
|
|
402
402
|
async function send(){var sessionId=state.selectedId;var text=$('prompt').value;var attachments=currentAttachments();if(!sessionId||(!text.trim()&&!attachments.length)||state.uploading)return;try{var patch={model:$('session-model').value,subModel:$('session-sub-model').value,effort:$('session-effort').value};if(patch.model!==state.detail.model||patch.subModel!==state.detail.subModel||patch.effort!==state.detail.effort){var updated=await api('/api/sessions/'+encodeURIComponent(sessionId),{method:'PATCH',body:JSON.stringify(patch)});if(state.selectedId===sessionId){state.detail=Object.assign({},state.detail,updated.session);renderDetail();}await loadSessions();}await api('/api/sessions/'+encodeURIComponent(sessionId)+'/messages',{method:'POST',body:JSON.stringify({text:text,attachmentIds:attachments.map(function(item){return item.attachmentId;})})});delete state.configDrafts[sessionId];delete state.promptDrafts[sessionId];delete state.attachmentDrafts[sessionId];if(state.selectedId===sessionId){$('prompt').value='';renderAttachmentDrafts();state.detail.events=[];state.detail.status='running';renderDetail();}var token=++state.detailRequestToken;await loadDetail(sessionId,token);}catch(error){toast(error.message,true);}}
|
|
403
403
|
['session-model','session-sub-model','session-effort'].forEach(function(id){$(id).addEventListener('input',rememberDraft);$(id).addEventListener('change',rememberDraft);});
|
|
@@ -56,8 +56,14 @@ function parseArgs(argv) {
|
|
|
56
56
|
function readConfig() {
|
|
57
57
|
const args = parseArgs(process.argv.slice(2));
|
|
58
58
|
const upstreamRaw = args.upstream?.toString() ??
|
|
59
|
-
process.env.CHATCCC_LITELLM_PROXY_UPSTREAM
|
|
60
|
-
|
|
59
|
+
process.env.CHATCCC_LITELLM_PROXY_UPSTREAM;
|
|
60
|
+
if (!upstreamRaw?.trim()) {
|
|
61
|
+
throw new Error("Missing proxy upstream: set --upstream or CHATCCC_LITELLM_PROXY_UPSTREAM");
|
|
62
|
+
}
|
|
63
|
+
const upstream = new URL(upstreamRaw.trim());
|
|
64
|
+
if (upstream.protocol !== "http:" && upstream.protocol !== "https:") {
|
|
65
|
+
throw new Error("Upstream must use http:// or https://");
|
|
66
|
+
}
|
|
61
67
|
const portRaw = args.port ?? Number(process.env.CHATCCC_LITELLM_PROXY_PORT ?? "18081");
|
|
62
68
|
if (!Number.isInteger(portRaw) || portRaw <= 0 || portRaw > 65535) {
|
|
63
69
|
throw new Error(`Invalid port: ${portRaw}`);
|
|
@@ -65,7 +71,7 @@ function readConfig() {
|
|
|
65
71
|
return {
|
|
66
72
|
host: args.host ?? process.env.CHATCCC_LITELLM_PROXY_HOST ?? "127.0.0.1",
|
|
67
73
|
port: portRaw,
|
|
68
|
-
upstream
|
|
74
|
+
upstream,
|
|
69
75
|
logDir: args.logDir ?? process.env.CHATCCC_LITELLM_PROXY_LOG_DIR ??
|
|
70
76
|
join(homedir(), ".chatccc", "logs", "litellm-proxy"),
|
|
71
77
|
logSecrets: args.logSecrets ?? process.env.CHATCCC_LITELLM_PROXY_LOG_SECRETS === "1",
|
|
@@ -77,7 +83,7 @@ function printHelp() {
|
|
|
77
83
|
Options:
|
|
78
84
|
--host <host> Listen host, default 127.0.0.1
|
|
79
85
|
--port <port> Listen port, default 18081
|
|
80
|
-
--upstream <url> Upstream LiteLLM base URL
|
|
86
|
+
--upstream <url> Upstream LiteLLM base URL; required unless set via environment
|
|
81
87
|
--log-dir <path> Log directory, default %USERPROFILE%/.chatccc/logs/litellm-proxy
|
|
82
88
|
--log-secrets Log sensitive headers instead of redacting them
|
|
83
89
|
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/** ChatCCC's streamed-response watchdog; not a provider or tool-execution timeout. */
|
|
2
|
+
export function getDefaultResponseStallTimeoutMs(tool) {
|
|
3
|
+
return (tool === "ccc" ? 10 : 3) * 60 * 1000;
|
|
4
|
+
}
|
|
5
|
+
export function formatResponseStallRecoveryExhaustedNotice(tool) {
|
|
6
|
+
const minutes = getDefaultResponseStallTimeoutMs(tool) / 60_000;
|
|
7
|
+
return `⚠️ 自动续跑仍连续 ${minutes} 分钟没有生成新回复,本次不再自动继续。`;
|
|
8
|
+
}
|
|
1
9
|
/**
|
|
2
10
|
* Tracks how long the displayed output character count has remained unchanged.
|
|
3
11
|
* Leaving a monitored phase clears the window; returning starts a fresh one.
|
package/dist/src/session.js
CHANGED
|
@@ -18,7 +18,7 @@ import { buildImSkillsPromptCached, exportSkillSubDocs, sessionImSkillsCacheDir,
|
|
|
18
18
|
import { clearAgentCapabilityGrants, issueAgentCapabilityGrant, } from "./agent-capability-grants.js";
|
|
19
19
|
import { createFinalReplyDelivery } from "./final-reply-delivery.js";
|
|
20
20
|
import { applyPrivacy } from "./privacy.js";
|
|
21
|
-
import { hasResponseStalled, observeResponseProgress } from "./response-stall.js";
|
|
21
|
+
import { formatResponseStallRecoveryExhaustedNotice, getDefaultResponseStallTimeoutMs, hasResponseStalled, observeResponseProgress, } from "./response-stall.js";
|
|
22
22
|
import { classifyTerminalError, formatTerminalErrorNotice, formatTerminalErrorReason, } from "./terminal-error.js";
|
|
23
23
|
import { MAX_PROCESSED, clearFeishuMessageLedgerMemory, processedMessages, } from "./feishu-message-ingress.js";
|
|
24
24
|
export { MAX_PROCESSED, processedMessages };
|
|
@@ -94,11 +94,12 @@ const DEFAULT_RESPONSE_STALL_CHECK_INTERVAL_MS = 5000;
|
|
|
94
94
|
const DEFAULT_FINAL_RESPONSE_CLOSE_TIMEOUT_MS = 10_000;
|
|
95
95
|
export const RESPONSE_STALL_RECOVERY_PROMPT = "完成了吗?如果没完成继续";
|
|
96
96
|
export const RESPONSE_STALL_RECOVERY_NOTICE = `检测到会话停滞,正在自动确认并继续。\n\n${RESPONSE_STALL_RECOVERY_PROMPT}`;
|
|
97
|
-
export const RESPONSE_STALL_RECOVERY_EXHAUSTED_NOTICE = "
|
|
97
|
+
export const RESPONSE_STALL_RECOVERY_EXHAUSTED_NOTICE = formatResponseStallRecoveryExhaustedNotice("claude");
|
|
98
98
|
const RESPONSE_STALL_RECOVERY_DELAY_MS = 200;
|
|
99
99
|
let processMonitorIntervalMs = DEFAULT_PROCESS_MONITOR_INTERVAL_MS;
|
|
100
100
|
let avatarRefreshIntervalMs = DEFAULT_AVATAR_REFRESH_INTERVAL_MS;
|
|
101
|
-
|
|
101
|
+
// Test override only; normal turns resolve their own adapter-specific default.
|
|
102
|
+
let responseStallTimeoutMs;
|
|
102
103
|
let responseStallCheckIntervalMs = DEFAULT_RESPONSE_STALL_CHECK_INTERVAL_MS;
|
|
103
104
|
let finalResponseCloseTimeoutMs = DEFAULT_FINAL_RESPONSE_CLOSE_TIMEOUT_MS;
|
|
104
105
|
let isProcessAliveImpl = (pid) => {
|
|
@@ -140,7 +141,7 @@ export function _setResponseStallTimeoutForTest(ms) {
|
|
|
140
141
|
responseStallTimeoutMs = ms;
|
|
141
142
|
}
|
|
142
143
|
export function _resetResponseStallTimeoutForTest() {
|
|
143
|
-
responseStallTimeoutMs =
|
|
144
|
+
responseStallTimeoutMs = undefined;
|
|
144
145
|
}
|
|
145
146
|
export function _setResponseStallCheckIntervalForTest(ms) {
|
|
146
147
|
responseStallCheckIntervalMs = ms;
|
|
@@ -1039,7 +1040,7 @@ export async function initClaudeSession(tool, overrideCwd, chatId) {
|
|
|
1039
1040
|
// 先固定对外错误,再 abort 适配器,避免适配器自己的 abort 错误赢得竞态。
|
|
1040
1041
|
reject(timeoutError);
|
|
1041
1042
|
createController.abort();
|
|
1042
|
-
}, responseStallTimeoutMs);
|
|
1043
|
+
}, responseStallTimeoutMs ?? DEFAULT_RESPONSE_STALL_TIMEOUT_MS);
|
|
1043
1044
|
createTimeout.unref?.();
|
|
1044
1045
|
});
|
|
1045
1046
|
let result;
|
|
@@ -1316,11 +1317,12 @@ export async function runAgentSession(sessionId, userText, platform, _chatId, ms
|
|
|
1316
1317
|
let streamTerminalError;
|
|
1317
1318
|
let runOutcome = "error";
|
|
1318
1319
|
const responseStallDetectionEnabled = adapter.responseStallDetectionEnabled !== false;
|
|
1320
|
+
const stallTimeoutMs = responseStallTimeoutMs ?? getDefaultResponseStallTimeoutMs(tool);
|
|
1319
1321
|
const runningPrompt = activePrompts.get(sessionId);
|
|
1320
1322
|
if (runningPrompt) {
|
|
1321
1323
|
startPromptAvatarRefresh(sessionId, tool, platform, runningPrompt);
|
|
1322
1324
|
// 在消费第一个事件前建立阶段感知的零字符基线;启动阶段不计时,只有后续
|
|
1323
|
-
// 收到明确的 responding
|
|
1325
|
+
// 收到明确的 responding 状态后才会启动回复停滞保护(CCC 10 分钟,其他 3 分钟)。
|
|
1324
1326
|
runningPrompt.responseProgress = observeResponseProgress(undefined, monitorsOutputProgress(activityTracker.activity.kind), 0, activityTracker.activity.startedAt);
|
|
1325
1327
|
const checkResponseStall = async () => {
|
|
1326
1328
|
const current = activePrompts.get(sessionId);
|
|
@@ -1334,7 +1336,7 @@ export async function runAgentSession(sessionId, userText, platform, _chatId, ms
|
|
|
1334
1336
|
|| current.autoEnded
|
|
1335
1337
|
|| current.finalResponseObserved
|
|
1336
1338
|
|| !monitorsOutputProgress(activityTracker.activity.kind)
|
|
1337
|
-
|| !hasResponseStalled(current.responseProgress, Date.now(),
|
|
1339
|
+
|| !hasResponseStalled(current.responseProgress, Date.now(), stallTimeoutMs)) {
|
|
1338
1340
|
return;
|
|
1339
1341
|
}
|
|
1340
1342
|
const autoEndedAt = Date.now();
|
|
@@ -1383,7 +1385,7 @@ export async function runAgentSession(sessionId, userText, platform, _chatId, ms
|
|
|
1383
1385
|
}
|
|
1384
1386
|
current.controller.abort();
|
|
1385
1387
|
await killProcessTree(current.processPid);
|
|
1386
|
-
console.warn(`[${ts()}] [RESPONSE-STALL] Session ${sessionId} auto-ended after
|
|
1388
|
+
console.warn(`[${ts()}] [RESPONSE-STALL] Session ${sessionId} auto-ended after ${stallTimeoutMs / 60_000} minutes without reply progress`);
|
|
1387
1389
|
};
|
|
1388
1390
|
if (responseStallDetectionEnabled) {
|
|
1389
1391
|
const responseStallMonitor = setInterval(() => {
|
|
@@ -1666,7 +1668,7 @@ export async function runAgentSession(sessionId, userText, platform, _chatId, ms
|
|
|
1666
1668
|
if (wasAutoRecovery) {
|
|
1667
1669
|
// 这是紧接第一次停滞而启动的恢复轮;再次发生相同停滞即终止
|
|
1668
1670
|
// 自动链,避免第三轮及之后的无限续跑。
|
|
1669
|
-
await pp.sendText(activeAutoEnded,
|
|
1671
|
+
await pp.sendText(activeAutoEnded, formatResponseStallRecoveryExhaustedNotice(tool)).catch(() => { });
|
|
1670
1672
|
}
|
|
1671
1673
|
else if (hasAutoRecoveryReservation(sessionId)) {
|
|
1672
1674
|
// 用户可见提示与内部恢复 prompt 分离:提示发送失败不影响恢复,
|
package/dist/src/web-ui.js
CHANGED
|
@@ -922,12 +922,12 @@ header .badge{font-size:13px;padding:4px 12px;border-radius:12px;font-weight:500
|
|
|
922
922
|
</div>
|
|
923
923
|
<div class="form-group">
|
|
924
924
|
<label>子模型(选填)</label>
|
|
925
|
-
<input type="text" id="field-CHATCCC_CCC_SUB_MODEL" placeholder="留空跟随主模型;用于压缩摘要、子代理任务等轻量环节">
|
|
926
|
-
</div>
|
|
927
|
-
<div class="form-group">
|
|
928
|
-
<label>图片模型(选填)</label>
|
|
929
|
-
<input type="text" id="field-CHATCCC_CCC_VISION_MODEL" placeholder="例如 deepseek-flash;留空跟随 DeepCCC 设置,未配置则由主模型直接看图">
|
|
930
|
-
</div>
|
|
925
|
+
<input type="text" id="field-CHATCCC_CCC_SUB_MODEL" placeholder="留空跟随主模型;用于压缩摘要、子代理任务等轻量环节">
|
|
926
|
+
</div>
|
|
927
|
+
<div class="form-group">
|
|
928
|
+
<label>图片模型(选填)</label>
|
|
929
|
+
<input type="text" id="field-CHATCCC_CCC_VISION_MODEL" placeholder="例如 deepseek-flash;留空跟随 DeepCCC 设置,未配置则由主模型直接看图">
|
|
930
|
+
</div>
|
|
931
931
|
<div class="form-group">
|
|
932
932
|
<label>备选模型(选填)</label>
|
|
933
933
|
<input type="text" id="field-CHATCCC_CCC_ALTERNATIVE_MODEL" placeholder="加入 /model 列表,便于会话内切换">
|
|
@@ -1302,8 +1302,8 @@ header .badge{font-size:13px;padding:4px 12px;border-radius:12px;font-weight:500
|
|
|
1302
1302
|
<div class="config-row"><span class="key">Base URL</span><span class="val" id="cfg-CCC_BASE_URL">-</span></div>
|
|
1303
1303
|
<div class="config-row"><span class="key">API 协议</span><span class="val" id="cfg-CCC_PROVIDER">-</span></div>
|
|
1304
1304
|
<div class="config-row"><span class="key">模型</span><span class="val" id="cfg-CCC_MODEL">-</span></div>
|
|
1305
|
-
<div class="config-row"><span class="key">子模型</span><span class="val" id="cfg-CCC_SUB_MODEL">-</span></div>
|
|
1306
|
-
<div class="config-row"><span class="key">图片模型</span><span class="val" id="cfg-CCC_VISION_MODEL">-</span></div>
|
|
1305
|
+
<div class="config-row"><span class="key">子模型</span><span class="val" id="cfg-CCC_SUB_MODEL">-</span></div>
|
|
1306
|
+
<div class="config-row"><span class="key">图片模型</span><span class="val" id="cfg-CCC_VISION_MODEL">-</span></div>
|
|
1307
1307
|
<div class="config-row"><span class="key">备选模型</span><span class="val" id="cfg-CCC_ALTERNATIVE_MODEL">-</span></div>
|
|
1308
1308
|
<div class="config-row"><span class="key">Effort</span><span class="val" id="cfg-CCC_EFFORT">-</span></div>
|
|
1309
1309
|
<div class="config-row"><span class="key">最大输出 Token</span><span class="val" id="cfg-CCC_MAX_OUTPUT_TOKENS">-</span></div>
|
|
@@ -1358,7 +1358,7 @@ const AGENT_FIELDS = {
|
|
|
1358
1358
|
claude: ['CHATCCC_ANTHROPIC_MODEL','CHATCCC_ANTHROPIC_SUBAGENT_MODEL','CHATCCC_ANTHROPIC_EFFORT','CHATCCC_ANTHROPIC_API_KEY','CHATCCC_ANTHROPIC_BASE_URL','CHATCCC_ANTHROPIC_MAX_TURN'],
|
|
1359
1359
|
cursor: ['CHATCCC_CURSOR_PATH','CHATCCC_CURSOR_MODEL','CHATCCC_CURSOR_ALTERNATIVE_MODEL','CHATCCC_CURSOR_AVATAR_BATTERY_MODE','CHATCCC_CURSOR_ON_DEMAND_MONTHLY_BUDGET'],
|
|
1360
1360
|
codex: ['CHATCCC_CODEX_PATH','CHATCCC_CODEX_MODEL','CHATCCC_CODEX_ALTERNATIVE_MODEL','CHATCCC_CODEX_EFFORT','CHATCCC_CODEX_FAST_MODE'],
|
|
1361
|
-
ccc: ['CHATCCC_CCC_API_KEY','CHATCCC_CCC_BASE_URL','CHATCCC_CCC_MODEL','CHATCCC_CCC_SUB_MODEL','CHATCCC_CCC_VISION_MODEL','CHATCCC_CCC_ALTERNATIVE_MODEL','CHATCCC_CCC_EFFORT','CHATCCC_CCC_MAX_OUTPUT_TOKENS','CHATCCC_CCC_PROVIDER','CHATCCC_CCC_GIT_COAUTHOR','CHATCCC_CCC_CONTEXT_WINDOW'],
|
|
1361
|
+
ccc: ['CHATCCC_CCC_API_KEY','CHATCCC_CCC_BASE_URL','CHATCCC_CCC_MODEL','CHATCCC_CCC_SUB_MODEL','CHATCCC_CCC_VISION_MODEL','CHATCCC_CCC_ALTERNATIVE_MODEL','CHATCCC_CCC_EFFORT','CHATCCC_CCC_MAX_OUTPUT_TOKENS','CHATCCC_CCC_PROVIDER','CHATCCC_CCC_GIT_COAUTHOR','CHATCCC_CCC_CONTEXT_WINDOW'],
|
|
1362
1362
|
dsh: ['CHATCCC_DSH_API_KEY','CHATCCC_DSH_BASE_URL','CHATCCC_DSH_MODEL','CHATCCC_DSH_SUB_MODEL','CHATCCC_DSH_ALTERNATIVE_MODEL','CHATCCC_DSH_PROVIDER','CHATCCC_DSH_MAX_TOKENS']
|
|
1363
1363
|
};
|
|
1364
1364
|
const FEISHU_FIELDS = ['CHATCCC_APP_ID','CHATCCC_APP_SECRET'];
|
|
@@ -1753,8 +1753,8 @@ function renderStep2() {
|
|
|
1753
1753
|
var coAuthorField = document.getElementById('field-CHATCCC_CCC_GIT_COAUTHOR');
|
|
1754
1754
|
if (coAuthorField) coAuthorField.value = c.ccc.gitCoAuthor == null ? 'inherit' : (c.ccc.gitCoAuthor ? 'enabled' : 'disabled');
|
|
1755
1755
|
prefillNested('field-CHATCCC_CCC_MODEL', c.ccc.model);
|
|
1756
|
-
prefillNested('field-CHATCCC_CCC_SUB_MODEL', c.ccc.subModel);
|
|
1757
|
-
prefillNested('field-CHATCCC_CCC_VISION_MODEL', c.ccc.visionModel);
|
|
1756
|
+
prefillNested('field-CHATCCC_CCC_SUB_MODEL', c.ccc.subModel);
|
|
1757
|
+
prefillNested('field-CHATCCC_CCC_VISION_MODEL', c.ccc.visionModel);
|
|
1758
1758
|
prefillNested('field-CHATCCC_CCC_ALTERNATIVE_MODEL', c.ccc.alternativeModel);
|
|
1759
1759
|
prefillNested('field-CHATCCC_CCC_EFFORT', c.ccc.effort);
|
|
1760
1760
|
prefillNested('field-CHATCCC_CCC_MAX_OUTPUT_TOKENS', c.ccc.maxOutputTokens);
|
|
@@ -1963,8 +1963,8 @@ function renderStep3() {
|
|
|
1963
1963
|
lines.push('<div class="config-row"><span class="key">API Key</span><span class="val">' + (vars.CHATCCC_CCC_API_KEY ? '***已设置***' : '(留空)') + '</span></div>');
|
|
1964
1964
|
lines.push('<div class="config-row"><span class="key">Base URL</span><span class="val">' + (vars.CHATCCC_CCC_BASE_URL || '(留空)') + '</span></div>');
|
|
1965
1965
|
lines.push('<div class="config-row"><span class="key">模型</span><span class="val">' + (vars.CHATCCC_CCC_MODEL || '(留空)') + '</span></div>');
|
|
1966
|
-
lines.push('<div class="config-row"><span class="key">子模型</span><span class="val">' + (vars.CHATCCC_CCC_SUB_MODEL || '(留空,跟随主模型)') + '</span></div>');
|
|
1967
|
-
lines.push('<div class="config-row"><span class="key">图片模型</span><span class="val">' + (vars.CHATCCC_CCC_VISION_MODEL || '(跟随 DeepCCC)') + '</span></div>');
|
|
1966
|
+
lines.push('<div class="config-row"><span class="key">子模型</span><span class="val">' + (vars.CHATCCC_CCC_SUB_MODEL || '(留空,跟随主模型)') + '</span></div>');
|
|
1967
|
+
lines.push('<div class="config-row"><span class="key">图片模型</span><span class="val">' + (vars.CHATCCC_CCC_VISION_MODEL || '(跟随 DeepCCC)') + '</span></div>');
|
|
1968
1968
|
lines.push('<div class="config-row"><span class="key">备选模型</span><span class="val">' + (vars.CHATCCC_CCC_ALTERNATIVE_MODEL || '(留空)') + '</span></div>');
|
|
1969
1969
|
lines.push('<div class="config-row"><span class="key">Effort</span><span class="val">' + (vars.CHATCCC_CCC_EFFORT || '(留空)') + '</span></div>');
|
|
1970
1970
|
lines.push('<div class="config-row"><span class="key">最大输出 Token</span><span class="val">' + (vars.CHATCCC_CCC_MAX_OUTPUT_TOKENS || '(跟随 DeepCCC)') + '</span></div>');
|
|
@@ -2197,8 +2197,8 @@ function updateDashboardUI() {
|
|
|
2197
2197
|
document.getElementById('cfg-CCC_BASE_URL').textContent = (c.ccc && c.ccc.DEEPSEEK_BASE_URL) || '(留空)';
|
|
2198
2198
|
document.getElementById('cfg-CCC_PROVIDER').textContent = (c.ccc && c.ccc.provider) ? c.ccc.provider : '(跟随 DeepCCC 内核配置)';
|
|
2199
2199
|
document.getElementById('cfg-CCC_MODEL').textContent = (c.ccc && c.ccc.model) || '(留空)';
|
|
2200
|
-
document.getElementById('cfg-CCC_SUB_MODEL').textContent = (c.ccc && c.ccc.subModel) || '(留空,跟随主模型)';
|
|
2201
|
-
document.getElementById('cfg-CCC_VISION_MODEL').textContent = (c.ccc && c.ccc.visionModel) || '(跟随 DeepCCC)';
|
|
2200
|
+
document.getElementById('cfg-CCC_SUB_MODEL').textContent = (c.ccc && c.ccc.subModel) || '(留空,跟随主模型)';
|
|
2201
|
+
document.getElementById('cfg-CCC_VISION_MODEL').textContent = (c.ccc && c.ccc.visionModel) || '(跟随 DeepCCC)';
|
|
2202
2202
|
document.getElementById('cfg-CCC_ALTERNATIVE_MODEL').textContent = (c.ccc && c.ccc.alternativeModel) || '(留空)';
|
|
2203
2203
|
document.getElementById('cfg-CCC_EFFORT').textContent = (c.ccc && c.ccc.effort) || '(跟随 DeepCCC 内核配置)';
|
|
2204
2204
|
document.getElementById('cfg-CCC_MAX_OUTPUT_TOKENS').textContent = c.ccc && c.ccc.maxOutputTokens
|
|
@@ -2292,7 +2292,7 @@ function editSection(section) {
|
|
|
2292
2292
|
'CHATCCC_CCC_API_KEY': 'API Key', 'CHATCCC_CCC_BASE_URL': 'Base URL',
|
|
2293
2293
|
'CHATCCC_CCC_PROVIDER': 'API 协议(选填)',
|
|
2294
2294
|
'CHATCCC_CCC_GIT_COAUTHOR': 'Git 提交共同作者',
|
|
2295
|
-
'CHATCCC_CCC_MODEL': '模型', 'CHATCCC_CCC_SUB_MODEL': '子模型', 'CHATCCC_CCC_VISION_MODEL': '图片模型', 'CHATCCC_CCC_ALTERNATIVE_MODEL': '备选模型', 'CHATCCC_CCC_EFFORT': 'Effort', 'CHATCCC_CCC_MAX_OUTPUT_TOKENS': '最大输出 Token', 'CHATCCC_CCC_CONTEXT_WINDOW': '上下文窗口',
|
|
2295
|
+
'CHATCCC_CCC_MODEL': '模型', 'CHATCCC_CCC_SUB_MODEL': '子模型', 'CHATCCC_CCC_VISION_MODEL': '图片模型', 'CHATCCC_CCC_ALTERNATIVE_MODEL': '备选模型', 'CHATCCC_CCC_EFFORT': 'Effort', 'CHATCCC_CCC_MAX_OUTPUT_TOKENS': '最大输出 Token', 'CHATCCC_CCC_CONTEXT_WINDOW': '上下文窗口',
|
|
2296
2296
|
'CHATCCC_DSH_API_KEY': 'API Key', 'CHATCCC_DSH_BASE_URL': 'Base URL', 'CHATCCC_DSH_MODEL': '模型', 'CHATCCC_DSH_SUB_MODEL': '子模型', 'CHATCCC_DSH_ALTERNATIVE_MODEL': '备选模型', 'CHATCCC_DSH_PROVIDER': 'Provider 路由', 'CHATCCC_DSH_MAX_TOKENS': '单次最大输出 Tokens'
|
|
2297
2297
|
};
|
|
2298
2298
|
var hintMap = {
|
|
@@ -2350,8 +2350,8 @@ function editSection(section) {
|
|
|
2350
2350
|
else if (key === 'CHATCCC_CCC_PROVIDER') val = state.config.ccc.provider || '';
|
|
2351
2351
|
else if (key === 'CHATCCC_CCC_GIT_COAUTHOR') val = state.config.ccc.gitCoAuthor == null ? 'inherit' : (state.config.ccc.gitCoAuthor ? 'enabled' : 'disabled');
|
|
2352
2352
|
else if (key === 'CHATCCC_CCC_MODEL') val = state.config.ccc.model || '';
|
|
2353
|
-
else if (key === 'CHATCCC_CCC_SUB_MODEL') val = state.config.ccc.subModel || '';
|
|
2354
|
-
else if (key === 'CHATCCC_CCC_VISION_MODEL') val = state.config.ccc.visionModel || '';
|
|
2353
|
+
else if (key === 'CHATCCC_CCC_SUB_MODEL') val = state.config.ccc.subModel || '';
|
|
2354
|
+
else if (key === 'CHATCCC_CCC_VISION_MODEL') val = state.config.ccc.visionModel || '';
|
|
2355
2355
|
else if (key === 'CHATCCC_CCC_ALTERNATIVE_MODEL') val = state.config.ccc.alternativeModel || '';
|
|
2356
2356
|
else if (key === 'CHATCCC_CCC_EFFORT') val = state.config.ccc.effort || '';
|
|
2357
2357
|
else if (key === 'CHATCCC_CCC_MAX_OUTPUT_TOKENS') val = state.config.ccc.maxOutputTokens || '';
|