@agentvault/grok-bridge 0.4.32 → 0.4.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,6 +60,28 @@ baked at the original install.
60
60
  Logs go to `<data-dir>/logs/grok-bridge.error.log` — the bridge writes to stderr,
61
61
  so the `.error.log` file is the one with content in it.
62
62
 
63
+ ## When a reply fails
64
+
65
+ When a Grok turn fails, the bridge records it first, then tells the chat, and only then restarts itself. It never drops a failed turn without a trace.
66
+
67
+ - **In a 1:1 with the owner**, the owner sees one plain sentence. It names the cause when the bridge can tell what it is. For example: "Ohtani couldn't answer this message: its xAI sign-in expired. Sign in again on the agent's computer." The bridge can tell an expired sign-in, a billing problem, rate limiting, a model the account can't use, xAI being unreachable, and a Grok CLI too old to answer. Only the expired sign-in has been seen live so far. When the cause is unclear, the sentence just says the agent couldn't answer this message.
68
+ - **In a room**, the sentence never names the cause, because other people and agents can read it. The room just sees that the agent couldn't answer this message.
69
+ - **No notice** is posted for a turn the agent didn't owe a reply to: a room message that didn't @mention it, or a 1:1 the owner's device didn't vouch for.
70
+ - **In every case**, the cause is recorded privately for the owner under **Health, Recent problems**.
71
+
72
+ Every failed turn ends this process, and the service manager starts a fresh one. That is on purpose: the Grok CLI does not confirm a cancel, so the old session could still speak. The fresh process starts a new Grok session. The bridge saves no Grok session to resume, so there is no saved session to lose or repair.
73
+
74
+ The log holds one line per event, with codes and exit numbers only. It never holds message text or provider error text:
75
+
76
+ | Log line | What it means |
77
+ |----------|---------------|
78
+ | `turn_failed code=<code> exit=<n or none>` | The turn failed. `exit` is the Grok CLI's exit status when it died mid-turn, otherwise `none`. A notice follows when the turn owed a reply. |
79
+ | `notice sent to <chat>` | The failure notice was delivered. |
80
+ | `notice_failed code=<code>` or `reason=timeout` | The failure notice could not be delivered. The failure is still recorded under Health. |
81
+ | `turn_cancelled reason=shutdown` | The bridge was already shutting down, so the turn was cut short on purpose. Nothing is recorded or posted. |
82
+
83
+ The Grok CLI's own error output can repeat the provider's error text, so the log records only its size and level (`grok: stderr lines=<n> bytes=<n> level=ERROR`). A failed start is logged the same way, by cause only: `fatal: grok did not start: code=<code> exit=<n or none> ...`. To see the CLI's own words, run `grok` by hand.
84
+
63
85
  ## Copied-from ledger — REVIEW PERIODICALLY
64
86
 
65
87
  These files were copied once from the Claude bridge and are now owned here. A fix
@@ -23,6 +23,23 @@ export declare class AcpTimeout extends Error {
23
23
  readonly ms: number;
24
24
  constructor(method: string, ms: number);
25
25
  }
26
+ /**
27
+ * The agent answered a request with a JSON-RPC `error` (#1560). The message is
28
+ * unchanged from before this class existed (`<method>: <error JSON>`); the
29
+ * fields let the turn-failure classifier read the code and `data` without
30
+ * re-parsing it. Both may carry provider text: never log or send them.
31
+ */
32
+ export declare class AcpRpcError extends Error {
33
+ readonly method: string;
34
+ readonly rpcCode: unknown;
35
+ readonly rpcMessage: unknown;
36
+ readonly rpcData: unknown;
37
+ constructor(method: string, error: {
38
+ code?: unknown;
39
+ message?: unknown;
40
+ data?: unknown;
41
+ });
42
+ }
26
43
  /**
27
44
  * JSON-RPC over a child's stdio. Transport only — it knows nothing about ACP
28
45
  * methods, sessions or Grok.
package/dist/bridge.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * bridge declares its own in its bridge.ts; that declaration was NOT copied.
14
14
  * Type-only, so this cannot create a runtime import cycle. */
15
15
  import { type ToolSpanSink } from "@agentvault/agentvault";
16
- import type { RoomSession } from "./grok-session.js";
16
+ import type { ReplySink, RoomSession } from "./grok-session.js";
17
17
  import { type RoomContextLimits } from "./room-context.js";
18
18
  import { type TerminalVerdict } from "./service/self-uninstall.js";
