@agentvault/muse-bridge 0.1.38 → 0.1.39

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
@@ -62,11 +62,52 @@ the conversation and tool history remain available. The adapter neither edits
62
62
  Muse journals nor rotates session IDs. It binds only to loopback with a fresh
63
63
  secret route and closes at turn end. Diagnostics contain counts and fixed outcomes.
64
64
 
65
- If an eligible room or owner-attested DM turn fails before attempting a reply,
66
- the bridge attempts one generic failure notice on that turn's captured reply
67
- channel. The notice waits at most ten seconds before the next queued turn advances.
68
- Echo exec/provider behavior remains unchanged; eligible terminal failure notices
69
- apply to both providers.
65
+ ## When a reply fails
66
+
67
+ A failed turn is never silent. Here is what happens, step by step:
68
+
69
+ 1. **The bridge records it.** It sends one `model_turn` problem to the agent's
70
+ Health page (Recent problems), with a code for the cause and the chat it was
71
+ answering. It also writes one log line:
72
+ `turn_failed code=<code> exit=<exit status or none>`. Meta's status number and
73
+ a short error-type token may follow it. Provider text, request ids and message
74
+ text never go to the log, the chat or Health.
75
+ 2. **Then it tells the chat.** If the turn owed a reply (an owner 1:1, or a room
76
+ message addressed to this agent), it posts one short sentence in that chat:
77
+ - In your 1:1, the sentence names the cause, such as an expired Meta sign-in.
78
+ - In a room, it is always the plain "couldn't answer this message" sentence.
79
+ The cause is about your own Meta account, so it stays private on Health.
80
+ The notice waits at most ten seconds before the next queued turn goes ahead.
81
+
82
+ The causes this bridge can tell apart today:
83
+
84
+ | Code | What it means |
85
+ |---|---|
86
+ | `provider_auth_failed` | Meta answered 401: sign in again on the agent's computer. |
87
+ | `provider_billing` | Meta answered 402. |
88
+ | `model_rate_limited` | Meta answered 429. Try again in a few minutes. |
89
+ | `model_unavailable` | Meta answered 404: the model is no longer available. |
90
+ | `provider_unreachable` | Meta answered 5xx, or the bridge could not reach Meta at all. |
91
+ | `ai_tool_unsupported` | The `muse` binary is missing, not executable, or TUI-only. |
92
+ | `model_error` | Anything else, including a turn that timed out. |
93
+
94
+ **A saved session that can't be reopened restarts by itself.** Each lane (your
95
+ own, and the shared one for everyone else) resumes one saved Muse session. When
96
+ Meta says that session's saved reasoning has expired, the turn would fail every
97
+ time. Instead, the bridge starts one new session, gives it that chat's recent
98
+ messages, and answers your message. No notice is sent. The log says
99
+ `turn_recovered code=session_resume_failed lane=<owner|shared>`.
100
+
101
+ - The new id replaces the old one in `muse-session-id` (or
102
+ `muse-owner-session-id`) only after the new session answers.
103
+ - The first id it ever replaced is kept in `<file>.prev`. That file is never
104
+ overwritten.
105
+ - It tries this once per turn. If the new session fails too, you get the notice.
106
+ - Your lane is seeded only from your own 1:1 chat. A full-access room turn is not
107
+ seeded at all, so other members' words never enter your lane. The shared lane
108
+ is seeded only from the room being answered.
109
+
110
+ Tip: to find these in the log, search for `turn_failed` or `turn_recovered`.
70
111
 
71
112
  ## Copied-from ledger — REVIEW PERIODICALLY
72
113
 
package/dist/bridge.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * `arming_snapshot` (`=== true` only). Do not copy grok grant-trim.
3
3
  * Do not call decideArming, host-trust, or osIsolated. */
4
4
  import { type ToolSpanSink } from "@agentvault/agentvault";
5
- import type { RoomSession } from "./muse-session.js";
5
+ import { type RoomSession, type TurnFailedReport } from "./muse-session.js";
6
6
  import { type RoomContextLimits } from "./room-context.js";
7
7
  export declare function workAllowed(): boolean;
8
8
  export declare function gatesRemoved(): boolean;
@@ -31,6 +31,10 @@ export interface RoomMessage {
31
31
  }
