wherever-dev 0.17.0 → 0.18.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 (36) hide show
  1. package/dist/extension-lifecycle.d.ts +100 -0
  2. package/dist/extension-lifecycle.d.ts.map +1 -0
  3. package/dist/extension-lifecycle.js +186 -0
  4. package/dist/extension-lifecycle.js.map +1 -0
  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 +97 -2
  10. package/dist/session-pool.d.ts.map +1 -1
  11. package/dist/session-pool.js +286 -70
  12. package/dist/session-pool.js.map +1 -1
  13. package/package.json +1 -1
  14. package/public/_app/immutable/chunks/{tyMlRPpy.js → 6cDLdLMr.js} +2 -2
  15. package/public/_app/immutable/chunks/{tyMlRPpy.js.map → 6cDLdLMr.js.map} +1 -1
  16. package/public/_app/immutable/chunks/BWLk4g7S.js +2 -0
  17. package/public/_app/immutable/chunks/{BRpbyuah.js.map → BWLk4g7S.js.map} +1 -1
  18. package/public/_app/immutable/chunks/{C2Qht-9M.js → C2gDSNg3.js} +2 -2
  19. package/public/_app/immutable/chunks/{C2Qht-9M.js.map → C2gDSNg3.js.map} +1 -1
  20. package/public/_app/immutable/entry/{app.C-K4PQEc.js → app.DCsaSS2h.js} +3 -3
  21. package/public/_app/immutable/entry/{app.C-K4PQEc.js.map → app.DCsaSS2h.js.map} +1 -1
  22. package/public/_app/immutable/entry/start.CVu9YCQp.js +2 -0
  23. package/public/_app/immutable/entry/start.CVu9YCQp.js.map +1 -0
  24. package/public/_app/immutable/nodes/{0.DhT5vD6E.js → 0.BKhPUBoV.js} +2 -2
  25. package/public/_app/immutable/nodes/{0.DhT5vD6E.js.map → 0.BKhPUBoV.js.map} +1 -1
  26. package/public/_app/immutable/nodes/{1.Dg1qqEIS.js → 1.D-6k-nc0.js} +2 -2
  27. package/public/_app/immutable/nodes/{1.Dg1qqEIS.js.map → 1.D-6k-nc0.js.map} +1 -1
  28. package/public/_app/immutable/nodes/{2.gGFd8Q6p.js → 2.B1UIQ9ew.js} +46 -46
  29. package/public/_app/immutable/nodes/2.B1UIQ9ew.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/chunks/BRpbyuah.js +0 -2
  34. package/public/_app/immutable/entry/start.CMyrB3xe.js +0 -2
  35. package/public/_app/immutable/entry/start.CMyrB3xe.js.map +0 -1
  36. package/public/_app/immutable/nodes/2.gGFd8Q6p.js.map +0 -1
@@ -676,7 +676,10 @@ 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, clearPiExtensionCache, EXTENSION_SHUTDOWN_TIMEOUT_MS, EXTENSION_BIND_WARN_AFTER_MS, } from './extension-lifecycle.js';
679
680
  import { matchRemoteRepoRule } from './remote-candidates.js';
