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
@@ -0,0 +1,100 @@
1
+ import type { AgentSession } from '@earendil-works/pi-coding-agent';
2
+ /**
3
+ * The pi EXTENSION LIFECYCLE for server-created sessions.
4
+ *
5
+ * `createAgentSession()` only LOADS extensions. It does not start them: in the pi
6
+ * SDK it is `AgentSession.bindExtensions(...)` that emits `session_start` and then
7
+ * `resources_discover` (extension-contributed skills, prompts, themes). The pi CLI
8
+ * modes (interactive, print, rpc) all call it; a host that skips it leaves every
9
+ * extension that initialises on `session_start` dead. The pi-mcp-adapter was the
10
+ * visible victim ("MCP not initialized" on every `mcp(...)` call).
11
+ *
12
+ * Teardown has the same trap from the other side: `AgentSession.dispose()` does
13
+ * NOT emit `session_shutdown`. Only `AgentSessionRuntime.dispose()` does, through
14
+ * the internal (unexported) `emitSessionShutdownEvent`. Wherever owns bare
15
+ * AgentSessions, not runtimes, so without this module extensions never cleaned up
16
+ * (MCP connections, OAuth callback servers, timers) for the life of the process.
17
+ *
18
+ * The contract, used by every server-session path in session-pool.ts:
19
+ * - bind on create: `bindServerSessionExtensions()` right after
20
+ * `createAgentSession()`, before the session is tracked or handed to clients;
21
+ * - shut down before dispose: `shutdownAndDisposeAgentSession()` is the ONLY way
22
+ * a server session is disposed, so no call site can skip `session_shutdown`.
23
+ */
24
+ /**
25
+ * Drop pi's PROCESS-WIDE cache of loaded extension factories, so the next
26
+ * resource load re-reads extension code from disk.
27
+ *
28
+ * pi caches each extension's factory at module level (keyed by cwd), and only
29
+ * `DefaultResourceLoader.reload()` on an ALREADY-LOADED loader clears it: that is
30
+ * how pi's own `/reload` picks up edited extension code. Wherever's `/reload`
31
+ * rebuilds with a FRESH loader (see SessionPool.reloadSession), whose first
32
+ * `reload()` does not clear, so without this the rebuilt agent silently runs the
33
+ * old code. `clearExtensionCache` is not in the package's `exports` map, so it is
34
+ * reached through the module file next to the resolved entry point; it is the
35
+ * same module instance the SDK uses (same URL). If a future SDK moves it, reload
36
+ * still works for settings, skills, prompts and context files, and this logs
37
+ * why extension edits were not picked up. Pinned by test/session-reload-ws.test.ts.
38
+ * Clearing is safe for other sessions: their next build just reloads from disk.
39
+ */
40
+ export declare function clearPiExtensionCache(): Promise<void>;
41
+ /** Upper bound on extension `session_shutdown` handlers before we dispose anyway. */
42
+ export declare const EXTENSION_SHUTDOWN_TIMEOUT_MS = 5000;
43
+ /**
44
+ * After this long without `session_start` handlers finishing, log that the bind is
45
+ * stuck. It does NOT cancel the bind (a half-started extension set is worse than a
46
+ * slow one); it only makes a hang visible in the journal, where it otherwise
47
+ * shows up as a session that silently never opens.
48
+ */
49
+ export declare const EXTENSION_BIND_WARN_AFTER_MS = 15000;
50
+ type ExtensionBindings = Parameters<AgentSession['bindExtensions']>[0];
51
+ /**
52
+ * The bindings a server-created session hands to `bindExtensions`. Chosen against
53
+ * `AgentSession.bindExtensions` / `_applyExtensionBindings` in the bundled SDK:
54
+ *
55
+ * - `uiContext`: left UNSET. The runner then uses its no-op UI context, so
56
+ * `ctx.hasUI` is false and extensions take their non-interactive path. The web
57
+ * UI has no channel for extension dialogs (select / confirm / input / custom
58
+ * components); a context that pretended otherwise would make a dialog hang or
59
+ * silently resolve to a default the human never chose.
60
+ * - `mode: 'print'`: the SDK's own headless default, and the only non-json mode
61
+ * the SDK documents as compatible with `hasUI === false` ("true in TUI and RPC
62
+ * modes"). Passing it explicitly records the decision instead of inheriting it.
63
+ * `rpc` would claim a dialog-capable client we do not have.
64
+ * - `onError`: logs every extension error (handler throws in session_start,
65
+ * session_shutdown, tool hooks...) to the journal. Setting any binding also
66
+ * makes `AgentSession.reload()` re-emit `session_start` on reload, which it
67
+ * skips for a session that was never bound.
68
+ * - `commandContextActions`: minimal and honest. Only `waitForIdle` acts (on this
69
+ * very AgentSession). The session-REPLACING actions (newSession, fork,
70
+ * switchSession) and navigateTree answer `{ cancelled: true }`: sessions here
71
+ * are owned by the pool, keyed by file, and swapped only through the web
72
+ * protocol, so an extension must not do it behind the UI's back. The SDK's
73
+ * unbound defaults would instead report `{ cancelled: false }` for work that
74
+ * never happened.
75
+ * - `reload` is REFUSED too (logged, resolves without reloading). Not because the
76
+ * session could not survive it, but because `AgentSession.reload()` calls pi-ai's
77
+ * `resetApiProviders()`, which is PROCESS-WIDE: in a multi-session server, one
78
+ * session's reload would drop the custom API providers every OTHER live
79
+ * session's extensions registered. The web `/reload` does not use it either: it
80
+ * REBUILDS the agent (`SessionPool.reloadSession`). Routing an extension's
81
+ * `ctx.reload()` there is possible but would dispose the session whose command
82
+ * is still running, so it stays refused until that is designed.
83
+ * - `shutdownHandler`: left unset. `ctx.shutdown()` from an extension must not
84
+ * stop the whole multi-session server.
85
+ * - `abortHandler`: left unset, so `ctx.abort()` aborts this session's turn (the
86
+ * SDK default).
87
+ */
88
+ export declare function serverExtensionBindings(agentSession: AgentSession, label: string): ExtensionBindings;
89
+ /** Start the extensions of a freshly created server session (emits session_start + resources_discover). */
90
+ export declare function bindServerSessionExtensions(agentSession: AgentSession, label: string, warnAfterMs?: number): Promise<void>;
91
+ /**
92
+ * Emit `session_shutdown` to the session's extensions, then dispose it. The
93
+ * shutdown is awaited but bounded by `timeoutMs`, so a hung extension cannot
94
+ * block idle eviction or server shutdown. Never rejects. `reason` is `quit` for
95
+ * every teardown except the pool's `/reload` rebuild, which says `reload` so
96
+ * extensions can tell a restart from an exit (as they can under the pi CLI).
97
+ */
98
+ export declare function shutdownAndDisposeAgentSession(agentSession: AgentSession, label: string, timeoutMs?: number, reason?: 'quit' | 'reload'): Promise<void>;
99
+ export {};
100
+ //# sourceMappingURL=extension-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-lifecycle.d.ts","sourceRoot":"","sources":["../src/extension-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,iCAAiC,CAAC;AAEpF;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAa3D;AAED,qFAAqF;AACrF,eAAO,MAAM,6BAA6B,OAAQ,CAAC;AAEnD;;;;;GAKG;AACH,eAAO,MAAM,4BAA4B,QAAS,CAAC;AAEnD,KAAK,iBAAiB,GAAG,UAAU,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAWvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAmBpG;AAED,2GAA2G;AAC3G,wBAAsB,2BAA2B,CAC/C,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE,MAAM,EACb,WAAW,SAA+B,GACzC,OAAO,CAAC,IAAI,CAAC,CAcf;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CAClD,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE,MAAM,EACb,SAAS,SAAgC,EACzC,MAAM,GAAE,MAAM,GAAG,QAAiB,GACjC,OAAO,CAAC,IAAI,CAAC,CAoCf"}
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The pi EXTENSION LIFECYCLE for server-created sessions.
3
+ *
4
+ * `createAgentSession()` only LOADS extensions. It does not start them: in the pi
5
+ * SDK it is `AgentSession.bindExtensions(...)` that emits `session_start` and then
6
+ * `resources_discover` (extension-contributed skills, prompts, themes). The pi CLI
7
+ * modes (interactive, print, rpc) all call it; a host that skips it leaves every
8
+ * extension that initialises on `session_start` dead. The pi-mcp-adapter was the
9
+ * visible victim ("MCP not initialized" on every `mcp(...)` call).
10
+ *
11
+ * Teardown has the same trap from the other side: `AgentSession.dispose()` does
12
+ * NOT emit `session_shutdown`. Only `AgentSessionRuntime.dispose()` does, through
13
+ * the internal (unexported) `emitSessionShutdownEvent`. Wherever owns bare
14
+ * AgentSessions, not runtimes, so without this module extensions never cleaned up
15
+ * (MCP connections, OAuth callback servers, timers) for the life of the process.
16
+ *
17
+ * The contract, used by every server-session path in session-pool.ts:
18
+ * - bind on create: `bindServerSessionExtensions()` right after
19
+ * `createAgentSession()`, before the session is tracked or handed to clients;
20
+ * - shut down before dispose: `shutdownAndDisposeAgentSession()` is the ONLY way
21
+ * a server session is disposed, so no call site can skip `session_shutdown`.
22
+ */
23
+ /**
24
+ * Drop pi's PROCESS-WIDE cache of loaded extension factories, so the next
25
+ * resource load re-reads extension code from disk.
26
+ *
27
+ * pi caches each extension's factory at module level (keyed by cwd), and only
28
+ * `DefaultResourceLoader.reload()` on an ALREADY-LOADED loader clears it: that is
29
+ * how pi's own `/reload` picks up edited extension code. Wherever's `/reload`
30
+ * rebuilds with a FRESH loader (see SessionPool.reloadSession), whose first
31
+ * `reload()` does not clear, so without this the rebuilt agent silently runs the
32
+ * old code. `clearExtensionCache` is not in the package's `exports` map, so it is
33
+ * reached through the module file next to the resolved entry point; it is the
34
+ * same module instance the SDK uses (same URL). If a future SDK moves it, reload
35
+ * still works for settings, skills, prompts and context files, and this logs
36
+ * why extension edits were not picked up. Pinned by test/session-reload-ws.test.ts.
37
+ * Clearing is safe for other sessions: their next build just reloads from disk.
38
+ */
39
+ export async function clearPiExtensionCache() {
40
+ try {
41
+ const entry = import.meta.resolve('@earendil-works/pi-coding-agent');
42
+ const loader = (await import(new URL('./core/extensions/loader.js', entry).href));
43
+ if (typeof loader.clearExtensionCache !== 'function')
44
+ throw new Error('clearExtensionCache not found');
45
+ loader.clearExtensionCache();
46
+ }
47
+ catch (err) {
48
+ console.error(`[wherever] could not clear pi's extension cache; /reload will not pick up edited extension code: ${err.message}`);
49
+ }
50
+ }
51
+ /** Upper bound on extension `session_shutdown` handlers before we dispose anyway. */
52
+ export const EXTENSION_SHUTDOWN_TIMEOUT_MS = 5_000;
53
+ /**
54
+ * After this long without `session_start` handlers finishing, log that the bind is
55
+ * stuck. It does NOT cancel the bind (a half-started extension set is worse than a
56
+ * slow one); it only makes a hang visible in the journal, where it otherwise
57
+ * shows up as a session that silently never opens.
58
+ */
59
+ export const EXTENSION_BIND_WARN_AFTER_MS = 15_000;
60
+ function logExtensionError(label, err) {
61
+ // stderr is the wherever journal under systemd. Never swallowed: an extension
62
+ // that fails to start is otherwise invisible from the web UI.
63
+ console.error(`[wherever] extension error in ${label} (${err.extensionPath}, ${err.event}): ${err.error}` +
64
+ (err.stack ? `\n${err.stack}` : ''));
65
+ }
66
+ /**
67
+ * The bindings a server-created session hands to `bindExtensions`. Chosen against
68
+ * `AgentSession.bindExtensions` / `_applyExtensionBindings` in the bundled SDK:
69
+ *
70
+ * - `uiContext`: left UNSET. The runner then uses its no-op UI context, so
71
+ * `ctx.hasUI` is false and extensions take their non-interactive path. The web
72
+ * UI has no channel for extension dialogs (select / confirm / input / custom
73
+ * components); a context that pretended otherwise would make a dialog hang or
74
+ * silently resolve to a default the human never chose.
75
+ * - `mode: 'print'`: the SDK's own headless default, and the only non-json mode
76
+ * the SDK documents as compatible with `hasUI === false` ("true in TUI and RPC
77
+ * modes"). Passing it explicitly records the decision instead of inheriting it.
78
+ * `rpc` would claim a dialog-capable client we do not have.
79
+ * - `onError`: logs every extension error (handler throws in session_start,
80
+ * session_shutdown, tool hooks...) to the journal. Setting any binding also
81
+ * makes `AgentSession.reload()` re-emit `session_start` on reload, which it
82
+ * skips for a session that was never bound.
83
+ * - `commandContextActions`: minimal and honest. Only `waitForIdle` acts (on this
84
+ * very AgentSession). The session-REPLACING actions (newSession, fork,
85
+ * switchSession) and navigateTree answer `{ cancelled: true }`: sessions here
86
+ * are owned by the pool, keyed by file, and swapped only through the web
87
+ * protocol, so an extension must not do it behind the UI's back. The SDK's
88
+ * unbound defaults would instead report `{ cancelled: false }` for work that
89
+ * never happened.
90
+ * - `reload` is REFUSED too (logged, resolves without reloading). Not because the
91
+ * session could not survive it, but because `AgentSession.reload()` calls pi-ai's
92
+ * `resetApiProviders()`, which is PROCESS-WIDE: in a multi-session server, one
93
+ * session's reload would drop the custom API providers every OTHER live
94
+ * session's extensions registered. The web `/reload` does not use it either: it
95
+ * REBUILDS the agent (`SessionPool.reloadSession`). Routing an extension's
96
+ * `ctx.reload()` there is possible but would dispose the session whose command
97
+ * is still running, so it stays refused until that is designed.
98
+ * - `shutdownHandler`: left unset. `ctx.shutdown()` from an extension must not
99
+ * stop the whole multi-session server.
100
+ * - `abortHandler`: left unset, so `ctx.abort()` aborts this session's turn (the
101
+ * SDK default).
102
+ */
103
+ export function serverExtensionBindings(agentSession, label) {
104
+ const refuse = (action) => async () => {
105
+ console.warn(`[wherever] extension asked to ${action} in ${label}; not supported for server sessions`);
106
+ return { cancelled: true };
107
+ };
108
+ return {
109
+ mode: 'print',
110
+ onError: (err) => logExtensionError(label, err),
111
+ commandContextActions: {
112
+ waitForIdle: () => agentSession.waitForIdle(),
113
+ reload: async () => {
114
+ await refuse('reload (process-wide provider reset)')();
115
+ },
116
+ newSession: refuse('start a new session'),
117
+ fork: refuse('fork the session'),
118
+ navigateTree: refuse('navigate the session tree'),
119
+ switchSession: refuse('switch session'),
120
+ },
121
+ };
122
+ }
123
+ /** Start the extensions of a freshly created server session (emits session_start + resources_discover). */
124
+ export async function bindServerSessionExtensions(agentSession, label, warnAfterMs = EXTENSION_BIND_WARN_AFTER_MS) {
125
+ const started = Date.now();
126
+ const watchdog = setTimeout(() => {
127
+ console.error(`[wherever] extension session_start for ${label} still running after ${warnAfterMs}ms; the session cannot open until it finishes`);
128
+ }, warnAfterMs);
129
+ try {
130
+ await agentSession.bindExtensions(serverExtensionBindings(agentSession, label));
131
+ }
132
+ finally {
133
+ clearTimeout(watchdog);
134
+ const elapsed = Date.now() - started;
135
+ if (elapsed >= warnAfterMs)
136
+ console.error(`[wherever] extension session_start for ${label} finished after ${elapsed}ms`);
137
+ }
138
+ }
139
+ /**
140
+ * Emit `session_shutdown` to the session's extensions, then dispose it. The
141
+ * shutdown is awaited but bounded by `timeoutMs`, so a hung extension cannot
142
+ * block idle eviction or server shutdown. Never rejects. `reason` is `quit` for
143
+ * every teardown except the pool's `/reload` rebuild, which says `reload` so
144
+ * extensions can tell a restart from an exit (as they can under the pi CLI).
145
+ */
146
+ export async function shutdownAndDisposeAgentSession(agentSession, label, timeoutMs = EXTENSION_SHUTDOWN_TIMEOUT_MS, reason = 'quit') {
147
+ // Stop any in-flight turn FIRST, synchronously. dispose() would abort it, but
148
+ // it runs only after the (up to timeoutMs) shutdown handlers; until then a live
149
+ // turn would keep streaming, running tools and appending to the transcript,
150
+ // which recreates a just-deleted session file or races a CLI that took over.
151
+ // This mirrors dispose()'s own first step and cannot hang.
152
+ try {
153
+ agentSession.agent.abort();
154
+ }
155
+ catch (err) {
156
+ console.error(`[wherever] abort failed for ${label}:`, err);
157
+ }
158
+ try {
159
+ // Read the runner NOW: `reload()` replaces it, and the live one is the one
160
+ // whose extensions hold resources.
161
+ const runner = agentSession.extensionRunner;
162
+ if (runner.hasHandlers('session_shutdown')) {
163
+ let timer;
164
+ const timedOut = await Promise.race([
165
+ runner.emit({ type: 'session_shutdown', reason }).then(() => false),
166
+ new Promise((resolve) => {
167
+ timer = setTimeout(() => resolve(true), timeoutMs);
168
+ }),
169
+ ]).finally(() => clearTimeout(timer));
170
+ if (timedOut) {
171
+ console.error(`[wherever] extension session_shutdown for ${label} exceeded ${timeoutMs}ms; disposing anyway`);
172
+ }
173
+ }
174
+ }
175
+ catch (err) {
176
+ // emit() already routes handler throws to onError; this is the runner itself failing.
177
+ console.error(`[wherever] session_shutdown failed for ${label}:`, err);
178
+ }
179
+ try {
180
+ agentSession.dispose();
181
+ }
182
+ catch (err) {
183
+ console.error(`[wherever] dispose failed for ${label}:`, err);
184
+ }
185
+ }
186
+ //# sourceMappingURL=extension-lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-lifecycle.js","sourceRoot":"","sources":["../src/extension-lifecycle.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB;IACzC,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,iCAAiC,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,IAAI,GAAG,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,CAE/E,CAAC;QACF,IAAI,OAAO,MAAM,CAAC,mBAAmB,KAAK,UAAU;YAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;QACvG,MAAM,CAAC,mBAAmB,EAAE,CAAC;IAC/B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CACX,oGAAqG,GAAa,CAAC,OAAO,EAAE,CAC7H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,qFAAqF;AACrF,MAAM,CAAC,MAAM,6BAA6B,GAAG,KAAK,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAInD,SAAS,iBAAiB,CAAC,KAAa,EAAE,GAAmB;IAC3D,8EAA8E;IAC9E,8DAA8D;IAC9D,OAAO,CAAC,KAAK,CACX,iCAAiC,KAAK,KAAK,GAAG,CAAC,aAAa,KAAK,GAAG,CAAC,KAAK,MAAM,GAAG,CAAC,KAAK,EAA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EAAE;oBAC/B,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;gBACrD,CAAC,CAAC;aACH,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;YACtC,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,6CAA6C,KAAK,aAAa,SAAS,sBAAsB,CAAC,CAAC;YAChH,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,sFAAsF;QACtF,OAAO,CAAC,KAAK,CAAC,0CAA0C,KAAK,GAAG,EAAE,GAAG,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,CAAC;QACH,YAAY,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,KAAK,GAAG,EAAE,GAAG,CAAC,CAAC;IAChE,CAAC;AACH,CAAC"}
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { createServer as createHttpServer } from 'node:http';
3
3
  import { createServer as createHttpsServer, request as httpRequest } from 'node:https';
