wherever-dev 0.23.0 → 0.25.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 (86) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/assistant-channels.d.ts +46 -1
  3. package/dist/assistant-channels.d.ts.map +1 -1
  4. package/dist/assistant-channels.js +57 -1
  5. package/dist/assistant-channels.js.map +1 -1
  6. package/dist/assistant-controller.d.ts +14 -0
  7. package/dist/assistant-controller.d.ts.map +1 -1
  8. package/dist/assistant-controller.js +26 -2
  9. package/dist/assistant-controller.js.map +1 -1
  10. package/dist/assistant-folder.d.ts +14 -1
  11. package/dist/assistant-folder.d.ts.map +1 -1
  12. package/dist/assistant-folder.js +33 -2
  13. package/dist/assistant-folder.js.map +1 -1
  14. package/dist/assistant-schedule.d.ts +42 -3
  15. package/dist/assistant-schedule.d.ts.map +1 -1
  16. package/dist/assistant-schedule.js +113 -2
  17. package/dist/assistant-schedule.js.map +1 -1
  18. package/dist/assistant-scheduler.d.ts +28 -6
  19. package/dist/assistant-scheduler.d.ts.map +1 -1
  20. package/dist/assistant-scheduler.js +59 -12
  21. package/dist/assistant-scheduler.js.map +1 -1
  22. package/dist/assistant-tool-text.d.ts.map +1 -1
  23. package/dist/assistant-tool-text.js +5 -1
  24. package/dist/assistant-tool-text.js.map +1 -1
  25. package/dist/assistant-tools.d.ts +65 -16
  26. package/dist/assistant-tools.d.ts.map +1 -1
  27. package/dist/assistant-tools.js +95 -9
  28. package/dist/assistant-tools.js.map +1 -1
  29. package/dist/attach-file-tool.d.ts +17 -0
  30. package/dist/attach-file-tool.d.ts.map +1 -1
  31. package/dist/attach-file-tool.js +44 -37
  32. package/dist/attach-file-tool.js.map +1 -1
  33. package/dist/cli-requests.d.ts +2 -1
  34. package/dist/cli-requests.d.ts.map +1 -1
  35. package/dist/cli-requests.js.map +1 -1
  36. package/dist/commands/config.d.ts +28 -0
  37. package/dist/commands/config.d.ts.map +1 -0
  38. package/dist/commands/config.js +128 -0
  39. package/dist/commands/config.js.map +1 -0
  40. package/dist/commands/install.d.ts.map +1 -1
  41. package/dist/commands/install.js +2 -0
  42. package/dist/commands/install.js.map +1 -1
  43. package/dist/config-dir.d.ts +13 -0
  44. package/dist/config-dir.d.ts.map +1 -1
  45. package/dist/config-dir.js +13 -0
  46. package/dist/config-dir.js.map +1 -1
  47. package/dist/index.js +192 -44
  48. package/dist/index.js.map +1 -1
  49. package/dist/protocol.d.ts +7 -0
  50. package/dist/protocol.d.ts.map +1 -1
  51. package/dist/session-pool.d.ts +32 -6
  52. package/dist/session-pool.d.ts.map +1 -1
  53. package/dist/session-pool.js +94 -37
  54. package/dist/session-pool.js.map +1 -1
  55. package/dist/telegram-channel.d.ts +14 -2
  56. package/dist/telegram-channel.d.ts.map +1 -1
  57. package/dist/telegram-channel.js +41 -8
  58. package/dist/telegram-channel.js.map +1 -1
  59. package/dist/telegram-replies.d.ts +18 -0
  60. package/dist/telegram-replies.d.ts.map +1 -1
  61. package/dist/telegram-replies.js +41 -23
  62. package/dist/telegram-replies.js.map +1 -1
  63. package/package.json +1 -1
  64. package/public/_app/immutable/chunks/{FePVnZ_7.js → CRvF0-wF.js} +2 -2
  65. package/public/_app/immutable/chunks/{FePVnZ_7.js.map → CRvF0-wF.js.map} +1 -1
  66. package/public/_app/immutable/chunks/{CLKlGLL7.js → ClUQt0nO.js} +2 -2
  67. package/public/_app/immutable/chunks/{CLKlGLL7.js.map → ClUQt0nO.js.map} +1 -1
  68. package/public/_app/immutable/chunks/{BHw5ar2A.js → XW0SPyOK.js} +2 -2
  69. package/public/_app/immutable/chunks/{BHw5ar2A.js.map → XW0SPyOK.js.map} +1 -1
  70. package/public/_app/immutable/entry/{app.BJxkSaKZ.js → app.D1EX_9pb.js} +3 -3
  71. package/public/_app/immutable/entry/{app.BJxkSaKZ.js.map → app.D1EX_9pb.js.map} +1 -1
  72. package/public/_app/immutable/entry/start.ga0QZFSJ.js +2 -0
  73. package/public/_app/immutable/entry/start.ga0QZFSJ.js.map +1 -0
  74. package/public/_app/immutable/nodes/{0.DGFJlad5.js → 0.DsJW22vw.js} +2 -2
  75. package/public/_app/immutable/nodes/{0.DGFJlad5.js.map → 0.DsJW22vw.js.map} +1 -1
  76. package/public/_app/immutable/nodes/{1.Cy3IVwDh.js → 1.BsL25UTD.js} +2 -2
  77. package/public/_app/immutable/nodes/{1.Cy3IVwDh.js.map → 1.BsL25UTD.js.map} +1 -1
  78. package/public/_app/immutable/nodes/2.DO5lRCyx.js +124 -0
  79. package/public/_app/immutable/nodes/2.DO5lRCyx.js.map +1 -0
  80. package/public/_app/version.json +1 -1
  81. package/public/index.html +10 -10
  82. package/public/service-worker.js +1 -1
  83. package/public/_app/immutable/entry/start.CRP1MCwE.js +0 -2
  84. package/public/_app/immutable/entry/start.CRP1MCwE.js.map +0 -1
  85. package/public/_app/immutable/nodes/2.eb9p7ShF.js +0 -123
  86. package/public/_app/immutable/nodes/2.eb9p7ShF.js.map +0 -1
