@tothemax/tasking 0.7.0 → 0.8.0

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 (113) hide show
  1. package/README.md +3 -3
  2. package/assets/workflows/WORKFLOW.code-mr.en.md.example +32 -3
  3. package/assets/workflows/WORKFLOW.code-mr.md.example +28 -3
  4. package/assets/workflows/WORKFLOW.feishu-direct.en.md.example +32 -3
  5. package/assets/workflows/WORKFLOW.feishu-direct.md.example +28 -3
  6. package/assets/workflows/WORKFLOW.grill-openspec.en.md.example +32 -3
  7. package/assets/workflows/WORKFLOW.grill-openspec.md.example +28 -3
  8. package/assets/workflows/WORKFLOW.minimal.en.md.example +32 -3
  9. package/assets/workflows/WORKFLOW.minimal.md.example +28 -3
  10. package/dist/adapters/feishu/source.d.ts.map +1 -1
  11. package/dist/adapters/feishu/source.js +4 -4
  12. package/dist/adapters/feishu/source.js.map +1 -1
  13. package/dist/bridge/binding-store.d.ts +2 -0
  14. package/dist/bridge/binding-store.d.ts.map +1 -1
  15. package/dist/bridge/binding-store.js +8 -0
  16. package/dist/bridge/binding-store.js.map +1 -1
  17. package/dist/bridge/commands.d.ts +19 -0
  18. package/dist/bridge/commands.d.ts.map +1 -1
  19. package/dist/bridge/commands.js +40 -1
  20. package/dist/bridge/commands.js.map +1 -1
  21. package/dist/bridge/comment-bridge.d.ts.map +1 -1
  22. package/dist/bridge/comment-bridge.js +9 -1
  23. package/dist/bridge/comment-bridge.js.map +1 -1
  24. package/dist/cli/doctor.d.ts +2 -0
  25. package/dist/cli/doctor.d.ts.map +1 -1
  26. package/dist/cli/doctor.js +52 -1
  27. package/dist/cli/doctor.js.map +1 -1
  28. package/dist/cli/help.d.ts.map +1 -1
  29. package/dist/cli/help.js +5 -1
  30. package/dist/cli/help.js.map +1 -1
  31. package/dist/cli/index.d.ts.map +1 -1
  32. package/dist/cli/index.js +5 -0
  33. package/dist/cli/index.js.map +1 -1
  34. package/dist/cli/init.d.ts +4 -1
  35. package/dist/cli/init.d.ts.map +1 -1
  36. package/dist/cli/init.js +31 -8
  37. package/dist/cli/init.js.map +1 -1
  38. package/dist/cli/model-picker.d.ts +6 -0
  39. package/dist/cli/model-picker.d.ts.map +1 -0
  40. package/dist/cli/model-picker.js +108 -0
  41. package/dist/cli/model-picker.js.map +1 -0
  42. package/dist/cli/tui-helpers.d.ts.map +1 -1
  43. package/dist/cli/tui-helpers.js +10 -0
  44. package/dist/cli/tui-helpers.js.map +1 -1
  45. package/dist/config/config-types.d.ts +16 -0
  46. package/dist/config/config-types.d.ts.map +1 -1
  47. package/dist/config/config-types.js +9 -0
  48. package/dist/config/config-types.js.map +1 -1
  49. package/dist/config/manager.d.ts +1 -0
  50. package/dist/config/manager.d.ts.map +1 -1
  51. package/dist/config/manager.js +14 -12
  52. package/dist/config/manager.js.map +1 -1
  53. package/dist/config/resolver.d.ts.map +1 -1
  54. package/dist/config/resolver.js +46 -2
  55. package/dist/config/resolver.js.map +1 -1
  56. package/dist/direct/auto-continue.d.ts +64 -0
  57. package/dist/direct/auto-continue.d.ts.map +1 -0
  58. package/dist/direct/auto-continue.js +142 -0
  59. package/dist/direct/auto-continue.js.map +1 -0
  60. package/dist/direct/card.d.ts +29 -3
  61. package/dist/direct/card.d.ts.map +1 -1
  62. package/dist/direct/card.js +150 -52
  63. package/dist/direct/card.js.map +1 -1
  64. package/dist/direct/driver.d.ts +1 -0
  65. package/dist/direct/driver.d.ts.map +1 -1
  66. package/dist/direct/driver.js +1 -0
  67. package/dist/direct/driver.js.map +1 -1
  68. package/dist/direct/manager.d.ts +20 -3
  69. package/dist/direct/manager.d.ts.map +1 -1
  70. package/dist/direct/manager.js +735 -62
  71. package/dist/direct/manager.js.map +1 -1
  72. package/dist/driver/opencode-models.d.ts +22 -0
  73. package/dist/driver/opencode-models.d.ts.map +1 -0
  74. package/dist/driver/opencode-models.js +77 -0
  75. package/dist/driver/opencode-models.js.map +1 -0
  76. package/dist/driver/session-ops.d.ts +9 -0
  77. package/dist/driver/session-ops.d.ts.map +1 -1
  78. package/dist/driver/session-ops.js +23 -0
  79. package/dist/driver/session-ops.js.map +1 -1
  80. package/dist/driver/turn-driver.d.ts +9 -1
  81. package/dist/driver/turn-driver.d.ts.map +1 -1
  82. package/dist/driver/turn-driver.js +160 -22
  83. package/dist/driver/turn-driver.js.map +1 -1
  84. package/dist/observability/http-dashboard.d.ts +2 -1
  85. package/dist/observability/http-dashboard.d.ts.map +1 -1
  86. package/dist/observability/http-dashboard.js +4 -3
  87. package/dist/observability/http-dashboard.js.map +1 -1
  88. package/dist/observability/snapshot.d.ts +2 -1
  89. package/dist/observability/snapshot.d.ts.map +1 -1
  90. package/dist/observability/snapshot.js +2 -0
  91. package/dist/observability/snapshot.js.map +1 -1
  92. package/dist/observability/terminal-dashboard.d.ts +2 -1
  93. package/dist/observability/terminal-dashboard.d.ts.map +1 -1
  94. package/dist/observability/terminal-dashboard.js +2 -0
  95. package/dist/observability/terminal-dashboard.js.map +1 -1
  96. package/dist/shared/card-payload.d.ts +3 -0
  97. package/dist/shared/card-payload.d.ts.map +1 -0
  98. package/dist/shared/card-payload.js +8 -0
  99. package/dist/shared/card-payload.js.map +1 -0
  100. package/dist/shared/types.d.ts +7 -0
  101. package/dist/shared/types.d.ts.map +1 -1
  102. package/dist/shared/types.js.map +1 -1
  103. package/dist/translate/dict.d.ts.map +1 -1
  104. package/dist/translate/dict.js +164 -6
  105. package/dist/translate/dict.js.map +1 -1
  106. package/dist/worker/runner.d.ts.map +1 -1
  107. package/dist/worker/runner.js +32 -2
  108. package/dist/worker/runner.js.map +1 -1
  109. package/dist/workspace/manager.d.ts +2 -1
  110. package/dist/workspace/manager.d.ts.map +1 -1
  111. package/dist/workspace/manager.js +14 -1
  112. package/dist/workspace/manager.js.map +1 -1
  113. 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