4
4
  import { connect as netConnect } from 'node:net';
5
5
  import { WebSocketServer, WebSocket } from 'ws';
6
- import { SessionPool, getWhereverConfig, getWhereverCertsDir, detectRemoteRepo, normalizePath, invalidateFolderExistence } from './session-pool.js';
6
+ import { SessionPool, RELOADING_REFUSAL, getWhereverConfig, getWhereverCertsDir, detectRemoteRepo, normalizePath, invalidateFolderExistence } from './session-pool.js';
7
7
  import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
8
8
  import { searchConversations } from './conversation-search.js';
9
9
  import { matchRemoteRepoRule, resolveRemoteCandidates } from './remote-candidates.js';
@@ -2686,6 +2686,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2686
2686
  // folder -- but the client is locked and, on the cold path below, no live
2687
2687
  // agent is built at all.
2688
2688
  const restoreInFlight = restoreJobs.get(meta.cwd)?.state === 'running';
2689
+ const reloadingNow = meta.resident && pool.isReloading(meta.sessionFile);
2689
2690
  const folderMissing = meta.folderMissing || restoreInFlight;
2690
2691
  client.folderMissingCwd = folderMissing ? meta.cwd : undefined;
2691
2692
  // A session whose cwd matches a sessions.readOnly glob is forced read-only.
