@agentvault/grok-bridge 0.4.32 → 0.4.34
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 +23 -0
- package/dist/acp-connection.d.ts +17 -0
- package/dist/bridge.d.ts +2 -2
- package/dist/grok-session.d.ts +78 -9
- package/dist/index.js +473 -168
- package/dist/turn-failure.d.ts +37 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,6 +60,29 @@ 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 notice=<sent, failed, timeout or none>` | The bridge was stopped or restarted (for example during an update) while this message was being answered or waiting its turn. Nothing replays it, so when the message owed a reply the chat gets the plain sentence "Ohtani couldn't answer this message." It never names a cause. `queued=true` marks a message that was still waiting, and `late=true` one that arrived while the bridge was stopping. `none` means the message did not owe a reply. The bridge waits at most 10 seconds for these sentences, so a stuck send cannot hold up the restart. Nothing is recorded under Health, because the model did not fail. |
|
|
82
|
+
| `turn_cancelled reason=terminal notice=none` | The device was revoked or its session was taken over, so the bridge stopped without posting anything. |
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
63
86
|
## Copied-from ledger — REVIEW PERIODICALLY
|
|
64
87
|
|
|
65
88
|
These files were copied once from the Claude bridge and are now owned here. A fix
|
package/dist/acp-connection.d.ts
CHANGED
|
@@ -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):
|
|
148
|
+
snapshotReply(channel: ReplyChannel, log?: (msg: string) => void): ReplySink;
|
|
149
149
|
}
|
|
150
150
|
export interface LifecycleChannel {
|
|
151
151
|
on(ev: "auth_failed", cb: (e: {
|
package/dist/grok-session.d.ts
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
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`. A notice sink
|
|
5
|
+
* that logs its own send failure resolves `false` (#1583: so the session can
|
|
6
|
+
* tell `notice=failed` from `notice=sent`); anything else counts as sent. */
|
|
7
|
+
export type ReplySink = (text: string, opts?: {
|
|
8
|
+
notice?: boolean;
|
|
9
|
+
}) => Promise<void | boolean>;
|
|
10
|
+
/** #1583: why the session was stopped. `shutdown` is our own stop or restart
|
|
11
|
+
* (SIGTERM, a fleet roll): owed turns are told. `terminal` is a revoked
|
|
12
|
+
* device or a session taken over: nothing is posted. */
|
|
13
|
+
export type StopReason = "shutdown" | "terminal";
|
|
14
|
+
/** What a pushed turn knows about where it came from. */
|
|
15
|
+
export interface PushOpts {
|
|
16
|
+
autoReplyOnText?: boolean;
|
|
17
|
+
replyExpected?: boolean;
|
|
18
|
+
/** #1560: the chat this turn answers. It names the failure span and picks the
|
|
19
|
+
* notice wording: only a 1:1 hears the cause, anything else the bare line. */
|
|
20
|
+
conversation?: ToolConversation;
|
|
21
|
+
}
|
|
2
22
|
/** Grok's OWN copy of the room-session contract. The Claude bridge has its own;
|
|
3
23
|
* the two are deliberately unrelated and must not be unified. */
|
|
4
24
|
export interface RoomSession {
|
|
5
|
-
push(text: string, reply?:
|
|
6
|
-
autoReplyOnText?: boolean;
|
|
7
|
-
replyExpected?: boolean;
|
|
8
|
-
}): void;
|
|
25
|
+
push(text: string, reply?: ReplySink, opts?: PushOpts): void;
|
|
9
26
|
}
|
|
10
27
|
export interface DriverLike {
|
|
11
28
|
deliver(text: string): Promise<TurnResult>;
|
|
@@ -27,6 +44,14 @@ export declare class GrokSession implements RoomSession {
|
|
|
27
44
|
private queue;
|
|
28
45
|
private running;
|
|
29
46
|
private invalidated;
|
|
47
|
+
/** Review F3: the error that failed this session, once one has. */
|
|
48
|
+
private failure;
|
|
49
|
+
/** #1583: set by stop(), which logs each cancelled turn itself. */
|
|
50
|
+
private stoppedFor;
|
|
51
|
+
/** #1583 review M1: open only while a `shutdown` stop() waits on its
|
|
52
|
+
* notices. The channel is still up (and ACKing) then, so a message that
|
|
53
|
+
* lands in this window is told under the same cap, and stop() waits for it. */
|
|
54
|
+
private stopWindow;
|
|
30
55
|
/** The message whose turn is in flight, or null between turns. Null is a
|
|
31
56
|
* DISTINCT state from "a message that carries no reply sink" — conflating
|
|
32
57
|
* them is what let a post-turn say fall through to the session-level sink. */
|
|
@@ -53,13 +78,18 @@ export declare class GrokSession implements RoomSession {
|
|
|
53
78
|
* it. Revisit once `_meta.agentProfile` is probed properly.
|
|
54
79
|
*/
|
|
55
80
|
identity?: string;
|
|
56
|
-
/** Fatal delivery failure: tear down this process for supervised restart.
|
|
81
|
+
/** Fatal delivery failure: tear down this process for supervised restart.
|
|
82
|
+
* #1560: runs only AFTER the failure is recorded and the notice is out. */
|
|
57
83
|
onFatal?: (error: unknown) => void | Promise<void>;
|
|
84
|
+
/** #1560: the name the owner reads in a failure notice. */
|
|
85
|
+
agentName?: string | (() => string | undefined);
|
|
86
|
+
/** #1560: where a failed turn's `model_turn` span goes (channel.telemetry). */
|
|
87
|
+
telemetry?: () => ToolSpanSink | null | undefined;
|
|
88
|
+
/** Test seam: the bound on the notice's send. */
|
|
89
|
+
noticeTimeoutMs?: number;
|
|
58
90
|
});
|
|
59
|
-
push(text: string, reply?:
|
|
60
|
-
|
|
61
|
-
replyExpected?: boolean;
|
|
62
|
-
}): void;
|
|
91
|
+
push(text: string, reply?: ReplySink, opts?: PushOpts): void;
|
|
92
|
+
private inbound;
|
|
63
93
|
/** Hand this to startRoomMcpServer({ onSay }). The behaviour is stable for
|
|
64
94
|
* the life of the session — the per-message routing happens HERE, not in
|
|
65
95
|
* the listener — but each call returns a NEW closure; do not rely on
|
|
@@ -67,10 +97,49 @@ export declare class GrokSession implements RoomSession {
|
|
|
67
97
|
sayHandler(): (text: string) => void;
|
|
68
98
|
/** Revoke output and future work BEFORE asynchronous process cleanup. */
|
|
69
99
|
invalidate(): void;
|
|
100
|
+
/**
|
|
101
|
+
* #1583: stop for good, BEFORE the process tears down. Revokes exactly like
|
|
102
|
+
* invalidate() (no later say leaves the device), then, for `shutdown`, tells
|
|
103
|
+
* every owed turn that will now never be answered: the one in flight and each
|
|
104
|
+
* one queued behind it. Nothing replays them after a restart.
|
|
105
|
+
*
|
|
106
|
+
* Always the BARE sentence, even in a 1:1: a shutdown is not the model's
|
|
107
|
+
* failure, so there is no cause to tell, and no `model_turn` span. "Owed" is
|
|
108
|
+
* the #1560 rule (`autoReplyOnText`): an addressed room turn or an attested
|
|
109
|
+
* 1:1, never an unaddressed room turn or an unattested DM.
|
|
110
|
+
*
|
|
111
|
+
* The notices go out together under ONE cap, so this resolves within
|
|
112
|
+
* `noticeTimeoutMs` even if every send hangs. Call it before channel.stop()
|
|
113
|
+
* closes the socket. Idempotent; a no-op once a failed turn has already
|
|
114
|
+
* invalidated the session (that path told its chats itself). Never throws.
|
|
115
|
+
*/
|
|
116
|
+
stop(opts: {
|
|
117
|
+
reason: StopReason;
|
|
118
|
+
}): Promise<void>;
|
|
119
|
+
/** The bare sentence for one owed, cancelled turn, raced against the shared
|
|
120
|
+
* cap. Settles, never rejects. */
|
|
121
|
+
private cancelNotice;
|
|
122
|
+
private agentName;
|
|
123
|
+
/** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
|
|
124
|
+
* fails, and it must be recorded and noticed before the process exits. */
|
|
125
|
+
turnInFlight(): boolean;
|
|
70
126
|
/** Resolves when the queue is empty. For tests and shutdown. */
|
|
71
127
|
idle(): Promise<void>;
|
|
72
128
|
private log;
|
|
73
129
|
private run;
|
|
130
|
+
/**
|
|
131
|
+
* #1560: a failed turn is never silent. In this order:
|
|
132
|
+
* 1. RECORD one `model_turn` span with the code (Health, Recent problems),
|
|
133
|
+
* 2. LOG the code and exit status only (`turn_failed code=<c> exit=<n|none>`),
|
|
134
|
+
* 3. NOTICE the chat with the owner sentence, only where the turn owed a
|
|
135
|
+
* reply (`autoReplyOnText`: an un-addressed room turn stays silent, #1107;
|
|
136
|
+
* an unattested 1:1 gets no plain text, #621). Only a 1:1 hears the
|
|
137
|
+
* cause; a room or an unknown chat gets the bare sentence, because the
|
|
138
|
+
* coded ones describe the owner's own provider account.
|
|
139
|
+
* The notice is bounded so the fatal teardown that follows always runs.
|
|
140
|
+
* Never throws.
|
|
141
|
+
*/
|
|
142
|
+
private reportFailure;
|
|
74
143
|
/**
|
|
75
144
|
* #416: when the owner expects an answer and the model produced prose but
|
|
76
145
|
* 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 ? "
|
|
11763
|
+
const raw = true ? "8b76eb4" : "";
|
|
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
|
-
|
|
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
|
|
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,358 @@ 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
|
+
/** #1583: set by stop(), which logs each cancelled turn itself. */
|
|
104053
|
+
stoppedFor = null;
|
|
104054
|
+
/** #1583 review M1: open only while a `shutdown` stop() waits on its
|
|
104055
|
+
* notices. The channel is still up (and ACKing) then, so a message that
|
|
104056
|
+
* lands in this window is told under the same cap, and stop() waits for it. */
|
|
104057
|
+
stopWindow = null;
|
|
104058
|
+
/** The message whose turn is in flight, or null between turns. Null is a
|
|
104059
|
+
* DISTINCT state from "a message that carries no reply sink" — conflating
|
|
104060
|
+
* them is what let a post-turn say fall through to the session-level sink. */
|
|
104061
|
+
current = null;
|
|
104062
|
+
saidThisTurn = false;
|
|
104063
|
+
drain = Promise.resolve();
|
|
104064
|
+
push(text, reply, opts) {
|
|
104065
|
+
if (this.invalidated && this.stopWindow) {
|
|
104066
|
+
const item = this.inbound(text, reply, opts);
|
|
104067
|
+
this.stopWindow.late.push(this.cancelNotice(item, this.stopWindow.cap).then((outcome) => {
|
|
104068
|
+
this.log(`turn_cancelled reason=shutdown late=true notice=${outcome}`);
|
|
104069
|
+
}));
|
|
104070
|
+
return;
|
|
104071
|
+
}
|
|
104072
|
+
if (this.invalidated) {
|
|
104073
|
+
this.log("push on invalidated session; DROPPED");
|
|
104074
|
+
if (this.failure) {
|
|
104075
|
+
const failure2 = this.failure;
|
|
104076
|
+
void this.reportFailure(this.inbound(text, reply, opts), failure2, 0).catch(() => {
|
|
104077
|
+
});
|
|
104078
|
+
}
|
|
104079
|
+
return;
|
|
104080
|
+
}
|
|
104081
|
+
this.queue.push(this.inbound(text, reply, opts));
|
|
104082
|
+
if (!this.running) this.drain = this.run();
|
|
104083
|
+
}
|
|
104084
|
+
inbound(text, reply, opts) {
|
|
104085
|
+
return {
|
|
104086
|
+
text,
|
|
104087
|
+
reply,
|
|
104088
|
+
autoReplyOnText: opts?.replyExpected ?? opts?.autoReplyOnText,
|
|
104089
|
+
sayAllowed: opts?.replyExpected ?? true,
|
|
104090
|
+
conversation: opts?.conversation ?? { kind: "unknown" }
|
|
104091
|
+
};
|
|
104092
|
+
}
|
|
104093
|
+
/** Hand this to startRoomMcpServer({ onSay }). The behaviour is stable for
|
|
104094
|
+
* the life of the session — the per-message routing happens HERE, not in
|
|
104095
|
+
* the listener — but each call returns a NEW closure; do not rely on
|
|
104096
|
+
* identity (e.g. for `===` comparisons or `removeListener`-style APIs). */
|
|
104097
|
+
sayHandler() {
|
|
104098
|
+
return (text) => {
|
|
104099
|
+
try {
|
|
104100
|
+
if (this.invalidated || !this.current) {
|
|
104101
|
+
this.log(`say arrived with no turn in flight; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
|
|
104102
|
+
return;
|
|
104103
|
+
}
|
|
104104
|
+
if (!this.current.sayAllowed) {
|
|
104105
|
+
this.log(
|
|
104106
|
+
`say during a turn this agent does not owe (no @mention) \u2014 SUPPRESSED: ${JSON.stringify(text.slice(0, 80))}`
|
|
104107
|
+
);
|
|
104108
|
+
return;
|
|
104109
|
+
}
|
|
104110
|
+
this.saidThisTurn = true;
|
|
104111
|
+
const sink = this.current.reply ?? this.opts.onSay;
|
|
104112
|
+
if (!sink) {
|
|
104113
|
+
this.log(`say had no sink for this turn; DROPPED: ${JSON.stringify(text.slice(0, 80))}`);
|
|
104114
|
+
return;
|
|
104115
|
+
}
|
|
104116
|
+
void Promise.resolve(sink(text)).catch(
|
|
104117
|
+
(e) => this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`)
|
|
104118
|
+
);
|
|
104119
|
+
} catch (e) {
|
|
104120
|
+
this.log(`say failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
104121
|
+
}
|
|
104122
|
+
};
|
|
104123
|
+
}
|
|
104124
|
+
/** Revoke output and future work BEFORE asynchronous process cleanup. */
|
|
104125
|
+
invalidate() {
|
|
104126
|
+
this.invalidated = true;
|
|
104127
|
+
this.current = null;
|
|
104128
|
+
this.queue = [];
|
|
104129
|
+
}
|
|
104130
|
+
/**
|
|
104131
|
+
* #1583: stop for good, BEFORE the process tears down. Revokes exactly like
|
|
104132
|
+
* invalidate() (no later say leaves the device), then, for `shutdown`, tells
|
|
104133
|
+
* every owed turn that will now never be answered: the one in flight and each
|
|
104134
|
+
* one queued behind it. Nothing replays them after a restart.
|
|
104135
|
+
*
|
|
104136
|
+
* Always the BARE sentence, even in a 1:1: a shutdown is not the model's
|
|
104137
|
+
* failure, so there is no cause to tell, and no `model_turn` span. "Owed" is
|
|
104138
|
+
* the #1560 rule (`autoReplyOnText`): an addressed room turn or an attested
|
|
104139
|
+
* 1:1, never an unaddressed room turn or an unattested DM.
|
|
104140
|
+
*
|
|
104141
|
+
* The notices go out together under ONE cap, so this resolves within
|
|
104142
|
+
* `noticeTimeoutMs` even if every send hangs. Call it before channel.stop()
|
|
104143
|
+
* closes the socket. Idempotent; a no-op once a failed turn has already
|
|
104144
|
+
* invalidated the session (that path told its chats itself). Never throws.
|
|
104145
|
+
*/
|
|
104146
|
+
async stop(opts) {
|
|
104147
|
+
if (this.invalidated) return;
|
|
104148
|
+
const reason = opts.reason;
|
|
104149
|
+
const inFlight = this.current;
|
|
104150
|
+
const queued = this.queue.slice();
|
|
104151
|
+
this.stoppedFor = reason;
|
|
104152
|
+
this.invalidate();
|
|
104153
|
+
const turns = [
|
|
104154
|
+
...inFlight ? [{ item: inFlight, queued: false }] : [],
|
|
104155
|
+
...queued.map((item) => ({ item, queued: true }))
|
|
104156
|
+
];
|
|
104157
|
+
if (turns.length === 0 || reason !== "shutdown") {
|
|
104158
|
+
turns.forEach(({ queued: q3 }) => this.log(`turn_cancelled reason=${reason}${q3 ? " queued=true" : ""} notice=none`));
|
|
104159
|
+
return;
|
|
104160
|
+
}
|
|
104161
|
+
let timer;
|
|
104162
|
+
const cap = new Promise((resolve4) => {
|
|
104163
|
+
timer = setTimeout(() => resolve4("timeout"), this.opts.noticeTimeoutMs ?? NOTICE_TIMEOUT_MS);
|
|
104164
|
+
});
|
|
104165
|
+
const window2 = { cap, late: [] };
|
|
104166
|
+
this.stopWindow = window2;
|
|
104167
|
+
try {
|
|
104168
|
+
const outcomes = await Promise.all(turns.map(({ item }) => this.cancelNotice(item, cap)));
|
|
104169
|
+
turns.forEach(({ queued: q3 }, i2) => {
|
|
104170
|
+
this.log(`turn_cancelled reason=${reason}${q3 ? " queued=true" : ""} notice=${outcomes[i2]}`);
|
|
104171
|
+
});
|
|
104172
|
+
while (window2.late.length) await Promise.all(window2.late.splice(0));
|
|
104173
|
+
} finally {
|
|
104174
|
+
this.stopWindow = null;
|
|
104175
|
+
clearTimeout(timer);
|
|
104176
|
+
}
|
|
104177
|
+
}
|
|
104178
|
+
/** The bare sentence for one owed, cancelled turn, raced against the shared
|
|
104179
|
+
* cap. Settles, never rejects. */
|
|
104180
|
+
async cancelNotice(item, cap) {
|
|
104181
|
+
if (!item.autoReplyOnText || !item.reply) return "none";
|
|
104182
|
+
const notice = ownerNoticeFor("model_error", { agentName: this.agentName() ?? "", provider: "xAI" });
|
|
104183
|
+
const sent = Promise.resolve().then(() => item.reply(notice, { notice: true })).then((r2) => r2 === false ? "failed" : "sent", () => "failed");
|
|
104184
|
+
return Promise.race([sent, cap]);
|
|
104185
|
+
}
|
|
104186
|
+
agentName() {
|
|
104187
|
+
try {
|
|
104188
|
+
const n2 = this.opts.agentName;
|
|
104189
|
+
return typeof n2 === "function" ? n2() : n2;
|
|
104190
|
+
} catch {
|
|
104191
|
+
return void 0;
|
|
104192
|
+
}
|
|
104193
|
+
}
|
|
104194
|
+
/** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
|
|
104195
|
+
* fails, and it must be recorded and noticed before the process exits. */
|
|
104196
|
+
turnInFlight() {
|
|
104197
|
+
return !this.invalidated && this.current !== null;
|
|
104198
|
+
}
|
|
104199
|
+
/** Resolves when the queue is empty. For tests and shutdown. */
|
|
104200
|
+
async idle() {
|
|
104201
|
+
await this.drain;
|
|
104202
|
+
}
|
|
104203
|
+
log(m2) {
|
|
104204
|
+
try {
|
|
104205
|
+
this.opts.log?.(`[grok-bridge] ${m2}`);
|
|
104206
|
+
} catch {
|
|
104207
|
+
}
|
|
104208
|
+
}
|
|
104209
|
+
async run() {
|
|
104210
|
+
this.running = true;
|
|
104211
|
+
try {
|
|
104212
|
+
while (!this.invalidated && this.queue.length) {
|
|
104213
|
+
const item = this.queue.shift();
|
|
104214
|
+
this.current = item;
|
|
104215
|
+
this.saidThisTurn = false;
|
|
104216
|
+
const startedAt = Date.now();
|
|
104217
|
+
try {
|
|
104218
|
+
const prompt = this.opts.identity ? `${this.opts.identity}
|
|
104219
|
+
|
|
104220
|
+
${item.text}` : item.text;
|
|
104221
|
+
const result = await this.driver.deliver(prompt);
|
|
104222
|
+
if (!this.invalidated) await this.maybeFallback(item, result);
|
|
104223
|
+
} catch (e) {
|
|
104224
|
+
const wasInvalidated = this.invalidated;
|
|
104225
|
+
const spokeThisTurn = this.saidThisTurn;
|
|
104226
|
+
const stranded = wasInvalidated ? [] : this.queue.slice();
|
|
104227
|
+
if (!wasInvalidated) this.failure = e ?? new Error("turn failed");
|
|
104228
|
+
this.invalidate();
|
|
104229
|
+
if (wasInvalidated) {
|
|
104230
|
+
if (!this.stoppedFor) this.log("turn_cancelled reason=shutdown");
|
|
104231
|
+
} else {
|
|
104232
|
+
try {
|
|
104233
|
+
await Promise.all([
|
|
104234
|
+
this.reportFailure(item, e, Date.now() - startedAt, spokeThisTurn),
|
|
104235
|
+
...stranded.map((s2) => this.reportFailure(s2, e, 0))
|
|
104236
|
+
]);
|
|
104237
|
+
} catch {
|
|
104238
|
+
this.log("turn_failed code=model_error exit=none report=failed");
|
|
104239
|
+
}
|
|
104240
|
+
try {
|
|
104241
|
+
await this.opts.onFatal?.(e);
|
|
104242
|
+
} catch (cleanupError) {
|
|
104243
|
+
this.log(`fatal cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
|
|
104244
|
+
}
|
|
104245
|
+
}
|
|
104246
|
+
} finally {
|
|
104247
|
+
this.current = null;
|
|
104248
|
+
}
|
|
104249
|
+
}
|
|
104250
|
+
} finally {
|
|
104251
|
+
this.running = false;
|
|
104252
|
+
}
|
|
104253
|
+
}
|
|
104254
|
+
/**
|
|
104255
|
+
* #1560: a failed turn is never silent. In this order:
|
|
104256
|
+
* 1. RECORD one `model_turn` span with the code (Health, Recent problems),
|
|
104257
|
+
* 2. LOG the code and exit status only (`turn_failed code=<c> exit=<n|none>`),
|
|
104258
|
+
* 3. NOTICE the chat with the owner sentence, only where the turn owed a
|
|
104259
|
+
* reply (`autoReplyOnText`: an un-addressed room turn stays silent, #1107;
|
|
104260
|
+
* an unattested 1:1 gets no plain text, #621). Only a 1:1 hears the
|
|
104261
|
+
* cause; a room or an unknown chat gets the bare sentence, because the
|
|
104262
|
+
* coded ones describe the owner's own provider account.
|
|
104263
|
+
* The notice is bounded so the fatal teardown that follows always runs.
|
|
104264
|
+
* Never throws.
|
|
104265
|
+
*/
|
|
104266
|
+
async reportFailure(item, err, durationMs, alreadySpoke = false) {
|
|
104267
|
+
let code = "model_error";
|
|
104268
|
+
let exit;
|
|
104269
|
+
try {
|
|
104270
|
+
code = classifyGrokFailure(err);
|
|
104271
|
+
exit = grokFailureExitCode(err);
|
|
104272
|
+
} catch {
|
|
104273
|
+
}
|
|
104274
|
+
let sink;
|
|
104275
|
+
try {
|
|
104276
|
+
sink = this.opts.telemetry?.();
|
|
104277
|
+
} catch {
|
|
104278
|
+
sink = null;
|
|
104279
|
+
}
|
|
104280
|
+
reportModelTurnFailure(sink, { code, conversation: item.conversation, durationMs });
|
|
104281
|
+
this.log(`turn_failed code=${code} exit=${exit ?? "none"}`);
|
|
104282
|
+
if (!item.autoReplyOnText || !item.reply) return;
|
|
104283
|
+
const agentName = this.agentName();
|
|
104284
|
+
const notice = ownerNoticeFor(item.conversation.kind === "direct" && !alreadySpoke ? code : "model_error", {
|
|
104285
|
+
agentName: agentName ?? "",
|
|
104286
|
+
provider: "xAI"
|
|
104287
|
+
});
|
|
104288
|
+
let timer;
|
|
104289
|
+
const timedOut = new Promise((resolve4) => {
|
|
104290
|
+
timer = setTimeout(() => resolve4("timeout"), this.opts.noticeTimeoutMs ?? NOTICE_TIMEOUT_MS);
|
|
104291
|
+
});
|
|
104292
|
+
const sent = Promise.resolve().then(() => item.reply(notice, { notice: true })).then(() => "sent", () => "threw");
|
|
104293
|
+
const outcome = await Promise.race([sent, timedOut]);
|
|
104294
|
+
if (timer) clearTimeout(timer);
|
|
104295
|
+
if (outcome === "timeout") this.log("notice_failed reason=timeout");
|
|
104296
|
+
else if (outcome === "threw") this.log("notice_failed reason=sink_threw");
|
|
104297
|
+
}
|
|
104298
|
+
/**
|
|
104299
|
+
* #416: when the owner expects an answer and the model produced prose but
|
|
104300
|
+
* never called the say tool, send the prose rather than dropping it.
|
|
104301
|
+
*
|
|
104302
|
+
* ONLY SAFE BECAUSE `spoke` IS REAL. Over a stdio MCP child the say never
|
|
104303
|
+
* reaches the driver, so `spoke` is permanently false and this would fire on
|
|
104304
|
+
* every turn — double-posting everything the agent said. It depends on the
|
|
104305
|
+
* in-process HTTP listener.
|
|
104306
|
+
*/
|
|
104307
|
+
async maybeFallback(item, result) {
|
|
104308
|
+
const alreadySpoke = this.saidThisTurn || result.spoke;
|
|
104309
|
+
const text = result.text.trim();
|
|
104310
|
+
if (!item.autoReplyOnText) {
|
|
104311
|
+
if (!alreadySpoke && text) {
|
|
104312
|
+
this.log(
|
|
104313
|
+
`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))}`
|
|
104314
|
+
);
|
|
104315
|
+
}
|
|
104316
|
+
return;
|
|
104317
|
+
}
|
|
104318
|
+
if (alreadySpoke) return;
|
|
104319
|
+
if (!text) return;
|
|
104320
|
+
const sink = item.reply ?? this.opts.onSay;
|
|
104321
|
+
if (!sink) return;
|
|
104322
|
+
try {
|
|
104323
|
+
await sink(text);
|
|
104324
|
+
this.log("delivered assistant prose via the auto-reply fallback");
|
|
104325
|
+
} catch (e) {
|
|
104326
|
+
this.log(`fallback send failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
104327
|
+
}
|
|
104328
|
+
}
|
|
104329
|
+
};
|
|
104330
|
+
|
|
104062
104331
|
// src/grok-room-plugin.ts
|
|
104063
104332
|
import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync3, chmodSync as chmodSync4 } from "node:fs";
|
|
104064
104333
|
import { join as join11 } from "node:path";
|
|
@@ -104311,10 +104580,6 @@ function handleMcpFrame(frame, onSay) {
|
|
|
104311
104580
|
}
|
|
104312
104581
|
|
|
104313
104582
|
// src/grok-room-http.ts
|
|
104314
|
-
function redactCredential(text, secret) {
|
|
104315
|
-
if (!secret) return text;
|
|
104316
|
-
return text.split(secret).join("[redacted]");
|
|
104317
|
-
}
|
|
104318
104583
|
async function startRoomMcpServer(opts) {
|
|
104319
104584
|
const seen = [];
|
|
104320
104585
|
const token = randomBytes4(24).toString("base64url");
|
|
@@ -104582,9 +104847,20 @@ var ActiveTarget = class {
|
|
|
104582
104847
|
}) {
|
|
104583
104848
|
const t2 = this.target;
|
|
104584
104849
|
const where = !t2 ? "nowhere" : t2.kind === "room" ? `room ${t2.roomId.slice(0, 8)}` : "1:1 owner";
|
|
104585
|
-
return async (text) => {
|
|
104586
|
-
if (!t2) return;
|
|
104850
|
+
return async (text, opts) => {
|
|
104851
|
+
if (!t2) return opts?.notice ? false : void 0;
|
|
104587
104852
|
const startedAt = Date.now();
|
|
104853
|
+
if (opts?.notice) {
|
|
104854
|
+
try {
|
|
104855
|
+
if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
|
|
104856
|
+
else await sendDm(channel, t2, text);
|
|
104857
|
+
log(`notice sent to ${where}`);
|
|
104858
|
+
return true;
|
|
104859
|
+
} catch (err) {
|
|
104860
|
+
log(`notice_failed code=${classifyToolError(err)}`);
|
|
104861
|
+
return false;
|
|
104862
|
+
}
|
|
104863
|
+
}
|
|
104588
104864
|
try {
|
|
104589
104865
|
if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
|
|
104590
104866
|
else await sendDm(channel, t2, text);
|
|
@@ -104730,7 +105006,8 @@ function wireBridge(channel, session2, target, opts = {}) {
|
|
|
104730
105006
|
|
|
104731
105007
|
${turnText}` : turnText, target.snapshotReply(channel, log), {
|
|
104732
105008
|
autoReplyOnText: false,
|
|
104733
|
-
replyExpected: owes
|
|
105009
|
+
replyExpected: owes,
|
|
105010
|
+
conversation: { kind: "room", id: e.roomId }
|
|
104734
105011
|
});
|
|
104735
105012
|
if (held.entries.length > 0) {
|
|
104736
105013
|
roomContext.clear(e.roomId);
|
|
@@ -104746,7 +105023,11 @@ ${turnText}` : turnText, target.snapshotReply(channel, log), {
|
|
|
104746
105023
|
log("inbound 1:1 DM from owner");
|
|
104747
105024
|
}
|
|
104748
105025
|
target.setDm(metadata?.conversationId, metadata?.conversationGroupId);
|
|
104749
|
-
session2.push(text, target.snapshotReply(channel, log), {
|
|
105026
|
+
session2.push(text, target.snapshotReply(channel, log), {
|
|
105027
|
+
autoReplyOnText: ownerAttested,
|
|
105028
|
+
// #1560: names the failure span; a 1:1 is the one chat that hears the cause.
|
|
105029
|
+
conversation: metadata?.conversationId ? { kind: "direct", id: metadata.conversationId } : { kind: "direct" }
|
|
105030
|
+
});
|
|
104750
105031
|
});
|
|
104751
105032
|
}
|
|
104752
105033
|
|
|
@@ -104808,28 +105089,42 @@ async function reap(r2, opts = {}) {
|
|
|
104808
105089
|
|
|
104809
105090
|
// src/index.ts
|
|
104810
105091
|
var shuttingDown = false;
|
|
105092
|
+
var CHILD_EXIT_GRACE_MS = 15e3;
|
|
105093
|
+
var SHUTDOWN_BOUND_MS = 15e3;
|
|
104811
105094
|
var exiting = false;
|
|
104812
105095
|
var driver;
|
|
104813
105096
|
var session;
|
|
104814
105097
|
var mcp;
|
|
104815
105098
|
var channelRef;
|
|
104816
105099
|
var childRef;
|
|
104817
|
-
var reapAll = async () => {
|
|
105100
|
+
var reapAll = async (reason = "shutdown") => {
|
|
104818
105101
|
shuttingDown = true;
|
|
104819
|
-
|
|
105102
|
+
try {
|
|
105103
|
+
await session?.stop({ reason });
|
|
105104
|
+
} catch {
|
|
105105
|
+
session?.invalidate();
|
|
105106
|
+
}
|
|
104820
105107
|
return reap(
|
|
104821
105108
|
{ channel: channelRef, driver, mcp, child: childRef },
|
|
104822
105109
|
{ log: (m2) => logLine("[grok-bridge] " + m2) }
|
|
104823
105110
|
);
|
|
104824
105111
|
};
|
|
104825
|
-
var shutdown = async (code = 0) => {
|
|
105112
|
+
var shutdown = async (code = 0, reason = "shutdown") => {
|
|
104826
105113
|
if (exiting) return;
|
|
104827
105114
|
exiting = true;
|
|
105115
|
+
let bound;
|
|
104828
105116
|
try {
|
|
104829
|
-
await
|
|
105117
|
+
const timedOut = await Promise.race([
|
|
105118
|
+
reapAll(reason).then(() => false),
|
|
105119
|
+
new Promise((resolve4) => {
|
|
105120
|
+
bound = setTimeout(() => resolve4(true), SHUTDOWN_BOUND_MS);
|
|
105121
|
+
})
|
|
105122
|
+
]);
|
|
105123
|
+
if (timedOut) logLine(`[grok-bridge] teardown timed out after ${SHUTDOWN_BOUND_MS}ms; exiting anyway`);
|
|
104830
105124
|
} catch (error2) {
|
|
104831
105125
|
logLine("[grok-bridge] teardown failed:", error2);
|
|
104832
105126
|
} finally {
|
|
105127
|
+
clearTimeout(bound);
|
|
104833
105128
|
process.exit(code);
|
|
104834
105129
|
}
|
|
104835
105130
|
};
|
|
@@ -104850,7 +105145,7 @@ async function main() {
|
|
|
104850
105145
|
const info = parseInfoFlags(process.argv.slice(2));
|
|
104851
105146
|
if (info.showVersion || info.showHelp) {
|
|
104852
105147
|
const version2 = buildClientVersion2(
|
|
104853
|
-
true ? "0.4.
|
|
105148
|
+
true ? "0.4.34" : void 0
|
|
104854
105149
|
);
|
|
104855
105150
|
if (info.showVersion) printLine(version2);
|
|
104856
105151
|
if (info.showHelp) {
|
|
@@ -104889,7 +105184,7 @@ async function main() {
|
|
|
104889
105184
|
process.exit(0);
|
|
104890
105185
|
}
|
|
104891
105186
|
const cfg = loadConfig(process.env, process.argv.slice(2));
|
|
104892
|
-
logLine(`[grok-bridge] version: ${true ? "0.4.
|
|
105187
|
+
logLine(`[grok-bridge] version: ${true ? "0.4.34" : "dev"}`);
|
|
104893
105188
|
mkdirSync7(cfg.workspaceDir, { recursive: true });
|
|
104894
105189
|
mkdirSync7(cfg.fenceHome, { recursive: true });
|
|
104895
105190
|
seedFenceCredential({
|
|
@@ -104904,7 +105199,7 @@ async function main() {
|
|
|
104904
105199
|
agentName: cfg.agentName,
|
|
104905
105200
|
platform: "node",
|
|
104906
105201
|
clientVersion: buildClientVersion2(
|
|
104907
|
-
true ? "0.4.
|
|
105202
|
+
true ? "0.4.34" : void 0
|
|
104908
105203
|
)
|
|
104909
105204
|
});
|
|
104910
105205
|
channelRef = channel;
|
|
@@ -104948,6 +105243,10 @@ async function main() {
|
|
|
104948
105243
|
const msg = describeChildExit(shuttingDown, code, signal);
|
|
104949
105244
|
if (!msg) return;
|
|
104950
105245
|
logLine(`[grok-bridge] fatal: ${msg}`);
|
|
105246
|
+
if (session?.turnInFlight()) {
|
|
105247
|
+
setTimeout(() => void shutdown(1), CHILD_EXIT_GRACE_MS);
|
|
105248
|
+
return;
|
|
105249
|
+
}
|
|
104951
105250
|
void shutdown(1);
|
|
104952
105251
|
});
|
|
104953
105252
|
child.stderr.on("error", () => {
|
|
@@ -104955,13 +105254,11 @@ async function main() {
|
|
|
104955
105254
|
child.stdout.on("error", () => {
|
|
104956
105255
|
});
|
|
104957
105256
|
child.stderr.on("data", (b2) => {
|
|
104958
|
-
|
|
104959
|
-
if (
|
|
104960
|
-
|
|
104961
|
-
|
|
104962
|
-
}
|
|
104963
|
-
t2 = t2.trim();
|
|
104964
|
-
if (t2) logLine(`[grok-bridge] grok: ${t2.slice(0, 500)}`);
|
|
105257
|
+
const t2 = b2.toString().replace(/\x1b\[[0-9;]*m/g, "");
|
|
105258
|
+
if (!t2.trim()) return;
|
|
105259
|
+
const lines = t2.split("\n").filter((l2) => l2.trim()).length;
|
|
105260
|
+
const level2 = /\bERROR\b/.test(t2) ? "ERROR" : /\bWARN\b/.test(t2) ? "WARN" : null;
|
|
105261
|
+
logLine(`[grok-bridge] grok: stderr lines=${lines} bytes=${b2.length}${level2 ? ` level=${level2}` : ""}`);
|
|
104965
105262
|
});
|
|
104966
105263
|
driver = new GrokDriver(child, {
|
|
104967
105264
|
cwd: cfg.workspaceDir,
|
|
@@ -104972,14 +105269,19 @@ async function main() {
|
|
|
104972
105269
|
session = new GrokSession(driver, {
|
|
104973
105270
|
log: (m2) => logLine(m2),
|
|
104974
105271
|
identity,
|
|
104975
|
-
onFatal: () => shutdown(1)
|
|
105272
|
+
onFatal: () => shutdown(1),
|
|
105273
|
+
// #1560: a failed turn records a `model_turn` span on the channel's
|
|
105274
|
+
// telemetry before onFatal runs. shutdown() -> reap() -> channel.stop()
|
|
105275
|
+
// flushes that buffer before closing the socket, so the span is not lost.
|
|
105276
|
+
telemetry: () => channel.telemetry,
|
|
105277
|
+
agentName: () => channel.ownDisplayName?.trim() || cfg.agentName
|
|
104976
105278
|
});
|
|
104977
105279
|
process.on("SIGTERM", () => void shutdown(0));
|
|
104978
105280
|
process.on("SIGINT", () => void shutdown(0));
|
|
104979
105281
|
try {
|
|
104980
105282
|
await driver.start();
|
|
104981
105283
|
} catch (err) {
|
|
104982
|
-
logLine(
|
|
105284
|
+
logLine(`[grok-bridge] fatal: grok did not start: ${grokFatalLine(err)}`);
|
|
104983
105285
|
await shutdown(1);
|
|
104984
105286
|
return;
|
|
104985
105287
|
}
|
|
@@ -104994,7 +105296,9 @@ async function main() {
|
|
|
104994
105296
|
});
|
|
104995
105297
|
attachLifecycle2(channel, {
|
|
104996
105298
|
log: (m2) => logLine("[grok-bridge] " + m2),
|
|
104997
|
-
|
|
105299
|
+
// #1583: silent. A revoked or replaced device has no chat to tell, and a
|
|
105300
|
+
// reconnect loop has no socket to tell it over.
|
|
105301
|
+
onTerminal: (_reason, o2) => void shutdown(o2.restart ? 1 : 0, "terminal")
|
|
104998
105302
|
});
|
|
104999
105303
|
channel.on("ready", () => {
|
|
105000
105304
|
if (clearPendingInviteIfConsumed(cfg.dataDir, hasPersistedCreds)) {
|
|
@@ -105005,7 +105309,8 @@ async function main() {
|
|
|
105005
105309
|
await channel.start();
|
|
105006
105310
|
}
|
|
105007
105311
|
main().catch(async (err) => {
|
|
105008
|
-
logLine(
|
|
105312
|
+
if (mayCarryProviderText(err)) logLine(`[grok-bridge] fatal: ${grokFatalLine(err)}`);
|
|
105313
|
+
else logLine("[grok-bridge] fatal:", err);
|
|
105009
105314
|
await shutdown(1);
|
|
105010
105315
|
});
|
|
105011
105316
|
/*! 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