681
+ /** What a send (or model change) gets while the session's agent is being rebuilt. */
682
+ export const RELOADING_REFUSAL = 'The session is reloading, so this was not delivered. Try again once it is ready.';
680
683
  export class SessionPool {
681
684
  sessions = new Map();
682
685
  pendingSessions = new Map();
@@ -698,7 +701,20 @@ export class SessionPool {
698
701
  /** How long an unanswered sudo prompt survives, if its session outlives it. */
699
702
  static SUDO_PROMPT_TTL_MS = 30 * 60_000;
700
703
  onEvent;
701
- constructor(idleTimeoutMs = 300_000) {
704
+ /**
705
+ * Extra inline extensions loaded into EVERY server-created session, after the
706
+ * built-in ones. Not used by the server itself; it is the seam tests use to
707
+ * observe the extension lifecycle (session_start / session_shutdown).
708
+ */
709
+ extraExtensionFactories;
710
+ /** Bound on extension `session_shutdown` before dispose (see extension-lifecycle.ts). */
711
+ extensionShutdownTimeoutMs;
712
+ /** When a stuck `session_start` gets logged (see extension-lifecycle.ts). */
713
+ extensionBindWarnAfterMs;
714
+ constructor(idleTimeoutMs = 300_000, options = {}) {
715
+ this.extraExtensionFactories = options.extraExtensionFactories ?? [];
716
+ this.extensionShutdownTimeoutMs = options.extensionShutdownTimeoutMs ?? EXTENSION_SHUTDOWN_TIMEOUT_MS;
717
+ this.extensionBindWarnAfterMs = options.extensionBindWarnAfterMs ?? EXTENSION_BIND_WARN_AFTER_MS;
702
718
  this.agentDir = getAgentDir();
703
719
  this.authStorage = AuthStorage.create();
704
720
  this.modelRegistry = ModelRegistry.create(this.authStorage);
@@ -961,32 +977,11 @@ export class SessionPool {
961
977
  break;
962
978
  }
963
979
  }
964
- const settingsManager = SettingsManager.create(normalizedCwd, this.agentDir);
965
- // The conversation-mode signal is an INLINE pi extension (the SDK-supported
966
- // way to get a before_agent_start hook on a server-created session, the
967
- // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
968
- // per session, so the armed flag can never cross sessions.
969
- const conversationSignal = createConversationModeSignal();
970
- const resourceLoader = new DefaultResourceLoader({
971
- cwd: normalizedCwd,
972
- agentDir: this.agentDir,
973
- settingsManager,
974
- extensionFactories: [conversationSignal.inlineExtension],
975
- });
976
- await resourceLoader.reload();
977
- const { session: agentSession } = await createAgentSession({
980
+ const { agentSession, conversationSignal } = await this.buildServerAgent({
978
981
  cwd: normalizedCwd,
979
- authStorage: this.authStorage,
980
- modelRegistry: this.modelRegistry,
981
- model,
982
982
  sessionManager,
983
- settingsManager,
984
- resourceLoader,
985
- // Register attach_file + say for server-created sessions (web frontend
986
- // with no CLI bridge). Both tools are self-contained; their UI affordance
987
- // (attach_file's download button, say's spoken-reply card) is driven by
988
- // the tool call reaching the web UI, no bridge/marker needed.
989
- customTools: [createAttachFileTool(normalizedCwd), createSayTool()],
983
+ model,
984
+ label: resolvedFile,
990
985
  });
991
986
  const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
992
987
  const tracked = {
@@ -1200,28 +1195,11 @@ export class SessionPool {
1200
1195
  model = this.modelRegistry.find(parsed.provider, parsed.id);
1201
1196
  }
1202
1197
  }
1203
- const settingsManager = SettingsManager.create(resolvedCwd, this.agentDir);
1204
- // Per-turn conversation-mode signal (see the other DefaultResourceLoader
1205
- // call for the rationale).
1206
- const conversationSignal = createConversationModeSignal();
1207
- const resourceLoader = new DefaultResourceLoader({
1198
+ const { agentSession, conversationSignal } = await this.buildServerAgent({
1208
1199
  cwd: resolvedCwd,
1209
- agentDir: this.agentDir,
1210
- settingsManager,
1211
- extensionFactories: [conversationSignal.inlineExtension],
1212
- });
1213
- await resourceLoader.reload();
1214
- const { session: agentSession } = await createAgentSession({
1215
- cwd: resolvedCwd,
1216
- authStorage: this.authStorage,
1217
- modelRegistry: this.modelRegistry,
1218
- model,
1219
1200
  sessionManager,
1220
- settingsManager,
1221
- resourceLoader,
1222
- // Register attach_file + say for server-created sessions (see the other
1223
- // createAgentSession call for the rationale).
1224
- customTools: [createAttachFileTool(resolvedCwd), createSayTool()],
1201
+ model,
1202
+ label: resolvedCwd,
1225
1203
  });
1226
1204
  const sessionFile = normalizeSessionFile(agentSession.sessionFile || '');
1227
1205
  const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
@@ -1560,6 +1538,11 @@ export class SessionPool {
1560
1538
  const tracked = this.getSession(sessionFileOrId);
1561
1539
  if (!tracked)
1562
1540
  return;
1541
+ // Backstop for the WS layer's own check: mid-reload the tracked agent is the
1542
+ // one being shut down. Throwing surfaces as a retryable session_error.
1543
+ if (tracked.type === 'server' && tracked.reloading) {
1544
+ throw new Error(RELOADING_REFUSAL);
1545
+ }
1563
1546
  tracked.lastActivity = Date.now();
1564
1547
  this.cancelIdleCheck(tracked.sessionFile);
1565
1548
  const isBash = text.trimStart().startsWith('!');
@@ -1623,15 +1606,23 @@ export class SessionPool {
1623
1606
  // expansions are start-of-message anchored, and any trailing text after
1624
1607
  // "/skill:<name> " is preserved and appended after the skill block. Plain
1625
1608
  // text keeps the sendUserMessage() path (extension "input"-event source).
1626
- if (text.startsWith('/')) {
1627
- await tracked.agentSession.prompt(text, {
1628
- expandPromptTemplates: true,
1629
- streamingBehavior,
1630
- source: 'interactive',
1631
- });
1609
+ // Counted as busy (synchronously, before the first await) so a /reload
1610
+ // cannot dispose the agent under a send that pi has not started streaming.
1611
+ tracked.busy = (tracked.busy ?? 0) + 1;
1612
+ try {
1613
+ if (text.startsWith('/')) {
1614
+ await tracked.agentSession.prompt(text, {
1615
+ expandPromptTemplates: true,
1616
+ streamingBehavior,
1617
+ source: 'interactive',
1618
+ });
1619
+ }
1620
+ else {
1621
+ await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
1622
+ }
1632
1623
  }
1633
- else {
1634
- await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
1624
+ finally {
1625
+ tracked.busy -= 1;
1635
1626
  }
1636
1627
  }
1637
1628
  else if (tracked.type === 'cli') {
@@ -1656,6 +1647,19 @@ export class SessionPool {
1656
1647
  // custom executor that feeds the password over stdin; when omitted the agent
1657
1648
  // uses its default local shell backend.
1658
1649
  async runServerBash(tracked, command, excludeFromContext, operations) {
1650
+ // Never run on the old agent mid-reload (submitSudoPassword waits the reload out).
1651
+ if (tracked.reloading)
1652
+ throw new Error(RELOADING_REFUSAL);
1653
+ // Busy for the whole command: a reload would otherwise abort it via dispose().
1654
+ tracked.busy = (tracked.busy ?? 0) + 1;
1655
+ try {
1656
+ await this.runServerBashUnguarded(tracked, command, excludeFromContext, operations);
1657
+ }
1658
+ finally {
1659
+ tracked.busy -= 1;
1660
+ }
1661
+ }
1662
+ async runServerBashUnguarded(tracked, command, excludeFromContext, operations) {
1659
1663
  if (this.onEvent) {
1660
1664
  this.onEvent(tracked.sessionFile, {
1661
1665
  type: 'tool_execution_start',
@@ -1762,9 +1766,18 @@ export class SessionPool {
1762
1766
  if (!pending)
1763
1767
  return false;
1764
1768
  this.pendingSudo.delete(promptId);
1765
- const tracked = this.getSession(pending.sessionFileOrId);
1769
+ let tracked = this.getSession(pending.sessionFileOrId);
1766
1770
  if (!tracked)
1767
1771
  return false;
1772
+ // The password answers a prompt the user already saw; a /reload that started
1773
+ // meanwhile must not make them retype it. Wait the (bounded) reload out and
1774
+ // run on the rebuilt agent. The password lives only in this closure meanwhile.
1775
+ if (tracked.type === 'server' && tracked.reloading) {
1776
+ await tracked.reloadPromise;
1777
+ tracked = this.getSession(pending.sessionFileOrId);
1778
+ if (!tracked)
1779
+ return false;
1780
+ }
1768
1781
  tracked.lastActivity = Date.now();
1769
1782
  this.cancelIdleCheck(tracked.sessionFile);
1770
1783
  if (tracked.type === 'server') {
@@ -1836,6 +1849,8 @@ export class SessionPool {
1836
1849
  if (!tracked)
1837
1850
  return { error: 'Session not found' };
1838
1851
  if (tracked.type === 'server') {
1852
+ if (tracked.reloading)
1853
+ return { error: RELOADING_REFUSAL };
1839
1854
  const parsed = this.parseModelStr(modelStr);
1840
1855
  if (!parsed)
1841
1856
  return { error: `Invalid model format: ${modelStr}` };
@@ -1928,14 +1943,27 @@ export class SessionPool {
1928
1943
  clearTimeout(tracked.idleTimer);
1929
1944
  tracked.idleTimer = null;
1930
1945
  }
1946
+ /**
1947
+ * Tear a session down. The pool entry is dropped SYNCHRONOUSLY (so nothing can
1948
+ * reach a half-dead session), then a server session's extensions get their
1949
+ * bounded `session_shutdown` before the agent is disposed. The returned promise
1950
+ * settles when that is done and never rejects; callers that do not need to wait
1951
+ * (idle eviction, the delete handler) may ignore it.
1952
+ */
1931
1953
  destroySession(sessionFileOrId, reason) {
1932
1954
  const tracked = this.getSession(sessionFileOrId);
1933
1955
  if (!tracked)
1934
- return;
1935
- this.cancelIdleCheck(tracked.sessionFile);
1936
- if (tracked.type === 'server') {
1956
+ return Promise.resolve();
1957
+ let teardown = Promise.resolve();
1958
+ if (tracked.type === 'server' && tracked.reloading) {
1959
+ // reloadSession owns the agent mid-rebuild: it is already shutting the old
1960
+ // one down, and it releases the new one once it sees the entry is gone.
1961
+ // Waiting for it keeps server shutdown from exiting mid-teardown.
1962
+ teardown = (tracked.reloadPromise ?? Promise.resolve()).then(() => { }, () => { });
1963
+ }
1964
+ else if (tracked.type === 'server') {
1937
1965
  tracked.eventUnsubscribe();
1938
- tracked.agentSession.dispose();
1966
+ teardown = shutdownAndDisposeAgentSession(tracked.agentSession, `${tracked.sessionFile} (${reason})`, this.extensionShutdownTimeoutMs);
1939
1967
  }
1940
1968
  else {
1941
1969
  try {
@@ -1943,14 +1971,8 @@ export class SessionPool {
1943
1971
  }
1944
1972
  catch (err) { }
1945
1973
  }
1946
- this.sessions.delete(tracked.sessionFile);
1947
- // A prompt whose session is gone can never be answered: drop it here so an
1948
- // abandoned prompt is bounded by the session's own lifetime (idle eviction)
1949
- // rather than waiting for someone to type the next `!sudo`.
1950
- for (const [id, p] of this.pendingSudo) {
1951
- if (p.sessionFileOrId === tracked.sessionFile)
1952
- this.pendingSudo.delete(id);
1953
- }
1974
+ this.dropSessionEntry(tracked);
1975
+ return teardown;
1954
1976
  }
1955
1977
  async registerCliSession(rawSessionFile, cwd, modelStr, cliWs, isStreaming = false) {
1956
1978
  // Canonicalize the CLI-reported path so it keys the same entry the server
@@ -1972,17 +1994,28 @@ export class SessionPool {
1972
1994
  // (the tool-call flavour specifically) so the caller can warn accurately.
1973
1995
  let interruptedTurn = false;
1974
1996
  let interruptedToolCall = false;
1997
+ let serverTeardown = Promise.resolve();
1975
1998
  if (existing) {
1976
1999
  clients = existing.clients;
1977
2000
  this.cancelIdleCheck(sessionFile);
1978
- if (existing.type === 'server') {
2001
+ if (existing.type === 'server' && existing.reloading) {
2002
+ // Mid-reload there is no turn to interrupt (reload refuses while
2003
+ // streaming), and reloadSession owns the agent: it releases the rebuilt
2004
+ // one once it sees this CLI entry has replaced its own.
2005
+ }
2006
+ else if (existing.type === 'server') {
1979
2007
  interruptedToolCall = existing.inFlightToolCount > 0;
1980
2008
  interruptedTurn = interruptedToolCall || existing.agentSession.isStreaming;
1981
2009
  try {
1982
2010
  existing.eventUnsubscribe();
1983
- existing.agentSession.dispose();
1984
2011
  }
1985
2012
  catch (err) { }
2013
+ // Start the server agent's teardown NOW (its in-flight turn is aborted
2014
+ // synchronously, then session_shutdown, then dispose), but only AWAIT
2015
+ // it after the CLI entry has replaced it in the pool, so no message can
2016
+ // reach the dying agent while its extensions shut down. The CLI's pi
2017
+ // process binds its own extensions; nothing to do for it.
2018
+ serverTeardown = shutdownAndDisposeAgentSession(existing.agentSession, `${sessionFile} (cli takeover)`, this.extensionShutdownTimeoutMs);
1986
2019
  }
1987
2020
  }
1988
2021
  let sessionId = existing?.sessionId;
@@ -2038,6 +2071,7 @@ export class SessionPool {
2038
2071
  this.cancelIdleCheck(sessionFile);
2039
2072
  }
2040
2073
  this.sessions.set(sessionFile, tracked);
2074
+ await serverTeardown;
2041
2075
  return { tracked, interruptedTurn, interruptedToolCall };
2042
2076
  }
2043
2077
  async unregisterCliSession(rawSessionFile) {
@@ -2098,8 +2132,190 @@ export class SessionPool {
2098
2132
  }
2099
2133
  async disposeAll() {
2100
2134
  const sessionIds = Array.from(this.sessions.keys());
2101
- for (const id of sessionIds) {
2102
- this.destroySession(id, 'server shutdown');
2135
+ // In parallel: each teardown is bounded on its own, so shutdown takes at most
2136
+ // one extension-shutdown timeout, not one per session.
2137
+ await Promise.all(sessionIds.map((id) => this.destroySession(id, 'server shutdown')));
2138
+ }
2139
+ /**
2140
+ * Build and START a live server agent: fresh settings, resource loader
2141
+ * (extensions, skills, prompts, context files), createAgentSession, then
2142
+ * bindExtensions. The ONE place a server agent is built, shared by loadSession,
2143
+ * createNewSession and reloadSession, so the three can never drift in which
2144
+ * tools, extensions or lifecycle a server session gets.
2145
+ */
2146
+ async buildServerAgent(opts) {
2147
+ const settingsManager = SettingsManager.create(opts.cwd, this.agentDir);
2148
+ // The conversation-mode signal is an INLINE pi extension (the SDK-supported
2149
+ // way to get a before_agent_start hook on a server-created session, the
2150
+ // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
2151
+ // per session, so the armed flag can never cross sessions.
2152
+ const conversationSignal = createConversationModeSignal();
2153
+ const resourceLoader = new DefaultResourceLoader({
2154
+ cwd: opts.cwd,
2155
+ agentDir: this.agentDir,
2156
+ settingsManager,
2157
+ extensionFactories: [conversationSignal.inlineExtension, ...this.extraExtensionFactories],
2158
+ });
2159
+ await resourceLoader.reload();
2160
+ const { session: agentSession } = await createAgentSession({
2161
+ cwd: opts.cwd,
2162
+ authStorage: this.authStorage,
2163
+ modelRegistry: this.modelRegistry,
2164
+ model: opts.model,
2165
+ thinkingLevel: opts.thinkingLevel,
2166
+ sessionManager: opts.sessionManager,
2167
+ settingsManager,
2168
+ resourceLoader,
2169
+ // Register attach_file + say for server-created sessions (web frontend
2170
+ // with no CLI bridge). Both tools are self-contained; their UI affordance
2171
+ // (attach_file's download button, say's spoken-reply card) is driven by
2172
+ // the tool call reaching the web UI, no bridge/marker needed.
2173
+ customTools: [createAttachFileTool(opts.cwd), createSayTool()],
2174
+ sessionStartEvent: opts.sessionStartEvent,
2175
+ });
2176
+ // Start the extensions BEFORE the session is tracked or reaches a client:
2177
+ // createAgentSession only loads them, bindExtensions emits session_start +
2178
+ // resources_discover (see extension-lifecycle.ts for the chosen bindings).
2179
+ await this.bindOrDispose(agentSession, opts.label);
2180
+ return { agentSession, conversationSignal };
2181
+ }
2182
+ /** True while `reloadSession` is rebuilding this session's agent. */
2183
+ isReloading(sessionFileOrId) {
2184
+ const tracked = this.getSession(sessionFileOrId);
2185
+ return tracked?.type === 'server' && tracked.reloading === true;
2186
+ }
2187
+ /**
2188
+ * The web `/reload`: re-read settings, extensions, skills, prompts and context
2189
+ * files for a server session, like pi's `/reload`, WITHOUT calling
2190
+ * `AgentSession.reload()`.
2191
+ *
2192
+ * pi's in-place reload calls pi-ai's `resetApiProviders()`, which is
2193
+ * process-wide: every OTHER live session's extension-registered API providers
2194
+ * would vanish for the seconds the reloading session spends re-loading its
2195
+ * extensions. So the agent is REBUILT instead, through the same builder as a
2196
+ * load: the old agent gets `session_shutdown` (reason `reload`) and is
2197
+ * disposed, then a new AgentSession is built on the SAME SessionManager (so
2198
+ * entries not yet flushed to disk survive, exactly as in an in-place reload),
2199
+ * keeping the current model and thinking level, and its extensions get
2200
+ * `session_start` (reason `reload`). The tracked entry is updated in place, so
2201
+ * clients, idle state and the pool key are untouched.
2202
+ *
2203
+ * Refused while the agent is doing anything (streaming, compacting, running a
2204
+ * `!command`, or a send still in its pre-stream phase: see `busy`), for CLI
2205
+ * bridges (the terminal pi owns that agent) and while already reloading; a
2206
+ * refusal returns `started: false` and changes nothing. `onStart` runs once
2207
+ * every check has passed, before the old agent is touched. If the rebuild
2208
+ * fails the old agent is already gone, so the entry is dropped and the next
2209
+ * load builds a fresh one.
2210
+ *
2211
+ * Unlike pi's in-place reload, the rebuild does NOT carry over an active-tool
2212
+ * set an extension narrowed with `setActiveTools`, extension flag values, or
2213
+ * messages an extension queued for the next turn: the new agent starts from
2214
+ * the defaults, as a fresh load would.
2215
+ */
2216
+ async reloadSession(sessionFileOrId, opts = {}) {
2217
+ const tracked = this.getSession(sessionFileOrId);
2218
+ if (!tracked)
2219
+ return { error: 'Session not found.', started: false };
2220
+ if (tracked.type !== 'server') {
2221
+ return { error: 'This session is running in a terminal pi. Run /reload in that terminal.', started: false };
2222
+ }
2223
+ if (tracked.reloading)
2224
+ return { error: 'This session is already reloading.', started: false };
2225
+ const old = tracked.agentSession;
2226
+ // `busy` covers what pi's flags miss: a send still in extension commands /
2227
+ // input handlers / compaction check (not yet streaming), and a `!command`.
2228
+ if (old.isStreaming || old.isCompacting || old.isBashRunning || (tracked.busy ?? 0) > 0) {
2229
+ return { error: 'Wait for the current response to finish before reloading.', started: false };
2230
+ }
2231
+ // Everything from here to the first await is synchronous, so no send can
2232
+ // slip in between the checks above and `reloading` being observable.
2233
+ tracked.reloading = true;
2234
+ tracked.lastActivity = Date.now();
2235
+ const run = this.runReload(tracked, opts);
2236
+ tracked.reloadPromise = run;
2237
+ return run;
2238
+ }
2239
+ async runReload(tracked, opts) {
2240
+ const old = tracked.agentSession;
2241
+ const label = `${tracked.sessionFile} (reload)`;
2242
+ try {
2243
+ // Past every refusal: the caller can now tell clients the agent is going away.
2244
+ opts.onStart?.();
2245
+ tracked.eventUnsubscribe();
2246
+ const { sessionManager, model, thinkingLevel } = old;
2247
+ await shutdownAndDisposeAgentSession(old, label, this.extensionShutdownTimeoutMs, 'reload');
2248
+ // Otherwise the fresh loader below reuses pi's cached factories: the old code.
2249
+ await clearPiExtensionCache();
2250
+ let built;
2251
+ try {
2252
+ built = await this.buildServerAgent({
2253
+ cwd: tracked.cwd,
2254
+ sessionManager,
2255
+ model,
2256
+ thinkingLevel,
2257
+ sessionStartEvent: { type: 'session_start', reason: 'reload' },
2258
+ label,
2259
+ });
2260
+ }
2261
+ catch (err) {
2262
+ if (this.sessions.get(tracked.sessionFile) !== tracked) {
2263
+ return { error: 'The session was closed while it was reloading.', started: true, closed: true };
2264
+ }
2265
+ this.dropSessionEntry(tracked);
2266
+ return {
2267
+ error: `Reload failed: ${err.message}. Re-open the session to start a fresh agent.`,
2268
+ started: true,
2269
+ };
2270
+ }
2271
+ // The session may have been destroyed (deleted, evicted, taken over by a
2272
+ // CLI, server shutdown) while we were rebuilding. Those paths leave a
2273
+ // reloading agent to us, so the new one is ours to release.
2274
+ if (this.sessions.get(tracked.sessionFile) !== tracked) {
2275
+ await shutdownAndDisposeAgentSession(built.agentSession, `${label} (closed during reload)`, this.extensionShutdownTimeoutMs);
2276
+ return { error: 'The session was closed while it was reloading.', started: true, closed: true };
2277
+ }
2278
+ tracked.agentSession = built.agentSession;
2279
+ tracked.conversationSignal = built.conversationSignal;
2280
+ tracked.model = built.agentSession.model ? `${built.agentSession.model.provider}:${built.agentSession.model.id}` : '';
2281
+ tracked.inFlightToolCount = 0;
2282
+ tracked.isIdle = true;
2283
+ tracked.eventUnsubscribe = this.setupEventListeners(tracked.sessionFile, built.agentSession);
2284
+ return { started: true };
2285
+ }
2286
+ finally {
2287
+ tracked.reloading = false;
2288
+ tracked.reloadPromise = undefined;
2289
+ if (this.sessions.get(tracked.sessionFile) === tracked)
2290
+ this.scheduleIdleCheck(tracked.sessionFile);
2291
+ }
2292
+ }
2293
+ /**
2294
+ * Forget a session entry (its agent's teardown is the caller's business). A
2295
+ * sudo prompt whose session is gone can never be answered: drop it here so an
2296
+ * abandoned prompt is bounded by the session's own lifetime (idle eviction)
2297
+ * rather than waiting for someone to type the next `!sudo`.
2298
+ */
2299
+ dropSessionEntry(tracked) {
2300
+ this.cancelIdleCheck(tracked.sessionFile);
2301
+ this.sessions.delete(tracked.sessionFile);
2302
+ for (const [id, p] of this.pendingSudo) {
2303
+ if (p.sessionFileOrId === tracked.sessionFile)
2304
+ this.pendingSudo.delete(id);
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Bind a freshly created server session's extensions; if that throws, shut
2309
+ * down and dispose the session so a failed create leaks nothing, then rethrow
2310
+ * (the callers turn it into their `{ error }` result).
2311
+ */
2312
+ async bindOrDispose(agentSession, label) {
2313
+ try {
2314
+ await bindServerSessionExtensions(agentSession, label, this.extensionBindWarnAfterMs);
2315
+ }
2316
+ catch (err) {
2317
+ await shutdownAndDisposeAgentSession(agentSession, `${label} (bind failed)`, this.extensionShutdownTimeoutMs);
2318
+ throw err;
2103
2319
  }
2104
2320
  }
2105
2321
  setupEventListeners(sessionFile, agentSession) {