@agentvault/claude-bridge 0.8.28 → 0.8.30

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/dist/bridge.d.ts CHANGED
@@ -162,6 +162,13 @@ export interface ReplyChannel {
162
162
  groupId?: string;
163
163
  }): Promise<T>;
164
164
  }
165
+ /**
166
+ * #1467: the owner's Claude plan refused a turn. One `ai.agent.tool.invoke`
167
+ * error span (tool `model_turn`, code `plan_limit_reached`) with the reset time
168
+ * when known. No conversation: the limit is the plan's, not one chat's — and
169
+ * so the span never says who was being answered. Never throws.
170
+ */
171
+ export declare function reportPlanLimit(channel: Pick<ReplyChannel, "telemetry">, resetsAt: number | undefined): void;
165
172
  /**
166
173
  * Tracks the destination of the most recent inbound message and routes outbound
167
174
  * replies there. Replaces the bridge's old single `activeRoomId` string so the
package/dist/index.js CHANGED
@@ -11718,11 +11718,11 @@ async function joinWithFirstMatchingKp(welcomeBytes, candidates) {
11718
11718
  return null;
11719
11719
  }
11720
11720
  function ownIdentity() {
11721
- const v22 = true ? "0.23.60" : FALLBACK;
11721
+ const v22 = true ? "0.23.61" : FALLBACK;
11722
11722
  return `${PACKAGE}@${v22}`;
11723
11723
  }
11724
11724
  function buildSha() {
11725
- const raw = true ? "9599d8e" : "";
11725
+ const raw = true ? "129e537" : "";
11726
11726
  const cleaned = (raw ?? "").trim();
11727
11727
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11728
11728
  }
@@ -12540,6 +12540,10 @@ function buildToolInvokeSpan(report) {
12540
12540
  "tool.duration_ms": durationMs
12541
12541
  };
12542
12542
  if (isError) attributes["tool.error_kind"] = safeErrorKind(report.errorKind);
12543
+ const resets = report.limitResetsAt;
12544
+ if (attributes["tool.error_kind"] === "plan_limit_reached" && typeof resets === "number" && Number.isInteger(resets) && resets > 0 && resets < 1e11) {
12545
+ attributes["av.limit_resets_at"] = resets;
12546
+ }
12543
12547
  if (kind !== "unknown" && typeof conv.id === "string" && conv.id) {
12544
12548
  attributes["av.conversation_id"] = conv.id.slice(0, 64);
12545
12549
  }
@@ -70780,6 +70784,11 @@ var init_dist = __esm({
70780
70784
  "ambiguous_target",
70781
70785
  "no_receipt",
70782
70786
  "invalid_request",
70787
+ // #1467: the owner's own AI plan refused the turn (a bridge on a subscription).
70788
+ "plan_limit_reached",
70789
+ // #1467: a Muse turn failed — Meta answered 429, or anything else.
70790
+ "model_rate_limited",
70791
+ "model_error",
70783
70792
  UNCLASSIFIED_ERROR
70784
70793
  ];
70785
70794
  KNOWN_CODES = new Set(KNOWN_TOOL_ERROR_CODES);
@@ -70991,6 +71000,17 @@ var init_dist = __esm({
70991
71000
  * self-heal rather than be logged and dropped. */
70992
71001
  _mlsCommitFailCounts = /* @__PURE__ */ new Map();
70993
71002
  static MAX_MLS_DECRYPT_FAILS = 3;
71003
+ /**
71004
+ * #1518: ids of MLS application frames this process has already decrypted
71005
+ * (server-assigned `mls_messages.id`, the same on the live delivery pull and
71006
+ * on a `/sync` / reconnect replay). A replayed frame cannot be decrypted a
71007
+ * second time — forward secrecy deleted its key — so without this every
71008
+ * reconnect after a backend deploy fed already-read messages into the
71009
+ * decrypt-failure counter and re-admitted the agent (+2 epochs). Insertion
71010
+ * ordered; the oldest ids fall out past DECRYPTED_ID_CAP.
71011
+ */
71012
+ _decryptedMessageIds = /* @__PURE__ */ new Map();
71013
+ static DECRYPTED_ID_CAP = 5e3;
70994
71014
  /**
70995
71015
  * #1084: consecutive resyncs that found NOTHING to apply, per group.
70996
71016
  *
@@ -73196,7 +73216,7 @@ ${text}`,
73196
73216
  */
73197
73217
  sendActivitySpan(spanData) {
73198
73218
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
73199
- const pluginVersion = true ? "0.23.60" : "0.0.0-dev";
73219
+ const pluginVersion = true ? "0.23.61" : "0.0.0-dev";
73200
73220
  const agentName = this.config.agentName ?? "Agent";
73201
73221
  const resource = {
73202
73222
  "service.name": "agentvault-agent",
@@ -75406,7 +75426,7 @@ ${text}`,
75406
75426
  agentVersion: this.config.agentVersion ?? "0.0.0",
75407
75427
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
75408
75428
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
75409
- pluginVersion: true ? "0.23.60" : "0.0.0-dev"
75429
+ pluginVersion: true ? "0.23.61" : "0.0.0-dev"
75410
75430
  });
75411
75431
  this._telemetryReporter.startAutoFlush(3e4);
75412
75432
  }
@@ -75738,7 +75758,7 @@ ${text}`,
75738
75758
  agentVersion: this.config.agentVersion ?? "0.0.0",
75739
75759
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
75740
75760
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
75741
- pluginVersion: true ? "0.23.60" : "0.0.0-dev"
75761
+ pluginVersion: true ? "0.23.61" : "0.0.0-dev"
75742
75762
  });