@@ -2709,7 +2710,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2709
2710
  folderConflict,
2710
2711
  folderMissing,
2711
2712
  contextUsage: meta.resident ? (pool.getContextUsage(meta.sessionFile) ?? null) : null,
2712
- pending: !meta.resident,
2713
+ // A resident session mid-/reload has no usable agent yet: paint it as
2714
+ // pending; the reload's own session_ready (sent to every viewer, this
2715
+ // one included once attached below) ends it.
2716
+ pending: !meta.resident || reloadingNow,
2713
2717
  });
2714
2718
  sendWS(client.ws, {
2715
2719
  type: 'message_history',
@@ -2743,6 +2747,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2743
2747
  pool.addClient(meta.sessionFile, client.id);
2744
2748
  switchClientSession(client, meta.sessionFile, pool, onSessionsUpdated);
2745
2749
  client.readOnly = forcedReadOnly;
2750
+ // Mid-/reload: the reload's completion frame is this client's ready.
2751
+ if (reloadingNow)
2752
+ break;
2746
2753
  sendWS(client.ws, {
2747
2754
  type: 'session_ready',
2748
2755
  sessionId: meta.sessionId,
@@ -3152,6 +3159,15 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3152
3159
  });
3153
3160
  break;
3154
3161
  }
3162
+ // A /reload is rebuilding the agent. The composer is blocked on every viewer
3163
+ // (session_reloading), so this is a race or an old client: answer, retryably.
3164
+ if (pool.isReloading(client.sessionId)) {
3165
+ // session_error is what fails the message on the client (Retry), but it
3166
+ // also clears agentPending: re-assert the reload block right after it.
3167
+ sendWS(client.ws, { type: 'session_error', sessionId: msg.sessionId, error: RELOADING_REFUSAL });
3168
+ sendWS(client.ws, { type: 'session_reloading', sessionId: attached.sessionId });
3169
+ break;
3170
+ }
3155
3171
  const streaming = pool.isStreaming(client.sessionId);
3156
3172
  // The optional conversationMode field is the per-turn spoken-conversation
3157
3173
  // signal (absent = off). It only decides whether a hint is appended to this
@@ -3203,6 +3219,74 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3203
3219
  await pool.cancelSteerQueue(client.sessionId);
3204
3220
  break;
3205
3221
  }
