@evandu/super-pi 0.1.240 → 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.
- package/dist/client/.super-pi-client-sources.json +5 -5
- package/dist/client/assets/{CodeMirrorEditor-CQea8mRO.js → CodeMirrorEditor-CiOKD-_q.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-DZDcD4zI.js → GitDiffEditor-D5VMi7K-.js} +1 -1
- package/dist/client/assets/index-CwH7sttH.css +1 -0
- package/dist/client/assets/{index-DxjIxdVK.js → index-oUDSLOqG.js} +18 -11
- package/dist/client/index.html +2 -2
- package/dist/server/application/extension-ui-service.d.ts +3 -1
- package/dist/server/application/extension-ui-service.js +20 -7
- package/dist/server/application/run-service.d.ts +15 -12
- package/dist/server/application/run-service.js +183 -157
- package/dist/server/application/workspace-service.js +1 -1
- package/dist/server/exec-service.d.ts +14 -7
- package/dist/server/exec-service.js +66 -40
- package/dist/server/http-server.js +13 -7
- package/dist/server/index.js +6 -6
- package/dist/server/store.d.ts +7 -1
- package/dist/server/store.js +72 -35
- package/dist/server/subagent-runs.d.ts +3 -2
- package/dist/server/subagent-runs.js +45 -33
- package/dist/server/subagents.d.ts +1 -0
- package/dist/server/subagents.js +30 -12
- package/dist/server/types.d.ts +13 -11
- package/dist/server/ws-server.d.ts +3 -0
- package/dist/server/ws-server.js +40 -6
- package/dist/shared/background-task.d.ts +22 -0
- package/dist/shared/background-task.js +5 -0
- package/package.json +1 -1
- package/dist/client/assets/index-BGbZwftQ.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
|
-
|
|
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,48 +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
|
|
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
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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", 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
370
|
}
|
|
359
|
-
|
|
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
|
+
});
|
|
360
398
|
}
|
|
361
399
|
/**
|
|
362
400
|
* Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
|
|
@@ -405,42 +443,43 @@ export class RunService {
|
|
|
405
443
|
})());
|
|
406
444
|
}
|
|
407
445
|
dispatchBackgroundResult(conversationId, messageId) {
|
|
408
|
-
return this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
|
|
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))
|
|
450
|
+
return;
|
|
451
|
+
const pending = this.pendingBackgroundWakeups.get(conversationId);
|
|
452
|
+
if (!pending)
|
|
453
|
+
return;
|
|
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);
|
|
409
462
|
}
|
|
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
463
|
async stopBackgroundTask(taskId) {
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
this.execService.kill(taskId);
|
|
425
|
-
}
|
|
426
|
-
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;
|
|
427
468
|
}
|
|
469
|
+
if (task?.agentId === "exec")
|
|
470
|
+
this.execService?.kill(taskId);
|
|
428
471
|
this.subagents.stop(taskId);
|
|
429
|
-
if (task
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
if (task?.conversationId) {
|
|
441
|
-
await this.settleBackgroundStatus(task.conversationId);
|
|
442
|
-
}
|
|
443
|
-
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);
|
|
444
483
|
}
|
|
445
484
|
hasActiveBackgroundTasks(conversationId) {
|
|
446
485
|
const tasks = this.store.snapshot().backgroundTasks ?? [];
|
|
@@ -709,6 +748,12 @@ export class RunService {
|
|
|
709
748
|
const controller = this.activeRuns.get(conversationId);
|
|
710
749
|
return verifyCapability(conversationId, capability, { running: Boolean(controller && !controller.signal.aborted) });
|
|
711
750
|
}
|
|
751
|
+
foregroundSignal(conversationId) {
|
|
752
|
+
return this.activeRuns.get(conversationId)?.signal;
|
|
753
|
+
}
|
|
754
|
+
canAdmitBackgroundTask(signal) {
|
|
755
|
+
return !this.shuttingDown && !signal?.aborted;
|
|
756
|
+
}
|
|
712
757
|
/**
|
|
713
758
|
* Aborts all active conversation runs and sub-agents.
|
|
714
759
|
*/
|
|
@@ -761,7 +806,7 @@ export class RunService {
|
|
|
761
806
|
/**
|
|
762
807
|
* Stops an active turn run for a conversation.
|
|
763
808
|
*/
|
|
764
|
-
async stopRun(conversationId) {
|
|
809
|
+
async stopRun(conversationId, options) {
|
|
765
810
|
// Abort immediately before waiting for the conversation lane; otherwise a stop queued behind a
|
|
766
811
|
// long streaming command could never reach the controller that it is meant to cancel.
|
|
767
812
|
const controller = this.activeRuns.get(conversationId);
|
|
@@ -770,36 +815,33 @@ export class RunService {
|
|
|
770
815
|
// A synchronous task tool can be waiting for its child HTTP response. Stop children and plans
|
|
771
816
|
// before awaiting the parent's idle promise, otherwise parent and child wait on each other until
|
|
772
817
|
// 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
818
|
this.workflows.stopConversation(conversationId);
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
}
|
|
781
|
-
catch { /* ignore if already exited */ }
|
|
782
|
-
}
|
|
783
|
-
this.subagents.stop(task.id);
|
|
784
|
-
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)));
|
|
785
824
|
}
|
|
786
825
|
// Cancel human-facing waits BEFORE asking Pi to become idle. A session can be blocked inside an
|
|
787
826
|
// extension UI bridge or the question tool; Pi's idle promise cannot settle until that wait is
|
|
788
827
|
// released, so cancelling after `runtime.stop()` turns a click into the full idle backstop.
|
|
789
|
-
await this.cancelPendingRunInteractions(conversationId);
|
|
828
|
+
await this.cancelPendingRunInteractions(conversationId, options?.foregroundOnly);
|
|
790
829
|
// Persisting cancelled question rows yields to other commands. The old turn can finish and a
|
|
791
830
|
// new one can claim its slot during that await; runtime.stop looks up the CURRENT SDK turn by id,
|
|
792
831
|
// so calling it unconditionally here would abort the new turn on behalf of the old stop click.
|
|
793
832
|
if (this.activeRuns.get(conversationId) === controller)
|
|
794
833
|
await this.runtime.stop?.(conversationId);
|
|
795
|
-
|
|
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;
|
|
796
838
|
}
|
|
797
839
|
/** Releases waits that can prevent Pi's abort from reaching its idle state. Idempotent by design. */
|
|
798
|
-
async cancelPendingRunInteractions(conversationId) {
|
|
840
|
+
async cancelPendingRunInteractions(conversationId, foregroundOnly) {
|
|
799
841
|
this.cancelledQuestionConversations.add(conversationId);
|
|
800
842
|
this.cancelQuestionWaiters(conversationId);
|
|
801
843
|
this.memory?.cancel(conversationId);
|
|
802
|
-
this.extensionUiService.cancelPendingUi(conversationId, "aborted");
|
|
844
|
+
this.extensionUiService.cancelPendingUi(conversationId, "aborted", foregroundOnly ? {} : undefined);
|
|
803
845
|
// Read only this conversation. The old full-state snapshot cloned every historical transcript before
|
|
804
846
|
// the stop could even settle its pending questions.
|
|
805
847
|
await Promise.all(this.store.pendingQuestions(conversationId).map(async (pending) => {
|
|
@@ -814,7 +856,7 @@ export class RunService {
|
|
|
814
856
|
}
|
|
815
857
|
}));
|
|
816
858
|
}
|
|
817
|
-
async stopRunUnsafe(conversationId, expectedController) {
|
|
859
|
+
async stopRunUnsafe(conversationId, expectedController, foregroundOnly) {
|
|
818
860
|
// A newer turn may have claimed this conversation while the old SDK session was draining. Its
|
|
819
861
|
// pending question belongs to the new turn and must never be cancelled by the stale stop.
|
|
820
862
|
// The first cancellation happens at stop arrival, before waiting for Pi idle. Keep this call here
|
|
@@ -829,7 +871,7 @@ export class RunService {
|
|
|
829
871
|
return;
|
|
830
872
|
if (expectedController && currentAtEntry && currentAtEntry !== expectedController)
|
|
831
873
|
return;
|
|
832
|
-
await this.cancelPendingRunInteractions(conversationId);
|
|
874
|
+
await this.cancelPendingRunInteractions(conversationId, foregroundOnly);
|
|
833
875
|
// THE `question` TOOL IS A PENDING ASK THE STOP MUST SETTLE, not a client-only state. Its row only
|
|
834
876
|
// ever leaves `pending` through the user's `question.answer` command, so a stop used to leave the
|
|
835
877
|
// ask waiting forever: the extension's HTTP handler never returned, the ask's 250ms full-snapshot
|
|
@@ -993,7 +1035,7 @@ export class RunService {
|
|
|
993
1035
|
}
|
|
994
1036
|
};
|
|
995
1037
|
traceScope("opened");
|
|
996
|
-
this.extensionUiService.cancelPendingUi(conversation.id, "expired");
|
|
1038
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
997
1039
|
const uiHost = this.extensionUiService.createHost(conversation.id);
|
|
998
1040
|
let assistant = assistantMessage;
|
|
999
1041
|
let closedOwnScope = false;
|
|
@@ -1841,7 +1883,7 @@ export class RunService {
|
|
|
1841
1883
|
finally {
|
|
1842
1884
|
this.releaseRunSlot(conversation.id, controller);
|
|
1843
1885
|
if (!this.activeRuns.has(conversation.id))
|
|
1844
|
-
this.extensionUiService.cancelPendingUi(conversation.id, "expired");
|
|
1886
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
1845
1887
|
this.broadcaster.broadcastState();
|
|
1846
1888
|
}
|
|
1847
1889
|
}
|
|
@@ -2079,7 +2121,7 @@ export class RunService {
|
|
|
2079
2121
|
// An old turn can unwind after stop has admitted a new one. Do not cancel the new turn's
|
|
2080
2122
|
// extension dialog merely because this turn's finally block ran late.
|
|
2081
2123
|
if (!this.activeRuns.has(conversation.id))
|
|
2082
|
-
this.extensionUiService.cancelPendingUi(conversation.id, "expired");
|
|
2124
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
2083
2125
|
this.broadcaster.broadcastState();
|
|
2084
2126
|
}
|
|
2085
2127
|
}
|
|
@@ -2148,7 +2190,7 @@ export class RunService {
|
|
|
2148
2190
|
// Clear before abort so the old turn cannot drain an explicit steer while winding down.
|
|
2149
2191
|
await this.clearPiQueues(conversationId);
|
|
2150
2192
|
if (this.activeRuns.has(conversationId))
|
|
2151
|
-
await this.stopRun(conversationId);
|
|
2193
|
+
await this.stopRun(conversationId, { foregroundOnly: true });
|
|
2152
2194
|
// Drop any undelivered steers before the selected message claims the next turn.
|
|
2153
2195
|
await this.clearPiQueues(conversationId);
|
|
2154
2196
|
await this.awaitRunSlotReleased(conversationId);
|
|
@@ -2157,6 +2199,7 @@ export class RunService {
|
|
|
2157
2199
|
finally {
|
|
2158
2200
|
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2159
2201
|
this.interruptTargets.delete(conversationId);
|
|
2202
|
+
this.wakeWaitingBackgroundResult(conversationId);
|
|
2160
2203
|
}
|
|
2161
2204
|
}
|
|
2162
2205
|
/**
|
|
@@ -2181,8 +2224,14 @@ export class RunService {
|
|
|
2181
2224
|
return undefined;
|
|
2182
2225
|
const reserved = this.interruptTargets.get(conversationId);
|
|
2183
2226
|
const busy = this.activeRuns.has(conversationId);
|
|
2184
|
-
if (options?.ifIdle && (reserved || busy))
|
|
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
|
+
}
|
|
2185
2233
|
return undefined;
|
|
2234
|
+
}
|
|
2186
2235
|
this.assertHistoryAvailable(conversationId);
|
|
2187
2236
|
if (reserved && reserved !== messageId)
|
|
2188
2237
|
throw new Error("打断回复正在启动,请等待所选消息开始回答");
|
|
@@ -2225,7 +2274,7 @@ export class RunService {
|
|
|
2225
2274
|
finally {
|
|
2226
2275
|
this.releaseRunSlot(conversationId, controller);
|
|
2227
2276
|
if (!this.activeRuns.has(conversationId))
|
|
2228
|
-
this.extensionUiService.cancelPendingUi(conversationId, "expired");
|
|
2277
|
+
this.extensionUiService.cancelPendingUi(conversationId, "expired", {});
|
|
2229
2278
|
this.broadcaster.broadcastState();
|
|
2230
2279
|
}
|
|
2231
2280
|
}
|
|
@@ -2465,8 +2514,7 @@ export class RunService {
|
|
|
2465
2514
|
// WHERE THE CARD GOES. Resolved once, here, and written onto the record at creation - the run is born
|
|
2466
2515
|
// knowing where it was asked for, so no later update has to supply it and a card cannot drift.
|
|
2467
2516
|
const origin = await this.waitForToolCall(conversationId, body.toolCallId);
|
|
2468
|
-
const dispatch =
|
|
2469
|
-
...(backgroundId ? { id: backgroundId } : {}),
|
|
2517
|
+
const dispatch = {
|
|
2470
2518
|
conversationId: conversation.id,
|
|
2471
2519
|
agentId: subagentType,
|
|
2472
2520
|
task,
|
|
@@ -2479,77 +2527,55 @@ export class RunService {
|
|
|
2479
2527
|
...(body.loopId ? { loopId: body.loopId } : {}),
|
|
2480
2528
|
...(body.role ? { role: body.role } : {}),
|
|
2481
2529
|
denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
await this.store.setBackgroundTask({
|
|
2530
|
+
};
|
|
2531
|
+
if (!this.canAdmitBackgroundTask(signal))
|
|
2532
|
+
throw new Error("原回合已停止,任务未启动");
|
|
2533
|
+
if (backgroundId) {
|
|
2534
|
+
const taskRecord = {
|
|
2488
2535
|
id: backgroundId,
|
|
2489
|
-
conversationId:
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
}
|
|
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
|
+
}
|
|
2497
2544
|
this.broadcaster.broadcastState();
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
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>`;
|
|
2545
|
+
// Once admitted, this run owns its controller in the recorder.
|
|
2546
|
+
const settled = (async () => {
|
|
2547
|
+
let run;
|
|
2508
2548
|
try {
|
|
2509
|
-
|
|
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
|
-
}
|
|
2549
|
+
run = await this.subagents.dispatch({ id: backgroundId, ...dispatch });
|
|
2520
2550
|
}
|
|
2521
2551
|
catch (error) {
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
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.
|
|
2552
|
+
await this.finishBackgroundResult(taskRecord, {
|
|
2553
|
+
status: "failed", reason: error instanceof Error ? error.message : String(error),
|
|
2554
|
+
}, true);
|
|
2555
|
+
return;
|
|
2537
2556
|
}
|
|
2538
|
-
|
|
2539
|
-
|
|
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 });
|
|
2540
2569
|
}
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
this.broadcaster.broadcastState();
|
|
2544
|
-
console.warn(`Super Pi: background sub-agent dispatch failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
2545
|
-
}));
|
|
2570
|
+
})();
|
|
2571
|
+
void this.trackDetached(settled).catch(error => console.warn("Super Pi: could not record background sub-agent completion:", error));
|
|
2546
2572
|
return {
|
|
2547
2573
|
mode: "async",
|
|
2548
2574
|
status: 202,
|
|
2549
2575
|
body: { run: { id: backgroundId, status: "running", agentId: subagentType }, background: true },
|
|
2550
2576
|
};
|
|
2551
2577
|
}
|
|
2552
|
-
const run = await dispatch;
|
|
2578
|
+
const run = await this.subagents.dispatch({ ...dispatch, signal });
|
|
2553
2579
|
if (run.status === "completed")
|
|
2554
2580
|
this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
|
|
2555
2581
|
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);
|
|
@@ -16,14 +16,19 @@ export interface ExecSession {
|
|
|
16
16
|
killed: boolean;
|
|
17
17
|
}
|
|
18
18
|
/** Callback fired when an exec session ends, with the final result. */
|
|
19
|
-
export type
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
export type ExecCompletion = {
|
|
20
|
+
status: "exited" | "cancelled" | "interrupted";
|
|
21
|
+
signal?: number;
|
|
22
|
+
offset: number;
|
|
23
|
+
};
|
|
24
|
+
export type ExecCompleteHandler = (sessionId: string, exitCode: number, stdout: string, stderr: string, completion: ExecCompletion) => void;
|
|
25
|
+
type ExecCheckpoint = (id: string, output: string, offset: number) => Promise<void>;
|
|
22
26
|
export declare class ExecService {
|
|
27
|
+
private readonly onCheckpoint?;
|
|
23
28
|
private readonly sessions;
|
|
24
29
|
private readonly broadcast;
|
|
25
30
|
private readonly onComplete;
|
|
26
|
-
constructor(broadcast: (event: ExecEvent) => void, onComplete: ExecCompleteHandler);
|
|
31
|
+
constructor(broadcast: (event: ExecEvent) => void, onComplete: ExecCompleteHandler, onCheckpoint?: ExecCheckpoint | undefined);
|
|
27
32
|
get status(): {
|
|
28
33
|
enabled: boolean;
|
|
29
34
|
reason?: string;
|
|
@@ -32,7 +37,9 @@ export declare class ExecService {
|
|
|
32
37
|
outputSnapshots(state: Pick<AppState, "conversations" | "backgroundTasks">, scope?: {
|
|
33
38
|
conversationId?: string;
|
|
34
39
|
}): ExecEvent[];
|
|
35
|
-
kill(id: string): void;
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
kill(id: string, cancellation?: "cancelled" | "interrupted"): void;
|
|
41
|
+
stop(id: string, cancellation?: "cancelled" | "interrupted"): Promise<boolean>;
|
|
42
|
+
closeAll(): Promise<void>;
|
|
43
|
+
private finish;
|
|
38
44
|
}
|
|
45
|
+
export {};
|