75743
75763
  this._telemetryReporter.startAutoFlush(3e4);
75744
75764
  }
@@ -76174,9 +76194,14 @@ ${text}`,
76174
76194
  if (groupId) void this._requestWelcomeSelfHeal(groupId);
76175
76195
  return;
76176
76196
  }
76197
+ if (this._alreadyDecrypted(data.message_id)) {
76198
+ console.debug(`[SecureChannel] MLS 1:1 frame ${String(data.message_id).slice(0, 8)} already read \u2014 replay skipped`);
76199
+ return;
76200
+ }
76177
76201
  try {
76178
76202
  const cipherBytes = new Uint8Array(Buffer.from(data.payload, "hex"));
76179
76203
  const result = await mgr.decrypt(cipherBytes);
76204
+ this._rememberDecrypted(data.message_id);
76180
76205
  if (mgrKey) this._mlsDecryptFailCounts.delete(mgrKey);
76181
76206
  const mlsGroupId = (convGroupId ? this._persisted?.mlsGroups?.[convGroupId]?.mlsGroupId : null) ?? this._persisted?.mlsConversations?.[convId]?.mlsGroupId ?? groupId;
76182
76207
  if (mlsGroupId) {
@@ -77199,9 +77224,14 @@ ${baseText}`;
77199
77224
  }
77200
77225
  return;
77201
77226
  }
77227
+ if (this._alreadyDecrypted(data.message_id)) {
77228
+ console.debug(`[SecureChannel] MLS room frame ${String(data.message_id).slice(0, 8)} already read \u2014 replay skipped`);
77229
+ return;
77230
+ }
77202
77231
  try {
77203
77232
  const ciphertext = Buffer.from(data.payload, "hex");
77204
77233
  const result = await mlsGroup.decrypt(new Uint8Array(ciphertext));
77234
+ this._rememberDecrypted(data.message_id);
77205
77235
  this._mlsDecryptFailCounts.delete(resolvedRoomId);
77206
77236
  await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mlsGroup.exportState()));
