pi-muse-tether 0.1.0 → 0.2.0

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
@@ -5,9 +5,10 @@ import { MuseLedger } from "./request-ledger.js";
5
5
  import type { TurnInputPart } from "./wire-types.js";
6
6
  import { homedir, tmpdir } from "node:os";
7
7
  import { createHash } from "node:crypto";
8
- import { mkdtemp, rm } from "node:fs/promises";
8
+ import { mkdtemp, realpath, rm } from "node:fs/promises";
9
+ import { setTimeout as delay } from "node:timers/promises";
9
10
  import { isAbsolute, join } from "node:path";
10
- import { writePromptSettings, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
11
+ import { writePromptSettings, privateWorkspace, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
11
12
  import { writeFile } from "node:fs/promises";
12
13
  import {
13
14
  Connection, DiscardedSessions, MspError, Session, readSessionDurability,
@@ -16,6 +17,9 @@ import {
16
17
  type SessionOptions, type SpawnMspConnectionOptions, type ViewEvent,
17
18
  } from "@muse-code/sdk";
18
19
 
20
+ /** Inventory recheck pacing while Muse 1.4.15 starts session MCP (~200 ms measured). */
21
+ const MCP_READY_RECHECK_MS = 25;
22
+
19
23
  type InitializeResult = Parameters<typeof readSessionDurability>[0];
20
24
  export type MuseApproval = Parameters<ApprovalHandler>[0];
21
25
  export type MuseFrame = { method: string; params?: Record<string, unknown> };
@@ -54,8 +58,10 @@ export interface MuseHostOptions {
54
58
  onEvent?: (event: MuseHostEvent) => void;
55
59
  /** Stop an opening host when its Pi binding is retired. */
56
60
  signal?: AbortSignal;
61
+ /** Set by openMuseHost for private prompts: the empty trusted workspace. */
62
+ privateWorkspace?: string;
57
63
  /**
58
- * Required to allow anything. Must validate schema/args and reserve the exact
64
+ * Required to allow anything. Must validate identity and reserve the exact
59
65
  * generation, session, turn, approvalId, toolCallId and rawArgs for the later
60
66
  * broker request. A true answer is permission to reach the proxy, NOT execute.
61
67
  * Synchronous by design: no stale requirement can wait on human interaction.
@@ -76,14 +82,23 @@ export function policyDenial(error: unknown, seen=new Set<unknown>()): boolean {
76
82
  const value = error as Record<string, unknown>;
77
83
  if ([value.status, value.httpStatus, value.statusCode, value.code].includes(403) ||
78
84
  value.kind === "client_attestation_denied" || value.code === "client_attestation_denied") return true;
79
- if (value.quota !== undefined || value.requestDenied === true) return true;
80
- // SDK errorKind is an open string, not a closed enum. Refusals always win.
85
+ // SDK errorKind is an open string. Only account/policy refusals latch;
86
+ // quota and rate limits fence the current binding without poisoning later hosts.
81
87
  if ([value.errorKind, value.kind, value.code].some(v => typeof v === "string" &&
82
- /auth|attestation|policy|quota|plan.*limit|rate.?limit|permission|forbidden/i.test(v))) return true;
88
+ /auth|attestation|policy|permission|forbidden/i.test(v))) return true;
83
89
  if (typeof value.message === "string" && /\bHTTP\s+403\b|\bclient_attestation_denied\b/.test(value.message)) return true;
84
90
  return [value.data, value.error, value.cause].some((nested) => nested !== error && policyDenial(nested, seen));
85
91
  }
86
92
 
93
+ function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
94
+ if (!error || typeof error !== "object" || seen.has(error)) return false;
95
+ seen.add(error);
96
+ const value = error as Record<string, unknown>;
97
+ if ([value.status, value.httpStatus, value.statusCode, value.code].includes(429) || value.quota !== undefined ||
98
+ [value.errorKind, value.kind, value.code].some(v => typeof v === "string" && /quota|plan.*limit|rate.?limit/i.test(v))) return true;
99
+ return [value.data, value.error, value.cause].some(nested => quotaDenial(nested, seen));
100
+ }
101
+
87
102
  const canonical = (v:any):string => v && typeof v === "object"
88
103
  ? Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
89
104
  : JSON.stringify(v);
@@ -234,8 +249,9 @@ export class MuseHost {
234
249
  approvalMode: "promptUnmatched",
235
250
  ...(this.#options.model === undefined ? {} : { modelId: this.#options.model }),
236
251
  // Without workspaceRoot, serve silently ignored run.system_prompt in
237
- // the live qualification. Explicit workspace construction is essential.
238
- ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.cwd} : {}),
252
+ // the live qualification. Explicit workspace construction is essential;
253
+ // the private trusted workspace keeps project rules out (settings.ts).
254
+ ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.privateWorkspace ?? this.#options.cwd} : {}),
239
255
  config: { mcpServers: this.#options.mcpServers ?? {} },
240
256
  }, { maxAttempts: 1 }); // no engine retry/replay
241
257
  this.#assertLive();
@@ -250,7 +266,7 @@ export class MuseHost {
250
266
  const waiting=this.#options.waitForToolReceipt?.();
251
267
  if(waiting)await waiting;
252
268
  // Refuse invalid/foreign requests immediately, without waiting for a Pi
253
- // result that must never exist. Reserve exact valid args before holding.
269
+ // result that must never exist. Reserve exact args before holding.
254
270
  const decision=this.#decide(request);
255
271
  if(decision.choiceId!=="allow_once")return decision;
256
272
  const result=this.#options.waitForPiToolResult?.(request);
@@ -269,6 +285,7 @@ export class MuseHost {
269
285
  if(!(typeof sub.subscriptionId==="number" && Number.isFinite(sub.subscriptionId)))throw new Error("Muse rawLog subscription absent");
270
286
  this.#logSubscription=sub.subscriptionId;
271
287
  }
288
+ await this.#awaitSessionMcp();
272
289
  // Entire drain is synchronous. A newly arriving event cannot overtake it.
273
290
  const held = this.#held;
274
291
  this.#held = [];
@@ -285,6 +302,47 @@ export class MuseHost {
285
302
  }
286
303
  }
287
304
 
305
+ /** Muse 1.4.15 starts session MCP servers after session/start returns, and
306
+ * a turn sent first fails "unknown tool" (measured 2026-11-10: "starting"
307
+ * with no tools, "connected" ~200 ms later). The client sends no readiness
308
+ * notification, so ask its inventory until every required server is
309
+ * connected with every Pi tool. No deadline: Pi's abort owns cancellation.
310
+ * 1.4.14 has no inventory method and was already ready at session/start. */
311
+ async #awaitSessionMcp() {
312
+ const names = Object.keys(this.#options.mcpServers ?? {});
313
+ for (;;) {
314
+ if (!names.length) return;
315
+ this.#assertLive();
316
+ this.#options.signal?.throwIfAborted();
317
+ let inventory: any;
318
+ try {
319
+ inventory = await (this.connection as any).request("mcpServer/readInventory", { sessionId: this.sessionId, includeTools: true });
320
+ } catch (error: any) {
321
+ // Only the typed old-client refusal skips readiness. experimentalRequired
322
+ // also uses -32601; a frame without data.kind is rejected by the SDK as
323
+ // ProtocolError (fail-closed), not evidence of an older client.
324
+ if (error?.kind === "methodNotFound" || error?.data?.kind === "methodNotFound") return;
325
+ throw error;
326
+ }
327
+ if (!Array.isArray(inventory?.servers)) throw new Error("Muse session MCP inventory malformed: servers must be an array");
328
+ const rows = names.map(name => ({ name, row: inventory.servers.find((s: any) => s?.name === name) }));
329
+ // Registration can be asynchronous: absent rows and starting are pending.
330
+ // 1.4.15 binary inventory labels include withheld and closed. These,
331
+ // explicit failures (failed/error/forfeited), and all unrecognized states
332
+ // fail closed, naming the state; only starting/absence are pending.
333
+ const failed = rows.find(({ row }) => row && row.state !== "starting" && row.state !== "connected");
334
+ if (failed) throw new Error(`Muse session MCP server ${failed.name} unavailable (${failed.row?.state ?? "absent"}); no model request submitted`);
335
+ if (rows.every(({ row }) => row?.state === "connected")) {
336
+ const pi = rows.find(({ name }) => name === "pi")?.row;
337
+ const missing = pi ? this.#options.tools.filter(tool => !(pi.tools as unknown[] | undefined)?.includes(tool)) : [];
338
+ if (missing.length) throw new Error(`Muse session MCP server pi connected without Pi tools ${missing.join(", ")}; no model request submitted`);
339
+ return;
340
+ }
341
+ // Recheck pacing only (not a deadline), well under the measured ~200 ms startup.
342
+ await delay(MCP_READY_RECHECK_MS, undefined, { signal: this.#options.signal });
343
+ }
344
+ }
345
+
288
346
  /** The single ingress, also used by synthetic frame fixtures. */
289
347
  receive(frame: MuseFrame): void {
290
348
  if(frame.method==="log/gap" && (frame.params as any)?.subscriptionId===this.#logSubscription){this.fence("Muse rawLog gap; complete tool batch unknown");return;}
@@ -335,6 +393,10 @@ export class MuseHost {
335
393
  this.#emit({kind:"frame",frame});
336
394
  this.#refusal(policyDenial(params.error) ? params.error : params);return;
337
395
  }
396
+ if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
397
+ this.#emit({kind:"frame",frame});
398
+ this.fence("Muse quota refused; no replay"); return;
399
+ }
338
400
  if(retry){
339
401
  if(!this.#busy || params.turnId!==this.#submission?.turnId) {
340
402
  this.fence("Muse retry has foreign or inactive turn identity");return;
@@ -451,12 +513,14 @@ export class MuseHost {
451
513
  if (this.#busy) throw new Error("Muse predecessor has no turn/completed terminal");
452
514
  await this.#options.verifyLogin?.();
453
515
  if (!this.#options.echo) {
454
- const result = await this.connection.request("usage/read", {}).catch(error=>{this.#refusal(error);throw error;});
516
+ 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;});
455
517
  const usage = result.usage as any;
456
518
  publishQuota(usage); this.ledger.quota(usage);
457
519
  // Muse reports percentages; 100% is the provider's exhausted plan boundary.
458
- if (quotaExhausted(usage))
520
+ if (quotaExhausted(usage)) {
521
+ this.fence("Muse plan usage limit reached; no turn submitted");
459
522
  throw new Error("Muse plan usage limit reached; no turn submitted");
523
+ }
460
524
  }
461
525
  const commandId = this.connection.mintCommandId();
462
526
  const submission: Submission = { commandId, turnId: undefined, terminal: false, started: false };
@@ -491,10 +555,13 @@ export class MuseHost {
491
555
  this.#assertLive();
492
556
  return { turnId: ack.turnId, commandId };
493
557
  } catch (error) {
494
- this.#retrySafe = !submission.started && submission.turnId===undefined && error instanceof MspError &&
558
+ this.#retrySafe = !policyDenial(error) && !quotaDenial(error) && !submission.started && submission.turnId===undefined && error instanceof MspError &&
495
559
  ((error.code===-32001 && error.kind==="overloaded") || (error.code===-32031 && error.kind==="backpressured"));
496
560
  this.#refusal(error);
497
- this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
561
+ if (quotaDenial(error) && !policyDenial(error)) {
562
+ this.ledger.record("quota_refusal", {phase:"turn_admission"});
563
+ this.fence("Muse quota refused; no replay");
564
+ } else this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
498
565
  throw error;
499
566
  }
500
567
  }
@@ -556,10 +623,13 @@ export async function discoverMuseCatalog() {
556
623
  await qualifyMuseVersion(launch.command,launch.env??{});
557
624
  const handshake = spawnMspConnection(launch);
558
625
  try {
559
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.0" },
626
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
560
627
  capabilities: { requestedCapabilities: ["sessionMcp"], userInputDialogs: false } });
561
628
  const catalog = await spawned.connection.request("model/list", {});
562
629
  return catalog as typeof catalog & {models:any[]};
630
+ } catch (error) {
631
+ if (policyDenial(error)) policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
632
+ throw error;
563
633
  } finally { await handshake.close(); }
564
634
  }
565
635
 
@@ -567,7 +637,9 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
567
637
  const launch = museLaunchOptions(options); // preflight BEFORE filesystem/process work
568
638
  options.signal?.throwIfAborted();
569
639
  await qualifyMuseVersion(launch.command, launch.env??{}, options.signal, options.toolBatches);
570
- const home = await mkdtemp(join(tmpdir(), "pi-muse-host-"));
640
+ // Muse canonicalizes workspaceRoot before trust lookup (e.g. macOS /var).
641
+ // One canonical root owns settings, trust, auth link and raw/coding workspace.
642
+ const home = await realpath(await mkdtemp(join(tmpdir(), "pi-muse-host-")));
571
643
  const env = options.echo ? { ...launch.env,
572
644
  HOME: home, XDG_CONFIG_HOME: join(home, "config"), XDG_DATA_HOME: join(home, "data"),
573
645
  XDG_CACHE_HOME: join(home, "cache"), XDG_STATE_HOME: join(home, "state") } : {
@@ -584,11 +656,12 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
584
656
  try {
585
657
  if (options.privatePrompt) {
586
658
  await writePromptSettings(home, options.privatePrompt.systemPrompt, options.tools, options.privatePrompt.skillsOff);
659
+ options = {...options, privateWorkspace: privateWorkspace(home)};
587
660
  if(!options.echo){
588
661
  const verify=await linkHostLogin(home,launch.env?.XDG_CONFIG_HOME??join(homedir(),".config"));
589
662
  verifyLogin=async()=>{
590
663
  const metadata=await verify();
591
- if(metadata.realFileChanged)host?.ledger.record("auth_metadata_refresh",{metadata});
664
+ if(metadata.realMetadataChanged)host?.ledger.record("auth_metadata_change",{metadata});
592
665
  options.onEvent?.({kind:"auth-metadata",metadata});
593
666
  return metadata;
594
667
  };
@@ -615,8 +688,8 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
615
688
  return {};
616
689
  });
617
690
  try {
618
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.0" },
619
- capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches)?{experimentalApi:true}:{}) } });
691
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
692
+ capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches||Object.keys(options.mcpServers??{}).length)?{experimentalApi:true}:{}) } });
620
693
  if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported; no model request submitted");
621
694
  if (!options.echo) {
622
695
  const catalog = await spawned.connection.request("model/list", {});
@@ -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
  }