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/provider.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import {
2
2
  createAssistantMessageEventStream,
3
- validateToolArguments,
4
3
  isContextOverflow,
5
4
  } from "@earendil-works/pi-ai";
6
5
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
@@ -29,6 +28,45 @@ import type { MuseHostOptions } from "./host.js";
29
28
  import { isQualifiedMuseModel, museResponseIdentity, museModelRoute } from "./model-route.js";
30
29
  export { isQualifiedMuseModel } from "./model-route.js";
31
30
 
31
+ /** Per logical Pi request: native ingress waits for acknowledged admission and
32
+ * async observers before Pi normalization. Status 0 means non-HTTP, never 200.
33
+ * Muse owns/folds its SDK state first; callbacks observe, not replace, events. */
34
+ function requestHooks(model:any,options:any,onError:(error:Error)=>void) {
35
+ if(!options.onResponse && !options.onProviderStreamEvent)return {
36
+ enqueue:(work:()=>void)=>work(),observe:(_event:any,consume:()=>void)=>consume(),admit:async(_acceptance:string)=>{},
37
+ };
38
+ let admitted=false,failed=false;
39
+ let tail=Promise.resolve();
40
+ const waiting:Array<()=>Promise<void>|void>=[];
41
+ const enqueue=(work:()=>Promise<void>|void)=>{
42
+ if(failed)return;
43
+ if(!admitted){waiting.push(work);return;}
44
+ tail=tail.then(async()=>{if(!failed)await work();}).catch(error=>{
45
+ failed=true;onError(error instanceof Error?error:new Error(String(error)));
46
+ });
47
+ };
48
+ return {
49
+ enqueue,
50
+ observe(event:any,consume:()=>void) {
51
+ // Failure control is immediate even when admission never succeeds. It
52
+ // cannot wait behind a response observer or be mistaken for a response.
53
+ if(event.kind==="fenced"){failed=true;waiting.length=0;consume();return;}
54
+ enqueue(async()=>{
55
+ await options.onProviderStreamEvent?.({transport:"official-muse-client",source:"muse-host",event:structuredClone(event)},model);
56
+ options.signal?.throwIfAborted();
57
+ consume();
58
+ });
59
+ },
60
+ async admit(acceptance:string) {
61
+ if(admitted || failed)return;
62
+ await options.onResponse?.({status:0,headers:{"x-pi-tether-transport":"official-muse-client","x-pi-tether-response":"logical-admission","x-pi-tether-acceptance":acceptance}},model);
63
+ options.signal?.throwIfAborted();
64
+ admitted=true;
65
+ for(const work of waiting.splice(0))enqueue(work);
66
+ },
67
+ };
68
+ }
69
+
32
70
  /** Isolated instance for qualification fixtures; production uses the qualified default below. */