package/dist/index.js CHANGED
@@ -5,11 +5,11 @@ import { connect as netConnect } from 'node:net';
5
5
  import { WebSocketServer, WebSocket } from 'ws';
6
6
  import { SessionPool, RELOADING_REFUSAL, getWhereverConfig, getWhereverCertsDir, getWhereverStateDir, detectRemoteRepo, normalizePath, invalidateFolderExistence } from './session-pool.js';
7
7
  import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
8
- import { startAssistantFolder } from './assistant-folder.js';
8
+ import { canonicalPath, startAssistantFolder } from './assistant-folder.js';
9
9
  import { AssistantController } from './assistant-controller.js';
10
10
  import { AssistantScheduler } from './assistant-scheduler.js';
11
- import { assistantNotActiveError, setTimezone, testNotification, WEB_TIMEZONE_SOURCE, } from './assistant-tools.js';
12
- import { ChannelDispatcher } from './assistant-channels.js';
11
+ import { assistantNotActiveError, testNotification, webTimezoneReport, } from './assistant-tools.js';
12
+ import { ChannelDispatcher, reportDroppedBeyondChannels } from './assistant-channels.js';
13
13
  import { WebPushChannel, resolveVapidSubject, validateSubscription } from './web-push.js';
14
14
  import { TelegramChannel } from './telegram-channel.js';
15
15
  import { normalizeToolCalls } from './telegram-replies.js';
@@ -38,11 +38,17 @@ import { fileURLToPath } from 'node:url';
38
38
  import os from 'node:os';
39
39
  import { execFileSync } from 'node:child_process';
40
40
  import { runInstall, runUninstall, runServiceStatus, parseInstallOptions, printInstallHelp, } from './commands/install.js';
41
+ import { runConfigCommand } from './commands/config.js';
42
+ import { getWhereverConfigPath } from './config-dir.js';
41
43
  const __filename = fileURLToPath(import.meta.url);
42
44
  const __dirname = path.dirname(__filename);
43
45
  const devStaticPath = path.resolve(__dirname, '../../web/build');
44
46
  const prodStaticPath = path.resolve(__dirname, '../public');
45
- const staticDir = fs.existsSync(devStaticPath) ? devStaticPath : prodStaticPath;
47
+ // TEST-ONLY lever: `WHEREVER_TEST_STATIC_DIR` serves the web app from that
48
+ // directory, so a test of static serving does not depend on a web build being
49
+ // present (CI's server jobs build none). Unset (every real deployment) it is a
50
+ // no-op.
51
+ const staticDir = process.env.WHEREVER_TEST_STATIC_DIR || (fs.existsSync(devStaticPath) ? devStaticPath : prodStaticPath);
46
52
  // When true (set via --debug), the served dashboard index.html is rewritten so
47
53
  // eruda's custom-plugin loader is enabled. Plugin loading is the only eruda
48
54
  // feature that takes a URL parameter into a <script src>, so it is kept off by
