wherever-dev 0.21.0 → 0.22.0

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 (111) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/assistant-channels.d.ts +242 -0
  3. package/dist/assistant-channels.d.ts.map +1 -0
  4. package/dist/assistant-channels.js +270 -0
  5. package/dist/assistant-channels.js.map +1 -0
  6. package/dist/assistant-controller.d.ts +228 -0
  7. package/dist/assistant-controller.d.ts.map +1 -0
  8. package/dist/assistant-controller.js +314 -0
  9. package/dist/assistant-controller.js.map +1 -0
  10. package/dist/assistant-cron.d.ts +87 -0
  11. package/dist/assistant-cron.d.ts.map +1 -0
  12. package/dist/assistant-cron.js +352 -0
  13. package/dist/assistant-cron.js.map +1 -0
  14. package/dist/assistant-folder.d.ts +161 -0
  15. package/dist/assistant-folder.d.ts.map +1 -0
  16. package/dist/assistant-folder.js +333 -0
  17. package/dist/assistant-folder.js.map +1 -0
  18. package/dist/assistant-schedule.d.ts +236 -0
  19. package/dist/assistant-schedule.d.ts.map +1 -0
  20. package/dist/assistant-schedule.js +454 -0
  21. package/dist/assistant-schedule.js.map +1 -0
  22. package/dist/assistant-scheduler.d.ts +210 -0
  23. package/dist/assistant-scheduler.d.ts.map +1 -0
  24. package/dist/assistant-scheduler.js +472 -0
  25. package/dist/assistant-scheduler.js.map +1 -0
  26. package/dist/assistant-tool-text.d.ts +40 -0
  27. package/dist/assistant-tool-text.d.ts.map +1 -0
  28. package/dist/assistant-tool-text.js +102 -0
  29. package/dist/assistant-tool-text.js.map +1 -0
  30. package/dist/assistant-tools.d.ts +207 -0
  31. package/dist/assistant-tools.d.ts.map +1 -0
  32. package/dist/assistant-tools.js +390 -0
  33. package/dist/assistant-tools.js.map +1 -0
  34. package/dist/attach-file-tool.d.ts +20 -1
  35. package/dist/attach-file-tool.d.ts.map +1 -1
  36. package/dist/attach-file-tool.js +45 -3
  37. package/dist/attach-file-tool.js.map +1 -1
  38. package/dist/cli-requests.d.ts +90 -0
  39. package/dist/cli-requests.d.ts.map +1 -0
  40. package/dist/cli-requests.js +75 -0
  41. package/dist/cli-requests.js.map +1 -0
  42. package/dist/download-grants.d.ts +12 -0
  43. package/dist/download-grants.d.ts.map +1 -0
  44. package/dist/download-grants.js +76 -0
  45. package/dist/download-grants.js.map +1 -0
  46. package/dist/index.js +431 -20
  47. package/dist/index.js.map +1 -1
  48. package/dist/protocol.d.ts +43 -0
  49. package/dist/protocol.d.ts.map +1 -1
  50. package/dist/reply-routing.d.ts +106 -0
  51. package/dist/reply-routing.d.ts.map +1 -0
  52. package/dist/reply-routing.js +174 -0
  53. package/dist/reply-routing.js.map +1 -0
  54. package/dist/session-pool.d.ts +243 -4
  55. package/dist/session-pool.d.ts.map +1 -1
  56. package/dist/session-pool.js +464 -100
  57. package/dist/session-pool.js.map +1 -1
  58. package/dist/telegram-channel.d.ts +272 -0
  59. package/dist/telegram-channel.d.ts.map +1 -0
  60. package/dist/telegram-channel.js +701 -0
  61. package/dist/telegram-channel.js.map +1 -0
  62. package/dist/telegram-files.d.ts +101 -0
  63. package/dist/telegram-files.d.ts.map +1 -0
  64. package/dist/telegram-files.js +145 -0
  65. package/dist/telegram-files.js.map +1 -0
  66. package/dist/telegram-pairing.d.ts +119 -0
  67. package/dist/telegram-pairing.d.ts.map +1 -0
  68. package/dist/telegram-pairing.js +97 -0
  69. package/dist/telegram-pairing.js.map +1 -0
  70. package/dist/telegram-replies.d.ts +94 -0
  71. package/dist/telegram-replies.d.ts.map +1 -0
  72. package/dist/telegram-replies.js +329 -0
  73. package/dist/telegram-replies.js.map +1 -0
  74. package/dist/telegram-token.d.ts +55 -0
  75. package/dist/telegram-token.d.ts.map +1 -0
  76. package/dist/telegram-token.js +86 -0
  77. package/dist/telegram-token.js.map +1 -0
  78. package/dist/web-push.d.ts +167 -0
  79. package/dist/web-push.d.ts.map +1 -0
  80. package/dist/web-push.js +387 -0
  81. package/dist/web-push.js.map +1 -0
  82. package/package.json +1 -1
  83. package/public/_app/immutable/assets/0.BkzT3rFr.css +1 -0
  84. package/public/_app/immutable/chunks/CExVgK9Z.js +2 -0
  85. package/public/_app/immutable/chunks/CExVgK9Z.js.map +1 -0
  86. package/public/_app/immutable/chunks/CkOw6fRa.js +2 -0
  87. package/public/_app/immutable/chunks/{idnZrCTB.js.map → CkOw6fRa.js.map} +1 -1
  88. package/public/_app/immutable/chunks/DyHllYtq.js +2 -0
  89. package/public/_app/immutable/chunks/{DJMI34rR.js.map → DyHllYtq.js.map} +1 -1
  90. package/public/_app/immutable/entry/{app.CF_gzWKW.js → app.D3PEFbtP.js} +3 -3
  91. package/public/_app/immutable/entry/{app.CF_gzWKW.js.map → app.D3PEFbtP.js.map} +1 -1
  92. package/public/_app/immutable/entry/start.BR00Qps5.js +2 -0
  93. package/public/_app/immutable/entry/start.BR00Qps5.js.map +1 -0
  94. package/public/_app/immutable/nodes/{0.CIIhZFWl.js → 0.DG3L8hMN.js} +3 -3
  95. package/public/_app/immutable/nodes/{0.CIIhZFWl.js.map → 0.DG3L8hMN.js.map} +1 -1
  96. package/public/_app/immutable/nodes/{1.D4WVeMej.js → 1.BCpuoZxW.js} +2 -2
  97. package/public/_app/immutable/nodes/{1.D4WVeMej.js.map → 1.BCpuoZxW.js.map} +1 -1
  98. package/public/_app/immutable/nodes/2.D2auiZW1.js +122 -0
  99. package/public/_app/immutable/nodes/2.D2auiZW1.js.map +1 -0
  100. package/public/_app/version.json +1 -1
  101. package/public/index.html +11 -11
  102. package/public/service-worker.js +1 -1
  103. package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
  104. package/public/_app/immutable/chunks/CkzyFwPn.js +0 -2
  105. package/public/_app/immutable/chunks/CkzyFwPn.js.map +0 -1
  106. package/public/_app/immutable/chunks/DJMI34rR.js +0 -2
  107. package/public/_app/immutable/chunks/idnZrCTB.js +0 -2
  108. package/public/_app/immutable/entry/start.GpPJ13Gr.js +0 -2
  109. package/public/_app/immutable/entry/start.GpPJ13Gr.js.map +0 -1
  110. package/public/_app/immutable/nodes/2._KcrsFWH.js +0 -120
  111. package/public/_app/immutable/nodes/2._KcrsFWH.js.map +0 -1
