@llblab/pi-telegram 0.11.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +20 -15
  2. package/BACKLOG.md +1 -11
  3. package/CHANGELOG.md +41 -1
  4. package/README.md +15 -41
  5. package/api/inbound.ts +14 -0
  6. package/api/keyboard.ts +10 -0
  7. package/api/outbound.ts +11 -0
  8. package/api/sections.ts +17 -0
  9. package/api/updates.ts +11 -0
  10. package/api/voice.ts +24 -0
  11. package/docs/README.md +7 -5
  12. package/docs/architecture.md +162 -226
  13. package/docs/callback-namespaces.md +3 -3
  14. package/docs/command-templates.md +18 -16
  15. package/docs/{inbound-handlers.md → inbound.md} +14 -11
  16. package/docs/locks.md +3 -3
  17. package/docs/{outbound-handlers.md → outbound.md} +14 -11
  18. package/docs/public-api.md +420 -0
  19. package/docs/{extension-sections.md → sections.md} +34 -30
  20. package/docs/ui-style.md +165 -0
  21. package/docs/{external-handlers.md → updates.md} +33 -31
  22. package/docs/voice.md +27 -19
  23. package/index.ts +88 -242
  24. package/lib/bindings.ts +299 -0
  25. package/lib/command-templates.ts +249 -60
  26. package/lib/commands.ts +114 -1
  27. package/lib/config.ts +44 -4
  28. package/lib/{inbound-handlers.ts → inbound.ts} +31 -21
  29. package/lib/lifecycle.ts +41 -6
  30. package/lib/locks.ts +4 -1
  31. package/lib/menu-model.ts +3 -3
  32. package/lib/menu-queue.ts +1 -1
  33. package/lib/menu-settings.ts +21 -10
  34. package/lib/menu-status.ts +1 -1
  35. package/lib/menu.ts +1 -1
  36. package/lib/outbound-buttons.ts +226 -0
  37. package/lib/outbound-markup.ts +357 -0
  38. package/lib/outbound-voice.ts +263 -0
  39. package/lib/outbound.ts +908 -0
  40. package/lib/polling.ts +4 -3
  41. package/lib/preview.ts +2 -2
  42. package/lib/queue.ts +3 -0
  43. package/lib/replies.ts +4 -1
  44. package/lib/routing.ts +44 -3
  45. package/lib/{extension-sections.ts → sections.ts} +37 -8
  46. package/lib/status.ts +13 -0
  47. package/lib/{api.ts → telegram-api.ts} +4 -4
  48. package/lib/text-groups.ts +3 -2
  49. package/lib/updates.ts +121 -1
  50. package/lib/voice.ts +67 -21
  51. package/package.json +13 -3
  52. package/lib/external-handlers.ts +0 -166
  53. package/lib/outbound-handlers.ts +0 -1663
@@ -8,26 +8,28 @@ import { spawn } from "node:child_process";
8
8
  import { homedir } from "node:os";
9
9
  import { isAbsolute, resolve } from "node:path";
10
10
 
11
- export type CommandTemplateMode = "sequence" | "parallel";
12
11
  export type CommandTemplateFailureScope = "continue" | "branch" | "root";
13
12
 
14
13
  export interface CommandTemplateObjectConfig {
15
14
  label?: string;
16
- mode?: CommandTemplateMode;
15
+ parallel?: boolean;
16
+ when?: boolean | string;
17
17
  template?: CommandTemplateValue;
18
18
  args?: string[];
19
19
  defaults?: Record<string, unknown>;
20
- timeout?: number;
21
- delay?: number;
20
+ timeout?: number | string;
21
+ delay?: number | string;
22
22
  output?: string;
23
- retry?: number;
24
- critical?: boolean;
23
+ retry?: number | string;
25
24
  failure?: CommandTemplateFailureScope;
26
25
  recover?: CommandTemplateValue;
27
26
  repeat?: number | string;
28
27
  }
29
28
 
30
- export type CommandTemplateValue = string | CommandTemplateConfig[] | CommandTemplateObjectConfig;
29
+ export type CommandTemplateValue =
30
+ | string
31
+ | CommandTemplateConfig[]
32
+ | CommandTemplateObjectConfig;
31
33
 
