chatccc 0.2.307 → 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.
@@ -21,6 +21,10 @@ import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs, } from "
21
21
  import { applyPrivacy, applyPrivacyToJson } from "./privacy.js";
22
22
  import { buildWorkspaceMap, needsWorkspaceOrientation } from "./workspace-map.js";
23
23
  import { compactToolLoopMessages } from "./turn-context.js";
24
+ import { modelToolViews } from "./model-tool-view.js";
25
+ import { readProjectInstructionFiles } from "./project-instructions.js";
26
+ import { compactJsonText } from "./tool-argument-replay.js";
27
+ import { InstructionReplayCache } from "./instruction-replay.js";
24
28
  import { ImageInputRuntime, redactImageData } from "./multimodal.js";
25
29
  export { DecisionSession } from "./decision-session.js";
26
30
  export { CompletionSession } from "./completion-session.js";
@@ -56,6 +60,7 @@ const SYSTEM_PROMPT = [
56
60
  "- 区分来源归属:用户原话/明确决策、助手写入文档的内容、助手推断是三件事。文档或摘要里有某条设定,不等于用户说过;说“你说过/你的设定”前必须能指向用户消息原文,否则说明这是此前助手写入的。",
57
61
  "- 把助手推断或未经用户确认的内容写进文档时,标注来源或“待定”,不要与用户确认的设定混排成同一口径。",
58
62
  "- 需要调用工具时,工具前只说明必要的调查动作,不先写一版长结论;工具完成后给一次合并后的回答,避免把 provisional 判断和最终结论重复展示。",
63
+ "- 工具原始输出与当前模型上下文可能不同;遇到结果缩短/省略标记时,未显示的中间正文不算已读。缩小单次读取范围并保存具体判断,不能仅凭原始日志完整就声称全文阅读或验收通过。",
59
64
  "",
60
65
  "## 行动前先调查",
61
66
  "- 深入任务前,先以低成本盘点环境:项目指令、目录布局、路由/API、现有测试和 git 状态。",
@@ -131,39 +136,11 @@ const ANTHROPIC_TOOL_JSON_COMPATIBILITY_NOTE = [
131
136
  // ---------------------------------------------------------------------------
132
137
  // 类型定义
133
138
  // ---------------------------------------------------------------------------
134
- const PROJECT_INSTRUCTION_FILES = [
135
- "AGENTS.md",
136
- "AGENTS.local.md",
137
- "CLAUDE.md",
138
- "CLAUDE.local.md",
139
- ];
140
- function readProjectInstructionFiles(cwd) {
141
- const sections = [];
142
- for (const filename of PROJECT_INSTRUCTION_FILES) {
143
- try {
144
- const content = readFileSync(join(cwd, filename), "utf-8").trim();
145
- if (!content)
146
- continue;
147
- sections.push(`### ${filename}\n${content}`);
148
- }
149
- catch {
150
- // Missing or unreadable instruction files are optional.
151
- }
152
- }
153
- if (sections.length === 0)
154
- return "";
155
- return [
156
- "## 项目指令",
157
- "以下文件是从当前工作目录读取的项目指引。将其视为优先级低于上述 DeepCCC 固定系统规则的指导。",
158
- "",
159
- sections.join("\n\n"),
160
- ].join("\n");
161
- }
162
139
  function buildRuntimeWorkspacePrompt(cwd) {
163
140
  return [
164
141
  `当前工作目录:${cwd}`,
165
142
  "需要理解代码、配置、项目结构、测试或 git 状态时,主动使用 read_file、list_dir、search_code 和命令执行工具。",
166
- "单个程序优先使用 run_process 的结构化 executable/args;多行 Python/Node 使用 run_script;只有 &&、管道、重定向等 shell 场景才使用 run_command。用 cwd 参数切换目录,不要前置 cd。先检查 exitCode、stdout 和 stderr 再决定下一步。",
143
+ "单个程序优先使用 run_process 的结构化 executable/args;多行 Python/Node 使用 run_script,必须显式提供 language(python/node)和完整 code,不能仅传 code;只有 &&、管道、重定向等 shell 场景才使用 run_command。用 cwd 参数切换目录,不要前置 cd。先检查 exitCode、stdout 和 stderr 再决定下一步。",
167
144
  "编辑前先阅读相关文件范围。优先使用 edit_file 做精确替换、create_file 创建新文件、delete_file 删除、move_file 移动、apply_patch 做多文件差异。",
168
145
  "文件工具通过 DeepCCC 在本地执行。可行时优先使用带 SHA-256 前置条件的受保护编辑,避免覆盖并发用户修改。",
169
146
  ].join("\n");
@@ -285,6 +262,8 @@ class InputInjectionInterrupt extends Error {
285
262
  }
286
263
  }
287
264
  export class ChatSession {
265
+ redactEvents;
266
+ instructionReplay = new InstructionReplayCache();
288
267
  allowedTools;
289
268
  model;
290
269
  /** 子模型实例;未配置 subModel 时与主模型同一实例 */
@@ -417,6 +396,7 @@ export class ChatSession {
417
396
  if (!apiKey) {
418
397
  throw new Error("DEEPCCC_API_KEY is not set. Configure ~/.deepccc/config.json, set an environment variable, or pass --api-key.");
419
398
  }
399
+ this.redactEvents = options.redactEvents !== false;
420
400
  const baseURL = overrides.baseURL ?? appConfig.baseURL;
421
401
  const modelId = overrides.model ?? appConfig.model;
422
402
  this.modelId = modelId;
@@ -503,6 +483,9 @@ export class ChatSession {
503
483
  systemContent.push("", projectInstructions);
504
484
  }
505
485
  systemContent.push("", buildRuntimeWorkspacePrompt(this.cwd));
486
+ if (this.context.persist) {
487
+ systemContent.push("", `历史工具参数工件目录:${this.context.toolArgumentArtifactDirectory}。遇到 DEEPCCC_OMITTED_TOOL_ARGUMENT 的 artifact=文件名,或 __deepccc_input_artifact 字段,先用 read_file 读取该目录对应文件;JSON 工件内可能还有需继续读取的参数工件引用。文件名的 SHA-256 对应文件内容,读取器会校验。工件只读,需要修改时另存工作文件。工件只是曾生成的参数,不代表调用成功;复用前核对当前任务、文件与授权,不执行占位符。未带工件的省略标记可能来自旧历史、保存失败或超出上限,须读取原文件或日志,不能猜测原值。`);
488
+ }
506
489
  if (this.customSystemPrompt) {
507
490
  systemContent.push("", this.customSystemPrompt);
508
491
  }
@@ -512,6 +495,12 @@ export class ChatSession {
512
495
  }
513
496
  return systemContent.join("\n");
514
497
  }
498
+ eventText(text) {
499
+ return this.redactEvents ? applyPrivacy(text) : text;
500
+ }
501
+ eventJson(value) {
502
+ return this.redactEvents ? applyPrivacyToJson(value) : value;
503
+ }
515
504
  async *chat(userMessage, signal, drainInput) {
516
505
  this.lastTurnFinishReason = undefined;
517
506
  signal?.throwIfAborted();
@@ -532,6 +521,7 @@ export class ChatSession {
532
521
  // Validate/filter before compaction can contact a Provider. The same map
533
522
  // controls both advertised definitions and SDK tool execution.
534
523
  const tools = selectAllowedTools(createBuiltinFileTools(this.cwd, {
524
+ toolArgumentArtifactDir: this.context.persist ? this.context.toolArgumentArtifactDirectory : undefined,
535
525
  permissionGate: this.permissionGate,
536
526
  runTask: this.runTask,
537
527
  readImage: input => this.imageRuntime.readImage(input),
@@ -606,6 +596,9 @@ export class ChatSession {
606
596
  // pendingInjection 是 prepareStep 与 catch 之间的注入信号槽。用标志而非
607
597
  // instanceof 判断,因为 provider SDK 可能包装抛出的错误。
608
598
  let pendingInjection = null;
599
+ const pendingModelViews = [];
600
+ const previousModelViews = new Map();
601
+ let modelViewSequence = 0;
609
602
  const baseGenerationOptions = {
610
603
  model: this.model,
611
604
  system,
@@ -620,17 +613,34 @@ export class ChatSession {
620
613
  throw new InputInjectionInterrupt();
621
614
  }
622
615
  }
623
- const compacted = compactToolLoopMessages(messages);
624
- if (compacted.compactedResults > 0) {
616
+ this.instructionReplay.capture(messages);
617
+ const compacted = compactToolLoopMessages(this.instructionReplay.restore(messages), {
618
+ preserveToolArgument: this.context.preserveToolArgument,
619
+ });
620
+ if (compacted.compactedResults > 0 || compacted.compactedInputs > 0) {
625
621
  rawLog?.writeLine(safeRawStreamJson({
626
622
  type: "deepccc_intra_turn_tool_context_compacted",
627
623
  stepNumber,
628
624
  compactedResults: compacted.compactedResults,
629
625
  originalToolChars: compacted.originalToolChars,
630
626
  retainedToolChars: compacted.retainedToolChars,
627
+ compactedInputs: compacted.compactedInputs,
628
+ originalInputChars: compacted.originalInputChars,
629
+ retainedInputChars: compacted.retainedInputChars,
630
+ retainedInstructionResults: compacted.retainedInstructionResults,
631
+ retainedExecutionSummaries: compacted.retainedExecutionSummaries,
631
632
  }));
632
633
  }
633
634
  const images = await this.imageRuntime.prepare(compacted.messages, signal);
635
+ if (this.streaming && !this.redactEvents) {
636
+ const sequence = ++modelViewSequence;
637
+ for (const view of modelToolViews(messages, images.messages)) {
638
+ if (previousModelViews.get(view.tool_call_id) === view.model_output_sha256)
639
+ continue;
640
+ previousModelViews.set(view.tool_call_id, view.model_output_sha256);
641
+ pendingModelViews.push({ type: "model_tool_view", sequence, step_number: stepNumber, ...view });
642
+ }
643
+ }
634
644
  return { messages: images.messages, ...(images.hasImages && images.model ? { model: this.providerFactory(images.model) } : {}) };
635
645
  },
636
646
  ...(this.maxOutputTokens !== undefined
@@ -683,6 +693,8 @@ export class ChatSession {
683
693
  stream = generateResultToFullStream(result);
684
694
  }
685
695
  for await (const part of stream) {
696
+ for (const view of pendingModelViews.splice(0))
697
+ yield view;
686
698
  for (const notice of this.imageNotices.splice(0))
687
699
  yield { type: "image_input", ...notice };
688
700
  rawLog?.writeLine(safeRawStreamJson(part));
@@ -706,13 +718,14 @@ export class ChatSession {
706
718
  previous.text += part.text;
707
719
  else
708
720
  timeline.push({ type: "text", text: part.text });
709
- // 隐私替换只在展示层:safeAccumulated 供事件消费者(终端/JSONL)使用,
710
- // fullText 原文用于持久化上下文,避免替换结果回流污染上下文。
711
- const safeText = applyPrivacy(part.text);
721
+ // Event redaction defaults to display mode. Explicit machine
722
+ // consumers can opt out; persisted/model context stays original.
723
+ const safeText = this.eventText(part.text);
712
724
  safeAccumulated += safeText;
713
725
  yield { type: "text", text: safeText, accumulated: safeAccumulated };
714
726
  }
715
727
  else if (part.type === "tool-call") {
728
+ this.instructionReplay.observeCall(part.toolCallId, part.toolName, part.input);
716
729
  const input = safeJson(part.input);
717
730
  toolContext.push(`tool_call ${part.toolName}: ${input}`);
718
731
  toolCallsById.set(part.toolCallId, { id: part.toolCallId, name: part.toolName, input });
@@ -722,10 +735,11 @@ export class ChatSession {
722
735
  type: "tool_use",
723
736
  id: part.toolCallId,
724
737
  name: part.toolName,
725
- input: applyPrivacyToJson(part.input),
738
+ input: this.eventJson(part.input),
726
739
  };
727
740
  }
728
741
  else if (part.type === "tool-result") {
742
+ this.instructionReplay.observeFileResult(part.toolCallId, part.output);
729
743
  const output = truncateToolContext(safeJson(part.output));
730
744
  toolContext.push(`tool_result ${part.toolName}: ${output}`);
731
745
  const call = toolCallsById.get(part.toolCallId);
@@ -736,12 +750,13 @@ export class ChatSession {
736
750
  type: "tool_result",
737
751
  tool_use_id: part.toolCallId,
738
752
  name: part.toolName,
739
- content: applyPrivacyToJson(part.output),
753
+ content: this.eventJson(part.output),
740
754
  is_error: false,
741
755
  };
742
756
  }
743
757
  else if (part.type === "tool-error") {
744
758
  const message = errorMessage(part.error);
759
+ this.instructionReplay.observeError(part.toolCallId, message);
745
760
  toolContext.push(`tool_error ${part.toolName}: ${message}`);
746
761
  const call = toolCallsById.get(part.toolCallId);
747
762
  if (call) {
@@ -753,7 +768,7 @@ export class ChatSession {
753
768
  type: "tool_result",
754
769
  tool_use_id: part.toolCallId,
755
770
  name: part.toolName,
756
- content: applyPrivacy(message),
771
+ content: this.eventText(message),
757
772
  is_error: true,
758
773
  };
759
774
  }
@@ -763,7 +778,7 @@ export class ChatSession {
763
778
  throw new InputInjectionInterrupt();
764
779
  }
765
780
  const message = errorMessage(part.error);
766
- yield { type: "error", message: applyPrivacy(message) };
781
+ yield { type: "error", message: this.eventText(message) };
767
782
  throw new Error(message);
768
783
  }
769
784
  }
@@ -802,6 +817,7 @@ export class ChatSession {
802
817
  transcriptLines: toolContext,
803
818
  toolCalls: collectedToolCalls,
804
819
  timeline,
820
+ preserveToolArgument: this.context.preserveToolArgument,
805
821
  }));
806
822
  yield { type: "done", text: safeAccumulated };
807
823
  return;
@@ -819,6 +835,7 @@ export class ChatSession {
819
835
  transcriptLines: toolContext,
820
836
  toolCalls: collectedToolCalls,
821
837
  timeline: timeline.map((entry) => ({ ...entry })),
838
+ preserveToolArgument: this.context.preserveToolArgument,
822
839
  }));
823
840
  }
824
841
  const injectedText = await this.imageRuntime.normalizePrompt(pendingInjection);
@@ -856,12 +873,13 @@ export class ChatSession {
856
873
  transcriptLines: toolContext,
857
874
  toolCalls: collectedToolCalls,
858
875
  timeline: interruptedTimeline,
876
+ preserveToolArgument: this.context.preserveToolArgument,
859
877
  }));
860
878
  }
861
879
  yield { type: "done", text: safeAccumulated };
862
880
  return;
863
881
  }
864
- yield { type: "error", message: applyPrivacy(message) };
882
+ yield { type: "error", message: this.eventText(message) };
865
883
  throw err;
866
884
  }
