@agentvault/grok-bridge 0.4.33 → 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 CHANGED
@@ -78,7 +78,8 @@ The log holds one line per event, with codes and exit numbers only. It never hol
78
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
79
  | `notice sent to <chat>` | The failure notice was delivered. |
80
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. |
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. |
82
83
 
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.
84
85
 
@@ -1,10 +1,16 @@
1
1
  import { type ToolConversation, type ToolSpanSink } from "@agentvault/agentvault";
2
2
  import type { TurnResult } from "./agent-driver.js";
3
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`. */
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. */
5
7
  export type ReplySink = (text: string, opts?: {
6
8
  notice?: boolean;
7
- }) => Promise<void>;
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";
8
14
  /** What a pushed turn knows about where it came from. */
9
15
  export interface PushOpts {
10
16
  autoReplyOnText?: boolean;
@@ -40,6 +46,12 @@ export declare class GrokSession implements RoomSession {
40
46
  private invalidated;
41
47
  /** Review F3: the error that failed this session, once one has. */
42
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;
43
55
  /** The message whose turn is in flight, or null between turns. Null is a
44
56
  * DISTINCT state from "a message that carries no reply sink" — conflating
45
57
  * them is what let a post-turn say fall through to the session-level sink. */
@@ -85,6 +97,29 @@ export declare class GrokSession implements RoomSession {
85
97
  sayHandler(): (text: string) => void;
86
98
  /** Revoke output and future work BEFORE asynchronous process cleanup. */
87
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;
88
123
  /** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
89
124
  * fails, and it must be recorded and noticed before the process exits. */
90
125
  turnInFlight(): boolean;
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 ? "bcded1f" : "";
11763
+ const raw = true ? "8b76eb4" : "";
11764
11764
  const cleaned = (raw ?? "").trim();
11765
11765
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11766
11766
  }
@@ -104049,6 +104049,12 @@ var GrokSession = class {
104049
104049
  invalidated = false;
104050
104050
  /** Review F3: the error that failed this session, once one has. */
104051
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;
104052
104058
  /** The message whose turn is in flight, or null between turns. Null is a
104053
104059
  * DISTINCT state from "a message that carries no reply sink" — conflating
104054
104060
  * them is what let a post-turn say fall through to the session-level sink. */
@@ -104056,6 +104062,13 @@ var GrokSession = class {
104056
104062
  saidThisTurn = false;
104057
104063
  drain = Promise.resolve();
104058
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
+ }
104059
104072
  if (this.invalidated) {
104060
104073
  this.log("push on invalidated session; DROPPED");
104061
104074
  if (this.failure) {
@@ -104114,6 +104127,70 @@ var GrokSession = class {
104114
104127
  this.current = null;
104115
104128
  this.queue = [];
104116
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
+ }
104117
104194
  /** True while a turn is in flight. #1560: if the CLI dies now, THAT turn
104118
104195
  * fails, and it must be recorded and noticed before the process exits. */
104119
104196
  turnInFlight() {
@@ -104150,7 +104227,7 @@ ${item.text}` : item.text;
104150
104227
  if (!wasInvalidated) this.failure = e ?? new Error("turn failed");
104151
104228
  this.invalidate();
