chatccc 0.2.306 → 0.2.308

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.
@@ -1,87 +1,217 @@
1
+ import { compactJsonValue } from "./tool-argument-replay.js";
2
+ import { instructionPath } from "./instruction-replay.js";
1
3
  export const DEFAULT_STEP_TOOL_CONTEXT_CHARS = 96_000;
2
4
  export const DEFAULT_STEP_TOOL_RESULT_CHARS = 24_000;
3
5
  export const DEFAULT_STEP_RECENT_RESULTS = 4;
6
+ export const DEFAULT_STEP_TOOL_INPUT_CHARS = 64_000;
7
+ export const DEFAULT_STEP_INSTRUCTION_CHARS = 32_000;
4
8
  const OMITTED = "[earlier tool result omitted from subsequent model steps to keep this turn within its context budget; rerun a focused read/search if still needed]";
5
9
  const TRUNCATED = "...[tool result shortened for subsequent model steps]...";
6
- function serialized(output) {
10
+ function serialized(value) {
7
11
  try {
8
- return JSON.stringify(output);
12
+ return JSON.stringify(value) ?? String(value);
9
13
  }
10
14
  catch {
11
- return String(output);
15
+ return String(value);
12
16
  }
13
17
  }
18
+ function excerpt(value, maximum, marker) {
19
+ if (value.length <= maximum)
20
+ return value;
21
+ const available = Math.max(0, maximum - marker.length);
22
+ const head = Math.ceil(available * 0.6);
23
+ const tail = Math.max(0, available - head);
24
+ return value.slice(0, head) + marker + (tail ? value.slice(-tail) : "");
25
+ }
14
26
  function shortened(output, maximum) {
15
27
  const raw = serialized(output);
16
28
  if (raw.length <= maximum)
17
29
  return output;
18
- const available = Math.max(0, maximum - TRUNCATED.length - 2);
19
- const head = Math.ceil(available * 0.6);
20
- const tail = Math.max(0, available - head);
21
- return { type: "text", value: `${raw.slice(0, head)}${TRUNCATED}${tail ? raw.slice(-tail) : ""}` };
30
+ let allowance = Math.max(0, maximum - 40);
31
+ // Escaping happens again when the excerpt is serialized into a model message.
32
+ for (let attempt = 0; attempt < 12; attempt++) {
33
+ const result = { type: "text", value: excerpt(raw, allowance, TRUNCATED) };
34
+ const size = serialized(result).length;
35
+ if (size <= maximum)
36
+ return result;
37
+ allowance = Math.max(0, allowance - Math.max(1, size - maximum));
38
+ }
39
+ return { type: "text", value: "[output omitted; reread evidence]" };
22
40
  }
23
- /** Bound tool payload replayed by the AI SDK between steps of one turn. */
41
+ function recordValue(output) {
42
+ let value = "value" in output ? output.value : undefined;
43
+ if (typeof value === "string" && value.trim().startsWith("{")) {
44
+ try {
45
+ value = JSON.parse(value);
46
+ }
47
+ catch {
48
+ return;
49
+ }
50
+ }
51
+ return value && typeof value === "object" && !Array.isArray(value)
52
+ ? value : undefined;
53
+ }
54
+ function executionSummary(output) {
55
+ const value = recordValue(output);
56
+ const failed = output.type === "error-text" || output.type === "error-json"
57
+ || value?.timedOut === true || value?.is_error === true
58
+ || (typeof value?.exitCode === "number" && value.exitCode !== 0);
59
+ if (!failed && (!value || !("exitCode" in value || "taskId" in value || "running" in value)))
60
+ return;
61
+ const summary = {
62
+ contextSummary: true, executionFailed: failed, originalOutputChars: serialized(output).length,
63
+ outputOmitted: true,
64
+ notice: "Output body is not retained here; inspect saved artifacts before claiming it was read.",
65
+ };
66
+ if (value) {
67
+ for (const key of ["exitCode", "signal", "timedOut", "running", "backgrounded", "taskId", "cwd", "command"]) {
68
+ const item = value[key];
69
+ if (typeof item === "string")
70
+ summary[key] = excerpt(item, 600, "...[omitted]...");
71
+ else if (item === null || typeof item === "number" || typeof item === "boolean")
72
+ summary[key] = item;
73
+ }
74
+ if (failed && typeof value.stderr === "string")
75
+ summary.stderr = excerpt(value.stderr, 1200, "...[stderr omitted]...");
76
+ if (failed && typeof value.error === "string")
77
+ summary.error = excerpt(value.error, 600, "...[error omitted]...");
78
+ }
79
+ else if ("value" in output)
80
+ summary.error = excerpt(serialized(output.value), 1200, "...[error omitted]...");
81
+ return { output: { type: "json", value: summary }, failed };
82
+ }
83
+ /** Preserve argument keys/types, while trimming oversized historical string values. */
84
+ function shortenedInput(input, maximum, preserveArgument) {
85
+ return compactJsonValue(input, maximum, false, preserveArgument);
86
+ }
87
+ /** Changes only a model-facing clone, never executed calls or persisted history. */
24
88
  export function compactToolLoopMessages(input, options = {}) {
25
89
  const maximum = Math.max(1_000, options.maxToolChars ?? DEFAULT_STEP_TOOL_CONTEXT_CHARS);
26
90
  const perResult = Math.max(500, options.maxResultChars ?? DEFAULT_STEP_TOOL_RESULT_CHARS);
27
- const keepRecent = Math.max(0, options.keepRecentResults ?? DEFAULT_STEP_RECENT_RESULTS);
91
+ const keepRecent = Math.max(0, Math.floor(options.keepRecentResults ?? DEFAULT_STEP_RECENT_RESULTS));
28
92
  const messages = structuredClone(input);
29
- const refs = [];
30
- for (let message = 0; message < messages.length; message += 1) {
31
- const item = messages[message];
32
- if (item.role !== "tool" || !Array.isArray(item.content))
93
+ const callInstructions = new Map();
94
+ const calls = [];
95
+ for (const message of messages) {
96
+ if (message.role !== "assistant" || !Array.isArray(message.content))
33
97
  continue;
34
- for (let part = 0; part < item.content.length; part += 1) {
35
- const content = item.content[part];
36
- if (content.type !== "tool-result")
98
+ for (const part of message.content) {
99
+ if (part.type !== "tool-call")
37
100
  continue;
38
- refs.push({ message, part, original: serialized(content.output).length });
101
+ if (part.toolName === "read_file")
102
+ callInstructions.set(part.toolCallId, instructionPath(part.input));
103
+ calls.push({ part, original: serialized(part.input).length });
39
104
  }
40
105
  }
41
- const originalToolChars = refs.reduce((sum, ref) => sum + ref.original, 0);
42
- let retainedToolChars = 0;
43
- let compactedResults = 0;
44
- const omittedOutput = { type: "text", value: OMITTED };
45
- const omittedSize = serialized(omittedOutput).length;
46
- const recentCount = Math.min(keepRecent, refs.length);
47
- const olderCount = refs.length - recentCount;
48
- const recentCap = recentCount > 0
49
- ? Math.max(500, Math.min(perResult, Math.floor(Math.max(0, maximum - olderCount * omittedSize) / recentCount)))
50
- : perResult;
51
- const prepared = refs.map((ref, index) => {
52
- const message = messages[ref.message];
106
+ const originalInputChars = calls.reduce((sum, call) => sum + call.original, 0);
107
+ const inputMaximum = Math.max(1_000, options.maxToolInputChars ?? DEFAULT_STEP_TOOL_INPUT_CHARS);
108
+ if (originalInputChars > inputMaximum) {
109
+ const olderCount = Math.max(0, calls.length - keepRecent);
110
+ const recentSize = calls.slice(olderCount).reduce((sum, call) => sum + Math.min(16_000, call.original), 0);
111
+ const olderCap = Math.max(256, Math.min(4_000, Math.floor(Math.max(0, inputMaximum - recentSize) / Math.max(1, olderCount))));
112
+ calls.forEach((call, index) => { call.part.input = shortenedInput(call.part.input, index < olderCount ? olderCap : 16_000, options.preserveToolArgument); });
113
+ }
114
+ const refs = [];
115
+ for (const message of messages) {
53
116
  if (message.role !== "tool" || !Array.isArray(message.content))
54
- return null;
55
- const part = message.content[ref.part];
56
- if (part.type !== "tool-result")
57
- return null;
58
- const recent = index >= refs.length - keepRecent;
59
- const capped = shortened(part.output, recent ? recentCap : perResult);
60
- return { message, partIndex: ref.part, part, capped, cappedSize: serialized(capped).length, recent };
61
- }).filter((item) => item !== null);
62
- // Start from the smallest protocol-valid representation, protecting the most
63
- // recent results (still capped individually), then spend remaining budget on
64
- // older evidence from newest to oldest.
65
- for (const item of prepared) {
66
- const output = item.recent ? item.capped : omittedOutput;
67
- item.message.content[item.partIndex] = { ...item.part, output };
68
- retainedToolChars += item.recent ? item.cappedSize : omittedSize;
69
- if (serialized(item.part.output) !== serialized(output))
70
- compactedResults += 1;
117
+ continue;
118
+ for (const [partIndex, part] of message.content.entries()) {
119
+ if (part.type !== "tool-result")
120
+ continue;
121
+ refs.push({ message, partIndex, part, original: serialized(part.output).length,
122
+ instruction: callInstructions.get(part.toolCallId), status: executionSummary(part.output), superseded: false });
123
+ }
124
+ }
125
+ const latestInstruction = new Map();
126
+ refs.forEach((item, index) => { if (item.instruction)
127
+ latestInstruction.set(item.instruction.key, index); });
128
+ refs.forEach((item, index) => { item.superseded = !!item.instruction && latestInstruction.get(item.instruction.key) !== index; });
129
+ let omitted = { type: "text", value: OMITTED };
130
+ if (refs.length * serialized(omitted).length > maximum / 2)
131
+ omitted = { type: "text", value: "[earlier output omitted; reread focused evidence]" };
132
+ if (refs.length * serialized(omitted).length > maximum)
133
+ omitted = { type: "text", value: "[omitted]" };
134
+ if (refs.length * serialized(omitted).length > maximum) {
135
+ throw new Error("Too many tool results for this context budget; checkpoint and start a new turn");
136
+ }
137
+ const outputs = refs.map(item => item.superseded
138
+ ? { type: "text", value: "[superseded instruction read omitted; use the later read of this same file]" }
139
+ : omitted);
140
+ let retainedToolChars = outputs.reduce((sum, output) => sum + serialized(output).length, 0);
141
+ if (retainedToolChars > maximum) {
142
+ outputs.forEach((_, index) => { outputs[index] = omitted; });
143
+ retainedToolChars = outputs.reduce((sum, output) => sum + serialized(output).length, 0);
144
+ }
145
+ const selected = new Set();
146
+ const restore = (index, desired, limit = maximum) => {
147
+ const before = serialized(outputs[index]).length;
148
+ const available = Math.min(limit, maximum - retainedToolChars + before);
149
+ if (available < 100 && serialized(desired).length > available)
150
+ return false;
151
+ const output = serialized(desired).length <= available ? desired : shortened(desired, available);
152
+ const size = serialized(output).length;
153
+ if (size > available)
154
+ return false;
155
+ outputs[index] = output;
156
+ retainedToolChars += size - before;
157
+ selected.add(index);
158
+ return true;
159
+ };
160
+ refs.forEach((item, index) => {
161
+ if (!item.superseded && item.original <= serialized(outputs[index]).length)
162
+ restore(index, item.part.output);
163
+ });
164
+ let instructionSpent = 0;
165
+ const lastMessage = messages.at(-1);
166
+ const freshIds = new Set(lastMessage?.role === "tool" && Array.isArray(lastMessage.content)
167
+ ? lastMessage.content.filter(part => part.type === "tool-result").map(part => part.toolCallId) : []);
168
+ const instructionBudget = Math.min(options.maxInstructionChars ?? DEFAULT_STEP_INSTRUCTION_CHARS, Math.floor(maximum / 2));
169
+ const instructionIndices = [...latestInstruction.values()].sort((a, b) => Number(refs[b].instruction?.primary) - Number(refs[a].instruction?.primary) || b - a);
170
+ for (const index of instructionIndices) {
171
+ if (selected.has(index) || refs[index].status?.failed)
172
+ continue;
173
+ const allowance = Math.min(freshIds.has(refs[index].part.toolCallId) ? instructionBudget : perResult, instructionBudget - instructionSpent);
174
+ if (allowance < 100)
175
+ continue;
176
+ if (restore(index, refs[index].part.output, allowance))
177
+ instructionSpent += serialized(outputs[index]).length;
178
+ }
179
+ // The latest tool batch has not yet been read by the next model step. Keep
180
+ // complete fresh results when the aggregate budget allows; perResult is a
181
+ // historical retention limit, not an unconditional first-display truncator.
182
+ for (let index = refs.length - 1; index >= 0; index--) {
183
+ if (!selected.has(index) && !refs[index].superseded && freshIds.has(refs[index].part.toolCallId)) {
184
+ restore(index, refs[index].part.output);
185
+ }
186
+ }
187
+ for (let index = refs.length - 1; index >= 0; index--) {
188
+ if (!selected.has(index) && !refs[index].superseded && refs[index].status?.failed)
189
+ restore(index, refs[index].status.output);
190
+ }
191
+ for (let index = Math.max(0, refs.length - keepRecent); index < refs.length; index++) {
192
+ if (!selected.has(index) && !refs[index].superseded)
193
+ restore(index, refs[index].part.output, perResult);
71
194
  }
72
- for (let index = prepared.length - keepRecent - 1; index >= 0; index -= 1) {
73
- const item = prepared[index];
74
- const delta = item.cappedSize - omittedSize;
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)
195
+ for (let index = refs.length - keepRecent - 1; index >= 0; index--) {
196
+ if (selected.has(index) || refs[index].superseded)
78
197
  continue;
79
- item.message.content[item.partIndex] = { ...item.part, output: item.capped };
80
- retainedToolChars += delta;
81
- if (serialized(item.part.output) !== serialized(omittedOutput))
82
- compactedResults -= 1;
83
- if (serialized(item.part.output) !== serialized(item.capped))
84
- compactedResults += 1;
198
+ const desired = shortened(refs[index].part.output, perResult);
199
+ if (serialized(desired).length - serialized(outputs[index]).length <= maximum - retainedToolChars)
200
+ restore(index, desired);
201
+ else if (refs[index].status)
202
+ restore(index, refs[index].status.output);
85
203
  }
86
- return { messages, originalToolChars, retainedToolChars, compactedResults };
204
+ refs.forEach((item, index) => { item.message.content[item.partIndex] = { ...item.part, output: outputs[index] }; });
205
+ return {
206
+ messages,
207
+ originalToolChars: refs.reduce((sum, item) => sum + item.original, 0),
208
+ retainedToolChars,
209
+ compactedResults: refs.filter((item, index) => serialized(item.part.output) !== serialized(outputs[index])).length,
210
+ originalInputChars,
211
+ retainedInputChars: calls.reduce((sum, call) => sum + serialized(call.part.input).length, 0),
212
+ compactedInputs: calls.filter(call => serialized(call.part.input).length !== call.original).length,
213
+ retainedInstructionResults: instructionIndices.filter(index => selected.has(index) && !refs[index].status?.failed).length,
214
+ retainedExecutionSummaries: refs.filter((item, index) => selected.has(index) && item.status
215
+ && serialized(item.part.output) !== serialized(outputs[index])).length,
216
+ };
87
217
  }
@@ -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);});
@@ -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();
@@ -83,7 +83,7 @@ function printHelp() {
83
83
  Options:
84
84
  --host <host> Listen host, default 127.0.0.1
85
85
  --port <port> Listen port, default 18081
86
- --upstream <url> Upstream LiteLLM base URL; required unless set via environment
86
+ --upstream <url> Upstream LiteLLM base URL; required unless set via environment
87
87
  --log-dir <path> Log directory, default %USERPROFILE%/.chatccc/logs/litellm-proxy
88
88
  --log-secrets Log sensitive headers instead of redacting them
89
89
 
@@ -102,6 +102,7 @@ export function reduceProgress(prev, event) {
102
102
  case "error":
103
103
  return withProgressView(prev, { status: "error", showStop: false });
104
104
  case "compact":
105
+ case "model_tool_view":
105
106
  // 旧上下文压缩不影响当前过程展示
106
107
  return prev;
107
108
  case "input_injected": {