wherever-dev 0.21.1 → 0.22.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 (103) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/assistant-channels.d.ts +242 -0
  3. package/dist/assistant-channels.d.ts.map +1 -0
  4. package/dist/assistant-channels.js +270 -0
  5. package/dist/assistant-channels.js.map +1 -0
  6. package/dist/assistant-controller.d.ts +228 -0
  7. package/dist/assistant-controller.d.ts.map +1 -0
  8. package/dist/assistant-controller.js +314 -0
  9. package/dist/assistant-controller.js.map +1 -0
  10. package/dist/assistant-cron.d.ts +87 -0
  11. package/dist/assistant-cron.d.ts.map +1 -0
  12. package/dist/assistant-cron.js +352 -0
  13. package/dist/assistant-cron.js.map +1 -0
  14. package/dist/assistant-folder.d.ts +161 -0
  15. package/dist/assistant-folder.d.ts.map +1 -0
  16. package/dist/assistant-folder.js +333 -0
  17. package/dist/assistant-folder.js.map +1 -0
  18. package/dist/assistant-schedule.d.ts +236 -0
  19. package/dist/assistant-schedule.d.ts.map +1 -0
  20. package/dist/assistant-schedule.js +454 -0
  21. package/dist/assistant-schedule.js.map +1 -0
  22. package/dist/assistant-scheduler.d.ts +210 -0
  23. package/dist/assistant-scheduler.d.ts.map +1 -0
  24. package/dist/assistant-scheduler.js +472 -0
  25. package/dist/assistant-scheduler.js.map +1 -0
  26. package/dist/assistant-tool-text.d.ts +40 -0
  27. package/dist/assistant-tool-text.d.ts.map +1 -0
  28. package/dist/assistant-tool-text.js +102 -0
  29. package/dist/assistant-tool-text.js.map +1 -0
  30. package/dist/assistant-tools.d.ts +222 -0
  31. package/dist/assistant-tools.d.ts.map +1 -0
  32. package/dist/assistant-tools.js +411 -0
  33. package/dist/assistant-tools.js.map +1 -0
  34. package/dist/cli-requests.d.ts +90 -0
  35. package/dist/cli-requests.d.ts.map +1 -0
  36. package/dist/cli-requests.js +75 -0
  37. package/dist/cli-requests.js.map +1 -0
  38. package/dist/index.js +427 -7
  39. package/dist/index.js.map +1 -1
  40. package/dist/protocol.d.ts +43 -0
  41. package/dist/protocol.d.ts.map +1 -1
  42. package/dist/reply-routing.d.ts +106 -0
  43. package/dist/reply-routing.d.ts.map +1 -0
  44. package/dist/reply-routing.js +174 -0
  45. package/dist/reply-routing.js.map +1 -0
  46. package/dist/session-pool.d.ts +235 -4
  47. package/dist/session-pool.d.ts.map +1 -1
  48. package/dist/session-pool.js +446 -100
  49. package/dist/session-pool.js.map +1 -1
  50. package/dist/telegram-channel.d.ts +275 -0
  51. package/dist/telegram-channel.d.ts.map +1 -0
  52. package/dist/telegram-channel.js +702 -0
  53. package/dist/telegram-channel.js.map +1 -0
  54. package/dist/telegram-files.d.ts +101 -0
  55. package/dist/telegram-files.d.ts.map +1 -0
  56. package/dist/telegram-files.js +145 -0
  57. package/dist/telegram-files.js.map +1 -0
  58. package/dist/telegram-pairing.d.ts +119 -0
  59. package/dist/telegram-pairing.d.ts.map +1 -0
  60. package/dist/telegram-pairing.js +97 -0
  61. package/dist/telegram-pairing.js.map +1 -0
  62. package/dist/telegram-replies.d.ts +140 -0
  63. package/dist/telegram-replies.d.ts.map +1 -0
  64. package/dist/telegram-replies.js +474 -0
  65. package/dist/telegram-replies.js.map +1 -0
  66. package/dist/telegram-token.d.ts +55 -0
  67. package/dist/telegram-token.d.ts.map +1 -0
  68. package/dist/telegram-token.js +86 -0
  69. package/dist/telegram-token.js.map +1 -0
  70. package/dist/web-push.d.ts +167 -0
  71. package/dist/web-push.d.ts.map +1 -0
  72. package/dist/web-push.js +387 -0
  73. package/dist/web-push.js.map +1 -0
  74. package/package.json +1 -1
  75. package/public/_app/immutable/assets/0.hWfYEET-.css +1 -0
  76. package/public/_app/immutable/chunks/Cuh9gHb6.js +2 -0
  77. package/public/_app/immutable/chunks/Cuh9gHb6.js.map +1 -0
  78. package/public/_app/immutable/chunks/DEUwJYqt.js +2 -0
  79. package/public/_app/immutable/chunks/{BQ9B_G4h.js.map → DEUwJYqt.js.map} +1 -1
  80. package/public/_app/immutable/chunks/DSPDB3Gw.js +2 -0
  81. package/public/_app/immutable/chunks/{BUONgvl4.js.map → DSPDB3Gw.js.map} +1 -1
  82. package/public/_app/immutable/entry/{app.BZO7Xckk.js → app.BkV4f8p8.js} +3 -3
  83. package/public/_app/immutable/entry/{app.BZO7Xckk.js.map → app.BkV4f8p8.js.map} +1 -1
  84. package/public/_app/immutable/entry/start.D5TsAoxn.js +2 -0
  85. package/public/_app/immutable/entry/start.D5TsAoxn.js.map +1 -0
  86. package/public/_app/immutable/nodes/{0.Czz2XmZU.js → 0.DR4K9Ylw.js} +3 -3
  87. package/public/_app/immutable/nodes/{0.Czz2XmZU.js.map → 0.DR4K9Ylw.js.map} +1 -1
  88. package/public/_app/immutable/nodes/{1.DDvrriUW.js → 1.DdqkeKC4.js} +2 -2
  89. package/public/_app/immutable/nodes/{1.DDvrriUW.js.map → 1.DdqkeKC4.js.map} +1 -1
  90. package/public/_app/immutable/nodes/2.n5lfdeec.js +122 -0
  91. package/public/_app/immutable/nodes/2.n5lfdeec.js.map +1 -0
  92. package/public/_app/version.json +1 -1
  93. package/public/index.html +11 -11
  94. package/public/service-worker.js +1 -1
  95. package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
  96. package/public/_app/immutable/chunks/BQ9B_G4h.js +0 -2
  97. package/public/_app/immutable/chunks/BUONgvl4.js +0 -2
  98. package/public/_app/immutable/chunks/DauELski.js +0 -2
  99. package/public/_app/immutable/chunks/DauELski.js.map +0 -1
  100. package/public/_app/immutable/entry/start.DWD60uNu.js +0 -2
  101. package/public/_app/immutable/entry/start.DWD60uNu.js.map +0 -1
  102. package/public/_app/immutable/nodes/2.C7E8EMKX.js +0 -120
  103. package/public/_app/immutable/nodes/2.C7E8EMKX.js.map +0 -1