33
71
  export function createMuseProvider(config: {
34
72
  openHost?: (options: MuseHostOptions) => Promise<MuseHost>;
@@ -74,6 +112,7 @@ type Episode = {
74
112
  textIndex?: number;
75
113
  detachAbort?: () => void;
76
114
  thinking?: Map<string,number>;
115
+ hooks: ReturnType<typeof requestHooks>;
77
116
  };
78
117
  type Binding = {
79
118
  key: string;
@@ -98,9 +137,8 @@ type Binding = {
98
137
  abort: AbortController;
99
138
  pending: Map<string, { invocation: BridgeInvocation; callId: string; result?: BridgeResult; verified: boolean }>;
100
139
  batch?: string[];
101
- batchSpec?: Array<{callId:string;name:string;args:Record<string,unknown>;piCallId:string;nativeOnly?:boolean;verified?:boolean;nativeStart?:{itemId:string;turnId:string;recordedAt:string};journal?:{entryId:string;response:BridgeResult}}>;
140
+ batchSpec?: Array<{callId:string;name:string;args:Record<string,unknown>;piCallId:string;verified?:boolean;nativeStart?:{itemId:string;turnId:string;recordedAt:string};journal?:{entryId:string;response:BridgeResult}}>;
102
141
  tools: Array<{name:string;description:string;inputSchema:any}>;
103
- schemaRefusals: Map<string,{name:string;args:Record<string,unknown>;approvalId:string;sessionId:string;turnId:string;settled:boolean}>;
104
142
  approvalHolds: Map<string,{approvalId:string;requirement:string;ready:boolean;promise:Promise<void>;resolve:()=>void;reject:(error:Error)=>void}>;
105
143
  steeringPending?: boolean;
106
144
  deferredTerminal?: any;
@@ -223,14 +261,6 @@ function fail(b: Binding, reason: string) {
223
261
  }
224
262
  void closeBinding(b);
225
263
  }
226
- function validArguments(tool: Binding["tools"][number] | undefined, callId:string, args:Record<string,unknown>): boolean {
227
- if (!tool) return false;
228
- try {
229
- const checked=validateToolArguments({name:tool.name,description:tool.description ?? "",parameters:tool.inputSchema} as any,
230
- {type:"toolCall",id:callId,name:tool.name,arguments:args as any});
231
- return canonical(args)===canonical(checked);
232
- } catch { return false; }
233
- }
234
264
  function settleBatch(b:Binding) {
235
265
  if (b.batchSpec?.every(c=>c.verified)) {
236
266
  b.batch=undefined; b.batchSpec=undefined; b.batchSurfaced=false;
@@ -282,7 +312,7 @@ function emitFrame(b: Binding, event: any) {
282
312
  // Never defer that divergence until Pi returns, or accept the next batch.
283
313
  if(event.kind==="frame") {
284
314
  const {method,params:p={}}=event.frame,item=p.item;
285
- const spec=item?.kind==="toolCall" ? b.batchSpec?.find(c=>c.callId===item.callId && !c.nativeOnly && !c.verified) : undefined;
315
+ const spec=item?.kind==="toolCall" ? b.batchSpec?.find(c=>c.callId===item.callId && !c.verified) : undefined;
286
316
  if(spec && (method==="item/started" || method==="item/completed" && item.status==="timedOut")) {
287
317
  try {
288
318
  if(item.tool!==spec.name || item.args!==undefined && canonical(JSON.parse(item.args))!==canonical(spec.args) ||
@@ -348,15 +378,9 @@ function emitFrame(b: Binding, event: any) {
348
378
  }
349
379
  // A committed spec is sufficient to schedule Pi; MCP invocations may be
350
380
  // sequential and need the first journaled result before the next exists.
351
- if(event.calls.some((call:any)=>{
352
- const refusal=b.schemaRefusals.get(call.callId);
353
- return refusal && (refusal.name!==call.name || canonical(refusal.args)!==canonical(call.args));
354
- })) {fail(b,"Muse schema refusal differs from committed tool batch");return;}
355
- b.batchSpec=event.calls.map((call:any)=>{
356
- const nativeOnly=!validArguments(b.tools.find(t=>call.name===`mcp__pi__${t.name}`),call.callId,call.args);
357
- const refusal=b.schemaRefusals.get(call.callId);
358
- return {...call,piCallId:b.pending.get(call.callId)?.invocation.piCallId ?? randomUUID(),nativeOnly,verified:nativeOnly && refusal?.settled===true};
359
- });
381
+ // Pi owns validation and coercion, including its normal error tool result.
382
+ // Keep original model arguments immutable for native/MCP identity checks.
383
+ b.batchSpec=event.calls.map((call:any)=>({...call,piCallId:b.pending.get(call.callId)?.invocation.piCallId ?? randomUUID()}));
360
384
  b.batch = event.calls.map((x:any)=>x.callId);
361
385
  for (const call of event.calls) {
362
386
  const pending=b.pending.get(call.callId);
@@ -403,32 +427,6 @@ function emitFrame(b: Binding, event: any) {
403
427
  try { applyMuseUsage(e.output,p); } catch(error:any) { fail(b,error.message); return; }
404
428
  }
405
429
  const item = p.item;
406
- const refusal=item?.kind==="toolCall" ? b.schemaRefusals.get(item.callId) : undefined;
407
- if(frame.method==="item/completed" && refusal) {
408
- // This tool never crossed MCP: the public SDK approval handler refused its
409
- // schema. Only the matching native rejection, not a synthetic Pi result,
410
- // can settle it. Retain this receipt for receipt-before-commit delivery.
411
- try {
412
- if(item.itemId!==refusal.approvalId || item.tool!==refusal.name ||
413
- p.sessionId!==refusal.sessionId || item.turnId!==refusal.turnId ||
414
- canonical(JSON.parse(item.args))!==canonical(refusal.args) ||
415
- item.status!=="rejected" || item.failureKind!=="approval_denied" ||
416
- item.failureReason!=="approval aborted" || b.pending.has(item.callId))
417
- throw new Error("identity or rejection differs from schema refusal");
418
- if(!refusal.settled) b.host?.ledger?.record("tool_schema_refusal_settled",{
419
- callId:item.callId,approvalId:refusal.approvalId,itemId:item.itemId,
420
- status:item.status,failureKind:item.failureKind,failureReason:item.failureReason,
421
- sourceRange:p.sourceRange,owner:"native-approval",piExecuted:false,
422
- });
423
- refusal.settled=true;
424
- const spec=b.batchSpec?.find(c=>c.callId===item.callId);
425
- if(spec) {
426
- if(!spec.nativeOnly)throw new Error("schema refusal targets executable Pi spec");
427
- spec.verified=true;settleBatch(b);
428
- }
429
- } catch(error:any) { fail(b,`Muse native schema refusal receipt: ${error.message}`); }
430
- return;
431
- }
432
430
  if (
433
431
  frame.method === "item/completed" &&
434
432
  item?.kind === "toolCall" &&
@@ -443,21 +441,32 @@ function emitFrame(b: Binding, event: any) {
443
441
  throw new Error("Muse tool result receipt invocation differs from pending MCP call");
444
442
  let redactions: import("./tool-result-receipt.js").VendorRedaction[] = [];
445
443
  let images: import("./tool-result-receipt.js").UnverifiableImage[] = [];
446
- const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; });
444
+ let truncatedView: import("./tool-result-receipt.js").TruncatedView | undefined;
445
+ const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; }, view => { truncatedView = view; });
447
446
  if (!b.bridge.verifyContent(pending.invocation, receipt))
448
447
  throw new Error("Muse tool result mismatch");
448
+ if (truncatedView) b.host?.ledger?.record("tool_result_truncated_view", {
449
+ callId:item.callId, piToolCallId:b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId:item.itemId,
450
+ source:{tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId},
451
+ outputRefAvailability:item.outputRef?.availability ?? "absent", view:truncatedView,
452
+ evidence:"declared-lossy-view", exactModelConsumption:false,
453
+ });
449
454
  if (redactions.length) {
450
455
  b.host?.ledger?.record("tool_result_vendor_redaction", {
451
- callId: item.callId, itemId: item.itemId, count: redactions.length,
452
- rule: "unique-nonempty-intraline-context-v2", spans: redactions,
453
- textProjection: r.content.length > 1 ? "lf-joined-text-parts" : "single-text",
456
+ callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
457
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
458
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})}, count: redactions.length,
459
+ rule: "positional-declared-loss-v4", spans: redactions, evidence:"declared-lossy",
460
+ textProjection: r.isError ? "lf-joined-all-text-parts" : images.length ? "native-ordered-parts-with-image-metadata" : "native-text-chunk-fold",
454
461
  exactModelConsumption: false,
455
462
  });
456
463
  publishRedactionStatus(b, redactions.length);
457
464
  }
458
465
  if (images.length) b.host?.ledger?.record("tool_result_image_unverifiable", {
459
466
  callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
460
- images, delivered: true, unverifiableInContent: true,
467
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
468
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})},
469
+ images:images.map(image=>({...image,modelVisibility:image.modelVisibility??"unproven"})), deliveredToMcp: true, evidence:"declared-lossy", unverifiableInContent: true,
461
470
  rule: "mcp-image-placeholder-v1", exactModelConsumption: false,
462
471
  });
463
472
  pending.verified = true;
@@ -466,17 +475,17 @@ function emitFrame(b: Binding, event: any) {
466
475
  if(spec)spec.verified=true;
467
476
  settleBatch(b);
468
477
  };
469
- if (item.outputRef) {
478
+ if (item.outputRef && !(item.truncated === true && ["missing","unsupported","accessFailed"].includes(item.outputRef.availability))) {
470
479
  b.verifyingReceipt = readStoredToolOutput(item, offset => {
471
480
  if (!b.host?.readToolOutput) throw new Error("Muse host cannot read item/outputRef");
472
481
  return b.host.readToolOutput(item, offset);
473
- }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt: ${error.message}`); }).finally(() => {
482
+ }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }).finally(() => {
474
483
  b.verifyingReceipt=undefined;
475
484
  const events=b.buffered.splice(0);
476
485
  for(const next of events)emitFrame(b,next);
477
486
  });
478
487
  } else {
479
- try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt: ${error.message}`); }
488
+ try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }
480
489
  }
481
490
  }
482
491
  }