32
32
  export interface MessageMeta {
33
33
  roomId?: string;
34
+ /** SecureChannel's id for this message; the DR path records history under it. */
35
+ messageId?: string;
36
+ /** The message's send time (`created_at`); history records it as `ts`. */
37
+ timestamp?: string;
34
38
  /** #1418 — the 1:1 conversation the message came from. A reply is sent as
35
39
  * that conversation's turn, so it reaches that person only. */
36
40
  conversationId?: string;
@@ -70,7 +74,34 @@ export interface RoomChannel {
70
74
  on(ev: "state", cb: (s: string) => void): unknown;
71
75
  sendToRoom(roomId: string, text: string): Promise<void>;
72
76
  send(text: string): Promise<void>;
77
+ /** #1560: a room's recent history (SecureChannel). Seeds a fresh session only. */
78
+ getRoomHistory?(roomId: string, max: number): HistoryLine[];
79
+ /** #1560: one person's 1:1 history, scoped by the group the frame decrypted
80
+ * under (SecureChannel). Seeds a fresh owner-lane session only. */
81
+ getConversationHistory?(conversationId: string, max: number, opts?: {
82
+ groupId?: string;
83
+ }): HistoryLine[];
84
+ }
85
+ /** The part of a SecureChannel history entry a seed uses. */
86
+ export interface HistoryLine {
87
+ sender: string;
88
+ text: string;
89
+ id?: string;
90
+ ts?: string;
91
+ }
92
+ /** The message a turn answers, as far as SecureChannel identifies it. */
93
+ export interface CurrentMessage {
94
+ text: string;
95
+ id?: string;
96
+ ts?: string;
73
97
  }
98
+ /**
99
+ * #1560: recent entries as `sender: text`, oldest first, for a fresh session.
100
+ * The bridge's own failure notices (today's and the old fixed line) are
101
+ * dropped, and so is the message being answered (it is the turn itself; an
102
+ * attachment message is captured as its caption alone). Undefined when empty.
103
+ */
104
+ export declare function seedFrom(entries: HistoryLine[] | undefined, current?: CurrentMessage): string | undefined;
74
105
  export declare class RoomHushState {
75
106
  private until;
76
107
  set(roomId: string, hushedUntilIso: string | null): void;
@@ -103,15 +134,13 @@ export interface ReplyChannel {
103
134
  * conversation it answers — never the text or the error message. Never throws.
104
135
  */
105
136
  /**
106
- * #1467: a Muse turn failed. One `ai.agent.tool.invoke` error span (tool
107
- * `model_turn`): `model_rate_limited` when Meta answered 429, else
108
- * `model_error`. No conversation and no text. Never throws.
137
+ * #1467/#1560: a Muse turn failed. One `model_turn` error span through the
138
+ * shared `reportModelTurnFailure`: the turn's code from the closed set, the
139
+ * conversation it was answering, and its duration. Never text. Never throws.
109
140
  */
110
141
  export declare function reportTurnFailure(channel: {
111
142
  telemetry?: ToolSpanSink | null;
112
- } | undefined, failure: {
113
- upstreamStatus?: number;
114
- }): void;
143
+ } | undefined, report: Pick<TurnFailedReport, "code" | "conversation" | "durationMs">): void;
115
144
  export declare class ActiveTarget {
116
145
  private target;
117
146
  setRoom(roomId: string): void;
package/dist/index.js CHANGED
@@ -11849,7 +11849,7 @@ function ownIdentity() {
11849
11849
  return `${PACKAGE}@${v2}`;
11850
11850
  }
11851
11851
  function buildSha() {
11852
- const raw = true ? "2ee9fe7" : "";
11852
+ const raw = true ? "bcded1f" : "";
11853
11853
  const cleaned = (raw ?? "").trim();
11854
11854
  return !cleaned || cleaned === "unknown" ? null : cleaned;
11855
11855
  }
@@ -73431,9 +73431,9 @@ ${text}`,
73431
73431
  HISTORY_RESTORE_TIMEOUT_MS2
73432
73432
  );
73433
73433
  let rejectOnAbort = null;
73434
- const isCurrent = () => !controller.signal.aborted && !this._stopped && lifecycle === this._lifecycleGeneration && this._historyRestoreController === controller;
73434
+ const isCurrent2 = () => !controller.signal.aborted && !this._stopped && lifecycle === this._lifecycleGeneration && this._historyRestoreController === controller;
73435
73435
  const discardLateClient = (client) => {
73436
- if (isCurrent()) return;
73436
+ if (isCurrent2()) return;
73437
73437
  if (this._historyBackupClient === client) {
73438
73438
  this._historyBackupClient = null;
73439
73439
  this._historyKeyCacheIdentity = null;
@@ -73451,7 +73451,7 @@ ${text}`,
73451
73451
  void clientAcquisition.then(discardLateClient, () => {
73452
73452
  });
73453
73453
  const client = await Promise.race([clientAcquisition, abort]);
73454
- if (!isCurrent()) {
73454
+ if (!isCurrent2()) {
73455
73455
  discardLateClient(client);
73456
73456
  return;
73457
73457
  }
@@ -73460,7 +73460,7 @@ ${text}`,
73460
73460
  client.clearHistoryKeyCache();
73461
73461
  this._historyKeyCacheIdentity = null;
73462
73462
  }
73463
- if (!isCurrent()) {
73463
+ if (!isCurrent2()) {
73464
73464
  discardLateClient(client);
73465
73465
  return;
73466
73466
  }
@@ -73468,7 +73468,7 @@ ${text}`,
73468
73468
  client.restore({ code, codeHashHex, signal: controller.signal }),
73469
73469
  abort
73470
73470
  ]);
73471
- if (!restored || !isCurrent()) {
73471
+ if (!restored || !isCurrent2()) {
73472
73472
  return;
73473
73473
  }
73474
73474
  if (state.hubId && state.hubId !== restored.hubId) {
@@ -73489,9 +73489,9 @@ ${text}`,
73489
73489
  restoredHistoryGenerationId: restored.generationId,
73490
73490
  historyRecoveryState: "complete"
73491
73491
  };
73492
- if (!isCurrent()) return;
73492
+ if (!isCurrent2()) return;
73493
73493
  await this._saveHistoryState(restoredState, { controller, lifecycle });
73494
- if (!isCurrent()) return;
73494
+ if (!isCurrent2()) return;
73495
73495
  this._persisted = restoredState;
73496
73496
  this.emit("history_recovery", {
73497
73497
  state: "restored",
@@ -104036,18 +104036,54 @@ init_fence_auth();
104036
104036
  import { chmodSync as chmodSync5, mkdirSync as mkdirSync6 } from "node:fs";
104037
104037
  import { join as join17 } from "node:path";
104038
104038
 
104039
+ // src/muse-session.ts
104040
+ await init_dist();
104041
+
104042
+ // src/turn-failure.ts
104043
+ function facts(err) {
104044
+ return err !== null && typeof err === "object" ? err : {};
104045
+ }
104046
+ function upstreamStatusOf(err) {
104047
+ const s2 = facts(err).upstreamStatus;
104048
+ return typeof s2 === "number" && Number.isInteger(s2) && s2 >= 400 && s2 <= 599 ? s2 : void 0;
104049
+ }
104050
+ function exitCodeOf(err) {
104051
+ const c2 = facts(err).exitCode;
104052
+ return typeof c2 === "number" && Number.isInteger(c2) ? c2 : void 0;
104053
+ }
104054
+ function classifyMuseFailure(err) {
104055
+ const f2 = facts(err);
104056
+ if (f2.museToolUnsupported === true) return "ai_tool_unsupported";
104057
+ const status = upstreamStatusOf(err);
104058
+ if (status === 401) return "provider_auth_failed";
104059
+ if (status === 402) return "provider_billing";
104060
+ if (status === 429) return "model_rate_limited";
104061
+ if (status === 404) return "model_unavailable";
104062
+ if (status !== void 0 && status >= 500) return "provider_unreachable";
104063
+ if (f2.providerUnreachable === true) return "provider_unreachable";
104064
+ return "model_error";
104065
+ }
104066
+ var EXPIRED_REASONING = /\breasoning ([`'"]?)encrypted_content\1 has expired\b/i;
104067
+ function isStaleSession(err) {
104068
+ if (!(err instanceof Error)) return false;
104069
+ return EXPIRED_REASONING.test(err.message.slice(-2e3));
104070
+ }
104071
+
104039
104072
  // src/muse-session.ts
104040
104073
  var ERROR_TYPE = /\(([a-z][a-z_]{2,40})\)\s*$/;
104041
104074
  function describeTurnFailure(err) {
104042
104075
  const message = err instanceof Error ? err.message : "";
104043
104076
  if (message === "muse turn stopped") return null;
104044
- const status = err?.upstreamStatus;
104077
+ const status = upstreamStatusOf(err);
104045
104078
  const type = ERROR_TYPE.exec(message.slice(-200))?.[1];
104046
104079
  return {
104047
- ...typeof status === "number" && Number.isInteger(status) && status >= 400 && status <= 599 ? { upstreamStatus: status } : {},
104080
+ ...status !== void 0 ? { upstreamStatus: status } : {},
104048
104081
  ...type ? { errorType: type } : {}
104049
104082
  };
104050
104083
  }
104084
+ var LEGACY_FAILURE_NOTICE = "I couldn't complete this reply. Please try again.";
104085
+ var SEED_LIMIT = 8192;
104086
+ var SEED_HEADER = "[AgentVault: your saved session could not be reopened, so this is a new one. Recent messages from this chat, oldest first, for context:]";
104051
104087
  var MuseSession = class {
104052
104088
  constructor(driver, opts = {}) {
104053
104089
  this.driver = driver;
@@ -104059,14 +104095,19 @@ var MuseSession = class {
104059
104095
  running = false;
104060
104096
  current = null;
104061
104097
  saidThisTurn = false;
104098
+ /** One failure notice per turn (re-review N1 split this from saidThisTurn). */
104099
+ noticedThisTurn = false;
104062
104100
  drain = Promise.resolve();
104063
104101
  push(text, reply, opts) {
104102
+ const conv = opts?.conversation;
104064
104103
  this.queue.push({
104065
104104
  text,
104066
104105
  reply,
104067
104106
  autoReplyOnText: opts?.replyExpected ?? opts?.autoReplyOnText,
104068
104107
  sayAllowed: opts?.replyExpected ?? true,
104069
- ownerTurn: opts?.ownerTurn === true
104108
+ ownerTurn: opts?.ownerTurn === true,
104109
+ conversation: conv && (conv.kind === "room" || conv.kind === "direct") && conv.id ? { kind: conv.kind, id: conv.id } : { kind: "unknown" },
104110
+ ...typeof opts?.seed === "string" && opts.seed.trim() ? { seed: opts.seed.slice(-SEED_LIMIT) } : {}
104070
104111
  });
104071
104112
  if (!this.running) this.drain = this.run();
104072
104113
  }
@@ -104113,24 +104154,13 @@ var MuseSession = class {
104113
104154
  const item = this.queue.shift();
104114
104155
  this.current = item;
104115
104156
  this.saidThisTurn = false;
104157
+ this.noticedThisTurn = false;
104158
+ const startedAt = Date.now();
104116
104159
  try {
104117
- const prompt = this.opts.identity ? `${this.opts.identity}
104118
-
104119
- ${item.text}` : item.text;
104120
- const result = await this.driver.runTurn(prompt, { ownerTurn: item.ownerTurn });
104160
+ const result = await this.runWithRecovery(item);
104121
104161
  await this.maybeFallback(item, result);
104122
104162
  } catch (err) {
104123
- const failure2 = describeTurnFailure(err);
104124
- if (failure2) {
104125
- this.log(`turn failed reason=driver${failure2.upstreamStatus ? ` upstream_status=${failure2.upstreamStatus}` : ""}${failure2.errorType ? ` error_type=${failure2.errorType}` : ""}`);
104126
- try {
104127
- this.opts.onTurnFailed?.(failure2);
104128
- } catch {
104129
- }
104130
- } else {
104131
- this.log("turn failed reason=stopped");
104132
- }
104133
- await this.failureNotice(item);
104163
+ await this.turnFailed(item, err, Date.now() - startedAt);
104134
104164
  } finally {
104135
104165
  this.current = null;
104136
104166
  }
@@ -104139,13 +104169,82 @@ ${item.text}` : item.text;
104139
104169
  this.running = false;
104140
104170
  }
104141
104171
  }
104142
- async failureNotice(item) {
104143
- if (!item.autoReplyOnText || this.saidThisTurn) return;
104172
+ prompt(item, seed) {
104173
+ const body = seed ? `${SEED_HEADER}
104174
+ ${seed}
104175
+
104176
+ ${item.text}` : item.text;
104177
+ return this.opts.identity ? `${this.opts.identity}
104178
+
104179
+ ${body}` : body;
104180
+ }
104181
+ /**
104182
+ * #1560: one turn on the stored session. If Meta says that session can no
104183
+ * longer be continued, ONE fresh session, seeded with this chat's recent
104184
+ * messages, answers instead, and the driver keeps it. Once per turn: a
104185
+ * fresh session that fails is a real failure for the caller to report. A
104186
+ * model that already spoke this turn is never re-run (no double answer).
104187
+ */
104188
+ async runWithRecovery(item) {
104189
+ try {
104190
+ return await this.driver.runTurn(this.prompt(item), { ownerTurn: item.ownerTurn });
104191
+ } catch (err) {
104192
+ if (!isStaleSession(err) || this.saidThisTurn) throw err;
104193
+ const lane = item.ownerTurn ? "owner" : "shared";
104194
+ this.log(`session_resume_failed lane=${lane} action=fresh_session seeded=${item.seed ? "yes" : "no"}`);
104195
+ const result = await this.driver.runTurn(this.prompt(item, item.seed), {
104196
+ ownerTurn: item.ownerTurn,
104197
+ freshSession: true
104198
+ });
104199
+ this.log(`turn_recovered code=session_resume_failed lane=${lane}`);
104200
+ return result;
104201
+ }
104202
+ }
104203
+ /**
104204
+ * #1560: RECORD FIRST (the report and the log line), then the notice, so a
104205
+ * notice that stalls or fails cannot lose the record. Only the code, the exit
104206
+ * status and #1467's safe parts (Meta's status number, an error-type token)
104207
+ * are logged; never the error's text.
104208
+ */
104209
+ async turnFailed(item, err, durationMs) {
104210
+ const info = describeTurnFailure(err);
104211
+ if (!info) {
104212
+ this.log("turn_cancelled reason=stopped");
104213
+ await this.failureNotice(item, "model_error");
104214
+ return;
104215
+ }
104216
+ const code = classifyMuseFailure(err);
104217
+ const exitCode = exitCodeOf(err);
104218
+ try {
104219
+ this.opts.onTurnFailed?.({
104220
+ code,
104221
+ ...exitCode !== void 0 ? { exitCode } : {},
104222
+ conversation: item.conversation,
104223
+ durationMs
104224
+ });
104225
+ } catch {
104226
+ }
104227
+ this.log(
104228
+ `turn_failed code=${code} exit=${exitCode ?? "none"}${info.upstreamStatus ? ` upstream_status=${info.upstreamStatus}` : ""}${info.errorType ? ` error_type=${info.errorType}` : ""}`
104229
+ );
104230
+ await this.failureNotice(item, item.conversation.kind === "room" ? "model_error" : code);
104231
+ }
104232
+ async failureNotice(item, code) {
104233
+ if (!item.autoReplyOnText || this.noticedThisTurn) return;
104144
104234
  const sink = item.reply ?? this.opts.onSay;
104145
104235
  if (!sink) return;
104236
+ if (this.saidThisTurn) code = "model_error";
104237
+ this.noticedThisTurn = true;
104146
104238
  this.saidThisTurn = true;
104239
+ let name;
104240
+ try {
104241
+ name = this.opts.agentName?.();
104242
+ } catch {
104243
+ name = void 0;
104244
+ }
104245
+ const notice = ownerNoticeFor(code, { agentName: name ?? "", provider: "Meta" });
104147
104246
  let timer;
104148
- const delivery = Promise.resolve().then(() => sink("I couldn't complete this reply. Please try again.")).then(
104247
+ const delivery = Promise.resolve().then(() => sink(notice)).then(
104149
104248
  () => {
104150
104249
  this.log("failure_notice outcome=delivered");
104151
104250
  },
@@ -104202,7 +104301,7 @@ ${item.text}` : item.text;
104202
104301
  // src/muse-driver.ts
104203
104302
  import { spawn } from "node:child_process";
104204
104303
  import { randomUUID as randomUUID5 } from "node:crypto";
104205
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "node:fs";
104304
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
104206
104305
  import { join as join11 } from "node:path";
104207
104306
 
104208
104307
  // src/muse-spawn.ts
@@ -104386,6 +104485,7 @@ async function createMuseProviderAdapter(opts) {
104386
104485
  }
104387
104486
  };
104388
104487
  let lastStatus;
104488
+ let transportFailed = false;
104389
104489
  const server = createServer2((req, res) => {
104390
104490
  const abort = new AbortController();
104391
104491
  const stop = () => abort.abort();
@@ -104464,12 +104564,19 @@ async function createMuseProviderAdapter(opts) {
104464
104564
  }
104465
104565
  }
104466
104566
  }
104567
+ transportFailed = false;
104467
104568
  if (!response.ok) {
104468
104569
  lastStatus = response.status;
104469
104570
  log(`upstream_error status=${response.status}${limitHeaderNote(response.headers)}`);
104571
+ } else {
104572
+ lastStatus = void 0;
104470
104573
  }
104471
104574
  await forward(response, res, abort.signal, inspected);
104472
104575
  })().catch(() => {
104576
+ if (!abort.signal.aborted) {
104577
+ transportFailed = true;
104578
+ lastStatus = void 0;
104579
+ }
104473
104580
  log("request_failed reason=transport");
104474
104581
  error2(502);
104475
104582
  }).finally(() => {
@@ -104512,7 +104619,8 @@ async function createMuseProviderAdapter(opts) {
104512
104619
  return {
104513
104620
  baseUrl: `http://127.0.0.1:${address.port}${route.slice(0, -"/responses".length)}`,
104514
104621
  close,
104515
- upstreamStatus: () => lastStatus
104622
+ upstreamStatus: () => lastStatus,
104623
+ transportFailed: () => transportFailed
104516
104624
  };
104517
104625
  }
104518
104626
 
@@ -104549,6 +104657,12 @@ var MuseDriver = class {
104549
104657
  ownerSessionId() {
104550
104658
  return this.ownerId;
104551
104659
  }
104660
+ /**
104661
+ * One turn on the lane's stored session. `freshSession` (#1560) runs it on a
104662
+ * NEW session id instead, and only when that turn succeeds does the new id
104663
+ * replace the lane's stored one (the first id ever replaced is kept in
104664
+ * `<file>.prev`, never overwritten). A fresh turn that fails changes nothing.
104665
+ */
104552
104666
  runTurn(prompt, opts = {}) {
104553
104667
  if (!this.persistedId || !this.ownerId) {
104554
104668
  throw new Error("MuseDriver.runTurn before start()");
@@ -104557,10 +104671,31 @@ var MuseDriver = class {
104557
104671
  throw new Error("MuseDriver.runTurn called while a turn is in flight");
104558
104672
  }
104559
104673
  this.current = { spoke: false, cancelled: false };
104560
- return this.executeTurn(prompt, opts.ownerTurn === true).finally(() => {
104674
+ const ownerTurn = opts.ownerTurn === true;
104675
+ const fresh = opts.freshSession === true ? randomUUID5() : void 0;
104676
+ return this.executeTurn(prompt, ownerTurn, fresh).then((result) => {
104677
+ if (fresh) this.replaceSession(ownerTurn, fresh);
104678
+ return result;
104679
+ }).finally(() => {
104561
104680
  this.current = null;
104562
104681
  });
104563
104682
  }
104683
+ /** #1560: the lane's stored session is replaced by `id`, which just answered. */
104684
+ replaceSession(ownerTurn, id) {
104685
+ const file = join11(this.opts.dataDir, ownerTurn ? OWNER_SESSION_FILE : SESSION_FILE);
104686
+ const old = ownerTurn ? this.ownerId : this.persistedId;
104687
+ if (ownerTurn) this.ownerId = id;
104688
+ else this.persistedId = id;
104689
+ try {
104690
+ if (old) keepFirst(`${file}.prev`, old);
104691
+ const tmp = `${file}.${id}.tmp`;
104692
+ writeFileSync2(tmp, id + "\n", { encoding: "utf8", mode: 384 });
104693
+ renameSync(tmp, file);
104694
+ } catch (err) {
104695
+ const code = err?.code;
104696
+ this.opts.log?.(`[muse-bridge] session_id_write_failed code=${typeof code === "string" ? code : "unknown"}`);
104697
+ }
104698
+ }
104564
104699
  noteSaid(_text) {
104565
104700
  if (this.current) this.current.spoke = true;
104566
104701
  }
@@ -104580,8 +104715,8 @@ var MuseDriver = class {
104580
104715
  const dead = await waitForExit(child, SIGKILL_GRACE_MS);
104581
104716
  if (!dead) child.kill("SIGKILL");
104582
104717
  }
104583
- async executeTurn(prompt, ownerTurn) {
104584
- const sessionId = ownerTurn ? this.ownerId : this.persistedId;
104718
+ async executeTurn(prompt, ownerTurn, freshId) {
104719
+ const sessionId = freshId ?? (ownerTurn ? this.ownerId : this.persistedId);
104585
104720
  if (!sessionId) {
104586
104721
  throw new Error("MuseDriver.runTurn before start()");
104587
104722
  }
@@ -104615,6 +104750,9 @@ var MuseDriver = class {
104615
104750
  if (typeof status === "number" && err instanceof Error) {
104616
104751
  err.upstreamStatus = status;
104617
104752
  }
104753
+ if (adapter.transportFailed?.() === true && err instanceof Error) {
104754
+ err.providerUnreachable = true;
104755
+ }
104618
104756
  throw err;
104619
104757
  } finally {
104620
104758
  await adapter.close();
@@ -104629,8 +104767,18 @@ var MuseDriver = class {
104629
104767
  });
104630
104768
  this.child = child;
104631
104769
  try {
104632
- const helpText2 = await collectOutput(child);
104633
- assertMuseExec(helpText2);
104770
+ let helpText2;
104771
+ try {
104772
+ helpText2 = await collectOutput(child);
104773
+ } catch (err) {
104774
+ throw markIfMissingBinary(err);
104775
+ }
104776
+ try {
104777
+ assertMuseExec(helpText2);
104778
+ } catch (err) {
104779
+ if (err instanceof Error) err.museToolUnsupported = true;
104780
+ throw err;
104781
+ }
104634
104782
  this.probed = true;
104635
104783
  } finally {
104636
104784
  if (this.child === child) this.child = null;
@@ -104664,8 +104812,12 @@ var MuseDriver = class {
104664
104812
  resolve5({ text: terminal.text, spoke });
104665
104813
  return;
104666
104814
  }
104815
+ const withExit = (e) => {
104816
+ if (typeof exitCode === "number") e.exitCode = exitCode;
104817
+ return e;
104818
+ };
104667
104819
  if (terminal?.ok === false) {
104668
- reject(terminal.error);
104820
+ reject(withExit(terminal.error));
104669
104821
  return;
104670
104822
  }
104671
104823
  if (timedOut) {
@@ -104675,9 +104827,9 @@ var MuseDriver = class {
104675
104827
  const redacted = redactSecrets(stderr).trim();
104676
104828
  const detail = redacted ? ` ${redacted}` : "";
104677
104829
  reject(
104678
- new Error(
104830
+ withExit(new Error(
104679
104831
  `muse exec ended with no terminal event (code=${String(exitCode)} signal=${String(exitSignal)});${detail}`
104680
- )
104832
+ ))
104681
104833
  );
104682
104834
  };
104683
104835
  const timer = setTimeout(() => {
@@ -104732,7 +104884,7 @@ var MuseDriver = class {
104732
104884
  if (!terminal) {
104733
104885
  terminal = {
104734
104886
  ok: false,
104735
- error: err instanceof Error ? err : new Error(String(err))
104887
+ error: markIfMissingBinary(err instanceof Error ? err : new Error(String(err)))
104736
104888
  };
104737
104889
  }
104738
104890
  reap();
@@ -104764,6 +104916,20 @@ function loadOrMintId(file) {
104764
104916
  writeFileSync2(file, id + "\n", { encoding: "utf8" });
104765
104917
  return id;
104766
104918
  }
104919
+ function keepFirst(path2, value) {
104920
+ try {
104921
+ writeFileSync2(path2, value + "\n", { encoding: "utf8", mode: 384, flag: "wx" });
104922
+ } catch (err) {
104923
+ if (err?.code !== "EEXIST") throw err;
104924
+ }
104925
+ }
104926
+ function markIfMissingBinary(err) {
104927
+ const code = err?.code;
104928
+ if (err instanceof Error && (code === "ENOENT" || code === "EACCES")) {
104929
+ err.museToolUnsupported = true;
104930
+ }
104931
+ return err;
104932
+ }
104767
104933
  function readFlag(value) {
104768
104934
  return typeof value === "function" ? value() : value;
104769
104935
  }
@@ -105222,6 +105388,37 @@ function resetOwnerPower() {
105222
105388
  workAllowedFlag = false;
105223
105389
  gatesRemovedFlag = false;
105224
105390
  }
105391
+ function sameInstant(a2, b2) {
105392
+ if (typeof a2 !== "string" || typeof b2 !== "string") return false;
105393
+ const x2 = Date.parse(a2);
105394
+ return Number.isFinite(x2) && x2 === Date.parse(b2);
105395
+ }
105396
+ function isCurrent(last, current) {
105397
+ if (last.sender === "agent") return false;
105398
+ if (current.id && last.id === current.id) return true;
105399
+ const textMatches = last.text === current.text || last.text.length > 0 && current.text.endsWith(`
105400
+
105401
+ ${last.text}`);
105402
+ return textMatches && sameInstant(last.ts, current.ts);
105403
+ }
105404
+ var SEED_MESSAGES = 20;
105405
+ var SEED_CHARS = 8192;
105406
+ function seedFrom(entries, current) {
105407
+ const kept = (Array.isArray(entries) ? entries : []).filter(
105408
+ (e) => e && typeof e.text === "string" && typeof e.sender === "string" && !(e.sender === "agent" && (isOwnerNotice(e.text) || e.text === LEGACY_FAILURE_NOTICE))
105409
+ );
105410
+ const last = kept[kept.length - 1];
105411
+ if (current && last && isCurrent(last, current)) kept.pop();
105412
+ const text = kept.map((e) => `${e.sender}: ${e.text}`).join("\n").slice(-SEED_CHARS);
105413
+ return text.trim() ? text : void 0;
105414
+ }
105415
+ function safeHistory(read) {
105416
+ try {
105417
+ return read();
105418
+ } catch {
105419
+ return void 0;
105420
+ }
105421
+ }
105225
105422
  var RoomHushState = class {
105226
105423
  until = /* @__PURE__ */ new Map();
105227
105424
  set(roomId, hushedUntilIso) {
@@ -105239,14 +105436,13 @@ var RoomHushState = class {
105239
105436
  return t2 !== void 0 && now < t2;
105240
105437
  }
105241
105438
  };
105242
- function reportTurnFailure(channel, failure2) {
105439
+ function reportTurnFailure(channel, report) {
105243
105440
  try {
105244
- reportToolInvoke(channel?.telemetry, {
105245
- toolName: "model_turn",
105246
- outcome: "error",
105247
- errorKind: failure2.upstreamStatus === 429 ? "model_rate_limited" : "model_error",
105248
- durationMs: 0,
105249
- conversation: { kind: "unknown" }
105441
+ const sink = channel?.telemetry;
105442
+ reportModelTurnFailure(sink && typeof sink.reportCustomSpan === "function" ? sink : null, {
105443
+ code: report.code,
105444
+ conversation: report.conversation,
105445
+ durationMs: report.durationMs
105250
105446
  });
105251
105447
  } catch {
105252
105448
  }
@@ -105444,6 +105640,7 @@ function wireBridge(channel, session, target, opts = {}) {
105444
105640
  const body = fileLocked ? `${turnText}
105445
105641
 
105446
105642
  ${FILE_LOCK_NOTE}` : turnText;
105643
+ const seed = workAllowed() && gatesRemoved() ? void 0 : seedFrom(safeHistory(() => channel.getRoomHistory?.(e.roomId, SEED_MESSAGES)), { text: e.plaintext, ts: e.timestamp });
105447
105644
  session.push(
105448
105645
  contextBlock ? `${contextBlock}
105449
105646
 
@@ -105452,7 +105649,9 @@ ${body}` : body,
105452
105649
  {
105453
105650
  autoReplyOnText: false,
105454
105651
  replyExpected: owes,
105455
- ownerTurn: ownerPowered
105652
+ ownerTurn: ownerPowered,
105653
+ conversation: { kind: "room", id: e.roomId },
105654
+ ...seed ? { seed } : {}
105456
105655
  }
105457
105656
  );
105458
105657
  if (ownerPowered) {
@@ -105475,10 +105674,19 @@ ${body}` : body,
105475
105674
  } else {
105476
105675
  log("inbound 1:1 DM from owner");
105477
105676
  }
105478
- target.setDm(metadata?.conversationId, metadata?.conversationGroupId);
105677
+ const conversationId = typeof metadata?.conversationId === "string" ? metadata.conversationId : void 0;
105678
+ const groupId = typeof metadata?.conversationGroupId === "string" ? metadata.conversationGroupId : void 0;
105679
+ target.setDm(conversationId, groupId);
105680
+ const seed = ownerAttested && conversationId ? seedFrom(safeHistory(() => channel.getConversationHistory?.(conversationId, SEED_MESSAGES, { groupId })), {
105681
+ text,
105682
+ ...typeof metadata?.messageId === "string" && metadata.messageId ? { id: metadata.messageId } : {},
105683
+ ...typeof metadata?.timestamp === "string" ? { ts: metadata.timestamp } : {}
105684
+ }) : void 0;
105479
105685
  session.push(text, target.snapshotReply(channel, log), {
105480
105686
  autoReplyOnText: ownerAttested,
105481
- ownerTurn: ownerAttested
105687
+ ownerTurn: ownerAttested,
105688
+ conversation: conversationId ? { kind: "direct", id: conversationId } : { kind: "unknown" },
105689
+ ...seed ? { seed } : {}
105482
105690
  });
105483
105691
  });
105484
105692
  }
@@ -105537,7 +105745,7 @@ function mkdir700(path2) {
105537
105745
  chmodSync5(path2, 448);
105538
105746
  }
105539
105747
  function packageVersion() {
105540
- return true ? "0.1.38" : void 0;
105748
+ return true ? "0.1.39" : void 0;
105541
105749
  }
105542
105750
  function helpText(version2) {
105543
105751
  return [
@@ -105665,9 +105873,12 @@ async function main(opts = {}) {
105665
105873
  session = new MuseSession(driver, {
105666
105874
  log: (m2) => logLine(m2),
105667
105875
  identity,
105668
- // #1467: every failed turn reaches Recent problems (and Admin) — `channel`
105669
- // is read when the failure happens, after it is connected.
105670
- onTurnFailed: (failure2) => reportTurnFailure(channel, failure2)
105876
+ // #1560: the notice names the agent as the app shows it.
105877
+ agentName: () => channel?.ownDisplayName?.toString().trim() || cfg.agentName,
105878
+ // #1467/#1560: every failed turn reaches Recent problems (and Admin) with
105879
+ // its code and conversation — `channel` is read when the failure happens,
105880
+ // after it is connected.
105881
+ onTurnFailed: (report) => reportTurnFailure(channel, report)
105671
105882
  });
105672
105883
  try {
105673
105884
  await driver.start();
@@ -50,12 +50,21 @@ export declare class MuseDriver {
50
50
  start(): Promise<string>;
51
51
  sessionId(): string | null;
52
52
  ownerSessionId(): string | null;
53
+ /**
54
+ * One turn on the lane's stored session. `freshSession` (#1560) runs it on a
55
+ * NEW session id instead, and only when that turn succeeds does the new id
56
+ * replace the lane's stored one (the first id ever replaced is kept in
57
+ * `<file>.prev`, never overwritten). A fresh turn that fails changes nothing.
58
+ */
53
59
  runTurn(prompt: string, opts?: {
54
60
  ownerTurn?: boolean;
61
+ freshSession?: boolean;
55
62
  }): Promise<{
56
63
  text: string;
57
64
  spoke: boolean;
58
65
  }>;
66
+ /** #1560: the lane's stored session is replaced by `id`, which just answered. */
67
+ private replaceSession;
59
68
  noteSaid(_text: string): void;
60
69
  stop(): Promise<void>;
61
70
  /** SIGTERM, then SIGKILL if still alive after 2s. Does not fulfill runTurn. */
@@ -3,6 +3,8 @@ export interface MuseProviderAdapter {
3
3
  close(): Promise<void>;
4
4
  /** #1467: the last error status Meta returned this turn; undefined if none. */
5
5
  upstreamStatus?(): number | undefined;
6
+ /** #1560: a request this turn could not reach Meta at all (no HTTP answer). */
7
+ transportFailed?(): boolean;
6
8
  }
7
9
  export declare function limitHeaderNote(headers: Headers): string;
8
10
  export interface MuseProviderAdapterOptions {
@@ -1,18 +1,34 @@
1
+ import { type ToolConversation, type TurnFailureCode } from "@agentvault/agentvault";
2
+ export interface PushOpts {
3
+ autoReplyOnText?: boolean;
4
+ replyExpected?: boolean;
5
+ ownerTurn?: boolean;
6
+ /** #1560: the chat this turn answers — names the failure report. */
7
+ conversation?: ToolConversation;
8
+ /** #1560: that chat's recent messages, used ONLY if the stored session is
9
+ * gone and this turn has to start a fresh one. The bridge decides what may
10
+ * seed which lane; the session never builds a seed itself. */
11
+ seed?: string;
12
+ }
1
13
  export interface RoomSession {
2
- push(text: string, reply?: (text: string) => Promise<void>, opts?: {
3
- autoReplyOnText?: boolean;
4
- replyExpected?: boolean;
5
- ownerTurn?: boolean;
6
- }): void;
14
+ push(text: string, reply?: (text: string) => Promise<void>, opts?: PushOpts): void;
7
15
  }
8
16
  export interface DriverLike {
9
17
  runTurn(prompt: string, opts?: {
10
18
  ownerTurn?: boolean;
19
+ freshSession?: boolean;
11
20
  }): Promise<{
12
21
  text: string;
13
22
  spoke: boolean;
14
23
  }>;
15
24
  }
25
+ /** #1560: what the failure report gets. A code, never the error's text. */
26
+ export interface TurnFailedReport {
27
+ code: TurnFailureCode;
28
+ exitCode?: number;
29
+ conversation: ToolConversation;
30
+ durationMs: number;
31
+ }
16
32
  /**
17
33
  * Serializes inbound messages onto MuseDriver.runTurn and routes the say back.
18
34
  *
@@ -20,8 +36,9 @@ export interface DriverLike {
20
36
  * cannot redirect a private 1:1 reply, because the newer message only becomes
21
37
  * current when its own turn starts.
22
38
  */
23
- /** #1467: what is safe to keep about a failed turn — never its message text. */
24
- export interface TurnFailure {
39
+ /** #1467: what is safe to keep about a failed turn — never its message text.
40
+ * (Not the plugin's `TurnFailure` class; that name is not shadowed here.) */
41
+ export interface TurnFailureInfo {
25
42
  /** The error status Meta's API returned this turn, when it returned one. */
26
43
  upstreamStatus?: number;
27
44
  /** The provider's error type, e.g. "invalid_request_error" — only a short
@@ -29,7 +46,9 @@ export interface TurnFailure {
29
46
  errorType?: string;
30
47
  }
31
48
  /** A failed turn → what to report, or null when the turn was stopped on purpose. */
32
- export declare function describeTurnFailure(err: unknown): TurnFailure | null;
49
+ export declare function describeTurnFailure(err: unknown): TurnFailureInfo | null;
50
+ /** #1560: the fixed line this bridge posted before — never seed material. */
51
+ export declare const LEGACY_FAILURE_NOTICE = "I couldn't complete this reply. Please try again.";
33
52
  export declare class MuseSession implements RoomSession {
34
53
  private readonly driver;
35
54
  private readonly opts;
@@ -37,23 +56,39 @@ export declare class MuseSession implements RoomSession {
37
56
  private running;
38
57
  private current;
39
58
  private saidThisTurn;
59
+ /** One failure notice per turn (re-review N1 split this from saidThisTurn). */
60
+ private noticedThisTurn;
40
61
  private drain;
41
62
  constructor(driver: DriverLike, opts?: {
42
63
  onSay?: (text: string) => Promise<void>;
43
64
  log?: (m: string) => void;
44
65
  identity?: string;
45
- /** #1467: a turn failed (not stopped). Fire-and-forget; a throw is swallowed. */
46
- onTurnFailed?: (failure: TurnFailure) => void;
66
+ /** #1560: the name the owner reads in a failure notice. */
67
+ agentName?: () => string | undefined;
68
+ /** #1467/#1560: a turn failed (not stopped). Fire-and-forget; a throw is swallowed. */
69
+ onTurnFailed?: (report: TurnFailedReport) => void;
47
70
  });
48
- push(text: string, reply?: (text: string) => Promise<void>, opts?: {
49
- autoReplyOnText?: boolean;
50
- replyExpected?: boolean;
51
- ownerTurn?: boolean;
52
- }): void;
71
+ push(text: string, reply?: (text: string) => Promise<void>, opts?: PushOpts): void;
53
72
  sayHandler(): (text: string) => void;
54
73
  idle(): Promise<void>;
55
74
  private log;
56
75
  private run;
76
+ private prompt;
77
+ /**
78
+ * #1560: one turn on the stored session. If Meta says that session can no
79
+ * longer be continued, ONE fresh session, seeded with this chat's recent
80
+ * messages, answers instead, and the driver keeps it. Once per turn: a
81
+ * fresh session that fails is a real failure for the caller to report. A
82
+ * model that already spoke this turn is never re-run (no double answer).
83
+ */
84
+ private runWithRecovery;
85
+ /**
86
+ * #1560: RECORD FIRST (the report and the log line), then the notice, so a
87
+ * notice that stalls or fails cannot lose the record. Only the code, the exit
88
+ * status and #1467's safe parts (Meta's status number, an error-type token)
89
+ * are logged; never the error's text.
90
+ */
91
+ private turnFailed;
57
92
  private failureNotice;
58
93
  /**
59
94
  * Room/DM fallback only when this turn authorised a reply AND the model
@@ -0,0 +1,39 @@
1
+ /**
2
+ * #1560 — why a Muse turn failed, as one code from the shared closed set
3
+ * (`TURN_FAILURE_CODES` in @agentvault/agentvault), and whether the stored
4
+ * Muse session itself is gone.
5
+ *
6
+ * The classifier reads only FACTS the driver attached to the error: Meta's
7
+ * HTTP status as seen by our own loopback adapter (a number), and two flags
8
+ * (`providerUnreachable`, `museToolUnsupported`). It never reads, keeps or
9
+ * returns provider text. A cause this bridge cannot detect stays
10
+ * `model_error`; nothing is guessed (403, for one, is not mapped: no Meta
11
+ * 403 has been observed).
12
+ *
13
+ * Every code is a literal `return "<code>"` so the plugin's code scan
14
+ * (`tool-error-codes.test.ts`) sees each one this file can emit.
15
+ */
16
+ import type { TurnFailureCode } from "@agentvault/agentvault";
17
+ /** The facts a failed turn's error may carry. Numbers and flags only. */
18
+ export interface MuseFailureFacts {
19
+ /** The last error status Meta answered this turn (adapter-observed). */
20
+ upstreamStatus?: number;
21
+ /** The muse child's exit status, when it exited with one. */
22
+ exitCode?: number;
23
+ /** Our adapter could not reach Meta at all (DNS, refused, reset). */
24
+ providerUnreachable?: boolean;
25
+ /** The muse binary is missing, not executable, or lacks `exec --json --session-id`. */
26
+ museToolUnsupported?: boolean;
27
+ }
28
+ /** Meta's status when it is a real HTTP error status, else undefined. */
29
+ export declare function upstreamStatusOf(err: unknown): number | undefined;
30
+ /** The child's exit status when it is an integer, else undefined. */
31
+ export declare function exitCodeOf(err: unknown): number | undefined;
32
+ export declare function classifyMuseFailure(err: unknown): TurnFailureCode;
33
+ /**
34
+ * The stored session cannot be continued: Meta refuses the encrypted
35
+ * reasoning it holds. Recorded on wowzer 64 times over 10 days on one session
36
+ * id. The text is tested here, in a local, and never kept.
37
+ */
38
+ export declare function isStaleSession(err: unknown): boolean;
39
+ //# sourceMappingURL=turn-failure.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/muse-bridge",
3
- "version": "0.1.38",
3
+ "version": "0.1.39",
4
4
  "type": "module",
5
5
  "description": "AgentVault Muse Bridge — daemon bridging a Muse agent into E2E-encrypted AgentVault direct messages and rooms.",
6
6
  "main": "dist/index.js",