package/dist/index.js CHANGED
@@ -5,6 +5,18 @@ 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';
9
+ import { AssistantController } from './assistant-controller.js';
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';
13
+ import { WebPushChannel, resolveVapidSubject, validateSubscription } from './web-push.js';
14
+ import { TelegramChannel } from './telegram-channel.js';
15
+ import { normalizeToolCalls } from './telegram-replies.js';
16
+ import { normalizeUserId } from './telegram-pairing.js';
17
+ import { resolveTelegramToken, takeTelegramTokenEnv } from './telegram-token.js';
18
+ import { DEFAULT_GRACE_MS } from './assistant-schedule.js';
19
+ import { createCliRequestRouter, assistantInfoChangedFrame } from './cli-requests.js';
8
20
  import { readStarredSet, setSessionStarred, validateStarInput, forgetStar } from './session-stars.js';
9
21
  import { piSdkInfo } from './pi-sdk.js';
10
22
  import { searchConversations } from './conversation-search.js';
@@ -790,7 +802,12 @@ function parseArgs() {
790
802
  // `token` above; nothing reads these variables again.
791
803
  delete process.env.WHEREVER_TOKEN;
792
804
  delete process.env.PI_REMOTE_TOKEN;
793
- return { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
805
+ // The assistant's Telegram bot token variables, for the same reason (ADR 0007,
806
+ // ADR 0018): captured and scrubbed here ALWAYS, before anything is spawned.
807
+ // The token FILE is only read later, and only while the assistant is active
808
+ // and Telegram is enabled (telegram-token.ts).
809
+ const telegramTokenEnv = takeTelegramTokenEnv();
810
+ return { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug, telegramTokenEnv };
794
811
  }
795
812
  /** Loopback-only binds are the safe default; everything else is reachable by others. */
796
813
  function isLoopbackHost(host) {
@@ -899,13 +916,69 @@ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
899
916
  kill();
900
917
  }
901
918
  }
