pi-muse-tether 0.2.0 → 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.
@@ -1,3 +1,4 @@
1
+ import { qualifiedBatchBuilds } from "./qualification-records.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import { promisify } from "node:util";
3
4
  import { readFile, realpath, stat } from "node:fs/promises";
@@ -10,7 +11,7 @@ export const TESTED_CLI_MAX = "1.4.15";
10
11
  /** Exact builds whose experimental rawLog committed-batch boundary was live
11
12
  * qualified: 1.4.14-R7309.1 (original), 1.4.15-R8339.1 (2026-11-10: parallel
12
13
  * two-call batch, private prompt, session MCP readiness, Ember). */
13
- export const QUALIFIED_BATCH_BUILDS = ["Muse Code 1.4.14 (1.4.14-R7309.1)", "Muse Code 1.4.15 (1.4.15-R8339.1)"] as const;
14
+ export const QUALIFIED_BATCH_BUILDS = () => qualifiedBatchBuilds();
14
15
  /** The tether's SDK is pinned independently, not required to equal the CLI. */
15
16
  export const QUALIFIED_SDK = "1.4.14";
16
17
  const warnedNewerCliVersions = new Set<string>();
@@ -24,20 +25,17 @@ const compareVersions = (a: string, b: string) => {
24
25
  export const isNewerThanTestedCli = (version: string) => compareVersions(version, TESTED_CLI_MAX) > 0;
25
26
  export const strictCliVersion = (env: NodeJS.ProcessEnv = process.env) => env.PI_MUSE_TETHER_STRICT_VERSION === "1";
26
27
 
27
- export function assertQualifiedVersions(clientOutput: string, sdk: string, rawLog = false, env: NodeJS.ProcessEnv = process.env) {
28
+ export function assertQualifiedVersions(clientOutput: string, sdk: string, env: NodeJS.ProcessEnv = process.env) {
28
29
  const match = /^Muse Code (\d+\.\d+\.\d+)(?: \(\1-R[\d.]+\))?$/.exec(clientOutput.trim());
29
30
  if (!match || compareVersions(match[1], MIN_CLI_VERSION) < 0 || sdk !== QUALIFIED_SDK)
30
31
  throw new Error(`Unqualified Muse client/SDK: client=${clientOutput.trim()}, SDK=${sdk}; requires Muse Code >=${MIN_CLI_VERSION}, SDK ${QUALIFIED_SDK}; no model request submitted.`);
31
- // Experimental committed-batch payloads remain qualified ONLY against this
32
- // exact build. Warn-and-continue never enables rawLog on an untested build.
33
- if (rawLog && !(QUALIFIED_BATCH_BUILDS as readonly string[]).includes(clientOutput.trim()))
34
- throw new Error(`Unqualified Muse experimental rawLog/committed-batch build; requires one of ${QUALIFIED_BATCH_BUILDS.join(", ")}; no model request submitted.`);
32
+ // Experimental capability is negotiated and its frames checked at runtime.
33
+ // Qualification records report evidence; they do not deny unknown builds.
35
34
  if (isNewerThanTestedCli(match[1])) {
36
- if (strictCliVersion(env))
37
- throw new Error(`Unqualified Muse Code ${match[1]}: newer than tested range ${MIN_CLI_VERSION}-${TESTED_CLI_MAX}; PI_MUSE_TETHER_STRICT_VERSION=1 refuses it; no model request submitted.`);
35
+ if (strictCliVersion(env)) throw new Error(`Unqualified Muse Code ${match[1]}: PI_MUSE_TETHER_STRICT_VERSION=1 refuses newer than tested ${TESTED_CLI_MAX}; no model request submitted.`);
38
36
  if (!warnedNewerCliVersions.has(match[1])) {
39
37
  warnedNewerCliVersions.add(match[1]);
40
- console.warn(`[pi-muse-tether] Muse Code ${match[1]} is newer than tested range ${MIN_CLI_VERSION}-${TESTED_CLI_MAX}; continuing, not yet qualified (including private settings prompt delivery). Set PI_MUSE_TETHER_STRICT_VERSION=1 to refuse newer clients. Experimental rawLog/committed-batch mode remains exact-build gated.`);
38
+ console.warn(`[pi-muse-tether] Muse Code ${match[1]}: continuing, not yet qualified; capability/schema checks govern batching. PI_MUSE_TETHER_STRICT_VERSION=1 opts into refusing newer builds.`);
41
39
  }
42
40
  }
43
41
  return {client: match[1], sdk};
@@ -60,7 +58,6 @@ export async function qualifyMuseVersion(
60
58
  binary: string,
61
59
  env: NodeJS.ProcessEnv,
62
60
  signal?: AbortSignal,
63
- rawLog = false,
64
61
  ) {
65
62
  const entry = createRequire(import.meta.url).resolve("@muse-code/sdk");
66
63
  const sdk = JSON.parse(
@@ -69,15 +66,16 @@ export async function qualifyMuseVersion(
69
66
  signal?.throwIfAborted();
70
67
  const identity = await binaryIdentity(binary);
71
68
  signal?.throwIfAborted();
72
- const key = identity && JSON.stringify([identity, sdk, rawLog]);
69
+ const key = identity && JSON.stringify([identity, sdk]);
73
70
  const cached = key && versionCache.get(key);
74
- if (cached) return assertQualifiedVersions(cached, sdk, rawLog, env);
71
+ if (cached) return assertQualifiedVersions(cached, sdk, env);
75
72
  const { stdout } = await promisify(execFile)(binary, ["--version"], {
76
- env: { ...env, MUSE_NO_AUTO_UPDATE: "1" },
73
+ env,
77
74
  signal,
78
75
  });
79
- const result = assertQualifiedVersions(stdout, sdk, rawLog, env);
76
+ const result = assertQualifiedVersions(stdout, sdk, env);
80
77
  signal?.throwIfAborted();
81
78
  if (key && identity === await binaryIdentity(binary)) versionCache.set(key, stdout);
82
79
  return result;
83
80
  }
81
+
package/src/doctor.ts CHANGED
@@ -1,22 +1,33 @@
1
1
  import { museModelRoute } from "./model-route.js";
2
2
  import { assertLoginSafe } from "./settings.js";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
3
+ import { clientStatus, resolveMuseBinary } from "./qualification-records.js";
4
+ import { museFeatureStatus } from "./features.js";
5
+ import { qualifyClient } from "./qualification.js";
5
6
  import { qualifyMuseVersion, MIN_CLI_VERSION, TESTED_CLI_MAX, isNewerThanTestedCli, strictCliVersion } from "./cli-version.js";
6
7
  import { museLedgerPath } from "./request-ledger.js";
7
8
  import { MUSE_CACHE_POLICY } from "./cache-policy.js";
8
9
  /** Local diagnostic only: --version, no account/auth contents, quota or inference. */
9
- export async function museDoctor(modelId?: string) {
10
- const binary =
11
- process.env.PI_MUSE_TETHER_BINARY ?? join(homedir(), ".local/bin/muse");
10
+ export async function museDoctor(modelId?: string, args = "") {
11
+ const [command, ...arguments_] = args.trim().split(/\s+/);
12
+ if (command === "qualify") {
13
+ const builds=arguments_.filter(value=>!value.startsWith("--"));
14
+ if (builds.length > 1 || arguments_.some(value=>value.startsWith("--") && value !== "--live")) throw new Error("Usage: /muse-doctor qualify [build] [--live]");
15
+ return JSON.stringify(await qualifyClient(builds[0],arguments_.includes("--live"),modelId ? museModelRoute(modelId)?.modelId : undefined),null,2);
16
+ }
17
+ if (command && command !== "qualify") throw new Error("Unknown /muse-doctor command; use /muse-doctor or /muse-doctor qualify [build] [--live]");
18
+ const binary = resolveMuseBinary();
12
19
  const { META_API_KEY: _, ...env } = process.env;
13
20
  try {
14
21
  assertLoginSafe();
15
- const versions = await qualifyMuseVersion(binary, env);
22
+ const versions = await qualifyMuseVersion(binary, {...env, MUSE_NO_AUTO_UPDATE:"1"});
23
+ let status:unknown;
24
+ try { status=clientStatus(); } catch (error) { status={unavailable:String(error)}; }
16
25
  return JSON.stringify(
17
26
  {
18
27
  ok: true,
19
28
  binary,
29
+ clientStatus:status,
30
+ features:museFeatureStatus(),
20
31
  ...versions,
21
32
  versionPolicy: {minimum:MIN_CLI_VERSION, testedMaximum:TESTED_CLI_MAX, newerThanTested:isNewerThanTestedCli(versions.client), strict:strictCliVersion()},
22
33
  contributorMode: modelId ? museModelRoute(modelId)?.contributorMode ?? null : null,
@@ -0,0 +1,25 @@
1
+ export type MuseFeature = "rawLog" | "privatePrompt" | "sessionMcp" | "catalogue";
2
+ const observed = new Map<MuseFeature,{build:string;status:string;reason?:string}>();
3
+ export function featureNotice(build:string,feature:MuseFeature,reason:string,fallback:string) {
4
+ observed.set(feature,{build,status:fallback,reason});
5
+ return `[pi-muse-tether] ${JSON.stringify({code:"MUSE_FEATURE_DEGRADED",build,feature,reason,fallback,remedy:"/muse-doctor qualify [build]"})}`;
6
+ }
7
+ export function featureActive(build:string,feature:MuseFeature) { observed.set(feature,{build,status:"active"}); }
8
+ export const MUSE_FEATURE_CONTRACT = {
9
+ rawLog:{stability:"experimental",check:"qualification evidence + initialize grant + recorded envelope and consumed payload schema",fallback:"sequential Pi tools; no replay"},
10
+ privatePrompt:{stability:"experimental",check:"experimentalApi negotiation + session reviewer shape; exact instruction delivery attested by live qualification",fallback:"supported run.developer_prompt; appended, not replacement"},
11
+ sessionMcp:{stability:"stable capability with experimental configuration",check:"initialize sessionMcp grant + session/start identity + inventory readiness/tool names",fallback:"typed refusal; Pi must own tools"},
12
+ versionPolicy:{minimum:"protocol-compatible floor",testedRange:"declared evidence, warning above maximum",strict:"explicit opt-in refuses above maximum",updates:"vendor-owned; no production suppression"},
13
+ } as const;
14
+ export const museFeatureStatus = () => ({
15
+ rawLog:{status:"not negotiated",fallback:"sequential unless qualified and granted"},
16
+ privatePrompt:{status:"not negotiated",fallback:"append supported developer instructions"},
17
+ sessionMcp:{status:"not negotiated",fallback:"refuse if unavailable"},
18
+ ...Object.fromEntries(observed),
19
+ });
20
+ export class MuseFeatureUnavailable extends Error {
21
+ readonly code="MUSE_FEATURE_UNAVAILABLE";
22
+ constructor(readonly build:string,readonly feature:MuseFeature,readonly causeDescription:string) {
23
+ super(`${featureNotice(build,feature,causeDescription,"refused: Pi must own tools")}; MUSE_FEATURE_UNAVAILABLE: run /muse-doctor qualify ${build}`);
24
+ }
25
+ }
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";
@@ -27,6 +30,7 @@ export type MuseHostEvent =
27
30
  | { kind: "frame"; frame: MuseFrame }
28
31
  | { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number }
29
32
  | { kind: "fenced"; reason: string }
33
+ | { kind: "degraded"; feature: "rawLog"; reason: string }
30
34
  | { kind: "tool-batch"; calls: Array<{callId:string;name:string;args:Record<string,unknown>}> }
31
35
  | { kind: "auth-metadata"; metadata: unknown };
32
36
 
@@ -34,6 +38,9 @@ export interface MuseHostOptions {
34
38
  cwd: string;
35
39
  /** Requires the pinned experimental rawLog batch boundary; never timing heuristics. */
36
40
  toolBatches?: boolean;
41
+ /** Only the explicitly isolated, opt-in qualifier can probe before certification. */
42
+ qualificationProbe?: boolean;
43
+ clientBuild?: string;
37
44
  purpose?: "coding" | "raw";
38
45
  piSessionId?: string;
39
46
  reasoningEffort?: ReturnType<typeof museEffort>;
@@ -90,6 +97,16 @@ export function policyDenial(error: unknown, seen=new Set<unknown>()): boolean {
90
97
  return [value.data, value.error, value.cause].some((nested) => nested !== error && policyDenial(nested, seen));
91
98
  }
92
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
+ }
93
110
  function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
94
111
  if (!error || typeof error !== "object" || seen.has(error)) return false;
95
112
  seen.add(error);
@@ -108,10 +125,11 @@ function validateOptions(options: MuseHostOptions): void {
108
125
  if (options.contributorMode !== undefined && !["on","off"].includes(options.contributorMode))
109
126
  throw new Error("Muse contributor mode must be on or off");
110
127
  const candidate = options.privatePrompt !== undefined && options.promptMode === "replace";
111
- 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");
112
130
  if (!options.echo) assertLoginSafe();
113
- if (options.promptMode !== "none" && !candidate) throw new Error("Muse prompt mode unsupported: no qualified instruction isolation");
114
- 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");
115
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");
116
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");
117
135
  if (options.echo !== true && process.env.PI_MUSE_TETHER_LIVE !== "1") throw new Error("Live Muse requires explicit PI_MUSE_TETHER_LIVE=1");
@@ -123,7 +141,7 @@ function validateOptions(options: MuseHostOptions): void {
123
141
  /** Supported official flags only; no config mutation, trust, login or credential I/O. */
124
142
  export function museLaunchOptions(options: MuseHostOptions): SpawnMspConnectionOptions {
125
143
  validateOptions(options);
126
- const command = options.binary ?? process.env.PI_MUSE_TETHER_BINARY ?? join(homedir(), ".local/bin/muse");
144
+ const command = options.binary ?? resolveMuseBinary();
127
145
  if (!isAbsolute(command)) throw new Error("Muse binary must be absolute");
128
146
  return {
129
147
  command,
@@ -135,7 +153,7 @@ export function museLaunchOptions(options: MuseHostOptions): SpawnMspConnectionO
135
153
  "--config", `run.toolset=${JSON.stringify(options.tools.map(name => `mcp__pi__${name}`))}`,
136
154
  "--disable-request-user-input", ...(options.echo ? ["--provider", "echo"] : [])],
137
155
  cwd: options.cwd,
138
- 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
139
157
  ? ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "MUSE_NO_AUTO_UPDATE", "MUSE_WIRE_DIR", "MUSE_TRANSPORT_TRACE"].includes(key)
140
158
  : !["META_API_KEY", "MUSE_CONTRIBUTOR_MODE"].includes(key))),
141
159
  // No tether workload timeout: SDK SS2.1.2 owns the default 30s close deadline.
@@ -198,8 +216,12 @@ export class MuseHost {
198
216
  this.#tools = new Set(options.tools.map((name) => `mcp__pi__${name}`));
199
217
  this.#durability = readSessionDurability(initialized);
200
218
  if (this.#durability.kind !== "ephemeral") throw new Error("Muse requires declared ephemeral session durability");
201
- if (!initialized.grantedCapabilities.includes("sessionMcp")) throw new Error("Muse did not grant sessionMcp");
202
- 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
+ }
203
225
  connection.onNotification((frame) => this.receive(frame as MuseFrame));
204
226
  connection.onServerRequest(async (request) => {
205
227
  if (request.method === "approval/request" || request.method === "userInput/request") {
@@ -220,6 +242,15 @@ export class MuseHost {
220
242
  get sessionId(): string { if (!this.#session) throw new Error("Muse session not open"); return this.#session.sessionId; }
221
243
  get view(): SessionFoldView { if (!this.#session) throw new Error("Muse session not open"); return this.#session.fold; }
222
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
+ }
223
254
  get batches(): boolean { return this.#options.toolBatches === true; }
224
255
  /** Official read-only byte-ranged output API; no filesystem/path fallback. */
225
256
  async readToolOutput(item: { itemId: string; outputRef: { id: string } }, offsetBytes: number) {
@@ -230,6 +261,10 @@ export class MuseHost {
230
261
  /** SDK Connection.command's documented nothing-admitted overload classes. */
231
262
  get retrySafe(): boolean { return this.#retrySafe; }
232
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
+ }
233
268
  if(!policyDenial(error))return false;
234
269
  policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
235
270
  this.fence(policyLatch);return true;
@@ -258,7 +293,7 @@ export class MuseHost {
258
293
  const result = raw as unknown as Extract<NonNullable<SessionOptions["opening"]>, { verb: "session/start" }>["result"];
259
294
  if (typeof result.session?.sessionId !== "string") throw new Error("Invalid Muse session/start result");
260
295
  if(this.#options.privatePrompt && (result.session as any).permissionState?.reviewerAuthority!=="human")
261
- 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");
262
297
  this.#session = this.makeSession({ sessionId: result.session.sessionId, durability: this.#durability,
263
298
  discarded: this.#discarded, connection: this.connection, opening: { verb: "session/start", result } });
264
299
  this.ledger.opened(this.#session.sessionId);
@@ -277,15 +312,22 @@ export class MuseHost {
277
312
  return this.#decide(request);
278
313
  });
279
314
  this.#session.onApprovalError((error) => { if(!this.#refusal(error))this.fence("Muse approval round trip failed"); });
280
- if(this.batches) {
315
+ if(this.batches) { try {
281
316
  const streams=await this.connection.command("log/streams",{sessionId:this.sessionId},{maxAttempts:1});
282
317
  const stream=(streams.streams as any[])?.map(s=>s.stream).find(s=>s?.kind==="session.live" && s.id===this.sessionId);
283
318
  if(!stream)throw new Error("Muse rawLog session stream absent; parallel tools unsupported");
284
319
  const sub=await this.connection.command("log/subscribe",{sessionId:this.sessionId,stream},{maxAttempts:1});
285
320
  if(!(typeof sub.subscriptionId==="number" && Number.isFinite(sub.subscriptionId)))throw new Error("Muse rawLog subscription absent");
286
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));
287
330
  }
288
- await this.#awaitSessionMcp();
289
331
  // Entire drain is synchronous. A newly arriving event cannot overtake it.
290
332
  const held = this.#held;
291
333
  this.#held = [];
@@ -345,15 +387,15 @@ export class MuseHost {
345
387
 
346
388
  /** The single ingress, also used by synthetic frame fixtures. */
347
389
  receive(frame: MuseFrame): void {
348
- 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;}
349
391
  if(frame.method==="log/record") {
350
392
  const p=frame.params as any;
351
393
  if(this.#logSubscription===undefined || p?.subscriptionId!==this.#logSubscription || this.#reason || this.#dead)return;
352
394
  const payload=p.record?.payload, event=payload?.event;
353
- if(payload?.kind==="run" && event?.kind==="assistant_tool_calls_committed") {
395
+ if(this.batches && payload?.kind==="run" && event?.kind==="assistant_tool_calls_committed") {
354
396
  if(!this.#busy || payload.run_id!==this.#submission?.turnId){this.fence("Muse committed tool batch has foreign turn identity");return;}
355
397
  try {
356
- 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);
357
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");
358
400
  const signatures=calls.map((c:any)=>JSON.stringify([c.callId,c.name,canonical(c.args)]));
359
401
  const batch=JSON.stringify(signatures);
@@ -364,7 +406,9 @@ export class MuseHost {
364
406
  calls.forEach((c:any,i:number)=>this.#committedCalls.set(c.callId,signatures[i]));
365
407
  this.#committedBatches.add(batch);
366
408
  this.#emit({kind:"tool-batch",calls});
367
- }catch{this.fence("Muse malformed committed tool batch");}
409
+ }catch{
410
+ this.degradeBatches("Batch schema mismatch");
411
+ }
368
412
  }
369
413
  return;
370
414
  }
@@ -389,9 +433,9 @@ export class MuseHost {
389
433
  const retry=["turn/retryScheduled","turn/modelRetryScheduled"].includes(frame.method);
390
434
  if(retry)this.ledger.observe(frame); // Includes refused retries, before any latch.
391
435
  // Only protocol error fields count; model/user/tool text is never scanned.
392
- 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))){
393
437
  this.#emit({kind:"frame",frame});
394
- this.#refusal(policyDenial(params.error) ? params.error : params);return;
438
+ this.#refusal(policyDenial(params.error) || serverRequiresUpgrade(params.error) ? params.error : params);return;
395
439
  }
396
440
  if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
397
441
  this.#emit({kind:"frame",frame});
@@ -634,9 +678,19 @@ export async function discoverMuseCatalog() {
634
678
  }
635
679
 
636
680
  export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost> {
637
- 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)};
638
683
  options.signal?.throwIfAborted();
639
- await qualifyMuseVersion(launch.command, launch.env??{}, options.signal, options.toolBatches);
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"]};
640
694
  // Muse canonicalizes workspaceRoot before trust lookup (e.g. macOS /var).
641
695
  // One canonical root owns settings, trust, auth link and raw/coding workspace.
642
696
  const home = await realpath(await mkdtemp(join(tmpdir(), "pi-muse-host-")));
@@ -655,7 +709,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
655
709
  };
656
710
  try {
657
711
  if (options.privatePrompt) {
658
- 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");
659
713
  options = {...options, privateWorkspace: privateWorkspace(home)};
660
714
  if(!options.echo){
661
715
  const verify=await linkHostLogin(home,launch.env?.XDG_CONFIG_HOME??join(homedir(),".config"));
@@ -669,7 +723,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
669
723
  const skills=options.privatePrompt.skillsOff??await discoverSkillsOff(launch.command,options.cwd,env);
670
724
  // Inventory is finished before the model host starts. Only this generation
671
725
  // can see this settings path; auxiliary summaries stage their own files.
672
- 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});
673
727
  }
674
728
  } catch (error) { await cleanup(); throw error; }
675
729
  const handshake = spawnMspConnection({ ...launch, env });
@@ -690,7 +744,17 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
690
744
  try {
691
745
  const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
692
746
  capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches||Object.keys(options.mcpServers??{}).length)?{experimentalApi:true}:{}) } });
693
- if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported; no model request submitted");
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
+ }
694
758
  if (!options.echo) {
695
759
  const catalog = await spawned.connection.request("model/list", {});
696
760
  const selected = (catalog.models as any[])?.find((m) => m.modelId === options.model);
@@ -704,6 +768,8 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
704
768
  host = new MuseHost(spawned.connection, spawned.initializeResult, {...options,verifyLogin}, async () => {
705
769
  try { await spawned.close(); } finally { await cleanup(); }
706
770
  });
771
+ if (batchReason) host.degradeBatches(batchReason);
772
+ else if (host.batches) featureActive(options.clientBuild ?? "unknown build","rawLog");
707
773
  void spawned.child.exit.then((exit) => host!.hostExited(exit));
708
774
  // These pre-open frames cannot belong to a newly created root session.
709
775
  held.length = 0;
@@ -712,6 +778,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
712
778
  if(policyDenial(error))policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
713
779
  await (host ? host.close() : handshake.close()).catch(() => undefined);
714
780
  await cleanup();
781
+ if (serverRequiresUpgrade(error)) throw new MuseUpgradeRequired(options.clientBuild ?? clientBuildLabel(launch.command));
715
782
  throw error;
716
783
  } finally { options.signal?.removeEventListener("abort", abortOpen); }
717
784
  }
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) ||
@@ -521,6 +543,15 @@ function surface(b: Binding, inv: BridgeInvocation) {
521
543
  fail(b, "Muse MCP invocation does not match a one-shot approval");
522
544
  throw new Error("Unapproved MCP invocation");
523
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
+ }
524
555
  b.reservations.delete(callId);
525
556
  b.approvalHolds.delete(callId); // Actual MCP invocation ends the approval handoff.
526
557
  if(b.batchSpec){
@@ -531,10 +562,13 @@ function surface(b: Binding, inv: BridgeInvocation) {
531
562
  }
532
563
  if(b.batchSpec?.find(c=>c.callId===callId)?.verified){fail(b,"Muse duplicate batch invocation");throw new Error("Duplicate invocation");}
533
564
  b.pending.set(callId, { invocation: inv, callId, verified: false });
534
- 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.
535
568
  if(b.pending.size!==1){fail(b,"Concurrent Muse tools require committed batch capability");throw new Error("Missing tool batch");}
536
569
  b.batch=[callId];
537
- 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);
538
572
  }
539
573
  const spec=b.batchSpec?.find(c=>c.callId===callId);
540
574
  if(spec?.journal)deliverResult(b,spec);
@@ -877,7 +911,7 @@ function streamEffective(model: any, input: any, options: any = {}) {
877
911
  try {
878
912
  const args = JSON.parse(request.rawArgs);
879
913
  const spec=candidate.batchSpec?.find(c=>c.callId===request.toolCallId);
880
- 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;
881
915
  const previous = reservations.get(request.toolCallId);
882
916
  if (
883
917
  previous &&
@@ -0,0 +1,99 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, openSync, closeSync, readSync, fstatSync, statSync, realpathSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { dirname, isAbsolute, join } from "node:path";
6
+ export interface QualificationRecord {build:string;sha256:string;schemaHash:string;results:Record<string,unknown>;qualified:boolean;}
7
+ export const QUALIFICATION_CHECKS=["batchBoundary","privatePrompt","sessionMcp","resume","image"] as const;
8
+ function validateRecord(record:QualificationRecord,expectedBuild=record.build) {
9
+ checkedBuild(record.build);
10
+ if (record.build !== expectedBuild || !/^[a-f0-9]{64}$/.test(record.sha256) || typeof record.qualified !== "boolean" || !record.results || typeof record.results !== "object") throw new Error("Invalid qualification record identity/results");
11
+ if (record.qualified && (!/^[a-f0-9]{64}$/.test(record.schemaHash) || record.results.offline !== true || !QUALIFICATION_CHECKS.every(name=>(record.results.live as any)?.[name]?.status === "passed"))) throw new Error("Complete qualification requires matching offline and every named live result");
12
+ return record;
13
+ }
14
+ export function checkedBuild(build: string) {
15
+ if (!/^\d+\.\d+\.\d+-R\d+(?:\.\d+)?$/.test(build)) throw new Error(`Invalid Muse build: ${build}`);
16
+ return build;
17
+ }
18
+ export const qualificationHome = () => process.env.PI_MUSE_TETHER_QUALIFICATION_HOME ?? join(process.env.XDG_DATA_HOME || join(homedir(),".local/share"),"pi-muse-tether/qualifications");
19
+ export function binaryHash(path:string) {
20
+ const fd=openSync(path,"r"), hash=createHash("sha256");
21
+ try {
22
+ // Filesystem-reported block size is an I/O chunk, never a workload cap.
23
+ const buffer=Buffer.allocUnsafe(fstatSync(fd).blksize);
24
+ for (;;) { const bytes=readSync(fd,buffer); if (!bytes) break; hash.update(buffer.subarray(0,bytes)); }
25
+ return hash.digest("hex");
26
+ } finally { closeSync(fd); }
27
+ }
28
+ export function schemaHash(binary:string) {
29
+ const out=mkdtempSync(join(tmpdir(),"muse-schema-"));
30
+ try {
31
+ const {META_API_KEY:_,...env}=process.env;
32
+ execFileSync(binary,["schema","generate-json-schema","--experimental","--out",out],{env:{...env,MUSE_NO_AUTO_UPDATE:"1",HOME:out,XDG_CONFIG_HOME:join(out,"config"),XDG_DATA_HOME:join(out,"data"),XDG_CACHE_HOME:join(out,"cache"),XDG_STATE_HOME:join(out,"state")},maxBuffer:Infinity});
33
+ return binaryHash(join(out,"msp.schema.json"));
34
+ } finally {rmSync(out,{recursive:true,force:true});}
35
+ }
36
+ export function resolveMuseBinary() {
37
+ const path=process.env.PI_MUSE_TETHER_BINARY ?? join(homedir(),".local/bin/muse");
38
+ if (!isAbsolute(path)) throw new Error("Muse binary must be absolute");
39
+ return path;
40
+ }
41
+ export function selectedClient(binary=resolveMuseBinary()) {
42
+ const {META_API_KEY:_,...env}=process.env;
43
+ const home=mkdtempSync(join(tmpdir(),"muse-version-"));
44
+ let output:string;
45
+ try {
46
+ output=execFileSync(binary,["--version"],{env:{...env,NODE_OPTIONS:undefined,MUSE_NO_AUTO_UPDATE:"1",HOME:home,XDG_CONFIG_HOME:join(home,"config"),XDG_DATA_HOME:join(home,"data"),XDG_CACHE_HOME:join(home,"cache"),XDG_STATE_HOME:join(home,"state")},encoding:"utf8"}).trim();
47
+ } finally { rmSync(home,{recursive:true,force:true}); }
48
+ const build=checkedBuild(/\(([^)]+)\)/.exec(output)?.[1] ?? "unknown");
49
+ // Hash official executable bytes, not the mutable launcher script.
50
+ const executable=binary.endsWith("/muse") ? join(dirname(binary),`muse-bin-${build}`) : binary;
51
+ return {build,binary:executable,sha256:binaryHash(executable)};
52
+ }
53
+ export function readQualification(build:string):QualificationRecord|undefined {
54
+ const path=join(qualificationHome(),`${checkedBuild(build)}.json`);
55
+ return existsSync(path)?validateRecord(JSON.parse(readFileSync(path,"utf8")),build):undefined;
56
+ }
57
+ export function writeQualification(record:QualificationRecord) {
58
+ validateRecord(record);
59
+ mkdirSync(qualificationHome(),{recursive:true,mode:0o700});
60
+ const target=join(qualificationHome(),`${checkedBuild(record.build)}.json`), temp=`${target}.${randomUUID()}.tmp`;
61
+ writeFileSync(temp,JSON.stringify(record,null,2)+"\n",{mode:0o600,flag:"wx"});renameSync(temp,target);
62
+ }
63
+ export const QUALIFICATION_SEEDS:QualificationRecord[] = JSON.parse(readFileSync(new URL("../assets/qualification-seeds.json",import.meta.url),"utf8"));
64
+ export const LEGACY_BATCH_BUILDS=QUALIFICATION_SEEDS.map(record=>record.build);
65
+ export function clientBuildLabel(binary=resolveMuseBinary()) {
66
+ const direct=/muse-bin-(\d+\.\d+\.\d+-R\d+(?:\.\d+)?)$/.exec(binary)?.[1];
67
+ if (direct) return direct;
68
+ try { return checkedBuild(readFileSync(join(dirname(binary),".muse-version"),"utf8").trim()); } catch { return "unknown build"; }
69
+ }
70
+ const eligibilityCache=new Map<string,{build:string;qualified:boolean;reason:string}>();
71
+ function fileIdentity(path:string) {
72
+ const s=statSync(path,{bigint:true});
73
+ return JSON.stringify([realpathSync(path),String(s.dev),String(s.ino),String(s.size),String(s.mtimeNs),String(s.ctimeNs)]);
74
+ }
75
+ export function batchEligibility(binary:string) {
76
+ const build=clientBuildLabel(binary), record=build === "unknown build" ? undefined : readQualification(build);
77
+ const seed=QUALIFICATION_SEEDS.find(record=>record.build===build);
78
+ if (!record?.qualified && !seed?.qualified) return {build,qualified:false,reason:"No completed batch qualification record"};
79
+ const executable=binary.endsWith("/muse") ? join(dirname(binary),`muse-bin-${build}`) : binary;
80
+ const evidence=record?.qualified ? record : seed!, identity=fileIdentity(executable), key=JSON.stringify([identity,evidence]);
81
+ const cached=eligibilityCache.get(key); if(cached)return cached;
82
+ const sha256=binaryHash(executable), schema=schemaHash(executable);
83
+ if (identity!==fileIdentity(executable)) return {build,qualified:false,reason:"Official client changed during qualification identity check"};
84
+ const result={build,qualified:evidence.sha256===sha256 && evidence.schemaHash===schema,reason:"Qualification binary/schema identity check"};
85
+ eligibilityCache.set(key,result);return result;
86
+ }
87
+ export function qualifiedBatchBuilds() {
88
+ const records=existsSync(qualificationHome())?readdirSync(qualificationHome()).filter(name=>/^\d+\.\d+\.\d+-R\d+(?:\.\d+)?\.json$/.test(name)).map(name=>readQualification(name.slice(0,-5))!).filter(record=>record.qualified).map(record=>record.build):[];
89
+ return [...new Set([...LEGACY_BATCH_BUILDS,...records])];
90
+ }
91
+ export function clientStatus(verify=true) {
92
+ if (!verify) {
93
+ const binary=resolveMuseBinary(), build=clientBuildLabel(binary);
94
+ const record=build === "unknown build" ? undefined : readQualification(build);
95
+ return {build,binary,qualification:record?.qualified || LEGACY_BATCH_BUILDS.includes(build) ? "recorded; runtime binary/schema check pending" : "unqualified; sequential tools",batchPolicy:"qualification + negotiated capability + runtime schema"};
96
+ }
97
+ const client=selectedClient(), record=readQualification(client.build);
98
+ return {...client,qualification:record && record.sha256 === client.sha256 ? record : null, legacyQualified:LEGACY_BATCH_BUILDS.includes(client.build), batchPolicy:"qualification evidence + rawLog grant + runtime schema validation; unknown builds run sequentially"};
99
+ }