3222
+ case 'session_reload': {
3223
+ if (!client.sessionId)
3224
+ return;
3225
+ // Same authority guard as 'message': only reload the session this
3226
+ // connection is attached to AND looking at.
3227
+ const attached = pool.getSession(client.sessionId);
3228
+ const target = msg.sessionId ? pool.getSession(msg.sessionId) : attached;
3229
+ if (!attached || !target || target !== attached) {
3230
+ sendWS(client.ws, {
3231
+ type: 'session_error',
3232
+ sessionId: msg.sessionId,
3233
+ error: 'The session changed, so it was not reloaded. Re-open it and try /reload again.',
3234
+ });
3235
+ break;
3236
+ }
3237
+ const refuse = (message) => sendWS(client.ws, { type: 'session_notice', sessionId: attached.sessionId, level: 'warning', message });
3238
+ // Reloading re-runs extension code and rebuilds the agent every viewer
3239
+ // shares: an observe-only client may not trigger that.
3240
+ if (client.readOnly) {
3241
+ refuse('This session is read-only from here, so it was not reloaded.');
3242
+ break;
3243
+ }
3244
+ const sessionFile = attached.sessionFile;
3245
+ const sessionId = attached.sessionId;
3246
+ // Tell the connections that are CURRENTLY on this session, decided at send
3247
+ // time: a viewer who switched away mid-reload must not get this session's
3248
+ // frames (the client's session_error handler is not session-scoped). Found
3249
+ // by scanning connections rather than the pool entry, because a failed
3250
+ // rebuild drops the entry while its viewers are still attached to the file.
3251
+ const tellViewers = (message) => {
3252
+ for (const c of clients.values()) {
3253
+ if (c.sessionId === sessionFile)
3254
+ sendWS(c.ws, message);
3255
+ }
3256
+ };
3257
+ const result = await pool.reloadSession(sessionFile, {
3258
+ onStart: () => tellViewers({ type: 'session_reloading', sessionId }),
3259
+ });
3260
+ if (!result.started) {
3261
+ refuse(result.error ?? 'The session could not be reloaded.');
3262
+ break;
3263
+ }
3264
+ if (result.closed) {
3265
+ // Deleted / evicted / taken over mid-reload: the path that closed it has
3266
+ // already told its viewers what happened. An error on top would mislead.
3267
+ break;
3268
+ }
3269
+ if (result.error) {
3270
+ // Every current viewer saw session_reloading, so each needs its end.
3271
+ tellViewers({ type: 'session_error', sessionId, error: result.error });
3272
+ break;
3273
+ }
3274
+ tellViewers({
3275
+ type: 'session_ready',
3276
+ sessionId,
3277
+ sessionFile,
3278
+ model: pool.getSession(sessionFile)?.model,
3279
+ isStreaming: pool.isStreaming(sessionFile),
3280
+ contextUsage: pool.getContextUsage(sessionFile) ?? null,
3281
+ });
3282
+ tellViewers({
3283
+ type: 'session_notice',
3284
+ sessionId,
3285
+ level: 'info',
3286
+ message: 'Reloaded extensions, skills, prompts and context files.',
3287
+ });
3288
+ break;
3289
+ }
3206
3290
  case 'bash_sudo_password': {
3207
3291
  if (!client.sessionId)
3208
3292
  return;
@@ -3227,6 +3311,13 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3227
3311
  case 'model_change': {
3228
3312
  if (!client.sessionId)
3229
3313
  return;
3314
+ if (pool.isReloading(client.sessionId)) {
3315
+ // A notice, not session_error: the latter would clear the reload's
3316
+ // composer block on this client before the rebuilt agent is ready.
3317
+ const reloadingId = pool.getSession(client.sessionId)?.sessionId ?? '';
3318
+ sendWS(client.ws, { type: 'session_notice', sessionId: reloadingId, level: 'warning', message: RELOADING_REFUSAL });
3319
+ break;
3320
+ }
3230
3321
  const result = await pool.changeModel(client.sessionId, msg.model);
3231
3322
  if (result.error) {
3232
3323
  sendWS(client.ws, { type: 'session_error', error: result.error });