pi-muse-tether 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ - Long or redacted tool results no longer kill the turn: complete `[REDACTED]` lines and Muse's 64 KiB view truncation (including one-line results) are reconciled against Pi's original result. Unsupported vendor transformations still stop safely.
6
+ - Support qualified Muse Code 1.4.15-R8339.1 alongside 1.4.14-R7309.1, including session MCP readiness and canonical private-workspace trust paths.
7
+ - Expose the full valid provider catalogue (Ember and Spark 1.2 appear); offer contributor picker routes only for verified model recipes (Spark 1.3/1.2, Wonder, Wonder Full), without guessing support for unknown models.
8
+ - Newer Muse Code clients warn instead of disappearing from `/model`; `PI_MUSE_TETHER_STRICT_VERSION=1` refuses them. Coding still requires a qualified client build.
9
+ - After switching an existing install to 1.4.15, run one Muse turn so the client rewrites its saved model list in the new format; until then the client serves only its built-in list.
10
+
3
11
  ## 0.1.1
4
12
 
5
13
  - Pi's provider hooks now fire.
package/README.md CHANGED
@@ -6,8 +6,8 @@ Use your Muse Code subscription in [Pi](https://github.com/earendil-works/pi), t
6
6
  Hi, I do most of my work in Pi and I also pay for Muse Code. While Meta has not been magnanimous enough to let us use our subscription directly in third-party harnesses, it still offers an [official SDK](https://github.com/meta-models/muse-code-sdk) for building clients around its installed coding agent. Pi is my main harness and I don't want to be swapping coding agents, and most importantly I don't want to juggle identities and system prompts. The goal of this tether is to unlock the high limits a subscription allows while using your own Pi custom prompt as much as possible, staying lighter on the system prompt than the less-than-optimal vendor harnesses, and not having to go through the API. I wrote it with a coding agent.
7
7
 
8
8
  <picture>
9
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/kyraneth/pi-muse-tether/main/assets/flow-dark.svg">
10
- <img alt="Pi sends the prompt, tools and history through the tether and the official Muse client to the model. A tool call comes back the same way to Pi, which runs the tool and saves the result. The result then goes back to the model." width="700" src="https://raw.githubusercontent.com/kyraneth/pi-muse-tether/main/assets/flow-light.svg">
9
+ <source media="(prefers-color-scheme: dark)" srcset="assets/flow-dark.svg">
10
+ <img alt="Pi sends the prompt, tools and history through the tether and the official Muse client to the model. A tool call comes back the same way to Pi, which runs the tool and saves the result. The result then goes back to the model." width="700" src="assets/flow-light.svg">
11
11
  </picture>
12
12
 
13
13
  ## Who it's for
@@ -16,7 +16,7 @@ This is for you if you've built your workflow around Pi, with your own system pr
16
16
 
17
17
  ## Install
18
18
 
19
- Sign in with the official Muse Code client first. You need Node 24 or newer. I tested this with Pi 1.5.0 and Muse Code 1.4.14, and other versions may be refused.
19
+ Sign in with the official Muse Code client first. You need Node 24 or newer. I tested this with Pi 1.5.0 and Muse Code 1.4.14 and 1.4.15; see the version policy below.
20
20
 
21
21
  ```sh
22
22
  pi install npm:pi-muse-tether
@@ -25,13 +25,29 @@ PI_MUSE_TETHER_LIVE=1 pi --provider pi-muse-tether --model muse-spark-1.3
25
25
 
26
26
  Keep `PI_MUSE_TETHER_LIVE=1` set whenever you want to use Muse. Without it you only get an offline test model. If it worked, the Muse models your account can use appear under `pi-muse-tether` in `/model`, and `/muse-doctor` shows the local versions it found.
27
27
 
28
+ ## Muse Code version policy
29
+
30
+ The minimum client is **1.4.14**, the oldest version qualified for the tether’s private-XDG prompt/isolation recipe. The tested ceiling is **1.4.15**. Older or unparseable clients are refused. Newer clients warn once per version per Pi process and continue, **not yet qualified**, including private-settings prompt delivery. Set `PI_MUSE_TETHER_STRICT_VERSION=1` to refuse clients above the tested ceiling instead. `/muse-doctor` reports the range and whether the installed client exceeds it. This policy never updates your client.
31
+
32
+ The SDK remains independently pinned to **`@muse-code/sdk` 1.4.14**; it need not equal the client version. This permits forward client use, not a claim of SDK/client compatibility qualification. The experimental `rawLog`/committed-tool-batch protocol is different: its payload is qualified per exact build, currently **1.4.14-R7309.1** and **1.4.15-R8339.1**, so it refuses every other build even when catalogue discovery and non-batch sessions are allowed with a warning. **Shipped live coding sessions use this batch protocol by default**, so on an unqualified newer build the picker can populate but live coding still refuses before submission. There is no silent single-tool fallback.
33
+
34
+ Muse 1.4.15 changed two things the tether now handles. It starts session tool servers after `session/start` returns, so the tether waits (via `mcpServer/readInventory`) until its tool server is connected with every Pi tool before the first turn; a withheld or failed server stops before any model request. It also starts session tool servers only in a trusted workspace. The tether names an empty, private, tether-owned workspace and trusts only that one; it never trusts your project, because a trusted project also loads its rules files (for example `AGENTS.md`) into the model. Pi still owns the working directory and every tool path.
35
+
36
+ ## Models in the picker
37
+
38
+ With live mode enabled, the tether reads the official client’s `model/list`. Every valid Muse catalogue row appears with its own context/output limits and supported thinking levels; there is no model allowlist. New client models do not need a tether code change. The catalogue is read again after each agent run, and the provider is re-registered only when the exposed models or their metadata change. Discovery failure removes live entries, keeps the offline `echo` model, and is reported by `/muse-doctor`.
39
+
40
+ Each catalogue `<id>` offers its normal route (contributor mode off). Only models with verified contributor support also offer `<id>-contributor` (Contributor, mode on): currently Spark 1.3, Spark 1.2, Wonder 1.0 and Wonder Full 1.0. **Ember 1.0 has only a Normal route**: the client ignores contributor mode for Ember and the API has no Ember contributor model. Future models appear normally without a tether update; contributor routes require verifying the client's on/off wire model and the contributor model's API support, then adding the native ID to the documented `VERIFIED_CONTRIBUTOR_MODEL_IDS` constant in `src/model-route.ts`. For backward compatibility, **`muse-spark-1.3` stays contributor-on**, labelled Contributor; `muse-spark-1.3-contributor` is an explicit alias for that same native model and mode. Existing Wonder names and modes are unchanged. Contributor suffixes select CLI recipes, not native catalogue IDs. The `-contributor` suffix is reserved for these local routes: a native catalogue row using it is skipped with a named `/muse-doctor` diagnostic, without hiding other models.
41
+
42
+ Only thinking levels present in that model’s catalogue are offered; unsupported levels are refused before submission (for example, Spark 1.2 `max`). Unknown prices remain `null`, labelled **pricing unknown**; no model borrows another’s rates. Assistant messages report `responseModel` from the selected recipe: the native ID for Normal, or `<id>-contributor` for Contributor. Its source is marked derived, not response-attested; catalogue availability alone does not prove physical response identity or contributor support.
43
+
28
44
  ## How it works
29
45
 
30
46
  The tether starts the official Muse client in the background and passes it Pi's system prompt, tools and history. When the model asks for a tool, the call comes back to Pi, as the diagram shows. Pi runs it under its normal guards and saves the result to its own history, and only then does the tether send the result back to Muse.
31
47
 
32
48
  ## How close it is to the direct API
33
49
 
34
- I ran two real coding tasks through each route, once per route, on a build from just before this release. These are single runs, so read them as a rough comparison. [How I measured](https://github.com/kyraneth/pi-muse-tether/blob/main/docs/DETAILS.md#how-i-measured).
50
+ I ran two real coding tasks through each route, once per route, on a build from just before this release. These are single runs, so read them as a rough comparison. [How I measured](docs/DETAILS.md#how-i-measured).
35
51
 
36
52
  | | Tether | Direct API |
37
53
  |---|---|---|
@@ -55,11 +71,11 @@ The last row is the difference you will notice most.
55
71
 
56
72
  - 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
73
  - You need control over retries. Muse retries some server errors by itself, and I found no way to turn that off.
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
- - 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).
74
+ - Your tool results must reach the model unchanged. Muse sometimes replaces secret-looking text with `[REDACTED]`, even in harmless prose. Declared loss continues with source/position evidence in the ledger, including uncertain alignments; it does not prove the model saw the original. Literal markers may already be source text.
75
+ - 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](docs/DETAILS.md).
60
76
  - 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
77
  - 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
78
 
63
79
  ## More
64
80
 
65
- This is an independent project, and neither Muse nor Meta made it. The technical details are in [docs/DETAILS.md](https://github.com/kyraneth/pi-muse-tether/blob/main/docs/DETAILS.md). Please report problems in the [issues](https://github.com/kyraneth/pi-muse-tether/issues). [MIT license](https://github.com/kyraneth/pi-muse-tether/blob/main/LICENSE).
81
+ This is an independent project, and neither Muse nor Meta made it. The technical details are in [docs/DETAILS.md](docs/DETAILS.md). Please report problems in the [issues](https://github.com/kyraneth/pi-muse-tether/issues). [MIT license](LICENSE).
package/docs/DETAILS.md CHANGED
@@ -4,7 +4,7 @@ Use Muse Code models in [Pi](https://github.com/earendil-works/pi) through the o
4
4
 
5
5
  ## Install and first use
6
6
 
7
- Requires Node.js 24+, Pi 1.5.0, the official Muse Code 1.4.14 client (qualified build R7309.1), and an account entitled to the selected model. The adapter pins `@muse-code/sdk` 1.4.14. Other versions are not qualified and may be refused.
7
+ Requires Node.js 24+, Pi 1.5.0, the official Muse Code client, and an account entitled to the selected model. Qualified builds are 1.4.14-R7309.1 and 1.4.15-R8339.1 for private prompt settings, session MCP and experimental rawLog committed tool batches. The 1.4.15 qualification includes asynchronous MCP readiness and an Ember tool-batch workload; it does not establish equal workload coverage for every model. The adapter independently pins `@muse-code/sdk` 1.4.14. Newer ordinary clients warn (strict mode refuses); experimental batches remain exact-build gated.
8
8
 
9
9
  ```sh
10
10
  pi install npm:pi-muse-tether
@@ -73,7 +73,7 @@ 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 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.
76
+ Declared redaction needs at least one positional alignment with nonempty single-line holes. Line-start, line-end and whole-line loss continue as declared-lossy; adjacent markers form one combined region, without claiming an internal split. Ambiguous alignments also continue: evidence records all viable start/end boundaries and the covering source range, explicitly marked ambiguous rather than inventing an exact removal. If that region swallows literal source markers their identity is likewise uncertain; unchanged literal markers alone never declare loss. The pinned client also canonicalizes a case-insensitive `bearer ` prefix to `Bearer ` immediately before a redaction. That narrowly located codec transformation is separately hashed and declared, not treated as permission to normalize arbitrary text. Newline removal, impossible alignment, changed text outside the declared regions, status changes and image metadata changes still fence. Surrounding bytes are verified, not bytes inside holes or whether they were secrets. Ledger rows link native/Pi call IDs, journal entry, tool/source path and original part byte ranges; ambiguous ranges retain candidate boundaries. Diagnostics contain offsets, lengths and hashes, never removed text. `exactModelConsumption:false` never attests consumption of the original bytes.
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
79
 
package/index.ts CHANGED
@@ -18,22 +18,24 @@ 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
- 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
- }
27
- const liveModels = catalog ? museCatalogModels(catalog) : [];
28
- const catalogueDiagnostics = catalog ? museCatalogAssessment(catalog).diagnostics :
29
- { status: catalogueError ? "discovery failed" : "live disabled", ...(catalogueError ? {error: catalogueError} : {}) };
21
+ const discover = async () => {
22
+ if (process.env.PI_MUSE_TETHER_LIVE !== "1")
23
+ return {models: [], diagnostics: {status: "live disabled"}};
24
+ try {
25
+ const catalog = await discoverMuseCatalog();
26
+ return {models: museCatalogModels(catalog), diagnostics: museCatalogAssessment(catalog).diagnostics};
27
+ } catch (error) {
28
+ return {models: [], diagnostics: {status: "discovery failed", error: error instanceof Error ? error.message : String(error)}};
29
+ }
30
+ };
31
+ let catalogue = await discover();
30
32
  registerApiDispatch(ID, stream);
31
- pi.registerProvider(ID, {
33
+ const registerProvider = () => pi.registerProvider(ID, {
32
34
  api: ID,
33
35
  apiKey: "unused",
34
36
  baseUrl: "pi-muse-tether",
35
37
  models: [
36
- ...liveModels,
38
+ ...catalogue.models,
37
39
  {
38
40
  id: "echo",
39
41
  name: "Muse echo (offline fixture)",
@@ -46,7 +48,18 @@ export async function registerMuseExtension(pi: ExtensionAPI, provider = {stream
46
48
  ],
47
49
  streamSimple: stream,
48
50
  });
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");}});
51
+ registerProvider();
52
+ // Lifecycle refresh, not a timer or inference request. Also compare metadata:
53
+ // changed limits/efforts must reach Pi even when the IDs have not changed.
54
+ const modelShape = (models: typeof catalogue.models) =>
55
+ JSON.stringify([...models].sort((a, b) => a.id.localeCompare(b.id)));
56
+ pi.on("agent_end", async () => {
57
+ const next = await discover();
58
+ const changed = modelShape(next.models) !== modelShape(catalogue.models);
59
+ catalogue = next;
60
+ if (changed) registerProvider();
61
+ });
62
+ 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:catalogue.diagnostics},null,2),"info");}});
50
63
  pi.on("session_start", async (_event, ctx) => {
51
64
  setQuotaListener(payload=>ctx.ui.setStatus("muse-rate-limit",quotaStatusLine(payload)));
52
65
  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.1",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Use your Muse Code subscription in Pi through the official client",
6
6
  "license": "MIT",
package/src/catalog.ts CHANGED
@@ -1,17 +1,8 @@
1
1
  import { museThinkingLevelMap } from "./thinking-config.js";
2
2
  import { museModelCost } from "./usage.js";
3
+ import { isMuseModelId, museModelRoute } from "./model-route.js";
3
4
  export { isQualifiedMuseModel, museResponseIdentity } from "./model-route.js";
4
5
 
5
- /** Supported official logical IDs, never invented contributor aliases. Limits
6
- * and efforts come exclusively from the receiving official model/list. */
7
- export const MUSE_MODEL_GROUPS = [
8
- ["muse-spark-1.3", "muse-spark-1.3-contributor"],
9
- ["muse-wonder-1.0"],
10
- ["muse-wonder-full-1.0"],
11
- ] as const;
12
- const isCatalogueModel = (id: string) =>
13
- MUSE_MODEL_GROUPS.some(group => (group as readonly string[]).includes(id));
14
-
15
6
  /** Diagnosis only, no workaround: an official client may receive no models
16
7
  * on one network path while the same account works on another. */
17
8
  export const EMPTY_CATALOGUE_HINT = ". The official Muse client received an empty model catalogue. "
@@ -19,9 +10,15 @@ export const EMPTY_CATALOGUE_HINT = ". The official Muse client received an empt
19
10
  + "account works elsewhere, Meta may be refusing this network path (seen on datacenter IPv6); "
20
11
  + "see the pi-muse-tether README section \"Empty catalogue on some cloud networks\"";
21
12
 
13
+ /** Contributor suffixes belong to the picker, never the native namespace. */
14
+ function catalogueIdProblem(id: unknown): string | undefined {
15
+ if (!isMuseModelId(id)) return "invalid Muse model ID shape";
16
+ if (id.endsWith("-contributor")) return "reserved local -contributor suffix";
17
+ }
18
+
22
19
  export function museCatalogAssessment(catalog: any) {
23
20
  const rows: any[] = Array.isArray(catalog?.models) ? catalog.models : [];
24
- const valid = (catalog?.source === "providerCatalog" ? rows : []).filter(m => m && typeof m === "object" && isCatalogueModel(m.modelId) &&
21
+ const valid = (catalog?.source === "providerCatalog" ? rows : []).filter(m => m && typeof m === "object" && !catalogueIdProblem(m.modelId) &&
25
22
  m.providerId === "meta" && typeof m.displayLabel === "string" && m.displayLabel.length &&
26
23
  Number.isSafeInteger(m.contextLimit) && m.contextLimit > 0 &&
27
24
  Number.isSafeInteger(m.outputLimit) && m.outputLimit > 0 &&
@@ -29,23 +26,29 @@ export function museCatalogAssessment(catalog: any) {
29
26
  m.variants.every((tier: unknown) => typeof tier === "string" &&
30
27
  Object.values(museThinkingLevelMap([tier])).includes(tier)) &&
31
28
  m.variants.includes(m.defaultReasoningEffort));
32
- const missing = MUSE_MODEL_GROUPS.filter(group => !valid.some(m => (group as readonly string[]).includes(m.modelId)));
33
29
  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})),
30
+ profileId: catalog?.profileId ?? null,
31
+ rejectedRoutes: rows.flatMap(m => {
32
+ const reason = catalogueIdProblem(m?.modelId);
33
+ return reason ? [`${String(m?.modelId)}: ${reason}`] : [];
34
+ }), models: rows.map(m => ({modelId:m?.modelId,contextLimit:m?.contextLimit,outputLimit:m?.outputLimit,variants:m?.variants})),
35
35
  ...(!rows.length ? {hint:EMPTY_CATALOGUE_HINT} : {}) } };
