wherever-dev 0.17.1 → 0.18.1

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 (35) hide show
  1. package/dist/extension-lifecycle.d.ts +27 -7
  2. package/dist/extension-lifecycle.d.ts.map +1 -1
  3. package/dist/extension-lifecycle.js +39 -8
  4. package/dist/extension-lifecycle.js.map +1 -1
  5. package/dist/index.js +93 -2
  6. package/dist/index.js.map +1 -1
  7. package/dist/protocol.d.ts +6 -0
  8. package/dist/protocol.d.ts.map +1 -1
  9. package/dist/session-pool.d.ts +103 -0
  10. package/dist/session-pool.d.ts.map +1 -1
  11. package/dist/session-pool.js +332 -74
  12. package/dist/session-pool.js.map +1 -1
  13. package/package.json +1 -1
  14. package/public/_app/immutable/chunks/{BhP7_nMn.js → B-wwgngN.js} +2 -2
  15. package/public/_app/immutable/chunks/{BhP7_nMn.js.map → B-wwgngN.js.map} +1 -1
  16. package/public/_app/immutable/chunks/{BRAYQ_mD.js → BS1e7MNH.js} +2 -2
  17. package/public/_app/immutable/chunks/{BRAYQ_mD.js.map → BS1e7MNH.js.map} +1 -1
  18. package/public/_app/immutable/chunks/{Bio1jLTG.js → D7tJYS3B.js} +2 -2
  19. package/public/_app/immutable/chunks/{Bio1jLTG.js.map → D7tJYS3B.js.map} +1 -1
  20. package/public/_app/immutable/entry/{app.D06PTvNp.js → app.vIHfKp_M.js} +3 -3
  21. package/public/_app/immutable/entry/{app.D06PTvNp.js.map → app.vIHfKp_M.js.map} +1 -1
  22. package/public/_app/immutable/entry/start.DLmhFByO.js +2 -0
  23. package/public/_app/immutable/entry/start.DLmhFByO.js.map +1 -0
  24. package/public/_app/immutable/nodes/{0.05Mp-ARy.js → 0.OosB8P5k.js} +2 -2
  25. package/public/_app/immutable/nodes/{0.05Mp-ARy.js.map → 0.OosB8P5k.js.map} +1 -1
  26. package/public/_app/immutable/nodes/{1.C_Y-Wpdd.js → 1.DJT-BX9k.js} +2 -2
  27. package/public/_app/immutable/nodes/{1.C_Y-Wpdd.js.map → 1.DJT-BX9k.js.map} +1 -1
  28. package/public/_app/immutable/nodes/{2.DmncGYOi.js → 2.CuG3NS5s.js} +46 -46
  29. package/public/_app/immutable/nodes/2.CuG3NS5s.js.map +1 -0
  30. package/public/_app/version.json +1 -1
  31. package/public/index.html +10 -10
  32. package/public/service-worker.js +1 -1
  33. package/public/_app/immutable/entry/start.DoiCihIa.js +0 -2
  34. package/public/_app/immutable/entry/start.DoiCihIa.js.map +0 -1
  35. package/public/_app/immutable/nodes/2.DmncGYOi.js.map +0 -1
@@ -676,8 +676,13 @@ import { randomUUID } from 'node:crypto';
676
676
  import { createAttachFileTool } from './attach-file-tool.js';
677
677
  import { createSayTool } from './say-tool.js';
678
678
  import { createConversationModeSignal } from './conversation-mode-hint.js';
679
- import { bindServerSessionExtensions, shutdownAndDisposeAgentSession, EXTENSION_SHUTDOWN_TIMEOUT_MS, EXTENSION_BIND_WARN_AFTER_MS, } from './extension-lifecycle.js';
679
+ import { bindServerSessionExtensions, shutdownAndDisposeAgentSession, clearPiExtensionCache, EXTENSION_SHUTDOWN_TIMEOUT_MS, EXTENSION_BIND_WARN_AFTER_MS, } from './extension-lifecycle.js';
680
+ /** How long startup waits for the extension-provider discovery before going on
681
+ * without it (see SessionPool.initialize). */
682
+ const EXTENSION_DISCOVERY_WAIT_MS = 10_000;
680
683
  import { matchRemoteRepoRule } from './remote-candidates.js';
