wherever-dev 0.21.1 → 0.22.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.
- package/CHANGELOG.md +20 -0
- package/dist/assistant-channels.d.ts +242 -0
- package/dist/assistant-channels.d.ts.map +1 -0
- package/dist/assistant-channels.js +270 -0
- package/dist/assistant-channels.js.map +1 -0
- package/dist/assistant-controller.d.ts +228 -0
- package/dist/assistant-controller.d.ts.map +1 -0
- package/dist/assistant-controller.js +314 -0
- package/dist/assistant-controller.js.map +1 -0
- package/dist/assistant-cron.d.ts +87 -0
- package/dist/assistant-cron.d.ts.map +1 -0
- package/dist/assistant-cron.js +352 -0
- package/dist/assistant-cron.js.map +1 -0
- package/dist/assistant-folder.d.ts +161 -0
- package/dist/assistant-folder.d.ts.map +1 -0
- package/dist/assistant-folder.js +333 -0
- package/dist/assistant-folder.js.map +1 -0
- package/dist/assistant-schedule.d.ts +236 -0
- package/dist/assistant-schedule.d.ts.map +1 -0
- package/dist/assistant-schedule.js +454 -0
- package/dist/assistant-schedule.js.map +1 -0
- package/dist/assistant-scheduler.d.ts +210 -0
- package/dist/assistant-scheduler.d.ts.map +1 -0
- package/dist/assistant-scheduler.js +472 -0
- package/dist/assistant-scheduler.js.map +1 -0
- package/dist/assistant-tool-text.d.ts +40 -0
- package/dist/assistant-tool-text.d.ts.map +1 -0
- package/dist/assistant-tool-text.js +102 -0
- package/dist/assistant-tool-text.js.map +1 -0
- package/dist/assistant-tools.d.ts +207 -0
- package/dist/assistant-tools.d.ts.map +1 -0
- package/dist/assistant-tools.js +390 -0
- package/dist/assistant-tools.js.map +1 -0
- package/dist/cli-requests.d.ts +90 -0
- package/dist/cli-requests.d.ts.map +1 -0
- package/dist/cli-requests.js +75 -0
- package/dist/cli-requests.js.map +1 -0
- package/dist/index.js +396 -7
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +43 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/reply-routing.d.ts +106 -0
- package/dist/reply-routing.d.ts.map +1 -0
- package/dist/reply-routing.js +174 -0
- package/dist/reply-routing.js.map +1 -0
- package/dist/session-pool.d.ts +232 -4
- package/dist/session-pool.d.ts.map +1 -1
- package/dist/session-pool.js +446 -100
- package/dist/session-pool.js.map +1 -1
- package/dist/telegram-channel.d.ts +272 -0
- package/dist/telegram-channel.d.ts.map +1 -0
- package/dist/telegram-channel.js +701 -0
- package/dist/telegram-channel.js.map +1 -0
- package/dist/telegram-files.d.ts +101 -0
- package/dist/telegram-files.d.ts.map +1 -0
- package/dist/telegram-files.js +145 -0
- package/dist/telegram-files.js.map +1 -0
- package/dist/telegram-pairing.d.ts +119 -0
- package/dist/telegram-pairing.d.ts.map +1 -0
- package/dist/telegram-pairing.js +97 -0
- package/dist/telegram-pairing.js.map +1 -0
- package/dist/telegram-replies.d.ts +94 -0
- package/dist/telegram-replies.d.ts.map +1 -0
- package/dist/telegram-replies.js +329 -0
- package/dist/telegram-replies.js.map +1 -0
- package/dist/telegram-token.d.ts +55 -0
- package/dist/telegram-token.d.ts.map +1 -0
- package/dist/telegram-token.js +86 -0
- package/dist/telegram-token.js.map +1 -0
- package/dist/web-push.d.ts +167 -0
- package/dist/web-push.d.ts.map +1 -0
- package/dist/web-push.js +387 -0
- package/dist/web-push.js.map +1 -0
- package/package.json +1 -1
- package/public/_app/immutable/assets/0.BkzT3rFr.css +1 -0
- package/public/_app/immutable/chunks/CExVgK9Z.js +2 -0
- package/public/_app/immutable/chunks/CExVgK9Z.js.map +1 -0
- package/public/_app/immutable/chunks/CkOw6fRa.js +2 -0
- package/public/_app/immutable/chunks/{BQ9B_G4h.js.map → CkOw6fRa.js.map} +1 -1
- package/public/_app/immutable/chunks/DyHllYtq.js +2 -0
- package/public/_app/immutable/chunks/{BUONgvl4.js.map → DyHllYtq.js.map} +1 -1
- package/public/_app/immutable/entry/{app.BZO7Xckk.js → app.D3PEFbtP.js} +3 -3
- package/public/_app/immutable/entry/{app.BZO7Xckk.js.map → app.D3PEFbtP.js.map} +1 -1
- package/public/_app/immutable/entry/start.BR00Qps5.js +2 -0
- package/public/_app/immutable/entry/start.BR00Qps5.js.map +1 -0
- package/public/_app/immutable/nodes/{0.Czz2XmZU.js → 0.DG3L8hMN.js} +3 -3
- package/public/_app/immutable/nodes/{0.Czz2XmZU.js.map → 0.DG3L8hMN.js.map} +1 -1
- package/public/_app/immutable/nodes/{1.DDvrriUW.js → 1.BCpuoZxW.js} +2 -2
- package/public/_app/immutable/nodes/{1.DDvrriUW.js.map → 1.BCpuoZxW.js.map} +1 -1
- package/public/_app/immutable/nodes/2.D2auiZW1.js +122 -0
- package/public/_app/immutable/nodes/2.D2auiZW1.js.map +1 -0
- package/public/_app/version.json +1 -1
- package/public/index.html +11 -11
- package/public/service-worker.js +1 -1
- package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
- package/public/_app/immutable/chunks/BQ9B_G4h.js +0 -2
- package/public/_app/immutable/chunks/BUONgvl4.js +0 -2
- package/public/_app/immutable/chunks/DauELski.js +0 -2
- package/public/_app/immutable/chunks/DauELski.js.map +0 -1
- package/public/_app/immutable/entry/start.DWD60uNu.js +0 -2
- package/public/_app/immutable/entry/start.DWD60uNu.js.map +0 -1
- package/public/_app/immutable/nodes/2.C7E8EMKX.js +0 -120
- package/public/_app/immutable/nodes/2.C7E8EMKX.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -5,6 +5,17 @@ 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, 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 { normalizeUserId } from './telegram-pairing.js';
|
|
16
|
+
import { resolveTelegramToken, takeTelegramTokenEnv } from './telegram-token.js';
|
|
17
|
+
import { DEFAULT_GRACE_MS } from './assistant-schedule.js';
|
|
18
|
+
import { createCliRequestRouter, assistantInfoChangedFrame } from './cli-requests.js';
|
|
8
19
|
import { readStarredSet, setSessionStarred, validateStarInput, forgetStar } from './session-stars.js';
|
|
9
20
|
import { piSdkInfo } from './pi-sdk.js';
|
|
10
21
|
import { searchConversations } from './conversation-search.js';
|
|
@@ -790,7 +801,12 @@ function parseArgs() {
|
|
|
790
801
|
// `token` above; nothing reads these variables again.
|
|
791
802
|
delete process.env.WHEREVER_TOKEN;
|
|
792
803
|
delete process.env.PI_REMOTE_TOKEN;
|
|
793
|
-
|
|
804
|
+
// The assistant's Telegram bot token variables, for the same reason (ADR 0007,
|
|
805
|
+
// ADR 0018): captured and scrubbed here ALWAYS, before anything is spawned.
|
|
806
|
+
// The token FILE is only read later, and only while the assistant is active
|
|
807
|
+
// and Telegram is enabled (telegram-token.ts).
|
|
808
|
+
const telegramTokenEnv = takeTelegramTokenEnv();
|
|
809
|
+
return { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug, telegramTokenEnv };
|
|
794
810
|
}
|
|
795
811
|
/** Loopback-only binds are the safe default; everything else is reachable by others. */
|
|
796
812
|
function isLoopbackHost(host) {
|
|
@@ -899,13 +915,69 @@ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
|
|
|
899
915
|
kill();
|
|
900
916
|
}
|
|
901
917
|
}
|
|
918
|
+
/**
|
|
919
|
+
* The scheduler's grace window from `assistantScheduleGraceMinutes`: a finite
|
|
920
|
+
* number >= 0, else the default (1 h) with a warning.
|
|
921
|
+
*/
|
|
922
|
+
function scheduleGraceMs(minutes) {
|
|
923
|
+
if (minutes === undefined)
|
|
924
|
+
return DEFAULT_GRACE_MS;
|
|
925
|
+
if (typeof minutes === 'number' && Number.isFinite(minutes) && minutes >= 0)
|
|
926
|
+
return minutes * 60_000;
|
|
927
|
+
console.warn(`[wherever] ignoring assistantScheduleGraceMinutes=${JSON.stringify(minutes)} (not a number >= 0); using 60`);
|
|
928
|
+
return DEFAULT_GRACE_MS;
|
|
929
|
+
}
|
|
902
930
|
async function main() {
|
|
903
|
-
const { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
|
|
931
|
+
const { port, host, socket, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug, telegramTokenEnv } = parseArgs();
|
|
904
932
|
debugEnabled = debug;
|
|
905
933
|
console.log(`[wherever] pi SDK ${piSdkInfo.version}: ` +
|
|
906
934
|
(piSdkInfo.tier === 'bundled' ? `bundled (${piSdkInfo.why})` : `${piSdkInfo.tier}, from ${piSdkInfo.root} (${piSdkInfo.why})`));
|
|
907
935
|
const sessionPool = new SessionPool(idleTimeout, { getStarred: readStarredSet });
|
|
908
936
|
await sessionPool.initialize();
|
|
937
|
+
// The assistant folder (opt-in via `assistantFolder`, see assistant-folder.ts):
|
|
938
|
+
// resolved, created, locked and seeded ONCE here, so a config change takes
|
|
939
|
+
// effect on restart only. The status is a start-time snapshot served by
|
|
940
|
+
// /config. The lock is released on shutdown and, as a backstop, on any exit.
|
|
941
|
+
const assistant = startAssistantFolder(getWhereverConfig());
|
|
942
|
+
sessionPool.setAssistantFolder(assistant.status.active ? (assistant.status.folder ?? undefined) : undefined);
|
|
943
|
+
// The assistant tools (assistant-tools.ts) in every server session, and the
|
|
944
|
+
// timezone line in the assistant folder: registered while `assistantFolder`
|
|
945
|
+
// is CONFIGURED. The backend is the scheduler, set below once it has started;
|
|
946
|
+
// until then, and for a server refused by the folder lock, every tool answers
|
|
947
|
+
// the lock-state error. Unset = no hooks, so sessions are exactly as before.
|
|
948
|
+
let assistantBackend = null;
|
|
949
|
+
// `assistant_notify`'s backend (the channel dispatcher + the scheduler's job
|
|
950
|
+
// mapping), set below once the channels have started. The tool itself is
|
|
951
|
+
// registered ONLY while the assistant is active (a refused server's sessions
|
|
952
|
+
// do not see it), see AssistantSessionHooks.notify.
|
|
953
|
+
let notifyBackend = null;
|
|
954
|
+
// The same hooks also answer the CLI bridge's tool-twin ops (cli-requests.ts).
|
|
955
|
+
let assistantHooks;
|
|
956
|
+
if (assistant.status.configured && assistant.status.folder) {
|
|
957
|
+
assistantHooks = {
|
|
958
|
+
folder: assistant.status.folder,
|
|
959
|
+
access: () => assistantBackend
|
|
960
|
+
? { ok: true, backend: assistantBackend }
|
|
961
|
+
: { ok: false, error: assistantNotActiveError(assistant.status.lock) },
|
|
962
|
+
...(assistant.status.active
|
|
963
|
+
? {
|
|
964
|
+
notify: () => notifyBackend
|
|
965
|
+
? { ok: true, backend: notifyBackend }
|
|
966
|
+
: { ok: false, error: 'the assistant channels are still starting; try again in a moment' },
|
|
967
|
+
}
|
|
968
|
+
: {}),
|
|
969
|
+
};
|
|
970
|
+
sessionPool.setAssistantSessionHooks(assistantHooks);
|
|
971
|
+
}
|
|
972
|
+
const currentTimezone = () => {
|
|
973
|
+
try {
|
|
974
|
+
return assistantBackend ? assistantBackend.getUserTimezone() : null;
|
|
975
|
+
}
|
|
976
|
+
catch {
|
|
977
|
+
return null;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
process.on('exit', () => assistant.release());
|
|
909
981
|
// Abandoned partial uploads (untouched for 24 h) are collected at startup and
|
|
910
982
|
// then hourly. A no-op when the staging dir was never created. The startup
|
|
911
983
|
// pass is awaited (one readdir) so it is done before the first upload arrives.
|
|
@@ -920,6 +992,190 @@ async function main() {
|
|
|
920
992
|
const uploadGcTimer = setInterval(runUploadGc, 60 * 60 * 1000);
|
|
921
993
|
uploadGcTimer.unref?.();
|
|
922
994
|
const clients = new Map();
|
|
995
|
+
/** The assistant's channel dispatcher, set once the channels start (below; only while active). */
|
|
996
|
+
let channelDispatcher = null;
|
|
997
|
+
// The assistant controller (assistant-controller.ts): which session is the
|
|
998
|
+
// current assistant session, and its reset. Built, and the pool's
|
|
999
|
+
// session-created callback registered, ONLY while the assistant is active, so
|
|
1000
|
+
// with `assistantFolder` unset (or refused) session creation, `session_new`
|
|
1001
|
+
// and idle teardown are exactly as before.
|
|
1002
|
+
const assistantController = assistant.status.active && assistant.status.folder
|
|
1003
|
+
? new AssistantController({
|
|
1004
|
+
pool: sessionPool,
|
|
1005
|
+
folder: assistant.status.folder,
|
|
1006
|
+
stateDir: getWhereverStateDir(),
|
|
1007
|
+
onChange: (pointer) => {
|
|
1008
|
+
const update = { type: 'assistant_status', ...pointer, timezone: currentTimezone() };
|
|
1009
|
+
for (const c of clients.values()) {
|
|
1010
|
+
if (!c.isCliBridge)
|
|
1011
|
+
sendWS(c.ws, update);
|
|
1012
|
+
}
|
|
1013
|
+
},
|
|
1014
|
+
// Messages a reset or an aborted settle dropped: reported to the
|
|
1015
|
+
// channels they came from (the dispatcher exists by then; before it
|
|
1016
|
+
// does, nothing has been sent from a channel, so nothing is lost).
|
|
1017
|
+
onDropped: (dropped) => channelDispatcher?.reportDropped(dropped),
|
|
1018
|
+
})
|
|
1019
|
+
: null;
|
|
1020
|
+
if (assistantController) {
|
|
1021
|
+
sessionPool.onSessionCreated = (sessionFile, cwd) => assistantController.handleSessionCreated(sessionFile, cwd);
|
|
1022
|
+
}
|
|
1023
|
+
// The assistant scheduler (assistant-scheduler.ts, ADR 0015): fires the jobs in
|
|
1024
|
+
// `<assistantFolder>/schedule.json`. Built and started ONLY while the
|
|
1025
|
+
// assistant is active (configured AND this server holds the folder lock), so
|
|
1026
|
+
// with `assistantFolder` unset or refused there is no timer and nothing is
|
|
1027
|
+
// written to the state dir.
|
|
1028
|
+
const assistantScheduler = assistantController && assistant.status.folder
|
|
1029
|
+
? new AssistantScheduler({
|
|
1030
|
+
folder: assistant.status.folder,
|
|
1031
|
+
stateDir: getWhereverStateDir(),
|
|
1032
|
+
pool: sessionPool,
|
|
1033
|
+
controller: assistantController,
|
|
1034
|
+
graceMs: scheduleGraceMs(getWhereverConfig().assistantScheduleGraceMinutes),
|
|
1035
|
+
// Every change of the user's timezone (the web's report, or
|
|
1036
|
+
// `assistant_set_timezone`) goes through the scheduler's setter, which
|
|
1037
|
+
// calls this: CLI bridges get `assistant_info_changed`, dashboards an
|
|
1038
|
+
// `assistant_status` carrying the new zone.
|
|
1039
|
+
onTimezoneChange: () => {
|
|
1040
|
+
pushAssistantInfoChanged();
|
|
1041
|
+
broadcastAssistantStatus();
|
|
1042
|
+
},
|
|
1043
|
+
})
|
|
1044
|
+
: null;
|
|
1045
|
+
await assistantScheduler?.start();
|
|
1046
|
+
assistantBackend = assistantScheduler;
|
|
1047
|
+
// The assistant's CHANNELS (assistant-channels.ts): built and started ONLY
|
|
1048
|
+
// while the assistant is active, like the scheduler. Web Push (web-push.ts,
|
|
1049
|
+
// ADR 0017) is on unless `assistantWebPush.enabled` is false; it writes
|
|
1050
|
+
// nothing until a device subscribes (the VAPID keys are made on first use).
|
|
1051
|
+
const webPushChannel = assistantController && getWhereverConfig().assistantWebPush?.enabled !== false
|
|
1052
|
+
? new WebPushChannel({
|
|
1053
|
+
stateDir: getWhereverStateDir(),
|
|
1054
|
+
subject: resolveVapidSubject({
|
|
1055
|
+
subject: getWhereverConfig().assistantWebPush?.subject,
|
|
1056
|
+
publicUrl: getWhereverConfig().publicUrl,
|
|
1057
|
+
}),
|
|
1058
|
+
})
|
|
1059
|
+
: null;
|
|
1060
|
+
// Telegram (telegram-channel.ts): only while the assistant is active (two
|
|
1061
|
+
// servers must never poll one bot; the folder lock decides) AND
|
|
1062
|
+
// `assistantTelegram.enabled` is true. Otherwise the token file is not even
|
|
1063
|
+
// read and nothing is logged. A token that cannot be resolved DISABLES
|
|
1064
|
+
// Telegram with a loud error and the server carries on (ADR 0018).
|
|
1065
|
+
const telegramConfig = getWhereverConfig().assistantTelegram;
|
|
1066
|
+
const telegramEnabled = !!assistantController && telegramConfig?.enabled === true;
|
|
1067
|
+
let telegramChannel = null;
|
|
1068
|
+
let telegramDisabledError = null;
|
|
1069
|
+
if (telegramEnabled) {
|
|
1070
|
+
const resolved = resolveTelegramToken({
|
|
1071
|
+
env: telegramTokenEnv,
|
|
1072
|
+
configToken: telegramConfig?.token,
|
|
1073
|
+
readFile: (p) => fs.readFileSync(p, 'utf8'),
|
|
1074
|
+
});
|
|
1075
|
+
for (const w of resolved.warnings)
|
|
1076
|
+
console.warn(`[wherever] telegram: ${w}`);
|
|
1077
|
+
const configuredUserId = normalizeUserId(telegramConfig?.userId);
|
|
1078
|
+
if (telegramConfig?.userId !== undefined && !configuredUserId) {
|
|
1079
|
+
console.warn(`[wherever] telegram: ignoring assistantTelegram.userId=${JSON.stringify(telegramConfig.userId)} (not a numeric Telegram user id); pairing by code instead`);
|
|
1080
|
+
}
|
|
1081
|
+
if (!resolved.ok) {
|
|
1082
|
+
telegramDisabledError = resolved.error;
|
|
1083
|
+
console.error(`[wherever] ERROR: Telegram is DISABLED: ${resolved.error}. The server keeps running without it.`);
|
|
1084
|
+
}
|
|
1085
|
+
else {
|
|
1086
|
+
console.log(`[wherever] telegram: bot token from ${resolved.source}`);
|
|
1087
|
+
telegramChannel = new TelegramChannel({
|
|
1088
|
+
token: resolved.token,
|
|
1089
|
+
stateDir: getWhereverStateDir(),
|
|
1090
|
+
configuredUserId,
|
|
1091
|
+
apiBaseUrl: typeof telegramConfig?.apiBaseUrl === 'string' && telegramConfig.apiBaseUrl.trim() ? telegramConfig.apiBaseUrl.trim() : undefined,
|
|
1092
|
+
// A notification links to the target session when the public URL is set.
|
|
1093
|
+
publicUrl: getWhereverConfig().publicUrl,
|
|
1094
|
+
// A file from Telegram lands where a web upload into the assistant
|
|
1095
|
+
// session does (`uploads.type`), under the same size limit.
|
|
1096
|
+
uploadDir: () => resolveUploadDir(getWhereverConfig(), assistant.status.folder ?? undefined),
|
|
1097
|
+
maxUploadBytes: () => uploadMaxBytes(getWhereverConfig()),
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
const assistantChannels = [
|
|
1102
|
+
...(webPushChannel ? [webPushChannel] : []),
|
|
1103
|
+
...(telegramChannel ? [telegramChannel] : []),
|
|
1104
|
+
];
|
|
1105
|
+
channelDispatcher = assistantController
|
|
1106
|
+
? new ChannelDispatcher({ controller: assistantController, pool: sessionPool, channels: assistantChannels })
|
|
1107
|
+
: null;
|
|
1108
|
+
await channelDispatcher?.start();
|
|
1109
|
+
if (channelDispatcher && assistantScheduler) {
|
|
1110
|
+
const scheduler = assistantScheduler;
|
|
1111
|
+
const dispatcher = channelDispatcher;
|
|
1112
|
+
notifyBackend = {
|
|
1113
|
+
notify: (n) => dispatcher.notify(n),
|
|
1114
|
+
jobOrigin: (jobId) => {
|
|
1115
|
+
const job = scheduler.store.read().valid.find((v) => v.job.id === jobId)?.job;
|
|
1116
|
+
return job ? { originSessionId: job.originSessionId, originCwd: job.originCwd } : null;
|
|
1117
|
+
},
|
|
1118
|
+
jobForSession: (sessionFile) => scheduler.jobForSession(sessionFile),
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
/** The Web Push part of the assistant status (only while active). */
|
|
1122
|
+
const webPushStatus = () => ({
|
|
1123
|
+
enabled: !!webPushChannel,
|
|
1124
|
+
publicKey: webPushChannel?.existingPublicKey() ?? null,
|
|
1125
|
+
subscriptions: webPushChannel?.subscriptions().length ?? 0,
|
|
1126
|
+
});
|
|
1127
|
+
/**
|
|
1128
|
+
* The Telegram part of the assistant status (only while active): `enabled`
|
|
1129
|
+
* (`assistantTelegram.enabled`), and the channel's state: `disabled` (not
|
|
1130
|
+
* enabled, or no usable token: `error`), `starting`, `unpaired` (+ the
|
|
1131
|
+
* one-time `code`), `paired` (+ `user`) or `error` (the token was rejected).
|
|
1132
|
+
*/
|
|
1133
|
+
const telegramStatus = () => telegramChannel
|
|
1134
|
+
? { enabled: true, ...telegramChannel.status() }
|
|
1135
|
+
: telegramEnabled
|
|
1136
|
+
? { enabled: true, state: 'disabled', error: telegramDisabledError ?? 'Telegram could not start' }
|
|
1137
|
+
: { enabled: false, state: 'disabled' };
|
|
1138
|
+
/** Re-send the live assistant status (pointer + timezone) to every dashboard. */
|
|
1139
|
+
const broadcastAssistantStatus = () => {
|
|
1140
|
+
if (!assistantController)
|
|
1141
|
+
return;
|
|
1142
|
+
const update = { type: 'assistant_status', ...assistantController.status(), timezone: currentTimezone() };
|
|
1143
|
+
for (const c of clients.values()) {
|
|
1144
|
+
if (!c.isCliBridge)
|
|
1145
|
+
sendWS(c.ws, update);
|
|
1146
|
+
}
|
|
1147
|
+
};
|
|
1148
|
+
/**
|
|
1149
|
+
* A web client's timezone report (`client_timezone`, sent on connect): made the
|
|
1150
|
+
* user's current timezone when it differs, only while the assistant is active.
|
|
1151
|
+
* Otherwise ignored, so nothing is written. An unknown zone is logged and ignored.
|
|
1152
|
+
*/
|
|
1153
|
+
const onClientTimezone = (timezone) => {
|
|
1154
|
+
if (!assistantBackend || typeof timezone !== 'string' || !timezone.trim())
|
|
1155
|
+
return;
|
|
1156
|
+
const r = setTimezone(assistantBackend, { timezone }, WEB_TIMEZONE_SOURCE);
|
|
1157
|
+
if (!r.ok)
|
|
1158
|
+
console.warn(`[wherever] assistant: ignoring the web's timezone report: ${r.error}`);
|
|
1159
|
+
};
|
|
1160
|
+
// The CLI bridge's request/response path (ADR 0016, cli-requests.ts). Built
|
|
1161
|
+
// whether or not the assistant is active: `assistant_info` is how a terminal pi
|
|
1162
|
+
// learns it is NOT, and that answer is what keeps its tool twins inactive.
|
|
1163
|
+
const currentAssistantInfo = () => ({
|
|
1164
|
+
assistantFolder: assistantController ? assistant.status.folder : null,
|
|
1165
|
+
timezone: assistantController ? currentTimezone() : null,
|
|
1166
|
+
});
|
|
1167
|
+
const cliRequests = createCliRequestRouter({ assistantInfo: currentAssistantInfo, assistantHooks: () => assistantHooks });
|
|
1168
|
+
// Push the current assistant info to every connected CLI bridge, which updates
|
|
1169
|
+
// its cached `assistant_info`. The folder takes effect on restart only, so the
|
|
1170
|
+
// one runtime change is the user's timezone: the scheduler's
|
|
1171
|
+
// `onTimezoneChange` calls this.
|
|
1172
|
+
const pushAssistantInfoChanged = () => {
|
|
1173
|
+
const frame = assistantInfoChangedFrame(currentAssistantInfo());
|
|
1174
|
+
for (const c of clients.values()) {
|
|
1175
|
+
if (c.isCliBridge)
|
|
1176
|
+
sendWS(c.ws, frame);
|
|
1177
|
+
}
|
|
1178
|
+
};
|
|
923
1179
|
// expandTilde so `~/certs/...` works from a systemd `Environment=` line or an
|
|
924
1180
|
// EnvironmentFile, neither of which is shell-expanded. Without it the read
|
|
925
1181
|
// below fails and (before the explicit-TLS check further down) the server
|
|
@@ -1263,7 +1519,7 @@ async function main() {
|
|
|
1263
1519
|
sessionPool.onEvent = broadcastAgentEvent;
|
|
1264
1520
|
const requestHandler = async (req, res) => {
|
|
1265
1521
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
1266
|
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
1522
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
|
|
1267
1523
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
1268
1524
|
if (req.method === 'OPTIONS') {
|
|
1269
1525
|
res.writeHead(200);
|
|
@@ -1285,7 +1541,12 @@ async function main() {
|
|
|
1285
1541
|
pathname.startsWith('/check-remote-repo') ||
|
|
1286
1542
|
pathname.startsWith('/remote-candidates') ||
|
|
1287
1543
|
pathname.startsWith('/autocomplete-path') ||
|
|
1288
|
-
pathname.startsWith('/session/')
|
|
1544
|
+
pathname.startsWith('/session/') ||
|
|
1545
|
+
// Only while Web Push runs (assistant active): otherwise
|
|
1546
|
+
// /push/* is an unknown route, exactly as before.
|
|
1547
|
+
(!!webPushChannel && pathname.startsWith('/push/')) ||
|
|
1548
|
+
// Likewise only while the Telegram channel runs.
|
|
1549
|
+
(!!telegramChannel && pathname.startsWith('/telegram/'));
|
|
1289
1550
|
if (isApiRequest && !authenticate(req, token)) {
|
|
1290
1551
|
sendJSON(res, 401, { error: 'Unauthorized' });
|
|
1291
1552
|
return;
|
|
@@ -1427,6 +1688,68 @@ async function main() {
|
|
|
1427
1688
|
}
|
|
1428
1689
|
return;
|
|
1429
1690
|
}
|
|
1691
|
+
// --- Web Push subscriptions (web-push.ts, ADR 0017) ----------------------
|
|
1692
|
+
// Token-gated via isApiRequest, and only while Web Push runs (assistant
|
|
1693
|
+
// active): otherwise these fall through to the static handler like any
|
|
1694
|
+
// unknown route. `GET .../vapid-public-key` generates the keypair on first use.
|
|
1695
|
+
if (webPushChannel && pathname.startsWith('/push/')) {
|
|
1696
|
+
try {
|
|
1697
|
+
if (pathname === '/push/vapid-public-key' && req.method === 'GET') {
|
|
1698
|
+
sendJSON(res, 200, { publicKey: webPushChannel.publicKey() });
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
if (pathname === '/push/subscription' && req.method === 'GET') {
|
|
1702
|
+
const endpoint = url.searchParams.get('endpoint') || '';
|
|
1703
|
+
sendJSON(res, 200, { subscribed: !!endpoint && webPushChannel.isSubscribed(endpoint) });
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
if (pathname === '/push/subscription' && (req.method === 'POST' || req.method === 'DELETE')) {
|
|
1707
|
+
let parsed;
|
|
1708
|
+
try {
|
|
1709
|
+
parsed = JSON.parse((await readBody(req)) || '{}');
|
|
1710
|
+
}
|
|
1711
|
+
catch {
|
|
1712
|
+
sendJSON(res, 400, { error: 'Invalid request' });
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
if (req.method === 'POST') {
|
|
1716
|
+
const v = validateSubscription(parsed?.subscription ?? parsed);
|
|
1717
|
+
if (!v.ok) {
|
|
1718
|
+
sendJSON(res, 400, { error: v.error });
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
const subscriptions = await webPushChannel.subscribe(v.subscription);
|
|
1722
|
+
sendJSON(res, 200, { subscribed: true, subscriptions });
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
const endpoint = typeof parsed?.endpoint === 'string' ? parsed.endpoint : '';
|
|
1726
|
+
if (!endpoint) {
|
|
1727
|
+
sendJSON(res, 400, { error: 'Missing "endpoint"' });
|
|
1728
|
+
return;
|
|
1729
|
+
}
|
|
1730
|
+
const removed = await webPushChannel.unsubscribe(endpoint);
|
|
1731
|
+
sendJSON(res, 200, { subscribed: false, removed });
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
catch (err) {
|
|
1736
|
+
sendJSON(res, 500, { error: err.message || 'Web Push failed' });
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
// --- Telegram re-pair (telegram-channel.ts) -------------------------------
|
|
1741
|
+
// Token-gated via isApiRequest, and only while the Telegram channel runs:
|
|
1742
|
+
// otherwise an unknown route. Forgets the stored pairing and issues a new
|
|
1743
|
+
// one-time code; refused (409) while the user id comes from the config.
|
|
1744
|
+
if (telegramChannel && pathname === '/telegram/repair' && req.method === 'POST') {
|
|
1745
|
+
const r = telegramChannel.repair();
|
|
1746
|
+
if (!r.ok) {
|
|
1747
|
+
sendJSON(res, 409, { error: r.error, telegram: telegramStatus() });
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
sendJSON(res, 200, { ok: true, telegram: telegramStatus() });
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1430
1753
|
if (pathname === '/config' && req.method === 'GET') {
|
|
1431
1754
|
const config = getWhereverConfig();
|
|
1432
1755
|
let searchFolder = config.searchFolder;
|
|
@@ -1457,6 +1780,19 @@ async function main() {
|
|
|
1457
1780
|
searchFolder: searchFolder || null,
|
|
1458
1781
|
searchCreateRemote: !!config.searchCreateRemote,
|
|
1459
1782
|
searchDefaultModel,
|
|
1783
|
+
// Start-time snapshot (see startAssistantFolder): configured / folder /
|
|
1784
|
+
// active / lock. Later assistant tasks add fields to this object.
|
|
1785
|
+
// Plus, while active, the controller's pointer (currentSessionId /
|
|
1786
|
+
// currentSessionFile), which is live, not a start-time snapshot.
|
|
1787
|
+
// While active, also the user's current timezone (live).
|
|
1788
|
+
// While active, also the Web Push state (enabled, the VAPID public key
|
|
1789
|
+
// once generated, how many devices are subscribed; whether THIS device
|
|
1790
|
+
// is, the web asks `GET /push/subscription`).
|
|
1791
|
+
// While active, also the Telegram state (telegramStatus above; the
|
|
1792
|
+
// one-time pairing code is in it while unpaired, behind the token gate).
|
|
1793
|
+
assistant: assistantController
|
|
1794
|
+
? { ...assistant.status, ...assistantController.status(), timezone: currentTimezone(), webPush: webPushStatus(), telegram: telegramStatus() }
|
|
1795
|
+
: assistant.status,
|
|
1460
1796
|
appearance: {
|
|
1461
1797
|
label,
|
|
1462
1798
|
accent,
|
|
@@ -2318,7 +2654,7 @@ async function main() {
|
|
|
2318
2654
|
return;
|
|
2319
2655
|
}
|
|
2320
2656
|
try {
|
|
2321
|
-
await handleWSMessage(msg, client, sessionPool, clients, broadcastToSession, broadcastSessionsUpdated);
|
|
2657
|
+
await handleWSMessage(msg, client, sessionPool, clients, broadcastToSession, broadcastSessionsUpdated, assistantController, cliRequests, onClientTimezone);
|
|
2322
2658
|
}
|
|
2323
2659
|
catch (err) {
|
|
2324
2660
|
console.error('WS message processing error:', err);
|
|
@@ -2482,7 +2818,10 @@ This encrypts all network traffic securely and enables safe, private remote acce
|
|
|
2482
2818
|
for (const c of clients.values()) {
|
|
2483
2819
|
c.ws.close();
|
|
2484
2820
|
}
|
|
2821
|
+
assistantScheduler?.stop();
|
|
2822
|
+
await channelDispatcher?.stop();
|
|
2485
2823
|
await sessionPool.disposeAll();
|
|
2824
|
+
assistant.release();
|
|
2486
2825
|
server.close();
|
|
2487
2826
|
process.exit(0);
|
|
2488
2827
|
};
|
|
@@ -2817,12 +3156,41 @@ function sendQueueSnapshot(client, sessionFile, sessionId, pool) {
|
|
|
2817
3156
|
return;
|
|
2818
3157
|
sendWS(client.ws, { type: 'queue_update', sessionId, steering });
|
|
2819
3158
|
}
|
|
2820
|
-
async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated) {
|
|
3159
|
+
async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated, assistantController = null, cliRequests = null, onClientTimezone = () => { }) {
|
|
2821
3160
|
switch (msg.type) {
|
|
3161
|
+
case 'client_timezone':
|
|
3162
|
+
// The web's timezone report on connect (see onClientTimezone in main).
|
|
3163
|
+
onClientTimezone(msg.timezone);
|
|
3164
|
+
break;
|
|
3165
|
+
case 'assistant_open':
|
|
3166
|
+
case 'assistant_reset': {
|
|
3167
|
+
// The Assistant entry point and its Reset action. The asker gets the
|
|
3168
|
+
// session to open and loads it through the normal session_load, so every
|
|
3169
|
+
// load-time decision (read-only, folder conflict, cold build) applies.
|
|
3170
|
+
if (!assistantController) {
|
|
3171
|
+
sendWS(client.ws, { type: 'session_error', error: 'The assistant is not active on this server (set assistantFolder in the config).' });
|
|
3172
|
+
return;
|
|
3173
|
+
}
|
|
3174
|
+
try {
|
|
3175
|
+
const cur = msg.type === 'assistant_reset' ? await assistantController.reset() : await assistantController.ensureCurrent();
|
|
3176
|
+
sendWS(client.ws, { type: 'assistant_current', sessionFile: cur.sessionFile, sessionId: cur.sessionId, cwd: cur.cwd });
|
|
3177
|
+
onSessionsUpdated();
|
|
3178
|
+
}
|
|
3179
|
+
catch (err) {
|
|
3180
|
+
sendWS(client.ws, { type: 'session_error', error: `Assistant: ${err.message}` });
|
|
3181
|
+
}
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
2822
3184
|
case 'cli_register': {
|
|
2823
3185
|
client.isCliBridge = true;
|
|
2824
3186
|
client.sessionId = msg.sessionFile;
|
|
2825
|
-
|
|
3187
|
+
// `isNew` fires the pool's session-created callback (a fresh terminal pi in
|
|
3188
|
+
// assistantFolder moves the assistant pointer); `capabilities` is stored on
|
|
3189
|
+
// the entry. Older extensions send neither (ADR 0016).
|
|
3190
|
+
const result = await pool.registerCliSession(msg.sessionFile, msg.cwd, msg.model || '', client.ws, msg.isStreaming === true, {
|
|
3191
|
+
isNew: msg.isNew === true,
|
|
3192
|
+
capabilities: Array.isArray(msg.capabilities) ? msg.capabilities : [],
|
|
3193
|
+
});
|
|
2826
3194
|
if (result.error) {
|
|
2827
3195
|
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
2828
3196
|
}
|
|
@@ -2899,6 +3267,27 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
2899
3267
|
pool.handleCliEvent(client.sessionId, msg.event);
|
|
2900
3268
|
break;
|
|
2901
3269
|
}
|
|
3270
|
+
case 'cli_request': {
|
|
3271
|
+
// ADR 0016. The caller is the session THIS connection registered, never a
|
|
3272
|
+
// field of the request, so whatever an op stamps as origin is server-side.
|
|
3273
|
+
// Answered to the asker only. A request with no id cannot be answered.
|
|
3274
|
+
if (!cliRequests)
|
|
3275
|
+
return;
|
|
3276
|
+
// The tool-twin ops also need the session's id and cwd (the origin they
|
|
3277
|
+
// stamp), read from the pool's entry for it.
|
|
3278
|
+
const tracked = client.isCliBridge && client.sessionId ? pool.getSession(client.sessionId) : null;
|
|
3279
|
+
const caller = client.isCliBridge && client.sessionId
|
|
3280
|
+
? {
|
|
3281
|
+
sessionFile: tracked?.sessionFile ?? client.sessionId,
|
|
3282
|
+
sessionId: tracked?.sessionId ?? null,
|
|
3283
|
+
...(tracked ? { cwd: tracked.cwd } : {}),
|
|
3284
|
+
}
|
|
3285
|
+
: null;
|
|
3286
|
+
const response = await cliRequests.handle(msg, caller);
|
|
3287
|
+
if (response)
|
|
3288
|
+
sendWS(client.ws, response);
|
|
3289
|
+
break;
|
|
3290
|
+
}
|
|
2902
3291
|
case 'connect':
|
|
2903
3292
|
break;
|
|
2904
3293
|
case 'ping':
|