pi-muse-tether 0.1.1 → 0.2.1

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/src/host.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { resolveMuseBinary, batchEligibility, clientBuildLabel } from "./qualification-records.js";
2
+ import { featureNotice, featureActive, MuseFeatureUnavailable } from "./features.js";
3
+ import { committedCalls } from "./batch-schema.js";
1
4
  import { qualifyMuseVersion } from "./cli-version.js";
2
5
  import { museEffort } from "./thinking-config.js";
3
6
  import { publishQuota, quotaExhausted } from "./rate-limit.js";
@@ -5,9 +8,10 @@ import { MuseLedger } from "./request-ledger.js";
5
8
  import type { TurnInputPart } from "./wire-types.js";
6
9
  import { homedir, tmpdir } from "node:os";
7
10
  import { createHash } from "node:crypto";
8
- import { mkdtemp, rm } from "node:fs/promises";
11
+ import { mkdtemp, realpath, rm } from "node:fs/promises";
12
+ import { setTimeout as delay } from "node:timers/promises";
9
13
  import { isAbsolute, join } from "node:path";
10
- import { writePromptSettings, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
14
+ import { writePromptSettings, privateWorkspace, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
11
15
  import { writeFile } from "node:fs/promises";
12
16
  import {
13
17
  Connection, DiscardedSessions, MspError, Session, readSessionDurability,
@@ -16,6 +20,9 @@ import {
16
20
  type SessionOptions, type SpawnMspConnectionOptions, type ViewEvent,
17
21
  } from "@muse-code/sdk";
18
22
 
23
+ /** Inventory recheck pacing while Muse 1.4.15 starts session MCP (~200 ms measured). */
24
+ const MCP_READY_RECHECK_MS = 25;
25
+
19
26
  type InitializeResult = Parameters<typeof readSessionDurability>[0];
20
27
  export type MuseApproval = Parameters<ApprovalHandler>[0];
21
28
  export type MuseFrame = { method: string; params?: Record<string, unknown> };
@@ -23,6 +30,7 @@ export type MuseHostEvent =
23
30
  | { kind: "frame"; frame: MuseFrame }
24
31
  | { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number }
25
32
  | { kind: "fenced"; reason: string }
33
+ | { kind: "degraded"; feature: "rawLog"; reason: string }
26
34
  | { kind: "tool-batch"; calls: Array<{callId:string;name:string;args:Record<string,unknown>}> }
27
35
  | { kind: "auth-metadata"; metadata: unknown };
28
36
 
@@ -30,6 +38,9 @@ export interface MuseHostOptions {
30
38
  cwd: string;
31
39
  /** Requires the pinned experimental rawLog batch boundary; never timing heuristics. */
32
40
  toolBatches?: boolean;
41
+ /** Only the explicitly isolated, opt-in qualifier can probe before certification. */
42
+ qualificationProbe?: boolean;
43
+ clientBuild?: string;
33
44
  purpose?: "coding" | "raw";
34
45
  piSessionId?: string;
35
46
  reasoningEffort?: ReturnType<typeof museEffort>;
@@ -54,6 +65,8 @@ export interface MuseHostOptions {
54
65
  onEvent?: (event: MuseHostEvent) => void;
55
66
  /** Stop an opening host when its Pi binding is retired. */
56
67
  signal?: AbortSignal;
68
+ /** Set by openMuseHost for private prompts: the empty trusted workspace. */
69
+ privateWorkspace?: string;
57
70
  /**
58
71
  * Required to allow anything. Must validate identity and reserve the exact
59
72
  * generation, session, turn, approvalId, toolCallId and rawArgs for the later
@@ -84,6 +97,16 @@ export function policyDenial(error: unknown, seen=new Set<unknown>()): boolean {
84
97
  return [value.data, value.error, value.cause].some((nested) => nested !== error && policyDenial(nested, seen));
85
98
  }
86
99
 
100
+ export class MuseUpgradeRequired extends Error {
101
+ readonly code = "MUSE_UPGRADE_REQUIRED";
102
+ constructor(readonly build: string) { super(`MUSE_UPGRADE_REQUIRED: Meta requires a newer official client than ${build}; update through Meta's launcher, then run /muse-doctor qualify. No fallback or replay.`); }
103
+ }
104
+ export function serverRequiresUpgrade(error: unknown, seen = new Set<unknown>()): boolean {
105
+ if (!error || typeof error !== "object" || seen.has(error)) return false;
106
+ seen.add(error); const value=error as Record<string,unknown>;
107
+ 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
+ return [value.error,value.data,value.cause].some(nested => serverRequiresUpgrade(nested,seen));
109
+ }
87
110
  function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
88
111
  if (!error || typeof error !== "object" || seen.has(error)) return false;
89
112
  seen.add(error);
@@ -102,10 +125,11 @@ function validateOptions(options: MuseHostOptions): void {
102
125
  if (options.contributorMode !== undefined && !["on","off"].includes(options.contributorMode))
103
126
  throw new Error("Muse contributor mode must be on or off");
104
127
  const candidate = options.privatePrompt !== undefined && options.promptMode === "replace";
105
- if (options.privatePrompt && !candidate) throw new Error("Muse private prompt settings require replace mode");
128
+ const appended = options.privatePrompt !== undefined && options.promptMode === "append";
129
+ if (options.privatePrompt && !candidate && !appended) throw new Error("Muse private prompt settings require replace or appended fallback mode");
106
130
  if (!options.echo) assertLoginSafe();
107
- if (options.promptMode !== "none" && !candidate) throw new Error("Muse prompt mode unsupported: no qualified instruction isolation");
108
- if (options.tools.length === 0 && !(options.purpose === "raw" && candidate)) throw new Error("Muse tools-empty/raw completion unsupported");
131
+ if (options.promptMode !== "none" && !candidate && !appended) throw new Error("Muse prompt mode unsupported: no instruction mechanism");
132
+ if (options.tools.length === 0 && !(options.purpose === "raw" && (candidate || appended))) throw new Error("Muse tools-empty/raw completion unsupported");
109
133
  if (options.purpose === "raw" && (options.tools.length || Object.keys(options.mcpServers ?? {}).length)) throw new Error("Muse raw completion must have no tools or MCP servers");
110
134
  if (Object.values(options.mcpServers ?? {}).some((server:any)=>server.mode !== undefined && server.mode !== "required")) throw new Error("Muse Pi MCP servers must be required; no optional fallback");
111
135
  if (options.echo !== true && process.env.PI_MUSE_TETHER_LIVE !== "1") throw new Error("Live Muse requires explicit PI_MUSE_TETHER_LIVE=1");
@@ -117,7 +141,7 @@ function validateOptions(options: MuseHostOptions): void {
117
141
  /** Supported official flags only; no config mutation, trust, login or credential I/O. */
118
142
  export function museLaunchOptions(options: MuseHostOptions): SpawnMspConnectionOptions {
119
143
  validateOptions(options);
120
- const command = options.binary ?? process.env.PI_MUSE_TETHER_BINARY ?? join(homedir(), ".local/bin/muse");
144
+ const command = options.binary ?? resolveMuseBinary();
121
145
  if (!isAbsolute(command)) throw new Error("Muse binary must be absolute");
122
146
  return {
123
147
  command,
@@ -129,7 +153,7 @@ export function museLaunchOptions(options: MuseHostOptions): SpawnMspConnectionO
129
153
  "--config", `run.toolset=${JSON.stringify(options.tools.map(name => `mcp__pi__${name}`))}`,
130
154
  "--disable-request-user-input", ...(options.echo ? ["--provider", "echo"] : [])],
131
155
  cwd: options.cwd,
132
- env: Object.fromEntries(Object.entries({ ...process.env, MUSE_NO_AUTO_UPDATE: "1" }).filter(([key]) => options.echo
156
+ env: Object.fromEntries(Object.entries({ ...process.env }).filter(([key]) => options.echo
133
157
  ? ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "MUSE_NO_AUTO_UPDATE", "MUSE_WIRE_DIR", "MUSE_TRANSPORT_TRACE"].includes(key)
134
158
  : !["META_API_KEY", "MUSE_CONTRIBUTOR_MODE"].includes(key))),
135
159
  // No tether workload timeout: SDK SS2.1.2 owns the default 30s close deadline.
@@ -192,8 +216,12 @@ export class MuseHost {
192
216
  this.#tools = new Set(options.tools.map((name) => `mcp__pi__${name}`));
193
217
  this.#durability = readSessionDurability(initialized);
194
218
  if (this.#durability.kind !== "ephemeral") throw new Error("Muse requires declared ephemeral session durability");
195
- if (!initialized.grantedCapabilities.includes("sessionMcp")) throw new Error("Muse did not grant sessionMcp");
196
- if(options.toolBatches && !initialized.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported");
219
+ if (!initialized.grantedCapabilities.includes("sessionMcp")) throw new MuseFeatureUnavailable(options.clientBuild ?? "unknown build","sessionMcp","initialize did not grant session MCP");
220
+ featureActive(options.clientBuild ?? "unknown build","sessionMcp");
221
+ if(options.toolBatches && !initialized.grantedCapabilities.includes("rawLog")) {
222
+ this.#options.toolBatches=false;
223
+ this.degradeBatches("rawLog not granted");
224
+ }
197
225
  connection.onNotification((frame) => this.receive(frame as MuseFrame));
198
226
  connection.onServerRequest(async (request) => {
199
227
  if (request.method === "approval/request" || request.method === "userInput/request") {
@@ -214,6 +242,15 @@ export class MuseHost {
214
242
  get sessionId(): string { if (!this.#session) throw new Error("Muse session not open"); return this.#session.sessionId; }
215
243
  get view(): SessionFoldView { if (!this.#session) throw new Error("Muse session not open"); return this.#session.fold; }
216
244
  get fencedReason(): string | undefined { return this.#reason; }
245
+ #degradedNotice = false;
246
+ degradeBatches(reason: string) {
247
+ this.#options.toolBatches=false;
248
+ if (!this.#degradedNotice) {
249
+ this.#degradedNotice=true;
250
+ console.warn(featureNotice(this.#options.clientBuild ?? "unknown build","rawLog",reason,"using sequential tools (no replay)"));
251
+ this.#emit({kind:"degraded",feature:"rawLog",reason});
252
+ }
253
+ }
217
254
  get batches(): boolean { return this.#options.toolBatches === true; }
218
255
  /** Official read-only byte-ranged output API; no filesystem/path fallback. */
219
256
  async readToolOutput(item: { itemId: string; outputRef: { id: string } }, offsetBytes: number) {
@@ -224,6 +261,10 @@ export class MuseHost {
224
261
  /** SDK Connection.command's documented nothing-admitted overload classes. */
225
262
  get retrySafe(): boolean { return this.#retrySafe; }
226
263
  #refusal(error:unknown) {
264
+ if (serverRequiresUpgrade(error)) {
265
+ const build = this.#options.clientBuild ?? clientBuildLabel(this.#options.binary ?? process.env.PI_MUSE_TETHER_BINARY);
266
+ this.fence(new MuseUpgradeRequired(build).message); return true;
267
+ }
227
268
  if(!policyDenial(error))return false;
228
269
  policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
229
270
  this.fence(policyLatch);return true;
@@ -243,15 +284,16 @@ export class MuseHost {
243
284
  approvalMode: "promptUnmatched",
244
285
  ...(this.#options.model === undefined ? {} : { modelId: this.#options.model }),
245
286
  // Without workspaceRoot, serve silently ignored run.system_prompt in
246
- // the live qualification. Explicit workspace construction is essential.
247
- ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.cwd} : {}),
287
+ // the live qualification. Explicit workspace construction is essential;
288
+ // the private trusted workspace keeps project rules out (settings.ts).
289
+ ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.privateWorkspace ?? this.#options.cwd} : {}),
248
290
  config: { mcpServers: this.#options.mcpServers ?? {} },
249
291
  }, { maxAttempts: 1 }); // no engine retry/replay
250
292
  this.#assertLive();
251
293
  const result = raw as unknown as Extract<NonNullable<SessionOptions["opening"]>, { verb: "session/start" }>["result"];
252
294
  if (typeof result.session?.sessionId !== "string") throw new Error("Invalid Muse session/start result");
253
295
  if(this.#options.privatePrompt && (result.session as any).permissionState?.reviewerAuthority!=="human")
254
- throw new Error("Muse private recipe requires verified human reviewer; no model request submitted");
296
+ throw new MuseFeatureUnavailable(this.#options.clientBuild ?? "unknown build","sessionMcp","Private tool recipe lacks verified human reviewer; Pi cannot safely own approvals");
255
297
  this.#session = this.makeSession({ sessionId: result.session.sessionId, durability: this.#durability,
256
298
  discarded: this.#discarded, connection: this.connection, opening: { verb: "session/start", result } });
257
299
  this.ledger.opened(this.#session.sessionId);
@@ -270,13 +312,21 @@ export class MuseHost {
270
312
  return this.#decide(request);
271
313
  });
272
314
  this.#session.onApprovalError((error) => { if(!this.#refusal(error))this.fence("Muse approval round trip failed"); });
273
- if(this.batches) {
315
+ if(this.batches) { try {
274
316
  const streams=await this.connection.command("log/streams",{sessionId:this.sessionId},{maxAttempts:1});
275
317
  const stream=(streams.streams as any[])?.map(s=>s.stream).find(s=>s?.kind==="session.live" && s.id===this.sessionId);
276
318
  if(!stream)throw new Error("Muse rawLog session stream absent; parallel tools unsupported");
277
319
  const sub=await this.connection.command("log/subscribe",{sessionId:this.sessionId,stream},{maxAttempts:1});
278
320
  if(!(typeof sub.subscriptionId==="number" && Number.isFinite(sub.subscriptionId)))throw new Error("Muse rawLog subscription absent");
279
321
  this.#logSubscription=sub.subscriptionId;
322
+ } catch (error) {
323
+ if (policyDenial(error)) throw error;
324
+ this.degradeBatches("rawLog schema/subscription unavailable");
325
+ } }
326
+ try { await this.#awaitSessionMcp(); }
327
+ catch(error) {
328
+ if (this.#options.signal?.aborted || policyDenial(error)) throw error;
329
+ throw new MuseFeatureUnavailable(this.#options.clientBuild ?? "unknown build","sessionMcp",error instanceof Error ? error.message : String(error));
280
330
  }
281
331
  // Entire drain is synchronous. A newly arriving event cannot overtake it.
282
332
  const held = this.#held;
@@ -294,17 +344,58 @@ export class MuseHost {
294
344
  }
295
345
  }
296
346
 
347
+ /** Muse 1.4.15 starts session MCP servers after session/start returns, and
348
+ * a turn sent first fails "unknown tool" (measured 2026-11-10: "starting"
349
+ * with no tools, "connected" ~200 ms later). The client sends no readiness
350
+ * notification, so ask its inventory until every required server is
351
+ * connected with every Pi tool. No deadline: Pi's abort owns cancellation.
352
+ * 1.4.14 has no inventory method and was already ready at session/start. */
353
+ async #awaitSessionMcp() {
354
+ const names = Object.keys(this.#options.mcpServers ?? {});
355
+ for (;;) {
356
+ if (!names.length) return;
357
+ this.#assertLive();
358
+ this.#options.signal?.throwIfAborted();
359
+ let inventory: any;
360
+ try {
361
+ inventory = await (this.connection as any).request("mcpServer/readInventory", { sessionId: this.sessionId, includeTools: true });
362
+ } catch (error: any) {
363
+ // Only the typed old-client refusal skips readiness. experimentalRequired
364
+ // also uses -32601; a frame without data.kind is rejected by the SDK as
365
+ // ProtocolError (fail-closed), not evidence of an older client.
366
+ if (error?.kind === "methodNotFound" || error?.data?.kind === "methodNotFound") return;
367
+ throw error;
368
+ }
369
+ if (!Array.isArray(inventory?.servers)) throw new Error("Muse session MCP inventory malformed: servers must be an array");
370
+ const rows = names.map(name => ({ name, row: inventory.servers.find((s: any) => s?.name === name) }));
371
+ // Registration can be asynchronous: absent rows and starting are pending.
372
+ // 1.4.15 binary inventory labels include withheld and closed. These,
373
+ // explicit failures (failed/error/forfeited), and all unrecognized states
374
+ // fail closed, naming the state; only starting/absence are pending.
375
+ const failed = rows.find(({ row }) => row && row.state !== "starting" && row.state !== "connected");
376
+ if (failed) throw new Error(`Muse session MCP server ${failed.name} unavailable (${failed.row?.state ?? "absent"}); no model request submitted`);
377
+ if (rows.every(({ row }) => row?.state === "connected")) {
378
+ const pi = rows.find(({ name }) => name === "pi")?.row;
379
+ const missing = pi ? this.#options.tools.filter(tool => !(pi.tools as unknown[] | undefined)?.includes(tool)) : [];
380
+ if (missing.length) throw new Error(`Muse session MCP server pi connected without Pi tools ${missing.join(", ")}; no model request submitted`);
381
+ return;
382
+ }
383
+ // Recheck pacing only (not a deadline), well under the measured ~200 ms startup.
384
+ await delay(MCP_READY_RECHECK_MS, undefined, { signal: this.#options.signal });
385
+ }
386
+ }
387
+
297
388
  /** The single ingress, also used by synthetic frame fixtures. */
298
389
  receive(frame: MuseFrame): void {
299
- if(frame.method==="log/gap" && (frame.params as any)?.subscriptionId===this.#logSubscription){this.fence("Muse rawLog gap; complete tool batch unknown");return;}
390
+ if(frame.method==="log/gap" && (frame.params as any)?.subscriptionId===this.#logSubscription){this.degradeBatches("rawLog gap");return;}
300
391
  if(frame.method==="log/record") {
301
392
  const p=frame.params as any;
302
393
  if(this.#logSubscription===undefined || p?.subscriptionId!==this.#logSubscription || this.#reason || this.#dead)return;
303
394
  const payload=p.record?.payload, event=payload?.event;
304
- if(payload?.kind==="run" && event?.kind==="assistant_tool_calls_committed") {
395
+ if(this.batches && payload?.kind==="run" && event?.kind==="assistant_tool_calls_committed") {
305
396
  if(!this.#busy || payload.run_id!==this.#submission?.turnId){this.fence("Muse committed tool batch has foreign turn identity");return;}
306
397
  try {
307
- const calls=event.tool_calls.map((c:any)=>({callId:c.call_id,name:c.name,args:typeof c.args==="string"?JSON.parse(c.args):c.args}));
398
+ const calls=committedCalls(p);
308
399
  if(!calls.length || calls.some((c:any)=>typeof c.callId!=="string"||!this.#tools.has(c.name)||!c.args||typeof c.args!=="object"||Array.isArray(c.args)))throw new Error("Malformed committed tool batch");
309
400
  const signatures=calls.map((c:any)=>JSON.stringify([c.callId,c.name,canonical(c.args)]));
310
401
  const batch=JSON.stringify(signatures);
@@ -315,7 +406,9 @@ export class MuseHost {
315
406
  calls.forEach((c:any,i:number)=>this.#committedCalls.set(c.callId,signatures[i]));
316
407
  this.#committedBatches.add(batch);
317
408
  this.#emit({kind:"tool-batch",calls});
318
- }catch{this.fence("Muse malformed committed tool batch");}
409
+ }catch{
410
+ this.degradeBatches("Batch schema mismatch");
411
+ }
319
412
  }
320
413
  return;
321
414
  }
@@ -340,9 +433,9 @@ export class MuseHost {
340
433
  const retry=["turn/retryScheduled","turn/modelRetryScheduled"].includes(frame.method);
341
434
  if(retry)this.ledger.observe(frame); // Includes refused retries, before any latch.
342
435
  // Only protocol error fields count; model/user/tool text is never scanned.
343
- if(policyDenial(params.error) || (["turn/retryScheduled","turn/modelRetryScheduled"].includes(frame.method) && policyDenial(params))){
436
+ if(serverRequiresUpgrade(params.error) || (retry && serverRequiresUpgrade(params)) || policyDenial(params.error) || (["turn/retryScheduled","turn/modelRetryScheduled"].includes(frame.method) && policyDenial(params))){
344
437
  this.#emit({kind:"frame",frame});
345
- this.#refusal(policyDenial(params.error) ? params.error : params);return;
438
+ this.#refusal(policyDenial(params.error) || serverRequiresUpgrade(params.error) ? params.error : params);return;
346
439
  }
347
440
  if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
348
441
  this.#emit({kind:"frame",frame});
@@ -574,7 +667,7 @@ export async function discoverMuseCatalog() {
574
667
  await qualifyMuseVersion(launch.command,launch.env??{});
575
668
  const handshake = spawnMspConnection(launch);
576
669
  try {
577
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
670
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
578
671
  capabilities: { requestedCapabilities: ["sessionMcp"], userInputDialogs: false } });
579
672
  const catalog = await spawned.connection.request("model/list", {});
580
673
  return catalog as typeof catalog & {models:any[]};
@@ -585,10 +678,22 @@ export async function discoverMuseCatalog() {
585
678
  }
586
679
 
587
680
  export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost> {
588
- const launch = museLaunchOptions(options); // preflight BEFORE filesystem/process work
681
+ let launch = museLaunchOptions(options); // preflight BEFORE filesystem/process work
682
+ options = {...options, binary:launch.command, clientBuild:clientBuildLabel(launch.command)};
589
683
  options.signal?.throwIfAborted();
590
- await qualifyMuseVersion(launch.command, launch.env??{}, options.signal, options.toolBatches);
591
- const home = await mkdtemp(join(tmpdir(), "pi-muse-host-"));
684
+ await qualifyMuseVersion(launch.command, launch.env??{}, options.signal);
685
+ options={...options,clientBuild:clientBuildLabel(launch.command)};
686
+ if (options.qualificationProbe && !process.env.PI_MUSE_TETHER_QUALIFICATION_REAL_CONFIG) throw new Error("Qualification probe requires the isolated opt-in worker");
687
+ let batchReason:string|undefined;
688
+ if (options.toolBatches && !options.echo && !options.qualificationProbe) {
689
+ let eligible;
690
+ try { eligible=batchEligibility(launch.command); } catch { eligible={qualified:false,reason:"Qualification schema/identity check unavailable"}; }
691
+ if (!eligible.qualified) { batchReason=eligible.reason; options={...options,toolBatches:false}; }
692
+ }
693
+ if (!options.toolBatches && !options.echo) launch = {...launch, args:[...(launch.args ?? []), "--config", "run.parallel_tool_calls=false"]};
694
+ // Muse canonicalizes workspaceRoot before trust lookup (e.g. macOS /var).
695
+ // One canonical root owns settings, trust, auth link and raw/coding workspace.
696
+ const home = await realpath(await mkdtemp(join(tmpdir(), "pi-muse-host-")));
592
697
  const env = options.echo ? { ...launch.env,
593
698
  HOME: home, XDG_CONFIG_HOME: join(home, "config"), XDG_DATA_HOME: join(home, "data"),
594
699
  XDG_CACHE_HOME: join(home, "cache"), XDG_STATE_HOME: join(home, "state") } : {
@@ -604,7 +709,8 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
604
709
  };
605
710
  try {
606
711
  if (options.privatePrompt) {
607
- await writePromptSettings(home, options.privatePrompt.systemPrompt, options.tools, options.privatePrompt.skillsOff);
712
+ await writePromptSettings(home, options.privatePrompt.systemPrompt, options.tools, options.privatePrompt.skillsOff, options.promptMode === "append" ? "append" : "replace");
713
+ options = {...options, privateWorkspace: privateWorkspace(home)};
608
714
  if(!options.echo){
609
715
  const verify=await linkHostLogin(home,launch.env?.XDG_CONFIG_HOME??join(homedir(),".config"));
610
716
  verifyLogin=async()=>{
@@ -617,7 +723,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
617
723
  const skills=options.privatePrompt.skillsOff??await discoverSkillsOff(launch.command,options.cwd,env);
618
724
  // Inventory is finished before the model host starts. Only this generation
619
725
  // can see this settings path; auxiliary summaries stage their own files.
620
- await writeFile(join(home,"config/muse/settings.json"),JSON.stringify(promptSettings(options.privatePrompt.systemPrompt,options.tools,skills)),{mode:0o600});
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});
621
727
  }
622
728
  } catch (error) { await cleanup(); throw error; }
623
729
  const handshake = spawnMspConnection({ ...launch, env });
@@ -636,9 +742,19 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
636
742
  return {};
637
743
  });
638
744
  try {
639
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
640
- capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches)?{experimentalApi:true}:{}) } });
641
- if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported; no model request submitted");
745
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
746
+ capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches||Object.keys(options.mcpServers??{}).length)?{experimentalApi:true}:{}) } });
747
+ if (options.privatePrompt && options.promptMode === "replace" && spawned.initializeResult.experimentalApi === false) {
748
+ await spawned.close(); await cleanup();
749
+ console.warn(featureNotice(options.clientBuild ?? "unknown build","privatePrompt","experimental private replacement not negotiated","Pi prompt appended through supported run.developer_prompt, not replacing Muse instructions"));
750
+ return openMuseHost({...options,promptMode:"append"});
751
+ }
752
+ if (options.privatePrompt && options.promptMode === "replace") featureActive(options.clientBuild ?? "unknown build","privatePrompt");
753
+ if (!spawned.initializeResult.grantedCapabilities.includes("sessionMcp")) throw new MuseFeatureUnavailable(options.clientBuild ?? "unknown build","sessionMcp","initialize did not grant session MCP");
754
+ if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog")) {
755
+ batchReason="rawLog not granted";
756
+ options = {...options, toolBatches:false};
757
+ }
642
758
  if (!options.echo) {
643
759
  const catalog = await spawned.connection.request("model/list", {});
644
760
  const selected = (catalog.models as any[])?.find((m) => m.modelId === options.model);
@@ -652,6 +768,8 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
652
768
  host = new MuseHost(spawned.connection, spawned.initializeResult, {...options,verifyLogin}, async () => {
653
769
  try { await spawned.close(); } finally { await cleanup(); }
654
770
  });
771
+ if (batchReason) host.degradeBatches(batchReason);
772
+ else if (host.batches) featureActive(options.clientBuild ?? "unknown build","rawLog");
655
773
  void spawned.child.exit.then((exit) => host!.hostExited(exit));
656
774
  // These pre-open frames cannot belong to a newly created root session.
657
775
  held.length = 0;
@@ -660,6 +778,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
660
778
  if(policyDenial(error))policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
661
779
  await (host ? host.close() : handshake.close()).catch(() => undefined);
662
780
  await cleanup();
781
+ if (serverRequiresUpgrade(error)) throw new MuseUpgradeRequired(options.clientBuild ?? clientBuildLabel(launch.command));
663
782
  throw error;
664
783
  } finally { options.signal?.removeEventListener("abort", abortOpen); }
665
784
  }
@@ -1,20 +1,31 @@
1
- /** Local picker routes, NOT a list of physical provider model IDs. Wonder
2
- * contributor suffixes distinguish CLI recipes; MSP always gets catalogue IDs. */
1
+ /** Shape only, never an availability allowlist. The host checks model/list
2
+ * again before submitting a turn. Contributor suffixes are local CLI recipes. */
3
+ export const isMuseModelId = (id: unknown): id is string =>
4
+ typeof id === "string" && /^muse-[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id);
5
+
6
+ /** Verified 2026-11-10 by official-client contributor on/off request traces
7
+ * (the wire model ID changes only for these) and direct Meta API requests.
8
+ * Ember ignores contributor mode and its contributor API ID returns model_not_found.
9
+ * This gates contributor recipes only, never normal catalogue availability.
10
+ * Add a native ID only after verifying its contributor wire model and API support. */
11
+ export const VERIFIED_CONTRIBUTOR_MODEL_IDS: ReadonlySet<string> = new Set([
12
+ "muse-spark-1.3", "muse-spark-1.2", "muse-wonder-1.0", "muse-wonder-full-1.0",
13
+ ]);
14
+
3
15
  export function museModelRoute(id: string): {modelId:string;contributorMode:"on"|"off"} | undefined {
4
- if (["muse-spark-1.3", "muse-spark-1.3-contributor"].includes(id))
5
- return {modelId:id,contributorMode:"on"};
6
- for (const modelId of ["muse-wonder-1.0", "muse-wonder-full-1.0"]) {
7
- if (id === modelId) return {modelId,contributorMode:"off"};
8
- if (id === `${modelId}-contributor`) return {modelId,contributorMode:"on"};
9
- }
10
- return undefined;
16
+ if (!isMuseModelId(id)) return undefined;
17
+ const contributor = id.endsWith("-contributor");
18
+ const modelId = contributor ? id.slice(0, -"-contributor".length) : id;
19
+ if (!isMuseModelId(modelId) || (contributor && !VERIFIED_CONTRIBUTOR_MODEL_IDS.has(modelId))) return undefined;
20
+ return {modelId, contributorMode: contributor || modelId === "muse-spark-1.3" ? "on" : "off"};
11
21
  }
12
22
  export const isQualifiedMuseModel = (id:string) => museModelRoute(id) !== undefined;
13
23
  export function museResponseIdentity(id:string) {
14
24
  const route = museModelRoute(id);
15
25
  if (!route) return {};
16
- if (route.modelId.startsWith("muse-spark-1.3"))
26
+ if (route.modelId === "muse-spark-1.3")
17
27
  return {responseModel:"muse-spark-1.3-contributor",responseModelSource:"derived:fixed-contributor-on-recipe",contributorMode:route.contributorMode,nativeModel:route.modelId};
18
- // model/list establishes logical selection, not physical response identity.
19
- return {responseModelSource:"unknown:physical-model-id;catalogue-logical-selection",contributorMode:route.contributorMode,nativeModel:route.modelId};
28
+ // Recipe-derived identity, not a claim that the response carried model metadata.
29
+ return {responseModel:route.contributorMode === "on" ? `${route.modelId}-contributor` : route.modelId,
30
+ responseModelSource:"derived:selected-native-model-and-contributor-recipe",contributorMode:route.contributorMode,nativeModel:route.modelId};
20
31
  }
package/src/provider.ts CHANGED
@@ -261,14 +261,28 @@ function fail(b: Binding, reason: string) {
261
261
  }
262
262
  void closeBinding(b);
263
263
  }
264
+ const sequentialCalls = new WeakMap<Binding, BridgeInvocation[]>();
265
+ const sequentialStarts = new WeakMap<Binding, Map<string,{itemId:string;turnId:string;recordedAt:string}>>();
264
266
  function settleBatch(b:Binding) {
265
267
  if (b.batchSpec?.every(c=>c.verified)) {
266
268
  b.batch=undefined; b.batchSpec=undefined; b.batchSurfaced=false;
267
269
  b.receiptsDone?.(); b.receiptsDone=undefined;
270
+ const next = sequentialCalls.get(b)?.shift();
271
+ if (next && !b.closed) surface(b, next);
268
272
  }
269
273
  }
270
274
  function emitFrame(b: Binding, event: any) {
271
275
  if (b.closed) return;
276
+ if (event.kind === "degraded" && event.feature === "rawLog") {
277
+ // An approval may already be waiting for a committed frame that was lost.
278
+ // Let its exact, validated MCP invocation enter the sequential queue; never
279
+ // wait for a Pi result whose tool has not been surfaced yet.
280
+ for (const [callId,hold] of b.approvalHolds) if (!hold.ready) {
281
+ hold.ready=true; hold.resolve();
282
+ b.host?.ledger?.record("tool_approval_released",{callId,reason:"rawLog degradation; sequential MCP ownership"});
283
+ }
284
+ return;
285
+ }
272
286
  if (
273
287
  event.kind === "frame" &&
274
288
  ["approval/request", "approval/requested", "approval/updated"].includes(
@@ -313,6 +327,14 @@ function emitFrame(b: Binding, event: any) {
313
327
  if(event.kind==="frame") {
314
328
  const {method,params:p={}}=event.frame,item=p.item;
315
329
  const spec=item?.kind==="toolCall" ? b.batchSpec?.find(c=>c.callId===item.callId && !c.verified) : undefined;
330
+ if (!spec && method === "item/started" && item?.kind === "toolCall") {
331
+ const reservation=b.reservations.get(item.callId);
332
+ if (reservation && item.tool === `mcp__pi__${reservation.name}`) {
333
+ const starts=sequentialStarts.get(b) ?? new Map();
334
+ starts.set(item.callId,{itemId:item.itemId,turnId:item.turnId,recordedAt:item.recordedAt});
335
+ sequentialStarts.set(b,starts);
336
+ }
337
+ }
316
338
  if(spec && (method==="item/started" || method==="item/completed" && item.status==="timedOut")) {
317
339
  try {
318
340
  if(item.tool!==spec.name || item.args!==undefined && canonical(JSON.parse(item.args))!==canonical(spec.args) ||
@@ -441,13 +463,22 @@ function emitFrame(b: Binding, event: any) {
441
463
  throw new Error("Muse tool result receipt invocation differs from pending MCP call");
442
464
  let redactions: import("./tool-result-receipt.js").VendorRedaction[] = [];
443
465
  let images: import("./tool-result-receipt.js").UnverifiableImage[] = [];
444
- const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; });
466
+ let truncatedView: import("./tool-result-receipt.js").TruncatedView | undefined;
467
+ const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; }, view => { truncatedView = view; });
445
468
  if (!b.bridge.verifyContent(pending.invocation, receipt))
446
469
  throw new Error("Muse tool result mismatch");
470
+ if (truncatedView) b.host?.ledger?.record("tool_result_truncated_view", {
471
+ callId:item.callId, piToolCallId:b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId:item.itemId,
472
+ source:{tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId},
473
+ outputRefAvailability:item.outputRef?.availability ?? "absent", view:truncatedView,
474
+ evidence:"declared-lossy-view", exactModelConsumption:false,
475
+ });
447
476
  if (redactions.length) {
448
477
  b.host?.ledger?.record("tool_result_vendor_redaction", {
449
- callId: item.callId, itemId: item.itemId, count: redactions.length,
450
- rule: "unique-nonempty-intraline-v3", spans: redactions, evidence:"declared-lossy",
478
+ callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
479
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
480
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})}, count: redactions.length,
481
+ rule: "positional-declared-loss-v4", spans: redactions, evidence:"declared-lossy",
451
482
  textProjection: r.isError ? "lf-joined-all-text-parts" : images.length ? "native-ordered-parts-with-image-metadata" : "native-text-chunk-fold",
452
483
  exactModelConsumption: false,
453
484
  });
@@ -455,6 +486,8 @@ function emitFrame(b: Binding, event: any) {
455
486
  }
456
487
  if (images.length) b.host?.ledger?.record("tool_result_image_unverifiable", {
457
488
  callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
489
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
490
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})},
458
491
  images:images.map(image=>({...image,modelVisibility:image.modelVisibility??"unproven"})), deliveredToMcp: true, evidence:"declared-lossy", unverifiableInContent: true,
459
492
  rule: "mcp-image-placeholder-v1", exactModelConsumption: false,
460
493
  });
@@ -464,17 +497,17 @@ function emitFrame(b: Binding, event: any) {
464
497
  if(spec)spec.verified=true;
465
498
  settleBatch(b);
466
499
  };
467
- if (item.outputRef) {
500
+ if (item.outputRef && !(item.truncated === true && ["missing","unsupported","accessFailed"].includes(item.outputRef.availability))) {
468
501
  b.verifyingReceipt = readStoredToolOutput(item, offset => {
469
502
  if (!b.host?.readToolOutput) throw new Error("Muse host cannot read item/outputRef");
470
503
  return b.host.readToolOutput(item, offset);
471
- }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt: ${error.message}`); }).finally(() => {
504
+ }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }).finally(() => {
472
505
  b.verifyingReceipt=undefined;
473
506
  const events=b.buffered.splice(0);
474
507
  for(const next of events)emitFrame(b,next);
475
508
  });
476
509
  } else {
477
- try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt: ${error.message}`); }
510
+ try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }
478
511
  }
479
512
  }
480
513
  }
@@ -510,6 +543,15 @@ function surface(b: Binding, inv: BridgeInvocation) {
510
543
  fail(b, "Muse MCP invocation does not match a one-shot approval");
511
544
  throw new Error("Unapproved MCP invocation");
512
545
  }
546
+ if (b.host?.batches && !b.batchSpec) b.host.degradeBatches?.("rawLog batch boundary absent before MCP invocation");
547
+ const committedSpec=b.batchSpec?.find(spec=>spec.callId===callId);
548
+ if (!b.host?.batches && b.batch && !committedSpec) {
549
+ const queue = sequentialCalls.get(b) ?? [];
550
+ if (queue.some(previous => (previous.metadata as any)?.callId === callId)) {
551
+ fail(b, "Duplicate queued Muse invocation"); throw new Error("Duplicate invocation");
552
+ }
553
+ queue.push(inv); sequentialCalls.set(b, queue); return;
554
+ }
513
555
  b.reservations.delete(callId);
514
556
  b.approvalHolds.delete(callId); // Actual MCP invocation ends the approval handoff.
515
557
  if(b.batchSpec){
@@ -520,10 +562,13 @@ function surface(b: Binding, inv: BridgeInvocation) {
520
562
  }
521
563
  if(b.batchSpec?.find(c=>c.callId===callId)?.verified){fail(b,"Muse duplicate batch invocation");throw new Error("Duplicate invocation");}
522
564
  b.pending.set(callId, { invocation: inv, callId, verified: false });
523
- if (!(config.toolBatches ?? true) || !b.host?.batches) {
565
+ if ((!(config.toolBatches ?? true) || !b.host?.batches) && !b.batchSpec) {
566
+ // A batch surfaced before degradation must finish under its existing spec.
567
+ // Only genuinely new calls enter the sequential ownership path.
524
568
  if(b.pending.size!==1){fail(b,"Concurrent Muse tools require committed batch capability");throw new Error("Missing tool batch");}
525
569
  b.batch=[callId];
526
- b.batchSpec=[{callId,name:`mcp__pi__${inv.name}`,args:inv.arguments,piCallId:inv.piCallId}];
570
+ b.batchSpec=[{callId,name:`mcp__pi__${inv.name}`,args:inv.arguments,piCallId:inv.piCallId,nativeStart:sequentialStarts.get(b)?.get(callId)}];
571
+ sequentialStarts.get(b)?.delete(callId);
527
572
  }
528
573
  const spec=b.batchSpec?.find(c=>c.callId===callId);
529
574
  if(spec?.journal)deliverResult(b,spec);
@@ -579,7 +624,7 @@ function flushTools(b: Binding) {
579
624
  /** Live inference is explicit opt-in; echo always launches the offline provider. */
580
625
  function streamEffective(model: any, input: any, options: any = {}) {
581
626
  if(config.modelAllowed && !config.modelAllowed(model)){
582
- const refused=createAssistantMessageEventStream();const output=message(model);output.stopReason="error";output.errorMessage="Muse model is not qualified for Pi prompt/compaction; select a catalogue-registered Spark 1.3 contributor, Wonder or Wonder Full route";
627
+ const refused=createAssistantMessageEventStream();const output=message(model);output.stopReason="error";output.errorMessage="Muse model is not qualified for Pi prompt/compaction; select a catalogue-registered Muse route";
583
628
  refused.push({type:"error",reason:"error",error:output});refused.end();return refused;
584
629
  }
585
630
  const context = piContext(input);
@@ -866,7 +911,7 @@ function streamEffective(model: any, input: any, options: any = {}) {
866
911
  try {
867
912
  const args = JSON.parse(request.rawArgs);
868
913
  const spec=candidate.batchSpec?.find(c=>c.callId===request.toolCallId);
869
- if(candidate.closed || (candidate.batchSpec && (!spec || spec.verified || spec.name!==request.toolName || canonical(spec.args)!==canonical(args))))return false;
914
+ if(candidate.closed || (spec && (spec.verified || spec.name!==request.toolName || canonical(spec.args)!==canonical(args))) || (candidate.host?.batches && candidate.batchSpec && !spec))return false;
870
915
  const previous = reservations.get(request.toolCallId);
871
916
  if (
872
917
  previous &&
@@ -925,7 +970,7 @@ function streamViaMuse(model:any,input:any,options:any={}) {
925
970
  throw new Error("Muse onPayload must return a logical request with systemPrompt, messages and tools");
926
971
  if(effective.messages.some((entry:any)=>entry?.role==="system"))
927
972
  throw new Error("Muse logical payload messages exclude system messages; edit logical systemPrompt and tools instead");
928
- const request={...effective,tools:effective.tools.map((tool:any,index:number)=>index ? tool : ({...tool,description:`${tool.description??""}\n\nTransport notice: [REDACTED] in tool text can be official-client redaction; original bytes in those spans are unavailable. Tool images are delivered without pixel attestation; GIF/WebP visibility is unqualified. Images attached to failed tool results are omitted by the official client.`}))};
973
+ const request={...effective,tools:effective.tools.map((tool:any,index:number)=>index ? tool : ({...tool,description:`${tool.description??""}\n\nTransport notice: the official-client transcript view of a tool result may be truncated; full model consumption cannot be inferred from that view. [REDACTED] in tool text can be official-client redaction; original bytes in those spans are unavailable. Literal [REDACTED] may already be source text: a marker alone does not prove loss. The client may canonicalize bearer to Bearer immediately before a redaction. Tool images are delivered without pixel attestation; GIF/WebP visibility is unqualified. Images attached to failed tool results are omitted by the official client.`}))};
929
974
  for await(const event of streamEffective(model,request,options))stream.push(event);
930
975
  stream.end();
931
976
  } catch(error:any) {