@evandu/super-pi 0.1.239 → 0.1.241

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 (33) hide show
  1. package/dist/client/.super-pi-client-sources.json +8 -8
  2. package/dist/client/assets/{CodeMirrorEditor-CtzPSOsS.js → CodeMirrorEditor-CiOKD-_q.js} +1 -1
  3. package/dist/client/assets/{GitDiffEditor-iNVZVVMb.js → GitDiffEditor-D5VMi7K-.js} +1 -1
  4. package/dist/client/assets/index-CwH7sttH.css +1 -0
  5. package/dist/client/assets/index-oUDSLOqG.js +347 -0
  6. package/dist/client/index.html +2 -2
  7. package/dist/server/application/extension-ui-service.d.ts +3 -1
  8. package/dist/server/application/extension-ui-service.js +20 -7
  9. package/dist/server/application/run-service.d.ts +19 -61
  10. package/dist/server/application/run-service.js +221 -372
  11. package/dist/server/application/workspace-service.js +1 -1
  12. package/dist/server/content-search.d.ts +13 -39
  13. package/dist/server/content-search.js +202 -219
  14. package/dist/server/exec-service.d.ts +14 -7
  15. package/dist/server/exec-service.js +66 -40
  16. package/dist/server/http-server.js +69 -31
  17. package/dist/server/index.js +6 -6
  18. package/dist/server/store.d.ts +11 -24
  19. package/dist/server/store.js +88 -62
  20. package/dist/server/subagent-runs.d.ts +3 -2
  21. package/dist/server/subagent-runs.js +45 -33
  22. package/dist/server/subagents.d.ts +1 -0
  23. package/dist/server/subagents.js +30 -12
  24. package/dist/server/types.d.ts +13 -11
  25. package/dist/server/ws-server.d.ts +3 -0
  26. package/dist/server/ws-server.js +40 -6
  27. package/dist/shared/background-task.d.ts +22 -0
  28. package/dist/shared/background-task.js +5 -0
  29. package/dist/shared/content-search.d.ts +22 -0
  30. package/dist/shared/content-search.js +1 -0
  31. package/package.json +1 -1
  32. package/dist/client/assets/index-C5kxyPTT.js +0 -340
  33. package/dist/client/assets/index-DN0oBG6l.css +0 -1
@@ -12,11 +12,12 @@ import { toWorkspaceRelative } from "../files.js";
12
12
  import { inScope, refreshWorkspaceIndex } from "../file-index.js";
13
13
  import { resolveSessionCwd } from "../session-cwd.js";
14
14
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
15
+ import { BACKGROUND_LOG_LIMIT, subagentProgress } from "../../shared/background-task.js";
15
16
  import { execFile } from "node:child_process";
16
17
  import { promisify } from "node:util";
17
18
  import { randomUUID } from "node:crypto";
18
- import { isAbsolute, resolve } from "node:path";
19
- import { lstat } from "node:fs/promises";
19
+ import { isAbsolute, join, resolve } from "node:path";
20
+ import { lstat, mkdir, writeFile } from "node:fs/promises";
20
21
  import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
21
22
  const execFileAsync = promisify(execFile);
22
23
  /**
@@ -212,6 +213,7 @@ export class RunService {
212
213
  runCompletions = new Map();
213
214
  /** A selected interrupt owns the next free run slot, even while the old child exits. */
214
215
  interruptTargets = new Map();
216
+ pendingBackgroundWakeups = new Map();
215
217
  shuttingDown = false;
216
218
  /** Preserve incoming background results as waiting messages while the server drains its producers. */
