@teamclaws/teamclaw 2026.8.0 → 2026.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 (54) hide show
  1. package/dist/api.js +1 -0
  2. package/dist/index.js +325 -0
  3. package/dist/src/config.js +381 -0
  4. package/dist/src/controller/controller-capacity.js +14 -0
  5. package/dist/src/controller/controller-service.js +393 -0
  6. package/dist/src/controller/controller-tools.js +582 -0
  7. package/dist/src/controller/delivery-report.js +458 -0
  8. package/dist/src/controller/github-auth.js +564 -0
  9. package/dist/src/controller/http-server.js +6032 -0
  10. package/dist/src/controller/kickoff-orchestrator.js +220 -0
  11. package/dist/src/controller/managed-gateway-process.js +286 -0
  12. package/dist/src/controller/message-router.js +38 -0
  13. package/dist/src/controller/orchestration-manifest.js +173 -0
  14. package/dist/src/controller/preview-manager.js +586 -0
  15. package/dist/src/controller/prompt-injector.js +187 -0
  16. package/dist/src/controller/role-inference.js +35 -0
  17. package/dist/src/controller/task-router.js +67 -0
  18. package/dist/src/controller/tunnel-manager.js +548 -0
  19. package/dist/src/controller/websocket.js +42 -0
  20. package/dist/src/controller/worker-provisioning.js +1648 -0
  21. package/dist/src/discovery.js +86 -0
  22. package/dist/src/git-collaboration.js +694 -0
  23. package/dist/src/identity.js +131 -0
  24. package/dist/src/install-defaults.js +1 -0
  25. package/dist/src/interaction-contracts.js +531 -0
  26. package/dist/src/networking.js +91 -0
  27. package/dist/src/openclaw-workspace.js +903 -0
  28. package/dist/src/prompt-policy.js +373 -0
  29. package/dist/src/protocol.js +58 -0
  30. package/dist/src/roles.js +349 -0
  31. package/dist/src/state.js +183 -0
  32. package/dist/src/task-executor.js +1033 -0
  33. package/dist/src/teamauto/github-client.js +192 -0
  34. package/dist/src/teamauto/norms.js +85 -0
  35. package/dist/src/teamauto/repo-sync.js +201 -0
  36. package/dist/src/teamauto/scanner.js +179 -0
  37. package/dist/src/teamauto/schedule.js +123 -0
  38. package/dist/src/teamauto/scheduler.js +688 -0
  39. package/dist/src/teamauto/store.js +133 -0
  40. package/dist/src/types.js +243 -0
  41. package/dist/src/ui/app.js +4292 -0
  42. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  43. package/dist/src/ui/github-login.html +296 -0
  44. package/dist/src/ui/index.html +414 -0
  45. package/dist/src/ui/style.css +2611 -0
  46. package/dist/src/worker/http-handler.js +146 -0
  47. package/dist/src/worker/message-queue.js +24 -0
  48. package/dist/src/worker/prompt-injector.js +42 -0
  49. package/dist/src/worker/skill-installer.js +253 -0
  50. package/dist/src/worker/tools.js +541 -0
  51. package/dist/src/worker/worker-service.js +234 -0
  52. package/dist/src/workspace-browser.js +269 -0
  53. package/openclaw.plugin.json +1 -1
  54. package/package.json +1 -1