19
19
  export interface RoomMessage {
@@ -145,7 +145,7 @@ export declare class ActiveTarget {
145
145
  * these per inbound (at push time) and hands it to the session, so a room message
146
146
  * arriving mid-compose can never redirect a private 1:1 reply into the room.
147
147
  */
148
- snapshotReply(channel: ReplyChannel, log?: (msg: string) => void): (text: string) => Promise<void>;
148
+ snapshotReply(channel: ReplyChannel, log?: (msg: string) => void): ReplySink;
149
149
  }
150
150
  export interface LifecycleChannel {
151
151
  on(ev: "auth_failed", cb: (e: {
@@ -1,11 +1,22 @@
1
+ import { type ToolConversation, type ToolSpanSink } from "@agentvault/agentvault";
1
2
  import type { TurnResult } from "./agent-driver.js";
3
+ /** A reply sink. `{ notice: true }` marks the #1560 failure notice: delivered
4
+ * to the same chat, but not recorded as the agent's own `say`. */
5
+ export type ReplySink = (text: string, opts?: {
6
+ notice?: boolean;
7
+ }) => Promise<void>;
8
+ /** What a pushed turn knows about where it came from. */
9
+ export interface PushOpts {
10
+ autoReplyOnText?: boolean;
11
+ replyExpected?: boolean;
12
+ /** #1560: the chat this turn answers. It names the failure span and picks the
13
+ * notice wording: only a 1:1 hears the cause, anything else the bare line. */
14
+ conversation?: ToolConversation;
15
+ }
2
16
  /** Grok's OWN copy of the room-session contract. The Claude bridge has its own;
3
17
  * the two are deliberately unrelated and must not be unified. */
4
18
  export interface RoomSession {
5
- push(text: string, reply?: (text: string) => Promise<void>, opts?: {
6
- autoReplyOnText?: boolean;
7
- replyExpected?: boolean;
8
- }): void;
19
+ push(text: string, reply?: ReplySink, opts?: PushOpts): void;
9
20
  }
10
21
  export interface DriverLike {
11
22
  deliver(text: string): Promise<TurnResult>;
@@ -27,6 +38,8 @@ export declare class GrokSession implements RoomSession {
27
38
  private queue;
28
39
  private running;
29
40
  private invalidated;
41
+ /** Review F3: the error that failed this session, once one has. */
42
+ private failure;
30
43
  /** The message whose turn is in flight, or null between turns. Null is a
31
44
  * DISTINCT state from "a message that carries no reply sink" — conflating
32
45
  * them is what let a post-turn say fall through to the session-level sink. */
@@ -53,13 +66,18 @@ export declare class GrokSession implements RoomSession {
53
66
  * it. Revisit once `_meta.agentProfile` is probed properly.
54
67
  */
55
68
  identity?: string;
56
- /** Fatal delivery failure: tear down this process for supervised restart. */
69
+ /** Fatal delivery failure: tear down this process for supervised restart.
70
+ * #1560: runs only AFTER the failure is recorded and the notice is out. */
57
71
  onFatal?: (error: unknown) => void | Promise<void>;
72
+ /** #1560: the name the owner reads in a failure notice. */
73
+ agentName?: string | (() => string | undefined);
74
+ /** #1560: where a failed turn's `model_turn` span goes (channel.telemetry). */
75
+ telemetry?: () => ToolSpanSink | null | undefined;
76
+ /** Test seam: the bound on the notice's send. */
77
+ noticeTimeoutMs?: number;
58
78
  });
59
- push(text: string, reply?: (text: string) => Promise<void>, opts?: {
60
- autoReplyOnText?: boolean;
61
- replyExpected?: boolean;
62
- }): void;
79
+ push(text: string, reply?: ReplySink, opts?: PushOpts): void;
80
+ private inbound;
63
81
  /** Hand this to startRoomMcpServer({ onSay }). The behaviour is stable for
64
82
  * the life of the session — the per-message routing happens HERE, not in
65
83
  * the listener — but each call returns a NEW closure; do not rely on
@@ -67,10 +85,26 @@ export declare class GrokSession implements RoomSession {
67
85
  sayHandler(): (text: string) => void;
68
86
  /** Revoke output and future work BEFORE asynchronous process cleanup. */
69
87
  invalidate(): void;
88
+ /** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
89
+ * fails, and it must be recorded and noticed before the process exits. */
90
+ turnInFlight(): boolean;
70
91
  /** Resolves when the queue is empty. For tests and shutdown. */
71
92
  idle(): Promise<void>;
72
93
  private log;
73
94
  private run;
95
+ /**
96
+ * #1560: a failed turn is never silent. In this order:
97
+ * 1. RECORD one `model_turn` span with the code (Health, Recent problems),
98
+ * 2. LOG the code and exit status only (`turn_failed code=<c> exit=<n|none>`),
99
+ * 3. NOTICE the chat with the owner sentence, only where the turn owed a
100
+ * reply (`autoReplyOnText`: an un-addressed room turn stays silent, #1107;
101
+ * an unattested 1:1 gets no plain text, #621). Only a 1:1 hears the
102
+ * cause; a room or an unknown chat gets the bare sentence, because the
103
+ * coded ones describe the owner's own provider account.
104
+ * The notice is bounded so the fatal teardown that follows always runs.
105
+ * Never throws.
106
+ */
107
+ private reportFailure;
74
108
  /**
75
109
  * #416: when the owner expects an answer and the model produced prose but
76
110
  * never called the say tool, send the prose rather than dropping it.
package/dist/index.js CHANGED
@@ -11760,7 +11760,7 @@ function ownIdentity() {
11760
11760
  return `${PACKAGE}@${v2}`;
11761
11761
  }
11762
11762
  function buildSha() {
11763
- const raw = true ? "2ee9fe7" : "";
11763
+ const raw = true ? "bcded1f" : "";
11764
11764
  const cleaned = (raw ?? "").trim();
11765
11765
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11766
11766
  }
@@ -17830,6 +17830,48 @@ function armSseKeepAlive(intervalMs, onTick) {
17830
17830
  function asTurnFailureCode(code) {
17831
17831
  return typeof code === "string" && CODES.has(code) ? code : "model_error";
17832
17832
  }
17833
+ function clean5(value, max) {
17834
+ if (typeof value !== "string") return "";
17835
+ return value.replace(/@/g, "").replace(/\s+/g, " ").trim().slice(0, max).trim();
17836
+ }
17837
+ function ownerNoticeFor(code, ctx) {
17838
+ const a2 = clean5(ctx?.agentName, 80) || "Your agent";
17839
+ const p2 = clean5(ctx?.provider, 40) || "AI provider";
17840
+ const head = `${a2} couldn't answer this message`;
17841
+ switch (asTurnFailureCode(code)) {
17842
+ case "provider_auth_failed":
17843
+ return `${head}: its ${p2} sign-in expired. Sign in again on the agent's computer.`;
17844
+ case "provider_billing":
17845
+ return `${head}: its ${p2} account is out of credit or has a billing problem.`;
17846
+ case "model_rate_limited":
17847
+ return `${head}: it is being rate-limited by ${p2}. Try again in a few minutes.`;
17848
+ case "model_unavailable":
17849
+ return `${head}: the model it is set to use is no longer available.`;
17850
+ case "provider_unreachable":
17851
+ return `${head}: it can't reach ${p2} right now.`;
17852
+ case "ai_tool_unsupported":
17853
+ return `${head}: its AI tool needs attention on its computer.`;
17854
+ case "plan_limit_reached":
17855
+ return `${head}: it has reached its ${p2} plan's usage limit.`;
17856
+ default:
17857
+ return `${head}.`;
17858
+ }
17859
+ }
17860
+ function reportModelTurnFailure(sink, report) {
17861
+ try {
17862
+ const code = asTurnFailureCode(report.code);
17863
+ const isPlan = code === "plan_limit_reached";
17864
+ reportToolInvoke(sink, {
17865
+ toolName: "model_turn",
17866
+ outcome: "error",
17867
+ errorKind: code,
17868
+ durationMs: report.durationMs,
17869
+ conversation: isPlan ? { kind: "unknown" } : report.conversation,
17870
+ ...isPlan && report.limitResetsAt !== void 0 ? { limitResetsAt: report.limitResetsAt } : {}
17871
+ });
17872
+ } catch {
17873
+ }
17874
+ }
17833
17875
  var __create, __defProp2, __getOwnPropDesc, __getOwnPropNames2, __getProtoOf, __hasOwnProp, __esm2, __commonJS, __export2, __copyProps, __toESM, SENTINEL, WRAPPERS, INSTRUCTION, init_abstention, AMBIGUOUS_OWNER_ERROR, init_owner_routing, init_envelope_text, init_mls_commit_classify, MENTION_RE, BROADCAST_NAMES, PRIVATE_ROOM_TURN_NOTE, GENERIC_AGENT_NAMES, init_room_protocol, __filename, __dirname, url, path, Module, Module, root, window_, crypto_, randomValuesStandard, crypto2, randomValueNodeJS, _Module, libsodium_sumo_default, init_libsodium_sumo, a, r, t, c, libsodium_wrappers_default, init_libsodium_wrappers, init_keys, init_x3dh, MAX_SKIP, CHAIN_KEY_SEED, MSG_KEY_SEED, HEADER_KEY_SEED, DoubleRatchet, init_ratchet, init_file_crypto, DOMAIN_DID_DOCUMENT, DOMAIN_TRANSFER_INTENT, DOMAIN_TRANSFER_ACCEPT, BASE58_ALPHABET, init_did, BUILTIN_PATTERNS, ScanEngine, init_scan_engine, init_merkle, VC_CONTEXT_V2, AV_CREDENTIAL_CONTEXT, CRYPTOSUITE, BASE58_ALPHABET2, init_vc, init_transport, init_telemetry, TelemetryReporter, init_telemetry_reporter, CROCKFORD, ARGON2_OPSLIMIT, ARGON2_MEMLIMIT, SALT_BYTES, NONCE_BYTES, KEY_BYTES, BACKUP_VERSION, MAX_BACKUP_SIZE, init_backup, atitle, aobject, aopts, isLE, swap8IfBE, swap32IfBE, hasHexBuiltin, hexes, oidNist, init_utils, BSIGMA, init_blake, U32_MASK64, _32n, fromNumH, fromNumL, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, add3L, add3H, add4L, add4H, add5L, add5H, init_u64, HashMD, SHA256_IV, SHA384_IV, SHA512_IV, init_md, B2B_IV, BBUF, _BLAKE2, _BLAKE2b, blake2b, init_blake2, CROCKFORD2, SALT_BYTES2, NONCE_BYTES2, KEY_BYTES2, TAG_BYTES, ENVELOPE_OVERHEAD, AAD_PREFIX, UUID_RE, UUID_V4_RE, DIGEST_ID_RE, TIMESTAMP_RE, encoder, decoder, HISTORY_MAGIC, HISTORY_ARCHIVE_VERSION, HISTORY_MAX_ENTRIES, HISTORY_MAX_BLOB_BYTES, HISTORY_KDF_OPSLIMIT, HISTORY_KDF_MEMLIMIT, HistoryEntryTooLargeError, init_history_backup, init_approval, encVoid, init_tlsEncoder, uint8Encoder, encodeUint8, decodeUint8, uint16Encoder, encodeUint16, decodeUint16, uint32Encoder, encodeUint32, decodeUint32, uint64Encoder, encodeUint64, decodeUint64, init_number, init_tlsDecoder, init_enumHelpers, defaultProposalTypes, defaultProposalTypeEncoder, encodeDefaultProposalType, decodeDefaultProposalType, init_defaultProposalType, defaultExtensionTypes, defaultExtensionTypeEncoder, encodeDefaultExtensionType, decodeDefaultExtensionType, init_defaultExtensionType, acceptAll, init_incomingMessageAction, MlsError, ValidationError, CodecError, UsageError, DependencyError, CryptoVerificationError, CryptoError, InternalError, init_mlsError, init_byteArray, varLenDataEncoder, decodeVarLenData, init_variableLength, init_constantTimeCompare, extensionTypeEncoder, encodeExtensionType, decodeExtensionType, extensionEncoder, encodeExtension, decodeExtension, init_extension, credentialTypes, credentialTypeEncoder, encodeCredentialType, decodeCredentialType, init_credentialType, credentialBasicEncoder, encodeCredentialBasic, credentialX509Encoder, encodeCredentialX509, credentialCustomEncoder, encodeCredentialCustom, credentialEncoder, encodeCredential, decodeCredentialBasic, decodeCredentialX509, decodeCredential, init_credential, externalSenderEncoder, encodeExternalSender, decodeExternalSender, init_externalSender, init_hash, init_optional, ciphersuites, ciphersuiteEncoder, encodeCiphersuite, decodeCiphersuite, ciphersuiteValues, init_ciphersuite, init_signature, protocolVersions, protocolVersionEncoder, encodeProtocolVersion, decodeProtocolVersion, init_protocolVersion, capabilitiesEncoder, encodeCapabilities, decodeCapabilities, init_capabilities, leafNodeSources, leafNodeSourceEncoder, encodeLeafNodeSource, decodeLeafNodeSource, init_leafNodeSource, lifetimeEncoder, encodeLifetime, decodeLifetime, defaultLifetime, init_lifetime, leafNodeDataEncoder, encodeLeafNodeData, decodeLeafNodeData, leafNodeInfoKeyPackageEncoder, encodeLeafNodeInfoKeyPackage, leafNodeInfoUpdateOmittedEncoder, encodeLeafNodeInfoUpdateOmitted, leafNodeInfoCommitOmittedEncoder, encodeLeafNodeInfoCommitOmitted, leafNodeInfoOmittedEncoder, encodeLeafNodeInfoOmitted, decodeLeafNodeInfoKeyPackage, decodeLeafNodeInfoUpdateOmitted, decodeLeafNodeInfoCommitOmitted, decodeLeafNodeInfoOmitted, leafNodeInfoUpdateEncoder, encodeLeafNodeInfoUpdate, leafNodeInfoCommitEncoder, encodeLeafNodeInfoCommit, leafNodeInfoEncoder, encodeLeafNodeInfo, decodeLeafNodeInfoUpdate, decodeLeafNodeInfoCommit, decodeLeafNodeInfo, leafNodeTBSEncoder, encodeLeafNodeTBS, leafNodeEncoder, encodeLeafNode, decodeLeafNode, decodeLeafNodeKeyPackage, decodeLeafNodeCommit, decodeLeafNodeUpdate, init_leafNode, keyPackageTBSEncoder, encodeKeyPackageTBS, decodeKeyPackageTBS, keyPackageEncoder, encodeKeyPackage, decodeKeyPackage, init_keyPackage, init_kdf, pskTypes, pskTypeEncoder, encodePskType, decodePskType, resumptionPSKUsages, resumptionPSKUsageEncoder, encodeResumptionPSKUsage, decodeResumptionPSKUsage, encodePskInfoExternal, encodePskInfoResumption, decodePskInfoResumption, pskInfoEncoder, encodePskInfo, decodePskInfo, pskIdEncoder, encodePskId, decodePskId, pskLabelEncoder, encodePskLabel, decodePskLabel, init_presharedkey, addEncoder, encodeAdd, decodeAdd, updateEncoder, encodeUpdate, decodeUpdate, removeEncoder, encodeRemove, decodeRemove, pskEncoder, encodePSK, decodePSK, reinitEncoder, encodeReinit, decodeReinit, externalInitEncoder, encodeExternalInit, decodeExternalInit, groupContextExtensionsEncoder, encodeGroupContextExtensions, decodeGroupContextExtensions, proposalAddEncoder, encodeProposalAdd, proposalUpdateEncoder, encodeProposalUpdate, proposalRemoveEncoder, encodeProposalRemove, proposalPSKEncoder, encodeProposalPSK, proposalReinitEncoder, encodeProposalReinit, proposalExternalInitEncoder, encodeProposalExternalInit, proposalGroupContextExtensionsEncoder, encodeProposalGroupContextExtensions, proposalCustomEncoder, encodeProposalCustom, proposalEncoder, encodeProposal, decodeProposalAdd, decodeProposalUpdate, decodeProposalRemove, decodeProposalPSK, decodeProposalReinit, decodeProposalExternalInit, decodeProposalGroupContextExtensions, decodeProposal, init_proposal, proposalOrRefTypes, proposalOrRefTypeEncoder, encodeProposalOrRefType, decodeProposalOrRefType, proposalOrRefProposalEncoder, encodeProposalOrRefProposal, proposalOrRefProposalRefEncoder, encodeProposalOrRefProposalRef, proposalOrRefEncoder, encodeProposalOrRef, decodeProposalOrRef, init_proposalOrRefType, init_hpke, groupContextEncoder, encodeGroupContext, decodeGroupContext, init_groupContext, nodeTypes, nodeTypeEncoder, encodeNodeType, decodeNodeType, init_nodeType, parentNodeEncoder, encodeParentNode, decodeParentNode, init_parentNode, init_treemath, nodeEncoder, encodeNode, decodeNode, ratchetTreeEncoder, encodeRatchetTree, decodeRatchetTree, init_ratchetTree, leafNodeHashInputEncoder, encodeLeafNodeHashInput, decodeLeafNodeHashInput, parentNodeHashInputEncoder, encodeParentNodeHashInput, decodeParentNodeHashInput, treeHashInputEncoder, encodeTreeHashInput, decodeTreeHashInput, init_treeHash, parentHashInputEncoder, encodeParentHashInput, decodeParentHashInput, init_parentHash, hpkeCiphertextEncoder, encodeHpkeCiphertext, decodeHpkeCiphertext, init_hpkeCiphertext, updatePathNodeEncoder, encodeUpdatePathNode, decodeUpdatePathNode, updatePathEncoder, encodeUpdatePath, decodeUpdatePath, init_updatePath, commitEncoder, encodeCommit, decodeCommit, init_commit, contentTypes, contentTypeEncoder, encodeContentType, decodeContentType, init_contentType, wireformats, wireformatEncoder, encodeWireformat, decodeWireformat, init_wireformat, senderTypes, senderTypeEncoder, encodeSenderType, decodeSenderType, senderEncoder, encodeSender, decodeSender, reuseGuardEncoder, encodeReuseGuard, decodeReuseGuard, senderDataEncoder, encodeSenderData, decodeSenderData, senderDataAADEncoder, encodeSenderDataAAD, decodeSenderDataAAD, init_sender, framedContentApplicationDataEncoder, encodeFramedContentApplicationData, framedContentProposalDataEncoder, encodeFramedContentProposalData, framedContentCommitDataEncoder, encodeFramedContentCommitData, framedContentInfoEncoder, encodeFramedContentInfo, decodeFramedContentApplicationData, decodeFramedContentProposalData, decodeFramedContentCommitData, decodeFramedContentInfo, framedContentEncoder, encodeFramedContent, decodeFramedContent, senderInfoEncoder, encodeSenderInfo, framedContentTBSEncoder, encodeFramedContentTBS, encodeFramedContentAuthDataContent, encodeFramedContentAuthDataCommit, framedContentAuthDataEncoder, encodeFramedContentAuthData, decodeFramedContentAuthDataCommit, init_framedContent, authenticatedContentEncoder, encodeAuthenticatedContent, decodeAuthenticatedContent, authenticatedContentTBMEncoder, encodeAuthenticatedContentTBM, init_authenticatedContent, publicMessageInfoEncoder, encodePublicMessageInfo, publicMessageEncoder, encodePublicMessage, decodePublicMessage, init_publicMessage, init_messageProtectionPublic, init_externalProposal, requiredCapabilitiesEncoder, encodeRequiredCapabilities, decodeRequiredCapabilities, init_requiredCapabilities, defaultAuthenticationService, init_authenticationService, defaultPaddingConfig, init_paddingConfig, defaultKeyPackageEqualityConfig, init_keyPackageEqualityConfig, defaultLifetimeConfig, init_lifetimeConfig, defaultKeyRetentionConfig, init_keyRetentionConfig, groupInfoTBSEncoder, encodeGroupInfoTBS, decodeGroupInfoTBS, groupInfoEncoder, encodeGroupInfo, decodeGroupInfo, init_groupInfo, keyScheduleEncoder, encodeKeySchedule, decodeKeySchedule, init_keySchedule, generationSecretEncoder, decodeGenerationSecret, secretTreeNodeEncoder, decodeSecretTreeNode, secretTreeEncoder, decodeSecretTree, init_secretTree, confirmedTranscriptHashInputEncoder, encodeConfirmedTranscriptHashInput, decodeConfirmedTranscriptHashInput, init_transcriptHash, groupSecretsEncoder, encodeGroupSecrets, decodeGroupSecrets, init_groupSecrets, encryptedGroupSecretsEncoder, encodeEncryptedGroupSecrets, decodeEncryptedGroupSecrets, welcomeEncoder, encodeWelcome, decodeWelcome, init_welcome, init_pathSecrets, privateKeyPathEncoder, decodePrivateKeyPath, init_privateKeyPath, proposalWithSenderEncoder, decodeProposalWithSender, unappliedProposalsEncoder, decodeUnappliedProposals, init_unappliedProposals, emptyPskIndex, init_pskIndex, init_addToMap, defaultClientConfig, init_clientConfig, init_array, stringEncoder, encodeString, decodeString, init_string, activeEncoder, suspendedPendingReinitEncoder, removedFromGroupEncoder, groupActiveStateEncoder, decodeGroupActiveState, init_groupActiveState, epochReceiverDataEncoder, decodeEpochReceiverData, init_epochReceiverData, groupStateEncoder, encodeGroupState, decodeGroupState, groupStateEncoderWithoutTree, encodeGroupStateWithoutTree, emptyProposals, init_clientState, privateMessageEncoder, encodePrivateMessage, decodePrivateMessage, privateContentAADEncoder, encodePrivateContentAAD, decodePrivateContentAAD, init_privateMessage, init_messageProtection, init_createMessage, init_createCommit, init_processMessages, init_makeHashImpl, HpkeError, InvalidParamError, SerializeError, DeserializeError, EncapError, DecapError, ExportError, SealError, OpenError, MessageLimitReachedError, DeriveKeyPairError, NotSupportedError, init_errors, dntGlobals, dntGlobalThis, init_dnt_shims, NativeAlgorithm, init_algorithm, Mode, KemId, KdfId, AeadId, init_identifiers, INPUT_LENGTH_LIMIT, INFO_LENGTH_LIMIT, MINIMUM_PSK_LENGTH, EMPTY, BYTE_TO_BIGINT_256, init_consts, SUITE_ID_HEADER_KEM, init_kemInterface, HPKE_VERSION, HkdfNative, HkdfSha256Native, HkdfSha384Native, HkdfSha512Native, init_hkdf, isCryptoKeyPair, init_misc, LABEL_EAE_PRK, LABEL_SHARED_SECRET, Dhkem, init_dhkem, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, init_dhkemPrimitives, Bignum, init_bignum, LABEL_CANDIDATE, ORDER_P_256, ORDER_P_384, ORDER_P_521, PKCS8_ALG_ID_P_256, PKCS8_ALG_ID_P_384, PKCS8_ALG_ID_P_521, EC_P_256_PARAMS, EC_P_384_PARAMS, EC_P_521_PARAMS, Ec, init_ec, init_xCryptoKey, init_xCurve, init_hybridkem, AEAD_USAGES, init_aeadEncryptionContext, _endianTestBuffer, _endianTestBytes, isLE2, init_noble, init_hash2, _HMAC, hmac, init_hmac, init_md2, U32_MASK642, _32n2, init_u642, init_sha2, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, init_sha3, init_modular, init_curve, init_montgomery, init_mod, AesGcmContext, Aes128Gcm, Aes256Gcm, init_aesGcm, init_exportOnly, init_emitNotSupported, LABEL_SEC, ExporterContextImpl, RecipientExporterContextImpl, SenderExporterContextImpl, init_exporterContext, EncryptionContextImpl, init_encryptionContext, __classPrivateFieldGet, __classPrivateFieldSet, _Mutex_locked, Mutex, init_mutex, __classPrivateFieldGet2, __classPrivateFieldSet2, _RecipientContextImpl_mutex, RecipientContextImpl, init_recipientContext, __classPrivateFieldGet3, __classPrivateFieldSet3, _SenderContextImpl_mutex, SenderContextImpl, init_senderContext, LABEL_BASE_NONCE, LABEL_EXP, LABEL_INFO_HASH, LABEL_KEY, LABEL_PSK_ID_HASH, LABEL_SECRET, SUITE_ID_HEADER_HPKE, CipherSuiteNative, init_cipherSuiteNative, DhkemP256HkdfSha256Native, DhkemP384HkdfSha384Native, DhkemP521HkdfSha512Native, init_dhkemNative, CipherSuite, DhkemP256HkdfSha256, DhkemP384HkdfSha384, DhkemP521HkdfSha512, HkdfSha256, HkdfSha384, HkdfSha512, init_native, ALG_NAME, PKCS8_ALG_ID_X25519, BASE_POINT_X25519, X25519, init_x25519, DhkemX25519HkdfSha256, init_dhkemX25519, PKCS8_ALG_ID_X448, init_x448, init_dhkemX448, init_mod2, init_hpke2, isLE3, wrapCipher, init_utils2, encodeStr, sigma16, sigma32, sigma16_32, sigma32_32, BLOCK_LEN, BLOCK_LEN32, MAX_COUNTER, U32_EMPTY, _XorStreamPRG, createPRG, init_arx, Poly1305, poly1305, init_poly1305, chacha_exports, chacha20orig, chacha20, xchacha20, chacha8, chacha12, ZEROS16, updatePadded, ZEROS32, _poly1305_aead, chacha20poly1305, xchacha20poly1305, rngChacha20, rngChacha8, init_chacha, init_makeAead, init_makeKdfImpl, init_makeDhKem, init_makeHpke, defaultRng, init_rng, crypto3, init_cryptoNode, isLE4, swap32IfBE3, hasHexBuiltin2, hexes2, asciis, Hash, init_utils3, HashMD3, SHA256_IV3, SHA384_IV3, SHA512_IV3, init_md3, U32_MASK643, _32n3, shrSH3, shrSL3, rotrSH3, rotrSL3, rotrBH3, rotrBL3, rotlSH2, rotlSL2, rotlBH2, rotlBL2, add3L3, add3H3, add4L3, add4H3, add5L3, add5H3, init_u643, SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, SHA384, sha2563, sha5122, sha3842, init_sha22, _0n2, _1n2, isPosBig, bitMask, notImplemented, init_utils4, _0n3, _1n3, _2n2, _3n, _4n, _5n, _7n2, _8n, _9n, _16n, isNegativeLE, FIELD_FIELDS, init_modular2, _0n4, _1n4, pointPrecomputes, pointWindowSizes, wNAF, init_curve2, _0n5, _1n5, _2n3, _8n2, PrimeEdwardsPoint, init_edwards, os2ip, _DST_scalar, init_hash_to_curve, _0n6, _1n6, _2n4, init_montgomery2, ed25519_exports, _0n7, _1n7, _2n5, _3n2, _5n2, _8n3, ed25519_CURVE_p, ed25519_CURVE, ED25519_SQRT_M1, Fp, Fn, ed25519Defaults, ed25519, ed25519ctx, ed25519ph, x25519, ELL2_C1, ELL2_C2, ELL2_C3, ELL2_C1_EDWARDS, ed25519_hasher, SQRT_M1, SQRT_AD_MINUS_ONE, INVSQRT_A_MINUS_D, ONE_MINUS_D_SQ, D_MINUS_ONE_SQ, invertSqrt, MAX_255B, bytes255ToNumberLE, _RistrettoPoint, ristretto255, ristretto255_hasher, ED25519_TORSION_SUBGROUP, edwardsToMontgomery, RistrettoPoint, hashToCurve, encodeToCurve, hashToRistretto255, hash_to_ristretto255, init_ed25519, _0n8, _1n8, _2n6, _7n3, _256n2, _0x71n2, SHA3_PI2, SHA3_ROTL2, _SHA3_IOTA2, IOTAS2, SHA3_IOTA_H2, SHA3_IOTA_L2, rotlH, rotlL, Keccak, genShake, shake2562, init_sha32, ed448_exports, ed448_CURVE, E448_CURVE, shake256_114, shake256_64, _1n9, _2n7, _3n3, _4n2, _11n, _22n, _44n, _88n, _223n, Fp2, Fn2, Fp448, Fn448, ED448_DEF, ed448, ed448ph, E448, x448, ELL2_C12, ELL2_J, ed448_hasher, ONE_MINUS_D, ONE_MINUS_TWO_D, SQRT_MINUS_D, INVSQRT_MINUS_D, invertSqrt2, _DecafPoint, decaf448, decaf448_hasher, ED448_TORSION_SUBGROUP, DecafPoint, hashToCurve2, encodeToCurve2, hashToDecaf448, hash_to_decaf448, edwardsToMontgomery2, init_ed448, HMAC, hmac2, init_hmac2, divNearest, DERErr, DER, _0n9, _1n10, _2n8, _3n4, _4n3, init_weierstrass, init_shortw_utils, nist_exports, p256_CURVE, p384_CURVE, p521_CURVE, Fp256, Fp384, Fp521, p256, p256_hasher, p384, p384_hasher, p521, secp256r1, secp384r1, secp521r1, p521_hasher, init_nist, init_makeNobleSignatureImpl, defaultCryptoProvider, init_provider, init_getCiphersuiteImpl, init_resumption, SHA256_K2, SHA256_W2, SHA2_32B, _SHA256, K5122, SHA512_Kh2, SHA512_Kl2, SHA512_W_H2, SHA512_W_L2, SHA2_64B, _SHA512, _SHA384, sha2564, sha5123, sha3843, init_sha23, _HMAC2, hmac3, init_hmac3, init_makeHashImpl2, init_makeNobleSignatureImpl2, BLOCK_SIZE, ZEROS162, ZEROS322, POLY, mul2, swapLE, estimateWindow, GHASH, Polyval, ghash, polyval, init_polyval, BLOCK_SIZE2, BLOCK_SIZE32, EMPTY_BLOCK, POLY2, sbox, rotr32_8, rotl32_8, tableEncoding, xPowers, gcm, _CMAC, cmac, init_aes, init_makeAead2, init_makeKdfImpl2, init_makeDhKem2, init_makeHpke2, init_rng2, nobleCryptoProvider, init_provider2, mlsPublicMessageEncoder, encodeMlsPublicMessage, mlsWelcomeEncoder, encodeMlsWelcome, mlsPrivateMessageEncoder, encodeMlsPrivateMessage, mlsGroupInfoEncoder, encodeMlsGroupInfo, mlsKeyPackageEncoder, encodeMlsKeyPackage, mlsMessageContentEncoder, encodeMlsMessageContent, decodeMlsMessageContent, mlsMessageEncoder, encodeMlsMessage, decodeMlsMessage, init_message, greaseValues, defaultGreaseConfig, init_grease, init_defaultCapabilities, init_src, DEFAULT_CIPHERSUITE, MLSGroupManager, init_mls_group, DOMAIN, NONCE_BYTES3, init_owner_sync, init_mls_delivery_order, init_mls_presend_epoch, dist_exports, init_dist2, DIR_MODE, FILE_MODE, init_secure_file, SYNC_LOCK_STALE_MS, pendingKpPath, DECRYPTED_IDS_FILE, init_mls_state, init_mls_kp_pool, PACKAGE, FALLBACK, MAX_LEN, DISALLOWED, init_client_version, CredentialStore, init_credential_store, init_crypto_helpers, STATE_FILE, LEGACY_STATE_FILE, init_state, ACTIVATION_DOMAIN, UUID_RE2, init_transport2, A2ALogGate, init_a2a_log_gate, NOT_A_MEMBER_DETAIL, init_mls_membership_probe, FIRST_DIRTY_DELAY_MS, RETRY_BASE_DELAYS_MS, MAX_RETRY_DELAY_MS, JITTER_FRACTION, HistoryBackupScheduler, init_history_backup_scheduler, FILE_MODE2, init_history_recovery_file, TENANT_ID_PATTERN, DIR_MODE2, FILE_MODE3, HISTORY_RECOVERY_VERIFY_TIMEOUT_MS, VERIFY_TIMEOUT_MESSAGE, HistoryRecoveryVerificationTimeoutError, init_history_recovery_code, ACTIONS, init_decision_reply, KP_BACKOFF_INITIAL_MS, KP_BACKOFF_MAX_MS, KP_RACE_RETRY_MS, KP_RACE_RETRY_LIMIT, consoleLogger, short, WelcomeKeyPackageBackoff, init_welcome_kp_backoff, history_backup_client_exports, HISTORY_RESTORE_TIMEOUT_MS, HISTORY_RESTORE_RESPONSE_MAX_BYTES, HISTORY_ENVELOPE_MIN_BYTES, HISTORY_AAD_PREFIX, UUID_RE3, GENERATION_RESPONSE_KEYS, utf8Encoder, utf8Decoder, HistoryBackupClient, init_history_backup_client, openclaw_compat_exports, defaultImporter, HEARTBEAT_CANDIDATES, _heartbeatFn, init_openclaw_compat, TOOL_INVOKE_SPAN_NAME, UNCLASSIFIED_ERROR, KNOWN_TOOL_ERROR_CODES, KNOWN_CODES, CLASS_NAME_RE, TOOL_NAME_RE, ERROR_TEXT_CODES, _conversation, init_tool_telemetry, http_handlers_exports, init_http_handlers, mcp_proxy_helpers_exports, init_mcp_proxy_helpers, workspace_handlers_exports, MAX_FILE_SIZE, init_workspace_handlers, ROOM_AGENT_TYPES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, UUID_RE4, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, HISTORY_RESTORE_TIMEOUT_MS2, ROOM_ROSTER_REFRESH_TIMEOUT_MS, HISTORY_UPLOAD_TIMEOUT_MS, CANONICAL_TIMESTAMP_RE, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, _turnConversation, PERSON_INVOLVED_WINDOW_MS, ATTESTED_INBOUND_MAX, UNMAPPED_RECONCILE_COOLDOWN_MS, TOPIC_ID_RE, ROOM_FULFIL_COOLDOWN_MS, SecureChannel, init_channel, init_types, DEFAULT_API_URL, DEFAULT_HTTP_PORT, init_account_config, init_lifecycle, _ocRuntime, _channels, agentVaultPlugin, init_openclaw_plugin, init_gateway_send, init_llm_response_parser, OPENROUTER_PRICING, init_llm_pricing_openrouter, LEGACY_PRICING, PRICING, init_llm_cost, traceStore, init_fetch_interceptor, init_tool_audit, init_harness_compat, managedRoutesRequested, init_openclaw_entry, util, objectUtil, ZodParsedType, getParsedType, init_util, ZodIssueCode, ZodError, init_ZodError, errorMap, en_default, init_en, overrideErrorMap, init_errors2, makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, init_parseUtil, init_typeAliases, errorUtil, init_errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, init_types2, init_external, init_v3, util_exports, Cached, EVALUATING, captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, highSurrogate, Class, installing, broke, breaker, CONSTANT_CATCH, init_util2, _a2, _zodDesc, _E, $ZodAsyncError, $ZodEncodeError, globalConfig, init_core, _messageDesc, _issuesDesc, _installedToString, initializer, $ZodError, $ZodRealError, init_errors3, _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, COMPILE_INVALID, COMPILE_FALLBACK, validate, validateAsync, _encode, _decode, _encodeAsync, _decodeAsync, _safeEncode, _safeDecode, _safeEncodeAsync, _safeDecodeAsync, init_parse, cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, dateSource, date, anyString, integer, number, boolean, _null, lowercase, uppercase, init_regexes, $ZodCheck, _whenHasLength, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite, init_checks, Doc, init_doc, version, init_versions, $ZodType, toStandardResult, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT, URL_UNPARSEABLE, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodNull, $ZodUnknown, $ZodNever, arraySize, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodRecord, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodPreprocess, $ZodReadonly, $ZodCustom, init_schemas, $ZodCyclicError, STATE, NO_ISSUES, recursive, NONE, ASSUMED, PROVEN, handoff, open4, memo, init_memoizer, error, init_en2, init_locales, _a3, $ZodRegistry, globalRegistry, init_registries, init_compile, init_api, FOLDABLE_KEYS, UNION_KEYS, createToJSONSchemaMethod, createStandardJSONSchemaMethod, init_to_json_schema, narrowMin, narrowMax, narrowBoth, addDivisor, addPattern, intersectMime, setFormat, minContributor, maxContributor, formatContributor, contributors, formatMap, exactPatterns, exactPattern, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, pendingRecords, recordProcessor, nullableProcessor, nonoptionalProcessor, UNREPRESENTABLE_DEFAULT, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors, init_json_schema_processors, init_json_schema, init_core2, init_parse2, ZodMiniType, ZodMiniObject, init_schemas2, init_checks2, init_iso, init_coerce, init_external2, init_v4_mini, init_zod_compat, init_checks3, _installedErrorProtos, initializer2, ZodRealError, init_errors4, parse2, parseAsync2, safeParse3, safeParseAsync3, encode3, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2, init_parse3, ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodNull2, ZodUnknown2, ZodNever2, ZodArray2, ZodObject2, ZodUnion2, ZodDiscriminatedUnion2, ZodIntersection2, ZodRecord2, ZodEnum2, ZodLiteral2, ZodTransform, ZodOptional2, ZodExactOptional, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodCatch2, ZodPipe, ZodPreprocess, ZodReadonly2, ZodCustom, init_schemas3, ZodFirstPartyTypeKind2, init_compat, iso_exports2, init_iso2, init_coerce2, init_external3, init_classic, init_v4, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, JSONRPC_VERSION, AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskCreationParamsSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResultResponseSchema, isJSONRPCResultResponse, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, isInitializeRequest, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, McpError, UrlElicitationRequiredError, init_types3, init_interfaces, ignoreOverride, defaultOptions, getDefaultOptions, init_Options, getRefs, init_Refs, init_errorMessages, getRelativePath, init_getRelativePath, init_any, init_array2, init_bigint, init_boolean, init_branded, parseCatchDef, init_catch, integerDateParser, init_date, init_default, init_effects, init_enum, isJsonSchema7AllOfType, init_intersection, init_literal, emojiRegex2, zodPatterns, ALPHA_NUMERIC, init_string2, init_record, init_map, init_nativeEnum, init_never, init_null, primitiveMappings, asAnyOf, init_union, init_nullable, init_number2, init_object, parseOptionalDef, init_optional2, parsePipelineDef, init_pipeline, init_promise, init_set, init_tuple, init_undefined, init_unknown, parseReadonlyDef, init_readonly, selectParser, init_selectParser, get$ref, addMeta, init_parseDef, init_parseTypes, zodToJsonSchema, init_zodToJsonSchema, init_esm, init_zod_json_schema_compat, DEFAULT_REQUEST_TIMEOUT_MSEC, Protocol, init_protocol, require_code, require_scope, require_codegen, require_util, require_names, require_errors, require_boolSchema, require_rules, require_applicability, require_dataType, require_defaults, require_code2, require_keyword, require_subschema, require_fast_deep_equal, require_json_schema_traverse, require_resolve, require_validate, require_validation_error, require_ref_error, require_compile, require_data, require_utils, require_schemes, require_fast_uri, require_uri, require_core, require_id, require_ref, require_core2, require_limitNumber, require_multipleOf, require_ucs2length, require_limitLength, require_pattern, require_limitProperties, require_required, require_limitItems, require_equal, require_uniqueItems, require_const, require_enum, require_validation, require_additionalItems, require_items, require_prefixItems, require_items2020, require_contains, require_dependencies, require_propertyNames, require_additionalProperties, require_properties, require_patternProperties, require_not, require_anyOf, require_oneOf, require_allOf, require_if, require_thenElse, require_applicator, require_format, require_format2, require_metadata, require_draft7, require_types, require_discriminator, require_json_schema_draft_07, require_ajv, require_formats, require_limit, require_dist, import_ajv, import_ajv_formats, AjvJsonSchemaValidator, init_ajv_provider, ExperimentalServerTasks, init_server, init_helpers, Server, init_server2, COMPLETABLE_SYMBOL, McpZodTypeKind, init_completable, init_uriTemplate, TOOL_NAME_REGEX, init_toolNameValidation, ExperimentalMcpServerTasks, init_mcp_server, init_zod, McpServer, EMPTY_OBJECT_JSON_SCHEMA, EMPTY_COMPLETION_RESULT, init_mcp, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, init_dist22, require_content_type, import_content_type, init_mediaType, DEFAULT_MAX_REQUEST_BODY_SIZE, MAX_BATCH_SIZE, init_requestBody, DEFAULT_SSE_KEEP_ALIVE_MS, MAX_TIMER_DELAY_MS, init_sseKeepAlive, WebStandardStreamableHTTPServerTransport, init_webStandardStreamableHttp, StreamableHTTPServerTransport, init_streamableHttp, AgentVaultMcpServer, init_mcp_server2, init_mcp_handlers, init_skill_manifest, init_skill_invoker, spanBuffer, init_skill_telemetry, PolicyEnforcer, init_policy_enforcer, TURN_FAILURE_CODES, CODES, TurnFailure, NOTICE_RE, init_turn_failure, VERSION, init_index;
17834
17876
  var init_dist = __esm({
17835
17877
  async "../plugin/dist/index.js"() {
@@ -103734,146 +103776,7 @@ function seedFenceCredential(opts) {
103734
103776
  }
103735
103777
 
103736
103778
  // src/grok-session.ts
103737
- var GrokSession = class {
103738
- constructor(driver2, opts = {}) {
103739
- this.driver = driver2;
103740
- this.opts = opts;
103741
- }
103742
- driver;
103743
- opts;
103744
- queue = [];
103745
- running = false;
103746
- invalidated = false;
103747
- /** The message whose turn is in flight, or null between turns. Null is a
103748
- * DISTINCT state from "a message that carries no reply sink" — conflating
103749
- * them is what let a post-turn say fall through to the session-level sink. */
103750
- current = null;
103751
- saidThisTurn = false;
103752
- drain = Promise.resolve();
103753
- push(text, reply, opts) {
103754
- if (this.invalidated) {
103755
- this.log("push on invalidated session; DROPPED");
103756
- return;
103757
- }
103758
- this.queue.push({
103759
- text,
103760
- reply,
103761
- autoReplyOnText: opts?.replyExpected ?? opts?.autoReplyOnText,
103762
- sayAllowed: opts?.replyExpected ?? true
103763
- });
103764
- if (!this.running) this.drain = this.run();
103765
- }
103766
- /** Hand this to startRoomMcpServer({ onSay }). The behaviour is stable for
103767
- * the life of the session — the per-message routing happens HERE, not in
103768
- * the listener — but each call returns a NEW closure; do not rely on
103769
- * identity (e.g. for `===` comparisons or `removeListener`-style APIs). */
103770
- sayHandler() {
103771
- return (text) => {
103772
- try {
103773
- if (this.invalidated || !this.current) {
103774
- this.log(`say arrived with no turn in flight; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
103775
- return;
103776
- }
103777
- if (!this.current.sayAllowed) {
103778
- this.log(
103779
- `say during a turn this agent does not owe (no @mention) \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 80))}`
103780
- );
103781
- return;
103782
- }
103783
- this.saidThisTurn = true;
103784
- const sink = this.current.reply ?? this.opts.onSay;
103785
- if (!sink) {
103786
- this.log(`say had no sink for this turn; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
103787
- return;
103788
- }
103789
- void Promise.resolve(sink(text)).catch(
103790
- (e) => this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`)
103791
- );
103792
- } catch (e) {
103793
- this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`);
103794
- }
103795
- };
103796
- }
103797
- /** Revoke output and future work BEFORE asynchronous process cleanup. */
103798
- invalidate() {
103799
- this.invalidated = true;
103800
- this.current = null;
103801
- this.queue = [];
103802
- }
103803
- /** Resolves when the queue is empty. For tests and shutdown. */
103804
- async idle() {
103805
- await this.drain;
103806
- }
103807
- log(m2) {
103808
- try {
103809
- this.opts.log?.(`[grok-bridge] ${m2}`);
103810
- } catch {
103811
- }
103812
- }
103813
- async run() {
103814
- this.running = true;
103815
- try {
103816
- while (!this.invalidated && this.queue.length) {
103817
- const item = this.queue.shift();
103818
- this.current = item;
103819
- this.saidThisTurn = false;
103820
- try {
103821
- const prompt = this.opts.identity ? `${this.opts.identity}
103822
-
103823
- ${item.text}` : item.text;
103824
- const result = await this.driver.deliver(prompt);
103825
- if (!this.invalidated) await this.maybeFallback(item, result);
103826
- } catch (e) {
103827
- const wasInvalidated = this.invalidated;
103828
- this.invalidate();
103829
- this.log(`turn failed: ${e instanceof Error ? e.message : String(e)}`);
103830
- if (!wasInvalidated) {
103831
- try {
103832
- await this.opts.onFatal?.(e);
103833
- } catch (cleanupError) {
103834
- this.log(`fatal cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
103835
- }
103836
- }
103837
- } finally {
103838
- this.current = null;
103839
- }
103840
- }
103841
- } finally {
103842
- this.running = false;
103843
- }
103844
- }
103845
- /**
103846
- * #416: when the owner expects an answer and the model produced prose but
103847
- * never called the say tool, send the prose rather than dropping it.
103848
- *
103849
- * ONLY SAFE BECAUSE `spoke` IS REAL. Over a stdio MCP child the say never
103850
- * reaches the driver, so `spoke` is permanently false and this would fire on
103851
- * every turn — double-posting everything the agent said. It depends on the
103852
- * in-process HTTP listener.
103853
- */
103854
- async maybeFallback(item, result) {
103855
- const alreadySpoke = this.saidThisTurn || result.spoke;
103856
- const text = result.text.trim();
103857
- if (!item.autoReplyOnText) {
103858
- if (!alreadySpoke && text) {
103859
- this.log(
103860
- `turn produced ${text.length} chars of prose but this turn does not authorise a plain-text reply \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 160))}`
103861
- );
103862
- }
103863
- return;
103864
- }
103865
- if (alreadySpoke) return;
103866
- if (!text) return;
103867
- const sink = item.reply ?? this.opts.onSay;
103868
- if (!sink) return;
103869
- try {
103870
- await sink(text);
103871
- this.log("delivered assistant prose via the auto-reply fallback");
103872
- } catch (e) {
103873
- this.log(`fallback send failed: ${e instanceof Error ? e.message : String(e)}`);
103874
- }
103875
- }
103876
- };
103779
+ await init_dist();
103877
103780
 
103878
103781
  // src/acp-connection.ts
103879
103782
  var AcpChildDied = class extends Error {
@@ -103898,6 +103801,20 @@ var AcpTimeout = class extends Error {
103898
103801
  method;
103899
103802
  ms;
103900
103803
  };
103804
+ var AcpRpcError = class extends Error {
103805
+ constructor(method, error2) {
103806
+ super(`${method}: ${JSON.stringify(error2)}`);
103807
+ this.method = method;
103808
+ this.name = "AcpRpcError";
103809
+ this.rpcCode = error2?.code;
103810
+ this.rpcMessage = error2?.message;
103811
+ this.rpcData = error2?.data;
103812
+ }
103813
+ method;
103814
+ rpcCode;
103815
+ rpcMessage;
103816
+ rpcData;
103817
+ };
103901
103818
  var AcpConnection = class {
103902
103819
  constructor(child, opts) {
103903
103820
  this.child = child;
@@ -104051,7 +103968,7 @@ var AcpConnection = class {
104051
103968
  return;
104052
103969
  }
104053
103970
  const p2 = this.clearPending(msg.id);
104054
- if (msg.error) p2.reject(new Error(`${p2.method}: ${JSON.stringify(msg.error)}`));
103971
+ if (msg.error) p2.reject(new AcpRpcError(p2.method, msg.error));
104055
103972
  else p2.resolve(msg.result);
104056
103973
  return;
104057
103974
  }
@@ -104059,6 +103976,287 @@ var AcpConnection = class {
104059
103976
  }
104060
103977
  };
104061
103978
 
103979
+ // src/turn-failure.ts
103980
+ var METHOD_NOT_FOUND = -32601;
103981
+ var PROVIDER_STATUS_RE = /\((\d{3})\) from https?:\/\//;
103982
+ var AUTH_RE = /Invalid or expired credentials/;
103983
+ var MODEL_UNAVAILABLE_RE = /is not in your available models/;
103984
+ var NETWORK_RE = /error sending request|dns error|tcp connect error/;
103985
+ function failureText(err) {
103986
+ let text = "";
103987
+ if (err instanceof AcpRpcError) {
103988
+ const data = err.rpcData;
103989
+ const parts = [typeof err.rpcMessage === "string" ? err.rpcMessage : ""];
103990
+ if (typeof data === "string") parts.push(data);
103991
+ else if (data !== void 0) {
103992
+ try {
103993
+ parts.push(JSON.stringify(data));
103994
+ } catch {
103995
+ }
103996
+ }
103997
+ text = parts.join("\n");
103998
+ } else if (err instanceof Error) {
103999
+ text = err.message;
104000
+ }
104001
+ return text.slice(0, 16 * 1024);
104002
+ }
104003
+ function classifyGrokFailure(err) {
104004
+ if (err instanceof AcpTimeout || err instanceof AcpChildDied) return "model_error";
104005
+ if (err instanceof AcpRpcError && err.rpcCode === METHOD_NOT_FOUND) return "ai_tool_unsupported";
104006
+ const text = failureText(err);
104007
+ if (!text) return "model_error";
104008
+ const status = PROVIDER_STATUS_RE.exec(text)?.[1];
104009
+ if (status === "401") return "provider_auth_failed";
104010
+ if (status === "402") return "provider_billing";
104011
+ if (status === "429") return "model_rate_limited";
104012
+ if (status !== void 0 && status.startsWith("5")) return "provider_unreachable";
104013
+ if (status !== void 0) return "model_error";
104014
+ if (AUTH_RE.test(text)) return "provider_auth_failed";
104015
+ if (MODEL_UNAVAILABLE_RE.test(text)) return "model_unavailable";
104016
+ if (NETWORK_RE.test(text)) return "provider_unreachable";
104017
+ return "model_error";
104018
+ }
104019
+ function grokFatalLine(err) {
104020
+ const exit = grokFailureExitCode(err);
104021
+ const name = err instanceof Error && /^[A-Za-z][A-Za-z0-9_]{0,47}$/.test(err.name) ? err.name : "unknown";
104022
+ let line = `code=${classifyGrokFailure(err)} exit=${exit ?? "none"} error=${name}`;
104023
+ if (err instanceof AcpRpcError) {
104024
+ line += ` method=${/^[a-z/_]{1,40}$/.test(err.method) ? err.method : "unknown"}`;
104025
+ if (typeof err.rpcCode === "number" && Number.isInteger(err.rpcCode)) line += ` rpc=${err.rpcCode}`;
104026
+ }
104027
+ return line;
104028
+ }
104029
+ function mayCarryProviderText(err) {
104030
+ if (err instanceof AcpRpcError || err instanceof AcpChildDied || err instanceof AcpTimeout) return true;
104031
+ const text = err instanceof Error ? err.message : typeof err === "string" ? err : "";
104032
+ return PROVIDER_STATUS_RE.test(text) || AUTH_RE.test(text);
104033
+ }
104034
+ function grokFailureExitCode(err) {
104035
+ return err instanceof AcpChildDied && typeof err.code === "number" ? err.code : void 0;
104036
+ }
104037
+
104038
+ // src/grok-session.ts
104039
+ var NOTICE_TIMEOUT_MS = 1e4;
104040
+ var GrokSession = class {
104041
+ constructor(driver2, opts = {}) {
104042
+ this.driver = driver2;
104043
+ this.opts = opts;
104044
+ }
104045
+ driver;
104046
+ opts;
104047
+ queue = [];
104048
+ running = false;
104049
+ invalidated = false;
104050
+ /** Review F3: the error that failed this session, once one has. */
104051
+ failure = void 0;
104052
+ /** The message whose turn is in flight, or null between turns. Null is a
104053
+ * DISTINCT state from "a message that carries no reply sink" — conflating
104054
+ * them is what let a post-turn say fall through to the session-level sink. */
104055
+ current = null;
104056
+ saidThisTurn = false;
104057
+ drain = Promise.resolve();
104058
+ push(text, reply, opts) {
104059
+ if (this.invalidated) {
104060
+ this.log("push on invalidated session; DROPPED");
104061
+ if (this.failure) {
104062
+ const failure2 = this.failure;
104063
+ void this.reportFailure(this.inbound(text, reply, opts), failure2, 0).catch(() => {
104064
+ });
104065
+ }
104066
+ return;
104067
+ }
104068
+ this.queue.push(this.inbound(text, reply, opts));
104069
+ if (!this.running) this.drain = this.run();
104070
+ }
104071
+ inbound(text, reply, opts) {
104072
+ return {
104073
+ text,
104074
+ reply,
104075
+ autoReplyOnText: opts?.replyExpected ?? opts?.autoReplyOnText,
104076
+ sayAllowed: opts?.replyExpected ?? true,
104077
+ conversation: opts?.conversation ?? { kind: "unknown" }
104078
+ };
104079
+ }
104080
+ /** Hand this to startRoomMcpServer({ onSay }). The behaviour is stable for
104081
+ * the life of the session — the per-message routing happens HERE, not in
104082
+ * the listener — but each call returns a NEW closure; do not rely on
104083
+ * identity (e.g. for `===` comparisons or `removeListener`-style APIs). */
104084
+ sayHandler() {
104085
+ return (text) => {
104086
+ try {
104087
+ if (this.invalidated || !this.current) {
104088
+ this.log(`say arrived with no turn in flight; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
104089
+ return;
104090
+ }
104091
+ if (!this.current.sayAllowed) {
104092
+ this.log(
104093
+ `say during a turn this agent does not owe (no @mention) \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 80))}`
104094
+ );
104095
+ return;
104096
+ }
104097
+ this.saidThisTurn = true;
104098
+ const sink = this.current.reply ?? this.opts.onSay;
104099
+ if (!sink) {
104100
+ this.log(`say had no sink for this turn; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
104101
+ return;
104102
+ }
104103
+ void Promise.resolve(sink(text)).catch(
104104
+ (e) => this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`)
104105
+ );
104106
+ } catch (e) {
104107
+ this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`);
104108
+ }
104109
+ };
104110
+ }
104111
+ /** Revoke output and future work BEFORE asynchronous process cleanup. */
104112
+ invalidate() {
104113
+ this.invalidated = true;
104114
+ this.current = null;
104115
+ this.queue = [];
104116
+ }
104117
+ /** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
104118
+ * fails, and it must be recorded and noticed before the process exits. */
104119
+ turnInFlight() {
104120
+ return !this.invalidated && this.current !== null;
104121
+ }
104122
+ /** Resolves when the queue is empty. For tests and shutdown. */
104123
+ async idle() {
104124
+ await this.drain;
104125
+ }
104126
+ log(m2) {
104127
+ try {
104128
+ this.opts.log?.(`[grok-bridge] ${m2}`);
104129
+ } catch {
104130
+ }
104131
+ }
104132
+ async run() {
104133
+ this.running = true;
104134
+ try {
104135
+ while (!this.invalidated && this.queue.length) {
104136
+ const item = this.queue.shift();
104137
+ this.current = item;
104138
+ this.saidThisTurn = false;
104139
+ const startedAt = Date.now();
104140
+ try {
104141
+ const prompt = this.opts.identity ? `${this.opts.identity}
104142
+
104143
+ ${item.text}` : item.text;
104144
+ const result = await this.driver.deliver(prompt);
104145
+ if (!this.invalidated) await this.maybeFallback(item, result);
104146
+ } catch (e) {
104147
+ const wasInvalidated = this.invalidated;
104148
+ const spokeThisTurn = this.saidThisTurn;
104149
+ const stranded = wasInvalidated ? [] : this.queue.slice();
104150
+ if (!wasInvalidated) this.failure = e ?? new Error("turn failed");
104151
+ this.invalidate();
104152
+ if (wasInvalidated) {
104153
+ this.log("turn_cancelled reason=shutdown");
104154
+ } else {
104155
+ try {
104156
+ await Promise.all([
104157
+ this.reportFailure(item, e, Date.now() - startedAt, spokeThisTurn),
104158
+ ...stranded.map((s2) => this.reportFailure(s2, e, 0))
104159
+ ]);
104160
+ } catch {
104161
+ this.log("turn_failed code=model_error exit=none report=failed");
104162
+ }
104163
+ try {
104164
+ await this.opts.onFatal?.(e);
104165
+ } catch (cleanupError) {
104166
+ this.log(`fatal cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
104167
+ }
104168
+ }
104169
+ } finally {
104170
+ this.current = null;
104171
+ }
104172
+ }
104173
+ } finally {
104174
+ this.running = false;
104175
+ }
104176
+ }
104177
+ /**
104178
+ * #1560: a failed turn is never silent. In this order:
104179
+ * 1. RECORD one `model_turn` span with the code (Health, Recent problems),
104180
+ * 2. LOG the code and exit status only (`turn_failed code=<c> exit=<n|none>`),
104181
+ * 3. NOTICE the chat with the owner sentence, only where the turn owed a
104182
+ * reply (`autoReplyOnText`: an un-addressed room turn stays silent, #1107;
104183
+ * an unattested 1:1 gets no plain text, #621). Only a 1:1 hears the
104184
+ * cause; a room or an unknown chat gets the bare sentence, because the
104185
+ * coded ones describe the owner's own provider account.
104186
+ * The notice is bounded so the fatal teardown that follows always runs.
104187
+ * Never throws.
104188
+ */
104189
+ async reportFailure(item, err, durationMs, alreadySpoke = false) {
104190
+ let code = "model_error";
104191
+ let exit;
104192
+ try {
104193
+ code = classifyGrokFailure(err);
104194
+ exit = grokFailureExitCode(err);
104195
+ } catch {
104196
+ }
104197
+ let sink;
104198
+ try {
104199
+ sink = this.opts.telemetry?.();
104200
+ } catch {
104201
+ sink = null;
104202
+ }
104203
+ reportModelTurnFailure(sink, { code, conversation: item.conversation, durationMs });
104204
+ this.log(`turn_failed code=${code} exit=${exit ?? "none"}`);
104205
+ if (!item.autoReplyOnText || !item.reply) return;
104206
+ let agentName;
104207
+ try {
104208
+ const n2 = this.opts.agentName;
104209
+ agentName = typeof n2 === "function" ? n2() : n2;
104210
+ } catch {
104211
+ agentName = void 0;
104212
+ }
104213
+ const notice = ownerNoticeFor(item.conversation.kind === "direct" && !alreadySpoke ? code : "model_error", {
104214
+ agentName: agentName ?? "",
104215
+ provider: "xAI"
104216
+ });
104217
+ let timer;
104218
+ const timedOut = new Promise((resolve4) => {
104219
+ timer = setTimeout(() => resolve4("timeout"), this.opts.noticeTimeoutMs ?? NOTICE_TIMEOUT_MS);
104220
+ });
104221
+ const sent = Promise.resolve().then(() => item.reply(notice, { notice: true })).then(() => "sent", () => "threw");
104222
+ const outcome = await Promise.race([sent, timedOut]);
104223
+ if (timer) clearTimeout(timer);
104224
+ if (outcome === "timeout") this.log("notice_failed reason=timeout");
104225
+ else if (outcome === "threw") this.log("notice_failed reason=sink_threw");
104226
+ }
104227
+ /**
104228
+ * #416: when the owner expects an answer and the model produced prose but
104229
+ * never called the say tool, send the prose rather than dropping it.
104230
+ *
104231
+ * ONLY SAFE BECAUSE `spoke` IS REAL. Over a stdio MCP child the say never
104232
+ * reaches the driver, so `spoke` is permanently false and this would fire on
104233
+ * every turn — double-posting everything the agent said. It depends on the
104234
+ * in-process HTTP listener.
104235
+ */
104236
+ async maybeFallback(item, result) {
104237
+ const alreadySpoke = this.saidThisTurn || result.spoke;
104238
+ const text = result.text.trim();
104239
+ if (!item.autoReplyOnText) {
104240
+ if (!alreadySpoke && text) {
104241
+ this.log(
104242
+ `turn produced ${text.length} chars of prose but this turn does not authorise a plain-text reply \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 160))}`
104243
+ );
104244
+ }
104245
+ return;
104246
+ }
104247
+ if (alreadySpoke) return;
104248
+ if (!text) return;
104249
+ const sink = item.reply ?? this.opts.onSay;
104250
+ if (!sink) return;
104251
+ try {
104252
+ await sink(text);
104253
+ this.log("delivered assistant prose via the auto-reply fallback");
104254
+ } catch (e) {
104255
+ this.log(`fallback send failed: ${e instanceof Error ? e.message : String(e)}`);
104256
+ }
104257
+ }
104258
+ };
104259
+
104062
104260
  // src/grok-room-plugin.ts
