@agentvault/openai-bridge 0.1.12 → 0.1.14

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/index.js CHANGED
@@ -22,6 +22,8 @@ __export(dist_exports, {
22
22
  PolicyEnforcer: () => PolicyEnforcer,
23
23
  SecureChannel: () => SecureChannel,
24
24
  TOOL_INVOKE_SPAN_NAME: () => TOOL_INVOKE_SPAN_NAME,
25
+ TURN_FAILURE_CODES: () => TURN_FAILURE_CODES,
26
+ TurnFailure: () => TurnFailure,
25
27
  VERSION: () => VERSION,
26
28
  agentVaultPlugin: () => agentVaultPlugin,
27
29
  buildToolInvokeSpan: () => buildToolInvokeSpan,
@@ -42,6 +44,7 @@ __export(dist_exports, {
42
44
  handleTargetsRequest: () => handleTargetsRequest,
43
45
  historyRecoveryCodePath: () => historyRecoveryCodePath,
44
46
  invokeSkill: () => invokeSkill,
47
+ isOwnerNotice: () => isOwnerNotice,
45
48
  isUsingManagedRoutes: () => managedRoutesRequested,
46
49
  listAccountIds: () => listAccountIds,
47
50
  listTargets: () => listTargets,
@@ -52,10 +55,12 @@ __export(dist_exports, {
52
55
  mergeSkills: () => mergeSkills,
53
56
  offerHistoryRecoveryConfiguration: () => offerHistoryRecoveryConfiguration,
54
57
  owesRoomReply: () => owesRoomReply,
58
+ ownerNoticeFor: () => ownerNoticeFor,
55
59
  parseMentions: () => parseMentions,
56
60
  parseSkillMd: () => parseSkillMd,
57
61
  parseTarget: () => parseTarget,
58
62
  readMaskedHistoryRecoveryCode: () => readMaskedHistoryRecoveryCode,
63
+ reportModelTurnFailure: () => reportModelTurnFailure,
59
64
  reportSkillInvocation: () => reportSkillInvocation,
60
65
  reportToolInvoke: () => reportToolInvoke,
61
66
  requestHeartbeatNow: () => requestHeartbeatNow,
@@ -176,6 +181,9 @@ function resolveOwn(mention, names) {
176
181
  }
177
182
  function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true) {
178
183
  const mentions = parseMentions(plaintext);
184
+ if (senderIsAgent === false && namesAgentPlainly(plaintext, agentName, roomDisplayName, ownDisplayName)) {
185
+ return true;
186
+ }
179
187
  if (mentions.length === 0) return false;
180
188
  const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
181
189
  if (mentions.some((m2) => resolveOwn(m2, ownNames) !== null)) return true;
@@ -199,6 +207,21 @@ function ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName) {
199
207
  add4(ownDisplayName);
200
208
  return names;
201
209
  }
210
+ function namesAgentPlainly(text, agentName, roomDisplayName, ownDisplayName) {
211
+ const names = /* @__PURE__ */ new Set();
212
+ for (const n2 of [agentName, roomDisplayName, ownDisplayName]) {
213
+ if (!n2) continue;
214
+ const lower = n2.toLowerCase().trim();
215
+ for (const candidate of [lower, lower.split(/[\s(]/)[0]]) {
216
+ if (candidate.length >= 3 && !GENERIC_AGENT_NAMES.has(candidate)) names.add(candidate);
217
+ }
218
+ }
219
+ for (const name of names) {
220
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
221
+ if (new RegExp(`(?<![\\p{L}\\p{N}_@-])${escaped}(?![\\p{L}\\p{N}_-])`, "iu").test(text)) return true;
222
+ }
223
+ return false;
224
+ }
202
225
  function stripMentions(text, agentName, accountId, roomDisplayName, ownDisplayName) {
203
226
  const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
204
227
  return text.replace(new RegExp(MENTION_RE.source, MENTION_RE.flags), (full, name) => {
@@ -4135,8 +4158,8 @@ async function generateBackupCode() {
4135
4158
  return code;
4136
4159
  }
4137
4160
  function formatBackupCode(code) {
4138
- const clean5 = code.replace(/[-\s]/g, "").toUpperCase();
4139
- return clean5.match(/.{1,4}/g)?.join("-") ?? clean5;
4161
+ const clean6 = code.replace(/[-\s]/g, "").toUpperCase();
4162
+ return clean6.match(/.{1,4}/g)?.join("-") ?? clean6;
4140
4163
  }
4141
4164
  function normalizeBackupCode(input) {
4142
4165
  return input.replace(/[-\s]/g, "").toUpperCase();
@@ -11812,11 +11835,11 @@ async function joinWithFirstMatchingKp(welcomeBytes, candidates) {
11812
11835
  return null;
11813
11836
  }
11814
11837
  function ownIdentity() {
11815
- const v2 = true ? "0.23.63" : FALLBACK;
11838
+ const v2 = true ? "0.23.64" : FALLBACK;
11816
11839
  return `${PACKAGE}@${v2}`;
11817
11840
  }
11818
11841
  function buildSha() {
11819
- const raw = true ? "52249f2" : "";
11842
+ const raw = true ? "0e95fe8" : "";
11820
11843
  const cleaned = (raw ?? "").trim();
11821
11844
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11822
11845
  }
@@ -18509,7 +18532,55 @@ function reportSkillInvocation(opts) {
18509
18532
  spanBuffer.push(span);
18510
18533
  return span;
18511
18534
  }
18512
- 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, 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_exports2, 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, 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, VERSION, init_index;
18535
+ function asTurnFailureCode(code) {
18536
+ return typeof code === "string" && CODES.has(code) ? code : "model_error";
18537
+ }
18538
+ function clean5(value, max) {
18539
+ if (typeof value !== "string") return "";
18540
+ return value.replace(/@/g, "").replace(/\s+/g, " ").trim().slice(0, max).trim();
18541
+ }
18542
+ function ownerNoticeFor(code, ctx) {
18543
+ const a2 = clean5(ctx?.agentName, 80) || "Your agent";
18544
+ const p2 = clean5(ctx?.provider, 40) || "AI provider";
18545
+ const head = `${a2} couldn't answer this message`;
18546
+ switch (asTurnFailureCode(code)) {
18547
+ case "provider_auth_failed":
18548
+ return `${head}: its ${p2} sign-in expired. Sign in again on the agent's computer.`;
18549
+ case "provider_billing":
18550
+ return `${head}: its ${p2} account is out of credit or has a billing problem.`;
18551
+ case "model_rate_limited":
18552
+ return `${head}: it is being rate-limited by ${p2}. Try again in a few minutes.`;
18553
+ case "model_unavailable":
18554
+ return `${head}: the model it is set to use is no longer available.`;
18555
+ case "provider_unreachable":
18556
+ return `${head}: it can't reach ${p2} right now.`;
18557
+ case "ai_tool_unsupported":
18558
+ return `${head}: its AI tool needs attention on its computer.`;
18559
+ case "plan_limit_reached":
18560
+ return `${head}: it has reached its ${p2} plan's usage limit.`;
18561
+ default:
18562
+ return `${head}.`;
18563
+ }
18564
+ }
18565
+ function isOwnerNotice(text) {
18566
+ return typeof text === "string" && NOTICE_RE.test(text);
18567
+ }
18568
+ function reportModelTurnFailure(sink, report) {
18569
+ try {
18570
+ const code = asTurnFailureCode(report.code);
18571
+ const isPlan = code === "plan_limit_reached";
18572
+ reportToolInvoke(sink, {
18573
+ toolName: "model_turn",
18574
+ outcome: "error",
18575
+ errorKind: code,
18576
+ durationMs: report.durationMs,
18577
+ conversation: isPlan ? { kind: "unknown" } : report.conversation,
18578
+ ...isPlan && report.limitResetsAt !== void 0 ? { limitResetsAt: report.limitResetsAt } : {}
18579
+ });
18580
+ } catch {
18581
+ }
18582
+ }
18583
+ 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, 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_exports2, 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, 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;
18513
18584
  var init_dist = __esm({
18514
18585
  async "../plugin/dist/index.js"() {
18515
18586
  "use strict";
@@ -18583,6 +18654,7 @@ var init_dist = __esm({
18583
18654
  "use strict";
18584
18655
  MENTION_RE = /@([\w-]+)/gi;
18585
18656
  BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
18657
+ GENERIC_AGENT_NAMES = /* @__PURE__ */ new Set(["default", "agent", "assistant", "bot", "main"]);
18586
18658
  }
18587
18659
  });
18588
18660
  init_libsodium_sumo = __esm2({
@@ -71510,6 +71582,12 @@ var init_dist = __esm({
71510
71582
  // #1467: a Muse turn failed — Meta answered 429, or anything else.
71511
71583
  "model_rate_limited",
71512
71584
  "model_error",
71585
+ // #1560: a failed model turn named for the owner (turn-failure.ts). Never send codes.
71586
+ "provider_auth_failed",
71587
+ "provider_billing",
71588
+ "model_unavailable",
71589
+ "provider_unreachable",
71590
+ "ai_tool_unsupported",
71513
71591
  UNCLASSIFIED_ERROR
71514
71592
  ];
71515
71593
  KNOWN_CODES = new Set(KNOWN_TOOL_ERROR_CODES);
@@ -73477,6 +73555,33 @@ ${text}`,
73477
73555
  const tag = `room:${roomId}`;
73478
73556
  return history.filter((e) => e.topicId === tag).slice(-maxMessages);
73479
73557
  }
73558
+ /**
73559
+ * #1560 — recent history of one person's 1:1 chat, for LLM context
73560
+ * injection by a bridge. Scoped by the group the inbound frame DECRYPTED
73561
+ * under (`opts.groupId`, #1416/#1418): never another person's entries, and
73562
+ * never a room's or an A2A channel's. Time-ordered, last `maxMessages`
73563
+ * (capped at 100). Synchronous and pure: no new storage, no network.
73564
+ */
73565
+ getConversationHistory(conversationId, maxMessages = 20, opts = {}) {
73566
+ if (!(maxMessages > 0)) return [];
73567
+ if (this._knownDmGroups().size === 0) return [];
73568
+ if (opts.groupId) {
73569
+ const convs = this._conversationsOfGroup(opts.groupId);
73570
+ if (convs.length > 0 && !convs.includes(conversationId)) return [];
73571
+ }
73572
+ return this._historyForCatchup("dm", void 0, void 0, {
73573
+ groupId: opts.groupId,
73574
+ conversationId
73575
+ }).slice(-Math.min(maxMessages, 100));
73576
+ }
73577
+ /** Every conversation mapped to `groupId` (one per browser of its person). */
73578
+ _conversationsOfGroup(groupId) {
73579
+ const out = [];
73580
+ for (const [convId, gid] of this._sessionGroupIds) {
73581
+ if (gid === groupId) out.push(convId);
73582
+ }
73583
+ return out;
73584
+ }
73480
73585
  /**
73481
73586
  * Encrypt and send a message to ALL owner devices (fanout).
73482
73587
  * Each session gets the same plaintext encrypted independently.
@@ -73954,7 +74059,7 @@ ${text}`,
73954
74059
  */
73955
74060
  sendActivitySpan(spanData) {
73956
74061
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
73957
- const pluginVersion = true ? "0.23.63" : "0.0.0-dev";
74062
+ const pluginVersion = true ? "0.23.64" : "0.0.0-dev";
73958
74063
  const agentName = this.config.agentName ?? "Agent";
73959
74064
  const resource = {
73960
74065
  "service.name": "agentvault-agent",
@@ -76165,7 +76270,7 @@ ${text}`,
76165
76270
  agentVersion: this.config.agentVersion ?? "0.0.0",
76166
76271
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
76167
76272
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
76168
- pluginVersion: true ? "0.23.63" : "0.0.0-dev"
76273
+ pluginVersion: true ? "0.23.64" : "0.0.0-dev"
76169
76274
  });
76170
76275
  this._telemetryReporter.startAutoFlush(3e4);
76171
76276
  }
@@ -76498,7 +76603,7 @@ ${text}`,
76498
76603
  agentVersion: this.config.agentVersion ?? "0.0.0",
76499
76604
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
76500
76605
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
76501
- pluginVersion: true ? "0.23.63" : "0.0.0-dev"
76606
+ pluginVersion: true ? "0.23.64" : "0.0.0-dev"
76502
76607
  });
76503
76608
  this._telemetryReporter.startAutoFlush(3e4);
76504
76609
  }
@@ -103062,6 +103167,34 @@ data:
103062
103167
  };
103063
103168
  }
103064
103169
  });
103170
+ init_turn_failure = __esm2({
103171
+ "src/turn-failure.ts"() {
103172
+ "use strict";
103173
+ init_tool_telemetry();
103174
+ TURN_FAILURE_CODES = [
103175
+ "provider_auth_failed",
103176
+ "provider_billing",
103177
+ "model_rate_limited",
103178
+ "model_unavailable",
103179
+ "provider_unreachable",
103180
+ "ai_tool_unsupported",
103181
+ "plan_limit_reached",
103182
+ "model_error"
103183
+ ];
103184
+ CODES = new Set(TURN_FAILURE_CODES);
103185
+ TurnFailure = class extends Error {
103186
+ code;
103187
+ exitCode;
103188
+ constructor(code, opts = {}, message = "Codex turn failed") {
103189
+ super(message);
103190
+ this.name = "TurnFailure";
103191
+ this.code = asTurnFailureCode(code);
103192
+ if (opts.exitCode !== void 0) this.exitCode = opts.exitCode;
103193
+ }
103194
+ };
103195
+ NOTICE_RE = /^[^\n@]{1,120} couldn't answer this message(?:\.|: [^\n]{1,200})$/;
103196
+ }
103197
+ });
103065
103198
  init_index = __esm2({
103066
103199
  async "src/index.ts"() {
103067
103200
  await init_channel();
@@ -103082,7 +103215,8 @@ data:
103082
103215
  await init_policy_enforcer();
103083
103216
  init_room_protocol();
103084
103217
  init_tool_telemetry();
103085
- VERSION = true ? "0.23.63" : "0.0.0-dev";
103218
+ init_turn_failure();
103219
+ VERSION = true ? "0.23.64" : "0.0.0-dev";
103086
103220
  }
103087
103221
  });
103088
103222
  await init_index();
@@ -103096,18 +103230,32 @@ import { join as join8 } from "node:path";
103096
103230
  async function findRollout(layout, id) {
103097
103231
  let visited = 0;
103098
103232
  const matches = [];
103233
+ let unwalked = false;
103234
+ const root3 = join8(layout.codex, "sessions");
103099
103235
  async function walk(directory, depth) {
103100
- const handle = await opendir(directory);
103236
+ let handle;
103237
+ try {
103238
+ handle = await opendir(directory);
103239
+ } catch (error2) {
103240
+ if (depth === 0 && error2.code === "ENOENT")
103241
+ throw new RolloutMissing();
103242
+ throw error2;
103243
+ }
103101
103244
  for await (const entry of handle) {
103102
103245
  if (++visited > 4096 || entry.isSymbolicLink())
103103
103246
  throw invalid();
103104
- if (entry.isDirectory() && depth < 3)
103105
- await walk(join8(directory, entry.name), depth + 1);
103106
- else if (entry.isFile() && entry.name.endsWith(`-${id}.jsonl`))
103247
+ if (entry.isDirectory()) {
103248
+ if (depth < 3)
103249
+ await walk(join8(directory, entry.name), depth + 1);
103250
+ else
103251
+ unwalked = true;
103252
+ } else if (entry.isFile() && entry.name.endsWith(`-${id}.jsonl`))
103107
103253
  matches.push(join8(directory, entry.name));
103108
103254
  }
103109
103255
  }
103110
- await walk(join8(layout.codex, "sessions"), 0);
103256
+ await walk(root3, 0);
103257
+ if (matches.length === 0)
103258
+ throw unwalked ? invalid() : new RolloutMissing();
103111
103259
  if (matches.length !== 1)
103112
103260
  throw invalid();
103113
103261
  return matches[0];
@@ -103188,19 +103336,26 @@ async function verifyFinalReply(layout, id, stdoutText, before) {
103188
103336
  throw invalid();
103189
103337
  }
103190
103338
  }
103191
- var UUID, invalid;
103339
+ var UUID, INVALID2, invalid, RolloutMissing;
103192
103340
  var init_rollout = __esm({
103193
103341
  "src/rollout.ts"() {
103194
103342
  "use strict";
103195
103343
  UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
103196
- invalid = () => new Error("Codex final reply could not be verified");
103344
+ INVALID2 = "Codex final reply could not be verified";
103345
+ invalid = () => new Error(INVALID2);
103346
+ RolloutMissing = class extends Error {
103347
+ constructor() {
103348
+ super(INVALID2);
103349
+ this.name = "RolloutMissing";
103350
+ }
103351
+ };
103197
103352
  }
103198
103353
  });
103199
103354
 
103200
103355
  // src/driver.ts
103201
103356
  import { spawn, execFile } from "node:child_process";
103202
103357
  import { constants as constants4 } from "node:fs";
103203
- import { mkdir as mkdir5, chmod as chmod3, readFile as readFile6, writeFile as writeFile4, rename as rename5, access, realpath } from "node:fs/promises";
103358
+ import { mkdir as mkdir5, chmod as chmod3, readFile as readFile6, writeFile as writeFile4, rename as rename5, access, realpath, link, unlink as unlink2 } from "node:fs/promises";
103204
103359
  import { createHash as createHash2, randomUUID as randomUUID5 } from "node:crypto";
103205
103360
  import { join as join9, isAbsolute } from "node:path";
103206
103361
  import { StringDecoder } from "node:string_decoder";
@@ -103224,7 +103379,7 @@ function childEnvironment(layout) {
103224
103379
  }
103225
103380
  function buildInvocation(layout, sessionId) {
103226
103381
  if (sessionId && !UUID2.test(sessionId))
103227
- throw new Error("Invalid stored Codex session");
103382
+ throw new TurnFailure("model_error", {}, "Invalid stored Codex session");
103228
103383
  const args = [
103229
103384
  "exec",
103230
103385
  "--json",
@@ -103267,16 +103422,65 @@ async function resolveCodex(path2 = process.env.PATH ?? "") {
103267
103422
  } catch {
103268
103423
  }
103269
103424
  }
103270
- throw new Error(`Install Codex CLI ${SUPPORTED_CODEX_VERSION} and put codex on PATH`);
103425
+ throw new TurnFailure("ai_tool_unsupported", {}, `Install Codex CLI ${SUPPORTED_CODEX_VERSION} and put codex on PATH`);
103271
103426
  }
103272
- async function checkVersion(binary, layout) {
103427
+ async function checkVersion(binary, layout, timeoutMs = 5e3) {
103273
103428
  if (!isAbsolute(binary))
103274
- throw new Error("Codex executable must be absolute");
103429
+ throw new TurnFailure("ai_tool_unsupported", {}, "Codex executable must be absolute");
103275
103430
  const version2 = await new Promise((resolve4, reject) => {
103276
- execFile(binary, ["--version"], { cwd: layout.work, env: childEnvironment(layout), timeout: 5e3, maxBuffer: 4096 }, (error2, stdout) => error2 ? reject(new Error("Cannot run Codex CLI; install the native 0.154.0 executable (the isolated child PATH is /usr/bin:/bin)")) : resolve4(stdout.trim()));
103431
+ execFile(binary, ["--version"], { cwd: layout.work, env: childEnvironment(layout), timeout: timeoutMs, maxBuffer: 4096 }, (error2, stdout) => {
103432
+ if (!error2)
103433
+ resolve4(stdout.trim());
103434
+ else if (error2.killed === true && error2.signal === "SIGTERM" && error2.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
103435
+ reject(new TurnFailure("model_error", {}, "Codex CLI did not answer --version in time"));
103436
+ else
103437
+ reject(new TurnFailure("ai_tool_unsupported", {}, "Cannot run Codex CLI; install the native 0.154.0 executable (the isolated child PATH is /usr/bin:/bin)"));
103438
+ });
103277
103439
  });
103278
103440
  if (version2 !== `codex-cli ${SUPPORTED_CODEX_VERSION}`)
103279
- throw new Error(`Unsupported Codex CLI; install ${SUPPORTED_CODEX_VERSION}`);
103441
+ throw new TurnFailure("ai_tool_unsupported", {}, `Unsupported Codex CLI; install ${SUPPORTED_CODEX_VERSION}`);
103442
+ }
103443
+ function classifyCodexFailure(text) {
103444
+ if (typeof text !== "string")
103445
+ return "model_error";
103446
+ if (/(?:status|error:?)\s+401\b|401 Unauthorized|could not be refreshed|sign in again|invalid_api_key|invalid_refresh_token/i.test(text))
103447
+ return "provider_auth_failed";
103448
+ if (/unexpected status 5\d\d|stream disconnected|error sending request|failed to lookup address|ENOTFOUND|ECONNREFUSED|ETIMEDOUT/.test(text))
103449
+ return "provider_unreachable";
103450
+ return "model_error";
103451
+ }
103452
+ async function keepFirstPrivate(path2, value) {
103453
+ const temporary = `${path2}.${randomUUID5()}.tmp`;
103454
+ await writeFile4(temporary, value, { mode: 384, flag: "wx" });
103455
+ try {
103456
+ await link(temporary, path2);
103457
+ } catch (error2) {
103458
+ if (error2.code !== "EEXIST")
103459
+ throw error2;
103460
+ } finally {
103461
+ await unlink2(temporary).catch(() => void 0);
103462
+ }
103463
+ }
103464
+ function seededPrompt(seed, prompt) {
103465
+ if (!seed)
103466
+ return prompt;
103467
+ const budget = MAX_PROMPT_BYTES - Buffer.byteLength(prompt) - 2;
103468
+ if (budget <= 0)
103469
+ return prompt;
103470
+ const bytes = Buffer.from(seed, "utf8");
103471
+ if (bytes.length <= budget)
103472
+ return `${seed}
103473
+
103474
+ ${prompt}`;
103475
+ let start = bytes.length - budget;
103476
+ while (start < bytes.length && (bytes[start] & 192) === 128)
103477
+ start++;
103478
+ let kept = bytes.subarray(start).toString("utf8");
103479
+ const newline = kept.indexOf("\n");
103480
+ kept = newline >= 0 ? kept.slice(newline + 1) : "";
103481
+ return kept ? `${kept}
103482
+
103483
+ ${prompt}` : prompt;
103280
103484
  }
103281
103485
  function parseTurnUsage(raw) {
103282
103486
  if (!raw || typeof raw !== "object")
@@ -103288,13 +103492,17 @@ function parseTurnUsage(raw) {
103288
103492
  const cached2 = count(u2.cached_input_tokens);
103289
103493
  return { model: CODEX_MODEL, inputTokens, outputTokens, ...cached2 !== void 0 ? { cachedInputTokens: cached2 } : {} };
103290
103494
  }
103291
- var SUPPORTED_CODEX_VERSION, CODE_MODE_WARNING, UUID2, CODEX_MODEL, count, CodexDriver;
103495
+ var SUPPORTED_CODEX_VERSION, CODE_MODE_WARNING, MODEL_METADATA_WARNING, MAX_PROMPT_BYTES, STDERR_PREFIX_BYTES, UUID2, CODEX_MODEL, count, CodexDriver;
103292
103496
  var init_driver = __esm({
103293
- "src/driver.ts"() {
103497
+ async "src/driver.ts"() {
103294
103498
  "use strict";
103295
103499
  init_rollout();
103500
+ await init_dist();
103296
103501
  SUPPORTED_CODEX_VERSION = "0.154.0";
103297
103502
  CODE_MODE_WARNING = "Code Mode is unavailable because code-mode host is disabled. Code mode will fail closed; enable `features.code_mode_host` and install `codex-code-mode-host`.";
103503
+ MODEL_METADATA_WARNING = /^Model metadata for `[^`\n]{1,200}` not found\. Defaulting to fallback metadata;/;
103504
+ MAX_PROMPT_BYTES = 128 * 1024;
103505
+ STDERR_PREFIX_BYTES = 8 * 1024;
103298
103506
  UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
103299
103507
  CODEX_MODEL = "gpt-5.6-terra";
103300
103508
  count = (v2) => typeof v2 === "number" && Number.isSafeInteger(v2) && v2 >= 0 ? v2 : void 0;
@@ -103305,37 +103513,89 @@ var init_driver = __esm({
103305
103513
  options;
103306
103514
  busy = false;
103307
103515
  poisoned = false;
103308
- async run(key, prompt, signal) {
103309
- if (this.busy || this.poisoned || signal?.aborted || Buffer.byteLength(prompt) > 128 * 1024)
103310
- throw new Error("Codex turn failed");
103516
+ async run(key, prompt, signal, opts = {}) {
103517
+ if (this.busy || this.poisoned || signal?.aborted || Buffer.byteLength(prompt) > MAX_PROMPT_BYTES)
103518
+ throw new TurnFailure("model_error");
103311
103519
  this.busy = true;
103312
103520
  try {
103313
- const { binary, layout } = this.options;
103314
- await checkVersion(binary, layout);
103521
+ const { binary, layout, versionTimeoutMs } = this.options;
103522
+ await checkVersion(binary, layout, versionTimeoutMs);
103315
103523
  if (signal?.aborted)
103316
- throw new Error("Codex turn failed");
103524
+ throw new TurnFailure("model_error");
103317
103525
  const sessionFile = join9(layout.sessions, createHash2("sha256").update(key).digest("hex") + ".json");
103318
103526
  let sessionId;
103319
103527
  try {
103320
103528
  const stored = JSON.parse(await readFile6(sessionFile, "utf8"));
103321
103529
  if (typeof stored !== "string" || !UUID2.test(stored))
103322
- throw new Error("Invalid stored Codex session");
103530
+ throw new TurnFailure("model_error", {}, "Invalid stored Codex session");
103323
103531
  sessionId = stored;
103324
103532
  } catch (error2) {
103325
- if (error2.code !== "ENOENT")
103533
+ if (error2 instanceof TurnFailure || error2.code !== "ENOENT")
103326
103534
  throw error2;
103327
103535
  }
103328
- const before = sessionId ? await snapshotRollout(layout, sessionId) : void 0;
103329
- const result = await this.execute(prompt, sessionId, signal);
103536
+ const freshPrompt = seededPrompt(opts.freshContext, prompt);
103537
+ if (!sessionId) {
103538
+ const result2 = await this.execute(freshPrompt, void 0, signal);
103539
+ result2.text = await verifyFinalReply(layout, result2.sessionId, result2.text, void 0);
103540
+ if (signal?.aborted)
103541
+ throw new TurnFailure("model_error");
103542
+ await atomicPrivateWrite(sessionFile, JSON.stringify(result2.sessionId));
103543
+ return result2;
103544
+ }
103545
+ let before;
103546
+ try {
103547
+ before = await snapshotRollout(layout, sessionId);
103548
+ } catch (error2) {
103549
+ if (error2 instanceof RolloutMissing)
103550
+ return await this.recover(sessionFile, sessionId, freshPrompt, signal);
103551
+ throw new TurnFailure("model_error", {}, error2 instanceof Error ? error2.message : void 0);
103552
+ }
103553
+ let result;
103554
+ try {
103555
+ result = await this.execute(prompt, sessionId, signal);
103556
+ } catch (error2) {
103557
+ if (error2?.resumeRefused === true)
103558
+ return await this.recover(sessionFile, sessionId, freshPrompt, signal);
103559
+ throw error2;
103560
+ }
103330
103561
  result.text = await verifyFinalReply(layout, result.sessionId, result.text, before);
103331
103562
  if (signal?.aborted)
103332
- throw new Error("Codex turn failed");
103563
+ throw new TurnFailure("model_error");
103333
103564
  await atomicPrivateWrite(sessionFile, JSON.stringify(result.sessionId));
103334
103565
  return result;
103566
+ } catch (error2) {
103567
+ throw error2 instanceof TurnFailure ? error2 : new TurnFailure("model_error", {}, error2 instanceof Error ? error2.message : void 0);
103335
103568
  } finally {
103336
103569
  this.busy = false;
103337
103570
  }
103338
103571
  }
103572
+ /**
103573
+ * #1560 — the stored session is gone: run exactly one fresh, seeded session.
103574
+ * The stored id is replaced only after the fresh reply verifies; the first
103575
+ * replaced id is kept in `<file>.prev` and never overwritten.
103576
+ */
103577
+ async recover(sessionFile, oldId, freshPrompt, signal) {
103578
+ if (signal?.aborted || this.poisoned)
103579
+ throw new TurnFailure("model_error");
103580
+ const { layout } = this.options;
103581
+ const result = await this.execute(freshPrompt, void 0, signal);
103582
+ if (result.sessionId === oldId)
103583
+ throw new TurnFailure("model_error");
103584
+ try {
103585
+ result.text = await verifyFinalReply(layout, result.sessionId, result.text, void 0);
103586
+ } catch (error2) {
103587
+ throw new TurnFailure("model_error", {}, error2 instanceof Error ? error2.message : void 0);
103588
+ }
103589
+ if (signal?.aborted)
103590
+ throw new TurnFailure("model_error");
103591
+ await keepFirstPrivate(`${sessionFile}.prev`, JSON.stringify(oldId));
103592
+ await atomicPrivateWrite(sessionFile, JSON.stringify(result.sessionId));
103593
+ try {
103594
+ this.options.onRecovered?.("session_resume_failed");
103595
+ } catch {
103596
+ }
103597
+ return result;
103598
+ }
103339
103599
  execute(prompt, expectedId, signal) {
103340
103600
  const { binary, layout, timeoutMs = 12e4, killGraceMs = 500, maxLineBytes = 256 * 1024, maxOutputBytes = 2 * 1024 * 1024 } = this.options;
103341
103601
  const invocation = buildInvocation(layout, expectedId);
@@ -103343,6 +103603,9 @@ var init_driver = __esm({
103343
103603
  const child = spawn(binary, invocation.args, { cwd: invocation.cwd, env: invocation.env, stdio: ["pipe", "pipe", "pipe"], detached: true });
103344
103604
  let failed = false, closed = false, settled = false, started = false, terminal = false;
103345
103605
  let sessionId = "", text = "", buffered = "", bytes = 0;
103606
+ let eventText = "", itemText = "", errPrefix = "", errPrefixBytes = 0;
103607
+ let threadStarted = false, exitCode = null;
103608
+ let endedBy = "exit";
103346
103609
  let usage;
103347
103610
  const decoder2 = new StringDecoder("utf8");
103348
103611
  let killTimer;
@@ -103361,7 +103624,7 @@ var init_driver = __esm({
103361
103624
  clearTimeout(timeout);
103362
103625
  clearTimeout(killTimer);
103363
103626
  clearTimeout(reapTimer);
103364
- signal?.removeEventListener("abort", fail);
103627
+ signal?.removeEventListener("abort", onAbort);
103365
103628
  };
103366
103629
  const finish = (ok) => {
103367
103630
  if (settled)
@@ -103370,10 +103633,22 @@ var init_driver = __esm({
103370
103633
  cleanup();
103371
103634
  if (ok)
103372
103635
  resolve4({ text, sessionId, ...usage ? { usage } : {} });
103373
- else
103374
- reject(new Error("Codex turn failed"));
103636
+ else {
103637
+ let code = classifyCodexFailure(eventText);
103638
+ if (code === "model_error")
103639
+ code = classifyCodexFailure(itemText);
103640
+ if (code === "model_error" && !threadStarted)
103641
+ code = classifyCodexFailure(errPrefix);
103642
+ const resumeRefused = endedBy === "exit" && !threadStarted && typeof exitCode === "number" && /thread\/resume failed: no rollout found/.test(errPrefix);
103643
+ const error2 = new TurnFailure(code, typeof exitCode === "number" ? { exitCode } : {});
103644
+ Object.defineProperty(error2, "resumeRefused", { value: resumeRefused, enumerable: false });
103645
+ reject(error2);
103646
+ }
103647
+ eventText = itemText = errPrefix = "";
103375
103648
  };
103376
- const fail = () => {
103649
+ const fail = (why) => {
103650
+ if (!failed && why)
103651
+ endedBy = why;
103377
103652
  failed = true;
103378
103653
  text = "";
103379
103654
  if (killTimer || closed)
@@ -103385,10 +103660,11 @@ var init_driver = __esm({
103385
103660
  finish(false);
103386
103661
  }, killGraceMs + 5e3);
103387
103662
  };
103388
- const timeout = setTimeout(fail, timeoutMs);
103389
- signal?.addEventListener("abort", fail, { once: true });
103663
+ const onAbort = () => fail("abort");
103664
+ const timeout = setTimeout(() => fail("timeout"), timeoutMs);
103665
+ signal?.addEventListener("abort", onAbort, { once: true });
103390
103666
  if (signal?.aborted)
103391
- fail();
103667
+ onAbort();
103392
103668
  const line = (raw) => {
103393
103669
  if (failed)
103394
103670
  return;
@@ -103401,6 +103677,7 @@ var init_driver = __esm({
103401
103677
  if (sessionId || typeof e.thread_id !== "string" || !UUID2.test(e.thread_id) || expectedId && e.thread_id !== expectedId)
103402
103678
  throw new Error();
103403
103679
  sessionId = e.thread_id;
103680
+ threadStarted = true;
103404
103681
  break;
103405
103682
  case "turn.started":
103406
103683
  if (!sessionId || started)
@@ -103409,8 +103686,12 @@ var init_driver = __esm({
103409
103686
  break;
103410
103687
  case "item.completed":
103411
103688
  if (e.item?.type === "error") {
103412
- if (e.item.message !== CODE_MODE_WARNING)
103689
+ const message = e.item.message;
103690
+ const warning = message === CODE_MODE_WARNING || typeof message === "string" && MODEL_METADATA_WARNING.test(message);
103691
+ if (!warning) {
103692
+ itemText = typeof message === "string" ? message : "";
103413
103693
  throw new Error();
103694
+ }
103414
103695
  } else if (e.item?.type === "agent_message") {
103415
103696
  if (!started || typeof e.item.text !== "string")
103416
103697
  throw new Error();
@@ -103424,7 +103705,10 @@ var init_driver = __esm({
103424
103705
  usage = parseTurnUsage(e.usage);
103425
103706
  break;
103426
103707
  case "error":
103708
+ eventText = typeof e.message === "string" ? e.message : "";
103709
+ throw new Error();
103427
103710
  case "turn.failed":
103711
+ eventText = typeof e.error?.message === "string" ? e.error.message : "";
103428
103712
  throw new Error();
103429
103713
  case "item.started":
103430
103714
  case "item.updated":
@@ -103439,7 +103723,7 @@ var init_driver = __esm({
103439
103723
  child.stdout.on("data", (chunk) => {
103440
103724
  bytes += chunk.length;
103441
103725
  if (bytes > maxOutputBytes) {
103442
- fail();
103726
+ fail("overflow");
103443
103727
  return;
103444
103728
  }
103445
103729
  if (failed)
@@ -103452,17 +103736,23 @@ var init_driver = __esm({
103452
103736
  line(raw);
103453
103737
  }
103454
103738
  if (Buffer.byteLength(buffered) > maxLineBytes)
103455
- fail();
103739
+ fail("overflow");
103456
103740
  });
103457
103741
  child.stderr.on("data", (chunk) => {
103458
103742
  bytes += chunk.length;
103743
+ if (errPrefixBytes < STDERR_PREFIX_BYTES) {
103744
+ const part = chunk.subarray(0, STDERR_PREFIX_BYTES - errPrefixBytes);
103745
+ errPrefixBytes += part.length;
103746
+ errPrefix += part.toString("utf8");
103747
+ }
103459
103748
  if (bytes > maxOutputBytes)
103460
- fail();
103749
+ fail("overflow");
103461
103750
  });
103462
- child.stdin.on("error", fail);
103463
- child.on("error", fail);
103751
+ child.stdin.on("error", () => fail());
103752
+ child.on("error", () => fail());
103464
103753
  child.on("close", (code) => {
103465
103754
  closed = true;
103755
+ exitCode = code;
103466
103756
  killGroup("SIGKILL");
103467
103757
  const deadline = Date.now() + 5e3;
103468
103758
  const reaped = () => {
@@ -103494,7 +103784,7 @@ var init_driver = __esm({
103494
103784
  });
103495
103785
 
103496
103786
  // src/cli.ts
103497
- import { access as access2, readFile as readFile7, mkdir as mkdir6, unlink as unlink2, open as open6, stat as stat2 } from "node:fs/promises";
103787
+ import { access as access2, readFile as readFile7, mkdir as mkdir6, unlink as unlink3, open as open6, stat as stat2 } from "node:fs/promises";
103498
103788
  import { join as join10, isAbsolute as isAbsolute2 } from "node:path";
103499
103789
  import { createHash as createHash3 } from "node:crypto";
103500
103790
  function agentSlug(name) {
@@ -103717,7 +104007,7 @@ Pending invite: ${await exists(join10(root3, "pending-invite")) ? "present" : "m
103717
104007
  await invoke("/bin/launchctl", ["bootout", `gui/${deps.uid}/${spec.label}`]);
103718
104008
  else
103719
104009
  await invoke("/usr/bin/systemctl", ["--user", "disable", "--now", `${spec.label}.service`]);
103720
- await unlink2(spec.path).catch((error2) => {
104010
+ await unlink3(spec.path).catch((error2) => {
103721
104011
  if (error2.code !== "ENOENT")
103722
104012
  throw error2;
103723
104013
  });
@@ -103733,8 +104023,8 @@ var init_cli = __esm({
103733
104023
  async "src/cli.ts"() {
103734
104024
  "use strict";
103735
104025
  await init_dist();
103736
- init_driver();
103737
- VERSION2 = "0.1.12";
104026
+ await init_driver();
104027
+ VERSION2 = "0.1.14";
103738
104028
  HELP = `AgentVault OpenAI Bridge ${VERSION2}
103739
104029
  Usage: AV_AGENT_NAME=<name> agentvault-openai-bridge <command>
103740
104030
 
@@ -103773,7 +104063,7 @@ var init_bridge = __esm({
103773
104063
  this.waiting = [];
103774
104064
  for (const item of waiting)
103775
104065
  if (item.generation === this.generation && item.deviceId === this.channel.deviceId)
103776
- this.enqueue(item.kind, item.id, item.text);
104066
+ this.enqueue(item.kind, item.id, item.text, item.groupId);
103777
104067
  });
103778
104068
  this.listen("state", (state) => {
103779
104069
  if (state === "connecting") {
@@ -103784,10 +104074,8 @@ var init_bridge = __esm({
103784
104074
  this.invalidate();
103785
104075
  });
103786
104076
  this.listen("error", () => {
103787
- this.generation++;
103788
- this.active?.abort();
103789
104077
  });
103790
- this.listen("revoked", () => this.invalidate());
104078
+ this.listen("revoked", () => this.invalidate("revoked"));
103791
104079
  this.listen("room_hushed", (e) => {
103792
104080
  if (typeof e?.roomId !== "string")
103793
104081
  return;
@@ -103799,9 +104087,13 @@ var init_bridge = __esm({
103799
104087
  }
103800
104088
  });
103801
104089
  this.listen("message", (text, metadata) => {
103802
- if (metadata?.ownerDm1to1 !== true || metadata.roomId || typeof metadata.conversationId !== "string")
104090
+ if (metadata?.ownerDm1to1 !== true || metadata.roomId)
103803
104091
  return;
103804
- this.enqueue("dm", metadata.conversationId, text);
104092
+ if (typeof metadata.conversationId !== "string") {
104093
+ this.report("dm_dropped reason=unmapped_conversation");
104094
+ return;
104095
+ }
104096
+ this.enqueue("dm", metadata.conversationId, text, typeof metadata.conversationGroupId === "string" ? metadata.conversationGroupId : void 0);
103805
104097
  });
103806
104098
  this.listen("room_message", (e) => {
103807
104099
  if (typeof e?.roomId !== "string" || typeof e.plaintext !== "string" || this.hushed(e.roomId))
@@ -103824,6 +104116,8 @@ var init_bridge = __esm({
103824
104116
  ready = false;
103825
104117
  accepting = true;
103826
104118
  waiting = [];
104119
+ /** The reason each generation ended, keyed by the generation it ended (#1560). */
104120
+ cancelReasons = /* @__PURE__ */ new Map();
103827
104121
  stopped = false;
103828
104122
  active;
103829
104123
  hush = /* @__PURE__ */ new Map();
@@ -103835,14 +104129,40 @@ var init_bridge = __esm({
103835
104129
  hushed(id) {
103836
104130
  return (this.hush.get(id) ?? 0) > Date.now();
103837
104131
  }
103838
- invalidate() {
104132
+ /** Ends the current generation. Its reason is recorded BEFORE the bump, under
104133
+ * the generation it ends, so a later invalidate (stop after revoked) cannot
104134
+ * overwrite why the turns of that generation were cut. */
104135
+ invalidate(reason = "channel_state") {
103839
104136
  this.ready = false;
103840
104137
  this.accepting = false;
103841
104138
  this.waiting = [];
104139
+ this.cancelReasons.set(this.generation, reason);
104140
+ for (const key of this.cancelReasons.keys())
104141
+ if (key < this.generation - 32)
104142
+ this.cancelReasons.delete(key);
103842
104143
  this.generation++;
103843
104144
  this.active?.abort();
103844
104145
  }
103845
- enqueue(kind, id, text) {
104146
+ cancelReason(entryGeneration, target, kind, id) {
104147
+ if (entryGeneration !== this.generation)
104148
+ return this.cancelReasons.get(entryGeneration) ?? "unknown";
104149
+ if (target.deviceId !== this.channel.deviceId)
104150
+ return "device_changed";
104151
+ if (kind === "room" && this.hushed(id))
104152
+ return "hushed";
104153
+ return "unknown";
104154
+ }
104155
+ /** Recent entries as `sender: text`, without the bridge's own failure notices. */
104156
+ context(entries, current) {
104157
+ const kept = (entries ?? []).filter((entry) => !(entry.sender === "agent" && isOwnerNotice(entry.text)));
104158
+ const last = kept[kept.length - 1];
104159
+ if (current !== void 0 && last && last.sender === "owner" && (last.text === current || last.text.length > 0 && current.endsWith(`
104160
+
104161
+ ${last.text}`)))
104162
+ kept.pop();
104163
+ return kept.map((entry) => `${entry.sender}: ${entry.text}`).join("\n").slice(-8192);
104164
+ }
104165
+ enqueue(kind, id, text, groupId) {
103846
104166
  if (!this.accepting || this.stopped || !id || !this.channel.deviceId || typeof text !== "string" || !text.trim() || Buffer.byteLength(text) > 96 * 1024)
103847
104167
  return;
103848
104168
  if (this.pending + this.waiting.length >= this.maxQueue) {
@@ -103850,35 +104170,62 @@ var init_bridge = __esm({
103850
104170
  return;
103851
104171
  }
103852
104172
  if (!this.ready) {
103853
- this.waiting.push({ kind, id, text, deviceId: this.channel.deviceId, generation: this.generation });
104173
+ this.waiting.push({ kind, id, text, groupId, deviceId: this.channel.deviceId, generation: this.generation });
103854
104174
  return;
103855
104175
  }
103856
- const history = kind === "room" ? (this.channel.getRoomHistory?.(id, 20) ?? []).map((entry) => `${entry.sender}: ${entry.text}`).join("\n").slice(-8192) : "";
104176
+ const history = kind === "room" ? this.context(this.channel.getRoomHistory?.(id, 20)) : "";
104177
+ const seed = kind === "dm" ? this.context(this.channel.getConversationHistory?.(id, 20, { groupId }), text) : "";
104178
+ const freshContext = seed ? `Recent messages from this chat:
104179
+ ${seed}` : void 0;
103857
104180
  const target = { kind, id, deviceId: this.channel.deviceId };
103858
104181
  const generation = this.generation;
103859
104182
  const valid = () => this.ready && !this.stopped && generation === this.generation && target.deviceId === this.channel.deviceId && !(kind === "room" && this.hushed(id));
104183
+ const cancelled = () => this.report(`turn_cancelled reason=${this.cancelReason(generation, target, kind, id)}`);
103860
104184
  this.pending++;
103861
104185
  this.tail = this.tail.then(async () => {
103862
- if (!valid())
104186
+ if (!valid()) {
104187
+ cancelled();
103863
104188
  return;
104189
+ }
103864
104190
  const controller = new AbortController();
103865
104191
  this.active = controller;
103866
104192
  try {
103867
104193
  const startedAt = Date.now();
103868
- const reply = await this.driver.run(JSON.stringify([target.deviceId, kind, id]), `You are ${this.name}, an AgentVault conversational agent. Reply in plain text to this ${kind === "dm" ? "owner direct message" : "addressed room message"}. Filesystem, shell, web and integration tools are unavailable.
104194
+ let reply;
104195
+ try {
104196
+ reply = await this.driver.run(JSON.stringify([target.deviceId, kind, id]), `You are ${this.name}, an AgentVault conversational agent. Reply in plain text to this ${kind === "dm" ? "owner direct message" : "addressed room message"}. Filesystem, shell, web and integration tools are unavailable.
103869
104197
  ${history ? `Recent messages from this room (conversation context):
103870
104198
  ${history}
103871
104199
  ` : ""}
103872
104200
  Current message:
103873
- ${text}`, controller.signal);
104201
+ ${text}`, controller.signal, { freshContext });
104202
+ } catch (err) {
104203
+ if (controller.signal.aborted || !valid()) {
104204
+ cancelled();
104205
+ return;
104206
+ }
104207
+ await this.turnFailed(target, err, Date.now() - startedAt, controller.signal);
104208
+ return;
104209
+ }
103874
104210
  this.reportUsage(reply, Date.now() - startedAt);
103875
- if (!valid() || controller.signal.aborted)
104211
+ if (!valid() || controller.signal.aborted) {
104212
+ cancelled();
104213
+ return;
104214
+ }
104215
+ let cause;
104216
+ try {
104217
+ await this.deliver(target, reply.text, controller.signal, (e) => {
104218
+ cause = e;
104219
+ });
104220
+ } catch (err) {
104221
+ if (controller.signal.aborted || !valid())
104222
+ cancelled();
104223
+ else
104224
+ this.report(`reply_failed code=${classifyToolError(cause ?? err)}`);
103876
104225
  return;
103877
- await this.deliver(target, reply.text, controller.signal);
104226
+ }
103878
104227
  if (valid() && !controller.signal.aborted)
103879
104228
  this.report("delivered");
103880
- } catch {
103881
- this.report("turn_or_delivery_failed");
103882
104229
  } finally {
103883
104230
  this.active = void 0;
103884
104231
  }
@@ -103886,6 +104233,32 @@ ${text}`, controller.signal);
103886
104233
  this.pending--;
103887
104234
  });
103888
104235
  }
104236
+ /** #1560: a turn that failed (not one cancelled on purpose). RECORD FIRST —
104237
+ * the span and the log line — then post the notice, so a notice that stalls
104238
+ * or fails cannot lose the record. Only codes and the exit status are
104239
+ * logged, never the error's text. In a room the notice is the bare sentence:
104240
+ * the coded ones describe the owner's own provider account. */
104241
+ async turnFailed(target, err, durationMs, signal) {
104242
+ const code = err instanceof TurnFailure ? err.code : "model_error";
104243
+ const exitCode = err?.exitCode;
104244
+ const exit = typeof exitCode === "number" ? exitCode : "none";
104245
+ const sink = this.channel.telemetry;
104246
+ reportModelTurnFailure(sink && typeof sink.reportCustomSpan === "function" ? sink : null, {
104247
+ code,
104248
+ conversation: { kind: target.kind === "dm" ? "direct" : "room", id: target.id },
104249
+ durationMs
104250
+ });
104251
+ this.report(`turn_failed code=${code} exit=${exit}`);
104252
+ const notice = ownerNoticeFor(target.kind === "room" ? "model_error" : code, { agentName: this.channel.ownDisplayName?.trim() || this.name, provider: "OpenAI" });
104253
+ let cause;
104254
+ try {
104255
+ await this.deliverOnce(target, notice, signal, (e) => {
104256
+ cause = e;
104257
+ });
104258
+ } catch (noticeErr) {
104259
+ this.report(`notice_failed code=${classifyToolError(cause ?? noticeErr)}`);
104260
+ }
104261
+ }
103889
104262
  /** Health (2026-10-14): tokens for the model call. No cost — the bridge runs
103890
104263
  * on a ChatGPT login, so there is no per-token price to report honestly. */
103891
104264
  reportUsage(reply, latencyMs) {
@@ -103921,12 +104294,14 @@ ${text}`, controller.signal);
103921
104294
  } catch {
103922
104295
  }
103923
104296
  }
103924
- async deliver(target, text, signal) {
104297
+ async deliver(target, text, signal, onSendError = () => {
104298
+ }) {
103925
104299
  const startedAt = Date.now();
103926
104300
  let cause;
103927
104301
  try {
103928
104302
  await this.deliverOnce(target, text, signal, (e) => {
103929
104303
  cause = e;
104304
+ onSendError(e);
103930
104305
  });
103931
104306
  } catch (err) {
103932
104307
  this.reportReply(target, startedAt, { err: cause ?? err });
@@ -103950,7 +104325,7 @@ ${text}`, controller.signal);
103950
104325
  const timer = setTimeout(() => {
103951
104326
  finish(new Error("Delivery timed out"));
103952
104327
  this.stopped = true;
103953
- this.invalidate();
104328
+ this.invalidate("delivery_timeout");
103954
104329
  this.report("delivery_timeout");
103955
104330
  }, this.deliveryTimeoutMs);
103956
104331
  signal.addEventListener("abort", abort, { once: true });
@@ -103967,7 +104342,7 @@ ${text}`, controller.signal);
103967
104342
  }
103968
104343
  async stop() {
103969
104344
  this.stopped = true;
103970
- this.invalidate();
104345
+ this.invalidate("stop");
103971
104346
  for (const [event, fn] of this.listeners)
103972
104347
  this.channel.off(event, fn);
103973
104348
  this.listeners = [];
@@ -103978,7 +104353,7 @@ ${text}`, controller.signal);
103978
104353
  });
103979
104354
 
103980
104355
  // src/lock.ts
103981
- import { mkdir as mkdir7, open as open7, readFile as readFile8, rmdir, unlink as unlink3 } from "node:fs/promises";
104356
+ import { mkdir as mkdir7, open as open7, readFile as readFile8, rmdir, unlink as unlink4 } from "node:fs/promises";
103982
104357
  import { join as join11 } from "node:path";
103983
104358
  import { randomUUID as randomUUID6 } from "node:crypto";
103984
104359
  async function acquireLock(root3) {
@@ -104008,7 +104383,7 @@ async function acquireLock(root3) {
104008
104383
  if (error2.code !== "ESRCH")
104009
104384
  throw error2;
104010
104385
  }
104011
- await unlink3(path2);
104386
+ await unlink4(path2);
104012
104387
  }
104013
104388
  const file = await open7(path2, "wx", 384);
104014
104389
  try {
@@ -104022,7 +104397,7 @@ async function acquireLock(root3) {
104022
104397
  return async () => {
104023
104398
  const current = JSON.parse(await readFile8(path2, "utf8"));
104024
104399
  if (current.token === token)
104025
- await unlink3(path2);
104400
+ await unlink4(path2);
104026
104401
  };
104027
104402
  }
104028
104403
  var init_lock = __esm({
@@ -104034,11 +104409,15 @@ var init_lock = __esm({
104034
104409
  // src/runtime.ts
104035
104410
  var runtime_exports = {};
104036
104411
  __export(runtime_exports, {
104412
+ codexDriverOptions: () => codexDriverOptions,
104037
104413
  startBridge: () => startBridge
104038
104414
  });
104039
- import { unlink as unlink4, access as access3, mkdir as mkdir8, rename as rename6, chmod as chmod4, readFile as readFile9 } from "node:fs/promises";
104415
+ import { unlink as unlink5, access as access3, mkdir as mkdir8, rename as rename6, chmod as chmod4, readFile as readFile9 } from "node:fs/promises";
104040
104416
  import { join as join12 } from "node:path";
104041
104417
  import { randomUUID as randomUUID7 } from "node:crypto";
104418
+ function codexDriverOptions(config2, report) {
104419
+ return { binary: config2.binary, layout: config2.layout, onRecovered: (code) => report(`turn_recovered code=${code}`) };
104420
+ }
104042
104421
  async function startBridge(config2, injected) {
104043
104422
  const unlock = await acquireLock(config2.layout.root);
104044
104423
  const report = injected?.report ?? ((event) => {
@@ -104108,7 +104487,7 @@ async function startBridge(config2, injected) {
104108
104487
  const consumesInvite = !!config2.inviteToken && (config2.forceReEnroll || existing.length === 0);
104109
104488
  const options = { inviteToken: config2.inviteToken, dataDir: config2.layout.root, apiUrl: config2.apiUrl, agentName: config2.name, expectedFramework: "openai", forceReEnroll: config2.forceReEnroll ?? false, platform: "node", clientVersion: `@agentvault/openai-bridge@${VERSION2}` };
104110
104489
  channel = injected ? injected.createChannel(options) : new (await init_dist().then(() => dist_exports)).SecureChannel(options);
104111
- bridge = new OpenAIBridge(channel, injected?.driver ?? new CodexDriver({ binary: config2.binary, layout: config2.layout }), config2.name, (event) => {
104490
+ bridge = new OpenAIBridge(channel, injected?.driver ?? new CodexDriver(codexDriverOptions(config2, report)), config2.name, (event) => {
104112
104491
  report(event);
104113
104492
  if (event === "delivery_timeout") {
104114
104493
  deliveryFailed = true;
@@ -104122,7 +104501,7 @@ async function startBridge(config2, injected) {
104122
104501
  void (async () => {
104123
104502
  const path2 = join12(config2.layout.root, "pending-invite");
104124
104503
  if ((await readFile9(path2, "utf8")).trim() === config2.inviteToken)
104125
- await unlink4(path2);
104504
+ await unlink5(path2);
104126
104505
  })().catch(() => {
104127
104506
  });
104128
104507
  report("channel_ready");
@@ -104166,7 +104545,7 @@ async function startBridge(config2, injected) {
104166
104545
  var init_runtime = __esm({
104167
104546
  async "src/runtime.ts"() {
104168
104547
  "use strict";
104169
- init_driver();
104548
+ await init_driver();
104170
104549
  await init_bridge();
104171
104550
  await init_cli();
104172
104551
  init_lock();
@@ -104175,9 +104554,9 @@ var init_runtime = __esm({
104175
104554
 
104176
104555
  // src/index.ts
104177
104556
  await init_cli();
104178
- init_driver();
104557
+ await init_driver();
104179
104558
  await init_cli();
104180
- init_driver();
104559
+ await init_driver();
104181
104560
  await init_bridge();
104182
104561
  import { spawn as spawn2 } from "node:child_process";
104183
104562
  import { realpathSync } from "node:fs";