@evandu/super-pi 0.1.238 → 0.1.240

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.
@@ -8,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-D9r0K1_Y.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DxjIxdVK.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-sDaqj666.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-BGbZwftQ.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -179,14 +179,6 @@ export declare class RunService {
179
179
  resultPath: string;
180
180
  error?: string;
181
181
  }): Promise<void>;
182
- /**
183
- * Dispatches a background result (exec or child session) into the conversation.
184
- *
185
- * IDLE: starts a fresh turn via `processWaitingMessage`.
186
- * BUSY: attempts to steer the message into the running turn so it is delivered at the
187
- * very next tool batch boundary rather than waiting for the entire turn to complete.
188
- * INTERRUPTING: quietly leaves the message waiting; the interrupted or next turn will pick it up.
189
- */
190
182
  private dispatchBackgroundResult;
191
183
  /**
192
184
  * Stops an active background task (spawned process or detached subagent) on user request.
@@ -321,41 +313,8 @@ export declare class RunService {
321
313
  * the moment Pi holds it.
322
314
  */
323
315
  onPiQueue(conversationId: string, snapshot: PiQueueSnapshot): void;
324
- /**
325
- * The message a delivery is about, resolved by the text Pi announced.
326
- *
327
- * WHY THE TEXT AND NOT THE POSITION. A message that was STEERED is `sending` here - claimed, so the
328
- * user cannot withdraw it - and the oldest `sending` message is the one Pi picked up, because Pi's
329
- * steering queue is FIFO. That is the old rule and it still holds. A message that was handed to Pi's
330
- * FOLLOW-UP queue is NOT `sending`: Super Pi keeps it in its own list so the user can still withdraw
331
- * it, and a conversation can hold a `waiting` message and a `sending` one at the same time. For that
332
- * one, position is the wrong question and the text is the right one.
333
- *
334
- * THE TEXT IS THE SAME TEXT ON BOTH SIDES. Pi matches its own queue by `indexOf` on the message text
335
- * (`agent-session.ts:1123`), so two messages with identical words are ONE entry to Pi and the first of
336
- * them to Super Pi as well. Resolving by text is therefore not a guess that could pick a different
337
- * message than Pi did - it is the same comparison Pi itself made.
338
- *
339
- * A `sending` message wins over a `waiting` one with the same text, because Pi drains its steering
340
- * queue before its follow-up queue, so the steering message is the one that was delivered first.
341
- */
316
+ /** Ordinary waiting rows belong to Super Pi and cannot be delivered by a Pi event. */
342
317
  private matchDeliveredMessage;
343
- /**
344
- * Hands a waiting message to Pi's follow-up queue, so the run that is already going answers it.
345
- *
346
- * WHY THIS EXISTS. A message typed while the agent was busy used to wait for the current turn to END
347
- * and then be answered by a turn of its own - a fresh `prompt()`, which runs Pi's `_prepareRun`, which
348
- * emits `before_agent_start`. Super Pi's memory extension answers that hook with an HTTP search and
349
- * patches the system prompt with what came back, so every queued message paid for a round trip to the
350
- * memory endpoint and for a prompt larger than the one before it. A follow-up is delivered by Pi's
351
- * agent loop inside the running turn, so it pays for neither.
352
- *
353
- * IT IS AN OPTIMISATION, NOT A COMMITMENT. The message stays in Super Pi's own waiting list, so it is
354
- * still the user's to withdraw and still the user's to interrupt, and if Pi does not deliver it - the
355
- * run was aborted, the queues were cleared - the message falls back to being answered by a turn of its
356
- * own. Nothing is lost either way, which is what makes it safe to try.
357
- */
358
- private submitToPiQueue;
359
318
  /**
360
319
  * Empties Pi's steering and follow-up queues for a conversation.
361
320
  *
@@ -377,7 +336,6 @@ export declare class RunService {
377
336
  *
378
337
  * Remaining steering messages not in `excludeMessageIds` are put back into Pi's steering queue
379
338
  * in FIFO order (matching at most once per message ID even when two messages share identical text).
380
- * Remaining follow-up messages stay in Super Pi's waiting list and run after the active turn.
381
339
  */
382
340
  private clearPiQueues;