32
34
  export type CommandTemplateConfig = string | CommandTemplateObjectConfig;
33
35
 
@@ -88,11 +90,34 @@ function normalizeCommandTemplateDefaults(
88
90
  for (const [key, value] of Object.entries(defaults)) {
89
91
  normalized[key] = Array.isArray(value)
90
92
  ? value
91
- : value === undefined || value === null ? "" : String(value);
93
+ : value === undefined || value === null
94
+ ? ""
95
+ : String(value);
92
96
  }
93
97
  return normalized;
94
98
  }
95
99
 
100
+ export function resolveInheritedDefaultReferences(
101
+ ownDefaults: Record<string, unknown> | undefined,
102
+ inheritedDefaults: Record<string, unknown> | undefined,
103
+ runtimeValues: Record<string, unknown> = {},
104
+ ): Record<string, unknown> | undefined {
105
+ if (!ownDefaults || !inheritedDefaults) return ownDefaults;
106
+ const resolved = { ...ownDefaults };
107
+ for (const [key, value] of Object.entries(ownDefaults)) {
108
+ if (typeof value !== "string") continue;
109
+ const exact = /^\{([A-Za-z_][A-Za-z0-9_-]*)\}$/.exec(value);
110
+ if (
111
+ !exact ||
112
+ Object.hasOwn(runtimeValues, exact[1]) ||
113
+ !Object.hasOwn(inheritedDefaults, exact[1])
114
+ )
115
+ continue;
116
+ resolved[key] = inheritedDefaults[exact[1]];
117
+ }
118
+ return resolved;
119
+ }
120
+
96
121
  export function resolveCommandTemplateRepeat(
97
122
  value: number | string | undefined,
98
123
  values: Record<string, unknown> = {},
@@ -105,13 +130,17 @@ export function resolveCommandTemplateRepeat(
105
130
  }
106
131
  const trimmed = value.trim();
107
132
  if (/^\d+$/.test(trimmed)) return Number(trimmed);
108
- const lengthMatch = trimmed.match(/^\{?([A-Za-z_][A-Za-z0-9_-]*)\.length\}?$/);
133
+ const lengthMatch = trimmed.match(
134
+ /^\{?([A-Za-z_][A-Za-z0-9_-]*)\.length\}?$/,
135
+ );
109
136
  if (lengthMatch) {
110
137
  const source = values[lengthMatch[1]];
111
138
  if (Array.isArray(source)) return source.length;
112
139
  if (source === undefined) return undefined;
113
140
  }
114
- throw new Error("Command template repeat must be a positive integer or {array.length}.");
141
+ throw new Error(
142
+ "Command template repeat must be a positive integer or {array.length}.",
143
+ );
115
144
  }
116
145
 
