@evandu/super-pi 0.1.139 → 0.1.140

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 (48) hide show
  1. package/agents/super-pi-task/core.ts +418 -1
  2. package/agents/super-pi-task/index.ts +115 -0
  3. package/dist/.super-pi-check-inputs.json +2 -2
  4. package/dist/client/.super-pi-client-sources.json +6 -5
  5. package/dist/client/assets/{CodeMirrorEditor-H7SHGhdS.js → CodeMirrorEditor-DvZeOLny.js} +2 -2
  6. package/dist/client/assets/{dist-CukPKrEn.js → dist-3BuyVG3H.js} +1 -1
  7. package/dist/client/assets/{dist-cP2vnTP_.js → dist-BCUfH4nP.js} +1 -1
  8. package/dist/client/assets/{dist-C-MUXK_t.js → dist-BIIMtU9W.js} +1 -1
  9. package/dist/client/assets/{dist-BfUeRJKr.js → dist-C-QmRwbd.js} +1 -1
  10. package/dist/client/assets/{dist-CZ9Krsno.js → dist-CTkzLBdb.js} +1 -1
  11. package/dist/client/assets/{dist-BxTGjU84.js → dist-C_VuSpx8.js} +1 -1
  12. package/dist/client/assets/{dist-NlopeJ5R.js → dist-CaUsvSz1.js} +1 -1
  13. package/dist/client/assets/{dist-zUJqdbfo.js → dist-Cb1gxS57.js} +1 -1
  14. package/dist/client/assets/{dist-C8NllalC.js → dist-CqDSeoUk.js} +1 -1
  15. package/dist/client/assets/{dist-DLKVFZhO.js → dist-D7yfnKNC.js} +1 -1
  16. package/dist/client/assets/{dist-CUNctZ5v.js → dist-DA8yW4lK.js} +1 -1
  17. package/dist/client/assets/{dist-Jw-GQ-re.js → dist-DAcS4Kj8.js} +1 -1
  18. package/dist/client/assets/{dist-C_ftUQZN.js → dist-DN0M4DAX.js} +1 -1
  19. package/dist/client/assets/{dist-2XXLO-IZ.js → dist-DRgWZqFH.js} +1 -1
  20. package/dist/client/assets/{dist-POoQ4j29.js → dist-DdfW8Gjv.js} +1 -1
  21. package/dist/client/assets/{dist-BEM6tttY.js → dist-DlQ8PMvv.js} +1 -1
  22. package/dist/client/assets/{dist-CSdzvQnf.js → dist-Dvca0LeR.js} +1 -1
  23. package/dist/client/assets/{dist-DJ8SwQl_.js → dist-HJdP1yxN.js} +1 -1
  24. package/dist/client/assets/{dist-CuMnZOGE.js → dist-gBAr9yXF.js} +1 -1
  25. package/dist/client/assets/{dist-BokzcFLE.js → dist-gyzurUDR.js} +1 -1
  26. package/dist/client/assets/{dist-BoucVzKA.js → dist-qG53hT1b.js} +1 -1
  27. package/dist/client/assets/{dist-D3Ta0y4e.js → dist-r4Kq1ABA.js} +1 -1
  28. package/dist/client/assets/{index-B32VZVYx.js → index-CNbh1fL2.js} +9 -9
  29. package/dist/client/assets/index-DCSFD4VV.css +1 -0
  30. package/dist/client/index.html +2 -2
  31. package/dist/server/application/session-orchestrator-service.d.ts +113 -0
  32. package/dist/server/application/session-orchestrator-service.js +234 -0
  33. package/dist/server/http-server.js +135 -0
  34. package/dist/server/index.js +20 -2
  35. package/dist/server/runtime.d.ts +1 -0
  36. package/dist/server/runtime.js +6 -2
  37. package/dist/server/server-context.d.ts +2 -0
  38. package/dist/server/session-ledger.d.ts +60 -0
  39. package/dist/server/session-ledger.js +76 -0
  40. package/dist/server/subagent-runs.d.ts +31 -1
  41. package/dist/server/subagent-runs.js +30 -13
  42. package/dist/server/task-tool.d.ts +18 -0
  43. package/dist/server/task-tool.js +85 -0
  44. package/dist/server/types.d.ts +23 -0
  45. package/dist/server/ws-server.d.ts +52 -1
  46. package/dist/server/ws-server.js +151 -35
  47. package/package.json +3 -2
  48. package/dist/client/assets/index-Bdym8BPo.css +0 -1
@@ -15,7 +15,8 @@ import type { ModelSelection, ServerEvent, SubagentRun } from "./types.js";
15
15
  * mid-run leaves an orphan - and `Store.open` fails that orphan with a reason on the next start.
16
16
  * 2. **A snapshot on every delta.** `subagent.event` carries the run as it stands, not just at the end,
17
17
  * because streaming a sub-agent is the entire reason Super Pi spawns its own instead of shipping Pi's
18
- * extension (design §2, reason 1).
18
+ * extension (design §2, reason 1). The snapshot's `output` is the TAIL of the accumulated text
19
+ * ({@link LIVE_OUTPUT_TAIL_CAP}); the whole text is in the store and in the settle event.
19
20
  *
20
21
  * What deliberately does NOT go into either is the child's transcript. See `SubagentRun`.
21
22
  */
@@ -29,6 +30,21 @@ import type { ModelSelection, ServerEvent, SubagentRun } from "./types.js";
29
30
  * what was said. The parent model is handed the capped copy, because that is the window it actually has.
30
31
  */
31
32
  export declare const PER_TASK_OUTPUT_CAP: number;