- import { ALLOW_ALL_RULES, replyPermission, setSessionPermissions } from "../driver/session-ops.js";
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;
@@ -48,6 +50,7 @@ export class DirectSessionManager {
48
50
  dirSlots = new Map();
49
51
  running = false;
50
52
  halted = false;
53
+ sameDirWarned = false;
51
54
  ttlTimer = null;
52
55
  activeTurns = 0;
53
56
  waiters = [];
@@ -74,9 +77,25 @@ export class DirectSessionManager {
74
77
  return;
75
78
  this.running = true;
76
79
  this.halted = false;
80
+ this.syncSameDirConcurrencyWarning();
77
81
  this.ttlTimer = setInterval(() => this.expireIdle(), TTL_SWEEP_INTERVAL_MS);
78
82
  this.ttlTimer.unref?.();
79
83
  }
84
+ syncSameDirConcurrencyWarning() {
85
+ const config = this.deps.config();
86
+ const limit = this.dirConcurrencyLimit();
87
+ if (limit <= 1) {
88
+ this.sameDirWarned = false;
89
+ return;
90
+ }
91
+ if (this.sameDirWarned)
92
+ return;
93
+ this.sameDirWarned = true;
94
+ const autoNote = config.feishu.direct.auto_approve
95
+ ? " auto_approve is on: concurrent turns can write files without prompting."
96
+ : "";
97
+ this.deps.logger.warn(`same-directory turn concurrency enabled; concurrent turns share one working tree and may race on files or git.${autoNote}`, { max_concurrent_turns_per_dir: limit });
98
+ }
80
99
  stop() {
81
100
  this.running = false;
82
101
  this.halted = true;
@@ -170,6 +189,12 @@ export class DirectSessionManager {
170
189
  if (turn !== null && turn !== currentTurn) {
171
190
  return { toast: { type: "info", content: "该轮已结束" } };
172
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
+ }
173
198
  if (name === "stop") {
174
199
  if (!rt.turnInFlight || !rt.abort) {
175
200
  return { toast: { type: "info", content: "该轮已结束" } };
@@ -487,6 +512,8 @@ export class DirectSessionManager {
487
512
  "**命令**",
488
513
  "`/collect` → 收集多条消息;`/send` 提交为一轮;`/cancel` 丢弃",
489
514
  "`/auto [on|once|off|reset]` → 本会话权限姿态(下一轮生效)",
515
+ "`/loop on [N]` → 为下一条任务开启自动续跑;`/loop start` 立即继续;`/loop off` 关闭",
516
+ "`/loop prompt <文本>` → 设置续跑提示词(`reset` 恢复默认)",
490
517
  "`/name <文本>` → 会话改名(卡片头部与 TUI)",
491
518
  "`/agent <name>` · `/model <name>` → 切换 agent/model(`reset` 恢复)",
492
519
  "`/new` → 清空上下文开启新会话",
@@ -685,6 +712,7 @@ export class DirectSessionManager {
685
712
  }
686
713
  async enqueueRetry(rootId, prompt, fromTurn) {
687
714
  const rt = this.runtimeFor(rootId);
715
+ this.resumeAutoContinueForUserTurn(rt);
688
716
  if (rt.turnInFlight) {
689
717
  rt.queue.push(prompt);
690
718
  return;
@@ -698,6 +726,10 @@ export class DirectSessionManager {
698
726
  const config = this.deps.config();
699
727
  if (!isDirectEnabled(config))
700
728
  return false;
729
+ if (parseLoop(m.text) !== null) {
730
+ await this.deps.feishu.replyFlat(m.message_id, "请在 /chat 话题内使用 /loop。");
731
+ return true;
732
+ }
701
733
  const parsed = parseChat(m.text);
702
734
  if (!parsed)
703
735
  return false;
@@ -838,8 +870,12 @@ export class DirectSessionManager {
838
870
  await this.executeModel(session, trimmed);
839
871
  return true;
840
872
  }
873
+ if (trimmed === "/loop" || trimmed.startsWith("/loop ")) {
874
+ await this.executeLoop(session, trimmed);
875
+ return true;
876
+ }
841
877
  if (trimmed.startsWith("/")) {
842
- 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");
843
879
  return true;
844
880
  }
845
881
  const attachments = m.attachments ?? [];
@@ -910,10 +946,10 @@ export class DirectSessionManager {
910
946
  turn: session.turns,
911
947
  phase,
912
948
  toolCalls: 0,
949
+ segmentToolCalls: 0,
913
950
  durationSec: 0,
914
951
  turnTokens: 0,
915
- texts: note === "" ? [] : [note],
916
- tools: [],
952
+ events: note === "" ? [] : [{ kind: "text", text: note }],
917
953
  };
918
954
  if (hideFullDetail)
919
955
  state.hideFullDetail = true;
@@ -930,6 +966,18 @@ export class DirectSessionManager {
930
966
  });
931
967
  }
932
968
  }
969
+ listDirectDirs() {
970
+ const limit = this.dirConcurrencyLimit();
971
+ return [...this.dirSlots.entries()]
972
+ .filter(([, slot]) => slot.active > 0 || slot.waiters.length > 0)
973
+ .map(([path, slot]) => ({
974
+ path,
975
+ active: slot.active,
976
+ limit,
977
+ waiters: slot.waiters.length,
978
+ }))
979
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
980
+ }
933
981
  listActive() {
934
982
  const sessions = this.deps.store.listActiveDirectSessions();
935
983
  const config = this.deps.config();
@@ -1094,11 +1142,14 @@ export class DirectSessionManager {
1094
1142
  turn: null,
1095
1143
  turnStartedAt: 0,
1096
1144
  flushedTools: 0,
1145
+ toolPanels: [],
1097
1146
  autoOnce: false,
1098
1147
  turnUsedOnce: false,
1099
1148
  postureOpen: false,
1100
1149
  appliedAgent: null,
1101
1150
  appliedModel: null,
1151
+ lastResolvedModel: undefined,
1152
+ lastResolvedModelSession: undefined,
1102
1153
  contextTokens: 0,
1103
1154
  waitingApproval: false,
1104
1155
  waitingSince: null,
@@ -1113,13 +1164,22 @@ export class DirectSessionManager {
1113
1164
  flushInFlight: false,
1114
1165
  flushQueued: false,
1115
1166
  flushPromise: null,
1167
+ lastCardError: null,
1168
+ autoContinue: null,
1169
+ autoContinueBudget: null,
1116
1170
  };
1117
1171
  this.runtime.set(rootId, rt);
1118
1172
  }
1119
1173
  return rt;
1120
1174
  }
1175
+ resumeAutoContinueForUserTurn(rt) {
1176
+ if (rt.autoContinue === null)
1177
+ return;
1178
+ rt.autoContinue = resetAutoContinueRuns(rt.autoContinue);
1179
+ }
1121
1180
  enqueueTurn(rootId, message) {
1122
1181
  const rt = this.runtimeFor(rootId);
1182
+ this.resumeAutoContinueForUserTurn(rt);
1123
1183
  if (rt.turnInFlight) {
1124
1184
  rt.queue.push(message);
1125
1185
  if (this.cardsLive(rt)) {
@@ -1136,33 +1196,129 @@ export class DirectSessionManager {
1136
1196
  error: toTaskingError(e).message,
1137
1197
  }));
1138
1198
  }
1139
- 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) {
1140
1280
  const rt = this.runtimeFor(rootId);
1141
1281
  rt.turnInFlight = true;
1142
1282
  rt.stopRequested = false;
1143
1283
  try {
1144
1284
  let prompt = firstMessage;
1145
1285
  let retriedFrom = retryFromTurn;
1286
+ let auto = startAuto;
1146
1287
  for (;;) {
1147
1288
  const session = this.deps.store.getDirectSession(rootId);
1148
- if (!session || session.status === "done" || session.status === "expired")
1289
+ if (!session || session.status === "done" || session.status === "expired") {
1290
+ rt.autoContinue = null;
1149
1291
  break;
1292
+ }
1150
1293
  if (this.halted || rt.stopRequested)
1151
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
+ }
1152
1307
  await this.sealTurnCard(rt);
1153
1308
  const max = this.deps.config().feishu.direct.max_concurrent;
1154
- const busy = this.activeTurns >= max || this.dirSlotFor(session.path).busy;
1155
- await this.startTurnCard(session, rt, busy, retriedFrom);
1309
+ const busy = this.activeTurns >= max || this.dirActiveFor(session.path) >= this.dirConcurrencyLimit();
1310
+ await this.startTurnCard(session, rt, busy, retriedFrom, autoMeta);
1156
1311
  if (busy && !this.cardsLive(rt)) {
1157
1312
  await this.replySafe(rootId, "⏳ 目标目录或并发额度正被占用,排队等待中,空闲后自动开始…");
1158
1313
  }
1159
1314
  await this.acquireDir(session.path);
1315
+ let outcome;
1160
1316
  try {
1161
1317
  await this.acquireSlot();
1162
1318
  try {
1163
1319
  if (this.halted || rt.stopRequested)
1164
1320
  break;
1165
- await this.executeTurn(session, prompt, rt);
1321
+ outcome = await this.executeTurn(session, prompt, rt, auto);
1166
1322
  }
1167
1323
  finally {
1168
1324
  this.releaseSlot();
@@ -1171,27 +1327,121 @@ export class DirectSessionManager {
1171
1327
  finally {
1172
1328
  this.releaseDir(session.path);
1173
1329
  }
1174
- if (rt.queue.length === 0)
1330
+ if (this.halted || rt.stopRequested)
1175
1331
  break;
1176
- prompt = rt.queue.join("\n---\n");
1177
- rt.queue = [];
1178
- retriedFrom = undefined;
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)
1387
+ break;
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;
1179
1424
  }
1180
1425
  }
1181
1426
  finally {
1182
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
+ }
1183
1433
  }
1184
1434
  }
1185
1435
  cardsLive(rt) {
1186
1436
  return rt.cardsAvailable && rt.cardId !== null && rt.turn !== null;
1187
1437
  }
1188
- async startTurnCard(session, rt, busy, retryFromTurn) {
1438
+ async startTurnCard(session, rt, busy, retryFromTurn, autoMeta) {
1189
1439
  const fresh = this.deps.store.getDirectSession(session.root_id) ?? session;
1190
1440
  await rt.flushPromise?.catch(() => { });
1191
1441
  const prev = rt.turn;
1192
- if (prev !== null && prev.tools.length > rt.flushedTools) {
1193
- const pending = prev.tools.slice(rt.flushedTools);
1194
- 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;
1195
1445
  await this.replySafe(prev.rootId, truncate(toolTextLines(pending), 2000));
1196
1446
  }
1197
1447
  const state = {
@@ -1205,17 +1455,21 @@ export class DirectSessionManager {
1205
1455
  turn: fresh.turns + 1,
1206
1456
  phase: "running",
1207
1457
  toolCalls: 0,
1458
+ segmentToolCalls: 0,
1208
1459
  durationSec: 0,
1209
1460
  turnTokens: 0,
1210
- texts: [],
1211
- tools: [],
1461
+ events: [],
1462
+ segment: 1,
1212
1463
  };
1213
1464
  if (retryFromTurn !== undefined)
1214
1465
  state.retryFromTurn = retryFromTurn;
1466
+ if (autoMeta !== undefined)
1467
+ state.autoContinue = autoMeta;
1215
1468
  rt.turn = state;
1216
1469
  rt.turnUsedOnce = false;
1217
1470
  rt.turnStartedAt = 0;
1218
1471
  rt.flushedTools = 0;
1472
+ rt.toolPanels = [];
1219
1473
  rt.waitingApproval = false;
1220
1474
  rt.waitingSince = null;
1221
1475
  rt.fullDetail = [];
@@ -1224,6 +1478,7 @@ export class DirectSessionManager {
1224
1478
  const detailed = this.deps.config().feishu.direct.verbosity === "detailed";
1225
1479
  const replyCard = this.deps.feishu.replyCardInThread;
1226
1480
  rt.cardsAvailable = true;
1481
+ rt.lastCardError = null;
1227
1482
  if (!detailed || !replyCard) {
1228
1483
  rt.cardsAvailable = false;
1229
1484
  return;
@@ -1251,8 +1506,8 @@ export class DirectSessionManager {
1251
1506
  const updateCard = this.deps.feishu.updateCard;
1252
1507
  const cardId = rt.cardId;
1253
1508
  const turn = rt.turn;
1254
- const renderedTools = turn.tools.length;
1255
1509
  const sealed = { ...rt.turn, sealed: true };
1510
+ const renderedTools = rt.toolPanels.length;
1256
1511
  rt.cardId = null;
1257
1512
  if (!updateCard)
1258
1513
  return;
@@ -1294,13 +1549,19 @@ export class DirectSessionManager {
1294
1549
  error: toTaskingError(e).message,
1295
1550
  }));
1296
1551
  }
1297
- async flushTurnCard(rootId) {
1552
+ async flushTurnCard(rootId, wait = false) {
1298
1553
  const rt = this.runtimeFor(rootId);
1299
1554
  if (rt.turn === null)
1300
1555
  return;
1301
1556
  if (rt.flushInFlight) {
1302
1557
  rt.flushQueued = true;
1303
- 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;
1304
1565
  }
1305
1566
  rt.flushInFlight = true;
1306
1567
  const flight = this.flushTurnCardInner(rootId);
@@ -1349,13 +1610,32 @@ export class DirectSessionManager {
1349
1610
  }
1350
1611
  const updateCard = this.deps.feishu.updateCard;
1351
1612
  if (rt.cardsAvailable && rt.cardId !== null && updateCard) {
1352
- 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);
1353
1632
  const applySuccess = () => {
1354
1633
  if (rt.turn === turn)
1355
1634
  rt.flushedTools = Math.max(rt.flushedTools, renderedTools);
1356
1635
  };
1357
1636
  try {
1358
- await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
1637
+ await updateCard.call(this.deps.feishu, rt.cardId, renderedCard);
1638
+ rt.lastCardError = null;
1359
1639
  applySuccess();
1360
1640
  return;
1361
1641
  }
@@ -1366,6 +1646,7 @@ export class DirectSessionManager {
1366
1646
  });
1367
1647
  if (!isRetryableCardError(e)) {
1368
1648
  rt.cardsAvailable = false;
1649
+ rt.lastCardError = "permanent";
1369
1650
  }
1370
1651
  else {
1371
1652
  const base = this.deps.cardRetryDelayMs ?? CARD_RETRY_DELAY_MS;
@@ -1373,16 +1654,18 @@ export class DirectSessionManager {
1373
1654
  await sleepUnrefed(base + jitter);
1374
1655
  if (rt.turn === turn && rt.cardId !== null) {
1375
1656
  try {
1376
- await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
1657
+ await updateCard.call(this.deps.feishu, rt.cardId, renderedCard);
1658
+ rt.lastCardError = null;
1377
1659
  applySuccess();
1378
1660
  return;
1379
1661
  }
1380
1662
  catch (retryError) {
1381
- 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", {
1382
1664
  root_id: rootId,
1383
1665
  error: toTaskingError(retryError).message,
1384
1666
  });
1385
- rt.cardsAvailable = false;
1667
+ rt.lastCardError = "retryable";
1668
+ return;
1386
1669
  }
1387
1670
  }
1388
1671
  }
@@ -1390,14 +1673,132 @@ export class DirectSessionManager {
1390
1673
  }
1391
1674
  if (rt.turn !== turn)
1392
1675
  return;
1676
+ await this.sendToolFallback(rootId, rt);
1677
+ }
1678
+ async sendToolFallback(rootId, rt) {
1393
1679
  if (this.deps.config().feishu.direct.verbosity !== "detailed")
1394
1680
  return;
1395
- const pending = turn.tools.slice(rt.flushedTools);
1396
- rt.flushedTools = turn.tools.length;
1681
+ const pending = rt.toolPanels.slice(rt.flushedTools);
1682
+ rt.flushedTools = rt.toolPanels.length;
1397
1683
  if (pending.length === 0)
1398
1684
  return;
1399
1685
  await this.replySafe(rootId, truncate(toolTextLines(pending), 2000));
1400
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
+ }
1401
1802
  accumulateTool(rt, evt) {
1402
1803
  const panel = { tool: evt.tool ?? "tool" };
1403
1804
  if (evt.title !== undefined)
@@ -1424,7 +1825,8 @@ export class DirectSessionManager {
1424
1825
  rt.fullDetailBytes -= fullDetailBytes(dropped);
1425
1826
  rt.fullDetailDropped++;
1426
1827
  }
1427
- rt.turn?.tools.push(panel);
1828
+ rt.toolPanels.push(panel);
1829
+ rt.turn?.events.push({ kind: "tool", tool: panel });
1428
1830
  }
1429
1831
  async sendCompletion(session, delivery) {
1430
1832
  const verbosity = this.deps.config().feishu.direct.verbosity;
@@ -1438,7 +1840,7 @@ export class DirectSessionManager {
1438
1840
  statsLine: delivery.statsLine,
1439
1841
  note: delivery.note,
1440
1842
  });
1441
- if (JSON.stringify(card).length <= CARD_BUDGET_BYTES) {
1843
+ if (cardPayloadBytes(card) <= CARD_BUDGET_BYTES) {
1442
1844
  try {
1443
1845
  await replyCard.call(this.deps.feishu, session.root_id, card);
1444
1846
  return;
@@ -1501,8 +1903,11 @@ export class DirectSessionManager {
1501
1903
  return;
1502
1904
  rt.turn.toolCalls = stats.toolCalls;
1503
1905
  rt.turn.turnTokens = stats.totalTokens;
1504
- if (dropFinalText)
1505
- 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
+ }
1506
1911
  await this.finalizeCardPhase(rootId, phase, durationSec);
1507
1912
  }
1508
1913
  beginInterrupt(session, rt) {
@@ -1539,7 +1944,19 @@ export class DirectSessionManager {
1539
1944
  rt.turn.phase = phase;
1540
1945
  if (durationSec !== undefined)
1541
1946
  rt.turn.durationSec = durationSec;
1542
- 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
+ }
1543
1960
  }
1544
1961
  async acquireSlot() {
1545
1962
  const max = this.deps.config().feishu.direct.max_concurrent;
@@ -1557,7 +1974,7 @@ export class DirectSessionManager {
1557
1974
  }
1558
1975
  this.activeTurns = Math.max(0, this.activeTurns - 1);
1559
1976
  }
1560
- async executeTurn(session, prompt, rt) {
1977
+ async executeTurn(session, prompt, rt, auto = false) {
1561
1978
  const config = this.deps.config();
1562
1979
  const sessionId = session.session_id;
1563
1980
  const isFirstTurn = sessionId === null;
@@ -1577,6 +1994,7 @@ export class DirectSessionManager {
1577
1994
  switch_agent: switchAgent,
1578
1995
  switch_model: switchModel,
1579
1996
  poll_interval_ms: config.opencode.poll_interval_ms,
1997
+ max_concurrent_turns_per_dir: this.dirConcurrencyLimit(),
1580
1998
  tasking_version: readTaskingVersion(),
1581
1999
  command: describeApiCommand({
1582
2000
  command: config.opencode.command,
@@ -1586,7 +2004,9 @@ export class DirectSessionManager {
1586
2004
  message: truncate(prompt, 60),
1587
2005
  });
1588
2006
  this.deps.store.updateDirectSession(session.root_id, { status: "running" });
1589
- 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
+ }
1590
2010
  rt.stopRequested = false;
1591
2011
  rt.turnStartedAt = Date.now();
1592
2012
  const startedAt = rt.turnStartedAt;
@@ -1599,17 +2019,31 @@ export class DirectSessionManager {
1599
2019
  this.deps.store.addDirectSessionUsage(session.root_id, { input_tokens: 0, output_tokens: 0, total_tokens: 0 }, 1);
1600
2020
  const stats = {
1601
2021
  toolCalls: 0,
2022
+ fileMutations: 0,
1602
2023
  permissionRejections: 0,
1603
2024
  inputTokens: 0,
1604
2025
  outputTokens: 0,
1605
2026
  totalTokens: 0,
2027
+ textChars: 0,
1606
2028
  lastText: "",
1607
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
+ });
1608
2040
  const abort = new AbortController();
1609
2041
  rt.abort = abort;
1610
2042
  const onEvent = (evt) => {
1611
2043
  if (evt.type === "tool_use") {
1612
2044
  stats.toolCalls++;
2045
+ if (isFileMutationTool(evt.tool))
2046
+ stats.fileMutations++;
1613
2047
  if (evt.status === "error" &&
1614
2048
  typeof evt.error === "string" &&
1615
2049
  /permission/i.test(evt.error)) {
@@ -1626,8 +2060,8 @@ export class DirectSessionManager {
1626
2060
  }
1627
2061
  if (evt.type === "text" && typeof evt.text === "string" && evt.text.trim() !== "") {
1628
2062
  stats.lastText = evt.text;
1629
- if (rt.turn)
1630
- rt.turn.texts.push(evt.text);
2063
+ stats.textChars += evt.text.length;
2064
+ rt.turn?.events.push({ kind: "text", text: evt.text });
1631
2065
  this.scheduleFlush(session.root_id);
1632
2066
  }
1633
2067
  if (this.deps.activity) {
@@ -1691,20 +2125,27 @@ export class DirectSessionManager {
1691
2125
  rt.waitingApproval = waiting;
1692
2126
  rt.waitingSince = waiting ? Date.now() : null;
1693
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
+ },
1694
2134
  signal: abort.signal,
1695
2135
  });
1696
2136
  }
1697
2137
  catch (e) {
2138
+ const message = toTaskingError(e).message;
1698
2139
  rt.abort = null;
1699
2140
  rt.queue = [];
1700
2141
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1701
2142
  this.deps.logger.error("direct turn spawn failed", {
1702
2143
  root_id: session.root_id,
1703
- error: toTaskingError(e).message,
2144
+ error: message,
1704
2145
  });
1705
2146
  await this.finalizeTurnCard(session.root_id, "failed", stats, 0);
1706
- await this.replySafe(session.root_id, `⚠️ 本轮未能启动(${toTaskingError(e).message})。请重发消息重试。`);
1707
- return;
2147
+ await this.replySafe(session.root_id, `⚠️ 本轮未能启动(${message})。请重发消息重试。`);
2148
+ return buildOutcome("failed", message);
1708
2149
  }
1709
2150
  finally {
1710
2151
  rt.abort = null;
@@ -1714,8 +2155,9 @@ export class DirectSessionManager {
1714
2155
  }
1715
2156
  const durationSec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
1716
2157
  const fresh = this.deps.store.getDirectSession(session.root_id);
1717
- if (!fresh || fresh.status === "done" || fresh.status === "expired")
1718
- return;
2158
+ if (!fresh || fresh.status === "done" || fresh.status === "expired") {
2159
+ return buildOutcome("interrupted", "session ended");
2160
+ }
1719
2161
  rt.postureOpen = result.postureOpened;
1720
2162
  if (result.contextTokens !== undefined && result.contextTokens > rt.contextTokens) {
1721
2163
  rt.contextTokens = result.contextTokens;
@@ -1726,6 +2168,31 @@ export class DirectSessionManager {
1726
2168
  if (isFirstTurn || result.modelSwitched !== false) {
1727
2169
  rt.appliedModel = effectiveModel;
1728
2170
  }
2171
+ const resolvedModelKey = result.model ? formatResolvedModel(result.model) : null;
2172
+ if (resolvedModelKey !== null) {
2173
+ if (rt.lastResolvedModelSession === result.sessionId &&
2174
+ rt.lastResolvedModel !== undefined &&
2175
+ rt.lastResolvedModel !== resolvedModelKey) {
2176
+ this.deps.logger.warn(modelDriftMessage(rt.lastResolvedModel, resolvedModelKey), {
2177
+ root_id: session.root_id,
2178
+ session_id: result.sessionId,
2179
+ });
2180
+ }
2181
+ rt.lastResolvedModel = resolvedModelKey;
2182
+ rt.lastResolvedModelSession = result.sessionId;
2183
+ }
2184
+ this.deps.logger.info("direct turn finished", {
2185
+ root_id: session.root_id,
2186
+ status: result.status,
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,
2195
+ });
1729
2196
  const usage = result.usage;
1730
2197
  if (usage) {
1731
2198
  stats.inputTokens = usage.input_tokens;
@@ -1743,22 +2210,24 @@ export class DirectSessionManager {
1743
2210
  if (result.status === "interrupted" || rt.stopRequested) {
1744
2211
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1745
2212
  await this.finalizeTurnCard(session.root_id, "interrupted", stats, durationSec);
1746
- return;
2213
+ return buildOutcome("interrupted", result.error ?? "interrupted");
1747
2214
  }
1748
2215
  if (result.status === "timed_out") {
1749
2216
  const reason = result.error?.includes("inactivity_timeout")
1750
2217
  ? translate("无输出超时")
1751
- : translate("整体超时");
2218
+ : result.error?.includes("permission_timeout")
2219
+ ? translate("审批超时")
2220
+ : translate("整体超时");
1752
2221
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1753
2222
  await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec);
1754
2223
  await this.replySafe(session.root_id, `⚠️ 本轮${reason}被中止(${durationSec}s)。可用更小的任务描述重试。`);
1755
- return;
2224
+ return buildOutcome("timed_out", result.error ?? "turn_timeout");
1756
2225
  }
1757
2226
  if (result.status === "failed" || result.status === "error") {
1758
2227
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1759
2228
  await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec, true);
1760
2229
  await this.replySafe(session.root_id, `⚠️ 本轮未完成(${result.error ?? result.status},${durationSec}s)。${stats.lastText ? `\n\n${truncate(stats.lastText)}` : ""}`.trim());
1761
- return;
2230
+ return buildOutcome("failed", result.error ?? result.status);
1762
2231
  }
1763
2232
  this.deps.store.markDirectSessionStatus(session.root_id, "idle");
1764
2233
  await this.finalizeTurnCard(session.root_id, "completed", stats, durationSec, true);
@@ -1779,31 +2248,40 @@ export class DirectSessionManager {
1779
2248
  statsLine: statsLine.trim(),
1780
2249
  note: rejectionNote.trim(),
1781
2250
  });
2251
+ return buildOutcome("succeeded", null);
2252
+ }
2253
+ dirConcurrencyLimit() {
2254
+ return Math.max(1, Math.floor(this.deps.config().feishu.direct.max_concurrent_turns_per_dir));
2255
+ }
2256
+ dirActiveFor(dir) {
2257
+ return this.dirSlots.get(dir)?.active ?? 0;
1782
2258
  }
1783
- dirSlotFor(dir) {
2259
+ ensureDirSlot(dir) {
1784
2260
  let s = this.dirSlots.get(dir);
1785
2261
  if (!s) {
1786
- s = { busy: false, waiters: [] };
2262
+ s = { active: 0, waiters: [] };
1787
2263
  this.dirSlots.set(dir, s);
1788
2264
  }
1789
2265
  return s;
1790
2266
  }
1791
2267
  async acquireDir(dir) {
1792
- const s = this.dirSlotFor(dir);
1793
- if (!s.busy) {
1794
- s.busy = true;
2268
+ const s = this.ensureDirSlot(dir);
2269
+ if (s.active < this.dirConcurrencyLimit()) {
2270
+ s.active++;
1795
2271
  return;
1796
2272
  }
1797
2273
  await new Promise((resolve) => s.waiters.push(resolve));
1798
2274
  }
1799
2275
  releaseDir(dir) {
1800
- const s = this.dirSlotFor(dir);
1801
- const next = s.waiters.shift();
1802
- if (next) {
1803
- next();
2276
+ const s = this.ensureDirSlot(dir);
2277
+ const limit = this.dirConcurrencyLimit();
2278
+ if (s.waiters.length > 0 && s.active > 0 && s.active <= limit) {
2279
+ s.waiters.shift()?.();
1804
2280
  return;
1805
2281
  }
1806
- s.busy = false;
2282
+ s.active = Math.max(0, s.active - 1);
2283
+ if (s.active === 0 && s.waiters.length === 0)
2284
+ this.dirSlots.delete(dir);
1807
2285
  }
1808
2286
  async composePromptWithAttachments(session, m, text) {
1809
2287
  const attachments = m.attachments ?? [];
@@ -1918,10 +2396,171 @@ export class DirectSessionManager {
1918
2396
  await this.replySafe(session.root_id, `已将会话名改为「${trimmed}」。`);
1919
2397
  }
1920
2398
  async executeNew(session) {
2399
+ this.runtimeFor(session.root_id).autoContinue = null;
1921
2400
  this.deps.store.updateDirectSession(session.root_id, { session_id: null, last_prompt: null });
1922
2401
  await this.cleanupSession(session);
1923
2402
  await this.replySafe(session.root_id, "🆕 已开启新会话:上下文已清空(话题、目录与名称不变),旧 opencode 会话已删除。");
1924
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
+ }
1925
2564
  async executeAuto(session, text) {
1926
2565
  const rt = this.runtimeFor(session.root_id);
1927
2566
  const arg = text.slice("/auto".length).trim().toLowerCase();
@@ -2056,6 +2695,7 @@ export class DirectSessionManager {
2056
2695
  }
2057
2696
  async executeStop(session, operator) {
2058
2697
  const rt = this.runtimeFor(session.root_id);
2698
+ rt.autoContinue = null;
2059
2699
  const queued = rt.queue.length;
2060
2700
  rt.queue = [];
2061
2701
  if (rt.turnInFlight && rt.abort) {
@@ -2127,8 +2767,39 @@ function isRetryableCardError(e) {
2127
2767
  return true;
2128
2768
  if (e.category !== "feishu_api_status")
2129
2769
  return false;
2130
- const status = e.details?.status;
2131
- 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;
2132
2803
  }
2133
2804
  function toolTextLines(tools) {
2134
2805
  return tools
@@ -2209,7 +2880,7 @@ function renderChatHelp(scope) {
2209
2880
  "直连会话用法:",
2210
2881
  "/chat <项目名|绝对路径> <消息> 在指定目录创建 opencode 会话",
2211
2882
  "/chat 列出可用项目",
2212
- "会话创建后:在本话题内直接回复即续聊;/stop 中断当前任务;/done 结束会话",
2883
+ "会话创建后:在本话题内直接回复即续聊;/loop 自动续跑;/stop 中断当前任务;/done 结束会话",
2213
2884
  ].join("\n");
2214
2885
  }
2215
2886
  return [
@@ -2218,6 +2889,8 @@ function renderChatHelp(scope) {
2218
2889
  "直接发图片/文件 → 下载到工作区并把路径交给 agent",
2219
2890
  "/collect → 进入多消息收集模式(发完用 /send 提交为一轮,/cancel 丢弃)",
2220
2891
  "/auto [on|once|off] → 查看/切换本会话权限姿态(下一轮生效)",
2892
+ "/loop on [N] → 为下一条任务开启自动续跑;/loop start 立即继续;/loop off 关闭",
2893
+ "/loop prompt <文本> → 设置续跑提示词(/loop prompt reset 恢复默认)",
2221
2894
  "/name <文本> → 给本会话改名(卡片头部与 TUI 显示)",
2222
2895
  "/agent <name> → 切换本会话 agent(/agent reset 恢复)",
2223
2896
  "/model <name> → 切换本会话 model(/model reset 恢复)",