867
885
  finally {
@@ -1006,7 +1024,8 @@ function safeRawStreamJson(value) {
1006
1024
  }
1007
1025
  }
1008
1026
  function truncateToolContext(value) {
1009
- return value.length > 8000 ? `${value.slice(0, 8000)}...[truncated]` : value;
1027
+ return compactJsonText(value, 8000, true)
1028
+ ?? (value.length > 8000 ? `${value.slice(0, 8000)}...[truncated]` : value);
1010
1029
  }
1011
1030
  function formatDuration(ms) {
1012
1031
  if (ms % 60_000 === 0)
@@ -0,0 +1,91 @@
1
+ export function instructionPath(input) {
2
+ if (!input || typeof input !== "object")
3
+ return;
4
+ const path = input.path;
5
+ if (typeof path !== "string")
6
+ return;
7
+ const normalized = path.replace(/\\/g, "/").replace(/\/\.\//g, "/");
8
+ if (!/(?:^|\/)skills\/.+\/(?:SKILL\.md|references\/.+\.md)$/i.test(normalized))
9
+ return;
10
+ return { key: /^[a-z]:\//i.test(normalized) ? normalized.toLowerCase() : normalized,
11
+ primary: /\/SKILL\.md$/i.test(normalized) };
12
+ }
13
+ /** Retains actual tool evidence in this session, independently of bounded history. */
14
+ export class InstructionReplayCache {
15
+ sequence = 0;
16
+ calls = new Map();
17
+ observed = new Set();
18
+ latest = new Map();
19
+ observeCall(id, name, input) {
20
+ if (name !== "read_file" || this.calls.has(id))
21
+ return;
22
+ const path = instructionPath(input);
23
+ if (!path)
24
+ return;
25
+ this.calls.set(id, { id, key: path.key, sequence: ++this.sequence, input: structuredClone(input) });
26
+ }
27
+ observeOutput(id, output) {
28
+ const call = this.calls.get(id);
29
+ if (!call || this.observed.has(id))
30
+ return;
31
+ this.observed.add(id);
32
+ const old = this.latest.get(call.key);
33
+ if (old && old.sequence > call.sequence)
34
+ return;
35
+ this.latest.delete(call.key);
36
+ this.latest.set(call.key, { ...call, output: structuredClone(output) });
37
+ // Bound the number of full read results; the model-facing text budget is
38
+ // still applied by compactToolLoopMessages after restoration.
39
+ if (this.latest.size > 32)
40
+ this.latest.delete(this.latest.keys().next().value);
41
+ }
42
+ observeFileResult(id, value) {
43
+ if (!this.calls.has(id))
44
+ return;
45
+ const json = JSON.stringify(value);
46
+ this.observeOutput(id, json === undefined
47
+ ? { type: "text", value: "[instruction read returned no output; reload the file]" }
48
+ : { type: "json", value: JSON.parse(json) });
49
+ }
50
+ observeError(id, error) {
51
+ this.observeOutput(id, { type: "error-text", value: error });
52
+ }
53
+ capture(messages) {
54
+ for (const message of messages) {
55
+ if (!Array.isArray(message.content))
56
+ continue;
57
+ for (const part of message.content) {
58
+ if (message.role === "assistant" && part.type === "tool-call") {
59
+ this.observeCall(part.toolCallId, part.toolName, part.input);
60
+ }
61
+ else if (message.role === "tool" && part.type === "tool-result") {
62
+ this.observeOutput(part.toolCallId, part.output);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ restore(input) {
68
+ const messages = structuredClone(input);
69
+ for (const message of messages) {
70
+ if (!Array.isArray(message.content))
71
+ continue;
72
+ for (const part of message.content) {
73
+ if (part.type !== "tool-call" && part.type !== "tool-result")
74
+ continue;
75
+ const call = this.calls.get(part.toolCallId);
76
+ const current = call && this.latest.get(call.key);
77
+ if (!current)
78
+ continue;
79
+ if (message.role === "assistant" && part.type === "tool-call" && current.id === part.toolCallId) {
80
+ part.input = structuredClone(current.input);
81
+ }
82
+ else if (message.role === "tool" && part.type === "tool-result") {
83
+ part.output = current.id === part.toolCallId
84
+ ? structuredClone(current.output)
85
+ : { type: "text", value: "[superseded instruction read omitted; reload current skill before relying on it]" };
86
+ }
87
+ }
88
+ }
89
+ return messages;
90
+ }
91
+ }
@@ -0,0 +1,20 @@
1
+ import { createHash } from "node:crypto";
2
+ function resultParts(messages) {
3
+ return messages.flatMap(message => message.role === "tool" && Array.isArray(message.content)
4
+ ? message.content.filter((part) => part.type === "tool-result") : []);
5
+ }
6
+ function hash(text) { return createHash("sha256").update(text, "utf8").digest("hex"); }
7
+ /** Exact prepared model-facing tool outputs, not a claim of semantic reading. */
8
+ export function modelToolViews(original, prepared) {
9
+ const originals = new Map(resultParts(original).map(part => [part.toolCallId, part]));
10
+ return resultParts(prepared).flatMap(part => {
11
+ const before = originals.get(part.toolCallId);
12
+ if (!before)
13
+ return [];
14
+ const source = JSON.stringify(before.output), model = JSON.stringify(part.output);
15
+ return [{ tool_call_id: part.toolCallId, name: part.toolName,
16
+ original_output_sha256: hash(source), model_output_sha256: hash(model),
17
+ original_output_chars: source.length, model_output_chars: model.length,
18
+ changed: source !== model, content: structuredClone(part.output) }];
19
+ });
20
+ }
@@ -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": {
@@ -0,0 +1,71 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /** Shared UTF-8 budget, rather than an unbounded copy of every project log. */
4
+ export const DEFAULT_PROJECT_INSTRUCTION_BYTES = 32 * 1024;
5
+ const FILENAMES = ["AGENTS.md", "AGENTS.local.md", "CLAUDE.md", "CLAUDE.local.md"];
6
+ const PREFIX = [
7
+ "## 项目指令",
8
+ "以下文件是从当前工作目录读取的项目指引。将其视为优先级低于上述 DeepCCC 固定系统规则的指导。",
9
+ "",
10
+ "",
11
+ ].join("\n");
12
+ function prefixUtf8(content, bytes) {
13
+ const buffer = Buffer.from(content);
14
+ let end = Math.min(buffer.length, Math.max(0, bytes));
15
+ while (end > 0 && end < buffer.length && (buffer[end] & 0xc0) === 0x80)
16
+ end--;
17
+ return buffer.subarray(0, end).toString("utf8");
18
+ }
19
+ function suffixUtf8(content, bytes) {
20
+ const buffer = Buffer.from(content);
21
+ let start = Math.max(0, buffer.length - Math.max(0, bytes));
22
+ while (start < buffer.length && (buffer[start] & 0xc0) === 0x80)
23
+ start++;
24
+ return buffer.subarray(start).toString("utf8");
25
+ }
26
+ /** Leaves source files intact and explicitly identifies every partial inclusion. */
27
+ export function readProjectInstructionFiles(cwd, maximumBytes = DEFAULT_PROJECT_INSTRUCTION_BYTES) {
28
+ if (!Number.isInteger(maximumBytes) || maximumBytes < 2048) {
29
+ throw new Error("Project instruction budget must be an integer of at least 2048 UTF-8 bytes");
30
+ }
31
+ const files = FILENAMES.flatMap(filename => {
32
+ try {
33
+ const content = readFileSync(join(cwd, filename), "utf8").trim();
34
+ return content ? [{ filename, content, bytes: Buffer.byteLength(content) }] : [];
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ });
40
+ if (!files.length)
41
+ return "";
42
+ const full = PREFIX + files.map(file => `### ${file.filename}\n${file.content}`).join("\n\n");
43
+ if (Buffer.byteLength(full) <= maximumBytes)
44
+ return full;
45
+ // Reserve bounded metadata first. Small local overrides get their full share;
46
+ // a giant root file cannot consume the allocations of all later files.
47
+ let remaining = maximumBytes - Buffer.byteLength(PREFIX) - files.length * 400;
48
+ const budgets = new Map();
49
+ const bySize = [...files].sort((a, b) => a.bytes - b.bytes);
50
+ for (const [index, file] of bySize.entries()) {
51
+ const quota = Math.max(0, Math.min(file.bytes, Math.floor(remaining / (files.length - index))));
52
+ budgets.set(file.filename, quota);
53
+ remaining -= quota;
54
+ }
55
+ const sections = files.map(file => {
56
+ const budget = budgets.get(file.filename) ?? 0;
57
+ if (file.bytes <= budget)
58
+ return `### ${file.filename}\n${file.content}`;
59
+ const head = prefixUtf8(file.content, Math.floor(budget * 0.65));
60
+ const tail = suffixUtf8(file.content, budget - Buffer.byteLength(head));
61
+ const included = Buffer.byteLength(head) + Buffer.byteLength(tail);
62
+ return [
63
+ `### ${file.filename}`,
64
+ `[Bounded excerpt: ${included}/${file.bytes} UTF-8 bytes. Middle omitted, not loaded or assumed absent. Use read_file/search_code on ${file.filename} for relevant omitted instructions before editing. Source file is unchanged.]`,
65
+ head,
66
+ "...[project instruction middle omitted]...",
67
+ tail,
68
+ ].join("\n");
69
+ });
70
+ return PREFIX + sections.join("\n\n");
71
+ }
@@ -0,0 +1,58 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { artifactToolArgument, isOmittedToolArgument } from "./tool-argument-replay.js";
5
+ /** Matches the file tool's single-read byte limit; larger values keep the unavailable fallback. */
6
+ export const MAX_TOOL_ARGUMENT_ARTIFACT_BYTES = 1024 * 1024;
7
+ export class ToolArgumentArtifactStore {
8
+ directory;
9
+ sessionDirectory;
10
+ constructor(sessionDirectory) {
11
+ this.sessionDirectory = resolve(sessionDirectory);
12
+ this.directory = join(this.sessionDirectory, "tool-arguments");
13
+ }
14
+ preserve(text) {
15
+ if (isOmittedToolArgument(text))
16
+ return undefined;
17
+ if (Buffer.byteLength(text, "utf8") > MAX_TOOL_ARGUMENT_ARTIFACT_BYTES)
18
+ return undefined;
19
+ const digest = createHash("sha256").update(text, "utf8").digest("hex");
20
+ const filename = digest + ".txt";
21
+ try {
22
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
23
+ try {
24
+ writeFileSync(join(this.directory, filename), text, { encoding: "utf8", flag: "wx", mode: 0o600 });
25
+ }
26
+ catch (error) {
27
+ if (error.code !== "EEXIST")
28
+ throw error;
29
+ }
30
+ if (createHash("sha256").update(readFileSync(join(this.directory, filename))).digest("hex") !== digest) {
31
+ throw Object.assign(new Error("stored argument hash mismatch"), { code: "ARGUMENT_ARTIFACT_HASH_MISMATCH" });
32
+ }
33
+ return artifactToolArgument(filename);
34
+ }
35
+ catch (error) {
36
+ // Never advertise a nonexistent/corrupted artifact or echo the input value.
37
+ console.warn(`[DeepCCC] tool argument artifact unavailable (${error.code ?? "storage error"}); retaining unavailable-argument fallback`);
38
+ return undefined;
39
+ }
40
+ }
41
+ clear() {
42
+ // Only the literal owned child of this normalized session directory is removed.
43
+ const target = resolve(this.directory);
44
+ if (dirname(target) !== this.sessionDirectory || basename(target) !== "tool-arguments") {
45
+ throw new Error("Invalid tool argument artifact cleanup target");
46
+ }
47
+ rmSync(target, { recursive: true, force: true });
48
+ }
49
+ }
50
+ /** Resolve the expected content hash only inside this session's managed directory. */
51
+ export function expectedToolArgumentArtifactHash(directory, filePath) {
52
+ if (!directory)
53
+ return undefined;
54
+ const key = (value) => process.platform === "win32" ? resolve(value).toLowerCase() : resolve(value);
55
+ if (key(dirname(filePath)) !== key(directory))
56
+ return undefined;
57
+ return basename(filePath).match(/^([a-f0-9]{64})\.txt$/i)?.[1].toLowerCase();
58
+ }
@@ -0,0 +1,107 @@
1
+ /** Reserved whole-value marker: never expose a code-shaped historical excerpt. */
2
+ export function omittedToolArgument(characters) {
3
+ return `[[DEEPCCC_OMITTED_TOOL_ARGUMENT chars=${characters}; read the original saved file before reuse]]`;
4
+ }
5
+ export function isOmittedToolArgument(value) {
6
+ return typeof value === "string" && /^\[\[DEEPCCC_OMITTED_TOOL_ARGUMENT (?:chars=\d+; read the original saved file before reuse|artifact=[a-f0-9]{64}\.txt)\]\]$/.test(value);
7
+ }
8
+ export function artifactToolArgument(filename) {
9
+ if (!/^[a-f0-9]{64}\.txt$/.test(filename))
10
+ throw new Error("Invalid tool argument artifact name");
11
+ return `[[DEEPCCC_OMITTED_TOOL_ARGUMENT artifact=${filename}]]`;
12
+ }
13
+ const ARTIFACT_MARKER_CHARS = artifactToolArgument("0".repeat(64) + ".txt").length;
14
+ export function compactJsonValue(value, maximum, output = false, preserveArgument) {
15
+ const raw = JSON.stringify(value);
16
+ if (raw === undefined)
17
+ return value;
18
+ if (raw.length <= maximum)
19
+ return value;
20
+ const box = { value: JSON.parse(raw) };
21
+ const leaves = [];
22
+ const visit = (object, key) => {
23
+ const item = object[key];
24
+ if (typeof item === "string")
25
+ leaves.push({ object, key });
26
+ else if (item && typeof item === "object") {
27
+ for (const child of Object.keys(item))
28
+ visit(item, child);
29
+ }
30
+ };
31
+ visit(box, "value");
32
+ leaves.sort((a, b) => b.object[b.key].length - a.object[a.key].length);
33
+ for (const leaf of leaves) {
34
+ const text = leaf.object[leaf.key];
35
+ if (!output && isOmittedToolArgument(text))
36
+ continue;
37
+ const artifact = !output && preserveArgument && text.length > ARTIFACT_MARKER_CHARS
38
+ ? preserveArgument(text) : undefined;
39
+ const replacement = output
40
+ ? `[[DEEPCCC_OMITTED_TOOL_OUTPUT chars=${text.length}; inspect the saved evidence]]`
41
+ : artifact ?? omittedToolArgument(text.length);
42
+ if (replacement.length >= text.length)
43
+ continue;
44
+ if (output) {
45
+ const otherChars = JSON.stringify(box.value).length - JSON.stringify(text).length;
46
+ let available = Math.max(0, maximum - otherChars - 2 - replacement.length);
47
+ for (let attempt = 0; attempt < 8; attempt++) {
48
+ const head = Math.ceil(available / 2);
49
+ const tail = Math.floor(available / 2);
50
+ leaf.object[leaf.key] = text.slice(0, head) + replacement + (tail ? text.slice(-tail) : "");
51
+ const excess = JSON.stringify(box.value).length - maximum;
52
+ if (excess <= 0 || available === 0)
53
+ break;
54
+ available = Math.max(0, available - excess);
55
+ }
56
+ }
57
+ else {
58
+ leaf.object[leaf.key] = replacement;
59
+ }
60
+ if (JSON.stringify(box.value).length <= maximum)
61
+ return box.value;
62
+ }
63
+ if (!output && preserveArgument) {
64
+ // If a complete argument object does not fit, retain a short reference to
65
+ // its bounded projection. Nested artifact markers still recover original strings.
66
+ const marker = preserveArgument(JSON.stringify(box.value, null, 2));
67
+ const filename = marker?.match(/^\[\[DEEPCCC_OMITTED_TOOL_ARGUMENT artifact=([a-f0-9]{64}\.txt)\]\]$/)?.[1];
68
+ if (filename) {
69
+ const reference = { __deepccc_input_artifact: filename };
70
+ if (JSON.stringify(reference).length <= maximum)
71
+ return reference;
72
+ }
73
+ }
74
+ // A large collection of small fields may not fit. Keep valid JSON and state
75
+ // that the historical arguments are unavailable rather than inventing a raw call.
76
+ if (output && value && typeof value === "object" && !Array.isArray(value)) {
77
+ const record = value;
78
+ const status = { __deepccc_output_omitted: true };
79
+ for (const key of ["exitCode", "timedOut", "running", "taskId", "signal", "backgrounded"]) {
80
+ const item = record[key];
81
+ if (item !== null && !["string", "number", "boolean"].includes(typeof item))
82
+ continue;
83
+ const candidate = { ...status, [key]: item };
84
+ if (JSON.stringify(candidate).length <= maximum)
85
+ Object.assign(status, candidate);
86
+ }
87
+ if (Object.keys(status).length > 1 && JSON.stringify(status).length <= maximum)
88
+ return status;
89
+ }
90
+ const fallback = { __deepccc_payload_unavailable: true, originalChars: raw.length };
91
+ return JSON.stringify(fallback).length <= maximum ? fallback : {};
92
+ }
93
+ /** Undefined means plain text, so callers can retain their text-output policy. */
94
+ export function compactJsonText(text, maximum, output = false, preserveArgument) {
95
+ if (maximum < 2)
96
+ return "";
97
+ if (text.length <= maximum)
98
+ return text;
99
+ let value;
100
+ try {
101
+ value = JSON.parse(text);
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ return JSON.stringify(compactJsonValue(value, maximum, output, preserveArgument));
107
+ }