pi-muse-tether 0.1.0 → 0.1.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 +11 -0
- package/README.md +2 -2
- package/docs/DETAILS.md +9 -5
- package/index.ts +10 -3
- package/package.json +4 -4
- package/src/catalog.ts +9 -7
- package/src/cli-version.ts +25 -2
- package/src/host.ts +33 -12
- package/src/provider.ts +115 -76
- package/src/request-ledger.ts +5 -2
- package/src/settings.ts +9 -7
- package/src/tool-result-receipt.ts +112 -58
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
- Pi's provider hooks now fire.
|
|
6
|
+
- Tool results with images no longer kill the turn, including JPEG and several images at once.
|
|
7
|
+
- `[REDACTED]` at the start or end of a line, or across a whole line, no longer kills the turn. Any other changed text still stops it.
|
|
8
|
+
- Invalid tool arguments now get Pi's normal validation error, so the model can fix the call instead of stopping at an opaque denial.
|
|
9
|
+
- A quota refusal no longer blocks the whole account for the session.
|
|
10
|
+
- One bad model entry no longer blocks the others, and `/muse-doctor` reports catalog failures.
|
|
11
|
+
- An empty `XDG_STATE_HOME` now falls back to the home state folder.
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ Hi, I do most of my work in Pi and I also pay for Muse Code. While Meta has not
|
|
|
12
12
|
|
|
13
13
|
## Who it's for
|
|
14
14
|
|
|
15
|
-
This is for you if you've built your workflow around Pi, with your own system prompt, skills, extensions and subagents, and you have a Muse subscription. Muse becomes one more entry in `/model`. You can switch to it in the middle of a session and switch back later, and Pi keeps the whole conversation.
|
|
15
|
+
This is for you if you've built your workflow around Pi, with your own system prompt, skills, extensions and subagents, and you have a Muse subscription. Muse becomes one more entry in `/model`. You can switch to it in the middle of a session and switch back later, and Pi keeps the whole conversation. Pi's hooks keep working.
|
|
16
16
|
|
|
17
17
|
## Install
|
|
18
18
|
|
|
@@ -56,7 +56,7 @@ The last row is the difference you will notice most.
|
|
|
56
56
|
- You restart Pi often in long sessions. A restart starts a new Muse client, so the next turn begins with a cold cache and processes the whole history again.
|
|
57
57
|
- You need control over retries. Muse retries some server errors by itself, and I found no way to turn that off.
|
|
58
58
|
- Your tool results must reach the model unchanged. Muse sometimes replaces secret-looking text with `[REDACTED]`, so I can't tell exactly what the model saw.
|
|
59
|
-
-
|
|
59
|
+
- You need the model to see every image your tools return. Images no longer kill the turn, but I can't prove what the model saw. It read PNG and JPEG correctly in small tests, but with six images at once it got the last JPEG wrong and said it couldn't see the GIF and WebP. Images attached to a tool error never reach it, because the official client drops them. See [details](https://github.com/kyraneth/pi-muse-tether/blob/main/docs/DETAILS.md).
|
|
60
60
|
- Your tools run for a very long time. I tested one that ran for 5 minutes, and I don't know how much longer one can run.
|
|
61
61
|
- You're on a datacenter network with IPv6. On some of these, Muse returned an empty model list while the same account worked over IPv4. The tether stops and tells you when this happens.
|
|
62
62
|
|
package/docs/DETAILS.md
CHANGED
|
@@ -17,7 +17,7 @@ Without `PI_MUSE_TETHER_LIVE=1`, only the synthetic offline `echo` model is regi
|
|
|
17
17
|
|
|
18
18
|
## Choose a model
|
|
19
19
|
|
|
20
|
-
The live `model/list` catalog supplies windows, output limits, image capability and supported effort levels.
|
|
20
|
+
The live `model/list` catalog supplies windows, output limits, image capability and supported effort levels. Valid provider-catalog models register independently; missing or invalid rows are omitted, with no guessed model entry. Empty, bundled or failed discovery leaves the offline echo available, and `/muse-doctor` reports missing groups or discovery failure.
|
|
21
21
|
|
|
22
22
|
| Pi model ID | Selection |
|
|
23
23
|
| --- | --- |
|
|
@@ -57,7 +57,7 @@ For a desired 450,000-token compaction boundary, calculate `reserveTokens = actu
|
|
|
57
57
|
|
|
58
58
|
### Parallel tools, long tools, abort and steering
|
|
59
59
|
|
|
60
|
-
Coding requires the pinned experimental `rawLog` capability, `session.live` subscription and complete `assistant_tool_calls_committed` boundary. Missing support fails before inference, without timers or single-call fallbacks. One Pi assistant contains the ordered tool batch; Pi
|
|
60
|
+
Coding requires the pinned experimental `rawLog` capability, `session.live` subscription and complete `assistant_tool_calls_committed` boundary. Missing support fails before inference, without timers or single-call fallbacks. One Pi assistant contains the ordered tool batch; Pi validates/coerces its original arguments and journals validation errors or execution results before native approvals are released for exact receipt retrieval. Invalid arguments therefore produce the normal Pi validation message, not an opaque native approval denial. Native/MCP identity still binds the unchanged original arguments, including when Pi coerces them for execution. Raw records are consumed in memory, not logged wholesale.
|
|
61
61
|
|
|
62
62
|
**Long-tool limit:** a historical native MCP task timed out around 300 seconds while Pi was still running. Approval holding now avoids opening that native call during Pi execution. One synthetic 301-second live tool passed with the native MCP call open only briefly. That establishes the measured interval, **not unlimited approval patience or arbitrary long-build support**. No vendor no-deadline control is qualified. A late denial, timeout or host death can leave a real Pi side effect without a verified native receipt. Fencing cannot undo it or silently kill Pi's executor. Inspect uncertain effects before a new request; unknown work is never automatically replayed.
|
|
63
63
|
|
|
@@ -73,9 +73,13 @@ No pinned SDK per-turn disable-retry control is qualified. Startup retry setting
|
|
|
73
73
|
|
|
74
74
|
Muse receipts can replace secret-like text, including source-code token prefixes, with `[REDACTED]`. **What the model actually consumed is unknown.** No supported disable-redaction control was found in the inspected pinned surfaces, and no encoding/reflow bypass is used.
|
|
75
75
|
|
|
76
|
-
Accepted redaction needs nonempty single-line removed text,
|
|
76
|
+
Accepted redaction needs nonempty single-line removed text and one unambiguous positional alignment. Line-start, line-end and whole-line loss continue as declared-lossy; adjacent vendor markers are one combined nonempty loss region, without claiming an internal split. If a marker run mixes a literal Pi marker and a new redaction, only a uniquely aligned individual-token parse may accept it. Literal markers remain literal. Ambiguous alignment, newline removal or any other changed text still stops. Surrounding bytes are verified, not bytes inside holes or whether those bytes were secrets. Metadata diagnostics retain offsets, lengths and hashes, never removed text. `exactModelConsumption:false` means absence of proof, not proof that input was altered.
|
|
77
77
|
|
|
78
|
-
**
|
|
78
|
+
**Native empty-part projection:** successful results fold chunks with LF only after accumulated nonempty output, so leading empty parts add no separator while later empty parts do. An entirely empty success has the exact native display sentinel `[MCP tool returned no content]`. Failed results instead LF-join all text parts (including leading empty text), omit images, and use `MCP tool returned an error` if their joined text is empty. These are pinned-client receipt codecs, not global text cleanup.
|
|
79
|
+
|
|
80
|
+
**Image/multipart tool outputs (0.1.1):** PNG, JPEG, GIF and WebP are forwarded in arbitrary text/image layouts, including image-only, multiple images, empty text and errors. Receipt verification constructs the native ordered projection positionally; literal placeholder-shaped text and leading newlines are not stripped. Image metadata is declared-lossy, never exact pixel evidence; available `modelVisibleContent` derivatives do not upgrade that evidence. Truncated text still requires verified complete `item/readOutput` readback. Malformed encodings and genuine text/metadata mismatches still stop.
|
|
81
|
+
|
|
82
|
+
**Observed vendor limits:** the official failed-MCP path exposes only text (`failureReason`) and drops images from its receipt/model view. These images are explicitly marked `modelVisibility: omitted-error-result`, not claimed seen. A six-image live probe continued and read initial PNG/JPEG correctly, but reported GIF/WebP not visibly rendered and misidentified its last JPEG. Thus GIF/WebP transport acceptance and no-turn-failure are qualified, not their pixels or universal multi-image accuracy. A separate interleaved PNG/JPEG live probe read both images correctly. No format conversion or byte-equality claim is invented.
|
|
79
83
|
|
|
80
84
|
### Quota, usage and accounting
|
|
81
85
|
|
|
@@ -83,7 +87,7 @@ Native percentage/reset telemetry may initially be absent. Rounded 0% is not pro
|
|
|
83
87
|
|
|
84
88
|
### Empty catalog over some IPv6 paths
|
|
85
89
|
|
|
86
|
-
If
|
|
90
|
+
If `/muse-doctor` reports an empty catalog, compare the official client alone:
|
|
87
91
|
|
|
88
92
|
```sh
|
|
89
93
|
muse exec --model muse-spark-1.3 "hi"
|
package/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { museCatalogModels } from "./src/catalog.js";
|
|
1
|
+
import { museCatalogAssessment, museCatalogModels } from "./src/catalog.js";
|
|
2
2
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
|
|
4
4
|
import { registerApiDispatch } from "pi-tether-core/register";
|
|
@@ -18,8 +18,15 @@ export async function registerMuseExtension(pi: ExtensionAPI, provider = {stream
|
|
|
18
18
|
if (!template)
|
|
19
19
|
throw new Error("Pi supplied no catalog template for offline echo");
|
|
20
20
|
const stream = streamViaMuse;
|
|
21
|
-
|
|
21
|
+
let catalog: Awaited<ReturnType<typeof discoverMuseCatalog>> | undefined;
|
|
22
|
+
let catalogueError: string | undefined;
|
|
23
|
+
if (process.env.PI_MUSE_TETHER_LIVE === "1") {
|
|
24
|
+
try { catalog = await discoverMuseCatalog(); }
|
|
25
|
+
catch (error) { catalogueError = error instanceof Error ? error.message : String(error); }
|
|
26
|
+
}
|
|
22
27
|
const liveModels = catalog ? museCatalogModels(catalog) : [];
|
|
28
|
+
const catalogueDiagnostics = catalog ? museCatalogAssessment(catalog).diagnostics :
|
|
29
|
+
{ status: catalogueError ? "discovery failed" : "live disabled", ...(catalogueError ? {error: catalogueError} : {}) };
|
|
23
30
|
registerApiDispatch(ID, stream);
|
|
24
31
|
pi.registerProvider(ID, {
|
|
25
32
|
api: ID,
|
|
@@ -39,7 +46,7 @@ export async function registerMuseExtension(pi: ExtensionAPI, provider = {stream
|
|
|
39
46
|
],
|
|
40
47
|
streamSimple: stream,
|
|
41
48
|
});
|
|
42
|
-
pi.registerCommand("muse-doctor", {description:"Local Muse version, recipe and telemetry diagnostic (no model/account request)",handler:async(_args,ctx)=>{ctx.ui.notify(await museDoctor(ctx.model?.id),"info");}});
|
|
49
|
+
pi.registerCommand("muse-doctor", {description:"Local Muse version, recipe and telemetry diagnostic (no model/account request)",handler:async(_args,ctx)=>{ctx.ui.notify(JSON.stringify({...JSON.parse(await museDoctor(ctx.model?.id)),catalogue:catalogueDiagnostics},null,2),"info");}});
|
|
43
50
|
pi.on("session_start", async (_event, ctx) => {
|
|
44
51
|
setQuotaListener(payload=>ctx.ui.setStatus("muse-rate-limit",quotaStatusLine(payload)));
|
|
45
52
|
setRetryStatusListener(status=>ctx.ui.setStatus("muse-retry",status));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-muse-tether",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Use your Muse Code subscription in Pi through the official client",
|
|
6
6
|
"license": "MIT",
|
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
"homepage": "https://github.com/kyraneth/pi-muse-tether#readme",
|
|
10
10
|
"bugs": {"url": "https://github.com/kyraneth/pi-muse-tether/issues"},
|
|
11
11
|
"engines": {"node": ">=24"},
|
|
12
|
-
"files": ["index.ts", "src/", "README.md", "LICENSE", "assets/", "docs/DETAILS.md"],
|
|
12
|
+
"files": ["index.ts", "src/", "README.md", "CHANGELOG.md", "LICENSE", "assets/", "docs/DETAILS.md"],
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"@muse-code/sdk": "1.4.14",
|
|
15
|
-
"pi-tether-core": "0.1.
|
|
15
|
+
"pi-tether-core": "0.1.1"
|
|
16
16
|
},
|
|
17
17
|
"main": "index.ts",
|
|
18
18
|
"pi": {
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"typescript": "^5"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
|
-
"test": "vitest run tests --exclude tests/host.test.ts && node --import tsx --test tests/host.test.ts tests/catalog-entry.node.ts",
|
|
36
|
+
"test": "vitest run tests --exclude tests/host.test.ts --testTimeout=0 --hookTimeout=0 && node --import tsx --test tests/host.test.ts tests/catalog-entry.node.ts",
|
|
37
37
|
"dev:install-core": "node scripts/install-core-main.mjs",
|
|
38
38
|
"scan:public": "node scripts/check-public-tree.mjs",
|
|
39
39
|
"export:manifest": "node scripts/export-manifest"
|
package/src/catalog.ts
CHANGED
|
@@ -19,9 +19,9 @@ export const EMPTY_CATALOGUE_HINT = ". The official Muse client received an empt
|
|
|
19
19
|
+ "account works elsewhere, Meta may be refusing this network path (seen on datacenter IPv6); "
|
|
20
20
|
+ "see the pi-muse-tether README section \"Empty catalogue on some cloud networks\"";
|
|
21
21
|
|
|
22
|
-
export function
|
|
22
|
+
export function museCatalogAssessment(catalog: any) {
|
|
23
23
|
const rows: any[] = Array.isArray(catalog?.models) ? catalog.models : [];
|
|
24
|
-
const valid = rows.filter(m => isCatalogueModel(m.modelId) &&
|
|
24
|
+
const valid = (catalog?.source === "providerCatalog" ? rows : []).filter(m => m && typeof m === "object" && isCatalogueModel(m.modelId) &&
|
|
25
25
|
m.providerId === "meta" && typeof m.displayLabel === "string" && m.displayLabel.length &&
|
|
26
26
|
Number.isSafeInteger(m.contextLimit) && m.contextLimit > 0 &&
|
|
27
27
|
Number.isSafeInteger(m.outputLimit) && m.outputLimit > 0 &&
|
|
@@ -30,11 +30,13 @@ export function museCatalogModels(catalog: any) {
|
|
|
30
30
|
Object.values(museThinkingLevelMap([tier])).includes(tier)) &&
|
|
31
31
|
m.variants.includes(m.defaultReasoningEffort));
|
|
32
32
|
const missing = MUSE_MODEL_GROUPS.filter(group => !valid.some(m => (group as readonly string[]).includes(m.modelId)));
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
return { valid, diagnostics: { source: catalog?.source ?? null, providerId: catalog?.providerId ?? null,
|
|
34
|
+
profileId: catalog?.profileId ?? null, missing, models: rows.map(m => ({modelId:m?.modelId,contextLimit:m?.contextLimit,outputLimit:m?.outputLimit,variants:m?.variants})),
|
|
35
|
+
...(!rows.length ? {hint:EMPTY_CATALOGUE_HINT} : {}) } };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function museCatalogModels(catalog: any) {
|
|
39
|
+
const {valid} = museCatalogAssessment(catalog);
|
|
38
40
|
return valid.flatMap(m => (m.modelId.includes("wonder") ? ["off", "on"] : ["on"]).map(contributorMode => ({
|
|
39
41
|
id: m.modelId.includes("wonder") && contributorMode === "on" ? `${m.modelId}-contributor` : m.modelId,
|
|
40
42
|
name: `${m.displayLabel} · ${contributorMode === "on" ? "Contributor" : "Normal"}${museModelCost(m.modelId).input === null ? " · pricing unknown" : ""}`,
|
package/src/cli-version.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
|
-
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { readFile, realpath, stat } from "node:fs/promises";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { dirname, resolve } from "node:path";
|
|
6
6
|
export const QUALIFIED_CLIENT = "1.4.14";
|
|
@@ -17,6 +17,20 @@ export function assertQualifiedVersions(clientOutput: string, sdk: string, rawLo
|
|
|
17
17
|
);
|
|
18
18
|
return { client: match[1], sdk };
|
|
19
19
|
}
|
|
20
|
+
// Cache only the known official selector layout. Unknown launchers may delegate
|
|
21
|
+
// according to arbitrary state, so their version is probed for every host.
|
|
22
|
+
const versionCache = new Map<string, string>();
|
|
23
|
+
async function binaryIdentity(binary: string): Promise<string | undefined> {
|
|
24
|
+
try {
|
|
25
|
+
const path = await realpath(binary);
|
|
26
|
+
if (path.split("/").at(-1) !== "muse") return undefined;
|
|
27
|
+
const dir = dirname(path), selector = (await readFile(resolve(dir, ".muse-version"), "utf8")).trim();
|
|
28
|
+
if (!/^\d+\.\d+\.\d+-R\d+(?:\.\d+)?$/.test(selector)) return undefined;
|
|
29
|
+
const active = await realpath(resolve(dir, `muse-bin-${selector}`));
|
|
30
|
+
const fingerprint = async (name: string) => { const s = await stat(name, {bigint:true}); return [name, String(s.dev), String(s.ino), String(s.size), String(s.mtimeNs), String(s.ctimeNs)]; };
|
|
31
|
+
return JSON.stringify([await fingerprint(path), selector, await fingerprint(active)]);
|
|
32
|
+
} catch { return undefined; }
|
|
33
|
+
}
|
|
20
34
|
export async function qualifyMuseVersion(
|
|
21
35
|
binary: string,
|
|
22
36
|
env: NodeJS.ProcessEnv,
|
|
@@ -27,9 +41,18 @@ export async function qualifyMuseVersion(
|
|
|
27
41
|
const sdk = JSON.parse(
|
|
28
42
|
await readFile(resolve(dirname(entry), "../../package.json"), "utf8"),
|
|
29
43
|
).version;
|
|
44
|
+
signal?.throwIfAborted();
|
|
45
|
+
const identity = await binaryIdentity(binary);
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
const key = identity && JSON.stringify([identity, sdk, rawLog]);
|
|
48
|
+
const cached = key && versionCache.get(key);
|
|
49
|
+
if (cached) return assertQualifiedVersions(cached, sdk, rawLog);
|
|
30
50
|
const { stdout } = await promisify(execFile)(binary, ["--version"], {
|
|
31
51
|
env: { ...env, MUSE_NO_AUTO_UPDATE: "1" },
|
|
32
52
|
signal,
|
|
33
53
|
});
|
|
34
|
-
|
|
54
|
+
const result = assertQualifiedVersions(stdout, sdk, rawLog);
|
|
55
|
+
signal?.throwIfAborted();
|
|
56
|
+
if (key && identity === await binaryIdentity(binary)) versionCache.set(key, stdout);
|
|
57
|
+
return result;
|
|
35
58
|
}
|
package/src/host.ts
CHANGED
|
@@ -55,7 +55,7 @@ export interface MuseHostOptions {
|
|
|
55
55
|
/** Stop an opening host when its Pi binding is retired. */
|
|
56
56
|
signal?: AbortSignal;
|
|
57
57
|
/**
|
|
58
|
-
* Required to allow anything. Must validate
|
|
58
|
+
* Required to allow anything. Must validate identity and reserve the exact
|
|
59
59
|
* generation, session, turn, approvalId, toolCallId and rawArgs for the later
|
|
60
60
|
* broker request. A true answer is permission to reach the proxy, NOT execute.
|
|
61
61
|
* Synchronous by design: no stale requirement can wait on human interaction.
|
|
@@ -76,14 +76,23 @@ export function policyDenial(error: unknown, seen=new Set<unknown>()): boolean {
|
|
|
76
76
|
const value = error as Record<string, unknown>;
|
|
77
77
|
if ([value.status, value.httpStatus, value.statusCode, value.code].includes(403) ||
|
|
78
78
|
value.kind === "client_attestation_denied" || value.code === "client_attestation_denied") return true;
|
|
79
|
-
|
|
80
|
-
//
|
|
79
|
+
// SDK errorKind is an open string. Only account/policy refusals latch;
|
|
80
|
+
// quota and rate limits fence the current binding without poisoning later hosts.
|
|
81
81
|
if ([value.errorKind, value.kind, value.code].some(v => typeof v === "string" &&
|
|
82
|
-
/auth|attestation|policy|
|
|
82
|
+
/auth|attestation|policy|permission|forbidden/i.test(v))) return true;
|
|
83
83
|
if (typeof value.message === "string" && /\bHTTP\s+403\b|\bclient_attestation_denied\b/.test(value.message)) return true;
|
|
84
84
|
return [value.data, value.error, value.cause].some((nested) => nested !== error && policyDenial(nested, seen));
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
|
|
88
|
+
if (!error || typeof error !== "object" || seen.has(error)) return false;
|
|
89
|
+
seen.add(error);
|
|
90
|
+
const value = error as Record<string, unknown>;
|
|
91
|
+
if ([value.status, value.httpStatus, value.statusCode, value.code].includes(429) || value.quota !== undefined ||
|
|
92
|
+
[value.errorKind, value.kind, value.code].some(v => typeof v === "string" && /quota|plan.*limit|rate.?limit/i.test(v))) return true;
|
|
93
|
+
return [value.data, value.error, value.cause].some(nested => quotaDenial(nested, seen));
|
|
94
|
+
}
|
|
95
|
+
|
|
87
96
|
const canonical = (v:any):string => v && typeof v === "object"
|
|
88
97
|
? Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
|
|
89
98
|
: JSON.stringify(v);
|
|
@@ -250,7 +259,7 @@ export class MuseHost {
|
|
|
250
259
|
const waiting=this.#options.waitForToolReceipt?.();
|
|
251
260
|
if(waiting)await waiting;
|
|
252
261
|
// Refuse invalid/foreign requests immediately, without waiting for a Pi
|
|
253
|
-
// result that must never exist. Reserve exact
|
|
262
|
+
// result that must never exist. Reserve exact args before holding.
|
|
254
263
|
const decision=this.#decide(request);
|
|
255
264
|
if(decision.choiceId!=="allow_once")return decision;
|
|
256
265
|
const result=this.#options.waitForPiToolResult?.(request);
|
|
@@ -335,6 +344,10 @@ export class MuseHost {
|
|
|
335
344
|
this.#emit({kind:"frame",frame});
|
|
336
345
|
this.#refusal(policyDenial(params.error) ? params.error : params);return;
|
|
337
346
|
}
|
|
347
|
+
if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
|
|
348
|
+
this.#emit({kind:"frame",frame});
|
|
349
|
+
this.fence("Muse quota refused; no replay"); return;
|
|
350
|
+
}
|
|
338
351
|
if(retry){
|
|
339
352
|
if(!this.#busy || params.turnId!==this.#submission?.turnId) {
|
|
340
353
|
this.fence("Muse retry has foreign or inactive turn identity");return;
|
|
@@ -451,12 +464,14 @@ export class MuseHost {
|
|
|
451
464
|
if (this.#busy) throw new Error("Muse predecessor has no turn/completed terminal");
|
|
452
465
|
await this.#options.verifyLogin?.();
|
|
453
466
|
if (!this.#options.echo) {
|
|
454
|
-
const result = await this.connection.request("usage/read", {}).catch(error=>{this.#refusal(error);throw error;});
|
|
467
|
+
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
468
|
const usage = result.usage as any;
|
|
456
469
|
publishQuota(usage); this.ledger.quota(usage);
|
|
457
470
|
// Muse reports percentages; 100% is the provider's exhausted plan boundary.
|
|
458
|
-
if (quotaExhausted(usage))
|
|
471
|
+
if (quotaExhausted(usage)) {
|
|
472
|
+
this.fence("Muse plan usage limit reached; no turn submitted");
|
|
459
473
|
throw new Error("Muse plan usage limit reached; no turn submitted");
|
|
474
|
+
}
|
|
460
475
|
}
|
|
461
476
|
const commandId = this.connection.mintCommandId();
|
|
462
477
|
const submission: Submission = { commandId, turnId: undefined, terminal: false, started: false };
|
|
@@ -491,10 +506,13 @@ export class MuseHost {
|
|
|
491
506
|
this.#assertLive();
|
|
492
507
|
return { turnId: ack.turnId, commandId };
|
|
493
508
|
} catch (error) {
|
|
494
|
-
this.#retrySafe = !submission.started && submission.turnId===undefined && error instanceof MspError &&
|
|
509
|
+
this.#retrySafe = !policyDenial(error) && !quotaDenial(error) && !submission.started && submission.turnId===undefined && error instanceof MspError &&
|
|
495
510
|
((error.code===-32001 && error.kind==="overloaded") || (error.code===-32031 && error.kind==="backpressured"));
|
|
496
511
|
this.#refusal(error);
|
|
497
|
-
|
|
512
|
+
if (quotaDenial(error) && !policyDenial(error)) {
|
|
513
|
+
this.ledger.record("quota_refusal", {phase:"turn_admission"});
|
|
514
|
+
this.fence("Muse quota refused; no replay");
|
|
515
|
+
} else this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
|
|
498
516
|
throw error;
|
|
499
517
|
}
|
|
500
518
|
}
|
|
@@ -556,10 +574,13 @@ export async function discoverMuseCatalog() {
|
|
|
556
574
|
await qualifyMuseVersion(launch.command,launch.env??{});
|
|
557
575
|
const handshake = spawnMspConnection(launch);
|
|
558
576
|
try {
|
|
559
|
-
const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.
|
|
577
|
+
const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
|
|
560
578
|
capabilities: { requestedCapabilities: ["sessionMcp"], userInputDialogs: false } });
|
|
561
579
|
const catalog = await spawned.connection.request("model/list", {});
|
|
562
580
|
return catalog as typeof catalog & {models:any[]};
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (policyDenial(error)) policyLatch="Muse nonretryable provider refusal latched; account-owner review required";
|
|
583
|
+
throw error;
|
|
563
584
|
} finally { await handshake.close(); }
|
|
564
585
|
}
|
|
565
586
|
|
|
@@ -588,7 +609,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
|
|
|
588
609
|
const verify=await linkHostLogin(home,launch.env?.XDG_CONFIG_HOME??join(homedir(),".config"));
|
|
589
610
|
verifyLogin=async()=>{
|
|
590
611
|
const metadata=await verify();
|
|
591
|
-
if(metadata.
|
|
612
|
+
if(metadata.realMetadataChanged)host?.ledger.record("auth_metadata_change",{metadata});
|
|
592
613
|
options.onEvent?.({kind:"auth-metadata",metadata});
|
|
593
614
|
return metadata;
|
|
594
615
|
};
|
|
@@ -615,7 +636,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
|
|
|
615
636
|
return {};
|
|
616
637
|
});
|
|
617
638
|
try {
|
|
618
|
-
const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.
|
|
639
|
+
const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
|
|
619
640
|
capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches)?{experimentalApi:true}:{}) } });
|
|
620
641
|
if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported; no model request submitted");
|
|
621
642
|
if (!options.echo) {
|
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;
|
|
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.
|
|
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
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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" &&
|
|
@@ -449,15 +447,15 @@ function emitFrame(b: Binding, event: any) {
|
|
|
449
447
|
if (redactions.length) {
|
|
450
448
|
b.host?.ledger?.record("tool_result_vendor_redaction", {
|
|
451
449
|
callId: item.callId, itemId: item.itemId, count: redactions.length,
|
|
452
|
-
rule: "unique-nonempty-intraline-
|
|
453
|
-
textProjection: r.
|
|
450
|
+
rule: "unique-nonempty-intraline-v3", spans: redactions, evidence:"declared-lossy",
|
|
451
|
+
textProjection: r.isError ? "lf-joined-all-text-parts" : images.length ? "native-ordered-parts-with-image-metadata" : "native-text-chunk-fold",
|
|
454
452
|
exactModelConsumption: false,
|
|
455
453
|
});
|
|
456
454
|
publishRedactionStatus(b, redactions.length);
|
|
457
455
|
}
|
|
458
456
|
if (images.length) b.host?.ledger?.record("tool_result_image_unverifiable", {
|
|
459
457
|
callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
|
|
460
|
-
images,
|
|
458
|
+
images:images.map(image=>({...image,modelVisibility:image.modelVisibility??"unproven"})), deliveredToMcp: true, evidence:"declared-lossy", unverifiableInContent: true,
|
|
461
459
|
rule: "mcp-image-placeholder-v1", exactModelConsumption: false,
|
|
462
460
|
});
|
|
463
461
|
pending.verified = true;
|
|
@@ -495,7 +493,9 @@ function attach(b: Binding, e: Episode, signal?: AbortSignal) {
|
|
|
495
493
|
}
|
|
496
494
|
}
|
|
497
495
|
const events = b.buffered.splice(0);
|
|
498
|
-
|
|
496
|
+
// These frames were already observed while detached. Preserve that single
|
|
497
|
+
// observation, but gate their normalization behind this request's response.
|
|
498
|
+
for (const event of events) e.hooks.enqueue(() => emitFrame(b, event));
|
|
499
499
|
}
|
|
500
500
|
function surface(b: Binding, inv: BridgeInvocation) {
|
|
501
501
|
const callId = (inv.metadata as any)?.callId;
|
|
@@ -539,8 +539,7 @@ function flushTools(b: Binding) {
|
|
|
539
539
|
const e=b.episode;
|
|
540
540
|
if (!b.batch || b.batchSurfaced || !b.batchSpec) return;
|
|
541
541
|
if (!e || e.ended) {fail(b,"Pi episode detached during committed MCP batch");return;}
|
|
542
|
-
const executable=b.batchSpec
|
|
543
|
-
if(!executable.length)return; // Keep streaming until the native rejection receipt.
|
|
542
|
+
const executable=b.batchSpec;
|
|
544
543
|
b.batchSurfaced=true;
|
|
545
544
|
if (e.textIndex !== undefined)
|
|
546
545
|
e.stream.push({
|
|
@@ -578,7 +577,7 @@ function flushTools(b: Binding) {
|
|
|
578
577
|
e.stream.end();
|
|
579
578
|
}
|
|
580
579
|
/** Live inference is explicit opt-in; echo always launches the offline provider. */
|
|
581
|
-
function
|
|
580
|
+
function streamEffective(model: any, input: any, options: any = {}) {
|
|
582
581
|
if(config.modelAllowed && !config.modelAllowed(model)){
|
|
583
582
|
const refused=createAssistantMessageEventStream();const output=message(model);output.stopReason="error";output.errorMessage="Muse model is not qualified for Pi prompt/compaction; select a catalogue-registered Spark 1.3 contributor, Wonder or Wonder Full route";
|
|
584
583
|
refused.push({type:"error",reason:"error",error:output});refused.end();return refused;
|
|
@@ -587,7 +586,26 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
587
586
|
const requestedMode = selectMode(model);
|
|
588
587
|
if (!context.tools.length) {
|
|
589
588
|
if (rawCompletionQualified(model))
|
|
590
|
-
return streamRawCompletion(model, context, options, message,
|
|
589
|
+
return streamRawCompletion(model, context, options, message, async hostOptions => {
|
|
590
|
+
const hooks=requestHooks(model,options,error=>hostOptions.onEvent?.({kind:"fenced",reason:error.message}));
|
|
591
|
+
const host=await openHost({...hostOptions,onEvent:event=>hooks.observe(event,()=>hostOptions.onEvent?.(event))});
|
|
592
|
+
return new Proxy(host,{get(target,key){
|
|
593
|
+
if(key==="submitInput")return async (...args:any[])=>{
|
|
594
|
+
try {
|
|
595
|
+
const ack=await (target.submitInput as any)(...args);
|
|
596
|
+
await hooks.admit("turn/start");
|
|
597
|
+
return ack;
|
|
598
|
+
} catch(error) {
|
|
599
|
+
// Admission can fence before the raw stream begins awaiting its
|
|
600
|
+
// terminal promise. Preserve the host's neutral no-replay reason.
|
|
601
|
+
if(target.fencedReason)throw new Error(target.fencedReason);
|
|
602
|
+
throw error;
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
const value=Reflect.get(target,key,target);
|
|
606
|
+
return typeof value==="function"?value.bind(target):value;
|
|
607
|
+
}});
|
|
608
|
+
}, "replace");
|
|
591
609
|
// Refuse before looking up or attaching the coding binding. A failed summary
|
|
592
610
|
// must not retire or settle an unrelated parked coding request.
|
|
593
611
|
const refused=createAssistantMessageEventStream();const output=message(model);
|
|
@@ -596,7 +614,11 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
596
614
|
}
|
|
597
615
|
const stream = createAssistantMessageEventStream();
|
|
598
616
|
const output = message(model);
|
|
599
|
-
const episode: Episode = { stream, output, ended: false
|
|
617
|
+
const episode: Episode = { stream, output, ended: false, hooks: requestHooks(model,options,error=>{
|
|
618
|
+
if(binding)fail(binding,error.message);
|
|
619
|
+
else {output.stopReason="error";output.errorMessage=error.message;stream.push({type:"error",reason:"error",error:output});stream.end();}
|
|
620
|
+
}) };
|
|
621
|
+
let binding: Binding | undefined;
|
|
600
622
|
void (async () => {
|
|
601
623
|
let b: Binding | undefined;
|
|
602
624
|
try {
|
|
@@ -653,25 +675,24 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
653
675
|
b = undefined;
|
|
654
676
|
}
|
|
655
677
|
if (b) {
|
|
678
|
+
binding = b;
|
|
656
679
|
b.episode = episode;
|
|
657
680
|
if (!b.batch) {
|
|
658
681
|
const delta = context.messages.slice(b.messages.length);
|
|
659
682
|
if (!delta.length || !delta.every((m:any)=>m.role === "user"))
|
|
660
683
|
throw new Error("Muse completed-turn continuation requires an exact append of user messages");
|
|
661
684
|
const text = museCurrentInput(delta);
|
|
662
|
-
stream.push({
|
|
685
|
+
episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
|
|
663
686
|
attach(b, episode, options.signal);
|
|
664
687
|
if (b.closed) return;
|
|
665
688
|
b.messages = structuredClone(context.messages);
|
|
666
689
|
b.requestHash=lastUserHash(context.messages);
|
|
667
690
|
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
691
|
await b.host!.submitInput(text, museEffort(options.reasoning));
|
|
692
|
+
await episode.hooks.admit("turn/start");
|
|
672
693
|
return;
|
|
673
694
|
}
|
|
674
|
-
const pendingBatch=b.batchSpec
|
|
695
|
+
const pendingBatch=b.batchSpec!;
|
|
675
696
|
if (pendingBatch.some(p=>p.journal)) throw new Error("Muse pending result already supplied");
|
|
676
697
|
const delta = context.messages.slice(b.messages.length),
|
|
677
698
|
assistant = delta[0],
|
|
@@ -720,12 +741,15 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
720
741
|
assertToolResultVerifiable(response);
|
|
721
742
|
return {pending,entry,response};
|
|
722
743
|
});
|
|
723
|
-
stream.push({
|
|
744
|
+
episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
|
|
724
745
|
attach(b, episode, options.signal);
|
|
725
746
|
if (b.closed) return;
|
|
726
747
|
b.messages = structuredClone(context.messages);
|
|
727
748
|
b.requestHash=lastUserHash(context.messages);
|
|
728
749
|
b.messageHash = historyHash(context.messages);
|
|
750
|
+
// The native suspended MCP request already exists. A response hook may
|
|
751
|
+
// refuse its continuation before any journaled result is delivered.
|
|
752
|
+
await episode.hooks.admit("suspended-mcp-continuation");
|
|
729
753
|
b.steeringPending=steering.length>0;
|
|
730
754
|
const consumed=steering.length?new Promise<void>(resolve=>{b!.receiptsDone=resolve;}):undefined;
|
|
731
755
|
for(const {pending,entry,response} of journaled){
|
|
@@ -762,8 +786,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
762
786
|
const bridge = createMcpBridge({
|
|
763
787
|
sessionId: key,
|
|
764
788
|
generation: randomUUID(),
|
|
789
|
+
argumentValidation: "pi",
|
|
765
790
|
tools,
|
|
766
|
-
onInvocation: (inv) => surface(candidate, inv),
|
|
791
|
+
onInvocation: (inv) => candidate.episode!.hooks.enqueue(()=>surface(candidate, inv)),
|
|
767
792
|
});
|
|
768
793
|
candidate = {
|
|
769
794
|
key,
|
|
@@ -776,7 +801,6 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
776
801
|
park: parking && Boolean(sessionManager?.getSessionFile?.()),
|
|
777
802
|
reservations,
|
|
778
803
|
tools,
|
|
779
|
-
schemaRefusals:new Map(),
|
|
780
804
|
approvalHolds:new Map(),
|
|
781
805
|
buffered: [],
|
|
782
806
|
closed: false,
|
|
@@ -786,8 +810,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
786
810
|
abort: new AbortController(),
|
|
787
811
|
};
|
|
788
812
|
b = candidate;
|
|
813
|
+
binding = b;
|
|
789
814
|
bindings.set(key, b);
|
|
790
|
-
stream.push({
|
|
815
|
+
episode.hooks.enqueue(()=>stream.push({type:"start",partial:output}));
|
|
791
816
|
attach(b, episode, options.signal);
|
|
792
817
|
if (b.closed) return;
|
|
793
818
|
const descriptor = await bridge.start();
|
|
@@ -840,15 +865,6 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
840
865
|
if (!tool || !request.toolCallId) return false;
|
|
841
866
|
try {
|
|
842
867
|
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
868
|
const spec=candidate.batchSpec?.find(c=>c.callId===request.toolCallId);
|
|
853
869
|
if(candidate.closed || (candidate.batchSpec && (!spec || spec.verified || spec.name!==request.toolName || canonical(spec.args)!==canonical(args))))return false;
|
|
854
870
|
const previous = reservations.get(request.toolCallId);
|
|
@@ -869,7 +885,7 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
869
885
|
return false;
|
|
870
886
|
}
|
|
871
887
|
},
|
|
872
|
-
onEvent: (event: any) => emitFrame(candidate, event),
|
|
888
|
+
onEvent: (event: any) => candidate.episode!.hooks.observe(event,()=>emitFrame(candidate, event)),
|
|
873
889
|
}));
|
|
874
890
|
b.host = host;
|
|
875
891
|
host.ledger?.beginEpisode();
|
|
@@ -878,8 +894,9 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
878
894
|
return;
|
|
879
895
|
}
|
|
880
896
|
await host.submitInput(text, museEffort(options.reasoning));
|
|
897
|
+
await episode.hooks.admit("turn/start");
|
|
881
898
|
} catch (error: any) {
|
|
882
|
-
const reason = String(error?.message || error);
|
|
899
|
+
const reason = b?.host?.fencedReason ?? String(error?.message || error);
|
|
883
900
|
if (b) { b.episode = episode; fail(b, reason); }
|
|
884
901
|
else {
|
|
885
902
|
episode.ended = true;
|
|
@@ -896,6 +913,28 @@ function streamViaMuse(model: any, input: any, options: any = {}) {
|
|
|
896
913
|
})();
|
|
897
914
|
return stream;
|
|
898
915
|
}
|
|
916
|
+
function streamViaMuse(model:any,input:any,options:any={}) {
|
|
917
|
+
const stream=createAssistantMessageEventStream();
|
|
918
|
+
void (async()=>{
|
|
919
|
+
try {
|
|
920
|
+
// Expose the logical official-client request, not an invented HTTP body.
|
|
921
|
+
const payload={...structuredClone(piContext(input)),transport:"official-muse-client"};
|
|
922
|
+
const replacement=await options.onPayload?.(payload,model);
|
|
923
|
+
const effective=replacement===undefined?payload:replacement;
|
|
924
|
+
if(!effective || typeof effective!=="object" || !Array.isArray(effective.messages) || !Array.isArray(effective.tools) || typeof effective.systemPrompt!=="string")
|
|
925
|
+
throw new Error("Muse onPayload must return a logical request with systemPrompt, messages and tools");
|
|
926
|
+
if(effective.messages.some((entry:any)=>entry?.role==="system"))
|
|
927
|
+
throw new Error("Muse logical payload messages exclude system messages; edit logical systemPrompt and tools instead");
|
|
928
|
+
const request={...effective,tools:effective.tools.map((tool:any,index:number)=>index ? tool : ({...tool,description:`${tool.description??""}\n\nTransport notice: [REDACTED] in tool text can be official-client redaction; original bytes in those spans are unavailable. Tool images are delivered without pixel attestation; GIF/WebP visibility is unqualified. Images attached to failed tool results are omitted by the official client.`}))};
|
|
929
|
+
for await(const event of streamEffective(model,request,options))stream.push(event);
|
|
930
|
+
stream.end();
|
|
931
|
+
} catch(error:any) {
|
|
932
|
+
const output=message(model);output.stopReason=options.signal?.aborted?"aborted":"error";output.errorMessage=String(error?.message??error);
|
|
933
|
+
stream.push({type:"error",reason:output.stopReason,error:output});stream.end();
|
|
934
|
+
}
|
|
935
|
+
})();
|
|
936
|
+
return stream;
|
|
937
|
+
}
|
|
899
938
|
return {streamViaMuse,setSessionManager,retireAll,rawCompletionQualified,committedCompaction};
|
|
900
939
|
}
|
|
901
940
|
// Qualified against official Muse 1.4.14: private settings + explicit
|
package/src/request-ledger.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
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
|
};
|
|
@@ -1,70 +1,95 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import type { BridgeResult } from "pi-tether-core/mcp/bridge";
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* an
|
|
6
|
-
export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string };
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
4
|
+
/** MSP folds text chunks with LF boundaries and emits image metadata,
|
|
5
|
+
* never an attestation of pixels. Keep original parts for the Pi journal. */
|
|
6
|
+
export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string; modelVisibility?: "omitted-error-result" };
|
|
7
|
+
const imageMagic: Record<string, (b: Buffer) => boolean> = {
|
|
8
|
+
"image/png": b => b.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])),
|
|
9
|
+
"image/jpeg": b => b[0] === 255 && b[1] === 216 && b[2] === 255,
|
|
10
|
+
"image/gif": b => ["GIF87a", "GIF89a"].includes(b.subarray(0,6).toString("ascii")),
|
|
11
|
+
"image/webp": b => b.subarray(0,4).toString("ascii") === "RIFF" && b.subarray(8,12).toString("ascii") === "WEBP",
|
|
12
|
+
};
|
|
13
|
+
function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
|
|
14
|
+
const images: UnverifiableImage[] = [];
|
|
15
|
+
for (const [partIndex, part] of sent.content.entries()) {
|
|
16
|
+
if (part.type === "text" && typeof part.text === "string") continue;
|
|
17
|
+
if (part.type !== "image" || !part.data || !imageMagic[part.mimeType])
|
|
18
|
+
throw new Error("Muse tool result cannot verify MCP parts: unsupported image or content type");
|
|
19
|
+
const bytes = Buffer.from(part.data, "base64");
|
|
20
|
+
if (bytes.toString("base64") !== part.data || !imageMagic[part.mimeType](bytes))
|
|
21
|
+
throw new Error("Muse tool result cannot verify MCP parts: malformed image encoding or MIME signature");
|
|
22
|
+
images.push({ partIndex, sha256: createHash("sha256").update(bytes).digest("hex"), byteLen: bytes.length, mimeType: part.mimeType,
|
|
23
|
+
...(sent.isError === true ? {modelVisibility: "omitted-error-result" as const} : {}) });
|
|
24
|
+
}
|
|
25
|
+
return images;
|
|
16
26
|
}
|
|
17
27
|
export function assertToolResultVerifiable(sent: BridgeResult): void {
|
|
18
|
-
|
|
19
|
-
const multiText = sent.isError !== true && sent.content.length > 1 && sent.content.every(p => p.type === "text" && p.text.length > 0);
|
|
20
|
-
if (!singleText && !multiText && !imageDeclaration(sent)) {
|
|
21
|
-
const kinds = sent.content.map(p => p.type).join(",");
|
|
22
|
-
throw new Error(`Muse tool result cannot verify MCP parts [${kinds}]: MSP visibleOutput flattens text; modelVisibleContent exposes image metadata, not bytes or part boundaries`);
|
|
23
|
-
}
|
|
28
|
+
imageDeclarations(sent);
|
|
24
29
|
}
|
|
25
30
|
export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void): BridgeResult {
|
|
26
|
-
|
|
27
|
-
if (
|
|
31
|
+
const images = imageDeclarations(sent);
|
|
32
|
+
if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
|
|
28
33
|
if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
|
|
29
34
|
if (item.truncated && stored === undefined) throw new Error("Muse truncated tool result has no verifiable full outputRef readback");
|
|
30
35
|
const output = stored ?? item.visibleOutput;
|
|
31
|
-
if (stored !== undefined)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
36
|
+
if (stored !== undefined && (item.truncated ? !stored.startsWith(item.visibleOutput) : stored !== item.visibleOutput))
|
|
37
|
+
throw new Error("Muse stored tool output differs from visibleOutput");
|
|
38
|
+
let actual = output;
|
|
35
39
|
if (sent.isError === true) {
|
|
36
|
-
// ENOENT-style error frame: failed + verbatim failureReason; the display adds this prefix.
|
|
37
40
|
if (item.status !== "failed" || item.failureKind !== undefined || typeof item.failureReason !== "string")
|
|
38
41
|
throw new Error("Muse MCP error receipt requires failed status and verbatim failureReason without a host failureKind");
|
|
39
42
|
if (output !== `tool failed: ${item.failureReason}`) throw new Error("Muse MCP error visibleOutput differs from failureReason");
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined)
|
|
43
|
+
actual = item.failureReason;
|
|
44
|
+
} else if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined) {
|
|
43
45
|
throw new Error("Muse successful MCP receipt has non-completed status or failure fields");
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
46
|
+
}
|
|
47
|
+
// Construct the ordered native projection from Pi parts. Never search/remove
|
|
48
|
+
// placeholder-shaped strings: literal tool text and leading LF remain bytes.
|
|
49
|
+
let expected = "";
|
|
50
|
+
const protectedImages: { start: number; end: number }[] = [];
|
|
51
|
+
for (const [index, part] of sent.content.entries()) {
|
|
52
|
+
if (part.type === "text") {
|
|
53
|
+
// Native string folding ignores leading empty chunks but preserves a
|
|
54
|
+
// separator before an empty chunk after nonempty output (captured live).
|
|
55
|
+
expected += (expected ? "\n" : "") + part.text;
|
|
56
|
+
} else {
|
|
57
|
+
// The official client's failed MCP path projects text only. Images were
|
|
58
|
+
// delivered to MCP, NOT exposed to the model; declare that known loss.
|
|
59
|
+
if (sent.isError === true) continue;
|
|
60
|
+
const image = images.find(image => image.partIndex === index)!;
|
|
61
|
+
if (expected) expected += "\n";
|
|
62
|
+
const start = expected.length;
|
|
63
|
+
expected += `[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]`;
|
|
64
|
+
protectedImages.push({ start, end: expected.length });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// Failed MCP results use a separate native codec: all text parts are
|
|
68
|
+
// LF-joined (including leading empties), and images are dropped.
|
|
69
|
+
if (sent.isError === true) {
|
|
70
|
+
expected = sent.content.filter(part => part.type === "text").map(part => (part as {text:string}).text).join("\n");
|
|
71
|
+
if (!expected) expected = "MCP tool returned an error";
|
|
72
|
+
} else if (!expected) expected = "[MCP tool returned no content]";
|
|
73
|
+
const projected: BridgeResult = { content: [{ type: "text", text: expected }], isError: sent.isError === true };
|
|
54
74
|
let redactions: VendorRedaction[] = [];
|
|
55
|
-
const
|
|
56
|
-
if ((
|
|
57
|
-
|
|
58
|
-
|
|
75
|
+
const observed = reconcileVendorRedactions(projected, { content: [{ type: "text", text: actual }], isError: sent.isError === true }, spans => { redactions = spans; });
|
|
76
|
+
if ((observed.content[0] as { text: string }).text !== expected)
|
|
77
|
+
throw new Error("Muse tool result text projection mismatch (image placeholder differs or text changed)");
|
|
78
|
+
for (const span of redactions) {
|
|
79
|
+
if (protectedImages.some(range => span.piOffsetBytes < Buffer.byteLength(expected.slice(0, range.end)) &&
|
|
80
|
+
span.piOffsetBytes + span.piByteLen > Buffer.byteLength(expected.slice(0, range.start))))
|
|
81
|
+
throw new Error("Muse image placeholder differs: redaction cannot hide image metadata");
|
|
82
|
+
}
|
|
59
83
|
if (redactions.length) onRedactions?.(redactions);
|
|
60
|
-
if (
|
|
61
|
-
//
|
|
62
|
-
//
|
|
84
|
+
if (images.length) onImages?.(images);
|
|
85
|
+
// modelVisibleContent may contain image derivatives or metadata. It is useful
|
|
86
|
+
// evidence of delivery but never upgrades these declarations to exact pixels.
|
|
63
87
|
return sent;
|
|
64
88
|
}
|
|
65
89
|
|
|
66
|
-
/** Byte offsets address
|
|
67
|
-
*
|
|
90
|
+
/** Byte offsets address the constructed native Pi-parts projection and the
|
|
91
|
+
* actual Muse receipt. Image metadata occupies protected positions in this
|
|
92
|
+
* projection; no declared loss may cover those positions.
|
|
68
93
|
* Never include removed text in metadata. This is declared vendor loss, NOT
|
|
69
94
|
* proof that the model consumed the original bytes. */
|
|
70
95
|
export type VendorRedaction = { piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string };
|
|
@@ -76,7 +101,7 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
76
101
|
// DECLARED LOSSY TRANSPORT ACCEPTANCE, not verification of removed bytes.
|
|
77
102
|
// The pinned binary exposes the marker and token prefixes, but not a complete
|
|
78
103
|
// provable runtime pattern set. Conservative fallback: unique alignment,
|
|
79
|
-
// nonempty single-line removed spans
|
|
104
|
+
// nonempty single-line removed spans with unique positional alignment, including line edges.
|
|
80
105
|
// Literal Pi markers must match literally and may never be swallowed by a gap.
|
|
81
106
|
type Span = { piStart: number; piEnd: number; museStart: number };
|
|
82
107
|
const invalid = () => new Error("Muse tool result mismatch: invalid or ambiguous vendor redaction");
|
|
@@ -97,8 +122,23 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
97
122
|
}
|
|
98
123
|
return found;
|
|
99
124
|
}
|
|
100
|
-
function lineSpans(text: string, visible: string): Span[] {
|
|
101
|
-
|
|
125
|
+
function lineSpans(text: string, visible: string, groupAdjacent = true): Span[] {
|
|
126
|
+
// Adjacent vendor markers declare one combined loss region. Their internal
|
|
127
|
+
// split is unknowable; the combined nonempty region still aligns uniquely.
|
|
128
|
+
const pieces: string[] = [], widths: number[] = [];
|
|
129
|
+
let cursor = 0, at: number;
|
|
130
|
+
while ((at = visible.indexOf(marker, cursor)) !== -1) {
|
|
131
|
+
pieces.push(visible.slice(cursor, at));
|
|
132
|
+
cursor = at;
|
|
133
|
+
let width = 0;
|
|
134
|
+
while (visible.startsWith(marker, cursor)) {
|
|
135
|
+
width++; cursor += marker.length;
|
|
136
|
+
if (!groupAdjacent) break;
|
|
137
|
+
}
|
|
138
|
+
widths.push(width);
|
|
139
|
+
}
|
|
140
|
+
pieces.push(visible.slice(cursor));
|
|
141
|
+
const n = text.length;
|
|
102
142
|
if (pieces.length === 1 || !text.startsWith(pieces[0])) throw invalid();
|
|
103
143
|
// Each backward layer counts complete parses after one marker. Range sums
|
|
104
144
|
// make a variable-length hole O(1) per position: O(n * markerCount), not
|
|
@@ -119,13 +159,16 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
119
159
|
const current = new Uint8Array(n + 1), choice = new Int32Array(n + 1); choice.fill(-2);
|
|
120
160
|
for (let a = 0; a <= n; a++) {
|
|
121
161
|
if (text.startsWith(marker, a)) {
|
|
122
|
-
const end = a + marker.length;
|
|
162
|
+
const end = a + marker.length * widths[i];
|
|
163
|
+
if (!text.startsWith(marker.repeat(widths[i]), a)) continue;
|
|
123
164
|
current[a] = matches[end] ? next[end + chunk.length] ?? 0 : 0;
|
|
124
165
|
if (current[a] === 1) choice[a] = -1; // literal marker, never a hole
|
|
125
|
-
} else if (
|
|
126
|
-
const
|
|
166
|
+
} else if (barrier[a] > a) {
|
|
167
|
+
const minimumEnd = a + 1;
|
|
168
|
+
if (minimumEnd > barrier[a]) continue;
|
|
169
|
+
const ways = sum[minimumEnd] - sum[barrier[a] + 1];
|
|
127
170
|
current[a] = Math.min(2, ways);
|
|
128
|
-
if (ways === 1) choice[a] = first[
|
|
171
|
+
if (ways === 1) choice[a] = first[minimumEnd];
|
|
129
172
|
}
|
|
130
173
|
}
|
|
131
174
|
choices[i] = choice; next = current;
|
|
@@ -136,8 +179,8 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
136
179
|
for (let i = 0; i < choices.length; i++) {
|
|
137
180
|
const end = choices[i][a];
|
|
138
181
|
if (end >= 0) spans.push({ piStart: a, piEnd: end, museStart: b });
|
|
139
|
-
a = (end === -1 ? a + marker.length : end) + pieces[i + 1].length;
|
|
140
|
-
b += marker.length + pieces[i + 1].length;
|
|
182
|
+
a = (end === -1 ? a + marker.length * widths[i] : end) + pieces[i + 1].length;
|
|
183
|
+
b += marker.length * widths[i] + pieces[i + 1].length;
|
|
141
184
|
}
|
|
142
185
|
return spans;
|
|
143
186
|
}
|
|
@@ -145,8 +188,19 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
145
188
|
if (piLines.length !== museLines.length) throw invalid();
|
|
146
189
|
const aligned: Span[] = []; let piBase = 0, museBase = 0;
|
|
147
190
|
for (let i = 0; i < piLines.length; i++) {
|
|
148
|
-
if (piLines[i] !== museLines[i])
|
|
149
|
-
|
|
191
|
+
if (piLines[i] !== museLines[i]) {
|
|
192
|
+
let spans: Span[];
|
|
193
|
+
try { spans = lineSpans(piLines[i], museLines[i]); }
|
|
194
|
+
catch (error) {
|
|
195
|
+
// A contiguous visible marker run may mix exact literal Pi markers
|
|
196
|
+
// with a redaction beside them. Retry individual tokens only when Pi
|
|
197
|
+
// actually contains a literal; require the same unique alignment.
|
|
198
|
+
if (!piLines[i].includes(marker)) throw error;
|
|
199
|
+
spans = lineSpans(piLines[i], museLines[i], false);
|
|
200
|
+
}
|
|
201
|
+
for (const s of spans)
|
|
202
|
+
aligned.push({ piStart: piBase + s.piStart, piEnd: piBase + s.piEnd, museStart: museBase + s.museStart });
|
|
203
|
+
}
|
|
150
204
|
piBase += piLines[i].length + 1; museBase += museLines[i].length + 1;
|
|
151
205
|
}
|
|
152
206
|
if (!aligned.length) throw invalid();
|