217
219
  beginShutdown() {
@@ -238,6 +240,8 @@ export class RunService {
238
240
  this.activeRuns.delete(conversationId);
239
241
  this.runCompletions.get(conversationId)?.resolve();
240
242
  this.runCompletions.delete(conversationId);
243
+ if (!current.signal.aborted)
244
+ this.wakeWaitingBackgroundResult(conversationId);
241
245
  }
242
246
  /**
243
247
  * WHERE EACH TOOL CALL LANDED, per conversation, for as long as the turn that made it is still running.
@@ -304,7 +308,12 @@ export class RunService {
304
308
  return this.originForToolCall(conversationId, toolCallId);
305
309
  }
306
310
  execService;
307
- setExecService(execService) { this.execService = execService; }
311
+ backgroundLogDirectory;
312
+ execSettlements = new Map();
313
+ setExecService(execService, logDirectory) {
314
+ this.execService = execService;
315
+ this.backgroundLogDirectory = logDirectory;
316
+ }
308
317
  /**
309
318
  * Called by the exec completion handler in index.ts when a background exec session ends.
310
319
  * Injects the result into the conversation and cleans up the background task record.
@@ -315,70 +324,77 @@ export class RunService {
315
324
  * when nothing else is busy. The render stays as a 后台回传 block throughout - in dock and in
316
325
  * transcript - so a `role: "user"` is never impersonated.
317
326
  */
318
- enqueueExecResult(sessionId, exitCode, stdout, stderr) {
319
- const tasks = this.store.snapshot().backgroundTasks;
320
- const task = tasks.find((t) => t.id === sessionId);
327
+ enqueueExecResult(sessionId, exitCode, stdout, stderr, completion) {
328
+ const task = this.store.backgroundTask(sessionId);
321
329
  if (!task)
322
330
  return;
323
- const tag = exitCode === 0 ? "task_result" : "task_error";
324
- const body = exitCode === 0 ? stdout : (stderr || `Command exited with code ${exitCode}`);
325
- const message = `<task id="${sessionId}" state="${exitCode === 0 ? "completed" : "error"}" kind="exec">\n<summary>${task.title}</summary>\n<${tag}>\n${body}</${tag}>\n</task>`;
326
- void this.trackDetached((async () => {
327
- try {
328
- // Keep the dispatch card at its call after the running-task list is cleaned up.
329
- // The result message below keeps its separate arrival position in the transcript.
330
- if (task.originMessageId !== undefined && task.originCallRow !== undefined
331
- && this.store.snapshot().conversations.find(conversation => conversation.id === task.conversationId)
332
- ?.messages.find(message => message.id === task.originMessageId)?.toolCalls?.[task.originCallRow]) {
333
- const toolCalls = await this.store.updateToolCall(task.conversationId, task.originMessageId, task.originCallRow, { backgroundTask: { id: sessionId, status: exitCode === 0 ? "completed" : "failed", output: (stdout + stderr).slice(-512_000), exitCode } });
334
- this.broadcaster.broadcast({ type: "message.tools", conversationId: task.conversationId, messageId: task.originMessageId, toolCalls });
331
+ const output = (stdout + stderr).slice(-BACKGROUND_LOG_LIMIT);
332
+ const offset = completion?.offset ?? stdout.length + stderr.length;
333
+ const status = completion?.status === "cancelled" || completion?.status === "interrupted"
334
+ ? completion.status : exitCode === 0 && !completion?.signal ? "completed" : "failed";
335
+ const reason = status === "cancelled" ? "已由用户终止"
336
+ : status === "interrupted" ? "服务停止,任务已中断"
337
+ : completion?.signal ? `进程收到信号 ${completion.signal}`
338
+ : status === "failed" ? `Command exited with code ${exitCode}` : undefined;
339
+ const settling = this.trackDetached(this.finishBackgroundResult(task, {
340
+ status, output, outputOffset: offset, outputTruncated: offset > output.length,
341
+ exitCode, signal: completion?.signal, reason,
342
+ }, status === "completed" || status === "failed")).catch(error => {
343
+ console.warn("Super Pi: could not record background command completion:", error);
344
+ }).finally(() => {
345
+ if (this.execSettlements.get(sessionId) === settling)
346
+ this.execSettlements.delete(sessionId);
347
+ });
348
+ this.execSettlements.set(sessionId, settling);
349
+ }
350
+ async failBackgroundTaskStart(taskId, reason, cancelled = false) {
351
+ const task = this.store.backgroundTask(taskId);
352
+ if (task)
353
+ await this.finishBackgroundResult(task, { status: cancelled ? "cancelled" : "failed", reason }, false);
354
+ }
355
+ async finishBackgroundResult(task, outcome, deliver, summary) {
356
+ const queued = await this.serializeConversation(task.conversationId, async () => {
357
+ if (!this.store.backgroundTask(task.id))
358
+ return;
359
+ let logPath;
360
+ if (outcome.output && this.backgroundLogDirectory && /^[A-Za-z0-9_-]+$/u.test(task.id)) {
361
+ try {
362
+ await mkdir(this.backgroundLogDirectory, { recursive: true });
363
+ const path = join(this.backgroundLogDirectory, task.id + ".log");
364
+ await writeFile(path, outcome.output, "utf8");
365
+ logPath = path;
366
+ }
367
+ catch (error) {
368
+ console.warn("Super Pi: could not save background log file:", error);
335
369
  }
336
- this.broadcaster.broadcast({ type: "exec.exit", sessionId, exitCode, stdout, stderr });
337
- // QUEUE ITEM, NOT A NOTICE. `delivery: "waiting"` is what makes the row show in the dock; without
338
- // it the message is a transcript entry only and `takeNextWaitingMessage` (which `runConversationTurns`
339
- // calls after every turn) never picks it up.
340
- const queued = await this.serializeConversation(task.conversationId, async () => {
341
- const row = await this.store.addToolMessage(task.conversationId, message, { delivery: "waiting" });
342
- // Pi already owns every `sending` row. Put a result ahead of unclaimed user messages.
343
- await this.moveAheadOfUnclaimed(task.conversationId, row.id);
344
- this.broadcaster.broadcastState();
345
- return row;
346
- });
347
- // THE RESULT WAITS IN SUPER PI'S OWN QUEUE, AND THE QUEUE IS DRAINED ONE TURN AT A TIME.
348
- //
349
- // It used to go to Pi's own follow-up queue, and Pi DRAINS that queue all at once when a turn
350
- // ends - the pending messages are collected into one array and fed to the model as a single
351
- // turn. So two background results that finished close together were handed over TOGETHER, and
352
- // the agent answered both at once (ledger TEST-033). That path also had a second defect of its
353
- // own: Pi's queue knows nothing about the `waiting` row queued above, so delivering through it
354
- // while leaving the row waiting gave the model the SAME result twice (ledger TEST-011).
355
- //
356
- // So the result is not delivered through that channel at all. It stays a `waiting` row, and
357
- // Super Pi's own loop takes waiting messages ONE PER TURN - which is what that loop was built
358
- // for, and what the sub-agent result path has always done.
359
- //
360
- // IDLE: a turn of its own starts now, so the model processes the result without the user
361
- // having to send anything. The failure case is included on purpose: the model seeing
362
- // "[后台任务 X 失败]" is part of the same "after the current answer finishes, the result is
363
- // processed automatically" contract, and the auto-triggered turn goes through the same
364
- // `composePrompt` path the success case does.
365
- //
366
- // BUSY: steer the result into the running turn so Pi drains it at the very next tool batch
367
- // boundary instead of waiting for the whole turn to complete.
368
- void this.trackDetached(this.dispatchBackgroundResult(task.conversationId, queued.id)).catch(async (error) => {
369
- console.warn(`Super Pi: dispatch background exec result failed: ${error instanceof Error ? error.message : "unknown error"}`);
370
- await this.settleBackgroundStatus(task.conversationId);
371
- });
372
- }
373
- catch (error) {
374
- console.warn(`Super Pi: exec result could not be appended as a tool message: ${error instanceof Error ? error.message : "unknown error"}`);
375
- }
376
- finally {
377
- await this.store.removeBackgroundTask(sessionId);
378
- await this.settleBackgroundStatus(task.conversationId);
379
- this.broadcaster.broadcastState();
380
370
  }
381
- })());
371
+ const excerpt = capText(summary ?? outcome.output ?? "", 4000, "后台输出").text.trim();
372
+ const details = [
373
+ outcome.reason,
374
+ outcome.exitCode === undefined ? "" : `退出码:${outcome.exitCode}`,
375
+ excerpt || (!outcome.output ? "本次任务未产生输出。" : ""),
376
+ logPath ? `${outcome.outputTruncated ? "保留的日志尾部" : "日志文件"}:${logPath}` : "",
377
+ ].filter(Boolean).join("\n\n");
378
+ const ok = outcome.status === "completed";
379
+ const tag = ok ? "task_result" : "task_error";
380
+ const kind = task.agentId === "exec" ? "exec" : "subagent";
381
+ const result = `<task id="${task.id}" state="${ok ? "completed" : "error"}" kind="${kind}">\n<summary>${task.title}</summary>\n<${tag}>\n${details}</${tag}>\n</task>`;
382
+ return this.store.finishBackgroundTask(task.id, outcome, result, deliver);
383
+ });
384
+ if (!queued)
385
+ return;
386
+ if (task.agentId === "exec") {
387
+ this.broadcaster.broadcast({ type: "exec.exit", sessionId: task.id, conversationId: task.conversationId, exitCode: outcome.exitCode, stdout: outcome.output ?? "", stderr: "" });
388
+ }
389
+ this.broadcaster.broadcastState();
390
+ if (queued.delivery === "waiting")
391
+ this.startBackgroundResult(task.conversationId, queued.id);
392
+ await this.settleBackgroundStatus(task.conversationId);
393
+ }
394
+ startBackgroundResult(conversationId, messageId) {
395
+ void this.trackDetached(this.dispatchBackgroundResult(conversationId, messageId)).catch(error => {
396
+ console.warn("Super Pi: could not start a background completion turn:", error);
397
+ });
382
398
  }
383
399
  /**
384
400
  * Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
@@ -414,8 +430,7 @@ export class RunService {
414
430
  const current = this.store.conversation(parentId);
415
431
  if (!current || current.archivedAt)
416
432
  return undefined;
417
- const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting" });
418
- await this.moveAheadOfUnclaimed(parentId, row.id);
433
+ const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting", prioritizeWaiting: true });
419
434
  await this.store.markConversationReported(input.conversationId);
420
435
  this.broadcaster.broadcastState();
421
436
  return row;
@@ -427,104 +442,44 @@ export class RunService {
427
442
  });
428
443
  })());
429
444
  }
430
- /**
431
- * Dispatches a background result (exec or child session) into the conversation.
432
- *
433
- * IDLE: starts a fresh turn via `processWaitingMessage`.
434
- * BUSY: attempts to steer the message into the running turn so it is delivered at the
435
- * very next tool batch boundary rather than waiting for the entire turn to complete.
436
- * INTERRUPTING: quietly leaves the message waiting; the interrupted or next turn will pick it up.
437
- */
438
- async dispatchBackgroundResult(conversationId, messageId) {
439
- if (this.shuttingDown)
440
- return;
441
- if (this.interruptTargets.has(conversationId))
445
+ dispatchBackgroundResult(conversationId, messageId) {
446
+ return this.processWaitingMessage(conversationId, messageId, { ifIdle: true, backgroundResult: true });
447
+ }
448
+ wakeWaitingBackgroundResult(conversationId) {
449
+ if (this.shuttingDown || this.interruptTargets.has(conversationId) || this.activeRuns.has(conversationId))
442
450
  return;
443
- if (!this.activeRuns.has(conversationId)) {
444
- await this.processWaitingMessage(conversationId, messageId);
451
+ const pending = this.pendingBackgroundWakeups.get(conversationId);
452
+ if (!pending)
445
453
  return;
446
- }
447
- // Conversation is busy. Attempt to steer the background result directly into the active turn.
448
- try {
449
- // THE LANE IS RELEASED BEFORE THE FALLBACK. `processWaitingMessage` acquires this same lane,
450
- // so calling it from inside the serialized callback re-enters the lane and deadlocks: the
451
- // outer work waits for the inner one, and the inner one waits for the outer one.
452
- const startWaiting = await this.serializeConversation(conversationId, async () => {
453
- if (this.shuttingDown || this.interruptTargets.has(conversationId))
454
- return false;
455
- // `processWaitingMessage` acquires this lane, so the fallback must run after serialization exits.
456
- if (!this.activeRuns.has(conversationId))
457
- return true;
458
- if (!this.runtime.steer)
459
- return false;
460
- if (this.runtime.canSteer && !this.runtime.canSteer(conversationId))
461
- return false;
462
- const waiting = this.store.listWaitingMessages(conversationId);
463
- const item = waiting.find((m) => m.id === messageId && m.delivery === "waiting");
464
- if (!item)
465
- return false;
466
- await this.moveAheadOfUnclaimed(conversationId, messageId);
467
- this.broadcaster.broadcastState();
468
- const claimed = await this.store.claimWaitingMessage(conversationId, messageId);
469
- this.broadcaster.broadcastState();
470
- if (this.shuttingDown) {
471
- await this.store.releaseWaitingMessage(conversationId, claimed.id);
472
- this.broadcaster.broadcastState();
473
- return false;
474
- }
475
- try {
476
- await this.runtime.steer(conversationId, composePrompt(claimed), claimed.images);
477
- }
478
- catch (error) {
479
- await this.store.releaseWaitingMessage(conversationId, claimed.id);
480
- this.broadcaster.broadcastState();
481
- if (!(error instanceof SteerUnavailableError)) {
482
- console.warn(`Super Pi: steer background result failed: ${error instanceof Error ? error.message : "unknown error"}`);
483
- }
484
- }
485
- return false;
486
- });
487
- if (startWaiting)
488
- await this.processWaitingMessage(conversationId, messageId);
489
- }
490
- catch (error) {
491
- console.warn(`Super Pi: steer background result failed: ${error instanceof Error ? error.message : "unknown error"}`);
492
- }
454
+ const waiting = this.store.listWaitingMessages(conversationId).filter(item => item.delivery === "waiting" && pending.has(item.id));
455
+ const [next, ...remaining] = waiting;
456
+ if (remaining.length)
457
+ this.pendingBackgroundWakeups.set(conversationId, new Set(remaining.map(item => item.id)));
458
+ else
459
+ this.pendingBackgroundWakeups.delete(conversationId);
460
+ if (next)
461
+ this.startBackgroundResult(conversationId, next.id);
493
462
  }
494
- /**
495
- * Stops an active background task (spawned process or detached subagent) on user request.
496
- *
497
- * 1. Kills the underlying PTY child process if one exists in `execService`.
498
- * 2. If the task originated from a tool call in a conversation transcript, marks the tool
499
- * call as failed with a clear message and broadcasts `message.tools`.
500
- * 3. Removes the task from `state.backgroundTasks` and broadcasts `state` so the sidebar
501
- * updates immediately.
502
- */
503
463
  async stopBackgroundTask(taskId) {
504
- const tasks = this.store.snapshot().backgroundTasks ?? [];
505
- const task = tasks.find((t) => t.id === taskId);
506
- if (this.execService) {
507
- try {
508
- this.execService.kill(taskId);
509
- }
510
- catch { /* ignore if already exited */ }
464
+ const task = this.store.backgroundTask(taskId);
465
+ if (task?.agentId === "exec" && await this.execService?.stop?.(taskId)) {
466
+ await this.execSettlements.get(taskId);
467
+ return;
511
468
  }
469
+ if (task?.agentId === "exec")
470
+ this.execService?.kill(taskId);
512
471
  this.subagents.stop(taskId);
513
- if (task && task.originMessageId !== undefined && task.originCallRow !== undefined) {
514
- const conv = this.store.snapshot().conversations.find((c) => c.id === task.conversationId);
515
- const msg = conv?.messages.find((m) => m.id === task.originMessageId);
516
- if (msg?.toolCalls?.[task.originCallRow]?.backgroundTask) {
517
- const toolCalls = await this.store.updateToolCall(task.conversationId, task.originMessageId, task.originCallRow, {
518
- backgroundTask: { id: taskId, status: "failed", output: "已由用户手动终止" },
519
- });
520
- this.broadcaster.broadcast({ type: "message.tools", conversationId: task.conversationId, messageId: task.originMessageId, toolCalls });
521
- }
522
- }
523
- await this.store.removeBackgroundTask(taskId);
524
- if (task?.conversationId) {
525
- await this.settleBackgroundStatus(task.conversationId);
526
- }
527
- this.broadcaster.broadcastState();
472
+ if (!task)
473
+ return;
474
+ const run = task.agentId === "exec" ? undefined : this.store.snapshot().subagentRuns.find(item => item.id === task.id);
475
+ const output = run ? subagentProgress(run) : task.output;
476
+ await this.finishBackgroundResult(task, {
477
+ status: "cancelled",
478
+ reason: "已由用户手动终止",
479
+ output: output?.slice(-BACKGROUND_LOG_LIMIT),
480
+ outputOffset: task.outputOffset,
481
+ outputTruncated: task.outputTruncated || run?.outputTruncated || (output?.length ?? 0) > BACKGROUND_LOG_LIMIT || run?.toolCalls?.some(call => call.outputTruncated),
482
+ }, false);
528
483
  }
529
484
  hasActiveBackgroundTasks(conversationId) {
530
485
  const tasks = this.store.snapshot().backgroundTasks ?? [];
@@ -793,6 +748,12 @@ export class RunService {
793
748
  const controller = this.activeRuns.get(conversationId);
794
749
  return verifyCapability(conversationId, capability, { running: Boolean(controller && !controller.signal.aborted) });
795
750
  }
751
+ foregroundSignal(conversationId) {
752
+ return this.activeRuns.get(conversationId)?.signal;
753
+ }
754
+ canAdmitBackgroundTask(signal) {
755
+ return !this.shuttingDown && !signal?.aborted;
756
+ }
796
757
  /**
797
758
  * Aborts all active conversation runs and sub-agents.
798
759
  */
@@ -845,7 +806,7 @@ export class RunService {
845
806
  /**
846
807
  * Stops an active turn run for a conversation.
847
808
  */
848
- async stopRun(conversationId) {
809
+ async stopRun(conversationId, options) {
849
810
  // Abort immediately before waiting for the conversation lane; otherwise a stop queued behind a
850
811
  // long streaming command could never reach the controller that it is meant to cancel.
851
812
  const controller = this.activeRuns.get(conversationId);
@@ -854,36 +815,33 @@ export class RunService {
854
815
  // A synchronous task tool can be waiting for its child HTTP response. Stop children and plans
855
816
  // before awaiting the parent's idle promise, otherwise parent and child wait on each other until
856
817
  // the SDK's five-second backstop. Do this before any await so a stale stop cannot reach new work.
857
- this.subagents.stopConversation(conversationId);
858
818
  this.workflows.stopConversation(conversationId);
859
- const bgTasks = (this.store.snapshot().backgroundTasks ?? []).filter(t => t.conversationId === conversationId);
860
- for (const task of bgTasks) {
861
- if (this.execService) {
862
- try {
863
- this.execService.kill(task.id);
864
- }
865
- catch { /* ignore if already exited */ }
866
- }
867
- this.subagents.stop(task.id);
868
- await this.store.removeBackgroundTask(task.id);
819
+ let backgroundStops;
820
+ if (!options?.foregroundOnly) {
821
+ this.subagents.stopConversation(conversationId);
822
+ const tasks = this.store.snapshot().backgroundTasks.filter(task => task.conversationId === conversationId);
823
+ backgroundStops = Promise.allSettled(tasks.map(task => this.stopBackgroundTask(task.id)));
869
824
  }
870
825
  // Cancel human-facing waits BEFORE asking Pi to become idle. A session can be blocked inside an
871
826
  // extension UI bridge or the question tool; Pi's idle promise cannot settle until that wait is
872
827
  // released, so cancelling after `runtime.stop()` turns a click into the full idle backstop.
873
- await this.cancelPendingRunInteractions(conversationId);
828
+ await this.cancelPendingRunInteractions(conversationId, options?.foregroundOnly);
874
829
  // Persisting cancelled question rows yields to other commands. The old turn can finish and a
875
830
  // new one can claim its slot during that await; runtime.stop looks up the CURRENT SDK turn by id,
876
831
  // so calling it unconditionally here would abort the new turn on behalf of the old stop click.
877
832
  if (this.activeRuns.get(conversationId) === controller)
878
833
  await this.runtime.stop?.(conversationId);
879
- return this.serializeConversation(conversationId, () => this.stopRunUnsafe(conversationId, controller));
834
+ await this.serializeConversation(conversationId, () => this.stopRunUnsafe(conversationId, controller, options?.foregroundOnly));
835
+ const failed = (await backgroundStops)?.find(result => result.status === "rejected");
836
+ if (failed)
837
+ throw failed.reason;
880
838
  }
881
839
  /** Releases waits that can prevent Pi's abort from reaching its idle state. Idempotent by design. */
882
- async cancelPendingRunInteractions(conversationId) {
840
+ async cancelPendingRunInteractions(conversationId, foregroundOnly) {
883
841
  this.cancelledQuestionConversations.add(conversationId);
884
842
  this.cancelQuestionWaiters(conversationId);
885
843
  this.memory?.cancel(conversationId);
886
- this.extensionUiService.cancelPendingUi(conversationId, "aborted");
844
+ this.extensionUiService.cancelPendingUi(conversationId, "aborted", foregroundOnly ? {} : undefined);
887
845
  // Read only this conversation. The old full-state snapshot cloned every historical transcript before
888
846
  // the stop could even settle its pending questions.
889
847
  await Promise.all(this.store.pendingQuestions(conversationId).map(async (pending) => {
@@ -898,7 +856,7 @@ export class RunService {
898
856
  }
899
857
  }));
900
858
  }
901
- async stopRunUnsafe(conversationId, expectedController) {
859
+ async stopRunUnsafe(conversationId, expectedController, foregroundOnly) {
902
860
  // A newer turn may have claimed this conversation while the old SDK session was draining. Its
903
861
  // pending question belongs to the new turn and must never be cancelled by the stale stop.
904
862
  // The first cancellation happens at stop arrival, before waiting for Pi idle. Keep this call here
@@ -913,7 +871,7 @@ export class RunService {
913
871
  return;
914
872
  if (expectedController && currentAtEntry && currentAtEntry !== expectedController)
915
873
  return;
916
- await this.cancelPendingRunInteractions(conversationId);
874
+ await this.cancelPendingRunInteractions(conversationId, foregroundOnly);
917
875
  // THE `question` TOOL IS A PENDING ASK THE STOP MUST SETTLE, not a client-only state. Its row only
918
876
  // ever leaves `pending` through the user's `question.answer` command, so a stop used to leave the
919
877
  // ask waiting forever: the extension's HTTP handler never returned, the ask's 250ms full-snapshot
@@ -957,83 +915,12 @@ export class RunService {
957
915
  onPiQueue(conversationId, snapshot) {
958
916
  this.broadcaster.broadcast({ type: "pi.queue", conversationId, ...snapshot });
959
917
  }
960
- /**
961
- * The message a delivery is about, resolved by the text Pi announced.
962
- *
963
- * WHY THE TEXT AND NOT THE POSITION. A message that was STEERED is `sending` here - claimed, so the
964
- * user cannot withdraw it - and the oldest `sending` message is the one Pi picked up, because Pi's
965
- * steering queue is FIFO. That is the old rule and it still holds. A message that was handed to Pi's
966
- * FOLLOW-UP queue is NOT `sending`: Super Pi keeps it in its own list so the user can still withdraw
967
- * it, and a conversation can hold a `waiting` message and a `sending` one at the same time. For that
968
- * one, position is the wrong question and the text is the right one.
969
- *
970
- * THE TEXT IS THE SAME TEXT ON BOTH SIDES. Pi matches its own queue by `indexOf` on the message text
971
- * (`agent-session.ts:1123`), so two messages with identical words are ONE entry to Pi and the first of
972
- * them to Super Pi as well. Resolving by text is therefore not a guess that could pick a different
973
- * message than Pi did - it is the same comparison Pi itself made.
974
- *
975
- * A `sending` message wins over a `waiting` one with the same text, because Pi drains its steering
976
- * queue before its follow-up queue, so the steering message is the one that was delivered first.
977
- */
918
+ /** Ordinary waiting rows belong to Super Pi and cannot be delivered by a Pi event. */
978
919
  matchDeliveredMessage(conversationId, text) {
979
920
  if (!text)
980
921
  return undefined;
981
- const waiting = this.store.listWaitingMessages(conversationId);
982
- const match = waiting.find((item) => item.delivery === "sending" && composePrompt(item) === text)
983
- ?? waiting.find((item) => item.delivery === "waiting" && composePrompt(item) === text);
984
- return match?.id;
985
- }
986
- /**
987
- * Hands a waiting message to Pi's follow-up queue, so the run that is already going answers it.
988
- *
989
- * WHY THIS EXISTS. A message typed while the agent was busy used to wait for the current turn to END
990
- * and then be answered by a turn of its own - a fresh `prompt()`, which runs Pi's `_prepareRun`, which
991
- * emits `before_agent_start`. Super Pi's memory extension answers that hook with an HTTP search and
992
- * patches the system prompt with what came back, so every queued message paid for a round trip to the
993
- * memory endpoint and for a prompt larger than the one before it. A follow-up is delivered by Pi's
994
- * agent loop inside the running turn, so it pays for neither.
995
- *
996
- * IT IS AN OPTIMISATION, NOT A COMMITMENT. The message stays in Super Pi's own waiting list, so it is
997
- * still the user's to withdraw and still the user's to interrupt, and if Pi does not deliver it - the
998
- * run was aborted, the queues were cleared - the message falls back to being answered by a turn of its
999
- * own. Nothing is lost either way, which is what makes it safe to try.
1000
- */
1001
- async submitToPiQueue(conversationId, message) {
1002
- if (!this.runtime.followUp)
1003
- return;
1004
- // NOTHING TO FOLLOW UP ON. With no turn running, Pi would hold the message until the NEXT one,
1005
- // which is a later answer than the one the message is waiting for.
1006
- if (!this.activeRuns.has(conversationId))
1007
- return;
1008
- // A stop has already been requested. The old producer still owns the slot until its `finally`,
1009
- // but handing a follow-up to Pi here would let the dying turn consume it after the user pressed
1010
- // stop. Keep the row in Super Pi's waiting queue; the next turn will pick it up once the slot is
1011
- // genuinely released.
1012
- if (this.isStopping(conversationId))
1013
- return;
1014
- // AN INTERRUPT IS ALREADY STARTING. It aborts the run and empties Pi's queues, so a message handed
1015
- // to Pi now would be taken back a moment later. It waits in the list for the next run, exactly as it
1016
- // did before.
1017
- if (this.interruptTargets.has(conversationId))
1018
- return;
1019
- // The previous run may have taken this row while its persistence promise was still resolving.
1020
- if (!this.store.listWaitingMessages(conversationId).some(item => item.id === message.id && item.delivery === "waiting"))
1021
- return;
1022
- // A MESSAGE THAT IS A COMMAND IS NOT QUEUED. Pi expands a skill command or a prompt template before
1023
- // it queues the text (`agent-session.ts:2221-2222`), and it REFUSES an extension command outright.
1024
- // An expanded text is not the text Super Pi has, so the delivery could not be resolved back to its
1025
- // message - the answer would land under the wrong question. Such a message waits for a turn of its
1026
- // own, where it is the prompt and the question and the answer are the same thing.
1027
- if (composePrompt(message).startsWith("/"))
1028
- return;
1029
- try {
1030
- await this.runtime.followUp(conversationId, composePrompt(message), message.images);
1031
- }
1032
- catch (error) {
1033
- // THE FALLBACK IS THE OLD BEHAVIOUR, so a refusal here is not a failure: the message stays in the
1034
- // waiting list and the run's loop answers it with a turn of its own.
1035
- console.warn(`Super Pi: handing a queued message to Pi's follow-up queue failed: ${error instanceof Error ? error.message : "unknown error"}`);
1036
- }
922
+ return this.store.listWaitingMessages(conversationId)
923
+ .find((item) => item.delivery === "sending" && composePrompt(item) === text)?.id;
1037
924
  }
1038
925
  /**
1039
926
  * Empties Pi's steering and follow-up queues for a conversation.
@@ -1056,7 +943,6 @@ export class RunService {
1056
943
  *
1057
944
  * Remaining steering messages not in `excludeMessageIds` are put back into Pi's steering queue
1058
945
  * in FIFO order (matching at most once per message ID even when two messages share identical text).
1059
- * Remaining follow-up messages stay in Super Pi's waiting list and run after the active turn.
1060
946
  */
1061
947
  async clearPiQueues(conversationId, options) {
1062
948
  const evictedSteerIds = new Set();
@@ -1149,7 +1035,7 @@ export class RunService {
1149
1035
  }
1150
1036
  };
1151
1037
  traceScope("opened");
1152
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
1038
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
1153
1039
  const uiHost = this.extensionUiService.createHost(conversation.id);
1154
1040
  let assistant = assistantMessage;
1155
1041
  let closedOwnScope = false;
@@ -1618,17 +1504,8 @@ export class RunService {
1618
1504
  await this.store.checkpointMessage(conversation.id, previous.id);
1619
1505
  if (!acceptsEvent("steer.delivered"))
1620
1506
  return toolCalls;
1621
- // WHICH MESSAGE THIS DELIVERY IS ABOUT. Pi announces the text it picked up, and Pi itself matches
1622
- // its own queue by that text (`agent-session.ts:1123`), so the same text resolves to the same
1623
- // message on both sides - including when two messages carry identical words, where both sides
1624
- // pick the first. A message handed to Pi's FOLLOW-UP queue was never claimed here: it is still
1625
- // `waiting`, so the user can still withdraw it, and a conversation can hold a `waiting` and a
1626
- // `sending` message at the same time. Position cannot answer that one; the text can.
1627
- //
1628
- // WHEN THE TEXT MATCHES NOTHING the old position-based answer is used, which is the steer path's
1629
- // proven behaviour: the message Pi is holding is the one Pi picked up. A text that matches
1630
- // nothing AND has no `sending` message is a delivery of a message Super Pi no longer has - one
1631
- // the user withdrew - and there is then nothing to open an answer to.
1507
+ // Match explicitly steered messages by text. Pi can expand commands, so an unmatched
1508
+ // event can still correspond to a claimed steer. Waiting rows are never considered.
1632
1509
  const target = this.matchDeliveredMessage(conversation.id, text);
1633
1510
  const delivered = await this.store.deliverWaitingMessage(conversation.id, agentIdentity, target);
1634
1511
  // NOTHING TO DELIVER MEANS NOTHING TO SPLIT. Pi may announce a user `message_start` that this
@@ -1841,29 +1718,29 @@ export class RunService {
1841
1718
  for (;;) {
1842
1719
  if (controller.signal.aborted)
1843
1720
  break;
1844
- // PI'S QUEUES ARE EMPTIED BEFORE THE NEXT MESSAGE IS TAKEN. A message handed to Pi's follow-up
1845
- // queue is delivered by the agent loop inside the run that has just ended - Pi drains that queue
1846
- // before it settles - so whatever is STILL in the queue when the turn ended was not delivered.
1847
- // Emptying it gives those messages back: they are still in the waiting list, and the loop below
1848
- // answers them with a turn of their own, which is the behaviour there was before Pi's queue was
1849
- // used at all. Nothing is lost, and nothing is delivered twice.
1721
+ // Return any undelivered explicit steer to the durable queue before starting another turn.
1850
1722
  await this.clearPiQueues(conversation.id);
1851
1723
  await this.store.releaseSendingMessages(conversation.id);
1852
- // Taken AND opened, in that order, by two separate writes. The take is what bounds this loop -
1853
- // every pass strictly shrinks the waiting set - and it is what makes a crash honest, because a
1854
- // server that dies between the two has a message that is neither waiting nor answered, and the
1855
- // next boot leaves it alone rather than re-sending words Pi may already have seen.
1856
- const next = await this.store.takeNextWaitingMessage(conversation.id);
1724
+ if (controller.signal.aborted)
1725
+ break;
1726
+ const next = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
1857
1727
  if (!next)
1858
1728
  break;
1859
1729
  const current = this.turnContext(conversation.id).conversation;
1860
1730
  await this.assertModelSupportsImages(current, Boolean(next.images?.length), next.id);
1731
+ if (controller.signal.aborted)
1732
+ break;
1733
+ // Preflight can yield to an edit, withdrawal or higher-priority arrival. Open the head
1734
+ // only if it is still first, clearing its delivery flag and adding the reply together.
1735
+ const head = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
1736
+ if (head?.id !== next.id)
1737
+ continue;
1861
1738
  const followUp = await this.store.openTurnOnMessage(conversation.id, next.id, identity);
1862
1739
  this.broadcaster.broadcastState();
1863
1740
  const activeConversation = this.turnContext(conversation.id).conversation;
1864
1741
  // `composePrompt` synthesises the prose for a 后台回传 (the `<task>` envelope is what the transcript
1865
1742
  // column reads from; the prose is what leaves the server for Pi). For user messages it is a no-op.
1866
- await this.streamTurn(activeConversation, workspace, composePrompt(next), followUp.assistant, controller, followUp.user.id, next.images, identity);
1743
+ await this.streamTurn(activeConversation, workspace, composePrompt(followUp.user), followUp.assistant, controller, followUp.user.id, followUp.user.images, identity);
1867
1744
  }
1868
1745
  }
1869
1746
  finally {
@@ -1967,12 +1844,10 @@ export class RunService {
1967
1844
  options?.onAccepted?.(message.id);
1968
1845
  return;
1969
1846
  }
1970
- if (!this.activeRuns.has(conversationId) && !this.interruptTargets.has(conversationId))
1971
- await this.processWaitingMessage(conversationId, message.id);
1972
- else if (deliveryMode === "steer")
1847
+ if (deliveryMode === "steer")
1973
1848
  await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
1974
1849
  else
1975
- await this.submitToPiQueue(conversationId, message);
1850
+ await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
1976
1851
  options?.onAccepted?.(message.id);
1977
1852
  return;
1978
1853
  }
@@ -2008,7 +1883,7 @@ export class RunService {
2008
1883
  finally {
2009
1884
  this.releaseRunSlot(conversation.id, controller);
2010
1885
  if (!this.activeRuns.has(conversation.id))
2011
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
1886
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
2012
1887
  this.broadcaster.broadcastState();
2013
1888
  }
2014
1889
  }
@@ -2079,8 +1954,7 @@ export class RunService {
2079
1954
  // for a turn that had already begun. The state a message is born into is a claim about it, and a claim
2080
1955
  // retracted in the next frame is worse than never making it.
2081
1956
  //
2082
- // An aborted run is unwinding its slot. Wait out that brief cleanup rather than falsely
2083
- // treating it as an active turn and sending this message to a dying follow-up queue.
1957
+ // An aborted run is unwinding its slot and will not drain new waiting messages.
2084
1958
  const active = this.activeRuns.get(conversation.id);
2085
1959
  if (active?.signal.aborted) {
2086
1960
  await this.awaitRunSlotReleased(conversation.id, false);
@@ -2110,20 +1984,14 @@ export class RunService {
2110
1984
  this.broadcaster.broadcastState();
2111
1985
  accepted?.();
2112
1986
  if (!reservedController) {
2113
- // The turn that is running answers this message itself, through Pi's own follow-up queue, rather
2114
- // than by a turn of its own once the running one is over. The message stays in the waiting list
2115
- // either way, so it is still the user's to withdraw - Pi is holding a copy, not the only copy.
1987
+ // The current producer drains ordinary waiting messages one per turn.
2116
1988
  const waiting = this.store.listWaitingMessages(conversationId).find(item => item.id === message.id && item.delivery === "waiting");
2117
1989
  if (!waiting)
2118
1990
  return; // The owner already opened/delivered it while this write was pending.
2119
- if (!this.activeRuns.has(conversationId) && !this.interruptTargets.has(conversationId)) {
2120
- await this.processWaitingMessage(conversationId, message.id);
2121
- }
2122
- else if (deliveryMode === "steer") {
1991
+ if (deliveryMode === "steer")
2123
1992
  await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
2124
- }
2125
1993
  else
2126
- await this.submitToPiQueue(conversationId, message);
1994
+ await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
2127
1995
  return;
2128
1996
  }
2129
1997
  const controller = reservedController;
@@ -2253,7 +2121,7 @@ export class RunService {
2253
2121
  // An old turn can unwind after stop has admitted a new one. Do not cancel the new turn's
2254
2122
  // extension dialog merely because this turn's finally block ran late.
2255
2123
  if (!this.activeRuns.has(conversation.id))
2256
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
2124
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
2257
2125
  this.broadcaster.broadcastState();
2258
2126
  }
2259
2127
  }
@@ -2319,15 +2187,11 @@ export class RunService {
2319
2187
  throw new Error("这条消息已不在等待队列中,无法打断并回答");
2320
2188
  this.interruptTargets.set(conversationId, messageId);
2321
2189
  try {
2322
- // Clear BEFORE abort: Pi can drain follow-ups while the old turn is winding down.
2190
+ // Clear before abort so the old turn cannot drain an explicit steer while winding down.
2323
2191
  await this.clearPiQueues(conversationId);
2324
2192
  if (this.activeRuns.has(conversationId))
2325
- await this.stopRun(conversationId);
2326
- // PI'S QUEUES ARE EMPTIED BEFORE THE SELECTED MESSAGE IS ANSWERED ON ITS OWN. The message may be
2327
- // in Pi's follow-up queue - it was handed over when it was written - and Pi would deliver it when
2328
- // the aborted run ended. The message is about to be answered as a turn of its own, so the queue
2329
- // copy has to go: a message answered twice is worse than one answered once, and the transcript
2330
- // would show the same words under two answers.
2193
+ await this.stopRun(conversationId, { foregroundOnly: true });
2194
+ // Drop any undelivered steers before the selected message claims the next turn.
2331
2195
  await this.clearPiQueues(conversationId);
2332
2196
  await this.awaitRunSlotReleased(conversationId);
2333
2197
  await this.processWaitingMessage(conversationId, messageId);
@@ -2335,15 +2199,14 @@ export class RunService {
2335
2199
  finally {
2336
2200
  if (this.interruptTargets.get(conversationId) === messageId)
2337
2201
  this.interruptTargets.delete(conversationId);
2202
+ this.wakeWaitingBackgroundResult(conversationId);
2338
2203
  }
2339
2204
  }
2340
2205
  /**
2341
2206
  * The lower-level "wait for run slot, open the turn on a specific waiting message, run it" sequence.
2342
2207
  *
2343
- * Called from two places: the user-facing `sendQueued` (which adds a stop-clearing grace window
2344
- * before this) and the auto-trigger paths in `enqueueExecResult` and `dispatchTask`'s background
2345
- * branch (which only call it when `!this.activeRuns.has(conversationId)`). The two callers differ
2346
- * only in who arrived first; the open-turn-and-run contract is the same.
2208
+ * Automatic callers leave the row waiting if another producer owns the conversation.
2209
+ * Explicit actions report a conflict if their selected message cannot start.
2347
2210
  *
2348
2211
  * `runConversationTurns` owns opening the first turn. It must be the ONLY opener: opening here and
2349
2212
  * then asking that loop to run the same message used to splice two assistant placeholders under one
@@ -2352,22 +2215,34 @@ export class RunService {
2352
2215
  * `composePrompt` is what makes the `role: "tool"` path real - the `<task>` envelope stays in the
2353
2216
  * transcript, but the prose form of the same fact is what reaches Pi.
2354
2217
  */
2355
- async processWaitingMessage(conversationId, messageId) {
2218
+ async processWaitingMessage(conversationId, messageId, options) {
2356
2219
  // Serialize only the run claim. Holding the command lane for the entire Pi turn makes every
2357
2220
  // steer/reorder/cancel wait until that turn ends, which is especially visible after a background
2358
2221
  // result auto-starts a long follow-up. The activeRuns slot protects the turn after this lane exits.
2359
2222
  const controller = await this.serializeConversation(conversationId, async () => {
2360
2223
  if (this.shuttingDown)
2361
2224
  return undefined;
2362
- this.assertHistoryAvailable(conversationId);
2363
2225
  const reserved = this.interruptTargets.get(conversationId);
2226
+ const busy = this.activeRuns.has(conversationId);
2227
+ if (options?.ifIdle && (reserved || busy)) {
2228
+ if (options.backgroundResult) {
2229
+ const pending = this.pendingBackgroundWakeups.get(conversationId) ?? new Set();
2230
+ pending.add(messageId);
2231
+ this.pendingBackgroundWakeups.set(conversationId, pending);
2232
+ }
2233
+ return undefined;
2234
+ }
2235
+ this.assertHistoryAvailable(conversationId);
2364
2236
  if (reserved && reserved !== messageId)
2365
2237
  throw new Error("打断回复正在启动,请等待所选消息开始回答");
2366
- if (this.activeRuns.has(conversationId))
2238
+ if (busy)
2367
2239
  throw new Error("当前轮仍在运行;停止或等待它结束后再发送这条消息");
2368
2240
  const message = this.store.listWaitingMessages(conversationId).find((item) => item.id === messageId);
2369
- if (!message || message.delivery !== "waiting")
2241
+ if (!message || message.delivery !== "waiting") {
2242
+ if (options?.ifIdle)
2243
+ return undefined;
2370
2244
  throw new Error("等待中的消息不存在或已被处理");
2245
+ }
2371
2246
  const controller = new AbortController();
2372
2247
  this.cancelledQuestionConversations.delete(conversationId);
2373
2248
  this.claimRunSlot(conversationId, controller);
@@ -2399,7 +2274,7 @@ export class RunService {
2399
2274
  finally {
2400
2275
  this.releaseRunSlot(conversationId, controller);
2401
2276
  if (!this.activeRuns.has(conversationId))
2402
- this.extensionUiService.cancelPendingUi(conversationId, "expired");
2277
+ this.extensionUiService.cancelPendingUi(conversationId, "expired", {});
2403
2278
  this.broadcaster.broadcastState();
2404
2279
  }
2405
2280
  }
@@ -2436,8 +2311,7 @@ export class RunService {
2436
2311
  }
2437
2312
  /**
2438
2313
  * Steers a newly queued message into the running turn at the next turn boundary.
2439
- * Mirrors `dispatchBackgroundResult`'s lock-free fallback if the active run ends before the
2440
- * conversation lane is entered.
2314
+ * Starts a fresh turn if the active run ends before the conversation lane is entered.
2441
2315
  */
2442
2316
  async steerWaitingMessageOnBusyRun(conversationId, messageId) {
2443
2317
  const startWaiting = await this.serializeConversation(conversationId, async () => {
@@ -2474,7 +2348,7 @@ export class RunService {
2474
2348
  }
2475
2349
  });
2476
2350
  if (startWaiting) {
2477
- await this.processWaitingMessage(conversationId, messageId);
2351
+ await this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
2478
2352
  }
2479
2353
  }
2480
2354
  /**
@@ -2640,8 +2514,7 @@ export class RunService {
2640
2514
  // WHERE THE CARD GOES. Resolved once, here, and written onto the record at creation - the run is born
2641
2515
  // knowing where it was asked for, so no later update has to supply it and a card cannot drift.
2642
2516
  const origin = await this.waitForToolCall(conversationId, body.toolCallId);
2643
- const dispatch = this.subagents.dispatch({
2644
- ...(backgroundId ? { id: backgroundId } : {}),
2517
+ const dispatch = {
2645
2518
  conversationId: conversation.id,
2646
2519
  agentId: subagentType,
2647
2520
  task,
@@ -2654,79 +2527,55 @@ export class RunService {
2654
2527
  ...(body.loopId ? { loopId: body.loopId } : {}),
2655
2528
  ...(body.role ? { role: body.role } : {}),
2656
2529
  denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
2657
- // Bind work that arrives during teardown to its original turn, including aborts that happen
2658
- // while tool anchoring, agent lookup or the recorder's initial persistence is still pending.
2659
- signal,
2660
- });
2661
- if (body.background === true) {
2662
- await this.store.setBackgroundTask({
2530
+ };
2531
+ if (!this.canAdmitBackgroundTask(signal))
2532
+ throw new Error("原回合已停止,任务未启动");
2533
+ if (backgroundId) {
2534
+ const taskRecord = {
2663
2535
  id: backgroundId,
2664
- conversationId: conversation.id,
2665
- title: body.description?.trim() || subagentType,
2666
- agentId: subagentType,
2667
- status: "running",
2668
- startedAt: new Date().toISOString(),
2669
- resultBlockId: backgroundId,
2670
- ...(origin ? origin : {}),
2671
- });
2536
+ conversationId, title: body.description?.trim() || subagentType, agentId: subagentType,
2537
+ status: "running", startedAt: new Date().toISOString(), resultBlockId: backgroundId, ...origin,
2538
+ };
2539
+ await this.store.setBackgroundTask(taskRecord);
2540
+ if (!this.canAdmitBackgroundTask(signal) || !this.store.backgroundTask(backgroundId)) {
2541
+ await this.failBackgroundTaskStart(backgroundId, "原回合已停止,任务未启动", true);
2542
+ throw new Error("原回合已停止,任务未启动");
2543
+ }
2672
2544
  this.broadcaster.broadcastState();
2673
- void this.trackDetached(dispatch.then(async (run) => {
2674
- if (run.status === "completed")
2675
- this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
2676
- const result = run.status === "completed" ? run.output ?? "" : `Background task failed: ${run.error ?? run.status}`;
2677
- const tag = run.status === "completed" ? "task_result" : "task_error";
2678
- // A 后台回传 that the agent will actually get to read: same `<task>` envelope the transcript and
2679
- // dock render from, but with `delivery: "waiting"` so it lives in the queue, jumps to the
2680
- // front, and auto-triggers a turn when the conversation is idle. The render side is unchanged -
2681
- // still the 后台回传 column.
2682
- const message = `<task id="${run.id}" state="${run.status === "completed" ? "completed" : "error"}" kind="subagent">\n<summary>Background task ${run.status === "completed" ? "completed" : "failed"}: ${body.description?.trim() || subagentType}</summary>\n<${tag}>\n${result}</${tag}>\n</task>`;
2545
+ // Once admitted, this run owns its controller in the recorder.
2546
+ const settled = (async () => {
2547
+ let run;
2683
2548
  try {
2684
- const queued = await this.serializeConversation(conversation.id, async () => {
2685
- const row = await this.store.addToolMessage(conversation.id, message, { delivery: "waiting" });
2686
- await this.moveAheadOfUnclaimed(conversation.id, row.id);
2687
- this.broadcaster.broadcastState();
2688
- return row;
2689
- });
2690
- if (!signal?.aborted && run.status !== "stopped" && !this.activeRuns.has(conversation.id) && !this.interruptTargets.has(conversation.id)) {
2691
- void this.processWaitingMessage(conversation.id, queued.id).catch(async (error) => {
2692
- console.warn(`Super Pi: auto-trigger for background sub-agent result failed: ${error instanceof Error ? error.message : "unknown error"}`);
2693
- await this.settleBackgroundStatus(conversation.id);
2694
- });
2695
- }
2549
+ run = await this.subagents.dispatch({ id: backgroundId, ...dispatch });
2696
2550
  }
2697
2551
  catch (error) {
2698
- console.warn(`Super Pi: sub-agent result could not be appended as a tool message: ${error instanceof Error ? error.message : "unknown error"}`);
2699
- }
2700
- await this.store.removeBackgroundTask(run.id);
2701
- await this.settleBackgroundStatus(conversation.id);
2702
- this.broadcaster.broadcastState();
2703
- }).catch(async (error) => {
2704
- const message = `<task id="${backgroundId}" state="error" kind="subagent">\n<summary>Background task failed: ${body.description?.trim() || subagentType}</summary>\n<task_error>Background task failed before completion: ${error instanceof Error ? error.message : "unknown error"}</task_error>\n</task>`;
2705
- try {
2706
- await this.serializeConversation(conversationId, async () => {
2707
- const queued = await this.store.addToolMessage(conversationId, message, { delivery: "waiting" });
2708
- await this.moveAheadOfUnclaimed(conversationId, queued.id);
2709
- this.broadcaster.broadcastState();
2710
- });
2711
- // No auto-trigger on this failure branch (the result envelope says `state="error"` and the
2712
- // conversation is by construction not in a turn that asked for it). The row is visible in the
2713
- // dock for the reader to send-now or cancel.
2552
+ await this.finishBackgroundResult(taskRecord, {
2553
+ status: "failed", reason: error instanceof Error ? error.message : String(error),
2554
+ }, true);
2555
+ return;
2714
2556
  }
2715
- catch (innerError) {
2716
- console.warn(`Super Pi: sub-agent failure could not be appended as a tool message: ${innerError instanceof Error ? innerError.message : "unknown error"}`);
2557
+ const cancelled = run.status === "stopped";
2558
+ const status = run.status === "completed" ? "completed" : cancelled
2559
+ ? this.shuttingDown ? "interrupted" : "cancelled" : "failed";
2560
+ const lines = subagentProgress(run);
2561
+ await this.finishBackgroundResult(taskRecord, {
2562
+ status, reason: run.error, output: lines.slice(-BACKGROUND_LOG_LIMIT),
2563
+ outputTruncated: run.outputTruncated || lines.length > BACKGROUND_LOG_LIMIT || run.toolCalls?.some(call => call.outputTruncated),
2564
+ }, !cancelled, run.output ?? run.partialOutput ?? lines);
2565
+ if (run.status === "completed") {
2566
+ const current = this.store.conversation(conversationId);
2567
+ if (current && !current.archivedAt)
2568
+ this.memory?.review(current, { task: body.prompt, result: run.output });
2717
2569
  }
2718
- await this.store.removeBackgroundTask(backgroundId);
2719
- await this.settleBackgroundStatus(conversationId);
2720
- this.broadcaster.broadcastState();
2721
- console.warn(`Super Pi: background sub-agent dispatch failed: ${error instanceof Error ? error.message : "unknown error"}`);
2722
- }));
2570
+ })();
2571
+ void this.trackDetached(settled).catch(error => console.warn("Super Pi: could not record background sub-agent completion:", error));
2723
2572
  return {
2724
2573
  mode: "async",
2725
2574
  status: 202,
2726
2575
  body: { run: { id: backgroundId, status: "running", agentId: subagentType }, background: true },
2727
2576
  };
2728
2577
  }
2729
- const run = await dispatch;
2578
+ const run = await this.subagents.dispatch({ ...dispatch, signal });
2730
2579
  if (run.status === "completed")
2731
2580
  this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
2732
2581
  return {