omp-superagent 0.1.1 → 0.1.2

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 (60) hide show
  1. package/DESIGN.md +189 -48
  2. package/README.ko.md +30 -16
  3. package/README.md +39 -20
  4. package/THIRD_PARTY_NOTICES.md +81 -6
  5. package/docs/OPERATIONS.md +178 -30
  6. package/docs/discord-voice.md +96 -0
  7. package/docs/releases/0.1.2.md +53 -0
  8. package/package.json +13 -7
  9. package/scripts/ci.ts +10 -5
  10. package/scripts/release.ts +14 -6
  11. package/scripts/test-omp.sh +36 -0
  12. package/skills/head/SKILL.md +82 -241
  13. package/skills/head/references/model-selection.md +81 -261
  14. package/skills/head/references/routing.md +179 -354
  15. package/skills/head/references/supervision.md +120 -310
  16. package/skills/lane/SKILL.md +53 -175
  17. package/skills/lane/references/workflow.md +93 -347
  18. package/src/cli.ts +96 -10
  19. package/src/codex-live-bridge.py +73 -0
  20. package/src/codex-live.ts +244 -0
  21. package/src/codex-voice-requirements.txt +5 -0
  22. package/src/codex_live_auth.py +192 -0
  23. package/src/codex_live_media.py +219 -0
  24. package/src/codex_live_provider.py +192 -0
  25. package/src/config.ts +77 -2
  26. package/src/contracts.ts +70 -6
  27. package/src/decision-tool.ts +59 -0
  28. package/src/decisions.ts +143 -0
  29. package/src/delivery.ts +10 -0
  30. package/src/discord-context.ts +118 -0
  31. package/src/discord-voice-draft.ts +124 -0
  32. package/src/discord-voice-link.ts +270 -0
  33. package/src/discord-voice.ts +150 -0
  34. package/src/discord.ts +312 -45
  35. package/src/extension.ts +178 -21
  36. package/src/gateway-client.ts +11 -4
  37. package/src/gateway-server.ts +52 -4
  38. package/src/gateway-store.ts +16 -2
  39. package/src/gateway.ts +27 -11
  40. package/src/host-broker-services.ts +108 -0
  41. package/src/host-extension.ts +159 -47
  42. package/src/host-owner.ts +16 -0
  43. package/src/host-protocol.ts +9 -1
  44. package/src/host-services.ts +54 -0
  45. package/src/host.ts +3 -2
  46. package/src/installed-omp.ts +34 -26
  47. package/src/lane-extension.ts +5 -0
  48. package/src/lane-rows.ts +12 -0
  49. package/src/messengers.ts +38 -9
  50. package/src/native-presets.ts +91 -3
  51. package/src/native-settings.ts +3 -1
  52. package/src/openai-live.ts +377 -0
  53. package/src/pr-github-schema.ts +110 -0
  54. package/src/pr-github.ts +170 -0
  55. package/src/pr-watch.ts +200 -0
  56. package/src/runtime.ts +419 -54
  57. package/src/slack.ts +14 -11
  58. package/src/store.ts +86 -30
  59. package/src/telegram.ts +28 -12
  60. package/scripts/check-omp.ts +0 -4
package/src/slack.ts CHANGED
@@ -3,8 +3,10 @@ import { LogLevel, WebClient, type WebClientOptions } from "@slack/web-api";
3
3
  import { SocketModeClient } from "@slack/socket-mode";
4
4
  import { physicalRoute, physicalRouteKey, routeKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type Route } from "./contracts.ts";
5
5
  import { parseDialog, type Dialog } from "./dialog.ts";
6
- import { DeliveryError } from "./delivery.ts";
6
+ import { validateDecisionAnswer, validateDecisionResponse } from "./decisions";
7
+ import { approvalCardToken, DeliveryError } from "./delivery.ts";
7
8
  import { compareMessageIds } from "./message-order.ts";
9
+ import { MESSENGER_COMMANDS } from "./messenger-commands.ts";
8
10
  import { parseSlackCommand } from "./slack-commands.ts";
9
11
 
10
12
  type RecordValue = Record<string, unknown>;
