@evandu/super-pi 0.1.240 → 0.1.242

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 (50) hide show
  1. package/agents/code-auditor.md +52 -0
  2. package/agents/code-designer.md +52 -0
  3. package/agents/document-organizer.md +42 -0
  4. package/agents/solution-designer.md +52 -0
  5. package/agents/super-pi-memory/index.ts +3 -2
  6. package/dist/client/.super-pi-client-sources.json +8 -6
  7. package/dist/client/assets/{CodeMirrorEditor-CQea8mRO.js → CodeMirrorEditor-BXlGF-8I.js} +1 -1
  8. package/dist/client/assets/{GitDiffEditor-DZDcD4zI.js → GitDiffEditor-zWN38BGh.js} +1 -1
  9. package/dist/client/assets/index-BbMji0nU.css +1 -0
  10. package/dist/client/assets/{index-DxjIxdVK.js → index-D8M5Jjzq.js} +32 -25
  11. package/dist/client/index.html +2 -2
  12. package/dist/server/active-memory.d.ts +37 -5
  13. package/dist/server/active-memory.js +191 -10
  14. package/dist/server/agents.d.ts +1 -1
  15. package/dist/server/agents.js +1 -1
  16. package/dist/server/application/extension-ui-service.d.ts +3 -1
  17. package/dist/server/application/extension-ui-service.js +20 -7
  18. package/dist/server/application/group-chat-service.d.ts +55 -0
  19. package/dist/server/application/group-chat-service.js +547 -0
  20. package/dist/server/application/run-service.d.ts +16 -12
  21. package/dist/server/application/run-service.js +203 -158
  22. package/dist/server/application/workspace-service.js +1 -1
  23. package/dist/server/engineering-learning.d.ts +30 -0
  24. package/dist/server/engineering-learning.js +106 -0
  25. package/dist/server/exec-service.d.ts +14 -7
  26. package/dist/server/exec-service.js +66 -40
  27. package/dist/server/http-server.js +63 -7
  28. package/dist/server/index.js +11 -7
  29. package/dist/server/memory-recall.d.ts +16 -1
  30. package/dist/server/memory-recall.js +22 -8
  31. package/dist/server/memory.d.ts +10 -1
  32. package/dist/server/memory.js +11 -6
  33. package/dist/server/runtime.d.ts +12 -12
  34. package/dist/server/runtime.js +68 -11
  35. package/dist/server/server-context.d.ts +1 -0
  36. package/dist/server/store.d.ts +7 -1
  37. package/dist/server/store.js +72 -35
  38. package/dist/server/subagent-runs.d.ts +3 -2
  39. package/dist/server/subagent-runs.js +45 -33
  40. package/dist/server/subagents.d.ts +1 -0
  41. package/dist/server/subagents.js +30 -12
  42. package/dist/server/types.d.ts +13 -11
  43. package/dist/server/ws-server.d.ts +3 -0
  44. package/dist/server/ws-server.js +40 -6
  45. package/dist/shared/background-task.d.ts +22 -0
  46. package/dist/shared/background-task.js +5 -0
  47. package/dist/shared/group-chat.d.ts +62 -0
  48. package/dist/shared/group-chat.js +1 -0
  49. package/package.json +4 -1
  50. package/dist/client/assets/index-BGbZwftQ.css +0 -1
@@ -1,3 +1,4 @@
1
+ import { CODING_STANDARD_REQUEST } from "../active-memory.js";
1
2
  import { SteerUnavailableError } from "../runtime.js";
2
3
  import { checkSubagentDepth, parentDeniedTools, subagentRoster } from "../task-tool.js";
3
4
  import { newSubagentRunId } from "../subagents.js";
@@ -12,11 +13,12 @@ import { toWorkspaceRelative } from "../files.js";
12
13
  import { inScope, refreshWorkspaceIndex } from "../file-index.js";
13
14
  import { resolveSessionCwd } from "../session-cwd.js";
14
15
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
16
+ import { BACKGROUND_LOG_LIMIT, subagentProgress } from "../../shared/background-task.js";
15
17
  import { execFile } from "node:child_process";
16
18
  import { promisify } from "node:util";
17
19
  import { randomUUID } from "node:crypto";
18
- import { isAbsolute, resolve } from "node:path";
19
- import { lstat } from "node:fs/promises";
20
+ import { isAbsolute, join, resolve } from "node:path";
21
+ import { lstat, mkdir, writeFile } from "node:fs/promises";
20
22
  import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
21
23
  const execFileAsync = promisify(execFile);