@@ -373,8 +379,8 @@ function resolveHeartbeatMs(raw) {
373
379
  // CLI bridges are deliberately left ALONE: their re-registration is already
374
380
  // handled by registerCliSession/unregisterCliSession, and tearing one down here
375
381
  // would race a cli_register arriving on the new socket against the old socket's
376
- // async close teardown, which could unregister the session that was just
377
- // re-registered.
382
+ // async close teardown. (That teardown itself only removes the entry its own
383
+ // socket owns, so a reconnect that lands first survives it.)
378
384
  function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
379
385
  for (const prev of Array.from(clients.values())) {
380
386
  if (prev.clientKey !== clientKey || prev.isCliBridge)
@@ -996,6 +1002,11 @@ async function main() {
996
1002
  debugEnabled = debug;
997
1003
  console.log(`[wherever] pi SDK ${piSdkInfo.version}: ` +
998
1004
  (piSdkInfo.tier === 'bundled' ? `bundled (${piSdkInfo.why})` : `${piSdkInfo.tier}, from ${piSdkInfo.root} (${piSdkInfo.why})`));
1005
+ // Where the config comes from (ADR 0022): reading it never creates it, so a
1006
+ // missing file is said here instead of being silently seeded.
1007
+ const configPath = getWhereverConfigPath();
1008
+ console.log(`[wherever] config: ${configPath} ` +
1009
+ (fs.existsSync(configPath) ? '(found)' : '(not found, using built-in defaults)'));
999
1010
  const sessionPool = new SessionPool(idleTimeout, { getStarred: readStarredSet });
1000
1011
  await sessionPool.initialize();
1001
1012
  // The assistant folder (opt-in via `assistantFolder`, see assistant-folder.ts):
@@ -1005,10 +1016,15 @@ async function main() {
1005
1016
  const assistant = startAssistantFolder(getWhereverConfig());
1006
1017
  sessionPool.setAssistantFolder(assistant.status.active ? (assistant.status.folder ?? undefined) : undefined);
1007
1018
  // The assistant tools (assistant-tools.ts) in every server session, and the
1008
- // timezone line in the assistant folder: registered while `assistantFolder`
1009
- // is CONFIGURED. The backend is the scheduler, set below once it has started;
1010
- // until then, and for a server refused by the folder lock, every tool answers
1011
- // the lock-state error. Unset = no hooks, so sessions are exactly as before.
1019
+ // timezone line in the assistant folder: registered ONLY while the assistant
1020
+ // is ACTIVE (configured AND this server holds the folder lock). The backend is
1021
+ // the scheduler, set below once it has started; in that short boot window the
1022
+ // tools answer "the assistant scheduler is still starting". A server refused by the lock (or a lock error)
1023
+ // sets NO session hooks, so its sessions are exactly as with the assistant
1024
+ // unset (decision of assistant-schedule-tools-absent-when-not-active,
1025
+ // reversing assistant-schedule-tools-server decision 4). The CLI twin ops
1026
+ // still get the hooks while CONFIGURED, so a terminal pi's twin (which cannot
1027
+ // be hidden server-side) answers the lock-state error.
1012
1028
  let assistantBackend = null;
1013
1029
  // `assistant_notify`'s backend (the channel dispatcher + the scheduler's job
1014
1030
  // mapping), set below once the channels have started. The tool itself is
@@ -1022,7 +1038,9 @@ async function main() {
1022
1038
  folder: assistant.status.folder,
1023
1039
  access: () => assistantBackend
1024
1040
  ? { ok: true, backend: assistantBackend }
1025
- : { ok: false, error: assistantNotActiveError(assistant.status.lock) },
1041
+ : assistant.status.active
1042
+ ? { ok: false, error: 'the assistant scheduler is still starting; try again in a moment' }
1043
+ : { ok: false, error: assistantNotActiveError(assistant.status.lock) },
1026
1044
  ...(assistant.status.active
1027
1045
  ? {
1028
1046
  notify: () => notifyBackend
@@ -1031,7 +1049,8 @@ async function main() {
1031
1049
  }
1032
1050
  : {}),
1033
1051
  };
1034
- sessionPool.setAssistantSessionHooks(assistantHooks);
1052
+ if (assistant.status.active)
1053
+ sessionPool.setAssistantSessionHooks(assistantHooks);
1035
1054
  }
1036
1055
  const currentTimezone = () => {
1037
1056
  try {
@@ -1074,16 +1093,68 @@ async function main() {
1074
1093
  if (!c.isCliBridge)
1075
1094
  sendWS(c.ws, update);
1076
1095
  }
1096
+ refreshRetiredViewers();
1077
1097
  },
1078
1098
  // Messages a reset or an aborted settle dropped: reported to the
1079
1099
  // channels they came from (the dispatcher exists by then; before it
1080
- // does, nothing has been sent from a channel, so nothing is lost).
1081
- onDropped: (dropped) => channelDispatcher?.reportDropped(dropped),
1100
+ // does, nothing has been sent from a channel, so nothing is lost);
1101
+ // the web's own become a notice to the session's web viewers (the
1102
+ // retired session's, on a reset), and a scheduled job's are logged.
1103
+ onDropped: (dropped) => {
1104
+ channelDispatcher?.reportDropped(dropped);
1105
+ reportDroppedBeyondChannels(dropped, {
1106
+ notifyWebViewers: (sessionFile, message) => {
1107
+ const sessionId = sessionPool.getSession(sessionFile)?.sessionId;
1108
+ if (!sessionId)
1109
+ return;
1110
+ const notice = { type: 'session_notice', sessionId, level: 'warning', message };
1111
+ for (const c of clients.values()) {
1112
+ if (!c.isCliBridge && c.sessionId === sessionFile)
1113
+ sendWS(c.ws, notice);
1114
+ }
1115
+ },
1116
+ });
1117
+ },
1082
1118
  })
1083
1119
  : null;
1084
1120
  if (assistantController) {
1085
1121
  sessionPool.onSessionCreated = (sessionFile, cwd) => assistantController.handleSessionCreated(sessionFile, cwd);
1086
1122
  }
1123
+ /**
1124
+ * The pointer moved: re-evaluate every web viewer's RETIRED verdict (ADR 0020)
1125
+ * and tell those whose verdict changed, live (`assistant_retired`), so a tab
1126
+ * still on the old session turns read-only without a reload. Keyed on the
1127
+ * PAINTED session, so a cold load still building is covered too (its attach
1128
+ * re-derives read-only from the flag). Then every folder-conflict verdict is
1129
+ * re-sent: the newly retired session stopped being an occupant.
1130
+ */
1131
+ function refreshRetiredViewers() {
1132
+ if (!assistantController)
1133
+ return;
1134
+ for (const c of clients.values()) {
1135
+ if (c.isCliBridge || !c.paintedSessionFile || !c.paintedCwd || !c.paintedSessionId)
1136
+ continue;
1137
+ const retired = assistantController.isRetired(c.paintedSessionFile, c.paintedCwd);
1138
+ if (retired === (c.assistantRetired === true))
1139
+ continue;
1140
+ c.assistantRetired = retired || undefined;
1141
+ if (retired) {
1142
+ // Hard: it replaces any folder-conflict observation the client was in.
1143
+ c.readOnly = true;
1144
+ c.conflictObserver = false;
1145
+ }
1146
+ else {
1147
+ // Became current again (the pointer moved onto the painted session):
1148
+ // only the remaining reasons decide.
1149
+ c.readOnly =
1150
+ sessionPool.isReadOnlyCwd(c.paintedCwd) ||
1151
+ c.folderMissingCwd !== undefined ||
1152
+ (c.conflictObserver === true && !c.conflictContinued);
1153
+ }
1154
+ sendWS(c.ws, { type: 'assistant_retired', sessionId: c.paintedSessionId, retired, readOnly: c.readOnly });
1155
+ }
1156
+ broadcastFolderConflicts();
1157
+ }
1087
1158
  // The assistant scheduler (assistant-scheduler.ts, ADR 0015): fires the jobs in
1088
1159
  // `<assistantFolder>/schedule.json`. Built and started ONLY while the
1089
1160
  // assistant is active (configured AND this server holds the folder lock), so
@@ -1214,22 +1285,28 @@ async function main() {
1214
1285
  }
1215
1286
  };
1216
1287
  /**
1217
- * A web client's timezone report (`client_timezone`, sent on connect): made the
1218
- * user's current timezone when it differs, only while the assistant is active.
1219
- * Otherwise ignored, so nothing is written. An unknown zone is logged and ignored.
1288
+ * A web client's timezone report (`client_timezone`, sent only when the
1289
+ * device's zone moved, ADR 0019): applied by `webTimezoneReport` (a first
1290
+ * report never overrides `assistant_set_timezone`), only while the assistant
1291
+ * is active. Otherwise ignored, so nothing is written. An unknown zone is
1292
+ * logged and ignored.
1220
1293
  */
1221
- const onClientTimezone = (timezone) => {
1294
+ const onClientTimezone = (report) => {
1295
+ const { timezone } = report;
1222
1296
  if (!assistantBackend || typeof timezone !== 'string' || !timezone.trim())
1223
1297
  return;
1224
- const r = setTimezone(assistantBackend, { timezone }, WEB_TIMEZONE_SOURCE);
1298
+ const r = webTimezoneReport(assistantBackend, report);
1225
1299
  if (!r.ok)
1226
1300
  console.warn(`[wherever] assistant: ignoring the web's timezone report: ${r.error}`);
1227
1301
  };
1228
1302
  // The CLI bridge's request/response path (ADR 0016, cli-requests.ts). Built
1229
1303
  // whether or not the assistant is active: `assistant_info` is how a terminal pi
1230
1304
  // learns it is NOT, and that answer is what keeps its tool twins inactive.
1305
+ // The folder goes out CANONICAL (symlinks resolved): the bridge compares it
1306
+ // with the terminal pi's real cwd, and a bridge cannot realpath a path on the
1307
+ // server's side of a symlink it may not share.
1231
1308
  const currentAssistantInfo = () => ({
1232
- assistantFolder: assistantController ? assistant.status.folder : null,
1309
+ assistantFolder: assistantController && assistant.status.folder ? canonicalPath(assistant.status.folder) : null,
1233
1310
  timezone: assistantController ? currentTimezone() : null,
1234
1311
  });
1235
1312
  const cliRequests = createCliRequestRouter({ assistantInfo: currentAssistantInfo, assistantHooks: () => assistantHooks });
@@ -1313,7 +1390,16 @@ async function main() {
1313
1390
  console.log(`Self-signed certificates generated successfully in ${certsDir}`);
1314
1391
  }
1315
1392
  catch (err) {
1316
- console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
1393
+ const e = err;
1394
+ if (e.code === 'ENOENT' && e.syscall?.startsWith('spawn') && e.path === 'openssl') {
1395
+ // The binary itself is missing: say so, rather than the bare
1396
+ // `spawnSync openssl ENOENT` (the certs dir was created fine).
1397
+ console.warn(`Cannot generate self-signed certificates: \`openssl\` was not found on PATH. Falling back to HTTP. ` +
1398
+ `Install openssl (it is in the flake devshell, \`nix develop\`), pass --ssl-key/--ssl-cert, or pass --no-ssl to silence this.`);
1399
+ }
1400
+ else {
1401
+ console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
1402
+ }
1317
1403
  isSecure = false;
1318
1404
  }
1319
1405
  }
@@ -1375,7 +1461,7 @@ async function main() {
1375
1461
  // readOnly rides along every time so the client's composer mirrors the
1376
1462
  // server's authority rather than inferring it from `active`.
1377
1463
  for (const c of clients.values()) {
1378
- sendFolderConflict(c, sessionPool);
1464
+ sendFolderConflict(c, sessionPool, assistantController);
1379
1465
  }
1380
1466
  }
1381
1467
  function broadcastAgentEvent(sessionFile, event) {
@@ -1585,9 +1671,13 @@ async function main() {
1585
1671
  }
1586
1672
  }
1587
1673
  sessionPool.onEvent = broadcastAgentEvent;
1674
+ // DELETE is used only by Web Push's `/push/subscription`, so it is advertised
1675
+ // only while those routes exist: with the assistant off (or Web Push disabled)
1676
+ // the header is what it was before the assistant.
1677
+ const corsAllowMethods = webPushChannel ? 'GET, POST, DELETE, OPTIONS' : 'GET, POST, OPTIONS';
1588
1678
  const requestHandler = async (req, res) => {
1589
1679
  res.setHeader('Access-Control-Allow-Origin', '*');
1590
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
1680
+ res.setHeader('Access-Control-Allow-Methods', corsAllowMethods);
1591
1681
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
1592
1682
  if (req.method === 'OPTIONS') {
1593
1683
  res.writeHead(200);
@@ -2828,7 +2918,9 @@ async function main() {
2828
2918
  ws.on('close', async () => {
2829
2919
  if (client.sessionId) {
2830
2920
  if (client.isCliBridge) {
2831
- await sessionPool.unregisterCliSession(client.sessionId);
2921
+ // Only this socket's own registration: a reconnect may already
2922
+ // have replaced it (see unregisterCliSession).
2923
+ await sessionPool.unregisterCliSession(client.sessionId, ws);
2832
2924
  }
2833
2925
  else {
2834
2926
  sessionPool.removeClient(client.sessionId, clientId);
@@ -2984,6 +3076,8 @@ function clearPaintedSession(client) {
2984
3076
  client.paintedSessionFile = undefined;
2985
3077
  client.paintedSessionId = undefined;
2986
3078
  client.paintedCwd = undefined;
3079
+ // The retired verdict describes the painted session, so it goes with it.
3080
+ client.assistantRetired = undefined;
2987
3081
  }
2988
3082
  /**
2989
3083
  * TEST-ONLY lever: `WHEREVER_TEST_COLD_BUILD_DELAY_MS` holds a cold
@@ -3002,10 +3096,21 @@ function coldBuildTestDelay() {
3002
3096
  // is the whole definition of a folder conflict: two agents pointed at one working
3003
3097
  // tree. Two viewers of the SAME conversation are not a conflict (they share one
3004
3098
  // agent), and a session nobody is attached to is not one either (idle, no turns).
3005
- function folderHasOtherViewedSession(pool, mySessionFile, cwd) {
3099
+ //
3100
+ // A RETIRED assistant session (ADR 0020) never counts as an occupant: the
3101
+ // conflict would be one our own reset created, and it would open the CURRENT
3102
+ // session read-only behind the banner while a tab still views the old one.
3103
+ function folderHasOtherViewedSession(pool, mySessionFile, cwd, assistant) {
3006
3104
  return pool
3007
3105
  .getAllSessions()
3008
- .some((s) => s.sessionFile !== mySessionFile && s.cwd === cwd && s.clients.size > 0);
3106
+ .some((s) => s.sessionFile !== mySessionFile &&
3107
+ s.cwd === cwd &&
3108
+ s.clients.size > 0 &&
3109
+ !isRetiredAssistantSession(assistant, s.sessionFile, s.cwd));
3110
+ }
3111
+ /** Is this a retired assistant session (ADR 0020)? Always false while the assistant is not active. */
3112
+ function isRetiredAssistantSession(assistant, sessionFile, cwd) {
3113
+ return assistant !== null && assistant.isRetired(sessionFile, cwd);
3009
3114
  }
3010
3115
  // Recompute ONE client's folder-conflict state and settle the read-only it
3011
3116
  // imposed: releasing it once the conflict no longer holds is part of resolving,
@@ -3013,13 +3118,15 @@ function folderHasOtherViewedSession(pool, mySessionFile, cwd) {
3013
3118
  // cold attach and the "Continue anyway" reply so all three speak with one
3014
3119
  // authority. Returns null for connections the banner does not apply to (CLI
3015
3120
  // bridges, clients not attached to a session).
3016
- function resolveFolderConflictState(c, pool) {
3121
+ function resolveFolderConflictState(c, pool, assistant) {
3017
3122
  if (c.isCliBridge || !c.sessionId)
3018
3123
  return null;
3019
3124
  const mine = pool.getSession(c.sessionId);
3020
3125
  if (!mine)
3021
3126
  return null;
3022
- const active = folderHasOtherViewedSession(pool, mine.sessionFile, mine.cwd);
3127
+ // A retired assistant session is not a party to a folder conflict at all: its
3128
+ // own (hard) verdict already says why it is read-only and what to open instead.
3129
+ const active = c.assistantRetired !== true && folderHasOtherViewedSession(pool, mine.sessionFile, mine.cwd, assistant);
3023
3130
  // NOTE: every conflict is now between DIFFERENT session files in one folder --
3024
3131
  // an observer gets its own new session (session_new) or loads its own
3025
3132
  // (session_load), never the occupant's file -- so the scan above sees them all.
@@ -3037,17 +3144,20 @@ function resolveFolderConflictState(c, pool) {
3037
3144
  }
3038
3145
  return { cwd: mine.cwd, active };
3039
3146
  }
3040
- // Read-only PRECEDENCE in one place. Of the three reasons a client can be
3041
- // read-only, two are HARD and one is dismissible:
3147
+ // Read-only PRECEDENCE in one place. Of the four reasons a client can be
3148
+ // read-only, three are HARD and one is dismissible:
3042
3149
  // - a configured `sessions.readOnly` folder: a policy rule, never lifted;
3043
3150
  // - FOLDER MISSING: the working folder does not exist on this machine, so
3044
3151
  // there is nothing to drive; lifted only by restoring it and RELOADING;
3152
+ // - a RETIRED assistant session (ADR 0020): not the current pointer session
3153
+ // in `assistantFolder`; writing would fork the assistant's conversation into
3154
+ // a session nobody points at, so the remedy is opening the current one;
3045
3155
  // - a folder conflict: two live sessions in one folder, lifted by the user's
3046
3156
  // "Continue anyway".
3047
3157
  // Every site that LIFTS read-only asks this first, so the dismissible reason can
3048
3158
  // never dismiss a hard one.
3049
3159
  function hasHardReadOnly(client, pool, cwd) {
3050
- return pool.isReadOnlyCwd(cwd) || client.folderMissingCwd !== undefined;
3160
+ return pool.isReadOnlyCwd(cwd) || client.folderMissingCwd !== undefined || client.assistantRetired === true;
3051
3161
  }
3052
3162
  // ---------------------------------------------------------------------------
3053
3163
  // Restore jobs over the WebSocket
@@ -3258,8 +3368,8 @@ async function cloneForNewSession(targetPath, clients, pool, onStarted) {
3258
3368
  // Resolve and report in one step. Every folder_conflict frame goes out through
3259
3369
  // here, so the `readOnly` it carries can never drift from the authority that
3260
3370
  // produced `active`.
3261
- function sendFolderConflict(client, pool) {
3262
- const verdict = resolveFolderConflictState(client, pool);
3371
+ function sendFolderConflict(client, pool, assistant) {
3372
+ const verdict = resolveFolderConflictState(client, pool, assistant);
3263
3373
  if (!verdict)
3264
3374
  return;
3265
3375
  sendWS(client.ws, {
@@ -3300,8 +3410,8 @@ function sendQueueSnapshot(client, sessionFile, sessionId, pool) {
3300
3410
  async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated, assistantController = null, cliRequests = null, onClientTimezone = () => { }) {
3301
3411
  switch (msg.type) {
3302
3412
  case 'client_timezone':
3303
- // The web's timezone report on connect (see onClientTimezone in main).
3304
- onClientTimezone(msg.timezone);
3413
+ // The web's timezone report when its device moved (see onClientTimezone in main).
3414
+ onClientTimezone({ timezone: msg.timezone, first: msg.first });
3305
3415
  break;
3306
3416
  case 'assistant_open':
3307
3417
  case 'assistant_reset': {
@@ -3465,8 +3575,13 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3465
3575
  // client starts read-only (observing) until the user clicks "Continue
3466
3576
  // anyway" (folder_conflict_continue), which lifts read-only WITHOUT
3467
3577
  // aborting the other session -- both then run concurrently.
3468
- const conflict = pool.detectConflict(meta.sessionFile, meta.cwd);
3469
- const folderConflict = conflict.conflict && !!conflict.otherSessionId;
3578
+ //
3579
+ // A RETIRED assistant session (ADR 0020) is neither a party to a conflict
3580
+ // nor an occupant of one: it is hard read-only on its own account, and a
3581
+ // tab still viewing it must not lock the CURRENT session out.
3582
+ const retired = isRetiredAssistantSession(assistantController, meta.sessionFile, meta.cwd);
3583
+ const conflict = pool.detectConflict(meta.sessionFile, meta.cwd, (s) => isRetiredAssistantSession(assistantController, s.sessionFile, s.cwd));
3584
+ const folderConflict = !retired && conflict.conflict && !!conflict.otherSessionId;
3470
3585
  // This session's working folder is not usable as a working folder. TWO
3471
3586
  // things produce that, and they are one state because they have one
3472
3587
  // remedy and one rendering:
@@ -3486,11 +3601,13 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3486
3601
  const folderMissing = meta.folderMissing || restoreInFlight;
3487
3602
  client.folderMissingCwd = folderMissing ? meta.cwd : undefined;
3488
3603
  // A session whose cwd matches a sessions.readOnly glob is forced read-only.
3489
- // A missing folder forces it too (hard, see hasHardReadOnly). A folder
3490
- // conflict also starts the client read-only until they continue.
3491
- const forcedReadOnly = meta.readOnly || folderMissing || folderConflict;
3604
+ // A missing folder forces it too (hard, see hasHardReadOnly), and so does a
3605
+ // retired assistant session. A folder conflict also starts the client
3606
+ // read-only until they continue.
3607
+ const forcedReadOnly = meta.readOnly || folderMissing || retired || folderConflict;
3492
3608
  client.readOnly = forcedReadOnly;
3493
3609
  client.conflictObserver = folderConflict;
3610
+ client.assistantRetired = retired || undefined;
3494
3611
  client.pendingCwd = meta.cwd;
3495
3612
  // Bind uploads (and this load's late attach) to the session painted now.
3496
3613
  client.paintedSessionFile = meta.sessionFile;
@@ -3509,6 +3626,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3509
3626
  readOnly: forcedReadOnly,
3510
3627
  folderConflict,
3511
3628
  folderMissing,
3629
+ ...(retired ? { assistantRetired: true } : {}),
3512
3630
  contextUsage: meta.resident ? (pool.getContextUsage(meta.sessionFile) ?? null) : null,
3513
3631
  // A resident session mid-/reload has no usable agent yet: paint it as
3514
3632
  // pending; the reload's own session_ready (sent to every viewer, this
@@ -3619,9 +3737,12 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3619
3737
  // it, while `message` dropped their sends in silence. The conflict having
3620
3738
  // RESOLVED during the build is handled just below by the verdict, which
3621
3739
  // re-scans and releases read-only.
3740
+ // The retired verdict is read from the client, not from `retired`: the
3741
+ // pointer may have moved during the build (refreshRetiredViewers).
3622
3742
  client.readOnly =
3623
3743
  meta.readOnly ||
3624
3744
  pool.isReadOnlyCwd(result.tracked.cwd) ||
3745
+ client.assistantRetired === true ||
3625
3746
  (client.conflictObserver === true && !client.conflictContinued);
3626
3747
  sendWS(client.ws, {
3627
3748
  type: 'session_ready',
@@ -3639,7 +3760,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3639
3760
  // user continued through it). session_ready carries no readOnly, and the
3640
3761
  // periodic conflict broadcast is throttled, so state the verdict here
3641
3762
  // explicitly rather than leaving the composer to guess for up to 2s.
3642
- sendFolderConflict(client, pool);
3763
+ sendFolderConflict(client, pool, assistantController);
3643
3764
  })();
3644
3765
  break;
3645
3766
  }
@@ -3739,9 +3860,20 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3739
3860
  // clicks "Continue anyway", which lifts read-only WITHOUT touching the other
3740
3861
  // session. The difference from before is that the banner now sits on the
3741
3862
  // conversation they asked for, so continuing does what it says.
3742
- const folderOccupied = folderHasOtherViewedSession(pool, result.tracked.sessionFile, result.tracked.cwd);
3743
- client.readOnly = folderOccupied || pool.isReadOnlyCwd(result.tracked.cwd);
3863
+ //
3864
+ // A session created IN the assistant folder becomes the current assistant
3865
+ // session through the pool's session-created callback, which the
3866
+ // controller runs on its serial queue: wait for it, so the verdict below
3867
+ // sees the pointer already on the new session (and the one it replaced
3868
+ // already retired, so it is no occupant). Only for that folder: the queue
3869
+ // can hold a seconds-long load, which no other create should wait on.
3870
+ if (assistantController?.isFolder(result.tracked.cwd))
3871
+ await assistantController.idle();
3872
+ const retired = isRetiredAssistantSession(assistantController, result.tracked.sessionFile, result.tracked.cwd);
3873
+ const folderOccupied = !retired && folderHasOtherViewedSession(pool, result.tracked.sessionFile, result.tracked.cwd, assistantController);
3874
+ client.readOnly = retired || folderOccupied || pool.isReadOnlyCwd(result.tracked.cwd);
3744
3875
  client.conflictObserver = folderOccupied;
3876
+ client.assistantRetired = retired || undefined;
3745
3877
  client.paintedSessionFile = result.tracked.sessionFile;
3746
3878
  client.paintedSessionId = result.tracked.sessionId;
3747
3879
  client.paintedCwd = result.tracked.cwd;
@@ -3754,6 +3886,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3754
3886
  isStreaming: pool.isStreaming(result.tracked.sessionFile),
3755
3887
  readOnly: client.readOnly,
3756
3888
  folderConflict: folderOccupied,
3889
+ ...(retired ? { assistantRetired: true } : {}),
3757
3890
  });
3758
3891
  sendWS(client.ws, {
3759
3892
  type: 'message_history',
@@ -3843,7 +3976,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3843
3976
  // was already in flight when the continue was sent, so an in-flight update
3844
3977
  // carrying the pre-continue readOnly:true cannot leave the composer
3845
3978
  // disabled with the banner's button already gone.
3846
- sendFolderConflict(client, pool);
3979
+ sendFolderConflict(client, pool, assistantController);
3847
3980
  break;
3848
3981
  }
3849
3982
  case 'restore_start': {
@@ -3949,6 +4082,17 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
3949
4082
  }
3950
4083
  if (!client.sessionId)
3951
4084
  return;
4085
+ if (client.assistantRetired) {
4086
+ // A retired assistant session (ADR 0020): hard, so do not point at the
4087
+ // banner's "Continue anyway", point at the current session instead.
4088
+ sendWS(client.ws, {
4089
+ type: 'session_error',
4090
+ sessionId: msg.sessionId,
4091
+ error: 'This assistant session was retired (the assistant was reset), so it is read-only and the message was not delivered. ' +
4092
+ 'Open the current assistant session to continue.',
4093
+ });
4094
+ return;
4095
+ }
3952
4096
  if (client.readOnly) {
3953
4097
  // Never swallow a send. This is a legitimate refusal for an observe-only
3954
4098
  // session (a sessions.readOnly folder, or a folder conflict not continued
@@ -4417,6 +4561,7 @@ function getVersion() {
4417
4561
  * Subcommand dispatch. Every action is an explicit verb:
4418
4562
  * - `wherever start [server flags]` runs the server
4419
4563
  * - `wherever install|uninstall|service-status` manage the background service
4564
+ * - `wherever config init|show` write a starter config / show the effective one
4420
4565
  * - `wherever --version` (or `-v` / `version`) prints the version
4421
4566
  * - bare `wherever` (or `help`) prints usage
4422
4567
  * Server flags after `start` are consumed by parseArgs() (which reads
@@ -4446,6 +4591,9 @@ function dispatch() {
4446
4591
  case 'status':
4447
4592
  runServiceStatus(parseInstallOptions(rest));
4448
4593
  return;
4594
+ case 'config':
4595
+ process.exitCode = runConfigCommand(rest);
4596
+ return;
4449
4597
  case 'version':
4450
4598
  case '--version':
4451
4599
  case '-v':