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.
- package/CHANGELOG.md +9 -0
- package/README.md +3 -3
- package/assets/batch-boundary-schemas.json +202 -0
- package/assets/qualification-seeds.json +24 -0
- package/docs/CLIENT-LIFECYCLE.md +107 -0
- package/docs/CLIENT-QUALIFICATION.md +97 -0
- package/docs/DETAILS.md +3 -3
- package/index.ts +12 -1
- package/package.json +5 -3
- package/src/batch-schema.ts +33 -0
- package/src/catalog.ts +1 -1
- package/src/cli-version.ts +12 -14
- package/src/doctor.ts +17 -6
- package/src/features.ts +25 -0
- package/src/host.ts +88 -21
- package/src/provider.ts +37 -3
- package/src/qualification-records.ts +99 -0
- package/src/qualification.ts +205 -0
- package/src/request-ledger.ts +17 -2
- package/src/settings.ts +4 -4
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { binaryHash, checkedBuild, qualificationHome, selectedClient, readQualification, writeQualification, QUALIFICATION_CHECKS, type QualificationRecord } from "./qualification-records.js";
|
|
10
|
+
|
|
11
|
+
export type QualificationCheck = { status: "passed" | "failed" | "not-run" | "unsupported"; detail: string };
|
|
12
|
+
export type LiveResults = Record<"batchBoundary" | "privatePrompt" | "sessionMcp" | "resume" | "image", QualificationCheck>;
|
|
13
|
+
const liveNames = QUALIFICATION_CHECKS;
|
|
14
|
+
const notRun = (): LiveResults => Object.fromEntries(liveNames.map(name => [name, {status:"not-run", detail:"Explicit --live and UI confirmation required; no model request submitted."}])) as LiveResults;
|
|
15
|
+
const references = JSON.parse(readFileSync(new URL("../assets/batch-boundary-schemas.json", import.meta.url), "utf8"));
|
|
16
|
+
|
|
17
|
+
// Descriptions/titles are documentation, not protocol. Compare the entire
|
|
18
|
+
// reachable schema closure otherwise; additive/changed schemas require review,
|
|
19
|
+
// not a fabricated compatibility pass based on their build string.
|
|
20
|
+
function contract(schema: any, defs: any, seen = new Set<string>()): any {
|
|
21
|
+
if (Array.isArray(schema)) return schema.map(value => contract(value, defs, seen));
|
|
22
|
+
if (!schema || typeof schema !== "object") return schema;
|
|
23
|
+
if (schema.$ref) {
|
|
24
|
+
const name = schema.$ref.split("/").at(-1);
|
|
25
|
+
if (!schema.$ref.startsWith("#/$defs/") || !defs[name]) throw new Error(`Unresolved schema reference ${schema.$ref}`);
|
|
26
|
+
if (seen.has(name)) throw new Error(`Recursive schema reference ${name} requires review`);
|
|
27
|
+
return contract(defs[name], defs, new Set([...seen, name]));
|
|
28
|
+
}
|
|
29
|
+
return Object.fromEntries(Object.keys(schema).sort().filter(key => !["description", "title", "$comment"].includes(key)).map(key => [key, contract(schema[key], defs, seen)]));
|
|
30
|
+
}
|
|
31
|
+
/** Structural comparison with the retained v1414/v1415 envelope fixtures.
|
|
32
|
+
* This cannot establish the free-form committed event payload; live observation
|
|
33
|
+
* and the runtime committedCalls validator own that separate obligation. */
|
|
34
|
+
export function schemaCompatibility(candidate: any): {compatible:boolean; references:string[]} {
|
|
35
|
+
const defs = candidate?.$defs;
|
|
36
|
+
if (!defs) return {compatible:false,references:[]};
|
|
37
|
+
const matched: string[] = [];
|
|
38
|
+
for (const [index, reference] of references.schemas.entries()) {
|
|
39
|
+
try {
|
|
40
|
+
if (["LogRecordParams", "RawLogRecordEnvelope"].every(name => defs[name] && JSON.stringify(contract(defs[name], defs)) === JSON.stringify(contract(reference.$defs[name], reference.$defs))))
|
|
41
|
+
matched.push(references.sources[index].build);
|
|
42
|
+
} catch { /* An unknown schema construct/reference is not a pass. */ }
|
|
43
|
+
}
|
|
44
|
+
return {compatible:matched.length > 0, references:matched};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Read-only candidate qualification; never installs, promotes or switches the
|
|
48
|
+
* user's launcher. A caller must obtain UI confirmation before passing live=true.
|
|
49
|
+
* The environment gate is independent, so an accidental true cannot spend. */
|
|
50
|
+
export async function qualifyClient(build?: string, live = false, modelId?:string): Promise<QualificationRecord> {
|
|
51
|
+
if (build) checkedBuild(build);
|
|
52
|
+
if (live && process.env.PI_MUSE_TETHER_LIVE !== "1") throw new Error("Live qualification requires PI_MUSE_TETHER_LIVE=1 plus explicit --live/UI confirmation");
|
|
53
|
+
if (live && !modelId && !process.env.PI_MUSE_TETHER_QUALIFICATION_MODEL) throw new Error("Select a Muse model in Pi or set PI_MUSE_TETHER_QUALIFICATION_MODEL before explicit live qualification");
|
|
54
|
+
const selected = selectedClient();
|
|
55
|
+
if (build && build !== selected.build) throw new Error(`Selected official client is ${selected.build}, not ${build}; the official launcher cannot target historical builds. No install or model request made.`);
|
|
56
|
+
const scratch = mkdtempSync(join(tmpdir(), "muse-qualification-offline-"));
|
|
57
|
+
let record: QualificationRecord = {build:selected.build,sha256:selected.sha256,schemaHash:"",results:{offline:false,live:notRun()},qualified:false};
|
|
58
|
+
try {
|
|
59
|
+
const {META_API_KEY:_,...safeEnv}=process.env;
|
|
60
|
+
const env = {...safeEnv, NODE_OPTIONS:undefined, MUSE_NO_AUTO_UPDATE:"1", HOME:scratch, XDG_CONFIG_HOME:join(scratch,"config"), XDG_DATA_HOME:join(scratch,"data"), XDG_STATE_HOME:join(scratch,"state"), XDG_CACHE_HOME:join(scratch,"cache")};
|
|
61
|
+
const run = (args:string[]) => execFileSync(selected.binary, args, {env,cwd:scratch,encoding:"utf8",maxBuffer:Infinity});
|
|
62
|
+
const help = run(["schema", "--help"]);
|
|
63
|
+
if (!help.includes("generate-json-schema")) throw new Error("Official schema --help does not advertise generate-json-schema");
|
|
64
|
+
run(["schema", "generate-json-schema", "--help"]);
|
|
65
|
+
const output = join(scratch,"schema"); mkdirSync(output);
|
|
66
|
+
run(["schema", "generate-json-schema", "--experimental", "--out", output]);
|
|
67
|
+
const bytes = readFileSync(join(output,"msp.schema.json"));
|
|
68
|
+
record.schemaHash = createHash("sha256").update(bytes).digest("hex");
|
|
69
|
+
const compatibility = schemaCompatibility(JSON.parse(bytes.toString("utf8")));
|
|
70
|
+
record.results = {...record.results, offline:compatibility.compatible, schemaCompatibility:compatibility, cliHelp:{status:"passed",detail:"Inspected official schema --help and generate-json-schema --help with auto-update disabled."}};
|
|
71
|
+
if (!compatibility.compatible) record.results.error = "Schema differs from retained v1414/v1415 contracts; review required. No live suite submitted.";
|
|
72
|
+
if (live && compatibility.compatible) {
|
|
73
|
+
const run=await runIsolatedLive(selected.binary,modelId);
|
|
74
|
+
record.results.live=run.checks;record.results.liveEvidence={...run.evidence,at:new Date().toISOString()};
|
|
75
|
+
} else if (compatibility.compatible) {
|
|
76
|
+
const previous=readQualification(selected.build);
|
|
77
|
+
if(previous?.sha256 === record.sha256 && previous.schemaHash === record.schemaHash && previous.results.live) {
|
|
78
|
+
record.results.live=previous.results.live;
|
|
79
|
+
record.results.liveEvidence=previous.results.liveEvidence ?? {source:"previous hash-matching qualification record; not rerun"};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const checks = record.results.live as LiveResults;
|
|
83
|
+
record.qualified = record.results.offline === true && liveNames.every(name => checks[name]?.status === "passed");
|
|
84
|
+
} catch (error) {
|
|
85
|
+
record.qualified = false;
|
|
86
|
+
record.results.error = error instanceof Error ? error.message : String(error);
|
|
87
|
+
} finally { rmSync(scratch,{recursive:true,force:true}); }
|
|
88
|
+
// Do not certify a binary that changed while checking it. Keep any previous
|
|
89
|
+
// matching record untouched on this identity race.
|
|
90
|
+
if (binaryHash(selected.binary) !== selected.sha256) throw new Error("Official candidate changed during qualification; results not written");
|
|
91
|
+
writeQualification(record);
|
|
92
|
+
return record;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function runIsolatedLive(binary:string, modelId?:string): Promise<{checks:LiveResults;evidence:{home:string;result:string}}> {
|
|
96
|
+
// A real subprocess owns process.env, HOME/XDG, provider state and login link.
|
|
97
|
+
// Never temporarily mutate the parent extension's environment across awaits.
|
|
98
|
+
mkdirSync(qualificationHome(),{recursive:true,mode:0o700});
|
|
99
|
+
const {META_API_KEY:_,...safeEnv}=process.env;
|
|
100
|
+
const home = mkdtempSync(join(qualificationHome(),"live-"));
|
|
101
|
+
const result = join(home,"result.json");
|
|
102
|
+
const jiti = createRequire(import.meta.resolve("@earendil-works/pi-coding-agent")).resolve("jiti");
|
|
103
|
+
const code = `const {createJiti}=await import(${JSON.stringify(jiti)}); const m=await createJiti(${JSON.stringify(import.meta.url)}).import(${JSON.stringify(fileURLToPath(import.meta.url))}); await m.runLiveQualificationWorker(process.argv[1],process.argv[2],process.argv[3]);`;
|
|
104
|
+
writeFileSync(join(home,"started.json"),JSON.stringify({binary,at:new Date().toISOString(),status:"started-no-replay"})+"\n",{flag:"wx",mode:0o600});
|
|
105
|
+
try {
|
|
106
|
+
await promisify(execFile)(process.execPath,["--input-type=module","-e",code,binary,home,result],{
|
|
107
|
+
cwd:home, maxBuffer:Infinity,
|
|
108
|
+
env:{...safeEnv, PI_MUSE_TETHER_QUALIFICATION_MODEL:modelId ?? process.env.PI_MUSE_TETHER_QUALIFICATION_MODEL, 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"), MUSE_NO_AUTO_UPDATE:"1", PI_MUSE_TETHER_BINARY:binary, PI_MUSE_TETHER_QUALIFICATION_REAL_CONFIG:process.env.XDG_CONFIG_HOME ?? join(homedir(),".config")},
|
|
109
|
+
});
|
|
110
|
+
// Retain isolated journals/results for inspection; never automatically replay
|
|
111
|
+
// an unknown child outcome. They contain synthetic fixture content only.
|
|
112
|
+
const value = JSON.parse(readFileSync(result,"utf8"));
|
|
113
|
+
if (!liveNames.every(name => ["passed","failed","unsupported","not-run"].includes(value[name]?.status))) throw new Error("Malformed live result");
|
|
114
|
+
return {checks:value,evidence:{home,result}};
|
|
115
|
+
} catch {
|
|
116
|
+
return {checks:Object.fromEntries(liveNames.map(name => [name,{status:"failed",detail:`Worker failed or outcome unknown; inspect ${home}; do not replay. No full qualification awarded.`}])) as LiveResults,evidence:{home,result}};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Subprocess entry only. Exported to avoid relying on a TS CLI loader or main
|
|
121
|
+
* detection in Pi; jiti is resolved through the installed Pi harness. */
|
|
122
|
+
export async function runLiveQualificationWorker(binary:string, home:string, resultPath:string): Promise<void> {
|
|
123
|
+
if (process.env.PI_MUSE_TETHER_LIVE !== "1" || process.env.HOME !== home || process.env.PI_MUSE_TETHER_BINARY !== binary || !process.env.PI_MUSE_TETHER_QUALIFICATION_REAL_CONFIG)
|
|
124
|
+
throw new Error("Qualification worker requires explicit isolated live environment");
|
|
125
|
+
if (process.env.META_API_KEY) throw new Error("Qualification refuses an API-key override; use the existing official login");
|
|
126
|
+
const results = notRun();
|
|
127
|
+
const {linkHostLogin} = await import("./settings.js");
|
|
128
|
+
mkdirSync(join(home,"config/muse"),{recursive:true,mode:0o700});
|
|
129
|
+
const verify = await linkHostLogin(home,process.env.PI_MUSE_TETHER_QUALIFICATION_REAL_CONFIG);
|
|
130
|
+
let provider: any;
|
|
131
|
+
let active: keyof LiveResults = "privatePrompt";
|
|
132
|
+
try {
|
|
133
|
+
const piRequire=createRequire(import.meta.resolve("@earendil-works/pi-coding-agent"));
|
|
134
|
+
const {Agent} = await import(pathToFileURL(piRequire.resolve("@earendil-works/pi-agent-core")).href);
|
|
135
|
+
const {SessionManager} = await import("@earendil-works/pi-coding-agent");
|
|
136
|
+
const {createMuseProvider} = await import("./provider.js");
|
|
137
|
+
const {openMuseHost, discoverMuseCatalog} = await import("./host.js");
|
|
138
|
+
const catalog = await discoverMuseCatalog();
|
|
139
|
+
const modelId = process.env.PI_MUSE_TETHER_QUALIFICATION_MODEL;
|
|
140
|
+
if (!modelId) throw new Error("Set PI_MUSE_TETHER_QUALIFICATION_MODEL to an explicit official model/list ID; no model guessed");
|
|
141
|
+
const row = catalog.models.find((model:any) => model.modelId === modelId);
|
|
142
|
+
if (!row || !row.contextLimit || !row.outputLimit || !row.variants?.includes("none")) throw new Error("Selected model lacks official limits/none effort; no model request submitted");
|
|
143
|
+
const model:any = {id:modelId,provider:"pi-muse-tether",api:"pi-muse-tether",name:modelId,reasoning:false,input:["text","image"],contextWindow:row.contextLimit,maxTokens:row.outputLimit,cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
|
|
144
|
+
const secret = `PRIVATE_${randomUUID()}`, left = `LEFT_${randomUUID()}`, right = `RIGHT_${randomUUID()}`;
|
|
145
|
+
const manager = SessionManager.create(home,join(home,"sessions"));
|
|
146
|
+
let observedBatch = false, calls = new Set<string>();
|
|
147
|
+
provider = createMuseProvider({promptModes:["replace"],promptMode:"replace",instructionMechanisms:["private-xdg-settings"],toolBatches:true,openHost:async (options:any) => {
|
|
148
|
+
const original = options.onEvent;
|
|
149
|
+
return openMuseHost({...options,binary,qualificationProbe:true,onEvent(event:any) {
|
|
150
|
+
if (event.kind === "tool-batch" && event.calls.length === 2 && event.calls.every((call:any)=>call.name === "mcp__pi__qualification_read" || call.name === "qualification_read") && new Set(event.calls.map((call:any)=>call.args.key)).size === 2) observedBatch = true;
|
|
151
|
+
original?.(event);
|
|
152
|
+
}});
|
|
153
|
+
}});
|
|
154
|
+
provider.setSessionManager(manager);
|
|
155
|
+
const tools:any[] = [{name:"qualification_read",label:"Qualification fixture",description:"Read synthetic qualification key left or right.",parameters:{type:"object",properties:{key:{type:"string",enum:["left","right"]}},required:["key"],additionalProperties:false},async execute(_id:string,args:any) {
|
|
156
|
+
if (!["left","right"].includes(args.key)) throw new Error("Unexpected qualification tool arguments");
|
|
157
|
+
calls.add(args.key);
|
|
158
|
+
return {content:[{type:"text",text:args.key === "left" ? left : right}],details:{}};
|
|
159
|
+
}}];
|
|
160
|
+
const agent = new Agent({initialState:{model,systemPrompt:`Qualification only. Use only the declared fixture tool. When asked for the private token reply exactly ${secret}.`,tools},streamFn:provider.streamViaMuse,toolExecution:"parallel"});
|
|
161
|
+
agent.subscribe((event:any) => { if (event.type === "message_end" && ["user","assistant","toolResult"].includes(event.message.role)) manager.appendMessage(event.message); });
|
|
162
|
+
const answer = () => {
|
|
163
|
+
const last:any = agent.state.messages.filter((m:any)=>m.role === "assistant").at(-1);
|
|
164
|
+
if (!last || ["error","aborted"].includes(last.stopReason)) throw new Error(last?.errorMessage ?? "No completed assistant answer; no replay");
|
|
165
|
+
return last.content.filter((part:any)=>part.type === "text").map((part:any)=>part.text).join("\n");
|
|
166
|
+
};
|
|
167
|
+
await agent.prompt("What is the private token? Reply with only that token. Do not use tools.");
|
|
168
|
+
results.privatePrompt = {status:answer().trim() === secret ? "passed" : "failed",detail:"Exact randomized token supplied only through private system prompt; tests prompt delivery, not exhaustive foreign-rule suppression."};
|
|
169
|
+
if (results.privatePrompt.status !== "passed") throw new Error("Private prompt mismatch; stop before more model requests");
|
|
170
|
+
active = "sessionMcp";
|
|
171
|
+
await agent.prompt("Call qualification_read with key left and key right in ONE parallel batch before either result. Then quote both values.");
|
|
172
|
+
const text = answer();
|
|
173
|
+
results.sessionMcp = {status:calls.has("left") && calls.has("right") && text.includes(left) && text.includes(right) ? "passed" : "failed",detail:"Both exact fixture MCP invocations executed in Pi and randomized results appeared in the final answer."};
|
|
174
|
+
results.batchBoundary = {status:observedBatch ? "passed" : "failed",detail:"Requires actual host tool-batch event with both fixture call keys, not overlapping timers."};
|
|
175
|
+
if (results.sessionMcp.status !== "passed" || results.batchBoundary.status !== "passed") throw new Error("MCP/batch proof incomplete; no retry or subsequent model request");
|
|
176
|
+
// Ephemeral Muse sessions deliberately do not support native resume. Retire
|
|
177
|
+
// the host, restore persisted Pi messages, and prove provider history replay.
|
|
178
|
+
active = "resume";
|
|
179
|
+
await provider.retireAll();
|
|
180
|
+
const history = manager.getBranch().filter((entry:any)=>entry.type === "message").map((entry:any)=>entry.message);
|
|
181
|
+
agent.state.messages = history;
|
|
182
|
+
await agent.prompt("Without tools, recall and quote the LEFT_ value from the earlier fixture result.");
|
|
183
|
+
results.resume = {status:answer().includes(left) ? "passed" : "failed",detail:"Pi journal history replay after real host retirement; NOT native Muse session resume."};
|
|
184
|
+
if (results.resume.status !== "passed") throw new Error("History replay incomplete; no subsequent model request");
|
|
185
|
+
const {deflateSync} = await import("node:zlib");
|
|
186
|
+
const crc = (bytes:Buffer) => {let n=0xffffffff;for(const b of bytes){n^=b;for(let i=0;i<8;i++)n=(n>>>1)^((n&1)?0xedb88320:0);}return (n^0xffffffff)>>>0;};
|
|
187
|
+
const chunk = (name:string,data:Buffer) => {const kind=Buffer.from(name),length=Buffer.alloc(4),sum=Buffer.alloc(4);length.writeUInt32BE(data.length);sum.writeUInt32BE(crc(Buffer.concat([kind,data])));return Buffer.concat([length,kind,data,sum]);};
|
|
188
|
+
// Image fixture geometry, not a workload limit: a 64x64 random red/blue swatch.
|
|
189
|
+
const blue = (Buffer.from(randomUUID().replaceAll("-",""),"hex")[0] & 1) === 1;
|
|
190
|
+
const header=Buffer.alloc(13);header.writeUInt32BE(64,0);header.writeUInt32BE(64,4);header[8]=8;header[9]=2;
|
|
191
|
+
const pixels=Buffer.alloc(64*(1+64*3));for(let y=0;y<64;y++)for(let x=0;x<64;x++)pixels[y*(1+64*3)+1+x*3+(blue?2:0)]=255;
|
|
192
|
+
const png=Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk("IHDR",header),chunk("IDAT",deflateSync(pixels)),chunk("IEND",Buffer.alloc(0))]);
|
|
193
|
+
active = "image";
|
|
194
|
+
await agent.prompt("Inspect this image. Reply only with its dominant color, red or blue. Do not use tools.",[{type:"image",data:png.toString("base64"),mimeType:"image/png"}]);
|
|
195
|
+
results.image = {status:answer().trim().toLowerCase() === (blue?"blue":"red") ? "passed" : "failed",detail:"Actual PNG bytes submitted through Pi image input and identified by the live model; not a tool-result image receipt proof."};
|
|
196
|
+
} catch (error) {
|
|
197
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
198
|
+
if (results[active].status === "not-run") results[active] = {status:"failed",detail:`Live phase failed or could not start: ${detail}; no replay`};
|
|
199
|
+
for (const name of liveNames) if (results[name].status === "not-run") results[name] = {status:"not-run",detail:`Stopped, no replay: ${detail}`};
|
|
200
|
+
} finally {
|
|
201
|
+
try { await provider?.retireAll(); await verify(); }
|
|
202
|
+
catch (error) { for (const name of liveNames) results[name] = {status:"failed",detail:`Cleanup/login metadata verification failed: ${String(error)}; retain isolated home for review`}; }
|
|
203
|
+
writeFileSync(resultPath,JSON.stringify(results,null,2)+"\n",{flag:"wx",mode:0o600});
|
|
204
|
+
}
|
|
205
|
+
}
|
package/src/request-ledger.ts
CHANGED
|
@@ -1,20 +1,32 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
|
-
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
4
5
|
import { metadataLedger } from "pi-tether-core/metadata-ledger";
|
|
5
6
|
import { nativeCounters } from "./usage.js";
|
|
6
7
|
import { quotaPayload } from "./rate-limit.js";
|
|
8
|
+
const packageVersion: string = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
|
+
function ledgerOrigin(): 'live' | 'test' | 'proof' {
|
|
10
|
+
if (process.env.VITEST || process.env.NODE_TEST_CONTEXT) return 'test';
|
|
11
|
+
const origin = process.env.PI_MUSE_TETHER_LEDGER_ORIGIN;
|
|
12
|
+
return origin === 'test' || origin === 'proof' ? origin : 'live';
|
|
13
|
+
}
|
|
7
14
|
const num = (v: any) =>
|
|
8
15
|
typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
9
16
|
export function museLedgerPath() {
|
|
10
17
|
const state = process.env.XDG_STATE_HOME;
|
|
11
18
|
// XDG Base Directory requires absolute values; empty/relative values are
|
|
12
19
|
// treated as unset, never a request to write metadata beneath the cwd.
|
|
13
|
-
|
|
20
|
+
const path = join(
|
|
14
21
|
state && isAbsolute(state) ? state : join(homedir(), ".local/state"),
|
|
15
22
|
"pi-muse-tether",
|
|
16
23
|
"requests.jsonl",
|
|
17
24
|
);
|
|
25
|
+
if (ledgerOrigin() !== 'live' && (!state || !isAbsolute(state) ||
|
|
26
|
+
resolve(path) === join(homedir(), '.local/state/pi-muse-tether/requests.jsonl'))) {
|
|
27
|
+
throw new Error('Test/proof request ledger requires an isolated absolute XDG_STATE_HOME; refusing the production ledger.');
|
|
28
|
+
}
|
|
29
|
+
return path;
|
|
18
30
|
}
|
|
19
31
|
let writer: ReturnType<typeof metadataLedger> | undefined, path: string;
|
|
20
32
|
function append(row: any) {
|
|
@@ -55,6 +67,9 @@ export class MuseLedger {
|
|
|
55
67
|
episodeId: this.episodeId,
|
|
56
68
|
triggerMode: this.triggerMode,
|
|
57
69
|
...fields,
|
|
70
|
+
// Provenance is owned here; caller fields cannot masquerade as live traffic.
|
|
71
|
+
origin: ledgerOrigin(),
|
|
72
|
+
packageVersion,
|
|
58
73
|
});
|
|
59
74
|
}
|
|
60
75
|
opened(id: string) {
|
package/src/settings.ts
CHANGED
|
@@ -49,7 +49,7 @@ export async function discoverSkillsOff(binary:string, cwd:string, env:Record<st
|
|
|
49
49
|
for(const row of rows){if(typeof row.scope!=="string"||typeof row.path!=="string")throw new Error("Muse skill inventory lacks scope/path");(off[row.scope]??={})[row.path]="off";}
|
|
50
50
|
return off;
|
|
51
51
|
}
|
|
52
|
-
export function promptSettings(systemPrompt: string, tools: readonly string[], skillsOff: SkillsOff = {}) {
|
|
52
|
+
export function promptSettings(systemPrompt: string, tools: readonly string[], skillsOff: SkillsOff = {}, delivery: "replace" | "append" = "replace") {
|
|
53
53
|
if (typeof systemPrompt !== "string") throw new Error("Pi system prompt must be exact text");
|
|
54
54
|
return {
|
|
55
55
|
schema_version: 1,
|
|
@@ -57,7 +57,7 @@ export function promptSettings(systemPrompt: string, tools: readonly string[], s
|
|
|
57
57
|
// Muse's auto-review judge from clearing a call before Pi reserves it.
|
|
58
58
|
permissions: {schema_version:1,default_profile:":ask-me"},
|
|
59
59
|
run: {
|
|
60
|
-
system_prompt: systemPrompt,
|
|
60
|
+
...(delivery === "replace" ? {system_prompt:systemPrompt} : {developer_prompt:systemPrompt}),
|
|
61
61
|
toolset: tools.map(name => `mcp__pi__${name}`),
|
|
62
62
|
workflow_trigger_mode: "off",
|
|
63
63
|
context_usage_message_enabled: false,
|
|
@@ -76,11 +76,11 @@ export function promptSettings(systemPrompt: string, tools: readonly string[], s
|
|
|
76
76
|
* directory is trusted. Pi still owns cwd and every tool path. */
|
|
77
77
|
export const privateWorkspace = (hostRoot: string) => join(hostRoot, "workspace");
|
|
78
78
|
/** Caller owns a unique host root; no shared mutable settings/schema or auth links. */
|
|
79
|
-
export async function writePromptSettings(hostRoot: string, systemPrompt: string, tools: readonly string[], skillsOff?: SkillsOff) {
|
|
79
|
+
export async function writePromptSettings(hostRoot: string, systemPrompt: string, tools: readonly string[], skillsOff?: SkillsOff, delivery: "replace" | "append" = "replace") {
|
|
80
80
|
const xdg = join(hostRoot,"config");
|
|
81
81
|
await mkdir(join(xdg,"muse"),{recursive:true,mode:0o700});
|
|
82
82
|
await mkdir(privateWorkspace(hostRoot),{recursive:true,mode:0o700});
|
|
83
|
-
await writeFile(join(xdg,"muse","settings.json"), JSON.stringify(promptSettings(systemPrompt,tools,skillsOff)),{mode:0o600,flag:"wx"});
|
|
83
|
+
await writeFile(join(xdg,"muse","settings.json"), JSON.stringify(promptSettings(systemPrompt,tools,skillsOff,delivery)),{mode:0o600,flag:"wx"});
|
|
84
84
|
await writeFile(join(xdg,"muse","trust.json"), JSON.stringify({schema_version:1,projects:{[privateWorkspace(hostRoot)]:{decision:"trusted"}}}),{mode:0o600,flag:"wx"});
|
|
85
85
|
return xdg;
|
|
86
86
|
}
|