wherever-dev 0.21.1 → 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 (103) hide show
  1. package/CHANGELOG.md +20 -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/cli-requests.d.ts +90 -0
  35. package/dist/cli-requests.d.ts.map +1 -0
  36. package/dist/cli-requests.js +75 -0
  37. package/dist/cli-requests.js.map +1 -0
  38. package/dist/index.js +396 -7
  39. package/dist/index.js.map +1 -1
  40. package/dist/protocol.d.ts +43 -0
  41. package/dist/protocol.d.ts.map +1 -1
  42. package/dist/reply-routing.d.ts +106 -0
  43. package/dist/reply-routing.d.ts.map +1 -0
  44. package/dist/reply-routing.js +174 -0
  45. package/dist/reply-routing.js.map +1 -0
  46. package/dist/session-pool.d.ts +232 -4
  47. package/dist/session-pool.d.ts.map +1 -1
  48. package/dist/session-pool.js +446 -100
  49. package/dist/session-pool.js.map +1 -1
  50. package/dist/telegram-channel.d.ts +272 -0
  51. package/dist/telegram-channel.d.ts.map +1 -0
  52. package/dist/telegram-channel.js +701 -0
  53. package/dist/telegram-channel.js.map +1 -0
  54. package/dist/telegram-files.d.ts +101 -0
  55. package/dist/telegram-files.d.ts.map +1 -0
  56. package/dist/telegram-files.js +145 -0
  57. package/dist/telegram-files.js.map +1 -0
  58. package/dist/telegram-pairing.d.ts +119 -0
  59. package/dist/telegram-pairing.d.ts.map +1 -0
  60. package/dist/telegram-pairing.js +97 -0
  61. package/dist/telegram-pairing.js.map +1 -0
  62. package/dist/telegram-replies.d.ts +94 -0
  63. package/dist/telegram-replies.d.ts.map +1 -0
  64. package/dist/telegram-replies.js +329 -0
  65. package/dist/telegram-replies.js.map +1 -0
  66. package/dist/telegram-token.d.ts +55 -0
  67. package/dist/telegram-token.d.ts.map +1 -0
  68. package/dist/telegram-token.js +86 -0
  69. package/dist/telegram-token.js.map +1 -0
  70. package/dist/web-push.d.ts +167 -0
  71. package/dist/web-push.d.ts.map +1 -0
  72. package/dist/web-push.js +387 -0
  73. package/dist/web-push.js.map +1 -0
  74. package/package.json +1 -1
  75. package/public/_app/immutable/assets/0.BkzT3rFr.css +1 -0
  76. package/public/_app/immutable/chunks/CExVgK9Z.js +2 -0
  77. package/public/_app/immutable/chunks/CExVgK9Z.js.map +1 -0
  78. package/public/_app/immutable/chunks/CkOw6fRa.js +2 -0
  79. package/public/_app/immutable/chunks/{BQ9B_G4h.js.map → CkOw6fRa.js.map} +1 -1
  80. package/public/_app/immutable/chunks/DyHllYtq.js +2 -0
  81. package/public/_app/immutable/chunks/{BUONgvl4.js.map → DyHllYtq.js.map} +1 -1
  82. package/public/_app/immutable/entry/{app.BZO7Xckk.js → app.D3PEFbtP.js} +3 -3
  83. package/public/_app/immutable/entry/{app.BZO7Xckk.js.map → app.D3PEFbtP.js.map} +1 -1
  84. package/public/_app/immutable/entry/start.BR00Qps5.js +2 -0
  85. package/public/_app/immutable/entry/start.BR00Qps5.js.map +1 -0
  86. package/public/_app/immutable/nodes/{0.Czz2XmZU.js → 0.DG3L8hMN.js} +3 -3
  87. package/public/_app/immutable/nodes/{0.Czz2XmZU.js.map → 0.DG3L8hMN.js.map} +1 -1
  88. package/public/_app/immutable/nodes/{1.DDvrriUW.js → 1.BCpuoZxW.js} +2 -2
  89. package/public/_app/immutable/nodes/{1.DDvrriUW.js.map → 1.BCpuoZxW.js.map} +1 -1
  90. package/public/_app/immutable/nodes/2.D2auiZW1.js +122 -0
  91. package/public/_app/immutable/nodes/2.D2auiZW1.js.map +1 -0
  92. package/public/_app/version.json +1 -1
  93. package/public/index.html +11 -11
  94. package/public/service-worker.js +1 -1
  95. package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
  96. package/public/_app/immutable/chunks/BQ9B_G4h.js +0 -2
  97. package/public/_app/immutable/chunks/BUONgvl4.js +0 -2
  98. package/public/_app/immutable/chunks/DauELski.js +0 -2
  99. package/public/_app/immutable/chunks/DauELski.js.map +0 -1
  100. package/public/_app/immutable/entry/start.DWD60uNu.js +0 -2
  101. package/public/_app/immutable/entry/start.DWD60uNu.js.map +0 -1
  102. package/public/_app/immutable/nodes/2.C7E8EMKX.js +0 -120
  103. package/public/_app/immutable/nodes/2.C7E8EMKX.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
