@agentvault/claude-bridge 0.8.35 → 0.8.36

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/README.md CHANGED
@@ -51,6 +51,35 @@ The bridge replies to all messages received in the room. The `room_say`
51
51
  speak/observe tool (which lets Claude choose when to speak vs. just observe)
52
52
  is planned for v0.2.
53
53
 
54
+ ## When a reply fails
55
+
56
+ When a turn fails, the bridge records it first and then tells the chat. It does not drop a failed turn without a trace, and it never posts Claude Code's own error text into a chat.
57
+
58
+ - **In a 1:1**, the owner sees one plain sentence that names the cause when the bridge can tell what it is. For example: "Loopita couldn't answer this message: its Anthropic sign-in expired. Sign in again on the agent's computer." This bridge can tell when:
59
+ - the Claude sign-in expired or is not allowed (this includes "Your organization has disabled Claude subscription access"),
60
+ - the Anthropic account has a billing problem,
61
+ - Anthropic is rate-limiting the agent,
62
+ - the Claude plan's usage limit is reached,
63
+ - the chosen model is not available,
64
+ - Anthropic can't be reached, or
65
+ - Claude Code is missing on the agent's computer or will not start.
66
+
67
+ When the cause is unclear, the sentence simply says the agent couldn't answer this message.
68
+ - **In a room**, the sentence does not name the cause, because other people and agents can read it. The room just sees that the agent couldn't answer this message. A room message nobody addressed to this agent gets no notice at all.
69
+ - **In both cases**, the exact cause appears privately to the owner in the app under **Health, Recent problems**.
70
+
71
+ The bridge log (`agentvault-claude-bridge logs`) writes one line per event:
72
+
73
+ | Log line | What it means |
74
+ |----------|---------------|
75
+ | `turn_failed code=<code> exit=<n or none>` | Claude Code did not produce a reply. The code is the cause the bridge assigned. `exit` is the Claude Code exit status, or `none` when there is none to report. A turn that ran out of time also says `reason=timeout`. |
76
+ | `notice_failed code=<code>` | The turn failed, and the failure notice could not be delivered either. The failure is still recorded under Health. |
77
+ | `fatal: listener stopped code=<code> exit=<n or none>` | The always-on Claude session stopped. The bridge first tells any chat still waiting for an answer, then exits so its service restarts it. |
78
+
79
+ The local `logs/worker-incidents.jsonl` file records the same code for each failed tool turn. The log and that file hold only codes and exit numbers. They never hold message text or provider error text.
80
+
81
+ **Saved sessions.** This bridge does not save or resume a Claude Code session between runs, so there is no saved session to lose. Each tool turn runs in a fresh session, and the always-on session starts fresh when the bridge restarts.
82
+
54
83
  ## Security model
55
84
 
56
85
  - Sessions run with `permissionMode: "default"` and `allowedTools: []` — no
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ToolSpanSink } from "@agentvault/agentvault";
1
+ import { type ToolConversation, type ToolSpanSink } from "@agentvault/agentvault";
2
2
  import { ArmingState } from "./arming.js";
3
3
  import { type TerminalVerdict } from "./service/self-uninstall.js";
4
4
  import { type RoomContextLimits } from "./room-context.js";
@@ -142,6 +142,9 @@ export interface RoomSession {
142
142
  toolEligibleSender?: boolean;
143
143
  armed?: () => boolean;
144
144
  roomContext?: string;
145
+ /** #1560: the conversation this message came from. A failed turn's span
146
+ * names it, and only a "direct" one gets a notice that names the cause. */
147
+ conversation?: ToolConversation;
145
148
  }): unknown;
146
149
  }
147
150
  /** Where a reply should go: a room (sendToRoom) or a 1:1 DM (send). */
package/dist/index.js CHANGED
@@ -11760,7 +11760,7 @@ function ownIdentity() {
11760
11760
  return `${PACKAGE}@${v22}`;
11761
11761
  }
11762
11762
  function buildSha() {
11763
- const raw = true ? "2ee9fe7" : "";
11763
+ const raw = true ? "bcded1f" : "";
11764
11764
  const cleaned = (raw ?? "").trim();
11765
11765
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11766
11766
  }
