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.
- package/DESIGN.md +189 -48
- package/README.ko.md +30 -16
- package/README.md +39 -20
- package/THIRD_PARTY_NOTICES.md +81 -6
- package/docs/OPERATIONS.md +178 -30
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +13 -7
- package/scripts/ci.ts +10 -5
- package/scripts/release.ts +14 -6
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +82 -241
- package/skills/head/references/model-selection.md +81 -261
- package/skills/head/references/routing.md +179 -354
- package/skills/head/references/supervision.md +120 -310
- package/skills/lane/SKILL.md +53 -175
- package/skills/lane/references/workflow.md +93 -347
- package/src/cli.ts +96 -10
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +77 -2
- package/src/contracts.ts +70 -6
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +10 -0
- package/src/discord-context.ts +118 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +312 -45
- package/src/extension.ts +178 -21
- package/src/gateway-client.ts +11 -4
- package/src/gateway-server.ts +52 -4
- package/src/gateway-store.ts +16 -2
- package/src/gateway.ts +27 -11
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +159 -47
- package/src/host-owner.ts +16 -0
- package/src/host-protocol.ts +9 -1
- package/src/host-services.ts +54 -0
- package/src/host.ts +3 -2
- package/src/installed-omp.ts +34 -26
- package/src/lane-extension.ts +5 -0
- package/src/lane-rows.ts +12 -0
- package/src/messengers.ts +38 -9
- package/src/native-presets.ts +91 -3
- package/src/native-settings.ts +3 -1
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/runtime.ts +419 -54
- package/src/slack.ts +14 -11
- package/src/store.ts +86 -30
- package/src/telegram.ts +28 -12
- 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 {
|
|
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("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
48
|
-
// Slack reserves
|
|
49
|
-
//
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
|
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
|
-
|
|
560
|
-
|
|
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
|
|
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,
|
|
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 {
|
|
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
|
-
|
|
258
|
-
|
|
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 =
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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 =
|
|
590
|
+
const token = approvalCardToken(approval);
|
|
576
591
|
const pending = this.pending.get(token);
|
|
577
592
|
if (pending) { pending.active = false; this.save(pending); }
|
|
578
|
-
|
|
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");
|
package/scripts/check-omp.ts
DELETED