@evandu/super-pi 0.1.180 → 0.1.182

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 (42) hide show
  1. package/dist/client/.super-pi-client-sources.json +5 -5
  2. package/dist/client/assets/{CodeMirrorEditor-BdY_vez9.js → CodeMirrorEditor-DUyqaSOB.js} +2 -2
  3. package/dist/client/assets/{dist-BXrWZekq.js → dist-AQ8CYp6b.js} +1 -1
  4. package/dist/client/assets/{dist-CE4F-GnZ.js → dist-Bj218gfa.js} +1 -1
  5. package/dist/client/assets/{dist-tD_cG-sA.js → dist-C7PhA7pe.js} +1 -1
  6. package/dist/client/assets/{dist-Dl22kIFG.js → dist-CB124C6Z.js} +1 -1
  7. package/dist/client/assets/{dist-B_v-qVKZ.js → dist-CNem2r_T.js} +1 -1
  8. package/dist/client/assets/{dist-DjsQFuR8.js → dist-CPmDYAQT.js} +1 -1
  9. package/dist/client/assets/{dist-zNY48I29.js → dist-CU8JEI5K.js} +1 -1
  10. package/dist/client/assets/{dist-C_5fMTu2.js → dist-CeU4Svbh.js} +1 -1
  11. package/dist/client/assets/{dist-DfY4zXbE.js → dist-CkTZUfAR.js} +1 -1
  12. package/dist/client/assets/{dist-CcVJlndc.js → dist-CvLzvDh7.js} +1 -1
  13. package/dist/client/assets/{dist-1AZAH0Vw.js → dist-D3HMZhM-.js} +1 -1
  14. package/dist/client/assets/{dist-BzicsMSL.js → dist-D4lWO1EF.js} +1 -1
  15. package/dist/client/assets/{dist-RxPniecV.js → dist-DLOUy-hB.js} +1 -1
  16. package/dist/client/assets/{dist-BPaSHEMs.js → dist-DTd2PCza.js} +1 -1
  17. package/dist/client/assets/{dist-CxZY8nws.js → dist-Dkm31GRe.js} +1 -1
  18. package/dist/client/assets/{dist-DVYPDnbh.js → dist-Dlg4MpdE.js} +1 -1
  19. package/dist/client/assets/{dist-BXJ0FVm3.js → dist-Dnx8LlEL.js} +1 -1
  20. package/dist/client/assets/{dist-D-AKDchV.js → dist-NLNoAzKl.js} +1 -1
  21. package/dist/client/assets/{dist-Bxp6Lr31.js → dist-TX6Uhfee.js} +1 -1
  22. package/dist/client/assets/{dist-BiQDCO0Z.js → dist-dnyR0Vf6.js} +1 -1
  23. package/dist/client/assets/{dist-XnsZBWBb.js → dist-ka17rnWs.js} +1 -1
  24. package/dist/client/assets/{dist-D7S0Q68i.js → dist-nbHIDjzw.js} +1 -1
  25. package/dist/client/assets/{index-Cy4Cb9zB.js → index-BplDWdZp.js} +15 -15
  26. package/dist/client/assets/{index-DAKtgLA9.css → index-Ui6aXMVV.css} +1 -1
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/application/run-service.d.ts +1 -0
  29. package/dist/server/application/run-service.js +80 -24
  30. package/dist/server/application/session-orchestrator-service.js +4 -2
  31. package/dist/server/command-handler.js +2 -2
  32. package/dist/server/http-server.js +27 -6
  33. package/dist/server/length-continuation.d.ts +33 -0
  34. package/dist/server/length-continuation.js +63 -0
  35. package/dist/server/store.d.ts +2 -0
  36. package/dist/server/store.js +9 -0
  37. package/dist/server/types.d.ts +10 -0
  38. package/dist/server/update.d.ts +33 -0
  39. package/dist/server/update.js +46 -0
  40. package/dist/shared/session-reporting.d.ts +15 -0
  41. package/dist/shared/session-reporting.js +39 -0
  42. package/package.json +5 -1
@@ -8,8 +8,8 @@
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-Cy4Cb9zB.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-DAKtgLA9.css">
11
+ <script type="module" crossorigin src="/assets/index-BplDWdZp.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-Ui6aXMVV.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -86,6 +86,7 @@ export declare class RunService {
86
86
  setNameIndexes(indexes: Map<string, import("../file-name-index.js").FileNameIndex>): void;
87
87
  reviewMemoryBoundary(conversationId: string): void;
88
88
  private readonly activeRuns;
89
+ private readonly lengthContinuations;
89
90
  private readonly turnEventScopes;
90
91
  private readonly historyCutClaims;
91
92
  holdHistoryCut(conversationId: string): void;
@@ -6,7 +6,7 @@ import { verifyCapability } from "../capability.js";
6
6
  import { capText, validateWorkflowPlan, workflowSummary } from "../workflow.js";
7
7
  import { ensureNameIndex, recordWorkspacePath } from "../file-name-index.js";
8
8
  import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
9
- import { isLengthContinuation, lengthContinuationText } from "../length-continuation.js";
9
+ import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
10
10
  import { describeThrownWithStack } from "../failure-text.js";
