pi-muse-tether 0.2.2 → 0.2.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.4 — 2026-11-24
4
+
5
+ - Tool results containing images now work with Muse Code 1.4.25, which includes image dimensions in its placeholder text.
6
+
7
+ ## 0.2.3 — 2026-11-23
8
+
9
+ - Tests now refuse to write to the real request ledger, even when a test path points to it indirectly.
10
+ - Temporary rate limits no longer stop the client from retrying. Quota errors show the reset time when available, and empty usage events are ignored.
11
+ - Oversized sets of allowed values in tool schemas are rejected before sending. A response that skips required structured output now reports the failure without discarding its text, and retry messages show the cause when available.
12
+
3
13
  ## 0.2.2 — 2026-11-20
4
14
 
5
15
  - A turn whose frame is over the official Muse client's 10,485,760-byte inbound limit is refused before sending instead of ending the session: the error names the measured frame size, the limit and its source, and Pi's normal overflow recovery compacts the history and retries once. Long sessions with base64 images therefore continue rather than dying mid-work.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-muse-tether",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "description": "Use your Muse Code subscription in Pi through the official client",
6
6
  "license": "MIT",
package/src/host.ts CHANGED
@@ -3,7 +3,8 @@ import { featureNotice, featureActive, MuseFeatureUnavailable } from "./features
3
3
  import { committedCalls } from "./batch-schema.js";
4
4
  import { qualifyMuseVersion } from "./cli-version.js";
5
5
  import { museEffort } from "./thinking-config.js";
6
- import { publishQuota, quotaExhausted } from "./rate-limit.js";
6
+ import { hasQuotaData, publishQuota, quotaExhausted, quotaExhaustedResetIso } from "./rate-limit.js";
7
+ import { retryCause } from "./retry-status.js";
7
8
  import { MuseLedger } from "./request-ledger.js";
8
9
  import type { TurnInputPart } from "./wire-types.js";
9
10
  import { homedir, tmpdir } from "node:os";
@@ -63,7 +64,7 @@ export type MuseApproval = Parameters<ApprovalHandler>[0];
63
64
  export type MuseFrame = { method: string; params?: Record<string, unknown> };
64
65
  export type MuseHostEvent =
65
66
  | { kind: "frame"; frame: MuseFrame }
66
- | { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number }
67
+ | { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number; lastRetryCause?: string }
67
68
  | { kind: "fenced"; reason: string }
68
69
  | { kind: "degraded"; feature: "rawLog"; reason: string }
69
70
  | { kind: "tool-batch"; calls: Array<{callId:string;name:string;args:Record<string,unknown>}> }
@@ -142,15 +143,60 @@ export function serverRequiresUpgrade(error: unknown, seen = new Set<unknown>())
142
143
  if ([value.status,value.httpStatus,value.code].includes(426) || [value.kind,value.errorKind,value.code].some(v => typeof v === "string" && /^(upgrade_required|client_version_unsupported|minimum_client_version|client_upgrade_required)$/.test(v))) return true;
143
144
  return [value.error,value.data,value.cause].some(nested => serverRequiresUpgrade(nested,seen));
144
145
  }
146
+ const QUOTA_EXHAUSTION_MESSAGE = /quota\s*(?:exhausted|exceeded|limit|reached)|insufficient_quota|usage\s+limit\s+reached|plan\s+limit/i;
147
+
148
+ /**
149
+ * Definitive quota exhaustion only. Temporary HTTP 429 / rate-limit bursts
150
+ * belong to Muse Code's own retry chain and must not be fenced as exhausted
151
+ * subscription quota.
152
+ */
145
153
  function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
146
154
  if (!error || typeof error !== "object" || seen.has(error)) return false;
147
155
  seen.add(error);
148
156
  const value = error as Record<string, unknown>;
149
- if ([value.status, value.httpStatus, value.statusCode, value.code].includes(429) || value.quota !== undefined ||
150
- [value.errorKind, value.kind, value.code].some(v => typeof v === "string" && /quota|plan.*limit|rate.?limit/i.test(v))) return true;
157
+ if (value.quota !== undefined && value.quota !== null && typeof value.quota === "object") return true;
158
+ if ([value.errorKind, value.kind, value.code].some(v => typeof v === "string" && /quota|plan.*limit/i.test(v))) return true;
159
+ if ([value.message, value.reason].some(v => typeof v === "string" && QUOTA_EXHAUSTION_MESSAGE.test(v))) return true;
151
160
  return [value.data, value.error, value.cause].some(nested => quotaDenial(nested, seen));
152
161
  }
153
162
 