104063
104261
  import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync3, chmodSync as chmodSync4 } from "node:fs";
104064
104262
  import { join as join11 } from "node:path";
@@ -104311,10 +104509,6 @@ function handleMcpFrame(frame, onSay) {
104311
104509
  }
104312
104510
 
104313
104511
  // src/grok-room-http.ts
104314
- function redactCredential(text, secret) {
104315
- if (!secret) return text;
104316
- return text.split(secret).join("[redacted]");
104317
- }
104318
104512
  async function startRoomMcpServer(opts) {
104319
104513
  const seen = [];
104320
104514
  const token = randomBytes4(24).toString("base64url");
@@ -104582,9 +104776,19 @@ var ActiveTarget = class {
104582
104776
  }) {
104583
104777
  const t2 = this.target;
104584
104778
  const where = !t2 ? "nowhere" : t2.kind === "room" ? `room ${t2.roomId.slice(0, 8)}` : "1:1 owner";
104585
- return async (text) => {
104779
+ return async (text, opts) => {
104586
104780
  if (!t2) return;
104587
104781
  const startedAt = Date.now();
104782
+ if (opts?.notice) {
104783
+ try {
104784
+ if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
104785
+ else await sendDm(channel, t2, text);
104786
+ log(`notice sent to ${where}`);
104787
+ } catch (err) {
104788
+ log(`notice_failed code=${classifyToolError(err)}`);
104789
+ }
104790
+ return;
104791
+ }
104588
104792
  try {
104589
104793
  if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
104590
104794
  else await sendDm(channel, t2, text);
@@ -104730,7 +104934,8 @@ function wireBridge(channel, session2, target, opts = {}) {
104730
104934
 
104731
104935
  ${turnText}` : turnText, target.snapshotReply(channel, log), {
104732
104936
  autoReplyOnText: false,
104733
- replyExpected: owes
104937
+ replyExpected: owes,
104938
+ conversation: { kind: "room", id: e.roomId }
104734
104939
  });
104735
104940
  if (held.entries.length > 0) {
104736
104941
  roomContext.clear(e.roomId);
@@ -104746,7 +104951,11 @@ ${turnText}` : turnText, target.snapshotReply(channel, log), {
104746
104951
  log("inbound 1:1 DM from owner");
104747
104952
  }
104748
104953
  target.setDm(metadata?.conversationId, metadata?.conversationGroupId);
104749
- session2.push(text, target.snapshotReply(channel, log), { autoReplyOnText: ownerAttested });
104954
+ session2.push(text, target.snapshotReply(channel, log), {
104955
+ autoReplyOnText: ownerAttested,
104956
+ // #1560: names the failure span; a 1:1 is the one chat that hears the cause.
104957
+ conversation: metadata?.conversationId ? { kind: "direct", id: metadata.conversationId } : { kind: "direct" }
104958
+ });
104750
104959
  });
104751
104960
  }
104752
104961
 
@@ -104808,6 +105017,7 @@ async function reap(r2, opts = {}) {
104808
105017
 
104809
105018
  // src/index.ts
104810
105019
  var shuttingDown = false;
105020
+ var CHILD_EXIT_GRACE_MS = 15e3;
104811
105021
  var exiting = false;
104812
105022
  var driver;
104813
105023
  var session;
@@ -104850,7 +105060,7 @@ async function main() {
104850
105060
  const info = parseInfoFlags(process.argv.slice(2));
104851
105061
  if (info.showVersion || info.showHelp) {
104852
105062
  const version2 = buildClientVersion2(
104853
- true ? "0.4.32" : void 0
105063
+ true ? "0.4.33" : void 0
104854
105064
  );
104855
105065
  if (info.showVersion) printLine(version2);
104856
105066
  if (info.showHelp) {
@@ -104889,7 +105099,7 @@ async function main() {
104889
105099
  process.exit(0);
104890
105100
  }
104891
105101
  const cfg = loadConfig(process.env, process.argv.slice(2));
104892
- logLine(`[grok-bridge] version: ${true ? "0.4.32" : "dev"}`);
105102
+ logLine(`[grok-bridge] version: ${true ? "0.4.33" : "dev"}`);
104893
105103
  mkdirSync7(cfg.workspaceDir, { recursive: true });
104894
105104
  mkdirSync7(cfg.fenceHome, { recursive: true });
104895
105105
  seedFenceCredential({
@@ -104904,7 +105114,7 @@ async function main() {
104904
105114
  agentName: cfg.agentName,
104905
105115
  platform: "node",
104906
105116
  clientVersion: buildClientVersion2(
104907
- true ? "0.4.32" : void 0
105117
+ true ? "0.4.33" : void 0
104908
105118
  )
104909
105119
  });
104910
105120
  channelRef = channel;
@@ -104948,6 +105158,10 @@ async function main() {
104948
105158
  const msg = describeChildExit(shuttingDown, code, signal);
104949
105159
  if (!msg) return;
104950
105160
  logLine(`[grok-bridge] fatal: ${msg}`);
105161
+ if (session?.turnInFlight()) {
105162
+ setTimeout(() => void shutdown(1), CHILD_EXIT_GRACE_MS);
105163
+ return;
105164
+ }
104951
105165
  void shutdown(1);
104952
105166
  });
104953
105167
  child.stderr.on("error", () => {
@@ -104955,13 +105169,11 @@ async function main() {
104955
105169
  child.stdout.on("error", () => {
104956
105170
  });
104957
105171
  child.stderr.on("data", (b2) => {
104958
- let t2 = b2.toString();
104959
- if (mcp) {
104960
- t2 = redactCredential(t2, mcp.token);
104961
- t2 = redactCredential(t2, mcp.url);
104962
- }
104963
- t2 = t2.trim();
104964
- if (t2) logLine(`[grok-bridge] grok: ${t2.slice(0, 500)}`);
105172
+ const t2 = b2.toString().replace(/\x1b\[[0-9;]*m/g, "");
105173
+ if (!t2.trim()) return;
105174
+ const lines = t2.split("\n").filter((l2) => l2.trim()).length;
105175
+ const level2 = /\bERROR\b/.test(t2) ? "ERROR" : /\bWARN\b/.test(t2) ? "WARN" : null;
105176
+ logLine(`[grok-bridge] grok: stderr lines=${lines} bytes=${b2.length}${level2 ? ` level=${level2}` : ""}`);
104965
105177
  });
104966
105178
  driver = new GrokDriver(child, {
104967
105179
  cwd: cfg.workspaceDir,
@@ -104972,14 +105184,19 @@ async function main() {
104972
105184
  session = new GrokSession(driver, {
104973
105185
  log: (m2) => logLine(m2),
104974
105186
  identity,
104975
- onFatal: () => shutdown(1)
105187
+ onFatal: () => shutdown(1),
105188
+ // #1560: a failed turn records a `model_turn` span on the channel's
105189
+ // telemetry before onFatal runs. shutdown() -> reap() -> channel.stop()
105190
+ // flushes that buffer before closing the socket, so the span is not lost.
105191
+ telemetry: () => channel.telemetry,
105192
+ agentName: () => channel.ownDisplayName?.trim() || cfg.agentName
104976
105193
  });
104977
105194
  process.on("SIGTERM", () => void shutdown(0));
104978
105195
  process.on("SIGINT", () => void shutdown(0));
104979
105196
  try {
104980
105197
  await driver.start();
104981
105198
  } catch (err) {
104982
- logLine("[grok-bridge] fatal:", err);
105199
+ logLine(`[grok-bridge] fatal: grok did not start: ${grokFatalLine(err)}`);
104983
105200
  await shutdown(1);
104984
105201
  return;
104985
105202
  }
@@ -105005,7 +105222,8 @@ async function main() {
105005
105222
  await channel.start();
105006
105223
  }
105007
105224
  main().catch(async (err) => {
105008
- logLine("[grok-bridge] fatal:", err);
105225
+ if (mayCarryProviderText(err)) logLine(`[grok-bridge] fatal: ${grokFatalLine(err)}`);
105226
+ else logLine("[grok-bridge] fatal:", err);
105009
105227
  await shutdown(1);
105010
105228
  });
105011
105229
  /*! Bundled license information:
@@ -0,0 +1,37 @@
1
+ /**
2
+ * #1560 — name the cause of a failed Grok turn with a code from the shared
3
+ * closed set (`TURN_FAILURE_CODES` in the plugin). The code is all that leaves
4
+ * this file: the error's text is read here, in memory, and never kept,
5
+ * returned, logged or sent.
6
+ *
7
+ * WHAT THE CLI SENDS. A failed `session/prompt` comes back as a JSON-RPC error
8
+ * whose `data` carries the provider's HTTP answer, e.g. (observed live on
9
+ * ohtani, 2026-08-18):
10
+ *
11
+ * {"code":-32603,"message":"Internal error",
12
+ * "data":"Unauthorized (401) from https://cli-chat-proxy.grok.com/v1/responses: Invalid or expired credentials ..."}
13
+ *
14
+ * Only that 401 has been seen live. The other statuses rely on the same
15
+ * "<Reason> (<status>) from <url>" shape: grok 1.0.46's binary holds the
16
+ * reason table ("Payment Required (", "Too Many Requests (", "Service
17
+ * Unavailable (", ...) beside that format. A status the CLI does not say
18
+ * plainly (403, 404) stays `model_error` — never guess.
19
+ *
20
+ * Every code is a literal `return "<code>"`, so the plugin's tool-error-codes
21
+ * scan sees each one this file can emit.
22
+ */
23
+ import type { TurnFailureCode } from "@agentvault/agentvault";
24
+ export declare function classifyGrokFailure(err: unknown): TurnFailureCode;
25
+ /**
26
+ * Review S1: one log line for a fatal grok error: code, exit status, error
27
+ * class and, for a JSON-RPC refusal, our own method name and the numeric RPC
28
+ * code. Never the message: an AcpRpcError's message embeds the provider's
29
+ * `data` (an expired xAI sign-in landed in the log on every restart).
30
+ */
31
+ export declare function grokFatalLine(err: unknown): string;
32
+ /** True when an error may carry text from the Grok CLI or its provider, so
33
+ * only {@link grokFatalLine} may describe it. */
34
+ export declare function mayCarryProviderText(err: unknown): boolean;
35
+ /** The CLI's exit status when it died mid-turn; undefined otherwise. */
36
+ export declare function grokFailureExitCode(err: unknown): number | undefined;
37
+ //# sourceMappingURL=turn-failure.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/grok-bridge",
3
- "version": "0.4.32",
3
+ "version": "0.4.33",
4
4
  "type": "module",
5
5
  "description": "AgentVault Grok Bridge — daemon bridging a Grok agent into E2E-encrypted AgentVault direct messages and rooms.",
6
6
  "main": "dist/index.js",