@@ -1748,8 +1959,24 @@ export class SessionPool {
1748
1959
  * before_agent_start hook appends the hint to THIS turn's system prompt), and for
1749
1960
  * a CLI-bridge session it is relayed on `cli_message` so the extension's own
1750
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.
1751
1977
  */
1752
- 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;
1753
1980
  const tracked = this.getSession(sessionFileOrId);
1754
1981
  if (!tracked)
1755
1982
  return;
@@ -1785,13 +2012,11 @@ export class SessionPool {
1785
2012
  excludeFromContext: isExcluded,
1786
2013
  armedAt: now,
1787
2014
  });
1788
- if (this.onEvent) {
1789
- this.onEvent(tracked.sessionFile, {
1790
- type: 'bash_sudo_prompt',
1791
- promptId,
1792
- command,
1793
- });
1794
- }
2015
+ this.emitEvent(tracked.sessionFile, {
2016
+ type: 'bash_sudo_prompt',
2017
+ promptId,
2018
+ command,
2019
+ });
1795
2020
  return;
1796
2021
  }
1797
2022
  if (tracked.type === 'server') {
@@ -1820,35 +2045,77 @@ export class SessionPool {
1820
2045
  // so browser/server sessions behave exactly like the pi CLI: all three
1821
2046
  // expansions are start-of-message anchored, and any trailing text after
1822
2047
  // "/skill:<name> " is preserved and appended after the skill block. Plain
1823
- // 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.
1824
2051
  // Counted as busy (synchronously, before the first await) so a /reload
1825
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
+ };
1826
2065
  tracked.busy = (tracked.busy ?? 0) + 1;
1827
2066
  try {
1828
2067
  if (text.startsWith('/')) {
1829
2068
  await tracked.agentSession.prompt(text, {
1830
2069
  expandPromptTemplates: true,
2070
+ images: imageInputs,
1831
2071
  streamingBehavior,
1832
2072
  source: 'interactive',
2073
+ preflightResult,
1833
2074
  });
1834
2075
  }
1835
2076
  else {
1836
- 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
+ });
1837
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;
1838
2093
  }
1839
2094
  finally {
1840
2095
  tracked.busy -= 1;
1841
2096
  }
1842
2097
  }
1843
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');
1844
2103
  // Relay the signal to the bridged pi (omitted when off, so the payload is
1845
2104
  // unchanged for a non-conversation message and older extensions are fine).
1846
- tracked.cliWs.send(JSON.stringify({
1847
- type: 'cli_message',
1848
- message: text,
1849
- streamingBehavior,
1850
- ...(conversationMode ? { conversationMode: true } : {}),
1851
- }));
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
+ }
1852
2119
  }
1853
2120
  }
1854
2121
  // True when a `!command` invokes sudo as its leading program. We only special-
@@ -1875,44 +2142,36 @@ export class SessionPool {
1875
2142
  }
1876
2143
  }
1877
2144
  async runServerBashUnguarded(tracked, command, excludeFromContext, operations) {
1878
- if (this.onEvent) {
1879
- this.onEvent(tracked.sessionFile, {
1880
- type: 'tool_execution_start',
1881
- toolName: 'bash',
1882
- args: { command },
1883
- forceCommand: true,
1884
- });
1885
- }
2145
+ this.emitEvent(tracked.sessionFile, {
2146
+ type: 'tool_execution_start',
2147
+ toolName: 'bash',
2148
+ args: { command },
2149
+ forceCommand: true,
2150
+ });
1886
2151
  try {
1887
2152
  const result = await tracked.agentSession.executeBash(command, (chunk) => {
1888
- if (this.onEvent) {
1889
- this.onEvent(tracked.sessionFile, {
1890
- type: 'tool_execution_update',
1891
- toolName: 'bash',
1892
- delta: chunk,
1893
- });
1894
- }
1895
- }, { excludeFromContext, operations });
1896
- if (this.onEvent) {
1897
- this.onEvent(tracked.sessionFile, {
1898
- type: 'tool_execution_end',
2153
+ this.emitEvent(tracked.sessionFile, {
2154
+ type: 'tool_execution_update',
1899
2155
  toolName: 'bash',
1900
- result: result.output,
1901
- isError: result.exitCode !== 0,
1902
- forceCommand: true,
2156
+ delta: chunk,
1903
2157
  });
1904
- }
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
+ });
1905
2166
  }
1906
2167
  catch (err) {
1907
- if (this.onEvent) {
1908
- this.onEvent(tracked.sessionFile, {
1909
- type: 'tool_execution_end',
1910
- toolName: 'bash',
1911
- result: err.message,
1912
- isError: true,
1913
- forceCommand: true,
1914
- });
1915
- }
2168
+ this.emitEvent(tracked.sessionFile, {
2169
+ type: 'tool_execution_end',
2170
+ toolName: 'bash',
2171
+ result: err.message,
2172
+ isError: true,
2173
+ forceCommand: true,
2174
+ });
1916
2175
  }
1917
2176
  }
