pi-muse-tether 0.2.1 → 0.2.3

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3 — 2026-11-23
4
+
5
+ - Tests now refuse to write to the real request ledger, even when a test path points to it indirectly.
6
+ - Temporary rate limits no longer stop the client from retrying. Quota errors show the reset time when available, and empty usage events are ignored.
7
+ - 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.
8
+
9
+ ## 0.2.2 — 2026-11-20
10
+
11
+ - 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.
12
+ - A retry notification with an unknown or missing vendor `errorKind` is no longer fatal: the live turn continues and its status line shows the recorded cause, system and HTTP status instead of `undefined`. Observed real Wonder Full retries sent no kind and no status at all. A retry the vendor sends with no `errorKind` is honoured when this turn already saw a 5xx.
13
+ - Pi tools have a one-hour deadline in the private Muse host instead of hitting Muse's default five-minute tool deadline. A native timeout still settles only that call, not the whole turn. Muse consumes a timeout result and continues; Pi's late result stays journaled in Pi and is never replayed to Muse. The divergence is ledger-recorded with `exactModelConsumption:false`. Approval-hold behavior for native timeouts during held approvals is unchanged.
14
+ - A failed catalogue discovery no longer replaces the working catalogue with an empty one: the turn warns with the cause, the catalogue in use is kept so `/model` keeps working, and `/muse-doctor` reports the failure.
15
+ - Add `/muse-doctor ledger`: counts live rows only, splits them by event type and requested model, and reports every excluded row with its reason (test, proof, pre-0.2.1 rows without `origin`, unreadable lines).
16
+
3
17
  ## 0.2.1
4
18
 
5
19
  - Follow the official auto-updating Muse client; unknown builds run sequential Pi tools instead of refusing all turns. Parallel tools use qualification records, negotiated rawLog and runtime schema checks.
package/README.md CHANGED
@@ -45,6 +45,8 @@ Only thinking levels present in that model’s catalogue are offered; unsupporte
45
45
 
46
46
  The tether starts the official Muse client in the background and passes it Pi's system prompt, tools and history. When the model asks for a tool, the call comes back to Pi, as the diagram shows. Pi runs it under its normal guards and saves the result to its own history, and only then does the tether send the result back to Muse.
47
47
 
48
+ A session is bounded by the client, not by Pi: the official client refuses any single inbound message larger than 10 MiB (10,485,760 bytes). That covers the history imported on a cold start or a continued session, and base64 images count toward it even though they cost Pi few tokens. When a turn would exceed it, the tether refuses before sending, says the measured size and the limit, and Pi's own compaction then shrinks the history and retries once. If the session is still too large, start a new one.
49
+
48
50
  ## How close it is to the direct API
49
51
 