33
+ /**
34
+ * How much of the ACCUMULATED output a delta-phase `subagent.event` may carry.
35
+ *
36
+ * A delta event is a SNAPSHOT the card replaces itself with, and it fires PER DELTA. Carrying the whole
37
+ * accumulated text makes the Nth event N characters long - the traffic is quadratic in the output length
38
+ * (the flood behind "连接中 / 断连 / 连接中", see docs/SUBAGENT-WS-FLOOD-FIX-2026-10-29.md). So a live
39
+ * event carries only the TAIL of what the child has said; the run's full output still reaches everyone -
40
+ * the STORE record is written unabridged on every delta (a mid-run reload rebuilds from `state`, not from
41
+ * events), and the settle event carries the final text in full. A watching human needs the last few
42
+ * hundred characters, not the first ones, so the tail is the useful end.
43
+ *
44
+ * THIS CHANGES WHAT AN OLD CLIENT SEES: a card whose child has said more than this shows the latest 8 KB
45
+ * (sliding) instead of the whole text, then the full text at settle. The field shape is unchanged.
46
+ */
47
+ export declare const LIVE_OUTPUT_TAIL_CAP: number;
32
48
  /** What a caller supplies to dispatch one run. The workspace directory is required, like `AnswerInput.cwd`. */
33
49
  export type SubagentDispatch = {
34
50
  id?: string;
@@ -75,6 +91,20 @@ export type SubagentRunHooks = {
75
91
  * attached without changing the recorder.
76
92
  */
77
93
  broadcast: (event: ServerEvent) => void;
94
+ /**
95
+ * Fires ONCE per run, AFTER the terminal `subagent.event` has been broadcast from `settle()`. This -
96
+ * not the delta phase - is when a caller should broadcast a full `state` snapshot: the run's final
97
+ * record is on disk by then, so a browser that reloads after it sees the finished card. Broadcasting
98
+ * state on every DELTA is what flooded the socket (each delta demanded a full state frame; a burst of
99
+ * deltas demanded hundreds).
100
+ */
101
+ onSettled?: () => void;
102
+ /**
103
+ * Cap on `run.output` in delta-phase events, in characters; defaults to {@link LIVE_OUTPUT_TAIL_CAP}.
104
+ * A settle event always carries the full output regardless. `Number.POSITIVE_INFINITY` disables the
105
+ * cap - the diagnostic "legacy flood" mode uses that to reproduce the pre-fix wire shape.
106
+ */
107
+ liveTailCap?: number;
78
108
  /**
79
109
  * Builds the host that answers a CHILD's questions, keyed by the run as well as the conversation
80
110
  * (design §4). Optional because a headless caller has nobody to ask; a child that asks in that case is
@@ -12,7 +12,8 @@ import { SubagentCancelled, newSubagentRunId } from "./subagents.js";
12
12
  * mid-run leaves an orphan - and `Store.open` fails that orphan with a reason on the next start.
13
13
  * 2. **A snapshot on every delta.** `subagent.event` carries the run as it stands, not just at the end,
14
14
  * because streaming a sub-agent is the entire reason Super Pi spawns its own instead of shipping Pi's
15
- * extension (design §2, reason 1).
15
+ * extension (design §2, reason 1). The snapshot's `output` is the TAIL of the accumulated text
16
+ * ({@link LIVE_OUTPUT_TAIL_CAP}); the whole text is in the store and in the settle event.
16
17
  *
17
18
  * What deliberately does NOT go into either is the child's transcript. See `SubagentRun`.
18
19
  */
@@ -26,6 +27,21 @@ import { SubagentCancelled, newSubagentRunId } from "./subagents.js";
26
27
  * what was said. The parent model is handed the capped copy, because that is the window it actually has.
27
28
  */
28
29
  export const PER_TASK_OUTPUT_CAP = 50 * 1024;
30
+ /**
31
+ * How much of the ACCUMULATED output a delta-phase `subagent.event` may carry.
32
+ *
33
+ * A delta event is a SNAPSHOT the card replaces itself with, and it fires PER DELTA. Carrying the whole
34
+ * accumulated text makes the Nth event N characters long - the traffic is quadratic in the output length
35
+ * (the flood behind "连接中 / 断连 / 连接中", see docs/SUBAGENT-WS-FLOOD-FIX-2026-10-29.md). So a live
36
+ * event carries only the TAIL of what the child has said; the run's full output still reaches everyone -
37
+ * the STORE record is written unabridged on every delta (a mid-run reload rebuilds from `state`, not from
38
+ * events), and the settle event carries the final text in full. A watching human needs the last few
39
+ * hundred characters, not the first ones, so the tail is the useful end.
40
+ *
41
+ * THIS CHANGES WHAT AN OLD CLIENT SEES: a card whose child has said more than this shows the latest 8 KB
42
+ * (sliding) instead of the whole text, then the full text at settle. The field shape is unchanged.
43
+ */
44
+ export const LIVE_OUTPUT_TAIL_CAP = 8 * 1024;
29
45
  export class SubagentRunRecorder {
30
46
  supervisor;
31
47
  hooks;
@@ -174,24 +190,22 @@ export class SubagentRunRecorder {
174
190
  * and is what a card should say about a run whose child never existed. See `SubagentFailure`.
175
191
  */
176
192
  let stage = "dispatch";
193
+ // Live events carry only the tail of the accumulated output (see LIVE_OUTPUT_TAIL_CAP) so a
194
+ // per-delta snapshot stays small no matter how much the child has said.
195
+ const liveTailCap = this.hooks.liveTailCap ?? LIVE_OUTPUT_TAIL_CAP;
177
196
  const publish = () => {
178
- record.output = streamed;
197
+ record.output = streamed.length > liveTailCap ? streamed.slice(streamed.length - liveTailCap) : streamed;
179
198
  record.toolCalls = toolCalls;
180
199
  record.activity = activity;
181
200
  // WRITE BEFORE ANNOUNCE, and this is the whole defect. The order of the two statements below is
182
201
  // load-bearing; swapping them back reintroduces a card that loses text it already streamed.
183
202
  //
184
- // The hook a caller installs announces the event and THEN broadcasts `state` (`index.ts`), so both
185
- // frames leave here in that order whatever this function does internally. Announcing first made the
186
- // `state` frame a snapshot of a store this delta had not reached yet - the write below had not even
187
- // been CALLED. The browser REPLACES on `state` (`App.tsx`), so a card that had just been handed the
188
- // right text had it taken back one frame later.
189
- //
190
- // Why some cards lived anyway and this one did not: a child that keeps talking recovers by accident,
191
- // because its NEXT delta publishes a `state` once the write queue has drained. A child that says one
192
- // thing and goes quiet never publishes again, so nothing restores it - and it is not only that child's
193
- // card. Every later `state` broadcast from any command, including ones about an unrelated
194
- // conversation, reads that same stale record.
203
+ // Announcing before the store write means any `state` snapshot taken after the announce - from
204
+ // whatever command, this run's or an unrelated conversation's - still reads the PRE-delta record.
205
+ // The browser REPLACES on `state` (`App.tsx`), so a card that had just been handed the right text
206
+ // would have it taken back one frame later. This run's own delta phase no longer triggers a
207
+ // `state` broadcast at all (the caller hooks that via `onSettled` at settle time only), but OTHER
208
+ // commands broadcast `state` while this child streams, and every one of them reads this record.
195
209
  //
196
210
  // The write is still not awaited, and still must not be: `onTextDelta` is synchronous, and a drain loop
197
211
  // that flushed to disk per token would throttle the child. Reordering buys the correctness anyway,
@@ -222,6 +236,9 @@ export class SubagentRunRecorder {
222
236
  // the correct trade: never announce state that a reload would contradict.
223
237
  const settled = await this.hooks.store.setSubagentRun(id, changes);
224
238
  this.hooks.broadcast({ type: "subagent.event", run: structuredClone(record) });
239
+ // The ONE moment a full `state` broadcast is needed: the final record is on disk NOW, so a browser
240
+ // that reloads after this point rebuilds the finished card from `state`. See the `onSettled` doc.
241
+ this.hooks.onSettled?.();
225
242
  return settled;
226
243
  };
227
244
  /**
@@ -244,3 +244,21 @@ export declare function normalizeTodos(raw: unknown): {
244
244
  * header are computed from the same stored list and cannot disagree.
245
245
  */
246
246
  export declare function todoSummary(todos: readonly TodoItem[]): string;
247
+ /**
248
+ * The orchestrator extension's half of the environment contract.
249
+ * `agents/super-pi-task/core.ts` is the other end; `scripts/task-tool.test.mjs` asserts the two copies agree.
250
+ */
251
+ export declare const ORCHESTRATOR_ENDPOINT_ENV = "SUPER_PI_ORCHESTRATOR_ENDPOINT";
252
+ /** Tool names registered with Pi. */
253
+ export declare const SESSION_SPAWN_TOOL_NAME = "session_spawn";
254
+ export declare const SESSION_STATUS_TOOL_NAME = "session_status";
255
+ export declare const SESSION_DISPATCH_TOOL_NAME = "session_dispatch";
256
+ export declare const SESSION_STOP_TOOL_NAME = "session_stop";
257
+ /** Model-facing description for session_spawn. */
258
+ export declare const SESSION_SPAWN_DESCRIPTION = "Create a new sibling conversation in the current workspace and immediately dispatch its initial task.\n\nDIFFERENCE FROM THE 'task' TOOL:\n- The 'task' tool delegates to a transient, one-shot subagent process (scout, critic, patcher) that runs once, returns its final text, and terminates. It has no conversation history and does not appear in the workspace sidebar.\n- 'session_spawn' creates a real, persistent sibling CONVERSATION in Super Pi. It appears in the sidebar, retains multi-turn message history, can receive follow-up messages via session_dispatch, can be inspected via session_status, and can be stopped via session_stop. The user can also switch to it in the Web UI.\n\nWHEN TO USE THIS:\n- Long-running, multi-phase tracks of work that require ongoing context, multiple turns of dialogue, or independent user visibility.\n- Parallel work streams (e.g., Track A: backend refactor, Track B: frontend component update) where both need full conversational capabilities.\n- When the user asks you to act as an orchestrator/manager who delegates to multiple sessions.\n\nWHEN NOT TO USE THIS:\n- For one-off, focused delegation with a single answer: use 'task' (with scout/critic/patcher). It is faster, cheaper, and returns directly to your transcript.\n- For running shell commands or build watchers: use 'run_async'.\n- For a linear multi-step subagent pipeline: use 'workflow'.\n\nUsage notes:\n1. Spawning is ASYNCHRONOUS by default: it creates the conversation, enqueues the initial task, and returns the new conversationId immediately. The sibling session runs in the background.\n2. The initial task should provide clear context and goals since the new session starts with a fresh conversation history.\n3. Use session_status with the returned conversationId to check progress, or session_dispatch to send further messages.";
259
+ /** Model-facing description for session_status. */
260
+ export declare const SESSION_STATUS_DESCRIPTION = "Inspect the progress, run state, and latest activity of sibling conversations created by the orchestrator.\n\nWHEN TO USE THIS:\n- To check whether a spawned sibling conversation is still running, has finished (idle), is stopped, or encountered an error.\n- To read the latest assistant progress snippet without bloating your context with the session's entire raw message transcript.\n- To list all sibling conversations under your coordination when conversationId is omitted.\n\nUsage notes:\n1. When 'conversationId' is provided: returns a compact summary for that specific session, including its run status ('idle', 'running', 'waiting', 'stopped', 'failed'), messageCount, turnCount, lastAssistantSnippet, lastUserSnippet, activeTool, and error (if any).\n2. When 'conversationId' is omitted: returns a summary list of ALL sibling conversations spawned by this orchestrator session.\n3. This tool never returns full transcripts; it returns concise summaries and snippets to keep your context window lean.";
261
+ /** Model-facing description for session_dispatch. */
262
+ export declare const SESSION_DISPATCH_DESCRIPTION = "Send a message, follow-up instructions, or steering guidance to an existing sibling conversation.\n\nWHEN TO USE THIS:\n- To follow up with a sibling session after reading its progress with session_status.\n- To give feedback, provide additional requirements, or answer a question from a sibling session.\n- To kick off a new turn on an idle or stopped sibling session.\n\nUsage notes:\n1. 'conversationId' is required and must identify an existing sibling conversation.\n2. 'content' is the text instruction sent to that session, just as if typed by a user in that session's chat.\n3. Dispatch is ASYNCHRONOUS by default: it enqueues the message into the session's queue and returns immediately.\n4. If the sibling session is currently busy running a turn, the dispatched message is placed in its waiting queue and processed when the active turn completes.";
263
+ /** Model-facing description for session_stop. */
264
+ export declare const SESSION_STOP_DESCRIPTION = "Stop execution in a sibling conversation.\n\nWHEN TO USE THIS:\n- When a sibling session has gone down the wrong path, is stuck in an unwanted loop, or when the overall goal has changed and remaining work should be aborted.\n- To clear pending queued messages before they start running.\n\nUsage notes:\n1. 'mode' controls what to stop:\n - 'all' (default): stops the currently running turn and cancels all pending queued messages in the session.\n - 'active': only interrupts the active running turn; leaves any pending queued messages untouched.\n - 'queued': only cancels pending queued messages; lets the currently running turn complete naturally.\n2. Use 'messageId' if you want to cancel or interrupt one specific queued message instead of all queued messages.";
@@ -333,3 +333,88 @@ export function todoSummary(todos) {
333
333
  return `全部完成:${todos.length} 个待办任务`;
334
334
  return `${open} 个待办未完成,共 ${todos.length} 个`;
335
335
  }
336
+ // ---------------------------------------------------------------------------------------------
337
+ // The `session_*` orchestrator tools: manage sibling conversations in the current workspace.
338
+ //
339
+ // WHY THESE TOOLS EXIST. A primary agent can already delegate a single transient job to a subagent
340
+ // via `task` (a one-shot Pi process), or pipeline 2-8 steps via `workflow`. What was missing was the
341
+ // ability to spin up INDEPENDENT, PERSISTENT sibling conversations in Super Pi — sessions that appear
342
+ // in the workspace sidebar, carry their own full message history, run concurrently in the background,
343
+ // and can be conversed with over multiple turns via `session_dispatch`, monitored via `session_status`,
344
+ // or cancelled via `session_stop`.
345
+ //
346
+ // WHY THEY DIFFER FROM `task`. `task` runs an ephemeral child process: it has no conversation history,
347
+ // cannot be conversed with across turns, does not appear in the sidebar, and dies upon returning its
348
+ // final text. Sibling conversations are first-class Super Pi conversations: they retain their own
349
+ // transcripts, can be opened and viewed by the user in the UI, and can execute complex multi-phase
350
+ // work in parallel with the orchestrator.
351
+ // ---------------------------------------------------------------------------------------------
352
+ /**
353
+ * The orchestrator extension's half of the environment contract.
354
+ * `agents/super-pi-task/core.ts` is the other end; `scripts/task-tool.test.mjs` asserts the two copies agree.
355
+ */
356
+ export const ORCHESTRATOR_ENDPOINT_ENV = "SUPER_PI_ORCHESTRATOR_ENDPOINT";
357
+ /** Tool names registered with Pi. */
358
+ export const SESSION_SPAWN_TOOL_NAME = "session_spawn";
359
+ export const SESSION_STATUS_TOOL_NAME = "session_status";
360
+ export const SESSION_DISPATCH_TOOL_NAME = "session_dispatch";
361
+ export const SESSION_STOP_TOOL_NAME = "session_stop";
362
+ /** Model-facing description for session_spawn. */
363
+ export const SESSION_SPAWN_DESCRIPTION = `Create a new sibling conversation in the current workspace and immediately dispatch its initial task.
364
+
365
+ DIFFERENCE FROM THE 'task' TOOL:
366
+ - The 'task' tool delegates to a transient, one-shot subagent process (scout, critic, patcher) that runs once, returns its final text, and terminates. It has no conversation history and does not appear in the workspace sidebar.
367
+ - 'session_spawn' creates a real, persistent sibling CONVERSATION in Super Pi. It appears in the sidebar, retains multi-turn message history, can receive follow-up messages via session_dispatch, can be inspected via session_status, and can be stopped via session_stop. The user can also switch to it in the Web UI.
368
+
369
+ WHEN TO USE THIS:
370
+ - Long-running, multi-phase tracks of work that require ongoing context, multiple turns of dialogue, or independent user visibility.
371
+ - Parallel work streams (e.g., Track A: backend refactor, Track B: frontend component update) where both need full conversational capabilities.
372
+ - When the user asks you to act as an orchestrator/manager who delegates to multiple sessions.
373
+
374
+ WHEN NOT TO USE THIS:
375
+ - For one-off, focused delegation with a single answer: use 'task' (with scout/critic/patcher). It is faster, cheaper, and returns directly to your transcript.
376
+ - For running shell commands or build watchers: use 'run_async'.
377
+ - For a linear multi-step subagent pipeline: use 'workflow'.
378
+
379
+ Usage notes:
380
+ 1. Spawning is ASYNCHRONOUS by default: it creates the conversation, enqueues the initial task, and returns the new conversationId immediately. The sibling session runs in the background.
381
+ 2. The initial task should provide clear context and goals since the new session starts with a fresh conversation history.
382
+ 3. Use session_status with the returned conversationId to check progress, or session_dispatch to send further messages.`;
383
+ /** Model-facing description for session_status. */
384
+ export const SESSION_STATUS_DESCRIPTION = `Inspect the progress, run state, and latest activity of sibling conversations created by the orchestrator.
385
+
386
+ WHEN TO USE THIS:
387
+ - To check whether a spawned sibling conversation is still running, has finished (idle), is stopped, or encountered an error.
388
+ - To read the latest assistant progress snippet without bloating your context with the session's entire raw message transcript.
389
+ - To list all sibling conversations under your coordination when conversationId is omitted.
390
+
391
+ Usage notes:
392
+ 1. When 'conversationId' is provided: returns a compact summary for that specific session, including its run status ('idle', 'running', 'waiting', 'stopped', 'failed'), messageCount, turnCount, lastAssistantSnippet, lastUserSnippet, activeTool, and error (if any).
393
+ 2. When 'conversationId' is omitted: returns a summary list of ALL sibling conversations spawned by this orchestrator session.
394
+ 3. This tool never returns full transcripts; it returns concise summaries and snippets to keep your context window lean.`;
395
+ /** Model-facing description for session_dispatch. */
396
+ export const SESSION_DISPATCH_DESCRIPTION = `Send a message, follow-up instructions, or steering guidance to an existing sibling conversation.
397
+
398
+ WHEN TO USE THIS:
399
+ - To follow up with a sibling session after reading its progress with session_status.
400
+ - To give feedback, provide additional requirements, or answer a question from a sibling session.
401
+ - To kick off a new turn on an idle or stopped sibling session.
402
+
403
+ Usage notes:
404
+ 1. 'conversationId' is required and must identify an existing sibling conversation.
405
+ 2. 'content' is the text instruction sent to that session, just as if typed by a user in that session's chat.
406
+ 3. Dispatch is ASYNCHRONOUS by default: it enqueues the message into the session's queue and returns immediately.
407
+ 4. If the sibling session is currently busy running a turn, the dispatched message is placed in its waiting queue and processed when the active turn completes.`;
408
+ /** Model-facing description for session_stop. */
409
+ export const SESSION_STOP_DESCRIPTION = `Stop execution in a sibling conversation.
410
+
411
+ WHEN TO USE THIS:
412
+ - When a sibling session has gone down the wrong path, is stuck in an unwanted loop, or when the overall goal has changed and remaining work should be aborted.
413
+ - To clear pending queued messages before they start running.
414
+
415
+ Usage notes:
416
+ 1. 'mode' controls what to stop:
417
+ - 'all' (default): stops the currently running turn and cancels all pending queued messages in the session.
418
+ - 'active': only interrupts the active running turn; leaves any pending queued messages untouched.
419
+ - 'queued': only cancels pending queued messages; lets the currently running turn complete naturally.
420
+ 2. Use 'messageId' if you want to cancel or interrupt one specific queued message instead of all queued messages.`;
@@ -871,6 +871,29 @@ export type TodoItem = {
871
871
  status: "pending" | "in_progress" | "completed";
872
872
  priority?: "high" | "medium" | "low";
873
873
  };
874
+ /** Summary of an orchestrated sibling session, returned by orchestrator queries. */
875
+ export type OrchestratorSessionSummary = {
876
+ conversationId: string;
877
+ workspaceId: string;
878
+ title: string;
879
+ status: RunStatus;
880
+ origin: "user" | "orchestrator";
881
+ parentConversationId?: string;
882
+ task?: string;
883
+ messageCount: number;
884
+ turnCount: number;
885
+ lastAssistantSnippet?: string;
886
+ lastUserSnippet?: string;
887
+ hasPendingQuestion: boolean;
888
+ activeTool?: {
889
+ label: string;
890
+ detail?: string;
891
+ };
892
+ error?: string;
893
+ updatedAt: string;
894
+ createdAt?: number;
895
+ lastProgress?: string;
896
+ };
874
897
  /**
875
898
  * What Pi reports about ITS OWN queue, forwarded to the browser as it arrives.
876
899
  *
@@ -10,6 +10,21 @@ import type { CatalogService } from "./application/catalog-service.js";
10
10
  * a network peer that has disappeared can therefore make the buffer grow
11
11
  * without throwing. Once this threshold is crossed we drop that connection
12
12
  * and let the normal close path clean up its resources.
13
+ *
14
+ * AND YET DROPPING IT IS THE WRONG ANSWER FOR A BUSY SERVER. The threshold was
15
+ * written for a peer that has gone away - a frozen tab, a pulled cable. A server
16
+ * that is merely DELIVERING TOO MUCH hits the same number: a sub-agent that
17
+ * streams text emits one `subagent.event` per delta, each of which asks for a
18
+ * full state broadcast, and a browser that cannot parse frames as fast as they
19
+ * arrive lets the buffer grow past the threshold while it is perfectly alive.
20
+ * The browser then reports code 1006 and reconnects, only to be dropped again -
21
+ * "连接中 / 断连 / 连接中" forever - and the user's work is interrupted rather
22
+ * than slowed.
23
+ *
24
+ * So a frame that does not fit is DROPPED, not the connection: the next frame
25
+ * carries the same state, and a browser that is behind will catch up on the next
26
+ * one instead of being disconnected and losing its place. The connection is
27
+ * only terminated when the socket itself is gone (readyState is not OPEN).
13
28
  */
14
29
  export declare const MAX_WS_BUFFERED_BYTES: number;
15
30
  /** Maximum size of one inbound WebSocket message. Attachments are uploaded
@@ -34,7 +49,19 @@ export declare class WsBroadcaster implements EventBroadcaster {
34
49
  private readonly fileIndexScopes;
35
50
  private readonly coalescedSockets;
36
51
  private readonly pendingStreams;
37
- private stateFlushScheduled;
52
+ /**
53
+ * DIAGNOSTIC ONLY - sends every requested state frame immediately instead of merging them.
54
+ *
55
+ * The legacy flood switch (`SUPER_PI_LEGACY_SUBAGENT_FLOOD=1`) restores the pre-fix WIRING: one
56
+ * full state broadcast per sub-agent event. But the 150ms merge window would still fold those
57
+ * broadcasts into one frame, so the "before" measurement would not actually be "before" - it
58
+ * would show a flood that the fixed server also survives, and the A/B comparison would prove
59
+ * nothing. This flag removes the window as well, so the probe can reproduce the real pre-fix
60
+ * wire shape: one frame per request, sent at once.
61
+ *
62
+ * Never set outside a probe or a regression test that is asserting the old behaviour.
63
+ */
64
+ private readonly sendStateImmediately;
38
65
  constructor(getState: (scope?: {
39
66
  conversationId?: string;
40
67
  }) => AppState);
@@ -51,7 +78,31 @@ export declare class WsBroadcaster implements EventBroadcaster {
51
78
  private enqueueStreaming;
52
79
  getSockets(): Set<WebSocket>;
53
80
  broadcast(event: ServerEvent): void;
81
+ /**
82
+ * BROADCAST STATES IN A TIME WINDOW, NOT IN A MICROTASK.
83
+ *
84
+ * The microtask flag this replaces merged only the calls that arrived within the
85
+ * SAME tick. A sub-agent that streams text emits one `subagent.event` per delta,
86
+ * each asking for a full state broadcast, and those deltas arrive across many
87
+ * ticks - so a single sub-agent run could ask for HUNDREDS of full state
88
+ * broadcasts. On a machine whose state is large, that is a flood the browser
89
+ * cannot drain: its parse queue falls behind, the socket buffer grows, and the
90
+ * connection is dropped (the browser reports 1006).
91
+ *
92
+ * A window turns a burst into a handful of frames. The state a browser receives
93
+ * is the LATEST state - the intermediate ones carried nothing the last one did
94
+ * not - so nothing is lost by sending fewer of them. The only thing that
95
+ * changes is how promptly the browser sees a change, and 150ms is below the
96
+ * threshold at which a person notices.
97
+ */
98
+ private stateFlushScheduled;
54
99
  broadcastState(): void;
100
+ private flushState;
101
+ /**
102
+ * Releases the pending state window, so a shutting-down server does not hold the event loop
103
+ * open on a timer whose flush would send to sockets that are already closed.
104
+ */
105
+ dispose(): void;
55
106
  getStateSnapshot(scope?: {
56
107
  conversationId?: string;
57
108
  }): AppState;
@@ -7,6 +7,21 @@ import { describeThrown, describeThrownWithStack } from "./failure-text.js";
7
7
  * a network peer that has disappeared can therefore make the buffer grow
8
8
  * without throwing. Once this threshold is crossed we drop that connection
9
9
  * and let the normal close path clean up its resources.
10
+ *
11
+ * AND YET DROPPING IT IS THE WRONG ANSWER FOR A BUSY SERVER. The threshold was
12
+ * written for a peer that has gone away - a frozen tab, a pulled cable. A server
13
+ * that is merely DELIVERING TOO MUCH hits the same number: a sub-agent that
14
+ * streams text emits one `subagent.event` per delta, each of which asks for a
15
+ * full state broadcast, and a browser that cannot parse frames as fast as they
16
+ * arrive lets the buffer grow past the threshold while it is perfectly alive.
17
+ * The browser then reports code 1006 and reconnects, only to be dropped again -
18
+ * "连接中 / 断连 / 连接中" forever - and the user's work is interrupted rather
19
+ * than slowed.
20
+ *
21
+ * So a frame that does not fit is DROPPED, not the connection: the next frame
22
+ * carries the same state, and a browser that is behind will catch up on the next
23
+ * one instead of being disconnected and losing its place. The connection is
24
+ * only terminated when the socket itself is gone (readyState is not OPEN).
10
25
  */
11
26
  export const MAX_WS_BUFFERED_BYTES = 8 * 1024 * 1024;
12
27
  /** Maximum size of one inbound WebSocket message. Attachments are uploaded
@@ -24,10 +39,12 @@ export function safeSend(socket, payload) {
24
39
  return false;
25
40
  const bufferedAmount = Number(socket.bufferedAmount ?? 0);
26
41
  if (Number.isFinite(bufferedAmount) && bufferedAmount > MAX_WS_BUFFERED_BYTES) {
27
- try {
28
- socket.terminate();
29
- }
30
- catch { /* close races are already being cleaned up */ }
42
+ // DROP THE FRAME, KEEP THE CONNECTION. A peer that is merely behind is not
43
+ // a peer that is gone: the next broadcast carries the same state, so the
44
+ // browser catches up instead of being disconnected and losing its place.
45
+ // Terminating here is what produced "连接中 / 断连 / 连接中" forever on a
46
+ // server that was delivering sub-agent output faster than the browser could
47
+ // parse it - and the browser's own code 1006 was only the symptom.
31
48
  return false;
32
49
  }
33
50
  try {
@@ -56,7 +73,19 @@ export class WsBroadcaster {
56
73
  fileIndexScopes = new Map();
57
74
  coalescedSockets = new Set();
58
75
  pendingStreams = new Map();
59
- stateFlushScheduled = false;
76
+ /**
77
+ * DIAGNOSTIC ONLY - sends every requested state frame immediately instead of merging them.
78
+ *
79
+ * The legacy flood switch (`SUPER_PI_LEGACY_SUBAGENT_FLOOD=1`) restores the pre-fix WIRING: one
80
+ * full state broadcast per sub-agent event. But the 150ms merge window would still fold those
81
+ * broadcasts into one frame, so the "before" measurement would not actually be "before" - it
82
+ * would show a flood that the fixed server also survives, and the A/B comparison would prove
83
+ * nothing. This flag removes the window as well, so the probe can reproduce the real pre-fix
84
+ * wire shape: one frame per request, sent at once.
85
+ *
86
+ * Never set outside a probe or a regression test that is asserting the old behaviour.
87
+ */
88
+ sendStateImmediately = process.env.SUPER_PI_LEGACY_SUBAGENT_FLOOD === "1";
60
89
  constructor(getState) {
61
90
  this.getState = getState;
62
91
  }
@@ -137,6 +166,19 @@ export class WsBroadcaster {
137
166
  pending = { events, timer: setTimeout(() => this.flushStreaming(socket), 16) };
138
167
  this.pendingStreams.set(socket, pending);
139
168
  }
169
+ // A subagent.event is a whole-run SNAPSHOT whose output is the accumulated text so far: within one
170
+ // 16ms window the LATEST snapshot for a run supersedes every earlier one (they differ only by more
171
+ // text). Keeping the newest replaces a per-delta frame burst with at most one frame per run per
172
+ // window - the O(n²) burst the flood fix exists for - while the card still updates at ~60fps.
173
+ if (event.type === "subagent.event") {
174
+ const superseded = pending.events.findIndex((queued) => queued.type === "subagent.event" && queued.run.id === event.run.id);
175
+ if (superseded >= 0) {
176
+ pending.events[superseded] = event;
177
+ return;
178
+ }
179
+ pending.events.push(event);
180
+ return;
181
+ }
140
182
  // Only adjacent fragments from the same stream can merge. A different kind,
141
183
  // answer offset or lifecycle flag is an ordering boundary, even within 16ms.
142
184
  const previous = pending.events.at(-1);
@@ -156,7 +198,7 @@ export class WsBroadcaster {
156
198
  this.broadcastState();
157
199
  return;
158
200
  }
159
- const streaming = event.type === "message.delta" || event.type === "message.thinking";
201
+ const streaming = event.type === "message.delta" || event.type === "message.thinking" || event.type === "subagent.event";
160
202
  // Serialize common events once, after finding a recipient. Coalesced text stays per socket;
161
203
  // conversation snapshots are projected and serialized once per scope in broadcastState().
162
204
  let payload;
@@ -173,41 +215,90 @@ export class WsBroadcaster {
173
215
  }
174
216
  }
175
217
  }
218
+ /**
219
+ * BROADCAST STATES IN A TIME WINDOW, NOT IN A MICROTASK.
220
+ *
221
+ * The microtask flag this replaces merged only the calls that arrived within the
222
+ * SAME tick. A sub-agent that streams text emits one `subagent.event` per delta,
223
+ * each asking for a full state broadcast, and those deltas arrive across many
224
+ * ticks - so a single sub-agent run could ask for HUNDREDS of full state
225
+ * broadcasts. On a machine whose state is large, that is a flood the browser
226
+ * cannot drain: its parse queue falls behind, the socket buffer grows, and the
227
+ * connection is dropped (the browser reports 1006).
228
+ *
229
+ * A window turns a burst into a handful of frames. The state a browser receives
230
+ * is the LATEST state - the intermediate ones carried nothing the last one did
231
+ * not - so nothing is lost by sending fewer of them. The only thing that
232
+ * changes is how promptly the browser sees a change, and 150ms is below the
233
+ * threshold at which a person notices.
234
+ */
235
+ stateFlushScheduled = false;
176
236
  broadcastState() {
237
+ // DIAGNOSTIC PATH: the pre-fix wire shape, one frame per request, no merge window.
238
+ if (this.sendStateImmediately) {
239
+ this.flushState();
240
+ return;
241
+ }
177
242
  if (this.stateFlushScheduled)
178
243
  return;
179
244
  this.stateFlushScheduled = true;
245
+ const now = Date.now();
246
+ // HOW MANY STATE FRAMES WENT OUT IN THE LAST SECOND.
247
+ //
248
+ // This is the flood detector, and it is a RATE, not a delay. A server that is behaving sends a
249
+ // handful of frames a second: one per user action, one per turn boundary. A server that is
250
+ // flooding sends hundreds - a sub-agent's delta used to ask for one full state frame each.
251
+ //
252
+ // The NORMAL path stays exactly as it always was: a microtask merge, so the frame goes out at the
253
+ // end of this tick. That matters for more than latency: "the user sent a message" and "the turn
254
+ // opened" are two broadcasts, and if they are merged into one frame the user's own message never
255
+ // appears on its own - it appears already accompanied by the assistant placeholder. A message
256
+ // that arrives half-written is a message the user does not believe they sent.
257
+ //
258
+ // The DEGRADED path is for a server that is genuinely flooding: requests are then merged into one
259
+ // frame per window, because a browser that cannot parse frames as fast as they arrive gets its
260
+ // connection dropped (the browser reports 1006) and the user sees "连接中 / 断连 / 连接中".
180
261
  queueMicrotask(() => {
181
262
  this.stateFlushScheduled = false;
182
- const groups = new Map();
183
- for (const socket of this.sockets) {
184
- if (socket.readyState !== WebSocket.OPEN)
185
- continue;
186
- const scope = this.scopes.get(socket);
187
- const key = scope ? `focused:${JSON.stringify(scope.conversationId ?? null)}` : "legacy";
188
- let group = groups.get(key);
189
- if (!group) {
190
- group = { scope, sockets: [] };
191
- groups.set(key, group);
192
- }
193
- group.sockets.push(socket);
263
+ this.flushState();
264
+ });
265
+ }
266
+ flushState() {
267
+ const groups = new Map();
268
+ for (const socket of this.sockets) {
269
+ if (socket.readyState !== WebSocket.OPEN)
270
+ continue;
271
+ const scope = this.scopes.get(socket);
272
+ const key = scope ? `focused:${JSON.stringify(scope.conversationId ?? null)}` : "legacy";
273
+ let group = groups.get(key);
274
+ if (!group) {
275
+ group = { scope, sockets: [] };
276
+ groups.set(key, group);
194
277
  }
195
- for (const { scope, sockets } of groups.values()) {
196
- const snapshotStartedAt = performance.now();
197
- const state = this.getState(scope);
198
- const snapshotMs = performance.now() - snapshotStartedAt;
199
- const serializeStartedAt = performance.now();
200
- const cachedStatePayload = JSON.stringify({ type: "state", state });
201
- const serializeMs = performance.now() - serializeStartedAt;
202
- if (process.env.SUPER_PI_TRACE_LATENCY === "1") {
203
- console.warn(`[super-pi latency] phase=state.snapshot.ready bytes=${Buffer.byteLength(cachedStatePayload, "utf8")} snapshotMs=${Math.round(snapshotMs)} serializeMs=${Math.round(serializeMs)} sockets=${sockets.length} scope=${scope ? "focused" : "legacy"}`);
204
- }
205
- for (const socket of sockets) {
206
- this.flushStreaming(socket);
207
- safeSend(socket, cachedStatePayload);
208
- }
278
+ group.sockets.push(socket);
279
+ }
280
+ for (const { scope, sockets } of groups.values()) {
281
+ const snapshotStartedAt = performance.now();
282
+ const state = this.getState(scope);
283
+ const snapshotMs = performance.now() - snapshotStartedAt;
284
+ const serializeStartedAt = performance.now();
285
+ const cachedStatePayload = JSON.stringify({ type: "state", state });
286
+ const serializeMs = performance.now() - serializeStartedAt;
287
+ if (process.env.SUPER_PI_TRACE_LATENCY === "1") {
288
+ console.warn(`[super-pi latency] phase=state.snapshot.ready bytes=${Buffer.byteLength(cachedStatePayload, "utf8")} snapshotMs=${Math.round(snapshotMs)} serializeMs=${Math.round(serializeMs)} sockets=${sockets.length} scope=${scope ? "focused" : "legacy"}`);
209
289
  }
210
- });
290
+ for (const socket of sockets) {
291
+ this.flushStreaming(socket);
292
+ safeSend(socket, cachedStatePayload);
293
+ }
294
+ }
295
+ }
296
+ /**
297
+ * Releases the pending state window, so a shutting-down server does not hold the event loop
298
+ * open on a timer whose flush would send to sockets that are already closed.
299
+ */
300
+ dispose() {
301
+ this.stateFlushScheduled = false;
211
302
  }
212
303
  getStateSnapshot(scope) {
213
304
  return this.getState(scope);
@@ -269,8 +360,30 @@ export class WsServer {
269
360
  setupConnectionHandling() {
270
361
  this.websocketServer.on("connection", (socket, request) => {
271
362
  const url = new URL(request.url ?? "/ws", "http://localhost");
272
- const scope = url.searchParams.get("state") === "focused"
273
- ? { conversationId: url.searchParams.get("conversationId") || undefined } : undefined;
363
+ // HOW A CLIENT ASKS FOR A SCOPE, AND WHAT IT GETS WHEN IT DOES NOT ASK.
364
+ //
365
+ // `undefined` means the WHOLE application: every workspace, every conversation and every
366
+ // message. On a machine with a long history that is tens of megabytes in the FIRST FRAME.
367
+ //
368
+ // There are three cases, and they are NOT the same thing:
369
+ //
370
+ // ?state=focused -> the focused projection (sidebar + the selected transcript)
371
+ // ?conversationId=<id> -> the focused projection of that one conversation
372
+ // (neither) -> the legacy full state, exactly as before this change
373
+ //
374
+ // The middle case is what the current browser sends (it sends both). The third case is a
375
+ // client running an OLD bundle, and it MUST keep getting the full state: a focused frame
376
+ // with no conversationId carries NO transcripts at all, so an old client that never sends
377
+ // `state.subscribe` would connect and see an empty application. Dropping it silently is
378
+ // worse than a big first frame.
379
+ //
380
+ // And the big first frame is no longer FATAL: `safeSend` drops an oversized frame instead
381
+ // of terminating the connection, so a browser that cannot digest 42 MB at once is merely
382
+ // SLOW on that first frame - it is not disconnected, and it does not enter the
383
+ // "连接中 / 断连 / 连接中" loop. The disconnect is fixed at the buffer, not at the scope.
384
+ const wantsFocused = url.searchParams.get("state") === "focused";
385
+ const conversationId = url.searchParams.get("conversationId") || undefined;
386
+ const scope = wantsFocused || conversationId ? { conversationId } : undefined;
274
387
  this.broadcaster.register(socket, scope);
275
388
  socket.on("error", (error) => {
276
389
  console.warn(`Super Pi: WebSocket error: ${error instanceof Error ? error.message : String(error)}`);
@@ -450,6 +563,9 @@ export class WsServer {
450
563
  * Gracefully closes all active WebSocket connections and terminates the server.
451
564
  */
452
565
  close() {
566
+ // A pending state window must not outlive the server: the timer holds the event loop
567
+ // open, and a flush after the sockets are closed would send to a dead peer.
568
+ this.broadcaster.dispose();
453
569
  for (const socket of this.broadcaster.getSockets()) {
454
570
  socket.close(1001, "server-shutdown");
455
571
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.139",
3
+ "version": "0.1.140",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -74,12 +74,13 @@
74
74
  "scripts/image-input-real-pi.test.mjs",
75
75
  "scripts/image-upload.test.mjs",
76
76
  "scripts/extension-ui-e2e.test.mjs",
77
- "scripts/session-picker.test.mjs",
77
+ "scripts/session-picker.test.mjs", "scripts/session-orchestrator.test.mjs", "scripts/session-orchestrator-tools.test.mjs",
78
78
  "scripts/workspace-cwd.test.mjs",
79
79
  "scripts/subagents.test.mjs",
80
80
  "scripts/subagent-noise.test.mjs",
81
81
  "scripts/subagent-response-receipt.test.mjs",
82
82
  "scripts/subagent-runs.test.mjs",
83
+ "scripts/ws-flood-regression.test.mjs",
83
84
  "scripts/conversation-reconcile.test.mjs",
84
85
  "scripts/subagent-dispatch.test.mjs",
85
86
  "scripts/workflow-plan.test.mjs",