383
341
  /**
@@ -483,10 +441,8 @@ export declare class RunService {
483
441
  /**
484
442
  * The lower-level "wait for run slot, open the turn on a specific waiting message, run it" sequence.
485
443
  *
486
- * Called from two places: the user-facing `sendQueued` (which adds a stop-clearing grace window
487
- * before this) and the auto-trigger paths in `enqueueExecResult` and `dispatchTask`'s background
488
- * branch (which only call it when `!this.activeRuns.has(conversationId)`). The two callers differ
489
- * only in who arrived first; the open-turn-and-run contract is the same.
444
+ * Automatic callers leave the row waiting if another producer owns the conversation.
445
+ * Explicit actions report a conflict if their selected message cannot start.
490
446
  *
491
447
  * `runConversationTurns` owns opening the first turn. It must be the ONLY opener: opening here and
492
448
  * then asking that loop to run the same message used to splice two assistant placeholders under one
@@ -499,8 +455,7 @@ export declare class RunService {
499
455
  private steerUnsafe;
500
456
  /**
501
457
  * Steers a newly queued message into the running turn at the next turn boundary.
502
- * Mirrors `dispatchBackgroundResult`'s lock-free fallback if the active run ends before the
503
- * conversation lane is entered.
458
+ * Starts a fresh turn if the active run ends before the conversation lane is entered.
504
459
  */
505
460
  private steerWaitingMessageOnBusyRun;
506
461
  /**
@@ -338,33 +338,11 @@ export class RunService {
338
338
  // it the message is a transcript entry only and `takeNextWaitingMessage` (which `runConversationTurns`
339
339
  // calls after every turn) never picks it up.
340
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);
341
+ const row = await this.store.addToolMessage(task.conversationId, message, { delivery: "waiting", prioritizeWaiting: true });
344
342
  this.broadcaster.broadcastState();
345
343
  return row;
346
344
  });
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.
345
+ // A busy conversation already has a producer that will drain the waiting queue.
368
346
  void this.trackDetached(this.dispatchBackgroundResult(task.conversationId, queued.id)).catch(async (error) => {
369
347
  console.warn(`Super Pi: dispatch background exec result failed: ${error instanceof Error ? error.message : "unknown error"}`);
370
348
  await this.settleBackgroundStatus(task.conversationId);
@@ -414,8 +392,7 @@ export class RunService {
414
392
  const current = this.store.conversation(parentId);
415
393
  if (!current || current.archivedAt)
416
394
  return undefined;
417
- const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting" });
418
- await this.moveAheadOfUnclaimed(parentId, row.id);
395
+ const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting", prioritizeWaiting: true });
419
396
  await this.store.markConversationReported(input.conversationId);
420
397
  this.broadcaster.broadcastState();
421
398
  return row;
@@ -427,69 +404,8 @@ export class RunService {
427
404
  });
428
405
  })());
429
406
  }
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))
442
- return;
443
- if (!this.activeRuns.has(conversationId)) {
444
- await this.processWaitingMessage(conversationId, messageId);
445
- 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
- }
407
+ dispatchBackgroundResult(conversationId, messageId) {
408
+ return this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
493
409
  }
494
410
  /**
495
411
  * Stops an active background task (spawned process or detached subagent) on user request.
@@ -957,83 +873,12 @@ export class RunService {
957
873
  onPiQueue(conversationId, snapshot) {
958
874
  this.broadcaster.broadcast({ type: "pi.queue", conversationId, ...snapshot });
959
875
  }
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
- */
876
+ /** Ordinary waiting rows belong to Super Pi and cannot be delivered by a Pi event. */
978
877
  matchDeliveredMessage(conversationId, text) {
979
878
  if (!text)
980
879
  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
- }
880
+ return this.store.listWaitingMessages(conversationId)
881
+ .find((item) => item.delivery === "sending" && composePrompt(item) === text)?.id;
1037
882
  }
1038
883
  /**
1039
884
  * Empties Pi's steering and follow-up queues for a conversation.
@@ -1056,7 +901,6 @@ export class RunService {
1056
901
  *
1057
902
  * Remaining steering messages not in `excludeMessageIds` are put back into Pi's steering queue
1058
903
  * 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
904
  */
