cc-viewer 1.9.22 → 1.9.24

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.
Files changed (107) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +2 -2
  3. package/cli.js +25 -1
  4. package/dist/assets/App-BwRRqrP5.css +1 -0
  5. package/dist/assets/App-Cfmm41z0.js +2 -0
  6. package/dist/assets/ArchivePreview-BKXTsPsN.css +1 -0
  7. package/dist/assets/ArchivePreview-dKWXN9Zp.js +1 -0
  8. package/dist/assets/{MdxEditorPanel-CmHF9Mz1.js → MdxEditorPanel-CT6w8hjl.js} +1 -1
  9. package/dist/assets/Mobile-noWViQpL.js +1 -0
  10. package/dist/assets/{ProxyStatsModal-Ogrx3mxS.js → ProxyStatsModal-BeCRPqaC.js} +1 -1
  11. package/dist/assets/{_baseUniq-CsF04anE.js → _baseUniq-BGBEhBne.js} +1 -1
  12. package/dist/assets/{arc-BOacYe6N.js → arc-4pbWOEmh.js} +1 -1
  13. package/dist/assets/{architectureDiagram-Q4EWVU46-BSUEfjC_.js → architectureDiagram-Q4EWVU46-BHZPDnby.js} +1 -1
  14. package/dist/assets/{blockDiagram-DXYQGD6D-CC37UGtW.js → blockDiagram-DXYQGD6D-DszLU7Pg.js} +1 -1
  15. package/dist/assets/{c4Diagram-AHTNJAMY-IzgRD4uO.js → c4Diagram-AHTNJAMY-DbDJNYxl.js} +1 -1
  16. package/dist/assets/{channel-C6PxyQUn.js → channel-BpIsxDHj.js} +1 -1
  17. package/dist/assets/{chunk-4BX2VUAB-cdQt_dcU.js → chunk-4BX2VUAB-ChcBwBh2.js} +1 -1
  18. package/dist/assets/{chunk-4TB4RGXK-BpTDA_Pb.js → chunk-4TB4RGXK-DzBEAck_.js} +1 -1
  19. package/dist/assets/{chunk-55IACEB6-CcitNo0P.js → chunk-55IACEB6-9UDvmw07.js} +1 -1
  20. package/dist/assets/{chunk-EDXVE4YY-BjKwZ9I7.js → chunk-EDXVE4YY-DHEU2DKg.js} +1 -1
  21. package/dist/assets/{chunk-FMBD7UC4-vZDVX3tI.js → chunk-FMBD7UC4-sysT0Sy2.js} +1 -1
  22. package/dist/assets/{chunk-OYMX7WX6-DGkYahGo.js → chunk-OYMX7WX6-DLXt2vYo.js} +1 -1
  23. package/dist/assets/{chunk-QZHKN3VN-C9065hSE.js → chunk-QZHKN3VN-CDIkC7QK.js} +1 -1
  24. package/dist/assets/{chunk-YZCP3GAM-D_pcTg6_.js → chunk-YZCP3GAM-D9b_INz7.js} +1 -1
  25. package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +1 -0
  26. package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +1 -0
  27. package/dist/assets/clone-cWiXtXrO.js +1 -0
  28. package/dist/assets/{cose-bilkent-S5V4N54A-BPPFMIGv.js → cose-bilkent-S5V4N54A-DJQwV_Dp.js} +1 -1
  29. package/dist/assets/{dagre-KV5264BT-fjzhKO5o.js → dagre-KV5264BT-bl9Pq21t.js} +1 -1
  30. package/dist/assets/{diagram-5BDNPKRD-5L6FzTry.js → diagram-5BDNPKRD-BA8CJxzI.js} +1 -1
  31. package/dist/assets/{diagram-G4DWMVQ6-GOwcGpff.js → diagram-G4DWMVQ6-DzSQULuz.js} +1 -1
  32. package/dist/assets/{diagram-MMDJMWI5-BDsFE25W.js → diagram-MMDJMWI5-DhfHWnT4.js} +1 -1
  33. package/dist/assets/{diagram-TYMM5635-BqjpbSGH.js → diagram-TYMM5635-BbAoFfGS.js} +1 -1
  34. package/dist/assets/{erDiagram-SMLLAGMA-DWO3Dk1v.js → erDiagram-SMLLAGMA-CMjA2eBk.js} +1 -1
  35. package/dist/assets/{flowDiagram-DWJPFMVM-Br4nNBVd.js → flowDiagram-DWJPFMVM-bOubqgJ6.js} +1 -1
  36. package/dist/assets/{ganttDiagram-T4ZO3ILL-9sN-VOhw.js → ganttDiagram-T4ZO3ILL-BUIu7WwI.js} +1 -1
  37. package/dist/assets/{gitGraphDiagram-UUTBAWPF-BsPcTAKr.js → gitGraphDiagram-UUTBAWPF-B_vrztDU.js} +1 -1
  38. package/dist/assets/{graph-o31GzaB6.js → graph-BR3YGx52.js} +1 -1
  39. package/dist/assets/{index-DAjx9lT3.js → index-B88yR2TU.js} +1 -1
  40. package/dist/assets/{index-PDvAAbti.js → index-BMpUfdYI.js} +1 -1
  41. package/dist/assets/{index-DyV81jSF.js → index-BQx5MOpr.js} +1 -1
  42. package/dist/assets/index-Ca3a2tOc.js +2 -0
  43. package/dist/assets/{index-CuvDJTY7.js → index-ClTuiPoz.js} +1 -1
  44. package/dist/assets/{index-tZqiJJGq.js → index-DtZAmvwJ.js} +1 -1
  45. package/dist/assets/{index-B3b0lRUB.js → index-DwMyfQJq.js} +1 -1
  46. package/dist/assets/{index-CXMr3tiK.js → index-mvm_Pxcf.js} +1 -1
  47. package/dist/assets/{infoDiagram-42DDH7IO-VUMzEo4o.js → infoDiagram-42DDH7IO-Co9Db2ir.js} +1 -1
  48. package/dist/assets/{ishikawaDiagram-UXIWVN3A-BuzrU3sx.js → ishikawaDiagram-UXIWVN3A-4z7EydCd.js} +1 -1
  49. package/dist/assets/{journeyDiagram-VCZTEJTY-BZtR5BAF.js → journeyDiagram-VCZTEJTY-CtLfbhYE.js} +1 -1
  50. package/dist/assets/{jszip.min-CtodH5MV.js → jszip.min-DtbrAiWv.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-Cj_97xXb.js → kanban-definition-6JOO6SKY-9ZrhOvdX.js} +1 -1
  52. package/dist/assets/{layout-Du0I-tlh.js → layout-Ddo06NJO.js} +1 -1
  53. package/dist/assets/{linear-BJtxCASI.js → linear-BZUsBSwS.js} +1 -1
  54. package/dist/assets/{mermaid.core-QlorX0Yw.js → mermaid.core-O-x0KuTp.js} +2 -2
  55. package/dist/assets/{min-BVnQfunZ.js → min-PzJh19JL.js} +1 -1
  56. package/dist/assets/{mindmap-definition-QFDTVHPH-Bh_KL4qU.js → mindmap-definition-QFDTVHPH-C3MVo-7p.js} +1 -1
  57. package/dist/assets/{pieDiagram-DEJITSTG-Bvv0rC_q.js → pieDiagram-DEJITSTG-CMn9-kQc.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-34T5L4WZ-Bw8cGCRU.js → quadrantDiagram-34T5L4WZ-9eyqTdkj.js} +1 -1
  59. package/dist/assets/{requirementDiagram-MS252O5E-Cg9jQ71h.js → requirementDiagram-MS252O5E-BJbuDOpR.js} +1 -1
  60. package/dist/assets/{sankeyDiagram-XADWPNL6-BXJo6-CD.js → sankeyDiagram-XADWPNL6-CzQ1KxD3.js} +1 -1
  61. package/dist/assets/seqResourceLoaders-DH-Nl0yh.css +41 -0
  62. package/dist/assets/seqResourceLoaders-DeqzMajS.js +2 -0
  63. package/dist/assets/{sequenceDiagram-FGHM5R23-D7zpGxwq.js → sequenceDiagram-FGHM5R23-CfmSEAYp.js} +1 -1
  64. package/dist/assets/{stateDiagram-FHFEXIEX-Der2CqR1.js → stateDiagram-FHFEXIEX-Brw2ZXQC.js} +1 -1
  65. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DetvG_Lc.js → stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js} +1 -1
  66. package/dist/assets/{timeline-definition-GMOUNBTQ-0UenzEZ6.js → timeline-definition-GMOUNBTQ-DNi7GnlG.js} +1 -1
  67. package/dist/assets/{vendor-antd-I6I2F7Rv.js → vendor-antd-DWLgSkPo.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-Zkm6UHQg.js → vendor-codemirror-CKsm_iG4.js} +1 -1
  69. package/dist/assets/{vendor-mdxeditor-CC09MDyZ.js → vendor-mdxeditor-Dah6NK0y.js} +2 -2
  70. package/dist/assets/{vendor-qrcode-gZpmSeeh.js → vendor-qrcode-CDcb8weP.js} +1 -1
  71. package/dist/assets/{vendor-virtuoso-BGwznQ5y.js → vendor-virtuoso-DKUobZpA.js} +1 -1
  72. package/dist/assets/{vennDiagram-DHZGUBPP-COzYyZ5h.js → vennDiagram-DHZGUBPP-Cdkdx7gB.js} +1 -1
  73. package/dist/assets/{wardley-RL74JXVD-VZdOtN8t.js → wardley-RL74JXVD-YKzsVN4U.js} +1 -1
  74. package/dist/assets/{wardleyDiagram-NUSXRM2D-CVkL75Qy.js → wardleyDiagram-NUSXRM2D-gBsb6aut.js} +1 -1
  75. package/dist/assets/{xychartDiagram-5P7HB3ND-6CHBAYyF.js → xychartDiagram-5P7HB3ND-Bh63NWof.js} +1 -1
  76. package/dist/index.html +4 -4
  77. package/findcc.js +4 -4
  78. package/node_modules/@ccv/core/src/ask-auto-answer.js +122 -0
  79. package/node_modules/@ccv/core/src/contentFilter.js +4 -1
  80. package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
  81. package/package.json +1 -1
  82. package/server/i18n.js +4 -20
  83. package/server/lib/ask/ask-bridge.js +4 -1
  84. package/server/lib/ask/ask-reaper.js +1 -0
  85. package/server/lib/ask-auto-answer.js +153 -0
  86. package/server/lib/auto-approve.js +3 -1
  87. package/server/lib/binary-sniff.js +35 -0
  88. package/server/lib/ensure-hooks.js +134 -2
  89. package/server/lib/im/im-bridge-core.js +16 -0
  90. package/server/lib/scheduled-task-executor.js +14 -2
  91. package/server/lib/scheduled-task-store.js +129 -18
  92. package/server/lib/sdk-manager.js +178 -30
  93. package/server/pty-manager.js +103 -4
  94. package/server/routes/ask-perm.js +87 -6
  95. package/server/routes/files-content.js +46 -8
  96. package/server/routes/scheduled-tasks.js +13 -0
  97. package/server/server.js +100 -0
  98. package/server/system-prompt-templates/presets/kimi-k3.md +8 -0
  99. package/dist/assets/App-BN3viVRq.js +0 -2
  100. package/dist/assets/App-BvVdj099.css +0 -1
  101. package/dist/assets/Mobile-nbI6IeX_.js +0 -1
  102. package/dist/assets/classDiagram-6PBFFD2Q-BUmU_G-i.js +0 -1
  103. package/dist/assets/classDiagram-v2-HSJHXN6E-BUmU_G-i.js +0 -1
  104. package/dist/assets/clone-CvoOne2K.js +0 -1
  105. package/dist/assets/index-DoFyHmPM.js +0 -2
  106. package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
  107. package/dist/assets/seqResourceLoaders-n9iXZRHx.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // Ask / permission hook bridge routes (moved verbatim from server.js handleRequest).
