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.
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
17
17
  import { createTokenRefreshScheduler, type TokenRefreshScheduler } from "./token_refresh.js";
18
+ import type { ApiBaseUrlResolver } from "./base_urls.js";
18
19
  import { lockFilePath } from "./lockfile.js";
19
20
  import {
20
21
  type ConversationMintResponse,
@@ -178,15 +179,21 @@ export function isProcessAlive(pid: number): boolean {
178
179
  * bridge's log lines under its own tag.
179
180
  */
180
181
  export function acquireBridgeLock(opts: {
181
- baseUrl: string;
182
+ /**
183
+ * #480: the LOGICAL backend identity, NOT the API transport host. The lock
184
+ * path must stay stable when agent traffic is redirected, otherwise a running
185
+ * agent stops recognizing its own lock and the #311/#293 duplicate window
186
+ * re-opens. Injected rather than read from the env so this stays pure.
187
+ */
188
+ identityBaseUrl: string;
182
189
  fingerprint: string;
183
190
  sessionId: string;
184
191
  lockDir: string;
185
192
  logPrefix: string;
186
193
  }): BridgeLock {
187
- const { baseUrl, fingerprint, sessionId, lockDir, logPrefix } = opts;
194
+ const { identityBaseUrl, fingerprint, sessionId, lockDir, logPrefix } = opts;
188
195
  mkdirSync(lockDir, { recursive: true });
189
- const path = lockFilePath(baseUrl, fingerprint, sessionId, lockDir);
196
+ const path = lockFilePath(identityBaseUrl, fingerprint, sessionId, lockDir);
190
197
  const release = (): void => {
191
198
  try {
192
199
  unlinkSync(path);
@@ -250,11 +257,12 @@ function refreshLeadSeconds(logPrefix: string): number | undefined {
250
257
  export function startTokenRefresh(opts: {
251
258
  runtime: ConversationRuntime;
252
259
  fingerprint: string;
253
- baseUrl: string;
260
+ /** #480 — long-lived scheduler: read the host per refresh, never capture it. */
261
+ getBaseUrl: () => string;
254
262
  requestShutdown: (err: BridgeShutdownError) => void;
255
263
  logPrefix: string;
256
264
  }): TokenRefreshScheduler {
257
- const { runtime, fingerprint, baseUrl, requestShutdown, logPrefix } = opts;
265
+ const { runtime, fingerprint, getBaseUrl, requestShutdown, logPrefix } = opts;
258
266
  const leadSeconds = refreshLeadSeconds(logPrefix);
259
267
  const scheduler = createTokenRefreshScheduler(
260
268
  async () => {
@@ -262,7 +270,7 @@ export function startTokenRefresh(opts: {
262
270
  const headroomSeconds = 10;
263
271
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
264
272
  try {
265
- const refreshed = await refreshConversationToken(baseUrl, runtime.id, runtime.token, fingerprint);
273
+ const refreshed = await refreshConversationToken(getBaseUrl(), runtime.id, runtime.token, fingerprint);
266
274
  runtime.token = refreshed.conversation_token;
267
275
  runtime.expiresAt = refreshed.expires_at;
268
276
  process.stderr.write(`${logPrefix} token refreshed for conversation ${runtime.id}\n`);
@@ -428,7 +436,16 @@ export interface ConversationStreamDeps {
428
436
  watermarks: Map<string, BridgeWatermark>;
429
437
  /** Global shutdown signal — aborting it stops every stream. */
430
438
  parentSignal: AbortSignal;
431
- baseUrl: string;
439
+ /**
440
+ * #480: the API host as STATE, not a string. Passing the resolver rather than
441
+ * a captured value is what lets a long-lived stream follow the host the server
442
+ * announces mid-run; a `string` here would freeze the bootstrap host for the
443
+ * whole run. It also removes the swap hazard a second `string` field next to
444
+ * `identityBaseUrl` would create.
445
+ */
446
+ api: ApiBaseUrlResolver;
447
+ /** Logical backend identity — what the session handle is keyed on (#480). */
448
+ identityBaseUrl: string;
432
449
  lockDir: string;
433
450
  logPrefix: string;
434
451
  /** Session-handle tag distinguishing runtimes in the handle path (codex/gemma). */
@@ -453,7 +470,9 @@ export async function runConversationStream(
453
470
  minted: ConversationMintResponse,
454
471
  deps: ConversationStreamDeps,
455
472
  ): Promise<void> {
456
- const { fingerprint, instanceKey, options, activeStreams, watermarks, parentSignal, baseUrl, lockDir, logPrefix, sessionTag, makeRunTurn } = deps;
473
+ const { fingerprint, instanceKey, options, activeStreams, watermarks, parentSignal, api, identityBaseUrl, lockDir, logPrefix, sessionTag, makeRunTurn } = deps;
474
+ // #480: a FUNCTION, not a captured string — the host can change mid-stream.
475
+ const baseUrl = (): string => api.current();
457
476
  const convId = minted.conversation_id;
458
477
  if (parentSignal.aborted) return;
459
478
 
@@ -478,12 +497,14 @@ export async function runConversationStream(
478
497
  parentSignal.addEventListener("abort", onParentAbort, { once: true });
479
498
  // Per-conversation resume handle, keyed by conversation id so a secondary DM
480
499
  // never clobbers the main conversation's handle.
481
- writeHandle(sessionFilePath(baseUrl, `${instanceKey}:${sessionTag}:${convId}`, lockDir), convId);
500
+ // #480: keyed on the identity, not the transport host — a redirected agent
501
+ // must find the SAME handle and resume its conversation, not mint a new one.
502
+ writeHandle(sessionFilePath(identityBaseUrl, `${instanceKey}:${sessionTag}:${convId}`, lockDir), convId);
482
503
  // Token-refresh failure aborts ONLY this stream, not the whole bridge.
483
504
  startTokenRefresh({
484
505
  runtime,
485
506
  fingerprint,
486
- baseUrl,
507
+ getBaseUrl: baseUrl,
487
508
  requestShutdown: (err) => {
488
509
  if (!ctrl.signal.aborted) ctrl.abort(err);
489
510
  },
@@ -499,7 +520,7 @@ export async function runConversationStream(
499
520
  watermark = { lastId: 0 };
500
521
  watermarks.set(convId, watermark);
501
522
  }
502
- await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, baseUrl, logPrefix, runTurn, watermark });
523
+ await sseLoop({ minted, runtime, fingerprint, ownInstanceKey: instanceKey, options, signal: ctrl.signal, getBaseUrl: baseUrl, logPrefix, runTurn, watermark });
503
524
  } finally {
504
525
  parentSignal.removeEventListener("abort", onParentAbort);
505
526
  runtime.scheduler?.cancel();
@@ -537,7 +558,8 @@ export async function sseLoop(opts: {
537
558
  ownInstanceKey: string;
538
559
  options: SseLoopOptions;
539
560
  signal: AbortSignal;
540
- baseUrl: string;
561
+ /** #480 — the loop outlives the announcement; read the host per use. */
562
+ getBaseUrl: () => string;
541
563
  logPrefix: string;
542
564
  runTurn: RunTurn;
543
565
  /**
@@ -552,7 +574,8 @@ export async function sseLoop(opts: {
552
574
  /** Injectable catch-up fetch; defaults to messages.ts `fetchMessages`. */
553
575
  fetchMessagesImpl?: typeof fetchMessages;
554
576
  }): Promise<void> {
555
- const { minted, runtime, fingerprint, ownInstanceKey, options, signal, baseUrl, logPrefix, runTurn, watermark } = opts;
577
+ const { minted, runtime, fingerprint, ownInstanceKey, options, signal, getBaseUrl, logPrefix, runTurn, watermark } = opts;
578
+ const baseUrl = getBaseUrl; // called at each use below
556
579
  const fetchImpl = opts.fetchImpl ?? fetch;
557
580
  const fetchMessagesImpl = opts.fetchMessagesImpl ?? fetchMessages;
558
581
  const sseUrl = buildSseUrl(minted.ws_url, minted.conversation_id);
@@ -591,7 +614,7 @@ export async function sseLoop(opts: {
591
614
  process.stderr.write(`${logPrefix} turn on ${runtime.id} produced no text and used no outbound tool; nothing to deliver\n`);
592
615
  return false;
593
616
  case "auto-post":
594
- await postBridgeReply({ baseUrl, runtime, text: reply, ownPostedIds, signal, logPrefix });
617
+ await postBridgeReply({ baseUrl: baseUrl(), runtime, text: reply, ownPostedIds, signal, logPrefix });
595
618
  return false;
596
619
  }
597
620
  }
@@ -632,7 +655,7 @@ export async function sseLoop(opts: {
632
655
  if (!idStr) return;
633
656
  if (ackedIds.has(idStr) || ackInFlightIds.has(idStr)) return;
634
657
  ackInFlightIds.add(idStr);
635
- void ackMessage(baseUrl, runtime.id, runtime.token, idStr, signal, fetchImpl)
658
+ void ackMessage(baseUrl(), runtime.id, runtime.token, idStr, signal, fetchImpl)
636
659
  .then((ok) => {
637
660
  if (ok) ackedIds.add(idStr);
638
661
  else process.stderr.write(`${logPrefix} ack failed for message ${idStr} (will retry on reconnect)\n`);
@@ -690,7 +713,7 @@ export async function sseLoop(opts: {
690
713
  // is the SSE/voice host (the CF tunnel in staging/prod). Using ws_url here
691
714
  // 404s whenever the SSE host differs from the API host (masked in dev where
692
715
  // they collapse to one origin). The SSE subscription still uses ws_url.
693
- msgs = await fetchMessagesImpl(baseUrl, minted.conversation_id, runtime.token);
716
+ msgs = await fetchMessagesImpl(baseUrl(), minted.conversation_id, runtime.token);
694
717
  } catch (err) {
695
718
  if (err instanceof ConversationTokenExpiredError) throw err;
696
719
  process.stderr.write(`${logPrefix} catch-up fetch failed: ${safeErrorMessage(err)}\n`);
@@ -857,9 +880,69 @@ export function sanitizeAgentRole(raw: string | undefined): string {
857
880
  return code < 0x20 || code === 0x7f ? " " : ch;
858
881
  })
859
882
  .join("");
860
- const stripped = noCtrl.replace(/\s+/g, " ").trim();
861
- if (stripped.length <= MAX_ROLE_LENGTH) return stripped;
862
- return stripped.slice(0, MAX_ROLE_LENGTH).trimEnd();
883
+ const stripped = normalizeEscapables(noCtrl.replace(/\s+/g, " ").trim());
884
+ return capUtf16Safe(stripped, MAX_ROLE_LENGTH);
885
+ }
886
+
887
+ /**
888
+ * Normalize the two characters `JSON.stringify` expands MOST in practice (#479): a quote
889
+ * becomes an apostrophe, a backslash a forward slash. Both stay readable —
890
+ * `C:\Users` → `C:/Users`, `the "taskman" skill` → `the 'taskman' skill` — and
891
+ * neither `'` nor `/` is escaped, so a 600-char role can no longer encode to 1200
892
+ * and blow the instructions budget. Removing them outright would corrupt paths and
893
+ * citations; rewriting them keeps the meaning and bounds the length.
894
+ *
895
+ * They are not the ONLY expanding inputs: control characters (already turned into
896
+ * spaces by the callers) and a LONE SURROGATE (escaped as `\udXXX` — six chars for
897
+ * one code unit) also grow. Unpaired surrogates are therefore dropped here, and
898
+ * `capUtf16Safe` below makes sure the length cap never creates a new one. Between
899
+ * the two, no input can make the encoded text longer than the raw text.
900
+ */
901
+ function normalizeEscapables(text: string): string {
902
+ return dropLoneSurrogates(text).replaceAll('"', "'").replaceAll("\\", "/");
903
+ }
904
+
905
+ /**
906
+ * Drop UNPAIRED surrogates (#479 opus review). `capUtf16Safe` stops the cap from
907
+ * CREATING one, but an unpaired unit already present in the input would sail
908
+ * through and encode to `\udXXX` — six chars for one unit, so a 600-char role could
909
+ * still reach ~3600 encoded. Dropping them closes the last expansion path, which is
910
+ * what makes IDENTITY_BUDGET exact for ANY input and the clip a true never-path.
911
+ * A lone surrogate carries no text anyway: it is a broken half-character.
912
+ */
913
+ function dropLoneSurrogates(text: string): string {
914
+ let out = "";
915
+ for (let i = 0; i < text.length; i++) {
916
+ const code = text.charCodeAt(i);
917
+ const isHigh = code >= 0xd800 && code <= 0xdbff;
918
+ const isLow = code >= 0xdc00 && code <= 0xdfff;
919
+ if (isHigh) {
920
+ const next = text.charCodeAt(i + 1);
921
+ if (next >= 0xdc00 && next <= 0xdfff) {
922
+ out += text[i] + text[i + 1];
923
+ i++;
924
+ }
925
+ continue; // unpaired high → dropped
926
+ }
927
+ if (isLow) continue; // unpaired low → dropped
928
+ out += text[i];
929
+ }
930
+ return out;
931
+ }
932
+
933
+ /**
934
+ * Cap `text` to `max` UTF-16 units WITHOUT leaving a lone surrogate behind
935
+ * (codex-479 review): a plain `slice` can cut an emoji in half, and a lone
936
+ * surrogate is itself escaped by `JSON.stringify` (`\udXXX`) — the very expansion
937
+ * the normalization above exists to prevent, plus an unpaired code unit in the
938
+ * prompt. The cap stays in UTF-16 units so `IDENTITY_BUDGET` remains exact.
939
+ */
940
+ function capUtf16Safe(text: string, max: number): string {
941
+ if (text.length <= max) return text;
942
+ const cut = text.slice(0, max);
943
+ const last = cut.charCodeAt(cut.length - 1);
944
+ const orphanHighSurrogate = last >= 0xd800 && last <= 0xdbff;
945
+ return (orphanHighSurrogate ? cut.slice(0, -1) : cut).trimEnd();
863
946
  }
864
947
 
865
948
  /** Max explicit-name length after sanitization (chars). */
@@ -880,8 +963,8 @@ export function sanitizeAgentName(raw: string | undefined): string {
880
963
  return code < 0x20 || code === 0x7f ? " " : ch;
881
964
  })
882
965
  .join("");
883
- const stripped = noCtrl.replace(/\s+/g, " ").trim();
884
- return stripped.length <= MAX_NAME_LENGTH ? stripped : stripped.slice(0, MAX_NAME_LENGTH).trimEnd();
966
+ const stripped = normalizeEscapables(noCtrl.replace(/\s+/g, " ").trim());
967
+ return capUtf16Safe(stripped, MAX_NAME_LENGTH);
885
968
  }
886
969
 
887
970
  /**
@@ -907,6 +990,13 @@ export function sanitizeAgentName(raw: string | undefined): string {
907
990
  export function buildAgentIdentityInstructions(opts: {
908
991
  explicitName?: string;
909
992
  role?: string;
993
+ /**
994
+ * Hard ceiling (chars) for the RENDERED line (#479). The MCP client truncates
995
+ * long `instructions`, so the identity line must not eat the channel-contract
996
+ * budget: the caller reserves a slice and we fit into it OURSELVES rather than
997
+ * letting the client cut wherever it lands. Omitted = no ceiling.
998
+ */
999
+ budget?: number;
910
1000
  }): string {
911
1001
  const name = sanitizeAgentName(opts.explicitName);
912
1002
  const role = sanitizeAgentRole(opts.role);
@@ -918,8 +1008,57 @@ export function buildAgentIdentityInstructions(opts: {
918
1008
  const nameClause = name
919
1009
  ? ` Your explicit spawn name is ${JSON.stringify(name)}; if asked your name, answer with it.`
920
1010
  : " You do not have an explicit agent name, so do not invent one if asked.";
921
- const roleClause = role ? ` Your assigned role is ${JSON.stringify(role)}.` : "";
922
- return `${guard}${nameClause}${roleClause}`;
1011
+
1012
+ // The guard and the name are NEVER trimmed (#328: an agent that lost its name
1013
+ // is the bug this line exists to prevent; a half-quoted guard would weaken the
1014
+ // "descriptive DATA" framing). Only the role clause absorbs the budget.
1015
+ const fixed = `${guard}${nameClause}`;
1016
+ const roleClause = role ? renderRoleClause(role, budgetForRole(opts.budget, fixed.length)) : "";
1017
+ return `${fixed}${roleClause}`;
1018
+ }
1019
+
1020
+ /** Chars left for the role clause once guard + name are reserved. */
1021
+ function budgetForRole(budget: number | undefined, fixedLength: number): number {
1022
+ if (budget === undefined) return Number.POSITIVE_INFINITY;
1023
+ return budget - fixedLength;
1024
+ }
1025
+
1026
+ /**
1027
+ * Render ` Your assigned role is "<role>".` within `available` chars, or "" when
1028
+ * even the empty envelope does not fit (#479).
1029
+ *
1030
+ * Clipping happens on the role text BEFORE serialization, by CODE POINT — never
1031
+ * on the serialized string (codex review): cutting encoded text can split an
1032
+ * escape sequence (`é`) or a surrogate pair and leave the JSON string
1033
+ * unterminated, which is exactly what would break out of the quoted-data framing.
1034
+ * So we search the longest code-point prefix whose `JSON.stringify` still fits.
1035
+ */
1036
+ function renderRoleClause(role: string, available: number): string {
1037
+ const wrap = (encoded: string): string => ` Your assigned role is ${encoded}.`;
1038
+ if (wrap(JSON.stringify("")).length > available) return "";
1039
+ const full = wrap(JSON.stringify(role));
1040
+ if (full.length <= available) return full;
1041
+
1042
+ // Binary-search the longest fitting prefix. Code points, not UTF-16 units, so a
1043
+ // non-BMP character is never cut in half.
1044
+ const points = Array.from(role);
1045
+ let lo = 0;
1046
+ let hi = points.length;
1047
+ while (lo < hi) {
1048
+ const mid = Math.ceil((lo + hi) / 2);
1049
+ if (wrap(JSON.stringify(points.slice(0, mid).join(""))).length <= available) lo = mid;
1050
+ else hi = mid - 1;
1051
+ }
1052
+ const clipped = wrap(JSON.stringify(points.slice(0, lo).join("").trimEnd()));
1053
+ // Never silent: a clip means the operator's role prompt did not fully reach the
1054
+ // agent. Lengths only — the role itself is not logged (it can be long, and the
1055
+ // log is not the place for it).
1056
+ process.stderr.write(
1057
+ `[viber-channel] identity: role clause CLIPPED to fit the instructions budget ` +
1058
+ `(${points.length} code points → ${lo}; clause ${full.length} → ${clipped.length} chars, ` +
1059
+ `available ${available}). Shorten the role prompt to avoid losing its tail.\n`,
1060
+ );
1061
+ return clipped;
923
1062
  }
924
1063
 
925
1064
  /**
@@ -931,7 +1070,7 @@ export function buildAgentIdentityInstructions(opts: {
931
1070
  * - a Claude terminal session (#328) has no bridge — its label is
932
1071
  * `VIBER_CHANNEL_LABEL` (set by buildClaudeLaunchSpec) — so fall back to it.
933
1072
  */
934
- export function agentIdentityFromEnv(): string {
1073
+ export function agentIdentityFromEnv(budget?: number): string {
935
1074
  const explicit = process.env.VIBER_AGENT_NAME_EXPLICIT === "1";
936
1075
  // A BLANK bridge label counts as absent (defense in depth, #328): the terminal
937
1076
  // launcher wipes an inherited VIBER_CODEX_BRIDGE_LABEL to "", so a Claude
@@ -942,6 +1081,10 @@ export function agentIdentityFromEnv(): string {
942
1081
  return buildAgentIdentityInstructions({
943
1082
  explicitName: explicit ? label : undefined,
944
1083
  role: process.env.VIBER_AGENT_ROLE,
1084
+ // #479: the MCP surface passes IDENTITY_BUDGET so the line cannot eat the
1085
+ // channel contract. The bridges pass nothing — their developer instructions
1086
+ // are not truncated, so a full role is safe there.
1087
+ budget,
945
1088
  });
946
1089
  }
947
1090
 
@@ -952,6 +1095,8 @@ export interface BridgeIdentity {
952
1095
  instanceKey: string;
953
1096
  instanceToken: string;
954
1097
  bridgeLock: BridgeLock;
1098
+ /** #480 — host announced at register, when this call actually registered. */
1099
+ apiBaseUrlAnnounced?: string;
955
1100
  }
956
1101
 
957
1102
  /**
@@ -992,7 +1137,10 @@ export async function acquireBridgeInstance(opts: {
992
1137
  * both await an invite. Mirrors the Codex bridge's acquireBridgeIdentity, generic.
993
1138
  */
994
1139
  export async function acquireBridgeIdentity(opts: {
1140
+ /** Transport host — what we fetch (#480). */
995
1141
  baseUrl: string;
1142
+ /** Logical backend identity — keys the bridge lock (#480). */
1143
+ identityBaseUrl: string;
996
1144
  auth: AuthJson;
997
1145
  fingerprint: string;
998
1146
  label: string;
@@ -1002,17 +1150,22 @@ export async function acquireBridgeIdentity(opts: {
1002
1150
  sessionTag: string;
1003
1151
  reuseAuthInstance: boolean;
1004
1152
  }): Promise<BridgeIdentity> {
1005
- const { baseUrl, fingerprint, lockDir, logPrefix, sessionTag } = opts;
1153
+ const { identityBaseUrl, fingerprint, lockDir, logPrefix, sessionTag } = opts;
1006
1154
  mkdirSync(lockDir, { recursive: true });
1007
1155
  const acquired = await acquireBridgeInstance(opts);
1008
1156
  const bridgeLock = acquireBridgeLock({
1009
- baseUrl,
1157
+ identityBaseUrl,
1010
1158
  fingerprint,
1011
1159
  sessionId: `${sessionTag}-agent:${acquired.instance_key}`,
1012
1160
  lockDir,
1013
1161
  logPrefix,
1014
1162
  });
1015
- return { instanceKey: acquired.instance_key, instanceToken: acquired.instance_token, bridgeLock };
1163
+ return {
1164
+ instanceKey: acquired.instance_key,
1165
+ instanceToken: acquired.instance_token,
1166
+ bridgeLock,
1167
+ apiBaseUrlAnnounced: acquired.api_base_url,
1168
+ };
1016
1169
  }
1017
1170
 
1018
1171
  /** Live helpers a runtime adapter uses inside onStart (e.g. the Codex tool host). */
@@ -1030,7 +1183,10 @@ export interface BridgeHelpers {
1030
1183
 
1031
1184
  /** A runtime's adapter for the shared await-invite bridge. */
1032
1185
  export interface AwaitInviteAdapter {
1033
- baseUrl: string;
1186
+ /** #480 — API host as state (see ConversationStreamDeps.api). */
1187
+ api: ApiBaseUrlResolver;
1188
+ /** Logical backend identity — keys the lock + session handle (#480). */
1189
+ identityBaseUrl: string;
1034
1190
  lockDir: string;
1035
1191
  logPrefix: string;
1036
1192
  /** Lock + session-handle tag distinguishing runtimes (codex / gemma). */
@@ -1061,7 +1217,8 @@ export interface AwaitInviteAdapter {
1061
1217
  * makeRunTurn). Throws BridgeShutdownError so the caller maps it to an exit code.
1062
1218
  */
1063
1219
  export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise<void> {
1064
- const { baseUrl, lockDir, logPrefix, sessionTag, label, kind, options, auth, fingerprint, makeRunTurn, onStart, onShutdown } = adapter;
1220
+ const { api, identityBaseUrl, lockDir, logPrefix, sessionTag, label, kind, options, auth, fingerprint, makeRunTurn, onStart, onShutdown } = adapter;
1221
+ const baseUrl = (): string => api.current();
1065
1222
  const shutdown = new AbortController();
1066
1223
  let bridgeLock: BridgeLock | null = null;
1067
1224
  let controlStream: PersistentControlStream | null = null;
@@ -1076,6 +1233,9 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1076
1233
  let instanceKey = "";
1077
1234
 
1078
1235
  const startConversation = (minted: ConversationMintResponse): void => {
1236
+ // A pushed join is the only announcement a bridge that reuses a persisted
1237
+ // token ever sees (no register call ⇒ nothing announced there).
1238
+ api.offer(minted.api_base_url);
1079
1239
  if (!voiceBaseUrl) voiceBaseUrl = minted.ws_url;
1080
1240
  process.stderr.write(`${logPrefix} join pushed for ${minted.conversation_id} — starting stream\n`);
1081
1241
  // `let task!` (not const): the `.finally` closure reads `task`; with a const
@@ -1088,7 +1248,8 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1088
1248
  activeStreams,
1089
1249
  watermarks,
1090
1250
  parentSignal: shutdown.signal,
1091
- baseUrl,
1251
+ api,
1252
+ identityBaseUrl,
1092
1253
  lockDir,
1093
1254
  logPrefix,
1094
1255
  sessionTag,
@@ -1110,11 +1271,14 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1110
1271
 
1111
1272
  try {
1112
1273
  const identity = await acquireBridgeIdentity({
1113
- baseUrl, auth, fingerprint, label, kind, lockDir, logPrefix, sessionTag,
1274
+ baseUrl: baseUrl(), identityBaseUrl, auth, fingerprint, label, kind, lockDir, logPrefix, sessionTag,
1114
1275
  reuseAuthInstance: options.reuseAuthInstance ?? false,
1115
1276
  });
1116
1277
  bridgeLock = identity.bridgeLock;
1117
1278
  instanceKey = identity.instanceKey;
1279
+ // #480: adopt BEFORE the control stream and the heartbeat start — they are
1280
+ // this bridge's two longest-lived flows and the whole point of the change.
1281
+ api.offer(identity.apiBaseUrlAnnounced);
1118
1282
 
1119
1283
  const helpers: BridgeHelpers = {
1120
1284
  startConversation,
@@ -1128,7 +1292,9 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1128
1292
 
1129
1293
  process.stderr.write(`${logPrefix} await-invite: control stream open, waiting for joins (instance ${identity.instanceKey.slice(0, 8)})\n`);
1130
1294
  controlStream = runPersistentControlStream(
1131
- { baseUrl, instanceId: identity.instanceKey, instanceToken: identity.instanceToken, signal: shutdown.signal },
1295
+ // Evaluated here, i.e. AFTER api.offer() above — so the stream opens on
1296
+ // the announced host rather than the bootstrap one.
1297
+ { getBaseUrl: baseUrl, instanceId: identity.instanceKey, instanceToken: identity.instanceToken, signal: shutdown.signal },
1132
1298
  {
1133
1299
  log: (m) => process.stderr.write(m),
1134
1300
  onJoin: (minted) => startConversation(minted),
@@ -1141,12 +1307,12 @@ export async function runAwaitInviteBridge(adapter: AwaitInviteAdapter): Promise
1141
1307
  );
1142
1308
  },
1143
1309
  onBeatNow: () => {
1144
- void sendInstanceHeartbeat(baseUrl, identity.instanceKey, identity.instanceToken);
1310
+ void sendInstanceHeartbeat(baseUrl(), identity.instanceKey, identity.instanceToken);
1145
1311
  },
1146
1312
  },
1147
1313
  );
1148
1314
  const ihb = startInstanceHeartbeat({
1149
- baseUrl,
1315
+ getBaseUrl: baseUrl,
1150
1316
  instanceId: identity.instanceKey,
1151
1317
  getInstanceToken: () => identity.instanceToken,
1152
1318
  });
@@ -29,6 +29,7 @@ import {
29
29
  type AgentToolsContext,
30
30
  type AgentToolResult,
31
31
  } from "./agent_tools.js";
32
+ import { CONTRACT_STYLE_NEUTRAL, CONTRACT_STYLE_TOOLS } from "./channel_instructions.js";
32
33
 
33
34
  /** The three channel tools, named so codex (and the elicitation whitelist) match. */
34
35
  export const BRIDGE_TOOL_NAMES = ["send_message", "list_agents", "message_agent"] as const;
@@ -44,17 +45,32 @@ export const TOOL_DEFS = [
44
45
  {
45
46
  name: "send_message",
46
47
  description:
47
- "Reply to the USER. This is the ONLY way to reach the user — they do NOT see your runtime/stdout, so never answer there. " +
48
- "Post your reply into the current Viber conversation. `text` is the conversational reply — " +
49
- "read aloud AND shown as Markdown, so keep it short and natural but use light Markdown (short " +
50
- "lists, numbered steps, **bold**) for readability; put actions/questions here, visibly. " +
51
- "`artifact` is optional HEAVY/LONG content (big code, large tables, long analyses, json, " +
52
- "sanitized html) shown in a side viewer; when used, keep `text` a brief summary pointing to it. " +
53
- "Calling this IS your reply for the turn.",
48
+ // #479 codex review: this used to claim send_message was "the ONLY way to
49
+ // reach the user". False on THIS surface — the bridge auto-posts a turn's
50
+ // text when no outbound tool succeeded, and the system prompt says so. Two
51
+ // contradictory statements about delivery is exactly the defect #479 fixes
52
+ // elsewhere, so the wording is non-exclusive here.
53
+ "Reply to the USER by posting into the current Viber conversation. Your runtime/stdout is NOT the user — never treat it as the reply. " +
54
+ "Calling this delivers your reply for the turn (and suppresses the bridge's auto-post fallback). " +
55
+ // #479 volet 2: the SAME contract fragments Claude gets. They used to exist
56
+ // only in the MCP `instructions` blob, which never reaches codex/gemma at all
57
+ // — so NO EMOJI and the literal-identifier rule were simply absent here.
58
+ CONTRACT_STYLE_NEUTRAL +
59
+ " " +
60
+ CONTRACT_STYLE_TOOLS,
54
61
  inputSchema: {
55
62
  type: "object",
56
63
  properties: {
57
- text: { type: "string", description: "Spoken/conversational reply. Plain sentences." },
64
+ // #479: this used to read "Plain sentences." — a leftover of the retired
65
+ // "no markdown" rule, contradicting the description right above it, which
66
+ // asks for light Markdown. The contract has ONE wording now.
67
+ text: {
68
+ type: "string",
69
+ description:
70
+ "Spoken/conversational reply: read aloud AND shown as Markdown. Short and natural, light " +
71
+ "Markdown (short lists, **bold**) for readability. Actions and questions go here, visibly. " +
72
+ "NO emoji (it is read aloud). Write identifiers LITERALLY (288, auth.json).",
73
+ },
58
74
  artifact: {
59
75
  type: "object",
60
76
  properties: {
@@ -2,12 +2,84 @@
2
2
  // server. Extracted into a PURE function so it can be asserted in tests without
3
3
  // booting the MCP server (#390 step-03).
4
4
  //
5
- // #369 truncation fix: Claude Code truncates long MCP `instructions`
6
- // ("…[truncated]") and this blob was ~3 KB → the TAIL was dropped before the
7
- // agent saw it (that hid the agent's name #328, and threatened the #332 pointer
8
- // + exit-intent). So: CRITICAL lines are FRONT-LOADED (identity → core reply →
9
- // actions/questions → anti-deadlock → capabilities → exit) and the nice-to-have
10
- // style notes live at the tail where a cut is harmless.
5
+ // Claude Code truncates long MCP `instructions` ("…[truncated]"). #369 addressed
6
+ // that by FRONT-LOADING the critical lines (identity → core reply →
7
+ // actions/questions → anti-deadlock → capabilities → exit) and parking the style
8
+ // notes at the tail.
9
+ //
10
+ // #479: front-loading is a BUDGET, not a fix — and the budget was full. The blob
11
+ // was 1829 chars and the identity line prefixed to it reaches 946 (name 80 + a
12
+ // 600-char ASCII role) and up to ~1626 when the role holds quotes/backslashes,
13
+ // which `JSON.stringify` doubles. Two real sessions were observed cut mid-line.
14
+ // So the budget is now EXPLICIT and TESTED:
15
+ //
16
+ // INSTRUCTIONS_CAP ≥ blob + IDENTITY_BUDGET + SAFETY_MARGIN
17
+ //
18
+ // and the identity line is clipped by US (in buildAgentIdentityInstructions) to
19
+ // IDENTITY_BUDGET instead of being cut wherever the client lands. The style rules
20
+ // that used to sit at the tail now live in the TOOL `description`s, which are
21
+ // never truncated.
22
+
23
+ /**
24
+ * The style half of the channel contract, in the form EVERY runtime can obey
25
+ * (#479 volet 2). Claude, codex and gemma all post into the same conversation, so
26
+ * these rules are runtime-NEUTRAL: they mention no tool and no artifact.
27
+ *
28
+ * Gemma matters here: it has no filesystem and no tools, so anything it must obey
29
+ * has to be IN the prompt — "read file X" is inert for it.
30
+ */
31
+ export const CONTRACT_STYLE_NEUTRAL =
32
+ "Your reply is BOTH read aloud (TTS) AND shown as Markdown: lead with the answer, no preamble, " +
33
+ "and keep it short and natural. Light Markdown (short bullet/numbered lists, **bold**) aids " +
34
+ "readability. NO EMOJI — it is read aloud and becomes spoken noise. Write identifiers LITERALLY " +
35
+ "(288, auth.json, viber-dev.dgypx.dev): never spell out dots or dashes.";
36
+
37
+ /**
38
+ * The tool-dependent half. Only for runtimes that actually HAVE the channel tools
39
+ * (Claude, codex) — never sent to gemma, which would be told to call tools it does
40
+ * not have.
41
+ *
42
+ * It deliberately says nothing about WHETHER to call send_message: Claude must
43
+ * always call it, while the codex bridge auto-posts a turn's text when no outbound
44
+ * tool was used. That difference is real and each runtime states its own policy.
45
+ */
46
+ export const CONTRACT_STYLE_TOOLS =
47
+ "Put ACTIONS and QUESTIONS in the spoken `text`, visibly — never only in the artifact. The " +
48
+ "`artifact` (format: markdown default, or code/json/html) carries HEAVY/LONG content (big code, " +
49
+ "large tables, long analyses, JSON, file lists); when you use it, keep `text` a brief spoken " +
50
+ "summary pointing to it. In an html artifact, scripts, event handlers, iframes and inline styles " +
51
+ "are stripped server-side before display — do not rely on them.";
52
+
53
+ /**
54
+ * Chars the client is assumed to keep. The observed cut is around 2048, but
55
+ * NOBODY has measured whether it counts characters or tokens (#479 step-04
56
+ * measures it) — so we sit deliberately under the observed value.
57
+ */
58
+ export const INSTRUCTIONS_CAP = 2000;
59
+
60
+ /** Slack kept under the cap so a small edit cannot silently reintroduce a cut. */
61
+ export const SAFETY_MARGIN = 96;
62
+
63
+ /**
64
+ * Chars reserved for the identity line. NOT a magic number: it is the WORST
65
+ * NOMINAL identity line — fixed framing + `MAX_NAME_LENGTH` + an ASCII role of
66
+ * `MAX_ROLE_LENGTH` (the cap vibe-master already applies to `rolePrompt`) — so a
67
+ * legitimate 600-char role survives WHOLE. `agent_identity.test.ts` asserts this
68
+ * value against the real builder, so a reworded framing fails the build instead
69
+ * of silently clipping every team role.
70
+ *
71
+ * This is a FIXED budget guarded by tests, not `CAP - blob - margin` computed at
72
+ * runtime: a blob that grows too big must FAIL THE BUILD, never silently shave the
73
+ * operator's role prompt.
74
+ *
75
+ * Quotes and backslashes in a role are normalized (`"`→`'`, `\`→`/`) rather than
76
+ * escaped, so a role at `MAX_ROLE_LENGTH` fits whole. The clip in
77
+ * `buildAgentIdentityInstructions` remains as a backstop, and it logs.
78
+ */
79
+ export const IDENTITY_BUDGET = 946;
80
+
81
+ /** Chars the blob itself may occupy. Asserted by the budget test (#479). */
82
+ export const BLOB_BUDGET = INSTRUCTIONS_CAP - IDENTITY_BUDGET - SAFETY_MARGIN;
11
83
 
12
84
  /**
13
85
  * Build the MCP `instructions` string.
@@ -26,17 +98,17 @@ export function buildChannelInstructions(identityLine: string): string {
26
98
  // "microphone" = voice, "conversation" = typed UI text (both = the USER),
27
99
  // "agent-dm" = another agent. Naming the real values (not the server name)
28
100
  // avoids the old imprecise "source=viber-channel" cue.
29
- 'To reply to the USER, ALWAYS use send_message — NEVER write your answer to the terminal / your runtime stdout (the user does not watch it; there may be many terminals). A <channel> event whose metadata source (the last source= attribute) is "microphone" (voice) or "conversation" (typed text) is the user talking to you → reply with send_message. source="agent-dm" is ANOTHER agent → reply with message_agent. send_message = the user; message_agent = other agents ONLY, never the user.',
30
- "Your send_message `text` is BOTH read aloud (TTS) AND shown as Markdown — make it natural aloud AND easy to read; lead with the answer, no preamble.",
31
- "Put ACTIONS and QUESTIONS in `text`, visibly — never bury them in the artifact. Use light Markdown (short bullet/numbered lists, **bold**) to stay readable; a short spoken list is fine.",
101
+ 'Reply to the USER only with send_message — NEVER write your answer to the terminal / your runtime stdout. The LAST source= of a <channel> event decides: "microphone" (voice) or "conversation" (typed) is the USER → send_message; source="agent-dm" is ANOTHER agent → message_agent, never the user.',
102
+ "`text` is BOTH read aloud (TTS) AND shown as Markdown: lead with the answer, light Markdown (short lists, **bold**). Put ACTIONS and QUESTIONS in `text` — never only in the artifact.",
32
103
  // #343 anti-deadlock (hands-free: the user is NOT watching the terminal).
33
- "CRITICAL — while this channel is active, NEVER block on a terminal prompt or AskUserQuestion: the user is hands-free and cannot see the terminal, so it deadlocks. Put EVERY question or choice in send_message `text` and take the answer from the next user message (voice or typed).",
104
+ "CRITICAL — NEVER block on a terminal prompt or AskUserQuestion: the user is hands-free, so it deadlocks. Every question or choice goes in `text`; the answer arrives as the next user message (voice or typed).",
34
105
  // #332 discoverability pointer (the how-to lives in the capabilities tool).
35
- "To orchestrate or spawn OTHER agents (Codex, Claude, Gemma) on this machine, call the `capabilities` tool for how — only when relevant.",
36
- "On exit intent (bye, au revoir, stop) call stop_conversation(), speak a brief farewell, and stop.",
37
- // --- nice-to-have style notes (safe near the tail) ---
38
- "The `artifact` (format: markdown default, or code/json/html) is for HEAVY/LONG content (big code, large tables, long analyses, JSON, file lists); keep `text` a brief spoken summary that points to it ('details on the side'). Scripts/event handlers are stripped server-side.",
39
- "NO EMOJI in `text` (read aloud — an emoji becomes spoken noise). Write identifiers LITERALLY (288, auth.json, viber-dev.dgypx.dev) — never spell out dots/dashes; a lone long token or path is better placed in the artifact.",
106
+ "Call `capabilities` to spawn or orchestrate OTHER agents (Codex, Claude, Gemma). On exit intent (bye, stop) call stop_conversation(), speak a brief farewell, and stop.",
107
+ // #479: the style rules (artifact, NO EMOJI, literal identifiers) used to sit
108
+ // here at the tail — exactly where the client's cut landed. They now live in
109
+ // the TOOL `description`s, which are never truncated. This pointer is what
110
+ // stays, so an agent knows where the rest of the contract is.
111
+ "The send_message tool description carries the rest of the contract — artifact, no emoji, identifiers.",
40
112
  ]
41
113
  .filter((line) => line.length > 0)
42
114
  .join(" ");