@@ -17830,6 +17830,48 @@ function armSseKeepAlive(intervalMs, onTick) {
17830
17830
  function asTurnFailureCode(code) {
17831
17831
  return typeof code === "string" && CODES.has(code) ? code : "model_error";
17832
17832
  }
17833
+ function clean5(value, max) {
17834
+ if (typeof value !== "string") return "";
17835
+ return value.replace(/@/g, "").replace(/\s+/g, " ").trim().slice(0, max).trim();
17836
+ }
17837
+ function ownerNoticeFor(code, ctx) {
17838
+ const a2 = clean5(ctx?.agentName, 80) || "Your agent";
17839
+ const p2 = clean5(ctx?.provider, 40) || "AI provider";
17840
+ const head = `${a2} couldn't answer this message`;
17841
+ switch (asTurnFailureCode(code)) {
17842
+ case "provider_auth_failed":
17843
+ return `${head}: its ${p2} sign-in expired. Sign in again on the agent's computer.`;
17844
+ case "provider_billing":
17845
+ return `${head}: its ${p2} account is out of credit or has a billing problem.`;
17846
+ case "model_rate_limited":
17847
+ return `${head}: it is being rate-limited by ${p2}. Try again in a few minutes.`;
17848
+ case "model_unavailable":
17849
+ return `${head}: the model it is set to use is no longer available.`;
17850
+ case "provider_unreachable":
17851
+ return `${head}: it can't reach ${p2} right now.`;
17852
+ case "ai_tool_unsupported":
17853
+ return `${head}: its AI tool needs attention on its computer.`;
17854
+ case "plan_limit_reached":
17855
+ return `${head}: it has reached its ${p2} plan's usage limit.`;
17856
+ default:
17857
+ return `${head}.`;
17858
+ }
17859
+ }
17860
+ function reportModelTurnFailure(sink, report) {
17861
+ try {
17862
+ const code = asTurnFailureCode(report.code);
17863
+ const isPlan = code === "plan_limit_reached";
17864
+ reportToolInvoke(sink, {
17865
+ toolName: "model_turn",
17866
+ outcome: "error",
17867
+ errorKind: code,
17868
+ durationMs: report.durationMs,
17869
+ conversation: isPlan ? { kind: "unknown" } : report.conversation,
17870
+ ...isPlan && report.limitResetsAt !== void 0 ? { limitResetsAt: report.limitResetsAt } : {}
17871
+ });
17872
+ } catch {
17873
+ }
17874
+ }
17833
17875
  var __create, __defProp2, __getOwnPropDesc, __getOwnPropNames2, __getProtoOf, __hasOwnProp, __esm2, __commonJS, __export2, __copyProps, __toESM, SENTINEL, WRAPPERS, INSTRUCTION, init_abstention, AMBIGUOUS_OWNER_ERROR, init_owner_routing, init_envelope_text, init_mls_commit_classify, MENTION_RE, BROADCAST_NAMES, PRIVATE_ROOM_TURN_NOTE, GENERIC_AGENT_NAMES, init_room_protocol, __filename, __dirname, url, path, Module, Module, root, window_, crypto_, randomValuesStandard, crypto2, randomValueNodeJS, _Module, libsodium_sumo_default, init_libsodium_sumo, a, r, t, c, libsodium_wrappers_default, init_libsodium_wrappers, init_keys, init_x3dh, MAX_SKIP, CHAIN_KEY_SEED, MSG_KEY_SEED, HEADER_KEY_SEED, DoubleRatchet, init_ratchet, init_file_crypto, DOMAIN_DID_DOCUMENT, DOMAIN_TRANSFER_INTENT, DOMAIN_TRANSFER_ACCEPT, BASE58_ALPHABET, init_did, BUILTIN_PATTERNS, ScanEngine, init_scan_engine, init_merkle, VC_CONTEXT_V2, AV_CREDENTIAL_CONTEXT, CRYPTOSUITE, BASE58_ALPHABET2, init_vc, init_transport, init_telemetry, TelemetryReporter, init_telemetry_reporter, CROCKFORD, ARGON2_OPSLIMIT, ARGON2_MEMLIMIT, SALT_BYTES, NONCE_BYTES, KEY_BYTES, BACKUP_VERSION, MAX_BACKUP_SIZE, init_backup, atitle, aobject, aopts, isLE, swap8IfBE, swap32IfBE, hasHexBuiltin, hexes, oidNist, init_utils, BSIGMA, init_blake, U32_MASK64, _32n, fromNumH, fromNumL, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, add3L, add3H, add4L, add4H, add5L, add5H, init_u64, HashMD, SHA256_IV, SHA384_IV, SHA512_IV, init_md, B2B_IV, BBUF, _BLAKE2, _BLAKE2b, blake2b, init_blake2, CROCKFORD2, SALT_BYTES2, NONCE_BYTES2, KEY_BYTES2, TAG_BYTES, ENVELOPE_OVERHEAD, AAD_PREFIX, UUID_RE, UUID_V4_RE, DIGEST_ID_RE, TIMESTAMP_RE, encoder, decoder, HISTORY_MAGIC, HISTORY_ARCHIVE_VERSION, HISTORY_MAX_ENTRIES, HISTORY_MAX_BLOB_BYTES, HISTORY_KDF_OPSLIMIT, HISTORY_KDF_MEMLIMIT, HistoryEntryTooLargeError, init_history_backup, init_approval, encVoid, init_tlsEncoder, uint8Encoder, encodeUint8, decodeUint8, uint16Encoder, encodeUint16, decodeUint16, uint32Encoder, encodeUint32, decodeUint32, uint64Encoder, encodeUint64, decodeUint64, init_number, init_tlsDecoder, init_enumHelpers, defaultProposalTypes, defaultProposalTypeEncoder, encodeDefaultProposalType, decodeDefaultProposalType, init_defaultProposalType, defaultExtensionTypes, defaultExtensionTypeEncoder, encodeDefaultExtensionType, decodeDefaultExtensionType, init_defaultExtensionType, acceptAll, init_incomingMessageAction, MlsError, ValidationError, CodecError, UsageError, DependencyError, CryptoVerificationError, CryptoError, InternalError, init_mlsError, init_byteArray, varLenDataEncoder, decodeVarLenData, init_variableLength, init_constantTimeCompare, extensionTypeEncoder, encodeExtensionType, decodeExtensionType, extensionEncoder, encodeExtension, decodeExtension, init_extension, credentialTypes, credentialTypeEncoder, encodeCredentialType, decodeCredentialType, init_credentialType, credentialBasicEncoder, encodeCredentialBasic, credentialX509Encoder, encodeCredentialX509, credentialCustomEncoder, encodeCredentialCustom, credentialEncoder, encodeCredential, decodeCredentialBasic, decodeCredentialX509, decodeCredential, init_credential, externalSenderEncoder, encodeExternalSender, decodeExternalSender, init_externalSender, init_hash, init_optional, ciphersuites, ciphersuiteEncoder, encodeCiphersuite, decodeCiphersuite, ciphersuiteValues, init_ciphersuite, init_signature, protocolVersions, protocolVersionEncoder, encodeProtocolVersion, decodeProtocolVersion, init_protocolVersion, capabilitiesEncoder, encodeCapabilities, decodeCapabilities, init_capabilities, leafNodeSources, leafNodeSourceEncoder, encodeLeafNodeSource, decodeLeafNodeSource, init_leafNodeSource, lifetimeEncoder, encodeLifetime, decodeLifetime, defaultLifetime, init_lifetime, leafNodeDataEncoder, encodeLeafNodeData, decodeLeafNodeData, leafNodeInfoKeyPackageEncoder, encodeLeafNodeInfoKeyPackage, leafNodeInfoUpdateOmittedEncoder, encodeLeafNodeInfoUpdateOmitted, leafNodeInfoCommitOmittedEncoder, encodeLeafNodeInfoCommitOmitted, leafNodeInfoOmittedEncoder, encodeLeafNodeInfoOmitted, decodeLeafNodeInfoKeyPackage, decodeLeafNodeInfoUpdateOmitted, decodeLeafNodeInfoCommitOmitted, decodeLeafNodeInfoOmitted, leafNodeInfoUpdateEncoder, encodeLeafNodeInfoUpdate, leafNodeInfoCommitEncoder, encodeLeafNodeInfoCommit, leafNodeInfoEncoder, encodeLeafNodeInfo, decodeLeafNodeInfoUpdate, decodeLeafNodeInfoCommit, decodeLeafNodeInfo, leafNodeTBSEncoder, encodeLeafNodeTBS, leafNodeEncoder, encodeLeafNode, decodeLeafNode, decodeLeafNodeKeyPackage, decodeLeafNodeCommit, decodeLeafNodeUpdate, init_leafNode, keyPackageTBSEncoder, encodeKeyPackageTBS, decodeKeyPackageTBS, keyPackageEncoder, encodeKeyPackage, decodeKeyPackage, init_keyPackage, init_kdf, pskTypes, pskTypeEncoder, encodePskType, decodePskType, resumptionPSKUsages, resumptionPSKUsageEncoder, encodeResumptionPSKUsage, decodeResumptionPSKUsage, encodePskInfoExternal, encodePskInfoResumption, decodePskInfoResumption, pskInfoEncoder, encodePskInfo, decodePskInfo, pskIdEncoder, encodePskId, decodePskId, pskLabelEncoder, encodePskLabel, decodePskLabel, init_presharedkey, addEncoder, encodeAdd, decodeAdd, updateEncoder, encodeUpdate, decodeUpdate, removeEncoder, encodeRemove, decodeRemove, pskEncoder, encodePSK, decodePSK, reinitEncoder, encodeReinit, decodeReinit, externalInitEncoder, encodeExternalInit, decodeExternalInit, groupContextExtensionsEncoder, encodeGroupContextExtensions, decodeGroupContextExtensions, proposalAddEncoder, encodeProposalAdd, proposalUpdateEncoder, encodeProposalUpdate, proposalRemoveEncoder, encodeProposalRemove, proposalPSKEncoder, encodeProposalPSK, proposalReinitEncoder, encodeProposalReinit, proposalExternalInitEncoder, encodeProposalExternalInit, proposalGroupContextExtensionsEncoder, encodeProposalGroupContextExtensions, proposalCustomEncoder, encodeProposalCustom, proposalEncoder, encodeProposal, decodeProposalAdd, decodeProposalUpdate, decodeProposalRemove, decodeProposalPSK, decodeProposalReinit, decodeProposalExternalInit, decodeProposalGroupContextExtensions, decodeProposal, init_proposal, proposalOrRefTypes, proposalOrRefTypeEncoder, encodeProposalOrRefType, decodeProposalOrRefType, proposalOrRefProposalEncoder, encodeProposalOrRefProposal, proposalOrRefProposalRefEncoder, encodeProposalOrRefProposalRef, proposalOrRefEncoder, encodeProposalOrRef, decodeProposalOrRef, init_proposalOrRefType, init_hpke, groupContextEncoder, encodeGroupContext, decodeGroupContext, init_groupContext, nodeTypes, nodeTypeEncoder, encodeNodeType, decodeNodeType, init_nodeType, parentNodeEncoder, encodeParentNode, decodeParentNode, init_parentNode, init_treemath, nodeEncoder, encodeNode, decodeNode, ratchetTreeEncoder, encodeRatchetTree, decodeRatchetTree, init_ratchetTree, leafNodeHashInputEncoder, encodeLeafNodeHashInput, decodeLeafNodeHashInput, parentNodeHashInputEncoder, encodeParentNodeHashInput, decodeParentNodeHashInput, treeHashInputEncoder, encodeTreeHashInput, decodeTreeHashInput, init_treeHash, parentHashInputEncoder, encodeParentHashInput, decodeParentHashInput, init_parentHash, hpkeCiphertextEncoder, encodeHpkeCiphertext, decodeHpkeCiphertext, init_hpkeCiphertext, updatePathNodeEncoder, encodeUpdatePathNode, decodeUpdatePathNode, updatePathEncoder, encodeUpdatePath, decodeUpdatePath, init_updatePath, commitEncoder, encodeCommit, decodeCommit, init_commit, contentTypes, contentTypeEncoder, encodeContentType, decodeContentType, init_contentType, wireformats, wireformatEncoder, encodeWireformat, decodeWireformat, init_wireformat, senderTypes, senderTypeEncoder, encodeSenderType, decodeSenderType, senderEncoder, encodeSender, decodeSender, reuseGuardEncoder, encodeReuseGuard, decodeReuseGuard, senderDataEncoder, encodeSenderData, decodeSenderData, senderDataAADEncoder, encodeSenderDataAAD, decodeSenderDataAAD, init_sender, framedContentApplicationDataEncoder, encodeFramedContentApplicationData, framedContentProposalDataEncoder, encodeFramedContentProposalData, framedContentCommitDataEncoder, encodeFramedContentCommitData, framedContentInfoEncoder, encodeFramedContentInfo, decodeFramedContentApplicationData, decodeFramedContentProposalData, decodeFramedContentCommitData, decodeFramedContentInfo, framedContentEncoder, encodeFramedContent, decodeFramedContent, senderInfoEncoder, encodeSenderInfo, framedContentTBSEncoder, encodeFramedContentTBS, encodeFramedContentAuthDataContent, encodeFramedContentAuthDataCommit, framedContentAuthDataEncoder, encodeFramedContentAuthData, decodeFramedContentAuthDataCommit, init_framedContent, authenticatedContentEncoder, encodeAuthenticatedContent, decodeAuthenticatedContent, authenticatedContentTBMEncoder, encodeAuthenticatedContentTBM, init_authenticatedContent, publicMessageInfoEncoder, encodePublicMessageInfo, publicMessageEncoder, encodePublicMessage, decodePublicMessage, init_publicMessage, init_messageProtectionPublic, init_externalProposal, requiredCapabilitiesEncoder, encodeRequiredCapabilities, decodeRequiredCapabilities, init_requiredCapabilities, defaultAuthenticationService, init_authenticationService, defaultPaddingConfig, init_paddingConfig, defaultKeyPackageEqualityConfig, init_keyPackageEqualityConfig, defaultLifetimeConfig, init_lifetimeConfig, defaultKeyRetentionConfig, init_keyRetentionConfig, groupInfoTBSEncoder, encodeGroupInfoTBS, decodeGroupInfoTBS, groupInfoEncoder, encodeGroupInfo, decodeGroupInfo, init_groupInfo, keyScheduleEncoder, encodeKeySchedule, decodeKeySchedule, init_keySchedule, generationSecretEncoder, decodeGenerationSecret, secretTreeNodeEncoder, decodeSecretTreeNode, secretTreeEncoder, decodeSecretTree, init_secretTree, confirmedTranscriptHashInputEncoder, encodeConfirmedTranscriptHashInput, decodeConfirmedTranscriptHashInput, init_transcriptHash, groupSecretsEncoder, encodeGroupSecrets, decodeGroupSecrets, init_groupSecrets, encryptedGroupSecretsEncoder, encodeEncryptedGroupSecrets, decodeEncryptedGroupSecrets, welcomeEncoder, encodeWelcome, decodeWelcome, init_welcome, init_pathSecrets, privateKeyPathEncoder, decodePrivateKeyPath, init_privateKeyPath, proposalWithSenderEncoder, decodeProposalWithSender, unappliedProposalsEncoder, decodeUnappliedProposals, init_unappliedProposals, emptyPskIndex, init_pskIndex, init_addToMap, defaultClientConfig, init_clientConfig, init_array, stringEncoder, encodeString, decodeString, init_string, activeEncoder, suspendedPendingReinitEncoder, removedFromGroupEncoder, groupActiveStateEncoder, decodeGroupActiveState, init_groupActiveState, epochReceiverDataEncoder, decodeEpochReceiverData, init_epochReceiverData, groupStateEncoder, encodeGroupState, decodeGroupState, groupStateEncoderWithoutTree, encodeGroupStateWithoutTree, emptyProposals, init_clientState, privateMessageEncoder, encodePrivateMessage, decodePrivateMessage, privateContentAADEncoder, encodePrivateContentAAD, decodePrivateContentAAD, init_privateMessage, init_messageProtection, init_createMessage, init_createCommit, init_processMessages, init_makeHashImpl, HpkeError, InvalidParamError, SerializeError, DeserializeError, EncapError, DecapError, ExportError, SealError, OpenError, MessageLimitReachedError, DeriveKeyPairError, NotSupportedError, init_errors, dntGlobals, dntGlobalThis, init_dnt_shims, NativeAlgorithm, init_algorithm, Mode, KemId, KdfId, AeadId, init_identifiers, INPUT_LENGTH_LIMIT, INFO_LENGTH_LIMIT, MINIMUM_PSK_LENGTH, EMPTY, BYTE_TO_BIGINT_256, init_consts, SUITE_ID_HEADER_KEM, init_kemInterface, HPKE_VERSION, HkdfNative, HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, init_hkdf, isCryptoKeyPair, init_misc, LABEL_EAE_PRK, LABEL_SHARED_SECRET, Dhkem, init_dhkem, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, init_dhkemPrimitives, Bignum, init_bignum, LABEL_CANDIDATE, ORDER_P_256, ORDER_P_384, ORDER_P_521, PKCS8_ALG_ID_P_256, PKCS8_ALG_ID_P_384, PKCS8_ALG_ID_P_521, EC_P_256_PARAMS, EC_P_384_PARAMS, EC_P_521_PARAMS, Ec, init_ec, init_xCryptoKey, init_xCurve, init_hybridkem, AEAD_USAGES, init_aeadEncryptionContext, _endianTestBuffer, _endianTestBytes, isLE2, init_noble, init_hash2, _HMAC, hmac, init_hmac, init_md2, U32_MASK642, _32n2, init_u642, init_sha2, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, init_sha3, init_modular, init_curve, init_montgomery, init_mod, AesGcmContext, Aes128Gcm, Aes256Gcm, init_aesGcm, init_exportOnly, init_emitNotSupported, LABEL_SEC, ExporterContextImpl, RecipientExporterContextImpl, SenderExporterContextImpl, init_exporterContext, EncryptionContextImpl, init_encryptionContext, __classPrivateFieldGet, __classPrivateFieldSet, _Mutex_locked, Mutex, init_mutex, __classPrivateFieldGet2, __classPrivateFieldSet2, _RecipientContextImpl_mutex, RecipientContextImpl, init_recipientContext, __classPrivateFieldGet3, __classPrivateFieldSet3, _SenderContextImpl_mutex, SenderContextImpl, init_senderContext, LABEL_BASE_NONCE, LABEL_EXP, LABEL_INFO_HASH, LABEL_KEY, LABEL_PSK_ID_HASH, LABEL_SECRET, SUITE_ID_HEADER_HPKE, CipherSuiteNative, init_cipherSuiteNative, DhkemP256HkdfSha256Native, DhkemP384HkdfSha384Native, DhkemP521HkdfSha512Native, init_dhkemNative, CipherSuite, DhkemP256HkdfSha256, DhkemP384HkdfSha384, DhkemP521HkdfSha512, HkdfSha256, HkdfSha384, HkdfSha512, init_native, ALG_NAME, PKCS8_ALG_ID_X25519, BASE_POINT_X25519, X25519, init_x25519, DhkemX25519HkdfSha256, init_dhkemX25519, PKCS8_ALG_ID_X448, init_x448, init_dhkemX448, init_mod2, init_hpke2, isLE3, wrapCipher, init_utils2, encodeStr, sigma16, sigma32, sigma16_32, sigma32_32, BLOCK_LEN, BLOCK_LEN32, MAX_COUNTER, U32_EMPTY, _XorStreamPRG, createPRG, init_arx, Poly1305, poly1305, init_poly1305, chacha_exports, chacha20orig, chacha20, xchacha20, chacha8, chacha12, ZEROS16, updatePadded, ZEROS32, _poly1305_aead, chacha20poly1305, xchacha20poly1305, rngChacha20, rngChacha8, init_chacha, init_makeAead, init_makeKdfImpl, init_makeDhKem, init_makeHpke, defaultRng, init_rng, crypto3, init_cryptoNode, isLE4, swap32IfBE3, hasHexBuiltin2, hexes2, asciis, Hash, init_utils3, HashMD3, SHA256_IV3, SHA384_IV3, SHA512_IV3, init_md3, U32_MASK643, _32n3, shrSH3, shrSL3, rotrSH3, rotrSL3, rotrBH3, rotrBL3, rotlSH2, rotlSL2, rotlBH2, rotlBL2, add3L3, add3H3, add4L3, add4H3, add5L3, add5H3, init_u643, SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, SHA384, sha2563, sha5122, sha3842, init_sha22, _0n2, _1n2, isPosBig, bitMask, notImplemented, init_utils4, _0n3, _1n3, _2n2, _3n, _4n, _5n, _7n2, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS, init_modular2, _0n4, _1n4, pointPrecomputes, pointWindowSizes, wNAF, init_curve2, _0n5, _1n5, _2n3, _8n2, PrimeEdwardsPoint, init_edwards, os2ip, _DST_scalar, init_hash_to_curve, _0n6, _1n6, _2n4, init_montgomery2, ed25519_exports, _0n7, _1n7, _2n5, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, Fp, Fn, ed25519Defaults, ed25519, ed25519ctx, ed25519ph, x25519, ELL2_C1, ELL2_C2, ELL2_C3, ELL2_C1_EDWARDS, ed25519_hasher, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, _RistrettoPoint, ristretto255, ristretto255_hasher, ED25519_TORSION_SUBGROUP, edwardsToMontgomery, RistrettoPoint, hashToCurve, encodeToCurve, hashToRistretto255, hash_to_ristretto255, init_ed25519, _0n8, _1n8, _2n6, _7n3, _256n2, _0x71n2, SHA3_PI2, SHA3_ROTL2, _SHA3_IOTA2, IOTAS2, SHA3_IOTA_H2, SHA3_IOTA_L2, rotlH, rotlL, Keccak, genShake, shake2562, init_sha32, ed448_exports, ed448_CURVE, E448_CURVE, shake256_114, shake256_64, _1n9, _2n7, _3n3, _4n2, _11n, _22n, _44n, _88n, _223n, Fp2, Fn2, Fp448, Fn448, ED448_DEF, ed448, ed448ph, E448, x448, ELL2_C12, ELL2_J, ed448_hasher, ONE_MINUS_D, ONE_MINUS_TWO_D, SQRT_MINUS_D, INVSQRT_MINUS_D, invertSqrt2, _DecafPoint, decaf448, decaf448_hasher, ED448_TORSION_SUBGROUP, DecafPoint, hashToCurve2, encodeToCurve2, hashToDecaf448, hash_to_decaf448, edwardsToMontgomery2, init_ed448, HMAC, hmac2, init_hmac2, divNearest, DERErr, DER, _0n9, _1n10, _2n8, _3n4, _4n3, init_weierstrass, init_shortw_utils, nist_exports, p256_CURVE, p384_CURVE, p521_CURVE, Fp256, Fp384, Fp521, p256, p256_hasher, p384, p384_hasher, p521, secp256r1, secp384r1, secp521r1, p521_hasher, init_nist, init_makeNobleSignatureImpl, defaultCryptoProvider, init_provider, init_getCiphersuiteImpl, init_resumption, SHA256_K2, SHA256_W2, SHA2_32B, _SHA256, K5122, SHA512_Kh2, SHA512_Kl2, SHA512_W_H2, SHA512_W_L2, SHA2_64B, _SHA512, _SHA384, sha2564, sha5123, sha3843, init_sha23, _HMAC2, hmac3, init_hmac3, init_makeHashImpl2, init_makeNobleSignatureImpl2, BLOCK_SIZE, ZEROS162, ZEROS322, POLY, mul2, swapLE, estimateWindow, GHASH, Polyval, ghash, polyval, init_polyval, BLOCK_SIZE2, BLOCK_SIZE32, EMPTY_BLOCK, POLY2, sbox, rotr32_8, rotl32_8, tableEncoding, xPowers, gcm, _CMAC, cmac, init_aes, init_makeAead2, init_makeKdfImpl2, init_makeDhKem2, init_makeHpke2, init_rng2, nobleCryptoProvider, init_provider2, mlsPublicMessageEncoder, encodeMlsPublicMessage, mlsWelcomeEncoder, encodeMlsWelcome, mlsPrivateMessageEncoder, encodeMlsPrivateMessage, mlsGroupInfoEncoder, encodeMlsGroupInfo, mlsKeyPackageEncoder, encodeMlsKeyPackage, mlsMessageContentEncoder, encodeMlsMessageContent, decodeMlsMessageContent, mlsMessageEncoder, encodeMlsMessage, decodeMlsMessage, init_message, greaseValues, defaultGreaseConfig, init_grease, init_defaultCapabilities, init_src, DEFAULT_CIPHERSUITE, MLSGroupManager, init_mls_group, DOMAIN, NONCE_BYTES3, init_owner_sync, init_mls_delivery_order, init_mls_presend_epoch, dist_exports, init_dist2, DIR_MODE, FILE_MODE, init_secure_file, SYNC_LOCK_STALE_MS, pendingKpPath, DECRYPTED_IDS_FILE, init_mls_state, init_mls_kp_pool, PACKAGE, FALLBACK, MAX_LEN, DISALLOWED, init_client_version, CredentialStore, init_credential_store, init_crypto_helpers, STATE_FILE, LEGACY_STATE_FILE, init_state, ACTIVATION_DOMAIN, UUID_RE2, init_transport2, A2ALogGate, init_a2a_log_gate, NOT_A_MEMBER_DETAIL, init_mls_membership_probe, FIRST_DIRTY_DELAY_MS, RETRY_BASE_DELAYS_MS, MAX_RETRY_DELAY_MS, JITTER_FRACTION, HistoryBackupScheduler, init_history_backup_scheduler, FILE_MODE2, init_history_recovery_file, TENANT_ID_PATTERN, DIR_MODE2, FILE_MODE3, HISTORY_RECOVERY_VERIFY_TIMEOUT_MS, VERIFY_TIMEOUT_MESSAGE, HistoryRecoveryVerificationTimeoutError, init_history_recovery_code, ACTIONS, init_decision_reply, KP_BACKOFF_INITIAL_MS, KP_BACKOFF_MAX_MS, KP_RACE_RETRY_MS, KP_RACE_RETRY_LIMIT, consoleLogger, short, WelcomeKeyPackageBackoff, init_welcome_kp_backoff, history_backup_client_exports, HISTORY_RESTORE_TIMEOUT_MS, HISTORY_RESTORE_RESPONSE_MAX_BYTES, HISTORY_ENVELOPE_MIN_BYTES, HISTORY_AAD_PREFIX, UUID_RE3, GENERATION_RESPONSE_KEYS, utf8Encoder, utf8Decoder, HistoryBackupClient, init_history_backup_client, openclaw_compat_exports, defaultImporter, HEARTBEAT_CANDIDATES, _heartbeatFn, init_openclaw_compat, TOOL_INVOKE_SPAN_NAME, UNCLASSIFIED_ERROR, KNOWN_TOOL_ERROR_CODES, KNOWN_CODES, CLASS_NAME_RE, TOOL_NAME_RE, ERROR_TEXT_CODES, _conversation, init_tool_telemetry, http_handlers_exports, init_http_handlers, mcp_proxy_helpers_exports, init_mcp_proxy_helpers, workspace_handlers_exports, MAX_FILE_SIZE, init_workspace_handlers, ROOM_AGENT_TYPES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, UUID_RE4, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, HISTORY_RESTORE_TIMEOUT_MS2, ROOM_ROSTER_REFRESH_TIMEOUT_MS, HISTORY_UPLOAD_TIMEOUT_MS, CANONICAL_TIMESTAMP_RE, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, _turnConversation, PERSON_INVOLVED_WINDOW_MS, ATTESTED_INBOUND_MAX, UNMAPPED_RECONCILE_COOLDOWN_MS, TOPIC_ID_RE, ROOM_FULFIL_COOLDOWN_MS, SecureChannel, init_channel, init_types, DEFAULT_API_URL, DEFAULT_HTTP_PORT, init_account_config, init_lifecycle, _ocRuntime, _channels, agentVaultPlugin, init_openclaw_plugin, init_gateway_send, init_llm_response_parser, OPENROUTER_PRICING, init_llm_pricing_openrouter, LEGACY_PRICING, PRICING, init_llm_cost, traceStore, init_fetch_interceptor, init_tool_audit, init_harness_compat, managedRoutesRequested, init_openclaw_entry, util, objectUtil, ZodParsedType, getParsedType, init_util, ZodIssueCode, ZodError, init_ZodError, errorMap, en_default, init_en, overrideErrorMap, init_errors2, makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, init_parseUtil, init_typeAliases, errorUtil, init_errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, init_types2, init_external, init_v3, util_exports, Cached, EVALUATING, captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, highSurrogate, Class, installing, broke, breaker, CONSTANT_CATCH, init_util2, _a2, _zodDesc, _E, $ZodAsyncError, $ZodEncodeError, globalConfig, init_core, _messageDesc, _issuesDesc, _installedToString, initializer, $ZodError, $ZodRealError, init_errors3, _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, COMPILE_INVALID, COMPILE_FALLBACK, validate, validateAsync, _encode, _decode, _encodeAsync, _decodeAsync, _safeEncode, _safeDecode, _safeEncodeAsync, _safeDecodeAsync, init_parse, cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, dateSource, date, anyString, integer, number, boolean, _null, lowercase, uppercase, init_regexes, $ZodCheck, _whenHasLength, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite, init_checks, Doc, init_doc, version, init_versions, $ZodType, toStandardResult, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT, URL_UNPARSEABLE, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodNull, $ZodUnknown, $ZodNever, arraySize, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom, init_schemas, $ZodCyclicError, STATE, NO_ISSUES, recursive, NONE, ASSUMED, PROVEN, handoff, open4, memo, init_memoizer, error, init_en2, init_locales, _a3, $ZodRegistry, globalRegistry, init_registries, init_compile, init_api, FOLDABLE_KEYS, UNION_KEYS, createToJSONSchemaMethod, createStandardJSONSchemaMethod, init_to_json_schema, narrowMin, narrowMax, narrowBoth, addDivisor, addPattern, intersectMime, setFormat, minContributor, maxContributor, formatContributor, contributors, formatMap, exactPatterns, exactPattern, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, pendingRecords, recordProcessor, nullableProcessor, nonoptionalProcessor, UNREPRESENTABLE_DEFAULT, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors, init_json_schema_processors, init_json_schema, init_core2, init_parse2, ZodMiniType, ZodMiniObject, init_schemas2, init_checks2, init_iso, init_coerce, init_external2, init_v4_mini, init_zod_compat, init_checks3, _installedErrorProtos, initializer2, ZodRealError, init_errors4, parse2, parseAsync2, safeParse3, safeParseAsync3, encode3, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2, init_parse3, ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodNull2, ZodUnknown2, ZodNever2, ZodArray2, ZodObject2, ZodUnion2, ZodDiscriminatedUnion2, ZodIntersection2, ZodRecord2, ZodEnum2, ZodLiteral2, ZodTransform, ZodOptional2, ZodExactOptional, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodCatch2, ZodPipe, ZodPreprocess, ZodReadonly2, ZodCustom, init_schemas3, ZodFirstPartyTypeKind2, init_compat, iso_exports2, init_iso2, init_coerce2, init_external3, init_classic, init_v4, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, JSONRPC_VERSION, AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskCreationParamsSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResultResponseSchema, isJSONRPCResultResponse, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, isInitializeRequest, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, McpError, UrlElicitationRequiredError, init_types3, init_interfaces, ignoreOverride, defaultOptions, getDefaultOptions, init_Options, getRefs, init_Refs, init_errorMessages, getRelativePath, init_getRelativePath, init_any, init_array2, init_bigint, init_boolean, init_branded, parseCatchDef, init_catch, integerDateParser, init_date, init_default, init_effects, init_enum, isJsonSchema7AllOfType, init_intersection, init_literal, emojiRegex2, zodPatterns, ALPHA_NUMERIC, init_string2, init_record, init_map, init_nativeEnum, init_never, init_null, primitiveMappings, asAnyOf, init_union, init_nullable, init_number2, init_object, parseOptionalDef, init_optional2, parsePipelineDef, init_pipeline, init_promise, init_set, init_tuple, init_undefined, init_unknown, parseReadonlyDef, init_readonly, selectParser, init_selectParser, get$ref, addMeta, init_parseDef, init_parseTypes, zodToJsonSchema, init_zodToJsonSchema, init_esm, init_zod_json_schema_compat, DEFAULT_REQUEST_TIMEOUT_MSEC, Protocol, init_protocol, require_code, require_scope, require_codegen, require_util, require_names, require_errors, require_boolSchema, require_rules, require_applicability, require_dataType, require_defaults, require_code2, require_keyword, require_subschema, require_fast_deep_equal, require_json_schema_traverse, require_resolve, require_validate, require_validation_error, require_ref_error, require_compile, require_data, require_utils, require_schemes, require_fast_uri, require_uri, require_core, require_id, require_ref, require_core2, require_limitNumber, require_multipleOf, require_ucs2length, require_limitLength, require_pattern, require_limitProperties, require_required, require_limitItems, require_equal, require_uniqueItems, require_const, require_enum, require_validation, require_additionalItems, require_items, require_prefixItems, require_items2020, require_contains, require_dependencies, require_propertyNames, require_additionalProperties, require_properties, require_patternProperties, require_not, require_anyOf, require_oneOf, require_allOf, require_if, require_thenElse, require_applicator, require_format, require_format2, require_metadata, require_draft7, require_types, require_discriminator, require_json_schema_draft_07, require_ajv, require_formats, require_limit, require_dist, import_ajv, import_ajv_formats, AjvJsonSchemaValidator, init_ajv_provider, ExperimentalServerTasks, init_server, init_helpers, Server, init_server2, COMPLETABLE_SYMBOL, McpZodTypeKind, init_completable, init_uriTemplate, TOOL_NAME_REGEX, init_toolNameValidation, ExperimentalMcpServerTasks, init_mcp_server, init_zod, McpServer, EMPTY_OBJECT_JSON_SCHEMA, EMPTY_COMPLETION_RESULT, init_mcp, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, init_dist22, require_content_type, import_content_type, init_mediaType, DEFAULT_MAX_REQUEST_BODY_SIZE, MAX_BATCH_SIZE, init_requestBody, DEFAULT_SSE_KEEP_ALIVE_MS, MAX_TIMER_DELAY_MS, init_sseKeepAlive, WebStandardStreamableHTTPServerTransport, init_webStandardStreamableHttp, StreamableHTTPServerTransport, init_streamableHttp, AgentVaultMcpServer, init_mcp_server2, init_mcp_handlers, init_skill_manifest, init_skill_invoker, spanBuffer, init_skill_telemetry, PolicyEnforcer, init_policy_enforcer, TURN_FAILURE_CODES, CODES, TurnFailure, NOTICE_RE, init_turn_failure, VERSION, init_index;
17834
17876
  var init_dist = __esm({
17835
17877
  async "../plugin/dist/index.js"() {
@@ -145004,7 +145046,132 @@ function usageFromResult(result, fallbackModel) {
145004
145046
  return out;
145005
145047
  }
145006
145048
 
145049
+ // src/turn-failure.ts
145050
+ await init_dist();
145051
+ var PROVIDER = "Anthropic";
145052
+ function classifyClaudeFailure(s10) {
145053
+ if (s10?.planLimit === true)
145054
+ return "plan_limit_reached";
145055
+ const e7 = s10?.assistantError;
145056
+ if (e7 === "authentication_failed" || e7 === "oauth_org_not_allowed")
145057
+ return "provider_auth_failed";
145058
+ if (e7 === "billing_error")
145059
+ return "provider_billing";
145060
+ if (e7 === "rate_limit")
145061
+ return "model_rate_limited";
145062
+ if (e7 === "server_error")
145063
+ return "provider_unreachable";
145064
+ if (s10?.subtype === "error_max_turns")
145065
+ return "model_error";
145066
+ const st = s10?.apiErrorStatus;
145067
+ if (st === 401 || st === 403)
145068
+ return "provider_auth_failed";
145069
+ if (st === 402)
145070
+ return "provider_billing";
145071
+ if (st === 429)
145072
+ return "model_rate_limited";
145073
+ if (st === 404)
145074
+ return "model_unavailable";
145075
+ if (typeof st === "number" && st >= 500 && st <= 599)
145076
+ return "provider_unreachable";
145077
+ if (s10?.connectionRetry === true && (st === void 0 || st === null))
145078
+ return "provider_unreachable";
145079
+ return "model_error";
145080
+ }
145081
+ var CLI_UNSUPPORTED_RE = /^(?:Native CLI binary for \S+ not found\b|Claude Code executable not found at |Failed to spawn Claude Code process: )/;
145082
+ var EXIT_RE = /^Claude Code process exited with code (\d{1,3})$/;
145083
+ function classifyClaudeThrow(err) {
145084
+ if (err instanceof TurnFailure)
145085
+ return err.code;
145086
+ const msg = err instanceof Error ? err.message : "";
145087
+ if (CLI_UNSUPPORTED_RE.test(msg))
145088
+ return "ai_tool_unsupported";
145089
+ return "model_error";
145090
+ }
145091
+ function exitCodeOf(err) {
145092
+ if (err instanceof TurnFailure)
145093
+ return err.exitCode;
145094
+ const m6 = EXIT_RE.exec(err instanceof Error ? err.message : "");
145095
+ return m6 ? Number(m6[1]) : void 0;
145096
+ }
145097
+ function reportTurnFailed(deps, t7, log) {
145098
+ const conversation = t7.conversation ?? { kind: "unknown" };
145099
+ if (!t7.spanRecorded) {
145100
+ let sink;
145101
+ try {
145102
+ sink = deps?.telemetry?.();
145103
+ } catch {
145104
+ sink = null;
145105
+ }
145106
+ reportModelTurnFailure(sink && typeof sink.reportCustomSpan === "function" ? sink : null, {
145107
+ code: t7.code,
145108
+ conversation,
145109
+ durationMs: Math.max(0, Math.round(t7.durationMs))
145110
+ });
145111
+ }
145112
+ const exit = typeof t7.exitCode === "number" ? t7.exitCode : "none";
145113
+ safeLog(log, `[bridge] turn_failed code=${t7.code} exit=${exit}${t7.reason ? ` reason=${t7.reason}` : ""}`);
145114
+ if (!t7.owed || !t7.reply) return Promise.resolve();
145115
+ let name;
145116
+ try {
145117
+ name = deps?.agentName?.();
145118
+ } catch {
145119
+ name = void 0;
145120
+ }
145121
+ const notice = ownerNoticeFor(conversation.kind === "direct" && !t7.spoke ? t7.code : "model_error", {
145122
+ agentName: typeof name === "string" ? name.trim() : "",
145123
+ provider: PROVIDER
145124
+ });
145125
+ const reply = t7.reply;
145126
+ return (async () => {
145127
+ try {
145128
+ await reply(notice);
145129
+ } catch (err) {
145130
+ safeLog(log, `[bridge] notice_failed code=${classifyToolError(err)}`);
145131
+ }
145132
+ })();
145133
+ }
145134
+ function safeLog(log, m6) {
145135
+ try {
145136
+ log(m6);
145137
+ } catch {
145138
+ }
145139
+ }
145140
+ var FLUSH_TIMEOUT_MS = 5e3;
145141
+ var FATAL_DEADLINE_MS = 15e3;
145142
+ async function settleWithin(p2, ms2) {
145143
+ let timer;
145144
+ try {
145145
+ await Promise.race([
145146
+ p2.then(() => void 0, () => void 0),
145147
+ new Promise((resolve5) => {
145148
+ timer = setTimeout(resolve5, ms2);
145149
+ timer.unref?.();
145150
+ })
145151
+ ]);
145152
+ } finally {
145153
+ if (timer) clearTimeout(timer);
145154
+ }
145155
+ }
145156
+ async function stopAfterListenerFailure(err, deps) {
145157
+ const sequence = (async () => {
145158
+ try {
145159
+ await deps.session.failOpenTurns(err);
145160
+ } catch {
145161
+ }
145162
+ try {
145163
+ await settleWithin(Promise.resolve(deps.flush?.()), deps.flushTimeoutMs ?? FLUSH_TIMEOUT_MS);
145164
+ } catch {
145165
+ }
145166
+ })();
145167
+ await settleWithin(sequence, deps.deadlineMs ?? FATAL_DEADLINE_MS);
145168
+ const exit = exitCodeOf(err);
145169
+ safeLog(deps.log, `[bridge] fatal: listener stopped code=${classifyClaudeThrow(err)} exit=${exit ?? "none"}`);
145170
+ deps.exit(1);
145171
+ }
145172
+
145007
145173
  // src/session.ts
145174
+ var NOTICE_WAIT_MS = 1e4;
145008
145175
  function makeRoomSayTool(onSay) {
145009
145176
  return bs(
145010
145177
  "say",
@@ -145035,7 +145202,10 @@ function newTurn(item) {
145035
145202
  text: "",
145036
145203
  sawResult: false,
145037
145204
  refused: false,
145038
- telemetry: {}
145205
+ telemetry: {},
145206
+ conversation: item?.conversation,
145207
+ connectionRetry: false,
145208
+ startedAt: Date.now()
145039
145209
  };
145040
145210
  }
145041
145211
  var PersistentClaudeSession = class {
@@ -145069,6 +145239,13 @@ var PersistentClaudeSession = class {
145069
145239
  roomServer;
145070
145240
  /** AbortController for the in-flight query(); abort() triggers it (queue timeout). */
145071
145241
  _abort;
145242
+ /** #1560: every failure notice still being sent, so a worker's start()
145243
+ * settles only after its notice did (the queue then moves on). */
145244
+ notices = [];
145245
+ /** #1560: the code of the first failed turn this session recorded. */
145246
+ firstFailure;
145247
+ /** Review X1: set by abort(); the aborter owns the failure report from then on. */
145248
+ aborted = false;
145072
145249
  /**
145073
145250
  * Queue an inbound message for the model.
145074
145251
  * @param opts.autoReplyOnText — for 1:1 DMs (where the owner always expects a
@@ -145107,7 +145284,8 @@ ${text}` : text;
145107
145284
  autoReplyOnText: opts?.autoReplyOnText,
145108
145285
  replyExpected: opts?.replyExpected,
145109
145286
  toolEligibleSender: opts?.toolEligibleSender,
145110
- armed: opts?.armed
145287
+ armed: opts?.armed,
145288
+ conversation: opts?.conversation
145111
145289
  };
145112
145290
  if (this.waiting) {
145113
145291
  const w2 = this.waiting;
@@ -145139,6 +145317,7 @@ ${text}` : text;
145139
145317
  }
145140
145318
  /** Abort the in-flight query() — used by the worker queue on a per-task timeout. */
145141
145319
  abort() {
145320
+ this.aborted = true;
145142
145321
  this._abort?.abort();
145143
145322
  }
145144
145323
  /**
@@ -145313,8 +145492,17 @@ ${text}` : text;
145313
145492
  resetsAt: rejected && typeof at === "number" && Number.isFinite(at) ? Math.floor(at) : void 0
145314
145493
  };
145315
145494
  }
145495
+ } else if (m6.type === "system") {
145496
+ const sys = m6;
145497
+ if (sys.subtype === "api_retry" && sys.error_status === null) this.turn().connectionRetry = true;
145316
145498
  } else if (m6.type === "assistant") {
145317
- if (m6.error === "rate_limit") this.turn().refused = true;
145499
+ const error63 = m6.error;
145500
+ if (error63 === "rate_limit") this.turn().refused = true;
145501
+ if (typeof error63 === "string" && error63) {
145502
+ this.turn().assistantError = error63;
145503
+ continue;
145504
+ }
145505
+ this.turn().connectionRetry = false;
145318
145506
  const blocks = m6.message?.content ?? [];
145319
145507
  const text = blocks.filter((b5) => b5.type === "text").map((b5) => b5.text ?? "").join("");
145320
145508
  if (text.trim()) {
@@ -145333,7 +145521,7 @@ ${text}` : text;
145333
145521
  const str = (k2) => typeof r7[k2] === "string" ? r7[k2] : void 0;
145334
145522
  const usage = r7.usage ?? {};
145335
145523
  const unum = (k2) => typeof usage[k2] === "number" ? usage[k2] : void 0;
145336
- this.reportPlanLimitIfAny(turn);
145524
+ const planLimit = this.reportPlanLimitIfAny(turn);
145337
145525
  turn.telemetry = {
145338
145526
  durationMs: num2("duration_ms"),
145339
145527
  durationApiMs: num2("duration_api_ms"),
@@ -145350,7 +145538,16 @@ ${text}` : text;
145350
145538
  } catch {
145351
145539
  }
145352
145540
  const reply = turn.reply;
145353
- if (turn.replyExpected && !turn.said && turn.text.trim()) {
145541
+ const answered = turn.said || turn.text.trim() !== "";
145542
+ if (r7.is_error === true || turn.assistantError !== void 0 && !answered) {
145543
+ this.failTurn(turn, classifyClaudeFailure({
145544
+ assistantError: turn.assistantError,
145545
+ apiErrorStatus: r7.api_error_status,
145546
+ connectionRetry: turn.connectionRetry,
145547
+ subtype: r7.subtype,
145548
+ planLimit
145549
+ }), { spanRecorded: planLimit });
145550
+ } else if (turn.replyExpected && !turn.said && turn.text.trim()) {
145354
145551
  if (reply) {
145355
145552
  void reply(turn.text);
145356
145553
  } else {
@@ -145369,25 +145566,84 @@ ${text}` : text;
145369
145566
  `[drop-probe] STREAM ENDED before result: composed ${turn.text.length} chars, reply expected, said=false \u2014 reply DROPPED (no result event)`
145370
145567
  );
145371
145568
  }
145569
+ if (this.notices.length > 0) await settleWithin(Promise.allSettled(this.notices), NOTICE_WAIT_MS);
145372
145570
  }
145373
145571
  }
145572
+ /**
145573
+ * #1560: the code of the first turn this session recorded as failed, or
145574
+ * undefined. The worker queue reads it so a failure the session already
145575
+ * reported (span, log, notice) is never reported a second time when the
145576
+ * SDK then throws.
145577
+ */
145578
+ failureCode() {
145579
+ return this.firstFailure;
145580
+ }
145581
+ /**
145582
+ * #1560: record one failed turn (once) and, if it owed a reply, start its
145583
+ * notice. The record is synchronous; the notice is tracked in `notices`.
145584
+ */
145585
+ failTurn(turn, code, extra = {}) {
145586
+ if (turn.failed !== void 0 || this.aborted) return Promise.resolve();
145587
+ turn.failed = code;
145588
+ this.firstFailure ??= code;
145589
+ const notice = reportTurnFailed(
145590
+ this.opts.failure,
145591
+ {
145592
+ code,
145593
+ exitCode: extra.exitCode,
145594
+ conversation: turn.conversation,
145595
+ durationMs: turn.telemetry.durationMs ?? Date.now() - turn.startedAt,
145596
+ spanRecorded: extra.spanRecorded,
145597
+ reply: turn.reply,
145598
+ // The #416 reply rule: a room turn owes a reply only when it was
145599
+ // addressed (#1107); a 1:1 only when it is owner-attested (#621).
145600
+ // Review L2: an unattested DM gets no notice at all, as on grok and
145601
+ // muse — the coded sentences describe the owner's own account.
145602
+ // Re-review N1: once the agent already spoke this turn, the notice is
145603
+ // the bare sentence; silence after a partial answer is the #1560 bug.
145604
+ owed: turn.replyExpected,
145605
+ spoke: turn.said
145606
+ },
145607
+ (m6) => logLine(m6)
145608
+ );
145609
+ const tracked = notice.finally(() => {
145610
+ const i2 = this.notices.indexOf(tracked);
145611
+ if (i2 >= 0) this.notices.splice(i2, 1);
145612
+ });
145613
+ this.notices.push(tracked);
145614
+ return tracked;
145615
+ }
145616
+ /**
145617
+ * #1560: the query() stopped with turns still unanswered (the listener's
145618
+ * fatal path). Each one is recorded and, where owed, told — a message
145619
+ * already handed to the model and one still waiting alike. Resolves once
145620
+ * every notice has settled. Never throws.
145621
+ */
145622
+ async failOpenTurns(err) {
145623
+ const code = classifyClaudeThrow(err);
145624
+ const exitCode = exitCodeOf(err);
145625
+ const open6 = [...this.turns, ...this.pending.splice(0).map((item) => newTurn(item))];
145626
+ this.turns = [];
145627
+ await Promise.allSettled(open6.map((turn) => this.failTurn(turn, code, { exitCode })));
145628
+ }
145374
145629
  /**
145375
145630
  * #1467: at a turn's result, report it when Claude refused it with a rate
145376
145631
  * limit WHILE the plan's status is rejected. A refusal with the plan allowed
145377
145632
  * is a short-term rate limit, not the plan's cap; a rejected status with no
145378
- * refusal (extra usage, model fallback) was served. Never throws.
145633
+ * refusal (extra usage, model fallback) was served. Never throws. Returns
145634
+ * whether it was the plan's limit (#1560: that span is the turn's one span).
145379
145635
  */
145380
145636
  reportPlanLimitIfAny(turn) {
145381
- if (!turn.refused || !this.planLimit.rejected) return;
145637
+ if (!turn.refused || !this.planLimit.rejected) return false;
145382
145638
  try {
145383
145639
  this.opts.onPlanLimit?.({ resetsAt: this.planLimit.resetsAt });
145384
145640
  } catch {
145385
145641
  }
145642
+ return true;
145386
145643
  }
145387
145644
  };
145388
145645
 
145389
145646
  // src/worker-queue.ts
145390
- var GENERIC_ERROR = "Sorry \u2014 I couldn't complete that request.";
145391
145647
  var WorkerQueue = class {
145392
145648
  constructor(deps) {
145393
145649
  this.deps = deps;
@@ -145431,6 +145687,14 @@ var WorkerQueue = class {
145431
145687
  snapshotOf(session) {
145432
145688
  return session?.snapshot?.();
145433
145689
  }
145690
+ /** The failure the session itself already recorded, if any. */
145691
+ failureOf(session) {
145692
+ try {
145693
+ return session?.failureCode?.();
145694
+ } catch {
145695
+ return void 0;
145696
+ }
145697
+ }
145434
145698
  /** Best-effort trap emit. A broken sink must never break the queue. */
145435
145699
  emitIncident(rec) {
145436
145700
  try {
@@ -145452,7 +145716,8 @@ var WorkerQueue = class {
145452
145716
  autoReplyOnText: task.autoReplyOnText,
145453
145717
  replyExpected: task.replyExpected,
145454
145718
  toolEligibleSender: task.toolEligibleSender,
145455
- armed: task.armed
145719
+ armed: task.armed,
145720
+ conversation: task.conversation
145456
145721
  });
145457
145722
  const currentSession = session;
145458
145723
  const timeout = new Promise((_resolve, reject) => {
@@ -145464,9 +145729,11 @@ var WorkerQueue = class {
145464
145729
  });
145465
145730
  await Promise.race([session.start(), timeout]);
145466
145731
  const okSnap = this.snapshotOf(session);
145732
+ const failedCode = this.failureOf(session);
145467
145733
  this.emitIncident({
145468
145734
  at: new Date(startedAt).toISOString(),
145469
- outcome: "ok",
145735
+ outcome: failedCode ? "error" : "ok",
145736
+ ...failedCode ? { code: failedCode } : {},
145470
145737
  waitedMs,
145471
145738
  ranMs: Date.now() - startedAt,
145472
145739
  timeoutMs: this.deps.timeoutMs,
@@ -145476,14 +145743,14 @@ var WorkerQueue = class {
145476
145743
  replyExpected: task.replyExpected,
145477
145744
  ...okSnap ? { session: okSnap } : {}
145478
145745
  });
145479
- } catch (e7) {
145480
- const err = e7;
145481
- this.deps.log(`[worker-queue] task failed: ${err.message}`);
145746
+ } catch (err) {
145747
+ const handled = this.failureOf(session);
145748
+ const code = handled ?? (timedOut ? "model_error" : classifyClaudeThrow(err));
145482
145749
  const snap = this.snapshotOf(session);
145483
145750
  this.emitIncident({
145484
145751
  at: new Date(startedAt).toISOString(),
145485
145752
  outcome: timedOut ? "timeout" : "error",
145486
- error: err.message,
145753
+ code,
145487
145754
  waitedMs,
145488
145755
  ranMs: Date.now() - startedAt,
145489
145756
  timeoutMs: this.deps.timeoutMs,
@@ -145494,10 +145761,24 @@ var WorkerQueue = class {
145494
145761
  ...snap ? { session: snap } : {}
145495
145762
  });
145496
145763
  session?.abort();
145497
- try {
145498
- await task.reply(GENERIC_ERROR);
145499
- } catch (replyErr) {
145500
- this.deps.log(`[worker-queue] failed to deliver error reply: ${replyErr.message}`);
145764
+ if (handled === void 0) {
145765
+ await reportTurnFailed(
145766
+ this.deps.failure,
145767
+ {
145768
+ code,
145769
+ exitCode: timedOut ? void 0 : exitCodeOf(err),
145770
+ ...timedOut ? { reason: "timeout" } : {},
145771
+ conversation: task.conversation,
145772
+ durationMs: Date.now() - startedAt,
145773
+ reply: task.reply,
145774
+ // Every worker task owes its reply: the router queues only owner
145775
+ // DMs and addressed armed-room turns. Re-review N1: a worker that
145776
+ // already spoke still gets the closing (bare) sentence.
145777
+ owed: task.replyExpected !== false,
145778
+ spoke: snap?.said === true
145779
+ },
145780
+ this.deps.log
145781
+ );
145501
145782
  }
145502
145783
  } finally {
145503
145784
  if (timer) clearTimeout(timer);
@@ -145520,7 +145801,8 @@ function makeRouter(deps) {
145520
145801
  instruction: text,
145521
145802
  reply: replySink,
145522
145803
  autoReplyOnText: true,
145523
- replyExpected: opts?.replyExpected
145804
+ replyExpected: opts?.replyExpected,
145805
+ ...opts?.conversation ? { conversation: opts.conversation } : {}
145524
145806
  });
145525
145807
  return false;
145526
145808
  }
@@ -145531,7 +145813,8 @@ function makeRouter(deps) {
145531
145813
  autoReplyOnText: false,
145532
145814
  replyExpected: opts?.replyExpected,
145533
145815
  toolEligibleSender: opts.toolEligibleSender,
145534
- armed: opts.armed
145816
+ armed: opts.armed,
145817
+ ...opts?.conversation ? { conversation: opts.conversation } : {}
145535
145818
  });
145536
145819
  return false;
145537
145820
  }
@@ -146180,7 +146463,8 @@ ${FILE_LOCK_NOTE}` : turnText, target.snapshotReply(channel, log), {
146180
146463
  replyExpected: owes,
146181
146464
  toolEligibleSender: e7.senderIsAgent === false && e7.senderIsOwner === true && e7.foreignContent === false,
146182
146465
  armed: () => arming.isArmed(e7.roomId),
146183
- ...contextBlock ? { roomContext: contextBlock } : {}
146466
+ ...contextBlock ? { roomContext: contextBlock } : {},
146467
+ conversation: { kind: "room", id: e7.roomId }
146184
146468
  });
146185
146469
  if (delivered !== false) {
146186
146470
  if (held.entries.length > 0) {
@@ -146202,7 +146486,10 @@ ${FILE_LOCK_NOTE}` : turnText, target.snapshotReply(channel, log), {
146202
146486
  log("inbound 1:1 DM from owner");
146203
146487
  }
146204
146488
  target.setDm(metadata?.conversationId, metadata?.conversationGroupId);
146205
- session.push(text, target.snapshotReply(channel, log), { autoReplyOnText: ownerAttested });
146489
+ session.push(text, target.snapshotReply(channel, log), {
146490
+ autoReplyOnText: ownerAttested,
146491
+ conversation: metadata?.conversationId ? { kind: "direct", id: metadata.conversationId } : { kind: "direct" }
146492
+ });
146206
146493
  });
146207
146494
  const workerCapable = !!opts.workspaceDir;
146208
146495
  const osIsolated = opts.osIsolated !== void 0 ? opts.osIsolated : process.env.AV_WORKER_OS_ISOLATED === "1" || process.env.AV_WORKER_OS_ISOLATED === "true";
@@ -146389,7 +146676,7 @@ function answerInfoFlags(argv, version3, print) {
146389
146676
 
146390
146677
  // src/index.ts
146391
146678
  async function main() {
146392
- if (answerInfoFlags(process.argv, true ? "0.8.35" : void 0, printLine)) {
146679
+ if (answerInfoFlags(process.argv, true ? "0.8.36" : void 0, printLine)) {
146393
146680
  process.exit(0);
146394
146681
  }
146395
146682
  if (process.argv[2] === "recovery" && await (await init_recovery().then(() => recovery_exports)).maybeRunRecoverySubcommand()) {
@@ -146417,7 +146704,7 @@ async function main() {
146417
146704
  "[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"
146418
146705
  );
146419
146706
  }
146420
- logLine(`[bridge] version: ${true ? "0.8.35" : "dev"}`);
146707
+ logLine(`[bridge] version: ${true ? "0.8.36" : "dev"}`);
146421
146708
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
146422
146709
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
146423
146710
  if (cfg.armRoom) {
@@ -146449,7 +146736,7 @@ async function main() {
146449
146736
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
146450
146737
  // package name attached to the bridge's version number, which is worse
146451
146738
  // than either alone.
146452
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.35" : "dev"}`
146739
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.36" : "dev"}`
146453
146740
  });
146454
146741
  const agentSystemPrompt = cfg.systemPrompt ?? identityPrompt(cfg.agentName);
146455
146742
  const deviceJwt = () => {
@@ -146478,10 +146765,15 @@ async function main() {
146478
146765
  reportPlanLimit(channel, resetsAt);
146479
146766
  logLine(`[bridge] Claude plan limit reached${resetsAt ? ` (resets at epoch ${resetsAt})` : ""}`);
146480
146767
  };
146768
+ const failure3 = {
146769
+ agentName: () => channel.ownDisplayName?.trim() || cfg.agentName,
146770
+ telemetry: () => channel.telemetry ?? null
146771
+ };
146481
146772
  const listener = new PersistentClaudeSession({
146482
146773
  model: cfg.model,
146483
146774
  onUsage: reportUsage,
146484
146775
  onPlanLimit,
146776
+ failure: failure3,
146485
146777
  systemPrompt: agentSystemPrompt,
146486
146778
  // Claude speaks by calling the say tool → the session routes it to the reply
146487
146779
  // bound to the message being answered (wireBridge captures that per inbound via
@@ -146500,6 +146792,7 @@ async function main() {
146500
146792
  systemPrompt: agentSystemPrompt,
146501
146793
  onUsage: reportUsage,
146502
146794
  onPlanLimit,
146795
+ failure: failure3,
146503
146796
  onObserve: (text) => logLine(`[worker] observed (${text.length} chars, not sent)`),
146504
146797
  worker: true,
146505
146798
  // Task 4: the hard backstop — no tool runs on any worker turn (owner DM or
@@ -146524,6 +146817,7 @@ async function main() {
146524
146817
  }),
146525
146818
  timeoutMs: WORKER_TIMEOUT_MS,
146526
146819
  log: (m6) => logLine(m6),
146820
+ failure: failure3,
146527
146821
  // TRAP (2026-07-25). The 07-24 five-minute silence was diagnosable only by
146528
146822
  // luck — the drop-trap happened to record a reply landing 300.016s after the
146529
146823
  // ack, and 300s is WORKER_TIMEOUT_MS exactly. Nothing recorded WHY the worker
@@ -146583,10 +146877,14 @@ async function main() {
146583
146877
  "room_joined",
146584
146878
  (e7) => logLine(`[bridge] joined room ${e7.name} (${e7.roomId})`)
146585
146879
  );
146586
- listener.start().catch((err) => {
146587
- logLine("[bridge] fatal:", err);
146588
- process.exit(1);
146589
- });
146880
+ listener.start().catch(
146881
+ (err) => stopAfterListenerFailure(err, {
146882
+ session: listener,
146883
+ flush: () => channel.telemetry?.flush?.(),
146884
+ log: (m6) => logLine(m6),
146885
+ exit: (code) => process.exit(code)
146886
+ })
146887
+ );
146590
146888
  await channel.start();
146591
146889
  }
146592
146890
  main().catch((err) => {
package/dist/router.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ToolConversation } from "@agentvault/agentvault";
1
2
  import type { ReplySink } from "./session.js";
2
3
  import type { WorkerTask } from "./worker-queue.js";
3
4
  /** The push interface wireBridge drives (matches PersistentClaudeSession.push). */
@@ -9,6 +10,8 @@ export interface PushLike {
9
10
  armed?: () => boolean;
10
11
  /** Held "earlier in this room" block — see room-context.ts. */
11
12
  roomContext?: string;
13
+ /** #1560: the conversation this message came from. */
14
+ conversation?: ToolConversation;
12
15
  }): unknown;
13
16
  }
14
17
  export interface RouterDeps {
package/dist/session.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { type LlmUsage } from "./usage-report.js";
3
+ import type { ToolConversation, TurnFailureCode } from "@agentvault/agentvault";
4
+ import { type FailureDeps } from "./turn-failure.js";
3
5
  /**
4
6
  * The one tool the room session exposes: `room_say`. Speaking to the room is an
5
7
  * explicit choice — Claude calls this only when it has something to add, and
@@ -115,6 +117,13 @@ export interface SessionOpts {
115
117
  onPlanLimit?: (info: {
116
118
  resetsAt?: number;
117
119
  }) => void;
120
+ /**
121
+ * #1560: a failed turn is recorded (one `model_turn` span, one coded log
122
+ * line) and, when the turn owed a reply, answered with the owner notice.
123
+ * Absent: the failure is still logged by code and the bare notice is still
124
+ * posted, with no span.
125
+ */
126
+ failure?: FailureDeps;
118
127
  }
119
128
  export declare class PersistentClaudeSession {
120
129
  private opts;
@@ -144,6 +153,13 @@ export declare class PersistentClaudeSession {
144
153
  private roomServer;
145
154
  /** AbortController for the in-flight query(); abort() triggers it (queue timeout). */
146
155
  private _abort?;
156
+ /** #1560: every failure notice still being sent, so a worker's start()
157
+ * settles only after its notice did (the queue then moves on). */
158
+ private notices;
159
+ /** #1560: the code of the first failed turn this session recorded. */
160
+ private firstFailure?;
161
+ /** Review X1: set by abort(); the aborter owns the failure report from then on. */
162
+ private aborted;
147
163
  constructor(opts: SessionOpts);
148
164
  /**
149
165
  * Queue an inbound message for the model.
@@ -166,6 +182,8 @@ export declare class PersistentClaudeSession {
166
182
  toolEligibleSender?: boolean;
167
183
  armed?: () => boolean;
168
184
  roomContext?: string;
185
+ /** #1560: the conversation this message came from (span + notice wording). */
186
+ conversation?: ToolConversation;
169
187
  }): void;
170
188
  /** Route a say-tool message to the reply bound to the in-flight message, falling
171
189
  * back to opts.onSay. This is what closes the DM→room leak: the destination is
@@ -208,11 +226,31 @@ export declare class PersistentClaudeSession {
208
226
  */
209
227
  private buildSdkOptions;
210
228
  start(): Promise<void>;
229
+ /**
230
+ * #1560: the code of the first turn this session recorded as failed, or
231
+ * undefined. The worker queue reads it so a failure the session already
232
+ * reported (span, log, notice) is never reported a second time when the
233
+ * SDK then throws.
234
+ */
235
+ failureCode(): TurnFailureCode | undefined;
236
+ /**
237
+ * #1560: record one failed turn (once) and, if it owed a reply, start its
238
+ * notice. The record is synchronous; the notice is tracked in `notices`.
239
+ */
240
+ private failTurn;
241
+ /**
242
+ * #1560: the query() stopped with turns still unanswered (the listener's
243
+ * fatal path). Each one is recorded and, where owed, told — a message
244
+ * already handed to the model and one still waiting alike. Resolves once
245
+ * every notice has settled. Never throws.
246
+ */
247
+ failOpenTurns(err: unknown): Promise<void>;
211
248
  /**
212
249
  * #1467: at a turn's result, report it when Claude refused it with a rate
213
250
  * limit WHILE the plan's status is rejected. A refusal with the plan allowed
214
251
  * 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.
252
+ * refusal (extra usage, model fallback) was served. Never throws. Returns
253
+ * whether it was the plan's limit (#1560: that span is the turn's one span).
216
254
  */
217
255
  private reportPlanLimitIfAny;
218
256
  }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * #1560 slice 2 — a Claude turn that fails is shown to the owner, never
3
+ * swallowed, and never repeats the provider's words.
4
+ *
5
+ * The codes, the owner sentences and the span all come from the plugin's
6
+ * shared table (`packages/plugin/src/turn-failure.ts`), unchanged. This file
7
+ * only decides WHICH code a Claude Code failure is, and runs the one failure
8
+ * path both lanes use: record the span, log the code, then post the notice.
9
+ *
10
+ * What Claude Code tells us about a failed turn (SDK 0.2.141):
11
+ * - the made-up `assistant` message carries `error`, a closed enum
12
+ * (SDKAssistantMessageError). Its text block is the PROVIDER'S message,
13
+ * e.g. "Failed to authenticate. API Error: 401 OAuth access token has
14
+ * expired…". That text is never sent, logged or put in a span;
15
+ * - the `result` carries `is_error: true` and `api_error_status`;
16
+ * - `system/api_retry` carries `error_status: null` for a connection error
17
+ * with no HTTP response (the SDK's own type doc says so);
18
+ * - with no result at all, the SDK throws its own fixed messages for a
19
+ * missing or unspawnable CLI, and "Claude Code process exited with code N".
20
+ *
21
+ * Only those structured signals and the SDK's own fixed messages are read.
22
+ * The thrown "Claude Code returned an error result: <text>" carries provider
23
+ * text and is never matched for a code.
24
+ */
25
+ import { type ToolConversation, type ToolSpanSink, type TurnFailureCode } from "@agentvault/agentvault";
26
+ /** The provider named in a 1:1 notice. Claude Code signs in to Anthropic. */
27
+ export declare const PROVIDER = "Anthropic";
28
+ /** What the session saw on a failed turn. All fields optional; absent is absent. */
29
+ export interface ClaudeFailureSignal {
30
+ /** The made-up assistant message's `error` (SDKAssistantMessageError). */
31
+ assistantError?: unknown;
32
+ /** The result's `api_error_status`. */
33
+ apiErrorStatus?: unknown;
34
+ /** The turn saw `system/api_retry` with `error_status: null` (no HTTP response). */
35
+ connectionRetry?: boolean;
36
+ /** #1467: this refusal was the plan's own limit (already reported as its own span). */
37
+ planLimit?: boolean;
38
+ /** The result's `subtype` (e.g. "error_max_turns"). */
39
+ subtype?: unknown;
40
+ }
41
+ /**
42
+ * The code for a turn Claude Code reported as failed.
43
+ *
44
+ * Every branch is a literal `return "<code>"` on purpose: the plugin's
45
+ * tool-error-codes.test.ts scans this file for `return "<code>"` and checks
46
+ * each against KNOWN_TOOL_ERROR_CODES. A lookup table, ternary or variable
47
+ * would hide a code from that scan, so do not refactor this into one.
48
+ *
49
+ * The enum wins over the status: it is Claude Code's own reading of the
50
+ * response. The statuses follow the Anthropic API's documented error codes
51
+ * (401 authentication, 402 billing, 403 permission, 404 not found, 429 rate
52
+ * limit, 5xx/529 server or overloaded).
53
+ *
54
+ * `oauth_org_not_allowed` ("Your organization has disabled Claude
55
+ * subscription access for Claude Code", observed on loopita 09-25 and 10-02)
56
+ * is a SIGN-IN problem, not billing: the fix is to sign Claude Code in with an
57
+ * account or API key that is allowed. The billing sentence would send the
58
+ * owner to pay, which would not fix it.
59
+ */
60
+ export declare function classifyClaudeFailure(s: ClaudeFailureSignal): TurnFailureCode;
61
+ /**
62
+ * The code for a turn that ended in a THROW with no failed result to read
63
+ * (a missing CLI, a crash, a spawn error). Read in memory only; the message
64
+ * is never kept, logged or returned.
65
+ */
66
+ export declare function classifyClaudeThrow(err: unknown): TurnFailureCode;
67
+ /** The CLI's exit status when the SDK names one, else undefined. */
68
+ export declare function exitCodeOf(err: unknown): number | undefined;
69
+ /** What the failure path needs from the bridge. Every field optional (tests, legacy callers). */
70
+ export interface FailureDeps {
71
+ /** The name the owner knows this agent by (hub display name, else config). */
72
+ agentName?: () => string | undefined;
73
+ /** SecureChannel's TelemetryReporter. */
74
+ telemetry?: () => ToolSpanSink | null | undefined;
75
+ }
76
+ export interface FailedTurn {
77
+ code: TurnFailureCode;
78
+ exitCode?: number;
79
+ /** Only `"timeout"` today: the queue gave up on the turn. */
80
+ reason?: "timeout";
81
+ conversation?: ToolConversation;
82
+ durationMs: number;
83
+ /** The span is already recorded (#1467's plan-limit span). Exactly one per turn. */
84
+ spanRecorded?: boolean;
85
+ /** Where this turn's reply goes. */
86
+ reply?: (text: string) => void | Promise<void>;
87
+ /** Did this turn owe a reply? A room turn nobody addressed stays silent (#1107). */
88
+ owed: boolean;
89
+ /** The agent already said something this turn (re-review N1): the notice is
90
+ * then the BARE sentence. A partial "On it." must never be the last word. */
91
+ spoke?: boolean;
92
+ }
93
+ /**
94
+ * The one failure path. RECORD FIRST — the span and the log line, both
95
+ * synchronously — then post the notice, so a notice that stalls or fails
96
+ * cannot lose the record. Only the code and the exit status are logged.
97
+ *
98
+ * The notice names the cause only in a 1:1. Anywhere else (a room, or a turn
99
+ * whose conversation is unknown) it is the bare sentence: the coded ones
100
+ * describe the owner's own provider account. Never throws.
101
+ */
102
+ export declare function reportTurnFailed(deps: FailureDeps | undefined, t: FailedTurn, log: (m: string) => void): Promise<void>;
103
+ /**
104
+ * Review F1: the WHOLE fatal sequence (tell owed turns, then flush) is capped.
105
+ * A notice send that never settles (e.g. a stuck MLS catch-up) must not keep a
106
+ * deaf process alive: the supervisor can only restart a process that exits.
107
+ */
108
+ export declare const FATAL_DEADLINE_MS = 15000;
109
+ /** Resolves when `p` settles or after `ms`, whichever comes first. Never rejects. */
110
+ export declare function settleWithin(p: Promise<unknown>, ms: number): Promise<void>;
111
+ /**
112
+ * The always-on listener's query() rejected. Tell every owed turn it had not
113
+ * answered, flush telemetry so those spans are not lost with the process,
114
+ * then log the code (never the error text) and exit so the supervisor
115
+ * restarts the bridge. Never throws before `exit`, and always reaches it
116
+ * within `deadlineMs`.
117
+ */
118
+ export declare function stopAfterListenerFailure(err: unknown, deps: {
119
+ session: {
120
+ failOpenTurns(err: unknown): Promise<void>;
121
+ };
122
+ flush?: () => unknown;
123
+ log: (m: string) => void;
124
+ exit: (code: number) => void;
125
+ flushTimeoutMs?: number;
126
+ deadlineMs?: number;
127
+ }): Promise<void>;
128
+ //# sourceMappingURL=turn-failure.d.ts.map
@@ -1,4 +1,6 @@
1
+ import type { ToolConversation, TurnFailureCode } from "@agentvault/agentvault";
1
2
  import type { PersistentClaudeSession, ReplySink } from "./session.js";
3
+ import { type FailureDeps } from "./turn-failure.js";
2
4
  /** One tool-eligible turn to run in an isolated ephemeral worker. */
3
5
  export type WorkerTask = {
4
6
  /** The single instruction that seeds the worker's conversation. */
@@ -15,6 +17,8 @@ export type WorkerTask = {
15
17
  /** Armed-room turns: live getter the gate reads per tool decision (mid-turn
16
18
  * disarm denies the next call). Absent for owner DMs. */
17
19
  armed?: () => boolean;
20
+ /** #1560: the conversation this task answers (span + notice wording). */
21
+ conversation?: ToolConversation;
18
22
  };
19
23
  /**
20
24
  * Forensic record of EVERY task the queue runs — clean or not.
@@ -36,8 +40,13 @@ export type WorkerIncident = {
36
40
  /** ISO timestamp — the bridge's own logs are unstamped, so this is the anchor. */
37
41
  at: string;
38
42
  outcome: "ok" | "timeout" | "error";
39
- /** Absent on a clean turn — its presence is what marks a real incident. */
40
- error?: string;
43
+ /**
44
+ * #1560: the failure's code. Absent on a clean turn — its presence is what
45
+ * marks a real incident. Replaces the old `error` (the raw error message),
46
+ * which wrote the provider's text — "…OAuth access token has expired…" — to
47
+ * this file on every failed turn.
48
+ */
49
+ code?: TurnFailureCode;
41
50
  /**
42
51
  * enqueue -> start. THE load-bearing field: it separates "this task hung" from
43
52
  * "this task was stuck behind one that hung". Both look identical to the owner
@@ -102,13 +111,16 @@ export interface WorkerQueueDeps {
102
111
  * no trap.
103
112
  */
104
113
  onIncident?: (rec: WorkerIncident) => void;
114
+ /** #1560: span sink + agent name for the failure notice. */
115
+ failure?: FailureDeps;
105
116
  }
106
117
  /**
107
118
  * Serial FIFO of tool-eligible turns. One worker runs at a time (concurrent tool
108
119
  * calls against one device/workspace can interleave destructively; the owner is a
109
120
  * single actor). Each task runs in a fresh ephemeral worker seeded with only its
110
- * instruction; on error or timeout the worker is torn down, a generic message is
111
- * sent to the task's reply, and the queue advances.
121
+ * instruction; on error or timeout the worker is torn down, the failure is
122
+ * recorded by code and the owner notice is sent to the task's reply (#1560),
123
+ * and the queue advances.
112
124
  *
113
125
  * ⚠️ A task cannot wedge the queue PERMANENTLY, but it absolutely can wedge it for
114
126
  * up to `timeoutMs`. Serial + a 5-minute cap means ONE hung worker delays every
@@ -138,6 +150,8 @@ export declare class WorkerQueue {
138
150
  * indistinguishable from a turn that did nothing.
139
151
  */
140
152
  private snapshotOf;
153
+ /** The failure the session itself already recorded, if any. */
154
+ private failureOf;
141
155
  /** Best-effort trap emit. A broken sink must never break the queue. */
142
156
  private emitIncident;
143
157
  private runOne;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.8.35",
3
+ "version": "0.8.36",
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",