77207
77237
  if (result.isHandshake || !result.plaintext) {
@@ -78379,16 +78409,57 @@ ${baseText}`;
78379
78409
  }
78380
78410
  return await mlsGroup.encrypt(plaintextBytes);
78381
78411
  }
78412
+ /** #1518: is the server answering at all? Bounded; any failure is "no". */
78413
+ async _serverReachable() {
78414
+ try {
78415
+ const res = await fetch(`${this.config.apiUrl}/health`, { signal: AbortSignal.timeout(5e3) });
78416
+ return res.ok;
78417
+ } catch {
78418
+ return false;
78419
+ }
78420
+ }
78421
+ /** #1518: the server is down — don't re-key (that needs the same server).
78422
+ * Clear the run so the next failures ask again. Reported as handled. */
78423
+ _deferResync(groupKey, groupId, why) {
78424
+ this._mlsDecryptFailCounts.delete(groupKey);
78425
+ console.warn(
78426
+ `[SecureChannel] Resync for ${groupId.slice(0, 8)}: server unreachable (${why}) \u2014 NOT re-keying; will retry (#1518)`
78427
+ );
78428
+ return true;
78429
+ }
78430
+ /** #1518: has this process already decrypted the frame with this id? */
78431
+ _alreadyDecrypted(messageId) {
78432
+ return typeof messageId === "string" && messageId !== "" && this._decryptedMessageIds.has(messageId);
78433
+ }
78434
+ /** #1518: remember a decrypted frame's id (bounded; oldest dropped). */
78435
+ _rememberDecrypted(messageId) {
78436
+ if (typeof messageId !== "string" || messageId === "") return;
78437
+ this._decryptedMessageIds.set(messageId, true);
78438
+ if (this._decryptedMessageIds.size > _SecureChannel.DECRYPTED_ID_CAP) {
78439
+ const oldest = this._decryptedMessageIds.keys().next().value;
78440
+ if (oldest !== void 0) this._decryptedMessageIds.delete(oldest);
78441
+ }
78442
+ }
78382
78443
  async _resyncOnDivergence(groupKey, groupId) {
78383
78444
  const mgr = this._mlsGroups.get(groupKey);
78384
78445
  if (!mgr?.isInitialized) return false;
78385
78446
  const fromEpoch = Number(mgr.epoch);
78386
78447
  try {
78387
- const res = await fetch(
78388
- `${this.config.apiUrl}/api/v1/mls/groups/${groupId}/sync?last_epoch=${fromEpoch}`,
78389
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
78390
- );
78448
+ let res;
78449
+ try {
78450
+ res = await fetch(
78451
+ `${this.config.apiUrl}/api/v1/mls/groups/${groupId}/sync?last_epoch=${fromEpoch}`,
78452
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
78453
+ );
78454
+ } catch (netErr) {
78455
+ if (!await this._serverReachable()) return this._deferResync(groupKey, groupId, String(netErr));
78456
+ console.warn(`[SecureChannel] Resync-on-divergence failed for ${groupId.slice(0, 8)}:`, netErr);
78457
+ return false;
78458
+ }
78391
78459
  if (!res.ok) {
78460
+ if ((res.status >= 500 || res.status === 429) && !await this._serverReachable()) {
78461
+ return this._deferResync(groupKey, groupId, `HTTP ${res.status}`);
78462
+ }
78392
78463
  console.warn(`[SecureChannel] Resync /sync failed for ${groupId.slice(0, 8)}: ${res.status}`);
78393
78464
  return false;
78394
78465
  }
@@ -79503,9 +79574,14 @@ ${baseText}`;
79503
79574
  console.warn(`[SecureChannel] MLS group not loaded for A2A ${a2aChannelId.slice(0, 8)}`);
79504
79575
  return;
79505
79576
  }
79577
+ if (this._alreadyDecrypted(data.message_id)) {
79578
+ console.debug(`[SecureChannel] MLS A2A frame ${String(data.message_id).slice(0, 8)} already read \u2014 replay skipped`);
79579
+ return;
79580
+ }
79506
79581
  try {
79507
79582
  const ciphertext = new Uint8Array(Buffer.from(data.payload, "hex"));
79508
79583
  const result = await mlsGroup.decrypt(ciphertext);
79584
+ this._rememberDecrypted(data.message_id);
79509
79585
  this._mlsDecryptFailCounts.delete(`a2a:${a2aChannelId}`);
79510
79586
  await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mlsGroup.exportState()));
79511
79587
  if (result.isHandshake || !result.plaintext) {
@@ -102156,7 +102232,7 @@ data:
102156
102232
  await init_policy_enforcer();
102157
102233
  init_room_protocol();
102158
102234
  init_tool_telemetry();
102159
- VERSION = true ? "0.23.60" : "0.0.0-dev";
102235
+ VERSION = true ? "0.23.61" : "0.0.0-dev";
102160
102236
  }
102161
102237
  });
102162
102238
  await init_index();
@@ -144600,6 +144676,27 @@ function makeRoomSayTool(onSay) {
144600
144676
  );
144601
144677
  }
144602
144678
  var ROOM_SAY_TOOL_NAME = "mcp__room__say";
144679
+ function newTurn(item) {
144680
+ return {
144681
+ reply: item?.reply,
144682
+ autoReply: item?.autoReplyOnText ?? false,
144683
+ toolEligibleSender: item?.toolEligibleSender === true,
144684
+ roomReplyExpected: item?.replyExpected === true,
144685
+ hasRoomContext: item?.armed !== void 0,
144686
+ // D5: THIS turn's armed getter; the gate calls it live per tool decision.
144687
+ armed: item?.armed ?? (() => false),
144688
+ // Fallback signal, decoupled from the tool gate. Defaults to autoReplyOnText
144689
+ // so an owner 1:1 DM keeps the #416 behavior; a room turn sets it explicitly
144690
+ // according to the shared @mention policy.
144691
+ replyExpected: item?.replyExpected ?? item?.autoReplyOnText ?? false,
144692
+ sayAllowed: item?.replyExpected ?? true,
144693
+ said: false,
144694
+ text: "",
144695
+ sawResult: false,
144696
+ refused: false,
144697
+ telemetry: {}
144698
+ };
144699
+ }
144603
144700
  var PersistentClaudeSession = class {
144604
144701
  constructor(opts) {
144605
144702
  this.opts = opts;
@@ -144607,54 +144704,26 @@ var PersistentClaudeSession = class {
144607
144704
  opts;
144608
144705
  waiting = null;
144609
144706
  pending = [];
144610
- /** Reply sink bound to the message currently being processed. Set as each
144611
- * message is handed to the model so the say tool routes to the right place. */
144612
- activeReply;
144613
- /** Owner-DM attestation also enables its plain-text fallback. Room turns
144614
- * carry separate sender authority and can never become DMs on disarm. */
144615
- currentAutoReply = false;
144616
- currentToolEligibleSender = false;
144617
- currentRoomReplyExpected = false;
144618
- currentHasRoomContext = false;
144619
- /** Called per tool decision so a mid-turn room disarm takes effect live. */
144620
- currentArmedGetter = () => false;
144621
- /** Effective prose fallback policy, including the separate owner-DM default. */
144622
- currentReplyExpected = false;
144623
- /** #1180: whether the say tool may deliver on this turn. Rooms pass an explicit
144624
- * `replyExpected` (#1107: no @ → nobody replies) and that decides it; a 1:1 DM
144625
- * passes none and say stays allowed there. Distinct from `currentReplyExpected`,
144626
- * which drives only the #416 prose fallback and is false for un-attested DMs. */
144627
- currentSayAllowed = true;
144628
- saidThisTurn = false;
144629
- turnText = "";
144630
- /** #630 drop-probe: did a `result` event arrive for the CURRENT turn? Reset per
144631
- * turn in input(), set in the result block. Distinguishes a turn that never
144632
- * reached a result boundary (the silent-drop prime suspect) from a healthy
144633
- * #416 fallback delivery (which delivers via `void reply(...)` WITHOUT setting
144634
- * saidThisTurn, so !saidThisTurn alone would false-flag it). */
144635
- sawResultThisTurn = false;
144636
144707
  /**
144637
- * Per-turn telemetry lifted off the SDK's `result` message.
144638
- *
144639
- * The message arrives on EVERY turn and we kept one boolean from it
144640
- * (`sawResultThisTurn`), discarding the rest. That is the #791 shape: data
144641
- * delivered on the healthy path that nothing reads.
144642
- *
144643
- * It costs us a real answer. A turn that produced nothing (`composed=0,
144644
- * said=false`) could be the model choosing silence, the turn cap being hit, or
144645
- * the provider returning 429 — three different bugs with one symptom, and
144646
- * `subtype`/`apiErrorStatus` are what separate them. 4 of 12 turns on
144647
- * 2026-08-07 were silent and could not be attributed.
144648
- *
144649
- * `durationApiMs` vs `durationMs` also gives the model-time / SDK-overhead
144650
- * split directly. That split previously had to be reconstructed by joining
144651
- * `WorkerIncident.ranMs` against SDK transcripts on disk by wall clock.
144652
- *
144653
- * Every field is OPTIONAL and left undefined when no result arrives (abort or
144654
- * crash mid-turn): absent must read as absent, never as a zero that looks like
144655
- * a real measurement.
144708
+ * #1508: one entry per message the SDK has pulled, oldest first. The SDK
144709
+ * reads queued prompts EAGERLY (measured: a second message is pulled 300 ms
144710
+ * after the first, long before turn 1's output), yet answers them one turn
144711
+ * and one `result` each, in order. So a turn's settings live with ITS
144712
+ * message: input() appends, a `result` retires the head. Everything the
144713
+ * running turn reads — reply target, owed/allowed rules, composed text —
144714
+ * comes from the head (`turn()`), never from the newest message.
144715
+ */
144716
+ turns = [];
144717
+ /** The turn most recently retired. `turn()` falls back to it between turns,
144718
+ * so a late say goes where it did before (the last message's reply). */
144719
+ settled = newTurn();
144720
+ /**
144721
+ * #1467: the plan's limit status as the SDK last reported it. SESSION-level
144722
+ * on purpose: the CLI emits `rate_limit_event` only when the status CHANGES
144723
+ * (`if(!j$(V0,K))YT8(K)` in SDK 0.2.141), so every refused turn after the
144724
+ * first arrives with no event of its own. Never reset per turn.
144656
144725
  */
144657
- resultTelemetry = {};
144726
+ planLimit = { rejected: false };
144658
144727
  /** In-process room MCP server — hoisted so buildSdkOptions can reference it. */
144659
144728
  roomServer;
144660
144729
  /** AbortController for the in-flight query(); abort() triggers it (queue timeout). */
@@ -144682,7 +144751,14 @@ ${text}` : text;
144682
144751
  type: "user",
144683
144752
  message: { role: "user", content },
144684
144753
  parent_tool_use_id: null,
144685
- session_id: ""
144754
+ session_id: "",
144755
+ // #1508 LOAD-BEARING: without this the CLI drains queued prompts
144756
+ // ("next", the default) into the RUNNING turn after each tool call —
144757
+ // and the listener speaks through a tool (room say). Measured live
144758
+ // (SDK 0.2.141): a message queued during `say` was answered inside turn 1
144759
+ // ("DONE-ONE DONE-TWO", one result); with "later" each got its own turn
144760
+ // and result. One merge would leave the turn FIFO one behind for good.
144761
+ priority: "later"
144686
144762
  };
144687
144763
  const item = {
144688
144764
  msg,
@@ -144704,16 +144780,22 @@ ${text}` : text;
144704
144780
  * back to opts.onSay. This is what closes the DM→room leak: the destination is
144705
144781
  * the one captured for the message being answered, not a live global target. */
144706
144782
  async deliver(text) {
144707
- if (!this.currentSayAllowed) {
144783
+ const turn = this.turn();
144784
+ if (!turn.sayAllowed) {
144708
144785
  logLine(
144709
144786
  `[session] say during a turn this agent does not owe (no @mention) \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 80))}`
144710
144787
  );
144711
144788
  return;
144712
144789
  }
144713
- this.saidThisTurn = true;
144714
- if (this.activeReply) await this.activeReply(text);
144790
+ turn.said = true;
144791
+ if (turn.reply) await turn.reply(text);
144715
144792
  else if (this.opts.onSay) await this.opts.onSay(text);
144716
144793
  }
144794
+ /** #1508: the turn now producing output — the oldest pulled message not yet
144795
+ * answered — or, between turns, the one just answered. */
144796
+ turn() {
144797
+ return this.turns[0] ?? this.settled;
144798
+ }
144717
144799
  /** Abort the in-flight query() — used by the worker queue on a per-task timeout. */
144718
144800
  abort() {
144719
144801
  this._abort?.abort();
@@ -144729,11 +144811,12 @@ ${text}` : text;
144729
144811
  * Read-only; it must never mutate turn state.
