my-durable 0.0.43 → 0.0.45

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.
@@ -31,6 +31,7 @@ const store = await Store.open({
31
31
  name: config.name,
32
32
  provider: config.provider,
33
33
  envFile: config.envFile,
34
+ telegramToken: process.env.DPI_TELEGRAM_TOKEN,
34
35
  });
35
36
 
36
37
  const app = express();
@@ -40,7 +40,14 @@ export const NOTIFY_HELP = `dpi notify — outbound notifications (webhook / ntf
40
40
  LAN sinks (http://192.168.x.x, http://localhost) are refused by default:
41
41
  start the device with DPI_NOTIFY_ALLOW_PRIVATE=1 to allow them.`;
42
42
 
43
- export const EMITTED_EVENTS = ["session.failed", "schedule.ok", "schedule.failed", "test"] as const;
43
+ export const EMITTED_EVENTS = [
44
+ "session.failed",
45
+ "schedule.ok",
46
+ "schedule.failed",
47
+ "graph.ok",
48
+ "graph.failed",
49
+ "test",
50
+ ] as const;
44
51
 
45
52
  export const defaultNotifyIo = (): ScheduleIo => ({
46
53
  ...defaultDoctorIo(),
@@ -5,7 +5,7 @@ import type { Conversation, Harness } from "@earendil-works/pi-durable";
5
5
  import { DEVICE_DOC_KINDS, type SessionRow, type Store } from "./store.js";
6
6
  import { agentStream, deviceStream, sessionStream } from "./streams.js";
7
7
  import { idempotent } from "./idempotency.js";
8
- import { invalid } from "./errors.js";
8
+ import { invalid, notFound } from "./errors.js";
9
9
  import type { DevicePairing } from "./pairing.js";
10
10
 
11
11
  type Async = (req: Request, res: Response) => Promise<unknown>;
@@ -216,6 +216,23 @@ export function v1(
216
216
  r.delete("/notify/sinks/:id", route(async (req, res) => res.json(await store.removeNotifySink(param(req, "id")))));
217
217
  r.post("/notify/test", route(async (_req, res) => res.json({ results: await store.testNotifySinks() })));
218
218
 
219
+ // ----------------------------------------------------- task-graphs
220
+ // The device owns execution (sequential, topological); these routes only
221
+ // read, edit and START a run — the answer streams back through the tree.
222
+ r.get("/graphs", (req, res) => {
223
+ const includeArchived = req.query.includeArchived === "1" || req.query.includeArchived === "true";
224
+ res.json({ graphs: store.graphList(includeArchived) });
225
+ });
226
+ r.get("/graphs/:id", route(async (req, res) => {
227
+ const found = store.graphGet(param(req, "id"));
228
+ if (!found) throw notFound(`no graph ${param(req, "id")}`);
229
+ res.json(found);
230
+ }));
231
+ r.post("/graphs", route(async (req, res) => res.status(201).json(await store.createGraph(req.body ?? {}))));
232
+ r.patch("/graphs/:id", route(async (req, res) => res.json(await store.updateGraph(param(req, "id"), req.body ?? {}))));
233
+ r.delete("/graphs/:id", route(async (req, res) => res.json(await store.removeGraph(param(req, "id")))));
234
+ r.post("/graphs/:id/run", route(async (req, res) => res.status(202).json(await store.runGraphNow(param(req, "id")))));
235
+
219
236
  // -------------------------------------------------------- schedules
220
237
  // The device owns execution (systemd/cron are deliberately rejected by config);
221
238
  // these routes only read and edit the schedule records.
@@ -52,6 +52,15 @@ 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
54
  import { KeepAwake } from "./awake.js";
55
+ import { TelegramBridge, defaultTelegramIo, type TelegramBroker } from "./telegram.js";
56
+ import {
57
+ GraphRegistry,
58
+ readyTasks,
59
+ topoOrder,
60
+ type GraphRecord,
61
+ type GraphRunRecord,
62
+ type GraphTask,
63
+ } from "./graphs.js";
55
64
  import { ScheduleRegistry, type ScheduleCreateInput, type ScheduleRecord } from "./schedules.js";
56
65
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
57
66
  import { zipSync, type ZipEntry } from "./zip.js";
@@ -147,6 +156,8 @@ export interface StoreOptions {
147
156
  provider: "openrouter" | "faux";
148
157
  /** The env file the daemon booted from (config.ts's `envFile`); backs the env UI. */
149
158
  envFile?: string;
159
+ /** Bot token for the Telegram chat bridge; absent = the bridge stays idle. */
160
+ telegramToken?: string;
150
161
  }
151
162
 
152
163
  /** Agent documents a client may read or stream, by kind. */
@@ -286,6 +297,11 @@ export class Store {
286
297
  /** Keep-awake (Wave 3): holds the OS awake while any session is busy. */
287
298
  readonly awake = new KeepAwake();
288
299
  private awakeTimer?: ReturnType<typeof setTimeout>;
300
+ /** Telegram chat bridge (Wave 3): bound chats talk to sessions. */
301
+ telegram?: TelegramBridge;
302
+ /** Task-graphs (Wave 3): a DAG of prompt-tasks, each run as a fresh session. */
303
+ graphs!: GraphRegistry;
304
+ private graphRunsInFlight = new Set<string>();
289
305
  uid!: string;
290
306
  modelList: ModelInfo[] = [];
291
307
  private unlockCatalog: () => void;
@@ -317,6 +333,12 @@ export class Store {
317
333
  get notifyPath() {
318
334
  return join(this.options.dataDir, "notify.json");
319
335
  }
336
+ get telegramPath() {
337
+ return join(this.options.dataDir, "telegram.json");
338
+ }
339
+ get graphsPath() {
340
+ return join(this.options.dataDir, "graphs.json");
341
+ }
320
342
  get name() {
321
343
  return this.options.name;
322
344
  }
@@ -387,6 +409,19 @@ export class Store {
387
409
  // ntfy often lives on the LAN; the operator opts in explicitly.
388
410
  allowPrivateHosts: process.env.DPI_NOTIFY_ALLOW_PRIVATE === "1",
389
411
  });
412
+ // Telegram bridge (Wave 3): chats bound to sessions. The broker below is
413
+ // the ONLY bridge-to-store surface — the module itself knows the protocol.
414
+ store.telegram = await TelegramBridge.open(store.telegramPath, defaultTelegramIo(), store.telegramBroker(), {
415
+ warn: (m) => process.emitWarning(`telegram: ${m}`),
416
+ });
417
+ if (options.telegramToken) store.telegram.start(options.telegramToken);
418
+ store.graphs = await GraphRegistry.open(store.graphsPath, {
419
+ warn: (m) => process.emitWarning(`graphs: ${m}`),
420
+ });
421
+ // A restart mid-run never loses the graph: the run flips to interrupted
422
+ // with its running tasks back to pending, and `run` continues from there.
423
+ for (const run of await store.graphs.recoverInterrupted())
424
+ process.emitWarning(`graphs: run ${run.id} of ${run.graphId} was interrupted by a restart; run it again to continue`);
390
425
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
391
426
  store.shared = await SharedState.open(store.sharedStatePath);
392
427
  store.shared.harness.subscribeCommits(() => store.notify());
@@ -477,7 +512,14 @@ export class Store {
477
512
  ...(this.modelsKeyless ? { providerKeyMissing: true } : {}),
478
513
  storage: { dataDir: this.options.dataDir, catalogPath: this.catalogPath, appStatePath: this.sharedStatePath },
479
514
  codeDir: CODE_DIR,
480
- capabilities: this.awake.mode === "none" ? ["events", "docs", "demo", "jobs"] : ["events", "docs", "demo", "jobs", "keep-awake"],
515
+ capabilities: [
516
+ "events",
517
+ "docs",
518
+ "demo",
519
+ "jobs",
520
+ ...(this.awake.mode !== "none" ? (["keep-awake"] as const) : []),
521
+ ...(this.telegram?.running ? (["telegram"] as const) : []),
522
+ ],
481
523
  /** How this device holds the OS awake while sessions run ("none" = it cannot). */
482
524
  keepAwake: this.awake.mode,
483
525
  jobs: JOB_DEFS,
@@ -797,6 +839,150 @@ export class Store {
797
839
  return result;
798
840
  }
799
841
 
842
+ /** The store side of the Telegram bridge: sessions in, answers out. */
843
+ private telegramBroker(): TelegramBroker {
844
+ return {
845
+ listSessions: () => this.list().map((row) => ({ id: row.id, name: row.name })),
846
+ sendToSession: async (sessionId, text) => {
847
+ const { c } = await this.resolveAgent(sessionId, "main");
848
+ const submission = await this.send(c, {
849
+ content: text,
850
+ whenBusy: "followUp",
851
+ requestId: `telegram-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
852
+ });
853
+ return { submissionId: submission.id as number };
854
+ },
855
+ awaitAnswer: async (sessionId, submissionId, timeoutMs) => {
856
+ const row = this.resolveSession(sessionId);
857
+ const h = this.harness(row);
858
+ await this.settled(h, submissionId, timeoutMs).catch(() => undefined);
859
+ const c = await h.conversation(1 as ConversationId, ctx);
860
+ if (!c) return undefined;
861
+ return lastAssistantText(await this.activeEntries(c)) ?? undefined;
862
+ },
863
+ };
864
+ }
865
+
866
+ // ------------------------------------------------ task-graphs (Wave 3)
867
+
868
+ graphList(includeArchived = false): Array<GraphRecord & { lastRun?: GraphRunRecord }> {
869
+ return this.graphs.list({ includeArchived }).map((g) => ({ ...g, lastRun: this.graphs.lastRun(g.id) }));
870
+ }
871
+
872
+ graphGet(id: string): { graph: GraphRecord; runs: GraphRunRecord[] } | undefined {
873
+ const graph = this.graphs.get(id);
874
+ if (!graph) return undefined;
875
+ return { graph, runs: this.graphs.runs(id) };
876
+ }
877
+
878
+ async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
879
+ const created = await this.graphs.create(body as never);
880
+ this.notify();
881
+ return created;
882
+ }
883
+
884
+ async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
885
+ const updated = await this.graphs.update(id, body as never);
886
+ this.notify();
887
+ return updated;
888
+ }
889
+
890
+ async removeGraph(id: string): Promise<{ removed: boolean }> {
891
+ if (this.graphRunsInFlight.has(id)) throw invalid("this graph is running");
892
+ const removed = await this.graphs.remove(id);
893
+ this.notify();
894
+ return { removed };
895
+ }
896
+
897
+ /**
898
+ * Start a run. Execution is sequential in topological order — deterministic
899
+ * and debuggable on a single device — and happens in the background: the
900
+ * route answers with the run record immediately, statuses flow through the
901
+ * tree and GET /graphs/:id.
902
+ */
903
+ async runGraphNow(id: string): Promise<{ run: GraphRunRecord }> {
904
+ const record = this.graphs.get(id);
905
+ if (!record) throw notFound(`no graph ${id}`);
906
+ if (this.graphRunsInFlight.has(record.id)) throw invalid("this graph is already running");
907
+ const run = await this.graphs.beginRun(record.id);
908
+ this.graphRunsInFlight.add(record.id);
909
+ this.notify();
910
+ void this.executeGraphRun(record, run.id).catch(() => undefined);
911
+ return { run };
912
+ }
913
+
914
+ /** One task = one fresh session (the schedules rule: never overwrite prior work). */
915
+ private async executeGraphTask(record: GraphRecord, runId: string, taskId: string) {
916
+ const task = record.tasks.find((t) => t.id === taskId);
917
+ if (!task) return;
918
+ await this.graphs.markTask(record.id, runId, taskId, { status: "running" });
919
+ this.notify();
920
+ try {
921
+ const session = await this.create({
922
+ name: `${record.name} · ${task.name}`,
923
+ cwd: record.cwd,
924
+ ...(task.model ? { model: task.model } : {}),
925
+ });
926
+ await this.graphs.markTask(record.id, runId, taskId, { sessionId: session.id });
927
+ const row = this.resolveSession(session.id);
928
+ const h = this.harness(row);
929
+ const { c } = await this.resolveAgent(session.id, "main");
930
+ const submission = await this.send(c, {
931
+ content: task.prompt,
932
+ whenBusy: "followUp",
933
+ requestId: `graph-${runId}-${taskId}`,
934
+ });
935
+ const outcome = await this.waitForGraphAnswer(h, submission.id as number);
936
+ await this.graphs.markTask(record.id, runId, taskId, outcome.ok ? { status: "ok" } : { status: "failed", error: outcome.error });
937
+ } catch (e) {
938
+ const error = String(e instanceof Error ? e.message : e).slice(0, 300);
939
+ await this.graphs.markTask(record.id, runId, taskId, { status: "failed", error }).catch(() => undefined);
940
+ }
941
+ this.notify();
942
+ }
943
+
944
+ /** A task turn gets 30 minutes; `settled` waits ≤5 min a call, so this polls. */
945
+ private async waitForGraphAnswer(h: Harness, submissionId: number): Promise<{ ok: true } | { ok: false; error: string }> {
946
+ const deadline = Date.now() + 30 * 60_000;
947
+ for (;;) {
948
+ try {
949
+ const r = await this.settled(h, submissionId, 60_000);
950
+ if ("answer" in r) return { ok: true };
951
+ if (r.status === "unanswered") return { ok: false, error: `unanswered: ${r.reason}` };
952
+ } catch (e) {
953
+ return { ok: false, error: String(e instanceof Error ? e.message : e).slice(0, 300) };
954
+ }
955
+ if (Date.now() >= deadline) return { ok: false, error: "timed out after 30 minutes" };
956
+ }
957
+ }
958
+
959
+ private async executeGraphRun(record: GraphRecord, runId: string) {
960
+ try {
961
+ const order = topoOrder(record.tasks);
962
+ for (;;) {
963
+ const run = this.graphs.runs(record.id).find((r) => r.id === runId);
964
+ if (!run || run.status !== "running") break;
965
+ const ready = readyTasks(record.tasks, run.tasks).sort((a, b) => order.indexOf(a) - order.indexOf(b));
966
+ if (!ready.length) break; // complete (or fully skipped) — the registry closed it
967
+ await this.executeGraphTask(record, runId, ready[0]!);
968
+ }
969
+ const final = this.graphs.runs(record.id).find((r) => r.id === runId);
970
+ if (final?.status === "ok" || final?.status === "failed")
971
+ void this.notifyEvent({
972
+ kind: final.status === "ok" ? "graph.ok" : "graph.failed",
973
+ title: `Graph ${final.status === "ok" ? "finished" : "failed"}: ${record.name}`,
974
+ body:
975
+ final.status === "ok"
976
+ ? `Every task of "${record.name}" finished ok on ${this.name}.`
977
+ : `A task of "${record.name}" failed on ${this.name}; its dependants were skipped.`,
978
+ data: { graphId: record.id, runId: final.id },
979
+ });
980
+ } finally {
981
+ this.graphRunsInFlight.delete(record.id);
982
+ this.notify();
983
+ }
984
+ }
985
+
800
986
  /** `spawnKey` records which tool call created the session, in the same transaction as the session row. */
801
987
  async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
802
988
  if (typeof body?.name !== "string") throw invalid("name is required");
@@ -2131,6 +2317,9 @@ export class Store {
2131
2317
  this.stopScheduler();
2132
2318
  if (this.awakeTimer) clearTimeout(this.awakeTimer);
2133
2319
  this.awake.stop();
2320
+ this.telegram?.stop();
2321
+ // A graceful stop marks an in-flight graph run interrupted (not lost).
2322
+ await this.graphs?.recoverInterrupted().catch(() => undefined);
2134
2323
  for (const { harness, unlock, unsubscribe } of this.opened.values()) {
2135
2324
  unsubscribe();
2136
2325
  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
+ }