104152
104229
  if (wasInvalidated) {
104153
- this.log("turn_cancelled reason=shutdown");
104230
+ if (!this.stoppedFor) this.log("turn_cancelled reason=shutdown");
104154
104231
  } else {
104155
104232
  try {
104156
104233
  await Promise.all([
@@ -104203,13 +104280,7 @@ ${item.text}` : item.text;
104203
104280
  reportModelTurnFailure(sink, { code, conversation: item.conversation, durationMs });
104204
104281
  this.log(`turn_failed code=${code} exit=${exit ?? "none"}`);
104205
104282
  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
- }
104283
+ const agentName = this.agentName();
104213
104284
  const notice = ownerNoticeFor(item.conversation.kind === "direct" && !alreadySpoke ? code : "model_error", {
104214
104285
  agentName: agentName ?? "",
104215
104286
  provider: "xAI"
@@ -104777,17 +104848,18 @@ var ActiveTarget = class {
104777
104848
  const t2 = this.target;
104778
104849
  const where = !t2 ? "nowhere" : t2.kind === "room" ? `room ${t2.roomId.slice(0, 8)}` : "1:1 owner";
104779
104850
  return async (text, opts) => {
104780
- if (!t2) return;
104851
+ if (!t2) return opts?.notice ? false : void 0;
104781
104852
  const startedAt = Date.now();
104782
104853
  if (opts?.notice) {
104783
104854
  try {
104784
104855
  if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
104785
104856
  else await sendDm(channel, t2, text);
104786
104857
  log(`notice sent to ${where}`);
104858
+ return true;
104787
104859
  } catch (err) {
104788
104860
  log(`notice_failed code=${classifyToolError(err)}`);
104861
+ return false;
104789
104862
  }
104790
- return;
104791
104863
  }
104792
104864
  try {
104793
104865
  if (t2.kind === "room") await channel.sendToRoom(t2.roomId, text);
@@ -105018,28 +105090,41 @@ async function reap(r2, opts = {}) {
105018
105090
  // src/index.ts
105019
105091
  var shuttingDown = false;
105020
105092
  var CHILD_EXIT_GRACE_MS = 15e3;
105093
+ var SHUTDOWN_BOUND_MS = 15e3;
105021
105094
  var exiting = false;
105022
105095
  var driver;
105023
105096
  var session;
105024
105097
  var mcp;
105025
105098
  var channelRef;
105026
105099
  var childRef;
105027
- var reapAll = async () => {
105100
+ var reapAll = async (reason = "shutdown") => {
105028
105101
  shuttingDown = true;
105029
- session?.invalidate();
105102
+ try {
105103
+ await session?.stop({ reason });
105104
+ } catch {
105105
+ session?.invalidate();
105106
+ }
105030
105107
  return reap(
105031
105108
  { channel: channelRef, driver, mcp, child: childRef },
105032
105109
  { log: (m2) => logLine("[grok-bridge] " + m2) }
105033
105110
  );
105034
105111
  };
105035
- var shutdown = async (code = 0) => {
105112
+ var shutdown = async (code = 0, reason = "shutdown") => {
105036
105113
  if (exiting) return;
105037
105114
  exiting = true;
105115
+ let bound;
105038
105116
  try {
105039
- await reapAll();
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`);
105040
105124
  } catch (error2) {
105041
105125
  logLine("[grok-bridge] teardown failed:", error2);
105042
105126
  } finally {
105127
+ clearTimeout(bound);
105043
105128
  process.exit(code);
105044
105129
  }
105045
105130
  };
@@ -105060,7 +105145,7 @@ async function main() {
105060
105145
  const info = parseInfoFlags(process.argv.slice(2));
105061
105146
  if (info.showVersion || info.showHelp) {
105062
105147
  const version2 = buildClientVersion2(
105063
- true ? "0.4.33" : void 0
105148
+ true ? "0.4.34" : void 0
105064
105149
  );
105065
105150
  if (info.showVersion) printLine(version2);
105066
105151
  if (info.showHelp) {
@@ -105099,7 +105184,7 @@ async function main() {
105099
105184
  process.exit(0);
105100
105185
  }
105101
105186
  const cfg = loadConfig(process.env, process.argv.slice(2));
105102
- logLine(`[grok-bridge] version: ${true ? "0.4.33" : "dev"}`);
105187
+ logLine(`[grok-bridge] version: ${true ? "0.4.34" : "dev"}`);
105103
105188
  mkdirSync7(cfg.workspaceDir, { recursive: true });
105104
105189
  mkdirSync7(cfg.fenceHome, { recursive: true });
105105
105190
  seedFenceCredential({
@@ -105114,7 +105199,7 @@ async function main() {
105114
105199
  agentName: cfg.agentName,
105115
105200
  platform: "node",
105116
105201
  clientVersion: buildClientVersion2(
105117
- true ? "0.4.33" : void 0
105202
+ true ? "0.4.34" : void 0
105118
105203
  )
105119
105204
  });
105120
105205
  channelRef = channel;
@@ -105211,7 +105296,9 @@ async function main() {
105211
105296
  });
105212
105297
  attachLifecycle2(channel, {
105213
105298
  log: (m2) => logLine("[grok-bridge] " + m2),
105214
- onTerminal: (_reason, o2) => void shutdown(o2.restart ? 1 : 0)
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")
105215
105302
  });
105216
105303
  channel.on("ready", () => {
105217
105304
  if (clearPendingInviteIfConsumed(cfg.dataDir, hasPersistedCreds)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/grok-bridge",
3
- "version": "0.4.33",
3
+ "version": "0.4.34",
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",