144730
144812
  */
144731
144813
  snapshot() {
144814
+ const turn = this.turn();
144732
144815
  return {
144733
- composedChars: this.turnText.length,
144734
- sawResult: this.sawResultThisTurn,
144735
- said: this.saidThisTurn,
144736
- ...this.resultTelemetry
144816
+ composedChars: turn.text.length,
144817
+ sawResult: turn.sawResult,
144818
+ said: turn.said,
144819
+ ...turn.telemetry
144737
144820
  };
144738
144821
  }
144739
144822
  async *input() {
@@ -144748,18 +144831,7 @@ ${text}` : text;
144748
144831
  this.waiting = resolve5;
144749
144832
  });
144750
144833
  }
144751
- this.activeReply = item.reply;
144752
- this.currentAutoReply = item.autoReplyOnText ?? false;
144753
- this.currentToolEligibleSender = item.toolEligibleSender === true;
144754
- this.currentRoomReplyExpected = item.replyExpected === true;
144755
- this.currentHasRoomContext = item.armed !== void 0;
144756
- this.currentReplyExpected = item.replyExpected ?? item.autoReplyOnText ?? false;
144757
- this.currentSayAllowed = item.replyExpected ?? true;
144758
- this.currentArmedGetter = item.armed ?? (() => false);
144759
- this.saidThisTurn = false;
144760
- this.turnText = "";
144761
- this.sawResultThisTurn = false;
144762
- this.resultTelemetry = {};
144834
+ this.turns.push(newTurn(item));
144763
144835
  yield item.msg;
144764
144836
  }
144765
144837
  }
@@ -144790,7 +144862,7 @@ ${text}` : text;
144790
144862
  osIsolated: this.opts.osIsolated ?? false,
144791
144863
  // Tools require owner-DM attestation without room context, or a verified
144792
144864
  // human sender addressing this agent in an armed room. A reply alone grants no authority.
144793
- // D5: currentArmedGetter() is called HERE on every tool decision, so a
144865
+ // D5: the turn's armed() is called HERE on every tool decision, so a
144794
144866
  // mid-turn disarm denies the next call. See worker-permission.test.ts +
144795
144867
  // session.test.ts for the covering assertions.
144796
144868
  //
@@ -144799,12 +144871,12 @@ ${text}` : text;
144799
144871
  // off, even if the router ever mis-routed. `?? false` is the fail-closed
144800
144872
  // default (no getter ⇒ no tools). Read LIVE per tool decision so a Work-off
144801
144873
  // flip / fail-closed reconnect window denies the very next call.
144802
- isToolTurn: () => (this.opts.workAllowed?.() ?? false) && (this.currentAutoReply && !this.currentHasRoomContext || this.currentToolEligibleSender && this.currentRoomReplyExpected && this.currentArmedGetter()),
144874
+ isToolTurn: () => (this.opts.workAllowed?.() ?? false) && (this.turn().autoReply && !this.turn().hasRoomContext || this.turn().toolEligibleSender && this.turn().roomReplyExpected && this.turn().armed()),
144803
144875
  // Full-access lane: a 1:1 owner DM, whose ephemeral worker is seeded with
144804
144876
  // ONLY the owner's own message, so no third party can steer the turn.
144805
144877
  // The presence of room context is fixed for the turn. Disarming a room
144806
144878
  // must never promote a both-flags turn to the full-access owner-DM lane.
144807
- isOwnerDmTurn: () => this.currentAutoReply && !this.currentHasRoomContext,
144879
+ isOwnerDmTurn: () => this.turn().autoReply && !this.turn().hasRoomContext,
144808
144880
  // #627: the owner removed all gates for this device. Evaluated by
144809
144881
  // gateDecision AFTER isToolTurn, so an unarmed room turn stays chat-only
144810
144882
  // — this widens what a tool turn may do, never which turns get tools.
@@ -144813,7 +144885,7 @@ ${text}` : text;
144813
144885
  gatesRemoved: () => this.opts.gatesRemoved?.() ?? false,
144814
144886
  // Slice 2 Plan B: emit an audit self-report for each tool decision on an
144815
144887
  // armed-room turn (both allow and deny). room_say is excluded by the hook.
144816
- isArmedTurn: () => this.currentArmedGetter(),
144888
+ isArmedTurn: () => this.turn().armed(),
144817
144889
  onToolDecision: (d10) => {
144818
144890
  if (!this.opts.apiUrl || !this.opts.roomId) return;
144819
144891
  reportToolAudit({
@@ -144890,21 +144962,38 @@ ${text}` : text;
144890
144962
  });
144891
144963
  try {
144892
144964
  for await (const m6 of q10) {
144893
- if (m6.type === "assistant") {
144965
+ if (m6.type === "rate_limit_event") {
144966
+ const info = m6.rate_limit_info;
144967
+ if (info && typeof info === "object") {
144968
+ const at = info.resetsAt;
144969
+ const rejected = info.status === "rejected" && info.isUsingOverage !== true;
144970
+ this.planLimit = {
144971
+ rejected,
144972
+ resetsAt: rejected && typeof at === "number" && Number.isFinite(at) ? Math.floor(at) : void 0
144973
+ };
144974
+ }
144975
+ } else if (m6.type === "assistant") {
144976
+ if (m6.error === "rate_limit") this.turn().refused = true;
144894
144977
  const blocks = m6.message?.content ?? [];
144895
144978
  const text = blocks.filter((b5) => b5.type === "text").map((b5) => b5.text ?? "").join("");
144896
144979
  if (text.trim()) {
144897
- this.turnText += text;
144980
+ this.turn().text += text;
144898
144981
  this.opts.onObserve?.(text);
144899
144982
  }
144900
144983
  } else if (m6.type === "result") {
144901
- this.sawResultThisTurn = true;
144984
+ if (this.turns.length === 0) {
144985
+ logLine("[session] result with no message waiting for it \u2014 ignored");
144986
+ continue;
144987
+ }
144988
+ const turn = this.turns[0];
144989
+ turn.sawResult = true;
144902
144990
  const r7 = m6;
144903
144991
  const num2 = (k2) => typeof r7[k2] === "number" ? r7[k2] : void 0;
144904
144992
  const str = (k2) => typeof r7[k2] === "string" ? r7[k2] : void 0;
144905
144993
  const usage = r7.usage ?? {};
144906
144994
  const unum = (k2) => typeof usage[k2] === "number" ? usage[k2] : void 0;
144907
- this.resultTelemetry = {
144995
+ this.reportPlanLimitIfAny(turn);
144996
+ turn.telemetry = {
144908
144997
  durationMs: num2("duration_ms"),
144909
144998
  durationApiMs: num2("duration_api_ms"),
144910
144999
  numTurns: num2("num_turns"),
@@ -144919,26 +145008,41 @@ ${text}` : text;
144919
145008
  if (usageEntries.length > 0) this.opts.onUsage?.(usageEntries, num2("duration_api_ms"));
144920
145009
  } catch {
144921
145010
  }
144922
- const reply = this.activeReply;
144923
- if (this.currentReplyExpected && !this.saidThisTurn && this.turnText.trim()) {
145011
+ const reply = turn.reply;
145012
+ if (turn.replyExpected && !turn.said && turn.text.trim()) {
144924
145013
  if (reply) {
144925
- void reply(this.turnText);
145014
+ void reply(turn.text);
144926
145015
  } else {
144927
145016
  logLine(
144928
- `[drop-probe] BLOCKED at result: composed ${this.turnText.length} chars, reply expected but activeReply unset \u2014 reply DROPPED`
145017
+ `[drop-probe] BLOCKED at result: composed ${turn.text.length} chars, reply expected but no reply sink \u2014 reply DROPPED`
144929
145018
  );
144930
145019
  }
144931
145020
  }
145021
+ this.settled = this.turns.shift();
144932
145022
  }
144933
145023
  }
144934
145024
  } finally {
144935
- if (this.currentReplyExpected && !this.saidThisTurn && !this.sawResultThisTurn && this.turnText.trim()) {
145025
+ const turn = this.turn();
145026
+ if (turn.replyExpected && !turn.said && !turn.sawResult && turn.text.trim()) {
144936
145027
  logLine(
144937
- `[drop-probe] STREAM ENDED before result: composed ${this.turnText.length} chars, reply expected, said=false \u2014 reply DROPPED (no result event)`
145028
+ `[drop-probe] STREAM ENDED before result: composed ${turn.text.length} chars, reply expected, said=false \u2014 reply DROPPED (no result event)`
144938
145029
  );
144939
145030
  }
144940
145031
  }
144941
145032
  }
145033
+ /**
145034
+ * #1467: at a turn's result, report it when Claude refused it with a rate
145035
+ * limit WHILE the plan's status is rejected. A refusal with the plan allowed
145036
+ * is a short-term rate limit, not the plan's cap; a rejected status with no
145037
+ * refusal (extra usage, model fallback) was served. Never throws.
145038
+ */
145039
+ reportPlanLimitIfAny(turn) {
145040
+ if (!turn.refused || !this.planLimit.rejected) return;
145041
+ try {
145042
+ this.opts.onPlanLimit?.({ resetsAt: this.planLimit.resetsAt });
145043
+ } catch {
145044
+ }
145045
+ }
144942
145046
  };
