@tothemax/tasking 0.7.1 → 0.8.1

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 (68) hide show
  1. package/assets/workflows/WORKFLOW.code-mr.en.md.example +10 -2
  2. package/assets/workflows/WORKFLOW.code-mr.md.example +10 -2
  3. package/assets/workflows/WORKFLOW.feishu-direct.en.md.example +10 -2
  4. package/assets/workflows/WORKFLOW.feishu-direct.md.example +10 -2
  5. package/assets/workflows/WORKFLOW.grill-openspec.en.md.example +10 -2
  6. package/assets/workflows/WORKFLOW.grill-openspec.md.example +10 -2
  7. package/assets/workflows/WORKFLOW.minimal.en.md.example +10 -2
  8. package/assets/workflows/WORKFLOW.minimal.md.example +10 -2
  9. package/dist/adapters/feishu/source.d.ts.map +1 -1
  10. package/dist/adapters/feishu/source.js +4 -4
  11. package/dist/adapters/feishu/source.js.map +1 -1
  12. package/dist/bridge/binding-store.d.ts +2 -0
  13. package/dist/bridge/binding-store.d.ts.map +1 -1
  14. package/dist/bridge/binding-store.js +8 -0
  15. package/dist/bridge/binding-store.js.map +1 -1
  16. package/dist/bridge/commands.d.ts +19 -0
  17. package/dist/bridge/commands.d.ts.map +1 -1
  18. package/dist/bridge/commands.js +40 -1
  19. package/dist/bridge/commands.js.map +1 -1
  20. package/dist/bridge/comment-bridge.d.ts.map +1 -1
  21. package/dist/bridge/comment-bridge.js +9 -1
  22. package/dist/bridge/comment-bridge.js.map +1 -1
  23. package/dist/cli/init.d.ts.map +1 -1
  24. package/dist/cli/init.js +20 -8
  25. package/dist/cli/init.js.map +1 -1
  26. package/dist/config/config-types.d.ts +14 -0
  27. package/dist/config/config-types.d.ts.map +1 -1
  28. package/dist/config/config-types.js +8 -0
  29. package/dist/config/config-types.js.map +1 -1
  30. package/dist/config/manager.d.ts +1 -0
  31. package/dist/config/manager.d.ts.map +1 -1
  32. package/dist/config/manager.js +14 -12
  33. package/dist/config/manager.js.map +1 -1
  34. package/dist/config/resolver.d.ts.map +1 -1
  35. package/dist/config/resolver.js +44 -2
  36. package/dist/config/resolver.js.map +1 -1
  37. package/dist/direct/auto-continue.d.ts +64 -0
  38. package/dist/direct/auto-continue.d.ts.map +1 -0
  39. package/dist/direct/auto-continue.js +142 -0
  40. package/dist/direct/auto-continue.js.map +1 -0
  41. package/dist/direct/card.d.ts +29 -3
  42. package/dist/direct/card.d.ts.map +1 -1
  43. package/dist/direct/card.js +150 -52
  44. package/dist/direct/card.js.map +1 -1
  45. package/dist/direct/driver.d.ts +1 -0
  46. package/dist/direct/driver.d.ts.map +1 -1
  47. package/dist/direct/driver.js +1 -0
  48. package/dist/direct/driver.js.map +1 -1
  49. package/dist/direct/manager.d.ts +13 -1
  50. package/dist/direct/manager.d.ts.map +1 -1
  51. package/dist/direct/manager.js +665 -50
  52. package/dist/direct/manager.js.map +1 -1
  53. package/dist/driver/session-ops.d.ts +1 -0
  54. package/dist/driver/session-ops.d.ts.map +1 -1
  55. package/dist/driver/session-ops.js +2 -0
  56. package/dist/driver/session-ops.js.map +1 -1
  57. package/dist/driver/turn-driver.d.ts +6 -0
  58. package/dist/driver/turn-driver.d.ts.map +1 -1
  59. package/dist/driver/turn-driver.js +132 -34
  60. package/dist/driver/turn-driver.js.map +1 -1
  61. package/dist/shared/card-payload.d.ts +3 -0
  62. package/dist/shared/card-payload.d.ts.map +1 -0
  63. package/dist/shared/card-payload.js +8 -0
  64. package/dist/shared/card-payload.js.map +1 -0
  65. package/dist/translate/dict.d.ts.map +1 -1
  66. package/dist/translate/dict.js +114 -4
  67. package/dist/translate/dict.js.map +1 -1
  68. package/package.json +2 -2