@@ -0,0 +1,1033 @@
1
+ import { buildDeliverableMetadataPolicy, buildResultContractGuidance, buildTaskExecutionRules, buildVerificationPolicy, buildWorkerMemoryContractRules, } from "./prompt-policy.js";
2
+ import { buildTeamClawProjectWorkspacePath, resolveTeamClawWorkspaceDir, resolveTeamClawProjectsDir, } from "./openclaw-workspace.js";
3
+ import { getRole } from "./roles.js";
4
+ const TEAMCLAW_ROLE_IDS_TEXT = [
5
+ "pm", "architect", "developer", "qa",
6
+ "release-engineer", "infra-engineer", "devops", "security-engineer",
7
+ "designer", "marketing", "data-engineer",
8
+ ];
9
+ const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
10
+ /** Checkpoint heartbeat cadence (resume support). */
11
+ const CHECKPOINT_EMIT_INTERVAL_MS = 15_000;
12
+ const SESSION_PROGRESS_MESSAGE_LIMIT = 200;
13
+ const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
14
+ const RUN_WAIT_SLICE_MS = 30_000;
15
+ const RATE_LIMIT_STALL_PROBE_MS = 5 * 60 * 1000;
16
+ const RATE_LIMIT_PROBE_TIMEOUT_MS = 60_000;
17
+ const BACKGROUND_WORK_PROBE_MS = 60_000;
18
+ const BACKGROUND_WORK_PROBE_TIMEOUT_MS = 60_000;
19
+ const INACTIVITY_PROBE_TIMEOUT_MS = 60_000;
20
+ const CHILD_SESSION_PROGRESS_POLL_INTERVAL_MS = 5_000;
21
+ const RATE_LIMIT_WAITING_SENTINEL = "TEAMCLAW_STILL_WAITING";
22
+ const TOOL_CALL_BLOCK_TYPES = new Set(["tool_use", "toolcall", "tool_call"]);
23
+ const TOOL_RESULT_BLOCK_TYPES = new Set(["tool_result", "tool_result_error"]);
24
+ export function createRoleTaskExecutor(deps) {
25
+ const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
26
+ const roleDef = getRole(role);
27
+ const roleSystemPrompt = roleDef
28
+ ? roleDef.systemPrompt
29
+ : `You are a ${role} in a virtual software team. Complete the assigned task.`;
30
+ return async (taskDescription, assignment) => {
31
+ const taskId = assignment.taskId;
32
+ const sessionKey = getSessionKey(assignment);
33
+ const idempotencyKey = getIdempotencyKey?.(assignment);
34
+ const taskMessage = buildTaskMessage(taskDescription, taskId, roleDef?.label ?? role, {
35
+ inlineContract: true,
36
+ projectDir: assignment.projectDir,
37
+ teamContext: assignment.teamContext,
38
+ });
39
+ const workspaceDir = resolveTeamClawWorkspaceDir();
40
+ logger.info(`TeamClaw: executing task ${taskId} as ${role} via subagent`);
41
+ function buildSubagentRunOptions(options) {
42
+ // OpenClaw 2026.10+ renamed the subagent working-directory override from
43
+ // `workspaceDir` to `cwd`. Pass both so the run lands in the project
44
+ // workspace on legacy and current hosts (each host ignores the key it
45
+ // does not know).
46
+ const enrichedOptions = {
47
+ ...options,
48
+ workspaceDir,
49
+ cwd: options.cwd ?? workspaceDir,
50
+ };
51
+ // Per-role model override ("provider/model"): takes precedence over the
52
+ // teamclaw agent entry model for this role's subagent runs.
53
+ const roleModel = deps.config?.roleModelOverrides?.[role];
54
+ if (roleModel) {
55
+ const slashIndex = roleModel.indexOf("/");
56
+ if (slashIndex > 0) {
57
+ enrichedOptions.provider = roleModel.slice(0, slashIndex);
58
+ enrichedOptions.model = roleModel.slice(slashIndex + 1);
59
+ }
60
+ else {
61
+ enrichedOptions.model = roleModel;
62
+ }
63
+ }
64
+ return enrichedOptions;
65
+ }
66
+ async function emitExecutionEvent(event) {
67
+ if (!reportExecutionEvent) {
68
+ return;
69
+ }
70
+ try {
71
+ await Promise.resolve(reportExecutionEvent(taskId, {
72
+ role,
73
+ source: event.source ?? "worker",
74
+ ...event,
75
+ }));
76
+ }
77
+ catch (err) {
78
+ logger.warn(`TeamClaw: failed to report execution event for task ${taskId}: ${String(err)}`);
79
+ }
80
+ }
81
+ try {
82
+ // Checkpoint heartbeat state for resume support.
83
+ let lastCheckpointAt = 0;
84
+ const runResult = await runtime.subagent.run(buildSubagentRunOptions({
85
+ sessionKey,
86
+ message: taskMessage,
87
+ extraSystemPrompt: roleSystemPrompt,
88
+ idempotencyKey,
89
+ }));
90
+ logger.info(`TeamClaw: subagent run started for task ${taskId}, runId=${runResult.runId}`);
91
+ await emitExecutionEvent({
92
+ type: "lifecycle",
93
+ phase: "run_started",
94
+ source: "subagent",
95
+ status: "running",
96
+ runId: runResult.runId,
97
+ sessionKey,
98
+ message: `Subagent run started (${runResult.runId})`,
99
+ });
100
+ const progressSnapshot = {
101
+ fingerprints: [],
102
+ childSessionKeys: [],
103
+ childFingerprints: new Map(),
104
+ lastChildPollAt: 0,
105
+ lastAssistantMessage: "",
106
+ latestMessages: [],
107
+ lastActivityAt: Date.now(),
108
+ };
109
+ const rateLimitState = {
110
+ active: false,
111
+ probeCount: 0,
112
+ };
113
+ const inactivityState = {
114
+ active: false,
115
+ nextProbeAt: Date.now() + taskTimeoutMs,
116
+ probeCount: 0,
117
+ };
118
+ const noteObservedActivity = () => {
119
+ const now = Date.now();
120
+ progressSnapshot.lastActivityAt = now;
121
+ inactivityState.active = false;
122
+ inactivityState.visibleAt = undefined;
123
+ inactivityState.nextProbeAt = now + taskTimeoutMs;
124
+ };
125
+ const backgroundWaitState = {
126
+ active: false,
127
+ probeCount: 0,
128
+ };
129
+ const markRateLimitWaiting = async () => {
130
+ if (rateLimitState.active) {
131
+ return;
132
+ }
133
+ const now = Date.now();
134
+ rateLimitState.active = true;
135
+ rateLimitState.visibleAt = now;
136
+ rateLimitState.nextProbeAt = now + RATE_LIMIT_STALL_PROBE_MS;
137
+ await emitExecutionEvent({
138
+ type: "progress",
139
+ phase: "model_rate_limit_waiting",
140
+ source: "worker",
141
+ status: "running",
142
+ runId: runResult.runId,
143
+ sessionKey,
144
+ message: "Model rate limit reached. OpenClaw is retrying upstream; TeamClaw will keep waiting for the task to continue.",
145
+ });
146
+ };
147
+ const clearRateLimitWaiting = () => {
148
+ rateLimitState.active = false;
149
+ rateLimitState.visibleAt = undefined;
150
+ rateLimitState.nextProbeAt = undefined;
151
+ };
152
+ const markBackgroundWorkWaiting = async () => {
153
+ if (backgroundWaitState.active) {
154
+ return;
155
+ }
156
+ const now = Date.now();
157
+ backgroundWaitState.active = true;
158
+ backgroundWaitState.visibleAt = now;
159
+ backgroundWaitState.nextProbeAt = now + BACKGROUND_WORK_PROBE_MS;
160
+ await emitExecutionEvent({
161
+ type: "progress",
162
+ phase: "background_work_waiting",
163
+ source: "worker",
164
+ status: "running",
165
+ runId: runResult.runId,
166
+ sessionKey,
167
+ message: "The worker ended its last turn while background work was still running. TeamClaw will keep checking until the real final deliverable is ready.",
168
+ });
169
+ };
170
+ const clearBackgroundWorkWaiting = () => {
171
+ backgroundWaitState.active = false;
172
+ backgroundWaitState.visibleAt = undefined;
173
+ backgroundWaitState.nextProbeAt = undefined;
174
+ };
175
+ const syncSessionProgress = async () => {
176
+ const sessionMessages = await runtime.subagent.getSessionMessages({
177
+ sessionKey,
178
+ limit: SESSION_PROGRESS_MESSAGE_LIMIT,
179
+ });
180
+ progressSnapshot.latestMessages = Array.isArray(sessionMessages.messages) ? sessionMessages.messages : [];
181
+ const entries = buildSessionProgressEntries(progressSnapshot.latestMessages, taskMessage);
182
+ const newEntries = getNewSessionProgressEntries(entries, progressSnapshot.fingerprints);
183
+ progressSnapshot.fingerprints = entries.map((entry) => entry.fingerprint);
184
+ if (newEntries.length > 0) {
185
+ noteObservedActivity();
186
+ }
187
+ progressSnapshot.childSessionKeys = mergeChildSessionKeys(progressSnapshot.childSessionKeys, collectChildSessionKeys(progressSnapshot.latestMessages));
188
+ for (const entry of newEntries) {
189
+ if (entry.isRateLimit) {
190
+ await markRateLimitWaiting();
191
+ continue;
192
+ }
193
+ if (rateLimitState.active && isStillWaitingResponse(entry.message)) {
194
+ continue;
195
+ }
196
+ if (rateLimitState.active && isInternalRetryPrompt(entry.message, entry.stream)) {
197
+ continue;
198
+ }
199
+ if (rateLimitState.active) {
200
+ clearRateLimitWaiting();
201
+ }
202
+ if (entry.stream === "assistant") {
203
+ progressSnapshot.lastAssistantMessage = entry.message;
204
+ // Checkpoint heartbeat: persist the latest assistant turn so an
205
+ // interrupted execution resumes with fresh context (max once per
206
+ // CHECKPOINT_EMIT_INTERVAL_MS to bound controller write load).
207
+ if (reportCheckpoint && Date.now() - lastCheckpointAt >= CHECKPOINT_EMIT_INTERVAL_MS) {
208
+ lastCheckpointAt = Date.now();
209
+ void Promise.resolve(reportCheckpoint(taskId, {
210
+ lastAssistantMessage: entry.message.slice(0, 8000),
211
+ sessionKey,
212
+ })).catch(() => { });
213
+ }
214
+ }
215
+ await emitExecutionEvent({
216
+ type: "progress",
217
+ phase: entry.phase,
218
+ source: "subagent",
219
+ stream: entry.stream,
220
+ runId: runResult.runId,
221
+ sessionKey,
222
+ message: entry.message,
223
+ });
224
+ }
225
+ if (Date.now() - progressSnapshot.lastChildPollAt >= CHILD_SESSION_PROGRESS_POLL_INTERVAL_MS) {
226
+ progressSnapshot.lastChildPollAt = Date.now();
227
+ const childRateLimitDetected = await syncChildSessionRateLimits(runtime, progressSnapshot);
228
+ if (childRateLimitDetected) {
229
+ await markRateLimitWaiting();
230
+ }
231
+ }
232
+ };
233
+ const extractSessionAssistantTurn = async () => {
234
+ let turn = extractLastAssistantTurn(progressSnapshot.latestMessages);
235
+ if (!turn.text && !turn.backgroundPending) {
236
+ const sessionMessages = await runtime.subagent.getSessionMessages({
237
+ sessionKey,
238
+ limit: 100,
239
+ });
240
+ progressSnapshot.latestMessages = Array.isArray(sessionMessages.messages) ? sessionMessages.messages : [];
241
+ turn = extractLastAssistantTurn(sessionMessages.messages);
242
+ }
243
+ return turn;
244
+ };
245
+ const probeRateLimitedTaskCompletion = async () => {
246
+ rateLimitState.probeCount += 1;
247
+ const now = Date.now();
248
+ rateLimitState.visibleAt = now;
249
+ rateLimitState.nextProbeAt = now + RATE_LIMIT_STALL_PROBE_MS;
250
+ await emitExecutionEvent({
251
+ type: "progress",
252
+ phase: "model_rate_limit_probe",
253
+ source: "worker",
254
+ status: "running",
255
+ runId: runResult.runId,
256
+ sessionKey,
257
+ message: `Model rate limit has delayed task progress for over ${formatDuration(RATE_LIMIT_STALL_PROBE_MS)}. Re-checking whether the current task has already completed.`,
258
+ });
259
+ const probeRun = await runtime.subagent.run(buildSubagentRunOptions({
260
+ sessionKey,
261
+ message: buildRateLimitProbeMessage(taskId, roleDef?.label ?? role),
262
+ extraSystemPrompt: roleSystemPrompt,
263
+ idempotencyKey: `${idempotencyKey ?? `teamclaw-${taskId}`}:rate-limit-probe:${rateLimitState.probeCount}`,
264
+ }));
265
+ const probeWait = await runtime.subagent.waitForRun({
266
+ runId: probeRun.runId,
267
+ timeoutMs: RATE_LIMIT_PROBE_TIMEOUT_MS,
268
+ });
269
+ try {
270
+ await syncSessionProgress();
271
+ }
272
+ catch (err) {
273
+ logger.debug?.(`TeamClaw: failed probe session sync for ${taskId}: ${String(err)}`);
274
+ }
275
+ if (probeWait.status !== "ok") {
276
+ return null;
277
+ }
278
+ const probeTurn = await extractSessionAssistantTurn();
279
+ if (!probeTurn.text || probeTurn.backgroundPending || isRateLimitMessage(probeTurn.text) || isStillWaitingResponse(probeTurn.text)) {
280
+ await emitExecutionEvent({
281
+ type: "progress",
282
+ phase: "model_rate_limit_still_waiting",
283
+ source: "worker",
284
+ status: "running",
285
+ runId: runResult.runId,
286
+ sessionKey,
287
+ message: "The task is still waiting on model availability. TeamClaw will continue waiting.",
288
+ });
289
+ return null;
290
+ }
291
+ clearRateLimitWaiting();
292
+ return probeTurn.text;
293
+ };
294
+ const probeBackgroundTaskCompletion = async () => {
295
+ backgroundWaitState.probeCount += 1;
296
+ const now = Date.now();
297
+ backgroundWaitState.visibleAt = now;
298
+ backgroundWaitState.nextProbeAt = now + BACKGROUND_WORK_PROBE_MS;
299
+ await emitExecutionEvent({
300
+ type: "progress",
301
+ phase: "background_work_probe",
302
+ source: "worker",
303
+ status: "running",
304
+ runId: runResult.runId,
305
+ sessionKey,
306
+ message: `Background work has been running for over ${formatDuration(BACKGROUND_WORK_PROBE_MS)}. Re-checking whether the original task is now complete.`,
307
+ });
308
+ const probeRun = await runtime.subagent.run(buildSubagentRunOptions({
309
+ sessionKey,
310
+ message: buildBackgroundWorkProbeMessage(taskId, roleDef?.label ?? role),
311
+ extraSystemPrompt: roleSystemPrompt,
312
+ idempotencyKey: `${idempotencyKey ?? `teamclaw-${taskId}`}:background-work-probe:${backgroundWaitState.probeCount}`,
313
+ }));
314
+ const probeWait = await runtime.subagent.waitForRun({
315
+ runId: probeRun.runId,
316
+ timeoutMs: BACKGROUND_WORK_PROBE_TIMEOUT_MS,
317
+ });
318
+ try {
319
+ await syncSessionProgress();
320
+ }
321
+ catch (err) {
322
+ logger.debug?.(`TeamClaw: failed background probe session sync for ${taskId}: ${String(err)}`);
323
+ }
324
+ if (probeWait.status !== "ok") {
325
+ if (probeWait.status === "error" && isRateLimitMessage(probeWait.error || "")) {
326
+ await markRateLimitWaiting();
327
+ }
328
+ return null;
329
+ }
330
+ const probeTurn = await extractSessionAssistantTurn();
331
+ if (!probeTurn.text ||
332
+ probeTurn.backgroundPending ||
333
+ isRateLimitMessage(probeTurn.text) ||
334
+ isStillWaitingResponse(probeTurn.text)) {
335
+ await emitExecutionEvent({
336
+ type: "progress",
337
+ phase: "background_work_still_waiting",
338
+ source: "worker",
339
+ status: "running",
340
+ runId: runResult.runId,
341
+ sessionKey,
342
+ message: "The task is still waiting on background work. TeamClaw will continue waiting.",
343
+ });
344
+ return null;
345
+ }
346
+ clearBackgroundWorkWaiting();
347
+ return probeTurn;
348
+ };
349
+ const probeInactiveTaskCompletion = async () => {
350
+ inactivityState.probeCount += 1;
351
+ const now = Date.now();
352
+ inactivityState.active = true;
353
+ inactivityState.visibleAt = now;
354
+ inactivityState.nextProbeAt = now + taskTimeoutMs;
355
+ await emitExecutionEvent({
356
+ type: "progress",
357
+ phase: "inactivity_probe",
358
+ source: "worker",
359
+ status: "running",
360
+ runId: runResult.runId,
361
+ sessionKey,
362
+ message: `No new visible task progress has appeared for over ${formatDuration(taskTimeoutMs)}. Re-checking whether the original task is complete or still actively running.`,
363
+ });
364
+ const probeRun = await runtime.subagent.run(buildSubagentRunOptions({
365
+ sessionKey,
366
+ message: buildInactivityProbeMessage(taskId, roleDef?.label ?? role, taskTimeoutMs),
367
+ extraSystemPrompt: roleSystemPrompt,
368
+ idempotencyKey: `${idempotencyKey ?? `teamclaw-${taskId}`}:inactivity-probe:${inactivityState.probeCount}`,
369
+ }));
370
+ const probeWait = await runtime.subagent.waitForRun({
371
+ runId: probeRun.runId,
372
+ timeoutMs: INACTIVITY_PROBE_TIMEOUT_MS,
373
+ });
374
+ try {
375
+ await syncSessionProgress();
376
+ }
377
+ catch (err) {
378
+ logger.debug?.(`TeamClaw: failed inactivity probe session sync for ${taskId}: ${String(err)}`);
379
+ }
380
+ if (probeWait.status === "error" && isRateLimitMessage(probeWait.error || "")) {
381
+ await markRateLimitWaiting();
382
+ return null;
383
+ }
384
+ if (probeWait.status !== "ok") {
385
+ return null;
386
+ }
387
+ const probeTurn = await extractSessionAssistantTurn();
388
+ if (!probeTurn.text || probeTurn.backgroundPending || isRateLimitMessage(probeTurn.text) || isStillWaitingResponse(probeTurn.text)) {
389
+ inactivityState.active = false;
390
+ inactivityState.visibleAt = undefined;
391
+ inactivityState.nextProbeAt = Date.now() + taskTimeoutMs;
392
+ await emitExecutionEvent({
393
+ type: "progress",
394
+ phase: "inactivity_still_waiting",
395
+ source: "worker",
396
+ status: "running",
397
+ runId: runResult.runId,
398
+ sessionKey,
399
+ message: "The task is still actively pending with no final result yet. TeamClaw will continue waiting instead of failing it.",
400
+ });
401
+ return null;
402
+ }
403
+ if (rateLimitState.active) {
404
+ clearRateLimitWaiting();
405
+ }
406
+ noteObservedActivity();
407
+ return probeTurn;
408
+ };
409
+ let keepPolling = true;
410
+ const pollSessionProgress = (async () => {
411
+ while (keepPolling) {
412
+ try {
413
+ await syncSessionProgress();
414
+ }
415
+ catch (err) {
416
+ logger.debug?.(`TeamClaw: failed to sync session progress for ${taskId}: ${String(err)}`);
417
+ }
418
+ if (!keepPolling) {
419
+ break;
420
+ }
421
+ await delay(SESSION_PROGRESS_POLL_INTERVAL_MS);
422
+ }
423
+ })();
424
+ let waitResult;
425
+ let completionOverride = null;
426
+ try {
427
+ while (true) {
428
+ if (rateLimitState.active && (rateLimitState.nextProbeAt ?? Number.POSITIVE_INFINITY) <= Date.now()) {
429
+ completionOverride = await probeRateLimitedTaskCompletion();
430
+ if (completionOverride) {
431
+ waitResult = { status: "ok" };
432
+ break;
433
+ }
434
+ }
435
+ if (!rateLimitState.active
436
+ && !backgroundWaitState.active
437
+ && (inactivityState.nextProbeAt ?? Number.POSITIVE_INFINITY) <= Date.now()) {
438
+ const inactivityProbeTurn = await probeInactiveTaskCompletion();
439
+ if (inactivityProbeTurn) {
440
+ completionOverride = inactivityProbeTurn.text;
441
+ waitResult = { status: "ok" };
442
+ break;
443
+ }
444
+ }
445
+ waitResult = await runtime.subagent.waitForRun({
446
+ runId: runResult.runId,
447
+ timeoutMs: RUN_WAIT_SLICE_MS,
448
+ });
449
+ if (waitResult.status === "ok") {
450
+ break;
451
+ }
452
+ if (waitResult.status === "error") {
453
+ if (isRateLimitMessage(waitResult.error || "")) {
454
+ await markRateLimitWaiting();
455
+ continue;
456
+ }
457
+ break;
458
+ }
459
+ }
460
+ }
461
+ finally {
462
+ keepPolling = false;
463
+ await pollSessionProgress;
464
+ }
465
+ try {
466
+ await syncSessionProgress();
467
+ }
468
+ catch (err) {
469
+ logger.debug?.(`TeamClaw: failed final session progress sync for ${taskId}: ${String(err)}`);
470
+ }
471
+ if (waitResult.status === "ok") {
472
+ let assistantTurn = completionOverride
473
+ ? buildAssistantTurnSnapshot(completionOverride)
474
+ : await extractSessionAssistantTurn();
475
+ while (isBackgroundWorkPendingTurn(assistantTurn)) {
476
+ await markBackgroundWorkWaiting();
477
+ const nextProbeAt = backgroundWaitState.nextProbeAt ?? (Date.now() + BACKGROUND_WORK_PROBE_MS);
478
+ const delayMs = Math.max(1_000, nextProbeAt - Date.now());
479
+ await delay(delayMs);
480
+ const probeTurn = await probeBackgroundTaskCompletion();
481
+ if (probeTurn) {
482
+ assistantTurn = probeTurn;
483
+ break;
484
+ }
485
+ assistantTurn = await extractSessionAssistantTurn();
486
+ }
487
+ if (waitResult.status === "ok") {
488
+ if (rateLimitState.active) {
489
+ clearRateLimitWaiting();
490
+ }
491
+ const rawResult = assistantTurn.text;
492
+ if (rawResult && normalizeComparableText(rawResult) !== normalizeComparableText(progressSnapshot.lastAssistantMessage)) {
493
+ await emitExecutionEvent({
494
+ type: "output",
495
+ phase: "final_output",
496
+ source: "subagent",
497
+ message: rawResult,
498
+ });
499
+ }
500
+ clearBackgroundWorkWaiting();
501
+ // Extract inline result contract if present
502
+ const extracted = extractInlineResultContract(rawResult);
503
+ if (extracted) {
504
+ logger.info(`TeamClaw: task ${taskId} — extracted inline result contract from ${role}`);
505
+ return { text: extracted.cleanedText || rawResult, contract: extracted.contract };
506
+ }
507
+ if (rawResult && isApprovalRequiredResponse(rawResult)) {
508
+ logger.warn(`TeamClaw: task ${taskId} is blocked waiting for exec approval as ${role}`);
509
+ return {
510
+ text: rawResult,
511
+ contract: buildApprovalBlockedContract(rawResult),
512
+ };
513
+ }
514
+ logger.info(`TeamClaw: task ${taskId} completed successfully as ${role}`);
515
+ return { text: rawResult };
516
+ }
517
+ clearBackgroundWorkWaiting();
518
+ }
519
+ await emitExecutionEvent({
520
+ type: "error",
521
+ phase: "run_failed",
522
+ source: "subagent",
523
+ status: "failed",
524
+ message: waitResult.error || "Task execution failed",
525
+ });
526
+ throw new Error(waitResult.error || "Task execution failed");
527
+ }
528
+ catch (err) {
529
+ const errorMsg = err instanceof Error ? err.message : String(err);
530
+ await emitExecutionEvent({
531
+ type: "error",
532
+ phase: "execution_error",
533
+ source: "worker",
534
+ status: "failed",
535
+ message: errorMsg,
536
+ });
537
+ logger.error(`TeamClaw: task ${taskId} execution failed for ${role}: ${errorMsg}`);
538
+ throw err;
539
+ }
540
+ };
541
+ }
542
+ function formatDuration(timeoutMs) {
543
+ const totalSeconds = Math.ceil(timeoutMs / 1000);
544
+ if (totalSeconds % 3600 === 0) {
545
+ const hours = totalSeconds / 3600;
546
+ return `${hours} hour${hours === 1 ? "" : "s"}`;
547
+ }
548
+ if (totalSeconds % 60 === 0) {
549
+ const minutes = totalSeconds / 60;
550
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
551
+ }
552
+ return `${totalSeconds} second${totalSeconds === 1 ? "" : "s"}`;
553
+ }
554
+ function delay(ms) {
555
+ return new Promise((resolve) => {
556
+ setTimeout(resolve, ms);
557
+ });
558
+ }
559
+ function buildSessionProgressEntries(messages, taskMessage) {
560
+ const entries = [];
561
+ const normalizedTaskMessage = normalizeComparableText(taskMessage);
562
+ for (const rawMessage of messages) {
563
+ if (!rawMessage || typeof rawMessage !== "object") {
564
+ continue;
565
+ }
566
+ const message = rawMessage;
567
+ const role = normalizeSessionRole(message.role);
568
+ if (!role) {
569
+ continue;
570
+ }
571
+ const rendered = renderSessionMessage(message, role);
572
+ if (!rendered.message) {
573
+ continue;
574
+ }
575
+ const comparableMessage = normalizeComparableText(rendered.message);
576
+ if (role === "user" && normalizedTaskMessage && comparableMessage.includes(normalizedTaskMessage)) {
577
+ continue;
578
+ }
579
+ entries.push({
580
+ fingerprint: `${rendered.stream}:${comparableMessage}`,
581
+ message: rendered.message,
582
+ phase: rendered.stream,
583
+ stream: rendered.stream,
584
+ isRateLimit: isRateLimitMessage(rendered.message),
585
+ });
586
+ }
587
+ return entries;
588
+ }
589
+ function collectChildSessionKeys(messages) {
590
+ const keys = new Set();
591
+ for (const message of messages) {
592
+ if (!message || typeof message !== "object") {
593
+ continue;
594
+ }
595
+ const content = message.content;
596
+ const text = typeof content === "string"
597
+ ? content
598
+ : Array.isArray(content)
599
+ ? content
600
+ .map((entry) => (entry && typeof entry === "object" && typeof entry.text === "string")
601
+ ? entry.text
602
+ : "")
603
+ .filter(Boolean)
604
+ .join("\n")
605
+ : "";
606
+ for (const match of text.matchAll(/"childSessionKey"\s*:\s*"([^"]+)"/g)) {
607
+ const childSessionKey = match[1]?.trim();
608
+ if (childSessionKey) {
609
+ keys.add(childSessionKey);
610
+ }
611
+ }
612
+ }
613
+ return Array.from(keys);
614
+ }
615
+ function mergeChildSessionKeys(existing, discovered) {
616
+ const keys = new Set(existing);
617
+ for (const childSessionKey of discovered) {
618
+ keys.add(childSessionKey);
619
+ }
620
+ return Array.from(keys);
621
+ }
622
+ async function syncChildSessionRateLimits(runtime, snapshot) {
623
+ let detected = false;
624
+ for (const childSessionKey of snapshot.childSessionKeys) {
625
+ try {
626
+ const sessionMessages = await runtime.subagent.getSessionMessages({
627
+ sessionKey: childSessionKey,
628
+ limit: SESSION_PROGRESS_MESSAGE_LIMIT,
629
+ });
630
+ const entries = buildSessionProgressEntries(sessionMessages.messages, "");
631
+ const previousFingerprints = snapshot.childFingerprints.get(childSessionKey) ?? [];
632
+ const newEntries = getNewSessionProgressEntries(entries, previousFingerprints);
633
+ snapshot.childFingerprints.set(childSessionKey, entries.map((entry) => entry.fingerprint));
634
+ if (newEntries.some((entry) => entry.isRateLimit)) {
635
+ detected = true;
636
+ }
637
+ }
638
+ catch (_err) {
639
+ // Child session updates are best-effort only.
640
+ }
641
+ }
642
+ return detected;
643
+ }
644
+ function getNewSessionProgressEntries(entries, previousFingerprints) {
645
+ if (entries.length === 0) {
646
+ return [];
647
+ }
648
+ if (previousFingerprints.length === 0) {
649
+ return entries;
650
+ }
651
+ const currentFingerprints = entries.map((entry) => entry.fingerprint);
652
+ const maxOverlap = Math.min(previousFingerprints.length, currentFingerprints.length);
653
+ let overlap = 0;
654
+ for (let size = maxOverlap; size > 0; size -= 1) {
655
+ let matches = true;
656
+ for (let index = 0; index < size; index += 1) {
657
+ if (previousFingerprints[previousFingerprints.length - size + index] !== currentFingerprints[index]) {
658
+ matches = false;
659
+ break;
660
+ }
661
+ }
662
+ if (matches) {
663
+ overlap = size;
664
+ break;
665
+ }
666
+ }
667
+ return entries.slice(overlap);
668
+ }
669
+ function normalizeSessionRole(value) {
670
+ if (typeof value !== "string") {
671
+ return "";
672
+ }
673
+ const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
674
+ if (normalized === "toolresult") {
675
+ return "tool_result";
676
+ }
677
+ return normalized;
678
+ }
679
+ function renderSessionMessage(message, role) {
680
+ const content = message.content;
681
+ if (typeof content === "string") {
682
+ return {
683
+ message: truncateProgressMessage(content),
684
+ stream: role,
685
+ };
686
+ }
687
+ if (Array.isArray(content)) {
688
+ const textParts = [];
689
+ const toolCalls = [];
690
+ let toolResultCount = 0;
691
+ let toolResultErrors = 0;
692
+ for (const entry of content) {
693
+ if (!entry || typeof entry !== "object") {
694
+ continue;
695
+ }
696
+ const block = entry;
697
+ const type = normalizeBlockType(block.type);
698
+ if (type === "text") {
699
+ const text = typeof block.text === "string" ? block.text.trim() : "";
700
+ if (text) {
701
+ textParts.push(text);
702
+ }
703
+ continue;
704
+ }
705
+ if (TOOL_CALL_BLOCK_TYPES.has(type)) {
706
+ const name = typeof block.name === "string" ? block.name.trim() : "";
707
+ if (name) {
708
+ toolCalls.push(name);
709
+ }
710
+ continue;
711
+ }
712
+ if (TOOL_RESULT_BLOCK_TYPES.has(type)) {
713
+ toolResultCount += 1;
714
+ if (block.is_error === true) {
715
+ toolResultErrors += 1;
716
+ }
717
+ }
718
+ }
719
+ const parts = [];
720
+ if (textParts.length > 0) {
721
+ parts.push(textParts.join("\n"));
722
+ }
723
+ if (toolCalls.length > 0) {
724
+ parts.push(`[tool call] ${toolCalls.join(", ")}`);
725
+ }
726
+ if (toolResultCount > 0) {
727
+ parts.push(`[tool result] ${toolResultCount}${toolResultErrors > 0 ? ` (${toolResultErrors} error)` : ""}`);
728
+ }
729
+ if (parts.length > 0) {
730
+ return {
731
+ message: truncateProgressMessage(parts.join("\n")),
732
+ stream: textParts.length > 0 ? role : "tool",
733
+ };
734
+ }
735
+ }
736
+ const fallbackToolName = typeof message.toolName === "string"
737
+ ? message.toolName.trim()
738
+ : (typeof message.tool_name === "string" ? message.tool_name.trim() : "");
739
+ if (fallbackToolName) {
740
+ return {
741
+ message: `[tool call] ${fallbackToolName}`,
742
+ stream: "tool",
743
+ };
744
+ }
745
+ return {
746
+ message: truncateProgressMessage(safeJsonStringify(message)),
747
+ stream: role || "session",
748
+ };
749
+ }
750
+ function normalizeBlockType(value) {
751
+ if (typeof value !== "string") {
752
+ return "";
753
+ }
754
+ return value.trim().toLowerCase();
755
+ }
756
+ function truncateProgressMessage(value) {
757
+ const trimmed = value.trim();
758
+ if (!trimmed) {
759
+ return "";
760
+ }
761
+ if (trimmed.length <= MAX_SESSION_PROGRESS_MESSAGE_CHARS) {
762
+ return trimmed;
763
+ }
764
+ return `${trimmed.slice(0, MAX_SESSION_PROGRESS_MESSAGE_CHARS)}\n… (truncated)`;
765
+ }
766
+ function normalizeComparableText(value) {
767
+ return value.trim().replace(/\r\n/g, "\n");
768
+ }
769
+ function safeJsonStringify(value) {
770
+ try {
771
+ return typeof value === "string" ? value : JSON.stringify(value);
772
+ }
773
+ catch (_err) {
774
+ return String(value);
775
+ }
776
+ }
777
+ function buildTaskMessage(taskDescription, taskId, roleLabel, options) {
778
+ const rules = [
779
+ ...buildTaskExecutionRules(RATE_LIMIT_WAITING_SENTINEL),
780
+ "Before your final reply, you MUST call teamclaw_submit_result_contract to deliver the structured result for this task. Do not end your turn without it.",
781
+ ...buildWorkerMemoryContractRules(),
782
+ ...buildVerificationPolicy(),
783
+ ...buildDeliverableMetadataPolicy(),
784
+ ...buildResultContractGuidance({ inlineContract: Boolean(options?.inlineContract) }),
785
+ ];
786
+ const sections = [
787
+ taskDescription,
788
+ "",
789
+ "## Task Context",
790
+ `Reference: ${taskId}`,
791
+ `Assigned Role: ${roleLabel}`,
792
+ ];
793
+ if (options?.projectDir) {
794
+ const workspaceProjectPath = buildTeamClawProjectWorkspacePath(options.projectDir);
795
+ const absoluteProjectPath = `${resolveTeamClawProjectsDir()}/${options.projectDir}`.replace(/\/+/gu, "/");
796
+ sections.push("", "## Working Directory", `This task's project directory is: \`${workspaceProjectPath}/\``, `Authoritative absolute path: \`${absoluteProjectPath}/\``, "All files you create, read, or modify for this task MUST be inside this directory.", "If the directory is empty, create the necessary structure. If it already has files from prior tasks in the same project, build on them.", "If the task description mentions a different absolute workspace path, treat that path as stale guidance and use this authoritative project directory instead.", "When the task references project-local files such as `ARCHITECTURE.md`, `README.md`, or `package.json`, resolve them inside this project directory first.", "Do NOT place files in the workspace root or any other project's directory.");
797
+ }
798
+ if (options?.teamContext) {
799
+ const contextLines = [];
800
+ if (options.teamContext.requirementSummary) {
801
+ contextLines.push(`Requirement summary: ${options.teamContext.requirementSummary}`);
802
+ }
803
+ if (options.teamContext.projectName) {
804
+ contextLines.push(`Project name: ${options.teamContext.projectName}`);
805
+ }
806
+ if (options.teamContext.requiredRoles && options.teamContext.requiredRoles.length > 0) {
807
+ contextLines.push(`Required TeamClaw roles: ${options.teamContext.requiredRoles.join(", ")}`);
808
+ }
809
+ const appendTaskBucket = (label, entries) => {
810
+ if (!entries || entries.length === 0) {
811
+ return;
812
+ }
813
+ contextLines.push("", label);
814
+ for (const entry of entries) {
815
+ const roleText = entry.assignedRole ? ` (${entry.assignedRole})` : "";
816
+ const summaryText = entry.summary ? `: ${entry.summary}` : "";
817
+ contextLines.push(`- [${entry.id}] ${entry.title}${roleText} [${entry.status}]${summaryText}`);
818
+ }
819
+ };
820
+ appendTaskBucket("Active same-requirement tasks:", options.teamContext.activeTasks);
821
+ appendTaskBucket("Blocked same-requirement tasks:", options.teamContext.blockedTasks);
822
+ appendTaskBucket("Recent completed upstream tasks:", options.teamContext.recentCompletedTasks);
823
+ if (options.teamContext.pendingClarifications && options.teamContext.pendingClarifications.length > 0) {
824
+ contextLines.push("", "Pending clarifications:");
825
+ for (const clarification of options.teamContext.pendingClarifications) {
826
+ contextLines.push(`- ${clarification.question}${clarification.blockingReason ? ` — ${clarification.blockingReason}` : ""}`);
827
+ }
828
+ }
829
+ if (options.teamContext.answeredClarifications && options.teamContext.answeredClarifications.length > 0) {
830
+ contextLines.push("", "Recently answered clarifications (treat these as authoritative and do not ask the same question again unless the answer is still objectively missing or invalid):");
831
+ for (const clarification of options.teamContext.answeredClarifications) {
832
+ const meta = [
833
+ clarification.answeredBy ? `answered by ${clarification.answeredBy}` : "",
834
+ clarification.blockingReason ? `was blocked by ${clarification.blockingReason}` : "",
835
+ ].filter(Boolean).join("; ");
836
+ contextLines.push(`- Q: ${clarification.question}`);
837
+ contextLines.push(` A: ${clarification.answer}${meta ? ` (${meta})` : ""}`);
838
+ }
839
+ }
840
+ if (options.teamContext.kickoffSummary) {
841
+ contextLines.push("", "Team kickoff consensus:", options.teamContext.kickoffSummary);
842
+ }
843
+ if (options.teamContext.handoffPlan) {
844
+ contextLines.push("", `Current handoff plan: ${options.teamContext.handoffPlan}`);
845
+ }
846
+ if (options.teamContext.notes) {
847
+ contextLines.push("", `Controller notes: ${options.teamContext.notes}`);
848
+ }
849
+ if (contextLines.length > 0) {
850
+ sections.push("", "## TeamClaw Requirement Context", ...contextLines);
851
+ }
852
+ }
853
+ sections.push("", "## Execution Rules", ...rules);
854
+ return sections.join("\n");
855
+ }
856
+ /**
857
+ * Extract an inline result contract from a fenced ```teamclaw-result-contract block.
858
+ * Returns the parsed contract and the text with the block removed, or null if
859
+ * no valid contract is found.
860
+ */
861
+ export function extractInlineResultContract(text) {
862
+ // Match ```teamclaw-result-contract ... ``` blocks (greedy last match)
863
+ const pattern = /```teamclaw-result-contract\s*\n([\s\S]*?)```/g;
864
+ let lastMatch = null;
865
+ let match;
866
+ while ((match = pattern.exec(text)) !== null) {
867
+ lastMatch = match;
868
+ }
869
+ if (!lastMatch) {
870
+ return null;
871
+ }
872
+ const jsonStr = lastMatch[1].trim();
873
+ try {
874
+ const parsed = JSON.parse(jsonStr);
875
+ if (!parsed || typeof parsed !== "object") {
876
+ return null;
877
+ }
878
+ // Remove the contract block from the text for a clean result
879
+ const cleanedText = text.slice(0, lastMatch.index).trimEnd()
880
+ + text.slice(lastMatch.index + lastMatch[0].length).trimStart();
881
+ return { contract: parsed, cleanedText: cleanedText.trim() };
882
+ }
883
+ catch {
884
+ return null;
885
+ }
886
+ }
887
+ function buildRateLimitProbeMessage(taskId, roleLabel) {
888
+ return [
889
+ `This is a follow-up check for task ${taskId} (${roleLabel}).`,
890
+ "The earlier run appears to be delayed by upstream model rate limiting.",
891
+ "Do not restart the task from scratch.",
892
+ "If the original task is fully complete now, immediately submit the structured result contract and provide the final result for that original task.",
893
+ `If the original task is not complete yet, reply with exactly ${RATE_LIMIT_WAITING_SENTINEL}.`,
894
+ ].join("\n");
895
+ }
896
+ function buildBackgroundWorkProbeMessage(taskId, roleLabel) {
897
+ return [
898
+ `This is a follow-up check for task ${taskId} (${roleLabel}).`,
899
+ "Your previous turn ended while background work was still running.",
900
+ "Do not restart the task from scratch.",
901
+ "Inspect the background coding or process session you previously started, continue from the existing workspace/session state, and only finalize once the original task deliverable is genuinely complete.",
902
+ "Do not call sessions_yield again unless you are still explicitly waiting on unfinished background work.",
903
+ "If the original task is fully complete now, immediately submit the structured result contract and provide the final result for that original task.",
904
+ `If the original task is not complete yet, reply with exactly ${RATE_LIMIT_WAITING_SENTINEL}.`,
905
+ ].join("\n");
906
+ }
907
+ function buildInactivityProbeMessage(taskId, roleLabel, inactivityMs) {
908
+ return [
909
+ `This is a follow-up check for task ${taskId} (${roleLabel}).`,
910
+ `There has been no new visible progress for over ${formatDuration(inactivityMs)}.`,
911
+ "Do not restart the task from scratch.",
912
+ "Continue from the existing workspace and session state only.",
913
+ "If the original task is fully complete now, immediately submit the structured result contract and provide the final result for that original task.",
914
+ `If the original task is not complete yet, reply with exactly ${RATE_LIMIT_WAITING_SENTINEL}.`,
915
+ ].join("\n");
916
+ }
917
+ function buildAssistantTurnSnapshot(text, toolCalls = []) {
918
+ const normalizedText = String(text || "").trim();
919
+ const normalizedToolCalls = toolCalls
920
+ .map((name) => String(name || "").trim().toLowerCase())
921
+ .filter(Boolean);
922
+ const yielded = normalizedToolCalls.includes("sessions_yield");
923
+ return {
924
+ text: normalizedText,
925
+ toolCalls: normalizedToolCalls,
926
+ yielded,
927
+ backgroundPending: yielded || isBackgroundWorkPendingMessage(normalizedText),
928
+ };
929
+ }
930
+ function extractLastAssistantTurn(messages) {
931
+ const assistantMessages = messages.filter((message) => {
932
+ if (!message || typeof message !== "object") {
933
+ return false;
934
+ }
935
+ return message.role === "assistant";
936
+ });
937
+ const lastAssistant = assistantMessages[assistantMessages.length - 1];
938
+ if (!lastAssistant) {
939
+ return buildAssistantTurnSnapshot("");
940
+ }
941
+ if (typeof lastAssistant.content === "string") {
942
+ return buildAssistantTurnSnapshot(lastAssistant.content);
943
+ }
944
+ if (Array.isArray(lastAssistant.content)) {
945
+ const textBlocks = lastAssistant.content
946
+ .filter((block) => {
947
+ return !!block && typeof block === "object" && block.type === "text";
948
+ })
949
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
950
+ .filter(Boolean);
951
+ const toolCalls = lastAssistant.content
952
+ .filter((block) => {
953
+ return !!block
954
+ && typeof block === "object"
955
+ && TOOL_CALL_BLOCK_TYPES.has(normalizeBlockType(block.type));
956
+ })
957
+ .map((block) => (typeof block.name === "string" ? block.name : ""))
958
+ .filter(Boolean);
959
+ if (textBlocks.length > 0 || toolCalls.length > 0) {
960
+ return buildAssistantTurnSnapshot(textBlocks.join("\n"), toolCalls);
961
+ }
962
+ }
963
+ return buildAssistantTurnSnapshot(JSON.stringify(lastAssistant));
964
+ }
965
+ function isRateLimitMessage(value) {
966
+ return /(rate[_ ]limit|too many requests|429\b|resource has been exhausted|tokens per day|quota|throttl)/i.test(String(value || ""));
967
+ }
968
+ function isStillWaitingResponse(value) {
969
+ const normalized = String(value || "").trim();
970
+ if (!normalized) {
971
+ return true;
972
+ }
973
+ if (normalized === RATE_LIMIT_WAITING_SENTINEL) {
974
+ return true;
975
+ }
976
+ return /(still waiting|continue waiting|not complete yet|尚未完成|继续等待|仍在等待)/i.test(normalized);
977
+ }
978
+ function extractPendingApprovalCommands(value) {
979
+ const matches = String(value || "").match(/\/approve\s+[^\s]+\s+(?:allow-once|allow-always|deny)\b/gi) ?? [];
980
+ return Array.from(new Set(matches.map((entry) => entry.trim()).filter(Boolean)));
981
+ }
982
+ function isApprovalRequiredResponse(value) {
983
+ const normalized = String(value || "").trim();
984
+ if (!normalized) {
985
+ return false;
986
+ }
987
+ return /approval required|i need approval to run commands|pending exec commands?|reply with:\s*\/approve|需要批准|等待.*批准/i.test(normalized)
988
+ || extractPendingApprovalCommands(normalized).length > 0;
989
+ }
990
+ function buildApprovalBlockedContract(rawResult) {
991
+ const approvalCommands = extractPendingApprovalCommands(rawResult);
992
+ const blockingReason = "Pending exec approval is required before this task can continue.";
993
+ return {
994
+ version: "1.0",
995
+ outcome: "blocked",
996
+ summary: "Task is blocked waiting for exec approval.",
997
+ deliverables: approvalCommands.map((command) => ({
998
+ kind: "command",
999
+ value: command,
1000
+ summary: "Approval command emitted by the worker runtime.",
1001
+ })),
1002
+ keyPoints: approvalCommands,
1003
+ blockers: [blockingReason],
1004
+ followUps: [{
1005
+ type: "clarification",
1006
+ reason: blockingReason,
1007
+ }],
1008
+ questions: [
1009
+ "A worker command needs exec approval before this task can continue. Should TeamClaw retry after the approval policy is fixed or the commands are approved?",
1010
+ ],
1011
+ notes: rawResult,
1012
+ };
1013
+ }
1014
+ function isInternalRetryPrompt(value, stream) {
1015
+ if (stream !== "user") {
1016
+ return false;
1017
+ }
1018
+ const normalized = String(value || "").trim();
1019
+ if (!normalized) {
1020
+ return false;
1021
+ }
1022
+ return /continue where you left off\. the previous model attempt failed or timed out\./i.test(normalized);
1023
+ }
1024
+ function isBackgroundWorkPendingMessage(value) {
1025
+ const normalized = String(value || "").trim();
1026
+ if (!normalized) {
1027
+ return false;
1028
+ }
1029
+ return /(running in background|background session|command still running \(session|monitor progress and report back when complete|后台.*运行中|后台.*会在完成后汇报|后台.*完成后再汇报)/i.test(normalized);
1030
+ }
1031
+ function isBackgroundWorkPendingTurn(turn) {
1032
+ return turn.backgroundPending || isStillWaitingResponse(turn.text);
1033
+ }