144943
145047
 
144944
145048
  // src/worker-queue.ts
@@ -145495,6 +145599,19 @@ function reportSay(channel, t7, startedAt, failure3) {
145495
145599
  } catch {
145496
145600
  }
145497
145601
  }
145602
+ function reportPlanLimit(channel, resetsAt) {
145603
+ try {
145604
+ reportToolInvoke(channel.telemetry, {
145605
+ toolName: "model_turn",
145606
+ outcome: "error",
145607
+ errorKind: "plan_limit_reached",
145608
+ durationMs: 0,
145609
+ conversation: { kind: "unknown" },
145610
+ limitResetsAt: resetsAt
145611
+ });
145612
+ } catch {
145613
+ }
145614
+ }
145498
145615
  async function sendDm(channel, t7, text) {
145499
145616
  if ((t7.conversationId || t7.groupId) && typeof channel.runForConversation === "function") {
145500
145617
  await channel.runForConversation(
@@ -145899,7 +146016,7 @@ async function main() {
145899
146016
  "[bridge] warning: passing the invite token on the command line is visible to other local users via 'ps'. Prefer: AV_INVITE_TOKEN=\u2026 npx @agentvault/claude-bridge"
145900
146017
  );
145901
146018
  }
145902
- logLine(`[bridge] version: ${true ? "0.8.28" : "dev"}`);
146019
+ logLine(`[bridge] version: ${true ? "0.8.30" : "dev"}`);
145903
146020
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
145904
146021
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
145905
146022
  if (cfg.armRoom) {
@@ -145931,7 +146048,7 @@ async function main() {
145931
146048
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
145932
146049
  // package name attached to the bridge's version number, which is worse
145933
146050
  // than either alone.
145934
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.28" : "dev"}`
146051
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.30" : "dev"}`
145935
146052
  });
145936
146053
  const agentSystemPrompt = cfg.systemPrompt ?? identityPrompt(cfg.agentName);
145937
146054
  const deviceJwt = () => {
@@ -145956,9 +146073,14 @@ async function main() {
145956
146073
  });
145957
146074
  }
145958
146075
  };