1918
2177
  // Build BashOperations that run a leading-`sudo` command non-interactively by
@@ -2051,12 +2310,52 @@ export class SessionPool {
2051
2310
  return null;
2052
2311
  return [...tracked.agentSession.getSteeringMessages()];
2053
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
+ }
2054
2351
  async cancelSteerQueue(sessionFileOrId) {
2055
2352
  const tracked = this.getSession(sessionFileOrId);
2056
2353
  if (!tracked)
2057
2354
  return;
2058
2355
  if (tracked.type === 'server') {
2059
2356
  tracked.agentSession.clearQueue();
2357
+ // pi dropped its whole queue: so do the routing queues (ADR 0014).
2358
+ this.routing.get(tracked.sessionFile)?.clear();
2060
2359
  }
2061
2360
  }
2062
2361
  async changeModel(sessionFileOrId, modelStr) {
@@ -2145,6 +2444,8 @@ export class SessionPool {
2145
2444
  if (!tracked)
2146
2445
  return;
2147
2446
  this.cancelIdleCheck(tracked.sessionFile);
2447
+ if (tracked.type === 'cli' && this.pinnedSessions.has(tracked.sessionFile))
2448
+ return;
2148
2449
  if (tracked.clients.size === 0 && tracked.isIdle) {
2149
2450
  tracked.idleTimer = setTimeout(() => {
2150
2451
  this.destroySession(tracked.sessionFile, 'idle timeout');
@@ -2189,7 +2490,16 @@ export class SessionPool {
2189
2490
  this.dropSessionEntry(tracked);
2190
2491
  return teardown;
2191
2492
  }
2192
- 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 = {}) {
2193
2503
  // Canonicalize the CLI-reported path so it keys the same entry the server
2194
2504
  // would compute itself (see normalizeSessionFile). Without this, a CLI on a
2195
2505
  // different pi version can register a second, parallel session for the same
@@ -2279,6 +2589,9 @@ export class SessionPool {
2279
2589
  // joining a mid-tool-call CLI session would see Abort disabled + an enabled
2280
2590
  // composer while the CLI is still working. isStreaming carries that state.
2281
2591
  isStreaming,
2592
+ capabilities: Array.isArray(opts.capabilities)
2593
+ ? opts.capabilities.filter((c) => typeof c === 'string')
2594
+ : [],
2282
2595
  };
2283
2596
  // A session registered mid-turn is not idle; keep it from being idle-reaped.
2284
2597
  if (isStreaming) {
@@ -2287,8 +2600,19 @@ export class SessionPool {
2287
2600
  }
2288
2601
  this.sessions.set(sessionFile, tracked);
2289
2602
  await serverTeardown;
2603
+ if (opts.isNew === true && !existing)
2604
+ this.emitSessionCreated(sessionFile, normalizedCwd);
2290
2605
  return { tracked, interruptedTurn, interruptedToolCall };
2291
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
+ }
2292
2616
  async unregisterCliSession(rawSessionFile) {
2293
2617
  const sessionFile = normalizeSessionFile(rawSessionFile);
2294
2618
  const tracked = this.sessions.get(sessionFile);
@@ -2301,15 +2625,13 @@ export class SessionPool {
2301
2625
  const result = await this.loadSession(sessionFile, tracked.cwd, tracked.model);
2302
2626
  if (!result.error && result.tracked) {
2303
2627
  result.tracked.clients = tracked.clients;
2304
- if (this.onEvent) {
2305
- if (tracked.isStreaming) {
2306
- this.onEvent(sessionFile, {
2307
- type: 'session_error',
2308
- error: 'CLI terminal disconnected. Active execution was aborted.'
2309
- });
2310
- }
2311
- 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
+ });
2312
2633
  }
2634
+ this.emitEvent(sessionFile, { type: 'agent_end' });
2313
2635
  }
2314
2636
  }
2315
2637
  }
@@ -2341,9 +2663,10 @@ export class SessionPool {
2341
2663
  // on join, and let it flow through onEvent for live broadcast.
2342
2664
  tracked.contextUsage = event.contextUsage ?? null;
2343
2665
  }
2344
- if (this.onEvent) {
2345
- this.onEvent(sessionFile, event);
2346
- }
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);
2347
2670
  }
2348
2671
  async disposeAll() {
2349
2672
  const sessionIds = Array.from(this.sessions.keys());
@@ -2365,13 +2688,24 @@ export class SessionPool {
2365
2688
  // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
2366
2689
  // per session, so the armed flag can never cross sessions.
2367
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
+ });
2368
2702
  const resourceLoader = new DefaultResourceLoader({
2369
2703
  cwd: opts.cwd,
2370
2704
  agentDir: this.agentDir,
2371
2705
  settingsManager,
2372
2706
  // pi's built-in MCP, codemode and tool search come first, as in the CLI
2373
2707
  // (see builtin-extensions.ts: the SDK does not load them by itself).
2374
- extensionFactories: [...serverBuiltinExtensions, conversationSignal.inlineExtension, ...this.extraExtensionFactories],
2708
+ extensionFactories: parts.extensionFactories,
2375
2709
  // Never the CLI bridge (`@wherever-dev/pi`) in a server session: in-process
2376
2710
  // it registers this very session as a CLI and loops takeover/handback. The
2377
2711
  // identification rule is documented at isCliBridgeExtensionPath.
@@ -2402,7 +2736,9 @@ export class SessionPool {
2402
2736
  // with no CLI bridge). Both tools are self-contained; their UI affordance
2403
2737
  // (attach_file's download button, say's spoken-reply card) is driven by
2404
2738
  // the tool call reaching the web UI, no bridge/marker needed.
2405
- customTools: [createAttachFileTool(opts.cwd, () => getWhereverConfig().downloads), createSayTool()],
2739
+ // Plus, while `assistantFolder` is configured, the assistant tools (see
2740
+ // composeServerAgentParts).
2741
+ customTools: parts.customTools,
2406
2742
  sessionStartEvent: opts.sessionStartEvent,
2407
2743
  });
2408
2744
  // Start the extensions BEFORE the session is tracked or reaches a client:
@@ -2531,6 +2867,8 @@ export class SessionPool {
2531
2867
  dropSessionEntry(tracked) {
2532
2868
  this.cancelIdleCheck(tracked.sessionFile);
2533
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);
2534
2872
  for (const [id, p] of this.pendingSudo) {
2535
2873
  if (p.sessionFileOrId === tracked.sessionFile)
2536
2874
  this.pendingSudo.delete(id);
@@ -2555,49 +2893,57 @@ export class SessionPool {
2555
2893
  const tracked = this.sessions.get(sessionFile);
2556
2894
  if (!tracked)
2557
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);
2558
2900
  if (this.onEvent) {
2559
2901
  this.onEvent(sessionFile, event);
2560
2902
  }
2561
- switch (event.type) {
2562
- case 'agent_start':
2563
- tracked.isIdle = false;
2564
- tracked.lastActivity = Date.now();
2565
- this.cancelIdleCheck(sessionFile);
2566
- break;
2567
- case 'agent_end':
2568
- tracked.isIdle = true;
2569
- tracked.lastActivity = Date.now();
2570
- // A turn ended: nothing is in flight anymore. Reset defensively in case
2571
- // a start/end pair was ever missed, so the count cannot drift positive.
2572
- if (tracked.type === 'server')
2573
- tracked.inFlightToolCount = 0;
2574
- this.scheduleIdleCheck(sessionFile);
2575
- break;
2576
- case 'tool_execution_start':
2577
- if (tracked.type === 'server')
2578
- tracked.inFlightToolCount++;
2579
- tracked.lastActivity = Date.now();
2580
- break;
2581
- case 'tool_execution_end':
2582
- // Clamp at 0: an unmatched end must never make the count negative.
2583
- if (tracked.type === 'server')
2584
- tracked.inFlightToolCount = Math.max(0, tracked.inFlightToolCount - 1);
2585
- tracked.lastActivity = Date.now();
2586
- break;
2587
- case 'message_update':
2588
- case 'message_end':
2589
- tracked.lastActivity = Date.now();
2590
- break;
2591
- case 'model_select': {
2592
- const evt = event;
2593
- const modelStr = evt.model ? `${evt.model.provider}:${evt.model.id}` : '';
2594
- if (modelStr) {
2595
- tracked.model = modelStr;
2596
- }
2597
- 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;
2598
2943
  }
2944
+ break;
2599
2945
  }
2600
- });
2946
+ }
2601
2947
  }
2602
2948
  parseModelStr(modelStr) {
2603
2949
  const colonIdx = modelStr.indexOf(':');