@@ -1,14 +1,16 @@
1
1
  import { existsSync, mkdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { basename, extname, join } from "node:path";
3
3
  import { toSecondsStr, } from "../adapters/feishu/source.js";
4
- import { parseChat } from "../bridge/commands.js";
4
+ import { parseChat, parseLoop } from "../bridge/commands.js";
5
5
  import { readTaskingVersion } from "../cli/version.js";
6
+ import { AUTO_CONTINUE_PROMPT_MAX_CHARS, } from "../config/config-types.js";
6
7
  import { defaultApiExec, describeApiCommand } from "../driver/api-client.js";
7
8
  import { ApprovalCoordinator } from "../driver/approval.js";
8
9
  import { ALLOW_ALL_RULES, formatResolvedModel, modelDriftMessage, replyPermission, setSessionPermissions, } from "../driver/session-ops.js";
9
10
  import { TaskingError, toTaskingError } from "../shared/errors.js";
10
11
  import { redactSecrets } from "../shared/redact.js";
11
- import { CARD_BUDGET_BYTES, buildApprovalCard, buildCompletionCard, buildInfoCard, buildTurnCard, formatTokens, isFailed, toolSummary, } from "./card.js";
12
+ import { classifyAutoTurn, freshAutoContinueState, isFileMutationTool, resetAutoContinueRuns, } from "./auto-continue.js";
13
+ import { CARD_BUDGET_BYTES, buildApprovalCard, buildCompletionCard, buildInfoCard, buildTurnCard, cardFits, cardPayloadBytes, formatTokens, isFailed, renderedCardFits, toolSummary, } from "./card.js";
12
14
  import { createDefaultTurnDriver } from "./driver.js";
13
15
  const MAX_MESSAGE_CHARS = 3500;
14
16
  const TTL_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
@@ -187,6 +189,12 @@ export class DirectSessionManager {
187
189
  if (turn !== null && turn !== currentTurn) {
188
190
  return { toast: { type: "info", content: "该轮已结束" } };
189
191
  }
192
+ const activeCardId = rt.cardId ?? session.card_message_id;
193
+ if ((name === "stop" || name === "retry" || name === "full") &&
194
+ activeCardId !== null &&
195
+ action.messageId !== activeCardId) {
196
+ return { toast: { type: "info", content: translate("该片段已结束") } };
197
+ }
190
198
  if (name === "stop") {
191
199
  if (!rt.turnInFlight || !rt.abort) {
192
200
  return { toast: { type: "info", content: "该轮已结束" } };
@@ -504,6 +512,8 @@ export class DirectSessionManager {
504
512
  "**命令**",
505
513
  "`/collect` → 收集多条消息;`/send` 提交为一轮;`/cancel` 丢弃",
506
514
  "`/auto [on|once|off|reset]` → 本会话权限姿态(下一轮生效)",
515
+ "`/loop on [N]` → 为下一条任务开启自动续跑;`/loop start` 立即继续;`/loop off` 关闭",
516
+ "`/loop prompt <文本>` → 设置续跑提示词(`reset` 恢复默认)",
507
517
  "`/name <文本>` → 会话改名(卡片头部与 TUI)",
508
518
  "`/agent <name>` · `/model <name>` → 切换 agent/model(`reset` 恢复)",
509
519
  "`/new` → 清空上下文开启新会话",
@@ -702,6 +712,7 @@ export class DirectSessionManager {
702
712
  }
703
713
  async enqueueRetry(rootId, prompt, fromTurn) {
704
714
  const rt = this.runtimeFor(rootId);
715
+ this.resumeAutoContinueForUserTurn(rt);
705
716
  if (rt.turnInFlight) {
706
717
  rt.queue.push(prompt);
707
718
  return;
@@ -715,6 +726,10 @@ export class DirectSessionManager {
715
726
  const config = this.deps.config();
716
727
  if (!isDirectEnabled(config))
717
728
  return false;
729
+ if (parseLoop(m.text) !== null) {
730
+ await this.deps.feishu.replyFlat(m.message_id, "请在 /chat 话题内使用 /loop。");
731
+ return true;
732
+ }
718
733
  const parsed = parseChat(m.text);
719
734
  if (!parsed)
720
735
  return false;
@@ -855,8 +870,12 @@ export class DirectSessionManager {
855
870
  await this.executeModel(session, trimmed);
856
871
  return true;
857
872
  }
873
+ if (trimmed === "/loop" || trimmed.startsWith("/loop ")) {
874
+ await this.executeLoop(session, trimmed);
875
+ return true;
876
+ }
858
877
  if (trimmed.startsWith("/")) {
859
- await this.replySafe(m.root_id, "未知命令。直连会话支持:直接回复续聊、/collect、/send、/cancel、/auto、/agent、/model、/new、/name、/status、/stop、/done、/help");
878
+ await this.replySafe(m.root_id, "未知命令。直连会话支持:直接回复续聊、/collect、/send、/cancel、/auto、/agent、/model、/loop、/new、/name、/status、/stop、/done、/help");
860
879
  return true;
861
880
  }
862
881
  const attachments = m.attachments ?? [];
@@ -927,10 +946,10 @@ export class DirectSessionManager {
927
946
  turn: session.turns,
928
947
  phase,
929
948
  toolCalls: 0,
949
+ segmentToolCalls: 0,
930
950
  durationSec: 0,
931
951
  turnTokens: 0,
932
- texts: note === "" ? [] : [note],
933
- tools: [],
952
+ events: note === "" ? [] : [{ kind: "text", text: note }],
934
953
  };
935
954
  if (hideFullDetail)
936
955
  state.hideFullDetail = true;
@@ -1123,6 +1142,7 @@ export class DirectSessionManager {
1123
1142
  turn: null,
1124
1143
  turnStartedAt: 0,
1125
1144
  flushedTools: 0,
1145
+ toolPanels: [],
1126
1146
  autoOnce: false,
1127
1147
  turnUsedOnce: false,
1128
1148
  postureOpen: false,
@@ -1144,13 +1164,22 @@ export class DirectSessionManager {
1144
1164
  flushInFlight: false,
1145
1165
  flushQueued: false,
1146
1166
  flushPromise: null,
1167
+ lastCardError: null,
1168
+ autoContinue: null,
1169
+ autoContinueBudget: null,
1147
1170
  };
1148
1171
  this.runtime.set(rootId, rt);
1149
1172
  }
1150
1173
  return rt;
1151
1174
  }
1175
+ resumeAutoContinueForUserTurn(rt) {
1176
+ if (rt.autoContinue === null)
1177
+ return;
1178
+ rt.autoContinue = resetAutoContinueRuns(rt.autoContinue);
1179
+ }
1152
1180
  enqueueTurn(rootId, message) {
1153
1181
  const rt = this.runtimeFor(rootId);
1182
+ this.resumeAutoContinueForUserTurn(rt);
1154
1183
  if (rt.turnInFlight) {
1155
1184
  rt.queue.push(message);
1156
1185
  if (this.cardsLive(rt)) {
@@ -1167,33 +1196,129 @@ export class DirectSessionManager {
1167
1196
  error: toTaskingError(e).message,
1168
1197
  }));
1169
1198
  }
1170
- async runTurnLoop(rootId, firstMessage, retryFromTurn) {
1199
+ autoBudget(rt) {
1200
+ return rt.autoContinueBudget ?? this.deps.config().feishu.direct.auto_continue.budget;
1201
+ }
1202
+ beginAutoTurn(rt) {
1203
+ if (rt.autoContinue === null)
1204
+ return null;
1205
+ const budget = this.autoBudget(rt);
1206
+ if (rt.autoContinue.used >= budget)
1207
+ return null;
1208
+ rt.autoContinue.used += 1;
1209
+ return { index: rt.autoContinue.used, max: budget };
1210
+ }
1211
+ async sendAutoPause(rootId, reason, metrics, rt) {
1212
+ const budget = this.autoBudget(rt);
1213
+ const streak = this.deps.config().feishu.direct.auto_continue.no_progress_streak;
1214
+ const used = rt.autoContinue?.used ?? 0;
1215
+ this.deps.logger.info("auto_continue_pause", {
1216
+ root_id: rootId,
1217
+ reason,
1218
+ budget,
1219
+ used,
1220
+ status: metrics.status,
1221
+ duration_ms: metrics.durationMs,
1222
+ tool_calls: metrics.toolCalls,
1223
+ file_mutations: metrics.fileMutations,
1224
+ output_tokens: metrics.outputTokens,
1225
+ text_chars: metrics.textChars,
1226
+ });
1227
+ const lines = [];
1228
+ if (reason === "question") {
1229
+ lines.push(translate("🔄 自动续跑已暂停:模型在提问"));
1230
+ }
1231
+ else if (reason === "repetition") {
1232
+ lines.push(translate(`🔄 自动续跑已暂停:连续 ${streak} 轮回复重复且没有文件改动`));
1233
+ }
1234
+ else {
1235
+ lines.push(translate(`🔄 自动续跑已暂停:连续 ${streak} 轮低产出`));
1236
+ lines.push(translate(`(工具 ${metrics.toolCalls} · 输出 ${metrics.outputTokens} tokens · 文本 ${metrics.textChars} 字)`));
1237
+ }
1238
+ lines.push(translate(`预算:${used}/${budget} · 回复任意消息自动继续,或 /loop off 关闭。`));
1239
+ await this.replySafe(rootId, lines.join("\n"));
1240
+ }
1241
+ async sendAutoStop(rootId, reason, metrics, rt, detail) {
1242
+ const budget = this.autoBudget(rt);
1243
+ const used = rt.autoContinue?.used ?? 0;
1244
+ this.deps.logger.info("auto_continue_stop", {
1245
+ root_id: rootId,
1246
+ reason,
1247
+ detail: detail ?? null,
1248
+ budget,
1249
+ used,
1250
+ status: metrics?.status ?? null,
1251
+ error: metrics?.error ?? null,
1252
+ duration_ms: metrics?.durationMs ?? null,
1253
+ tool_calls: metrics?.toolCalls ?? null,
1254
+ file_mutations: metrics?.fileMutations ?? null,
1255
+ output_tokens: metrics?.outputTokens ?? null,
1256
+ text_chars: metrics?.textChars ?? null,
1257
+ });
1258
+ const lines = [];
1259
+ if (reason === "budget") {
1260
+ lines.push(translate(detail === "timeout"
1261
+ ? `🔄 自动续跑已停止:本轮超时且预算用完(${used}/${budget})`
1262
+ : `🔄 自动续跑已停止:预算用完(${used}/${budget})`));
1263
+ lines.push(translate("/loop start 重新开干,或 /loop on N 设置新预算。"));
1264
+ }
1265
+ else if (reason === "permission_timeout") {
1266
+ lines.push(translate("🔄 自动续跑已停止:本轮审批超时"));
1267
+ lines.push(translate("/loop start 重新开干。"));
1268
+ }
1269
+ else if (reason === "failed") {
1270
+ const detailText = metrics?.error ? ` (${metrics.error})` : "";
1271
+ lines.push(translate("🔄 自动续跑已停止:本轮失败") + detailText);
1272
+ lines.push(translate("/loop start 重新开干。"));
1273
+ }
1274
+ else {
1275
+ lines.push(translate("🔄 自动续跑已停止:本轮已中断"));
1276
+ }
1277
+ await this.replySafe(rootId, lines.join("\n"));
1278
+ }
1279
+ async runTurnLoop(rootId, firstMessage, retryFromTurn, startAuto = false) {
1171
1280
  const rt = this.runtimeFor(rootId);
1172
1281
  rt.turnInFlight = true;
1173
1282
  rt.stopRequested = false;
1174
1283
  try {
1175
1284
  let prompt = firstMessage;
1176
1285
  let retriedFrom = retryFromTurn;
1286
+ let auto = startAuto;
1177
1287
  for (;;) {
1178
1288
  const session = this.deps.store.getDirectSession(rootId);
1179
- if (!session || session.status === "done" || session.status === "expired")
1289
+ if (!session || session.status === "done" || session.status === "expired") {
1290
+ rt.autoContinue = null;
1180
1291
  break;
1292
+ }
1181
1293
  if (this.halted || rt.stopRequested)
1182
1294
  break;
1295
+ if (auto && (rt.autoContinue === null || rt.autoContinue.pausedReason !== null))
1296
+ break;
1297
+ let autoMeta;
1298
+ if (auto) {
1299
+ const meta = this.beginAutoTurn(rt);
1300
+ if (meta === null) {
1301
+ await this.sendAutoStop(rootId, "budget", null, rt);
1302
+ rt.autoContinue = null;
1303
+ break;
1304
+ }
1305
+ autoMeta = meta;
1306
+ }
1183
1307
  await this.sealTurnCard(rt);
1184
1308
  const max = this.deps.config().feishu.direct.max_concurrent;
1185
1309
  const busy = this.activeTurns >= max || this.dirActiveFor(session.path) >= this.dirConcurrencyLimit();
1186
- await this.startTurnCard(session, rt, busy, retriedFrom);
1310
+ await this.startTurnCard(session, rt, busy, retriedFrom, autoMeta);
1187
1311
  if (busy && !this.cardsLive(rt)) {
1188
1312
  await this.replySafe(rootId, "⏳ 目标目录或并发额度正被占用,排队等待中,空闲后自动开始…");
1189
1313
  }
1190
1314
  await this.acquireDir(session.path);
1315
+ let outcome;
1191
1316
  try {
1192
1317
  await this.acquireSlot();
1193
1318
  try {
1194
1319
  if (this.halted || rt.stopRequested)
1195
1320
  break;
1196
- await this.executeTurn(session, prompt, rt);
1321
+ outcome = await this.executeTurn(session, prompt, rt, auto);
1197
1322
  }
1198
1323
  finally {
1199
1324
  this.releaseSlot();
@@ -1202,27 +1327,121 @@ export class DirectSessionManager {
1202
1327
  finally {
1203
1328
  this.releaseDir(session.path);
1204
1329
  }
1205
- if (rt.queue.length === 0)
1330
+ if (this.halted || rt.stopRequested)
1331
+ break;
1332
+ if (auto && rt.autoContinue === null)
1333
+ break;
1334
+ const fresh = this.deps.store.getDirectSession(rootId);
1335
+ if (!fresh || fresh.status === "done" || fresh.status === "expired") {
1336
+ rt.autoContinue = null;
1337
+ break;
1338
+ }
1339
+ if (rt.queue.length > 0) {
1340
+ if (rt.autoContinue)
1341
+ rt.autoContinue = resetAutoContinueRuns(rt.autoContinue);
1342
+ prompt = rt.queue.join("\n---\n");
1343
+ rt.queue = [];
1344
+ retriedFrom = undefined;
1345
+ auto = false;
1346
+ continue;
1347
+ }
1348
+ if (!auto) {
1349
+ if (rt.autoContinue)
1350
+ rt.autoContinue = resetAutoContinueRuns(rt.autoContinue);
1351
+ if (outcome.status !== "succeeded") {
1352
+ if (rt.autoContinue !== null) {
1353
+ const timeout = outcome.status === "timed_out" && !outcome.error?.includes("permission_timeout");
1354
+ if (timeout && rt.autoContinue.used < this.autoBudget(rt)) {
1355
+ rt.autoContinue = resetAutoContinueRuns(rt.autoContinue);
1356
+ prompt = this.effectiveLoopPrompt(fresh);
1357
+ retriedFrom = undefined;
1358
+ auto = true;
1359
+ continue;
1360
+ }
1361
+ const reason = outcome.status === "interrupted"
1362
+ ? "interrupted"
1363
+ : outcome.error?.includes("permission_timeout")
1364
+ ? "permission_timeout"
1365
+ : outcome.status === "timed_out"
1366
+ ? "budget"
1367
+ : "failed";
1368
+ await this.sendAutoStop(rootId, reason, outcome, rt, outcome.status === "timed_out" ? "timeout" : undefined);
1369
+ rt.autoContinue = null;
1370
+ }
1371
+ break;
1372
+ }
1373
+ if (rt.autoContinue === null)
1374
+ break;
1375
+ if (rt.autoContinue.used >= this.autoBudget(rt)) {
1376
+ await this.sendAutoStop(rootId, "budget", outcome, rt);
1377
+ rt.autoContinue = null;
1378
+ break;
1379
+ }
1380
+ prompt = this.effectiveLoopPrompt(fresh);
1381
+ retriedFrom = undefined;
1382
+ auto = true;
1383
+ continue;
1384
+ }
1385
+ const loopState = rt.autoContinue;
1386
+ if (loopState === null)
1206
1387
  break;
1207
- prompt = rt.queue.join("\n---\n");
1208
- rt.queue = [];
1209
- retriedFrom = undefined;
1388
+ const decision = classifyAutoTurn({
1389
+ metrics: outcome,
1390
+ state: loopState,
1391
+ budget: this.autoBudget(rt),
1392
+ streakThreshold: this.deps.config().feishu.direct.auto_continue.no_progress_streak,
1393
+ });
1394
+ rt.autoContinue = decision.state;
1395
+ this.deps.logger.info("auto_continue_turn", {
1396
+ root_id: rootId,
1397
+ auto_turn: loopState.used,
1398
+ budget: this.autoBudget(rt),
1399
+ status: outcome.status,
1400
+ duration_ms: outcome.durationMs,
1401
+ tool_calls: outcome.toolCalls,
1402
+ file_mutations: outcome.fileMutations,
1403
+ output_tokens: outcome.outputTokens,
1404
+ text_chars: outcome.textChars,
1405
+ last_text_chars: outcome.lastText.length,
1406
+ low_work_run: decision.state.lowWorkRun,
1407
+ repeat_run: decision.state.repeatRun,
1408
+ decision: decision.action,
1409
+ reason: decision.action === "continue" || decision.action === "retry" ? null : decision.reason,
1410
+ });
1411
+ if (decision.action === "continue" || decision.action === "retry") {
1412
+ prompt = this.effectiveLoopPrompt(fresh);
1413
+ retriedFrom = undefined;
1414
+ auto = true;
1415
+ continue;
1416
+ }
1417
+ if (decision.action === "pause") {
1418
+ await this.sendAutoPause(rootId, decision.reason, outcome, rt);
1419
+ break;
1420
+ }
1421
+ await this.sendAutoStop(rootId, decision.reason, outcome, rt, decision.detail);
1422
+ rt.autoContinue = null;
1423
+ break;
1210
1424
  }
1211
1425
  }
1212
1426
  finally {
1213
1427
  rt.turnInFlight = false;
1428
+ const pending = rt.queue;
1429
+ rt.queue = [];
1430
+ if (pending.length > 0 && !this.halted) {
1431
+ this.enqueueTurn(rootId, pending.join("\n---\n"));
1432
+ }
1214
1433
  }
1215
1434
  }
1216
1435
  cardsLive(rt) {
1217
1436
  return rt.cardsAvailable && rt.cardId !== null && rt.turn !== null;
1218
1437
  }
1219
- async startTurnCard(session, rt, busy, retryFromTurn) {
1438
+ async startTurnCard(session, rt, busy, retryFromTurn, autoMeta) {
1220
1439
  const fresh = this.deps.store.getDirectSession(session.root_id) ?? session;
1221
1440
  await rt.flushPromise?.catch(() => { });
1222
1441
  const prev = rt.turn;
1223
- if (prev !== null && prev.tools.length > rt.flushedTools) {
1224
- const pending = prev.tools.slice(rt.flushedTools);
1225
- rt.flushedTools = prev.tools.length;
1442
+ if (prev !== null && rt.toolPanels.length > rt.flushedTools) {
1443
+ const pending = rt.toolPanels.slice(rt.flushedTools);
1444
+ rt.flushedTools = rt.toolPanels.length;
1226
1445
  await this.replySafe(prev.rootId, truncate(toolTextLines(pending), 2000));
1227
1446
  }
1228
1447
  const state = {
@@ -1236,17 +1455,21 @@ export class DirectSessionManager {
1236
1455
  turn: fresh.turns + 1,
1237
1456
  phase: "running",
1238
1457
  toolCalls: 0,
1458
+ segmentToolCalls: 0,
1239
1459
  durationSec: 0,
1240
1460
  turnTokens: 0,
1241
- texts: [],
1242
- tools: [],
1461
+ events: [],
1462
+ segment: 1,
1243
1463
  };
1244
1464
  if (retryFromTurn !== undefined)
1245
1465
  state.retryFromTurn = retryFromTurn;
1466
+ if (autoMeta !== undefined)
1467
+ state.autoContinue = autoMeta;
1246
1468
  rt.turn = state;
1247
1469
  rt.turnUsedOnce = false;
1248
1470
  rt.turnStartedAt = 0;
1249
1471
  rt.flushedTools = 0;
1472
+ rt.toolPanels = [];
1250
1473
  rt.waitingApproval = false;
1251
1474
  rt.waitingSince = null;
1252
1475
  rt.fullDetail = [];
@@ -1255,6 +1478,7 @@ export class DirectSessionManager {
1255
1478
  const detailed = this.deps.config().feishu.direct.verbosity === "detailed";
1256
1479
  const replyCard = this.deps.feishu.replyCardInThread;
1257
1480
  rt.cardsAvailable = true;
1481
+ rt.lastCardError = null;
1258
1482
  if (!detailed || !replyCard) {
1259
1483
  rt.cardsAvailable = false;
1260
1484
  return;
@@ -1282,8 +1506,8 @@ export class DirectSessionManager {
1282
1506
  const updateCard = this.deps.feishu.updateCard;
1283
1507
  const cardId = rt.cardId;
1284
1508
  const turn = rt.turn;
1285
- const renderedTools = turn.tools.length;
1286
1509
  const sealed = { ...rt.turn, sealed: true };
1510
+ const renderedTools = rt.toolPanels.length;
1287
1511
  rt.cardId = null;
1288
1512
  if (!updateCard)
1289
1513
  return;
@@ -1325,13 +1549,19 @@ export class DirectSessionManager {
1325
1549
  error: toTaskingError(e).message,
1326
1550
  }));
1327
1551
  }
1328
- async flushTurnCard(rootId) {
1552
+ async flushTurnCard(rootId, wait = false) {
1329
1553
  const rt = this.runtimeFor(rootId);
1330
1554
  if (rt.turn === null)
1331
1555
  return;
1332
1556
  if (rt.flushInFlight) {
1333
1557
  rt.flushQueued = true;
1334
- return;
1558
+ if (!wait)
1559
+ return;
1560
+ for (let i = 0; i < 5 && rt.flushInFlight; i++) {
1561
+ await rt.flushPromise?.catch(() => { });
1562
+ }
1563
+ if (rt.turn === null)
1564
+ return;
1335
1565
  }
1336
1566
  rt.flushInFlight = true;
1337
1567
  const flight = this.flushTurnCardInner(rootId);
@@ -1380,13 +1610,32 @@ export class DirectSessionManager {
1380
1610
  }
1381
1611
  const updateCard = this.deps.feishu.updateCard;
1382
1612
  if (rt.cardsAvailable && rt.cardId !== null && updateCard) {
1383
- const renderedTools = turn.tools.length;
1613
+ turn.segmentToolCalls = countToolEvents(turn.events);
1614
+ let plannedCard = null;
1615
+ if (!cardFits(turn) && turn.events.length > 1) {
1616
+ const denseCard = buildTurnCard(turn);
1617
+ if (renderedCardFits(denseCard, turn)) {
1618
+ plannedCard = denseCard;
1619
+ }
1620
+ else {
1621
+ const split = await this.splitTurnCard(rt);
1622
+ if (split) {
1623
+ if (rt.cardsAvailable)
1624
+ return;
1625
+ await this.sendToolFallback(rootId, rt);
1626
+ return;
1627
+ }
1628
+ }
1629
+ }
1630
+ const renderedTools = rt.toolPanels.length;
1631
+ const renderedCard = plannedCard ?? buildTurnCard(turn);
1384
1632
  const applySuccess = () => {
1385
1633
  if (rt.turn === turn)
1386
1634
  rt.flushedTools = Math.max(rt.flushedTools, renderedTools);
1387
1635
  };
1388
1636
  try {
1389
- await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
1637
+ await updateCard.call(this.deps.feishu, rt.cardId, renderedCard);
1638
+ rt.lastCardError = null;
1390
1639
  applySuccess();
1391
1640
  return;
1392
1641
  }
@@ -1397,6 +1646,7 @@ export class DirectSessionManager {
1397
1646
  });
1398
1647
  if (!isRetryableCardError(e)) {
1399
1648
  rt.cardsAvailable = false;
1649
+ rt.lastCardError = "permanent";
1400
1650
  }
1401
1651
  else {
1402
1652
  const base = this.deps.cardRetryDelayMs ?? CARD_RETRY_DELAY_MS;
@@ -1404,16 +1654,18 @@ export class DirectSessionManager {
1404
1654
  await sleepUnrefed(base + jitter);
1405
1655
  if (rt.turn === turn && rt.cardId !== null) {
1406
1656
  try {
1407
- await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
1657
+ await updateCard.call(this.deps.feishu, rt.cardId, renderedCard);
1658
+ rt.lastCardError = null;
1408
1659
  applySuccess();
1409
1660
  return;
1410
1661
  }
1411
1662
  catch (retryError) {
1412
- this.deps.logger.warn("direct card update retry failed; falling back to text", {
1663
+ this.deps.logger.warn("direct card update retry failed; will retry on next flush", {
1413
1664
  root_id: rootId,
1414
1665
  error: toTaskingError(retryError).message,
1415
1666
  });
1416
- rt.cardsAvailable = false;
1667
+ rt.lastCardError = "retryable";
1668
+ return;
1417
1669
  }
1418
1670
  }
1419
1671
  }
@@ -1421,14 +1673,132 @@ export class DirectSessionManager {
1421
1673
  }
1422
1674
  if (rt.turn !== turn)
1423
1675
  return;
1676
+ await this.sendToolFallback(rootId, rt);
1677
+ }
1678
+ async sendToolFallback(rootId, rt) {
1424
1679
  if (this.deps.config().feishu.direct.verbosity !== "detailed")
1425
1680
  return;
1426
- const pending = turn.tools.slice(rt.flushedTools);
1427
- rt.flushedTools = turn.tools.length;
1681
+ const pending = rt.toolPanels.slice(rt.flushedTools);
1682
+ rt.flushedTools = rt.toolPanels.length;
1428
1683
  if (pending.length === 0)
1429
1684
  return;
1430
1685
  await this.replySafe(rootId, truncate(toolTextLines(pending), 2000));
1431
1686
  }
1687
+ async splitTurnCard(rt) {
1688
+ const turn = rt.turn;
1689
+ const updateCard = this.deps.feishu.updateCard;
1690
+ if (!turn || rt.cardId === null || !updateCard)
1691
+ return false;
1692
+ const all = turn.events;
1693
+ const suffixStart = findFullSuffixStart(turn);
1694
+ if (suffixStart <= 0 || suffixStart >= all.length)
1695
+ return false;
1696
+ const prefix = all.slice(0, suffixStart);
1697
+ const suffix = all.slice(suffixStart);
1698
+ turn.segmented = true;
1699
+ let lo = 1;
1700
+ let hi = prefix.length;
1701
+ let capacity = 1;
1702
+ while (lo <= hi) {
1703
+ const mid = Math.floor((lo + hi) / 2);
1704
+ const candidateState = { ...turn, events: prefix.slice(0, mid) };
1705
+ if (renderedCardFits(buildTurnCard(candidateState), candidateState)) {
1706
+ capacity = mid;
1707
+ lo = mid + 1;
1708
+ }
1709
+ else {
1710
+ hi = mid - 1;
1711
+ }
1712
+ }
1713
+ const chunkCount = Math.max(1, Math.ceil(prefix.length / capacity));
1714
+ const chunkSize = Math.ceil(prefix.length / chunkCount);
1715
+ const chunks = [];
1716
+ for (let i = 0; i < prefix.length; i += chunkSize) {
1717
+ chunks.push(prefix.slice(i, i + chunkSize));
1718
+ }
1719
+ if (chunks.length === 0)
1720
+ return false;
1721
+ const first = chunks[0] ?? [];
1722
+ const oldCardId = rt.cardId;
1723
+ const oldView = {
1724
+ ...turn,
1725
+ events: first,
1726
+ segmentToolCalls: countToolEvents(first),
1727
+ sealed: true,
1728
+ continued: true,
1729
+ };
1730
+ let renderedTools = 0;
1731
+ try {
1732
+ await updateCard.call(this.deps.feishu, oldCardId, buildTurnCard(oldView));
1733
+ }
1734
+ catch (e) {
1735
+ this.deps.logger.warn("direct segment seal failed", {
1736
+ root_id: turn.rootId,
1737
+ error: toTaskingError(e).message,
1738
+ });
1739
+ }
1740
+ renderedTools += countToolEvents(first);
1741
+ rt.cardId = null;
1742
+ let lastSegment = turn.segment ?? 1;
1743
+ let active = first;
1744
+ for (let i = 1; i < chunks.length; i++) {
1745
+ const chunk = chunks[i] ?? [];
1746
+ const segment = lastSegment + 1;
1747
+ const messageId = await this.replySegmentCard(turn, chunk, segment, true);
1748
+ if (messageId === null) {
1749
+ rt.cardsAvailable = false;
1750
+ break;
1751
+ }
1752
+ rt.cardId = messageId;
1753
+ lastSegment = segment;
1754
+ active = chunk;
1755
+ renderedTools += countToolEvents(chunk);
1756
+ }
1757
+ if (rt.cardsAvailable) {
1758
+ const segment = lastSegment + 1;
1759
+ const messageId = await this.replySegmentCard(turn, suffix, segment, false);
1760
+ if (messageId === null) {
1761
+ rt.cardsAvailable = false;
1762
+ }
1763
+ else {
1764
+ rt.cardId = messageId;
1765
+ lastSegment = segment;
1766
+ active = suffix;
1767
+ renderedTools += countToolEvents(suffix);
1768
+ }
1769
+ }
1770
+ turn.events = active;
1771
+ turn.segment = lastSegment;
1772
+ turn.segmentToolCalls = countToolEvents(active);
1773
+ rt.flushedTools = Math.max(rt.flushedTools, renderedTools);
1774
+ return true;
1775
+ }
1776
+ async replySegmentCard(turn, events, segment, history) {
1777
+ const replyCard = this.deps.feishu.replyCardInThread;
1778
+ if (!replyCard)
1779
+ return null;
1780
+ try {
1781
+ const created = await replyCard.call(this.deps.feishu, turn.rootId, buildTurnCard({
1782
+ ...turn,
1783
+ events,
1784
+ segment,
1785
+ segmentToolCalls: countToolEvents(events),
1786
+ ...(history ? { sealed: true, continued: true } : {}),
1787
+ }));
1788
+ this.deps.store.updateDirectSession(turn.rootId, { card_message_id: created.message_id });
1789
+ if (created.thread_id) {
1790
+ this.deps.store.updateDirectSession(turn.rootId, { thread_id: created.thread_id });
1791
+ }
1792
+ return created.message_id;
1793
+ }
1794
+ catch (e) {
1795
+ this.deps.logger.warn("direct segment card create failed; falling back to text", {
1796
+ root_id: turn.rootId,
1797
+ error: toTaskingError(e).message,
1798
+ });
1799
+ return null;
1800
+ }
1801
+ }
1432
1802
  accumulateTool(rt, evt) {
1433
1803
  const panel = { tool: evt.tool ?? "tool" };
1434
1804
  if (evt.title !== undefined)
@@ -1455,7 +1825,8 @@ export class DirectSessionManager {
1455
1825
  rt.fullDetailBytes -= fullDetailBytes(dropped);
1456
1826
  rt.fullDetailDropped++;
1457
1827
  }
1458
- rt.turn?.tools.push(panel);
1828
+ rt.toolPanels.push(panel);
1829
+ rt.turn?.events.push({ kind: "tool", tool: panel });
1459
1830
  }
1460
1831
  async sendCompletion(session, delivery) {
1461
1832
  const verbosity = this.deps.config().feishu.direct.verbosity;
@@ -1469,7 +1840,7 @@ export class DirectSessionManager {
1469
1840
  statsLine: delivery.statsLine,
1470
1841
  note: delivery.note,
1471
1842
  });
1472
- if (JSON.stringify(card).length <= CARD_BUDGET_BYTES) {
1843
+ if (cardPayloadBytes(card) <= CARD_BUDGET_BYTES) {
1473
1844
  try {
1474
1845
  await replyCard.call(this.deps.feishu, session.root_id, card);
1475
1846
  return;
@@ -1532,8 +1903,11 @@ export class DirectSessionManager {
1532
1903
  return;
1533
1904
  rt.turn.toolCalls = stats.toolCalls;
1534
1905
  rt.turn.turnTokens = stats.totalTokens;
1535
- if (dropFinalText)
1536
- rt.turn.finalized = true;
1906
+ if (dropFinalText) {
1907
+ const lastText = rt.turn.events.findLastIndex((event) => event.kind === "text");
1908
+ if (lastText >= 0)
1909
+ rt.turn.events.splice(lastText, 1);
1910
+ }
1537
1911
  await this.finalizeCardPhase(rootId, phase, durationSec);
1538
1912
  }
1539
1913
  beginInterrupt(session, rt) {
@@ -1570,7 +1944,19 @@ export class DirectSessionManager {
1570
1944
  rt.turn.phase = phase;
1571
1945
  if (durationSec !== undefined)
1572
1946
  rt.turn.durationSec = durationSec;
1573
- await this.flushTurnCard(rootId);
1947
+ await this.flushTurnCard(rootId, true);
1948
+ if (phase === "running" || rt.cardId === null)
1949
+ return;
1950
+ const base = this.deps.cardRetryDelayMs ?? CARD_RETRY_DELAY_MS;
1951
+ for (let attempt = 0; attempt < 2 && rt.lastCardError === "retryable"; attempt++) {
1952
+ await sleepUnrefed(base * (attempt + 1));
1953
+ rt.cardsAvailable = true;
1954
+ rt.lastCardError = null;
1955
+ await this.flushTurnCard(rootId, true);
1956
+ }
1957
+ if (rt.lastCardError !== null) {
1958
+ await this.replySafe(rootId, translate("本轮已结束(卡片更新失败)"));
1959
+ }
1574
1960
  }
1575
1961
  async acquireSlot() {
1576
1962
  const max = this.deps.config().feishu.direct.max_concurrent;
@@ -1588,7 +1974,7 @@ export class DirectSessionManager {
1588
1974
  }
1589
1975
  this.activeTurns = Math.max(0, this.activeTurns - 1);
1590
1976
  }
1591
- async executeTurn(session, prompt, rt) {
1977
+ async executeTurn(session, prompt, rt, auto = false) {
1592
1978
  const config = this.deps.config();
1593
1979
  const sessionId = session.session_id;
1594
1980
  const isFirstTurn = sessionId === null;
@@ -1618,7 +2004,9 @@ export class DirectSessionManager {
1618
2004
  message: truncate(prompt, 60),
1619
2005
  });
1620
2006
  this.deps.store.updateDirectSession(session.root_id, { status: "running" });
1621
- this.deps.store.updateDirectSession(session.root_id, { last_prompt: prompt });
2007
+ if (!auto) {
2008
+ this.deps.store.updateDirectSession(session.root_id, { last_prompt: prompt });
2009
+ }
1622
2010
  rt.stopRequested = false;
1623
2011
  rt.turnStartedAt = Date.now();
1624
2012
  const startedAt = rt.turnStartedAt;
@@ -1631,17 +2019,31 @@ export class DirectSessionManager {
1631
2019
  this.deps.store.addDirectSessionUsage(session.root_id, { input_tokens: 0, output_tokens: 0, total_tokens: 0 }, 1);
1632
2020
  const stats = {
1633
2021
  toolCalls: 0,
2022
+ fileMutations: 0,
1634
2023
  permissionRejections: 0,
1635
2024
  inputTokens: 0,
1636
2025
  outputTokens: 0,
1637
2026
  totalTokens: 0,
2027
+ textChars: 0,
1638
2028
  lastText: "",
1639
2029
  };
2030
+ const buildOutcome = (status, error) => ({
2031
+ status,
2032
+ error,
2033
+ toolCalls: stats.toolCalls,
2034
+ fileMutations: stats.fileMutations,
2035
+ outputTokens: stats.outputTokens,
2036
+ textChars: stats.textChars,
2037
+ lastText: stats.lastText,
2038
+ durationMs: Date.now() - startedAt,
2039
+ });
1640
2040
  const abort = new AbortController();
1641
2041
  rt.abort = abort;
1642
2042
  const onEvent = (evt) => {
1643
2043
  if (evt.type === "tool_use") {
1644
2044
  stats.toolCalls++;
2045
+ if (isFileMutationTool(evt.tool))
2046
+ stats.fileMutations++;
1645
2047
  if (evt.status === "error" &&
1646
2048
  typeof evt.error === "string" &&
1647
2049
  /permission/i.test(evt.error)) {
@@ -1658,8 +2060,8 @@ export class DirectSessionManager {
1658
2060
  }
1659
2061
  if (evt.type === "text" && typeof evt.text === "string" && evt.text.trim() !== "") {
1660
2062
  stats.lastText = evt.text;
1661
- if (rt.turn)
1662
- rt.turn.texts.push(evt.text);
2063
+ stats.textChars += evt.text.length;
2064
+ rt.turn?.events.push({ kind: "text", text: evt.text });
1663
2065
  this.scheduleFlush(session.root_id);
1664
2066
  }
1665
2067
  if (this.deps.activity) {
@@ -1723,20 +2125,27 @@ export class DirectSessionManager {
1723
2125
  rt.waitingApproval = waiting;
1724
2126
  rt.waitingSince = waiting ? Date.now() : null;
1725
2127
  },
2128
+ onAnchorLost: () => {
2129
+ this.deps.logger.warn("direct turn anchor lost; settling by session idle / baseline output", {
2130
+ root_id: session.root_id,
2131
+ session_id: sessionId ?? undefined,
2132
+ });
2133
+ },
1726
2134
  signal: abort.signal,
1727
2135
  });
1728
2136
  }
1729
2137
  catch (e) {
2138
+ const message = toTaskingError(e).message;
1730
2139
  rt.abort = null;
1731
2140
  rt.queue = [];
1732
2141
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1733
2142
  this.deps.logger.error("direct turn spawn failed", {
1734
2143
  root_id: session.root_id,
1735
- error: toTaskingError(e).message,
2144
+ error: message,
1736
2145
  });
1737
2146
  await this.finalizeTurnCard(session.root_id, "failed", stats, 0);
1738
- await this.replySafe(session.root_id, `⚠️ 本轮未能启动(${toTaskingError(e).message})。请重发消息重试。`);
1739
- return;
2147
+ await this.replySafe(session.root_id, `⚠️ 本轮未能启动(${message})。请重发消息重试。`);
2148
+ return buildOutcome("failed", message);
1740
2149
  }
1741
2150
  finally {
1742
2151
  rt.abort = null;
@@ -1746,8 +2155,9 @@ export class DirectSessionManager {
1746
2155
  }
1747
2156
  const durationSec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
1748
2157
  const fresh = this.deps.store.getDirectSession(session.root_id);
1749
- if (!fresh || fresh.status === "done" || fresh.status === "expired")
1750
- return;
2158
+ if (!fresh || fresh.status === "done" || fresh.status === "expired") {
2159
+ return buildOutcome("interrupted", "session ended");
2160
+ }
1751
2161
  rt.postureOpen = result.postureOpened;
1752
2162
  if (result.contextTokens !== undefined && result.contextTokens > rt.contextTokens) {
1753
2163
  rt.contextTokens = result.contextTokens;
@@ -1775,6 +2185,13 @@ export class DirectSessionManager {
1775
2185
  root_id: session.root_id,
1776
2186
  status: result.status,
1777
2187
  resolved_model: resolvedModelKey,
2188
+ error: result.error,
2189
+ duration_ms: Date.now() - startedAt,
2190
+ tools: stats.toolCalls,
2191
+ auto_continue: auto,
2192
+ settled_by: result.settledBy ?? null,
2193
+ anchor_seen: result.anchorSeen ?? null,
2194
+ prompt_message_id: result.promptMessageId ?? null,
1778
2195
  });
1779
2196
  const usage = result.usage;
1780
2197
  if (usage) {
@@ -1793,22 +2210,24 @@ export class DirectSessionManager {
1793
2210
  if (result.status === "interrupted" || rt.stopRequested) {
1794
2211
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1795
2212
  await this.finalizeTurnCard(session.root_id, "interrupted", stats, durationSec);
1796
- return;
2213
+ return buildOutcome("interrupted", result.error ?? "interrupted");
1797
2214
  }
1798
2215
  if (result.status === "timed_out") {
1799
2216
  const reason = result.error?.includes("inactivity_timeout")
1800
2217
  ? translate("无输出超时")
1801
- : translate("整体超时");
2218
+ : result.error?.includes("permission_timeout")
2219
+ ? translate("审批超时")
2220
+ : translate("整体超时");
1802
2221
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1803
2222
  await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec);
1804
2223
  await this.replySafe(session.root_id, `⚠️ 本轮${reason}被中止(${durationSec}s)。可用更小的任务描述重试。`);
1805
- return;
2224
+ return buildOutcome("timed_out", result.error ?? "turn_timeout");
1806
2225
  }
1807
2226
  if (result.status === "failed" || result.status === "error") {
1808
2227
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1809
2228
  await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec, true);
1810
2229
  await this.replySafe(session.root_id, `⚠️ 本轮未完成(${result.error ?? result.status},${durationSec}s)。${stats.lastText ? `\n\n${truncate(stats.lastText)}` : ""}`.trim());
1811
- return;
2230
+ return buildOutcome("failed", result.error ?? result.status);
1812
2231
  }
1813
2232
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1814
2233
  await this.finalizeTurnCard(session.root_id, "completed", stats, durationSec, true);
@@ -1829,6 +2248,7 @@ export class DirectSessionManager {
1829
2248
  statsLine: statsLine.trim(),
1830
2249
  note: rejectionNote.trim(),
1831
2250
  });
2251
+ return buildOutcome("succeeded", null);
1832
2252
  }
1833
2253
  dirConcurrencyLimit() {
1834
2254
  return Math.max(1, Math.floor(this.deps.config().feishu.direct.max_concurrent_turns_per_dir));
@@ -1976,10 +2396,171 @@ export class DirectSessionManager {
1976
2396
  await this.replySafe(session.root_id, `已将会话名改为「${trimmed}」。`);
1977
2397
  }
1978
2398
  async executeNew(session) {
2399
+ this.runtimeFor(session.root_id).autoContinue = null;
1979
2400
  this.deps.store.updateDirectSession(session.root_id, { session_id: null, last_prompt: null });
1980
2401
  await this.cleanupSession(session);
1981
2402
  await this.replySafe(session.root_id, "🆕 已开启新会话:上下文已清空(话题、目录与名称不变),旧 opencode 会话已删除。");
1982
2403
  }
2404
+ effectiveLoopPrompt(session) {
2405
+ return session.loop_prompt ?? this.deps.config().feishu.direct.auto_continue.prompt;
2406
+ }
2407
+ loopPauseLabel(reason) {
2408
+ if (reason === "question")
2409
+ return translate("模型在提问");
2410
+ if (reason === "repetition")
2411
+ return translate("回复重复且无文件改动");
2412
+ if (reason === "low_work")
2413
+ return translate("连续低产出");
2414
+ return "";
2415
+ }
2416
+ loopStatusCard(session, rt) {
2417
+ const config = this.deps.config();
2418
+ const state = rt.autoContinue;
2419
+ const streak = config.feishu.direct.auto_continue.no_progress_streak;
2420
+ const budget = this.autoBudget(rt);
2421
+ const used = state?.used ?? 0;
2422
+ const prompt = this.effectiveLoopPrompt(session);
2423
+ const budgetSource = rt.autoContinueBudget === null ? translate("配置默认") : translate("会话设置");
2424
+ const promptSource = session.loop_prompt === null ? translate("配置来源") : translate("会话来源");
2425
+ const paused = state?.pausedReason === null || state?.pausedReason === undefined
2426
+ ? ""
2427
+ : ` (${this.loopPauseLabel(state.pausedReason)})`;
2428
+ const mode = state === null
2429
+ ? translate("关闭状态")
2430
+ : state.pausedReason !== null
2431
+ ? `${translate("暂停状态")}${paused}`
2432
+ : translate("开启状态");
2433
+ const lines = [
2434
+ `${translate("自动续跑状态")}: ${mode}`,
2435
+ `${translate("自动续跑预算")}: ${used}/${budget} (${translate("剩余轮次")} ${Math.max(0, budget - used)}, ${budgetSource})`,
2436
+ `${translate("下一次自动轮")}: ${Math.min(budget, used + 1)}/${budget}`,
2437
+ `${translate("低产出计数")}: ${state?.lowWorkRun ?? 0}/${streak} · ${translate("重复计数")}: ${state?.repeatRun ?? 0}/${streak}`,
2438
+ `${translate("续跑提示词")} (${promptSource}): ${truncate(prompt, 200)}`,
2439
+ `${translate("停止规则")}: ${translate("连续")} ${streak} ${translate("轮低产出 / 重复;提问暂停;预算/失败/审批超时硬停")}`,
2440
+ ...(state?.pausedReason === null || state?.pausedReason === undefined
2441
+ ? []
2442
+ : [`${translate("上次暂停")}: ${this.loopPauseLabel(state.pausedReason)}`]),
2443
+ "",
2444
+ translate("用法:/loop on [N]|/loop start [N]|/loop off|/loop prompt [文本|reset]"),
2445
+ ];
2446
+ return buildInfoCard({ title: "🔄 自动续跑", lines });
2447
+ }
2448
+ async executeLoop(session, text) {
2449
+ const parsed = parseLoop(text);
2450
+ if (parsed === null)
2451
+ return;
2452
+ const rt = this.runtimeFor(session.root_id);
2453
+ if (parsed.kind === "invalid") {
2454
+ await this.replyInfoCard(session, buildInfoCard({
2455
+ title: "⚠️ /loop 用法",
2456
+ lines: [parsed.reason],
2457
+ }), parsed.reason);
2458
+ return;
2459
+ }
2460
+ if (parsed.kind === "status") {
2461
+ const fallback = [
2462
+ translate("自动续跑状态见下"),
2463
+ translate("用法:/loop on [N]|/loop start [N]|/loop off|/loop prompt [文本|reset]"),
2464
+ ].join("\n");
2465
+ await this.replyInfoCard(session, this.loopStatusCard(session, rt), fallback);
2466
+ return;
2467
+ }
2468
+ if (parsed.kind === "off") {
2469
+ rt.autoContinue = null;
2470
+ const textOut = translate("🔄 自动续跑已关闭。当前轮会跑完;预算偏好保留,重新开启用 /loop on。");
2471
+ await this.replyInfoCard(session, buildInfoCard({ title: "🔄 自动续跑已关闭", lines: [textOut] }), textOut);
2472
+ return;
2473
+ }
2474
+ if (parsed.kind === "on") {
2475
+ if (parsed.budget !== null)
2476
+ rt.autoContinueBudget = parsed.budget;
2477
+ if (rt.autoContinue === null) {
2478
+ rt.autoContinue = freshAutoContinueState();
2479
+ }
2480
+ else {
2481
+ const keepUsed = parsed.budget === null ? rt.autoContinue.used : 0;
2482
+ rt.autoContinue = { ...resetAutoContinueRuns(rt.autoContinue), used: keepUsed };
2483
+ }
2484
+ const budget = this.autoBudget(rt);
2485
+ const lines = [
2486
+ `${translate("已开启,最多 ")}${budget}${translate(" 轮 Auto-continue。")}`,
2487
+ translate("下一条任务开始后生效;/loop start 可立即开干。"),
2488
+ `${translate("续跑提示词")}: ${truncate(this.effectiveLoopPrompt(session), 200)}`,
2489
+ translate("关闭:/loop off|中断:/stop"),
2490
+ ];
2491
+ await this.replyInfoCard(session, buildInfoCard({ title: "🔄 自动续跑已开启", lines }), lines.join("\n"));
2492
+ return;
2493
+ }
2494
+ if (parsed.kind === "start") {
2495
+ const hasTask = session.turns > 0 || session.last_prompt !== null || rt.turnInFlight || rt.queue.length > 0;
2496
+ if (!hasTask) {
2497
+ const msg = translate("还没有任务。请先发送任务消息,再 /loop start。");
2498
+ await this.replyInfoCard(session, buildInfoCard({ title: "⚠️ 无法开始", lines: [msg] }), msg);
2499
+ return;
2500
+ }
2501
+ if (parsed.budget !== null)
2502
+ rt.autoContinueBudget = parsed.budget;
2503
+ if (rt.autoContinue === null) {
2504
+ rt.autoContinue = freshAutoContinueState();
2505
+ }
2506
+ else {
2507
+ rt.autoContinue = {
2508
+ ...resetAutoContinueRuns(rt.autoContinue),
2509
+ used: parsed.budget === null ? rt.autoContinue.used : 0,
2510
+ };
2511
+ }
2512
+ const budget = this.autoBudget(rt);
2513
+ const lines = [
2514
+ `${translate("已开始,最多 ")}${budget}${translate(" 轮 Auto-continue。")}`,
2515
+ `${translate("续跑提示词")}: ${truncate(this.effectiveLoopPrompt(session), 200)}`,
2516
+ translate("中断:/stop|关闭:/loop off"),
2517
+ ];
2518
+ await this.replyInfoCard(session, buildInfoCard({ title: "🔄 自动续跑已开始", lines }), lines.join("\n"));
2519
+ if (rt.turnInFlight) {
2520
+ const queued = translate("当前轮结束后立即开始。");
2521
+ await this.replySafe(session.root_id, queued);
2522
+ return;
2523
+ }
2524
+ void this.runTurnLoop(session.root_id, this.effectiveLoopPrompt(session), undefined, true).catch((e) => this.deps.logger.error("direct auto-continue start failed", {
2525
+ root_id: session.root_id,
2526
+ error: toTaskingError(e).message,
2527
+ }));
2528
+ return;
2529
+ }
2530
+ if (parsed.kind === "prompt") {
2531
+ if (parsed.reset) {
2532
+ this.deps.store.updateDirectSession(session.root_id, { loop_prompt: null });
2533
+ const lines = [
2534
+ translate("已恢复配置默认提示词。"),
2535
+ `${translate("当前提示词")}: ${truncate(this.deps.config().feishu.direct.auto_continue.prompt, 200)}`,
2536
+ ];
2537
+ await this.replyInfoCard(session, buildInfoCard({ title: "✍️ 续跑提示词已恢复默认", lines }), lines.join("\n"));
2538
+ return;
2539
+ }
2540
+ if (parsed.text === null) {
2541
+ const prompt = this.effectiveLoopPrompt(session);
2542
+ const source = session.loop_prompt === null ? translate("配置来源") : translate("会话来源");
2543
+ const lines = [
2544
+ `${translate("当前提示词")} (${source}): ${truncate(prompt, 200)}`,
2545
+ translate("设置:/loop prompt <文本>|恢复默认:/loop prompt reset"),
2546
+ ];
2547
+ await this.replyInfoCard(session, buildInfoCard({ title: "✍️ 续跑提示词", lines }), lines.join("\n"));
2548
+ return;
2549
+ }
2550
+ const prompt = parsed.text.trim();
2551
+ if (prompt.length > AUTO_CONTINUE_PROMPT_MAX_CHARS) {
2552
+ const msg = translate("续跑提示词必须是 1–2000 字。");
2553
+ await this.replyInfoCard(session, buildInfoCard({ title: "⚠️ 无法设置", lines: [msg] }), msg);
2554
+ return;
2555
+ }
2556
+ this.deps.store.updateDirectSession(session.root_id, { loop_prompt: prompt });
2557
+ const lines = [
2558
+ translate("已更新,下一轮生效。"),
2559
+ `${translate("当前提示词")} (${translate("会话来源")}): ${truncate(prompt, 200)}`,
2560
+ ];
2561
+ await this.replyInfoCard(session, buildInfoCard({ title: "✍️ 续跑提示词已更新", lines }), lines.join("\n"));
2562
+ }
2563
+ }
1983
2564
  async executeAuto(session, text) {
1984
2565
  const rt = this.runtimeFor(session.root_id);
1985
2566
  const arg = text.slice("/auto".length).trim().toLowerCase();
@@ -2114,6 +2695,7 @@ export class DirectSessionManager {
2114
2695
  }
2115
2696
  async executeStop(session, operator) {
2116
2697
  const rt = this.runtimeFor(session.root_id);
2698
+ rt.autoContinue = null;
2117
2699
  const queued = rt.queue.length;
2118
2700
  rt.queue = [];
2119
2701
  if (rt.turnInFlight && rt.abort) {
@@ -2185,8 +2767,39 @@ function isRetryableCardError(e) {
2185
2767
  return true;
2186
2768
  if (e.category !== "feishu_api_status")
2187
2769
  return false;
2188
- const status = e.details?.status;
2189
- return status === 429 || (typeof status === "number" && status >= 500);
2770
+ const details = e.details;
2771
+ const status = details?.status;
2772
+ if (status === 429 || (typeof status === "number" && status >= 500))
2773
+ return true;
2774
+ const body = typeof details?.body === "string" ? details.body : "";
2775
+ try {
2776
+ const parsed = JSON.parse(body);
2777
+ return parsed.code === 230020 || parsed.code === 200810;
2778
+ }
2779
+ catch {
2780
+ const code = /"code"\s*:\s*(\d+)/.exec(body)?.[1];
2781
+ return code === "230020" || code === "200810";
2782
+ }
2783
+ }
2784
+ function countToolEvents(events) {
2785
+ return events.filter((event) => event.kind === "tool").length;
2786
+ }
2787
+ function findFullSuffixStart(state) {
2788
+ const total = state.events.length;
2789
+ if (total === 0)
2790
+ return 0;
2791
+ if (!cardFits({ ...state, events: state.events.slice(total - 1) }))
2792
+ return total - 1;
2793
+ let lo = 0;
2794
+ let hi = total - 1;
2795
+ while (lo < hi) {
2796
+ const mid = Math.floor((lo + hi) / 2);
2797
+ if (cardFits({ ...state, events: state.events.slice(mid) }))
2798
+ hi = mid;
2799
+ else
2800
+ lo = mid + 1;
2801
+ }
2802
+ return lo;
2190
2803
  }
2191
2804
  function toolTextLines(tools) {
2192
2805
  return tools
@@ -2267,7 +2880,7 @@ function renderChatHelp(scope) {
2267
2880
  "直连会话用法:",
2268
2881
  "/chat <项目名|绝对路径> <消息> 在指定目录创建 opencode 会话",
2269
2882
  "/chat 列出可用项目",
2270
- "会话创建后:在本话题内直接回复即续聊;/stop 中断当前任务;/done 结束会话",
2883
+ "会话创建后:在本话题内直接回复即续聊;/loop 自动续跑;/stop 中断当前任务;/done 结束会话",
2271
2884
  ].join("\n");
2272
2885
  }
2273
2886
  return [
@@ -2276,6 +2889,8 @@ function renderChatHelp(scope) {
2276
2889
  "直接发图片/文件 → 下载到工作区并把路径交给 agent",
2277
2890
  "/collect → 进入多消息收集模式(发完用 /send 提交为一轮,/cancel 丢弃)",
2278
2891
  "/auto [on|once|off] → 查看/切换本会话权限姿态(下一轮生效)",
2892
+ "/loop on [N] → 为下一条任务开启自动续跑;/loop start 立即继续;/loop off 关闭",
2893
+ "/loop prompt <文本> → 设置续跑提示词(/loop prompt reset 恢复默认)",
2279
2894
  "/name <文本> → 给本会话改名(卡片头部与 TUI 显示)",
2280
2895
  "/agent <name> → 切换本会话 agent(/agent reset 恢复)",
2281
2896
  "/model <name> → 切换本会话 model(/model reset 恢复)",