919
+ /**
920
+ * The scheduler's grace window from `assistantScheduleGraceMinutes`: a finite
921
+ * number >= 0, else the default (1 h) with a warning.
922
+ */
923
+ function scheduleGraceMs(minutes) {
924
+ if (minutes === undefined)
925
+ return DEFAULT_GRACE_MS;
926
+ if (typeof minutes === 'number' && Number.isFinite(minutes) && minutes >= 0)
927
+ return minutes * 60_000;
928
+ console.warn(`[wherever] ignoring assistantScheduleGraceMinutes=${JSON.stringify(minutes)} (not a number >= 0); using 60`);
929
+ return DEFAULT_GRACE_MS;
930
+ }
902
931
  async function main() {
903
- const { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
932
+ const { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug, telegramTokenEnv } = parseArgs();
904
933
  debugEnabled = debug;
905
934
  console.log(`[wherever] pi SDK ${piSdkInfo.version}: ` +
906
935
  (piSdkInfo.tier === 'bundled' ? `bundled (${piSdkInfo.why})` : `${piSdkInfo.tier}, from ${piSdkInfo.root} (${piSdkInfo.why})`));
907
936
  const sessionPool = new SessionPool(idleTimeout, { getStarred: readStarredSet });
908
937
  await sessionPool.initialize();
938
+ // The assistant folder (opt-in via `assistantFolder`, see assistant-folder.ts):
939
+ // resolved, created, locked and seeded ONCE here, so a config change takes
940
+ // effect on restart only. The status is a start-time snapshot served by
941
+ // /config. The lock is released on shutdown and, as a backstop, on any exit.
942
+ const assistant = startAssistantFolder(getWhereverConfig());
943
+ sessionPool.setAssistantFolder(assistant.status.active ? (assistant.status.folder ?? undefined) : undefined);
944
+ // The assistant tools (assistant-tools.ts) in every server session, and the
945
+ // timezone line in the assistant folder: registered while `assistantFolder`
946
+ // is CONFIGURED. The backend is the scheduler, set below once it has started;
947
+ // until then, and for a server refused by the folder lock, every tool answers
948
+ // the lock-state error. Unset = no hooks, so sessions are exactly as before.
949
+ let assistantBackend = null;
950
+ // `assistant_notify`'s backend (the channel dispatcher + the scheduler's job
951
+ // mapping), set below once the channels have started. The tool itself is
952
+ // registered ONLY while the assistant is active (a refused server's sessions
953
+ // do not see it), see AssistantSessionHooks.notify.
954
+ let notifyBackend = null;
955
+ // The same hooks also answer the CLI bridge's tool-twin ops (cli-requests.ts).
956
+ let assistantHooks;
957
+ if (assistant.status.configured && assistant.status.folder) {
958
+ assistantHooks = {
959
+ folder: assistant.status.folder,
960
+ access: () => assistantBackend
961
+ ? { ok: true, backend: assistantBackend }
962
+ : { ok: false, error: assistantNotActiveError(assistant.status.lock) },
963
+ ...(assistant.status.active
964
+ ? {
965
+ notify: () => notifyBackend
966
+ ? { ok: true, backend: notifyBackend }
967
+ : { ok: false, error: 'the assistant channels are still starting; try again in a moment' },
968
+ }
969
+ : {}),
970
+ };
971
+ sessionPool.setAssistantSessionHooks(assistantHooks);
972
+ }
973
+ const currentTimezone = () => {
974
+ try {
975
+ return assistantBackend ? assistantBackend.getUserTimezone() : null;
976
+ }
977
+ catch {
978
+ return null;
979
+ }
980
+ };
981
+ process.on('exit', () => assistant.release());
909
982
  // Abandoned partial uploads (untouched for 24 h) are collected at startup and
910
983
  // then hourly. A no-op when the staging dir was never created. The startup
911
984
  // pass is awaited (one readdir) so it is done before the first upload arrives.
@@ -920,6 +993,194 @@ async function main() {
920
993
  const uploadGcTimer = setInterval(runUploadGc, 60 * 60 * 1000);
921
994
  uploadGcTimer.unref?.();
922
995
  const clients = new Map();
996
+ /** The assistant's channel dispatcher, set once the channels start (below; only while active). */
997
+ let channelDispatcher = null;
998
+ // The assistant controller (assistant-controller.ts): which session is the
999
+ // current assistant session, and its reset. Built, and the pool's
1000
+ // session-created callback registered, ONLY while the assistant is active, so
1001
+ // with `assistantFolder` unset (or refused) session creation, `session_new`
1002
+ // and idle teardown are exactly as before.
1003
+ const assistantController = assistant.status.active && assistant.status.folder
1004
+ ? new AssistantController({
1005
+ pool: sessionPool,
1006
+ folder: assistant.status.folder,
1007
+ stateDir: getWhereverStateDir(),
1008
+ onChange: (pointer) => {
1009
+ const update = { type: 'assistant_status', ...pointer, timezone: currentTimezone() };
1010
+ for (const c of clients.values()) {
1011
+ if (!c.isCliBridge)
1012
+ sendWS(c.ws, update);
1013
+ }
1014
+ },
1015
+ // Messages a reset or an aborted settle dropped: reported to the
1016
+ // channels they came from (the dispatcher exists by then; before it
1017
+ // does, nothing has been sent from a channel, so nothing is lost).
1018
+ onDropped: (dropped) => channelDispatcher?.reportDropped(dropped),
1019
+ })
1020
+ : null;
1021
+ if (assistantController) {
1022
+ sessionPool.onSessionCreated = (sessionFile, cwd) => assistantController.handleSessionCreated(sessionFile, cwd);
1023
+ }
1024
+ // The assistant scheduler (assistant-scheduler.ts, ADR 0015): fires the jobs in
1025
+ // `<assistantFolder>/schedule.json`. Built and started ONLY while the
1026
+ // assistant is active (configured AND this server holds the folder lock), so
1027
+ // with `assistantFolder` unset or refused there is no timer and nothing is
1028
+ // written to the state dir.
1029
+ const assistantScheduler = assistantController && assistant.status.folder
1030
+ ? new AssistantScheduler({
1031
+ folder: assistant.status.folder,
1032
+ stateDir: getWhereverStateDir(),
1033
+ pool: sessionPool,
1034
+ controller: assistantController,
1035
+ graceMs: scheduleGraceMs(getWhereverConfig().assistantScheduleGraceMinutes),
1036
+ // Every change of the user's timezone (the web's report, or
1037
+ // `assistant_set_timezone`) goes through the scheduler's setter, which
1038
+ // calls this: CLI bridges get `assistant_info_changed`, dashboards an
1039
+ // `assistant_status` carrying the new zone.
1040
+ onTimezoneChange: () => {
1041
+ pushAssistantInfoChanged();
1042
+ broadcastAssistantStatus();
1043
+ },
1044
+ })
1045
+ : null;
1046
+ await assistantScheduler?.start();
1047
+ assistantBackend = assistantScheduler;
1048
+ // The assistant's CHANNELS (assistant-channels.ts): built and started ONLY
1049
+ // while the assistant is active, like the scheduler. Web Push (web-push.ts,
1050
+ // ADR 0017) is on unless `assistantWebPush.enabled` is false; it writes
1051
+ // nothing until a device subscribes (the VAPID keys are made on first use).
1052
+ const webPushChannel = assistantController && getWhereverConfig().assistantWebPush?.enabled !== false
1053
+ ? new WebPushChannel({
1054
+ stateDir: getWhereverStateDir(),
1055
+ subject: resolveVapidSubject({
1056
+ subject: getWhereverConfig().assistantWebPush?.subject,
1057
+ publicUrl: getWhereverConfig().publicUrl,
1058
+ }),
1059
+ })
1060
+ : null;
1061
+ // Telegram (telegram-channel.ts): only while the assistant is active (two
1062
+ // servers must never poll one bot; the folder lock decides) AND
1063
+ // `assistantTelegram.enabled` is true. Otherwise the token file is not even
1064
+ // read and nothing is logged. A token that cannot be resolved DISABLES
1065
+ // Telegram with a loud error and the server carries on (ADR 0018).
1066
+ const telegramConfig = getWhereverConfig().assistantTelegram;
1067
+ const telegramEnabled = !!assistantController && telegramConfig?.enabled === true;
1068
+ let telegramChannel = null;
1069
+ let telegramDisabledError = null;
1070
+ if (telegramEnabled) {
1071
+ const resolved = resolveTelegramToken({
1072
+ env: telegramTokenEnv,
1073
+ configToken: telegramConfig?.token,
1074
+ readFile: (p) => fs.readFileSync(p, 'utf8'),
1075
+ });
1076
+ for (const w of resolved.warnings)
1077
+ console.warn(`[wherever] telegram: ${w}`);
1078
+ const configuredUserId = normalizeUserId(telegramConfig?.userId);
1079
+ if (telegramConfig?.userId !== undefined && !configuredUserId) {
1080
+ console.warn(`[wherever] telegram: ignoring assistantTelegram.userId=${JSON.stringify(telegramConfig.userId)} (not a numeric Telegram user id); pairing by code instead`);
1081
+ }
1082
+ if (!resolved.ok) {
1083
+ telegramDisabledError = resolved.error;
1084
+ console.error(`[wherever] ERROR: Telegram is DISABLED: ${resolved.error}. The server keeps running without it.`);
1085
+ }
1086
+ else {
1087
+ console.log(`[wherever] telegram: bot token from ${resolved.source}`);
1088
+ telegramChannel = new TelegramChannel({
1089
+ token: resolved.token,
1090
+ stateDir: getWhereverStateDir(),
1091
+ configuredUserId,
1092
+ apiBaseUrl: typeof telegramConfig?.apiBaseUrl === 'string' && telegramConfig.apiBaseUrl.trim() ? telegramConfig.apiBaseUrl.trim() : undefined,
1093
+ // A notification links to the target session when the public URL is set.
1094
+ publicUrl: getWhereverConfig().publicUrl,
1095
+ // A file from Telegram lands where a web upload into the assistant
1096
+ // session does (`uploads.type`), under the same size limit.
1097
+ uploadDir: () => resolveUploadDir(getWhereverConfig(), assistant.status.folder ?? undefined),
1098
+ maxUploadBytes: () => uploadMaxBytes(getWhereverConfig()),
1099
+ toolCalls: normalizeToolCalls(telegramConfig?.toolCalls),
1100
+ });
1101
+ if (telegramConfig?.toolCalls !== undefined && telegramConfig.toolCalls !== 'off' && telegramConfig.toolCalls !== 'compact') {
1102
+ console.warn(`[wherever] telegram: ignoring assistantTelegram.toolCalls=${JSON.stringify(telegramConfig.toolCalls)} (expected "off" or "compact"); using "off"`);
1103
+ }
1104
+ }
1105
+ }
1106
+ const assistantChannels = [
1107
+ ...(webPushChannel ? [webPushChannel] : []),
1108
+ ...(telegramChannel ? [telegramChannel] : []),
1109
+ ];
1110
+ channelDispatcher = assistantController
1111
+ ? new ChannelDispatcher({ controller: assistantController, pool: sessionPool, channels: assistantChannels })
1112
+ : null;
1113
+ await channelDispatcher?.start();
1114
+ if (channelDispatcher && assistantScheduler) {
1115
+ const scheduler = assistantScheduler;
1116
+ const dispatcher = channelDispatcher;
1117
+ notifyBackend = {
1118
+ notify: (n) => dispatcher.notify(n),
1119
+ jobOrigin: (jobId) => {
1120
+ const job = scheduler.store.read().valid.find((v) => v.job.id === jobId)?.job;
1121
+ return job ? { originSessionId: job.originSessionId, originCwd: job.originCwd } : null;
1122
+ },
1123
+ jobForSession: (sessionFile) => scheduler.jobForSession(sessionFile),
1124
+ };
1125
+ }
1126
+ /** The Web Push part of the assistant status (only while active). */
1127
+ const webPushStatus = () => ({
1128
+ enabled: !!webPushChannel,
1129
+ publicKey: webPushChannel?.existingPublicKey() ?? null,
1130
+ subscriptions: webPushChannel?.subscriptions().length ?? 0,
1131
+ });
1132
+ /**
1133
+ * The Telegram part of the assistant status (only while active): `enabled`
1134
+ * (`assistantTelegram.enabled`), and the channel's state: `disabled` (not
1135
+ * enabled, or no usable token: `error`), `starting`, `unpaired` (+ the
1136
+ * one-time `code`), `paired` (+ `user`) or `error` (the token was rejected).
1137
+ */
1138
+ const telegramStatus = () => telegramChannel
1139
+ ? { enabled: true, ...telegramChannel.status() }
1140
+ : telegramEnabled
1141
+ ? { enabled: true, state: 'disabled', error: telegramDisabledError ?? 'Telegram could not start' }
1142
+ : { enabled: false, state: 'disabled' };
1143
+ /** Re-send the live assistant status (pointer + timezone) to every dashboard. */
1144
+ const broadcastAssistantStatus = () => {
1145
+ if (!assistantController)
1146
+ return;
1147
+ const update = { type: 'assistant_status', ...assistantController.status(), timezone: currentTimezone() };
1148
+ for (const c of clients.values()) {
1149
+ if (!c.isCliBridge)
1150
+ sendWS(c.ws, update);
1151
+ }
1152
+ };
1153
+ /**
1154
+ * A web client's timezone report (`client_timezone`, sent on connect): made the
1155
+ * user's current timezone when it differs, only while the assistant is active.
1156
+ * Otherwise ignored, so nothing is written. An unknown zone is logged and ignored.
1157
+ */
1158
+ const onClientTimezone = (timezone) => {
1159
+ if (!assistantBackend || typeof timezone !== 'string' || !timezone.trim())
1160
+ return;
1161
+ const r = setTimezone(assistantBackend, { timezone }, WEB_TIMEZONE_SOURCE);
1162
+ if (!r.ok)
1163
+ console.warn(`[wherever] assistant: ignoring the web's timezone report: ${r.error}`);
1164
+ };
1165
+ // The CLI bridge's request/response path (ADR 0016, cli-requests.ts). Built
1166
+ // whether or not the assistant is active: `assistant_info` is how a terminal pi
1167
+ // learns it is NOT, and that answer is what keeps its tool twins inactive.
1168
+ const currentAssistantInfo = () => ({
1169
+ assistantFolder: assistantController ? assistant.status.folder : null,
1170
+ timezone: assistantController ? currentTimezone() : null,
1171
+ });
1172
+ const cliRequests = createCliRequestRouter({ assistantInfo: currentAssistantInfo, assistantHooks: () => assistantHooks });
1173
+ // Push the current assistant info to every connected CLI bridge, which updates
1174
+ // its cached `assistant_info`. The folder takes effect on restart only, so the
1175
+ // one runtime change is the user's timezone: the scheduler's
1176
+ // `onTimezoneChange` calls this.
1177
+ const pushAssistantInfoChanged = () => {
1178
+ const frame = assistantInfoChangedFrame(currentAssistantInfo());
1179
+ for (const c of clients.values()) {
1180
+ if (c.isCliBridge)
1181
+ sendWS(c.ws, frame);
1182
+ }
1183
+ };
923
1184
  // expandTilde so `~/certs/...` works from a systemd `Environment=` line or an
924
1185
  // EnvironmentFile, neither of which is shell-expanded. Without it the read
925
1186
  // below fails and (before the explicit-TLS check further down) the server
@@ -1263,7 +1524,7 @@ async function main() {
1263
1524
  sessionPool.onEvent = broadcastAgentEvent;
1264
1525
  const requestHandler = async (req, res) => {
1265
1526
  res.setHeader('Access-Control-Allow-Origin', '*');
1266
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
1527
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
1267
1528
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
1268
1529
  if (req.method === 'OPTIONS') {
1269
1530
  res.writeHead(200);
@@ -1285,7 +1546,12 @@ async function main() {
1285
1546
  pathname.startsWith('/check-remote-repo') ||
1286
1547
  pathname.startsWith('/remote-candidates') ||
1287
1548
  pathname.startsWith('/autocomplete-path') ||
1288
- pathname.startsWith('/session/');
1549
+ pathname.startsWith('/session/') ||
1550
+ // Only while Web Push runs (assistant active): otherwise
1551
+ // /push/* is an unknown route, exactly as before.
1552
+ (!!webPushChannel && pathname.startsWith('/push/')) ||
1553
+ // Likewise only while the Telegram channel runs.
1554
+ (!!telegramChannel && pathname.startsWith('/telegram/'));
1289
1555
  if (isApiRequest && !authenticate(req, token)) {
1290
1556
  sendJSON(res, 401, { error: 'Unauthorized' });
1291
1557
  return;
@@ -1427,6 +1693,94 @@ async function main() {
1427
1693
  }
1428
1694
  return;
1429
1695
  }
1696
+ // --- Web Push subscriptions (web-push.ts, ADR 0017) ----------------------
1697
+ // Token-gated via isApiRequest, and only while Web Push runs (assistant
1698
+ // active): otherwise these fall through to the static handler like any
1699
+ // unknown route. `GET .../vapid-public-key` generates the keypair on first use.
1700
+ if (webPushChannel && pathname.startsWith('/push/')) {
1701
+ try {
1702
+ if (pathname === '/push/vapid-public-key' && req.method === 'GET') {
1703
+ sendJSON(res, 200, { publicKey: webPushChannel.publicKey() });
1704
+ return;
1705
+ }
1706
+ if (pathname === '/push/subscription' && req.method === 'GET') {
1707
+ const endpoint = url.searchParams.get('endpoint') || '';
1708
+ sendJSON(res, 200, { subscribed: !!endpoint && webPushChannel.isSubscribed(endpoint) });
1709
+ return;
1710
+ }
1711
+ if (pathname === '/push/subscription' && (req.method === 'POST' || req.method === 'DELETE')) {
1712
+ let parsed;
1713
+ try {
1714
+ parsed = JSON.parse((await readBody(req)) || '{}');
1715
+ }
1716
+ catch {
1717
+ sendJSON(res, 400, { error: 'Invalid request' });
1718
+ return;
1719
+ }
1720
+ if (req.method === 'POST') {
1721
+ const v = validateSubscription(parsed?.subscription ?? parsed);
1722
+ if (!v.ok) {
1723
+ sendJSON(res, 400, { error: v.error });
1724
+ return;
1725
+ }
1726
+ const subscriptions = await webPushChannel.subscribe(v.subscription);
1727
+ sendJSON(res, 200, { subscribed: true, subscriptions });
1728
+ return;
1729
+ }
1730
+ const endpoint = typeof parsed?.endpoint === 'string' ? parsed.endpoint : '';
1731
+ if (!endpoint) {
1732
+ sendJSON(res, 400, { error: 'Missing "endpoint"' });
1733
+ return;
1734
+ }
1735
+ const removed = await webPushChannel.unsubscribe(endpoint);
1736
+ sendJSON(res, 200, { subscribed: false, removed });
1737
+ return;
1738
+ }
1739
+ // The settings' "Send test notification": the same delivery as
1740
+ // `assistant_notify` (every channel), opening the session the calling
1741
+ // device has open (`sessionId`), or the main screen without one.
1742
+ if (pathname === '/push/test' && req.method === 'POST') {
1743
+ let parsed = {};
1744
+ try {
1745
+ parsed = JSON.parse((await readBody(req)) || '{}');
1746
+ }
1747
+ catch {
1748
+ parsed = {};
1749
+ }
1750
+ if (!notifyBackend || !assistant.status.folder) {
1751
+ sendJSON(res, 503, { error: 'the assistant channels are still starting; try again in a moment' });
1752
+ return;
1753
+ }
1754
+ const outcome = await testNotification(notifyBackend, {
1755
+ sessionId: parsed && typeof parsed === 'object' ? parsed.sessionId : undefined,
1756
+ assistantFolder: assistant.status.folder,
1757
+ });
1758
+ if (!outcome.ok) {
1759
+ sendJSON(res, 502, { error: outcome.error, deliveries: outcome.deliveries });
1760
+ return;
1761
+ }
1762
+ sendJSON(res, 200, { ok: true, deliveries: outcome.deliveries });
1763
+ return;
1764
+ }
1765
+ }
1766
+ catch (err) {
1767
+ sendJSON(res, 500, { error: err.message || 'Web Push failed' });
1768
+ return;
1769
+ }
1770
+ }
1771
+ // --- Telegram re-pair (telegram-channel.ts) -------------------------------
1772
+ // Token-gated via isApiRequest, and only while the Telegram channel runs:
1773
+ // otherwise an unknown route. Forgets the stored pairing and issues a new
1774
+ // one-time code; refused (409) while the user id comes from the config.
1775
+ if (telegramChannel && pathname === '/telegram/repair' && req.method === 'POST') {
1776
+ const r = telegramChannel.repair();
1777
+ if (!r.ok) {
1778
+ sendJSON(res, 409, { error: r.error, telegram: telegramStatus() });
1779
+ return;
1780
+ }
1781
+ sendJSON(res, 200, { ok: true, telegram: telegramStatus() });
1782
+ return;
1783
+ }
1430
1784
  if (pathname === '/config' && req.method === 'GET') {
1431
1785
  const config = getWhereverConfig();
1432
1786
  let searchFolder = config.searchFolder;
@@ -1457,6 +1811,19 @@ async function main() {
1457
1811
  searchFolder: searchFolder || null,
1458
1812
  searchCreateRemote: !!config.searchCreateRemote,
1459
1813
  searchDefaultModel,
1814
+ // Start-time snapshot (see startAssistantFolder): configured / folder /
1815
+ // active / lock. Later assistant tasks add fields to this object.
1816
+ // Plus, while active, the controller's pointer (currentSessionId /
1817
+ // currentSessionFile), which is live, not a start-time snapshot.
1818
+ // While active, also the user's current timezone (live).
1819
+ // While active, also the Web Push state (enabled, the VAPID public key
1820
+ // once generated, how many devices are subscribed; whether THIS device
1821
+ // is, the web asks `GET /push/subscription`).
1822
+ // While active, also the Telegram state (telegramStatus above; the
1823
+ // one-time pairing code is in it while unpaired, behind the token gate).
1824
+ assistant: assistantController
1825
+ ? { ...assistant.status, ...assistantController.status(), timezone: currentTimezone(), webPush: webPushStatus(), telegram: telegramStatus() }
1826
+ : assistant.status,
1460
1827
  appearance: {
1461
1828
  label,
1462
1829
  accent,
@@ -2318,7 +2685,7 @@ async function main() {
2318
2685
  return;
2319
2686
  }
2320
2687
  try {
2321
- await handleWSMessage(msg, client, sessionPool, clients, broadcastToSession, broadcastSessionsUpdated);
2688
+ await handleWSMessage(msg, client, sessionPool, clients, broadcastToSession, broadcastSessionsUpdated, assistantController, cliRequests, onClientTimezone);
2322
2689
  }
2323
2690
  catch (err) {
2324
2691
  console.error('WS message processing error:', err);
@@ -2482,7 +2849,10 @@ This encrypts all network traffic securely and enables safe, private remote acce
2482
2849
  for (const c of clients.values()) {
2483
2850
  c.ws.close();
2484
2851
  }
2852
+ assistantScheduler?.stop();
2853
+ await channelDispatcher?.stop();
2485
2854
  await sessionPool.disposeAll();
2855
+ assistant.release();
2486
2856
  server.close();
2487
2857
  process.exit(0);
2488
2858
  };
@@ -2817,12 +3187,41 @@ function sendQueueSnapshot(client, sessionFile, sessionId, pool) {
2817
3187
  return;
2818
3188
  sendWS(client.ws, { type: 'queue_update', sessionId, steering });
2819
3189
  }
2820
- async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated) {
3190
+ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated, assistantController = null, cliRequests = null, onClientTimezone = () => { }) {
2821
3191
  switch (msg.type) {
3192
+ case 'client_timezone':
3193
+ // The web's timezone report on connect (see onClientTimezone in main).
3194
+ onClientTimezone(msg.timezone);
3195
+ break;
3196
+ case 'assistant_open':
3197
+ case 'assistant_reset': {
3198
+ // The Assistant entry point and its Reset action. The asker gets the
3199
+ // session to open and loads it through the normal session_load, so every
3200
+ // load-time decision (read-only, folder conflict, cold build) applies.
3201
+ if (!assistantController) {
3202
+ sendWS(client.ws, { type: 'session_error', error: 'The assistant is not active on this server (set assistantFolder in the config).' });
3203
+ return;
3204
+ }
3205
+ try {
3206
+ const cur = msg.type === 'assistant_reset' ? await assistantController.reset() : await assistantController.ensureCurrent();
3207
+ sendWS(client.ws, { type: 'assistant_current', sessionFile: cur.sessionFile, sessionId: cur.sessionId, cwd: cur.cwd });
3208
+ onSessionsUpdated();
3209
+ }
3210
+ catch (err) {
3211
+ sendWS(client.ws, { type: 'session_error', error: `Assistant: ${err.message}` });
3212
+ }
3213
+ return;
3214
+ }
2822
3215
  case 'cli_register': {
2823
3216
  client.isCliBridge = true;
2824
3217
  client.sessionId = msg.sessionFile;
2825
- const result = await pool.registerCliSession(msg.sessionFile, msg.cwd, msg.model || '', client.ws, msg.isStreaming === true);
3218
+ // `isNew` fires the pool's session-created callback (a fresh terminal pi in
3219
+ // assistantFolder moves the assistant pointer); `capabilities` is stored on
3220
+ // the entry. Older extensions send neither (ADR 0016).
3221
+ const result = await pool.registerCliSession(msg.sessionFile, msg.cwd, msg.model || '', client.ws, msg.isStreaming === true, {
3222
+ isNew: msg.isNew === true,
3223
+ capabilities: Array.isArray(msg.capabilities) ? msg.capabilities : [],
3224
+ });
2826
3225
  if (result.error) {
2827
3226
  sendWS(client.ws, { type: 'session_error', error: result.error });
2828
3227
  }
@@ -2899,6 +3298,27 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2899
3298
  pool.handleCliEvent(client.sessionId, msg.event);
2900
3299
  break;
2901
3300
  }
3301
+ case 'cli_request': {
3302
+ // ADR 0016. The caller is the session THIS connection registered, never a
3303
+ // field of the request, so whatever an op stamps as origin is server-side.
3304
+ // Answered to the asker only. A request with no id cannot be answered.
3305
+ if (!cliRequests)
3306
+ return;
3307
+ // The tool-twin ops also need the session's id and cwd (the origin they
3308
+ // stamp), read from the pool's entry for it.
3309
+ const tracked = client.isCliBridge && client.sessionId ? pool.getSession(client.sessionId) : null;
3310
+ const caller = client.isCliBridge && client.sessionId
3311
+ ? {
3312
+ sessionFile: tracked?.sessionFile ?? client.sessionId,
3313
+ sessionId: tracked?.sessionId ?? null,
3314
+ ...(tracked ? { cwd: tracked.cwd } : {}),
3315
+ }
3316
+ : null;
3317
+ const response = await cliRequests.handle(msg, caller);
3318
+ if (response)
3319
+ sendWS(client.ws, response);
3320
+ break;
3321
+ }
2902
3322
  case 'connect':
2903
3323
  break;
2904
3324
  case 'ping':