omp-superagent 0.1.17 → 0.1.19
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 +15 -12
- package/config.example.json +4 -1
- package/docs/OPERATIONS.en.md +205 -59
- package/docs/OPERATIONS.md +173 -47
- package/docs/design/execution.md +119 -37
- package/docs/design/messaging.md +160 -45
- package/docs/releases/0.1.18.md +10 -0
- package/docs/releases/0.1.19.md +10 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +1 -1
- package/skills/head/SKILL.md +6 -5
- package/skills/head/references/model-selection.md +8 -22
- package/skills/head/references/routing.md +36 -17
- package/skills/lane/SKILL.md +24 -76
- package/skills/lane/references/workflow.md +7 -94
- package/src/cli.ts +36 -16
- package/src/config/config.ts +21 -2
- package/src/contracts.ts +66 -7
- package/src/cron/cron-jobs.ts +135 -92
- package/src/cron/cron-pr-intake.ts +18 -11
- package/src/extension.ts +25 -10
- package/src/gateway/gateway-client.ts +3 -1
- package/src/host-extension.ts +76 -8
- package/src/lane/lane-report.ts +1 -1
- package/src/lane/lane-rows.ts +2 -1
- package/src/lane/workflow.ts +12 -6
- package/src/lane-extension.ts +4 -21
- package/src/managed-super-probe.ts +21 -15
- package/src/messaging/messenger-command-catalog.json +1 -1
- package/src/messaging/messenger-commands.ts +8 -3
- package/src/messaging/result-attachment.ts +77 -19
- package/src/messaging/slack-context.ts +50 -0
- package/src/messaging/written-directives.ts +56 -0
- package/src/omp/exit-record.ts +27 -0
- package/src/omp/host-protocol.ts +20 -0
- package/src/omp/host.ts +73 -20
- package/src/omp/installed-omp.ts +15 -12
- package/src/omp/managed-super.ts +135 -65
- package/src/omp/superkit-skills.ts +15 -2
- package/src/pr/pr-intake-order.ts +62 -0
- package/src/pr/pr-intake-review.ts +49 -31
- package/src/pr/pr-intake-work.ts +3 -2
- package/src/routing/message-order.ts +22 -1
- package/src/routing/topic-request.ts +48 -4
- package/src/runtime/controller.ts +968 -338
- package/src/runtime/deferred-routing.ts +12 -4
- package/src/runtime/dm-timeline.ts +3 -3
- package/src/runtime/inbound-attachments.ts +70 -0
- package/src/runtime/local-host-fence.ts +85 -0
- package/src/runtime/model-journal.ts +14 -9
- package/src/runtime/native-frames.ts +5 -1
- package/src/runtime/result-attachments.ts +151 -24
- package/src/runtime/worker-result-download.ts +36 -0
- package/src/storage/deferred-routing.ts +25 -4
- package/src/storage/store.ts +445 -75
- package/src/worker/worker-checkout.ts +89 -9
- package/src/worker/worker-destination.ts +8 -7
- package/src/worker/worker-doctor.ts +29 -9
- package/src/worker/worker-enrollment.ts +44 -12
- package/src/worker/worker-git-startup.ts +157 -0
- package/src/worker/worker-host.ts +16 -26
- package/src/worker/worker-ledger.ts +42 -18
- package/src/worker/worker-placement-intent.ts +13 -0
- package/src/worker/worker-placement.ts +204 -28
- package/src/worker/worker-profile.ts +18 -65
- package/src/worker/worker-project-startup.ts +106 -0
- package/src/worker/worker-registration.ts +85 -30
- package/src/worker/worker-repository.ts +55 -6
- package/src/worker/worker-request.ts +13 -6
- package/src/worker/worker-result-attachments.ts +185 -0
- package/src/worker/worker-result-wire.ts +12 -0
- package/src/worker/worker-service.ts +51 -23
- package/src/worker/worker-trust.ts +19 -4
- package/src/worker/worker-wire.ts +47 -14
- package/upstream/super.json +2 -3
package/src/storage/store.ts
CHANGED
|
@@ -26,25 +26,71 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
26
26
|
import {
|
|
27
27
|
HEAD_MODEL_CONTROL, headRecoveryEffectsSettled, isRetiredScopeInput, laneFallbackKey, laneModelPickerRestoreKey, physicalRoute, physicalRouteKey, resolvePickerOption, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
|
|
28
28
|
type ActiveInputState, type KickoffHold, type OutputRecord, type Route, type SettlementOutput, type StorePort, type WorkflowActivation,
|
|
29
|
-
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope,
|
|
29
|
+
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope, type LocalHostIdentity,
|
|
30
30
|
} from "../contracts.ts";
|
|
31
31
|
import type { ApprovalResolution } from "../contracts";
|
|
32
32
|
import { captureDecision, resolveDecision } from "../lane/decisions";
|
|
33
33
|
import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
|
|
34
34
|
import { laneData, readLaneRows, toLane, type LaneRow } from "../lane/lane-rows";
|
|
35
|
-
import { compareMessageIds } from "../routing/message-order";
|
|
35
|
+
import { compareMessageIds, slackOutputTimestamp, slackWorkspaceQuestionTimestamp } from "../routing/message-order";
|
|
36
|
+
import { hasWorkerCurrentHeader, readWorkerCurrentDirective } from "../messaging/written-directives";
|
|
36
37
|
import { storedWorkflowName, workflowChoice } from "../lane/workflow";
|
|
37
38
|
import { laneWaitKey, type LaneReport } from "../lane/lane-report";
|
|
38
39
|
import { laneWatchReplySource } from "../lane/lane-watch";
|
|
39
40
|
import { discordWorkThreadOwnerKey, recordedDiscordWorkThreadSource } from "../messaging/discord-work-thread";
|
|
40
|
-
import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
|
|
41
|
-
import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
|
|
41
|
+
import { isOriginalAttachmentMessage, isResultAttachmentSnapshot } from "../messaging/result-attachment";
|
|
42
|
+
import { existingWorkspace, matchingSlackHistoryChoice, slackWorkspaceAnswer, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
|
|
42
43
|
import type { CronUpdate } from "../cron/cron-jobs";
|
|
43
44
|
import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
|
|
44
45
|
import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
|
|
46
|
+
import { matchesWorkerCurrentPlacement } from "../worker/worker-placement-intent";
|
|
45
47
|
import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
|
|
46
48
|
|
|
47
49
|
const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
|
|
50
|
+
const SLACK_JOINED_RETRY = "slack:joined-retry:";
|
|
51
|
+
const SLACK_JOINED_REJECTED_AT = "gateway:slack-joined-rejected-at:";
|
|
52
|
+
const SLACK_JOINED_RETRY_LIMIT = 2;
|
|
53
|
+
const SLACK_JOINED_FENCES = `WITH fences AS (
|
|
54
|
+
SELECT fence.physical_route, min(fence.sequence) AS sequence
|
|
55
|
+
FROM metadata AS retry JOIN outputs AS fence ON fence.id = substr(retry.key, ${SLACK_JOINED_RETRY.length + 1})
|
|
56
|
+
WHERE retry.key GLOB '${SLACK_JOINED_RETRY}*' AND fence.state = 'pending' AND json_extract(retry.value, '$.at') > ?
|
|
57
|
+
GROUP BY fence.physical_route
|
|
58
|
+
)`;
|
|
59
|
+
interface SlackJoinedRetry {
|
|
60
|
+
readonly count: number;
|
|
61
|
+
readonly at?: number;
|
|
62
|
+
readonly priorAttemptIds?: readonly string[];
|
|
63
|
+
}
|
|
64
|
+
interface GatewaySendAttempt {
|
|
65
|
+
readonly id: string;
|
|
66
|
+
readonly arguments: string;
|
|
67
|
+
readonly result: string | null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function gatewaySendSuccess(result: unknown): string | null {
|
|
71
|
+
return result && typeof result === "object" && "value" in result && typeof result.value === "string"
|
|
72
|
+
&& isDeepStrictEqual(result, { ok: true, value: result.value }) ? result.value : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseGatewaySendResult(receipt: string): unknown {
|
|
76
|
+
// Preserve the Rust u64 token before rounding can merge valid and invalid delays.
|
|
77
|
+
return JSON.parse(receipt, (key, value: unknown, context?: { source?: string }) => {
|
|
78
|
+
const token = context?.source;
|
|
79
|
+
return key === "retryAfterMs" && token && /^(?:0|[1-9]\d{0,19})$/u.test(token) ? BigInt(token) : value;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function gatewaySendRejection(result: unknown): { readonly retryAfterMs?: number } | null {
|
|
84
|
+
if (!result || typeof result !== "object" || !("error" in result) || typeof result.error !== "string") return null;
|
|
85
|
+
const rejection = { ok: false, certainty: "rejected", error: result.error };
|
|
86
|
+
if (!("retryAfterMs" in result)) return isDeepStrictEqual(result, rejection) ? {} : null;
|
|
87
|
+
const retryAfterMs = result.retryAfterMs;
|
|
88
|
+
if (typeof retryAfterMs !== "bigint" || retryAfterMs > 18_446_744_073_709_551_615n
|
|
89
|
+
|| !isDeepStrictEqual(result, { ...rejection, retryAfterMs })) return null;
|
|
90
|
+
// Gateway emits a u64. A delay outside the scheduler's safe range does
|
|
91
|
+
// not turn definitive non-delivery into an uncertain remote effect.
|
|
92
|
+
return retryAfterMs <= BigInt(Number.MAX_SAFE_INTEGER) ? { retryAfterMs: Number(retryAfterMs) } : {};
|
|
93
|
+
}
|
|
48
94
|
const retiredScopeId = (column: "id" | "source_id" | "retired.id" | "newer.id") =>
|
|
49
95
|
`(${column} GLOB 'scope-review:*' OR ${column} GLOB 'handoff:scope-review:*')`;
|
|
50
96
|
|
|
@@ -145,8 +191,10 @@ const inboundData = (input: Inbound): Inbound => ({
|
|
|
145
191
|
id: input.id, route: input.route, messageId: input.messageId, text: input.text,
|
|
146
192
|
...(input.discordOriginalText === undefined ? {} : { discordOriginalText: input.discordOriginalText }),
|
|
147
193
|
...(input.routingText === undefined ? {} : { routingText: input.routingText }),
|
|
194
|
+
...(input.slackVerifiedRoutingBody === true ? { slackVerifiedRoutingBody: true } : {}),
|
|
148
195
|
...(input.telegramProtectedCommand === undefined ? {} : { telegramProtectedCommand: input.telegramProtectedCommand }),
|
|
149
196
|
...(input.telegramOriginalText === undefined ? {} : { telegramOriginalText: input.telegramOriginalText }),
|
|
197
|
+
...(input.ownerWrittenPrefix === undefined ? {} : { ownerWrittenPrefix: input.ownerWrittenPrefix }),
|
|
150
198
|
...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
|
|
151
199
|
...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
|
|
152
200
|
...(input.pickerSelection === undefined ? {} : { pickerSelection: input.pickerSelection }),
|
|
@@ -158,7 +206,8 @@ const inboundData = (input: Inbound): Inbound => ({
|
|
|
158
206
|
function inboundIdentity(input: Inbound) {
|
|
159
207
|
// Derived routing text and independently edited references do not change the
|
|
160
208
|
// event identity. Keep the first snapshot, including on pre-upgrade replay.
|
|
161
|
-
const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText,
|
|
209
|
+
const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText,
|
|
210
|
+
slackVerifiedRoutingBody: _slackVerifiedRoutingBody, ownerWrittenPrefix: _ownerWrittenPrefix, ...data } = inboundData(input);
|
|
162
211
|
return {
|
|
163
212
|
...data,
|
|
164
213
|
// Slack supplies no command timestamp. A transport redelivery has a fresh
|
|
@@ -364,7 +413,7 @@ export class Store implements StorePort {
|
|
|
364
413
|
const selection = input.pickerSelection;
|
|
365
414
|
if (selection ? input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
|
|
366
415
|
|| input.id !== `picker:${selection.outputId}` || target !== "main"
|
|
367
|
-
|| selection.target !== undefined && (input.route.platform !== "discord" || selection.confirmed !== undefined
|
|
416
|
+
|| selection.target !== undefined && (input.route.platform !== "discord" && input.route.platform !== "slack" || selection.confirmed !== undefined
|
|
368
417
|
|| (selection.target !== "head" && selection.target !== "lane"))
|
|
369
418
|
: input.interactionId !== undefined && (input.route.platform !== "discord" || typeof input.interactionId !== "string" || !/^[1-9]\d{0,19}$/.test(input.interactionId))
|
|
370
419
|
|| (input.invocationId !== undefined && !slackInvocation)
|
|
@@ -378,7 +427,7 @@ export class Store implements StorePort {
|
|
|
378
427
|
receivePrWork(input: Inbound, target: string | null, r: ReviewRound): boolean {
|
|
379
428
|
const parent = { ...input.route, threadId: null };
|
|
380
429
|
const offer = this.output(`cron-pr:offer:${r.repository}:${r.number}`);
|
|
381
|
-
if (!r.automation || input.route.platform !== "discord" || !input.route.guildId || input.route.topicId !== undefined
|
|
430
|
+
if (!r.automation || (input.route.platform !== "discord" && input.route.platform !== "slack") || !input.route.guildId || input.route.topicId !== undefined
|
|
382
431
|
|| input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
|
|
383
432
|
|| input.pickerSelection || input.attachments.length || input.discordOriginalText !== undefined || input.reply
|
|
384
433
|
|| this.getMeta(`user-source:${input.id}`) !== null || r.automation.anchor !== input.route.threadId
|
|
@@ -544,6 +593,45 @@ export class Store implements StorePort {
|
|
|
544
593
|
return { source, route, outputSourceId };
|
|
545
594
|
}
|
|
546
595
|
|
|
596
|
+
resultAttachmentDelivery(id: string): ReturnType<StorePort["topicDelivery"]> {
|
|
597
|
+
const topic = this.topicDelivery(id);
|
|
598
|
+
const input = this.input(id);
|
|
599
|
+
const lane = input?.target && input.target !== "main" ? this.lane(input.target) : null;
|
|
600
|
+
const linked = this.getMeta(`handoff-source:${id}`);
|
|
601
|
+
const source = topic?.source ?? (linked === null ? null : this.input(linked));
|
|
602
|
+
if (!input || !source) return null;
|
|
603
|
+
const current = hasWorkerCurrentHeader(source.text);
|
|
604
|
+
if (!lane?.remote) return current ? null : topic;
|
|
605
|
+
if (this.getMeta(`user-source:${source.id}`) !== "true" || !isOriginalAttachmentMessage(source)
|
|
606
|
+
|| source.state === "cancelled" || source.state === "uncertain") return null;
|
|
607
|
+
|
|
608
|
+
const destination = topic?.route ?? lane.route;
|
|
609
|
+
const sourceKey = routeKey(source.route);
|
|
610
|
+
const sameRoute = sourceKey === routeKey(destination);
|
|
611
|
+
const opening = (current || !topic || !sameRoute) && this.confirmedOpening(source, input, lane);
|
|
612
|
+
if (current || !topic) {
|
|
613
|
+
const continuation = current && id === `handoff:${source.id}:${lane.id}` && linked === source.id
|
|
614
|
+
&& sourceKey === routeKey(lane.route) && routeKey(input.route) === sourceKey;
|
|
615
|
+
if (source.target !== "main" || !opening && !continuation) return null;
|
|
616
|
+
if (current) {
|
|
617
|
+
const directive = readWorkerCurrentDirective(source);
|
|
618
|
+
if (!directive || !matchesWorkerCurrentPlacement(directive, lane.remote)) return null;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// Text can follow a selected or reconciled work topic. File consent extends
|
|
623
|
+
// only to the exact native child created and confirmed for this parent input.
|
|
624
|
+
if (!sameRoute && opening && source.route.threadId === null && source.route.topicId === undefined
|
|
625
|
+
&& destination.threadId !== null && sourceKey === routeKey({ ...destination, threadId: null })) {
|
|
626
|
+
const created = this.getMeta(`handoff-route-result:${source.id}`);
|
|
627
|
+
if (created !== null && isDeepStrictEqual(JSON.parse(created), destination))
|
|
628
|
+
return { source, route: destination, outputSourceId: id };
|
|
629
|
+
}
|
|
630
|
+
// An explicit worker-current source is tied to its selected same-context
|
|
631
|
+
// opening or continuation. Ordinary files can return to their own topic.
|
|
632
|
+
return current && !sameRoute ? null : { source, route: source.route, outputSourceId: source.id };
|
|
633
|
+
}
|
|
634
|
+
|
|
547
635
|
hasTopicAdmission(target: string, generation: number): boolean {
|
|
548
636
|
const rows = this.db.query<InputRow, [string, number]>(
|
|
549
637
|
"SELECT * FROM inputs WHERE target = ? AND generation = ? AND request_id IS NOT NULL",
|
|
@@ -554,48 +642,71 @@ export class Store implements StorePort {
|
|
|
554
642
|
|
|
555
643
|
hasPendingTopicChoice(input: InputRecord, deadline: number): boolean {
|
|
556
644
|
const { platform, accountId, authorityId, guildId, channelId, threadId } = input.route;
|
|
557
|
-
if (platform !== "
|
|
645
|
+
if (threadId === null || platform !== "slack" && (platform !== "discord" || guildId === null)) return false;
|
|
558
646
|
// An input already ACKed to Gateway but still awaiting deferred topic routing
|
|
559
647
|
// has no head receipt yet either; it fences the choice like a pending ledger row.
|
|
560
648
|
const deferred = this.deferredRouting.choices(input, deadline);
|
|
561
649
|
// Gateway creates the shared ingress ledger; standalone Store use has none.
|
|
562
650
|
const ledger = this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get() !== null;
|
|
563
651
|
const questionId = `${input.id}:workspace`;
|
|
652
|
+
const slackQuestionTs = slackWorkspaceQuestionTimestamp(this, input);
|
|
564
653
|
const choices: readonly { readonly cwd: string }[] = JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]");
|
|
565
654
|
// The Gateway pending index skips delivered history, including terminal rejections.
|
|
566
655
|
// Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
|
|
567
656
|
// fences a timely-authored choice even when transport-delayed.
|
|
568
|
-
const rows = ledger ? this.db.query<DeferredChoiceRow, [number, number, string, string, string, string, string, string, string]>(`
|
|
657
|
+
const rows = ledger ? this.db.query<DeferredChoiceRow, [number, number, string, string, string, string, string | null, string, string]>(`
|
|
569
658
|
SELECT json_extract(data, '$.input.id') AS id,
|
|
570
659
|
json_extract(data, '$.input.text') AS text,
|
|
660
|
+
json_extract(data, '$.input.routingText') AS routingText,
|
|
661
|
+
json_type(data, '$.input.slackVerifiedRoutingBody') IS 'true' AS verifiedSlackBody,
|
|
571
662
|
json_extract(data, '$.input.messageId') AS messageId,
|
|
572
663
|
json_extract(data, '$.input.reply.messageId') AS replyId,
|
|
573
|
-
json_extract(data, '$.input.receivedAt') AS authoredAt
|
|
664
|
+
json_extract(data, '$.input.receivedAt') AS authoredAt,
|
|
665
|
+
coalesce(json_extract(data, '$.input.unresolvedReply'), 0)
|
|
666
|
+
OR json_type(data, '$.input.attachments') IS NOT 'array'
|
|
667
|
+
OR json_array_length(data, '$.input.attachments') > 0 AS attached
|
|
574
668
|
FROM gateway_events INDEXED BY gateway_events_pending WHERE delivered_at IS NULL
|
|
575
669
|
AND json_extract(data, '$.kind') = 'message'
|
|
576
670
|
AND json_type(data, '$.input.pickerSelection') IS NULL
|
|
577
671
|
AND (json_type(data, '$.input.messageId') = 'text'
|
|
578
672
|
OR json_type(data, '$.input.interactionId') = 'text')
|
|
579
|
-
AND json_type(data, '$.input.receivedAt') = 'integer'
|
|
673
|
+
AND (json_type(data, '$.input.receivedAt') = 'integer'
|
|
674
|
+
OR json_extract(data, '$.input.route.platform') = 'slack' AND json_type(data, '$.input.receivedAt') = 'real')
|
|
580
675
|
AND json_extract(data, '$.input.receivedAt') BETWEEN ? AND ?
|
|
581
676
|
AND json_extract(data, '$.input.id') <> ?
|
|
582
677
|
AND json_extract(data, '$.input.route.platform') = ?
|
|
583
678
|
AND json_extract(data, '$.input.route.accountId') = ?
|
|
584
679
|
AND json_extract(data, '$.input.route.authorityId') = ?
|
|
585
|
-
AND json_extract(data, '$.input.route.guildId')
|
|
680
|
+
AND json_extract(data, '$.input.route.guildId') IS ?
|
|
586
681
|
AND json_extract(data, '$.input.route.channelId') = ?
|
|
587
682
|
AND json_extract(data, '$.input.route.threadId') = ?
|
|
588
683
|
`) : null;
|
|
589
684
|
const pending = rows?.iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId) ?? [];
|
|
590
685
|
for (const candidates of [deferred, pending]) {
|
|
591
686
|
for (const row of candidates) {
|
|
592
|
-
|
|
687
|
+
const scope = platform === "slack" ? `${accountId}:${channelId}` : accountId;
|
|
688
|
+
if (row.messageId !== null && row.id.startsWith(`${platform}:${scope}:${row.messageId}:edit:`)) continue;
|
|
593
689
|
const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
|
|
594
690
|
const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
|
|
595
|
-
if (!questionReply && row.authoredAt < deadline - TOPIC_CHOICE_WAIT_MS) continue;
|
|
596
691
|
const text = row.text.trim();
|
|
597
|
-
|
|
692
|
+
const locallyTimely = questionReply || row.authoredAt >= deadline - TOPIC_CHOICE_WAIT_MS;
|
|
693
|
+
if (text === "/stop") {
|
|
694
|
+
if (locallyTimely) return true;
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
598
697
|
if (row.messageId === null || row.replyId !== null && !scopedReply || /^\/new(?:\s|$)/.test(text)) continue;
|
|
698
|
+
if (platform === "slack") {
|
|
699
|
+
// Slack may publish the exact question before HEAD commits its receipt.
|
|
700
|
+
// All manual answers use message order, not the local start of the window.
|
|
701
|
+
if (!slackQuestionTs || row.replyId !== null || row.attached || !/^\d{1,20}\.\d{6}$/u.test(row.messageId)
|
|
702
|
+
|| compareMessageIds("slack", row.messageId, slackQuestionTs) !== 1) continue;
|
|
703
|
+
const answer = slackWorkspaceAnswer(row.text, row.routingText, row.verifiedSlackBody === 1);
|
|
704
|
+
if (!answer || answer.source !== null && (answer.source !== input.messageId
|
|
705
|
+
|| this.firstAdmittedMessage(input.route, answer.source)?.id !== input.id)) continue;
|
|
706
|
+
if (matchingSlackHistoryChoice(answer.text, answer.cwd, choices)) return true;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (!locallyTimely) continue;
|
|
599
710
|
if (/^[1-9]\d*$/.test(text)) return true;
|
|
600
711
|
const request = topicRequest(text);
|
|
601
712
|
if (request.cwd === null ? !scopedReply : request.text.trim()) continue;
|
|
@@ -616,6 +727,7 @@ export class Store implements StorePort {
|
|
|
616
727
|
if (!Number.isSafeInteger(deadline) || Date.now() < deadline
|
|
617
728
|
|| current?.state !== "pending" || current.target !== null || routeKey(current.route) !== routeKey(input.route)
|
|
618
729
|
|| this.getMeta(`topic-choice-deadline:${input.id}`) !== String(deadline)
|
|
730
|
+
|| JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]").length === 0
|
|
619
731
|
|| this.getMeta(`topic-previous:${input.id}`) !== null || this.getMeta(automatic) !== null
|
|
620
732
|
|| this.hasPendingTopicChoice(current, deadline)) return false;
|
|
621
733
|
this.setMeta(automatic, pin);
|
|
@@ -769,13 +881,30 @@ export class Store implements StorePort {
|
|
|
769
881
|
.get(messageId, this.getMeta(`discord:output-part:${messageId}`), route.accountId, route.authorityId, route.guildId, route.channelId) !== null;
|
|
770
882
|
}
|
|
771
883
|
|
|
884
|
+
hasSlackHistoryChoice(route: Route, number: number, authoredAt: number, excludeSourceId?: string): boolean {
|
|
885
|
+
if (route.platform !== "slack" || route.threadId === null) return false;
|
|
886
|
+
// A lone late digit is ambiguous just after expiry. Once a later question
|
|
887
|
+
// is open, only overlapping answer windows can make its selection ambiguous.
|
|
888
|
+
const lateGrace = excludeSourceId === undefined ? TOPIC_CHOICE_WAIT_MS : 0;
|
|
889
|
+
return this.db.query(`SELECT 1 FROM outputs
|
|
890
|
+
JOIN metadata AS options ON options.key = 'topic-history:' || outputs.source_id
|
|
891
|
+
JOIN metadata AS deadline ON deadline.key = 'topic-choice-deadline:' || outputs.source_id
|
|
892
|
+
WHERE outputs.physical_route = ? AND outputs.state = 'sent' AND outputs.id = outputs.source_id || ':workspace'
|
|
893
|
+
AND json_array_length(options.value) >= ? AND CAST(deadline.value AS INTEGER) - ? <= ?
|
|
894
|
+
AND ? <= CAST(deadline.value AS INTEGER) + ?
|
|
895
|
+
AND outputs.source_id IS NOT ?
|
|
896
|
+
LIMIT 1`).get(physicalRouteKey(route), number, TOPIC_CHOICE_WAIT_MS, authoredAt, authoredAt, lateGrace, excludeSourceId ?? null) !== null;
|
|
897
|
+
}
|
|
898
|
+
|
|
772
899
|
sentOutputForMessage(route: Route, messageId: string): OutputRecord | null {
|
|
773
900
|
const scoped = this.outputReceiptsForMessage(route, messageId).filter(output => output.state === "sent");
|
|
774
901
|
return scoped.length === 1 ? scoped[0] ?? null : null;
|
|
775
902
|
}
|
|
776
903
|
|
|
777
904
|
private outputReceiptsForMessage(route: Route, messageId: string): OutputRecord[] {
|
|
778
|
-
const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`)
|
|
905
|
+
const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`)
|
|
906
|
+
: route.platform === "slack" ? this.getMeta(`slack:output-part:${JSON.stringify([route.accountId, route.channelId, messageId])}`)
|
|
907
|
+
: null;
|
|
779
908
|
// The Gateway can know a completed multipart send before this controller
|
|
780
909
|
// durably records its confirmation. Such a part identifies, but does not prove, placement.
|
|
781
910
|
const rows = this.db.query<OutputRow, [string, string | null]>(
|
|
@@ -877,22 +1006,26 @@ export class Store implements StorePort {
|
|
|
877
1006
|
if (!origin || origin.target !== "main") return null;
|
|
878
1007
|
const handoff = this.input(`handoff:${sourceId}:lane`);
|
|
879
1008
|
if (!handoff && this.getMeta(`handoff-intent:${sourceId}`) === null) return null;
|
|
880
|
-
|
|
881
|
-
|
|
1009
|
+
const lane = handoff?.target ? this.lane(handoff.target) : null;
|
|
1010
|
+
if (!lane || !handoff || this.getMeta(`user-source:${origin.id}`) !== "true" || !this.confirmedOpening(origin, handoff, lane)
|
|
1011
|
+
|| (lane.route.topicId ? physicalRouteKey(origin.route) !== physicalRouteKey(lane.route)
|
|
1012
|
+
: physicalRouteKey({ ...origin.route, threadId: null }) !== physicalRouteKey({ ...lane.route, threadId: null }))) return "unverified";
|
|
1013
|
+
return lane;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
private confirmedOpening(origin: InputRecord, handoff: InputRecord, lane: Lane): boolean {
|
|
1017
|
+
if (handoff.id !== `handoff:${origin.id}:lane` || this.getMeta(`handoff-source:${handoff.id}`) !== origin.id
|
|
1018
|
+
|| handoff.target !== lane.id || routeKey(handoff.route) !== routeKey(lane.route)) return false;
|
|
882
1019
|
// lane_start registers its exact creation source here; lane_message only
|
|
883
1020
|
// enqueues another input. The deterministic handoff ID alone is not proof.
|
|
884
1021
|
const binding = this.db.query<{ lane_id: string }, [string]>(
|
|
885
1022
|
"SELECT lane_id FROM lane_sources WHERE source_id = ?",
|
|
886
1023
|
).get(handoff.id);
|
|
887
|
-
|
|
888
|
-
if (!lane || handoff.target !== lane.id || routeKey(handoff.route) !== routeKey(lane.route)
|
|
889
|
-
|| (lane.route.topicId ? physicalRouteKey(origin.route) !== physicalRouteKey(lane.route)
|
|
890
|
-
: physicalRouteKey({ ...origin.route, threadId: null }) !== physicalRouteKey({ ...lane.route, threadId: null }))) return "unverified";
|
|
1024
|
+
if (binding?.lane_id !== lane.id) return false;
|
|
891
1025
|
const kickoffId = `${origin.id}:kickoff`;
|
|
892
1026
|
const kickoff = this.output(kickoffId);
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
return lane;
|
|
1027
|
+
return this.getMeta(`kickoff-output:${handoff.id}`) === kickoffId && kickoff?.state === "sent" && !!kickoff.remoteId
|
|
1028
|
+
&& kickoff.sourceId === handoff.id && routeKey(kickoff.route) === routeKey(lane.route);
|
|
896
1029
|
}
|
|
897
1030
|
|
|
898
1031
|
*admittedMessageIds(route: Route): Iterable<string> {
|
|
@@ -943,7 +1076,7 @@ export class Store implements StorePort {
|
|
|
943
1076
|
this.setMeta(`steering-topic-reply:${owner.id}`, JSON.stringify(topic.route));
|
|
944
1077
|
}
|
|
945
1078
|
}
|
|
946
|
-
if (submitted && lane?.route.platform === "
|
|
1079
|
+
if (submitted && lane?.route.threadId && (lane.route.platform === "slack" || lane.route.platform === "discord" && lane.route.guildId)) {
|
|
947
1080
|
if (ownerId === null || ownerId === id) this.setMeta(`lane-latest-run:${lane.id}`, id);
|
|
948
1081
|
}
|
|
949
1082
|
return submitted;
|
|
@@ -1030,7 +1163,7 @@ export class Store implements StorePort {
|
|
|
1030
1163
|
}
|
|
1031
1164
|
|
|
1032
1165
|
/**
|
|
1033
|
-
* When opted in on Discord (`editInPlace`), nonterminal progress uses one
|
|
1166
|
+
* When opted in on Discord or Slack (`editInPlace`), nonterminal progress uses one
|
|
1034
1167
|
* `⏳` status message edited in place. Each update stays its own immutable
|
|
1035
1168
|
* output; `claimOutput` decides whether it edits that message. By default (or
|
|
1036
1169
|
* on other platforms), every update posts as an ordinary new message.
|
|
@@ -1040,9 +1173,12 @@ export class Store implements StorePort {
|
|
|
1040
1173
|
stream: string,
|
|
1041
1174
|
editInPlace = false,
|
|
1042
1175
|
): boolean {
|
|
1043
|
-
if (!editInPlace || output.route.platform !== "discord") return this.queueOutput(output);
|
|
1044
|
-
this.setMeta(`status-stream:${output.id}`, stream);
|
|
1176
|
+
if (!editInPlace || output.route.platform !== "discord" && output.route.platform !== "slack") return this.queueOutput(output);
|
|
1045
1177
|
const text = /^(?:`{3,}|~{3,})/.test(output.text.trimStart()) ? `⏳\n${output.text}` : `⏳ ${output.text}`;
|
|
1178
|
+
// The Slack status marker is a single 3,000 UTF-16 unit section. Let the
|
|
1179
|
+
// ordinary Slack output path split or upload longer updates instead.
|
|
1180
|
+
if (output.route.platform === "slack" && text.length > 3_000) return this.queueOutput(output);
|
|
1181
|
+
this.setMeta(`status-stream:${output.id}`, stream);
|
|
1046
1182
|
return this.queueOutput({ ...output, text, status: true });
|
|
1047
1183
|
}
|
|
1048
1184
|
|
|
@@ -1279,10 +1415,11 @@ export class Store implements StorePort {
|
|
|
1279
1415
|
this.queueOutput({ ...output, sourceId: id, route: input.route });
|
|
1280
1416
|
}
|
|
1281
1417
|
} else if (this.queueOutput({ ...output, sourceId: id, route: input.route })
|
|
1282
|
-
&& settlement?.
|
|
1283
|
-
&& input.target === "main" && input.route.platform === "discord"
|
|
1418
|
+
&& settlement?.headFollowups?.length && state === "done" && input.state === "submitted"
|
|
1419
|
+
&& input.target === "main" && (input.route.platform === "discord" || input.route.platform === "slack")
|
|
1420
|
+
&& output.id === `${id}:answer`
|
|
1284
1421
|
&& !output.picker && output.text.trim() && this.ownerSource(id)?.id === id) {
|
|
1285
|
-
this.setMeta(
|
|
1422
|
+
this.setMeta(`${input.route.platform}-head-followups:${output.id}`, JSON.stringify(settlement.headFollowups));
|
|
1286
1423
|
}
|
|
1287
1424
|
}
|
|
1288
1425
|
this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
|
|
@@ -1426,7 +1563,7 @@ export class Store implements StorePort {
|
|
|
1426
1563
|
const { route } = input;
|
|
1427
1564
|
const fromExactParent = input.target && source.target === "main" && !source.pickerSelection
|
|
1428
1565
|
&& this.getMeta(`handoff-source:${input.id}`) === source.id && this.getMeta(`user-source:${source.id}`) === "true"
|
|
1429
|
-
&& route.platform === "discord" && route.guildId && route.threadId && route.topicId === undefined
|
|
1566
|
+
&& (route.platform === "discord" && route.guildId || route.platform === "slack") && route.threadId && route.topicId === undefined
|
|
1430
1567
|
&& routeKey({ ...route, threadId: null }) === routeKey(source.route) && this.laneForRoute(route)?.id === input.target;
|
|
1431
1568
|
if (handoffReply !== null) {
|
|
1432
1569
|
if (!fromExactParent || input.id !== `handoff:${source.id}:${input.target}` || routeKey(route) !== handoffReply)
|
|
@@ -1454,8 +1591,8 @@ export class Store implements StorePort {
|
|
|
1454
1591
|
|
|
1455
1592
|
queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
|
|
1456
1593
|
if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) return false;
|
|
1457
|
-
if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
|
|
1458
|
-
throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
|
|
1594
|
+
if (output.status && (output.route.platform !== "discord" && output.route.platform !== "slack" || output.picker || output.resultAttachment)) {
|
|
1595
|
+
throw new Error(`Status delivery requires a plain Discord or Slack message: ${output.id}`);
|
|
1459
1596
|
}
|
|
1460
1597
|
return this.db.transaction(() => {
|
|
1461
1598
|
const existing = this.output(output.id);
|
|
@@ -1467,6 +1604,7 @@ export class Store implements StorePort {
|
|
|
1467
1604
|
|| output.replyTo !== undefined && (!existing.replyTo
|
|
1468
1605
|
|| existing.replyTo.messageId !== output.replyTo.messageId
|
|
1469
1606
|
|| existing.replyTo.requireExisting !== output.replyTo.requireExisting
|
|
1607
|
+
|| existing.replyTo.joinedAnswerId !== output.replyTo.joinedAnswerId
|
|
1470
1608
|
|| physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
|
|
1471
1609
|
throw new Error(`Output identity conflict: ${output.id}`);
|
|
1472
1610
|
}
|
|
@@ -1484,7 +1622,7 @@ export class Store implements StorePort {
|
|
|
1484
1622
|
if (!isResultAttachmentSnapshot(attachment.payload))
|
|
1485
1623
|
throw new Error(`A new result attachment requires a native snapshot receipt: ${output.id}`);
|
|
1486
1624
|
const native = this.input(attachment.inputId);
|
|
1487
|
-
const topic = native && this.
|
|
1625
|
+
const topic = native && this.resultAttachmentDelivery(native.id);
|
|
1488
1626
|
const runId = native && this.getMeta(`steering-owner:${native.id}`);
|
|
1489
1627
|
const run = runId && this.input(runId);
|
|
1490
1628
|
const ownership = run && this.getMeta(`${native?.target === "main" ? "head-native-owner" : "lane-observation-owner"}:${run.id}`);
|
|
@@ -1496,15 +1634,19 @@ export class Store implements StorePort {
|
|
|
1496
1634
|
|| owner.generation !== attachment.generation || owner.sessionId !== attachment.sessionId
|
|
1497
1635
|
|| owner.sessionFile !== attachment.sessionFile
|
|
1498
1636
|
|| (topic ? topic.source.id !== original.id || topic.outputSourceId !== output.sourceId || routeKey(topic.route) !== routeKey(output.route)
|
|
1499
|
-
: native.target !== "main" || native.id !== original.id || native.id !== output.sourceId)) {
|
|
1637
|
+
: native.target !== "main" || native.id !== original.id || native.id !== output.sourceId || hasWorkerCurrentHeader(original.text))) {
|
|
1500
1638
|
throw new Error(`Result attachment does not match its original native request: ${output.id}`);
|
|
1501
1639
|
}
|
|
1502
1640
|
}
|
|
1503
1641
|
const replyOrigin = original ?? laneWatchReplySource(this, source, output.id);
|
|
1504
|
-
const
|
|
1642
|
+
const joinedAnswerId = output.replyTo?.joinedAnswerId;
|
|
1643
|
+
const slackLink = replyOrigin?.route.platform === "slack" && output.route.platform === "slack"
|
|
1644
|
+
&& joinedAnswerId !== undefined && output.replyTo?.requireExisting === true && !output.text && !output.status && !output.picker && !attachment;
|
|
1645
|
+
const replyTo = (replyOrigin?.route.platform === "discord" && joinedAnswerId === undefined || slackLink) && replyOrigin?.messageId
|
|
1505
1646
|
&& physicalRouteKey(replyOrigin.route) === physicalRouteKey(output.route)
|
|
1506
1647
|
? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId,
|
|
1507
|
-
...(output.replyTo?.requireExisting ? { requireExisting: true } : {})
|
|
1648
|
+
...(output.replyTo?.requireExisting ? { requireExisting: true } : {}),
|
|
1649
|
+
...(slackLink ? { joinedAnswerId } : {}) } : undefined;
|
|
1508
1650
|
if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
|
|
1509
1651
|
|| physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
|
|
1510
1652
|
throw new Error(`Output reply differs from its source: ${output.id}`);
|
|
@@ -1557,12 +1699,18 @@ export class Store implements StorePort {
|
|
|
1557
1699
|
}
|
|
1558
1700
|
|
|
1559
1701
|
outputs(physicalRoute?: string): OutputRecord[] {
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1702
|
+
const route = physicalRoute === undefined ? "" : "AND outputs.physical_route = ?";
|
|
1703
|
+
return this.db.query<OutputRow, string[]>(`SELECT * FROM outputs
|
|
1704
|
+
WHERE state = 'pending' ${route} ORDER BY sequence`)
|
|
1705
|
+
.all(...(physicalRoute === undefined ? [] : [physicalRoute])).map(toOutput);
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
deliverableOutputs(physicalRoute?: string): OutputRecord[] {
|
|
1709
|
+
const route = physicalRoute === undefined ? "" : "AND outputs.physical_route = ?";
|
|
1710
|
+
return this.db.query<OutputRow, [number, ...string[]]>(`${SLACK_JOINED_FENCES}
|
|
1711
|
+
SELECT outputs.* FROM outputs LEFT JOIN fences USING (physical_route)
|
|
1712
|
+
WHERE outputs.state = 'pending' AND (fences.sequence IS NULL OR outputs.sequence < fences.sequence) ${route}
|
|
1713
|
+
ORDER BY outputs.sequence`).all(Date.now(), ...(physicalRoute === undefined ? [] : [physicalRoute])).map(toOutput);
|
|
1566
1714
|
}
|
|
1567
1715
|
|
|
1568
1716
|
hasUnresolvedHeadDelivery(): boolean {
|
|
@@ -1654,6 +1802,9 @@ export class Store implements StorePort {
|
|
|
1654
1802
|
}
|
|
1655
1803
|
const output = this.output(id);
|
|
1656
1804
|
if (output?.state !== "pending") return false;
|
|
1805
|
+
if (output.route.platform === "slack" && this.db.query(`${SLACK_JOINED_FENCES}
|
|
1806
|
+
SELECT 1 FROM outputs JOIN fences USING (physical_route)
|
|
1807
|
+
WHERE outputs.id = ? AND outputs.sequence >= fences.sequence`).get(Date.now(), id)) return false;
|
|
1657
1808
|
if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) {
|
|
1658
1809
|
// Only the existing immutable answer can be sent. Do not consult live
|
|
1659
1810
|
// lane/HEAD ownership or mutate its historical reply/edit destination.
|
|
@@ -1674,11 +1825,46 @@ export class Store implements StorePort {
|
|
|
1674
1825
|
this.db.query("UPDATE outputs SET edit_of = ? WHERE id = ?")
|
|
1675
1826
|
.run(JSON.stringify({ route: physicalRoute(output.route), messageId: anchor.remoteId }), id);
|
|
1676
1827
|
}
|
|
1828
|
+
if (this.isSlackJoinedNotice(output)) {
|
|
1829
|
+
const retry = this.slackJoinedRetry(id);
|
|
1830
|
+
const prior = this.hasGatewayEffects() ? this.gatewaySendAttempts(id, SLACK_JOINED_RETRY_LIMIT + 1) : [];
|
|
1831
|
+
// While claimed, this fixes the pre-existing effects. A previous
|
|
1832
|
+
// retry's receipt cannot stand in for a new claim that never reached IPC.
|
|
1833
|
+
this.setMeta(`${SLACK_JOINED_RETRY}${id}`, JSON.stringify({
|
|
1834
|
+
...retry, priorAttemptIds: prior.map(attempt => attempt.id),
|
|
1835
|
+
}));
|
|
1836
|
+
}
|
|
1677
1837
|
return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'")
|
|
1678
1838
|
.run(id).changes === 1;
|
|
1679
1839
|
}).immediate();
|
|
1680
1840
|
}
|
|
1681
1841
|
|
|
1842
|
+
private isSlackJoinedNotice(output: OutputRecord): boolean {
|
|
1843
|
+
return output.remoteId === null && output.route.platform === "slack"
|
|
1844
|
+
&& Boolean(output.replyTo?.joinedAnswerId) && output.replyTo?.requireExisting === true && !output.text
|
|
1845
|
+
&& !output.resultAttachment && !output.status && !output.picker && !output.editOf;
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
private slackJoinedRetry(id: string): SlackJoinedRetry {
|
|
1849
|
+
const retry = this.getMeta(`${SLACK_JOINED_RETRY}${id}`);
|
|
1850
|
+
return retry === null ? { count: 0 } : JSON.parse(retry);
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
deferSlackJoinedOutput(id: string, delayMs: number): boolean {
|
|
1854
|
+
return this.db.transaction(() => {
|
|
1855
|
+
const output = this.output(id);
|
|
1856
|
+
if (output?.state !== "sending" || !this.isSlackJoinedNotice(output)) return false;
|
|
1857
|
+
return this.recordSlackJoinedRetry(id, this.slackJoinedRetry(id).count, Date.now(), delayMs);
|
|
1858
|
+
}).immediate();
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
private recordSlackJoinedRetry(id: string, count: number, completedAt: number, delayMs: number): boolean {
|
|
1862
|
+
const at = completedAt + Math.max(1000, delayMs);
|
|
1863
|
+
if (count >= SLACK_JOINED_RETRY_LIMIT || !Number.isSafeInteger(delayMs) || delayMs < 0 || !Number.isSafeInteger(at)) return false;
|
|
1864
|
+
this.setMeta(`${SLACK_JOINED_RETRY}${id}`, JSON.stringify({ at, count: count + 1 }));
|
|
1865
|
+
return this.db.query("UPDATE outputs SET state = 'pending', error = NULL WHERE id = ? AND state = 'sending'").run(id).changes === 1;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1682
1868
|
finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void {
|
|
1683
1869
|
this.db.transaction(() => {
|
|
1684
1870
|
const output = this.output(id);
|
|
@@ -1703,8 +1889,10 @@ export class Store implements StorePort {
|
|
|
1703
1889
|
}
|
|
1704
1890
|
this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
|
|
1705
1891
|
.run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
|
|
1706
|
-
if (state
|
|
1707
|
-
this.
|
|
1892
|
+
if (state !== "pending" && output.route.platform === "slack" && output.replyTo?.joinedAnswerId)
|
|
1893
|
+
this.db.query("DELETE FROM metadata WHERE key = ?").run(`${SLACK_JOINED_RETRY}${id}`);
|
|
1894
|
+
if (state === "sent" && remoteId && (output.route.platform === "discord" || output.route.platform === "slack")) {
|
|
1895
|
+
this.queueHeadFollowupLinks(output, remoteId);
|
|
1708
1896
|
}
|
|
1709
1897
|
const stream = this.getMeta(`status-stream:${id}`);
|
|
1710
1898
|
if (stream) {
|
|
@@ -1718,17 +1906,30 @@ export class Store implements StorePort {
|
|
|
1718
1906
|
this.db.query("DELETE FROM metadata WHERE key = ?").run(anchorKey);
|
|
1719
1907
|
}
|
|
1720
1908
|
}
|
|
1721
|
-
|
|
1722
|
-
// never with input admission or an unconfirmed send attempt.
|
|
1723
|
-
if (state === "sent" && id === `${output.sourceId}:workspace`
|
|
1724
|
-
&& this.getMeta(`topic-history:${output.sourceId}`) !== null && !this.getMeta(`topic-creator:${output.sourceId}`)) {
|
|
1725
|
-
this.setMeta(`topic-choice-deadline:${output.sourceId}`, String(Date.now() + TOPIC_CHOICE_WAIT_MS));
|
|
1726
|
-
}
|
|
1909
|
+
if (state === "sent") this.startTopicChoiceDeadline({ ...output, state, remoteId: remoteId ?? output.remoteId });
|
|
1727
1910
|
}).immediate();
|
|
1728
1911
|
}
|
|
1729
1912
|
|
|
1730
|
-
private
|
|
1731
|
-
const key = `
|
|
1913
|
+
private startTopicChoiceDeadline(output: OutputRecord): void {
|
|
1914
|
+
const key = `topic-choice-deadline:${output.sourceId}`;
|
|
1915
|
+
if (output.id !== `${output.sourceId}:workspace` || this.getMeta(`topic-creator:${output.sourceId}`)
|
|
1916
|
+
|| JSON.parse(this.getMeta(`topic-history:${output.sourceId}`) ?? "[]").length === 0 || this.getMeta(key) !== null) return;
|
|
1917
|
+
let confirmedAt = Date.now();
|
|
1918
|
+
if (output.route.platform === "slack") {
|
|
1919
|
+
const source = this.input(output.sourceId);
|
|
1920
|
+
const post = source && this.slackPlainPostTimestamp(output, source);
|
|
1921
|
+
if (!post) return;
|
|
1922
|
+
// The clock is the last verified physical post, not IPC return or
|
|
1923
|
+
// recovery time. Round up to whole milliseconds for the saved deadline.
|
|
1924
|
+
confirmedAt = Number((BigInt(post.replace(".", "")) + 999n) / 1000n);
|
|
1925
|
+
}
|
|
1926
|
+
const deadline = confirmedAt + TOPIC_CHOICE_WAIT_MS;
|
|
1927
|
+
if (Number.isSafeInteger(deadline)) this.setMeta(key, String(deadline));
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
private queueHeadFollowupLinks(output: OutputRecord, remoteId: string): void {
|
|
1931
|
+
const { platform } = output.route;
|
|
1932
|
+
const key = `${platform}-head-followups:${output.id}`;
|
|
1732
1933
|
const saved = this.getMeta(key);
|
|
1733
1934
|
if (!saved) return;
|
|
1734
1935
|
const owner = this.input(output.sourceId);
|
|
@@ -1736,31 +1937,40 @@ export class Store implements StorePort {
|
|
|
1736
1937
|
const guild = output.route.guildId;
|
|
1737
1938
|
const channel = output.route.threadId ?? output.route.channelId;
|
|
1738
1939
|
const snowflake = /^\d{1,20}$/u;
|
|
1940
|
+
const slack = platform === "slack";
|
|
1941
|
+
const messageId = slack ? /^\d{1,20}\.\d{6}$/u : snowflake;
|
|
1739
1942
|
if (owner?.target !== "main" || owner.state !== "done"
|
|
1740
|
-
|| (owner.messageId === null ? !owner.interactionId || target !== undefined
|
|
1741
|
-
|
|
1742
|
-
|
|
1943
|
+
|| (owner.messageId === null ? !(slack ? owner.invocationId : owner.interactionId) || target !== undefined
|
|
1944
|
+
: !slack && target?.messageId !== owner.messageId)
|
|
1945
|
+
|| !slack && (!snowflake.test(channel) || guild !== null && !snowflake.test(guild))) return;
|
|
1946
|
+
if (!messageId.test(remoteId)) {
|
|
1947
|
+
// A file receipt confirms publication, not an exact Slack message.
|
|
1948
|
+
if (slack && remoteId.startsWith("file:")) this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
const url = slack ? null : `https://discord.com/channels/${guild ?? "@me"}/${channel}/${remoteId}`;
|
|
1743
1952
|
const physical = new Set(owner.messageId === null ? [] : [owner.messageId]);
|
|
1744
1953
|
for (const id of JSON.parse(saved) as string[]) {
|
|
1745
1954
|
const source = this.input(id);
|
|
1746
1955
|
if (source?.target !== "main" || source.state !== "done" || source.generation !== owner.generation
|
|
1747
|
-
|| !source.messageId || !
|
|
1956
|
+
|| !source.messageId || !messageId.test(source.messageId) || physical.has(source.messageId)
|
|
1748
1957
|
|| routeKey(source.route) !== routeKey(output.route) || this.ownerSource(id)?.id !== id
|
|
1749
1958
|
|| this.getMeta(`steering-owner:${id}`) !== owner.id) continue;
|
|
1750
1959
|
physical.add(source.messageId);
|
|
1751
1960
|
this.queueOutput({ id: `${output.id}:joined:${id}`, sourceId: id, route: source.route,
|
|
1752
|
-
replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true
|
|
1753
|
-
|
|
1961
|
+
replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true,
|
|
1962
|
+
...(slack ? { joinedAnswerId: remoteId } : {}) },
|
|
1963
|
+
text: url ? `이 후속 메시지와 함께 처리한 [HEAD 통합 답변](<${url}>)` : "" });
|
|
1754
1964
|
}
|
|
1755
1965
|
// Commit the canonical send receipt and its dependent notices together.
|
|
1756
1966
|
this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
|
|
1757
1967
|
}
|
|
1758
1968
|
|
|
1759
|
-
createLane(lane: Lane & { model: LaneModel
|
|
1760
|
-
if (!isLaneModel(lane.model)
|
|
1969
|
+
createLane(lane: Lane & { model: LaneModel }, sourceId: string): Lane {
|
|
1970
|
+
if (!isLaneModel(lane.model)
|
|
1761
1971
|
|| (lane.modelPreset !== null && (typeof lane.modelPreset !== "string" || !lane.modelPreset.trim() || !lane.modelPresetSnapshot))
|
|
1762
1972
|
|| (lane.modelPreset === null && lane.modelPresetSnapshot !== null)) {
|
|
1763
|
-
throw new Error("A new lane requires an exact model and a
|
|
1973
|
+
throw new Error("A new lane requires an exact model and a matching preset snapshot when using a preset");
|
|
1764
1974
|
}
|
|
1765
1975
|
return this.db.transaction(() => {
|
|
1766
1976
|
const source = this.requireInput(sourceId);
|
|
@@ -1791,7 +2001,7 @@ export class Store implements StorePort {
|
|
|
1791
2001
|
if (!existing) {
|
|
1792
2002
|
this.db.query("INSERT INTO lanes(id, route_key, generation, data, remote) VALUES (?, ?, ?, ?, ?)")
|
|
1793
2003
|
.run(lane.id, routeKey(lane.route), lane.generation, laneData({
|
|
1794
|
-
...lane, model: { provider: lane.model.provider, id: lane.model.id },
|
|
2004
|
+
...lane, model: { provider: lane.model.provider, id: lane.model.id }, modelReason: lane.modelReason?.trim() || null,
|
|
1795
2005
|
}), lane.remote ? JSON.stringify(lane.remote) : null);
|
|
1796
2006
|
}
|
|
1797
2007
|
this.db.query("INSERT INTO lane_sources(source_id, lane_id) VALUES (?, ?)").run(sourceId, selected.id);
|
|
@@ -1815,13 +2025,13 @@ export class Store implements StorePort {
|
|
|
1815
2025
|
}
|
|
1816
2026
|
|
|
1817
2027
|
updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
|
|
1818
|
-
"workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
|
|
2028
|
+
"workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result" | "localOwner"
|
|
1819
2029
|
>>): boolean {
|
|
1820
2030
|
return this.db.transaction(() => {
|
|
1821
2031
|
const lane = this.lane(id);
|
|
1822
2032
|
if (!lane || lane.generation !== generation) return false;
|
|
1823
2033
|
// Explicitly copy the contract whitelist; runtime callers cannot change identity.
|
|
1824
|
-
for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
|
|
2034
|
+
for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result", "localOwner"] as const) {
|
|
1825
2035
|
if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
|
|
1826
2036
|
}
|
|
1827
2037
|
return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
@@ -1829,13 +2039,18 @@ export class Store implements StorePort {
|
|
|
1829
2039
|
}).immediate();
|
|
1830
2040
|
}
|
|
1831
2041
|
|
|
1832
|
-
retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath"
|
|
2042
|
+
retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath" | "localOwner">, orphan?: LocalHostIdentity): boolean {
|
|
1833
2043
|
return this.db.transaction(() => {
|
|
1834
2044
|
const lane = this.lane(expected.id);
|
|
1835
2045
|
if (!lane || lane.remote || expected.pid === null || lane.generation !== expected.generation
|
|
1836
|
-
|| lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath
|
|
2046
|
+
|| lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath
|
|
2047
|
+
|| lane.localOwner?.journalHeld || !isDeepStrictEqual(lane.localOwner, expected.localOwner)) return false;
|
|
2048
|
+
if (orphan) {
|
|
2049
|
+
if (orphan.pid !== lane.pid || orphan.sessionId !== lane.sessionId || orphan.sessionFile !== lane.sessionFile) return false;
|
|
2050
|
+
lane.localOwner = { ...orphan, journalHeld: true };
|
|
2051
|
+
} else delete lane.localOwner;
|
|
1837
2052
|
lane.pid = null;
|
|
1838
|
-
if (lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
|
|
2053
|
+
if (orphan || lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
|
|
1839
2054
|
return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
1840
2055
|
.run(laneData(lane), lane.id, lane.generation).changes === 1;
|
|
1841
2056
|
}).immediate();
|
|
@@ -1843,7 +2058,7 @@ export class Store implements StorePort {
|
|
|
1843
2058
|
|
|
1844
2059
|
private sentLaneModelPicker(source: InputRecord) {
|
|
1845
2060
|
const selection = source.pickerSelection;
|
|
1846
|
-
if (source.route.platform !== "discord" || selection?.target !== "lane" || selection.confirmed !== undefined
|
|
2061
|
+
if ((source.route.platform !== "discord" && source.route.platform !== "slack") || selection?.target !== "lane" || selection.confirmed !== undefined
|
|
1847
2062
|
|| source.id !== `picker:${selection.outputId}`) return null;
|
|
1848
2063
|
const card = this.output(selection.outputId);
|
|
1849
2064
|
const picker = card?.picker;
|
|
@@ -1859,6 +2074,8 @@ export class Store implements StorePort {
|
|
|
1859
2074
|
nextGeneration(id: string, pickerRestoreSourceId?: string): Lane {
|
|
1860
2075
|
return this.db.transaction(() => {
|
|
1861
2076
|
const lane = this.requireLane(id);
|
|
2077
|
+
if (lane.localOwner?.journalHeld) throw new Error("The original local Host journal is unverified; refusing relaunch");
|
|
2078
|
+
delete lane.localOwner;
|
|
1862
2079
|
const restoreKey = pickerRestoreSourceId === undefined ? null : laneModelPickerRestoreKey(pickerRestoreSourceId);
|
|
1863
2080
|
if (pickerRestoreSourceId !== undefined && restoreKey) {
|
|
1864
2081
|
const source = this.input(pickerRestoreSourceId);
|
|
@@ -1913,11 +2130,11 @@ export class Store implements StorePort {
|
|
|
1913
2130
|
}).immediate();
|
|
1914
2131
|
}
|
|
1915
2132
|
|
|
1916
|
-
changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason:
|
|
2133
|
+
changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: Lane["modelReason"],
|
|
1917
2134
|
preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata: Readonly<Record<string, string>> = {}, operatorSourceId?: string): boolean {
|
|
1918
|
-
if (!isLaneModel(model) || typeof reason !== "string" || !reason.trim()
|
|
2135
|
+
if (!isLaneModel(model) || (reason !== null && (typeof reason !== "string" || !reason.trim()))
|
|
1919
2136
|
|| (preset !== null && (typeof preset !== "string" || !preset.trim() || !snapshot)) || (preset === null && snapshot !== null)) {
|
|
1920
|
-
throw new Error("
|
|
2137
|
+
throw new Error("Invalid lane model selection or preset snapshot");
|
|
1921
2138
|
}
|
|
1922
2139
|
return this.db.transaction(() => {
|
|
1923
2140
|
const lane = this.lane(id);
|
|
@@ -2122,9 +2339,13 @@ export class Store implements StorePort {
|
|
|
2122
2339
|
|
|
2123
2340
|
recoverDeliveries(): void {
|
|
2124
2341
|
this.db.transaction(() => {
|
|
2342
|
+
const gateway = this.hasGatewayEffects();
|
|
2343
|
+
// Distinguish a complete receipt already durable at startup from one
|
|
2344
|
+
// arriving after the old send has been quarantined. Never clear a prior hold.
|
|
2345
|
+
if (gateway) this.recoverSlackDeliveries();
|
|
2125
2346
|
this.db.query("UPDATE outputs SET state = 'uncertain', error = ? WHERE state = 'sending'")
|
|
2126
2347
|
.run("Delivery interrupted before a durable receipt; reconcile before retrying.");
|
|
2127
|
-
if (!
|
|
2348
|
+
if (!gateway) return;
|
|
2128
2349
|
const retired = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'uncertain' AND remote_id IS NULL
|
|
2129
2350
|
AND (${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`).all();
|
|
2130
2351
|
const attempts = this.db.query<{ output: string; rejected: number }, [string]>(`SELECT
|
|
@@ -2149,6 +2370,155 @@ export class Store implements StorePort {
|
|
|
2149
2370
|
}).immediate();
|
|
2150
2371
|
}
|
|
2151
2372
|
|
|
2373
|
+
private hasGatewayEffects(): boolean {
|
|
2374
|
+
return this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get() !== null;
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
private gatewaySendAttempts(id: string, limit: number): GatewaySendAttempt[] {
|
|
2378
|
+
return this.db.query<GatewaySendAttempt, [string, number]>(`SELECT id, arguments,
|
|
2379
|
+
CASE WHEN state = 'complete' AND json_valid(result) THEN result END AS result
|
|
2380
|
+
FROM gateway_effects WHERE operation = 'send'
|
|
2381
|
+
AND (CASE WHEN json_valid(arguments) THEN json_extract(arguments, '$[0].id') END) = ? LIMIT ?`).all(id, limit);
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
reconcileSlackOutput(id: string): boolean {
|
|
2385
|
+
return this.db.transaction(() => {
|
|
2386
|
+
const output = this.output(id);
|
|
2387
|
+
return output?.state === "sending" && output.route.platform === "slack"
|
|
2388
|
+
&& this.hasGatewayEffects() && this.reconcileSlackPlainPost(output);
|
|
2389
|
+
}).immediate();
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
reconcileSlackJoinedOutput(id: string): boolean {
|
|
2393
|
+
return this.db.transaction(() => {
|
|
2394
|
+
const output = this.output(id);
|
|
2395
|
+
return output?.state === "sending" && this.isSlackJoinedNotice(output)
|
|
2396
|
+
&& this.hasGatewayEffects() && this.reconcileSlackJoinedReceipt(output);
|
|
2397
|
+
}).immediate();
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
private recoverSlackDeliveries(): void {
|
|
2401
|
+
const sending = this.db.query<OutputRow, []>(`SELECT * FROM outputs
|
|
2402
|
+
WHERE state = 'sending' AND remote_id IS NULL AND json_extract(route, '$.platform') = 'slack'
|
|
2403
|
+
AND (id IN (source_id || ':workspace', source_id || ':restart-ack')
|
|
2404
|
+
OR EXISTS (SELECT 1 FROM metadata WHERE key = 'kickoff-output:' || outputs.source_id AND value = outputs.id)
|
|
2405
|
+
OR json_type(reply_to, '$.joinedAnswerId') = 'text')
|
|
2406
|
+
ORDER BY sequence`).all();
|
|
2407
|
+
for (const row of sending) {
|
|
2408
|
+
const output = toOutput(row);
|
|
2409
|
+
if (output.id !== `${output.sourceId}:workspace` && this.isSlackJoinedNotice(output)) this.reconcileSlackJoinedReceipt(output);
|
|
2410
|
+
else this.reconcileSlackPlainPost(output);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
private reconcileSlackPlainPost(output: OutputRecord): boolean {
|
|
2415
|
+
const source = this.input(output.sourceId);
|
|
2416
|
+
if (output.remoteId !== null || !source || !this.isSlackPlainPost(output, source) || !this.isScopedSlackPlainPost(output, source)) return false;
|
|
2417
|
+
const attempts = this.gatewaySendAttempts(output.id, 2);
|
|
2418
|
+
const receipt = attempts.length === 1 ? attempts[0] : undefined;
|
|
2419
|
+
if (!receipt?.result || !isDeepStrictEqual(JSON.parse(receipt.arguments), [output])) return false;
|
|
2420
|
+
const result = parseGatewaySendResult(receipt.result);
|
|
2421
|
+
// A definitive non-post is terminal for these outputs, even if the
|
|
2422
|
+
// provider asked for a delay. Only a joined link has a retry contract.
|
|
2423
|
+
if (gatewaySendRejection(result)) {
|
|
2424
|
+
this.finishOutput(output.id, "failed", undefined, "Messenger rejected delivery");
|
|
2425
|
+
return true;
|
|
2426
|
+
}
|
|
2427
|
+
const remoteId = gatewaySendSuccess(result);
|
|
2428
|
+
if (remoteId === null || !this.slackPlainPostTimestamp({ ...output, state: "sent", remoteId }, source)) return false;
|
|
2429
|
+
this.finishOutput(output.id, "sent", remoteId);
|
|
2430
|
+
return true;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
private isScopedSlackPlainPost(output: OutputRecord, source: InputRecord): boolean {
|
|
2434
|
+
if (output.id === `${source.id}:workspace`) {
|
|
2435
|
+
return source.state === "pending" && source.target === null && this.getMeta(`user-source:${source.id}`) === "true";
|
|
2436
|
+
}
|
|
2437
|
+
if (output.id !== `${source.id}:restart-ack`) {
|
|
2438
|
+
return source.state === "pending" && this.getMeta(`kickoff-output:${source.id}`) === output.id
|
|
2439
|
+
&& this.db.query(`SELECT 1 FROM lane_sources JOIN lanes ON lanes.id = lane_sources.lane_id
|
|
2440
|
+
WHERE source_id = ? AND lane_id = ? AND lanes.route_key = ?`).get(source.id, source.target, routeKey(source.route)) !== null;
|
|
2441
|
+
}
|
|
2442
|
+
if (source.state !== "done" || source.target !== "main" || source.pickerSelection
|
|
2443
|
+
|| this.getMeta(`user-source:${source.id}`) !== "true" || this.getMeta(`handoff-source:${source.id}`) !== null) return false;
|
|
2444
|
+
// This proof only confirms the original acknowledgement. The restart
|
|
2445
|
+
// coordinator still owns checkpoint, native ownership and handoff checks.
|
|
2446
|
+
const saved = this.db.query<{ value: string }, [string]>(`SELECT value FROM metadata
|
|
2447
|
+
WHERE key = 'head:restart-fence' AND json_valid(value)
|
|
2448
|
+
AND value = (SELECT value FROM metadata WHERE key = ?)`).get(`head:restart:${source.id}`);
|
|
2449
|
+
if (!saved) return false;
|
|
2450
|
+
const fence: unknown = JSON.parse(saved.value);
|
|
2451
|
+
return !!fence && typeof fence === "object"
|
|
2452
|
+
&& "state" in fence && fence.state === "acknowledging"
|
|
2453
|
+
&& "inputId" in fence && fence.inputId === source.id
|
|
2454
|
+
&& "ackOutputId" in fence && fence.ackOutputId === output.id
|
|
2455
|
+
&& "requestId" in fence && typeof fence.requestId === "string" && !!fence.requestId
|
|
2456
|
+
&& "ownerPid" in fence && typeof fence.ownerPid === "number" && Number.isSafeInteger(fence.ownerPid) && fence.ownerPid > 0
|
|
2457
|
+
&& "sessionId" in fence && typeof fence.sessionId === "string" && !!fence.sessionId
|
|
2458
|
+
&& "sessionFile" in fence && typeof fence.sessionFile === "string" && !!fence.sessionFile
|
|
2459
|
+
&& (("stopBoundary" in fence ? fence.stopBoundary : null) ?? null) === this.getMeta("gateway:operator-stop");
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
private isSlackPlainPost(output: OutputRecord, source: InputRecord): boolean {
|
|
2463
|
+
return routeKey(source.route) === routeKey(output.route) && Boolean(output.text.trim())
|
|
2464
|
+
&& !output.replyTo && !output.editOf && !output.picker && !output.resultAttachment && !output.status;
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
private slackPlainPostTimestamp(output: OutputRecord, source: InputRecord): string | null {
|
|
2468
|
+
if (!this.isSlackPlainPost(output, source)) return null;
|
|
2469
|
+
const post = slackOutputTimestamp(this, output);
|
|
2470
|
+
const first = output.remoteId;
|
|
2471
|
+
// Opening handoffs copy the owner's message ID but change the route. Only
|
|
2472
|
+
// the recorded origin can tell whether that ID belongs to this Slack clock.
|
|
2473
|
+
const originId = this.getMeta(`handoff-source:${source.id}`);
|
|
2474
|
+
const origin = originId === null ? source : this.input(originId);
|
|
2475
|
+
if (!origin) return null;
|
|
2476
|
+
const sameSlackChannel = origin.route.platform === "slack" && origin.route.accountId === output.route.accountId
|
|
2477
|
+
&& origin.route.channelId === output.route.channelId;
|
|
2478
|
+
if (!post || !first || compareMessageIds("slack", first, "0.000000") !== 1
|
|
2479
|
+
|| sameSlackChannel && origin.messageId !== null && compareMessageIds("slack", first, origin.messageId) !== 1
|
|
2480
|
+
|| source.route.threadId !== null && compareMessageIds("slack", first, source.route.threadId) !== 1) return null;
|
|
2481
|
+
return post;
|
|
2482
|
+
}
|
|
2483
|
+
|
|
2484
|
+
private reconcileSlackJoinedReceipt(output: OutputRecord): boolean {
|
|
2485
|
+
const { at, count, priorAttemptIds } = this.slackJoinedRetry(output.id);
|
|
2486
|
+
if (!priorAttemptIds || priorAttemptIds.length !== count || count > SLACK_JOINED_RETRY_LIMIT) return false;
|
|
2487
|
+
const attempts = this.gatewaySendAttempts(output.id, count + 2);
|
|
2488
|
+
if (attempts.length !== count + 1) return false;
|
|
2489
|
+
const current = attempts.find(attempt => !priorAttemptIds.includes(attempt.id));
|
|
2490
|
+
if (!current?.result || priorAttemptIds.some(id => !attempts.some(attempt => attempt.id === id))) return false;
|
|
2491
|
+
for (const attempt of attempts) {
|
|
2492
|
+
if (!attempt.result || !isDeepStrictEqual(JSON.parse(attempt.arguments), [output])) return false;
|
|
2493
|
+
if (attempt !== current && gatewaySendRejection(parseGatewaySendResult(attempt.result))?.retryAfterMs === undefined) return false;
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
const result = parseGatewaySendResult(current.result);
|
|
2497
|
+
const remoteId = gatewaySendSuccess(result);
|
|
2498
|
+
if (remoteId !== null) {
|
|
2499
|
+
const reply = output.replyTo;
|
|
2500
|
+
const root = output.route.threadId;
|
|
2501
|
+
if (!reply?.joinedAnswerId || !/^\d{1,20}\.\d{6}$/u.test(remoteId)
|
|
2502
|
+
|| compareMessageIds("slack", remoteId, "0.000000") !== 1
|
|
2503
|
+
|| compareMessageIds("slack", remoteId, reply.messageId) !== 1
|
|
2504
|
+
|| compareMessageIds("slack", remoteId, reply.joinedAnswerId) !== 1
|
|
2505
|
+
|| root !== null && compareMessageIds("slack", remoteId, root) !== 1) return false;
|
|
2506
|
+
this.finishOutput(output.id, "sent", remoteId);
|
|
2507
|
+
return true;
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
const rejection = gatewaySendRejection(result);
|
|
2511
|
+
if (!rejection) return false;
|
|
2512
|
+
if (rejection.retryAfterMs !== undefined && count < SLACK_JOINED_RETRY_LIMIT) {
|
|
2513
|
+
const completed = this.getMeta(`${SLACK_JOINED_REJECTED_AT}${current.id}`);
|
|
2514
|
+
const completedAt = completed !== null && /^\d+$/u.test(completed) ? Number(completed) : NaN;
|
|
2515
|
+
if (!Number.isSafeInteger(completedAt) || completedAt < (at ?? 0)) return false;
|
|
2516
|
+
if (this.recordSlackJoinedRetry(output.id, count, completedAt, rejection.retryAfterMs)) return true;
|
|
2517
|
+
}
|
|
2518
|
+
this.finishOutput(output.id, "failed", undefined, "Gateway recorded definitive non-delivery");
|
|
2519
|
+
return true;
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2152
2522
|
getMeta(key: string): string | null {
|
|
2153
2523
|
return (this.db.query("SELECT value FROM metadata WHERE key = ?").get(key) as { value: string } | null)?.value ?? null;
|
|
2154
2524
|
}
|