2
- import { loadAskStore, consumeIfFinal as askStoreConsumeIfFinal, markCancelled as askStoreMarkCancelled } from '../lib/ask/ask-store.js';
2
+ import { loadAskStore, consumeIfFinal as askStoreConsumeIfFinal, markCancelled as askStoreMarkCancelled, markAnswered as askStoreMarkAnswered } from '../lib/ask/ask-store.js';
3
3
  import { runWaterfallHook, runParallelHook } from '../lib/plugin-loader.js';
4
4
  import { sendEventToClients } from '../lib/log-watcher.js';
5
5
  import { filterClientsByScope } from '../lib/v2/view-router.js';
@@ -9,6 +9,7 @@ import { getCurrentProjectKey, hasFork, resolveScoped } from '../lib/project-pre
9
9
  import { reportSwallowed } from '../lib/error-report.js';
10
10
  import { computeAutoApprove, createAutoApproveState } from '../lib/auto-approve.js';
11
11
  import { isPublishCommand } from '../lib/approval-policy.js';
12
+ import { computeAskAutoAnswer, createAskAutoAnswerState, pickAutoAnswers, replayAskAutoAnswerFields } from '../lib/ask-auto-answer.js';
12
13
 
13
14
  function pendingAsks(req, res, parsedUrl, isLocal, deps) {
14
15
  try {
@@ -17,6 +18,8 @@ function pendingAsks(req, res, parsedUrl, isLocal, deps) {
17
18
  // 答案投递仍由 WS ask-hook-answer 路径走 server 端 first-write-wins)。
18
19
  const memEntries = [...deps.pendingAskHooks.entries()].map(([id, e]) => ({
19
20
  id, questions: e.questions, createdAt: e.createdAt, source: 'memory',
21
+ // Hosting fields for the reconnect recovery chain (client countdown UI).
22
+ ...replayAskAutoAnswerFields(e.auto, e.autoCancelled),
20
23
  }));
21
24
  const memIds = new Set(memEntries.map(e => e.id));
22
25
  const diskAll = loadAskStore();
@@ -25,7 +28,12 @@ function pendingAsks(req, res, parsedUrl, isLocal, deps) {
25
28
  // 另外过滤 questions 数组非空(防御性)。
26
29
  const diskOnly = Object.values(diskAll)
27
30
  .filter(e => !memIds.has(e.id) && e.status === 'pending' && Array.isArray(e.questions) && e.questions.length > 0)
28
- .map(e => ({ id: e.id, questions: e.questions, createdAt: e.createdAt, source: 'disk' }));
31
+ .map(e => ({
32
+ id: e.id, questions: e.questions, createdAt: e.createdAt, source: 'disk',
33
+ // Timers are memory-only: after a server restart an orphaned pending ask
34
+ // degrades to manual answering (documented decision — no schema migration).
35
+ autoAnswerAt: null, autoAnswerSeconds: null, autoCancelled: false,
36
+ }));
29
37
  const all = [...memEntries, ...diskOnly].sort((a, b) => a.createdAt - b.createdAt);
30
38
  res.writeHead(200, { 'Content-Type': 'application/json' });
31
39
  res.end(JSON.stringify({ pendingAsks: all, askProtocolVersion: 1 }));
@@ -56,7 +64,7 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
56
64
  return;
57
65
  }
58
66
  try {
59
- const { questions, toolUseId } = JSON.parse(body);
67
+ const { questions, toolUseId, cwd } = JSON.parse(body);
60
68
  if (!Array.isArray(questions) || questions.length === 0) {
61
69
  res.writeHead(400, { 'Content-Type': 'application/json' });
62
70
  res.end(JSON.stringify({ error: 'Missing questions' }));
@@ -81,6 +89,7 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
81
89
  const oldest = deps.pendingAskHooks.get(oldestId);
82
90
  if (oldest) {
83
91
  clearTimeout(oldest.timer);
92
+ if (oldest.auto?.timer) clearTimeout(oldest.auto.timer);
84
93
  try { if (!oldest.res.headersSent) { oldest.res.writeHead(429, { 'Content-Type': 'application/json' }); oldest.res.end(JSON.stringify({ error: 'Too many concurrent requests' })); } } catch {}
85
94
  deps.pendingAskHooks.delete(oldestId);
86
95
  deps.persistAskDelete(oldestId);
@@ -106,13 +115,25 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
106
115
  && toolUseId.length > 0 && toolUseId.length <= 256
107
116
  && /^[a-zA-Z0-9_-]+$/.test(toolUseId);
108
117
  let id;
118
+ // A durable per-ask hosting cancel carried over from the slot being replaced
119
+ // (ask-bridge retry) — initialized before the placeholder is created below.
120
+ let _placeholderAutoCancelled = false;
109
121
  if (wantsToolUseId) {
110
122
  const existing = deps.pendingAskHooks.get(toolUseId);
111
123
  if (!existing) {
112
124
  id = toolUseId;
113
125
  } else if (!existing.res || existing.res.writableEnded || existing.res.destroyed) {
114
126
  // 旧 res 已断(包含占位 res:null 残留)— ask-bridge 重试同 toolUseId 合理,复用槽位
127
+ // Clear the stale hosting timer too: it would otherwise fire later against the
128
+ // re-registered entry and answer it at the OLD deadline with the OLD selection.
129
+ // The new entry arms a fresh full-length timer from this re-arrival (the disk
130
+ // schema carries no deadline, so the original one cannot be preserved).
115
131
  if (existing.timer) clearTimeout(existing.timer);
132
+ if (existing.auto?.timer) clearTimeout(existing.auto.timer);
133
+ // Preserve a durable per-ask hosting cancel across the retry: a user who
134
+ // cancelled hosting for THIS ask must not be auto-answered by the re-posted
135
+ // incarnation. (The cancelling tab also re-asserts via its local latch.)
136
+ if (existing.autoCancelled === true) _placeholderAutoCancelled = true;
116
137
  deps.pendingAskHooks.delete(toolUseId);
117
138
  deps.persistAskDelete(toolUseId);
118
139
  id = toolUseId;
@@ -132,7 +153,11 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
132
153
  // TOCTOU 防御:占位 id 之前先注册 res.on('close'),否则 await runWaterfallHook 期间 client
133
154
  // abort 的 close 事件落空 → entry 残到 HOOK_TIMEOUT(24h)。占位 set 提前到 await 之前防两条同 ms 并发
134
155
  // POST 的 do-while 都通过 collision check 后 set 互相覆盖(first res 永泄漏到 HOOK_TIMEOUT)。
135
- const _placeholderEntry = { questions, res, timer: null, createdAt: Date.now(), shortPoll: shortPollMode };
156
+ // Both hosting fields live on the placeholder too: a client ask-auto-cancel
157
+ // landing during the plugin-waterfall window stamps the durable flag here, and
158
+ // the live entry below inherits it (otherwise the cancel would be silently lost
159
+ // when the live object replaces the placeholder).
160
+ const _placeholderEntry = { questions, res, timer: null, createdAt: Date.now(), shortPoll: shortPollMode, autoCancelled: _placeholderAutoCancelled, auto: null };
136
161
  deps.pendingAskHooks.set(id, _placeholderEntry);
137
162
  deps.persistAskEntry(id, _placeholderEntry);
138
163
  // Seed waiter liveness for the reaper (ask-reaper.js). Optional chaining:
@@ -146,6 +171,7 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
146
171
  if (entry) {
147
172
  if (entry.shortPoll) return;
148
173
  if (entry.timer) clearTimeout(entry.timer);
174
+ if (entry.auto?.timer) clearTimeout(entry.auto.timer);
149
175
  deps.pendingAskHooks.delete(id);
150
176
  deps.persistAskDelete(id);
151
177
  if (deps.terminalWss) {
@@ -179,6 +205,7 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
179
205
  const timer = setTimeout(() => {
180
206
  const entry = deps.pendingAskHooks.get(id);
181
207
  if (entry) {
208
+ if (entry.auto?.timer) clearTimeout(entry.auto.timer); // defensive: outlives hosting in normal flows
182
209
  deps.pendingAskHooks.delete(id);
183
210
  deps.persistAskDelete(id);
184
211
  try {
@@ -199,7 +226,15 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
199
226
  }, HOOK_TIMEOUT);
200
227
 
201
228
  const askStartedAt = Date.now();
202
- const _liveEntry = { questions, res, timer, createdAt: askStartedAt, shortPoll: shortPollMode };
229
+ // Server-side hosting ("问答题自动托管"): when approvalModal.askAutoAnswerMinutes
230
+ // is set (0 = instant, N = N minutes), the server answers the ask itself at the
231
+ // wall-clock deadline (+1s buffer) even with no browser connected. Computed after
232
+ // the plugin waterfall so a plugin-answered ask never arms. The pick prefers the
233
+ // first option carrying a localized "Recommended" marker, else the first option.
234
+ const autoMeta = computeAskAutoAnswer(typeof cwd === 'string' && cwd ? cwd : undefined, { file: deps.getPrefsFile?.() });
235
+ const autoAnswers = autoMeta.enabled ? pickAutoAnswers(questions) : null;
236
+ const hosting = autoMeta.enabled && !!autoAnswers;
237
+ const _liveEntry = { ..._placeholderEntry, timer, createdAt: askStartedAt };
203
238
  deps.pendingAskHooks.set(id, _liveEntry);
204
239
  deps.persistAskEntry(id, _liveEntry);
205
240
 
@@ -214,8 +249,16 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
214
249
  }
215
250
 
216
251
  // Broadcast to all terminal WS clients — 附 startedAt + timeoutMs 让前端渲染倒计时
252
+ // Honor a cancel inherited from the placeholder (slot-reuse) or landed during the
253
+ // plugin waterfall: never advertise a countdown that the fire guard will no-op.
254
+ const hostingActive = hosting && !_liveEntry.autoCancelled;
217
255
  if (deps.terminalWss) {
218
- const pmsg = JSON.stringify({ type: 'ask-hook-pending', id, questions, startedAt: askStartedAt, timeoutMs: HOOK_TIMEOUT });
256
+ // Always stamp the hosting fields (null when off) so a client whose global pref
257
+ // disagrees with the fork-resolved server value never re-arms locally.
258
+ const pmsg = JSON.stringify({
259
+ type: 'ask-hook-pending', id, questions, startedAt: askStartedAt, timeoutMs: HOOK_TIMEOUT,
260
+ ...replayAskAutoAnswerFields(hostingActive ? autoMeta : null, _liveEntry.autoCancelled),
261
+ });
219
262
  deps.terminalWss.clients.forEach((client) => {
220
263
  if (client.readyState === 1) {
221
264
  try { client.send(pmsg); } catch {}
@@ -223,6 +266,43 @@ function askHook(req, res, parsedUrl, isLocal, deps) {
223
266
  });
224
267
  }
225
268
  deps.notifyParentPending({ type: 'ask-hook-pending', id, questions });
269
+
270
+ // Arm AFTER the entry is registered AND the pending frame is out: instant (0min)
271
+ // fires synchronously and resolves through the entry, so clients observe the
272
+ // order pending → resolved (never a ghost modal for an already-answered ask).
273
+ if (hostingActive) {
274
+ _liveEntry.auto = createAskAutoAnswerState(autoMeta, async () => {
275
+ const entry = deps.pendingAskHooks.get(id);
276
+ if (!entry || entry.autoCancelled) return;
277
+ if (entry.timer) clearTimeout(entry.timer);
278
+ deps.pendingAskHooks.delete(id);
279
+ deps.askWaiterLastPoll?.delete(id);
280
+ if (entry.shortPoll) {
281
+ // first-write-wins: a client answer (or another cc-viewer instance sharing
282
+ // ask-store.json) may have beaten the timer — never notify listeners with
283
+ // answers that disagree with the disk record.
284
+ let wrote = false;
285
+ try { wrote = await askStoreMarkAnswered(id, autoAnswers); } catch (err) { reportSwallowed('ask-perm.ask-auto-answered', err); }
286
+ if (!wrote) return;
287
+ deps.notifyShortPollAnswer?.(id, autoAnswers);
288
+ } else {
289
+ try {
290
+ if (entry.res && !entry.res.headersSent) {
291
+ entry.res.writeHead(200, { 'Content-Type': 'application/json' });
292
+ entry.res.end(JSON.stringify({ answers: autoAnswers }));
293
+ }
294
+ } catch {}
295
+ deps.persistAskDelete(id);
296
+ }
297
+ if (deps.terminalWss) {
298
+ const rmsg = JSON.stringify({ type: 'ask-hook-resolved', id, reason: 'auto-answered' });
299
+ deps.terminalWss.clients.forEach((c) => {
300
+ if (c.readyState === 1) try { c.send(rmsg); } catch {}
301
+ });
302
+ }
303
+ deps.notifyParentPending({ type: 'ask-hook-resolved', id });
304
+ });
305
+ }
226
306
  } catch {
227
307
  res.writeHead(400, { 'Content-Type': 'application/json' });
228
308
  res.end(JSON.stringify({ error: 'Invalid request body' }));
@@ -342,6 +422,7 @@ function askHookCancel(req, res, parsedUrl, isLocal, deps) {
342
422
  const entry = deps.pendingAskHooks.get(id);
343
423
  if (entry) {
344
424
  if (entry.timer) clearTimeout(entry.timer);
425
+ if (entry.auto?.timer) clearTimeout(entry.auto.timer);
345
426
  deps.pendingAskHooks.delete(id);
346
427
  deps.askWaiterLastPoll?.delete(id);
347
428
  if (entry.shortPoll) {
@@ -9,6 +9,7 @@ import { projectKeyForCwd } from '../lib/system-prompt-snapshots.js';
9
9
  import { loadWorkspaces } from '../workspace-registry.js';
10
10
  import { listLivePtys } from '../pty-manager.js';
11
11
  import { reportSwallowed } from '../lib/error-report.js';
12
+ import { isBinaryBuffer, getUtf16Encoding } from '../lib/binary-sniff.js';
12
13
  import { discoverClaudeMdCandidates, readCandidateById } from '../lib/claude-md-discovery.js';
13
14
  import { getClaudeConfigDir } from '../../findcc.js';
14
15
  import { _projectName } from '../interceptor.js';
@@ -158,10 +159,19 @@ function fileContentGetWithRoot(req, res, parsedUrl, reqPath, cwd) {
158
159
  res.end(JSON.stringify({ error: 'File too large' }));
159
160
  return;
160
161
  }
161
- const content = readFileSync(real, 'utf-8');
162
- // path 字段回返原始入参,前端用它做路径展示与后续 POST 引用
162
+ const raw = readFileSync(real);
163
+ if (isBinaryBuffer(raw)) {
164
+ res.writeHead(415, { 'Content-Type': 'application/json' });
165
+ res.end(JSON.stringify({ error: 'Binary file', reason: 'binary', size: st.size }));
166
+ return;
167
+ }
168
+ const encoding = getUtf16Encoding(raw);
169
+ const content = encoding === 'utf16le' ? raw.subarray(2).toString('utf16le')
170
+ : encoding === 'utf16be' ? raw.subarray(2).swap16().toString('utf16le')
171
+ : raw.toString('utf-8');
172
+ // Decoded UTF-16 remains read-only: the existing write endpoint emits UTF-8.
163
173
  res.writeHead(200, { 'Content-Type': 'application/json' });
164
- res.end(JSON.stringify({ path: reqPath, content, size: st.size }));
174
+ res.end(JSON.stringify({ path: reqPath, content, size: st.size, ...(encoding ? { encoding, readOnly: true } : {}) }));
165
175
  } catch (err) {
166
176
  const status = ERROR_STATUS_MAP[err.code] || 500;
167
177
  const message = status === 500 ? `Cannot read file: ${err.message}` : err.message;
@@ -405,7 +415,7 @@ function fileRaw(req, res, parsedUrl) {
405
415
  fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method);
406
416
  }
407
417
 
408
- function fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method) {
418
+ function fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method, options = {}) {
409
419
  try {
410
420
  if (!reqPath) {
411
421
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -417,7 +427,7 @@ function fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method) {
417
427
 
418
428
  // /tmp 原文件不存在时回退到持久化副本(保留原 fallback 语义,但用 policy 守卫)
419
429
  let policy = isReadAllowed(absPath);
420
- if (!policy.ok && policy.reason === 'realpath-failed' && isAbs) {
430
+ if (!policy.ok && policy.reason === 'realpath-failed' && isAbs && options.allowPersistedFallback !== false) {
421
431
  const pName = _projectName || 'default';
422
432
  const persistPrefix = join(getClaudeConfigDir(), 'cc-viewer', pName, 'images');
423
433
  const fileName = basename(absPath);
@@ -445,13 +455,14 @@ function fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method) {
445
455
  res.end(JSON.stringify({ error: 'Not a file' }));
446
456
  return;
447
457
  }
448
- if (stat.size > 10 * 1024 * 1024) {
458
+ const maxBytes = options.maxBytes ?? 10 * 1024 * 1024;
459
+ if (stat.size > maxBytes) {
449
460
  res.writeHead(413, { 'Content-Type': 'application/json' });
450
- res.end(JSON.stringify({ error: 'File too large' }));
461
+ res.end(JSON.stringify({ error: 'File too large', ...(options.archive ? { maxBytes, size: stat.size } : {}) }));
451
462
  return;
452
463
  }
453
464
  const ext = (targetFile.match(/\.[^.]+$/) || [''])[0].toLowerCase();
454
- const mime = FILE_RAW_MIME[ext] || 'application/octet-stream';
465
+ const mime = options.archive ? 'application/octet-stream' : FILE_RAW_MIME[ext] || 'application/octet-stream';
455
466
  const data = method === 'HEAD' ? null : readFileSync(targetFile);
456
467
  const size = method === 'HEAD' ? stat.size : data.length;
457
468
  const headers = { 'Content-Type': mime, 'Content-Length': size };
@@ -474,6 +485,24 @@ function fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, method) {
474
485
  }
475
486
  }
476
487
 
488
+ const ARCHIVE_RAW_MAX_BYTES = 32 * 1024 * 1024;
489
+ const ARCHIVE_PREVIEW_EXTENSIONS = new Set(['.zip', '.tar', '.gz', '.tgz']);
490
+
491
+ function archiveRaw(req, res, parsedUrl) {
492
+ const reqPath = parsedUrl.searchParams.get('path') || '';
493
+ const name = basename(reqPath).toLowerCase();
494
+ if (!reqPath || ![...ARCHIVE_PREVIEW_EXTENSIONS].some(ext => name.endsWith(ext))) {
495
+ res.writeHead(400, { 'Content-Type': 'application/json' });
496
+ res.end(JSON.stringify({ error: 'Unsupported archive path' }));
497
+ return;
498
+ }
499
+ const cwd = _viewRootOrReply(req, res, parsedUrl);
500
+ if (!cwd) return;
501
+ fileRawWithRoot(req, res, parsedUrl, reqPath, cwd, req.method, {
502
+ archive: true, maxBytes: ARCHIVE_RAW_MAX_BYTES, allowPersistedFallback: false,
503
+ });
504
+ }
505
+
477
506
  // Browser download endpoint: unlike fileRaw (inline preview, 10MB cap), this streams
478
507
  // the file with Content-Disposition: attachment so the browser saves it to disk.
479
508
  // No size cap — a download is precisely the path for files too large to preview.
@@ -718,6 +747,14 @@ function fileContentPost(req, res, parsedUrl, isLocal) {
718
747
  res.end(JSON.stringify({ error: 'Forbidden', reason: 'outside-view-root' }));
719
748
  return;
720
749
  }
750
+ if (existsSync(targetReal)) {
751
+ const raw = readFileSync(targetReal);
752
+ if (getUtf16Encoding(raw) || isBinaryBuffer(raw)) {
753
+ res.writeHead(415, { 'Content-Type': 'application/json' });
754
+ res.end(JSON.stringify({ error: 'File requires read-only preview', reason: 'encoding' }));
755
+ return;
756
+ }
757
+ }
721
758
  writeFileSync(targetReal, content, 'utf-8');
722
759
  const stat = statSync(targetReal);
723
760
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -840,6 +877,7 @@ export const filesContentRoutes = [
840
877
  { method: 'GET', match: 'exact', path: '/api/project-memory', handler: projectMemory },
841
878
  { method: 'GET', match: 'exact', path: '/api/claude-md', handler: claudeMd },
842
879
  { predicate: (url, method) => (url === '/api/file-raw' || url.startsWith('/api/file-raw/')) && (method === 'GET' || method === 'HEAD'), handler: fileRaw },
880
+ { predicate: (url, method) => url === '/api/archive-raw' && (method === 'GET' || method === 'HEAD'), handler: archiveRaw },
843
881
  { predicate: (url, method) => url === '/api/download-file' && (method === 'GET' || method === 'HEAD'), handler: fileDownload },
844
882
  { method: 'POST', match: 'exact', path: '/api/file-content', handler: fileContentPost },
845
883
  { method: 'GET', match: 'exact', path: '/api/target-files', handler: targetFiles },
@@ -165,10 +165,19 @@ function _publicTask(t) {
165
165
  // List payload keeps the full prompt OUT (it may carry secrets and every logged-in
166
166
  // viewer can read the list — security P2-3). Full prompts only ship when the project
167
167
  // resolves (bound / registry / live instance — see listHandler's fullPrompt gate).
168
+ // Attachments (absolute paths, usernames) and template snapshots get the same treatment.
168
169
  function _listTask(t) {
169
170
  const p = _publicTask(t);
170
171
  p.promptSummary = String(t.prompt || '').replace(/\s+/g, ' ').trim().slice(0, 200);
172
+ // Attachments-only tasks have no prompt text — fall back to file names so the list
173
+ // row and toasts never render blank.
174
+ if (!p.promptSummary && Array.isArray(t.attachments) && t.attachments.length) {
175
+ p.promptSummary = `[${t.attachments.map(a => a.name).filter(Boolean).join(', ')}]`.slice(0, 200);
176
+ }
171
177
  delete p.prompt;
178
+ delete p.attachments;
179
+ delete p.template;
180
+ delete p.templateContent;
172
181
  return p;
173
182
  }
174
183
 
@@ -190,6 +199,8 @@ function createHandler(req, res, parsedUrl, isLocal, deps) {
190
199
  out = await createTask(LOG_DIR, {
191
200
  project, cwd: resolved.cwd, prompt: body.prompt, mode: body.mode,
192
201
  schedule: body.schedule, enabled: body.enabled,
202
+ template: body.template, templateContent: body.templateContent,
203
+ attachments: body.attachments,
193
204
  }, Date.now());
194
205
  } catch (err) {
195
206
  reportSwallowed('scheduled-tasks.create', err);
@@ -210,6 +221,8 @@ function updateHandler(req, res, parsedUrl, isLocal, deps) {
210
221
  try {
211
222
  out = await updateTask(LOG_DIR, id, {
212
223
  prompt: body.prompt, mode: body.mode, schedule: body.schedule, enabled: body.enabled,
224
+ template: body.template, templateContent: body.templateContent,
225
+ attachments: body.attachments,
213
226
  }, Date.now());
214
227
  } catch (err) {
215
228
  reportSwallowed('scheduled-tasks.update', err);
package/server/server.js CHANGED
@@ -53,6 +53,7 @@ import * as imProcMgr from './lib/im/im-process-manager.js';
53
53
  import * as chatQueue from './lib/chat-queue.js';
54
54
  import { reportSwallowed } from './lib/error-report.js';
55
55
  import { cancelAutoApproveState } from './lib/auto-approve.js';
56
+ import { cancelAskAutoAnswerState, replayAskAutoAnswerFields } from './lib/ask-auto-answer.js';
56
57
  import { initScheduledTaskScheduler, startScheduledTaskScheduler, stopScheduledTaskScheduler } from './lib/scheduled-task-scheduler.js';
57
58
  import { executeScheduledTask } from './lib/scheduled-task-executor.js';
58
59
  import './lib/adapters/dingtalk-adapter.js'; // side-effect: registers the DingTalk adapter
@@ -760,6 +761,7 @@ const deps = {
760
761
  shortPollListeners,
761
762
  askWaiterLastPoll,
762
763
  notifyShortPollCancel: _notifyShortPollCancel,
764
+ notifyShortPollAnswer: _notifyShortPollAnswer,
763
765
  editorSessions,
764
766
  gitRestoreLocks,
765
767
  liveStreamLastSeq: _liveStreamLastSeq,
@@ -1660,6 +1662,7 @@ async function _doStart() {
1660
1662
  getPtyState: pmb.getPtyState,
1661
1663
  getPtyKind: pmb.getPtyKind,
1662
1664
  getPtySkipPermissions: pmb.getPtySkipPermissions,
1665
+ getPtyBootState: pmb.getPtyBootState,
1663
1666
  isStreaming: () => streamingState.active,
1664
1667
  getConfig: () => loadConfig(id),
1665
1668
  // 钉钉 AI 卡片逐字流式的文本源(仅 worker 注入):对话过程中读主 agent 累计文本,
@@ -1741,6 +1744,7 @@ function _buildPluginInteractions() {
1741
1744
  if (!entry) return false;
1742
1745
  const { res: hookRes, timer } = entry;
1743
1746
  clearTimeout(timer);
1747
+ if (entry.auto?.timer) clearTimeout(entry.auto.timer); // hosting timer must not fire post-resolve
1744
1748
  pendingAskHooks.delete(id);
1745
1749
  _persistAskDelete(id);
1746
1750
  try {
@@ -2263,6 +2267,10 @@ async function setupTerminalWebSocket(httpServer) {
2263
2267
  questions: entry.questions,
2264
2268
  startedAt: now, // 让前端按"还剩 remaining"起算(不是原 createdAt)
2265
2269
  timeoutMs: remaining, // 剩余可用时间
2270
+ // Hosting fields: keep the original absolute autoAnswerAt (do not rebase)
2271
+ // so a reconnected client's countdown stays on the server deadline, and a
2272
+ // cancelled hosting never re-arms.
2273
+ ...replayAskAutoAnswerFields(entry.auto, entry.autoCancelled),
2266
2274
  }));
2267
2275
  } catch {}
2268
2276
  }
@@ -2325,6 +2333,13 @@ async function setupTerminalWebSocket(httpServer) {
2325
2333
  if (p.kind === 'ask') {
2326
2334
  payload.startedAt = Date.now();
2327
2335
  payload.timeoutMs = p.remainingMs;
2336
+ // Hosting fields (autoAnswerAt / autoAnswerSeconds / autoCancelled) come
2337
+ // from the sdk-manager snapshot (_getPendingApprovals) — stamp them so a
2338
+ // reconnected client restores the server deadline countdown and a
2339
+ // cancelled hosting never re-arms.
2340
+ payload.autoAnswerAt = p.autoAnswerAt ?? null;
2341
+ payload.autoAnswerSeconds = p.autoAnswerSeconds ?? null;
2342
+ payload.autoCancelled = p.autoCancelled === true;
2328
2343
  } else {
2329
2344
  // plan/perm: carry the server-side auto-approve deadline so a reconnected
2330
2345
  // client renders the REMAINING time (and a cancelled one never re-arms)
@@ -2396,6 +2411,31 @@ async function setupTerminalWebSocket(httpServer) {
2396
2411
  }
2397
2412
  }
2398
2413
 
2414
+ // Replay the authoritative sdk-task table so a refreshed/reconnected client can
2415
+ // reconcile its delta-only tracker (the active-agents strip) — a task frame lost in
2416
+ // a WS gap is no longer unrecoverable, and a session switch drops the table so the
2417
+ // prior session's agents never linger. Unlike the snapshots above, an EMPTY
2418
+ // `tasks: []` is authoritative (reconciles the client to "no tasks") and must be
2419
+ // sent. Anchor by view instance (exact) else view project — sdk-skills parity. When
2420
+ // the anchor resolves to no session at all, synthesize that empty frame for a bound
2421
+ // view so the reconcile is not silently lost; an unbound view sends nothing.
2422
+ if (isSdkMode && _sdkGetSdkTaskSnapshot) {
2423
+ const anchor = ws._ccvViewInstance
2424
+ ? { instanceKey: ws._ccvViewInstance }
2425
+ : (_viewProj ? { project: _viewProj } : null);
2426
+ const taskSnap = anchor ? _sdkGetSdkTaskSnapshot(anchor) : _sdkGetSdkTaskSnapshot();
2427
+ const taskFrame = taskSnap || ((ws._ccvViewInstance || ws._ccvViewProject) ? {
2428
+ type: 'sdk-task-snapshot',
2429
+ ...(ws._ccvViewProject ? { project: ws._ccvViewProject } : {}),
2430
+ ...(ws._ccvViewInstance ? { instanceKey: ws._ccvViewInstance } : {}),
2431
+ sessionId: null,
2432
+ tasks: [],
2433
+ } : null);
2434
+ if (taskFrame && _sdkFrameForView(taskFrame)) {
2435
+ try { ws.send(JSON.stringify(taskFrame)); } catch {}
2436
+ }
2437
+ }
2438
+
2399
2439
  // Replay the chat-composer busy queue so a refreshed/reconnected page restores the
2400
2440
  // floating queued-message bubbles (server is the source of truth in both modes).
2401
2441
  replayQueueSnapshot();
@@ -2573,6 +2613,24 @@ async function setupTerminalWebSocket(httpServer) {
2573
2613
  try { ws.send(JSON.stringify(stateSnap)); } catch (err) { reportSwallowed('sdk.session-state-replay', err); }
2574
2614
  }
2575
2615
  }
2616
+ // Replay the authoritative sdk-task table for the JUST-viewed workspace
2617
+ // (skills parity) so switching back to a workspace whose agent is mid-run
2618
+ // restores the active-agents strip immediately, and an empty table clears
2619
+ // a previously viewed workspace's agents. Anchor AND filter against the
2620
+ // freshly-stamped view — _sdkFrameForView closes over the connection-time
2621
+ // _viewProj, which is the departing view on a cross-workspace attach.
2622
+ if (_sdkGetSdkTaskSnapshot) {
2623
+ const taskAnchor = ws._ccvViewInstance
2624
+ ? { instanceKey: ws._ccvViewInstance }
2625
+ : (ws._ccvViewProject ? { project: ws._ccvViewProject } : null);
2626
+ const taskSnap = taskAnchor ? _sdkGetSdkTaskSnapshot(taskAnchor) : _sdkGetSdkTaskSnapshot();
2627
+ if (taskSnap) {
2628
+ const fp = (typeof taskSnap.cwd === 'string' && taskSnap.cwd) ? (projectKeyForCwd(taskSnap.cwd) || null) : null;
2629
+ if (!fp || !ws._ccvViewProject || fp === ws._ccvViewProject) {
2630
+ try { ws.send(JSON.stringify(taskSnap)); } catch { }
2631
+ }
2632
+ }
2633
+ }
2576
2634
  replayQueueSnapshot();
2577
2635
  return;
2578
2636
  }
@@ -2721,6 +2779,9 @@ async function setupTerminalWebSocket(httpServer) {
2721
2779
  if (askEntry) {
2722
2780
  const { res: hookRes, timer } = askEntry;
2723
2781
  clearTimeout(timer);
2782
+ // Client answer wins: destroy the hosting timer so it cannot fire a
2783
+ // second, stale auto-answer after the manual one (perm parity :2856).
2784
+ if (askEntry.auto?.timer) clearTimeout(askEntry.auto.timer);
2724
2785
  pendingAskHooks.delete(askId);
2725
2786
  // Phase 3: short-poll 模式不立即删 disk —— 落 answered 让 GET listener / disk consume 拿
2726
2787
  if (askEntry.shortPoll) {
@@ -2866,6 +2927,7 @@ async function setupTerminalWebSocket(httpServer) {
2866
2927
  if (askEntry) {
2867
2928
  const { res: hookRes, timer } = askEntry;
2868
2929
  if (timer) clearTimeout(timer);
2930
+ if (askEntry.auto?.timer) clearTimeout(askEntry.auto.timer);
2869
2931
  pendingAskHooks.delete(cancelId);
2870
2932
  // Phase 3: short-poll 同样要让 disk + listener 知道,否则 ask-bridge 永远收不到 cancelled
2871
2933
  if (askEntry.shortPoll) {
@@ -2970,6 +3032,40 @@ async function setupTerminalWebSocket(httpServer) {
2970
3032
  }
2971
3033
  }
2972
3034
  }
3035
+ } else if (msg.type === 'ask-auto-cancel') {
3036
+ // Client cancelled the AskUserQuestion hosting ("取消托管") for ONE ask:
3037
+ // destroys the server-side hosting timer (SDK pending or PTY-hook entry),
3038
+ // the ask REMAINS pending for a manual answer, and the cancelled state is
3039
+ // replayed to fresh clients so they never re-arm the countdown. The global
3040
+ // setting is untouched — later asks are still hosted. Never a
3041
+ // pending-remove: the ask itself stays open.
3042
+ const rawAskAutoCancelId = msg.id != null ? String(msg.id) : null;
3043
+ const askAutoCancelId = validateApprovalId(msg.id);
3044
+ if (rawAskAutoCancelId && !askAutoCancelId) {
3045
+ console.warn('[server] ask-auto-cancel rejected: invalid id format');
3046
+ return;
3047
+ }
3048
+ let askAutoCancelHandled = false;
3049
+ let sdkBroadcast = false;
3050
+ if (askAutoCancelId && _sdkAutoCancelApproval) {
3051
+ try { askAutoCancelHandled = _sdkAutoCancelApproval(askAutoCancelId, 'ask') === true; } catch (err) { reportSwallowed('server.ask-auto-cancel', err); }
3052
+ sdkBroadcast = askAutoCancelHandled; // SDK's _autoCancelApproval already broadcast
3053
+ }
3054
+ if (!askAutoCancelHandled && askAutoCancelId) {
3055
+ const hookEntry = pendingAskHooks.get(askAutoCancelId);
3056
+ if (hookEntry) {
3057
+ askAutoCancelHandled = cancelAskAutoAnswerState(hookEntry);
3058
+ }
3059
+ }
3060
+ // Broadcast a valid id unless the SDK branch already emitted the same frame.
3061
+ // The PTY/unknown path always relays: sibling tabs may still be counting down
3062
+ // even if this server's entry is already gone (restart / answered elsewhere).
3063
+ if (askAutoCancelId && !sdkBroadcast && terminalWss) {
3064
+ const cmsg = JSON.stringify({ type: 'ask-auto-cancel', id: askAutoCancelId });
3065
+ terminalWss.clients.forEach((c) => {
3066
+ if (c.readyState === 1) try { c.send(cmsg); } catch {}
3067
+ });
3068
+ }
2973
3069
  } else if (msg.type === 'sdk-plan-answer') {
2974
3070
  // Plan approval in SDK mode
2975
3071
  let planAnswered = false;
@@ -4044,6 +4140,10 @@ export function setSdkGetMcpStatusSnapshot(fn) { _sdkGetMcpStatusSnapshot = fn;
4044
4140
  let _sdkGetSessionStateSnapshot = null;
4045
4141
  export function setSdkGetSessionStateSnapshot(fn) { _sdkGetSessionStateSnapshot = fn; }
4046
4142
 
4143
+ /** Reference to sdk-manager's getSdkTaskSnapshot (set by cli.js after import). */
4144
+ let _sdkGetSdkTaskSnapshot = null;
4145
+ export function setSdkGetSdkTaskSnapshot(fn) { _sdkGetSdkTaskSnapshot = fn; }
4146
+
4047
4147
  /** Reference to sdk-manager's sendQueuedNow (set by cli.js after import). */
4048
4148
  let _sdkSendQueuedNow = null;
4049
4149
  export function setSdkSendQueuedNow(fn) { _sdkSendQueuedNow = fn; }
@@ -37,6 +37,14 @@ IMPORTANT: Never generate or guess URLs unless you are confident they help the u
37
37
  - Every ten tool calls, write one line saying what you have confirmed and what is still missing; if you cannot, stop calling tools and report what you have.
38
38
  - Tool results and user messages may include <system-reminder> tags. They carry information from the system, not from the user.
39
39
 
40
+ # Handling tool errors (circuit breaker)
41
+ - A tool error is information, not a transient blip. Read the error message FIRST, diagnose the cause, THEN act — never retry before you understand why it failed.
42
+ - Distinguish failure kinds: an invalid-argument / validation error (bad params, missing required field, wrong type) will fail forever no matter how many times you resend it; only genuine transient failures (network, 5xx, timeout) justify a retry.
43
+ - Retry budget: at most ONE retry per tool call, and only after you have changed something (fixed the argument, corrected the path, adjusted the approach). Never resend the SAME call with the SAME arguments — that is a loop, not a retry.
44
+ - Hard circuit breaker: if the same tool with the same (or near-identical) arguments has failed twice in a row, STOP. Do not issue a third call. Report to the user what you were trying to do, quote the error, and ask how to proceed.
45
+ - Before any structured call (TaskUpdate, TaskCreate, Edit, Write), sanity-check the payload: required fields present? which field am I actually changing? If you cannot say what the call is supposed to change, do not send it.
46
+ - Self-check on loop: if you notice you are about to make a third near-identical call to the same tool, treat it as the circuit-breaker case above — stop and surface it instead of sending.
47
+
40
48
  # Working with teammates
41
49
  - Do not wait passively for a teammate to report back: teammates sometimes finish their task without sending you a message. No notification ≠ not done — check `~/.claude/projects/<slug>/<session>/subagents/agent-*.jsonl` (or SendMessage the teammate) before waiting.
42
50
  - When a teammate goes quiet, ask it directly for its result or status — treat silence as "finished or stuck", never as "still working". Read results back with `tail -N <file> | jq -r 'select(.type=="assistant") | .message.content[] | select(.type=="text") | .text'` — never Read the whole jsonl.