viber-channel 0.8.8 → 0.8.9
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/auth.ts +5 -0
- package/lib/base_urls.ts +250 -0
- package/lib/bridge_core.ts +200 -34
- package/lib/bridge_tool_host.ts +24 -8
- package/lib/channel_instructions.ts +87 -15
- package/lib/channel_session.ts +10 -0
- package/lib/claude_tool_defs.ts +124 -0
- package/lib/control_stream.ts +9 -2
- package/lib/conversation.ts +6 -0
- package/lib/dm_stream.ts +7 -2
- package/lib/hash_key.ts +65 -0
- package/lib/heartbeat.ts +13 -4
- package/lib/instance.ts +16 -2
- package/lib/lockfile.ts +9 -0
- package/lib/urls.ts +24 -3
- package/package.json +1 -1
- package/viber-channel.ts +46 -121
- package/viber-codex-bridge.ts +72 -27
- package/viber-gemma-bridge.ts +28 -8
package/viber-channel.ts
CHANGED
|
@@ -30,6 +30,8 @@ import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprot
|
|
|
30
30
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
|
|
31
31
|
import { join } from "node:path";
|
|
32
32
|
import { runConnect } from "./lib/connect.ts";
|
|
33
|
+
import { ApiBaseUrlResolver, identityBaseUrl } from "./lib/base_urls.ts";
|
|
34
|
+
import { isTrustedViberOrigin } from "./lib/urls.ts";
|
|
33
35
|
import { lockFilePath, lockSessionId } from "./lib/lockfile.ts";
|
|
34
36
|
import { resolveSessionFilePath, namedAgentLabel, clearHandle } from "./lib/channel_session.ts";
|
|
35
37
|
import { clientFingerprint } from "./lib/fingerprint.ts";
|
|
@@ -55,7 +57,8 @@ import {
|
|
|
55
57
|
} from "./lib/token_refresh.ts";
|
|
56
58
|
import { awaitStableStartup } from "./lib/startup_gate.ts";
|
|
57
59
|
import { agentIdentityFromEnv } from "./lib/bridge_core.ts";
|
|
58
|
-
import { buildChannelInstructions } from "./lib/channel_instructions.ts";
|
|
60
|
+
import { buildChannelInstructions, IDENTITY_BUDGET } from "./lib/channel_instructions.ts";
|
|
61
|
+
import { CLAUDE_TOOL_DEFS } from "./lib/claude_tool_defs.ts";
|
|
59
62
|
import { warnIfStale } from "./lib/version_check.ts";
|
|
60
63
|
import { capabilitiesText } from "./lib/capabilities.ts";
|
|
61
64
|
|
|
@@ -185,7 +188,9 @@ const LOCK_DIR =
|
|
|
185
188
|
process.env.APPDATA
|
|
186
189
|
? join(process.env.APPDATA, "viber")
|
|
187
190
|
: join(process.env.HOME ?? "/tmp", ".config", "viber");
|
|
188
|
-
|
|
191
|
+
// #480: the lock hash is keyed on the LOGICAL backend identity, never on the
|
|
192
|
+
// (possibly redirected, possibly normalized) API host — see lib/base_urls.ts.
|
|
193
|
+
const LOCK_BASE_URL = identityBaseUrl();
|
|
189
194
|
// #269: a fleet's parallel agents each carry their own VIBER_INSTANCE_TOKEN but
|
|
190
195
|
// often no VIBER_CHANNEL_SESSION_ID. Fold a HASH of the instance token into the
|
|
191
196
|
// lock's session axis so distinct env-injected instances get distinct locks
|
|
@@ -398,7 +403,17 @@ import {
|
|
|
398
403
|
} from "./lib/agent_tools.ts";
|
|
399
404
|
import { cfAccessHeaders } from "./lib/cfAccess.ts";
|
|
400
405
|
|
|
401
|
-
|
|
406
|
+
// #480: apiBase() is the TRANSPORT host (what we fetch). WEB_URL is the host a
|
|
407
|
+
// HUMAN should visit — a user has nothing to do on viber-api-staging, so links
|
|
408
|
+
// printed for them keep pointing at the web frontend. In step-02 both resolve to
|
|
409
|
+
// the same value unless VIBER_API_BASE_URL is set.
|
|
410
|
+
// #480: the API host is STATE, not a constant — the server announces it on the
|
|
411
|
+
// first authenticated response, so every transport read goes through apiBase().
|
|
412
|
+
// Declared here (not a module global inside base_urls.ts) so ownership is
|
|
413
|
+
// explicit and tests can build their own resolver.
|
|
414
|
+
const API = new ApiBaseUrlResolver(isTrustedViberOrigin);
|
|
415
|
+
const apiBase = (): string => API.current();
|
|
416
|
+
const WEB_URL = identityBaseUrl();
|
|
402
417
|
const label = process.env.VIBER_CONVERSATION_LABEL ?? defaultLabel(process.cwd());
|
|
403
418
|
|
|
404
419
|
// ---- MCP server ----
|
|
@@ -413,114 +428,15 @@ const mcp = new Server(
|
|
|
413
428
|
// The blob lives in a PURE builder (lib/channel_instructions.ts) so it can be
|
|
414
429
|
// asserted in tests without booting the server (#390). Identity is "" for JP's
|
|
415
430
|
// own session (no explicit-name flag) → filtered out; the rest applies to all.
|
|
416
|
-
|
|
431
|
+
// #479: the identity line is clipped to IDENTITY_BUDGET by US, so the client's
|
|
432
|
+
// ~2048 cut can no longer eat the tail of the contract.
|
|
433
|
+
instructions: buildChannelInstructions(agentIdentityFromEnv(IDENTITY_BUDGET)),
|
|
417
434
|
}
|
|
418
435
|
);
|
|
419
436
|
|
|
420
437
|
// ---- Tool registration (ListTools + CallTool) ----
|
|
421
438
|
|
|
422
|
-
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
423
|
-
tools: [
|
|
424
|
-
{
|
|
425
|
-
name: "send_message",
|
|
426
|
-
description:
|
|
427
|
-
"Reply to the USER. This is how you talk to the user — NOT the terminal / your stdout (they do not watch it). Calling this IS your reply for the turn. " +
|
|
428
|
-
"Send a message into the Viber conversation this channel is bound to. " +
|
|
429
|
-
"`text` is the conversational reply — it is BOTH read aloud (TTS) AND rendered as Markdown on screen, so keep it short and natural but use light Markdown (short bullet/numbered lists, **bold**) when it aids readability. Put any ACTIONS or QUESTIONS for the user here, visibly. " +
|
|
430
|
-
"`artifact` is optional and carries HEAVY/LONG content (big code, large tables, long analyses, JSON, sanitized HTML) rendered in a side viewer; when used, keep `text` a brief summary that points to it. " +
|
|
431
|
-
"Use `html` only when structural HTML markdown can't express is required; scripts and event handlers are stripped before display.",
|
|
432
|
-
inputSchema: {
|
|
433
|
-
type: "object" as const,
|
|
434
|
-
properties: {
|
|
435
|
-
text: {
|
|
436
|
-
type: "string",
|
|
437
|
-
minLength: 1,
|
|
438
|
-
description: "Conversational reply, read aloud AND shown as Markdown. Short and natural, but use light Markdown (short lists, numbered steps, **bold**) for readability. Actions/questions go here, visibly. NO emoji (it gets read aloud).",
|
|
439
|
-
},
|
|
440
|
-
artifact: {
|
|
441
|
-
type: "object",
|
|
442
|
-
description: "Optional technical content rendered in the artifact viewer alongside the spoken text.",
|
|
443
|
-
properties: {
|
|
444
|
-
content: {
|
|
445
|
-
type: "string",
|
|
446
|
-
minLength: 1,
|
|
447
|
-
description: "Artifact body — markdown, code, JSON, or HTML.",
|
|
448
|
-
},
|
|
449
|
-
format: {
|
|
450
|
-
type: "string",
|
|
451
|
-
enum: ["markdown", "code", "json", "html"],
|
|
452
|
-
description:
|
|
453
|
-
"Render format for the artifact body. Defaults to markdown if omitted. " +
|
|
454
|
-
"Use `html` only when structural HTML is required (styled cards, badges, mixed layouts); " +
|
|
455
|
-
"scripts, event handlers, iframes, and inline styles are stripped server-side before rendering.",
|
|
456
|
-
},
|
|
457
|
-
},
|
|
458
|
-
required: ["content"],
|
|
459
|
-
},
|
|
460
|
-
},
|
|
461
|
-
required: ["text"],
|
|
462
|
-
},
|
|
463
|
-
},
|
|
464
|
-
{
|
|
465
|
-
name: "list_agents",
|
|
466
|
-
description:
|
|
467
|
-
"List the OTHER agents (instances) you can talk to directly (#288). " +
|
|
468
|
-
"Returns each agent's id, label, runtime kind, and whether it is currently online. " +
|
|
469
|
-
"Use this to find the id of an agent (e.g. 'Codex Review') before calling message_agent. " +
|
|
470
|
-
"Normally scoped to this project; if the owner designated this instance an ORCHESTRATOR " +
|
|
471
|
-
"(#307), the list covers ALL the owner's projects and each entry carries a `project` field. " +
|
|
472
|
-
"You are never in the list.",
|
|
473
|
-
inputSchema: {
|
|
474
|
-
type: "object" as const,
|
|
475
|
-
properties: {},
|
|
476
|
-
required: [],
|
|
477
|
-
additionalProperties: false,
|
|
478
|
-
},
|
|
479
|
-
},
|
|
480
|
-
{
|
|
481
|
-
name: "message_agent",
|
|
482
|
-
description:
|
|
483
|
-
"Send a direct message to ANOTHER agent (#288) — NOT for replying to the user (use send_message for that). " +
|
|
484
|
-
"Pass the target agent's instance id (from list_agents, or the from_instance_id of a DM you received) " +
|
|
485
|
-
"and the message text. Opens or reuses a private 1:1 DM with that agent and posts your message; " +
|
|
486
|
-
"the agent's reply arrives back on this channel tagged source=agent-dm. " +
|
|
487
|
-
"Targets are normally same-project; an ORCHESTRATOR instance (#307) can also message agents " +
|
|
488
|
-
"of the owner's other projects (ids from its cross-project list_agents). " +
|
|
489
|
-
"Fails if the target agent is offline.",
|
|
490
|
-
inputSchema: {
|
|
491
|
-
type: "object" as const,
|
|
492
|
-
properties: {
|
|
493
|
-
instance_id: {
|
|
494
|
-
type: "string",
|
|
495
|
-
minLength: 1,
|
|
496
|
-
description: "The target agent's instance id (from list_agents or a received DM's from_instance_id).",
|
|
497
|
-
},
|
|
498
|
-
text: {
|
|
499
|
-
type: "string",
|
|
500
|
-
minLength: 1,
|
|
501
|
-
description: "The message to send to the target agent.",
|
|
502
|
-
},
|
|
503
|
-
},
|
|
504
|
-
required: ["instance_id", "text"],
|
|
505
|
-
additionalProperties: false,
|
|
506
|
-
},
|
|
507
|
-
},
|
|
508
|
-
{
|
|
509
|
-
name: "capabilities",
|
|
510
|
-
description:
|
|
511
|
-
"On-demand: learn what the Viber control plane (vibe-master) can do on this " +
|
|
512
|
-
"machine — how to spawn and supervise OTHER agents (Codex, Claude, Gemma). " +
|
|
513
|
-
"Call this only when orchestrating other agents is relevant; it is not part " +
|
|
514
|
-
"of the default context. Returns a short usage reference.",
|
|
515
|
-
inputSchema: {
|
|
516
|
-
type: "object" as const,
|
|
517
|
-
properties: {},
|
|
518
|
-
required: [],
|
|
519
|
-
additionalProperties: false,
|
|
520
|
-
},
|
|
521
|
-
},
|
|
522
|
-
],
|
|
523
|
-
}));
|
|
439
|
+
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: CLAUDE_TOOL_DEFS }));
|
|
524
440
|
|
|
525
441
|
// Live, by-reference view of this channel's runtime state for the shared tool
|
|
526
442
|
// logic (#317, lib/agent_tools.ts). Every getter reads the current module var at
|
|
@@ -528,7 +444,7 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
|
528
444
|
// Codex bridge implements the same AgentToolsContext against its own runtime,
|
|
529
445
|
// so both hosts run ONE tool implementation (no double maintenance).
|
|
530
446
|
const channelToolsCtx: AgentToolsContext = {
|
|
531
|
-
baseUrl: () =>
|
|
447
|
+
baseUrl: () => apiBase(),
|
|
532
448
|
instanceToken: () => INSTANCE_TOKEN,
|
|
533
449
|
voiceBaseUrl: () => VOICE_BASE_URL,
|
|
534
450
|
// send_message posts into the main conversation for the Claude MCP.
|
|
@@ -545,7 +461,7 @@ const channelToolsCtx: AgentToolsContext = {
|
|
|
545
461
|
}),
|
|
546
462
|
};
|
|
547
463
|
|
|
548
|
-
// NOTE: CONVERSATION_TOKEN
|
|
464
|
+
// NOTE: CONVERSATION_TOKEN and CONVERSATION_ID are populated after
|
|
549
465
|
// mintConversation() runs (below). The handler closure captures the variables
|
|
550
466
|
// by reference — by the time Claude Code calls the tool, they are populated.
|
|
551
467
|
mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
@@ -707,7 +623,12 @@ try {
|
|
|
707
623
|
// VIBER_INSTANCE_TOKEN > persisted auth.json instance_token > register a new
|
|
708
624
|
// one with the stable project_token (self-healing auth.json). The conversation
|
|
709
625
|
// handle is namespaced by the instance, not the local fingerprint/sessionId.
|
|
710
|
-
const acquired = await acquireInstance(
|
|
626
|
+
const acquired = await acquireInstance(apiBase(), auth, auth.client_fingerprint);
|
|
627
|
+
// #480: adopt as EARLY as possible. Register is the first authenticated
|
|
628
|
+
// response, and the heartbeat + control stream start right after this block —
|
|
629
|
+
// adopting later would leave the dominant traffic on the bootstrap host for the
|
|
630
|
+
// whole session (review of step-03).
|
|
631
|
+
API.offer(acquired.api_base_url);
|
|
711
632
|
let instanceToken = acquired.instance_token;
|
|
712
633
|
// Self-echo guard (#280 step-16) needs the REAL server instance id — never the
|
|
713
634
|
// token that instance_key may fall back to (Codex review P1). Undefined → ""
|
|
@@ -771,7 +692,7 @@ try {
|
|
|
771
692
|
try {
|
|
772
693
|
minted = await acquireConversation(
|
|
773
694
|
SESSION_FILE,
|
|
774
|
-
|
|
695
|
+
apiBase(),
|
|
775
696
|
auth.project_id,
|
|
776
697
|
instanceToken,
|
|
777
698
|
auth.client_fingerprint,
|
|
@@ -791,7 +712,7 @@ try {
|
|
|
791
712
|
`[viber-channel] instance token rejected (401 revoked) — re-registering a fresh instance once\n`,
|
|
792
713
|
);
|
|
793
714
|
const reg = await registerInstance(
|
|
794
|
-
|
|
715
|
+
apiBase(),
|
|
795
716
|
auth.project_id,
|
|
796
717
|
auth.project_token,
|
|
797
718
|
auth.client_fingerprint,
|
|
@@ -800,7 +721,7 @@ try {
|
|
|
800
721
|
instanceToken = reg.instance_token;
|
|
801
722
|
OWN_INSTANCE_ID = reg.instance_id;
|
|
802
723
|
// #398: re-attach the fresh (post-revocation) instance to its team.
|
|
803
|
-
await maybeAttachTeam(
|
|
724
|
+
await maybeAttachTeam(apiBase(), auth.project_id, auth.project_token, auth.client_fingerprint, reg.instance_id);
|
|
804
725
|
// #400: keep the SAME namespacing rule after a post-revocation re-register.
|
|
805
726
|
// A named agent stays keyed by its stable name (not the new instance_id),
|
|
806
727
|
// so its handle survives; the plain channel re-keys to the fresh id.
|
|
@@ -808,7 +729,7 @@ try {
|
|
|
808
729
|
try {
|
|
809
730
|
minted = await acquireConversation(
|
|
810
731
|
SESSION_FILE,
|
|
811
|
-
|
|
732
|
+
apiBase(),
|
|
812
733
|
auth.project_id,
|
|
813
734
|
instanceToken,
|
|
814
735
|
auth.client_fingerprint,
|
|
@@ -835,6 +756,10 @@ try {
|
|
|
835
756
|
// (below) is the short-lived tier and self-refreshes.
|
|
836
757
|
|
|
837
758
|
CONVERSATION_TOKEN = minted.conversation_token;
|
|
759
|
+
// #480: second chance to adopt — the paths that reuse a persisted/env token
|
|
760
|
+
// never register, so mint is their first announcement. Idempotent.
|
|
761
|
+
API.offer(minted.api_base_url);
|
|
762
|
+
// NB ws_url is the VOICE host (tunnel), never the REST host — do not conflate.
|
|
838
763
|
VOICE_BASE_URL = minted.ws_url;
|
|
839
764
|
CONVERSATION_ID = minted.conversation_id;
|
|
840
765
|
// Capture the durable instance_token for the agent-facing MCP tools (#288).
|
|
@@ -849,7 +774,7 @@ try {
|
|
|
849
774
|
// logged only: the conversation-token path already fails closed.
|
|
850
775
|
if (OWN_INSTANCE_ID !== "") {
|
|
851
776
|
const controlStream = runPersistentControlStream(
|
|
852
|
-
{
|
|
777
|
+
{ getBaseUrl: apiBase, instanceId: OWN_INSTANCE_ID, instanceToken },
|
|
853
778
|
{
|
|
854
779
|
log: (m) => process.stderr.write(m),
|
|
855
780
|
onJoin: (pushed) => startDmStream(pushed),
|
|
@@ -857,7 +782,7 @@ try {
|
|
|
857
782
|
process.stderr.write(`[viber-channel] control stream stopped (${reason})\n`),
|
|
858
783
|
// #311: the server is probing — answer with an immediate instance heartbeat.
|
|
859
784
|
onBeatNow: () => {
|
|
860
|
-
void sendInstanceHeartbeat(
|
|
785
|
+
void sendInstanceHeartbeat(apiBase(), OWN_INSTANCE_ID, INSTANCE_TOKEN);
|
|
861
786
|
},
|
|
862
787
|
},
|
|
863
788
|
);
|
|
@@ -870,7 +795,7 @@ try {
|
|
|
870
795
|
// half-open behind the tunnel). The instance_token is durable (#269/#274),
|
|
871
796
|
// read via closure so a re-register is picked up. unref'd internally.
|
|
872
797
|
const instanceHeartbeat = startInstanceHeartbeat({
|
|
873
|
-
|
|
798
|
+
getBaseUrl: apiBase,
|
|
874
799
|
instanceId: OWN_INSTANCE_ID,
|
|
875
800
|
getInstanceToken: () => INSTANCE_TOKEN,
|
|
876
801
|
// #400 (recadrage): renew this agent's conversation lease each beat. If the
|
|
@@ -933,7 +858,7 @@ try {
|
|
|
933
858
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
934
859
|
try {
|
|
935
860
|
const refreshed = await refreshConversationToken(
|
|
936
|
-
|
|
861
|
+
apiBase(),
|
|
937
862
|
CONVERSATION_ID,
|
|
938
863
|
CONVERSATION_TOKEN,
|
|
939
864
|
auth.client_fingerprint,
|
|
@@ -986,14 +911,14 @@ try {
|
|
|
986
911
|
// the user knows what to do instead of failing opaquely. Clean exit, no retry.
|
|
987
912
|
process.stderr.write(`[viber-channel] ${String(err)}\n`);
|
|
988
913
|
process.stderr.write(
|
|
989
|
-
`[viber-channel] If your project_token is no longer valid, run the connect flow again at ${
|
|
914
|
+
`[viber-channel] If your project_token is no longer valid, run the connect flow again at ${WEB_URL}/projects.\n`
|
|
990
915
|
);
|
|
991
916
|
await mcp.notification({
|
|
992
917
|
method: "notifications/claude/channel",
|
|
993
918
|
params: {
|
|
994
919
|
content:
|
|
995
920
|
`⚠️ Could not start the voice channel: ${String(err)}. ` +
|
|
996
|
-
`If your project_token was revoked, reconnect at ${
|
|
921
|
+
`If your project_token was revoked, reconnect at ${WEB_URL}/projects and run ` +
|
|
997
922
|
`\`bunx viber-channel connect <url>\` again, then restart this channel. ` +
|
|
998
923
|
`Otherwise this may be a temporary network issue — restart the channel to retry.`,
|
|
999
924
|
meta: { source: "system", type: "project_token_invalid" },
|
|
@@ -1081,7 +1006,7 @@ function ackInboundReceipt(msg: {
|
|
|
1081
1006
|
if (!idStr) return;
|
|
1082
1007
|
if (ackedMessageIds.has(idStr) || ackInFlightMessageIds.has(idStr)) return;
|
|
1083
1008
|
ackInFlightMessageIds.add(idStr);
|
|
1084
|
-
void ackMessage(
|
|
1009
|
+
void ackMessage(apiBase(), CONVERSATION_ID, CONVERSATION_TOKEN, idStr)
|
|
1085
1010
|
.then((ok) => {
|
|
1086
1011
|
if (ok) ackedMessageIds.add(idStr);
|
|
1087
1012
|
else process.stderr.write(`[viber-channel] ack failed for message ${idStr} (will retry on next delivery)\n`);
|
|
@@ -1197,7 +1122,7 @@ function startDmStream(minted: ConversationMintResponse): void {
|
|
|
1197
1122
|
// per-DM conversation heartbeat (#298) was removed in #315.
|
|
1198
1123
|
void runDmStream({
|
|
1199
1124
|
wsUrl: minted.ws_url,
|
|
1200
|
-
|
|
1125
|
+
getApiBaseUrl: apiBase,
|
|
1201
1126
|
conversationId: minted.conversation_id,
|
|
1202
1127
|
conversationToken: minted.conversation_token,
|
|
1203
1128
|
log: (m) => process.stderr.write(m),
|
package/viber-codex-bridge.ts
CHANGED
|
@@ -11,12 +11,15 @@ import { createHash } from "node:crypto";
|
|
|
11
11
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
12
|
import { dirname, join } from "node:path";
|
|
13
13
|
import { authFilePath, loadAuth } from "./lib/auth.ts";
|
|
14
|
+
import { CONTRACT_STYLE_NEUTRAL, CONTRACT_STYLE_TOOLS } from "./lib/channel_instructions.ts";
|
|
14
15
|
import {
|
|
15
16
|
ConversationMintError,
|
|
16
17
|
defaultLabel,
|
|
17
18
|
reattachConversation,
|
|
18
19
|
type ConversationMintResponse,
|
|
19
20
|
} from "./lib/conversation.ts";
|
|
21
|
+
import { ApiBaseUrlResolver, identityBaseUrl } from "./lib/base_urls.ts";
|
|
22
|
+
import { isTrustedViberOrigin } from "./lib/urls.ts";
|
|
20
23
|
import { sessionFilePath, writeHandle } from "./lib/channel_session.ts";
|
|
21
24
|
import { clientFingerprint } from "./lib/fingerprint.ts";
|
|
22
25
|
import { acquireInstance, instanceKindFromEnv, maybeAttachTeam, registerInstance } from "./lib/instance.ts";
|
|
@@ -25,8 +28,10 @@ import {
|
|
|
25
28
|
agentIdentityFromEnv,
|
|
26
29
|
BridgeShutdownError,
|
|
27
30
|
type BridgeLock,
|
|
31
|
+
type BridgeWatermark,
|
|
28
32
|
type ConversationMessage,
|
|
29
33
|
type ConversationRuntime,
|
|
34
|
+
type ConversationStreamDeps,
|
|
30
35
|
decideTurnPostAction,
|
|
31
36
|
type MakeRunTurn,
|
|
32
37
|
planAwaitInviteFirstPass,
|
|
@@ -65,7 +70,12 @@ import { startBridgeToolHost, type BridgeToolHost } from "./lib/bridge_tool_host
|
|
|
65
70
|
import type { AgentToolsContext } from "./lib/agent_tools.ts";
|
|
66
71
|
import type { OpenDmResult } from "./lib/peers.ts";
|
|
67
72
|
|
|
68
|
-
|
|
73
|
+
// #480: transport host vs logical identity. IDENTITY_URL is what the session and
|
|
74
|
+
// bridge-lock hashes are keyed on (this file builds several of them, below) —
|
|
75
|
+
// never apiBase(), which may point at another host or be normalized.
|
|
76
|
+
const API = new ApiBaseUrlResolver(isTrustedViberOrigin);
|
|
77
|
+
const apiBase = (): string => API.current();
|
|
78
|
+
const IDENTITY_URL = identityBaseUrl();
|
|
69
79
|
const LOCK_DIR =
|
|
70
80
|
process.env.APPDATA
|
|
71
81
|
? join(process.env.APPDATA, "viber")
|
|
@@ -221,8 +231,11 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):
|
|
|
221
231
|
|
|
222
232
|
// isProcessAlive + acquireBridgeLock moved to ./lib/bridge_core.ts (#318). A thin
|
|
223
233
|
// local binder keeps the call sites (and the per-agent log prefix) unchanged.
|
|
224
|
-
|
|
225
|
-
|
|
234
|
+
// #480: the parameter is the IDENTITY host, not the transport one — call sites
|
|
235
|
+
// pass IDENTITY_URL. Named accordingly so a future edit can't quietly hand it
|
|
236
|
+
// apiBase() and move every lock path.
|
|
237
|
+
function acquireBridgeLock(identityBaseUrl: string, fingerprint: string, sessionId: string): BridgeLock {
|
|
238
|
+
return coreAcquireBridgeLock({ identityBaseUrl, fingerprint, sessionId, lockDir: LOCK_DIR, logPrefix: LOG_PREFIX });
|
|
226
239
|
}
|
|
227
240
|
|
|
228
241
|
// shouldHandleMessage, planAwaitInviteFirstPass, senderLabel moved to
|
|
@@ -381,8 +394,15 @@ function resolveAgentTier(): AgentTier {
|
|
|
381
394
|
return "chat";
|
|
382
395
|
}
|
|
383
396
|
|
|
384
|
-
|
|
385
|
-
|
|
397
|
+
// #479 volet 2: the channel contract reaches codex here. It used to live ONLY in
|
|
398
|
+
// the MCP `instructions` blob of the Claude server, which no bridge ever reads —
|
|
399
|
+
// so NO EMOJI and the literal-identifier rule were absent from this runtime, and
|
|
400
|
+
// the tool schema even carried the retired "Plain sentences." rule. The fragments
|
|
401
|
+
// come from `channel_instructions.ts`, the contract's single home.
|
|
402
|
+
// Exported so a test can assert STRUCTURALLY that codex receives the shared
|
|
403
|
+
// fragments (#479 opus review): a regex on the text would still pass if the
|
|
404
|
+
// fragments changed and this line stopped matching them.
|
|
405
|
+
export const VOICE_CONCISE_LINE = `Your replies are returned to a voice/text conversation. ${CONTRACT_STYLE_NEUTRAL} ${CONTRACT_STYLE_TOOLS}`;
|
|
386
406
|
|
|
387
407
|
// #317 (iii): Codex now has the SAME three channel tools as Claude, served by the
|
|
388
408
|
// bridge's in-process MCP host. Describe them and the reply semantics. The legacy
|
|
@@ -920,14 +940,17 @@ async function acquireTargetConversation(
|
|
|
920
940
|
mkdirSync(LOCK_DIR, { recursive: true });
|
|
921
941
|
|
|
922
942
|
const label = process.env.VIBER_CODEX_BRIDGE_LABEL ?? `Codex bridge • ${defaultLabel(process.cwd())}`;
|
|
923
|
-
const acquired = await acquireBridgeInstance(
|
|
943
|
+
const acquired = await acquireBridgeInstance(apiBase(), auth, fingerprint, label, options);
|
|
944
|
+
// #480: adopt the announced host as soon as it is known — every long-lived flow
|
|
945
|
+
// started below (reattach, streams, refreshes, heartbeat) reads api.current().
|
|
946
|
+
API.offer(acquired.api_base_url);
|
|
924
947
|
let instanceToken = acquired.instance_token;
|
|
925
948
|
let instanceKey = acquired.instance_key;
|
|
926
|
-
let sessionPath = sessionFilePath(
|
|
949
|
+
let sessionPath = sessionFilePath(IDENTITY_URL, `${instanceKey}:codex:${targetConversationId}`, LOCK_DIR);
|
|
927
950
|
// #280 step-12: take the per-agent lock BEFORE reattach. reattach rotates the
|
|
928
951
|
// per-membership token, so a losing duplicate launch of the SAME identity must be
|
|
929
952
|
// stopped before it can rotate the winner's token (Codex review P2-B).
|
|
930
|
-
let bridgeLock = acquireBridgeLock(
|
|
953
|
+
let bridgeLock = acquireBridgeLock(IDENTITY_URL, fingerprint, `codex-agent:${instanceKey}`);
|
|
931
954
|
|
|
932
955
|
process.stderr.write(
|
|
933
956
|
`[viber-codex-bridge] joining conversation ${targetConversationId} (project=${auth.project_id}, session=${sessionPath})\n`,
|
|
@@ -938,12 +961,13 @@ async function acquireTargetConversation(
|
|
|
938
961
|
try {
|
|
939
962
|
try {
|
|
940
963
|
const minted = await reattachConversation(
|
|
941
|
-
|
|
964
|
+
apiBase(),
|
|
942
965
|
auth.project_id,
|
|
943
966
|
instanceToken,
|
|
944
967
|
fingerprint,
|
|
945
968
|
targetConversationId,
|
|
946
969
|
);
|
|
970
|
+
API.offer(minted.api_base_url);
|
|
947
971
|
writeHandle(sessionPath, minted.conversation_id);
|
|
948
972
|
process.stderr.write(`[viber-codex-bridge] join OK, conv_id=${minted.conversation_id}\n`);
|
|
949
973
|
return { minted, fingerprint, instanceKey, instanceToken, auth, bridgeLock };
|
|
@@ -952,26 +976,28 @@ async function acquireTargetConversation(
|
|
|
952
976
|
process.stderr.write(
|
|
953
977
|
"[viber-codex-bridge] instance token rejected (401 revoked) — re-registering a fresh instance once\n",
|
|
954
978
|
);
|
|
955
|
-
const reg = await registerInstance(
|
|
979
|
+
const reg = await registerInstance(apiBase(), auth.project_id, auth.project_token, fingerprint, label, instanceKindFromEnv() ?? "codex");
|
|
980
|
+
API.offer(reg.api_base_url);
|
|
956
981
|
instanceToken = reg.instance_token;
|
|
957
982
|
instanceKey = reg.instance_id;
|
|
958
983
|
// #398: re-attach the fresh (post-revocation) codex instance to its team.
|
|
959
|
-
await maybeAttachTeam(
|
|
984
|
+
await maybeAttachTeam(apiBase(), auth.project_id, auth.project_token, fingerprint, reg.instance_id);
|
|
960
985
|
// Identity changed → re-key the lock onto the new instance. Acquire the new
|
|
961
986
|
// lock BEFORE releasing the old one: if acquisition throws, the old lock is
|
|
962
987
|
// still held and the outer catch releases exactly it (no dangling reference).
|
|
963
|
-
const reLock = acquireBridgeLock(
|
|
988
|
+
const reLock = acquireBridgeLock(IDENTITY_URL, fingerprint, `codex-agent:${instanceKey}`);
|
|
964
989
|
bridgeLock.release();
|
|
965
990
|
bridgeLock = reLock;
|
|
966
|
-
sessionPath = sessionFilePath(
|
|
991
|
+
sessionPath = sessionFilePath(IDENTITY_URL, `${instanceKey}:codex:${targetConversationId}`, LOCK_DIR);
|
|
967
992
|
const minted = await reattachConversation(
|
|
968
|
-
|
|
993
|
+
apiBase(),
|
|
969
994
|
auth.project_id,
|
|
970
995
|
instanceToken,
|
|
971
996
|
fingerprint,
|
|
972
997
|
targetConversationId,
|
|
973
998
|
);
|
|
974
|
-
|
|
999
|
+
API.offer(minted.api_base_url);
|
|
1000
|
+
writeHandle(sessionPath, minted.conversation_id);
|
|
975
1001
|
process.stderr.write(`[viber-codex-bridge] join OK, conv_id=${minted.conversation_id}\n`);
|
|
976
1002
|
return { minted, fingerprint, instanceKey, instanceToken, auth, bridgeLock };
|
|
977
1003
|
}
|
|
@@ -1056,11 +1082,15 @@ async function acquireBridgeIdentity(
|
|
|
1056
1082
|
): Promise<{ instanceKey: string; instanceToken: string; bridgeLock: BridgeLock }> {
|
|
1057
1083
|
mkdirSync(LOCK_DIR, { recursive: true });
|
|
1058
1084
|
const label = process.env.VIBER_CODEX_BRIDGE_LABEL ?? `Codex bridge • ${defaultLabel(process.cwd())}`;
|
|
1059
|
-
const acquired = await acquireBridgeInstance(
|
|
1085
|
+
const acquired = await acquireBridgeInstance(apiBase(), auth, fingerprint, label, options);
|
|
1086
|
+
// #480: this exported helper starts a control stream + heartbeat right after,
|
|
1087
|
+
// so it must adopt here too — dropping the announcement would leave both on the
|
|
1088
|
+
// bootstrap host (review of step-04).
|
|
1089
|
+
API.offer(acquired.api_base_url);
|
|
1060
1090
|
const instanceKey = acquired.instance_key;
|
|
1061
1091
|
// #280 step-12: per-agent lock, held for the whole wait + lifetime. Two processes
|
|
1062
1092
|
// with the SAME identity can't both await an invite.
|
|
1063
|
-
const bridgeLock = acquireBridgeLock(
|
|
1093
|
+
const bridgeLock = acquireBridgeLock(IDENTITY_URL, fingerprint, `codex-agent:${instanceKey}`);
|
|
1064
1094
|
return { instanceKey, instanceToken: acquired.instance_token, bridgeLock };
|
|
1065
1095
|
}
|
|
1066
1096
|
|
|
@@ -1095,7 +1125,7 @@ export async function acquireConversationViaInvite(
|
|
|
1095
1125
|
|
|
1096
1126
|
const controlStream = runPersistentControlStream(
|
|
1097
1127
|
{
|
|
1098
|
-
|
|
1128
|
+
getBaseUrl: apiBase,
|
|
1099
1129
|
instanceId: instanceKey,
|
|
1100
1130
|
instanceToken,
|
|
1101
1131
|
signal: shutdown.signal,
|
|
@@ -1103,8 +1133,9 @@ export async function acquireConversationViaInvite(
|
|
|
1103
1133
|
{
|
|
1104
1134
|
log: (m) => process.stderr.write(m),
|
|
1105
1135
|
onJoin: (minted) => {
|
|
1106
|
-
const sessionPath = sessionFilePath(
|
|
1107
|
-
|
|
1136
|
+
const sessionPath = sessionFilePath(IDENTITY_URL, `${instanceKey}:codex:${minted.conversation_id}`, LOCK_DIR);
|
|
1137
|
+
API.offer(minted.api_base_url);
|
|
1138
|
+
writeHandle(sessionPath, minted.conversation_id);
|
|
1108
1139
|
},
|
|
1109
1140
|
// A revoke / 401 that arrives AFTER the first join (mid-conversation) must
|
|
1110
1141
|
// still stop the bridge — abort the shutdown controller the sseLoop watches.
|
|
@@ -1118,7 +1149,7 @@ export async function acquireConversationViaInvite(
|
|
|
1118
1149
|
},
|
|
1119
1150
|
// #311: answer the server's liveness probe with an immediate heartbeat.
|
|
1120
1151
|
onBeatNow: () => {
|
|
1121
|
-
void sendInstanceHeartbeat(
|
|
1152
|
+
void sendInstanceHeartbeat(apiBase(), instanceKey, instanceToken);
|
|
1122
1153
|
},
|
|
1123
1154
|
},
|
|
1124
1155
|
);
|
|
@@ -1127,7 +1158,7 @@ export async function acquireConversationViaInvite(
|
|
|
1127
1158
|
// never keeps this agent "online" after it dies. Stops on shutdown.
|
|
1128
1159
|
{
|
|
1129
1160
|
const ihb = startInstanceHeartbeat({
|
|
1130
|
-
|
|
1161
|
+
getBaseUrl: apiBase,
|
|
1131
1162
|
instanceId: instanceKey,
|
|
1132
1163
|
getInstanceToken: () => instanceToken,
|
|
1133
1164
|
});
|
|
@@ -1173,7 +1204,7 @@ function setupCodexRuntime(deps: {
|
|
|
1173
1204
|
}): { codex: CodexAppServer; toolHost: BridgeToolHost } {
|
|
1174
1205
|
const { tracker } = deps;
|
|
1175
1206
|
const bridgeToolsCtx: AgentToolsContext = {
|
|
1176
|
-
baseUrl: () =>
|
|
1207
|
+
baseUrl: () => apiBase(),
|
|
1177
1208
|
instanceToken: () => deps.instanceToken(),
|
|
1178
1209
|
voiceBaseUrl: () => deps.getVoiceBaseUrl(),
|
|
1179
1210
|
// send_message targets the conversation of the turn in flight (DM-aware).
|
|
@@ -1279,7 +1310,8 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<void
|
|
|
1279
1310
|
let toolHost: BridgeToolHost | null = null;
|
|
1280
1311
|
let codexInstanceKey = "";
|
|
1281
1312
|
await runAwaitInviteBridge({
|
|
1282
|
-
|
|
1313
|
+
api: API,
|
|
1314
|
+
identityBaseUrl: IDENTITY_URL,
|
|
1283
1315
|
lockDir: LOCK_DIR,
|
|
1284
1316
|
logPrefix: LOG_PREFIX,
|
|
1285
1317
|
sessionTag: "codex",
|
|
@@ -1313,20 +1345,33 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<void
|
|
|
1313
1345
|
// owns the one conversation directly. Kept codex-specific (gemma never uses it).
|
|
1314
1346
|
const shutdown = new AbortController();
|
|
1315
1347
|
const activeStreams = new Map<string, AbortController>();
|
|
1348
|
+
// Persistent per-conversation watermarks (#429) — one per bridge run, as on
|
|
1349
|
+
// the await-invite path. This path never had one (see the deps below).
|
|
1350
|
+
const watermarks = new Map<string, BridgeWatermark>();
|
|
1316
1351
|
let codex: CodexAppServer | null = null;
|
|
1317
1352
|
let toolHost: BridgeToolHost | null = null;
|
|
1318
1353
|
const res = await acquireTargetConversation(options.conversationId, options, auth, fingerprint);
|
|
1354
|
+
// `satisfies` (not `as const`) so an omitted field is a COMPILE error here,
|
|
1355
|
+
// at construction, instead of surfacing as `undefined` inside the stream.
|
|
1356
|
+
// #480 found this the hard way: `identityBaseUrl` was missing and the session
|
|
1357
|
+
// handle would have been keyed on the string "undefined" — silent, no test
|
|
1358
|
+
// failure, conversations re-minted in production.
|
|
1319
1359
|
const runTurnDeps = {
|
|
1320
1360
|
fingerprint,
|
|
1321
1361
|
instanceKey: res.instanceKey,
|
|
1322
1362
|
options,
|
|
1323
1363
|
activeStreams,
|
|
1364
|
+
// Pre-existing gap (#429 added `watermarks` to the deps but never to this
|
|
1365
|
+
// path): `runConversationStream` calls `watermarks.get(...)`, so this
|
|
1366
|
+
// object crashed with a TypeError. Found while fixing the above.
|
|
1367
|
+
watermarks,
|
|
1324
1368
|
parentSignal: shutdown.signal,
|
|
1325
|
-
|
|
1369
|
+
api: API,
|
|
1370
|
+
identityBaseUrl: IDENTITY_URL,
|
|
1326
1371
|
lockDir: LOCK_DIR,
|
|
1327
1372
|
logPrefix: LOG_PREFIX,
|
|
1328
1373
|
sessionTag: "codex",
|
|
1329
|
-
}
|
|
1374
|
+
} satisfies Omit<ConversationStreamDeps, "makeRunTurn">;
|
|
1330
1375
|
const rt = setupCodexRuntime({
|
|
1331
1376
|
tracker,
|
|
1332
1377
|
instanceToken: () => res.instanceToken,
|
|
@@ -1352,7 +1397,7 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<void
|
|
|
1352
1397
|
// falsely frees → another agent could load onto it. On a definite loss (a new
|
|
1353
1398
|
// holder took over), shut down so we never double-attach.
|
|
1354
1399
|
const ihb = startInstanceHeartbeat({
|
|
1355
|
-
|
|
1400
|
+
getBaseUrl: apiBase,
|
|
1356
1401
|
instanceId: res.instanceKey,
|
|
1357
1402
|
getInstanceToken: () => res.instanceToken,
|
|
1358
1403
|
getConversationId: () => res.minted.conversation_id,
|
package/viber-gemma-bridge.ts
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { join } from "node:path";
|
|
19
19
|
import { loadAuth } from "./lib/auth.ts";
|
|
20
|
+
import { ApiBaseUrlResolver, identityBaseUrl } from "./lib/base_urls.ts";
|
|
21
|
+
import { isTrustedViberOrigin } from "./lib/urls.ts";
|
|
22
|
+
import { CONTRACT_STYLE_NEUTRAL } from "./lib/channel_instructions.ts";
|
|
20
23
|
import { defaultLabel } from "./lib/conversation.ts";
|
|
21
24
|
import { clientFingerprint } from "./lib/fingerprint.ts";
|
|
22
25
|
import {
|
|
@@ -36,20 +39,36 @@ import {
|
|
|
36
39
|
} from "./lib/ollama_chat.ts";
|
|
37
40
|
|
|
38
41
|
const LOG_PREFIX = "[viber-gemma-bridge]";
|
|
39
|
-
|
|
42
|
+
// #480: transport host vs logical identity (the latter keys locks + handles).
|
|
43
|
+
const API = new ApiBaseUrlResolver(isTrustedViberOrigin);
|
|
44
|
+
const apiBase = (): string => API.current();
|
|
45
|
+
const IDENTITY_URL = identityBaseUrl();
|
|
40
46
|
const LOCK_DIR =
|
|
41
47
|
process.env.APPDATA
|
|
42
48
|
? join(process.env.APPDATA, "viber")
|
|
43
49
|
: join(process.env.HOME ?? "/tmp", ".config", "viber");
|
|
44
50
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Concise voice-friendly system prompt (ported from viber/standalone_ai.py).
|
|
53
|
+
*
|
|
54
|
+
* #479 volet 2: the channel contract now reaches gemma too — via the RUNTIME-NEUTRAL
|
|
55
|
+
* fragment only. Gemma has no tools and no artifact, so telling it to call
|
|
56
|
+
* send_message or to move content "to the side" would be an instruction it cannot
|
|
57
|
+
* follow. And since it has no filesystem either, everything it must obey has to be
|
|
58
|
+
* in this prompt: pointing it at a file would be inert.
|
|
59
|
+
*
|
|
60
|
+
* The old prompt said "no markdown" — the retired rule. Gemma's replies land in the
|
|
61
|
+
* same conversation as everyone else's: read aloud AND rendered as Markdown.
|
|
62
|
+
*/
|
|
63
|
+
export const SYSTEM_PROMPT =
|
|
64
|
+
"You are a friendly, concise voice assistant. Answer in the user's language. " +
|
|
65
|
+
"Keep replies to 2-3 sentences unless more detail is explicitly requested. " +
|
|
66
|
+
CONTRACT_STYLE_NEUTRAL;
|
|
50
67
|
// Append the agent identity (#309 step-17) after the base prompt so a spawned
|
|
51
68
|
// gemma agent knows its own name/role. Empty when neither was provided.
|
|
52
|
-
|
|
69
|
+
// Exported so a test can assert WHAT gemma is actually told (#479): it must carry
|
|
70
|
+
// the neutral contract and must NOT be told to use tools it does not have.
|
|
71
|
+
export const EFFECTIVE_SYSTEM_PROMPT = [SYSTEM_PROMPT, agentIdentityFromEnv()]
|
|
53
72
|
.filter((line) => line.length > 0)
|
|
54
73
|
.join("\n");
|
|
55
74
|
/** Keep the last N turns (user+assistant) of per-conversation history. */
|
|
@@ -146,7 +165,8 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<void
|
|
|
146
165
|
const label = process.env.VIBER_CODEX_BRIDGE_LABEL ?? `Gemma bridge • ${defaultLabel(process.cwd())}`;
|
|
147
166
|
|
|
148
167
|
await runAwaitInviteBridge({
|
|
149
|
-
|
|
168
|
+
api: API,
|
|
169
|
+
identityBaseUrl: IDENTITY_URL,
|
|
150
170
|
lockDir: LOCK_DIR,
|
|
151
171
|
logPrefix: LOG_PREFIX,
|
|
152
172
|
sessionTag: "gemma",
|