@@ -495,7 +504,9 @@ function attach(b: Binding, e: Episode, signal?: AbortSignal) {
495
504
  }
496
505
  }
497
506
  const events = b.buffered.splice(0);
498
- for (const event of events) emitFrame(b, event);
507
+ // These frames were already observed while detached. Preserve that single
508
+ // observation, but gate their normalization behind this request's response.
509
+ for (const event of events) e.hooks.enqueue(() => emitFrame(b, event));
499
510
  }
500
511
  function surface(b: Binding, inv: BridgeInvocation) {
501
512
  const callId = (inv.metadata as any)?.callId;
@@ -539,8 +550,7 @@ function flushTools(b: Binding) {
539
550
  const e=b.episode;
540
551
  if (!b.batch || b.batchSurfaced || !b.batchSpec) return;
541
552
  if (!e || e.ended) {fail(b,"Pi episode detached during committed MCP batch");return;}
542
- const executable=b.batchSpec.filter(c=>!c.nativeOnly);
543
- if(!executable.length)return; // Keep streaming until the native rejection receipt.
553
+ const executable=b.batchSpec;
544
554
  b.batchSurfaced=true;
545
555
  if (e.textIndex !== undefined)
546
556
  e.stream.push({
@@ -578,16 +588,35 @@ function flushTools(b: Binding) {
578
588
  e.stream.end();
579
589
  }
580
590
  /** Live inference is explicit opt-in; echo always launches the offline provider. */
581
- function streamViaMuse(model: any, input: any, options: any = {}) {
591
+ function streamEffective(model: any, input: any, options: any = {}) {
582
592
  if(config.modelAllowed && !config.modelAllowed(model)){
583
- 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";
593
+ 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";
584
594
  refused.push({type:"error",reason:"error",error:output});refused.end();return refused;
585
595
  }
586
596
  const context = piContext(input);
587
597
  const requestedMode = selectMode(model);
588
598
  if (!context.tools.length) {
589
599
  if (rawCompletionQualified(model))
590
- return streamRawCompletion(model, context, options, message, openHost, "replace");
600
+ return streamRawCompletion(model, context, options, message, async hostOptions => {
601
+ const hooks=requestHooks(model,options,error=>hostOptions.onEvent?.({kind:"fenced",reason:error.message}));
602
+ const host=await openHost({...hostOptions,onEvent:event=>hooks.observe(event,()=>hostOptions.onEvent?.(event))});
603
+ return new Proxy(host,{get(target,key){
604
+ if(key==="submitInput")return async (...args:any[])=>{
605
+ try {
606
+ const ack=await (target.submitInput as any)(...args);
607
+ await hooks.admit("turn/start");
608
+ return ack;
609
+ } catch(error) {
610
+ // Admission can fence before the raw stream begins awaiting its
611
+ // terminal promise. Preserve the host's neutral no-replay reason.
612
+ if(target.fencedReason)throw new Error(target.fencedReason);
613
+ throw error;
614
+ }
615
+ };
616
+ const value=Reflect.get(target,key,target);
617
+ return typeof value==="function"?value.bind(target):value;
618
+ }});
619
+ }, "replace");
591
620
  // Refuse before looking up or attaching the coding binding. A failed summary
592
621
  // must not retire or settle an unrelated parked coding request.
593
622
  const refused=createAssistantMessageEventStream();const output=message(model);
@@ -596,7 +625,11 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
596
625
  }
597
626
  const stream = createAssistantMessageEventStream();
598
627
  const output = message(model);
599
- const episode: Episode = { stream, output, ended: false };
628
+ const episode: Episode = { stream, output, ended: false, hooks: requestHooks(model,options,error=>{
629
+ if(binding)fail(binding,error.message);
630
+ else {output.stopReason="error";output.errorMessage=error.message;stream.push({type:"error",reason:"error",error:output});stream.end();}
631
+ }) };
632
+ let binding: Binding | undefined;
600
633
  void (async () => {
601
634
  let b: Binding | undefined;
602
635
  try {
@@ -653,25 +686,24 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
653
686
  b = undefined;
654
687
  }
655
688
  if (b) {
689
+ binding = b;
656
690
  b.episode = episode;
657
691
  if (!b.batch) {
658
692
  const delta = context.messages.slice(b.messages.length);
659
693
  if (!delta.length || !delta.every((m:any)=>m.role === "user"))
660
694
  throw new Error("Muse completed-turn continuation requires an exact append of user messages");
661
695
  const text = museCurrentInput(delta);
662
- stream.push({ type: "start", partial: output });
696
+ episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
663
697
  attach(b, episode, options.signal);
664
698
  if (b.closed) return;
665
699
  b.messages = structuredClone(context.messages);
666
700
  b.requestHash=lastUserHash(context.messages);
667
701
  b.messageHash = historyHash(b.messages);
668
- // Like the host's committed identities, refusals are native-turn scoped.
669
- // Call IDs may be reused in a later user turn, never within a repair.
670
- b.schemaRefusals.clear();
671
702
  await b.host!.submitInput(text, museEffort(options.reasoning));
703
+ await episode.hooks.admit("turn/start");
672
704
  return;
673
705
  }
674
- const pendingBatch=b.batchSpec!.filter(c=>!c.nativeOnly);
706
+ const pendingBatch=b.batchSpec!;
675
707
  if (pendingBatch.some(p=>p.journal)) throw new Error("Muse pending result already supplied");
676
708
  const delta = context.messages.slice(b.messages.length),
677
709
  assistant = delta[0],
@@ -720,12 +752,15 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
720
752
  assertToolResultVerifiable(response);
721
753
  return {pending,entry,response};
722
754
  });
723
- stream.push({ type: "start", partial: output });
755
+ episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
724
756
  attach(b, episode, options.signal);
725
757
  if (b.closed) return;
726
758
  b.messages = structuredClone(context.messages);
727
759
  b.requestHash=lastUserHash(context.messages);
728
760
  b.messageHash = historyHash(context.messages);
761
+ // The native suspended MCP request already exists. A response hook may
762
+ // refuse its continuation before any journaled result is delivered.
763
+ await episode.hooks.admit("suspended-mcp-continuation");
729
764
  b.steeringPending=steering.length>0;
730
765
  const consumed=steering.length?new Promise<void>(resolve=>{b!.receiptsDone=resolve;}):undefined;
731
766
  for(const {pending,entry,response} of journaled){
@@ -762,8 +797,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
762
797
  const bridge = createMcpBridge({
763
798
  sessionId: key,
764
799
  generation: randomUUID(),
800
+ argumentValidation: "pi",
765
801
  tools,
766
- onInvocation: (inv) => surface(candidate, inv),
802
+ onInvocation: (inv) => candidate.episode!.hooks.enqueue(()=>surface(candidate, inv)),
767
803
  });
768
804
  candidate = {
769
805
  key,
@@ -776,7 +812,6 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
776
812
  park: parking && Boolean(sessionManager?.getSessionFile?.()),
777
813
  reservations,
778
814
  tools,
779
- schemaRefusals:new Map(),
780
815
  approvalHolds:new Map(),
781
816
  buffered: [],
782
817
  closed: false,
@@ -786,8 +821,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
786
821
  abort: new AbortController(),
787
822
  };
788
823
  b = candidate;
824
+ binding = b;
789
825
  bindings.set(key, b);
790
- stream.push({ type: "start", partial: output });
826
+ episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
791
827
  attach(b, episode, options.signal);
792
828
  if (b.closed) return;
793
829
  const descriptor = await bridge.start();
@@ -840,15 +876,6 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
840
876
  if (!tool || !request.toolCallId) return false;
841
877
  try {
842
878
  const args = JSON.parse(request.rawArgs);
843
- if (!validArguments(tool,request.toolCallId,args)) {
844
- const previous=candidate.schemaRefusals.get(request.toolCallId);
845
- if(previous && (previous.name!==request.toolName || canonical(previous.args)!==canonical(args) || previous.approvalId!==request.approvalId || previous.sessionId!==request.sessionId || previous.turnId!==request.turnId))return false;
846
- if(!previous) {
847
- candidate.schemaRefusals.set(request.toolCallId,{name:request.toolName,args,approvalId:request.approvalId,sessionId:request.sessionId,turnId:request.turnId,settled:false});
848
- candidate.host?.ledger?.record("tool_schema_refusal",{callId:request.toolCallId,approvalId:request.approvalId,tool:request.toolName,reason:"Pi tool argument schema or coercion rejected",owner:"tether-approval",piExecuted:false});
849
- }
850
- return false;
851
- }
852
879
  const spec=candidate.batchSpec?.find(c=>c.callId===request.toolCallId);
853
880
  if(candidate.closed || (candidate.batchSpec && (!spec || spec.verified || spec.name!==request.toolName || canonical(spec.args)!==canonical(args))))return false;
854
881
  const previous = reservations.get(request.toolCallId);
@@ -869,7 +896,7 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
869
896
  return false;
870
897
  }
871
898
  },
872
- onEvent: (event: any) => emitFrame(candidate, event),
899
+ onEvent: (event: any) => candidate.episode!.hooks.observe(event,()=>emitFrame(candidate, event)),
873
900
  }));
874
901
  b.host = host;
875
902
  host.ledger?.beginEpisode();
@@ -878,8 +905,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
878
905
  return;
879
906
  }
880
907
  await host.submitInput(text, museEffort(options.reasoning));
908
+ await episode.hooks.admit("turn/start");
881
909
  } catch (error: any) {
882
- const reason = String(error?.message || error);
910
+ const reason = b?.host?.fencedReason ?? String(error?.message || error);
883
911
  if (b) { b.episode = episode; fail(b, reason); }
884
912
  else {
885
913
  episode.ended = true;
@@ -896,6 +924,28 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
896
924
  })();
897
925
  return stream;
898
926
  }
927
+ function streamViaMuse(model:any,input:any,options:any={}) {
928
+ const stream=createAssistantMessageEventStream();
929
+ void (async()=>{
930
+ try {
931
+ // Expose the logical official-client request, not an invented HTTP body.
932
+ const payload={...structuredClone(piContext(input)),transport:"official-muse-client"};
933
+ const replacement=await options.onPayload?.(payload,model);
934
+ const effective=replacement===undefined?payload:replacement;
935
+ if(!effective || typeof effective!=="object" || !Array.isArray(effective.messages) || !Array.isArray(effective.tools) || typeof effective.systemPrompt!=="string")
936
+ throw new Error("Muse onPayload must return a logical request with systemPrompt, messages and tools");
937
+ if(effective.messages.some((entry:any)=>entry?.role==="system"))
938
+ throw new Error("Muse logical payload messages exclude system messages; edit logical systemPrompt and tools instead");
939
+ 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.`}))};
940
+ for await(const event of streamEffective(model,request,options))stream.push(event);
941
+ stream.end();
942
+ } catch(error:any) {
943
+ const output=message(model);output.stopReason=options.signal?.aborted?"aborted":"error";output.errorMessage=String(error?.message??error);
944
+ stream.push({type:"error",reason:output.stopReason,error:output});stream.end();
945
+ }
946
+ })();
947
+ return stream;
948
+ }
899
949
  return {streamViaMuse,setSessionManager,retireAll,rawCompletionQualified,committedCompaction};
900
950
  }
901
951
  // Qualified against official Muse 1.4.14: private settings + explicit
@@ -1,14 +1,17 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import { isAbsolute, join } from "node:path";
4
4
  import { metadataLedger } from "pi-tether-core/metadata-ledger";
5
5
  import { nativeCounters } from "./usage.js";
6
6
  import { quotaPayload } from "./rate-limit.js";
7
7
  const num = (v: any) =>
8
8
  typeof v === "number" && Number.isFinite(v) ? v : null;
9
9
  export function museLedgerPath() {
10
+ const state = process.env.XDG_STATE_HOME;
11
+ // XDG Base Directory requires absolute values; empty/relative values are
12
+ // treated as unset, never a request to write metadata beneath the cwd.
10
13
  return join(
11
- process.env.XDG_STATE_HOME ?? join(homedir(), ".local/state"),
14
+ state && isAbsolute(state) ? state : join(homedir(), ".local/state"),
12
15
  "pi-muse-tether",
13
16
  "requests.jsonl",
14
17
  );
package/src/settings.ts CHANGED
@@ -15,20 +15,22 @@ export async function linkHostLogin(hostRoot:string, realConfigHome:string) {
15
15
  assertLoginSafe();
16
16
  const real=join(realConfigHome,"muse/auth.json"), link=join(hostRoot,"config/muse/auth.json");
17
17
  let before=await stat(real);await symlink(real,link);
18
- const ownedLink=await lstat(link);
19
18
  return async()=>{
20
- let intact=false;
19
+ let intact=false, missing=false;
21
20
  try {
22
21
  const privateState=await lstat(link);
23
- intact=privateState.isSymbolicLink() && privateState.ino===ownedLink.ino &&
24
- privateState.dev===ownedLink.dev && await readlink(link)===real;
25
- } catch { /* A missing/replaced private link is never repaired automatically. */ }
26
- if(!intact){loginFault="Muse login metadata symlink replaced; STOP, retain private config and request account-owner review";throw new Error(loginFault);}
22
+ // Boat lazyfs hydration changes st_dev/st_ino without changing this link.
23
+ // Ownership here is the login destination, not filesystem identity: a new
24
+ // symlink to the same target still gives the client the same login file.
25
+ intact=privateState.isSymbolicLink() && await readlink(link)===real;
26
+ } catch (error) { missing=(error as NodeJS.ErrnoException).code==="ENOENT"; }
27
+ if(!intact){loginFault=`Muse login metadata symlink ${missing?"missing":"replaced"}; STOP, retain private config and request account-owner review`;throw new Error(loginFault);}
27
28
  const after=await stat(real);
28
29
  const metadata={before:{inode:String(before.ino),size:before.size,mtimeMs:before.mtimeMs},after:{inode:String(after.ino),size:after.size,mtimeMs:after.mtimeMs},
29
- realFileChanged:before.ino!==after.ino || before.size!==after.size || before.mtimeMs!==after.mtimeMs,symlinkIntact:intact};
30
+ realMetadataChanged:before.ino!==after.ino || before.size!==after.size || before.mtimeMs!==after.mtimeMs,symlinkIntact:intact};
30
31
  // Account-owner observed a normal official-client refresh on main, 2026-11-02:
31
32
  // real-file replacement is metadata evidence, NOT a credential incident.
33
+ // Hydration can also change inode/timestamp precision: no refresh/content claim.
32
34
  before=after;
33
35
  return metadata;
34
36
  };
@@ -66,10 +68,19 @@ export function promptSettings(systemPrompt: string, tools: readonly string[], s
66
68
  context: {foreign_personal_rules:false,foreign_personal_skills:false},
67
69
  };
68
70
  }
71
+ /** The empty, tether-owned workspace a private-prompt session names. Muse
72
+ * honours run.system_prompt only with an explicit workspaceRoot, and Muse
73
+ * 1.4.15 starts session MCP only in a trusted workspace ("withheld"
74
+ * otherwise). Trusting the user's project would also load its rules files
75
+ * (AGENTS.md) into the model (measured 2026-11-10), so only this empty private
76
+ * directory is trusted. Pi still owns cwd and every tool path. */
77
+ export const privateWorkspace = (hostRoot: string) => join(hostRoot, "workspace");
69
78
  /** Caller owns a unique host root; no shared mutable settings/schema or auth links. */
70
79
  export async function writePromptSettings(hostRoot: string, systemPrompt: string, tools: readonly string[], skillsOff?: SkillsOff) {
71
80
  const xdg = join(hostRoot,"config");
72
81
  await mkdir(join(xdg,"muse"),{recursive:true,mode:0o700});
82
+ await mkdir(privateWorkspace(hostRoot),{recursive:true,mode:0o700});
73
83
  await writeFile(join(xdg,"muse","settings.json"), JSON.stringify(promptSettings(systemPrompt,tools,skillsOff)),{mode:0o600,flag:"wx"});
84
+ await writeFile(join(xdg,"muse","trust.json"), JSON.stringify({schema_version:1,projects:{[privateWorkspace(hostRoot)]:{decision:"trusted"}}}),{mode:0o600,flag:"wx"});
74
85
  return xdg;
75
86
  }