11
11
  import { toWorkspaceRelative } from "../files.js";
12
12
  import { refreshWorkspaceIndex } from "../file-index.js";
@@ -149,6 +149,7 @@ export class RunService {
149
149
  this.memory?.review(conversation);
150
150
  }
151
151
  activeRuns = new Map();
152
+ lengthContinuations = new Map();
152
153
  turnEventScopes = new Map();
153
154
  historyCutClaims = new Map();
154
155
  holdHistoryCut(conversationId) {
@@ -380,6 +381,7 @@ export class RunService {
380
381
  return undefined;
381
382
  const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting" });
382
383
  await this.moveAheadOfUnclaimed(parentId, row.id);
384
+ await this.store.markConversationReported(input.conversationId);
383
385
  this.broadcaster.broadcastState();
384
386
  return row;
385
387
  });
@@ -1282,12 +1284,15 @@ export class RunService {
1282
1284
  // spends writing its replacement text - and by the time the file path was on screen, the block looked
1283
1285
  // broken rather than early. The placeholder word is now only the FALLBACK for the first fragment, when
1284
1286
  // Pi has not yet said what the call is or what it opens.
1287
+ // 归属在宣布时刻一次性判死:当时 thinking 活着且 answer 还没来,它就永远是 thinking 里的调用
1288
+ const callThinkingBlock = (thinkingActive && !answerAfterThinking) ? thinkingBlock : null;
1285
1289
  enqueueTools("a tool call being prepared", () => this.store.appendToolCall(conversation.id, assistant.id, {
1286
1290
  label: call.name || "工具",
1287
1291
  ...(call.detail ? { detail: call.detail } : { detail: "正在生成参数…" }),
1288
1292
  preparing: true,
1289
1293
  at,
1290
1294
  thinkingAt,
1295
+ thinkingBlock: callThinkingBlock,
1291
1296
  }));
1292
1297
  // `thinkingAt` GOES WITH THE PLACEHOLDER. It is how much reasoning had been written when the
1293
1298
  // model announced this call, and the real call needs it to work out whether the reasoning kept
@@ -1297,7 +1302,16 @@ export class RunService {
1297
1302
  // model announced the call - because that is the only moment the block it belongs to is the
1298
1303
  // OPEN one. By the time the call runs, the reasoning may have ended and a LATER block may have
1299
1304
  // opened, and the index of the block the call belongs to is no longer the current one.
1300
- preparingRows.set(call.contentIndex, { row, name: call.name, thinkingAt, thinkingActive, thinkingBlock: thinkingActive ? thinkingBlock : null });
1305
+ // THE FOLD THIS CALL BELONGS TO, DECIDED AT THE MOMENT THE MODEL ANNOUNCED IT. A call announced
1306
+ // after the answer started belongs to no fold, even when the reasoning is still running.
1307
+ preparingRows.set(call.contentIndex, {
1308
+ row,
1309
+ name: call.name,
1310
+ thinkingAt,
1311
+ thinkingActive,
1312
+ thinkingBlock: callThinkingBlock,
1313
+ at,
1314
+ });
1301
1315
  };
1302
1316
  /**
1303
1317
  * THE AGENT IS ABOUT TO WRITE A FILE.
@@ -1386,13 +1400,31 @@ export class RunService {
1386
1400
  rowByToolCallId.set(call.id, row);
1387
1401
  this.noteToolCallSite(conversation.id, call.id, assistant.id, row);
1388
1402
  }
1389
- // The offset says whether the reasoning grew after this call was initiated. The captured
1390
- // `thinkingActive` flag covers the final-moment case, unless answer text later appeared after
1391
- // thinking_end. That exclusion keeps after-body questions out of the previous reasoning fold.
1392
- const callThinkingBlock = !answerAfterThinking && (prepared[1].thinkingAt < thought || prepared[1].thinkingActive) ? prepared[1].thinkingBlock : null;
1393
- // `at` is corrected to the execution position; `thinkingAt` stays at initiation so calls
1394
- // inside one reasoning block do not all collapse onto the final reasoning offset.
1395
- enqueueTools("a tool call", () => this.store.updateToolCall(conversation.id, assistant.id, row, { label: call.name, detail: call.detail, args: call.args, live: "", preparing: false, at, thinkingBlock: callThinkingBlock, ...(call.question ? { question: call.question } : {}) }));
1403
+ // THE FOLD WAS DECIDED WHEN THE CALL WAS ANNOUNCED, and it stays decided.
1404
+ //
1405
+ // This line used to re-judge the ownership at execution time ("the reasoning had already
1406
+ // stopped AND the answer has started since" - the two-fact rule added in 0.1.181). Two
1407
+ // judgements of one fact is one fact too many: the placeholder row was filed in the fold
1408
+ // when the model announced the call, and this line filed it back outside a moment later.
1409
+ // The reader watched the block JUMP out of the fold and into the answer flow - a wrong
1410
+ // intermediate state, even though the final state was right.
1411
+ //
1412
+ // The rule is the reader's, from 11-09: a call announced before the body text stays in the
1413
+ // block it was announced in. The announcement is the only moment that knows which block that
1414
+ // was, so it is the only moment allowed to decide.
1415
+ const callThinkingBlock = prepared[1].thinkingBlock;
1416
+ // at 也保持宣布时刻的 spoken 偏移,不按执行时刻重算;只有无占位符的调用才用执行时刻的 spoken
1417
+ const callAt = prepared[1].at;
1418
+ enqueueTools("a tool call", () => this.store.updateToolCall(conversation.id, assistant.id, row, {
1419
+ label: call.name,
1420
+ detail: call.detail,
1421
+ args: call.args,
1422
+ live: "",
1423
+ preparing: false,
1424
+ at: callAt,
1425
+ thinkingBlock: callThinkingBlock,
1426
+ ...(call.question ? { question: call.question } : {}),
1427
+ }));
1396
1428
  return;
1397
1429
  }
1398
1430
  const row = rows++;
@@ -1409,7 +1441,11 @@ export class RunService {
1409
1441
  // the reasoning still growing after the call was announced? Here the answer is read from
1410
1442
  // `thinkingActive`, because a call with no placeholder carries no earlier offset to compare.
1411
1443
  const thinkingAt = thought;
1412
- const callThinkingBlock = currentThinkingBlock();
1444
+ // A CALL ANNOUNCED AFTER THE ANSWER BELONGS TO NO FOLD, even when the reasoning is still running.
1445
+ // `currentThinkingBlock()` also marks the thinking as interrupted when it is not active, so it
1446
+ // must NOT be called once the answer has started - that would file an after-answer call between
1447
+ // two stretches of reasoning that were never separated by one.
1448
+ const callThinkingBlock = answerAfterThinking ? null : currentThinkingBlock();
1413
1449
  enqueueTools("a tool call", () => this.store.appendToolCall(conversation.id, assistant.id, { label: call.name, detail: call.detail, args: call.args, at, thinkingAt, thinkingBlock: callThinkingBlock, ...(call.question ? { question: call.question } : {}) }));
1414
1450
  };
1415
1451
  const onToolUpdate = (call) => {
@@ -1618,21 +1654,18 @@ export class RunService {
1618
1654
  await pendingTools;
1619
1655
  if (!acceptsEvent("text.delta"))
1620
1656
  continue;
1621
- // `waiting` → `running` ON THE FIRST DELTA, before the live write. The conversation was
1622
- // opened in `waiting` (see `openTurn` / `openTurnOnSpecificMessage` / `openTurnOnMessage`),
1623
- // and the first response token is the observable fact that says the LLM is actually
1624
- // answering rather than hanging on auth / quota / network. `promoteToRunning` is a no-op
1625
- // after the first signal so this stays a one-shot status write, not a per-token one.
1626
- await promoteToRunning();
1627
1657
  if (!acceptsEvent("text.delta"))
1628
1658
  continue;
1629
- if (!thinkingActive && thinkingBlock >= 0)
1659
+ // THE ANSWER ENDS THE PREVIOUS THINKING STAGE, WHATEVER THE REASONING IS DOING. It used to wait
1660
+ // for `!thinkingActive`, which meant a model that writes text while it is still reasoning never ended
1661
+ // its thinking stage at all - and every call after that text was filed inside the thinking fold.
1662
+ if (thinkingBlock >= 0)
1630
1663
  answerAfterThinking = true;
1631
1664
  this.store.appendAssistantDeltaLive(conversation.id, assistant.id, delta);
1632
1665
  spoken += delta.length;
1633
- // Tool events are structural transcript boundaries. Publish any boundary Pi announced before
1634
- // this text before publishing the text itself; this is a handful of writes per call, never one
1635
- // write per token, and preserves the event order a reconnecting client reconstructs.
1666
+ // Promote to running AFTER the store has received the first delta, so any state
1667
+ // snapshot emitted carries the live delta and does not wipe out client stream bounds.
1668
+ await promoteToRunning();
1636
1669
  this.broadcaster.broadcast({ type: "message.delta", conversationId: conversation.id, messageId: assistant.id, delta });
1637
1670
  scheduleCheckpoint();
1638
1671
  }
@@ -1836,15 +1869,16 @@ export class RunService {
1836
1869
  }
1837
1870
  await this.assertModelSupportsImages(conversation, false, message.id);
1838
1871
  await this.runUntilDrained(conversation, workspace, composePrompt(message), controller, message.id);
1872
+ // Turn completed cleanly without truncation; clear any stale warning and continuation tracking
1873
+ this.lengthContinuations.delete(conversationId);
1874
+ await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
1839
1875
  }
1840
1876
  catch (error) {
1841
1877
  // A TRUNCATED ANSWER IS NOT A DEAD CHILD. The model filled its single-response output budget
1842
1878
  // and stopped mid-sentence; the work it was doing is not over. The conversation goes back to
1843
- // `idle` - usable, not failed - and the truncation is recorded as a WARNING, so the orchestrator
1844
- // above can see that the child needs to be told to carry on rather than reported as broken.
1879
+ // `idle` - usable, not failed - and the error is raised so orchestrators can auto-continue.
1845
1880
  if (isLengthExceededError(error)) {
1846
1881
  await this.store.setStatus(conversation.id, "idle");
1847
- await this.store.setWarningReason(conversationId, formatTurnFailure(error));
1848
1882
  console.warn("Super Pi agent-dispatched turn was truncated by the output limit:", describeThrownWithStack(error));
1849
1883
  throw error;
1850
1884
  }
@@ -1879,6 +1913,10 @@ export class RunService {
1879
1913
  if (clientId && this.store.hasMessage(conversationId, clientId))
1880
1914
  return;
1881
1915
  this.memory?.cancel(conversationId);
1916
+ if (!isLengthContinuation(content)) {
1917
+ this.lengthContinuations.delete(conversationId);
1918
+ await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
1919
+ }
1882
1920
  const trimmed = content.trim();
1883
1921
  const validImages = Array.isArray(images) && images.length > 0 ? images : undefined;
1884
1922
  if (!trimmed && !validImages?.length)
@@ -1989,6 +2027,9 @@ export class RunService {
1989
2027
  throw error;
1990
2028
  }
1991
2029
  await this.runUntilDrained(conversation, workspace, expanded, controller, message.id, validImages);
2030
+ // Turn completed cleanly without truncation; clear any stale warning and continuation tracking
2031
+ this.lengthContinuations.delete(conversationId);
2032
+ await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
1992
2033
  }
1993
2034
  catch (error) {
1994
2035
  // A failing turn needs to be READ AS A FAILING TURN, not just stamped "failed" in a corner no one
@@ -2033,9 +2074,24 @@ export class RunService {
2033
2074
  // send is to offer a retry, which is the wrong move: retrying asks for the same answer again
2034
2075
  // instead of asking for the rest of this one.
2035
2076
  if (isLengthExceededError(error)) {
2077
+ const used = this.lengthContinuations.get(conversation.id) ?? 0;
2078
+ if (used < MAX_LENGTH_CONTINUATIONS && !controller.signal.aborted) {
2079
+ this.lengthContinuations.set(conversation.id, used + 1);
2080
+ console.warn(`Super Pi turn was truncated by output limit (${used + 1}/${MAX_LENGTH_CONTINUATIONS}); auto-continuing silently.`);
2081
+ const lastAssistant = conversation.messages.filter((m) => m.role === "assistant").pop();
2082
+ const continuationPrompt = buildLengthContinuationPrompt(lastAssistant);
2083
+ // Auto continue without exposing warning banner to user
2084
+ queueMicrotask(() => {
2085
+ void this.enqueueAndRunAsAgent(conversation.id, continuationPrompt).catch((contErr) => {
2086
+ console.warn("Super Pi auto-continuation dispatch error:", describeThrownWithStack(contErr));
2087
+ });
2088
+ });
2089
+ return;
2090
+ }
2091
+ this.lengthContinuations.delete(conversation.id);
2036
2092
  await this.store.setStatus(conversation.id, "idle");
2037
2093
  await this.store.setWarningReason(conversation.id, formatTurnFailure(error));
2038
- console.warn("Super Pi turn was truncated by the output limit:", describeThrownWithStack(error));
2094
+ console.warn("Super Pi turn reached maximum continuations after truncation:", describeThrownWithStack(error));
2039
2095
  return;
2040
2096
  }
2041
2097
  await this.store.setStatus(conversation.id, controller.signal.aborted ? "stopped" : "failed");
@@ -4,7 +4,7 @@ import { capText } from "../workflow.js";
4
4
  import { assertSessionCwdInsideWorkspace } from "../session-cwd.js";
5
5
  import { SessionWatchdog } from "./session-watchdog.js";
6
6
  import { isLengthExceededError } from "../turn-failure.js";
7
- import { LENGTH_CONTINUATION_PROMPT } from "../length-continuation.js";
7
+ import { buildLengthContinuationPrompt } from "../length-continuation.js";
8
8
  export const SESSION_OUTPUT_CHAR_LIMIT = 64 * 1024;
9
9
  export const sessionResultRelativePath = (conversationId) => `.super-pi/session-results/${conversationId}.md`;
10
10
  /**
@@ -347,7 +347,9 @@ export class SessionOrchestratorService {
347
347
  // THE ORDER GOES IN AS A SYSTEM MESSAGE, AND THE RUN IS WAITED FOR. The child must be given
348
348
  // the chance to finish before anything is reported to the parent - otherwise the parent would
349
349
  // receive a result that is missing the tail the child was about to write.
350
- await this.runService.enqueueAndRunAsAgent(conversationId, LENGTH_CONTINUATION_PROMPT);
350
+ const lastAssistant = this.store.conversation(conversationId)?.messages.filter((m) => m.role === "assistant").pop();
351
+ const prompt = buildLengthContinuationPrompt(lastAssistant);
352
+ await this.runService.enqueueAndRunAsAgent(conversationId, prompt);
351
353
  await this.runService.waitForConversationIdle(conversationId);
352
354
  }
353
355
  catch (error) {
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { join } from "node:path";
3
3
  import { KNOWN_APIS } from "./providers.js";
4
4
  import { CHILD_SESSION_LOCK_REASON } from "../shared/child-session-lock.js";
5
- import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot } from "./update.js";
5
+ import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
6
6
  /**
7
7
  * Routes client commands to appropriate application services and converts results or errors.
8
8
  */
@@ -455,7 +455,7 @@ export class CommandHandler {
455
455
  throw new Error("更新已经在进行中,请等它结束");
456
456
  const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
457
457
  const update = packageUpdateArgs(this.rootDir ?? import.meta.dirname);
458
- const updater = spawn(npmCmd, update.args, { stdio: "inherit", shell: process.platform === "win32", env: process.env });
458
+ const updater = spawn(npmCmd, shellArgs(update.args), { stdio: "inherit", shell: process.platform === "win32", env: process.env });
459
459
  // EXACTLY ONE RELEASE PER CHILD, for the same reason the HTTP endpoint does it: a spawn that
460
460
  // fails emits "error" and then "close", and releasing twice would free the slot out from
461
461
  // under an update that had already claimed it.
@@ -21,7 +21,7 @@ import { MAX_DOCUMENT_REQUEST_BYTES } from "./application/document-service.js";
21
21
  import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
22
22
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
23
23
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
24
- import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot } from "./update.js";
24
+ import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
25
25
  import { FileIndex } from "./file-index.js";
26
26
  import { ensureNameIndex, recordWorkspacePath } from "./file-name-index.js";
27
27
  import { resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
@@ -1044,7 +1044,10 @@ export function createHttpServer(options) {
1044
1044
  };
1045
1045
  // RESTART ONLY: the code on disk is already new, the running server is not. Re-downloading
1046
1046
  // 32.8 MB to restart a process is waste; the second button asks for exactly this.
1047
+ // The outcome is recorded here as well: from the client's point of view a restart is the
1048
+ // end of the update it started, and it needs to be able to say so.
1047
1049
  if (restartOnly) {
1050
+ recordUpdateOutcome(true);
1048
1051
  release();
1049
1052
  restartNow();
1050
1053
  return;
@@ -1053,18 +1056,28 @@ export function createHttpServer(options) {
1053
1056
  // npm's exit code correctly reflects whether the update succeeded.
1054
1057
  const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1055
1058
  const update = packageUpdateArgs(rootDir, wantedVersion);
1056
- const child = spawn(npmCmd, update.args, { stdio: "ignore", shell: process.platform === "win32", env: process.env });
1059
+ const child = spawn(npmCmd, shellArgs(update.args), { stdio: "ignore", shell: process.platform === "win32", env: process.env });
1060
+ // A SPAWN THAT NEVER STARTED. Node emits "error" and THEN "close" with a null code, so
1061
+ // without this flag the close handler would read that null as a finished install and tell
1062
+ // the user the update worked when npm never ran at all.
1063
+ let spawnFailed = false;
1057
1064
  child.on("close", (code) => {
1058
- release();
1059
- if (code === 0 || code === null) {
1065
+ // THE OUTCOME IS RECORDED BEFORE THE SLOT IS RELEASED. If the slot were released first,
1066
+ // a client polling at that exact moment would see "not updating" with no outcome
1067
+ // recorded and could not tell whether the install had worked.
1068
+ if (code === 0 || (code === null && !spawnFailed)) {
1069
+ recordUpdateOutcome(true);
1070
+ release();
1060
1071
  console.log("Super Pi: npm install completed, triggering restart.");
1061
1072
  restartNow();
1062
1073
  }
1063
1074
  else {
1075
+ recordUpdateOutcome(false, typeof code === "number" ? code : undefined);
1076
+ release();
1064
1077
  console.error(`Super Pi: npm install failed with code ${code}`);
1065
1078
  }
1066
1079
  });
1067
- child.on("error", (error) => { release(); console.warn(`Super Pi: update spawn failed: ${error instanceof Error ? error.message : "unknown error"}`); });
1080
+ child.on("error", (error) => { spawnFailed = true; recordUpdateOutcome(false); release(); console.warn(`Super Pi: update spawn failed: ${error instanceof Error ? error.message : "unknown error"}`); });
1068
1081
  child.unref();
1069
1082
  return;
1070
1083
  }
@@ -1075,6 +1088,14 @@ export function createHttpServer(options) {
1075
1088
  }
1076
1089
  try {
1077
1090
  const current = checkDiskVersion(rootDir);
1091
+ // AN UPDATE IS RUNNING, so the registry question is not worth asking. The client polls
1092
+ // this endpoint every two seconds while it waits for the install to finish, and npm's
1093
+ // registry does not need one machine to ask it for the latest version a hundred times a
1094
+ // minute. While the slot is held the answer is already known, so it is answered here.
1095
+ if (isUpdateInFlight()) {
1096
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ ...current, updating: true, lastUpdate: getLastUpdateOutcome() ?? null, updateAvailable: false }));
1097
+ return;
1098
+ }
1078
1099
  // Query the npm registry for the latest @evandu/super-pi version.
1079
1100
  const remoteVersion = await fetch("https://registry.npmjs.org/@evandu/super-pi/latest").then(async (result) => {
1080
1101
  if (!result.ok)
@@ -1082,7 +1103,7 @@ export function createHttpServer(options) {
1082
1103
  return result.json();
1083
1104
  });
1084
1105
  const latestVersion = typeof remoteVersion.version === "string" ? remoteVersion.version : undefined;
1085
- response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ ...current, latestVersion, updateAvailable: Boolean(latestVersion && latestVersion !== current.diskVersion) }));
1106
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ ...current, latestVersion, updateAvailable: Boolean(latestVersion && latestVersion !== current.diskVersion), updating: isUpdateInFlight(), lastUpdate: getLastUpdateOutcome() ?? null }));
1086
1107
  }