36
36
  }
37
37
 
38
38
  export function museCatalogModels(catalog: any) {
39
39
  const {valid} = museCatalogAssessment(catalog);
40
- return valid.flatMap(m => (m.modelId.includes("wonder") ? ["off", "on"] : ["on"]).map(contributorMode => ({
41
- id: m.modelId.includes("wonder") && contributorMode === "on" ? `${m.modelId}-contributor` : m.modelId,
42
- name: `${m.displayLabel} · ${contributorMode === "on" ? "Contributor" : "Normal"}${museModelCost(m.modelId).input === null ? " · pricing unknown" : ""}`,
43
- reasoning: m.variants.some((tier: string) => tier !== "none"),
44
- input: ["text", "image"] as ("text" | "image")[],
45
- thinkingLevelMap: museThinkingLevelMap(m.variants),
46
- contextWindow: m.contextLimit, maxTokens: m.outputLimit,
47
- // Pi's numeric-only cost interface has no unknown variant. Nulls are
48
- // intentional runtime metadata, not zero prices; never borrow Spark rates.
49
- cost: museModelCost(m.modelId) as any,
50
- })));
40
+ return valid.flatMap(m => [m.modelId, `${m.modelId}-contributor`].filter(id => museModelRoute(id)).map(id => {
41
+ const {contributorMode} = museModelRoute(id)!;
42
+ return {
43
+ id,
44
+ name: `${m.displayLabel} · ${contributorMode === "on" ? "Contributor" : "Normal"}${museModelCost(m.modelId).input === null ? " · pricing unknown" : ""}`,
45
+ reasoning: m.variants.some((tier: string) => tier !== "none"),
46
+ input: ["text", "image"] as ("text" | "image")[],
47
+ thinkingLevelMap: museThinkingLevelMap(m.variants),
48
+ contextWindow: m.contextLimit, maxTokens: m.outputLimit,
49
+ // Pi's numeric-only cost interface has no unknown variant. Nulls are
50
+ // intentional runtime metadata, not zero prices; never borrow Spark rates.
51
+ cost: museModelCost(m.modelId) as any,
52
+ };
53
+ }));
51
54
  }
