pi-roundtable-sandbox 0.43.0 → 0.44.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 +4 -0
- package/README.md +1 -1
- package/package.json +4 -3
- package/src/broker-listen.ts +164 -0
- package/src/broker.ts +6 -163
- package/src/pi-broker-compaction.ts +212 -0
- package/src/pi-broker-options.ts +133 -0
- package/src/pi-broker-upstream.ts +276 -0
- package/src/pi-broker.ts +30 -566
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { ChannelKey, Logger } from "pi-roundtable";
|
|
2
|
+
import type { SandboxCredentialScope } from "./broker.ts";
|
|
3
|
+
import type {
|
|
4
|
+
PiCompaction,
|
|
5
|
+
PiCompactRequest,
|
|
6
|
+
PiThinkingLevel,
|
|
7
|
+
PiToolResponse,
|
|
8
|
+
} from "./pi-protocol.ts";
|
|
9
|
+
|
|
10
|
+
export interface PiHostContext {
|
|
11
|
+
channel: ChannelKey;
|
|
12
|
+
profile: string;
|
|
13
|
+
speaker: { id: string; name: string; principalId?: string };
|
|
14
|
+
/** The host-judged level for this turn; the worker can request less but never more. */
|
|
15
|
+
thinking: PiThinkingLevel;
|
|
16
|
+
signal: AbortSignal;
|
|
17
|
+
/** When the turn must end, in epoch milliseconds; a host compactor gets at most half the time left. */
|
|
18
|
+
deadline?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface PiMcpServer {
|
|
21
|
+
name: string;
|
|
22
|
+
url: string;
|
|
23
|
+
tools: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
/** Defaults for a host compactor's limits. */
|
|
26
|
+
export const PI_COMPACT_LIMITS = {
|
|
27
|
+
/** A larger compact request falls back to Pi's summary unread. */
|
|
28
|
+
requestBytes: 32 * 1024 * 1024,
|
|
29
|
+
/** A compactor still running after this falls back to Pi's summary. */
|
|
30
|
+
timeoutMs: 120_000,
|
|
31
|
+
/** Compact requests one turn may make; the rest fall back to Pi's summary. */
|
|
32
|
+
compactsPerTurn: 3,
|
|
33
|
+
/** Compaction reports one turn may send. */
|
|
34
|
+
reportsPerTurn: 16,
|
|
35
|
+
} as const;
|
|
36
|
+
/** Compacts a sandbox session on the host, with what the worker cannot reach (a remote service, say). */
|
|
37
|
+
export interface PiCompactor {
|
|
38
|
+
/** The `engine` this compactor's compactions record in their details; the broker stamps it. */
|
|
39
|
+
engine: string;
|
|
40
|
+
/** A compaction, or undefined to leave it to Pi's own summary. A throw also falls back. */
|
|
41
|
+
compact(
|
|
42
|
+
request: PiCompactRequest,
|
|
43
|
+
context: { channel: ChannelKey; signal: AbortSignal },
|
|
44
|
+
): Promise<PiCompaction | undefined>;
|
|
45
|
+
/** Longest a compaction may take before Pi's summary runs instead (default 120 seconds). */
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
/** Largest request accepted, in bytes (default 32 MiB); a larger one falls back to Pi's summary. */
|
|
48
|
+
maxRequestBytes?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface PiBrokerOptions {
|
|
51
|
+
model: string;
|
|
52
|
+
/** Actual configured image, named in capability failures so the operator can rebuild it. */
|
|
53
|
+
workerImage?: string;
|
|
54
|
+
/** Host-only, read before each model call for its channel and speaker; a zero-argument function still works. Return `undefined` or an empty string when the scope has no token: the call fails rather than using another credential. Never sent to the worker. */
|
|
55
|
+
oauthToken: (
|
|
56
|
+
scope: SandboxCredentialScope,
|
|
57
|
+
) => string | undefined | Promise<string | undefined>;
|
|
58
|
+
tools?: {
|
|
59
|
+
names: readonly string[];
|
|
60
|
+
call(
|
|
61
|
+
name: string,
|
|
62
|
+
input: Record<string, unknown>,
|
|
63
|
+
context: PiHostContext,
|
|
64
|
+
): Promise<PiToolResponse>;
|
|
65
|
+
};
|
|
66
|
+
mcp?: {
|
|
67
|
+
servers: readonly PiMcpServer[];
|
|
68
|
+
token: () => string | Promise<string>;
|
|
69
|
+
};
|
|
70
|
+
upstream?: string;
|
|
71
|
+
fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
|
|
72
|
+
maxCalls?: number;
|
|
73
|
+
maxOutputTokens?: number;
|
|
74
|
+
/** Trusted endpoints can use HTTP only for explicitly configured local MCP. */
|
|
75
|
+
allowHttpMcp?: boolean;
|
|
76
|
+
/** Host-side compaction; without it the worker compacts with Pi's summary alone. */
|
|
77
|
+
compaction?: PiCompactor;
|
|
78
|
+
/** Receives upstream failures and the worker's compactions, per channel. */
|
|
79
|
+
logger?: Logger;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function endpoint(raw: string, allowHttp = false): URL {
|
|
83
|
+
// pi-lens-ignore: unchecked-throwing-call -- invalid trusted endpoint configuration must fail startup.
|
|
84
|
+
const url = new URL(raw);
|
|
85
|
+
if (
|
|
86
|
+
!(url.protocol === "https:" || (allowHttp && url.protocol === "http:")) ||
|
|
87
|
+
url.username ||
|
|
88
|
+
url.password ||
|
|
89
|
+
url.hash ||
|
|
90
|
+
url.search
|
|
91
|
+
)
|
|
92
|
+
throw new Error("Invalid trusted endpoint");
|
|
93
|
+
return url;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Refuses broker options that name an untrusted endpoint, a bad name, or a budget out of range. */
|
|
97
|
+
export function validateBrokerOptions(options: PiBrokerOptions): void {
|
|
98
|
+
endpoint(options.upstream ?? "https://api.anthropic.com");
|
|
99
|
+
for (const server of options.mcp?.servers ?? []) {
|
|
100
|
+
endpoint(server.url, options.allowHttpMcp);
|
|
101
|
+
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(server.name))
|
|
102
|
+
throw new Error("Invalid MCP server name");
|
|
103
|
+
}
|
|
104
|
+
if (
|
|
105
|
+
!Number.isSafeInteger(options.maxCalls ?? 128) ||
|
|
106
|
+
(options.maxCalls ?? 128) < 1 ||
|
|
107
|
+
(options.maxCalls ?? 128) > 1000
|
|
108
|
+
)
|
|
109
|
+
throw new Error("Invalid broker budget");
|
|
110
|
+
const compaction = options.compaction;
|
|
111
|
+
if (
|
|
112
|
+
compaction &&
|
|
113
|
+
(!/^[a-zA-Z0-9@/._-]{1,100}$/.test(compaction.engine) ||
|
|
114
|
+
!Number.isSafeInteger(
|
|
115
|
+
compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs,
|
|
116
|
+
) ||
|
|
117
|
+
(compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs) < 1000 ||
|
|
118
|
+
(compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs) > 600_000 ||
|
|
119
|
+
!Number.isSafeInteger(
|
|
120
|
+
compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes,
|
|
121
|
+
) ||
|
|
122
|
+
(compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes) < 1 ||
|
|
123
|
+
(compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes) >
|
|
124
|
+
96 * 1024 * 1024)
|
|
125
|
+
)
|
|
126
|
+
throw new Error("Invalid compactor");
|
|
127
|
+
if (
|
|
128
|
+
!Number.isSafeInteger(options.maxOutputTokens ?? 128_000) ||
|
|
129
|
+
(options.maxOutputTokens ?? 128_000) < 1025 ||
|
|
130
|
+
(options.maxOutputTokens ?? 128_000) > 200_000
|
|
131
|
+
)
|
|
132
|
+
throw new Error("Invalid output-token budget");
|
|
133
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import type { ChannelKey, Logger } from "pi-roundtable";
|
|
2
|
+
import { scrubDiagnostic } from "pi-roundtable/kit";
|
|
3
|
+
import { PI_MEDIA_LIMITS } from "./pi-protocol.ts";
|
|
4
|
+
import { isRecord } from "./protocol.ts";
|
|
5
|
+
|
|
6
|
+
const RESPONSE_HEADERS = ["content-type", "request-id", "x-should-retry"];
|
|
7
|
+
/** Headers the worker's client uses to back off or recover; each value is short and checked. */
|
|
8
|
+
function passthroughHeader(name: string): boolean {
|
|
9
|
+
return (
|
|
10
|
+
name === "retry-after" ||
|
|
11
|
+
name.startsWith("anthropic-ratelimit-") ||
|
|
12
|
+
RESPONSE_HEADERS.includes(name)
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
/** An error's name, message and cause chain, for a log line. */
|
|
16
|
+
export function errorText(error: unknown): string {
|
|
17
|
+
if (!(error instanceof Error)) return String(error);
|
|
18
|
+
const text = `${error.name}: ${error.message}`;
|
|
19
|
+
return error.cause === undefined
|
|
20
|
+
? text
|
|
21
|
+
: `${text} (cause: ${errorText(error.cause)})`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Watches a server-sent event stream as it passes and reports its first `error` event: an
|
|
25
|
+
* upstream can fail mid-answer after a 200, which the status alone never shows.
|
|
26
|
+
*/
|
|
27
|
+
function sseErrorWatcher(
|
|
28
|
+
onError: (data: string) => void,
|
|
29
|
+
): (chunk: Uint8Array, done: boolean) => void {
|
|
30
|
+
const decoder = new TextDecoder();
|
|
31
|
+
let pending = "";
|
|
32
|
+
let reported = false;
|
|
33
|
+
const scan = (event: string) => {
|
|
34
|
+
const lines = event.split(/\r?\n/);
|
|
35
|
+
const type = lines
|
|
36
|
+
.find((line) => line.startsWith("event:"))
|
|
37
|
+
?.slice(6)
|
|
38
|
+
.trim();
|
|
39
|
+
const data = lines
|
|
40
|
+
.filter((line) => line.startsWith("data:"))
|
|
41
|
+
.map((line) => line.slice(5).replace(/^ /, ""))
|
|
42
|
+
.join("\n");
|
|
43
|
+
let typed: unknown;
|
|
44
|
+
try {
|
|
45
|
+
typed = JSON.parse(data);
|
|
46
|
+
} catch {
|
|
47
|
+
typed = undefined;
|
|
48
|
+
}
|
|
49
|
+
if (type === "error" || (isRecord(typed) && typed.type === "error")) {
|
|
50
|
+
reported = true;
|
|
51
|
+
onError(data);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
return (chunk, done) => {
|
|
55
|
+
if (reported) return;
|
|
56
|
+
pending += decoder.decode(chunk, { stream: !done });
|
|
57
|
+
const events = pending.split(/\r?\n\r?\n/);
|
|
58
|
+
pending = done ? "" : (events.pop() ?? "");
|
|
59
|
+
// An event this long is no error report; keep scanning without holding it.
|
|
60
|
+
if (pending.length > 64 * 1024) pending = "";
|
|
61
|
+
for (const event of events) if (!reported) scan(event);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function streamBounded(
|
|
66
|
+
response: Response,
|
|
67
|
+
signal: AbortSignal,
|
|
68
|
+
maxBytes: number,
|
|
69
|
+
secret: string,
|
|
70
|
+
onFailure: (error: unknown) => void,
|
|
71
|
+
watch?: (chunk: Uint8Array, done: boolean) => void,
|
|
72
|
+
): ReadableStream<Uint8Array> {
|
|
73
|
+
const reader = response.body?.getReader();
|
|
74
|
+
let total = 0;
|
|
75
|
+
let carry = Buffer.alloc(0);
|
|
76
|
+
const variants = [
|
|
77
|
+
secret,
|
|
78
|
+
encodeURIComponent(secret),
|
|
79
|
+
Buffer.from(secret).toString("base64"),
|
|
80
|
+
Buffer.from(secret).toString("base64url"),
|
|
81
|
+
Buffer.from(secret).toString("hex"),
|
|
82
|
+
]
|
|
83
|
+
.filter(Boolean)
|
|
84
|
+
.map((s) => Buffer.from(s));
|
|
85
|
+
const tail = Math.max(0, ...variants.map((s) => s.length)) - 1;
|
|
86
|
+
return new ReadableStream({
|
|
87
|
+
async pull(controller) {
|
|
88
|
+
try {
|
|
89
|
+
signal.throwIfAborted();
|
|
90
|
+
const result = await reader?.read();
|
|
91
|
+
const data = Buffer.concat([carry, result?.value ?? new Uint8Array()]);
|
|
92
|
+
if (variants.some((s) => data.includes(s)))
|
|
93
|
+
throw new Error("Credential reflected");
|
|
94
|
+
total += result?.value?.byteLength ?? 0;
|
|
95
|
+
if (total > maxBytes) throw new Error("Response too large");
|
|
96
|
+
watch?.(result?.value ?? new Uint8Array(), !result || result.done);
|
|
97
|
+
if (!result || result.done) {
|
|
98
|
+
if (data.length) controller.enqueue(data);
|
|
99
|
+
controller.close();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const cut = Math.max(0, data.length - tail);
|
|
103
|
+
if (cut) controller.enqueue(data.subarray(0, cut));
|
|
104
|
+
carry = data.subarray(cut);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
onFailure(error);
|
|
107
|
+
await reader?.cancel().catch(() => {});
|
|
108
|
+
controller.error(new Error("Broker response failed"));
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
cancel: () => reader?.cancel(),
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** At most `limit` bytes of a body as text; the rest is cancelled, never read. */
|
|
116
|
+
async function bodyHead(
|
|
117
|
+
body: ReadableStream<Uint8Array>,
|
|
118
|
+
limit: number,
|
|
119
|
+
): Promise<string> {
|
|
120
|
+
const reader = body.getReader();
|
|
121
|
+
const chunks: Uint8Array[] = [];
|
|
122
|
+
let size = 0;
|
|
123
|
+
try {
|
|
124
|
+
while (size < limit) {
|
|
125
|
+
const { done, value } = await reader.read();
|
|
126
|
+
if (done) break;
|
|
127
|
+
chunks.push(value);
|
|
128
|
+
size += value.byteLength;
|
|
129
|
+
}
|
|
130
|
+
} catch {
|
|
131
|
+
// The worker's branch reports a broken stream; the log keeps what arrived.
|
|
132
|
+
} finally {
|
|
133
|
+
await reader.cancel().catch(() => {});
|
|
134
|
+
}
|
|
135
|
+
return Buffer.concat(chunks).subarray(0, limit).toString("utf8");
|
|
136
|
+
}
|
|
137
|
+
/** A credential as it may appear in text: raw, URL-encoded, base64 and hex. */
|
|
138
|
+
function secretForms(secret: string): string[] {
|
|
139
|
+
if (!secret) return [];
|
|
140
|
+
return [
|
|
141
|
+
secret,
|
|
142
|
+
encodeURIComponent(secret),
|
|
143
|
+
Buffer.from(secret).toString("base64"),
|
|
144
|
+
Buffer.from(secret).toString("base64url"),
|
|
145
|
+
Buffer.from(secret).toString("hex"),
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
/** A compactor's answer, or a rejection once the signal aborts, even if the compactor ignores it. */
|
|
149
|
+
export function abortableCompact<T>(
|
|
150
|
+
promise: Promise<T>,
|
|
151
|
+
signal: AbortSignal,
|
|
152
|
+
): Promise<T> {
|
|
153
|
+
return new Promise((resolve, reject) => {
|
|
154
|
+
const abort = () => reject(signal.reason);
|
|
155
|
+
if (signal.aborted) {
|
|
156
|
+
abort();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
160
|
+
promise
|
|
161
|
+
.then(resolve, reject)
|
|
162
|
+
.finally(() => signal.removeEventListener("abort", abort));
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** Logs a failed upstream call; the secret is masked wherever it shows. */
|
|
166
|
+
export type FailureLog = (
|
|
167
|
+
secret: string,
|
|
168
|
+
failure: { status?: number; body?: string; error?: unknown },
|
|
169
|
+
) => void;
|
|
170
|
+
|
|
171
|
+
/** Logs a failed upstream call with its latency; the body and error lose any credential. */
|
|
172
|
+
export function failureLog(
|
|
173
|
+
logger: Logger | undefined,
|
|
174
|
+
channel: ChannelKey,
|
|
175
|
+
upstream: string,
|
|
176
|
+
): FailureLog {
|
|
177
|
+
const started = Date.now();
|
|
178
|
+
return (secret, failure) => {
|
|
179
|
+
const clean = (text: string) =>
|
|
180
|
+
scrubDiagnostic(
|
|
181
|
+
secretForms(secret).reduce(
|
|
182
|
+
(masked, form) => masked.replaceAll(form, "[redacted]"),
|
|
183
|
+
text,
|
|
184
|
+
),
|
|
185
|
+
2000,
|
|
186
|
+
);
|
|
187
|
+
logger?.warn(
|
|
188
|
+
{
|
|
189
|
+
channel,
|
|
190
|
+
upstream,
|
|
191
|
+
...(failure.status === undefined ? {} : { status: failure.status }),
|
|
192
|
+
latencyMs: Date.now() - started,
|
|
193
|
+
...(failure.body === undefined ? {} : { body: clean(failure.body) }),
|
|
194
|
+
...(failure.error === undefined
|
|
195
|
+
? {}
|
|
196
|
+
: { error: clean(errorText(failure.error)) }),
|
|
197
|
+
},
|
|
198
|
+
"sandbox upstream call failed",
|
|
199
|
+
);
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/** The upstream call a broker request becomes, and what the worker is told of its answer. */
|
|
203
|
+
export async function forwardUpstream(call: {
|
|
204
|
+
fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
|
|
205
|
+
target: string;
|
|
206
|
+
headers: Headers;
|
|
207
|
+
body: Record<string, unknown>;
|
|
208
|
+
signal: AbortSignal;
|
|
209
|
+
secret: string;
|
|
210
|
+
/** An MCP server's answer also carries its session id. */
|
|
211
|
+
isMcp: boolean;
|
|
212
|
+
failed: FailureLog;
|
|
213
|
+
}): Promise<Response> {
|
|
214
|
+
const { fetchImpl, target, headers, body, signal, secret, isMcp, failed } =
|
|
215
|
+
call;
|
|
216
|
+
const upstream = await fetchImpl(target, {
|
|
217
|
+
method: "POST",
|
|
218
|
+
redirect: "error",
|
|
219
|
+
headers,
|
|
220
|
+
body: JSON.stringify(body),
|
|
221
|
+
signal,
|
|
222
|
+
});
|
|
223
|
+
// Errors keep their status, body and back-off headers so the worker can recognize an
|
|
224
|
+
// oversized context, a rate limit or an expired MCP session; the same scans apply.
|
|
225
|
+
const outgoing = new Headers();
|
|
226
|
+
for (const [name, value] of upstream.headers) {
|
|
227
|
+
if (
|
|
228
|
+
passthroughHeader(name) &&
|
|
229
|
+
value.length <= 256 &&
|
|
230
|
+
!value.includes(secret)
|
|
231
|
+
)
|
|
232
|
+
outgoing.set(name, value);
|
|
233
|
+
}
|
|
234
|
+
if (isMcp) {
|
|
235
|
+
const id = upstream.headers.get("mcp-session-id");
|
|
236
|
+
if (id && !id.includes(secret) && id.length <= 256)
|
|
237
|
+
outgoing.set("mcp-session-id", id);
|
|
238
|
+
}
|
|
239
|
+
if (upstream.status < 200 || upstream.status > 599) {
|
|
240
|
+
failed(secret, { status: upstream.status });
|
|
241
|
+
return new Response("Upstream refused", { status: 502 });
|
|
242
|
+
}
|
|
243
|
+
let answer = upstream;
|
|
244
|
+
if (upstream.status >= 400 && upstream.body) {
|
|
245
|
+
// The log reads the error body's head from one branch; the worker gets all of it from the other.
|
|
246
|
+
const [logged, sent] = upstream.body.tee();
|
|
247
|
+
void bodyHead(logged, 64 * 1024).then((body) =>
|
|
248
|
+
failed(secret, { status: upstream.status, body }),
|
|
249
|
+
);
|
|
250
|
+
answer = new Response(sent, { status: upstream.status });
|
|
251
|
+
} else if (upstream.status >= 400)
|
|
252
|
+
failed(secret, { status: upstream.status });
|
|
253
|
+
return new Response(
|
|
254
|
+
upstream.status === 204 || upstream.status === 205
|
|
255
|
+
? null
|
|
256
|
+
: streamBounded(
|
|
257
|
+
answer,
|
|
258
|
+
signal,
|
|
259
|
+
PI_MEDIA_LIMITS.totalFileBytes,
|
|
260
|
+
secret,
|
|
261
|
+
(error) => failed(secret, { status: upstream.status, error }),
|
|
262
|
+
upstream.status < 400 &&
|
|
263
|
+
(upstream.headers.get("content-type") ?? "").includes(
|
|
264
|
+
"text/event-stream",
|
|
265
|
+
)
|
|
266
|
+
? sseErrorWatcher((body) =>
|
|
267
|
+
failed(secret, {
|
|
268
|
+
status: upstream.status,
|
|
269
|
+
body: `stream error event: ${body}`,
|
|
270
|
+
}),
|
|
271
|
+
)
|
|
272
|
+
: undefined,
|
|
273
|
+
),
|
|
274
|
+
{ headers: outgoing, status: upstream.status },
|
|
275
|
+
);
|
|
276
|
+
}
|