22
24
  /**
@@ -147,6 +149,9 @@ export class RunService {
147
149
  cancelledQuestionConversations = new Set();
148
150
  memory;
149
151
  setMemory(memory) { this.memory = memory; }
152
+ async recordCodingStandards(conversationId, messageId) {
153
+ return this.memory?.rememberCodingStandards(conversationId, messageId).catch(() => "平台未能保存代码规范,请检查主动记忆设置。");
154
+ }
150
155
  /**
151
156
  * WHAT THE AGENT CHANGED, and what each file looked like before.
152
157
  *
@@ -212,6 +217,7 @@ export class RunService {
212
217
  runCompletions = new Map();
213
218
  /** A selected interrupt owns the next free run slot, even while the old child exits. */
214
219
  interruptTargets = new Map();
220
+ pendingBackgroundWakeups = new Map();
215
221
  shuttingDown = false;
216
222
  /** Preserve incoming background results as waiting messages while the server drains its producers. */
217
223
  beginShutdown() {
@@ -238,6 +244,8 @@ export class RunService {
238
244
  this.activeRuns.delete(conversationId);
239
245
  this.runCompletions.get(conversationId)?.resolve();
240
246
  this.runCompletions.delete(conversationId);
247
+ if (!current.signal.aborted)
248
+ this.wakeWaitingBackgroundResult(conversationId);
241
249
  }
242
250
  /**
243
251
  * WHERE EACH TOOL CALL LANDED, per conversation, for as long as the turn that made it is still running.
@@ -304,7 +312,12 @@ export class RunService {
304
312
  return this.originForToolCall(conversationId, toolCallId);
305
313
  }
306
314
  execService;
307
- setExecService(execService) { this.execService = execService; }
315
+ backgroundLogDirectory;
316
+ execSettlements = new Map();
317
+ setExecService(execService, logDirectory) {
318
+ this.execService = execService;
319
+ this.backgroundLogDirectory = logDirectory;
320
+ }
308
321
  /**
309
322
  * Called by the exec completion handler in index.ts when a background exec session ends.
310
323
  * Injects the result into the conversation and cleans up the background task record.
@@ -315,48 +328,77 @@ export class RunService {
315
328
  * when nothing else is busy. The render stays as a 后台回传 block throughout - in dock and in
316
329
  * transcript - so a `role: "user"` is never impersonated.
317
330
  */
318
- enqueueExecResult(sessionId, exitCode, stdout, stderr) {
319
- const tasks = this.store.snapshot().backgroundTasks;
320
- const task = tasks.find((t) => t.id === sessionId);
331
+ enqueueExecResult(sessionId, exitCode, stdout, stderr, completion) {
332
+ const task = this.store.backgroundTask(sessionId);
321
333
  if (!task)
322
334
  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 });
335
+ const output = (stdout + stderr).slice(-BACKGROUND_LOG_LIMIT);
336
+ const offset = completion?.offset ?? stdout.length + stderr.length;
337
+ const status = completion?.status === "cancelled" || completion?.status === "interrupted"
338
+ ? completion.status : exitCode === 0 && !completion?.signal ? "completed" : "failed";
339
+ const reason = status === "cancelled" ? "已由用户终止"
340
+ : status === "interrupted" ? "服务停止,任务已中断"
341
+ : completion?.signal ? `进程收到信号 ${completion.signal}`
342
+ : status === "failed" ? `Command exited with code ${exitCode}` : undefined;
343
+ const settling = this.trackDetached(this.finishBackgroundResult(task, {
344
+ status, output, outputOffset: offset, outputTruncated: offset > output.length,
345
+ exitCode, signal: completion?.signal, reason,
346
+ }, status === "completed" || status === "failed")).catch(error => {
347
+ console.warn("Super Pi: could not record background command completion:", error);
348
+ }).finally(() => {
349
+ if (this.execSettlements.get(sessionId) === settling)
350
+ this.execSettlements.delete(sessionId);
351
+ });
352
+ this.execSettlements.set(sessionId, settling);
353
+ }
354
+ async failBackgroundTaskStart(taskId, reason, cancelled = false) {
355
+ const task = this.store.backgroundTask(taskId);
356
+ if (task)
357
+ await this.finishBackgroundResult(task, { status: cancelled ? "cancelled" : "failed", reason }, false);
358
+ }
359
+ async finishBackgroundResult(task, outcome, deliver, summary) {
360
+ const queued = await this.serializeConversation(task.conversationId, async () => {
361
+ if (!this.store.backgroundTask(task.id))
362
+ return;
363
+ let logPath;
364
+ if (outcome.output && this.backgroundLogDirectory && /^[A-Za-z0-9_-]+$/u.test(task.id)) {
365
+ try {
366
+ await mkdir(this.backgroundLogDirectory, { recursive: true });
367
+ const path = join(this.backgroundLogDirectory, task.id + ".log");
368
+ await writeFile(path, outcome.output, "utf8");
369
+ logPath = path;
370
+ }
371
+ catch (error) {
372
+ console.warn("Super Pi: could not save background log file:", error);
335
373
  }
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", prioritizeWaiting: true });
342
- this.broadcaster.broadcastState();
343
- return row;
344
- });
345
- // A busy conversation already has a producer that will drain the waiting queue.
346
- void this.trackDetached(this.dispatchBackgroundResult(task.conversationId, queued.id)).catch(async (error) => {
347
- console.warn(`Super Pi: dispatch background exec result failed: ${error instanceof Error ? error.message : "unknown error"}`);
348
- await this.settleBackgroundStatus(task.conversationId);
349
- });
350
- }
351
- catch (error) {
352
- console.warn(`Super Pi: exec result could not be appended as a tool message: ${error instanceof Error ? error.message : "unknown error"}`);
353
- }
354
- finally {
355
- await this.store.removeBackgroundTask(sessionId);
356
- await this.settleBackgroundStatus(task.conversationId);
357
- this.broadcaster.broadcastState();
358
374
  }
359
- })());
375
+ const excerpt = capText(summary ?? outcome.output ?? "", 4000, "后台输出").text.trim();
376
+ const details = [
377
+ outcome.reason,
378
+ outcome.exitCode === undefined ? "" : `退出码:${outcome.exitCode}`,
379
+ excerpt || (!outcome.output ? "本次任务未产生输出。" : ""),
380
+ logPath ? `${outcome.outputTruncated ? "保留的日志尾部" : "日志文件"}:${logPath}` : "",
381
+ ].filter(Boolean).join("\n\n");
382
+ const ok = outcome.status === "completed";
383
+ const tag = ok ? "task_result" : "task_error";
384
+ const kind = task.agentId === "exec" ? "exec" : "subagent";
385
+ const result = `<task id="${task.id}" state="${ok ? "completed" : "error"}" kind="${kind}">\n<summary>${task.title}</summary>\n<${tag}>\n${details}</${tag}>\n</task>`;
386
+ return this.store.finishBackgroundTask(task.id, outcome, result, deliver);
387
+ });
388
+ if (!queued)
389
+ return;
390
+ if (task.agentId === "exec") {
391
+ this.broadcaster.broadcast({ type: "exec.exit", sessionId: task.id, conversationId: task.conversationId, exitCode: outcome.exitCode, stdout: outcome.output ?? "", stderr: "" });
392
+ }
393
+ this.broadcaster.broadcastState();
394
+ if (queued.delivery === "waiting")
395
+ this.startBackgroundResult(task.conversationId, queued.id);
396
+ await this.settleBackgroundStatus(task.conversationId);
397
+ }
398
+ startBackgroundResult(conversationId, messageId) {
399
+ void this.trackDetached(this.dispatchBackgroundResult(conversationId, messageId)).catch(error => {
400
+ console.warn("Super Pi: could not start a background completion turn:", error);
401
+ });
360
402
  }