@@ -3,19 +3,44 @@ import { promisify } from "node:util";
3
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
- export const QUALIFIED_CLIENT = "1.4.14";
6
+ /** Oldest client with the tested private-XDG prompt/isolation controls. */
7
+ export const MIN_CLI_VERSION = "1.4.14";
8
+ /** Raise only after qualification; newer clients are not thereby qualified. */
9
+ export const TESTED_CLI_MAX = "1.4.15";
10
+ /** Exact builds whose experimental rawLog committed-batch boundary was live
11
+ * qualified: 1.4.14-R7309.1 (original), 1.4.15-R8339.1 (2026-11-10: parallel
12
+ * two-call batch, private prompt, session MCP readiness, Ember). */
13
+ export const QUALIFIED_BATCH_BUILDS = ["Muse Code 1.4.14 (1.4.14-R7309.1)", "Muse Code 1.4.15 (1.4.15-R8339.1)"] as const;
14
+ /** The tether's SDK is pinned independently, not required to equal the CLI. */
7
15
  export const QUALIFIED_SDK = "1.4.14";
8
- export function assertQualifiedVersions(clientOutput: string, sdk: string, rawLog = false) {
9
- const match = /^Muse Code (\d+\.\d+\.\d+)(?: \(\1-R[\d.]+\))?$/.exec(
10
- clientOutput.trim(),
11
- );
12
- // Experimental committed-batch payloads are qualified against this exact build.
13
- if (match?.[1] !== QUALIFIED_CLIENT || sdk !== QUALIFIED_SDK ||
14
- (rawLog && clientOutput.trim() !== "Muse Code 1.4.14 (1.4.14-R7309.1)"))
15
- throw new Error(
16
- `Unqualified Muse client/SDK: client=${clientOutput.trim()}, SDK=${sdk}; requires Muse Code ${QUALIFIED_CLIENT}, SDK ${QUALIFIED_SDK}. Private settings prompt delivery must be requalified before upgrade; no model request submitted.`,
17
- );
18
- return { client: match[1], sdk };
16
+ const warnedNewerCliVersions = new Set<string>();
17
+ const compareVersions = (a: string, b: string) => {
18
+ const right = b.split(".").map(Number);
19
+ for (const [i, value] of a.split(".").map(Number).entries()) {
20
+ if (value !== right[i]) return value > right[i] ? 1 : -1;
21
+ }
22
+ return 0;
23
+ };
24
+ export const isNewerThanTestedCli = (version: string) => compareVersions(version, TESTED_CLI_MAX) > 0;
25
+ export const strictCliVersion = (env: NodeJS.ProcessEnv = process.env) => env.PI_MUSE_TETHER_STRICT_VERSION === "1";
26
+
27
+ export function assertQualifiedVersions(clientOutput: string, sdk: string, rawLog = false, env: NodeJS.ProcessEnv = process.env) {
28
+ const match = /^Muse Code (\d+\.\d+\.\d+)(?: \(\1-R[\d.]+\))?$/.exec(clientOutput.trim());
29
+ if (!match || compareVersions(match[1], MIN_CLI_VERSION) < 0 || sdk !== QUALIFIED_SDK)
30
+ throw new Error(`Unqualified Muse client/SDK: client=${clientOutput.trim()}, SDK=${sdk}; requires Muse Code >=${MIN_CLI_VERSION}, SDK ${QUALIFIED_SDK}; no model request submitted.`);
31
+ // Experimental committed-batch payloads remain qualified ONLY against this
32
+ // exact build. Warn-and-continue never enables rawLog on an untested build.
33
+ if (rawLog && !(QUALIFIED_BATCH_BUILDS as readonly string[]).includes(clientOutput.trim()))
34
+ throw new Error(`Unqualified Muse experimental rawLog/committed-batch build; requires one of ${QUALIFIED_BATCH_BUILDS.join(", ")}; no model request submitted.`);
35
+ if (isNewerThanTestedCli(match[1])) {
36
+ if (strictCliVersion(env))
37
+ throw new Error(`Unqualified Muse Code ${match[1]}: newer than tested range ${MIN_CLI_VERSION}-${TESTED_CLI_MAX}; PI_MUSE_TETHER_STRICT_VERSION=1 refuses it; no model request submitted.`);
38
+ if (!warnedNewerCliVersions.has(match[1])) {
39
+ warnedNewerCliVersions.add(match[1]);
40
+ console.warn(`[pi-muse-tether] Muse Code ${match[1]} is newer than tested range ${MIN_CLI_VERSION}-${TESTED_CLI_MAX}; continuing, not yet qualified (including private settings prompt delivery). Set PI_MUSE_TETHER_STRICT_VERSION=1 to refuse newer clients. Experimental rawLog/committed-batch mode remains exact-build gated.`);
41
+ }
42
+ }
43
+ return {client: match[1], sdk};
19
44
  }
20
45
  // Cache only the known official selector layout. Unknown launchers may delegate
21
46
  // according to arbitrary state, so their version is probed for every host.
@@ -46,12 +71,12 @@ export async function qualifyMuseVersion(
46
71
  signal?.throwIfAborted();
47
72
  const key = identity && JSON.stringify([identity, sdk, rawLog]);
48
73
  const cached = key && versionCache.get(key);
49
- if (cached) return assertQualifiedVersions(cached, sdk, rawLog);
74
+ if (cached) return assertQualifiedVersions(cached, sdk, rawLog, env);
50
75
  const { stdout } = await promisify(execFile)(binary, ["--version"], {
51
76
  env: { ...env, MUSE_NO_AUTO_UPDATE: "1" },
52
77
  signal,
53
78
  });
54
- const result = assertQualifiedVersions(stdout, sdk, rawLog);
79
+ const result = assertQualifiedVersions(stdout, sdk, rawLog, env);
55
80
  signal?.throwIfAborted();
56
81
  if (key && identity === await binaryIdentity(binary)) versionCache.set(key, stdout);
57
82
  return result;
package/src/doctor.ts CHANGED
@@ -2,7 +2,7 @@ import { museModelRoute } from "./model-route.js";
2
2
  import { assertLoginSafe } from "./settings.js";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { qualifyMuseVersion } from "./cli-version.js";
5
+ import { qualifyMuseVersion, MIN_CLI_VERSION, TESTED_CLI_MAX, isNewerThanTestedCli, strictCliVersion } from "./cli-version.js";
6
6
  import { museLedgerPath } from "./request-ledger.js";
7
7
  import { MUSE_CACHE_POLICY } from "./cache-policy.js";
8
8
  /** Local diagnostic only: --version, no account/auth contents, quota or inference. */
@@ -18,9 +18,10 @@ export async function museDoctor(modelId?: string) {
18
18
  ok: true,
19
19
  binary,
20
20
  ...versions,
21
+ versionPolicy: {minimum:MIN_CLI_VERSION, testedMaximum:TESTED_CLI_MAX, newerThanTested:isNewerThanTestedCli(versions.client), strict:strictCliVersion()},
21
22
  contributorMode: modelId ? museModelRoute(modelId)?.contributorMode ?? null : null,
22
23
  apiKeyForwarded: false,
23
- promptRecipe: "private-xdg-settings;explicit-workspaceRoot",
24
+ promptRecipe: "private-xdg-settings;private-trusted-workspaceRoot",
24
25
  ledger: museLedgerPath(),
25
26
  cache: MUSE_CACHE_POLICY,
26
27
  quota:
package/src/host.ts CHANGED
@@ -5,9 +5,10 @@ import { MuseLedger } from "./request-ledger.js";
5
5
  import type { TurnInputPart } from "./wire-types.js";
6
6
  import { homedir, tmpdir } from "node:os";
7
7
  import { createHash } from "node:crypto";
8
- import { mkdtemp, rm } from "node:fs/promises";
8
+ import { mkdtemp, realpath, rm } from "node:fs/promises";
9
+ import { setTimeout as delay } from "node:timers/promises";
9
10
  import { isAbsolute, join } from "node:path";
10
- import { writePromptSettings, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
11
+ import { writePromptSettings, privateWorkspace, promptSettings, discoverSkillsOff, linkHostLogin, assertLoginSafe, type SkillsOff } from "./settings.ts";
11
12
  import { writeFile } from "node:fs/promises";
12
13
  import {
13
14
  Connection, DiscardedSessions, MspError, Session, readSessionDurability,
@@ -16,6 +17,9 @@ import {
16
17
  type SessionOptions, type SpawnMspConnectionOptions, type ViewEvent,
17
18
  } from "@muse-code/sdk";
18
19
 
20
+ /** Inventory recheck pacing while Muse 1.4.15 starts session MCP (~200 ms measured). */
21
+ const MCP_READY_RECHECK_MS = 25;
22
+
19
23
  type InitializeResult = Parameters<typeof readSessionDurability>[0];
20
24
  export type MuseApproval = Parameters<ApprovalHandler>[0];
21
25
  export type MuseFrame = { method: string; params?: Record<string, unknown> };
@@ -54,6 +58,8 @@ export interface MuseHostOptions {
54
58
  onEvent?: (event: MuseHostEvent) => void;
55
59
  /** Stop an opening host when its Pi binding is retired. */
56
60
  signal?: AbortSignal;
61
+ /** Set by openMuseHost for private prompts: the empty trusted workspace. */
62
+ privateWorkspace?: string;
57
63
  /**
58
64
  * Required to allow anything. Must validate identity and reserve the exact
59
65
  * generation, session, turn, approvalId, toolCallId and rawArgs for the later
@@ -243,8 +249,9 @@ export class MuseHost {
243
249
  approvalMode: "promptUnmatched",
244
250
  ...(this.#options.model === undefined ? {} : { modelId: this.#options.model }),
245
251
  // Without workspaceRoot, serve silently ignored run.system_prompt in
246
- // the live qualification. Explicit workspace construction is essential.
247
- ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.cwd} : {}),
252
+ // the live qualification. Explicit workspace construction is essential;
253
+ // the private trusted workspace keeps project rules out (settings.ts).
254
+ ...(this.#options.privatePrompt ? {workspaceRoot: this.#options.privateWorkspace ?? this.#options.cwd} : {}),
248
255
  config: { mcpServers: this.#options.mcpServers ?? {} },
249
256
  }, { maxAttempts: 1 }); // no engine retry/replay
250
257
  this.#assertLive();
@@ -278,6 +285,7 @@ export class MuseHost {
278
285
  if(!(typeof sub.subscriptionId==="number" && Number.isFinite(sub.subscriptionId)))throw new Error("Muse rawLog subscription absent");
279
286
  this.#logSubscription=sub.subscriptionId;
280
287
  }
288
+ await this.#awaitSessionMcp();
281
289
  // Entire drain is synchronous. A newly arriving event cannot overtake it.
282
290
  const held = this.#held;
283
291
  this.#held = [];
@@ -294,6 +302,47 @@ export class MuseHost {
294
302
  }
295
303
  }
296
304
 
305
+ /** Muse 1.4.15 starts session MCP servers after session/start returns, and
306
+ * a turn sent first fails "unknown tool" (measured 2026-11-10: "starting"
307
+ * with no tools, "connected" ~200 ms later). The client sends no readiness
308
+ * notification, so ask its inventory until every required server is
309
+ * connected with every Pi tool. No deadline: Pi's abort owns cancellation.
310
+ * 1.4.14 has no inventory method and was already ready at session/start. */
311
+ async #awaitSessionMcp() {
312
+ const names = Object.keys(this.#options.mcpServers ?? {});
313
+ for (;;) {
314
+ if (!names.length) return;
315
+ this.#assertLive();
316
+ this.#options.signal?.throwIfAborted();
317
+ let inventory: any;
318
+ try {
319
+ inventory = await (this.connection as any).request("mcpServer/readInventory", { sessionId: this.sessionId, includeTools: true });
320
+ } catch (error: any) {
321
+ // Only the typed old-client refusal skips readiness. experimentalRequired
322
+ // also uses -32601; a frame without data.kind is rejected by the SDK as
323
+ // ProtocolError (fail-closed), not evidence of an older client.
324
+ if (error?.kind === "methodNotFound" || error?.data?.kind === "methodNotFound") return;
325
+ throw error;
326
+ }
327
+ if (!Array.isArray(inventory?.servers)) throw new Error("Muse session MCP inventory malformed: servers must be an array");
328
+ const rows = names.map(name => ({ name, row: inventory.servers.find((s: any) => s?.name === name) }));
329
+ // Registration can be asynchronous: absent rows and starting are pending.
330
+ // 1.4.15 binary inventory labels include withheld and closed. These,
331
+ // explicit failures (failed/error/forfeited), and all unrecognized states
332
+ // fail closed, naming the state; only starting/absence are pending.
333
+ const failed = rows.find(({ row }) => row && row.state !== "starting" && row.state !== "connected");
334
+ if (failed) throw new Error(`Muse session MCP server ${failed.name} unavailable (${failed.row?.state ?? "absent"}); no model request submitted`);
335
+ if (rows.every(({ row }) => row?.state === "connected")) {
336
+ const pi = rows.find(({ name }) => name === "pi")?.row;
337
+ const missing = pi ? this.#options.tools.filter(tool => !(pi.tools as unknown[] | undefined)?.includes(tool)) : [];
338
+ if (missing.length) throw new Error(`Muse session MCP server pi connected without Pi tools ${missing.join(", ")}; no model request submitted`);
339
+ return;
340
+ }
341
+ // Recheck pacing only (not a deadline), well under the measured ~200 ms startup.
342
+ await delay(MCP_READY_RECHECK_MS, undefined, { signal: this.#options.signal });
343
+ }
344
+ }
345
+
297
346
  /** The single ingress, also used by synthetic frame fixtures. */
298
347
  receive(frame: MuseFrame): void {
299
348
  if(frame.method==="log/gap" && (frame.params as any)?.subscriptionId===this.#logSubscription){this.fence("Muse rawLog gap; complete tool batch unknown");return;}
@@ -574,7 +623,7 @@ export async function discoverMuseCatalog() {
574
623
  await qualifyMuseVersion(launch.command,launch.env??{});
575
624
  const handshake = spawnMspConnection(launch);
576
625
  try {
577
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
626
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
578
627
  capabilities: { requestedCapabilities: ["sessionMcp"], userInputDialogs: false } });
579
628
  const catalog = await spawned.connection.request("model/list", {});
580
629
  return catalog as typeof catalog & {models:any[]};
@@ -588,7 +637,9 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
588
637
  const launch = museLaunchOptions(options); // preflight BEFORE filesystem/process work
589
638
  options.signal?.throwIfAborted();
590
639
  await qualifyMuseVersion(launch.command, launch.env??{}, options.signal, options.toolBatches);
591
- const home = await mkdtemp(join(tmpdir(), "pi-muse-host-"));
640
+ // Muse canonicalizes workspaceRoot before trust lookup (e.g. macOS /var).
641
+ // One canonical root owns settings, trust, auth link and raw/coding workspace.
642
+ const home = await realpath(await mkdtemp(join(tmpdir(), "pi-muse-host-")));
592
643
  const env = options.echo ? { ...launch.env,
593
644
  HOME: home, XDG_CONFIG_HOME: join(home, "config"), XDG_DATA_HOME: join(home, "data"),
594
645
  XDG_CACHE_HOME: join(home, "cache"), XDG_STATE_HOME: join(home, "state") } : {
@@ -605,6 +656,7 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
605
656
  try {
606
657
  if (options.privatePrompt) {
607
658
  await writePromptSettings(home, options.privatePrompt.systemPrompt, options.tools, options.privatePrompt.skillsOff);
659
+ options = {...options, privateWorkspace: privateWorkspace(home)};
608
660
  if(!options.echo){
609
661
  const verify=await linkHostLogin(home,launch.env?.XDG_CONFIG_HOME??join(homedir(),".config"));
610
662
  verifyLogin=async()=>{
@@ -636,8 +688,8 @@ export async function openMuseHost(options: MuseHostOptions): Promise<MuseHost>
636
688
  return {};
637
689
  });
638
690
  try {
639
- const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.1.1" },
640
- capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches)?{experimentalApi:true}:{}) } });
691
+ const spawned = await handshake.initialize({ clientInfo: { name: "pi_muse_tether", version: "0.2.0" },
692
+ capabilities: { requestedCapabilities: ["sessionMcp",...(options.toolBatches?["rawLog"]:[])], userInputDialogs: false, ...((options.privatePrompt||options.toolBatches||Object.keys(options.mcpServers??{}).length)?{experimentalApi:true}:{}) } });
641
693
  if(options.toolBatches && !spawned.initializeResult.grantedCapabilities.includes("rawLog"))throw new Error("Muse rawLog capability absent; parallel tools unsupported; no model request submitted");
642
694
  if (!options.echo) {
643
695
  const catalog = await spawned.connection.request("model/list", {});
@@ -1,20 +1,31 @@
1
- /** Local picker routes, NOT a list of physical provider model IDs. Wonder
2
- * contributor suffixes distinguish CLI recipes; MSP always gets catalogue IDs. */
1
+ /** Shape only, never an availability allowlist. The host checks model/list
2
+ * again before submitting a turn. Contributor suffixes are local CLI recipes. */
3
+ export const isMuseModelId = (id: unknown): id is string =>
4
+ typeof id === "string" && /^muse-[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id);
5
+
6
+ /** Verified 2026-11-10 by official-client contributor on/off request traces
7
+ * (the wire model ID changes only for these) and direct Meta API requests.
8
+ * Ember ignores contributor mode and its contributor API ID returns model_not_found.
9
+ * This gates contributor recipes only, never normal catalogue availability.
10
+ * Add a native ID only after verifying its contributor wire model and API support. */
11
+ export const VERIFIED_CONTRIBUTOR_MODEL_IDS: ReadonlySet<string> = new Set([
12
+ "muse-spark-1.3", "muse-spark-1.2", "muse-wonder-1.0", "muse-wonder-full-1.0",
13
+ ]);
14
+
3
15
  export function museModelRoute(id: string): {modelId:string;contributorMode:"on"|"off"} | undefined {
4
- if (["muse-spark-1.3", "muse-spark-1.3-contributor"].includes(id))
5
- return {modelId:id,contributorMode:"on"};
6
- for (const modelId of ["muse-wonder-1.0", "muse-wonder-full-1.0"]) {
7
- if (id === modelId) return {modelId,contributorMode:"off"};
8
- if (id === `${modelId}-contributor`) return {modelId,contributorMode:"on"};
9
- }
10
- return undefined;
16
+ if (!isMuseModelId(id)) return undefined;
17
+ const contributor = id.endsWith("-contributor");
18
+ const modelId = contributor ? id.slice(0, -"-contributor".length) : id;
19
+ if (!isMuseModelId(modelId) || (contributor && !VERIFIED_CONTRIBUTOR_MODEL_IDS.has(modelId))) return undefined;
20
+ return {modelId, contributorMode: contributor || modelId === "muse-spark-1.3" ? "on" : "off"};
11
21
  }
12
22
  export const isQualifiedMuseModel = (id:string) => museModelRoute(id) !== undefined;
13
23
  export function museResponseIdentity(id:string) {
14
24
  const route = museModelRoute(id);
15
25
  if (!route) return {};
16
- if (route.modelId.startsWith("muse-spark-1.3"))
26
+ if (route.modelId === "muse-spark-1.3")
17
27
  return {responseModel:"muse-spark-1.3-contributor",responseModelSource:"derived:fixed-contributor-on-recipe",contributorMode:route.contributorMode,nativeModel:route.modelId};
18
- // model/list establishes logical selection, not physical response identity.
19
- return {responseModelSource:"unknown:physical-model-id;catalogue-logical-selection",contributorMode:route.contributorMode,nativeModel:route.modelId};
28
+ // Recipe-derived identity, not a claim that the response carried model metadata.
29
+ return {responseModel:route.contributorMode === "on" ? `${route.modelId}-contributor` : route.modelId,
30
+ responseModelSource:"derived:selected-native-model-and-contributor-recipe",contributorMode:route.contributorMode,nativeModel:route.modelId};
20
31
  }
package/src/provider.ts CHANGED
@@ -441,13 +441,22 @@ function emitFrame(b: Binding, event: any) {
441
441
  throw new Error("Muse tool result receipt invocation differs from pending MCP call");
442
442
  let redactions: import("./tool-result-receipt.js").VendorRedaction[] = [];
443
443
  let images: import("./tool-result-receipt.js").UnverifiableImage[] = [];
444
- const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; });
444
+ let truncatedView: import("./tool-result-receipt.js").TruncatedView | undefined;
445
+ const receipt = toolResultReceipt(item, r, stored, spans => { redactions = spans; }, declared => { images = declared; }, view => { truncatedView = view; });
445
446
  if (!b.bridge.verifyContent(pending.invocation, receipt))
446
447
  throw new Error("Muse tool result mismatch");
448
+ if (truncatedView) b.host?.ledger?.record("tool_result_truncated_view", {
449
+ callId:item.callId, piToolCallId:b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId:item.itemId,
450
+ source:{tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId},
451
+ outputRefAvailability:item.outputRef?.availability ?? "absent", view:truncatedView,
452
+ evidence:"declared-lossy-view", exactModelConsumption:false,
453
+ });
447
454
  if (redactions.length) {
448
455
  b.host?.ledger?.record("tool_result_vendor_redaction", {
449
- callId: item.callId, itemId: item.itemId, count: redactions.length,
450
- rule: "unique-nonempty-intraline-v3", spans: redactions, evidence:"declared-lossy",
456
+ callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
457
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
458
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})}, count: redactions.length,
459
+ rule: "positional-declared-loss-v4", spans: redactions, evidence:"declared-lossy",
451
460
  textProjection: r.isError ? "lf-joined-all-text-parts" : images.length ? "native-ordered-parts-with-image-metadata" : "native-text-chunk-fold",
452
461
  exactModelConsumption: false,
453
462
  });
@@ -455,6 +464,8 @@ function emitFrame(b: Binding, event: any) {
455
464
  }
456
465
  if (images.length) b.host?.ledger?.record("tool_result_image_unverifiable", {
457
466
  callId: item.callId, piToolCallId: b.batchSpec?.find(c=>c.callId===item.callId)?.piCallId ?? pending.invocation.piCallId, itemId: item.itemId,
467
+ source: {tool:pending.invocation.name, piJournalEntryId:b.batchSpec?.find(c=>c.callId===item.callId)?.journal?.entryId,
468
+ ...(pending.invocation.name==="read" ? {path:pending.invocation.arguments.path} : {})},
458
469
  images:images.map(image=>({...image,modelVisibility:image.modelVisibility??"unproven"})), deliveredToMcp: true, evidence:"declared-lossy", unverifiableInContent: true,
459
470
  rule: "mcp-image-placeholder-v1", exactModelConsumption: false,
460
471
  });
@@ -464,17 +475,17 @@ function emitFrame(b: Binding, event: any) {
464
475
  if(spec)spec.verified=true;
465
476
  settleBatch(b);
466
477
  };
467
- if (item.outputRef) {
478
+ if (item.outputRef && !(item.truncated === true && ["missing","unsupported","accessFailed"].includes(item.outputRef.availability))) {
468
479
  b.verifyingReceipt = readStoredToolOutput(item, offset => {
469
480
  if (!b.host?.readToolOutput) throw new Error("Muse host cannot read item/outputRef");
470
481
  return b.host.readToolOutput(item, offset);
471
- }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt: ${error.message}`); }).finally(() => {
482
+ }).then(verify).catch(error => { if (!b.closed) fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }).finally(() => {
472
483
  b.verifyingReceipt=undefined;
473
484
  const events=b.buffered.splice(0);
474
485
  for(const next of events)emitFrame(b,next);
475
486
  });
476
487
  } else {
477
- try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt: ${error.message}`); }
488
+ try { verify(); } catch(error:any) { fail(b, `Muse tool result receipt (call ${item.callId}, item ${item.itemId}): ${error.message}`); }
478
489
  }
479
490
  }
480
491
  }
@@ -579,7 +590,7 @@ function flushTools(b: Binding) {
579
590
  /** Live inference is explicit opt-in; echo always launches the offline provider. */
580
591
  function streamEffective(model: any, input: any, options: any = {}) {
581
592
  if(config.modelAllowed && !config.modelAllowed(model)){
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";
593
+ const refused=createAssistantMessageEventStream();const output=message(model);output.stopReason="error";output.errorMessage="Muse model is not qualified for Pi prompt/compaction; select a catalogue-registered Muse route";
583
594
  refused.push({type:"error",reason:"error",error:output});refused.end();return refused;
584
595
  }
585
596
  const context = piContext(input);
@@ -925,7 +936,7 @@ function streamViaMuse(model:any,input:any,options:any={}) {
925
936
  throw new Error("Muse onPayload must return a logical request with systemPrompt, messages and tools");
926
937
  if(effective.messages.some((entry:any)=>entry?.role==="system"))
927
938
  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.`}))};
939
+ const request={...effective,tools:effective.tools.map((tool:any,index:number)=>index ? tool : ({...tool,description:`${tool.description??""}\n\nTransport notice: the official-client transcript view of a tool result may be truncated; full model consumption cannot be inferred from that view. [REDACTED] in tool text can be official-client redaction; original bytes in those spans are unavailable. Literal [REDACTED] may already be source text: a marker alone does not prove loss. The client may canonicalize bearer to Bearer immediately before a redaction. Tool images are delivered without pixel attestation; GIF/WebP visibility is unqualified. Images attached to failed tool results are omitted by the official client.`}))};
929
940
  for await(const event of streamEffective(model,request,options))stream.push(event);
930
941
  stream.end();
931
942
  } catch(error:any) {
package/src/settings.ts CHANGED
@@ -68,10 +68,19 @@ export function promptSettings(systemPrompt: string, tools: readonly string[], s
68
68
  context: {foreign_personal_rules:false,foreign_personal_skills:false},
69
69
  };
70
70
  }
71
+ /** The empty, tether-owned workspace a private-prompt session names. Muse
72
+ * honours run.system_prompt only with an explicit workspaceRoot, and Muse
73
+ * 1.4.15 starts session MCP only in a trusted workspace ("withheld"
74
+ * otherwise). Trusting the user's project would also load its rules files
75
+ * (AGENTS.md) into the model (measured 2026-11-10), so only this empty private
76
+ * directory is trusted. Pi still owns cwd and every tool path. */
77
+ export const privateWorkspace = (hostRoot: string) => join(hostRoot, "workspace");
71
78
  /** Caller owns a unique host root; no shared mutable settings/schema or auth links. */
72
79
  export async function writePromptSettings(hostRoot: string, systemPrompt: string, tools: readonly string[], skillsOff?: SkillsOff) {
73
80
  const xdg = join(hostRoot,"config");
74
81
  await mkdir(join(xdg,"muse"),{recursive:true,mode:0o700});
82
+ await mkdir(privateWorkspace(hostRoot),{recursive:true,mode:0o700});
75
83
  await writeFile(join(xdg,"muse","settings.json"), JSON.stringify(promptSettings(systemPrompt,tools,skillsOff)),{mode:0o600,flag:"wx"});
84
+ await writeFile(join(xdg,"muse","trust.json"), JSON.stringify({schema_version:1,projects:{[privateWorkspace(hostRoot)]:{decision:"trusted"}}}),{mode:0o600,flag:"wx"});
76
85
  return xdg;
77
86
  }
@@ -27,13 +27,27 @@ function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
27
27
  export function assertToolResultVerifiable(sent: BridgeResult): void {
28
28
  imageDeclarations(sent);
29
29
  }
30
- export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void): BridgeResult {
30
+ /** visibleBytes includes any displayed ellipsis; candidate offsets address the original projection. */
31
+ export type TruncatedView = { visibleBytes: number; projectionBytes: number; omittedOffsetBytes: number; omittedByteLen: number; sha256: string; ellipsisIdentity: "not-present" | "generated" | "ambiguous"; candidateOmittedOffsetsBytes: number[]; sources: {partIndex:number;partOffsetBytes:number;byteLen:number}[] };
32
+ /** MSP 1.4.14 live capture: 65,536 view bytes ended with U+2026, after an
33
+ * exact 65,533-byte original prefix. These observed lengths are not limits. */
34
+ function viewPrefixes(visible: string, full: string): string[] {
35
+ const candidates = [visible, ...(visible.endsWith("…") ? [visible.slice(0,-1)] : [])];
36
+ return candidates.filter(prefix => !(prefix.length && /[\uD800-\uDBFF]/.test(prefix.at(-1)!)) && full.startsWith(prefix));
37
+ }
38
+ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void, onTruncatedView?: (view: TruncatedView) => void): BridgeResult {
31
39
  const images = imageDeclarations(sent);
32
40
  if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
33
41
  if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
34
- if (item.truncated && stored === undefined) throw new Error("Muse truncated tool result has no verifiable full outputRef readback");
42
+ if (item.truncated !== undefined && typeof item.truncated !== "boolean")
43
+ throw new Error("Muse tool result truncated flag must be boolean");
44
+ const partial = item.truncated === true && stored === undefined;
45
+ if (partial && item.outputRef !== undefined && (!item.outputRef || !["missing","unsupported","accessFailed"].includes(item.outputRef.availability)))
46
+ throw new Error("Muse truncated view outputRef requires strict readback or known unavailability");
47
+ if (partial && (!onTruncatedView || sent.isError === true || images.length))
48
+ throw new Error("Muse truncated view requires full readback for this result shape");
35
49
  const output = stored ?? item.visibleOutput;
36
- if (stored !== undefined && (item.truncated ? !stored.startsWith(item.visibleOutput) : stored !== item.visibleOutput))
50
+ if (stored !== undefined && (item.truncated ? viewPrefixes(item.visibleOutput,stored).length === 0 : stored !== item.visibleOutput))
37
51
  throw new Error("Muse stored tool output differs from visibleOutput");
38
52
  let actual = output;
39
53
  if (sent.isError === true) {
@@ -48,11 +62,15 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
48
62
  // placeholder-shaped strings: literal tool text and leading LF remain bytes.
49
63
  let expected = "";
50
64
  const protectedImages: { start: number; end: number }[] = [];
65
+ const textSources: {partIndex:number; start:number; end:number}[] = [];
51
66
  for (const [index, part] of sent.content.entries()) {
52
67
  if (part.type === "text") {
53
68
  // Native string folding ignores leading empty chunks but preserves a
54
69
  // separator before an empty chunk after nonempty output (captured live).
55
- expected += (expected ? "\n" : "") + part.text;
70
+ if (expected) expected += "\n";
71
+ const start = Buffer.byteLength(expected);
72
+ expected += part.text;
73
+ textSources.push({partIndex:index,start,end:Buffer.byteLength(expected)});
56
74
  } else {
57
75
  // The official client's failed MCP path projects text only. Images were
58
76
  // delivered to MCP, NOT exposed to the model; declare that known loss.
@@ -69,17 +87,74 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
69
87
  if (sent.isError === true) {
70
88
  expected = sent.content.filter(part => part.type === "text").map(part => (part as {text:string}).text).join("\n");
71
89
  if (!expected) expected = "MCP tool returned an error";
90
+ textSources.length=0;
91
+ let offset=0;
92
+ for(const [partIndex,part] of sent.content.entries()) if(part.type==="text") {
93
+ textSources.push({partIndex,start:offset,end:offset+Buffer.byteLength(part.text)});
94
+ offset+=Buffer.byteLength(part.text)+1;
95
+ }
72
96
  } else if (!expected) expected = "[MCP tool returned no content]";
97
+ const locateSources=(redactions:VendorRedaction[])=>{
98
+ for(const span of redactions) span.sources=textSources.filter(s=>s.start<span.piOffsetBytes+span.piByteLen && s.end>span.piOffsetBytes).map(s=>({partIndex:s.partIndex,partOffsetBytes:Math.max(s.start,span.piOffsetBytes)-s.start,byteLen:Math.min(s.end,span.piOffsetBytes+span.piByteLen)-Math.max(s.start,span.piOffsetBytes)}));
99
+ };
100
+ if (partial) {
101
+ // The captured combined codec preserves line boundaries. Reconcile
102
+ // complete lines normally and the final line with the same v4 positional
103
+ // alignment in prefix mode, retaining every viable original cut.
104
+ const visibleEnd=actual.lastIndexOf("\n")+1;
105
+ let originalEnd=0;
106
+ for(let at=0;at<visibleEnd;at++) if(actual[at]==="\n") {
107
+ const next=expected.indexOf("\n",originalEnd);
108
+ if(next<0) throw new Error("Muse truncated view has more lines than native projection");
109
+ originalEnd=next+1;
110
+ }
111
+ const completeExpected=expected.slice(0,originalEnd),completeVisible=actual.slice(0,visibleEnd);
112
+ const projected:BridgeResult={content:[{type:"text",text:completeExpected}],isError:false};
113
+ let redactions:VendorRedaction[]=[];
114
+ const observed=reconcileVendorRedactions(projected,{content:[{type:"text",text:completeVisible}],isError:false},spans=>{redactions=spans;});
115
+ if ((observed.content[0] as {text:string}).text!==completeExpected)
116
+ throw new Error("Muse truncated view complete lines differ from native projection");
117
+ if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
118
+ const finalVisible=actual.slice(visibleEnd),finalExpected=expected.slice(originalEnd).split("\n",1)[0];
119
+ let finalSpans:VendorRedaction[]=[],prefix:PrefixAlignment|undefined;
120
+ reconcileVendorRedactions({content:[{type:"text",text:finalExpected}],isError:false},
121
+ {content:[{type:"text",text:finalVisible}],isError:false},spans=>{finalSpans=spans;},alignment=>{prefix=alignment;});
122
+ if(!prefix) throw new Error("Muse truncated view differs from native projection prefix");
123
+ const baseBytes=Buffer.byteLength(completeExpected),viewBaseBytes=Buffer.byteLength(completeVisible);
124
+ for(const span of finalSpans) {
125
+ span.piOffsetBytes+=baseBytes;span.museOffsetBytes+=viewBaseBytes;
126
+ if(span.candidateStartBytes)span.candidateStartBytes=span.candidateStartBytes.map(offset=>offset+baseBytes);
127
+ if(span.candidateEndBytes)span.candidateEndBytes=span.candidateEndBytes.map(offset=>offset+baseBytes);
128
+ }
129
+ redactions.push(...finalSpans);
130
+ if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
131
+ const candidateOmittedOffsetsBytes=prefix.cuts.map(cut=>baseBytes+Buffer.byteLength(finalExpected.slice(0,cut))).sort((a,b)=>a-b);
132
+ const omittedOffsetBytes=candidateOmittedOffsetsBytes[0], projectionBytes=Buffer.byteLength(expected);
133
+ const ellipsisIdentity=prefix.ellipsisIdentity;
134
+ const omitted = Buffer.from(expected, "utf8").subarray(omittedOffsetBytes);
135
+ locateSources(redactions);
136
+ // Both checks succeeded; publish no partial evidence on a rejected view.
137
+ if(redactions.length) onRedactions!(redactions);
138
+ onTruncatedView!({visibleBytes:Buffer.byteLength(item.visibleOutput),projectionBytes,omittedOffsetBytes,
139
+ omittedByteLen:omitted.length,sha256:createHash("sha256").update(omitted).digest("hex"),ellipsisIdentity,candidateOmittedOffsetsBytes,
140
+ sources:textSources.filter(s=>s.end>omittedOffsetBytes).map(s=>({partIndex:s.partIndex,
141
+ partOffsetBytes:Math.max(s.start,omittedOffsetBytes)-s.start,byteLen:s.end-Math.max(s.start,omittedOffsetBytes)}))});
142
+ return sent;
143
+ }
73
144
  const projected: BridgeResult = { content: [{ type: "text", text: expected }], isError: sent.isError === true };
74
145
  let redactions: VendorRedaction[] = [];
75
146
  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)");
147
+ if ((observed.content[0] as { text: string }).text !== expected) {
148
+ let at=0;
149
+ while(at<expected.length && at<actual.length && expected[at]===actual[at])at++;
150
+ throw new Error(`Muse tool result text projection mismatch (image placeholder differs or text changed) at projection byte ${Buffer.byteLength(expected.slice(0,at))}, receipt byte ${Buffer.byteLength(actual.slice(0,at))}`);
151
+ }
78
152
  for (const span of redactions) {
79
153
  if (protectedImages.some(range => span.piOffsetBytes < Buffer.byteLength(expected.slice(0, range.end)) &&
80
154
  span.piOffsetBytes + span.piByteLen > Buffer.byteLength(expected.slice(0, range.start))))
81
155
  throw new Error("Muse image placeholder differs: redaction cannot hide image metadata");
82
156
  }
157
+ locateSources(redactions);
83
158
  if (redactions.length) onRedactions?.(redactions);
84
159
  if (images.length) onImages?.(images);
85
160
  // modelVisibleContent may contain image derivatives or metadata. It is useful
@@ -87,25 +162,37 @@ export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string
87
162
  return sent;
88
163
  }
89
164
 
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.
93
- * Never include removed text in metadata. This is declared vendor loss, NOT
94
- * proof that the model consumed the original bytes. */
95
- export type VendorRedaction = { piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string };
165
+ /** Offsets address UTF-8 bytes in the native projection and vendor receipt.
166
+ * Ambiguous spans cover the union of viable alignments, not an invented exact
167
+ * removal. Hashes describe that source range; removed bytes are never logged. */
168
+ export type VendorRedaction = {
169
+ piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string;
170
+ reason: "vendor-redaction" | "ambiguous-vendor-redaction" | "vendor-bearer-prefix";
171
+ alignment: "unique" | "ambiguous";
172
+ ambiguityReason?: "multiple-alignments" | "literal-marker-identity";
173
+ sources?: {partIndex:number;partOffsetBytes:number;byteLen:number}[];
174
+ candidateStartBytes?: number[]; candidateEndBytes?: number[];
175
+ };
96
176
  const marker = "[REDACTED]";
97
- function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, report?: (spans: VendorRedaction[]) => void): BridgeResult {
177
+ type PrefixAlignment={cuts:number[];ellipsisIdentity:TruncatedView["ellipsisIdentity"]};
178
+ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, report?: (spans: VendorRedaction[]) => void, onPrefix?: (alignment:PrefixAlignment)=>void): BridgeResult {
98
179
  const pi = (sent.content[0] as {text:string}).text;
99
180
  const muse = (observed.content[0] as {text:string}).text;
100
- if (pi === muse || !muse.includes(marker)) return observed;
101
- // DECLARED LOSSY TRANSPORT ACCEPTANCE, not verification of removed bytes.
102
- // The pinned binary exposes the marker and token prefixes, but not a complete
103
- // provable runtime pattern set. Conservative fallback: unique alignment,
104
- // nonempty single-line removed spans with unique positional alignment, including line edges.
105
- // Literal Pi markers must match literally and may never be swallowed by a gap.
106
- type Span = { piStart: number; piEnd: number; museStart: number };
107
- const invalid = () => new Error("Muse tool result mismatch: invalid or ambiguous vendor redaction");
108
- // Match literal chunks with KMP, not a fresh suffix scan at every candidate.
181
+ if(onPrefix && !muse.includes(marker)) {
182
+ const prefixes=viewPrefixes(muse,pi);
183
+ if(!prefixes.length) throw new Error("Muse truncated view differs from native projection prefix");
184
+ onPrefix({cuts:prefixes.map(p=>p.length),ellipsisIdentity:muse.endsWith("…") ? prefixes.length===2 ? "ambiguous" : "generated" : "not-present"});
185
+ return sent;
186
+ }
187
+ if (!onPrefix && (pi === muse || !muse.includes(marker))) return observed;
188
+ const invalid = (piAt: number, museAt: number) => new Error(`Muse tool result mismatch: invalid vendor redaction at projection byte ${Buffer.byteLength(pi.slice(0, piAt))}, receipt byte ${Buffer.byteLength(muse.slice(0, museAt))}`);
189
+ const spans: VendorRedaction[] = [];
190
+ function record(start: number, end: number, visible: number, reason: VendorRedaction["reason"], alignment: VendorRedaction["alignment"], candidates?: {starts:number[];ends:number[]}) {
191
+ spans.push({piOffsetBytes:Buffer.byteLength(pi.slice(0,start)),museOffsetBytes:Buffer.byteLength(muse.slice(0,visible)),
192
+ piByteLen:Buffer.byteLength(pi.slice(start,end)),sha256:createHash("sha256").update(pi.slice(start,end)).digest("hex"),reason,alignment,
193
+ ...(candidates ? {candidateStartBytes:candidates.starts.map(a=>Buffer.byteLength(pi.slice(0,a))),candidateEndBytes:candidates.ends.map(a=>Buffer.byteLength(pi.slice(0,a)))} : {})});
194
+ }
195
+ // KMP keeps literal matching linear in the source length per marker.
109
196
  function starts(text: string, chunk: string): Uint8Array {
110
197
  const found = new Uint8Array(text.length + 1);
111
198
  if (!chunk.length) { found.fill(1); return found; }
@@ -122,99 +209,117 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
122
209
  }
123
210
  return found;
124
211
  }
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[] = [];
212
+ function line(text: string, visible: string, piBase: number, museBase: number) {
213
+ const pieces: string[] = [], widths: number[] = [], positions: number[] = [];
129
214
  let cursor = 0, at: number;
130
215
  while ((at = visible.indexOf(marker, cursor)) !== -1) {
131
- pieces.push(visible.slice(cursor, at));
132
- cursor = at;
216
+ pieces.push(visible.slice(cursor, at)); positions.push(at); cursor = at;
133
217
  let width = 0;
134
- while (visible.startsWith(marker, cursor)) {
135
- width++; cursor += marker.length;
136
- if (!groupAdjacent) break;
137
- }
218
+ while (visible.startsWith(marker, cursor)) { width++; cursor += marker.length; }
138
219
  widths.push(width);
139
220
  }
140
221
  pieces.push(visible.slice(cursor));
141
- const n = text.length;
142
- if (pieces.length === 1 || !text.startsWith(pieces[0])) throw invalid();
143
- // Each backward layer counts complete parses after one marker. Range sums
144
- // make a variable-length hole O(1) per position: O(n * markerCount), not
145
- // quadratic suffix rescanning for a single gap. 2 means ambiguous, not a cap.
146
- const barrier = new Int32Array(n + 1); barrier[n] = n;
147
- for (let a = n - 1; a >= 0; a--)
148
- barrier[a] = text[a] === "\r" || text.startsWith(marker, a) ? a : barrier[a + 1];
149
- let next = new Uint8Array(n + 1); next[n] = 1;
150
- const choices: Int32Array[] = [];
151
- for (let i = pieces.length - 2; i >= 0; i--) {
152
- const chunk = pieces[i + 1], matches = starts(text, chunk);
153
- const sum = new Float64Array(n + 2), first = new Int32Array(n + 2); first.fill(-1);
154
- for (let a = n; a >= 0; a--) {
155
- const ways = matches[a] ? next[a + chunk.length] ?? 0 : 0;
156
- sum[a] = sum[a + 1] + ways;
157
- first[a] = ways ? a : first[a + 1];
222
+ const n = text.length, count = widths.length;
223
+ const boundary=(at:number)=>!(at>0 && at<n && /[\uD800-\uDBFF]/.test(text[at-1]) && /[\uDC00-\uDFFF]/.test(text[at]));
224
+ if (!count || !boundary(pieces[0].length)) throw invalid(piBase, museBase);
225
+ const matches = pieces.map((chunk,i) => {
226
+ const exact = starts(text, chunk);
227
+ // Captured official-client codec: `bearer permission.` becomes
228
+ // `Bearer [REDACTED]`. ONLY the prefix immediately before a marker is
229
+ // case-folded; no other text/case/status/metadata normalization is allowed.
230
+ if (i < count && chunk.endsWith("Bearer ")) {
231
+ const prefix = chunk.slice(0,-7), candidates = starts(text,prefix);
232
+ for(let a=0;a+chunk.length<=n;a++)
233
+ if(candidates[a] && text.slice(a+prefix.length,a+chunk.length).toLowerCase()==="bearer ") exact[a]=1;
158
234
  }
159
- const current = new Uint8Array(n + 1), choice = new Int32Array(n + 1); choice.fill(-2);
160
- for (let a = 0; a <= n; a++) {
161
- if (text.startsWith(marker, a)) {
162
- const end = a + marker.length * widths[i];
163
- if (!text.startsWith(marker.repeat(widths[i]), a)) continue;
164
- current[a] = matches[end] ? next[end + chunk.length] ?? 0 : 0;
165
- if (current[a] === 1) choice[a] = -1; // literal marker, never a hole
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];
170
- current[a] = Math.min(2, ways);
171
- if (ways === 1) choice[a] = first[minimumEnd];
172
- }
235
+ return exact;
236
+ });
237
+ if (!matches[0][0]) throw invalid(piBase, museBase);
238
+ // Backward feasibility. A marker declares a nonempty single-line hole.
239
+ // Literal marker text is allowed inside a hole: when that loses identity,
240
+ // the evidence is ambiguous, never silently claimed exact or made fatal.
241
+ const layers: Uint8Array[] = [];
242
+ let next = new Uint8Array(n+1); if(onPrefix)next.fill(1);else next[n]=1;
243
+ const last=pieces[count],shortLast=onPrefix && last.endsWith("…") ? last.slice(0,-1) : undefined;
244
+ const shortMatches=shortLast===undefined ? undefined : starts(text,shortLast);
245
+ for(let i=count-1;i>=0;i--) {
246
+ const chunk=pieces[i+1], viable=new Uint8Array(n+1);
247
+ for(let end=0;end<=n;end++)
248
+ viable[end]=boundary(end) && ((end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && next[end+chunk.length]) ||
249
+ (i===count-1 && shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && next[end+shortLast.length])) ? 1 : 0;
250
+ layers[i]=viable;
251
+ const current=new Uint8Array(n+1); let found=false;
252
+ for(let a=n;a>=0;a--) {
253
+ // CR is a line boundary too, not something a declared hole may hide.
254
+ if(text[a]==="\r") found=false;
255
+ current[a]=found?1:0;
256
+ if(viable[a]) found=true;
173
257
  }
174
- choices[i] = choice; next = current;
175
- }
176
- let a = pieces[0].length, b = a;
177
- if (next[a] !== 1) throw invalid();
178
- const spans: Span[] = [];
179
- for (let i = 0; i < choices.length; i++) {
180
- const end = choices[i][a];
181
- if (end >= 0) spans.push({ piStart: a, piEnd: end, museStart: b });
182
- a = (end === -1 ? a + marker.length * widths[i] : end) + pieces[i + 1].length;
183
- b += marker.length * widths[i] + pieces[i + 1].length;
258
+ next=current;
184
259
  }
185
- return spans;
186
- }
187
- const piLines = pi.split("\n"), museLines = muse.split("\n");
188
- if (piLines.length !== museLines.length) throw invalid();
189
- const aligned: Span[] = []; let piBase = 0, museBase = 0;
190
- for (let i = 0; i < piLines.length; i++) {
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);
260
+ if(!next[pieces[0].length]) throw invalid(piBase, museBase);
261
+ // Forward reachable starts plus backward viable ends give all candidate
262
+ // boundaries without enumerating exponentially many complete parses.
263
+ let reachable=new Uint8Array(n+1);reachable[pieces[0].length]=1;
264
+ for(let i=0;i<count;i++) {
265
+ const viable=layers[i], chunk=pieces[i+1];
266
+ const candidateStarts:number[]=[], candidateEnds:number[]=[];
267
+ let lastEnd=-1;
268
+ for(let a=n;a>=0;a--) {
269
+ if(text[a]==="\r") lastEnd=-1;
270
+ if(reachable[a] && lastEnd>a) candidateStarts.push(a);
271
+ if(viable[a]) lastEnd=a;
272
+ }
273
+ candidateStarts.reverse();
274
+ let seen=false;
275
+ const following=new Uint8Array(n+1);let fullCut=false,shortCut=false;
276
+ for(let end=0;end<=n;end++) {
277
+ if(text[end-1]==="\r") seen=false;
278
+ if(end>0 && reachable[end-1] && text[end-1]!=="\r") seen=true;
279
+ if(seen && viable[end]) {
280
+ candidateEnds.push(end);
281
+ if(i===count-1 && onPrefix) {
282
+ if(end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && !(end+chunk.length>0 && /[\uD800-\uDBFF]/.test(text[end+chunk.length-1]))) {following[end+chunk.length]=1;fullCut=true;}
283
+ if(shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && !(end+shortLast.length>0 && /[\uD800-\uDBFF]/.test(text[end+shortLast.length-1]))) {following[end+shortLast.length]=1;shortCut=true;}
284
+ } else following[end+chunk.length]=1;
285
+ }
286
+ }
287
+ const multiple=candidateStarts.length!==1 || candidateEnds.length!==1;
288
+ const start=candidateStarts[0], end=candidateEnds.at(-1)!;
289
+ const literal=!multiple && text.slice(start,end)===marker.repeat(widths[i]);
290
+ const literalIdentity=!literal && text.slice(start,end).includes(marker);
291
+ const ambiguous=multiple || literalIdentity;
292
+ if(!literal)record(piBase+start,piBase+end,museBase+positions[i],ambiguous?"ambiguous-vendor-redaction":"vendor-redaction",ambiguous?"ambiguous":"unique",
293
+ ambiguous?{starts:candidateStarts.map(a=>piBase+a),ends:candidateEnds.map(a=>piBase+a)}:undefined);
294
+ if(!literal && ambiguous)spans.at(-1)!.ambiguityReason=multiple?"multiple-alignments":"literal-marker-identity";
295
+ // A canonicalized Bearer prefix belongs to the same declared codec loss,
296
+ // with its own exact source range (not hidden in the redaction's hash).
297
+ const prior=pieces[i];
298
+ if(prior.endsWith("Bearer ")) {
299
+ for(const a of candidateStarts) {
300
+ const p=a-7;
301
+ if(text.slice(p,a)!=="Bearer ")record(piBase+p,piBase+a,museBase+positions[i]-7,"vendor-bearer-prefix",ambiguous?"ambiguous":"unique");
302
+ }
303
+ }
304
+ reachable=following;
305
+ if(i===count-1 && onPrefix) {
306
+ const cuts:number[]=[];
307
+ for(let cut=0;cut<=n;cut++)if(following[cut] && !(cut>0 && /[\uD800-\uDBFF]/.test(text[cut-1])))cuts.push(cut);
308
+ if(!cuts.length)throw invalid(piBase,museBase);
309
+ onPrefix({cuts,ellipsisIdentity:shortLast===undefined ? "not-present" : fullCut && shortCut ? "ambiguous" : shortCut ? "generated" : "ambiguous"});
200
310
  }
201
- for (const s of spans)
202
- aligned.push({ piStart: piBase + s.piStart, piEnd: piBase + s.piEnd, museStart: museBase + s.museStart });
203
311
  }
204
- piBase += piLines[i].length + 1; museBase += museLines[i].length + 1;
205
312
  }
206
- if (!aligned.length) throw invalid();
207
- const spans = aligned.map(s => ({
208
- piOffsetBytes: Buffer.byteLength(pi.slice(0, s.piStart)),
209
- museOffsetBytes: Buffer.byteLength(muse.slice(0, s.museStart)),
210
- piByteLen: Buffer.byteLength(pi.slice(s.piStart, s.piEnd)),
211
- sha256: createHash("sha256").update(pi.slice(s.piStart, s.piEnd)).digest("hex"),
212
- }));
213
- // Reconstruct only after proving every byte outside the declared holes. The
214
- // bridge's original journal hash remains exact; the separate ledger records
215
- // that the actual vendor receipt contained holes, never exact consumption.
313
+ const piLines=pi.split("\n"), museLines=muse.split("\n");
314
+ if(piLines.length!==museLines.length)throw invalid(0,0);
315
+ let piBase=0,museBase=0;
316
+ for(let i=0;i<piLines.length;i++) {
317
+ if(onPrefix || piLines[i]!==museLines[i])line(piLines[i],museLines[i],piBase,museBase);
318
+ piBase+=piLines[i].length+1;museBase+=museLines[i].length+1;
319
+ }
320
+ if(!spans.length && !onPrefix)throw invalid(0,0);
216
321
  report?.(spans);
217
- return { content: [{type:"text",text:pi}], isError: observed.isError };
322
+ return {content:[{type:"text",text:pi}],isError:observed.isError};
218
323
  }
219
324
 
220
325
  export type OutputPage = { byteLen: number; content: string; encoding: string; eof: boolean; mediaType: string; offsetBytes: number };