my-durable 0.0.42 → 0.0.44

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.
@@ -51,6 +51,8 @@ import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/pr
51
51
  import { deviceVitals, type DeviceVitals } from "./vitals.js";
52
52
  import { ProjectRegistry, type ProjectRecord } from "./projects.js";
53
53
  import { EnvFileEditor, type EnvFileView } from "./env-vars.js";
54
+ import { KeepAwake } from "./awake.js";
55
+ import { TelegramBridge, defaultTelegramIo, type TelegramBroker } from "./telegram.js";
54
56
  import { ScheduleRegistry, type ScheduleCreateInput, type ScheduleRecord } from "./schedules.js";
55
57
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
56
58
  import { zipSync, type ZipEntry } from "./zip.js";
@@ -146,6 +148,8 @@ export interface StoreOptions {
146
148
  provider: "openrouter" | "faux";
147
149
  /** The env file the daemon booted from (config.ts's `envFile`); backs the env UI. */
148
150
  envFile?: string;
151
+ /** Bot token for the Telegram chat bridge; absent = the bridge stays idle. */
152
+ telegramToken?: string;
149
153
  }
150
154
 
151
155
  /** Agent documents a client may read or stream, by kind. */
@@ -282,6 +286,11 @@ export class Store {
282
286
  sinks!: NotifySinks;
283
287
  /** The daemon's env file, behind the guarded editor (secrets masked, managed keys refused). */
284
288
  readonly env: EnvFileEditor;
289
+ /** Keep-awake (Wave 3): holds the OS awake while any session is busy. */
290
+ readonly awake = new KeepAwake();
291
+ private awakeTimer?: ReturnType<typeof setTimeout>;
292
+ /** Telegram chat bridge (Wave 3): bound chats talk to sessions. */
293
+ telegram?: TelegramBridge;
285
294
  uid!: string;
286
295
  modelList: ModelInfo[] = [];
287
296
  private unlockCatalog: () => void;
@@ -313,6 +322,9 @@ export class Store {
313
322
  get notifyPath() {
314
323
  return join(this.options.dataDir, "notify.json");
315
324
  }
325
+ get telegramPath() {
326
+ return join(this.options.dataDir, "telegram.json");
327
+ }
316
328
  get name() {
317
329
  return this.options.name;
318
330
  }
@@ -383,6 +395,12 @@ export class Store {
383
395
  // ntfy often lives on the LAN; the operator opts in explicitly.
384
396
  allowPrivateHosts: process.env.DPI_NOTIFY_ALLOW_PRIVATE === "1",
385
397
  });
398
+ // Telegram bridge (Wave 3): chats bound to sessions. The broker below is
399
+ // the ONLY bridge-to-store surface — the module itself knows the protocol.
400
+ store.telegram = await TelegramBridge.open(store.telegramPath, defaultTelegramIo(), store.telegramBroker(), {
401
+ warn: (m) => process.emitWarning(`telegram: ${m}`),
402
+ });
403
+ if (options.telegramToken) store.telegram.start(options.telegramToken);
386
404
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
387
405
  store.shared = await SharedState.open(store.sharedStatePath);
388
406
  store.shared.harness.subscribeCommits(() => store.notify());
@@ -414,8 +432,38 @@ export class Store {
414
432
  }
415
433
  notify = () => {
416
434
  for (const fn of this.listeners) fn();
435
+ this.scheduleAwakeSync();
417
436
  };
418
437
 
438
+ /**
439
+ * Keep-awake piggybacks on notify (every state change) with a debounce, so
440
+ * there is no extra timer while the device is idle. The inhibitor itself is
441
+ * idempotent — start when the first session turns busy, stop at zero.
442
+ */
443
+ private scheduleAwakeSync() {
444
+ if (this.awakeTimer) return;
445
+ this.awakeTimer = setTimeout(() => {
446
+ this.awakeTimer = undefined;
447
+ void this.syncAwake();
448
+ }, 1000);
449
+ this.awakeTimer.unref?.();
450
+ }
451
+
452
+ /** Count busy sessions and tell the inhibitor. Never throws into a turn. */
453
+ private async syncAwake() {
454
+ try {
455
+ let busy = 0;
456
+ for (const [id, opened] of this.opened) {
457
+ if (!this.opened.has(id)) continue;
458
+ const tasks = await this.liveTasks(opened.harness);
459
+ if (tasks.some((t) => !t.background)) busy += 1;
460
+ }
461
+ this.awake.sync(busy);
462
+ } catch {
463
+ /* keep-awake must never break a turn */
464
+ }
465
+ }
466
+
419
467
  /** The git fs-watcher pokes the tree so every connected UI hears "dirty". */
420
468
  private gitWired = false;
421
469
  wireGitWatcher() {
@@ -443,7 +491,16 @@ export class Store {
443
491
  ...(this.modelsKeyless ? { providerKeyMissing: true } : {}),
444
492
  storage: { dataDir: this.options.dataDir, catalogPath: this.catalogPath, appStatePath: this.sharedStatePath },
445
493
  codeDir: CODE_DIR,
446
- capabilities: ["events", "docs", "demo", "jobs"],
494
+ capabilities: [
495
+ "events",
496
+ "docs",
497
+ "demo",
498
+ "jobs",
499
+ ...(this.awake.mode !== "none" ? (["keep-awake"] as const) : []),
500
+ ...(this.telegram?.running ? (["telegram"] as const) : []),
501
+ ],
502
+ /** How this device holds the OS awake while sessions run ("none" = it cannot). */
503
+ keepAwake: this.awake.mode,
447
504
  jobs: JOB_DEFS,
448
505
  };
449
506
  }
@@ -761,6 +818,30 @@ export class Store {
761
818
  return result;
762
819
  }
763
820
 
821
+ /** The store side of the Telegram bridge: sessions in, answers out. */
822
+ private telegramBroker(): TelegramBroker {
823
+ return {
824
+ listSessions: () => this.list().map((row) => ({ id: row.id, name: row.name })),
825
+ sendToSession: async (sessionId, text) => {
826
+ const { c } = await this.resolveAgent(sessionId, "main");
827
+ const submission = await this.send(c, {
828
+ content: text,
829
+ whenBusy: "followUp",
830
+ requestId: `telegram-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
831
+ });
832
+ return { submissionId: submission.id as number };
833
+ },
834
+ awaitAnswer: async (sessionId, submissionId, timeoutMs) => {
835
+ const row = this.resolveSession(sessionId);
836
+ const h = this.harness(row);
837
+ await this.settled(h, submissionId, timeoutMs).catch(() => undefined);
838
+ const c = await h.conversation(1 as ConversationId, ctx);
839
+ if (!c) return undefined;
840
+ return lastAssistantText(await this.activeEntries(c)) ?? undefined;
841
+ },
842
+ };
843
+ }
844
+
764
845
  /** `spawnKey` records which tool call created the session, in the same transaction as the session row. */
765
846
  async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
766
847
  if (typeof body?.name !== "string") throw invalid("name is required");
@@ -2093,6 +2174,9 @@ export class Store {
2093
2174
 
2094
2175
  async close() {
2095
2176
  this.stopScheduler();
2177
+ if (this.awakeTimer) clearTimeout(this.awakeTimer);
2178
+ this.awake.stop();
2179
+ this.telegram?.stop();
2096
2180
  for (const { harness, unlock, unsubscribe } of this.opened.values()) {
2097
2181
  unsubscribe();
2098
2182
  try {
@@ -0,0 +1,286 @@
1
+ /**
2
+ * `dpi telegram` — bind a Telegram chat to a device session (checklist Wave 3).
3
+ *
4
+ * Same shape as `dpi backup`: the CLI edits the device's own registry file
5
+ * (`<data dir>/telegram.json`) with the same injectable io the module uses, so
6
+ * the operator mints a bind code or unbinds a chat without the daemon in the
7
+ * way. The one thing the daemon is still asked for is the session list
8
+ * (`GET /v1/sessions`, the same endpoint/`DPI_TOKEN` rule `dpi schedule` uses) —
9
+ * names are nicer than ids in `status`, and `sessions` is only useful live; when
10
+ * the daemon is down both degrade to ids / an honest "no sessions" line.
11
+ *
12
+ * The bot token comes from `DPI_TELEGRAM_TOKEN` (process env or the env file,
13
+ * doctor's `deviceEndpoint` rule); without it `status` and `bind` say so and
14
+ * exit 1, because both would lie otherwise. Exit codes: 0 ok, 1 error, 2 usage
15
+ * error; nothing is ever thrown out of `telegramCli`. `argv` is what follows the
16
+ * `telegram` word (`telegramCli({ argv: ["bind"] })`).
17
+ */
18
+ import { homedir } from "node:os";
19
+ import { join, resolve } from "node:path";
20
+ import { expand, readEnvFile } from "./doctor.js";
21
+ import { defaultTelegramIo, TelegramBridge, type TelegramBroker, type TelegramIo } from "./telegram.js";
22
+
23
+ export interface TelegramCliArgs {
24
+ argv: readonly string[];
25
+ }
26
+
27
+ /** The CLI adds output, env and home to the module's io — one object, so a test fakes exactly what it needs. */
28
+ export interface TelegramCliIo extends TelegramIo {
29
+ print: (line: string) => void;
30
+ printErr: (line: string) => void;
31
+ env: Record<string, string | undefined>;
32
+ homedir: () => string;
33
+ }
34
+
35
+ export const defaultTelegramCliIo = (): TelegramCliIo => ({
36
+ ...defaultTelegramIo(),
37
+ print: (line) => process.stdout.write(`${line}\n`),
38
+ printErr: (line) => process.stderr.write(`${line}\n`),
39
+ env: process.env as Record<string, string | undefined>,
40
+ homedir,
41
+ });
42
+
43
+ export const TELEGRAM_HELP = `dpi telegram — bind a Telegram chat to a device session
44
+
45
+ dpi telegram status
46
+ dpi telegram bind [--session <id-prefix>]
47
+ dpi telegram unbind <chat-prefix>
48
+ dpi telegram sessions
49
+
50
+ status is a token configured, which chats are bound to which sessions
51
+ bind mint a single-use /start code (10 min); prints the message to send
52
+ your bot and the t.me deep link
53
+ unbind remove a chat binding by chat-id prefix
54
+ sessions the sessions a chat can switch between (/session <id-prefix>)
55
+
56
+ --home DIR device home (default: $DPI_HOME, else ~/.dpi)
57
+
58
+ The bot token is DPI_TELEGRAM_TOKEN (process env or the env file); the
59
+ registry is <home>/backend/telegram.json ($DPI_DATA_DIR overrides the dir).
60
+ Exit codes: 0 ok, 1 error, 2 usage error.`;
61
+
62
+ /** Everything the subcommands need from env + flags, resolved once. */
63
+ interface TelegramCliEnv {
64
+ home: string;
65
+ envFile: string;
66
+ dataDir: string;
67
+ registryPath: string;
68
+ /** DPI_TELEGRAM_TOKEN — the bot token; empty when unset. */
69
+ token: string;
70
+ /** DPI_TOKEN — the device API token, for the session list; empty when unset. */
71
+ apiToken: string;
72
+ baseUrl: string;
73
+ }
74
+
75
+ const flagValue = (argv: readonly string[], name: string): string | undefined => {
76
+ const i = argv.indexOf(name);
77
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
78
+ };
79
+
80
+ /**
81
+ * `--home` wins, then $DPI_HOME (process env only — the env file lives *inside*
82
+ * the home, so it cannot name it), then ~/.dpi. The env file is
83
+ * $DPI_ENV_FILE or `<home>/backend.env`; process env always beats it. This is
84
+ * doctor.ts's `deviceEndpoint` rule, async because this io's fs is async.
85
+ */
86
+ async function resolveEnv(argv: readonly string[], io: TelegramCliIo): Promise<TelegramCliEnv> {
87
+ const hd = io.homedir();
88
+ const home = resolve(expand(flagValue(argv, "--home") ?? io.env.DPI_HOME ?? join(hd, ".dpi"), hd));
89
+ const envFile = resolve(expand(io.env.DPI_ENV_FILE || join(home, "backend.env"), hd));
90
+ let fileEnv: Record<string, string> = {};
91
+ if (await io.exists(envFile)) {
92
+ try {
93
+ fileEnv = readEnvFile(await io.readFile(envFile));
94
+ } catch {
95
+ /* unreadable env file: fall back to process env, like doctor.ts */
96
+ }
97
+ }
98
+ const value = (key: string): string | undefined => io.env[key] ?? fileEnv[key];
99
+ const dataDir = resolve(expand(value("DPI_DATA_DIR") || join(home, "backend"), hd));
100
+ const host = value("DPI_HOST") || "127.0.0.1";
101
+ // A device listening on every interface is still reached over loopback here.
102
+ const probeHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
103
+ const port = Number(value("DPI_PORT") || "4780");
104
+ return {
105
+ home,
106
+ envFile,
107
+ dataDir,
108
+ registryPath: join(dataDir, "telegram.json"),
109
+ token: value("DPI_TELEGRAM_TOKEN") || "",
110
+ apiToken: value("DPI_TOKEN") || "",
111
+ baseUrl: `http://${probeHost}:${Number.isInteger(port) && port > 0 ? port : 4780}`,
112
+ };
113
+ }
114
+
115
+ /**
116
+ * The session list for names and `dpi telegram sessions`. Asked of the local
117
+ * daemon over its API; any failure (down, no token, odd shape) is an empty
118
+ * list, because a CLI that only *decorates* must not fail because of it.
119
+ */
120
+ async function fetchSessions(io: TelegramCliIo, env: TelegramCliEnv): Promise<Array<{ id: string; name: string }>> {
121
+ if (!env.apiToken) return [];
122
+ try {
123
+ const res = await io.fetch(`${env.baseUrl}/v1/sessions`, {
124
+ method: "GET",
125
+ headers: { authorization: `Bearer ${env.apiToken}` },
126
+ signal: AbortSignal.timeout(4_000),
127
+ });
128
+ if (!res.ok) return [];
129
+ const body = (await res.json()) as unknown;
130
+ const rows = Array.isArray(body)
131
+ ? body
132
+ : body !== null && typeof body === "object" && Array.isArray((body as { sessions?: unknown }).sessions)
133
+ ? (body as { sessions: unknown[] }).sessions
134
+ : [];
135
+ const out: Array<{ id: string; name: string }> = [];
136
+ for (const row of rows) {
137
+ if (row === null || typeof row !== "object") continue;
138
+ const source = row as Record<string, unknown>;
139
+ if (typeof source.id !== "string" || !source.id) continue;
140
+ out.push({ id: source.id, name: typeof source.name === "string" && source.name ? source.name : source.id });
141
+ }
142
+ return out;
143
+ } catch {
144
+ return [];
145
+ }
146
+ }
147
+
148
+ /** The bot's @username via getMe, for the t.me deep link; undefined whenever anything is off. */
149
+ async function botUsername(io: TelegramCliIo, token: string): Promise<string | undefined> {
150
+ try {
151
+ const res = await io.fetch(`https://api.telegram.org/bot${token}/getMe`, {
152
+ method: "GET",
153
+ signal: AbortSignal.timeout(8_000),
154
+ });
155
+ if (!res.ok) return undefined;
156
+ const body = (await res.json()) as { ok?: unknown; result?: { username?: unknown } };
157
+ return typeof body?.result?.username === "string" && body.result.username ? body.result.username : undefined;
158
+ } catch {
159
+ return undefined;
160
+ }
161
+ }
162
+
163
+ export async function telegramCli(args: TelegramCliArgs, io: TelegramCliIo = defaultTelegramCliIo()): Promise<number> {
164
+ try {
165
+ return await run(args, io);
166
+ } catch (error) {
167
+ // The CLI contract is an exit code, never a stack trace (backupCli's rule).
168
+ io.printErr(`dpi telegram: ${error instanceof Error ? error.message : String(error)}`);
169
+ return 1;
170
+ }
171
+ }
172
+
173
+ async function run(args: TelegramCliArgs, io: TelegramCliIo): Promise<number> {
174
+ const argv = args.argv;
175
+ if (argv.includes("--help") || argv.includes("-h")) {
176
+ io.print(TELEGRAM_HELP);
177
+ return 0;
178
+ }
179
+ const [sub = "", ...rest] = argv;
180
+ const env = await resolveEnv(rest, io);
181
+ const sessions = await fetchSessions(io, env);
182
+ const broker: TelegramBroker = {
183
+ listSessions: () => sessions.map((session) => ({ ...session })),
184
+ sendToSession: async () => {
185
+ throw new Error("the CLI does not submit to sessions; the device daemon does");
186
+ },
187
+ awaitAnswer: async () => undefined,
188
+ };
189
+ const openBridge = () =>
190
+ TelegramBridge.open(env.registryPath, io, broker, { warn: (message) => io.printErr(`[telegram] ${message}`) });
191
+
192
+ switch (sub) {
193
+ case "status":
194
+ return await statusCmd(io, env, openBridge);
195
+ case "bind":
196
+ return await bindCmd(rest, io, env, sessions, openBridge);
197
+ case "unbind":
198
+ return await unbindCmd(rest, io, openBridge);
199
+ case "sessions":
200
+ return sessionsCmd(io, env, sessions);
201
+ default:
202
+ io.printErr(
203
+ `dpi telegram: unknown subcommand '${sub || "(none)"}' — expected status, bind, unbind or sessions\n\n${TELEGRAM_HELP}`,
204
+ );
205
+ return 2;
206
+ }
207
+ }
208
+
209
+ async function statusCmd(io: TelegramCliIo, env: TelegramCliEnv, openBridge: () => Promise<TelegramBridge>): Promise<number> {
210
+ if (!env.token) {
211
+ io.printErr(`dpi telegram: no DPI_TELEGRAM_TOKEN in ${env.envFile}`);
212
+ return 1;
213
+ }
214
+ const status = (await openBridge()).status();
215
+ io.print(`token: configured (looked in ${env.envFile})`);
216
+ io.print(`registry: ${env.registryPath}, bridge ${status.running ? "running" : "stopped"}`);
217
+ if (!status.chats.length) io.print("no chats bound");
218
+ else {
219
+ io.print(`${status.chats.length} chat(s) bound:`);
220
+ for (const chat of status.chats) io.print(` ${chat.chatId} → ${chat.sessionName ?? chat.sessionId}`);
221
+ }
222
+ io.print(status.pendingCodes > 0 ? `${status.pendingCodes} pending bind code(s)` : "no pending bind codes");
223
+ return 0;
224
+ }
225
+
226
+ async function bindCmd(
227
+ rest: readonly string[],
228
+ io: TelegramCliIo,
229
+ env: TelegramCliEnv,
230
+ sessions: ReadonlyArray<{ id: string; name: string }>,
231
+ openBridge: () => Promise<TelegramBridge>,
232
+ ): Promise<number> {
233
+ if (!env.token) {
234
+ io.printErr(`dpi telegram: no DPI_TELEGRAM_TOKEN in ${env.envFile}`);
235
+ return 1;
236
+ }
237
+ let sessionId: string | undefined;
238
+ const sessionArg = flagValue(rest, "--session");
239
+ if (sessionArg !== undefined) {
240
+ const target = sessions.find((session) => session.id.startsWith(sessionArg));
241
+ if (!target) {
242
+ io.printErr(`dpi telegram bind: no session matching '${sessionArg}'`);
243
+ return 1;
244
+ }
245
+ sessionId = target.id;
246
+ }
247
+ let minted: { code: string; expiresAt: string };
248
+ try {
249
+ const bridge = await openBridge();
250
+ minted = sessionId === undefined ? await bridge.bind() : await bridge.bind(sessionId);
251
+ } catch (error) {
252
+ io.printErr(`dpi telegram bind: ${error instanceof Error ? error.message : String(error)}`);
253
+ return 1;
254
+ }
255
+ io.print(`send this to your bot: /start ${minted.code}`);
256
+ io.print(`the code expires ${minted.expiresAt}`);
257
+ const username = await botUsername(io, env.token);
258
+ if (username) io.print(`deep link: https://t.me/${username}?start=${minted.code}`);
259
+ else io.print("could not reach api.telegram.org for a deep link — send the /start line above");
260
+ return 0;
261
+ }
262
+
263
+ async function unbindCmd(rest: readonly string[], io: TelegramCliIo, openBridge: () => Promise<TelegramBridge>): Promise<number> {
264
+ const positional = rest.filter((arg) => !arg.startsWith("--") && arg !== flagValue(rest, "--home"));
265
+ if (positional.length !== 1) {
266
+ io.printErr(`dpi telegram unbind: expected exactly one chat-id prefix\n\n${TELEGRAM_HELP}`);
267
+ return 2;
268
+ }
269
+ const chatId = await (await openBridge()).unbind(positional[0]);
270
+ if (chatId === undefined) {
271
+ io.printErr(`dpi telegram unbind: no bound chat matching '${positional[0]}'`);
272
+ return 1;
273
+ }
274
+ io.print(`unbound chat ${chatId}`);
275
+ return 0;
276
+ }
277
+
278
+ function sessionsCmd(io: TelegramCliIo, env: TelegramCliEnv, sessions: ReadonlyArray<{ id: string; name: string }>): number {
279
+ if (!sessions.length) {
280
+ io.print(`no sessions (looked at ${env.baseUrl}/v1/sessions — is the device running?)`);
281
+ return 0;
282
+ }
283
+ io.print(`${sessions.length} session(s) a chat can switch to:`);
284
+ for (const session of sessions) io.print(` ${session.id} ${session.name}`);
285
+ return 0;
286
+ }