361
403
  /**
362
404
  * Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
@@ -405,42 +447,43 @@ export class RunService {
405
447
  })());
406
448
  }
407
449
  dispatchBackgroundResult(conversationId, messageId) {
408
- return this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
450
+ return this.processWaitingMessage(conversationId, messageId, { ifIdle: true, backgroundResult: true });
451
+ }
452
+ wakeWaitingBackgroundResult(conversationId) {
453
+ if (this.shuttingDown || this.interruptTargets.has(conversationId) || this.activeRuns.has(conversationId))
454
+ return;
455
+ const pending = this.pendingBackgroundWakeups.get(conversationId);
456
+ if (!pending)
457
+ return;
458
+ const waiting = this.store.listWaitingMessages(conversationId).filter(item => item.delivery === "waiting" && pending.has(item.id));
459
+ const [next, ...remaining] = waiting;
460
+ if (remaining.length)
461
+ this.pendingBackgroundWakeups.set(conversationId, new Set(remaining.map(item => item.id)));
462
+ else
463
+ this.pendingBackgroundWakeups.delete(conversationId);
464
+ if (next)
465
+ this.startBackgroundResult(conversationId, next.id);
409
466
  }
410
- /**
411
- * Stops an active background task (spawned process or detached subagent) on user request.
412
- *
413
- * 1. Kills the underlying PTY child process if one exists in `execService`.
414
- * 2. If the task originated from a tool call in a conversation transcript, marks the tool
415
- * call as failed with a clear message and broadcasts `message.tools`.
416
- * 3. Removes the task from `state.backgroundTasks` and broadcasts `state` so the sidebar
417
- * updates immediately.
418
- */
419
467
  async stopBackgroundTask(taskId) {
420
- const tasks = this.store.snapshot().backgroundTasks ?? [];
421
- const task = tasks.find((t) => t.id === taskId);
422
- if (this.execService) {
423
- try {
424
- this.execService.kill(taskId);
425
- }
426
- catch { /* ignore if already exited */ }
468
+ const task = this.store.backgroundTask(taskId);
469
+ if (task?.agentId === "exec" && await this.execService?.stop?.(taskId)) {
470
+ await this.execSettlements.get(taskId);
471
+ return;
427
472
  }
473
+ if (task?.agentId === "exec")
474
+ this.execService?.kill(taskId);
428
475
  this.subagents.stop(taskId);
429
- if (task && task.originMessageId !== undefined && task.originCallRow !== undefined) {
430
- const conv = this.store.snapshot().conversations.find((c) => c.id === task.conversationId);
431
- const msg = conv?.messages.find((m) => m.id === task.originMessageId);
432
- if (msg?.toolCalls?.[task.originCallRow]?.backgroundTask) {
433
- const toolCalls = await this.store.updateToolCall(task.conversationId, task.originMessageId, task.originCallRow, {
434
- backgroundTask: { id: taskId, status: "failed", output: "已由用户手动终止" },
435
- });
436
- this.broadcaster.broadcast({ type: "message.tools", conversationId: task.conversationId, messageId: task.originMessageId, toolCalls });
437
- }
438
- }
439
- await this.store.removeBackgroundTask(taskId);
440
- if (task?.conversationId) {
441
- await this.settleBackgroundStatus(task.conversationId);
442
- }
443
- this.broadcaster.broadcastState();
476
+ if (!task)
477
+ return;
478
+ const run = task.agentId === "exec" ? undefined : this.store.snapshot().subagentRuns.find(item => item.id === task.id);
479
+ const output = run ? subagentProgress(run) : task.output;
480
+ await this.finishBackgroundResult(task, {
481
+ status: "cancelled",
482
+ reason: "已由用户手动终止",
483
+ output: output?.slice(-BACKGROUND_LOG_LIMIT),
484
+ outputOffset: task.outputOffset,
485
+ outputTruncated: task.outputTruncated || run?.outputTruncated || (output?.length ?? 0) > BACKGROUND_LOG_LIMIT || run?.toolCalls?.some(call => call.outputTruncated),
486
+ }, false);
444
487
  }
445
488
  hasActiveBackgroundTasks(conversationId) {
446
489
  const tasks = this.store.snapshot().backgroundTasks ?? [];
@@ -709,6 +752,12 @@ export class RunService {
709
752
  const controller = this.activeRuns.get(conversationId);
710
753
  return verifyCapability(conversationId, capability, { running: Boolean(controller && !controller.signal.aborted) });
711
754
  }
755
+ foregroundSignal(conversationId) {
756
+ return this.activeRuns.get(conversationId)?.signal;
757
+ }
758
+ canAdmitBackgroundTask(signal) {
759
+ return !this.shuttingDown && !signal?.aborted;
760
+ }
712
761
  /**
713
762
  * Aborts all active conversation runs and sub-agents.
714
763
  */
@@ -761,7 +810,7 @@ export class RunService {
761
810
  /**
762
811
  * Stops an active turn run for a conversation.
763
812
  */
764
- async stopRun(conversationId) {
813
+ async stopRun(conversationId, options) {
765
814
  // Abort immediately before waiting for the conversation lane; otherwise a stop queued behind a
766
815
  // long streaming command could never reach the controller that it is meant to cancel.
767
816
  const controller = this.activeRuns.get(conversationId);
@@ -770,36 +819,33 @@ export class RunService {
770
819
  // A synchronous task tool can be waiting for its child HTTP response. Stop children and plans
771
820
  // before awaiting the parent's idle promise, otherwise parent and child wait on each other until
772
821
  // the SDK's five-second backstop. Do this before any await so a stale stop cannot reach new work.
773
- this.subagents.stopConversation(conversationId);
774
822
  this.workflows.stopConversation(conversationId);
775
- const bgTasks = (this.store.snapshot().backgroundTasks ?? []).filter(t => t.conversationId === conversationId);
776
- for (const task of bgTasks) {
777
- if (this.execService) {
778
- try {
779
- this.execService.kill(task.id);
780
- }
781
- catch { /* ignore if already exited */ }
782
- }
783
- this.subagents.stop(task.id);
784
- await this.store.removeBackgroundTask(task.id);
823
+ let backgroundStops;
824
+ if (!options?.foregroundOnly) {
825
+ this.subagents.stopConversation(conversationId);
826
+ const tasks = this.store.snapshot().backgroundTasks.filter(task => task.conversationId === conversationId);
827
+ backgroundStops = Promise.allSettled(tasks.map(task => this.stopBackgroundTask(task.id)));
785
828
  }
786
829
  // Cancel human-facing waits BEFORE asking Pi to become idle. A session can be blocked inside an
787
830
  // extension UI bridge or the question tool; Pi's idle promise cannot settle until that wait is
788
831
  // released, so cancelling after `runtime.stop()` turns a click into the full idle backstop.
789
- await this.cancelPendingRunInteractions(conversationId);
832
+ await this.cancelPendingRunInteractions(conversationId, options?.foregroundOnly);
790
833
  // Persisting cancelled question rows yields to other commands. The old turn can finish and a
791
834
  // new one can claim its slot during that await; runtime.stop looks up the CURRENT SDK turn by id,
792
835
  // so calling it unconditionally here would abort the new turn on behalf of the old stop click.
793
836
  if (this.activeRuns.get(conversationId) === controller)
794
837
  await this.runtime.stop?.(conversationId);
795
- return this.serializeConversation(conversationId, () => this.stopRunUnsafe(conversationId, controller));
838
+ await this.serializeConversation(conversationId, () => this.stopRunUnsafe(conversationId, controller, options?.foregroundOnly));
839
+ const failed = (await backgroundStops)?.find(result => result.status === "rejected");
840
+ if (failed)
841
+ throw failed.reason;
796
842
  }
797
843
  /** Releases waits that can prevent Pi's abort from reaching its idle state. Idempotent by design. */
798
- async cancelPendingRunInteractions(conversationId) {
844
+ async cancelPendingRunInteractions(conversationId, foregroundOnly) {
799
845
  this.cancelledQuestionConversations.add(conversationId);
800
846
  this.cancelQuestionWaiters(conversationId);
801
847
  this.memory?.cancel(conversationId);
802
- this.extensionUiService.cancelPendingUi(conversationId, "aborted");
848
+ this.extensionUiService.cancelPendingUi(conversationId, "aborted", foregroundOnly ? {} : undefined);
803
849
  // Read only this conversation. The old full-state snapshot cloned every historical transcript before
804
850
  // the stop could even settle its pending questions.
805
851
  await Promise.all(this.store.pendingQuestions(conversationId).map(async (pending) => {
@@ -814,7 +860,7 @@ export class RunService {
814
860
  }
815
861
  }));
816
862
  }
817
- async stopRunUnsafe(conversationId, expectedController) {
863
+ async stopRunUnsafe(conversationId, expectedController, foregroundOnly) {
818
864
  // A newer turn may have claimed this conversation while the old SDK session was draining. Its
819
865
  // pending question belongs to the new turn and must never be cancelled by the stale stop.
820
866
  // The first cancellation happens at stop arrival, before waiting for Pi idle. Keep this call here
@@ -829,7 +875,7 @@ export class RunService {
829
875
  return;
830
876
  if (expectedController && currentAtEntry && currentAtEntry !== expectedController)
831
877
  return;
832
- await this.cancelPendingRunInteractions(conversationId);
878
+ await this.cancelPendingRunInteractions(conversationId, foregroundOnly);
833
879
  // THE `question` TOOL IS A PENDING ASK THE STOP MUST SETTLE, not a client-only state. Its row only
834
880
  // ever leaves `pending` through the user's `question.answer` command, so a stop used to leave the
835
881
  // ask waiting forever: the extension's HTTP handler never returned, the ask's 250ms full-snapshot
@@ -993,9 +1039,10 @@ export class RunService {
993
1039
  }
994
1040
  };
995
1041
  traceScope("opened");
996
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
1042
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
997
1043
  const uiHost = this.extensionUiService.createHost(conversation.id);
998
1044
  let assistant = assistantMessage;
1045
+ let currentUserMessageId = userMessageId;
999
1046
  let closedOwnScope = false;
1000
1047
  let toolCalls = [];
1001
1048
  let pendingTools = Promise.resolve();
@@ -1473,6 +1520,14 @@ export class RunService {
1473
1520
  return toolCalls;
1474
1521
  if (!ownsScope())
1475
1522
  return toolCalls;
1523
+ if (this.memory) {
1524
+ const checkpointed = this.store.conversation(conversation.id);
1525
+ if (checkpointed)
1526
+ this.memory.learnFromTurn(checkpointed, currentUserMessageId, previous.id);
1527
+ }
1528
+ currentUserMessageId = delivered.user.id;
1529
+ if (CODING_STANDARD_REQUEST.test(delivered.user.content))
1530
+ await this.recordCodingStandards(conversation.id, delivered.user.id);
1476
1531
  const next = delivered.assistant;
1477
1532
  this.broadcaster.broadcastState();
1478
1533
  assistant = next;
@@ -1491,6 +1546,11 @@ export class RunService {
1491
1546
  };
1492
1547
  try {
1493
1548
  runCwd = await resolveSessionCwd(workspace.path, conversation.cwd);
1549
+ if (this.memory && CODING_STANDARD_REQUEST.test(prompt) && !controller.signal.aborted) {
1550
+ const result = await this.recordCodingStandards(conversation.id, userMessageId);
1551
+ if (result)
1552
+ prompt += `\n\n[平台记忆操作结果] ${result}`;
1553
+ }
1494
1554
  for await (const delta of this.runtime.answer({
1495
1555
  conversation,
1496
1556
  prompt,
@@ -1655,7 +1715,8 @@ export class RunService {
1655
1715
  if (closedOwnScope && this.activeRuns.get(conversation.id) === controller && !controller.signal.aborted) {
1656
1716
  const completed = this.store.snapshot().conversations.find(c => c.id === conversation.id);
1657
1717
  if (completed)
1658
- await this.memory?.completed(completed).catch(error => console.warn("Super Pi memory scheduling failed:", error));
1718
+ await this.memory?.completed(completed, { userMessageId: currentUserMessageId, assistantMessageId: assistant.id })
1719
+ .catch(error => console.warn("Super Pi memory scheduling failed:", error));
1659
1720
  }
1660
1721
  }
1661
1722
  /**
@@ -1841,7 +1902,7 @@ export class RunService {
1841
1902
  finally {
1842
1903
  this.releaseRunSlot(conversation.id, controller);
1843
1904
  if (!this.activeRuns.has(conversation.id))
1844
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
1905
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
1845
1906
  this.broadcaster.broadcastState();
1846
1907
  }
1847
1908
  }
@@ -2079,7 +2140,7 @@ export class RunService {
2079
2140
  // An old turn can unwind after stop has admitted a new one. Do not cancel the new turn's
2080
2141
  // extension dialog merely because this turn's finally block ran late.
2081
2142
  if (!this.activeRuns.has(conversation.id))
2082
- this.extensionUiService.cancelPendingUi(conversation.id, "expired");
2143
+ this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
2083
2144
  this.broadcaster.broadcastState();
2084
2145
  }
2085
2146
  }
@@ -2148,7 +2209,7 @@ export class RunService {
2148
2209
  // Clear before abort so the old turn cannot drain an explicit steer while winding down.
2149
2210
  await this.clearPiQueues(conversationId);
2150
2211
  if (this.activeRuns.has(conversationId))
2151
- await this.stopRun(conversationId);
2212
+ await this.stopRun(conversationId, { foregroundOnly: true });
2152
2213
  // Drop any undelivered steers before the selected message claims the next turn.
2153
2214
  await this.clearPiQueues(conversationId);
2154
2215
  await this.awaitRunSlotReleased(conversationId);
@@ -2157,6 +2218,7 @@ export class RunService {
2157
2218
  finally {
2158
2219
  if (this.interruptTargets.get(conversationId) === messageId)
2159
2220
  this.interruptTargets.delete(conversationId);
2221
+ this.wakeWaitingBackgroundResult(conversationId);
2160
2222
  }
2161
2223
  }
2162
2224
  /**
@@ -2181,8 +2243,14 @@ export class RunService {
2181
2243
  return undefined;
2182
2244
  const reserved = this.interruptTargets.get(conversationId);
2183
2245
  const busy = this.activeRuns.has(conversationId);
2184
- if (options?.ifIdle && (reserved || busy))
2246
+ if (options?.ifIdle && (reserved || busy)) {
2247
+ if (options.backgroundResult) {
2248
+ const pending = this.pendingBackgroundWakeups.get(conversationId) ?? new Set();
2249
+ pending.add(messageId);
2250
+ this.pendingBackgroundWakeups.set(conversationId, pending);
2251
+ }
2185
2252
  return undefined;
2253
+ }
2186
2254
  this.assertHistoryAvailable(conversationId);
2187
2255
  if (reserved && reserved !== messageId)
2188
2256
  throw new Error("打断回复正在启动,请等待所选消息开始回答");
@@ -2225,7 +2293,7 @@ export class RunService {
2225
2293
  finally {
2226
2294
  this.releaseRunSlot(conversationId, controller);
2227
2295
  if (!this.activeRuns.has(conversationId))
2228
- this.extensionUiService.cancelPendingUi(conversationId, "expired");
2296
+ this.extensionUiService.cancelPendingUi(conversationId, "expired", {});
2229
2297
  this.broadcaster.broadcastState();
2230
2298
  }
2231
2299
  }
@@ -2465,8 +2533,7 @@ export class RunService {
2465
2533
  // WHERE THE CARD GOES. Resolved once, here, and written onto the record at creation - the run is born
2466
2534
  // knowing where it was asked for, so no later update has to supply it and a card cannot drift.
2467
2535
  const origin = await this.waitForToolCall(conversationId, body.toolCallId);
2468
- const dispatch = this.subagents.dispatch({
2469
- ...(backgroundId ? { id: backgroundId } : {}),
2536
+ const dispatch = {
2470
2537
  conversationId: conversation.id,
2471
2538
  agentId: subagentType,
2472
2539
  task,
@@ -2479,77 +2546,55 @@ export class RunService {
2479
2546
  ...(body.loopId ? { loopId: body.loopId } : {}),
2480
2547
  ...(body.role ? { role: body.role } : {}),
2481
2548
  denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
2482
- // Bind work that arrives during teardown to its original turn, including aborts that happen
2483
- // while tool anchoring, agent lookup or the recorder's initial persistence is still pending.
2484
- signal,
2485
- });
2486
- if (body.background === true) {
2487
- await this.store.setBackgroundTask({
2549
+ };
2550
+ if (!this.canAdmitBackgroundTask(signal))
2551
+ throw new Error("原回合已停止,任务未启动");
2552
+ if (backgroundId) {
2553
+ const taskRecord = {
2488
2554
  id: backgroundId,
2489
- conversationId: conversation.id,
2490
- title: body.description?.trim() || subagentType,
2491
- agentId: subagentType,
2492
- status: "running",
2493
- startedAt: new Date().toISOString(),
2494
- resultBlockId: backgroundId,
2495
- ...(origin ? origin : {}),
2496
- });
2555
+ conversationId, title: body.description?.trim() || subagentType, agentId: subagentType,
2556
+ status: "running", startedAt: new Date().toISOString(), resultBlockId: backgroundId, ...origin,
2557
+ };
2558
+ await this.store.setBackgroundTask(taskRecord);
2559
+ if (!this.canAdmitBackgroundTask(signal) || !this.store.backgroundTask(backgroundId)) {
2560
+ await this.failBackgroundTaskStart(backgroundId, "原回合已停止,任务未启动", true);
2561
+ throw new Error("原回合已停止,任务未启动");
2562
+ }
2497
2563
  this.broadcaster.broadcastState();
2498
- void this.trackDetached(dispatch.then(async (run) => {
2499
- if (run.status === "completed")
2500
- this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
2501
- const result = run.status === "completed" ? run.output ?? "" : `Background task failed: ${run.error ?? run.status}`;
2502
- const tag = run.status === "completed" ? "task_result" : "task_error";
2503
- // A 后台回传 that the agent will actually get to read: same `<task>` envelope the transcript and
2504
- // dock render from, but with `delivery: "waiting"` so it lives in the queue, jumps to the
2505
- // front, and auto-triggers a turn when the conversation is idle. The render side is unchanged -
2506
- // still the 后台回传 column.
2507
- 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>`;
2564
+ // Once admitted, this run owns its controller in the recorder.
2565
+ const settled = (async () => {
2566
+ let run;
2508
2567
  try {
2509
- const queued = await this.serializeConversation(conversation.id, async () => {
2510
- const row = await this.store.addToolMessage(conversation.id, message, { delivery: "waiting", prioritizeWaiting: true });
2511
- this.broadcaster.broadcastState();
2512
- return row;
2513
- });
2514
- if (!signal?.aborted && run.status !== "stopped") {
2515
- void this.trackDetached(this.dispatchBackgroundResult(conversation.id, queued.id)).catch(async (error) => {
2516
- console.warn(`Super Pi: auto-trigger for background sub-agent result failed: ${error instanceof Error ? error.message : "unknown error"}`);
2517
- await this.settleBackgroundStatus(conversation.id);
2518
- });
2519
- }
2568
+ run = await this.subagents.dispatch({ id: backgroundId, ...dispatch });
2520
2569
  }
2521
2570
  catch (error) {
2522
- console.warn(`Super Pi: sub-agent result could not be appended as a tool message: ${error instanceof Error ? error.message : "unknown error"}`);
2523
- }
2524
- await this.store.removeBackgroundTask(run.id);
2525
- await this.settleBackgroundStatus(conversation.id);
2526
- this.broadcaster.broadcastState();
2527
- }).catch(async (error) => {
2528
- 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>`;
2529
- try {
2530
- await this.serializeConversation(conversationId, async () => {
2531
- await this.store.addToolMessage(conversationId, message, { delivery: "waiting", prioritizeWaiting: true });
2532
- this.broadcaster.broadcastState();
2533
- });
2534
- // No auto-trigger on this failure branch (the result envelope says `state="error"` and the
2535
- // conversation is by construction not in a turn that asked for it). The row is visible in the
2536
- // dock for the reader to send-now or cancel.
2571
+ await this.finishBackgroundResult(taskRecord, {
2572
+ status: "failed", reason: error instanceof Error ? error.message : String(error),
2573
+ }, true);
2574
+ return;
2537
2575
  }
2538
- catch (innerError) {
2539
- console.warn(`Super Pi: sub-agent failure could not be appended as a tool message: ${innerError instanceof Error ? innerError.message : "unknown error"}`);
2576
+ const cancelled = run.status === "stopped";
2577
+ const status = run.status === "completed" ? "completed" : cancelled
2578
+ ? this.shuttingDown ? "interrupted" : "cancelled" : "failed";
2579
+ const lines = subagentProgress(run);
2580
+ await this.finishBackgroundResult(taskRecord, {
2581
+ status, reason: run.error, output: lines.slice(-BACKGROUND_LOG_LIMIT),
2582
+ outputTruncated: run.outputTruncated || lines.length > BACKGROUND_LOG_LIMIT || run.toolCalls?.some(call => call.outputTruncated),
2583
+ }, !cancelled, run.output ?? run.partialOutput ?? lines);
2584
+ if (run.status === "completed") {
2585
+ const current = this.store.conversation(conversationId);
2586
+ if (current && !current.archivedAt)
2587
+ this.memory?.review(current, { task: body.prompt, result: run.output });
2540
2588
  }
2541
- await this.store.removeBackgroundTask(backgroundId);
2542
- await this.settleBackgroundStatus(conversationId);
2543
- this.broadcaster.broadcastState();
2544
- console.warn(`Super Pi: background sub-agent dispatch failed: ${error instanceof Error ? error.message : "unknown error"}`);
2545
- }));
2589
+ })();
2590
+ void this.trackDetached(settled).catch(error => console.warn("Super Pi: could not record background sub-agent completion:", error));
2546
2591
  return {
2547
2592
  mode: "async",
2548
2593
  status: 202,
2549
2594
  body: { run: { id: backgroundId, status: "running", agentId: subagentType }, background: true },
2550
2595
  };
2551
2596
  }
2552
- const run = await dispatch;
2597
+ const run = await this.subagents.dispatch({ ...dispatch, signal });
2553
2598
  if (run.status === "completed")
2554
2599
  this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
2555
2600
  return {
@@ -51,7 +51,7 @@ export class WorkspaceService {
51
51
  const affected = snapshot.conversations.filter((c) => c.workspaceId === workspaceId);
52
52
  for (const c of affected) {
53
53
  this.extensionUiService.cancelPendingUi(c.id, "aborted");
54
- if (this.runService.isRunning(c.id)) {
54
+ if (this.runService.isRunning(c.id) || snapshot.backgroundTasks.some(task => task.conversationId === c.id)) {
55
55
  await this.runService.stopRun(c.id);
56
56
  }
57
57
  this.runService.stopConversationSubagents(c.id);
@@ -0,0 +1,30 @@
1
+ import type { Message } from "./types.js";
2
+ export declare const ENGINEERING_ROLE_IDS: Set<string>;
3
+ export declare const isEngineeringRole: (id: string | undefined) => boolean;
4
+ export declare const STANDARD_PREFIX = "\u4EE3\u7801\u89C4\u8303\uFF1A";
5
+ export declare const LESSON_PREFIX = "\u5DE5\u7A0B\u9A8C\u8BC1\u7ECF\u9A8C\uFF1A";
6
+ export declare const sensitiveMemoryText: (text: string) => boolean;
7
+ export declare function userProse(text: string): string;
8
+ export declare function isLearningCandidate(userText: string, engineeringRole: boolean): boolean;
9
+ type Check = {
10
+ id: string;
11
+ command: string;
12
+ output: string;
13
+ status: "ok" | "error";
14
+ };
15
+ export type RecoveryEvidence = {
16
+ failed: Check;
17
+ passed: Check;
18
+ };
19
+ export declare function recoveries(messages: Message[], finalAssistantId: string): RecoveryEvidence[];
20
+ export declare function learningResult(text: string, userText: string | undefined, evidence: RecoveryEvidence[]): {
21
+ standards: {
22
+ applicability?: string;
23
+ rule: string;
24
+ }[];
25
+ lesson: {
26
+ rule: string;
27
+ applicability: string;
28
+ } | undefined;
29
+ };
30
+ export {};