1061
905
  async clearPiQueues(conversationId, options) {
1062
906
  const evictedSteerIds = new Set();
@@ -1618,17 +1462,8 @@ export class RunService {
1618
1462
  await this.store.checkpointMessage(conversation.id, previous.id);
1619
1463
  if (!acceptsEvent("steer.delivered"))
1620
1464
  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.
1465
+ // Match explicitly steered messages by text. Pi can expand commands, so an unmatched
1466
+ // event can still correspond to a claimed steer. Waiting rows are never considered.
1632
1467
  const target = this.matchDeliveredMessage(conversation.id, text);
1633
1468
  const delivered = await this.store.deliverWaitingMessage(conversation.id, agentIdentity, target);
1634
1469
  // NOTHING TO DELIVER MEANS NOTHING TO SPLIT. Pi may announce a user `message_start` that this
@@ -1841,29 +1676,29 @@ export class RunService {
1841
1676
  for (;;) {
1842
1677
  if (controller.signal.aborted)
1843
1678
  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.
1679
+ // Return any undelivered explicit steer to the durable queue before starting another turn.
1850
1680
  await this.clearPiQueues(conversation.id);
1851
1681
  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);
1682
+ if (controller.signal.aborted)
1683
+ break;
1684
+ const next = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
1857
1685
  if (!next)
1858
1686
  break;
1859
1687
  const current = this.turnContext(conversation.id).conversation;
1860
1688
  await this.assertModelSupportsImages(current, Boolean(next.images?.length), next.id);
1689
+ if (controller.signal.aborted)
1690
+ break;
1691
+ // Preflight can yield to an edit, withdrawal or higher-priority arrival. Open the head
1692
+ // only if it is still first, clearing its delivery flag and adding the reply together.
1693
+ const head = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
1694
+ if (head?.id !== next.id)
1695
+ continue;
1861
1696
  const followUp = await this.store.openTurnOnMessage(conversation.id, next.id, identity);
1862
1697
  this.broadcaster.broadcastState();
1863
1698
  const activeConversation = this.turnContext(conversation.id).conversation;
1864
1699
  // `composePrompt` synthesises the prose for a 后台回传 (the `<task>` envelope is what the transcript
1865
1700
  // 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);
1701
+ await this.streamTurn(activeConversation, workspace, composePrompt(followUp.user), followUp.assistant, controller, followUp.user.id, followUp.user.images, identity);
1867
1702
  }
1868
1703
  }
1869
1704
  finally {
@@ -1967,12 +1802,10 @@ export class RunService {
1967
1802
  options?.onAccepted?.(message.id);
1968
1803
  return;
1969
1804
  }
1970
- if (!this.activeRuns.has(conversationId) && !this.interruptTargets.has(conversationId))
1971
- await this.processWaitingMessage(conversationId, message.id);
1972
- else if (deliveryMode === "steer")
1805
+ if (deliveryMode === "steer")
1973
1806
  await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
1974
1807
  else
1975
- await this.submitToPiQueue(conversationId, message);
1808
+ await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
1976
1809
  options?.onAccepted?.(message.id);
1977
1810
  return;
1978
1811
  }
@@ -2079,8 +1912,7 @@ export class RunService {
2079
1912
  // for a turn that had already begun. The state a message is born into is a claim about it, and a claim
2080
1913
  // retracted in the next frame is worse than never making it.
2081
1914
  //
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.
1915
+ // An aborted run is unwinding its slot and will not drain new waiting messages.
2084
1916
  const active = this.activeRuns.get(conversation.id);
2085
1917
  if (active?.signal.aborted) {
2086
1918
  await this.awaitRunSlotReleased(conversation.id, false);
@@ -2110,20 +1942,14 @@ export class RunService {
2110
1942
  this.broadcaster.broadcastState();
2111
1943
  accepted?.();
2112
1944
  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.
1945
+ // The current producer drains ordinary waiting messages one per turn.
2116
1946
  const waiting = this.store.listWaitingMessages(conversationId).find(item => item.id === message.id && item.delivery === "waiting");
2117
1947
  if (!waiting)
2118
1948
  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") {
1949
+ if (deliveryMode === "steer")
2123
1950
  await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
2124
- }
2125
1951
  else
2126
- await this.submitToPiQueue(conversationId, message);
1952
+ await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
2127
1953
  return;
2128
1954
  }
2129
1955
  const controller = reservedController;
@@ -2319,15 +2145,11 @@ export class RunService {
2319
2145
  throw new Error("这条消息已不在等待队列中,无法打断并回答");
2320
2146
  this.interruptTargets.set(conversationId, messageId);
2321
2147
  try {
2322
- // Clear BEFORE abort: Pi can drain follow-ups while the old turn is winding down.
2148
+ // Clear before abort so the old turn cannot drain an explicit steer while winding down.
2323
2149
  await this.clearPiQueues(conversationId);
2324
2150
  if (this.activeRuns.has(conversationId))
2325
2151
  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.
2152
+ // Drop any undelivered steers before the selected message claims the next turn.
2331
2153
  await this.clearPiQueues(conversationId);
2332
2154
  await this.awaitRunSlotReleased(conversationId);
2333
2155
  await this.processWaitingMessage(conversationId, messageId);
@@ -2340,10 +2162,8 @@ export class RunService {
2340
2162
  /**
2341
2163
  * The lower-level "wait for run slot, open the turn on a specific waiting message, run it" sequence.
2342
2164
  *
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.
2165
+ * Automatic callers leave the row waiting if another producer owns the conversation.
2166
+ * Explicit actions report a conflict if their selected message cannot start.
2347
2167
  *
2348
2168
  * `runConversationTurns` owns opening the first turn. It must be the ONLY opener: opening here and
2349
2169
  * then asking that loop to run the same message used to splice two assistant placeholders under one
@@ -2352,22 +2172,28 @@ export class RunService {
2352
2172
  * `composePrompt` is what makes the `role: "tool"` path real - the `<task>` envelope stays in the
2353
2173
  * transcript, but the prose form of the same fact is what reaches Pi.
2354
2174
  */
2355
- async processWaitingMessage(conversationId, messageId) {
2175
+ async processWaitingMessage(conversationId, messageId, options) {
2356
2176
  // Serialize only the run claim. Holding the command lane for the entire Pi turn makes every
2357
2177
  // steer/reorder/cancel wait until that turn ends, which is especially visible after a background
2358
2178
  // result auto-starts a long follow-up. The activeRuns slot protects the turn after this lane exits.
2359
2179
  const controller = await this.serializeConversation(conversationId, async () => {
2360
2180
  if (this.shuttingDown)
2361
2181
  return undefined;
2362
- this.assertHistoryAvailable(conversationId);
2363
2182
  const reserved = this.interruptTargets.get(conversationId);
2183
+ const busy = this.activeRuns.has(conversationId);
2184
+ if (options?.ifIdle && (reserved || busy))
2185
+ return undefined;
2186
+ this.assertHistoryAvailable(conversationId);
2364
2187
  if (reserved && reserved !== messageId)
2365
2188
  throw new Error("打断回复正在启动,请等待所选消息开始回答");
2366
- if (this.activeRuns.has(conversationId))
2189
+ if (busy)
2367
2190
  throw new Error("当前轮仍在运行;停止或等待它结束后再发送这条消息");
2368
2191
  const message = this.store.listWaitingMessages(conversationId).find((item) => item.id === messageId);
2369
- if (!message || message.delivery !== "waiting")
2192
+ if (!message || message.delivery !== "waiting") {
2193
+ if (options?.ifIdle)
2194
+ return undefined;
2370
2195
  throw new Error("等待中的消息不存在或已被处理");
2196
+ }
2371
2197
  const controller = new AbortController();
2372
2198
  this.cancelledQuestionConversations.delete(conversationId);
2373
2199
  this.claimRunSlot(conversationId, controller);
@@ -2436,8 +2262,7 @@ export class RunService {
2436
2262
  }
2437
2263
  /**
2438
2264
  * 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.
2265
+ * Starts a fresh turn if the active run ends before the conversation lane is entered.
2441
2266
  */
2442
2267
  async steerWaitingMessageOnBusyRun(conversationId, messageId) {
2443
2268
  const startWaiting = await this.serializeConversation(conversationId, async () => {
@@ -2474,7 +2299,7 @@ export class RunService {
2474
2299
  }
2475
2300
  });
2476
2301
  if (startWaiting) {
2477
- await this.processWaitingMessage(conversationId, messageId);
2302
+ await this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
2478
2303
  }
2479
2304
  }
2480
2305
  /**
@@ -2682,13 +2507,12 @@ export class RunService {
2682
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>`;
2683
2508
  try {
2684
2509
  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);
2510
+ const row = await this.store.addToolMessage(conversation.id, message, { delivery: "waiting", prioritizeWaiting: true });
2687
2511
  this.broadcaster.broadcastState();
2688
2512
  return row;
2689
2513
  });
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) => {
2514
+ if (!signal?.aborted && run.status !== "stopped") {
2515
+ void this.trackDetached(this.dispatchBackgroundResult(conversation.id, queued.id)).catch(async (error) => {
2692
2516
  console.warn(`Super Pi: auto-trigger for background sub-agent result failed: ${error instanceof Error ? error.message : "unknown error"}`);
2693
2517
  await this.settleBackgroundStatus(conversation.id);
2694
2518
  });
@@ -2704,8 +2528,7 @@ export class RunService {
2704
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>`;
2705
2529
  try {
2706
2530
  await this.serializeConversation(conversationId, async () => {
2707
- const queued = await this.store.addToolMessage(conversationId, message, { delivery: "waiting" });
2708
- await this.moveAheadOfUnclaimed(conversationId, queued.id);
2531
+ await this.store.addToolMessage(conversationId, message, { delivery: "waiting", prioritizeWaiting: true });
2709
2532
  this.broadcaster.broadcastState();
2710
2533
  });
2711
2534
  // No auto-trigger on this failure branch (the result envelope says `state="error"` and the
@@ -1,42 +1,16 @@
1
- import type { FileIndexSnapshot } from "./file-index.js";
2
- export declare const MAX_CONTENT_RESULTS = 500;
3
- export declare const MAX_CONTENT_FILE_BYTES: number;
4
- export declare const MAX_CONTENT_DEPTH = 12;
5
- export declare const MAX_CONTENT_MS = 10000;
6
- export type ContentSearchCandidate = {
7
- path: string;
8
- kind: "file" | "directory";
9
- text: boolean | null;
10
- size: number | null;
11
- };
12
- export type ContentSearchHit = {
13
- path: string;
14
- name: string;
15
- line: number;
16
- text: string;
17
- };
18
- export type ContentSearchResult = {
19
- hits: ContentSearchHit[];
20
- truncated: boolean;
21
- skipped: string[];
22
- complete: boolean;
23
- reasons: string[];
24
- };
25
- type RipgrepMatch = {
26
- path: string;
27
- line: number;
28
- text: string;
29
- };
30
- type RipgrepRun = (input: {
31
- rgPath: string;
32
- pattern: string;
33
- paths: string[];
34
- signal: AbortSignal;
35
- onMatch: (match: RipgrepMatch) => Promise<boolean>;
36
- }) => Promise<void>;
1
+ import type { ContentSearchHit, ContentSearchSummary } from "../shared/content-search.js";
2
+ export declare const MAX_CONTENT_RESULTS = 20000;
37
3
  export type ContentSearchOptions = {
4
+ include?: string;
5
+ exclude?: string;
6
+ useIgnoreFiles?: boolean;
7
+ signal?: AbortSignal;
8
+ maxResults?: number;
9
+ onHits?: (hits: ContentSearchHit[]) => Promise<void>;
38
10
  resolveRipgrep?: () => Promise<string | undefined>;
39
- runRipgrep?: RipgrepRun;
40
11
  };
41
- export declare function searchByContent(root: string, candidates: readonly ContentSearchCandidate[], query: string, indexStatus?: Pick<FileIndexSnapshot, "complete" | "skipped">, options?: ContentSearchOptions): Promise<ContentSearchResult>;
42
- export {};
12
+ export declare function isProtectedSearchPath(path: string): boolean;
13
+ export declare function searchByContent(root: string, query: string, options?: ContentSearchOptions): Promise<ContentSearchSummary & {
14
+ hits: ContentSearchHit[];
15
+ skipped: string[];
16
+ }>;