684
+ /** What a send (or model change) gets while the session's agent is being rebuilt. */
685
+ export const RELOADING_REFUSAL = 'The session is reloading, so this was not delivered. Try again once it is ready.';
681
686
  export class SessionPool {
682
687
  sessions = new Map();
683
688
  pendingSessions = new Map();
@@ -720,8 +725,78 @@ export class SessionPool {
720
725
  }
721
726
  async initialize() {
722
727
  this.modelRegistry.refresh();
728
+ // Bounded: an extension that talks to something slow while loading must
729
+ // not hold the server's startup hostage. Past the bound the discovery keeps
730
+ // going in the background and still registers what it finds.
731
+ let bound;
732
+ await Promise.race([
733
+ this.discoverExtensionProviders(),
734
+ new Promise((r) => {
735
+ bound = setTimeout(r, EXTENSION_DISCOVERY_WAIT_MS);
736
+ bound.unref();
737
+ }),
738
+ ]);
739
+ clearTimeout(bound);
723
740
  this.warmSessionIndex();
724
741
  }
742
+ /**
743
+ * Register, in the shared registry, the providers that extensions declare
744
+ * (`pi.registerProvider` during load), from a loader that has just been
745
+ * reloaded.
746
+ *
747
+ * pi QUEUES those registrations while extensions load and flushes them in
748
+ * two places: `createAgentSessionServices` (what the pi CLI uses) right after
749
+ * loading, before the model is picked; and the extension runner's bind,
750
+ * which wherever reaches only AFTER `createAgentSession` has picked it. Our
751
+ * sessions go the second way, so without this a default model served by an
752
+ * extension provider (a local model behind an extension, say) resolved to
753
+ * nothing: the session came up as `unknown:unknown` and every prompt failed
754
+ * with "No API key found", while the same settings worked in the pi CLI.
755
+ *
756
+ * The queue is emptied afterwards, as the services path does, so the bind
757
+ * does not register the same providers a second time. Registrations live in
758
+ * the shared registry for the life of the process (they survive `refresh()`),
759
+ * which is what the other sessions and `/models` need.
760
+ */
761
+ registerExtensionProviders(resourceLoader, label) {
762
+ const runtime = resourceLoader.getExtensions().runtime;
763
+ for (const { name, config, extensionPath } of runtime.pendingProviderRegistrations) {
764
+ try {
765
+ this.modelRegistry.registerProvider(name, config);
766
+ }
767
+ catch (err) {
768
+ console.error(`[wherever] ${label}: extension ${extensionPath} failed to register provider "${name}": ${err instanceof Error ? err.message : String(err)}`);
769
+ }
770
+ }
771
+ runtime.pendingProviderRegistrations = [];
772
+ }
773
+ /**
774
+ * At startup, load the GLOBAL extensions (the agent dir's, and the packages
775
+ * its settings name) once just to learn their providers, so `/models`, the
776
+ * default-model lookup and a model picked in the new-session form see them
777
+ * before any session exists. The agent dir is used as the cwd so that no
778
+ * folder's project-level `.pi` resources are pulled in.
779
+ *
780
+ * Nothing is bound and the loader is then dropped, so these extension
781
+ * instances never get `session_start` or `session_shutdown`: anything a
782
+ * factory starts at LOAD time (rather than on session_start, as a
783
+ * well-behaved extension does) runs once more and is not torn down. Every
784
+ * session build already runs the same factories.
785
+ *
786
+ * Best-effort: a failure here only delays the providers to the first session.
787
+ */
788
+ async discoverExtensionProviders() {
789
+ try {
790
+ const cwd = this.agentDir;
791
+ const settingsManager = SettingsManager.create(cwd, this.agentDir);
792
+ const resourceLoader = new DefaultResourceLoader({ cwd, agentDir: this.agentDir, settingsManager });
793
+ await resourceLoader.reload();
794
+ this.registerExtensionProviders(resourceLoader, 'startup discovery');
795
+ }
796
+ catch (err) {
797
+ console.error(`[wherever] could not discover extension providers at startup: ${err instanceof Error ? err.message : String(err)}`);
798
+ }
799
+ }
725
800
  /** Resolve the on-disk sessions directory (agentDir/sessions). Session files
726
801
  * always live here as <subdir>/*.jsonl, so deletion/operations on a session
727
802
  * file are scoped to this root to prevent deleting arbitrary .jsonl files. */
@@ -949,9 +1024,11 @@ export class SessionPool {
949
1024
  const sessionCwd = cwd || header.cwd || process.cwd();
950
1025
  const normalizedCwd = normalizePath(sessionCwd);
951
1026
  let model;
1027
+ let modelRef;
952
1028
  if (modelStr) {
953
1029
  const parsed = this.parseModelStr(modelStr);
954
1030
  if (parsed) {
1031
+ modelRef = parsed;
955
1032
  model = this.modelRegistry.find(parsed.provider, parsed.id);
956
1033
  }
957
1034
  }
@@ -970,42 +1047,19 @@ export class SessionPool {
970
1047
  if (e.type !== 'model_change')
971
1048
  continue;
972
1049
  if ('provider' in e && 'modelId' in e) {
1050
+ modelRef ??= { provider: e.provider, id: e.modelId };
973
1051
  model = this.modelRegistry.find(e.provider, e.modelId);
974
1052
  }
975
1053
  break;
976
1054
  }
977
1055
  }
978
- const settingsManager = SettingsManager.create(normalizedCwd, this.agentDir);
979
- // The conversation-mode signal is an INLINE pi extension (the SDK-supported
980
- // way to get a before_agent_start hook on a server-created session, the
981
- // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
982
- // per session, so the armed flag can never cross sessions.
983
- const conversationSignal = createConversationModeSignal();
984
- const resourceLoader = new DefaultResourceLoader({
985
- cwd: normalizedCwd,
986
- agentDir: this.agentDir,
987
- settingsManager,
988
- extensionFactories: [conversationSignal.inlineExtension, ...this.extraExtensionFactories],
989
- });
990
- await resourceLoader.reload();
991
- const { session: agentSession } = await createAgentSession({
1056
+ const { agentSession, conversationSignal } = await this.buildServerAgent({
992
1057
  cwd: normalizedCwd,
993
- authStorage: this.authStorage,
994
- modelRegistry: this.modelRegistry,
995
- model,
996
1058
  sessionManager,
997
- settingsManager,
998
- resourceLoader,
999
- // Register attach_file + say for server-created sessions (web frontend
1000
- // with no CLI bridge). Both tools are self-contained; their UI affordance
1001
- // (attach_file's download button, say's spoken-reply card) is driven by
1002
- // the tool call reaching the web UI, no bridge/marker needed.
1003
- customTools: [createAttachFileTool(normalizedCwd), createSayTool()],
1059
+ model,
1060
+ modelRef,
1061
+ label: resolvedFile,
1004
1062
  });
1005
- // Start the extensions BEFORE the session is tracked or reaches a client:
1006
- // createAgentSession only loads them, bindExtensions emits session_start +
1007
- // resources_discover (see extension-lifecycle.ts for the chosen bindings).
1008
- await this.bindOrDispose(agentSession, resolvedFile);
1009
1063
  const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
1010
1064
  const tracked = {
1011
1065
  type: 'server',
@@ -1212,37 +1266,21 @@ export class SessionPool {
1212
1266
  }
1213
1267
  const sessionManager = SessionManager.create(resolvedCwd);
1214
1268
  let model;
1269
+ let modelRef;
1215
1270
  if (modelStr) {
1216
1271
  const parsed = this.parseModelStr(modelStr);
1217
1272
  if (parsed) {
1273
+ modelRef = parsed;
1218
1274
  model = this.modelRegistry.find(parsed.provider, parsed.id);
1219
1275
  }
1220
1276
  }
1221
- const settingsManager = SettingsManager.create(resolvedCwd, this.agentDir);
1222
- // Per-turn conversation-mode signal (see the other DefaultResourceLoader
1223
- // call for the rationale).
1224
- const conversationSignal = createConversationModeSignal();
1225
- const resourceLoader = new DefaultResourceLoader({
1277
+ const { agentSession, conversationSignal } = await this.buildServerAgent({
1226
1278
  cwd: resolvedCwd,
1227
- agentDir: this.agentDir,
1228
- settingsManager,
1229
- extensionFactories: [conversationSignal.inlineExtension, ...this.extraExtensionFactories],
1230
- });
1231
- await resourceLoader.reload();
1232
- const { session: agentSession } = await createAgentSession({
1233
- cwd: resolvedCwd,
1234
- authStorage: this.authStorage,
1235
- modelRegistry: this.modelRegistry,
1236
- model,
1237
1279
  sessionManager,
1238
- settingsManager,
1239
- resourceLoader,
1240
- // Register attach_file + say for server-created sessions (see the other
1241
- // createAgentSession call for the rationale).
1242
- customTools: [createAttachFileTool(resolvedCwd), createSayTool()],
1280
+ model,
1281
+ modelRef,
1282
+ label: resolvedCwd,
1243
1283
  });
1244
- // Start the extensions before tracking (see the other createAgentSession call).
1245
- await this.bindOrDispose(agentSession, agentSession.sessionFile || resolvedCwd);
1246
1284
  const sessionFile = normalizeSessionFile(agentSession.sessionFile || '');
1247
1285
  const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
1248
1286
  const tracked = {
@@ -1580,6 +1618,11 @@ export class SessionPool {
1580
1618
  const tracked = this.getSession(sessionFileOrId);
1581
1619
  if (!tracked)
1582
1620
  return;
1621
+ // Backstop for the WS layer's own check: mid-reload the tracked agent is the
1622
+ // one being shut down. Throwing surfaces as a retryable session_error.
1623
+ if (tracked.type === 'server' && tracked.reloading) {
1624
+ throw new Error(RELOADING_REFUSAL);
1625
+ }
1583
1626
  tracked.lastActivity = Date.now();
1584
1627
  this.cancelIdleCheck(tracked.sessionFile);
1585
1628
  const isBash = text.trimStart().startsWith('!');
@@ -1643,15 +1686,23 @@ export class SessionPool {
1643
1686
  // expansions are start-of-message anchored, and any trailing text after
1644
1687
  // "/skill:<name> " is preserved and appended after the skill block. Plain
1645
1688
  // text keeps the sendUserMessage() path (extension "input"-event source).
1646
- if (text.startsWith('/')) {
1647
- await tracked.agentSession.prompt(text, {
1648
- expandPromptTemplates: true,
1649
- streamingBehavior,
1650
- source: 'interactive',
1651
- });
1689
+ // Counted as busy (synchronously, before the first await) so a /reload
1690
+ // cannot dispose the agent under a send that pi has not started streaming.
1691
+ tracked.busy = (tracked.busy ?? 0) + 1;
1692
+ try {
1693
+ if (text.startsWith('/')) {
1694
+ await tracked.agentSession.prompt(text, {
1695
+ expandPromptTemplates: true,
1696
+ streamingBehavior,
1697
+ source: 'interactive',
1698
+ });
1699
+ }
1700
+ else {
1701
+ await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
1702
+ }
1652
1703
  }
1653
- else {
1654
- await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
1704
+ finally {
1705
+ tracked.busy -= 1;
1655
1706
  }
1656
1707
  }
1657
1708
  else if (tracked.type === 'cli') {
@@ -1676,6 +1727,19 @@ export class SessionPool {
1676
1727
  // custom executor that feeds the password over stdin; when omitted the agent
1677
1728
  // uses its default local shell backend.
1678
1729
  async runServerBash(tracked, command, excludeFromContext, operations) {
1730
+ // Never run on the old agent mid-reload (submitSudoPassword waits the reload out).
1731
+ if (tracked.reloading)
1732
+ throw new Error(RELOADING_REFUSAL);
1733
+ // Busy for the whole command: a reload would otherwise abort it via dispose().
1734
+ tracked.busy = (tracked.busy ?? 0) + 1;
1735
+ try {
1736
+ await this.runServerBashUnguarded(tracked, command, excludeFromContext, operations);
1737
+ }
1738
+ finally {
1739
+ tracked.busy -= 1;
1740
+ }
1741
+ }
1742
+ async runServerBashUnguarded(tracked, command, excludeFromContext, operations) {
1679
1743
  if (this.onEvent) {
1680
1744
  this.onEvent(tracked.sessionFile, {
1681
1745
  type: 'tool_execution_start',
@@ -1782,9 +1846,18 @@ export class SessionPool {
1782
1846
  if (!pending)
1783
1847
  return false;
1784
1848
  this.pendingSudo.delete(promptId);
1785
- const tracked = this.getSession(pending.sessionFileOrId);
1849
+ let tracked = this.getSession(pending.sessionFileOrId);
1786
1850
  if (!tracked)
1787
1851
  return false;
1852
+ // The password answers a prompt the user already saw; a /reload that started
1853
+ // meanwhile must not make them retype it. Wait the (bounded) reload out and
1854
+ // run on the rebuilt agent. The password lives only in this closure meanwhile.
1855
+ if (tracked.type === 'server' && tracked.reloading) {
1856
+ await tracked.reloadPromise;
1857
+ tracked = this.getSession(pending.sessionFileOrId);
1858
+ if (!tracked)
1859
+ return false;
1860
+ }
1788
1861
  tracked.lastActivity = Date.now();
1789
1862
  this.cancelIdleCheck(tracked.sessionFile);
1790
1863
  if (tracked.type === 'server') {
@@ -1856,6 +1929,8 @@ export class SessionPool {
1856
1929
  if (!tracked)
1857
1930
  return { error: 'Session not found' };
1858
1931
  if (tracked.type === 'server') {
1932
+ if (tracked.reloading)
1933
+ return { error: RELOADING_REFUSAL };
1859
1934
  const parsed = this.parseModelStr(modelStr);
1860
1935
  if (!parsed)
1861
1936
  return { error: `Invalid model format: ${modelStr}` };
@@ -1959,9 +2034,14 @@ export class SessionPool {
1959
2034
  const tracked = this.getSession(sessionFileOrId);
1960
2035
  if (!tracked)
1961
2036
  return Promise.resolve();
1962
- this.cancelIdleCheck(tracked.sessionFile);
1963
2037
  let teardown = Promise.resolve();
1964
- if (tracked.type === 'server') {
2038
+ if (tracked.type === 'server' && tracked.reloading) {
2039
+ // reloadSession owns the agent mid-rebuild: it is already shutting the old
2040
+ // one down, and it releases the new one once it sees the entry is gone.
2041
+ // Waiting for it keeps server shutdown from exiting mid-teardown.
2042
+ teardown = (tracked.reloadPromise ?? Promise.resolve()).then(() => { }, () => { });
2043
+ }
2044
+ else if (tracked.type === 'server') {
1965
2045
  tracked.eventUnsubscribe();
1966
2046
  teardown = shutdownAndDisposeAgentSession(tracked.agentSession, `${tracked.sessionFile} (${reason})`, this.extensionShutdownTimeoutMs);
1967
2047
  }
@@ -1971,14 +2051,7 @@ export class SessionPool {
1971
2051
  }
1972
2052
  catch (err) { }
1973
2053
  }
1974
- this.sessions.delete(tracked.sessionFile);
1975
- // A prompt whose session is gone can never be answered: drop it here so an
1976
- // abandoned prompt is bounded by the session's own lifetime (idle eviction)
1977
- // rather than waiting for someone to type the next `!sudo`.
1978
- for (const [id, p] of this.pendingSudo) {
1979
- if (p.sessionFileOrId === tracked.sessionFile)
1980
- this.pendingSudo.delete(id);
1981
- }
2054
+ this.dropSessionEntry(tracked);
1982
2055
  return teardown;
1983
2056
  }
1984
2057
  async registerCliSession(rawSessionFile, cwd, modelStr, cliWs, isStreaming = false) {
@@ -2005,7 +2078,12 @@ export class SessionPool {
2005
2078
  if (existing) {
2006
2079
  clients = existing.clients;
2007
2080
  this.cancelIdleCheck(sessionFile);
2008
- if (existing.type === 'server') {
2081
+ if (existing.type === 'server' && existing.reloading) {
2082
+ // Mid-reload there is no turn to interrupt (reload refuses while
2083
+ // streaming), and reloadSession owns the agent: it releases the rebuilt
2084
+ // one once it sees this CLI entry has replaced its own.
2085
+ }
2086
+ else if (existing.type === 'server') {
2009
2087
  interruptedToolCall = existing.inFlightToolCount > 0;
2010
2088
  interruptedTurn = interruptedToolCall || existing.agentSession.isStreaming;
2011
2089
  try {
@@ -2013,9 +2091,10 @@ export class SessionPool {
2013
2091
  }
2014
2092
  catch (err) { }
2015
2093
  // Start the server agent's teardown NOW (its in-flight turn is aborted
2016
- // synchronously, then session_shutdown, then dispose), but only AWAIT it after the CLI entry has replaced it in the pool, so
2017
- // no message can reach the dying agent while its extensions shut down.
2018
- // The CLI's pi process binds its own extensions; nothing to do for it.
2094
+ // synchronously, then session_shutdown, then dispose), but only AWAIT
2095
+ // it after the CLI entry has replaced it in the pool, so no message can
2096
+ // reach the dying agent while its extensions shut down. The CLI's pi
2097
+ // process binds its own extensions; nothing to do for it.
2019
2098
  serverTeardown = shutdownAndDisposeAgentSession(existing.agentSession, `${sessionFile} (cli takeover)`, this.extensionShutdownTimeoutMs);
2020
2099
  }
2021
2100
  }
@@ -2137,6 +2216,185 @@ export class SessionPool {
2137
2216
  // one extension-shutdown timeout, not one per session.
2138
2217
  await Promise.all(sessionIds.map((id) => this.destroySession(id, 'server shutdown')));
2139
2218
  }
2219
+ /**
2220
+ * Build and START a live server agent: fresh settings, resource loader
2221
+ * (extensions, skills, prompts, context files), createAgentSession, then
2222
+ * bindExtensions. The ONE place a server agent is built, shared by loadSession,
2223
+ * createNewSession and reloadSession, so the three can never drift in which
2224
+ * tools, extensions or lifecycle a server session gets.
2225
+ */
2226
+ async buildServerAgent(opts) {
2227
+ const settingsManager = SettingsManager.create(opts.cwd, this.agentDir);
2228
+ // The conversation-mode signal is an INLINE pi extension (the SDK-supported
2229
+ // way to get a before_agent_start hook on a server-created session, the
2230
+ // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
2231
+ // per session, so the armed flag can never cross sessions.
2232
+ const conversationSignal = createConversationModeSignal();
2233
+ const resourceLoader = new DefaultResourceLoader({
2234
+ cwd: opts.cwd,
2235
+ agentDir: this.agentDir,
2236
+ settingsManager,
2237
+ extensionFactories: [conversationSignal.inlineExtension, ...this.extraExtensionFactories],
2238
+ });
2239
+ await resourceLoader.reload();
2240
+ // Before createAgentSession picks the model: see registerExtensionProviders.
2241
+ this.registerExtensionProviders(resourceLoader, opts.label);
2242
+ // A model handed in was looked up BEFORE this build re-registered its
2243
+ // provider (a reload keeps the old session's model object), so take the
2244
+ // registry's current one: an extension edit picked up by /reload (a new
2245
+ // baseUrl, say) must reach the session. pi used to do this when the bind
2246
+ // flushed the registrations (_refreshCurrentModelFromRegistry); the flush
2247
+ // is now ours, so the refresh is too.
2248
+ // The name asked for wins; otherwise the model object handed in (a reload).
2249
+ const ref = opts.modelRef ?? (opts.model && { provider: opts.model.provider, id: opts.model.id });
2250
+ const model = (ref && this.modelRegistry.find(ref.provider, ref.id)) ?? opts.model;
2251
+ const { session: agentSession } = await createAgentSession({
2252
+ cwd: opts.cwd,
2253
+ authStorage: this.authStorage,
2254
+ modelRegistry: this.modelRegistry,
2255
+ model,
2256
+ thinkingLevel: opts.thinkingLevel,
2257
+ sessionManager: opts.sessionManager,
2258
+ settingsManager,
2259
+ resourceLoader,
2260
+ // Register attach_file + say for server-created sessions (web frontend
2261
+ // with no CLI bridge). Both tools are self-contained; their UI affordance
2262
+ // (attach_file's download button, say's spoken-reply card) is driven by
2263
+ // the tool call reaching the web UI, no bridge/marker needed.
2264
+ customTools: [createAttachFileTool(opts.cwd), createSayTool()],
2265
+ sessionStartEvent: opts.sessionStartEvent,
2266
+ });
2267
+ // Start the extensions BEFORE the session is tracked or reaches a client:
2268
+ // createAgentSession only loads them, bindExtensions emits session_start +
2269
+ // resources_discover (see extension-lifecycle.ts for the chosen bindings).
2270
+ await this.bindOrDispose(agentSession, opts.label);
2271
+ return { agentSession, conversationSignal };
2272
+ }
2273
+ /** True while `reloadSession` is rebuilding this session's agent. */
2274
+ isReloading(sessionFileOrId) {
2275
+ const tracked = this.getSession(sessionFileOrId);
2276
+ return tracked?.type === 'server' && tracked.reloading === true;
2277
+ }
2278
+ /**
2279
+ * The web `/reload`: re-read settings, extensions, skills, prompts and context
2280
+ * files for a server session, like pi's `/reload`, WITHOUT calling
2281
+ * `AgentSession.reload()`.
2282
+ *
2283
+ * pi's in-place reload calls pi-ai's `resetApiProviders()`, which is
2284
+ * process-wide: every OTHER live session's extension-registered API providers
2285
+ * would vanish for the seconds the reloading session spends re-loading its
2286
+ * extensions. So the agent is REBUILT instead, through the same builder as a
2287
+ * load: the old agent gets `session_shutdown` (reason `reload`) and is
2288
+ * disposed, then a new AgentSession is built on the SAME SessionManager (so
2289
+ * entries not yet flushed to disk survive, exactly as in an in-place reload),
2290
+ * keeping the current model and thinking level, and its extensions get
2291
+ * `session_start` (reason `reload`). The tracked entry is updated in place, so
2292
+ * clients, idle state and the pool key are untouched.
2293
+ *
2294
+ * Refused while the agent is doing anything (streaming, compacting, running a
2295
+ * `!command`, or a send still in its pre-stream phase: see `busy`), for CLI
2296
+ * bridges (the terminal pi owns that agent) and while already reloading; a
2297
+ * refusal returns `started: false` and changes nothing. `onStart` runs once
2298
+ * every check has passed, before the old agent is touched. If the rebuild
2299
+ * fails the old agent is already gone, so the entry is dropped and the next
2300
+ * load builds a fresh one.
2301
+ *
2302
+ * Unlike pi's in-place reload, the rebuild does NOT carry over an active-tool
2303
+ * set an extension narrowed with `setActiveTools`, extension flag values, or
2304
+ * messages an extension queued for the next turn: the new agent starts from
2305
+ * the defaults, as a fresh load would.
2306
+ */
2307
+ async reloadSession(sessionFileOrId, opts = {}) {
2308
+ const tracked = this.getSession(sessionFileOrId);
2309
+ if (!tracked)
2310
+ return { error: 'Session not found.', started: false };
2311
+ if (tracked.type !== 'server') {
2312
+ return { error: 'This session is running in a terminal pi. Run /reload in that terminal.', started: false };
2313
+ }
2314
+ if (tracked.reloading)
2315
+ return { error: 'This session is already reloading.', started: false };
2316
+ const old = tracked.agentSession;
2317
+ // `busy` covers what pi's flags miss: a send still in extension commands /
2318
+ // input handlers / compaction check (not yet streaming), and a `!command`.
2319
+ if (old.isStreaming || old.isCompacting || old.isBashRunning || (tracked.busy ?? 0) > 0) {
2320
+ return { error: 'Wait for the current response to finish before reloading.', started: false };
2321
+ }
2322
+ // Everything from here to the first await is synchronous, so no send can
2323
+ // slip in between the checks above and `reloading` being observable.
2324
+ tracked.reloading = true;
2325
+ tracked.lastActivity = Date.now();
2326
+ const run = this.runReload(tracked, opts);
2327
+ tracked.reloadPromise = run;
2328
+ return run;
2329
+ }
2330
+ async runReload(tracked, opts) {
2331
+ const old = tracked.agentSession;
2332
+ const label = `${tracked.sessionFile} (reload)`;
2333
+ try {
2334
+ // Past every refusal: the caller can now tell clients the agent is going away.
2335
+ opts.onStart?.();
2336
+ tracked.eventUnsubscribe();
2337
+ const { sessionManager, model, thinkingLevel } = old;
2338
+ await shutdownAndDisposeAgentSession(old, label, this.extensionShutdownTimeoutMs, 'reload');
2339
+ // Otherwise the fresh loader below reuses pi's cached factories: the old code.
2340
+ await clearPiExtensionCache();
2341
+ let built;
2342
+ try {
2343
+ built = await this.buildServerAgent({
2344
+ cwd: tracked.cwd,
2345
+ sessionManager,
2346
+ model,
2347
+ thinkingLevel,
2348
+ sessionStartEvent: { type: 'session_start', reason: 'reload' },
2349
+ label,
2350
+ });
2351
+ }
2352
+ catch (err) {
2353
+ if (this.sessions.get(tracked.sessionFile) !== tracked) {
2354
+ return { error: 'The session was closed while it was reloading.', started: true, closed: true };
2355
+ }
2356
+ this.dropSessionEntry(tracked);
2357
+ return {
2358
+ error: `Reload failed: ${err.message}. Re-open the session to start a fresh agent.`,
2359
+ started: true,
2360
+ };
2361
+ }
2362
+ // The session may have been destroyed (deleted, evicted, taken over by a
2363
+ // CLI, server shutdown) while we were rebuilding. Those paths leave a
2364
+ // reloading agent to us, so the new one is ours to release.
2365
+ if (this.sessions.get(tracked.sessionFile) !== tracked) {
2366
+ await shutdownAndDisposeAgentSession(built.agentSession, `${label} (closed during reload)`, this.extensionShutdownTimeoutMs);
2367
+ return { error: 'The session was closed while it was reloading.', started: true, closed: true };
2368
+ }
2369
+ tracked.agentSession = built.agentSession;
2370
+ tracked.conversationSignal = built.conversationSignal;
2371
+ tracked.model = built.agentSession.model ? `${built.agentSession.model.provider}:${built.agentSession.model.id}` : '';
2372
+ tracked.inFlightToolCount = 0;
2373
+ tracked.isIdle = true;
2374
+ tracked.eventUnsubscribe = this.setupEventListeners(tracked.sessionFile, built.agentSession);
2375
+ return { started: true };
2376
+ }
2377
+ finally {
2378
+ tracked.reloading = false;
2379
+ tracked.reloadPromise = undefined;
2380
+ if (this.sessions.get(tracked.sessionFile) === tracked)
2381
+ this.scheduleIdleCheck(tracked.sessionFile);
2382
+ }
2383
+ }
2384
+ /**
2385
+ * Forget a session entry (its agent's teardown is the caller's business). A
2386
+ * sudo prompt whose session is gone can never be answered: drop it here so an
2387
+ * abandoned prompt is bounded by the session's own lifetime (idle eviction)
2388
+ * rather than waiting for someone to type the next `!sudo`.
2389
+ */
2390
+ dropSessionEntry(tracked) {
2391
+ this.cancelIdleCheck(tracked.sessionFile);
2392
+ this.sessions.delete(tracked.sessionFile);
2393
+ for (const [id, p] of this.pendingSudo) {
2394
+ if (p.sessionFileOrId === tracked.sessionFile)
2395
+ this.pendingSudo.delete(id);
2396
+ }
2397
+ }
2140
2398
  /**
2141
2399
  * Bind a freshly created server session's extensions; if that throws, shut
2142
2400
  * down and dispose the session so a failed create leaks nothing, then rethrow