146076
+ const onPlanLimit = ({ resetsAt }) => {
146077
+ reportPlanLimit(channel, resetsAt);
146078
+ logLine(`[bridge] Claude plan limit reached${resetsAt ? ` (resets at epoch ${resetsAt})` : ""}`);
146079
+ };
145959
146080
  const listener = new PersistentClaudeSession({
145960
146081
  model: cfg.model,
145961
146082
  onUsage: reportUsage,
146083
+ onPlanLimit,
145962
146084
  systemPrompt: agentSystemPrompt,
145963
146085
  // Claude speaks by calling the say tool → the session routes it to the reply
145964
146086
  // bound to the message being answered (wireBridge captures that per inbound via
@@ -145976,6 +146098,7 @@ async function main() {
145976
146098
  model: cfg.model,
145977
146099
  systemPrompt: agentSystemPrompt,
145978
146100
  onUsage: reportUsage,
146101
+ onPlanLimit,
145979
146102
  onObserve: (text) => logLine(`[worker] observed (${text.length} chars, not sent)`),
145980
146103
  worker: true,
145981
146104
  // Task 4: the hard backstop — no tool runs on any worker turn (owner DM or
package/dist/session.d.ts CHANGED
@@ -38,6 +38,8 @@ export type SDKUserMessage = {
38
38
  };
39
39
  parent_tool_use_id: string | null;
40
40
  session_id?: string;
41
+ /** SDK 0.2.141: when the CLI may take a queued prompt. #1508 sends "later". */
42
+ priority?: "now" | "next" | "later";
41
43
  };
42
44
  export type QueryFn = (args: {
43
45
  prompt: AsyncIterable<SDKUserMessage>;
@@ -105,59 +107,39 @@ export interface SessionOpts {
105
107
  * telemetry can never break a turn.
106
108
  */
107
109
  onUsage?: (usage: LlmUsage[], durationApiMs?: number) => void;
110
+ /**
111
+ * #1467: the owner's Claude plan refused this turn. Called at most once per
112
+ * turn, with the plan's reset time in whole epoch seconds when the SDK gave
113
+ * one. Fire-and-forget; a throw is swallowed.
114
+ */
115
+ onPlanLimit?: (info: {
116
+ resetsAt?: number;
117
+ }) => void;
108
118
  }
109
119
  export declare class PersistentClaudeSession {
110
120
  private opts;
111
121
  private waiting;
112
122
  private pending;
113
- /** Reply sink bound to the message currently being processed. Set as each
114
- * message is handed to the model so the say tool routes to the right place. */
115
- private activeReply?;
116
- /** Owner-DM attestation also enables its plain-text fallback. Room turns
117
- * carry separate sender authority and can never become DMs on disarm. */
118
- private currentAutoReply;
119
- private currentToolEligibleSender;
120
- private currentRoomReplyExpected;
121
- private currentHasRoomContext;
122
- /** Called per tool decision so a mid-turn room disarm takes effect live. */
123
- private currentArmedGetter;
124
- /** Effective prose fallback policy, including the separate owner-DM default. */
125
- private currentReplyExpected;
126
- /** #1180: whether the say tool may deliver on this turn. Rooms pass an explicit
127
- * `replyExpected` (#1107: no @ → nobody replies) and that decides it; a 1:1 DM
128
- * passes none and say stays allowed there. Distinct from `currentReplyExpected`,
129
- * which drives only the #416 prose fallback and is false for un-attested DMs. */
130
- private currentSayAllowed;
131
- private saidThisTurn;
132
- private turnText;
133
- /** #630 drop-probe: did a `result` event arrive for the CURRENT turn? Reset per
134
- * turn in input(), set in the result block. Distinguishes a turn that never
135
- * reached a result boundary (the silent-drop prime suspect) from a healthy
136
- * #416 fallback delivery (which delivers via `void reply(...)` WITHOUT setting
137
- * saidThisTurn, so !saidThisTurn alone would false-flag it). */
138
- private sawResultThisTurn;
139
123
  /**
140
- * Per-turn telemetry lifted off the SDK's `result` message.
141
- *
142
- * The message arrives on EVERY turn and we kept one boolean from it
143
- * (`sawResultThisTurn`), discarding the rest. That is the #791 shape: data
144
- * delivered on the healthy path that nothing reads.
145
- *
146
- * It costs us a real answer. A turn that produced nothing (`composed=0,
147
- * said=false`) could be the model choosing silence, the turn cap being hit, or
148
- * the provider returning 429 — three different bugs with one symptom, and
149
- * `subtype`/`apiErrorStatus` are what separate them. 4 of 12 turns on
150
- * 2026-08-07 were silent and could not be attributed.
151
- *
152
- * `durationApiMs` vs `durationMs` also gives the model-time / SDK-overhead
153
- * split directly. That split previously had to be reconstructed by joining
154
- * `WorkerIncident.ranMs` against SDK transcripts on disk by wall clock.
155
- *
156
- * Every field is OPTIONAL and left undefined when no result arrives (abort or
157
- * crash mid-turn): absent must read as absent, never as a zero that looks like
158
- * a real measurement.
124
+ * #1508: one entry per message the SDK has pulled, oldest first. The SDK
125
+ * reads queued prompts EAGERLY (measured: a second message is pulled 300 ms
126
+ * after the first, long before turn 1's output), yet answers them one turn
127
+ * and one `result` each, in order. So a turn's settings live with ITS
128
+ * message: input() appends, a `result` retires the head. Everything the
129
+ * running turn reads — reply target, owed/allowed rules, composed text —
130
+ * comes from the head (`turn()`), never from the newest message.
131
+ */
132
+ private turns;
133
+ /** The turn most recently retired. `turn()` falls back to it between turns,
134
+ * so a late say goes where it did before (the last message's reply). */
135
+ private settled;
136
+ /**
137
+ * #1467: the plan's limit status as the SDK last reported it. SESSION-level
138
+ * on purpose: the CLI emits `rate_limit_event` only when the status CHANGES
139
+ * (`if(!j$(V0,K))YT8(K)` in SDK 0.2.141), so every refused turn after the
140
+ * first arrives with no event of its own. Never reset per turn.
159
141
  */
160
- private resultTelemetry;
142
+ private planLimit;
161
143
  /** In-process room MCP server — hoisted so buildSdkOptions can reference it. */
162
144
  private roomServer;
163
145
  /** AbortController for the in-flight query(); abort() triggers it (queue timeout). */
@@ -189,6 +171,9 @@ export declare class PersistentClaudeSession {
189
171
  * back to opts.onSay. This is what closes the DM→room leak: the destination is
190
172
  * the one captured for the message being answered, not a live global target. */
191
173
  deliver(text: string): Promise<void>;
174
+ /** #1508: the turn now producing output — the oldest pulled message not yet
175
+ * answered — or, between turns, the one just answered. */
176
+ private turn;
192
177
  /** Abort the in-flight query() — used by the worker queue on a per-task timeout. */
193
178
  abort(): void;
194
179
  /**
@@ -223,5 +208,12 @@ export declare class PersistentClaudeSession {
223
208
  */
224
209
  private buildSdkOptions;
225
210
  start(): Promise<void>;
211
+ /**
212
+ * #1467: at a turn's result, report it when Claude refused it with a rate
213
+ * limit WHILE the plan's status is rejected. A refusal with the plan allowed
214
+ * is a short-term rate limit, not the plan's cap; a rejected status with no
215
+ * refusal (extra usage, model fallback) was served. Never throws.
216
+ */
217
+ private reportPlanLimitIfAny;
226
218
  }
227
219
  //# sourceMappingURL=session.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.8.28",
3
+ "version": "0.8.30",
4
4
  "type": "module",
5
5
  "description": "AgentVault Claude Bridge — daemon for bridging a Claude agent into secure E2E-encrypted AgentVault 1:1 direct messages and rooms.",
6
6
  "main": "dist/index.js",