viber-channel 0.8.46 → 0.8.48
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/lib/ack_retry.ts +73 -0
- package/lib/bridge_core.ts +214 -21
- package/lib/capabilities.ts +15 -8
- package/lib/codex_model_pair.ts +21 -11
- package/lib/codex_models_refresh.ts +326 -0
- package/lib/control_stream.ts +49 -21
- package/lib/dm_stream.ts +276 -60
- package/lib/launch_confirm.ts +69 -0
- package/lib/main_catchup.ts +264 -0
- package/lib/messages.ts +65 -2
- package/lib/runner_stream.ts +47 -37
- package/lib/server_events.ts +144 -0
- package/lib/sse_idle.ts +136 -0
- package/lib/stream_log.ts +69 -0
- package/lib/team_role_tool.ts +1 -2
- package/package.json +1 -1
- package/viber-channel.ts +100 -18
- package/viber-codex-bridge.ts +3 -0
- package/lib/codex_default.ts +0 -11
package/lib/ack_retry.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded retry of a transport ACK (#751), shared by the Claude channel's DM
|
|
3
|
+
* streams and the Codex/Gemma bridge so both runtimes behave the same.
|
|
4
|
+
*
|
|
5
|
+
* - each attempt is bounded by {@link ACK_ATTEMPT_TIMEOUT_MS}: a POST that hangs
|
|
6
|
+
* can never keep an id "in flight" forever;
|
|
7
|
+
* - `ok` and `rejected` (4xx — the server will never accept it) are final;
|
|
8
|
+
* - `failed` (network, 5xx, 408, 429, timeout) retries after each delay, then
|
|
9
|
+
* gives up and returns `failed` — the caller retries on the next delivery.
|
|
10
|
+
* Never throws.
|
|
11
|
+
*/
|
|
12
|
+
export const ACK_ATTEMPT_TIMEOUT_MS = 10_000;
|
|
13
|
+
export const ACK_RETRY_DELAYS_MS = [1000, 2000, 4000];
|
|
14
|
+
|
|
15
|
+
/** Cap of an ACK-pending set (#751): the oldest ids are dropped beyond it. */
|
|
16
|
+
export const PENDING_ACKS_MAX = 1000;
|
|
17
|
+
|
|
18
|
+
/** Add `id` to a pending set, dropping the oldest entries beyond the cap. */
|
|
19
|
+
export function addPending(set: Set<string>, id: string, log?: (line: string) => void): void {
|
|
20
|
+
set.add(id);
|
|
21
|
+
if (set.size <= PENDING_ACKS_MAX) return;
|
|
22
|
+
let dropped = 0;
|
|
23
|
+
for (const old of set) {
|
|
24
|
+
if (set.size <= PENDING_ACKS_MAX) break;
|
|
25
|
+
set.delete(old);
|
|
26
|
+
dropped += 1;
|
|
27
|
+
}
|
|
28
|
+
log?.(`[ack] pending-ACK set over ${PENDING_ACKS_MAX}: dropped the ${dropped} oldest\n`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type AckOutcome = "ok" | "rejected" | "failed";
|
|
32
|
+
|
|
33
|
+
export async function ackWithRetry(
|
|
34
|
+
attempt: (signal: AbortSignal) => Promise<boolean | AckOutcome>,
|
|
35
|
+
opts: { delaysMs?: number[]; attemptTimeoutMs?: number; signal?: AbortSignal } = {},
|
|
36
|
+
): Promise<AckOutcome> {
|
|
37
|
+
const delays = opts.delaysMs ?? ACK_RETRY_DELAYS_MS;
|
|
38
|
+
const timeoutMs = opts.attemptTimeoutMs ?? ACK_ATTEMPT_TIMEOUT_MS;
|
|
39
|
+
for (let i = 0; i <= delays.length; i++) {
|
|
40
|
+
if (opts.signal?.aborted) return "failed";
|
|
41
|
+
const perAttempt = opts.signal
|
|
42
|
+
? AbortSignal.any([opts.signal, AbortSignal.timeout(timeoutMs)])
|
|
43
|
+
: AbortSignal.timeout(timeoutMs);
|
|
44
|
+
let r: boolean | AckOutcome;
|
|
45
|
+
try {
|
|
46
|
+
r = await Promise.race([
|
|
47
|
+
attempt(perAttempt),
|
|
48
|
+
new Promise<"failed">((resolve) => perAttempt.addEventListener("abort", () => resolve("failed"), { once: true })),
|
|
49
|
+
]);
|
|
50
|
+
} catch {
|
|
51
|
+
r = "failed";
|
|
52
|
+
}
|
|
53
|
+
if (r === true || r === "ok") return "ok";
|
|
54
|
+
if (r === "rejected") return "rejected";
|
|
55
|
+
if (i < delays.length) await sleep(delays[i], opts.signal);
|
|
56
|
+
}
|
|
57
|
+
return "failed";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
61
|
+
return new Promise((resolve) => {
|
|
62
|
+
if (signal?.aborted) return resolve();
|
|
63
|
+
const t = setTimeout(resolve, ms);
|
|
64
|
+
signal?.addEventListener(
|
|
65
|
+
"abort",
|
|
66
|
+
() => {
|
|
67
|
+
clearTimeout(t);
|
|
68
|
+
resolve();
|
|
69
|
+
},
|
|
70
|
+
{ once: true },
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
}
|
package/lib/bridge_core.ts
CHANGED
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
RefreshNetworkError,
|
|
25
25
|
refreshConversationToken,
|
|
26
26
|
} from "./conversation.js";
|
|
27
|
-
import {
|
|
27
|
+
import { ackMessageResult, ConversationTokenExpiredError, fetchMessages, fetchMessageWindow, type MessageWindowQuery, postMessage } from "./messages.js";
|
|
28
28
|
import { buildSseUrl } from "./urls.js";
|
|
29
29
|
import { cfAccessHeaders } from "./cfAccess.js";
|
|
30
30
|
import { sessionFilePath, writeHandle } from "./channel_session.js";
|
|
@@ -37,6 +37,10 @@ import {
|
|
|
37
37
|
type PersistentControlStream,
|
|
38
38
|
} from "./control_stream.js";
|
|
39
39
|
import { type PresenceGate, startCoverageWatch } from "./coverage_watch.js";
|
|
40
|
+
import { createIdleGuard, type IdleGuard } from "./sse_idle.js";
|
|
41
|
+
import { ackWithRetry, addPending } from "./ack_retry.js";
|
|
42
|
+
import { ackServerEvent, createServerEventHandler } from "./server_events.js";
|
|
43
|
+
import { createLaunchConfirmer, postLaunched } from "./launch_confirm.js";
|
|
40
44
|
import { type PresenceEndReason, type PresenceRecordHandle, startPresenceRecord } from "./presence_record.js";
|
|
41
45
|
|
|
42
46
|
/** A conversation message as it arrives over the conversation SSE / message list. */
|
|
@@ -61,6 +65,21 @@ export interface ConversationMessage {
|
|
|
61
65
|
export interface BridgeWatermark {
|
|
62
66
|
/** Highest delivered (replied-to) message id (0 = nothing delivered yet). */
|
|
63
67
|
lastId: number;
|
|
68
|
+
/**
|
|
69
|
+
* #751: ids whose transport ACK is not confirmed yet. At or below `lastId`,
|
|
70
|
+
* only these are re-acknowledged — a reconnect's full re-read never re-ACKs
|
|
71
|
+
* the whole history (one Worker subrequest each).
|
|
72
|
+
*/
|
|
73
|
+
pendingAcks?: Set<string>;
|
|
74
|
+
/**
|
|
75
|
+
* #751 (Codex, step-07): CONTIGUOUS coverage, advanced only by a fully processed
|
|
76
|
+
* page of the id-ordered window — never by a live delivery. Absent on a legacy
|
|
77
|
+
* watermark (`lastId` stands for it). The reconcile resumes from here, so a 101
|
|
78
|
+
* missed while 102 arrived live is still handled.
|
|
79
|
+
*/
|
|
80
|
+
floor?: number;
|
|
81
|
+
/** #751: ids delivered ABOVE `floor`. */
|
|
82
|
+
delivered?: Set<string>;
|
|
64
83
|
}
|
|
65
84
|
|
|
66
85
|
/** One live conversation stream's mutable runtime state (token rotates). */
|
|
@@ -480,7 +499,21 @@ export function readTurnDegradation(err: unknown): TurnDegradation | undefined {
|
|
|
480
499
|
* never skips. Pure + exported for unit tests (pattern `decideTurnPostAction`).
|
|
481
500
|
*/
|
|
482
501
|
export function watermarkShouldSkip(numId: number, watermark?: BridgeWatermark): boolean {
|
|
483
|
-
|
|
502
|
+
if (!watermark || !Number.isSafeInteger(numId)) return false;
|
|
503
|
+
return numId <= bridgeFloorOf(watermark) || !!watermark.delivered?.has(String(numId));
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** #751: the contiguous floor of a bridge watermark (a legacy one: its lastId). */
|
|
507
|
+
export function bridgeFloorOf(w: BridgeWatermark): number {
|
|
508
|
+
if (w.floor === undefined) w.floor = w.lastId;
|
|
509
|
+
return w.floor;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** #751: raise the contiguous floor (reconcile only) and forget the ids under it. */
|
|
513
|
+
export function bridgeAdvanceFloor(w: BridgeWatermark | undefined, to: number): void {
|
|
514
|
+
if (!w || !Number.isSafeInteger(to) || to <= bridgeFloorOf(w)) return;
|
|
515
|
+
w.floor = to;
|
|
516
|
+
for (const id of w.delivered ?? []) if (Number(id) <= to) w.delivered?.delete(id);
|
|
484
517
|
}
|
|
485
518
|
|
|
486
519
|
/**
|
|
@@ -490,9 +523,10 @@ export function watermarkShouldSkip(numId: number, watermark?: BridgeWatermark):
|
|
|
490
523
|
* gate; a NaN/absent/unsafe id is never watermarked. Pure + exported.
|
|
491
524
|
*/
|
|
492
525
|
export function watermarkAdvance(numId: number, watermark?: BridgeWatermark): void {
|
|
493
|
-
if (watermark
|
|
494
|
-
|
|
495
|
-
|
|
526
|
+
if (!watermark || !Number.isSafeInteger(numId)) return;
|
|
527
|
+
const floor = bridgeFloorOf(watermark);
|
|
528
|
+
if (numId > watermark.lastId) watermark.lastId = numId;
|
|
529
|
+
if (numId > floor) (watermark.delivered ??= new Set<string>()).add(String(numId));
|
|
496
530
|
}
|
|
497
531
|
|
|
498
532
|
/** Bearer + fingerprint + CF Access headers for a conversation request. */
|
|
@@ -547,6 +581,12 @@ export interface ConversationStreamDeps {
|
|
|
547
581
|
* whole point of the cross-run dedup.
|
|
548
582
|
*/
|
|
549
583
|
watermarks: Map<string, BridgeWatermark>;
|
|
584
|
+
/**
|
|
585
|
+
* #751: per-conversation injectors, set by each live sseLoop — a durable
|
|
586
|
+
* server event (delivery_failed…) is presented to the model as a turn on the
|
|
587
|
+
* conversation it concerns, serialised with the live turns.
|
|
588
|
+
*/
|
|
589
|
+
injectors?: Map<string, (text: string) => Promise<void>>;
|
|
550
590
|
/** Global shutdown signal — aborting it stops every stream. */
|
|
551
591
|
parentSignal: AbortSignal;
|
|
552
592
|
/**
|
|
@@ -632,10 +672,10 @@ export async function runConversationStream(
|
|
|
632
672
|
// abort+restart on re-join (the finally below deliberately does NOT delete it).
|
|
633
673
|
let watermark = watermarks.get(convId);
|
|
634
674
|
if (!watermark) {
|
|
635
|
-
watermark = { lastId: 0 };
|
|
675
|
+
watermark = { lastId: 0, pendingAcks: new Set<string>() }; // #751: ACK tracking on
|
|
636
676
|
watermarks.set(convId, watermark);
|
|
637
677
|
}
|
|
638
|
-
await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, getBaseUrl: baseUrl, logPrefix, runTurn, watermark, gate: deps.gate });
|
|
678
|
+
await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, getBaseUrl: baseUrl, logPrefix, runTurn, watermark, gate: deps.gate, injectors: deps.injectors });
|
|
639
679
|
} finally {
|
|
640
680
|
parentSignal.removeEventListener("abort", onParentAbort);
|
|
641
681
|
runtime.scheduler?.cancel();
|
|
@@ -690,6 +730,17 @@ export async function sseLoop(opts: {
|
|
|
690
730
|
fetchMessagesImpl?: typeof fetchMessages;
|
|
691
731
|
/** #627: the pause gate (see ConversationStreamDeps.gate). */
|
|
692
732
|
gate?: PresenceGate;
|
|
733
|
+
/** #751: idle deadline per wait for bytes; default `SSE_IDLE_TIMEOUT_MS`. */
|
|
734
|
+
idleTimeoutMs?: number;
|
|
735
|
+
/** Reconnect delay after a failure; default 2000 ms (tests shorten it). */
|
|
736
|
+
reconnectDelayMs?: number;
|
|
737
|
+
/** #751: bound of the reconcile REST phase (own guard); default 10 000 ms. */
|
|
738
|
+
catchUpTimeoutMs?: number;
|
|
739
|
+
/** #751: where to register this conversation's turn injector (see ConversationStreamDeps). */
|
|
740
|
+
injectors?: Map<string, (text: string) => Promise<void>>;
|
|
741
|
+
/** #751: ACK retry delays / per-attempt bound (tests shorten them). */
|
|
742
|
+
ackRetryDelaysMs?: number[];
|
|
743
|
+
ackAttemptTimeoutMs?: number;
|
|
693
744
|
}): Promise<void> {
|
|
694
745
|
const { minted, runtime, fingerprint, ownInstanceKey, options, signal, getBaseUrl, logPrefix, runTurn, watermark } = opts;
|
|
695
746
|
const deps = { gate: opts.gate };
|
|
@@ -731,7 +782,7 @@ export async function sseLoop(opts: {
|
|
|
731
782
|
// reply UNLESS an outbound tool already posted this turn (anti-double-post).
|
|
732
783
|
// Returns true when the reply was dropped because the stream was aborted
|
|
733
784
|
// mid-flight (caller must not trip the --once clean exit).
|
|
734
|
-
async function replyForTurn(content: string, echoMsg?: ConversationMessage): Promise<boolean> {
|
|
785
|
+
async function replyForTurn(content: string, echoMsg?: ConversationMessage, noAutoPost = false): Promise<boolean> {
|
|
735
786
|
let result: TurnResult;
|
|
736
787
|
try {
|
|
737
788
|
result = await runTurn(content, echoMsg, signal);
|
|
@@ -762,6 +813,14 @@ export async function sseLoop(opts: {
|
|
|
762
813
|
rearmFailureNotice();
|
|
763
814
|
return false;
|
|
764
815
|
case "auto-post":
|
|
816
|
+
if (noAutoPost) {
|
|
817
|
+
// #751: a server-event notice turn NEVER auto-posts — its text would land in
|
|
818
|
+
// the DM of the unhooked peer, get its own deadline, its own delivery_failed,
|
|
819
|
+
// another notice turn… (loop, Opus review). The model acts through tools.
|
|
820
|
+
process.stderr.write(`${logPrefix} notice turn on ${runtime.id}: reply not posted (notices never auto-post)\n`);
|
|
821
|
+
rearmFailureNotice();
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
765
824
|
await postBridgeReply({ baseUrl: baseUrl(), runtime, text: reply, ownPostedIds, signal, logPrefix, fetchImpl, gate: deps.gate });
|
|
766
825
|
rearmFailureNotice();
|
|
767
826
|
return false;
|
|
@@ -797,17 +856,41 @@ export async function sseLoop(opts: {
|
|
|
797
856
|
// the Worker's insertMessageAck qualification. N/A today: addressed_to is
|
|
798
857
|
// dormant and fan-out is per-conversation, so every connected bridge truly
|
|
799
858
|
// receives the message (consistent with decision A = delivered-to-bridge).
|
|
859
|
+
//
|
|
860
|
+
// #751: a PEER agent's message is acknowledged too — the transport receipt its
|
|
861
|
+
// sender relies on (the Worker accepts it only in a canonical-pair DM, from the
|
|
862
|
+
// other member). Elsewhere the Worker rejects it (4xx): the id is then marked
|
|
863
|
+
// done and never retried, so a multi-agent room costs one request per message.
|
|
800
864
|
function ackInboundReceipt(msg: ConversationMessage): void {
|
|
801
|
-
|
|
802
|
-
|
|
865
|
+
const fromWeb = (msg.role === "user" || msg.role === "user_voice") && !msg.sender_instance_id;
|
|
866
|
+
const fromPeer = !!msg.sender_instance_id && msg.sender_instance_id !== ownInstanceKey;
|
|
867
|
+
if (!fromWeb && !fromPeer) return;
|
|
803
868
|
const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
|
|
804
869
|
if (!idStr) return;
|
|
870
|
+
if (ownPostedIds.has(idStr)) return;
|
|
805
871
|
if (ackedIds.has(idStr) || ackInFlightIds.has(idStr)) return;
|
|
872
|
+
// Below the watermark, only an id still pending its ACK goes out again.
|
|
873
|
+
const n = Number(idStr);
|
|
874
|
+
// Tracking is on when the caller seeded `pendingAcks`; without it (unknown ACK
|
|
875
|
+
// state, #346 B.13) a re-delivered id is still re-acknowledged.
|
|
876
|
+
if (watermark?.pendingAcks && Number.isSafeInteger(n) && n <= watermark.lastId && !watermark.pendingAcks.has(idStr)) return;
|
|
806
877
|
ackInFlightIds.add(idStr);
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
878
|
+
const pending = watermark ? (watermark.pendingAcks ??= new Set<string>()) : undefined;
|
|
879
|
+
if (pending) addPending(pending, idStr, (l) => process.stderr.write(`${logPrefix} ${l}`));
|
|
880
|
+
// Same bounded retry as the Claude DM streams (#751): each attempt is timed
|
|
881
|
+
// out, failures retry in-run, a 4xx refusal is final.
|
|
882
|
+
void ackWithRetry((sig) => ackMessageResult(baseUrl(), runtime.id, runtime.token, idStr, sig, fetchImpl), {
|
|
883
|
+
delaysMs: opts.ackRetryDelaysMs,
|
|
884
|
+
attemptTimeoutMs: opts.ackAttemptTimeoutMs,
|
|
885
|
+
signal,
|
|
886
|
+
})
|
|
887
|
+
.then((r) => {
|
|
888
|
+
if (r !== "failed") {
|
|
889
|
+
ackedIds.add(idStr);
|
|
890
|
+
pending?.delete(idStr);
|
|
891
|
+
} else if (!signal.aborted) {
|
|
892
|
+
process.stderr.write(`${logPrefix} ack failed for message ${idStr} (will retry on reconnect)\n`);
|
|
893
|
+
}
|
|
811
894
|
})
|
|
812
895
|
.finally(() => ackInFlightIds.delete(idStr));
|
|
813
896
|
}
|
|
@@ -856,6 +939,23 @@ export async function sseLoop(opts: {
|
|
|
856
939
|
}
|
|
857
940
|
}
|
|
858
941
|
|
|
942
|
+
// #751: one turn at a time on this conversation — live messages and injected
|
|
943
|
+
// server events share this chain, so an injected notice never races a turn.
|
|
944
|
+
let turnChain: Promise<unknown> = Promise.resolve();
|
|
945
|
+
function serialTurn<T>(fn: () => Promise<T>): Promise<T> {
|
|
946
|
+
const next = turnChain.then(fn);
|
|
947
|
+
turnChain = next.catch(() => {});
|
|
948
|
+
return next;
|
|
949
|
+
}
|
|
950
|
+
if (opts.injectors) {
|
|
951
|
+
const convId = minted.conversation_id;
|
|
952
|
+
opts.injectors.set(convId, async (text: string) => {
|
|
953
|
+
// A notice turn: the model reads it, its text is never auto-posted (no loop).
|
|
954
|
+
await serialTurn(() => replyForTurn(text, undefined, true));
|
|
955
|
+
});
|
|
956
|
+
signal.addEventListener("abort", () => opts.injectors?.delete(convId), { once: true });
|
|
957
|
+
}
|
|
958
|
+
|
|
859
959
|
async function handleInboundMessage(msg: ConversationMessage): Promise<boolean> {
|
|
860
960
|
const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
|
|
861
961
|
// TRUTHY check (not `!== undefined`): idStr === "" must yield NaN, not
|
|
@@ -908,19 +1008,71 @@ export async function sseLoop(opts: {
|
|
|
908
1008
|
|
|
909
1009
|
// On every (re)connect the SSE has NO replay — re-read the message list and
|
|
910
1010
|
// process anything missed. The first pass seeds without replying.
|
|
1011
|
+
/**
|
|
1012
|
+
* #751: the legacy listing returns the OLDEST 500 messages — past that, neither
|
|
1013
|
+
* the first pass (#291 trigger + seed) nor a reconnect's catch-up saw the recent
|
|
1014
|
+
* ones. First pass: the most recent page (`?tail=500`). Afterwards: by id from
|
|
1015
|
+
* the watermark (or below it, an id still pending its ACK), paginated. An older
|
|
1016
|
+
* Worker (no `window` echo) answers the legacy listing, used as before.
|
|
1017
|
+
*/
|
|
1018
|
+
async function fetchReconcileWindow(
|
|
1019
|
+
rest: { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal },
|
|
1020
|
+
): Promise<{ msgs: Array<Record<string, unknown>>; windowed: boolean }> {
|
|
1021
|
+
const get = (q: MessageWindowQuery) =>
|
|
1022
|
+
rest.race(fetchMessageWindow(baseUrl(), minted.conversation_id, runtime.token, q, rest.signal, fetchImpl));
|
|
1023
|
+
if (!primed || !watermark) {
|
|
1024
|
+
const first = await get({ tail: 500 });
|
|
1025
|
+
if (!first.window && first.messages.length >= 500) {
|
|
1026
|
+
process.stderr.write(`${logPrefix} catch-up INCOMPLETE: this server ignores the window (legacy page of the OLDEST 500)\n`);
|
|
1027
|
+
}
|
|
1028
|
+
return { msgs: first.messages, windowed: false };
|
|
1029
|
+
}
|
|
1030
|
+
const pending = [...(watermark.pendingAcks ?? [])].map(Number).filter((n) => Number.isSafeInteger(n));
|
|
1031
|
+
const floor = bridgeFloorOf(watermark);
|
|
1032
|
+
let cursor = Math.max(0, pending.length > 0 ? Math.min(floor, Math.min(...pending) - 1) : floor);
|
|
1033
|
+
const out: Array<Record<string, unknown>> = [];
|
|
1034
|
+
let windowed = true;
|
|
1035
|
+
for (let page = 0; page < 10; page++) {
|
|
1036
|
+
const res = await get({ after: cursor });
|
|
1037
|
+
out.push(...res.messages);
|
|
1038
|
+
if (!res.window) {
|
|
1039
|
+
windowed = false; // a capped legacy page never sets a floor
|
|
1040
|
+
if (res.messages.length >= 500) process.stderr.write(`${logPrefix} catch-up INCOMPLETE: legacy page of 500\n`);
|
|
1041
|
+
break;
|
|
1042
|
+
}
|
|
1043
|
+
if (res.messages.length < res.window.max) break;
|
|
1044
|
+
const last = Number(res.messages[res.messages.length - 1]?.id);
|
|
1045
|
+
if (!Number.isSafeInteger(last) || last <= cursor) break;
|
|
1046
|
+
cursor = last;
|
|
1047
|
+
}
|
|
1048
|
+
return { msgs: out, windowed };
|
|
1049
|
+
}
|
|
1050
|
+
|
|
911
1051
|
async function reconcileMessages(): Promise<boolean> {
|
|
912
1052
|
let msgs: Array<Record<string, unknown>>;
|
|
1053
|
+
let windowed = false;
|
|
1054
|
+
// #751 (Codex, step-07): the REST reconcile runs on its OWN bounded guard — a
|
|
1055
|
+
// frozen Worker delays the live read by at most that bound, never deafens it.
|
|
1056
|
+
const rest = createIdleGuard({ idleMs: opts.catchUpTimeoutMs ?? 10_000, signal });
|
|
913
1057
|
try {
|
|
914
1058
|
// #333: catch-up is a REST call to GET /api/conversations/:id/messages,
|
|
915
1059
|
// which is served by the Worker API (baseUrl) — NOT by minted.ws_url, which
|
|
916
1060
|
// is the SSE/voice host (the CF tunnel in staging/prod). Using ws_url here
|
|
917
1061
|
// 404s whenever the SSE host differs from the API host (masked in dev where
|
|
918
1062
|
// they collapse to one origin). The SSE subscription still uses ws_url.
|
|
919
|
-
|
|
1063
|
+
if (opts.fetchMessagesImpl) {
|
|
1064
|
+
msgs = await rest.race(fetchMessagesImpl(baseUrl(), minted.conversation_id, runtime.token));
|
|
1065
|
+
} else {
|
|
1066
|
+
const w = await fetchReconcileWindow(rest);
|
|
1067
|
+
msgs = w.msgs;
|
|
1068
|
+
windowed = w.windowed;
|
|
1069
|
+
}
|
|
920
1070
|
} catch (err) {
|
|
921
1071
|
if (err instanceof ConversationTokenExpiredError) throw err;
|
|
922
1072
|
process.stderr.write(`${logPrefix} catch-up fetch failed: ${safeErrorMessage(err)}\n`);
|
|
923
1073
|
return false;
|
|
1074
|
+
} finally {
|
|
1075
|
+
rest.dispose();
|
|
924
1076
|
}
|
|
925
1077
|
const seed = (msg: ConversationMessage): void => {
|
|
926
1078
|
const idStr = msg.id !== undefined && msg.id !== null ? String(msg.id) : undefined;
|
|
@@ -942,7 +1094,7 @@ export async function sseLoop(opts: {
|
|
|
942
1094
|
`${logPrefix} join catch-up: forwarding trigger (most recent of ${msgs.length}), seeded ${plan.seed.length} prior\n`,
|
|
943
1095
|
);
|
|
944
1096
|
for (const m of plan.forward) {
|
|
945
|
-
if (await handleInboundMessage(m)) return true;
|
|
1097
|
+
if (await serialTurn(() => handleInboundMessage(m))) return true;
|
|
946
1098
|
}
|
|
947
1099
|
return false;
|
|
948
1100
|
}
|
|
@@ -953,7 +1105,13 @@ export async function sseLoop(opts: {
|
|
|
953
1105
|
seed(msg);
|
|
954
1106
|
continue;
|
|
955
1107
|
}
|
|
956
|
-
if (await handleInboundMessage(msg)) return true;
|
|
1108
|
+
if (await serialTurn(() => handleInboundMessage(msg))) return true;
|
|
1109
|
+
}
|
|
1110
|
+
// #751: a fully processed window page is covered — raise the contiguous floor
|
|
1111
|
+
// (the bridge handles at most once, so every processed id is settled).
|
|
1112
|
+
if (primed && windowed) {
|
|
1113
|
+
const ids = msgs.map((m) => Number(m.id)).filter((n) => Number.isSafeInteger(n));
|
|
1114
|
+
if (ids.length > 0) bridgeAdvanceFloor(watermark, Math.max(...ids));
|
|
957
1115
|
}
|
|
958
1116
|
if (!primed) {
|
|
959
1117
|
primed = true;
|
|
@@ -962,6 +1120,7 @@ export async function sseLoop(opts: {
|
|
|
962
1120
|
return false;
|
|
963
1121
|
}
|
|
964
1122
|
|
|
1123
|
+
let guard: IdleGuard | undefined;
|
|
965
1124
|
while (true) {
|
|
966
1125
|
try {
|
|
967
1126
|
if (signal.aborted) throw signal.reason;
|
|
@@ -969,7 +1128,11 @@ export async function sseLoop(opts: {
|
|
|
969
1128
|
requestHeaders.Accept = "text/event-stream";
|
|
970
1129
|
process.stderr.write(`${logPrefix} connecting to SSE: ${sseUrl}\n`);
|
|
971
1130
|
|
|
972
|
-
|
|
1131
|
+
// #751: bound every wait for bytes (headers, then each read) — the
|
|
1132
|
+
// server beats every ~15 s, a longer silence is a dead connection. Only
|
|
1133
|
+
// the WAIT is timed: a model turn between two reads is never counted.
|
|
1134
|
+
guard = createIdleGuard({ idleMs: opts.idleTimeoutMs, signal });
|
|
1135
|
+
const resp = await guard.race(fetchImpl(sseUrl, { headers: requestHeaders, signal: guard.signal }));
|
|
973
1136
|
if (resp.status === 401) throw new ConversationTokenExpiredError();
|
|
974
1137
|
if (!resp.ok || !resp.body) throw new Error(`SSE connection failed: HTTP ${resp.status}`);
|
|
975
1138
|
|
|
@@ -980,7 +1143,7 @@ export async function sseLoop(opts: {
|
|
|
980
1143
|
let buffer = "";
|
|
981
1144
|
|
|
982
1145
|
while (true) {
|
|
983
|
-
const { done, value } = await
|
|
1146
|
+
const { done, value } = await guard.read(reader);
|
|
984
1147
|
if (done) break;
|
|
985
1148
|
buffer += decoder.decode(value, { stream: true });
|
|
986
1149
|
|
|
@@ -1045,7 +1208,7 @@ export async function sseLoop(opts: {
|
|
|
1045
1208
|
process.stderr.write(`${logPrefix} ignored malformed message SSE payload: ${safeErrorMessage(err)}\n`);
|
|
1046
1209
|
continue;
|
|
1047
1210
|
}
|
|
1048
|
-
if (await handleInboundMessage(msg)) return;
|
|
1211
|
+
if (await serialTurn(() => handleInboundMessage(msg))) return;
|
|
1049
1212
|
}
|
|
1050
1213
|
}
|
|
1051
1214
|
}
|
|
@@ -1063,7 +1226,10 @@ export async function sseLoop(opts: {
|
|
|
1063
1226
|
throw new BridgeShutdownError("conversation token expired", 3);
|
|
1064
1227
|
}
|
|
1065
1228
|
process.stderr.write(`${logPrefix} SSE failed: ${String(err)}, retrying in 2s...\n`);
|
|
1066
|
-
await sleep(2000);
|
|
1229
|
+
await sleep(opts.reconnectDelayMs ?? 2000);
|
|
1230
|
+
} finally {
|
|
1231
|
+
guard?.dispose();
|
|
1232
|
+
guard = undefined;
|
|
1067
1233
|
}
|
|
1068
1234
|
}
|
|
1069
1235
|
}
|
|
@@ -1446,6 +1612,8 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
|
|
|
1446
1612
|
// abort+restart on re-join. Bounded growth: one `{lastId}` per convId seen —
|
|
1447
1613
|
// acceptable (consensus reviewers, step-01 invariant).
|
|
1448
1614
|
const watermarks = new Map<string, BridgeWatermark>();
|
|
1615
|
+
// #751: live conversations' turn injectors (durable server events → a turn).
|
|
1616
|
+
const injectors = new Map<string, (text: string) => Promise<void>>();
|
|
1449
1617
|
const streamTasks = new Set<Promise<void>>();
|
|
1450
1618
|
let voiceBaseUrl = "";
|
|
1451
1619
|
let instanceKey = "";
|
|
@@ -1469,6 +1637,7 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
|
|
|
1469
1637
|
options,
|
|
1470
1638
|
activeStreams,
|
|
1471
1639
|
watermarks,
|
|
1640
|
+
injectors,
|
|
1472
1641
|
parentSignal: shutdown.signal,
|
|
1473
1642
|
api,
|
|
1474
1643
|
identityBaseUrl,
|
|
@@ -1548,6 +1717,30 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
|
|
|
1548
1717
|
// #627: an old server may still probe; this agent never beats on the network —
|
|
1549
1718
|
// its runner answers for it (Python no longer probes a runner-covered agent).
|
|
1550
1719
|
onBeatNow: () => {},
|
|
1720
|
+
// #751: a durable server event is presented to the model as a turn on the
|
|
1721
|
+
// conversation it concerns (its auto-posted replies are DM messages too, with
|
|
1722
|
+
// their own deadline — a Codex replying to a deaf lead must learn it). Only
|
|
1723
|
+
// then is it ACKed; with no live conversation it stays un-ACKed and the
|
|
1724
|
+
// server re-pushes it.
|
|
1725
|
+
// #751: confirm this launch once the channel is connected server-side.
|
|
1726
|
+
onConnected: createLaunchConfirmer({
|
|
1727
|
+
jobName: process.env.VIBER_JOB_NAME,
|
|
1728
|
+
post: (job, sig) => postLaunched(baseUrl(), identity.instanceKey, identity.instanceToken, job, sig),
|
|
1729
|
+
log: (l) => process.stderr.write(`${logPrefix} ${l}`),
|
|
1730
|
+
}),
|
|
1731
|
+
onEvent: createServerEventHandler({
|
|
1732
|
+
ack: (eventId) => ackServerEvent(baseUrl(), identity.instanceKey, identity.instanceToken, eventId),
|
|
1733
|
+
surface: async (ev, text) => {
|
|
1734
|
+
const convId = typeof ev.data.conversation_id === "string" ? ev.data.conversation_id : "";
|
|
1735
|
+
// Only on the conversation it concerns — never on an unrelated one (the
|
|
1736
|
+
// user's, say). Not live: no ACK, the server re-pushes it later.
|
|
1737
|
+
const inject = convId ? injectors.get(convId) : undefined;
|
|
1738
|
+
if (!inject) throw new Error(`conversation ${convId || "?"} is not live here`);
|
|
1739
|
+
process.stderr.write(`${logPrefix} server event ${ev.eventId} -> turn on ${convId || "a live conversation"}\n`);
|
|
1740
|
+
await inject(`[Viber system notice — not from a person] ${text}`);
|
|
1741
|
+
},
|
|
1742
|
+
log: (l) => process.stderr.write(`${logPrefix} ${l}`),
|
|
1743
|
+
}),
|
|
1551
1744
|
},
|
|
1552
1745
|
);
|
|
1553
1746
|
controlStream.firstJoin.catch(() => {});
|
package/lib/capabilities.ts
CHANGED
|
@@ -13,7 +13,6 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Pure (no I/O) so it is trivially testable and identical across hosts.
|
|
15
15
|
*/
|
|
16
|
-
import { CODEX_DEFAULT_PAIR } from "./codex_default.js";
|
|
17
16
|
|
|
18
17
|
export function capabilitiesText(channelVersion: string | null = null): string {
|
|
19
18
|
return [
|
|
@@ -120,7 +119,8 @@ export function capabilitiesText(channelVersion: string | null = null): string {
|
|
|
120
119
|
" only; all roles of one template must share one permission) · count optional;",
|
|
121
120
|
" model/effort: on claude leave them OUT (runtime default) UNLESS the owner asks:",
|
|
122
121
|
" model opus|sonnet|haiku|fable, effort low|medium|high|xhigh|max. On codex BOTH are",
|
|
123
|
-
|
|
122
|
+
" REQUIRED: a model the owner's codex lists (see CODEX MODELS below), effort low",
|
|
123
|
+
" unless the owner asks for another.",
|
|
124
124
|
" (On the web, sidebar ⋯ → Add agent launches ONE named agent from the same library.)",
|
|
125
125
|
"OLD ONE-ROLE TEMPLATES (#678): a template with a single role was only a workaround",
|
|
126
126
|
" to launch one agent before launch-agent existed. Do not create new ones:",
|
|
@@ -191,15 +191,13 @@ export function capabilitiesText(channelVersion: string | null = null): string {
|
|
|
191
191
|
" permission REQUIRED read-only | read-write (gemma: read-only only)",
|
|
192
192
|
" rolePrompt REQUIRED non-empty, ≤ 600 chars AFTER {prefix} expands to 32 chars",
|
|
193
193
|
" model claude: optional, opus | sonnet | haiku | fable (a family, never a",
|
|
194
|
-
" version); codex: REQUIRED,
|
|
195
|
-
"
|
|
196
|
-
" gpt-5.5; gemma: ≤ 64, stored but not applied",
|
|
194
|
+
" version); codex: REQUIRED, a model of the owner's codex list",
|
|
195
|
+
" (CODEX MODELS below); gemma: ≤ 64, stored but not applied",
|
|
197
196
|
" effort claude: optional, low | medium | high | xhigh | max;",
|
|
198
|
-
" codex: REQUIRED, one
|
|
199
|
-
" max except gpt-5.5, ultra except the luna models and gpt-5.5;",
|
|
197
|
+
" codex: REQUIRED, one that model accepts (low on all);",
|
|
200
198
|
" gemma: refused",
|
|
201
199
|
" claude: leave model/effort OUT (runtime default) unless the",
|
|
202
|
-
|
|
200
|
+
" owner asks; codex: the model the owner names, effort low unless they ask",
|
|
203
201
|
" plugins claude only, optional: [\"name@marketplace\", …] ≤ 8, enabled for",
|
|
204
202
|
" that agent's session only (e.g. playwright@claude-plugins-official)",
|
|
205
203
|
" chrome claude only, optional: true launches it with Claude in Chrome",
|
|
@@ -242,6 +240,15 @@ export function capabilitiesText(channelVersion: string | null = null): string {
|
|
|
242
240
|
"to them FIRST and read their reply on that DM. Their `gh` has no usable token in",
|
|
243
241
|
"the sandbox (#525): run gh (labels, PR comments) for them.",
|
|
244
242
|
"",
|
|
243
|
+
"CODEX MODELS (#747): no list is written anywhere — the owner's list is what `model/list`",
|
|
244
|
+
"of THEIR codex CLI answers, sent by the Viber app when it starts. A codex role naming a",
|
|
245
|
+
"model that list lacks is refused \"not available\", and the refusal names the known ones.",
|
|
246
|
+
"When the owner says a new codex model is out, or such a refusal names a model the owner",
|
|
247
|
+
"wants, run on the owner's machine:",
|
|
248
|
+
" viber-gateway refresh-models",
|
|
249
|
+
"It updates the codex CLI when npm has a newer one, reads model/list and sends it; it prints",
|
|
250
|
+
"the codex version and the models sent (exit 0), or why it failed (exit 1). Then retry.",
|
|
251
|
+
"",
|
|
245
252
|
"Never launch agents by calling vibe-master yourself: launch-team / launch-agent (or the",
|
|
246
253
|
"web) is the ONLY launch path (#660), the one the runner supervises and relaunches.",
|
|
247
254
|
"viber-gateway has no --help: an unknown verb runs the startup command (exit 2",
|
package/lib/codex_model_pair.ts
CHANGED
|
@@ -93,14 +93,11 @@ async function collectCatalogue(fetchPage: ModelListFetch, expired: () => boolea
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
96
|
+
* #747: THIS codex's whole catalogue (`model/list`, every page), model slug → efforts, in the
|
|
97
|
+
* order codex answers. One deadline covers the whole pagination; an RPC failure, a malformed
|
|
98
|
+
* answer or the deadline all throw.
|
|
98
99
|
*/
|
|
99
|
-
export async function
|
|
100
|
-
pair: CodexPair,
|
|
101
|
-
fetchPage: ModelListFetch,
|
|
102
|
-
timeoutMs: number,
|
|
103
|
-
): Promise<void> {
|
|
100
|
+
export async function readCodexCatalogue(fetchPage: ModelListFetch, timeoutMs: number): Promise<Map<string, string[]>> {
|
|
104
101
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
105
102
|
let expired = false;
|
|
106
103
|
const deadline = new Promise<never>((_, reject) => {
|
|
@@ -111,20 +108,33 @@ export async function verifyCodexPair(
|
|
|
111
108
|
});
|
|
112
109
|
const walk = collectCatalogue(fetchPage, () => expired);
|
|
113
110
|
walk.catch(() => {}); // after the deadline its own rejection has nobody left to tell
|
|
111
|
+
try {
|
|
112
|
+
return await Promise.race([walk, deadline]);
|
|
113
|
+
} finally {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Throw unless THIS codex's catalogue carries the pair (the bridge, at startup).
|
|
120
|
+
*/
|
|
121
|
+
export async function verifyCodexPair(
|
|
122
|
+
pair: CodexPair,
|
|
123
|
+
fetchPage: ModelListFetch,
|
|
124
|
+
timeoutMs: number,
|
|
125
|
+
): Promise<void> {
|
|
114
126
|
let catalogue: Map<string, string[]>;
|
|
115
127
|
try {
|
|
116
|
-
catalogue = await
|
|
128
|
+
catalogue = await readCodexCatalogue(fetchPage, timeoutMs);
|
|
117
129
|
} catch (err) {
|
|
118
130
|
const why = err instanceof Error ? err.message : String(err);
|
|
119
131
|
throw new Error(`cannot check codex model ${pair.model} / effort ${pair.effort}: ${why}`);
|
|
120
|
-
} finally {
|
|
121
|
-
clearTimeout(timer);
|
|
122
132
|
}
|
|
123
133
|
const efforts = catalogue.get(pair.model);
|
|
124
134
|
if (efforts === undefined) {
|
|
125
135
|
throw new Error(
|
|
126
136
|
`codex model ${pair.model} is absent from the catalogue of THIS codex (has: ${[...catalogue.keys()].join(", ")}) — ` +
|
|
127
|
-
"
|
|
137
|
+
"run `viber-gateway refresh-models` (it updates codex) or re-edit the template",
|
|
128
138
|
);
|
|
129
139
|
}
|
|
130
140
|
if (!efforts.includes(pair.effort)) {
|