@@ -679,6 +679,8 @@ import { spawn } from 'node:child_process';
679
679
  import { randomUUID } from 'node:crypto';
680
680
  import { createAttachFileTool } from './attach-file-tool.js';
681
681
  import { createSayTool } from './say-tool.js';
682
+ import { assistantSessionParts } from './assistant-tools.js';
683
+ import { maybeSeedAssistantSession } from './assistant-folder.js';
682
684
  import { createConversationModeSignal } from './conversation-mode-hint.js';
683
685
  import { withoutCliBridgeExtension } from './cli-bridge-extension.js';
684
686
  import { serverBuiltinExtensions } from './builtin-extensions.js';
@@ -688,8 +690,41 @@ import { bindServerSessionExtensions, shutdownAndDisposeAgentSession, clearPiExt
688
690
  * without it (see SessionPool.initialize). */
689
691
  const EXTENSION_DISCOVERY_WAIT_MS = 10_000;
690
692
  import { matchRemoteRepoRule } from './remote-candidates.js';
693
+ import { ReplyRouting, WEB_ORIGIN } from './reply-routing.js';
691
694
  /** What a send (or model change) gets while the session's agent is being rebuilt. */
692
695
  export const RELOADING_REFUSAL = 'The session is reloading, so this was not delivered. Try again once it is ready.';
696
+ /**
697
+ * The extension factories and custom tools a server agent is built with. Pure,
698
+ * so the "assistant off = byte-identical" rule is testable without a pi
699
+ * runtime: with `assistant` undefined the result is exactly the pre-assistant
700
+ * set (pi's built-ins, the conversation-mode extension, the test seam's extras;
701
+ * `attach_file` and `say`). With it set, the assistant tools follow `say`, and
702
+ * in the assistant folder (or its `jobs/`) the timezone-line extension follows
703
+ * the conversation-mode one, so both APPEND to the prompt the event carries.
704
+ */
705
+ export function composeServerAgentParts(opts) {
706
+ const assistant = assistantSessionParts(opts.assistant, opts.cwd, opts.caller);
707
+ return {
708
+ extensionFactories: [
709
+ ...serverBuiltinExtensions,
710
+ opts.conversationExtension,
711
+ ...assistant.extensionFactories,
712
+ ...opts.extraExtensionFactories,
713
+ ],
714
+ customTools: [
715
+ createAttachFileTool(opts.cwd, () => getWhereverConfig().downloads),
716
+ createSayTool(),
717
+ ...assistant.customTools,
718
+ ],
719
+ };
720
+ }
721
+ /** `origins` aligned to `count` texts from the newest end; missing older ones are null. */
722
+ function alignFromEnd(count, origins) {
723
+ const out = new Array(count).fill(null);
724
+ for (let i = 1; i <= Math.min(count, origins.length); i++)
725
+ out[count - i] = origins[origins.length - i];
726
+ return out;
727
+ }
693
728
  export class SessionPool {
694
729
  sessions = new Map();
695
730
  pendingSessions = new Map();
@@ -718,7 +753,44 @@ export class SessionPool {
718
753
  pendingSudo = new Map();
719
754
  /** How long an unanswered sudo prompt survives, if its session outlives it. */
720
755
  static SUDO_PROMPT_TTL_MS = 30 * 60_000;
756
+ /**
757
+ * The WS broadcaster's slot (index.ts assigns it; tests assign it directly).
758
+ * It always runs FIRST for an event, before the pool's own idle bookkeeping
759
+ * and before any `subscribeEvents` listener, so its frames and their order
760
+ * are exactly what they were before the fan-out existed.
761
+ */
721
762
  onEvent;
763
+ /** Extra event subscribers (the fan-out beside `onEvent`), see `subscribeEvents`. */
764
+ eventListeners = new Set();
765
+ /**
766
+ * Per-user-message reply routing state (ADR 0014), keyed by session FILE so a
767
+ * CLI takeover (and the server agent rebuilt when the terminal leaves) keeps
768
+ * it. Always-on internal bookkeeping with no observable output: only
769
+ * `getReplyDestination` and `subscribeEvents` listeners read it. Dropped with
770
+ * the session entry.
771
+ */
772
+ routing = new Map();
773
+ /**
774
+ * Fired when a session is REALLY created: from `createNewSession` once the new
775
+ * session is in the pool, never when it hands back an existing viewed session
776
+ * and never for a caller that joined a pending create (that caller gets the
777
+ * same promise; the creation fired once). Registered only while the assistant
778
+ * is active (index.ts wires it to `AssistantController.handleSessionCreated`),
779
+ * so with `assistantFolder` unset nothing listens. A throwing or rejecting
780
+ * listener is logged and never fails the creation. `cli-bridge-foundation`
781
+ * also fires it for a `cli_register` with `isNew: true`.
782
+ */
783
+ onSessionCreated;
784
+ /**
785
+ * Session files exempt from CLI idle teardown (the current assistant session,
786
+ * pinned by the assistant controller). Only CLI-bridge entries honour it: an
787
+ * idle CLI session with no viewers is otherwise destroyed and its terminal
788
+ * reconnects with backoff, and a message sent in that window would build a
789
+ * SERVER agent on the same file beside the terminal's. A server session is
790
+ * still evicted as before; the controller reloads it before every send. Empty
791
+ * unless the assistant is active, so idle teardown is otherwise unchanged.
792
+ */
793
+ pinnedSessions = new Set();
722
794
  /**
723
795
  * Extra inline extensions loaded into EVERY server-created session, after the
724
796
  * built-in ones. Not used by the server itself; it is the seam tests use to
@@ -737,6 +809,28 @@ export class SessionPool {
737
809
  extensionShutdownTimeoutMs;
738
810
  /** When a stuck `session_start` gets logged (see extension-lifecycle.ts). */
739
811
  extensionBindWarnAfterMs;
812
+ /**
813
+ * The assistant folder THIS server holds the lock on (set once at start by
814
+ * `setAssistantFolder`), or undefined when the assistant is not configured or
815
+ * was refused. Only gates the `createNewSession` seeding hook for now.
816
+ */
817
+ assistantFolder;
818
+ /** Called once at server start with the ACTIVE assistant folder (see assistant-folder.ts). */
819
+ setAssistantFolder(folder) {
820
+ this.assistantFolder = folder;
821
+ }
822
+ /**
823
+ * The assistant's per-session additions (assistant-tools.ts): the
824
+ * `assistant_schedule_*` / `assistant_set_timezone` tools in EVERY server
825
+ * session, and the timezone line in the assistant folder and its `jobs/`. Set
826
+ * once at server start ONLY while `assistantFolder` is CONFIGURED (active or
827
+ * not: a refused server's tools answer a lock-state error), so with it unset a
828
+ * server session's tools, extensions and system prompt are exactly as before.
829
+ */
830
+ assistantHooks;
831
+ setAssistantSessionHooks(hooks) {
832
+ this.assistantHooks = hooks;
833
+ }
740
834
  constructor(idleTimeoutMs = 300_000, options = {}) {
741
835
  this.getStarred = options.getStarred ?? (() => new Set());
742
836
  // Before any extension can load: tells an in-process CLI bridge it must not
@@ -1248,6 +1342,9 @@ export class SessionPool {
1248
1342
  // search skill is preloaded). Self-healing:
1249
1343
  // re-created if the folder was deleted. Never clobbers an existing file.
1250
1344
  maybeSeedSearchWorkspace(resolvedCwd);
1345
+ // Same for the assistant folder: re-seeds any missing seed file, only when
1346
+ // this IS the active assistant folder (a no-op with the feature off).
1347
+ maybeSeedAssistantSession(resolvedCwd, this.assistantFolder);
1251
1348
  // Git initialization if requested. A folder that was just cloned already
1252
1349
  // has a `.git`, so the existence guard below makes this a no-op there.
1253
1350
  if (gitInit) {
@@ -1400,6 +1497,7 @@ export class SessionPool {
1400
1497
  conversationSignal,
1401
1498
  };
1402
1499
  this.sessions.set(sessionFile, tracked);
1500
+ this.emitSessionCreated(sessionFile, resolvedCwd);
1403
1501
  return { tracked, sessionFile };
1404
1502
  }
1405
1503
  catch (err) {
@@ -1412,6 +1510,119 @@ export class SessionPool {
1412
1510
  this.pendingCreateSessions.set(resolvedCwd, createPromise);
1413
1511
  return createPromise;
1414
1512
  }
1513
+ /**
1514
+ * Subscribe to every pool event, beside the WS broadcaster in `onEvent`
1515
+ * (which keeps running first, unchanged). Each listener is called after the
1516
+ * pool's own bookkeeping for the event, with the session's current reply
1517
+ * destination; a throwing or rejecting listener is logged and never affects
1518
+ * the broadcaster, the bookkeeping or the other listeners. Returns the
1519
+ * unsubscribe.
1520
+ */
1521
+ subscribeEvents(listener) {
1522
+ this.eventListeners.add(listener);
1523
+ return () => {
1524
+ this.eventListeners.delete(listener);
1525
+ };
1526
+ }
1527
+ /**
1528
+ * The origin (`none` for a web send, `telegram`, `schedule:<jobId>`, ...) of
1529
+ * the user message a session's current output answers, or null when it has
1530
+ * none (no user message yet, or one with nothing recorded for it, e.g. typed
1531
+ * directly in a CLI terminal). Updated on every user `message_end`.
1532
+ */
1533
+ getReplyDestination(sessionFileOrId) {
1534
+ const file = this.getSession(sessionFileOrId)?.sessionFile ?? normalizeSessionFile(sessionFileOrId);
1535
+ return this.routing.get(file)?.destination() ?? null;
1536
+ }
1537
+ /** The origins still waiting for their user message, oldest first (tests, diagnostics). */
1538
+ getRoutingSnapshot(sessionFileOrId) {
1539
+ const file = this.getSession(sessionFileOrId)?.sessionFile ?? normalizeSessionFile(sessionFileOrId);
1540
+ return this.routing.get(file)?.snapshot() ?? { promptOrSteer: [], followUp: [] };
1541
+ }
1542
+ routingFor(sessionFile) {
1543
+ let r = this.routing.get(sessionFile);
1544
+ if (!r) {
1545
+ r = new ReplyRouting();
1546
+ this.routing.set(sessionFile, r);
1547
+ }
1548
+ return r;
1549
+ }
1550
+ /**
1551
+ * Advance the routing state for an event, BEFORE anything sees it: a user
1552
+ * `message_end` sets the destination its output is fanned out with, and the
1553
+ * `agent_settled` trim runs before a settled handler can send (its new entry
1554
+ * must survive the trim). Server sessions trim to pi's real queue lengths;
1555
+ * CLI sessions, whose queues the server cannot see, are emptied.
1556
+ */
1557
+ routeEvent(tracked, event) {
1558
+ const r = this.routing.get(tracked.sessionFile);
1559
+ if (!r)
1560
+ return;
1561
+ if (event.type === 'message_end' && event.message?.role === 'user') {
1562
+ r.takeForUserMessage();
1563
+ }
1564
+ else if (event.type === 'agent_settled') {
1565
+ if (tracked.type === 'server') {
1566
+ r.trimToPiQueues(tracked.agentSession.getSteeringMessages().length, tracked.agentSession.getFollowUpMessages().length);
1567
+ }
1568
+ else {
1569
+ r.empty();
1570
+ }
1571
+ }
1572
+ }
1573
+ /** Broadcaster, then the extra listeners: for events the pool itself synthesises. */
1574
+ emitEvent(sessionFile, event) {
1575
+ if (this.onEvent)
1576
+ this.onEvent(sessionFile, event);
1577
+ this.notifyListeners(sessionFile, event);
1578
+ }
1579
+ notifyListeners(sessionFile, event) {
1580
+ if (this.eventListeners.size === 0)
1581
+ return;
1582
+ const destination = this.routing.get(sessionFile)?.destination() ?? null;
1583
+ const report = (err) => console.error(`[wherever] pool event listener failed for ${sessionFile}: ${err instanceof Error ? err.message : String(err)}`);
1584
+ for (const listener of [...this.eventListeners]) {
1585
+ try {
1586
+ const out = listener(sessionFile, event, destination);
1587
+ if (out && typeof out.then === 'function')
1588
+ out.then(undefined, report);
1589
+ }
1590
+ catch (err) {
1591
+ report(err);
1592
+ }
1593
+ }
1594
+ }
1595
+ /** Call `onSessionCreated`, isolating the creation from any listener failure. */
1596
+ emitSessionCreated(sessionFile, cwd) {
1597
+ const listener = this.onSessionCreated;
1598
+ if (!listener)
1599
+ return;
1600
+ const report = (err) => console.error(`[wherever] session-created listener failed for ${sessionFile}: ${err instanceof Error ? err.message : String(err)}`);
1601
+ try {
1602
+ const out = listener(sessionFile, cwd);
1603
+ if (out && typeof out.then === 'function')
1604
+ out.then(undefined, report);
1605
+ }
1606
+ catch (err) {
1607
+ report(err);
1608
+ }
1609
+ }
1610
+ /** Exempt a session file from CLI idle teardown (see `pinnedSessions`). */
1611
+ pinSession(sessionFile) {
1612
+ const key = normalizeSessionFile(sessionFile);
1613
+ this.pinnedSessions.add(key);
1614
+ const tracked = this.sessions.get(key);
1615
+ if (tracked?.type === 'cli')
1616
+ this.cancelIdleCheck(key);
1617
+ }
1618
+ /** Undo `pinSession`; an idle, unviewed CLI session becomes evictable again. */
1619
+ unpinSession(sessionFile) {
1620
+ const key = normalizeSessionFile(sessionFile);
1621
+ if (!this.pinnedSessions.delete(key))
1622
+ return;
1623
+ if (this.sessions.has(key))
1624
+ this.scheduleIdleCheck(key);
1625
+ }
1415
1626
  /**
1416
1627
  * Fork a session at a specific user message, mirroring pi's `/fork` with the
1417
1628
  * default `position: 'before'`. Opens the SOURCE session file, validates that
@@ -1600,6 +1811,24 @@ export class SessionPool {
1600
1811
  await annotateFolderExistence(folders);
1601
1812
  return folders;
1602
1813
  }
1814
+ /**
1815
+ * Where a session's transcript lives and which cwd it runs in, for a session
1816
+ * that is live (tracked) OR only on disk. Used by `GET /session/download`, which
1817
+ * must work for a session the server has not loaded (a deep link, a reload
1818
+ * after a restart): without the on-disk fallback it knew neither the cwd (so
1819
+ * even an in-cwd file 404ed) nor the transcript holding the attach grants.
1820
+ */
1821
+ async locateSession(sessionId) {
1822
+ const tracked = this.getSession(sessionId);
1823
+ if (tracked)
1824
+ return { sessionFile: tracked.sessionFile, cwd: tracked.cwd };
1825
+ // By id ONLY: a session NAME equal to this id must not shadow the real one.
1826
+ const infos = await scanDiskSessions(path.join(this.agentDir, 'sessions'), () => true, 'session lookup');
1827
+ const found = infos.find((s) => s.id === sessionId);
1828
+ if (!found)
1829
+ return undefined;
1830
+ return { sessionFile: found.path, cwd: resolveSessionCwd(found.cwd) };
1831
+ }
1603
1832
  /**
1604
1833
  * Find a session on disk by short ID or name, using the same cached scan as
1605
1834
  * listSessions(). Replaces `SessionManager.listAll()` on this lookup path:
@@ -1730,8 +1959,24 @@ export class SessionPool {
1730
1959
  * before_agent_start hook appends the hint to THIS turn's system prompt), and for
1731
1960
  * a CLI-bridge session it is relayed on `cli_message` so the extension's own
1732
1961
  * before_agent_start hook does the same in the bridged terminal pi.
1962
+ *
1963
+ * `origin` is where the message came from (ADR 0014): `telegram`,
1964
+ * `schedule:<jobId>`, ...; omitted = a web send, recorded as `none`. It is
1965
+ * recorded in the session's reply routing only for a send that WILL produce a
1966
+ * user message: never for a `!`/`!!` shell send or a non-resident session,
1967
+ * and dropped again when pi reports the message `handled` or the send throws.
1968
+ *
1969
+ * `images` are model IMAGE INPUTS sent with the message (task
1970
+ * `pool-send-images`, for a channel's photos): a server session passes them
1971
+ * to `prompt()` (pi normalizes and resizes them; a text-only model gets pi's
1972
+ * omission note instead), a CLI-bridge session relays them on `cli_message`
1973
+ * for the extension's `pi.sendUserMessage`. None (absent or empty) = exactly
1974
+ * the text-only send: `images: undefined` to `prompt()`, no `images` key on
1975
+ * `cli_message`. They never change routing (one send, one origin entry) and
1976
+ * are ignored by a `!`/`!!` shell send, which has no user message.
1733
1977
  */
1734
- async sendUserMessage(sessionFileOrId, text, streamingBehavior, conversationMode = false) {
1978
+ async sendUserMessage(sessionFileOrId, text, streamingBehavior, conversationMode = false, origin = WEB_ORIGIN, images) {
1979
+ const imageInputs = images && images.length > 0 ? images : undefined;
1735
1980
  const tracked = this.getSession(sessionFileOrId);
1736
1981
  if (!tracked)
1737
1982
  return;
@@ -1767,13 +2012,11 @@ export class SessionPool {
1767
2012
  excludeFromContext: isExcluded,
1768
2013
  armedAt: now,
1769
2014
  });
1770
- if (this.onEvent) {
1771
- this.onEvent(tracked.sessionFile, {
1772
- type: 'bash_sudo_prompt',
1773
- promptId,
1774
- command,
1775
- });
1776
- }
2015
+ this.emitEvent(tracked.sessionFile, {
2016
+ type: 'bash_sudo_prompt',
2017
+ promptId,
2018
+ command,
2019
+ });
1777
2020
  return;
1778
2021
  }
1779
2022
  if (tracked.type === 'server') {
@@ -1802,35 +2045,77 @@ export class SessionPool {
1802
2045
  // so browser/server sessions behave exactly like the pi CLI: all three
1803
2046
  // expansions are start-of-message anchored, and any trailing text after
1804
2047
  // "/skill:<name> " is preserved and appended after the skill block. Plain
1805
- // text keeps the sendUserMessage() path (extension "input"-event source).
2048
+ // text goes through prompt() exactly as sendUserMessage() would send it
2049
+ // (no expansion, extension "input"-event source); calling prompt() directly
2050
+ // is what lets the pool observe `preflightResult` for reply routing.
1806
2051
  // Counted as busy (synchronously, before the first await) so a /reload
1807
2052
  // cannot dispose the agent under a send that pi has not started streaming.
2053
+ const routing = this.routingFor(tracked.sessionFile);
2054
+ const ticket = routing.record(origin, streamingBehavior === 'followUp' ? 'followUp' : 'promptOrSteer');
2055
+ let preflightSeen = false;
2056
+ const preflightResult = (disposition) => {
2057
+ preflightSeen = true;
2058
+ if (disposition === 'handled')
2059
+ routing.drop(ticket);
2060
+ else if (disposition === 'started')
2061
+ routing.started(ticket);
2062
+ else
2063
+ routing.queued(ticket);
2064
+ };
1808
2065
  tracked.busy = (tracked.busy ?? 0) + 1;
1809
2066
  try {
1810
2067
  if (text.startsWith('/')) {
1811
2068
  await tracked.agentSession.prompt(text, {
1812
2069
  expandPromptTemplates: true,
2070
+ images: imageInputs,
1813
2071
  streamingBehavior,
1814
2072
  source: 'interactive',
2073
+ preflightResult,
1815
2074
  });
1816
2075
  }
1817
2076
  else {
1818
- await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
2077
+ await tracked.agentSession.prompt(text, {
2078
+ expandPromptTemplates: false,
2079
+ images: imageInputs,
2080
+ streamingBehavior,
2081
+ source: 'extension',
2082
+ preflightResult,
2083
+ });
1819
2084
  }
2085
+ // Returned without a preflight: pi deferred it (sent while it emits
2086
+ // agent_settled). It stays pending until the deferred prompt runs.
2087
+ if (!preflightSeen)
2088
+ routing.deferred(ticket);
2089
+ }
2090
+ catch (err) {
2091
+ routing.drop(ticket);
2092
+ throw err;
1820
2093
  }
1821
2094
  finally {
1822
2095
  tracked.busy -= 1;
1823
2096
  }
1824
2097
  }
1825
2098
  else if (tracked.type === 'cli') {
2099
+ // The server cannot see the terminal pi's preflight, so the entry stands
2100
+ // as relayed (ADR 0014's accepted CLI cost).
2101
+ const routing = this.routingFor(tracked.sessionFile);
2102
+ const ticket = routing.record(origin, streamingBehavior === 'followUp' ? 'followUp' : 'promptOrSteer');
1826
2103
  // Relay the signal to the bridged pi (omitted when off, so the payload is
1827
2104
  // unchanged for a non-conversation message and older extensions are fine).
1828
- tracked.cliWs.send(JSON.stringify({
1829
- type: 'cli_message',
1830
- message: text,
1831
- streamingBehavior,
1832
- ...(conversationMode ? { conversationMode: true } : {}),
1833
- }));
2105
+ try {
2106
+ tracked.cliWs.send(JSON.stringify({
2107
+ type: 'cli_message',
2108
+ message: text,
2109
+ streamingBehavior,
2110
+ ...(conversationMode ? { conversationMode: true } : {}),
2111
+ ...(imageInputs ? { images: imageInputs } : {}),
2112
+ }));
2113
+ routing.relayed(ticket);
2114
+ }
2115
+ catch (err) {
2116
+ routing.drop(ticket);
2117
+ throw err;
2118
+ }
1834
2119
  }
1835
2120
  }
1836
2121
  // True when a `!command` invokes sudo as its leading program. We only special-
@@ -1857,44 +2142,36 @@ export class SessionPool {
1857
2142
  }
1858
2143
  }
1859
2144
  async runServerBashUnguarded(tracked, command, excludeFromContext, operations) {
1860
- if (this.onEvent) {
1861
- this.onEvent(tracked.sessionFile, {
1862
- type: 'tool_execution_start',
1863
- toolName: 'bash',
1864
- args: { command },
1865
- forceCommand: true,
1866
- });
1867
- }
2145
+ this.emitEvent(tracked.sessionFile, {
2146
+ type: 'tool_execution_start',
2147
+ toolName: 'bash',
2148
+ args: { command },
2149
+ forceCommand: true,
2150
+ });
1868
2151
  try {
1869
2152
  const result = await tracked.agentSession.executeBash(command, (chunk) => {
1870
- if (this.onEvent) {
1871
- this.onEvent(tracked.sessionFile, {
1872
- type: 'tool_execution_update',
1873
- toolName: 'bash',
1874
- delta: chunk,
1875
- });
1876
- }
1877
- }, { excludeFromContext, operations });
1878
- if (this.onEvent) {
1879
- this.onEvent(tracked.sessionFile, {
1880
- type: 'tool_execution_end',
2153
+ this.emitEvent(tracked.sessionFile, {
2154
+ type: 'tool_execution_update',
1881
2155
  toolName: 'bash',
1882
- result: result.output,
1883
- isError: result.exitCode !== 0,
1884
- forceCommand: true,
2156
+ delta: chunk,
1885
2157
  });
1886
- }
2158
+ }, { excludeFromContext, operations });
2159
+ this.emitEvent(tracked.sessionFile, {
2160
+ type: 'tool_execution_end',
2161
+ toolName: 'bash',
2162
+ result: result.output,
2163
+ isError: result.exitCode !== 0,
2164
+ forceCommand: true,
2165
+ });
1887
2166
  }
1888
2167
  catch (err) {
1889
- if (this.onEvent) {
1890
- this.onEvent(tracked.sessionFile, {
1891
- type: 'tool_execution_end',
1892
- toolName: 'bash',
1893
- result: err.message,
1894
- isError: true,
1895
- forceCommand: true,
1896
- });
1897
- }
2168
+ this.emitEvent(tracked.sessionFile, {
2169
+ type: 'tool_execution_end',
2170
+ toolName: 'bash',
2171
+ result: err.message,
2172
+ isError: true,
2173
+ forceCommand: true,
2174
+ });
1898
2175
  }
1899
2176
  }
1900
2177
  // Build BashOperations that run a leading-`sudo` command non-interactively by
@@ -2033,12 +2310,52 @@ export class SessionPool {
2033
2310
  return null;
2034
2311
  return [...tracked.agentSession.getSteeringMessages()];
2035
2312
  }
2313
+ /**
2314
+ * Clear pi's pending steer AND followUp queues and return what was dropped
2315
+ * (the assistant reset records them, ADR 0014: an abort leaves them queued).
2316
+ * Null when the session is not resident or is a CLI bridge (whose queues the
2317
+ * server cannot see).
2318
+ *
2319
+ * `origins` gives each dropped text its routing origin (aligned by index,
2320
+ * null = not known), so the channel seam can report a dropped message to the
2321
+ * channel it came from. The routing entries are paired with pi's texts from
2322
+ * the NEWEST end, the same alignment the settle trim keeps (`trimToPiQueues`
2323
+ * keeps the newest): an older text with no entry left (e.g. a message typed
2324
+ * before the routing state existed) gets null.
2325
+ */
2326
+ clearQueuedMessages(sessionFileOrId) {
2327
+ const tracked = this.getSession(sessionFileOrId);
2328
+ if (!tracked || tracked.type !== 'server')
2329
+ return null;
2330
+ const cleared = tracked.agentSession.clearQueue();
2331
+ const dropped = this.routing.get(tracked.sessionFile)?.clear() ?? { promptOrSteer: [], followUp: [] };
2332
+ const steering = [...cleared.steering];
2333
+ const followUp = [...cleared.followUp];
2334
+ return {
2335
+ steering,
2336
+ followUp,
2337
+ origins: { steering: alignFromEnd(steering.length, dropped.promptOrSteer), followUp: alignFromEnd(followUp.length, dropped.followUp) },
2338
+ };
2339
+ }
2340
+ /**
2341
+ * How many messages pi holds queued (steer + followUp), or null when the
2342
+ * session is not resident or is a CLI bridge (whose queues the server cannot
2343
+ * see). The assistant scheduler delivers an inline job only once this is 0.
2344
+ */
2345
+ getQueuedMessageCount(sessionFileOrId) {
2346
+ const tracked = this.getSession(sessionFileOrId);
2347
+ if (!tracked || tracked.type !== 'server')
2348
+ return null;
2349
+ return tracked.agentSession.getSteeringMessages().length + tracked.agentSession.getFollowUpMessages().length;
2350
+ }
2036
2351
  async cancelSteerQueue(sessionFileOrId) {
2037
2352
  const tracked = this.getSession(sessionFileOrId);
2038
2353
  if (!tracked)
2039
2354
  return;
2040
2355
  if (tracked.type === 'server') {
2041
2356
  tracked.agentSession.clearQueue();
2357
+ // pi dropped its whole queue: so do the routing queues (ADR 0014).
2358
+ this.routing.get(tracked.sessionFile)?.clear();
2042
2359
  }
2043
2360
  }
2044
2361
  async changeModel(sessionFileOrId, modelStr) {
@@ -2127,6 +2444,8 @@ export class SessionPool {
2127
2444
  if (!tracked)
2128
2445
  return;
2129
2446
  this.cancelIdleCheck(tracked.sessionFile);
2447
+ if (tracked.type === 'cli' && this.pinnedSessions.has(tracked.sessionFile))
2448
+ return;
2130
2449
  if (tracked.clients.size === 0 && tracked.isIdle) {
2131
2450
  tracked.idleTimer = setTimeout(() => {
2132
2451
  this.destroySession(tracked.sessionFile, 'idle timeout');
@@ -2171,7 +2490,16 @@ export class SessionPool {
2171
2490
  this.dropSessionEntry(tracked);
2172
2491
  return teardown;
2173
2492
  }
2174
- async registerCliSession(rawSessionFile, cwd, modelStr, cliWs, isStreaming = false) {
2493
+ /**
2494
+ * Register (or re-register) a CLI-bridge session. `opts.isNew` is the
2495
+ * extension's claim that the session had no messages at its session_start
2496
+ * (ADR 0016): it fires `onSessionCreated` once the entry is in the pool, so a
2497
+ * fresh terminal `pi` in `assistantFolder` moves the assistant pointer. Only
2498
+ * when the pool had no entry for the file: a session the pool already tracks
2499
+ * was not just created, whatever the claim. `opts.capabilities` is stored on
2500
+ * the entry (see `getCliCapabilities`).
2501
+ */
2502
+ async registerCliSession(rawSessionFile, cwd, modelStr, cliWs, isStreaming = false, opts = {}) {
2175
2503
  // Canonicalize the CLI-reported path so it keys the same entry the server
2176
2504
  // would compute itself (see normalizeSessionFile). Without this, a CLI on a
2177
2505
  // different pi version can register a second, parallel session for the same
@@ -2261,6 +2589,9 @@ export class SessionPool {
2261
2589
  // joining a mid-tool-call CLI session would see Abort disabled + an enabled
2262
2590
  // composer while the CLI is still working. isStreaming carries that state.
2263
2591
  isStreaming,
2592
+ capabilities: Array.isArray(opts.capabilities)
2593
+ ? opts.capabilities.filter((c) => typeof c === 'string')
2594
+ : [],
2264
2595
  };
2265
2596
  // A session registered mid-turn is not idle; keep it from being idle-reaped.
2266
2597
  if (isStreaming) {
@@ -2269,8 +2600,19 @@ export class SessionPool {
2269
2600
  }
2270
2601
  this.sessions.set(sessionFile, tracked);
2271
2602
  await serverTeardown;
2603
+ if (opts.isNew === true && !existing)
2604
+ this.emitSessionCreated(sessionFile, normalizedCwd);
2272
2605
  return { tracked, interruptedTurn, interruptedToolCall };
2273
2606
  }
2607
+ /**
2608
+ * The capabilities a CLI-bridge session's extension reported on register
2609
+ * (`agent_settled`, `cli_request`, ...), or null when the session is not a
2610
+ * resident CLI-bridge session. Empty for an older extension.
2611
+ */
2612
+ getCliCapabilities(sessionFileOrId) {
2613
+ const tracked = this.getSession(sessionFileOrId);
2614
+ return tracked?.type === 'cli' ? tracked.capabilities : null;
2615
+ }
2274
2616
  async unregisterCliSession(rawSessionFile) {
2275
2617
  const sessionFile = normalizeSessionFile(rawSessionFile);
2276
2618
  const tracked = this.sessions.get(sessionFile);
@@ -2283,15 +2625,13 @@ export class SessionPool {
2283
2625
  const result = await this.loadSession(sessionFile, tracked.cwd, tracked.model);
2284
2626
  if (!result.error && result.tracked) {
2285
2627
  result.tracked.clients = tracked.clients;
2286
- if (this.onEvent) {
2287
- if (tracked.isStreaming) {
2288
- this.onEvent(sessionFile, {
2289
- type: 'session_error',
2290
- error: 'CLI terminal disconnected. Active execution was aborted.'
2291
- });
2292
- }
2293
- this.onEvent(sessionFile, { type: 'agent_end' });
2628
+ if (tracked.isStreaming) {
2629
+ this.emitEvent(sessionFile, {
2630
+ type: 'session_error',
2631
+ error: 'CLI terminal disconnected. Active execution was aborted.'
2632
+ });
2294
2633
  }
2634
+ this.emitEvent(sessionFile, { type: 'agent_end' });
2295
2635
  }
2296
2636
  }
2297
2637
  }
@@ -2323,9 +2663,10 @@ export class SessionPool {
2323
2663
  // on join, and let it flow through onEvent for live broadcast.
2324
2664
  tracked.contextUsage = event.contextUsage ?? null;
2325
2665
  }
2326
- if (this.onEvent) {
2327
- this.onEvent(sessionFile, event);
2328
- }
2666
+ // A forwarded user message_end (the extension does not forward
2667
+ // message_start) and, once forwarded, agent_settled drive the routing.
2668
+ this.routeEvent(tracked, event);
2669
+ this.emitEvent(sessionFile, event);
2329
2670
  }
2330
2671
  async disposeAll() {
2331
2672
  const sessionIds = Array.from(this.sessions.keys());
@@ -2347,13 +2688,24 @@ export class SessionPool {
2347
2688
  // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
2348
2689
  // per session, so the armed flag can never cross sessions.
2349
2690
  const conversationSignal = createConversationModeSignal();
2691
+ const parts = composeServerAgentParts({
2692
+ cwd: opts.cwd,
2693
+ conversationExtension: conversationSignal.inlineExtension,
2694
+ extraExtensionFactories: this.extraExtensionFactories,
2695
+ assistant: this.assistantHooks,
2696
+ caller: () => ({
2697
+ sessionId: opts.sessionManager.getSessionId() ?? null,
2698
+ cwd: opts.cwd,
2699
+ sessionFile: opts.sessionManager.getSessionFile() ?? null,
2700
+ }),
2701
+ });
2350
2702
  const resourceLoader = new DefaultResourceLoader({
2351
2703
  cwd: opts.cwd,
2352
2704
  agentDir: this.agentDir,
2353
2705
  settingsManager,
2354
2706
  // pi's built-in MCP, codemode and tool search come first, as in the CLI
2355
2707
  // (see builtin-extensions.ts: the SDK does not load them by itself).
2356
- extensionFactories: [...serverBuiltinExtensions, conversationSignal.inlineExtension, ...this.extraExtensionFactories],
2708
+ extensionFactories: parts.extensionFactories,
2357
2709
  // Never the CLI bridge (`@wherever-dev/pi`) in a server session: in-process
2358
2710
  // it registers this very session as a CLI and loops takeover/handback. The
2359
2711
  // identification rule is documented at isCliBridgeExtensionPath.
@@ -2384,7 +2736,9 @@ export class SessionPool {
2384
2736
  // with no CLI bridge). Both tools are self-contained; their UI affordance
2385
2737
  // (attach_file's download button, say's spoken-reply card) is driven by
2386
2738
  // the tool call reaching the web UI, no bridge/marker needed.
2387
- customTools: [createAttachFileTool(opts.cwd), createSayTool()],
2739
+ // Plus, while `assistantFolder` is configured, the assistant tools (see
2740
+ // composeServerAgentParts).
2741
+ customTools: parts.customTools,
2388
2742
  sessionStartEvent: opts.sessionStartEvent,
2389
2743
  });
2390
2744
  // Start the extensions BEFORE the session is tracked or reaches a client:
@@ -2513,6 +2867,8 @@ export class SessionPool {
2513
2867
  dropSessionEntry(tracked) {
2514
2868
  this.cancelIdleCheck(tracked.sessionFile);
2515
2869
  this.sessions.delete(tracked.sessionFile);
2870
+ // Its pi queues went with the agent (destroyed, or a failed reload).
2871
+ this.routing.delete(tracked.sessionFile);
2516
2872
  for (const [id, p] of this.pendingSudo) {
2517
2873
  if (p.sessionFileOrId === tracked.sessionFile)
2518
2874
  this.pendingSudo.delete(id);
@@ -2537,49 +2893,57 @@ export class SessionPool {
2537
2893
  const tracked = this.sessions.get(sessionFile);
2538
2894
  if (!tracked)
2539
2895
  return;
2896
+ // Routing first (the destination this event is fanned out with, and the
2897
+ // settle trim before a settled handler can send), then the broadcaster,
2898
+ // then the pool's own bookkeeping, then the extra listeners.
2899
+ this.routeEvent(tracked, event);
2540
2900
  if (this.onEvent) {
2541
2901
  this.onEvent(sessionFile, event);
2542
2902
  }
2543
- switch (event.type) {
2544
- case 'agent_start':
2545
- tracked.isIdle = false;
2546
- tracked.lastActivity = Date.now();
2547
- this.cancelIdleCheck(sessionFile);
2548
- break;
2549
- case 'agent_end':
2550
- tracked.isIdle = true;
2551
- tracked.lastActivity = Date.now();
2552
- // A turn ended: nothing is in flight anymore. Reset defensively in case
2553
- // a start/end pair was ever missed, so the count cannot drift positive.
2554
- if (tracked.type === 'server')
2555
- tracked.inFlightToolCount = 0;
2556
- this.scheduleIdleCheck(sessionFile);
2557
- break;
2558
- case 'tool_execution_start':
2559
- if (tracked.type === 'server')
2560
- tracked.inFlightToolCount++;
2561
- tracked.lastActivity = Date.now();
2562
- break;
2563
- case 'tool_execution_end':
2564
- // Clamp at 0: an unmatched end must never make the count negative.
2565
- if (tracked.type === 'server')
2566
- tracked.inFlightToolCount = Math.max(0, tracked.inFlightToolCount - 1);
2567
- tracked.lastActivity = Date.now();
2568
- break;
2569
- case 'message_update':
2570
- case 'message_end':
2571
- tracked.lastActivity = Date.now();
2572
- break;
2573
- case 'model_select': {
2574
- const evt = event;
2575
- const modelStr = evt.model ? `${evt.model.provider}:${evt.model.id}` : '';
2576
- if (modelStr) {
2577
- tracked.model = modelStr;
2578
- }
2579
- break;
2903
+ this.applyEventBookkeeping(sessionFile, tracked, event);
2904
+ this.notifyListeners(sessionFile, event);
2905
+ });
2906
+ }
2907
+ applyEventBookkeeping(sessionFile, tracked, event) {
2908
+ switch (event.type) {
2909
+ case 'agent_start':
2910
+ tracked.isIdle = false;
2911
+ tracked.lastActivity = Date.now();
2912
+ this.cancelIdleCheck(sessionFile);
2913
+ break;
2914
+ case 'agent_end':
2915
+ tracked.isIdle = true;
2916
+ tracked.lastActivity = Date.now();
2917
+ // A turn ended: nothing is in flight anymore. Reset defensively in case
2918
+ // a start/end pair was ever missed, so the count cannot drift positive.
2919
+ if (tracked.type === 'server')
2920
+ tracked.inFlightToolCount = 0;
2921
+ this.scheduleIdleCheck(sessionFile);
2922
+ break;
2923
+ case 'tool_execution_start':
2924
+ if (tracked.type === 'server')
2925
+ tracked.inFlightToolCount++;
2926
+ tracked.lastActivity = Date.now();
2927
+ break;
2928
+ case 'tool_execution_end':
2929
+ // Clamp at 0: an unmatched end must never make the count negative.
2930
+ if (tracked.type === 'server')
2931
+ tracked.inFlightToolCount = Math.max(0, tracked.inFlightToolCount - 1);
2932
+ tracked.lastActivity = Date.now();
2933
+ break;
2934
+ case 'message_update':
2935
+ case 'message_end':
2936
+ tracked.lastActivity = Date.now();
2937
+ break;
2938
+ case 'model_select': {
2939
+ const evt = event;
2940
+ const modelStr = evt.model ? `${evt.model.provider}:${evt.model.id}` : '';
2941
+ if (modelStr) {
2942
+ tracked.model = modelStr;
2580
2943
  }
2944
+ break;
2581
2945
  }
2582
- });
2946
+ }
2583
2947
  }
2584
2948
  parseModelStr(modelStr) {
2585
2949
  const colonIdx = modelStr.indexOf(':');