1087
1108
  catch (error) {
1088
1109
  response.writeHead(502, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
@@ -24,6 +24,10 @@
24
24
  * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
25
  */
26
26
  export declare const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
27
+ /**
28
+ * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
+ */
30
+ export declare const MAX_LENGTH_CONTINUATIONS = 3;
27
31
  /**
28
32
  * THE TEXT THE MODEL IS GIVEN.
29
33
  *
@@ -40,6 +44,35 @@ export declare const LENGTH_CONTINUATION_TEXT = "\u4E0A\u4E00\u6761\u56DE\u7B54\
40
44
  * the instruction rather than the markup.
41
45
  */
42
46
  export declare const LENGTH_CONTINUATION_PROMPT = "<continue_output>\u4E0A\u4E00\u6761\u56DE\u7B54\u56E0\u4E3A\u8FBE\u5230\u5355\u6B21\u8F93\u51FA\u7684\u957F\u5EA6\u4E0A\u9650\u88AB\u622A\u65AD\u4E86\u3002\u8BF7\u76F4\u63A5\u4ECE\u88AB\u622A\u65AD\u7684\u5730\u65B9\u63A5\u7740\u5199\u5B8C\uFF0C\u4E0D\u8981\u91CD\u590D\u5DF2\u7ECF\u5199\u8FC7\u7684\u5185\u5BB9\u3002</continue_output>";
47
+ /**
48
+ * Extracts the tail anchor text from truncated assistant content.
49
+ */
50
+ export declare function extractContinuationAnchor(text: string, maxLen?: number): string;
51
+ /**
52
+ * Checks whether text ends inside an unclosed code block (odd number of ```).
53
+ */
54
+ export declare function hasUnclosedCodeBlock(text: string): boolean;
55
+ /**
56
+ * Checks whether text ends inside an unclosed thinking block (<think> without </think>).
57
+ */
58
+ export declare function hasUnclosedThinking(text: string): boolean;
59
+ /**
60
+ * Constructs an intelligent continuation order tailored to the truncation context.
61
+ *
62
+ * When an anchor is available, pointing at the exact cut-off text gives the model an attention
63
+ * anchor and prevents it from freezing or emitting a single polite word.
64
+ */
65
+ export declare function buildLengthContinuationText(assistant?: {
66
+ content?: unknown;
67
+ toolCalls?: unknown[];
68
+ }): string;
69
+ /**
70
+ * Builds the full enclosed continuation prompt with envelope.
71
+ */
72
+ export declare function buildLengthContinuationPrompt(assistant?: {
73
+ content?: unknown;
74
+ toolCalls?: unknown[];
75
+ }): string;
43
76
  /**
44
77
  * Whether this content is a continuation order.
45
78
  */
@@ -24,6 +24,10 @@
24
24
  * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
25
  */
26
26
  export const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
27
+ /**
28
+ * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
+ */
30
+ export const MAX_LENGTH_CONTINUATIONS = 3;
27
31
  /**
28
32
  * THE TEXT THE MODEL IS GIVEN.
29
33
  *
@@ -40,6 +44,65 @@ export const LENGTH_CONTINUATION_TEXT = "上一条回答因为达到单次输出
40
44
  * the instruction rather than the markup.
41
45
  */
42
46
  export const LENGTH_CONTINUATION_PROMPT = `<${LENGTH_CONTINUATION_ENVELOPE}>${LENGTH_CONTINUATION_TEXT}</${LENGTH_CONTINUATION_ENVELOPE}>`;
47
+ /**
48
+ * Extracts the tail anchor text from truncated assistant content.
49
+ */
50
+ export function extractContinuationAnchor(text, maxLen = 60) {
51
+ const clean = text.trimEnd();
52
+ if (!clean)
53
+ return "";
54
+ if (clean.length <= maxLen)
55
+ return clean;
56
+ return clean.slice(-maxLen).trimStart();
57
+ }
58
+ /**
59
+ * Checks whether text ends inside an unclosed code block (odd number of ```).
60
+ */
61
+ export function hasUnclosedCodeBlock(text) {
62
+ const matches = text.match(/```/g);
63
+ return Boolean(matches && matches.length % 2 === 1);
64
+ }
65
+ /**
66
+ * Checks whether text ends inside an unclosed thinking block (<think> without </think>).
67
+ */
68
+ export function hasUnclosedThinking(text) {
69
+ const opens = (text.match(/<think>/g) || []).length;
70
+ const closes = (text.match(/<\/think>/g) || []).length;
71
+ return opens > closes;
72
+ }
73
+ /**
74
+ * Constructs an intelligent continuation order tailored to the truncation context.
75
+ *
76
+ * When an anchor is available, pointing at the exact cut-off text gives the model an attention
77
+ * anchor and prevents it from freezing or emitting a single polite word.
78
+ */
79
+ export function buildLengthContinuationText(assistant) {
80
+ if (!assistant)
81
+ return LENGTH_CONTINUATION_TEXT;
82
+ // Case 1: truncation happened inside tool call arguments
83
+ if (Array.isArray(assistant.toolCalls) && assistant.toolCalls.length > 0) {
84
+ const rawContent = typeof assistant.content === "string" ? assistant.content.trim() : "";
85
+ if (!rawContent || rawContent.length < 20) {
86
+ return "上一次工具调用因参数超出单次长度上限未完整执行。请将写入或修改操作拆分为更小的批次(如使用分块写入或局部编辑模式)重新发起调用。";
87
+ }
88
+ }
89
+ // Case 2: textual output
90
+ const content = typeof assistant.content === "string" ? assistant.content : "";
91
+ const anchor = extractContinuationAnchor(content);
92
+ if (!anchor)
93
+ return LENGTH_CONTINUATION_TEXT;
94
+ if (hasUnclosedCodeBlock(content)) {
95
+ return `上一条代码因为达到单次输出上限在以下断点处被截断:\n\`\`\`\n${anchor}\n\`\`\`\n请直接紧接上述断点继续写完后续代码并闭合代码块,严禁寒暄,不要重复断点之前已经写过的代码。`;
96
+ }
97
+ return `上一条回答因为达到单次输出上限在以下内容处被截断:\n"${anchor}"\n请直接紧接上述断点继续写完,严禁客套寒暄,不要重复断点之前的内容。`;
98
+ }
99
+ /**
100
+ * Builds the full enclosed continuation prompt with envelope.
101
+ */
102
+ export function buildLengthContinuationPrompt(assistant) {
103
+ const text = buildLengthContinuationText(assistant);
104
+ return `<${LENGTH_CONTINUATION_ENVELOPE}>${text}</${LENGTH_CONTINUATION_ENVELOPE}>`;
105
+ }
43
106
  /**
44
107
  * Whether this content is a continuation order.
45
108
  */
@@ -679,6 +679,8 @@ export declare class Store {
679
679
  setMessagePiEntryId(conversationId: string, messageId: string, piEntryId: string): Promise<void>;
680
680
  /** Cache a locator Pi itself resolved while serving this conversation; never trust it as authorization. */
681
681
  setConversationPiSessionFile(conversationId: string, path: string): Promise<void>;
682
+ /** Records that a child conversation has reported its result/progress to its parent. */
683
+ markConversationReported(conversationId: string, timestamp?: string): Promise<Conversation | undefined>;
682
684
  /**
683
685
  * Reverts the conversation to the state right after `messageId`, in `state.json` only.
684
686
  *
@@ -2148,6 +2148,15 @@ export class Store {
2148
2148
  conversation.piSessionFile = path;
2149
2149
  await this.persistMetadata(conversationId);
2150
2150
  }
2151
+ /** Records that a child conversation has reported its result/progress to its parent. */
2152
+ async markConversationReported(conversationId, timestamp) {
2153
+ const target = this.state.conversations.find((c) => c.id === conversationId);
2154
+ if (!target)
2155
+ return undefined;
2156
+ target.reportedToParentAt = timestamp || now();
2157
+ await this.persistMetadata(conversationId);
2158
+ return target;
2159
+ }
2151
2160
  /**
2152
2161
  * Reverts the conversation to the state right after `messageId`, in `state.json` only.
2153
2162
  *
@@ -559,6 +559,16 @@ export type Conversation = {
559
559
  * recorded simply means "top level", which is what those conversations genuinely are.
560
560
  */
561
561
  parentConversationId?: string;
562
+ /**
563
+ * 上次向父会话汇报的时间戳(ISO 字符串)。仅子会话有意义。
564
+ * 初始为空;父会话通过工具/转述/完成读取该子会话后写入。
565
+ * 只要本字段存在,子会话就在汇报轴上算「已汇报」。
566
+ */
567
+ reportedToParentAt?: string;
568
+ /**
569
+ * 用户上次点击阅读该会话的时间戳(ISO 字符串)。
570
+ * 顶层会话退回到根据这个判断未读;子会话不看这个。
571
+ */
562
572
  /** Stable memory-sharing identity, inherited at birth; forks start a new tree. */
563
573
  treeId?: string;
564
574
  /**
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Quote an argument for a shell on Windows.
3
+ *
4
+ * WHY THIS EXISTS. Node runs `spawn("npm.cmd", args, { shell: true })` by CONCATENATING the
5
+ * arguments into one command line - it does not escape them (Node's own DEP0190 warning says
6
+ * exactly that). So an argument with a space in it arrives at npm in pieces: measured, a
7
+ * `--prefix "C:\\Users\\Some Name\\npm"` reached npm as `C:\\Users\\Some Name` and npm
8
+ * answered `ENOENT ... lstat ... path C:\\Users\\Some`.
9
+ *
10
+ * The npm prefix is wherever the user's npm lives, so on a machine whose home directory has a
11
+ * space in it the update - and the CLI's update - would fail with a path that looks truncated.
12
+ * Quoting here is what makes the argument survive.
13
+ */
14
+ export declare function quoteForShell(value: string): string;
15
+ /** The arguments to hand to npm, quoted for the shell when the shell is what runs them. */
16
+ export declare function shellArgs(args: string[]): string[];
1
17
  /**
2
18
  * Return npm's install arguments for the package that is actually running.
3
19
  *
@@ -25,3 +41,20 @@ export declare function packageUpdateArgs(rootDir: string, version?: string): {
25
41
  export declare function claimUpdateSlot(): boolean;
26
42
  /** Releases the update slot, so the next update can start. */
27
43
  export declare function releaseUpdateSlot(): void;
44
+ /**
45
+ * Whether an update is running RIGHT NOW.
46
+ *
47
+ * The client used to keep its buttons disabled only for as long as its own request was in
48
+ * flight, which ended the moment the server answered 202 - while npm was still installing.
49
+ * The server knew the whole time (it holds the slot above), so it says so out loud and the
50
+ * client asks.
51
+ */
52
+ export declare function isUpdateInFlight(): boolean;
53
+ /** Records the outcome of an update attempt. */
54
+ export declare function recordUpdateOutcome(ok: boolean, code?: number): void;
55
+ /** The most recent update outcome, or undefined when no update has run in this process. */
56
+ export declare function getLastUpdateOutcome(): {
57
+ ok: boolean;
58
+ code?: number;
59
+ at: string;
60
+ } | undefined;
@@ -1,4 +1,24 @@
1
1
  import { sep } from "node:path";
2
+ /**
3
+ * Quote an argument for a shell on Windows.
4
+ *
5
+ * WHY THIS EXISTS. Node runs `spawn("npm.cmd", args, { shell: true })` by CONCATENATING the
6
+ * arguments into one command line - it does not escape them (Node's own DEP0190 warning says
7
+ * exactly that). So an argument with a space in it arrives at npm in pieces: measured, a
8
+ * `--prefix "C:\\Users\\Some Name\\npm"` reached npm as `C:\\Users\\Some Name` and npm
9
+ * answered `ENOENT ... lstat ... path C:\\Users\\Some`.
10
+ *
11
+ * The npm prefix is wherever the user's npm lives, so on a machine whose home directory has a
12
+ * space in it the update - and the CLI's update - would fail with a path that looks truncated.
13
+ * Quoting here is what makes the argument survive.
14
+ */
15
+ export function quoteForShell(value) {
16
+ return `"${String(value).replace(/"/g, '""')}"`;
17
+ }
18
+ /** The arguments to hand to npm, quoted for the shell when the shell is what runs them. */
19
+ export function shellArgs(args) {
20
+ return process.platform === "win32" ? args.map(quoteForShell) : args;
21
+ }
2
22
  /**
3
23
  * Return npm's install arguments for the package that is actually running.
4
24
  *
@@ -52,3 +72,29 @@ export function claimUpdateSlot() {
52
72
  export function releaseUpdateSlot() {
53
73
  updateInFlight = false;
54
74
  }
75
+ /**
76
+ * Whether an update is running RIGHT NOW.
77
+ *
78
+ * The client used to keep its buttons disabled only for as long as its own request was in
79
+ * flight, which ended the moment the server answered 202 - while npm was still installing.
80
+ * The server knew the whole time (it holds the slot above), so it says so out loud and the
81
+ * client asks.
82
+ */
83
+ export function isUpdateInFlight() {
84
+ return updateInFlight;
85
+ }
86
+ /**
87
+ * WHAT THE LAST UPDATE ACTUALLY DID.
88
+ *
89
+ * The outcome of the most recent update, so the client can tell the user what actually
90
+ * happened instead of showing a spinner forever.
91
+ */
92
+ let lastUpdate;
93
+ /** Records the outcome of an update attempt. */
94
+ export function recordUpdateOutcome(ok, code) {
95
+ lastUpdate = { ok, code, at: new Date().toISOString() };
96
+ }
97
+ /** The most recent update outcome, or undefined when no update has run in this process. */
98
+ export function getLastUpdateOutcome() {
99
+ return lastUpdate;
100
+ }
@@ -0,0 +1,15 @@
1
+ import { ChildSessionRow } from "./child-session-lock.js";
2
+ export type SessionReportingSnapshot = {
3
+ id: string;
4
+ parentConversationId?: string;
5
+ status?: string;
6
+ reportedToParentAt?: string;
7
+ archivedAt?: string;
8
+ };
9
+ export type ReportingAxisState = "pending_report" | "awaiting_subordinates" | "unread";
10
+ export declare function deriveReportingState(params: {
11
+ conversation: SessionReportingSnapshot;
12
+ parent?: ChildSessionRow;
13
+ directChildren: SessionReportingSnapshot[];
14
+ isTopLevelUnread: boolean;
15
+ }): ReportingAxisState | null;