@@ -45,13 +47,11 @@ const slackId = (value: unknown): value is string => string(value) && /^[A-Z][A-
45
47
  const hash = (value: string): string => createHash("sha256").update(value).digest("hex").slice(0, 24);
46
48
  const plain = (value: string) => ({ type: "plain_text", text: value || "(empty)", emoji: false });
47
49
  const escapeText = (value: string): string => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
48
- // Slack reserves leading slash commands in its composer. These are ordinary
49
- // authenticated owner messages, sharing the runtime's existing command parser,
50
- // including the head's bare query and argument forms of /model, /effort, /stop,
51
- // /compact, and the rest of the ordinary-text command surface.
52
- // Only an exact first token converts; lookalikes such as "!models" stay plain text.
53
- const controlText = (value: string): string => value.replace(/^!(new|main|stop|restart|resume|resolve|model|effort|help|status|context|compact|usage)(?=$|\s)/, "/$1");
54
- const tokenFor = (approval: Approval): string => hash(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)]));
50
+ // Slack reserves slash commands in its composer. Convert only an exact leading
51
+ // owner command, preserving argument whitespace and ignoring lookalikes.
52
+ const commandNames = new Set<string>(MESSENGER_COMMANDS.map(command => command.name));
53
+ const controlText = (value: string): string => value.replace(/^!(\S+)/, (token, name: string) =>
54
+ commandNames.has(name) ? `/${name}` : token);
55
55
  const compare = (left: string, right: string): number => {
56
56
  const result = compareMessageIds("slack", left, right);
57
57
  if (result === null) throw new DeliveryError("Invalid Slack message timestamp", "rejected");
@@ -445,7 +445,7 @@ export class SlackMessenger implements Messenger {
445
445
  async showApproval(approval: Approval): Promise<string> {
446
446
  await this.destination(approval.route);
447
447
  if (!this.handlers || approval.state !== "pending") throw new DeliveryError("Slack approval is not pending on a started messenger", "rejected");
448
- const token = tokenFor(approval);
448
+ const token = approvalCardToken(approval);
449
449
  const existing = this.pending.get(token);
450
450
  if (existing?.active && existing.messageId) {
451
451
  if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Slack approval receipt does not match its active card", "rejected");
@@ -482,7 +482,7 @@ export class SlackMessenger implements Messenger {
482
482
 
483
483
  async dismissApproval(approval: Approval): Promise<void> {
484
484
  this.assertRoute(approval.route);
485
- const token = tokenFor(approval);
485
+ const token = approvalCardToken(approval);
486
486
  let pending = this.pending.get(token);
487
487
  if (!pending && approval.remoteId) {
488
488
  let dialog: Dialog;
@@ -502,6 +502,7 @@ export class SlackMessenger implements Messenger {
502
502
  }
503
503
 
504
504
  private async finish(pending: Pending, response: DialogResponse): Promise<void> {
505
+ validateDecisionResponse(pending.approval, response);
505
506
  // Claim locally before persistence/host I/O. An ambiguous callback cannot
506
507
  // unlock the card for another answer; runtime remains native authority.
507
508
  pending.active = false;
@@ -642,7 +643,9 @@ export class SlackMessenger implements Messenger {
642
643
  pending.modal = undefined;
643
644
  if (!question.multi && pending.customInput !== undefined) pending.selected = [];
644
645
  } else if (!modal && actionName === `next-${pending.question}`) {
645
- pending.answers.push({ id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) });
646
+ const answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) };
647
+ if (pending.approval.decision) validateDecisionAnswer(question, answer);
648
+ pending.answers.push(answer);
646
649
  if (pending.question + 1 === dialog.questions.length) { await this.finish(pending, { answers: pending.answers }); await envelope.ack(); return; }
647
650
  pending.question++;
648
651
  pending.selected = [];
package/src/store.ts CHANGED
@@ -24,11 +24,14 @@ import { existsSync, mkdirSync, realpathSync } from "node:fs";
24
24
  import { basename, dirname, join, resolve } from "node:path";
25
25
  import { isDeepStrictEqual } from "node:util";
26
26
  import {
27
- physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
27
+ HEAD_MODEL_CONTROL, physicalRoute, physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
28
28
  type OutputRecord, type Route, type StorePort, type WorkflowActivation,
29
- type HeadRecoveryAttempt, type HeadRecoveryEffect,
29
+ type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect,
30
30
  } from "./contracts.ts";
31
- import { isLaneModel, sameLaneModel } from "./lane-models";
31
+ import type { ApprovalResolution } from "./contracts";
32
+ import { captureDecision, resolveDecision } from "./decisions";
33
+ import { isLaneModel, laneModelArgument, sameLaneModel } from "./lane-models";
34
+ import { readLaneRows, toLane } from "./lane-rows";
32
35
  import { workflowChoice } from "./workflow";
33
36
  import { laneWaitKey, type LaneReport } from "./lane-report";
34
37
 
@@ -45,6 +48,8 @@ const SCHEMA = `
45
48
  UNIQUE(target, generation, request_id)
46
49
  );
47
50
  CREATE INDEX IF NOT EXISTS inputs_queue ON inputs(target, state, sequence);
51
+ CREATE INDEX IF NOT EXISTS inputs_message_id ON inputs(json_extract(data, '$.messageId'))
52
+ WHERE json_type(data, '$.messageId') = 'text';
48
53
  CREATE TABLE IF NOT EXISTS lane_sources (
49
54
  source_id TEXT PRIMARY KEY REFERENCES inputs(id),
50
55
  lane_id TEXT NOT NULL REFERENCES lanes(id)
@@ -54,7 +59,7 @@ const SCHEMA = `
54
59
  source_id TEXT NOT NULL, route TEXT NOT NULL, text TEXT NOT NULL,
55
60
  state TEXT NOT NULL DEFAULT 'pending'
56
61
  CHECK(state IN ('pending','sending','sent','uncertain','failed')),
57
- remote_id TEXT, error TEXT
62
+ remote_id TEXT, error TEXT, reply_to TEXT
58
63
  );
59
64
  CREATE INDEX IF NOT EXISTS outputs_queue ON outputs(state, sequence);
60
65
  CREATE TABLE IF NOT EXISTS approvals (
@@ -66,6 +71,16 @@ const SCHEMA = `
66
71
  CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
67
72
  `;
68
73
 
74
+ const ADMITTED_MESSAGE_SCOPE = `FROM inputs
75
+ JOIN metadata ON metadata.key = 'user-source:' || inputs.id AND metadata.value = 'true'
76
+ WHERE json_type(inputs.data, '$.messageId') = 'text'
77
+ AND json_extract(inputs.data, '$.route.platform') = ?
78
+ AND json_extract(inputs.data, '$.route.channelId') = ?
79
+ AND json_extract(inputs.data, '$.route.accountId') = ?
80
+ AND json_extract(inputs.data, '$.route.authorityId') = ?
81
+ AND json_extract(inputs.data, '$.route.guildId') IS ?
82
+ AND json_extract(inputs.data, '$.route.threadId') IS ?`;
83
+
69
84
  interface InputRow {
70
85
  data: string;
71
86
  target: string | null;
@@ -77,6 +92,7 @@ interface OutputRow {
77
92
  id: string;
78
93
  source_id: string;
79
94
  route: string;
95
+ reply_to: string | null;
80
96
  text: string;
81
97
  state: OutputRecord["state"];
82
98
  remote_id: string | null;
@@ -91,27 +107,24 @@ const toInput = (row: InputRow): InputRecord => {
91
107
  };
92
108
  const toOutput = (row: OutputRow): OutputRecord => ({
93
109
  id: row.id, sourceId: row.source_id, route: JSON.parse(row.route) as Route,
110
+ ...(row.reply_to === null ? {} : { replyTo: JSON.parse(row.reply_to) as NonNullable<OutputRecord["replyTo"]> }),
94
111
  text: row.text, state: row.state, remoteId: row.remote_id, error: row.error,
95
112
  });
96
113
  const toApproval = (row: ApprovalRow): Approval => ({
97
114
  ...JSON.parse(row.data) as Approval, state: row.state, remoteId: row.remote_id,
98
115
  });
99
- const toLane = (row: { data: string }): Lane => {
100
- const lane = JSON.parse(row.data) as Lane;
101
- return { ...lane, model: lane.model ?? null, modelReason: lane.modelReason ?? null,
102
- modelPreset: lane.modelPreset ?? null, modelPresetSnapshot: lane.modelPresetSnapshot ?? null };
103
- };
104
116
  const inboundData = (input: Inbound): Inbound => ({
105
117
  id: input.id, route: input.route, messageId: input.messageId, text: input.text,
106
118
  ...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
107
119
  ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
108
120
  ...(input.reply === undefined ? {} : { reply: input.reply }),
121
+ ...(input.discordContext === undefined ? {} : { discordContext: input.discordContext }),
109
122
  receivedAt: input.receivedAt, attachments: input.attachments,
110
123
  });
111
124
  function inboundIdentity(input: Inbound) {
112
125
  // Referenced messages can be edited/deleted independently. A redelivery never
113
126
  // replaces the contextual snapshot admitted with the owner's original event.
114
- const { reply: _reply, ...data } = inboundData(input);
127
+ const { reply: _reply, discordContext: _context, ...data } = inboundData(input);
115
128
  return {
116
129
  ...data,
117
130
  // Slack supplies no command timestamp. A transport redelivery has a fresh
@@ -138,6 +151,7 @@ function inboundIdentity(input: Inbound) {
138
151
  const approvalIdentity = (approval: Approval) => ({
139
152
  id: approval.id, target: approval.target, generation: approval.generation,
140
153
  requestId: approval.requestId, route: approval.route, request: approval.request,
154
+ ...(approval.decision ? { decision: approval.decision } : {}),
141
155
  });
142
156
 
143
157
  export class Store implements StorePort {
@@ -167,6 +181,8 @@ export class Store implements StorePort {
167
181
  db.run("PRAGMA synchronous = FULL");
168
182
  db.run("PRAGMA foreign_keys = ON");
169
183
  db.run(SCHEMA);
184
+ const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
185
+ if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
170
186
  this.db = db;
171
187
  this.writerLock = lock;
172
188
  } catch (error) {
@@ -232,6 +248,15 @@ export class Store implements StorePort {
232
248
  return row ? toInput(row) : null;
233
249
  }
234
250
 
251
+ ownerSource(id: string): InputRecord | null {
252
+ let source = this.input(id);
253
+ while (source && this.getMeta(`user-source:${source.id}`) !== "true") {
254
+ const linked = this.getMeta(`handoff-source:${source.id}`) ?? this.getMeta(`activity-source:${source.id}`);
255
+ source = linked ? this.input(linked) : null;
256
+ }
257
+ return source;
258
+ }
259
+
235
260
  inputs(target?: string): InputRecord[] {
236
261
  const rows = this.db.query(`SELECT * FROM inputs
237
262
  WHERE state IN ('pending','submitted','uncertain') AND (?1 IS NULL OR target = ?1)
@@ -239,19 +264,21 @@ export class Store implements StorePort {
239
264
  return rows.map(toInput);
240
265
  }
241
266
 
242
- admittedMessages(route: Route): InputRecord[] {
243
- const rows = this.db.query(`SELECT inputs.* FROM inputs
244
- JOIN metadata ON metadata.key = 'user-source:' || inputs.id AND metadata.value = 'true'
245
- WHERE json_type(inputs.data, '$.messageId') = 'text'
246
- AND json_extract(inputs.data, '$.route.platform') = ?
247
- AND json_extract(inputs.data, '$.route.channelId') = ?
248
- AND json_extract(inputs.data, '$.route.accountId') = ?
249
- AND json_extract(inputs.data, '$.route.authorityId') = ?
250
- AND json_extract(inputs.data, '$.route.guildId') IS ?
251
- AND json_extract(inputs.data, '$.route.threadId') IS ?
252
- ORDER BY inputs.sequence`).all(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId) as InputRow[];
253
- const identity = physicalRouteKey(route);
254
- return rows.map(toInput).filter(input => physicalRouteKey(input.route) === identity);
267
+ firstAdmittedMessage(route: Route, messageId: string): InputRecord | null {
268
+ const row = this.db.query<InputRow, [string, string, string, string, string | null, string | null, string]>(
269
+ `SELECT inputs.* ${ADMITTED_MESSAGE_SCOPE}
270
+ AND json_extract(inputs.data, '$.messageId') = ?
271
+ ORDER BY inputs.sequence LIMIT 1`,
272
+ ).get(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, messageId);
273
+ return row ? toInput(row) : null;
274
+ }
275
+
276
+ *admittedMessageIds(route: Route): Iterable<string> {
277
+ const rows = this.db.query<{ messageId: string }, [string, string, string, string, string | null, string | null]>(
278
+ `SELECT json_extract(inputs.data, '$.messageId') AS messageId ${ADMITTED_MESSAGE_SCOPE}
279
+ ORDER BY inputs.sequence`,
280
+ ).iterate(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId);
281
+ for (const { messageId } of rows) yield messageId;
255
282
  }
256
283
 
257
284
  bindInput(id: string, target: string): void {
@@ -421,7 +448,7 @@ export class Store implements StorePort {
421
448
  }).immediate();
422
449
  }
423
450
 
424
- settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }): boolean {
451
+ settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }, headModel?: HeadModelChange): boolean {
425
452
  return this.db.transaction(() => {
426
453
  const input = this.input(id);
427
454
  if (!input || input.state === "done" || input.state === "cancelled" || input.state === state) return false;
@@ -454,6 +481,20 @@ export class Store implements StorePort {
454
481
  this.queueOutput({ ...output, sourceId: id, route: input.route });
455
482
  }
456
483
  this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
484
+ if (headModel && state === "done" && input.state === "submitted" && input.target === "main") {
485
+ const source = this.requireInput(headModel.sourceId);
486
+ if (source.state !== "done" || this.getMeta(`user-source:${source.id}`) !== "true"
487
+ || this.getMeta(`steering-owner:${source.id}`) !== input.id) {
488
+ throw new Error("Deferred HEAD model change lacks a completed original request");
489
+ }
490
+ const controlId = `head-model:${source.id}`;
491
+ this.receive({
492
+ id: controlId, route: source.route, messageId: source.messageId, receivedAt: source.receivedAt, attachments: [],
493
+ ...(source.interactionId === undefined ? {} : { interactionId: source.interactionId }),
494
+ ...(source.invocationId === undefined ? {} : { invocationId: source.invocationId }),
495
+ text: laneModelArgument(headModel.model),
496
+ }, "main", { [HEAD_MODEL_CONTROL]: controlId, [`activity-source:${controlId}`]: source.id });
497
+ }
457
498
  return true;
458
499
  }).immediate();
459
500
  }
@@ -549,15 +590,29 @@ export class Store implements StorePort {
549
590
  const existing = this.output(output.id);
550
591
  if (existing) {
551
592
  if (existing.sourceId !== output.sourceId || routeKey(existing.route) !== routeKey(output.route)
552
- || existing.text !== output.text) throw new Error(`Output identity conflict: ${output.id}`);
593
+ || existing.text !== output.text || output.replyTo !== undefined && (!existing.replyTo
594
+ || existing.replyTo.messageId !== output.replyTo.messageId
595
+ || physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
596
+ throw new Error(`Output identity conflict: ${output.id}`);
597
+ }
553
598
  return false;
554
599
  }
555
600
  const source = this.input(output.sourceId);
556
601
  if (source && routeKey(source.route) !== routeKey(output.route)) {
557
602
  throw new Error(`Output route differs from its source: ${output.id}`);
558
603
  }
559
- return this.db.query("INSERT INTO outputs(id, source_id, route, text) VALUES (?, ?, ?, ?)")
560
- .run(output.id, output.sourceId, JSON.stringify(output.route), output.text).changes === 1;
604
+ // Synthetic handoffs/reports can carry a copied messageId on a different
605
+ // route. Follow only durable source links, never that copy or ReplyContext.
606
+ const original = this.ownerSource(output.sourceId);
607
+ const replyTo = original?.route.platform === "discord" && original.messageId
608
+ && physicalRouteKey(original.route) === physicalRouteKey(output.route)
609
+ ? { route: physicalRoute(original.route), messageId: original.messageId } : undefined;
610
+ if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
611
+ || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
612
+ throw new Error(`Output reply differs from its source: ${output.id}`);
613
+ }
614
+ return this.db.query("INSERT INTO outputs(id, source_id, route, text, reply_to) VALUES (?, ?, ?, ?, ?)")
615
+ .run(output.id, output.sourceId, JSON.stringify(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null).changes === 1;
561
616
  }).immediate();
562
617
  }
563
618
 
@@ -646,8 +701,7 @@ export class Store implements StorePort {
646
701
  }
647
702
 
648
703
  lanes(): Lane[] {
649
- return (this.db.query("SELECT data FROM lanes ORDER BY rowid").all() as { data: string }[])
650
- .map(toLane);
704
+ return readLaneRows(this.db);
651
705
  }
652
706
 
653
707
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
@@ -726,6 +780,7 @@ export class Store implements StorePort {
726
780
  this.db.query("INSERT INTO approvals(id, target, generation, request_id, data, state, remote_id) VALUES (?, ?, ?, ?, ?, ?, ?)")
727
781
  .run(approval.id, approval.target, approval.generation, approval.requestId, JSON.stringify(approvalIdentity(approval)),
728
782
  approval.state, approval.remoteId);
783
+ captureDecision(this, approval);
729
784
  }).immediate();
730
785
  }
731
786
 
@@ -739,12 +794,13 @@ export class Store implements StorePort {
739
794
  AND (?1 IS NULL OR target = ?1) ORDER BY sequence`).all(target ?? null) as ApprovalRow[]).map(toApproval);
740
795
  }
741
796
 
742
- resolveApproval(id: string, generation: number, state: "answered" | "cancelled"): boolean {
797
+ resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean {
743
798
  return this.db.transaction(() => {
744
799
  const approval = this.approval(id);
745
800
  if (!approval || approval.state !== "pending" || approval.generation !== generation) return false;
746
801
  const lane = this.lane(approval.target);
747
802
  if (state === "answered" && lane && (lane.generation !== generation || lane.workState !== "open")) return false;
803
+ resolveDecision(this, approval, state, resolution);
748
804
  return this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
749
805
  .run(state, id, generation).changes === 1;
750
806
  }).immediate();
package/src/telegram.ts CHANGED
@@ -3,9 +3,10 @@ import { setTimeout as delay } from "node:timers/promises";
3
3
  import { Api, InputFile } from "grammy";
4
4
  import { AbortController as ApiAbortController, type AbortSignal as ApiAbortSignal } from "abort-controller";
5
5
  import type { CallbackQuery, Chat, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update, UserFromGetMe } from "grammy/types";
6
- import { physicalRouteKey, routeKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type ReplyContext, type Route, type StorePort } from "./contracts.ts";
6
+ import { physicalRouteKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type ReplyContext, type Route, type StorePort } from "./contracts.ts";
7
7
  import { parseDialog, type Dialog } from "./dialog.ts";
8
- import { DeliveryError } from "./delivery.ts";
8
+ import { validateDecisionAnswer, validateDecisionResponse } from "./decisions";
9
+ import { approvalCardToken, DeliveryError } from "./delivery.ts";
9
10
  import { MESSENGER_COMMANDS } from "./messenger-commands.ts";
10
11
 
11
12
  // grammY Api has no retry transformer installed. Only getUpdates is retried.
@@ -121,7 +122,6 @@ export class TelegramMessenger implements Messenger {
121
122
  return JSON.stringify({ id: file.id, name: file.name, url: file.url, size: file.size,
122
123
  ...(file.contentType ? { contentType: file.contentType } : {}) });
123
124
  }
124
- private approvalToken(approval: Approval): string { return hash(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)])); }
125
125
 
126
126
  async start(handlers: Handlers): Promise<void> {
127
127
  if (this.handlers) throw new DeliveryError("Telegram messenger is already started", "rejected");
@@ -254,8 +254,11 @@ export class TelegramMessenger implements Messenger {
254
254
  const reply = this.replyContext(message, route);
255
255
  // Preserve the existing owner-edit identity when optional context appears
256
256
  // after an adapter upgrade or an independently edited referenced message.
257
- const fileIdentity = files.map(({ voice: _voice, durationSeconds: _duration, ...file }) => file);
258
- const revision = message.edit_date === undefined ? "original" : `edit:${message.edit_date}:${hash(JSON.stringify([originalText, fileIdentity]))}`;
257
+ let revision = "original";
258
+ if (message.edit_date !== undefined) {
259
+ const fileIdentity = files.map(({ voice: _voice, durationSeconds: _duration, ...file }) => file);
260
+ revision = `edit:${message.edit_date}:${hash(JSON.stringify([originalText, fileIdentity]))}`;
261
+ }
259
262
  return { id: `telegram:${route.accountId}:${route.channelId}:${message.message_id}:${revision}`, route,
260
263
  messageId: String(message.message_id), text, receivedAt: (message.edit_date ?? message.date) * 1000, attachments: files,
261
264
  ...(reply ? { reply } : {}) };
@@ -407,7 +410,7 @@ export class TelegramMessenger implements Messenger {
407
410
  }
408
411
 
409
412
  async showApproval(approval: Approval): Promise<string> {
410
- const token = this.approvalToken(approval);
413
+ const token = approvalCardToken(approval);
411
414
  const existing = this.approvalFlights.get(token);
412
415
  if (existing) return existing;
413
416
  const flight = this.approvalCard(approval);
@@ -419,7 +422,7 @@ export class TelegramMessenger implements Messenger {
419
422
  private async approvalCard(approval: Approval): Promise<string> {
420
423
  this.assertRoute(approval.route);
421
424
  if (!this.handlers || approval.state !== "pending") throw new DeliveryError("Telegram approval is not pending on an active messenger", "rejected");
422
- const token = this.approvalToken(approval);
425
+ const token = approvalCardToken(approval);
423
426
  const existing = this.pending.get(token);
424
427
  if (existing?.active && existing.verified && existing.messageId) {
425
428
  if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Telegram approval receipt conflict", "rejected");
@@ -522,6 +525,7 @@ export class TelegramMessenger implements Messenger {
522
525
  } catch (error) { if (!notModified(error)) throw telegramDeliveryError(error); }
523
526
  }
524
527
  private async finish(pending: Pending, response: DialogResponse, eventId: string): Promise<void> {
528
+ validateDecisionResponse(pending.approval, response);
525
529
  pending.active = false; pending.lastUpdate = eventId;
526
530
  pending.answerRequest = hash(JSON.stringify(pending.approval.request)); this.save(pending);
527
531
  try { await this.handlers!.answer(pending.approval.id, response, pending.approval.route); }
@@ -531,8 +535,8 @@ export class TelegramMessenger implements Messenger {
531
535
  private async callback(query: CallbackQuery): Promise<void> {
532
536
  const parsed = /^omp:([a-f0-9]{24}):([a-z]+[0-9]*(?:-[0-9]+)?)$/.exec(query.data ?? "");
533
537
  const pending = parsed ? this.pending.get(parsed[1]!) : undefined;
534
- const reject = async () => {
535
- try { await this.api.answerCallbackQuery(query.id, { text: "This request is expired, unauthorized, or already being handled." }); }
538
+ const reject = async (text = "This request is expired, unauthorized, or already being handled.") => {
539
+ try { await this.api.answerCallbackQuery(query.id, { text }); }
536
540
  catch (error) { this.report(telegramDeliveryError(error)); }
537
541
  };
538
542
  if (!parsed || query.from.is_bot || String(query.from.id) !== this.options.ownerId || !pending?.active || !pending.verified || pending.busy || !this.handlers ||
@@ -559,7 +563,18 @@ export class TelegramMessenger implements Messenger {
559
563
  pending.selected = question.multi ? (pending.selected.includes(option.label) ? pending.selected.filter(value => value !== option.label) : [...pending.selected, option.label]) : [option.label];
560
564
  if (!question.multi) pending.customInput = undefined;
561
565
  } else if (action === `next-${pending.question}`) {
562
- pending.answers.push({ id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) });
566
+ const answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) };
567
+ if (pending.approval.decision) {
568
+ try { validateDecisionAnswer(question, answer); }
569
+ catch (error) {
570
+ if (!(error instanceof DeliveryError) || error.certainty !== "rejected") throw error;
571
+ // Definitive rejection is a consumed callback, not a polling
572
+ // failure: retain the draft while allowing the next update.
573
+ await reject("Choose an option or enter an answer before continuing.");
574
+ return;
575
+ }
576
+ }
577
+ pending.answers.push(answer);
563
578
  pending.question++; pending.selected = []; pending.customInput = undefined;
564
579
  if (pending.question === dialog.questions.length) { await this.finish(pending, { answers: pending.answers }, eventId); return; }
565
580
  } else { await reject(); return; }
@@ -572,10 +587,11 @@ export class TelegramMessenger implements Messenger {
572
587
 
573
588
  async dismissApproval(approval: Approval): Promise<void> {
574
589
  this.assertRoute(approval.route);
575
- const token = this.approvalToken(approval);
590
+ const token = approvalCardToken(approval);
576
591
  const pending = this.pending.get(token);
577
592
  if (pending) { pending.active = false; this.save(pending); }
578
- const saved = this.options.store.getMeta(this.stateKey(token));
593
+ // save() already erased partial answers for the in-memory card.
594
+ const saved = pending ? null : this.options.store.getMeta(this.stateKey(token));
579
595
  const progress = saved ? JSON.parse(saved) as Progress : undefined;
580
596
  const id = approval.remoteId ?? pending?.messageId ?? progress?.messageId;
581
597
  if (id) this.options.store.setMeta(this.cardKey(approval.route, id), "closed");
@@ -1,4 +0,0 @@
1
- import { inspectInstalledOmp } from "../src/installed-omp";
2
-
3
- const omp = await inspectInstalledOmp();
4
- console.log(`Installed stock OMP ${omp.version} (${omp.supported}; tested ${omp.testedVersion})`);