163
+ function quotaDetails(error: unknown, seen = new Set<unknown>()): { limitKind?: string; resetsAtMs?: number; message?: string } {
164
+ if (!error || typeof error !== "object" || seen.has(error)) return {};
165
+ seen.add(error);
166
+ const value = error as Record<string, any>;
167
+ let limitKind = typeof value.quota?.limitKind === "string" && value.quota.limitKind ? value.quota.limitKind : undefined;
168
+ let resetsAtMs = typeof value.quota?.resetsAtMs === "number" && Number.isFinite(value.quota.resetsAtMs)
169
+ ? value.quota.resetsAtMs
170
+ : typeof value.resetsAtMs === "number" && Number.isFinite(value.resetsAtMs)
171
+ ? value.resetsAtMs
172
+ : undefined;
173
+ let message = [value.message, value.reason].find((v): v is string => typeof v === "string" && v.trim().length > 0)?.trim();
174
+ for (const nested of [value.error, value.data, value.cause]) {
175
+ if (!nested || nested === error) continue;
176
+ const child = quotaDetails(nested, seen);
177
+ limitKind ??= child.limitKind;
178
+ resetsAtMs ??= child.resetsAtMs;
179
+ message ??= child.message;
180
+ }
181
+ return { limitKind, resetsAtMs, message };
182
+ }
183
+
184
+ /**
185
+ * Format a quota fence preserving the provider's message and reset time while
186
+ * keeping "quota exceeded" in the prefix so Pi never auto-retries even when the
187
+ * provider text contains "429" or "rate_limit_error".
188
+ */
189
+ function quotaFenceMessage(error: unknown): string {
190
+ const { limitKind, resetsAtMs, message } = quotaDetails(error);
191
+ const meta = [limitKind, resetsAtMs !== undefined ? `resets at ${new Date(resetsAtMs).toISOString()}` : undefined]
192
+ .filter(Boolean)
193
+ .join(", ");
194
+ const detail = [meta, message].filter(Boolean).join(" — ");
195
+ return detail
196
+ ? `Muse quota refused (quota exceeded); no replay: ${detail}`
197
+ : "Muse quota refused (quota exceeded); no replay";
198
+ }
199
+
154
200
  const canonical = (v:any):string => v && typeof v === "object"
155
201
  ? Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
156
202
  : JSON.stringify(v);
@@ -241,6 +287,7 @@ export class MuseHost {
241
287
  #committedCalls = new Map<string, string>();
242
288
  #committedBatches = new Set<string>();
243
289
  #lastRetryHttpStatus?: number;
290
+ #lastRetryCause?: string;
244
291
  #logSubscription?: number;
245
292
  #steers = new Set<string>();
246
293
  #discarded = new DiscardedSessions();
@@ -467,7 +514,10 @@ export class MuseHost {
467
514
  }
468
515
  return;
469
516
  }
470
- if (frame.method === "usage/changed") { publishQuota(frame.params); this.ledger.quota(frame.params); return; }
517
+ if (frame.method === "usage/changed") {
518
+ if (hasQuotaData(frame.params)) { publishQuota(frame.params); this.ledger.quota(frame.params); }
519
+ return;
520
+ }
471
521
  if (typeof frame.params?.sessionId !== "string") return;
