pi-muse-tether 0.2.2 → 0.2.3
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 +6 -0
- package/package.json +1 -1
- package/src/host.ts +72 -16
- package/src/provider.ts +22 -3
- package/src/rate-limit.ts +25 -1
- package/src/raw-completion.ts +2 -1
- package/src/request-ledger.ts +42 -11
- package/src/retry-status.ts +24 -3
- package/src/tool-schema.ts +54 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.3 — 2026-11-23
|
|
4
|
+
|
|
5
|
+
- Tests now refuse to write to the real request ledger, even when a test path points to it indirectly.
|
|
6
|
+
- Temporary rate limits no longer stop the client from retrying. Quota errors show the reset time when available, and empty usage events are ignored.
|
|
7
|
+
- Oversized sets of allowed values in tool schemas are rejected before sending. A response that skips required structured output now reports the failure without discarding its text, and retry messages show the cause when available.
|
|
8
|
+
|
|
3
9
|
## 0.2.2 — 2026-11-20
|
|
4
10
|
|
|
5
11
|
- A turn whose frame is over the official Muse client's 10,485,760-byte inbound limit is refused before sending instead of ending the session: the error names the measured frame size, the limit and its source, and Pi's normal overflow recovery compacts the history and retries once. Long sessions with base64 images therefore continue rather than dying mid-work.
|
package/package.json
CHANGED
package/src/host.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { featureNotice, featureActive, MuseFeatureUnavailable } from "./features
|
|
|
3
3
|
import { committedCalls } from "./batch-schema.js";
|
|
4
4
|
import { qualifyMuseVersion } from "./cli-version.js";
|
|
5
5
|
import { museEffort } from "./thinking-config.js";
|
|
6
|
-
import { publishQuota, quotaExhausted } from "./rate-limit.js";
|
|
6
|
+
import { hasQuotaData, publishQuota, quotaExhausted, quotaExhaustedResetIso } from "./rate-limit.js";
|
|
7
|
+
import { retryCause } from "./retry-status.js";
|
|
7
8
|
import { MuseLedger } from "./request-ledger.js";
|
|
8
9
|
import type { TurnInputPart } from "./wire-types.js";
|
|
9
10
|
import { homedir, tmpdir } from "node:os";
|
|
@@ -63,7 +64,7 @@ export type MuseApproval = Parameters<ApprovalHandler>[0];
|
|
|
63
64
|
export type MuseFrame = { method: string; params?: Record<string, unknown> };
|
|
64
65
|
export type MuseHostEvent =
|
|
65
66
|
| { kind: "frame"; frame: MuseFrame }
|
|
66
|
-
| { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number }
|
|
67
|
+
| { kind: "terminal"; turnId: string; status: "completed" | "cancelled" | "failed"; frame: MuseFrame; lastRetryHttpStatus?: number; lastRetryCause?: string }
|
|
67
68
|
| { kind: "fenced"; reason: string }
|
|
68
69
|
| { kind: "degraded"; feature: "rawLog"; reason: string }
|
|
69
70
|
| { kind: "tool-batch"; calls: Array<{callId:string;name:string;args:Record<string,unknown>}> }
|
|
@@ -142,15 +143,60 @@ export function serverRequiresUpgrade(error: unknown, seen = new Set<unknown>())
|
|
|
142
143
|
if ([value.status,value.httpStatus,value.code].includes(426) || [value.kind,value.errorKind,value.code].some(v => typeof v === "string" && /^(upgrade_required|client_version_unsupported|minimum_client_version|client_upgrade_required)$/.test(v))) return true;
|
|
143
144
|
return [value.error,value.data,value.cause].some(nested => serverRequiresUpgrade(nested,seen));
|
|
144
145
|
}
|
|
146
|
+
const QUOTA_EXHAUSTION_MESSAGE = /quota\s*(?:exhausted|exceeded|limit|reached)|insufficient_quota|usage\s+limit\s+reached|plan\s+limit/i;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Definitive quota exhaustion only. Temporary HTTP 429 / rate-limit bursts
|
|
150
|
+
* belong to Muse Code's own retry chain and must not be fenced as exhausted
|
|
151
|
+
* subscription quota.
|
|
152
|
+
*/
|
|
145
153
|
function quotaDenial(error: unknown, seen = new Set<unknown>()): boolean {
|
|
146
154
|
if (!error || typeof error !== "object" || seen.has(error)) return false;
|
|
147
155
|
seen.add(error);
|
|
148
156
|
const value = error as Record<string, unknown>;
|
|
149
|
-
if (
|
|
150
|
-
|
|
157
|
+
if (value.quota !== undefined && value.quota !== null && typeof value.quota === "object") return true;
|
|
158
|
+
if ([value.errorKind, value.kind, value.code].some(v => typeof v === "string" && /quota|plan.*limit/i.test(v))) return true;
|
|
159
|
+
if ([value.message, value.reason].some(v => typeof v === "string" && QUOTA_EXHAUSTION_MESSAGE.test(v))) return true;
|
|
151
160
|
return [value.data, value.error, value.cause].some(nested => quotaDenial(nested, seen));
|
|
152
161
|
}
|
|
153
162
|
|
|
163
|
+
function quotaDetails(error: unknown, seen = new Set<unknown>()): { limitKind?: string; resetsAtMs?: number; message?: string } {
|
|
164
|
+
if (!error || typeof error !== "object" || seen.has(error)) return {};
|
|
165
|
+
seen.add(error);
|
|
166
|
+
const value = error as Record<string, any>;
|
|
167
|
+
let limitKind = typeof value.quota?.limitKind === "string" && value.quota.limitKind ? value.quota.limitKind : undefined;
|
|
168
|
+
let resetsAtMs = typeof value.quota?.resetsAtMs === "number" && Number.isFinite(value.quota.resetsAtMs)
|
|
169
|
+
? value.quota.resetsAtMs
|
|
170
|
+
: typeof value.resetsAtMs === "number" && Number.isFinite(value.resetsAtMs)
|
|
171
|
+
? value.resetsAtMs
|
|
172
|
+
: undefined;
|
|
173
|
+
let message = [value.message, value.reason].find((v): v is string => typeof v === "string" && v.trim().length > 0)?.trim();
|
|
174
|
+
for (const nested of [value.error, value.data, value.cause]) {
|
|
175
|
+
if (!nested || nested === error) continue;
|
|
176
|
+
const child = quotaDetails(nested, seen);
|
|
177
|
+
limitKind ??= child.limitKind;
|
|
178
|
+
resetsAtMs ??= child.resetsAtMs;
|
|
179
|
+
message ??= child.message;
|
|
180
|
+
}
|
|
181
|
+
return { limitKind, resetsAtMs, message };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Format a quota fence preserving the provider's message and reset time while
|
|
186
|
+
* keeping "quota exceeded" in the prefix so Pi never auto-retries even when the
|
|
187
|
+
* provider text contains "429" or "rate_limit_error".
|
|
188
|
+
*/
|
|
189
|
+
function quotaFenceMessage(error: unknown): string {
|
|
190
|
+
const { limitKind, resetsAtMs, message } = quotaDetails(error);
|
|
191
|
+
const meta = [limitKind, resetsAtMs !== undefined ? `resets at ${new Date(resetsAtMs).toISOString()}` : undefined]
|
|
192
|
+
.filter(Boolean)
|
|
193
|
+
.join(", ");
|
|
194
|
+
const detail = [meta, message].filter(Boolean).join(" — ");
|
|
195
|
+
return detail
|
|
196
|
+
? `Muse quota refused (quota exceeded); no replay: ${detail}`
|
|
197
|
+
: "Muse quota refused (quota exceeded); no replay";
|
|
198
|
+
}
|
|
199
|
+
|
|
154
200
|
const canonical = (v:any):string => v && typeof v === "object"
|
|
155
201
|
? Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
|
|
156
202
|
: JSON.stringify(v);
|
|
@@ -241,6 +287,7 @@ export class MuseHost {
|
|
|
241
287
|
#committedCalls = new Map<string, string>();
|
|
242
288
|
#committedBatches = new Set<string>();
|
|
243
289
|
#lastRetryHttpStatus?: number;
|
|
290
|
+
#lastRetryCause?: string;
|
|
244
291
|
#logSubscription?: number;
|
|
245
292
|
#steers = new Set<string>();
|
|
246
293
|
#discarded = new DiscardedSessions();
|
|
@@ -467,7 +514,10 @@ export class MuseHost {
|
|
|
467
514
|
}
|
|
468
515
|
return;
|
|
469
516
|
}
|
|
470
|
-
if (frame.method === "usage/changed") {
|
|
517
|
+
if (frame.method === "usage/changed") {
|
|
518
|
+
if (hasQuotaData(frame.params)) { publishQuota(frame.params); this.ledger.quota(frame.params); }
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
471
521
|
if (typeof frame.params?.sessionId !== "string") return;
|
|
472
522
|
if (this.#opening && !this.#session) { this.#held.push(frame); return; }
|
|
473
523
|
if (this.#session && frame.params.sessionId === this.sessionId) this.#apply(frame);
|
|
@@ -494,7 +544,7 @@ export class MuseHost {
|
|
|
494
544
|
}
|
|
495
545
|
if (quotaDenial(params.error) || (retry && quotaDenial(params))) {
|
|
496
546
|
this.#emit({kind:"frame",frame});
|
|
497
|
-
this.fence(
|
|
547
|
+
this.fence(quotaFenceMessage(quotaDenial(params.error) ? params.error : params)); return;
|
|
498
548
|
}
|
|
499
549
|
if(retry){
|
|
500
550
|
if(!this.#busy || params.turnId!==this.#submission?.turnId) {
|
|
@@ -507,7 +557,9 @@ export class MuseHost {
|
|
|
507
557
|
// An unknown or missing kind must not end live work; account, quota, policy
|
|
508
558
|
// and upgrade refusals were already decided above, and the terminal frame
|
|
509
559
|
// still reports the real outcome and status.
|
|
510
|
-
if(typeof params.httpStatus==="number")this.#lastRetryHttpStatus=params.httpStatus;
|
|
560
|
+
if(typeof params.httpStatus==="number" && Number.isFinite(params.httpStatus))this.#lastRetryHttpStatus=params.httpStatus;
|
|
561
|
+
const cause = retryCause(params);
|
|
562
|
+
if (cause) this.#lastRetryCause = cause;
|
|
511
563
|
}
|
|
512
564
|
if (frame.method === "session/closed" && this.#busy) {
|
|
513
565
|
this.fence("Muse session closed during pending work; no replay"); return;
|
|
@@ -562,7 +614,7 @@ export class MuseHost {
|
|
|
562
614
|
const finish=()=>{
|
|
563
615
|
if(this.#reason||this.#closing||this.#dead)return;
|
|
564
616
|
this.#busy=false;
|
|
565
|
-
this.#emit({kind:"terminal",turnId:String(params.turnId),status:params.terminal as "completed"|"cancelled"|"failed",frame,lastRetryHttpStatus:this.#lastRetryHttpStatus});
|
|
617
|
+
this.#emit({kind:"terminal",turnId:String(params.turnId),status:params.terminal as "completed"|"cancelled"|"failed",frame,lastRetryHttpStatus:this.#lastRetryHttpStatus,lastRetryCause:this.#lastRetryCause});
|
|
566
618
|
};
|
|
567
619
|
// Do not release a completed coding turn (and permit a new auxiliary
|
|
568
620
|
// host) until refresh metadata is known safe. No credential bytes read.
|
|
@@ -620,18 +672,22 @@ export class MuseHost {
|
|
|
620
672
|
if (frameBytes > MUSE_INBOUND_FRAME_LIMIT_BYTES) throw new MuseFrameOverInboundLimit(frameBytes);
|
|
621
673
|
await this.#options.verifyLogin?.();
|
|
622
674
|
if (!this.#options.echo) {
|
|
623
|
-
const result = await this.connection.request("usage/read", {}).catch(error=>{if(!this.#refusal(error) && quotaDenial(error))this.fence(
|
|
675
|
+
const result = await this.connection.request("usage/read", {}).catch(error=>{if(!this.#refusal(error) && quotaDenial(error))this.fence(quotaFenceMessage(error));throw error;});
|
|
624
676
|
const usage = result.usage as any;
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
677
|
+
if (hasQuotaData(usage)) {
|
|
678
|
+
publishQuota(usage); this.ledger.quota(usage);
|
|
679
|
+
// Muse reports percentages; 100% is the provider's exhausted plan boundary.
|
|
680
|
+
if (quotaExhausted(usage)) {
|
|
681
|
+
const resetIso = quotaExhaustedResetIso(usage);
|
|
682
|
+
const msg = `Muse plan usage limit reached (quota exceeded); no turn submitted${resetIso ? ` (resets at ${resetIso})` : ""}`;
|
|
683
|
+
this.fence(msg);
|
|
684
|
+
throw new Error(msg);
|
|
685
|
+
}
|
|
630
686
|
}
|
|
631
687
|
}
|
|
632
688
|
const submission: Submission = { commandId, turnId: undefined, terminal: false, started: false };
|
|
633
689
|
this.#submission = submission;
|
|
634
|
-
this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined;
|
|
690
|
+
this.#committedCalls.clear(); this.#committedBatches.clear(); this.#lastRetryHttpStatus=undefined; this.#lastRetryCause=undefined;
|
|
635
691
|
this.#retrySafe = false;
|
|
636
692
|
this.#busy = true;
|
|
637
693
|
try {
|
|
@@ -673,7 +729,7 @@ export class MuseHost {
|
|
|
673
729
|
this.#refusal(error);
|
|
674
730
|
if (quotaDenial(error) && !policyDenial(error)) {
|
|
675
731
|
this.ledger.record("quota_refusal", {phase:"turn_admission"});
|
|
676
|
-
this.fence(
|
|
732
|
+
this.fence(quotaFenceMessage(error));
|
|
677
733
|
} else this.fence(`${policyDenial(error) ? "Muse nonretryable provider refusal" : "Muse turn admission failed; no replay"}: ${error instanceof Error ? error.message : String(error)}`);
|
|
678
734
|
throw error;
|
|
679
735
|
}
|
package/src/provider.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
} from "pi-tether-core/mcp/bridge";
|
|
24
24
|
import { openMuseHost, type MuseHost } from "./host.js";
|
|
25
25
|
import { streamRawCompletion } from "./raw-completion.js";
|
|
26
|
+
import { assertToolSchemasWithinEnumLimit } from "./tool-schema.js";
|
|
26
27
|
import type { MuseHostOptions } from "./host.js";
|
|
27
28
|
|
|
28
29
|
import { isQualifiedMuseModel, museResponseIdentity, museModelRoute } from "./model-route.js";
|
|
@@ -372,11 +373,12 @@ function emitFrame(b: Binding, event: any) {
|
|
|
372
373
|
// confirmed by turn/steer. A completed target must fail loudly, not drop it.
|
|
373
374
|
if (b.steeringPending && event.status === "completed") { b.deferredTerminal=event; return; }
|
|
374
375
|
if (event.status !== "completed") {
|
|
375
|
-
const
|
|
376
|
+
const error = event.frame?.params?.error;
|
|
377
|
+
const detail = [error?.message, event.frame?.params?.reason, error?.kind, event.lastRetryCause]
|
|
378
|
+
.find((v): v is string => typeof v === "string" && v.trim().length > 0);
|
|
376
379
|
// Preserve Pi's native overflow entry path without introducing a new
|
|
377
380
|
// generic retry policy or replaying an uncertain host request.
|
|
378
381
|
const overflow = typeof detail === "string" && isContextOverflow({...e.output,stopReason:"error",errorMessage:detail});
|
|
379
|
-
const error = event.frame?.params?.error;
|
|
380
382
|
const status = error?.httpStatus ?? error?.status ?? error?.statusCode ?? (event.status === "failed" ? event.lastRetryHttpStatus : undefined);
|
|
381
383
|
fail(b, overflow ? `Muse context overflow: ${detail}` : `Muse turn ended ${event.status}${typeof status === "number" ? ` (HTTP ${status})` : ""}${typeof detail === "string" ? `: ${detail}` : ""}`);
|
|
382
384
|
return;
|
|
@@ -394,6 +396,21 @@ function emitFrame(b: Binding, event: any) {
|
|
|
394
396
|
content: e.output.content[e.textIndex].text,
|
|
395
397
|
partial: e.output,
|
|
396
398
|
});
|
|
399
|
+
const expectsStructured = b.tools.some((t) => t.name === "structured_output");
|
|
400
|
+
const satisfiedStructured = b.messages.some(
|
|
401
|
+
(m: any) => m?.role === "toolResult" && m.toolName === "structured_output" && !m.isError,
|
|
402
|
+
);
|
|
403
|
+
if (expectsStructured && !satisfiedStructured) {
|
|
404
|
+
const textLength = e.output.content
|
|
405
|
+
.filter((part: any) => part?.type === "text" && typeof part.text === "string")
|
|
406
|
+
.reduce((sum: number, part: any) => sum + part.text.length, 0);
|
|
407
|
+
b.host?.ledger?.record("structured_output_omitted", { textLength });
|
|
408
|
+
fail(
|
|
409
|
+
b,
|
|
410
|
+
"Muse turn completed with plain text without calling declared structured_output; plain text preserved on the assistant message, no automatic resubmit",
|
|
411
|
+
);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
397
414
|
e.ended = true;
|
|
398
415
|
e.detachAbort?.();
|
|
399
416
|
b.messages.push(structuredClone(e.output));
|
|
@@ -694,7 +711,6 @@ function streamEffective(model: any, input: any, options: any = {}) {
|
|
|
694
711
|
// A genuinely new user request ends the old failure fence. Otherwise that
|
|
695
712
|
// stale fence would incorrectly block this new request's later tool batch.
|
|
696
713
|
if(blocked && context.messages.at(-1)?.role==="user")retryBlocks.delete(key);
|
|
697
|
-
b = bindings.get(key);
|
|
698
714
|
if (!context.tools.length)
|
|
699
715
|
throw new Error("Muse raw completion and compaction are unsupported");
|
|
700
716
|
const mode = requestedMode;
|
|
@@ -710,6 +726,9 @@ function streamEffective(model: any, input: any, options: any = {}) {
|
|
|
710
726
|
description: t.description,
|
|
711
727
|
inputSchema: t.parameters,
|
|
712
728
|
}));
|
|
729
|
+
// Refuse schemas over the provider's 3,000-enum cap locally before
|
|
730
|
+
// touching any binding or spawning a host; nothing was submitted.
|
|
731
|
+
assertToolSchemasWithinEnumLimit(tools);
|
|
713
732
|
const declarationHash = projectionHash(tools);
|
|
714
733
|
const route = museModelRoute(model.id);
|
|
715
734
|
const signature = requestSignature([model.id, route?.contributorMode, context.systemPrompt, tools, mode, process.cwd()]);
|
package/src/rate-limit.ts
CHANGED
|
@@ -25,9 +25,33 @@ export function quotaStatusLine(p: ReturnType<typeof quotaPayload>) {
|
|
|
25
25
|
const span = mins === null ? "window" : mins % 60 === 0 ? `${mins / 60}h` : `${mins}m`;
|
|
26
26
|
return `Muse ${span} ${pct(p.window.usedPercent)}${at(p.window.resetsAtMs)} · week ${pct(p.weekly.usedPercent)}`;
|
|
27
27
|
}
|
|
28
|
+
export function hasQuotaData(u: any): boolean {
|
|
29
|
+
const p = quotaPayload(u);
|
|
30
|
+
return (
|
|
31
|
+
p.observedAtMs !== null ||
|
|
32
|
+
p.tier !== null ||
|
|
33
|
+
p.window.usedPercent !== null ||
|
|
34
|
+
p.window.resetsAtMs !== null ||
|
|
35
|
+
p.window.windowDurationMins !== null ||
|
|
36
|
+
p.weekly.usedPercent !== null ||
|
|
37
|
+
p.weekly.resetsAtMs !== null
|
|
38
|
+
);
|
|
39
|
+
}
|
|
28
40
|
export function quotaExhausted(u: any) {
|
|
29
|
-
|
|
41
|
+
const windowPct = num(u?.window?.usedPercent);
|
|
42
|
+
const weeklyPct = num(u?.weekly?.usedPercent);
|
|
43
|
+
return (windowPct !== null && windowPct >= 100) || (weeklyPct !== null && weeklyPct >= 100);
|
|
30
44
|
} // vendor exhausted boundary
|
|
45
|
+
export function quotaExhaustedResetIso(u: any): string | undefined {
|
|
46
|
+
const resets: number[] = [];
|
|
47
|
+
const windowPct = num(u?.window?.usedPercent);
|
|
48
|
+
const windowReset = num(u?.window?.resetsAtMs);
|
|
49
|
+
if (windowPct !== null && windowPct >= 100 && windowReset !== null) resets.push(windowReset);
|
|
50
|
+
const weeklyPct = num(u?.weekly?.usedPercent);
|
|
51
|
+
const weeklyReset = num(u?.weekly?.resetsAtMs);
|
|
52
|
+
if (weeklyPct !== null && weeklyPct >= 100 && weeklyReset !== null) resets.push(weeklyReset);
|
|
53
|
+
return resets.length ? new Date(Math.max(...resets)).toISOString() : undefined;
|
|
54
|
+
}
|
|
31
55
|
let listener: ((p: ReturnType<typeof quotaPayload>) => void) | undefined;
|
|
32
56
|
let lastIdentity: string | undefined;
|
|
33
57
|
export function setQuotaListener(fn: typeof listener) {
|
package/src/raw-completion.ts
CHANGED
|
@@ -36,7 +36,8 @@ export function streamRawCompletion(model:any, context:any, options:any, makeMes
|
|
|
36
36
|
publishRetryStatus(statusOwner);
|
|
37
37
|
const error=event.frame?.params?.error;
|
|
38
38
|
const status=error?.httpStatus??error?.status??error?.statusCode??(event.status==="failed"?event.lastRetryHttpStatus:undefined);
|
|
39
|
-
|
|
39
|
+
const detail=[error?.message,event.frame?.params?.reason,error?.kind,event.lastRetryCause].find((v):v is string=>typeof v==="string"&&v.trim().length>0);
|
|
40
|
+
if(event.status!=="completed")refuse(new Error(`Muse raw completion ended ${event.status}${typeof status==="number"?` (HTTP ${status})`:""}${detail?`: ${detail}`:""}`));else finish();
|
|
40
41
|
return;
|
|
41
42
|
}
|
|
42
43
|
if(event.kind!=="frame")return;
|
package/src/request-ledger.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import { isAbsolute, join, resolve } from "node:path";
|
|
2
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import { homedir, userInfo } from "node:os";
|
|
4
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
5
5
|
import { metadataLedger } from "pi-tether-core/metadata-ledger";
|
|
6
6
|
import { nativeCounters } from "./usage.js";
|
|
7
7
|
import { quotaPayload } from "./rate-limit.js";
|
|
@@ -11,20 +11,50 @@ function ledgerOrigin(): 'live' | 'test' | 'proof' {
|
|
|
11
11
|
const origin = process.env.PI_MUSE_TETHER_LEDGER_ORIGIN;
|
|
12
12
|
return origin === 'test' || origin === 'proof' ? origin : 'live';
|
|
13
13
|
}
|
|
14
|
+
/** Resolve symlinks on the nearest existing ancestor so symlinked state dirs cannot alias production. */
|
|
15
|
+
function canonicalPath(target: string): string {
|
|
16
|
+
const abs = resolve(target);
|
|
17
|
+
const tail: string[] = [];
|
|
18
|
+
let cursor = abs;
|
|
19
|
+
for (;;) {
|
|
20
|
+
try {
|
|
21
|
+
const real = realpathSync(cursor);
|
|
22
|
+
return tail.length ? join(real, ...tail.reverse()) : real;
|
|
23
|
+
} catch (error: any) {
|
|
24
|
+
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') return abs;
|
|
25
|
+
const parent = dirname(cursor);
|
|
26
|
+
if (parent === cursor) return abs;
|
|
27
|
+
tail.push(cursor.slice(parent.length).replace(/^\/+/, ''));
|
|
28
|
+
cursor = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function productionLedgerPaths(): string[] {
|
|
33
|
+
const homes = new Set<string>([homedir()]);
|
|
34
|
+
try { homes.add(userInfo().homedir); } catch { /* passwd entry unavailable */ }
|
|
35
|
+
return [...homes].map(home => canonicalPath(join(home, '.local/state/pi-muse-tether/requests.jsonl')));
|
|
36
|
+
}
|
|
14
37
|
const num = (v: any) =>
|
|
15
38
|
typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
16
39
|
export function museLedgerPath() {
|
|
40
|
+
const explicit = process.env.PI_MUSE_TETHER_LEDGER_PATH;
|
|
17
41
|
const state = process.env.XDG_STATE_HOME;
|
|
18
42
|
// XDG Base Directory requires absolute values; empty/relative values are
|
|
19
43
|
// treated as unset, never a request to write metadata beneath the cwd.
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
44
|
+
const hasExplicit = Boolean(explicit && isAbsolute(explicit));
|
|
45
|
+
const path = hasExplicit
|
|
46
|
+
? resolve(explicit!)
|
|
47
|
+
: join(
|
|
48
|
+
state && isAbsolute(state) ? state : join(homedir(), ".local/state"),
|
|
49
|
+
"pi-muse-tether",
|
|
50
|
+
"requests.jsonl",
|
|
51
|
+
);
|
|
52
|
+
if (ledgerOrigin() !== 'live') {
|
|
53
|
+
const prodPaths = productionLedgerPaths();
|
|
54
|
+
const resolved = canonicalPath(path);
|
|
55
|
+
if ((!hasExplicit && (!state || !isAbsolute(state))) || prodPaths.includes(resolved)) {
|
|
56
|
+
throw new Error('Test/proof request ledger requires an isolated absolute XDG_STATE_HOME or PI_MUSE_TETHER_LEDGER_PATH; refusing the production ledger.');
|
|
57
|
+
}
|
|
28
58
|
}
|
|
29
59
|
return path;
|
|
30
60
|
}
|
|
@@ -95,6 +125,7 @@ export class MuseLedger {
|
|
|
95
125
|
attempt: num(p.attempt), nextAttempt: num(p.nextAttempt), maxAttempts: num(p.maxAttempts),
|
|
96
126
|
retryDelayMs: num(p.retryDelayMs), httpStatus: num(p.httpStatus),
|
|
97
127
|
errorKind: typeof p.errorKind === "string" ? p.errorKind : null,
|
|
128
|
+
reason: typeof p.reason === "string" ? p.reason : null,
|
|
98
129
|
system: typeof p.system === "string" ? p.system : null,
|
|
99
130
|
sourceRange: p.sourceRange ?? null, viewCursor: p.viewCursor ?? null,
|
|
100
131
|
});
|
package/src/retry-status.ts
CHANGED
|
@@ -8,14 +8,35 @@ export function publishRedactionStatus(owner: object, count: number) {
|
|
|
8
8
|
statuses.set(owner, `Muse redacted ${count} tool-result span${count === 1 ? "" : "s"} (vendor limit; not byte-exact model input)`);
|
|
9
9
|
listener?.([...statuses.values()].at(-1));
|
|
10
10
|
}
|
|
11
|
+
const text = (v: unknown) => (typeof v === "string" && v.trim().length ? v.trim() : undefined);
|
|
12
|
+
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
13
|
+
|
|
14
|
+
/** Extract the real underlying cause from a retry notification without rendering undefined/null. */
|
|
15
|
+
export function retryCause(params?: Record<string, any>): string | undefined {
|
|
16
|
+
if (!params || typeof params !== "object") return undefined;
|
|
17
|
+
const detail = text(params.errorKind) ?? text(params.reason) ?? text(params.error?.message) ?? text(params.error?.kind);
|
|
18
|
+
const parts = [text(params.system), detail].filter((v): v is string => Boolean(v));
|
|
19
|
+
return parts.length ? parts.join(": ") : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
11
22
|
export function publishRetryStatus(owner: object, params?: Record<string, any>) {
|
|
12
23
|
statuses.delete(owner);
|
|
13
24
|
if(params){
|
|
14
25
|
// The durable retry kind and HTTP status are optional open-vocabulary vendor
|
|
15
26
|
// fields; the recorded stopping reason is the real cause when either is absent.
|
|
16
|
-
const cause=
|
|
17
|
-
|
|
18
|
-
|
|
27
|
+
const cause = retryCause(params);
|
|
28
|
+
const nextAttempt = num(params.nextAttempt);
|
|
29
|
+
const maxAttempts = num(params.maxAttempts);
|
|
30
|
+
const retryDelayMs = num(params.retryDelayMs);
|
|
31
|
+
const httpStatus = num(params.httpStatus);
|
|
32
|
+
const attempt = nextAttempt !== undefined && maxAttempts !== undefined
|
|
33
|
+
? ` ${nextAttempt}/${maxAttempts}`
|
|
34
|
+
: nextAttempt !== undefined
|
|
35
|
+
? ` ${nextAttempt}`
|
|
36
|
+
: "";
|
|
37
|
+
const delay = retryDelayMs !== undefined ? ` in ${retryDelayMs} ms` : "";
|
|
38
|
+
const status = httpStatus !== undefined ? `, HTTP ${httpStatus}` : "";
|
|
39
|
+
statuses.set(owner, `Muse retry${attempt} scheduled${delay} (${cause || "cause not reported"}${status})`);
|
|
19
40
|
}
|
|
20
41
|
listener?.([...statuses.values()].at(-1));
|
|
21
42
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Muse provider API rejects any tool parameter JSON schema whose total
|
|
3
|
+
* enum values across all `enum` properties exceed 3,000. Vendor-imposed, not
|
|
4
|
+
* chosen here: observed 2026-11-20 against the Muse provider API as
|
|
5
|
+
* `API error 400: JSON schema exceeds the maximum of 3000 total enum values
|
|
6
|
+
* across all enum properties (invalid_request_error) [param=parameters]`
|
|
7
|
+
* (~3,750 enum values rejected; half-size payload accepted).
|
|
8
|
+
*/
|
|
9
|
+
export const MUSE_TOOL_SCHEMA_ENUM_LIMIT = 3_000;
|
|
10
|
+
|
|
11
|
+
/** Count total values across every `enum` array inside a JSON Schema object. */
|
|
12
|
+
export function countSchemaEnumValues(schema: unknown, seen = new Set<object>()): number {
|
|
13
|
+
if (!schema || typeof schema !== "object") return 0;
|
|
14
|
+
if (seen.has(schema)) return 0;
|
|
15
|
+
seen.add(schema);
|
|
16
|
+
if (Array.isArray(schema)) {
|
|
17
|
+
let total = 0;
|
|
18
|
+
for (const item of schema) total += countSchemaEnumValues(item, seen);
|
|
19
|
+
return total;
|
|
20
|
+
}
|
|
21
|
+
let total = 0;
|
|
22
|
+
for (const [key, value] of Object.entries(schema as Record<string, unknown>)) {
|
|
23
|
+
if (key === "enum" && Array.isArray(value)) {
|
|
24
|
+
total += value.length;
|
|
25
|
+
} else if (value && typeof value === "object") {
|
|
26
|
+
total += countSchemaEnumValues(value, seen);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return total;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Nothing was submitted: the provider API rejects schemas above this enum cap. */
|
|
33
|
+
export class MuseToolSchemaEnumLimitError extends Error {
|
|
34
|
+
readonly code = "MUSE_TOOL_SCHEMA_ENUM_LIMIT";
|
|
35
|
+
constructor(
|
|
36
|
+
readonly toolName: string,
|
|
37
|
+
readonly enumCount: number,
|
|
38
|
+
readonly limit: number = MUSE_TOOL_SCHEMA_ENUM_LIMIT,
|
|
39
|
+
) {
|
|
40
|
+
super(
|
|
41
|
+
`Muse request not sent: tool "${toolName}" JSON schema has ${enumCount} total enum values, exceeding the provider limit of ${limit} total enum values across all enum properties (source: observed 2026-11-20 from the Muse provider API as HTTP 400 invalid_request_error [param=parameters]). Simplify or split the schema and retry; nothing was submitted.`,
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function assertToolSchemasWithinEnumLimit(
|
|
47
|
+
tools: ReadonlyArray<{ name: string; inputSchema: unknown }>,
|
|
48
|
+
limit: number = MUSE_TOOL_SCHEMA_ENUM_LIMIT,
|
|
49
|
+
): void {
|
|
50
|
+
for (const tool of tools) {
|
|
51
|
+
const count = countSchemaEnumValues(tool.inputSchema);
|
|
52
|
+
if (count > limit) throw new MuseToolSchemaEnumLimitError(tool.name, count, limit);
|
|
53
|
+
}
|
|
54
|
+
}
|