117
146
  function getExecutableName(command: string | undefined): string {
@@ -124,14 +153,15 @@ function hasAnyFlag(args: string[], flags: string[]): boolean {
124
153
  }
125
154
 
126
155
  function hasRiskyPathArg(args: string[]): boolean {
127
- return args.some((arg) =>
128
- arg === "/" ||
129
- arg === "~" ||
130
- arg === "./" ||
131
- arg === "../" ||
132
- arg.includes("{") ||
133
- arg.startsWith("~/") ||
134
- arg.startsWith("/"),
156
+ return args.some(
157
+ (arg) =>
158
+ arg === "/" ||
159
+ arg === "~" ||
160
+ arg === "./" ||
161
+ arg === "../" ||
162
+ arg.includes("{") ||
163
+ arg.startsWith("~/") ||
164
+ arg.startsWith("/"),
135
165
  );
136
166
  }
137
167
 
@@ -143,20 +173,42 @@ function getLeafCommandTemplateWarnings(
143
173
  const args = parts.slice(1);
144
174
  const warnings: string[] = [];
145
175
  if (["bash", "sh", "zsh", "fish"].includes(command)) {
146
- const mode = hasAnyFlag(args, ["-c"]) ? "shell command strings" : "shell scripts";
147
- warnings.push(`${config.label ?? command}: invokes ${command}; ${mode} are trusted executable content and are not sandboxed by command-template argv splitting.`);
176
+ const shellContent = hasAnyFlag(args, ["-c"])
177
+ ? "shell command strings"
178
+ : "shell scripts";
179
+ warnings.push(
180
+ `${config.label ?? command}: invokes ${command}; ${shellContent} are trusted executable content and are not sandboxed by command-template argv splitting.`,
181
+ );
148
182
  }
149
- if (["node", "deno", "bun"].includes(command) && hasAnyFlag(args, ["-e", "--eval"])) {
150
- warnings.push(`${config.label ?? command}: invokes ${command} eval mode; code strings are trusted executable content and are not sandboxed.`);
183
+ if (
184
+ ["node", "deno", "bun"].includes(command) &&
185
+ hasAnyFlag(args, ["-e", "--eval"])
186
+ ) {
187
+ warnings.push(
188
+ `${config.label ?? command}: invokes ${command} eval mode; code strings are trusted executable content and are not sandboxed.`,
189
+ );
151
190
  }
152
- if (["python", "python3", "perl", "ruby"].includes(command) && hasAnyFlag(args, ["-c", "-e"])) {
153
- warnings.push(`${config.label ?? command}: invokes ${command} code-eval mode; code strings are trusted executable content and are not sandboxed.`);
191
+ if (
192
+ ["python", "python3", "perl", "ruby"].includes(command) &&
193
+ hasAnyFlag(args, ["-c", "-e"])
194
+ ) {
195
+ warnings.push(
196
+ `${config.label ?? command}: invokes ${command} code-eval mode; code strings are trusted executable content and are not sandboxed.`,
197
+ );
154
198
  }
155
- if (command === "rm" && (args.some((arg) => /^-[^-]*r/.test(arg) || /^-[^-]*f/.test(arg)) || hasRiskyPathArg(args))) {
156
- warnings.push(`${config.label ?? command}: removes filesystem paths; verify placeholders and paths before running trusted destructive commands.`);
199
+ if (
200
+ command === "rm" &&
201
+ (args.some((arg) => /^-[^-]*r/.test(arg) || /^-[^-]*f/.test(arg)) ||
202
+ hasRiskyPathArg(args))
203
+ ) {
204
+ warnings.push(
205
+ `${config.label ?? command}: removes filesystem paths; verify placeholders and paths before running trusted destructive commands.`,
206
+ );
157
207
  }
158
208
  if (["mv", "cp", "rsync"].includes(command) && hasRiskyPathArg(args)) {
159
- warnings.push(`${config.label ?? command}: mutates broad filesystem paths; verify placeholders and paths before running trusted commands.`);
209
+ warnings.push(
210
+ `${config.label ?? command}: mutates broad filesystem paths; verify placeholders and paths before running trusted commands.`,
211
+ );
160
212
  }
161
213
  return warnings;
162
214
  }
@@ -184,7 +236,10 @@ export function getCommandTemplateRepeatDefaults(
184
236
  for (const name of ["index", "prev", "next", "repeat"]) {
185
237
  const numeric = Number(values[name]);
186
238
  for (let underscores = 1; underscores <= 6; underscores += 1) {
187
- values[`${"_".repeat(underscores)}${name}`] = pad(numeric, underscores + 1);
239
+ values[`${"_".repeat(underscores)}${name}`] = pad(
240
+ numeric,
241
+ underscores + 1,
242
+ );
188
243
  }
189
244
  }
190
245
  return values;
@@ -194,7 +249,10 @@ function expandRepeatConfig(
194
249
  config: CommandTemplateObjectConfig,
195
250
  context: Pick<CommandTemplateObjectConfig, "args" | "defaults">,
196
251
  ): CommandTemplateObjectConfig[] | undefined {
197
- const repeat = resolveCommandTemplateRepeat(config.repeat, context.defaults ?? {});
252
+ const repeat = resolveCommandTemplateRepeat(
253
+ config.repeat,
254
+ context.defaults ?? {},
255
+ );
198
256
  if (repeat === undefined) return undefined;
199
257
  return Array.from({ length: repeat }, (_unused, index0) => {
200
258
  const { repeat: _repeat, ...rest } = config;
@@ -217,8 +275,9 @@ export function expandCommandTemplateConfigs(
217
275
  const inheritedDefaults = normalizeCommandTemplateDefaults(
218
276
  inherited.defaults,
219
277
  );
220
- const ownDefaults = normalizeCommandTemplateDefaults(
221
- normalizedConfig.defaults,
278
+ const ownDefaults = resolveInheritedDefaultReferences(
279
+ normalizeCommandTemplateDefaults(normalizedConfig.defaults),
280
+ inheritedDefaults,
222
281
  );
223
282
  const context = {
224
283
  ...(inherited.args !== undefined ? { args: inherited.args } : {}),
@@ -232,7 +291,9 @@ export function expandCommandTemplateConfigs(
232
291
  };
233
292
  const repeated = expandRepeatConfig(normalizedConfig, context);
234
293
  if (repeated) {
235
- return repeated.flatMap((step) => expandCommandTemplateConfigs(step, context));
294
+ return repeated.flatMap((step) =>
295
+ expandCommandTemplateConfigs(step, context),
296
+ );
236
297
  }
237
298
  const recoverConfig = normalizeRecoverConfig(normalizedConfig.recover);
238
299
  const recoverSteps = recoverConfig
@@ -253,7 +314,6 @@ export function expandCommandTemplateConfigs(
253
314
  ...context,
254
315
  template: normalizedConfig.template,
255
316
  retry: normalizedConfig.retry,
256
- critical: normalizedConfig.critical,
257
317
  },
258
318
  ...recoverSteps,
259
319
  ];
@@ -264,26 +324,40 @@ export function getCommandTemplateWarnings(
264
324
  ): string[] {
265
325
  return [
266
326
  ...new Set(
267
- expandCommandTemplateConfigs(config)
268
- .flatMap((leaf) => getLeafCommandTemplateWarnings(leaf)),
327
+ expandCommandTemplateConfigs(config).flatMap((leaf) =>
328
+ getLeafCommandTemplateWarnings(leaf),
329
+ ),
269
330
  ),
270
331
  ];
271
332
  }
272
333
 
273
- function parseCommandTemplateArgToken(value: string): { name: string; defaultValue?: string } {
334
+ function parseCommandTemplateArgToken(value: string): {
335
+ name: string;
336
+ defaultValue?: string;
337
+ } {
274
338
  const separatorIndex = value.indexOf("=");
275
- const rawName = separatorIndex === -1 ? value : value.slice(0, separatorIndex);
339
+ const rawName =
340
+ separatorIndex === -1 ? value : value.slice(0, separatorIndex);
276
341
  const colonIndex = rawName.indexOf(":");
277
342
  return {
278
343
  name: (colonIndex === -1 ? rawName : rawName.slice(0, colonIndex)).trim(),
279
- ...(separatorIndex === -1 ? {} : { defaultValue: value.slice(separatorIndex + 1).trim() }),
344
+ ...(separatorIndex === -1
345
+ ? {}
346
+ : { defaultValue: value.slice(separatorIndex + 1).trim() }),
280
347
  };
281
348
  }
282
349
 
283
- function parseCommandTemplatePlaceholderContent(content: string): { name: string; inlineDefault?: string } | undefined {
284
- const match = content.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?::(?:string|path|int|number|bool|array|enum\([^)]*\)))?(?:=([^}]*))?$/);
350
+ function parseCommandTemplatePlaceholderContent(
351
+ content: string,
352
+ ): { name: string; inlineDefault?: string } | undefined {
353
+ const match = content.match(
354
+ /^([A-Za-z_][A-Za-z0-9_-]*)(?::(?:string|path|int|number|bool|array|enum\([^)]*\)))?(?:=([^}]*))?$/,
355
+ );
285
356
  if (!match) return undefined;
286
- return { name: match[1], ...(match[2] !== undefined ? { inlineDefault: match[2] } : {}) };
357
+ return {
358
+ name: match[1],
359
+ ...(match[2] !== undefined ? { inlineDefault: match[2] } : {}),
360
+ };
287
361
  }
288
362
 
289
363
  export function getCommandTemplateDefaults(
@@ -376,7 +450,8 @@ function evaluateCommandTemplateExpression(
376
450
  function parsePrimary(): number {
377
451
  if (consume("(")) {
378
452
  const value = parseExpression();
379
- if (!consume(")")) throw new Error(`Invalid command template expression: ${expression}`);
453
+ if (!consume(")"))
454
+ throw new Error(`Invalid command template expression: ${expression}`);
380
455
  return value;
381
456
  }
382
457
  const numberMatch = source.slice(index).match(/^\d+/);
@@ -389,7 +464,9 @@ function evaluateCommandTemplateExpression(
389
464
  index += nameMatch[0].length;
390
465
  const value = values[nameMatch[0]];
391
466
  if (value === undefined || !/^-?\d+$/.test(String(value)))
392
- throw new Error(`Invalid command template expression variable: ${nameMatch[0]}`);
467
+ throw new Error(
468
+ `Invalid command template expression variable: ${nameMatch[0]}`,
469
+ );
393
470
  return Number(value);
394
471
  }
395
472
  throw new Error(`Invalid command template expression: ${expression}`);
@@ -412,7 +489,8 @@ function evaluateCommandTemplateExpression(
412
489
  }
413
490
  }
414
491
  const value = parseExpression();
415
- if (index !== source.length) throw new Error(`Invalid command template expression: ${expression}`);
492
+ if (index !== source.length)
493
+ throw new Error(`Invalid command template expression: ${expression}`);
416
494
  return value;
417
495
  }
418
496
 
@@ -422,25 +500,125 @@ function substituteCommandTemplateExpression(
422
500
  ): string | undefined {
423
501
  const padded = content.match(/^(_{1,6})\((.+)\)$/);
424
502
  if (padded) {
425
- return pad(evaluateCommandTemplateExpression(padded[2], values), padded[1].length + 1);
503
+ return pad(
504
+ evaluateCommandTemplateExpression(padded[2], values),
505
+ padded[1].length + 1,
506
+ );
426
507
  }
427
508
  if (!/[()+\-*\/%]/.test(content)) return undefined;
428
509
  return String(evaluateCommandTemplateExpression(content, values));
429
510
  }
430
511
 
512
+ function shouldResolveEmbeddedCommandTemplateToken(
513
+ token: string,
514
+ values: Record<string, unknown>,
515
+ ): boolean {
516
+ const matches = [...token.matchAll(/\{([^{}]+)\}/g)];
517
+ if (matches.length === 0) return false;
518
+ return matches.every((match) => {
519
+ const content = match[1];
520
+ if (resolveCommandTemplateNullish(content, values) !== undefined)
521
+ return true;
522
+ if (resolveCommandTemplateTernary(content, values) !== undefined)
523
+ return true;
524
+ const indexed = content.match(
525
+ /^([A-Za-z_][A-Za-z0-9_-]*)\[([A-Za-z_][A-Za-z0-9_-]*|\d+)\]$/,
526
+ );
527
+ if (indexed) return Object.hasOwn(values, indexed[1]);
528
+ const simple = parseCommandTemplatePlaceholderContent(content);
529
+ if (simple)
530
+ return (
531
+ Object.hasOwn(values, simple.name) || simple.inlineDefault !== undefined
532
+ );
533
+ try {
534
+ return substituteCommandTemplateExpression(content, values) !== undefined;
535
+ } catch {
536
+ return false;
537
+ }
538
+ });
539
+ }
540
+
541
+ function isFalsyCommandTemplateValue(value: unknown): boolean {
542
+ if (value === undefined || value === null || value === false) return true;
543
+ const normalized = String(value).trim().toLowerCase();
544
+ return normalized === "" || normalized === "0" || normalized === "false" || normalized === "no";
545
+ }
546
+
547
+ function resolveCommandTemplateCondition(
548
+ condition: string,
549
+ values: Record<string, unknown>,
550
+ ): unknown {
551
+ const trimmed = condition.trim();
552
+ const negated = trimmed.startsWith("!");
553
+ const name = negated ? trimmed.slice(1).trim() : trimmed;
554
+ const value = /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)
555
+ ? values[name]
556
+ : undefined;
557
+ return negated ? isFalsyCommandTemplateValue(value) : value;
558
+ }
559
+
560
+ export function shouldRunCommandTemplateNode(
561
+ value: boolean | string | undefined,
562
+ values: Record<string, unknown>,
563
+ ): boolean {
564
+ if (value === undefined) return true;
565
+ if (typeof value === "boolean") return value;
566
+ const trimmed = value.trim();
567
+ if (!trimmed) return false;
568
+ const exact = /^\{([^{}]+)\}$/.exec(trimmed);
569
+ const resolved = exact
570
+ ? resolveCommandTemplateValue(exact[1], values, "command template when")
571
+ : resolveCommandTemplateCondition(trimmed, values);
572
+ return !isFalsyCommandTemplateValue(resolved);
573
+ }
574
+
575
+ function resolveCommandTemplateNullish(
576
+ content: string,
577
+ values: Record<string, unknown>,
578
+ ): string | undefined {
579
+ const coalescing = content.match(/^([A-Za-z_][A-Za-z0-9_-]*)\?\?(.*)$/);
580
+ if (!coalescing) return undefined;
581
+ const value = values[coalescing[1]];
582
+ return isFalsyCommandTemplateValue(value) ? coalescing[2] : String(value);
583
+ }
584
+
585
+ function resolveCommandTemplateTernary(
586
+ content: string,
587
+ values: Record<string, unknown>,
588
+ ): string | undefined {
589
+ const ternary = content.match(/^([^?:]+)\?([^:]*):(.*)$/);
590
+ if (!ternary) return undefined;
591
+ const condition = resolveCommandTemplateCondition(ternary[1], values);
592
+ return isFalsyCommandTemplateValue(condition) ? ternary[3] : ternary[2];
593
+ }
594
+
431
595
  function resolveCommandTemplateValue(
432
596
  content: string,
433
597
  values: Record<string, unknown>,
434
598
  missingLabel: string,
435
599
  depth = 0,
436
600
  ): string | undefined {
437
- if (depth > 5) throw new Error(`Command template value recursion exceeded: ${content}`);
438
- const indexed = content.match(/^([A-Za-z_][A-Za-z0-9_-]*)\[([A-Za-z_][A-Za-z0-9_-]*|\d+)\]$/);
601
+ if (depth > 5)
602
+ throw new Error(`Command template value recursion exceeded: ${content}`);
603
+ const nullish = resolveCommandTemplateNullish(content, values);
604
+ if (nullish !== undefined) return nullish;
605
+ const ternary = resolveCommandTemplateTernary(content, values);
606
+ if (ternary !== undefined) return ternary;
607
+ const indexed = content.match(
608
+ /^([A-Za-z_][A-Za-z0-9_-]*)\[([A-Za-z_][A-Za-z0-9_-]*|\d+)\]$/,
609
+ );
439
610
  if (indexed) {
440
611
  const source = values[indexed[1]];
441
- const indexValue = /^\d+$/.test(indexed[2]) ? indexed[2] : values[indexed[2]];
612
+ const indexValue = /^\d+$/.test(indexed[2])
613
+ ? indexed[2]
614
+ : values[indexed[2]];
442
615
  const index = Number(indexValue);
443
- if (!Array.isArray(source) || !Number.isInteger(index) || index < 0 || index >= source.length) {
616
+ if (
617
+ !Array.isArray(source) ||
618
+ !Number.isInteger(index) ||
619
+ index < 0 ||
620
+ index >= source.length
621
+ ) {
444
622
  throw new Error(`Missing ${missingLabel} value: ${content}`);
445
623
  }
446
624
  return String(source[index] ?? "");
@@ -449,8 +627,16 @@ function resolveCommandTemplateValue(
449
627
  if (simple) {
450
628
  if (Object.hasOwn(values, simple.name)) {
451
629
  const raw = values[simple.name] ?? "";
452
- if (typeof raw === "string" && /^\{[^{}]+\}$/.test(raw)) {
453
- return substituteCommandTemplateToken(raw, values, missingLabel, depth + 1);
630
+ if (
631
+ typeof raw === "string" &&
632
+ shouldResolveEmbeddedCommandTemplateToken(raw, values)
633
+ ) {
634
+ return substituteCommandTemplateToken(
635
+ raw,
636
+ values,
637
+ missingLabel,
638
+ depth + 1,
639
+ );
454
640
  }
455
641
  return Array.isArray(raw) ? JSON.stringify(raw) : String(raw);
456
642
  }
@@ -467,14 +653,16 @@ export function substituteCommandTemplateToken(
467
653
  missingLabel = "command template",
468
654
  depth = 0,
469
655
  ): string {
470
- return token.replace(
471
- /\{([^{}]+)\}/g,
472
- (_match, content: string) => {
473
- const resolved = resolveCommandTemplateValue(content, values, missingLabel, depth);
474
- if (resolved !== undefined) return resolved;
475
- throw new Error(`Missing ${missingLabel} value: ${content}`);
476
- },
477
- );
656
+ return token.replace(/\{([^{}]+)\}/g, (_match, content: string) => {
657
+ const resolved = resolveCommandTemplateValue(
658
+ content,
659
+ values,
660
+ missingLabel,
661
+ depth,
662
+ );
663
+ if (resolved !== undefined) return resolved;
664
+ throw new Error(`Missing ${missingLabel} value: ${content}`);
665
+ });
478
666
  }
479
667
 
480
668
  export async function execCommandTemplate(
@@ -601,6 +789,7 @@ export function buildCommandTemplateInvocation(
601
789
  resolvedValues,
602
790
  options.missingLabel,
603
791
  ),
604
- );
792
+ )
793
+ .filter((part) => part !== "");
605
794
  return { command, args };
606
795
  }
package/lib/commands.ts CHANGED
@@ -307,6 +307,10 @@ export interface TelegramRuntimeEventRecorderPort {
307
307
  ) => void;
308
308
  }
309
309
 
310
+ export interface TelegramCompactConfirmationReplyMarkup {
311
+ inline_keyboard: { text: string; callback_data: string }[][];
312
+ }
313
+
310
314
  export interface TelegramCompactCommandDeps extends TelegramRuntimeEventRecorderPort {
311
315
  isIdle: () => boolean;
312
316
  hasPendingMessages: () => boolean;
@@ -327,6 +331,42 @@ export interface TelegramCompactCommandDeps extends TelegramRuntimeEventRecorder
327
331
  onError: (error: unknown) => void;
328
332
  }) => void;
329
333
  sendTextReply: (text: string) => Promise<void>;
334
+ suppressStartNotice?: boolean;
335
+ }
336
+
337
+ export interface TelegramCompactConfirmationDeps {
338
+ sendInteractiveMessage: (
339
+ chatId: number,
340
+ text: string,
341
+ mode: "html" | "plain",
342
+ replyMarkup: TelegramCompactConfirmationReplyMarkup,
343
+ ) => Promise<number | undefined>;
344
+ }
345
+
346
+ export interface TelegramCompactConfirmationCallbackQuery {
347
+ id: string;
348
+ data?: string;
349
+ message?: { chat?: { id?: number }; message_id?: number };
350
+ }
351
+
352
+ export interface TelegramCompactConfirmationCallbackDeps<TContext> {
353
+ ctx: TContext;
354
+ answerCallbackQuery: (
355
+ callbackQueryId: string,
356
+ text?: string,
357
+ ) => Promise<void>;
358
+ editInteractiveMessage: (
359
+ chatId: number,
360
+ messageId: number,
361
+ text: string,
362
+ mode: "html" | "plain",
363
+ replyMarkup: TelegramCompactConfirmationReplyMarkup,
364
+ ) => Promise<void>;
365
+ runCompact: (
366
+ ctx: TContext,
367
+ chatId: number,
368
+ replyToMessageId: number,
369
+ ) => Promise<void>;
330
370
  }
331
371
 
332
372
  export type TelegramControlCommandType =
@@ -580,6 +620,7 @@ export interface TelegramCommandRuntimeDeps<
580
620
  getPromptTemplateCommands?: () => readonly TelegramPromptTemplateMenuCommand[];
581
621
  persistConfig: () => Promise<void>;
582
622
  sendTextReply: (message: TMessage, text: string) => Promise<void>;
623
+ sendInteractiveMessage?: TelegramCompactConfirmationDeps["sendInteractiveMessage"];
583
624
  }
584
625
 
585
626
  export const TELEGRAM_APP_MENU_INTRO_HTML = [
@@ -784,6 +825,69 @@ function dispatchNextQueuedTelegramTurnAfterCompact(
784
825
  deps.dispatchNextQueuedTelegramTurn();
785
826
  }
786
827
 
828
+ export function buildTelegramCompactConfirmationReplyMarkup(): TelegramCompactConfirmationReplyMarkup {
829
+ return {
830
+ inline_keyboard: [
831
+ [
832
+ { text: "🗜 Yes, compact", callback_data: "compact:confirm" },
833
+ { text: "❌ No", callback_data: "compact:cancel" },
834
+ ],
835
+ ],
836
+ };
837
+ }
838
+
839
+ export function getTelegramCompactConfirmationHtml(): string {
840
+ return "<b>Compact session?</b>";
841
+ }
842
+
843
+ export async function openTelegramCompactConfirmation(
844
+ chatId: number,
845
+ deps: TelegramCompactConfirmationDeps,
846
+ ): Promise<void> {
847
+ await deps.sendInteractiveMessage(
848
+ chatId,
849
+ getTelegramCompactConfirmationHtml(),
850
+ "html",
851
+ buildTelegramCompactConfirmationReplyMarkup(),
852
+ );
853
+ }
854
+
855
+ export async function handleTelegramCompactConfirmationCallback<TContext>(
856
+ query: TelegramCompactConfirmationCallbackQuery,
857
+ deps: TelegramCompactConfirmationCallbackDeps<TContext>,
858
+ ): Promise<boolean> {
859
+ if (query.data !== "compact:confirm" && query.data !== "compact:cancel") {
860
+ return false;
861
+ }
862
+ const chatId = query.message?.chat?.id;
863
+ const messageId = query.message?.message_id;
864
+ if (typeof chatId !== "number" || typeof messageId !== "number") {
865
+ await deps.answerCallbackQuery(query.id, "Interactive message expired.");
866
+ return true;
867
+ }
868
+ if (query.data === "compact:cancel") {
869
+ await deps.editInteractiveMessage(
870
+ chatId,
871
+ messageId,
872
+ "Compaction cancelled.",
873
+ "plain",
874
+ { inline_keyboard: [] },
875
+ );
876
+ await deps.answerCallbackQuery(query.id);
877
+ return true;
878
+ }
879
+ await deps.editInteractiveMessage(
880
+ chatId,
881
+ messageId,
882
+ "Compaction started.",
883
+ "plain",
884
+ { inline_keyboard: [] },
885
+ );
886
+ await deps.answerCallbackQuery(query.id);
887
+ await deps.runCompact(deps.ctx, chatId, messageId);
888
+ return true;
889
+ }
890
+
787
891
  export async function handleTelegramCompactCommand(
788
892
  deps: TelegramCompactCommandDeps,
789
893
  ): Promise<void> {
@@ -834,7 +938,9 @@ export async function handleTelegramCompactCommand(
834
938
  await deps.sendTextReply(`Compaction failed: ${errorMessage}`);
835
939
  return;
836
940
  }
837
- await deps.sendTextReply("Compaction started.");
941
+ if (!deps.suppressStartNotice) {
942
+ await deps.sendTextReply("Compaction started.");
943
+ }
838
944
  if (compactionStillInProgress) deps.startTypingLoop?.();
839
945
  }
840
946
 
@@ -978,6 +1084,7 @@ export function createTelegramCommandHandlerTargetRuntime<
978
1084
  stopTypingLoop: deps.stopTypingLoop,
979
1085
  enqueueContinueTurn: deps.enqueueContinueTurn,
980
1086
  compact: deps.compact,
1087
+ sendInteractiveMessage: deps.sendInteractiveMessage,
981
1088
  enqueueControlItem: commandTargetRuntime.enqueueControlItem,
982
1089
  showStatus: commandTargetRuntime.showStatus,
983
1090
  openModelMenu: commandTargetRuntime.openModelMenu,
@@ -1110,6 +1217,12 @@ async function handleTelegramCommandRuntime<
1110
1217
  await deps.openQueueMenu(nextMessage, commandCtx);
1111
1218
  },
1112
1219
  handleCompact: async (nextMessage, commandCtx) => {
1220
+ if (deps.sendInteractiveMessage) {
1221
+ await openTelegramCompactConfirmation(nextMessage.chat.id, {
1222
+ sendInteractiveMessage: deps.sendInteractiveMessage,
1223
+ });
1224
+ return;
1225
+ }
1113
1226
  await handleTelegramCompactCommand({
1114
1227
  isIdle: () => deps.isIdle(commandCtx),
1115
1228
  hasPendingMessages: () => deps.hasPendingMessages(commandCtx),