472
522
  if (this.#opening && !this.#session) { this.#held.push(frame); return; }
473
523
  if (this.#session && frame.params.sessionId === this.sessionId) this.#apply(frame);
@@ -494,7 +544,7 @@ export class MuseHost {
494
544
  }
495
545
  if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
496
546
  this.#emit({kind:"frame",frame});
497
- this.fence("Muse quota refused; no replay"); return;
547
+ this.fence(quotaFenceMessage(quotaDenial(params.error) ? params.error : params)); return;
498
548
  }
499
549
  if(retry){
500
550
  if(!this.#busy || params.turnId!==this.#submission?.turnId) {
@@ -507,7 +557,9 @@ export class MuseHost {
507
557
  // An unknown or missing kind must not end live work; account, quota, policy
508
558
  // and upgrade refusals were already decided above, and the terminal frame
509
559
  // still reports the real outcome and status.
510
- if(typeof params.httpStatus==="number")this.#lastRetryHttpStatus=params.httpStatus;
560
+ if(typeof params.httpStatus==="number" && Number.isFinite(params.httpStatus))this.#lastRetryHttpStatus=params.httpStatus;
561
+ const cause = retryCause(params);
562
+ if (cause) this.#lastRetryCause = cause;
511
563
  }
512
564
  if (frame.method === "session/closed" && this.#busy) {
513
565
  this.fence("Muse session closed during pending work; no replay"); return;
@@ -562,7 +614,7 @@ export class MuseHost {
562
614
  const finish=()=>{
563
615
  if(this.#reason||this.#closing||this.#dead)return;
564
616
  this.#busy=false;
565
- this.#emit({kind:"terminal",turnId:String(params.turnId),status:params.terminal as "completed"|"cancelled"|"failed",frame,lastRetryHttpStatus:this.#lastRetryHttpStatus});
617
+ this.#emit({kind:"terminal",turnId:String(params.turnId),status:params.terminal as "completed"|"cancelled"|"failed",frame,lastRetryHttpStatus:this.#lastRetryHttpStatus,lastRetryCause:this.#lastRetryCause});
566
618
  };
567
619
  // Do not release a completed coding turn (and permit a new auxiliary
568
620
  // host) until refresh metadata is known safe. No credential bytes read.
@@ -620,18 +672,22 @@ export class MuseHost {
620
672
  if (frameBytes > MUSE_INBOUND_FRAME_LIMIT_BYTES) throw new MuseFrameOverInboundLimit(frameBytes);
621
673
  await this.#options.verifyLogin?.();
622
674
  if (!this.#options.echo) {
623
- const result = await this.connection.request("usage/read", {}).catch(error=>{if(!this.#refusal(error) && quotaDenial(error))this.fence("Muse quota refused; no replay");throw error;});
675
+ const result = await this.connection.request("usage/read", {}).catch(error=>{if(!this.#refusal(error) && quotaDenial(error))this.fence(quotaFenceMessage(error));throw error;});
624
676
  const usage = result.usage as any;
625
- publishQuota(usage); this.ledger.quota(usage);
626
- // Muse reports percentages; 100% is the provider's exhausted plan boundary.
627
- if (quotaExhausted(usage)) {
628
- this.fence("Muse plan usage limit reached; no turn submitted");
629
- throw new Error("Muse plan usage limit reached; no turn submitted");
677
+ if (hasQuotaData(usage)) {
678
+ publishQuota(usage); this.ledger.quota(usage);
679
+ // Muse reports percentages; 100% is the provider's exhausted plan boundary.
680
+ if (quotaExhausted(usage)) {
681
+ const resetIso = quotaExhaustedResetIso(usage);
682
+ const msg = `Muse plan usage limit reached (quota exceeded); no turn submitted${resetIso ? ` (resets at ${resetIso})` : ""}`;
683
+ this.fence(msg);
684
+ throw new Error(msg);
685
+ }
630
686
  }
631
687
  }
632
688
  const submission: Submission = { commandId, turnId: undefined, terminal: false, started: false };
633
689
  this.#submission = submission;
634
- this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined;
690
+ this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined; this.#lastRetryCause=undefined;
635
691
  this.#retrySafe = false;
636
692
  this.#busy = true;
637
693
  try {
@@ -673,7 +729,7 @@ export class MuseHost {
673
729
  this.#refusal(error);
674
730
  if (quotaDenial(error) && !policyDenial(error)) {
675
731
  this.ledger.record("quota_refusal", {phase:"turn_admission"});
676
- this.fence("Muse quota refused; no replay");
732
+ this.fence(quotaFenceMessage(error));
677
733
  } else this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
678
734
  throw error;
679
735
  }
package/src/provider.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  } from "pi-tether-core/mcp/bridge";
24
24
  import { openMuseHost, type MuseHost } from "./host.js";
25
25
  import { streamRawCompletion } from "./raw-completion.js";
26
+ import { assertToolSchemasWithinEnumLimit } from "./tool-schema.js";
26
27
  import type { MuseHostOptions } from "./host.js";
27
28
 
28
29
  import { isQualifiedMuseModel, museResponseIdentity, museModelRoute } from "./model-route.js";
@@ -372,11 +373,12 @@ function emitFrame(b: Binding, event: any) {
372
373
  // confirmed by turn/steer. A completed target must fail loudly, not drop it.
373
374
  if (b.steeringPending && event.status === "completed") { b.deferredTerminal=event; return; }
374
375
  if (event.status !== "completed") {
375
- const detail = event.frame?.params?.error?.message;
376
+ const error = event.frame?.params?.error;
377
+ const detail = [error?.message, event.frame?.params?.reason, error?.kind, event.lastRetryCause]
378
+ .find((v): v is string => typeof v === "string" && v.trim().length > 0);
376
379
  // Preserve Pi's native overflow entry path without introducing a new
377
380
  // generic retry policy or replaying an uncertain host request.
378
381
  const overflow = typeof detail === "string" && isContextOverflow({...e.output,stopReason:"error",errorMessage:detail});
379
- const error = event.frame?.params?.error;
380
382
  const status = error?.httpStatus ?? error?.status ?? error?.statusCode ?? (event.status === "failed" ? event.lastRetryHttpStatus : undefined);
381
383
  fail(b, overflow ? `Muse context overflow: ${detail}` : `Muse turn ended ${event.status}${typeof status === "number" ? ` (HTTP ${status})` : ""}${typeof detail === "string" ? `: ${detail}` : ""}`);
382
384
  return;
@@ -394,6 +396,21 @@ function emitFrame(b: Binding, event: any) {
394
396
  content: e.output.content[e.textIndex].text,
395
397
  partial: e.output,
396
398
  });
399
+ const expectsStructured = b.tools.some((t) => t.name === "structured_output");
400
+ const satisfiedStructured = b.messages.some(
401
+ (m: any) => m?.role === "toolResult" && m.toolName === "structured_output" && !m.isError,
402
+ );
403
+ if (expectsStructured && !satisfiedStructured) {
404
+ const textLength = e.output.content
405
+ .filter((part: any) => part?.type === "text" && typeof part.text === "string")
406
+ .reduce((sum: number, part: any) => sum + part.text.length, 0);
407
+ b.host?.ledger?.record("structured_output_omitted", { textLength });
408
+ fail(
409
+ b,
410
+ "Muse turn completed with plain text without calling declared structured_output; plain text preserved on the assistant message, no automatic resubmit",
411
+ );
412
+ return;
413
+ }
397
414
  e.ended = true;
398
415
  e.detachAbort?.();
399
416
  b.messages.push(structuredClone(e.output));
@@ -694,7 +711,6 @@ function streamEffective(model: any, input: any, options: any = {}) {
694
711
  // A genuinely new user request ends the old failure fence. Otherwise that
695
712
  // stale fence would incorrectly block this new request's later tool batch.
696
713
  if(blocked && context.messages.at(-1)?.role==="user")retryBlocks.delete(key);
697
- b = bindings.get(key);
698
714
  if (!context.tools.length)
699
715
  throw new Error("Muse raw completion and compaction are unsupported");
700
716
  const mode = requestedMode;
@@ -710,6 +726,9 @@ function streamEffective(model: any, input: any, options: any = {}) {
710
726
  description: t.description,
711
727
  inputSchema: t.parameters,
712
728
  }));
729
+ // Refuse schemas over the provider's 3,000-enum cap locally before
730
+ // touching any binding or spawning a host; nothing was submitted.
731
+ assertToolSchemasWithinEnumLimit(tools);
713
732
  const declarationHash = projectionHash(tools);
714
733
  const route = museModelRoute(model.id);
715
734
  const signature = requestSignature([model.id, route?.contributorMode, context.systemPrompt, tools, mode, process.cwd()]);
package/src/rate-limit.ts CHANGED
@@ -25,9 +25,33 @@ export function quotaStatusLine(p: ReturnType<typeof quotaPayload>) {
25
25
  const span = mins === null ? "window" : mins % 60 === 0 ? `${mins / 60}h` : `${mins}m`;
26
26
  return `Muse ${span} ${pct(p.window.usedPercent)}${at(p.window.resetsAtMs)} · week ${pct(p.weekly.usedPercent)}`;
27
27
  }
28
+ export function hasQuotaData(u: any): boolean {
29
+ const p = quotaPayload(u);
30
+ return (
31
+ p.observedAtMs !== null ||
32
+ p.tier !== null ||
33
+ p.window.usedPercent !== null ||
34
+ p.window.resetsAtMs !== null ||
35
+ p.window.windowDurationMins !== null ||
36
+ p.weekly.usedPercent !== null ||
37
+ p.weekly.resetsAtMs !== null
38
+ );
39
+ }
28
40
  export function quotaExhausted(u: any) {
29
- return u?.window?.usedPercent >= 100 || u?.weekly?.usedPercent >= 100;
41
+ const windowPct = num(u?.window?.usedPercent);
42
+ const weeklyPct = num(u?.weekly?.usedPercent);
43
+ return (windowPct !== null && windowPct >= 100) || (weeklyPct !== null && weeklyPct >= 100);
30
44
  } // vendor exhausted boundary
45
+ export function quotaExhaustedResetIso(u: any): string | undefined {
46
+ const resets: number[] = [];
47
+ const windowPct = num(u?.window?.usedPercent);
48
+ const windowReset = num(u?.window?.resetsAtMs);
49
+ if (windowPct !== null && windowPct >= 100 && windowReset !== null) resets.push(windowReset);
50
+ const weeklyPct = num(u?.weekly?.usedPercent);
51
+ const weeklyReset = num(u?.weekly?.resetsAtMs);
52
+ if (weeklyPct !== null && weeklyPct >= 100 && weeklyReset !== null) resets.push(weeklyReset);
53
+ return resets.length ? new Date(Math.max(...resets)).toISOString() : undefined;
54
+ }
31
55
  let listener: ((p: ReturnType<typeof quotaPayload>) => void) | undefined;
32
56
  let lastIdentity: string | undefined;
33
57
  export function setQuotaListener(fn: typeof listener) {
@@ -36,7 +36,8 @@ export function streamRawCompletion(model:any, context:any, options:any, makeMes
36
36
  publishRetryStatus(statusOwner);
37
37
  const error=event.frame?.params?.error;
38
38
  const status=error?.httpStatus??error?.status??error?.statusCode??(event.status==="failed"?event.lastRetryHttpStatus:undefined);
39
- if(event.status!=="completed")refuse(new Error(`Muse raw completion ended ${event.status}${typeof status==="number"?` (HTTP ${status})`:""}${error?.message?`: ${error.message}`:""}`));else finish();
39
+ const detail=[error?.message,event.frame?.params?.reason,error?.kind,event.lastRetryCause].find((v):v is string=>typeof v==="string"&&v.trim().length>0);
40
+ if(event.status!=="completed")refuse(new Error(`Muse raw completion ended ${event.status}${typeof status==="number"?` (HTTP ${status})`:""}${detail?`: ${detail}`:""}`));else finish();
40
41
  return;
41
42
  }
42
43
  if(event.kind!=="frame")return;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { isAbsolute, join, resolve } from "node:path";
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { homedir, userInfo } from "node:os";
4
+ import { dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { metadataLedger } from "pi-tether-core/metadata-ledger";
6
6
  import { nativeCounters } from "./usage.js";
7
7
  import { quotaPayload } from "./rate-limit.js";
@@ -11,20 +11,50 @@ function ledgerOrigin(): 'live' | 'test' | 'proof' {
11
11
  const origin = process.env.PI_MUSE_TETHER_LEDGER_ORIGIN;
12
12
  return origin === 'test' || origin === 'proof' ? origin : 'live';
13
13
  }
14
+ /** Resolve symlinks on the nearest existing ancestor so symlinked state dirs cannot alias production. */
15
+ function canonicalPath(target: string): string {
16
+ const abs = resolve(target);
17
+ const tail: string[] = [];
18
+ let cursor = abs;
19
+ for (;;) {
20
+ try {
21
+ const real = realpathSync(cursor);
22
+ return tail.length ? join(real, ...tail.reverse()) : real;
23
+ } catch (error: any) {
24
+ if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') return abs;
25
+ const parent = dirname(cursor);
26
+ if (parent === cursor) return abs;
27
+ tail.push(cursor.slice(parent.length).replace(/^\/+/, ''));
28
+ cursor = parent;
29
+ }
30
+ }
31
+ }
32
+ function productionLedgerPaths(): string[] {
33
+ const homes = new Set<string>([homedir()]);
34
+ try { homes.add(userInfo().homedir); } catch { /* passwd entry unavailable */ }
35
+ return [...homes].map(home => canonicalPath(join(home, '.local/state/pi-muse-tether/requests.jsonl')));
36
+ }
14
37
  const num = (v: any) =>
15
38
  typeof v === "number" && Number.isFinite(v) ? v : null;
16
39
  export function museLedgerPath() {
40
+ const explicit = process.env.PI_MUSE_TETHER_LEDGER_PATH;
17
41
  const state = process.env.XDG_STATE_HOME;
18
42
  // XDG Base Directory requires absolute values; empty/relative values are
19
43
  // treated as unset, never a request to write metadata beneath the cwd.
20
- const path = join(
21
- state && isAbsolute(state) ? state : join(homedir(), ".local/state"),
22
- "pi-muse-tether",
23
- "requests.jsonl",
24
- );
25
- if (ledgerOrigin() !== 'live' && (!state || !isAbsolute(state) ||
26
- resolve(path) === join(homedir(), '.local/state/pi-muse-tether/requests.jsonl'))) {
27
- throw new Error('Test/proof request ledger requires an isolated absolute XDG_STATE_HOME; refusing the production ledger.');
44
+ const hasExplicit = Boolean(explicit && isAbsolute(explicit));
45
+ const path = hasExplicit
46
+ ? resolve(explicit!)
47
+ : join(
48
+ state && isAbsolute(state) ? state : join(homedir(), ".local/state"),
49
+ "pi-muse-tether",
50
+ "requests.jsonl",
51
+ );
52
+ if (ledgerOrigin() !== 'live') {
53
+ const prodPaths = productionLedgerPaths();
54
+ const resolved = canonicalPath(path);
55
+ if ((!hasExplicit && (!state || !isAbsolute(state))) || prodPaths.includes(resolved)) {
56
+ throw new Error('Test/proof request ledger requires an isolated absolute XDG_STATE_HOME or PI_MUSE_TETHER_LEDGER_PATH; refusing the production ledger.');
57
+ }
28
58
  }
29
59
  return path;
30
60
  }
@@ -95,6 +125,7 @@ export class MuseLedger {
95
125
  attempt: num(p.attempt), nextAttempt: num(p.nextAttempt), maxAttempts: num(p.maxAttempts),
96
126
  retryDelayMs: num(p.retryDelayMs), httpStatus: num(p.httpStatus),
97
127
  errorKind: typeof p.errorKind === "string" ? p.errorKind : null,
128
+ reason: typeof p.reason === "string" ? p.reason : null,
98
129
  system: typeof p.system === "string" ? p.system : null,
99
130
  sourceRange: p.sourceRange ?? null, viewCursor: p.viewCursor ?? null,
100
131
  });
@@ -8,14 +8,35 @@ export function publishRedactionStatus(owner: object, count: number) {
8
8
  statuses.set(owner, `Muse redacted ${count} tool-result span${count === 1 ? "" : "s"} (vendor limit; not byte-exact model input)`);
9
9
  listener?.([...statuses.values()].at(-1));
10
10
  }
11
+ const text = (v: unknown) => (typeof v === "string" && v.trim().length ? v.trim() : undefined);
12
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
13
+
14
+ /** Extract the real underlying cause from a retry notification without rendering undefined/null. */
15
+ export function retryCause(params?: Record<string, any>): string | undefined {
16
+ if (!params || typeof params !== "object") return undefined;
17
+ const detail = text(params.errorKind) ?? text(params.reason) ?? text(params.error?.message) ?? text(params.error?.kind);
18
+ const parts = [text(params.system), detail].filter((v): v is string => Boolean(v));
19
+ return parts.length ? parts.join(": ") : undefined;
20
+ }
21
+
11
22
  export function publishRetryStatus(owner: object, params?: Record<string, any>) {
12
23
  statuses.delete(owner);
13
24
  if(params){
14
25
  // The durable retry kind and HTTP status are optional open-vocabulary vendor
15
26
  // fields; the recorded stopping reason is the real cause when either is absent.
16
- const cause=[typeof params.system==="string"?params.system:undefined,typeof params.errorKind==="string"?params.errorKind:params.reason]
17
- .filter(v=>typeof v==="string"&&v.length).join(": ");
18
- statuses.set(owner, `Muse retry ${params.nextAttempt}/${params.maxAttempts} scheduled in ${params.retryDelayMs} ms (${cause||"cause not reported"}${params.httpStatus===undefined ? "" : `, HTTP ${params.httpStatus}`})`);
27
+ const cause = retryCause(params);
28
+ const nextAttempt = num(params.nextAttempt);
29
+ const maxAttempts = num(params.maxAttempts);
30
+ const retryDelayMs = num(params.retryDelayMs);
31
+ const httpStatus = num(params.httpStatus);
32
+ const attempt = nextAttempt !== undefined && maxAttempts !== undefined
33
+ ? ` ${nextAttempt}/${maxAttempts}`
34
+ : nextAttempt !== undefined
35
+ ? ` ${nextAttempt}`
36
+ : "";
37
+ const delay = retryDelayMs !== undefined ? ` in ${retryDelayMs} ms` : "";
38
+ const status = httpStatus !== undefined ? `, HTTP ${httpStatus}` : "";
39
+ statuses.set(owner, `Muse retry${attempt} scheduled${delay} (${cause || "cause not reported"}${status})`);
19
40
  }
20
41
  listener?.([...statuses.values()].at(-1));
21
42
  }
@@ -10,7 +10,8 @@ const imageMagic: Record<string, (b: Buffer) => boolean> = {
10
10
  "image/gif": b => ["GIF87a", "GIF89a"].includes(b.subarray(0,6).toString("ascii")),
11
11
  "image/webp": b => b.subarray(0,4).toString("ascii") === "RIFF" && b.subarray(8,12).toString("ascii") === "WEBP",
12
12
  };
13
- function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
13
+ type ImageDimensions = { width: number; height: number };
14
+ function imageDeclarations(sent: BridgeResult, dimensions?: Map<number, ImageDimensions>): UnverifiableImage[] {
14
15
  const images: UnverifiableImage[] = [];
15
16
  for (const [partIndex, part] of sent.content.entries()) {
16
17
  if (part.type === "text" && typeof part.text === "string") continue;
@@ -19,6 +20,8 @@ function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
19
20
  const bytes = Buffer.from(part.data, "base64");
20
21
  if (bytes.toString("base64") !== part.data || !imageMagic[part.mimeType](bytes))
21
22
  throw new Error("Muse tool result cannot verify MCP parts: malformed image encoding or MIME signature");
23
+ const size = dimensions && parseImageDimensions(bytes, part.mimeType);
24
+ if (size) dimensions!.set(partIndex, size);
22
25
  images.push({ partIndex, sha256: createHash("sha256").update(bytes).digest("hex"), byteLen: bytes.length, mimeType: part.mimeType,
23
26
  ...(sent.isError === true ? {modelVisibility: "omitted-error-result" as const} : {}) });
24
27
  }
@@ -27,6 +30,71 @@ function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
27
30
  export function assertToolResultVerifiable(sent: BridgeResult): void {
28
31
  imageDeclarations(sent);
29
32
  }
33
+
34
+ // Header facts only; signatures have already been checked. Replace this
35
+ // local reader with shared result-parts image identities when available.
36
+ function parseImageDimensions(bytes: Buffer, mimeType: string): ImageDimensions | undefined {
37
+ let width = 0, height = 0;
38
+ if (mimeType === "image/png" && bytes.length >= 24 && bytes.readUInt32BE(8) === 13 &&
39
+ bytes.toString("latin1", 12, 16) === "IHDR") {
40
+ width = bytes.readUInt32BE(16);
41
+ height = bytes.readUInt32BE(20);
42
+ } else if (mimeType === "image/gif" && bytes.length >= 10) {
43
+ width = bytes.readUInt16LE(6);
44
+ height = bytes.readUInt16LE(8);
45
+ } else if (mimeType === "image/webp" && bytes.length >= 20) {
46
+ const riffEnd = bytes.readUInt32LE(4) + 8;
47
+ const chunkLength = bytes.readUInt32LE(16);
48
+ if (riffEnd > bytes.length || 20 + chunkLength + (chunkLength % 2) > riffEnd) return;
49
+ const kind = bytes.toString("latin1", 12, 16);
50
+ if (kind === "VP8X" && chunkLength >= 10) {
51
+ width = 1 + bytes.readUIntLE(24, 3);
52
+ height = 1 + bytes.readUIntLE(27, 3);
53
+ } else if (kind === "VP8L" && chunkLength >= 5 && bytes[20] === 0x2f) {
54
+ const bits = bytes.readUInt32LE(21);
55
+ width = 1 + (bits & 0x3fff);
56
+ height = 1 + ((bits >>> 14) & 0x3fff);
57
+ } else if (kind === "VP8 " && chunkLength >= 10 && (bytes[20] & 1) === 0 &&
58
+ bytes[23] === 0x9d && bytes[24] === 0x01 && bytes[25] === 0x2a) {
59
+ width = bytes.readUInt16LE(26) & 0x3fff;
60
+ height = bytes.readUInt16LE(28) & 0x3fff;
61
+ }
62
+ } else if (mimeType === "image/jpeg") {
63
+ let i = 2;
64
+ while (i < bytes.length && bytes[i++] === 0xff) {
65
+ while (bytes[i] === 0xff) i++;
66
+ if (i >= bytes.length) break;
67
+ const marker = bytes[i++];
68
+ if (marker === 0xd9 || marker === 0xda || marker === 0x00) break;
69
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
70
+ if (i + 2 > bytes.length) break;
71
+ const length = bytes.readUInt16BE(i);
72
+ if (length < 2 || i + length > bytes.length) break;
73
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
74
+ if (length >= 8) {
75
+ height = bytes.readUInt16BE(i + 3);
76
+ width = bytes.readUInt16BE(i + 5);
77
+ }
78
+ break;
79
+ }
80
+ i += length;
81
+ }
82
+ }
83
+ if (width && height) return { width, height };
84
+ }
85
+
86
+ const imagePlaceholder = /^\[MCP image content: media_type=(image\/(?:png|jpeg|webp|gif)), bytes=([1-9]\d*)(?:, dimensions=([1-9]\d*x[1-9]\d*)(?:, source_dimensions=([1-9]\d*x[1-9]\d*))?)?\]$/;
87
+ function matchesMuseImagePlaceholder(line: string, image: UnverifiableImage, size?: ImageDimensions): boolean {
88
+ const match = imagePlaceholder.exec(line);
89
+ if (!match || match[0] !== line) return false;
90
+ const [, mime, bytes, dimensions, sourceDimensions] = match;
91
+ if (!dimensions) return mime === image.mimeType && bytes === String(image.byteLen);
92
+ if (!size) return false;
93
+ const source = `${size.width}x${size.height}`;
94
+ // Muse can re-encode an image with or without changing its dimensions.
95
+ // The normalized MIME and size are descriptive, not evidence of source bytes.
96
+ return sourceDimensions ? sourceDimensions === source && dimensions !== source : dimensions === source;
97
+ }
30
98
  /** visibleBytes includes any displayed ellipsis; candidate offsets address the original projection. */
31
99
  export type TruncatedView = { visibleBytes: number; projectionBytes: number; omittedOffsetBytes: number; omittedByteLen: number; sha256: string; ellipsisIdentity: "not-present" | "generated" | "ambiguous"; candidateOmittedOffsetsBytes: number[]; sources: {partIndex:number;partOffsetBytes:number;byteLen:number}[] };
32
100
  /** MSP 1.4.14 live capture: 65,536 view bytes ended with U+2026, after an
@@ -36,7 +104,8 @@ function viewPrefixes(visible: string, full: string): string[] {
36
104
  return candidates.filter(prefix => !(prefix.length && /[\uD800-\uDBFF]/.test(prefix.at(-1)!)) && full.startsWith(prefix));
37
105
  }
38
106
  export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void, onTruncatedView?: (view: TruncatedView) => void): BridgeResult {
39
- const images = imageDeclarations(sent);
107
+ const dimensions = new Map<number, ImageDimensions>();
108
+ const images = imageDeclarations(sent, sent.isError === true ? undefined : dimensions);
40
109
  if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
41
110
  if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
42
111
  if (item.truncated !== undefined && typeof item.truncated !== "boolean")
@@ -60,25 +129,29 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
60
129
  }
61
130
  // Construct the ordered native projection from Pi parts. Never search/remove
62
131
  // placeholder-shaped strings: literal tool text and leading LF remain bytes.
63
- let expected = "";
132
+ let expected = "", expectedLine = 0;
133
+ const actualLines = images.length && sent.isError !== true ? actual.split("\n") : [];
64
134
  const protectedImages: { start: number; end: number }[] = [];
65
135
  const textSources: {partIndex:number; start:number; end:number}[] = [];
66
136
  for (const [index, part] of sent.content.entries()) {
67
137
  if (part.type === "text") {
68
138
  // Native string folding ignores leading empty chunks but preserves a
69
139
  // separator before an empty chunk after nonempty output (captured live).
70
- if (expected) expected += "\n";
140
+ if (expected) { expected += "\n"; expectedLine++; }
71
141
  const start = Buffer.byteLength(expected);
72
142
  expected += part.text;
143
+ if (actualLines.length) expectedLine += part.text.split("\n").length - 1;
73
144
  textSources.push({partIndex:index,start,end:Buffer.byteLength(expected)});
74
145
  } else {
75
146
  // The official client's failed MCP path projects text only. Images were
76
147
  // delivered to MCP, NOT exposed to the model; declare that known loss.
77
148
  if (sent.isError === true) continue;
78
149
  const image = images.find(image => image.partIndex === index)!;
79
- if (expected) expected += "\n";
150
+ if (expected) { expected += "\n"; expectedLine++; }
80
151
  const start = expected.length;
81
- expected += `[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]`;
152
+ const line = actualLines[expectedLine];
153
+ expected += line !== undefined && matchesMuseImagePlaceholder(line, image, dimensions.get(index)) ? line :
154
+ `[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]`;
82
155
  protectedImages.push({ start, end: expected.length });
83
156
  }
84
157
  }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The Muse provider API rejects any tool parameter JSON schema whose total
3
+ * enum values across all `enum` properties exceed 3,000. Vendor-imposed, not
4
+ * chosen here: observed 2026-11-20 against the Muse provider API as
5
+ * `API error 400: JSON schema exceeds the maximum of 3000 total enum values
6
+ * across all enum properties (invalid_request_error) [param=parameters]`
7
+ * (~3,750 enum values rejected; half-size payload accepted).
8
+ */
9
+ export const MUSE_TOOL_SCHEMA_ENUM_LIMIT = 3_000;
10
+
11
+ /** Count total values across every `enum` array inside a JSON Schema object. */
12
+ export function countSchemaEnumValues(schema: unknown, seen = new Set<object>()): number {
13
+ if (!schema || typeof schema !== "object") return 0;
14
+ if (seen.has(schema)) return 0;
15
+ seen.add(schema);
16
+ if (Array.isArray(schema)) {
17
+ let total = 0;
18
+ for (const item of schema) total += countSchemaEnumValues(item, seen);
19
+ return total;
20
+ }
21
+ let total = 0;
22
+ for (const [key, value] of Object.entries(schema as Record<string, unknown>)) {
23
+ if (key === "enum" && Array.isArray(value)) {
24
+ total += value.length;
25
+ } else if (value && typeof value === "object") {
26
+ total += countSchemaEnumValues(value, seen);
27
+ }
28
+ }
29
+ return total;
30
+ }
31
+
32
+ /** Nothing was submitted: the provider API rejects schemas above this enum cap. */
33
+ export class MuseToolSchemaEnumLimitError extends Error {
34
+ readonly code = "MUSE_TOOL_SCHEMA_ENUM_LIMIT";
35
+ constructor(
36
+ readonly toolName: string,
37
+ readonly enumCount: number,
38
+ readonly limit: number = MUSE_TOOL_SCHEMA_ENUM_LIMIT,
39
+ ) {
40
+ super(
41
+ `Muse request not sent: tool "${toolName}" JSON schema has ${enumCount} total enum values, exceeding the provider limit of ${limit} total enum values across all enum properties (source: observed 2026-11-20 from the Muse provider API as HTTP 400 invalid_request_error [param=parameters]). Simplify or split the schema and retry; nothing was submitted.`,
42
+ );
43
+ }
44
+ }
45
+
46
+ export function assertToolSchemasWithinEnumLimit(
47
+ tools: ReadonlyArray<{ name: string; inputSchema: unknown }>,
48
+ limit: number = MUSE_TOOL_SCHEMA_ENUM_LIMIT,
49
+ ): void {
50
+ for (const tool of tools) {
51
+ const count = countSchemaEnumValues(tool.inputSchema);
52
+ if (count > limit) throw new MuseToolSchemaEnumLimitError(tool.name, count, limit);
53
+ }
54
+ }