50
52
  I ran two real coding tasks through each route, once per route, on a build from just before this release. These are single runs, so read them as a rough comparison. [How I measured](docs/DETAILS.md#how-i-measured).
@@ -58,6 +60,12 @@ I ran two real coding tasks through each route, once per route, on a build from
58
60
 
59
61
  The last row is the difference you will notice most.
60
62
 
63
+ ## The request ledger
64
+
65
+ Every turn appends metadata-only rows to `~/.local/state/pi-muse-tether/requests.jsonl` (or `$XDG_STATE_HOME`): timing, token counts, retries, refusals and lifecycle events. No prompt, tool body, image bytes or credential is written. Since 0.2.1 each row also carries `origin` (`live`, `test` or `proof`) and the package version, and tests and proofs run in an isolated state directory.
66
+
67
+ Read it with `/muse-doctor ledger`. It counts live rows only, splits them by event type and requested model, and reports how many rows it excluded and why. Rows written before 0.2.1 have no `origin`, so they are reported as `unknown` rather than guessed at. Counting with `grep` over the raw file mixes fixture rows, legacy rows and passing mentions of an error string; this has produced wrong failure analyses before.
68
+
61
69
  ## Why not something else
62
70
 
63
71
  | Option | Why I didn't use it |
package/docs/DETAILS.md CHANGED
@@ -47,6 +47,8 @@ Muse sees names such as `mcp__pi__read`; Pi's actual names, schemas and executio
47
47
 
48
48
  Completed turns can reuse one ephemeral host while model, prompt, tools, working directory, owner and acknowledged history prefix match. Changed completed context imports the selected Pi branch as ordered inert JSON, not API-role replay. Historical calls are not dispatched; unresolved calls stay unresolved; thinking is omitted. Supported user images retain block references. Unsupported media refuses. A newly proposed action can still semantically duplicate an earlier action: there is no exactly-once semantic guarantee.
49
49
 
50
+ **Imported frame limit:** the official client refuses any single inbound message larger than 10,485,760 bytes (10 MiB). That limit is the client's, measured offline against 1.4.14/1.4.15 (10,485,760 bytes accepted, 10,485,761 rejected) and shipped as the SDK's frame limit. The tether measures the exact `turn/start` line before sending: history, current input and base64 images all count, even though images cost Pi few tokens. An oversized frame is refused with the measured size, the limit and the next step, and nothing is submitted; Pi's overflow recovery then compacts the history and retries once. If that still exceeds the limit, start a new Pi session.
51
+
50
52
  **Restart/cache limitation:** restarting Pi or Muse can require a cold full-history request. Some warm requests also miss cache. Cache key, scope and TTL remain unknown; no billed keepalive or cache-miss replay is used. Keeping a Muse host alive across Pi restarts is not implemented, and saving a vendor session alone is not a demonstrated cache fix.
51
53
 
52
54
  Raw summaries use separate ephemeral owners, no tools/MCP, one nonempty text assistant and native usage. Unexpected helpers/tools, multiple messages, failures or missing usage reject the summary without retiring the coding binding. Only committed Pi compaction retires it. Pi owns thresholds, persistence and re-import; there is no vendor compact command or fabricated summary.
@@ -59,13 +61,13 @@ For a desired 450,000-token compaction boundary, calculate `reserveTokens = actu
59
61
 
60
62
  Parallel coding requires matching qualification evidence, the experimental `rawLog` grant, a `session.live` subscription and schema-checked `assistant_tool_calls_committed` boundaries. Unknown builds, missing support, gaps or shape mismatches degrade to sequential tools with one notice, without timers, replay or client substitution. Concurrent native MCP calls queue and are verified one at a time. A degradation also releases approvals waiting on a lost boundary, so fallback cannot strand the turn. One Pi assistant contains the ordered tool batch; Pi validates/coerces its original arguments and journals validation errors or execution results before native approvals are released for exact receipt retrieval. Invalid arguments therefore produce the normal Pi validation message, not an opaque native approval denial. Native/MCP identity still binds the unchanged original arguments, including when Pi coerces them for execution. Raw records are consumed in memory, not logged wholesale.
61
63
 
62
- **Long-tool limit:** a historical native MCP task timed out around 300 seconds while Pi was still running. Approval holding now avoids opening that native call during Pi execution. One synthetic 301-second live tool passed with the native MCP call open only briefly. That establishes the measured interval, **not unlimited approval patience or arbitrary long-build support**. No vendor no-deadline control is qualified. A late denial, timeout or host death can leave a real Pi side effect without a verified native receipt. Fencing cannot undo it or silently kill Pi's executor. Inspect uncertain effects before a new request; unknown work is never automatically replayed.
64
+ **Long-tool limit:** Muse defaults to 300 seconds per MCP call. Its [documented `tool_timeout_sec`](https://meta-models.github.io/muse-code-sdk/1.4/guides/extend/mcp-servers/) is available in settings, not in MSP's `SessionMcpServerConfig`. The tether stages only the required Pi broker in the ephemeral host's private settings and gives it the same one-hour budget as the Claude tether. Each host still owns one session and one Pi broker; inventory and approvals remain bound to that session. No personal Muse settings are changed. Pi's own cancellation and tool-specific deadlines still apply. If a native timeout occurs, Muse consumes it for that call and continues; Pi can journal its late result, but the tether records the divergence as declared-lossy and never replays it. On qualified batch builds the approval hold still avoids opening the native call until Pi has journaled the result.
63
65
 
64
66
  Abort propagates Pi's signal, retires the host/bridge and retains emitted content and effects; no warm reuse after abort is promised. Steering uses Pi's queue and journals results before continuation. Scripted probes cover stream/tool/approval races, not every interactive TUI race or a long-tool abort.
65
67
 
66
68
  ### Vendor retries
67
69
 
68
- Each authored SDK command is sent once by the tether, but Muse may retry transient/server model failures inside the same turn before Pi sees an answer. Pi's retry setting cannot prevent those attempts. Retry notifications are not extra known billable completions. Refusal, auth, quota, policy and attestation checks stop first; unknown retry kinds fail closed and exhaustion preserves HTTP status. An uncertain Pi retry refuses without new admission. Only known nothing-admitted overloaded/backpressured SDK errors allow an ordinary subsequent attempt.
70
+ Each authored SDK command is sent once by the tether, but Muse may retry transient/server model failures inside the same turn before Pi sees an answer. Pi's retry setting cannot prevent those attempts. Retry notifications are not extra known billable completions. Refusal, auth, quota, policy and attestation checks stop first. The vendor's retry kind and HTTP status are optional open-vocabulary fields, so an unknown or missing kind is reported with the recorded cause instead of ending a live turn, and exhaustion preserves the HTTP status. An uncertain Pi retry refuses without new admission. Only known nothing-admitted overloaded/backpressured SDK errors allow an ordinary subsequent attempt.
69
71
 
70
72
  No pinned SDK per-turn disable-retry control is qualified. Startup retry settings have been observed in offline surfaces but effective loading and zero-retry semantics remain unproved; they are not applied by this tether.
71
73
 
package/index.ts CHANGED
@@ -55,18 +55,26 @@ export async function registerMuseExtension(pi: ExtensionAPI, provider = {stream
55
55
  // changed limits/efforts must reach Pi even when the IDs have not changed.
56
56
  const modelShape = (models: typeof catalogue.models) =>
57
57
  JSON.stringify([...models].sort((a, b) => a.id.localeCompare(b.id)));
58
- pi.on("agent_end", async () => {
58
+ const warnDiscovery = (ctx: any, error: string) =>
59
+ ctx.ui.notify(`[pi-muse-tether] Catalogue discovery failed: ${error}. Keeping the available catalogue; see /muse-doctor.`, "warning");
60
+ pi.on("agent_end", async (_event, ctx) => {
59
61
  const next = await discover();
62
+ if ("error" in next.diagnostics && next.diagnostics.error !== undefined) {
63
+ catalogue = {...next, models: catalogue.models};
64
+ warnDiscovery(ctx, next.diagnostics.error);
65
+ return;
66
+ }
60
67
  const changed = modelShape(next.models) !== modelShape(catalogue.models);
61
68
  catalogue = next;
62
69
  if (changed) registerProvider();
63
70
  });
64
- pi.registerCommand("muse-doctor", {description:"Muse client and qualification diagnostic; qualify [build] [--live]",handler:async(args,ctx)=>{
71
+ pi.registerCommand("muse-doctor", {description:"Muse client and qualification diagnostic; ledger, qualify [build] [--live]",handler:async(args,ctx)=>{
65
72
  if (args.split(/\s+/).includes("--live") && !await ctx.ui.confirm("Live Muse qualification", "Runs model requests (batch, private prompt, MCP, resume, image) in isolated state using your existing login. Proceed?")) return;
66
73
  try { ctx.ui.notify(JSON.stringify({...JSON.parse(await museDoctor(ctx.model?.id, args)),catalogue:catalogue.diagnostics},null,2),"info"); }
67
74
  catch(error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); }
68
75
  }});
69
76
  pi.on("session_start", async (_event, ctx) => {
77
+ if ("error" in catalogue.diagnostics && catalogue.diagnostics.error !== undefined) warnDiscovery(ctx, catalogue.diagnostics.error);
70
78
  if (process.env.PI_MUSE_TETHER_LIVE !== "1") ctx.ui.notify(featureNotice(clientBuildLabel(),"catalogue","PI_MUSE_TETHER_LIVE is unset","empty live catalogue; set PI_MUSE_TETHER_LIVE=1 to enable official discovery"),"warning");
71
79
  if (process.env.PI_MUSE_TETHER_LIVE === "1") {
72
80
  try { const status=clientStatus(false); ctx.ui.notify(`[pi-muse-tether] ${JSON.stringify(status)}; vendor updates are governed by capability/schema checks.`, "info"); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-muse-tether",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "description": "Use your Muse Code subscription in Pi through the official client",
6
6
  "license": "MIT",
package/src/doctor.ts CHANGED
@@ -5,6 +5,7 @@ import { museFeatureStatus } from "./features.js";
5
5
  import { qualifyClient } from "./qualification.js";
6
6
  import { qualifyMuseVersion, MIN_CLI_VERSION, TESTED_CLI_MAX, isNewerThanTestedCli, strictCliVersion } from "./cli-version.js";
7
7
  import { museLedgerPath } from "./request-ledger.js";
8
+ import { summarizeMuseLedger } from "./ledger-stats.js";
8
9
  import { MUSE_CACHE_POLICY } from "./cache-policy.js";
9
10
  /** Local diagnostic only: --version, no account/auth contents, quota or inference. */
10
11
  export async function museDoctor(modelId?: string, args = "") {
@@ -14,7 +15,11 @@ export async function museDoctor(modelId?: string, args = "") {
14
15
  if (builds.length > 1 || arguments_.some(value=>value.startsWith("--") && value !== "--live")) throw new Error("Usage: /muse-doctor qualify [build] [--live]");
15
16
  return JSON.stringify(await qualifyClient(builds[0],arguments_.includes("--live"),modelId ? museModelRoute(modelId)?.modelId : undefined),null,2);
16
17
  }
17
- if (command && command !== "qualify") throw new Error("Unknown /muse-doctor command; use /muse-doctor or /muse-doctor qualify [build] [--live]");
18
+ if (command === "ledger") {
19
+ if (arguments_.length) throw new Error("Usage: /muse-doctor ledger");
20
+ return JSON.stringify(await summarizeMuseLedger(), null, 2);
21
+ }
22
+ if (command && command !== "qualify") throw new Error("Unknown /muse-doctor command; use /muse-doctor, /muse-doctor ledger or /muse-doctor qualify [build] [--live]");
18
23
  const binary = resolveMuseBinary();
19
24
  const { META_API_KEY: _, ...env } = process.env;
20
25
  try {
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";
@@ -23,12 +24,47 @@ import {
23
24
  /** Inventory recheck pacing while Muse 1.4.15 starts session MCP (~200 ms measured). */
24
25
  const MCP_READY_RECHECK_MS = 25;
25
26
 
27
+ /**
28
+ * The official Muse Code client's app-server refuses any single inbound JSON-RPC
29
+ * frame larger than 10,485,760 bytes (10 MiB). Vendor-imposed, not chosen here:
30
+ * measured offline against 1.4.14/1.4.15 (2026-11-11) — 10,485,760 bytes
31
+ * accepted, 10,485,761 rejected with {code:-32002, kind:"inputTooLarge",
32
+ * limitBytes:10485760, retryable:false} — and @muse-code/sdk ships the same
33
+ * value as its private DEFAULT_FRAME_LIMIT_BYTES.
34
+ */
35
+ export const MUSE_INBOUND_FRAME_LIMIT_BYTES = 10_485_760;
36
+
37
+ /** The SDK writes one JSON line per frame; measure that exact line before sending. */
38
+ function turnStartFrameBytes(params: Record<string, unknown>): number {
39
+ // The numeric request id is minted inside the SDK connection, so it is
40
+ // measured as a single digit: a few bytes never decide admission here.
41
+ return Buffer.byteLength(`${JSON.stringify({ jsonrpc: "2.0", id: 0, method: "turn/start", params })}\n`);
42
+ }
43
+
44
+ /** Nothing was submitted: the client cannot read a frame this large. */
45
+ export class MuseFrameOverInboundLimit extends Error {
46
+ readonly code = "MUSE_FRAME_TOO_LARGE";
47
+ constructor(readonly frameBytes: number, readonly limitBytes: number = MUSE_INBOUND_FRAME_LIMIT_BYTES) {
48
+ super(`Muse turn not sent: this turn/start frame is ${frameBytes} bytes, which exceeds the limit of ${limitBytes} bytes the Muse client accepts in one inbound frame (source: official Muse Code client app-server, the same value as the SDK frame limit; measured 2026-11-11: 10,485,760 bytes accepted, 10,485,761 rejected). History, current input and base64 images all count toward the frame. Compact the Pi session or start a new one, then retry; nothing was submitted.`);
49
+ }
50
+ }
51
+
52
+ /** The client's own refusal of an oversized frame, reported with its limit. */
53
+ function inputTooLarge(error: unknown): number | undefined {
54
+ if (!error || typeof error !== "object") return undefined;
55
+ const value = error as Record<string, any>;
56
+ const kind = value.kind ?? value.errorKind ?? value.data?.kind;
57
+ if (value.code !== -32002 && kind !== "inputTooLarge") return undefined;
58
+ const limit = value.data?.limitBytes ?? value.limitBytes;
59
+ return typeof limit === "number" && limit > 0 ? limit : MUSE_INBOUND_FRAME_LIMIT_BYTES;
60
+ }
61
+
26
62
  type InitializeResult = Parameters<typeof readSessionDurability>[0];
27
63
  export type MuseApproval = Parameters<ApprovalHandler>[0];
28
64
  export type MuseFrame = { method: string; params?: Record<string, unknown> };
29
65
  export type MuseHostEvent =
30
66
  | { kind: "frame"; frame: MuseFrame }
31
- | { 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 }
32
68
  | { kind: "fenced"; reason: string }
33
69
  | { kind: "degraded"; feature: "rawLog"; reason: string }
34
70
  | { kind: "tool-batch"; calls: Array<{callId:string;name:string;args:Record<string,unknown>}> }
@@ -107,15 +143,60 @@ export function serverRequiresUpgrade(error: unknown, seen = new Set<unknown>())
107
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;
108
144
  return [value.error,value.data,value.cause].some(nested => serverRequiresUpgrade(nested,seen));
109
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
+ */
110
153
  function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
111
154
  if (!error || typeof error !== "object" || seen.has(error)) return false;
112
155
  seen.add(error);
113
156
  const value = error as Record<string, unknown>;
114
- if ([value.status, value.httpStatus, value.statusCode, value.code].includes(429) || value.quota !== undefined ||
115
- [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;
116
160
  return [value.data, value.error, value.cause].some(nested => quotaDenial(nested, seen));
117
161
  }
118
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
+
119
200
  const canonical = (v:any):string => v && typeof v === "object"
120
201
  ? Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
121
202
  : JSON.stringify(v);
@@ -160,6 +241,24 @@ export function museLaunchOptions(options: MuseHostOptions): SpawnMspConnectionO
160
241
  };
161
242
  }
162
243
 
244
+ /** The private host owns one workspace, one Pi broker and one Muse session.
245
+ * Only the settings-file registry exposes Muse's per-server tool deadline.
246
+ * The same name in both registries is rejected by session/start. */
247
+ function privatePiMcp(options: MuseHostOptions) {
248
+ if (!options.privateWorkspace) return undefined;
249
+ const pi = options.mcpServers?.pi as {transport?: string; command?: string; framing?: string} | undefined;
250
+ if (pi?.transport !== "stdio" || !pi.command) return undefined;
251
+ const framing = pi.framing === "lineDelimitedJson" ? "line_delimited_json"
252
+ : pi.framing === "contentLength" ? "content_length" : pi.framing;
253
+ return {
254
+ ...pi, framing, mode: "required",
255
+ // Muse documents no unlimited value. Match the Claude tether's existing
256
+ // one-hour DEFAULT_MCP_TOOL_TIMEOUT_MS (pi-claude-tether src/process-manager.ts).
257
+ // https://meta-models.github.io/muse-code-sdk/1.4/guides/extend/mcp-servers/
258
+ tool_timeout_sec: 3600,
259
+ };
260
+ }
261
+
163
262
  /** Deliberately hides submit/replay/pending mutators from the driver-facing type. */
164
263
  type Submission = { commandId: string; turnId?: string; terminal: boolean; started: boolean;
165
264
  admit?: () => void; refuse?: (error: Error) => void };
@@ -188,6 +287,7 @@ export class MuseHost {
188
287
  #committedCalls = new Map<string, string>();
189
288
  #committedBatches = new Set<string>();
190
289
  #lastRetryHttpStatus?: number;
290
+ #lastRetryCause?: string;
191
291
  #logSubscription?: number;
192
292
  #steers = new Set<string>();
193
293
  #discarded = new DiscardedSessions();
@@ -280,6 +380,8 @@ export class MuseHost {
280
380
  this.#assertLive();
281
381
  this.#opening = true;
282
382
  try {
383
+ const mcpServers = { ...this.#options.mcpServers };
384
+ if (privatePiMcp(this.#options)) delete mcpServers.pi;
283
385
  const raw = await this.connection.command("session/start", {
284
386
  approvalMode: "promptUnmatched",
285
387
  ...(this.#options.model === undefined ? {} : { modelId: this.#options.model }),
@@ -287,7 +389,7 @@ export class MuseHost {
287
389
  // the live qualification. Explicit workspace construction is essential;
288
390
  // the private trusted workspace keeps project rules out (settings.ts).
289
391
  ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.privateWorkspace ?? this.#options.cwd} : {}),
290
- config: { mcpServers: this.#options.mcpServers ?? {} },
392
+ config: { mcpServers },
291
393
  }, { maxAttempts: 1 }); // no engine retry/replay
292
394
  this.#assertLive();
293
395
  const result = raw as unknown as Extract<NonNullable<SessionOptions["opening"]>, { verb: "session/start" }>["result"];
@@ -412,7 +514,10 @@ export class MuseHost {
412
514
  }
413
515
  return;
414
516
  }
415
- 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
+ }
416
521
  if (typeof frame.params?.sessionId !== "string") return;
417
522
  if (this.#opening && !this.#session) { this.#held.push(frame); return; }
418
523
  if (this.#session && frame.params.sessionId === this.sessionId) this.#apply(frame);
@@ -439,20 +544,23 @@ export class MuseHost {
439
544
  }
440
545
  if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
441
546
  this.#emit({kind:"frame",frame});
442
- this.fence("Muse quota refused; no replay"); return;
547
+ this.fence(quotaFenceMessage(quotaDenial(params.error) ? params.error : params)); return;
443
548
  }
444
549
  if(retry){
445
550
  if(!this.#busy || params.turnId!==this.#submission?.turnId) {
446
551
  this.fence("Muse retry has foreign or inactive turn identity");return;
447
552
  }
448
- // Only known transient kinds pass. Unknown/missing open-vocabulary kinds fail closed.
449
- if(!["server","transient"].includes(String(params.errorKind)) ||
450
- (params.httpStatus!==undefined && !(typeof params.httpStatus==="number" && params.httpStatus>=500 && params.httpStatus<=599))) {
451
- this.#emit({kind:"frame",frame});
452
- this.fence(`Muse nontransient or unknown retry kind: ${String(params.errorKind)} (HTTP ${String(params.httpStatus)})`);return;
453
- }
553
+ // A scheduled retry is the vendor's own backoff inside an already admitted
554
+ // turn, and its durable kind vocabulary is open (`errorKind?: string`). Real
555
+ // Wonder Full turns sent a kindless `turn/retryScheduled` (2026-11-11T20:34
556
+ // and 20:43) with no 5xx anywhere in the turn, and the old fence ended them.
557
+ // An unknown or missing kind must not end live work; account, quota, policy
558
+ // and upgrade refusals were already decided above, and the terminal frame
559
+ // still reports the real outcome and status.
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;
454
563
  }
455
- if(retry && typeof params.httpStatus==="number")this.#lastRetryHttpStatus=params.httpStatus;
456
564
  if (frame.method === "session/closed" && this.#busy) {
457
565
  this.fence("Muse session closed during pending work; no replay"); return;
458
566
  }
@@ -506,7 +614,7 @@ export class MuseHost {
506
614
  const finish=()=>{
507
615
  if(this.#reason||this.#closing||this.#dead)return;
508
616
  this.#busy=false;
509
- 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});
510
618
  };
511
619
  // Do not release a completed coding turn (and permit a new auxiliary
512
620
  // host) until refresh metadata is known safe. No credential bytes read.
@@ -555,27 +663,37 @@ export class MuseHost {
555
663
  if (!this.#session) throw new Error("Muse session not open");
556
664
  if (!this.#emptyPending()) this.#assertLive();
557
665
  if (this.#busy) throw new Error("Muse predecessor has no turn/completed terminal");
666
+ const commandId = this.connection.mintCommandId();
667
+ // Refuse an unreadable frame before anything is written or billed. A long
668
+ // session that exceeds the client's inbound limit must name the size, the
669
+ // limit and the next step instead of dying mid-work with "no replay".
670
+ const input = typeof text === "string" ? [{ type: "text", text }] : text;
671
+ const frameBytes = turnStartFrameBytes({ sessionId: this.sessionId, commandId, input, reasoningEffort: effort });
672
+ if (frameBytes > MUSE_INBOUND_FRAME_LIMIT_BYTES) throw new MuseFrameOverInboundLimit(frameBytes);
558
673
  await this.#options.verifyLogin?.();
559
674
  if (!this.#options.echo) {
560
- 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;});
561
676
  const usage = result.usage as any;
562
- publishQuota(usage); this.ledger.quota(usage);
563
- // Muse reports percentages; 100% is the provider's exhausted plan boundary.
564
- if (quotaExhausted(usage)) {
565
- this.fence("Muse plan usage limit reached; no turn submitted");
566
- 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
+ }
567
686
  }
568
687
  }
569
- const commandId = this.connection.mintCommandId();
570
688
  const submission: Submission = { commandId, turnId: undefined, terminal: false, started: false };
571
689
  this.#submission = submission;
572
- this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined;
690
+ this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined; this.#lastRetryCause=undefined;
573
691
  this.#retrySafe = false;
574
692
  this.#busy = true;
575
693
  try {
576
694
  // Never Session.sendUserTurn: the SDK replay producer remains empty.
577
695
  const ack = await this.connection.command("turn/start", { sessionId: this.sessionId,
578
- input: typeof text === "string" ? [{ type: "text", text }] : text, reasoningEffort: effort }, { commandId, maxAttempts: 1 });
696
+ input, reasoningEffort: effort }, { commandId, maxAttempts: 1 });
579
697
  this.#assertLive();
580
698
  if (ack.commandId !== commandId || ack.status !== "accepted" || (ack.disposition !== "started" && ack.disposition !== "queued") ||
581
699
  typeof ack.turnId !== "string" || (submission.turnId !== undefined && submission.turnId !== ack.turnId)) {
@@ -599,12 +717,19 @@ export class MuseHost {
599
717
  this.#assertLive();
600
718
  return { turnId: ack.turnId, commandId };
601
719
  } catch (error) {
720
+ // The client's own inputTooLarge refusal is the frame limit measured above;
721
+ // nothing was admitted, so report both numbers and leave the host usable.
722
+ const limit = inputTooLarge(error);
723
+ if (limit !== undefined) {
724
+ this.#busy = false;
725
+ throw new MuseFrameOverInboundLimit(frameBytes, limit);
726
+ }
602
727
  this.#retrySafe = !policyDenial(error) && !quotaDenial(error) && !submission.started && submission.turnId===undefined && error instanceof MspError &&
603
728
  ((error.code===-32001 && error.kind==="overloaded") || (error.code===-32031 && error.kind==="backpressured"));
604
729
  this.#refusal(error);
605
730
  if (quotaDenial(error) && !policyDenial(error)) {
606
731
  this.ledger.record("quota_refusal", {phase:"turn_admission"});
607
- this.fence("Muse quota refused; no replay");
732
+ this.fence(quotaFenceMessage(error));
608
733
  } else this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
609
734
  throw error;
610
735
  }
@@ -723,7 +848,11 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
723
848
  const skills=options.privatePrompt.skillsOff??await discoverSkillsOff(launch.command,options.cwd,env);
724
849
  // Inventory is finished before the model host starts. Only this generation
725
850
  // can see this settings path; auxiliary summaries stage their own files.
726
- await writeFile(join(home,"config/muse/settings.json"),JSON.stringify(promptSettings(options.privatePrompt.systemPrompt,options.tools,skills,options.promptMode === "append" ? "append" : "replace")),{mode:0o600});
851
+ const pi = privatePiMcp(options);
852
+ const settings = promptSettings(options.privatePrompt.systemPrompt,options.tools,skills,options.promptMode === "append" ? "append" : "replace");
853
+ await writeFile(join(home,"config/muse/settings.json"),JSON.stringify({
854
+ ...settings, ...(pi ? {mcp_servers:{pi}} : {}),
855
+ }),{mode:0o600});
727
856
  }
728
857
  } catch (error) { await cleanup(); throw error; }
729
858
  const handshake = spawnMspConnection({ ...launch, env });
@@ -0,0 +1,54 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import { museLedgerPath } from "./request-ledger.js";
4
+ /** Why a row is not counted as live traffic. */
5
+ const EXCLUSIONS: Record<string, string> = {
6
+ test: "runner-isolated test row (VITEST, NODE_TEST_CONTEXT or PI_MUSE_TETHER_LEDGER_ORIGIN=test)",
7
+ proof: "proof row (PI_MUSE_TETHER_LEDGER_ORIGIN=proof)",
8
+ unknown: "row carries no origin (written by a tether older than 0.2.1); provenance is not recorded",
9
+ unreadable: "line is not valid JSON (partial append at a crash)",
10
+ };
11
+ function bump(counts: Record<string, number>, key: string) {
12
+ counts[key] = (counts[key] ?? 0) + 1;
13
+ }
14
+ function ranked(counts: Record<string, number>) {
15
+ return Object.fromEntries(
16
+ Object.entries(counts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
17
+ );
18
+ }
19
+ /**
20
+ * Counts live ledger rows only, split by event type and requested model, and
21
+ * reports every excluded row with its reason. Fixture, proof and pre-0.2.1 rows
22
+ * are never silently folded into traffic; count typed rows here rather than
23
+ * grepping the file.
24
+ */
25
+ export async function summarizeMuseLedger(path = museLedgerPath()) {
26
+ const byOrigin: Record<string, number> = {};
27
+ const byType: Record<string, number> = {};
28
+ const byModel: Record<string, number> = {};
29
+ let rows = 0, unreadable = 0, live = 0;
30
+ const lines = createInterface({ input: createReadStream(path, "utf8"), crlfDelay: Infinity });
31
+ try {
32
+ for await (const line of lines) {
33
+ const text = line.trim();
34
+ if (!text) continue;
35
+ rows++;
36
+ let row: any;
37
+ try { row = JSON.parse(text); } catch { unreadable++; continue; }
38
+ const origin = typeof row.origin === "string" ? row.origin : "unknown";
39
+ bump(byOrigin, origin);
40
+ if (origin !== "live") continue;
41
+ live++;
42
+ bump(byType, typeof row.type === "string" ? row.type : "unknown");
43
+ bump(byModel, typeof row.requestedModel === "string" ? row.requestedModel : "unknown");
44
+ }
45
+ } catch (error: any) {
46
+ if (error.code !== "ENOENT") throw error;
47
+ return { path, present: false, rows: 0, counted: { origin: "live", rows: 0 }, excluded: [], live: { byType: {}, byModel: {} } };
48
+ }
49
+ const excluded = Object.entries(byOrigin)
50
+ .filter(([origin]) => origin !== "live")
51
+ .map(([kind, count]) => ({ kind, rows: count, reason: EXCLUSIONS[kind] ?? "unrecognised origin; not treated as live traffic" }));
52
+ if (unreadable) excluded.push({ kind: "unreadable", rows: unreadable, reason: EXCLUSIONS.unreadable! });
53
+ return { path, present: true, rows, counted: { origin: "live", rows: live }, excluded, live: { byType: ranked(byType), byModel: ranked(byModel) } };
54
+ }
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";
@@ -137,7 +138,7 @@ type Binding = {
137
138
  abort: AbortController;
138
139
  pending: Map<string, { invocation: BridgeInvocation; callId: string; result?: BridgeResult; verified: boolean }>;
139
140
  batch?: string[];
140
- batchSpec?: Array<{callId:string;name:string;args:Record<string,unknown>;piCallId:string;verified?:boolean;nativeStart?:{itemId:string;turnId:string;recordedAt:string};journal?:{entryId:string;response:BridgeResult}}>;
141
+ batchSpec?: Array<{callId:string;name:string;args:Record<string,unknown>;piCallId:string;verified?:boolean;nativeTimedOut?:boolean;nativeStart?:{itemId:string;turnId:string;recordedAt:string};journal?:{entryId:string;response:BridgeResult}}>;
141
142
  tools: Array<{name:string;description:string;inputSchema:any}>;
142
143
  approvalHolds: Map<string,{approvalId:string;requirement:string;ready:boolean;promise:Promise<void>;resolve:()=>void;reject:(error:Error)=>void}>;
143
144
  steeringPending?: boolean;
@@ -264,7 +265,7 @@ function fail(b: Binding, reason: string) {
264
265
  const sequentialCalls = new WeakMap<Binding, BridgeInvocation[]>();
265
266
  const sequentialStarts = new WeakMap<Binding, Map<string,{itemId:string;turnId:string;recordedAt:string}>>();
266
267
  function settleBatch(b:Binding) {
267
- if (b.batchSpec?.every(c=>c.verified)) {
268
+ if (b.batchSpec?.every(c=>c.verified || c.nativeTimedOut)) {
268
269
  b.batch=undefined; b.batchSpec=undefined; b.batchSurfaced=false;
269
270
  b.receiptsDone?.(); b.receiptsDone=undefined;
270
271
  const next = sequentialCalls.get(b)?.shift();
@@ -321,12 +322,16 @@ function emitFrame(b: Binding, event: any) {
321
322
  fail(b,`Muse approval hold: native ${item.tool} ${item.callId} ended ${item.status} before actual MCP result delivery; no replay`);return;
322
323
  }
323
324
  }
324
- // Native tool termination is lifecycle state, not an ordinary future receipt.
325
- // Muse can time out its MCP request while Pi is still executing the tool.
326
- // Never defer that divergence until Pi returns, or accept the next batch.
325
+ // A Muse client native tool deadline is lifecycle state for the one call,
326
+ // not a fence for the whole turn. The client times out its own MCP
327
+ // request (~300 s observed on the wire; the qualified MSP/session MCP
328
+ // surface offers no deadline control) and continues with a timeout
329
+ // result for that call while Pi may still be executing. Record the
330
+ // divergence now and settle only this call; Pi's journaled result is
331
+ // never replayed to Muse and the turn carries on.
327
332
  if(event.kind==="frame") {
328
333
  const {method,params:p={}}=event.frame,item=p.item;
329
- const spec=item?.kind==="toolCall" ? b.batchSpec?.find(c=>c.callId===item.callId && !c.verified) : undefined;
334
+ const spec=item?.kind==="toolCall" ? b.batchSpec?.find(c=>c.callId===item.callId && !c.verified && !c.nativeTimedOut) : undefined;
330
335
  if (!spec && method === "item/started" && item?.kind === "toolCall") {
331
336
  const reservation=b.reservations.get(item.callId);
332
337
  if (reservation && item.tool === `mcp__pi__${reservation.name}`) {
@@ -345,8 +350,11 @@ function emitFrame(b: Binding, event: any) {
345
350
  const elapsed=Date.parse(item.recordedAt)-Date.parse(spec.nativeStart?.recordedAt ?? "");
346
351
  const observed=Number.isFinite(elapsed) && elapsed>=0 ? ` (~${Math.round(elapsed/1000)*1000} ms native elapsed; ${elapsed} ms from native timestamps)` : " (native elapsed unavailable)";
347
352
  const reason=`Muse native tool timeout: ${spec.name} ${item.callId} timedOut${observed}; Pi execution/consumption diverged; no replay`;
348
- b.host?.ledger?.record("tool_execution_divergence",{callId:item.callId,tool:spec.name,status:item.status,sourceRange:p.sourceRange,nativeStart:spec.nativeStart,nativeCompletedAt:item.recordedAt,piResultJournaled:Boolean(spec.journal),pendingMcp:b.pending.has(item.callId),reason});
349
- fail(b,reason);return;
353
+ const pendingMcp=b.pending.has(item.callId);
354
+ b.host?.ledger?.record("tool_execution_divergence",{callId:item.callId,tool:spec.name,status:item.status,sourceRange:p.sourceRange,nativeStart:spec.nativeStart,nativeCompletedAt:item.recordedAt,piResultJournaled:Boolean(spec.journal),pendingMcp,reason});
355
+ spec.nativeTimedOut=true;
356
+ b.pending.delete(item.callId);
357
+ return;
350
358
  }
351
359
  } catch(error:any) {fail(b,`Muse native tool lifecycle: ${error.message}`);return;}
352
360
  }
@@ -365,19 +373,22 @@ function emitFrame(b: Binding, event: any) {
365
373
  // confirmed by turn/steer. A completed target must fail loudly, not drop it.
366
374
  if (b.steeringPending && event.status === "completed") { b.deferredTerminal=event; return; }
367
375
  if (event.status !== "completed") {
368
- 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);
369
379
  // Preserve Pi's native overflow entry path without introducing a new
370
380
  // generic retry policy or replaying an uncertain host request.
371
381
  const overflow = typeof detail === "string" && isContextOverflow({...e.output,stopReason:"error",errorMessage:detail});
372
- const error = event.frame?.params?.error;
373
382
  const status = error?.httpStatus ?? error?.status ?? error?.statusCode ?? (event.status === "failed" ? event.lastRetryHttpStatus : undefined);
374
383
  fail(b, overflow ? `Muse context overflow: ${detail}` : `Muse turn ended ${event.status}${typeof status === "number" ? ` (HTTP ${status})` : ""}${typeof detail === "string" ? `: ${detail}` : ""}`);
375
384
  return;
376
385
  }
377
- if (b.pending.size || b.batch) {
386
+ if (b.pending.size || (b.batch && b.batchSpec?.some(c=>!c.verified && !c.nativeTimedOut))) {
378
387
  fail(b, "Muse result consumption is unverified");
379
388
  return;
380
389
  }
390
+ // A batch fully settled by native tool timeouts needs no receipt to retire.
391
+ if (b.batch) { b.batch=undefined; b.batchSpec=undefined; b.batchSurfaced=false; }
381
392
  if (e.textIndex !== undefined)
382
393
  e.stream.push({
383
394
  type: "text_end",
@@ -385,6 +396,21 @@ function emitFrame(b: Binding, event: any) {
385
396
  content: e.output.content[e.textIndex].text,
386
397
  partial: e.output,
387
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
+ }
388
414
  e.ended = true;
389
415
  e.detachAbort?.();
390
416
  b.messages.push(structuredClone(e.output));
@@ -395,6 +421,9 @@ function emitFrame(b: Binding, event: any) {
395
421
  return;
396
422
  }
397
423
  if (event.kind === "tool-batch") {
424
+ // A predecessor batch fully settled (including by native timeouts) no
425
+ // longer blocks Muse's next committed batch.
426
+ if (b.batch && b.batchSpec?.every(c=>c.verified || c.nativeTimedOut)) settleBatch(b);
398
427
  if (b.batch || !event.calls.length || new Set(event.calls.map((x:any)=>x.callId)).size !== event.calls.length) {
399
428
  fail(b, "Muse duplicate or overlapping committed tool batch"); return;
400
429
  }
@@ -682,7 +711,6 @@ function streamEffective(model: any, input: any, options: any = {}) {
682
711
  // A genuinely new user request ends the old failure fence. Otherwise that
683
712
  // stale fence would incorrectly block this new request's later tool batch.
684
713
  if(blocked && context.messages.at(-1)?.role==="user")retryBlocks.delete(key);
685
- b = bindings.get(key);
686
714
  if (!context.tools.length)
687
715
  throw new Error("Muse raw completion and compaction are unsupported");
688
716
  const mode = requestedMode;
@@ -698,6 +726,9 @@ function streamEffective(model: any, input: any, options: any = {}) {
698
726
  description: t.description,
699
727
  inputSchema: t.parameters,
700
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);
701
732
  const declarationHash = projectionHash(tools);
702
733
  const route = museModelRoute(model.id);
703
734
  const signature = requestSignature([model.id, route?.contributorMode, context.systemPrompt, tools, mode, process.cwd()]);
@@ -783,7 +814,9 @@ function streamEffective(model: any, input: any, options: any = {}) {
783
814
  // Reject unqualified rich layouts before delivering ANY batch response.
784
815
  // Captured LF text projection and [text, PNG] placeholder are checked
785
816
  // at the native receipt; image content remains explicitly unverifiable.
786
- assertToolResultVerifiable(response);
817
+ // A natively timed-out call is excluded from delivery; its Pi result
818
+ // is never delivered to Muse, so the layout gate does not apply.
819
+ if(!pending.nativeTimedOut)assertToolResultVerifiable(response);
787
820
  return {pending,entry,response};
788
821
  });
789
822
  episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
@@ -798,6 +831,13 @@ function streamEffective(model: any, input: any, options: any = {}) {
798
831
  b.steeringPending=steering.length>0;
799
832
  const consumed=steering.length?new Promise<void>(resolve=>{b!.receiptsDone=resolve;}):undefined;
800
833
  for(const {pending,entry,response} of journaled){
834
+ if(pending.nativeTimedOut){
835
+ // Muse already consumed the native timeout for this call (the
836
+ // departed MCP request is never revived). Pi keeps its real result
837
+ // in the journal; the divergence is declared, not replayed.
838
+ b.host?.ledger?.record("tool_native_timeout_consumed",{callId:pending.callId,piToolCallId:pending.piCallId,tool:pending.name,piJournalEntryId:entry.id,deliveredToMcp:false,modelConsumedNative:"timedOut",exactModelConsumption:false,evidence:"declared-lossy"});
839
+ continue;
840
+ }
801
841
  pending.journal={entryId:entry.id,response};
802
842
  const hold=b.approvalHolds.get(pending.callId);
803
843
  if(hold) {
@@ -941,7 +981,14 @@ function streamEffective(model: any, input: any, options: any = {}) {
941
981
  await host.submitInput(text, museEffort(options.reasoning));
942
982
  await episode.hooks.admit("turn/start");
943
983
  } catch (error: any) {
944
- const reason = b?.host?.fencedReason ?? String(error?.message || error);
984
+ // A frame over the client's inbound limit is a request-size overflow, the
985
+ // class Pi already recovers from: compact the session, then retry once.
986
+ // The prefix is the existing compact-and-retry contract (see below). Match
987
+ // the host's stable error code, not class identity: a replaced host module
988
+ // (vi.mock, another loader instance) would make `instanceof` throw here.
989
+ const reason = error?.code === "MUSE_FRAME_TOO_LARGE"
990
+ ? `Muse context overflow: ${error.message}`
991
+ : b?.host?.fencedReason ?? String(error?.message || error);
945
992
  if (b) { b.episode = episode; fail(b, reason); }
946
993
  else {
947
994
  episode.ended = true;
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,8 +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
- if(params)statuses.set(owner, `Muse retry ${params.nextAttempt}/${params.maxAttempts} scheduled in ${params.retryDelayMs} ms (${params.errorKind}${params.httpStatus === undefined ? "" : `, HTTP ${params.httpStatus}`})`);
24
+ if(params){
25
+ // The durable retry kind and HTTP status are optional open-vocabulary vendor
26
+ // fields; the recorded stopping reason is the real cause when either is absent.
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})`);
40
+ }
14
41
  listener?.([...statuses.values()].at(-1));
15
42
  }
@@ -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
+ }