@herbertgao/pi-extensions 2026.10.7 → 2026.10.9
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/README.md +4 -5
- package/THIRD_PARTY_NOTICES.md +2 -28
- package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +28 -27
- package/node_modules/@herbertgao/pi-cc-extensions/README.md +6 -6
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +16 -27
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +49 -48
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +2 -3
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +0 -60
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/reference/index.ts +2 -3
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer-layout.ts +105 -23
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +59 -43
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +96 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/index.ts +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +36 -34
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +7 -4
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +3 -2
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +23 -8
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +2 -2
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +24 -12
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/codemode.ts +121 -6
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-limits.ts +3 -2
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-palette.ts +39 -8
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/diff-presentation.ts +2 -2
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +13 -13
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/message-display.ts +3 -2
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +49 -49
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/result.ts +24 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-state.ts +51 -2
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
- package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-dark.json +71 -70
- package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-light.json +71 -70
- package/node_modules/@tifan/pi-inline-skills/package.json +5 -1
- package/node_modules/@tifan/pi-inline-skills/src/index.ts +5 -2
- package/node_modules/pi-provider-qoder/dist/index.js +136 -31
- package/node_modules/pi-provider-qoder/package.json +1 -1
- package/node_modules/pi-typesafe/README.md +3 -3
- package/node_modules/pi-typesafe/dist/backends.d.ts +7 -2
- package/node_modules/pi-typesafe/dist/backends.js +42 -0
- package/node_modules/pi-typesafe/dist/batch.d.ts +10 -6
- package/node_modules/pi-typesafe/dist/batch.js +20 -9
- package/node_modules/pi-typesafe/dist/client.d.ts +4 -1
- package/node_modules/pi-typesafe/dist/client.js +5 -4
- package/node_modules/pi-typesafe/dist/index.d.ts +2 -2
- package/node_modules/pi-typesafe/dist/index.js +1 -1
- package/node_modules/pi-typesafe/dist/schema.d.ts +18 -3
- package/node_modules/pi-typesafe/dist/schema.js +29 -3
- package/node_modules/pi-typesafe/package.json +1 -1
- package/node_modules/pi-web-access/CHANGELOG.md +16 -0
- package/node_modules/pi-web-access/README.md +5 -2
- package/node_modules/pi-web-access/dist/index.js +13 -2
- package/node_modules/pi-web-access/dist/mcp-cli.js +14 -3
- package/node_modules/pi-web-access/extract.ts +4 -2
- package/node_modules/pi-web-access/package.json +1 -1
- package/node_modules/pi-web-access/searxng.ts +2 -1
- package/node_modules/pi-web-access/ssrf-protection.ts +11 -0
- package/package.json +6 -11
- package/node_modules/pi-multi-account/CHANGELOG.md +0 -1264
- package/node_modules/pi-multi-account/CONTRIBUTING.md +0 -61
- package/node_modules/pi-multi-account/LICENSE +0 -21
- package/node_modules/pi-multi-account/README.md +0 -277
- package/node_modules/pi-multi-account/SECURITY.md +0 -27
- package/node_modules/pi-multi-account/auth-file-transaction.ts +0 -56
- package/node_modules/pi-multi-account/child-usability.ts +0 -233
- package/node_modules/pi-multi-account/compaction-summary.ts +0 -32
- package/node_modules/pi-multi-account/completion-route-planner.ts +0 -224
- package/node_modules/pi-multi-account/config-file-transaction.ts +0 -42
- package/node_modules/pi-multi-account/context-guard.ts +0 -420
- package/node_modules/pi-multi-account/cursor/LICENSE +0 -21
- package/node_modules/pi-multi-account/cursor/NOTICE +0 -2
- package/node_modules/pi-multi-account/cursor/auth.ts +0 -165
- package/node_modules/pi-multi-account/cursor/bridge-handle.ts +0 -155
- package/node_modules/pi-multi-account/cursor/conversation-registry.ts +0 -104
- package/node_modules/pi-multi-account/cursor/cursor-models-raw.json +0 -611
- package/node_modules/pi-multi-account/cursor/cursor-shared.ts +0 -192
- package/node_modules/pi-multi-account/cursor/h2-bridge.mjs +0 -175
- package/node_modules/pi-multi-account/cursor/index.ts +0 -572
- package/node_modules/pi-multi-account/cursor/message-parsing.ts +0 -323
- package/node_modules/pi-multi-account/cursor/prompt-usage.ts +0 -53
- package/node_modules/pi-multi-account/cursor/proto/agent_pb.ts +0 -15294
- package/node_modules/pi-multi-account/cursor/proxy.ts +0 -2510
- package/node_modules/pi-multi-account/cursor/session-lifecycle.ts +0 -40
- package/node_modules/pi-multi-account/cursor/sse-keepalive.ts +0 -24
- package/node_modules/pi-multi-account/cursor/stream-lifecycle.ts +0 -193
- package/node_modules/pi-multi-account/cursor/upstream-watchdog.ts +0 -88
- package/node_modules/pi-multi-account/cursor-bridge.ts +0 -240
- package/node_modules/pi-multi-account/cursor-model-name.ts +0 -12
- package/node_modules/pi-multi-account/index.ts +0 -12340
- package/node_modules/pi-multi-account/model-catalog.ts +0 -354
- package/node_modules/pi-multi-account/model-pins.ts +0 -36
- package/node_modules/pi-multi-account/package.json +0 -104
- package/node_modules/pi-multi-account/pi-contract.ts +0 -281
- package/node_modules/pi-multi-account/provider-payload-stream.ts +0 -52
- package/node_modules/pi-multi-account/provider-priority.ts +0 -189
- package/node_modules/pi-multi-account/slot-proxy-auth.ts +0 -177
- package/node_modules/pi-multi-account/slot-proxy.ts +0 -366
- package/node_modules/pi-multi-account/state-file-transaction.ts +0 -67
- package/node_modules/pi-multi-account/usage.ts +0 -1128
|
@@ -85,7 +85,7 @@ An enabled extension with no usable key looks exactly like a working one — one
|
|
|
85
85
|
|
|
86
86
|
The environment may lower an explicit cap but never raise it. A reached cap raises a `budget` error naming the cap, the amount used, and the day.
|
|
87
87
|
|
|
88
|
-
Need more than one request? `evaluateAll(request)` asks any number of questions about one state (over 32 are chunked and fanned out), and `evaluateMany(requests)` runs several requests at once. Both preserve order, bound concurrency, never throw, and stop submitting once the budget is gone. [`pi-typesafe/calibrate`](docs/api.md#calibration-pi-typesafecalibrate) turns labelled cases into thresholds with AUC, a sweep, and a replay runner.
|
|
88
|
+
Need more than one request? `evaluateAll(request)` asks any number of questions about one state (over the backend's limit, 32 or 16 on SubQ, are chunked and fanned out), and `evaluateMany(requests)` runs several requests at once. Both preserve order, bound concurrency, never throw, and stop submitting once the budget is gone. [`pi-typesafe/calibrate`](docs/api.md#calibration-pi-typesafecalibrate) turns labelled cases into thresholds with AUC, a sweep, and a replay runner.
|
|
89
89
|
|
|
90
90
|
## Commands
|
|
91
91
|
|
|
@@ -117,7 +117,7 @@ The main model can answer any of these questions in prose. It is slower, costs m
|
|
|
117
117
|
Only the state and questions you (or the agent, once enabled) submit, to `https://api.typesafe.ai` only. No files, conversation history, or telemetry. Error messages never include upstream response bodies, headers, keys, or your submitted state.
|
|
118
118
|
|
|
119
119
|
**Limits?**
|
|
120
|
-
Per request: 32 questions and 64 KiB of JSON. Per session: 20 attempts, 15-second timeout, no automatic retries. Per day: no cap unless you set one. Session limits reset when a session starts or reloads; daily counters live in `~/.pi/agent/pi-typesafe/usage.json` and roll over at local midnight. The SDK's `TYPESAFE_BASE_URL` and `TYPESAFE_LOG_LEVEL` overrides are ignored.
|
|
120
|
+
Per request: 32 questions (16 on SubQ) and 64 KiB of JSON. Per session: 20 attempts, 15-second timeout, no automatic retries. Per day: no cap unless you set one. Session limits reset when a session starts or reloads; daily counters live in `~/.pi/agent/pi-typesafe/usage.json` and roll over at local midnight. The SDK's `TYPESAFE_BASE_URL` and `TYPESAFE_LOG_LEVEL` overrides are ignored.
|
|
121
121
|
|
|
122
122
|
## For extension authors
|
|
123
123
|
|
|
@@ -142,7 +142,7 @@ if (!answer.ok) return { skipped: answer.errorCode === "budget" }; // never thr
|
|
|
142
142
|
|
|
143
143
|
Your extension owns its own user consent and budget; `/typesafe enable` applies only to this package's tool. Check `authState()` rather than your own consent flag before you report that judgments are on.
|
|
144
144
|
|
|
145
|
-
Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. These backends have no login store, so `/typesafe login` does not apply to them. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool always use the TypeSafe backend. Every export — the client, `ask`, batching, the usage ledger, auth state, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
|
|
145
|
+
Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. SubQ too: `createTypeSafe({ backend: "subq" })` sends them to `api.subq.ai` with the key from `SUBQ_API_KEY` and the model `subq-snap-preview`, priced at $0.05 per million input tokens. SubQ takes at most 16 questions in one request, a Choice of at least 2 options, and a Score of at most 10 levels: `evaluate` refuses a larger request before it sends it, `evaluateAll` splits to 16, and `client.limits` tells you the limit without a request. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. These backends have no login store, so `/typesafe login` does not apply to them. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool always use the TypeSafe backend. Every export — the client, `ask`, batching, the usage ledger, auth state, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
|
|
146
146
|
|
|
147
147
|
## Development
|
|
148
148
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import type { BackendLimits } from "./schema.js";
|
|
2
|
+
export type TypeSafeBackend = "typesafe" | "openrouter" | "commandcode" | "liquid" | "subq";
|
|
2
3
|
export interface BackendConfig {
|
|
3
|
-
/** Human name for status lines: "TypeSafe", "OpenRouter", "Command Code", "Liquid AI". */
|
|
4
|
+
/** Human name for status lines: "TypeSafe", "OpenRouter", "Command Code", "Liquid AI", "SubQ". */
|
|
4
5
|
label: string;
|
|
5
6
|
host: string;
|
|
6
7
|
/** The environment variable that carries this backend's key. Absent means the TypeSafe key resolution applies. */
|
|
@@ -15,6 +16,8 @@ export interface BackendConfig {
|
|
|
15
16
|
modelsIdField?: string;
|
|
16
17
|
/** Whether the model list checks the key. A public list accepts any key, so it proves nothing. Absent means it does. */
|
|
17
18
|
modelsVerifyKey?: boolean;
|
|
19
|
+
/** What one request may ask, where the backend accepts less than the schema. An absent field keeps the schema's bound. */
|
|
20
|
+
limits?: Readonly<Partial<BackendLimits>>;
|
|
18
21
|
}
|
|
19
22
|
/** A registry entry: a backend config that can also name a price per model. Caller-supplied endpoints carry none. */
|
|
20
23
|
export interface RegistryBackendConfig extends BackendConfig {
|
|
@@ -41,6 +44,8 @@ export interface ResolvedBackend extends RegistryBackendConfig {
|
|
|
41
44
|
readonly defaultModel?: string;
|
|
42
45
|
/** Always explicit after resolution. */
|
|
43
46
|
readonly modelsVerifyKey: boolean;
|
|
47
|
+
/** Every limit explicit: the backend's own, else the schema's bound. */
|
|
48
|
+
readonly limits: BackendLimits;
|
|
44
49
|
}
|
|
45
50
|
/** The backend every key and auth function assumes when none is named. */
|
|
46
51
|
export declare const DEFAULT_BACKEND: TypeSafeBackend;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TypeSafeIntegrationError } from "./errors.js";
|
|
2
|
+
import { DEFAULT_BACKEND_LIMITS } from "./schema.js";
|
|
2
3
|
/** The backend every key and auth function assumes when none is named. */
|
|
3
4
|
export const DEFAULT_BACKEND = "typesafe";
|
|
4
5
|
/** The environment variable and login store that the default backend reads. */
|
|
@@ -35,6 +36,17 @@ export const DECISIONS_BACKENDS = {
|
|
|
35
36
|
modelsVerifyKey: true,
|
|
36
37
|
prices: { d1: 0.04, "d1:free": 0 },
|
|
37
38
|
},
|
|
39
|
+
subq: {
|
|
40
|
+
label: "SubQ",
|
|
41
|
+
host: "https://api.subq.ai",
|
|
42
|
+
keyEnv: "SUBQ_API_KEY",
|
|
43
|
+
modelsField: "data",
|
|
44
|
+
modelsIdField: "id",
|
|
45
|
+
modelsVerifyKey: false,
|
|
46
|
+
// SubQ answers 422 to 17 questions, a 1-option Choice, or an 11-level Score. Its 255-option Choice cap is above the schema's 64.
|
|
47
|
+
limits: { maxQuestions: 16, minChoiceOptions: 2, maxScoreLevels: 10 },
|
|
48
|
+
prices: { "subq-snap-preview": 0.05 },
|
|
49
|
+
},
|
|
38
50
|
};
|
|
39
51
|
/** The registry entry for a backend name; a `configuration` error for a name the registry does not know. */
|
|
40
52
|
export function backendConfig(name) {
|
|
@@ -49,6 +61,7 @@ const DEFAULT_MODEL = {
|
|
|
49
61
|
openrouter: "typesafe/jev-1.13",
|
|
50
62
|
commandcode: "typesafe/jev",
|
|
51
63
|
liquid: "d1:free",
|
|
64
|
+
subq: "subq-snap-preview",
|
|
52
65
|
};
|
|
53
66
|
/**
|
|
54
67
|
* The model id to send for a caller's `model` on this backend. OpenRouter routes a bare Jev id under the `typesafe`
|
|
@@ -95,6 +108,32 @@ function refuse(message) {
|
|
|
95
108
|
function hasRawQueryOrFragment(value) {
|
|
96
109
|
return value.includes("?") || value.includes("#");
|
|
97
110
|
}
|
|
111
|
+
const LIMITS_MESSAGE = `Backend limits must be an object of whole numbers within the schema's bounds: maxQuestions 1–${DEFAULT_BACKEND_LIMITS.maxQuestions}, minChoiceOptions and maxChoiceOptions ${DEFAULT_BACKEND_LIMITS.minChoiceOptions}–${DEFAULT_BACKEND_LIMITS.maxChoiceOptions} with min at most max, maxScoreLevels 2–${DEFAULT_BACKEND_LIMITS.maxScoreLevels}.`;
|
|
112
|
+
/** An endpoint's limits, each within the schema's bound: a backend can narrow what the schema admits, never widen it. */
|
|
113
|
+
function resolveLimits(value) {
|
|
114
|
+
if (value === undefined)
|
|
115
|
+
return { ...DEFAULT_BACKEND_LIMITS };
|
|
116
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
117
|
+
refuse(LIMITS_MESSAGE);
|
|
118
|
+
const given = value;
|
|
119
|
+
const floors = { maxQuestions: 1, minChoiceOptions: DEFAULT_BACKEND_LIMITS.minChoiceOptions, maxChoiceOptions: DEFAULT_BACKEND_LIMITS.minChoiceOptions, maxScoreLevels: 2 };
|
|
120
|
+
const ceilings = { ...DEFAULT_BACKEND_LIMITS, minChoiceOptions: DEFAULT_BACKEND_LIMITS.maxChoiceOptions };
|
|
121
|
+
for (const key of Object.keys(given))
|
|
122
|
+
if (!Object.hasOwn(floors, key))
|
|
123
|
+
refuse(LIMITS_MESSAGE);
|
|
124
|
+
const limits = { ...DEFAULT_BACKEND_LIMITS };
|
|
125
|
+
for (const key of Object.keys(floors)) {
|
|
126
|
+
const field = given[key];
|
|
127
|
+
if (field === undefined)
|
|
128
|
+
continue;
|
|
129
|
+
if (typeof field !== "number" || !Number.isInteger(field) || field < floors[key] || field > ceilings[key])
|
|
130
|
+
refuse(LIMITS_MESSAGE);
|
|
131
|
+
limits[key] = field;
|
|
132
|
+
}
|
|
133
|
+
if (limits.minChoiceOptions > limits.maxChoiceOptions)
|
|
134
|
+
refuse(LIMITS_MESSAGE);
|
|
135
|
+
return limits;
|
|
136
|
+
}
|
|
98
137
|
/**
|
|
99
138
|
* Resolve a registry name or a caller-supplied endpoint into the validated form the client uses. A name resolves to
|
|
100
139
|
* its registry entry unchanged; an endpoint is validated field by field and returned as a fresh object whose `host`
|
|
@@ -112,6 +151,7 @@ export function resolveBackend(backend) {
|
|
|
112
151
|
keyEnv: entry.keyEnv ?? TYPESAFE_KEY_ENV,
|
|
113
152
|
defaultModel: defaultModelId(spec),
|
|
114
153
|
modelsVerifyKey: entry.modelsVerifyKey !== false,
|
|
154
|
+
limits: { ...DEFAULT_BACKEND_LIMITS, ...entry.limits },
|
|
115
155
|
};
|
|
116
156
|
}
|
|
117
157
|
if (spec === null || typeof spec !== "object") {
|
|
@@ -145,6 +185,7 @@ export function resolveBackend(backend) {
|
|
|
145
185
|
refuse("Backend modelsIdField must be a nonempty string.");
|
|
146
186
|
if (spec.modelsVerifyKey !== undefined && typeof spec.modelsVerifyKey !== "boolean")
|
|
147
187
|
refuse("Backend modelsVerifyKey must be a boolean.");
|
|
188
|
+
const limits = resolveLimits(spec.limits);
|
|
148
189
|
if (typeof spec.keyEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(spec.keyEnv))
|
|
149
190
|
refuse(KEY_ENV_MESSAGE);
|
|
150
191
|
if (spec.keyEnv.toUpperCase() === TYPESAFE_KEY_ENV) {
|
|
@@ -158,6 +199,7 @@ export function resolveBackend(backend) {
|
|
|
158
199
|
host: host.origin,
|
|
159
200
|
keyEnv: spec.keyEnv,
|
|
160
201
|
modelsVerifyKey: spec.modelsVerifyKey === true,
|
|
202
|
+
limits,
|
|
161
203
|
...(spec.path === undefined ? {} : { path: spec.path }),
|
|
162
204
|
...(spec.modelsPath === undefined ? {} : { modelsPath: spec.modelsPath }),
|
|
163
205
|
...(spec.modelsField === undefined ? {} : { modelsField: spec.modelsField }),
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Questions, SystemOneRequest, Usage } from "@typesafe-ai/sdk";
|
|
2
2
|
import type { Evaluation, TypeSafe } from "./client.js";
|
|
3
|
+
import type { BackendSpec } from "./backends.js";
|
|
3
4
|
/** Default number of requests in flight. TypeSafe answers in isolation, so a small pool is enough. */
|
|
4
5
|
export declare const DEFAULT_CONCURRENCY = 4;
|
|
5
6
|
/** One item's outcome. `skipped` marks work that was never started because of an abort or a stop rule. */
|
|
@@ -57,17 +58,20 @@ export interface BatchEvaluation<Q extends Questions = Questions> {
|
|
|
57
58
|
*/
|
|
58
59
|
export declare function evaluateMany<Q extends Questions>(client: TypeSafe, requests: readonly SystemOneRequest<Q>[], options?: BatchOptions): Promise<BatchEvaluation<Q>>;
|
|
59
60
|
/**
|
|
60
|
-
* Split a request that asks more questions than one request may carry into chunks of at most `maxQuestions
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
61
|
+
* Split a request that asks more questions than one request may carry into chunks of at most `maxQuestions`, capped at
|
|
62
|
+
* the question limit of `backend` (default: the TypeSafe backend). Sharing one state across several questions is one
|
|
63
|
+
* request; asking more than the per-request limit is the only reason to fan out, and the state is repeated in each
|
|
64
|
+
* chunk. The order of `questions` is preserved. A pure splitter: admission still happens once per chunk, in `evaluate`
|
|
65
|
+
* or `evaluateMany`, so what one accepts the others accept.
|
|
64
66
|
*/
|
|
65
67
|
export declare function chunkEvaluationRequest(request: SystemOneRequest<Questions>, options?: {
|
|
66
68
|
maxQuestions?: number;
|
|
69
|
+
backend?: BackendSpec;
|
|
67
70
|
}): SystemOneRequest<Questions>[];
|
|
68
71
|
/**
|
|
69
|
-
* Ask any number of questions about one state: chunk to the
|
|
70
|
-
* and model. Use this when one coherent state carries many
|
|
72
|
+
* Ask any number of questions about one state: chunk to the client's question limit, or the caller's `maxQuestions`
|
|
73
|
+
* when smaller, fan out, and merge the answers, usage, and model. Use this when one coherent state carries many
|
|
74
|
+
* independent questions; use `evaluate` for one request.
|
|
71
75
|
*/
|
|
72
76
|
export declare function evaluateAll<Q extends Questions>(client: TypeSafe, request: SystemOneRequest<Q>, options?: BatchOptions & {
|
|
73
77
|
maxQuestions?: number;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { TypeSafeIntegrationError } from "./errors.js";
|
|
2
|
-
import {
|
|
2
|
+
import { resolveBackend } from "./backends.js";
|
|
3
|
+
import { DEFAULT_BACKEND_LIMITS, prepareEvaluationRequest } from "./schema.js";
|
|
3
4
|
/** Default number of requests in flight. TypeSafe answers in isolation, so a small pool is enough. */
|
|
4
5
|
export const DEFAULT_CONCURRENCY = 4;
|
|
5
6
|
/**
|
|
@@ -86,14 +87,22 @@ export async function evaluateMany(client, requests, options = {}) {
|
|
|
86
87
|
});
|
|
87
88
|
return summarize(results, Math.round(performance.now() - start));
|
|
88
89
|
}
|
|
90
|
+
/** A caller's chunk size, capped at the backend's question limit; the limit itself when the caller names none. */
|
|
91
|
+
function chunkSize(maxQuestions, backendMax) {
|
|
92
|
+
return Math.max(1, Math.min(backendMax, Math.floor(maxQuestions ?? backendMax)));
|
|
93
|
+
}
|
|
89
94
|
/**
|
|
90
|
-
* Split a request that asks more questions than one request may carry into chunks of at most `maxQuestions
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
95
|
+
* Split a request that asks more questions than one request may carry into chunks of at most `maxQuestions`, capped at
|
|
96
|
+
* the question limit of `backend` (default: the TypeSafe backend). Sharing one state across several questions is one
|
|
97
|
+
* request; asking more than the per-request limit is the only reason to fan out, and the state is repeated in each
|
|
98
|
+
* chunk. The order of `questions` is preserved. A pure splitter: admission still happens once per chunk, in `evaluate`
|
|
99
|
+
* or `evaluateMany`, so what one accepts the others accept.
|
|
94
100
|
*/
|
|
95
101
|
export function chunkEvaluationRequest(request, options = {}) {
|
|
96
|
-
const limit =
|
|
102
|
+
const limit = chunkSize(options.maxQuestions, resolveBackend(options.backend).limits.maxQuestions);
|
|
103
|
+
return splitQuestions(request, limit);
|
|
104
|
+
}
|
|
105
|
+
function splitQuestions(request, limit) {
|
|
97
106
|
const questions = request.questions;
|
|
98
107
|
const entries = questions && typeof questions === "object" && !Array.isArray(questions) ? Object.entries(questions) : undefined;
|
|
99
108
|
// Anything that is not a plain question map, or that already fits, is one chunk and is validated later.
|
|
@@ -107,10 +116,12 @@ export function chunkEvaluationRequest(request, options = {}) {
|
|
|
107
116
|
return chunks;
|
|
108
117
|
}
|
|
109
118
|
/**
|
|
110
|
-
* Ask any number of questions about one state: chunk to the
|
|
111
|
-
* and model. Use this when one coherent state carries many
|
|
119
|
+
* Ask any number of questions about one state: chunk to the client's question limit, or the caller's `maxQuestions`
|
|
120
|
+
* when smaller, fan out, and merge the answers, usage, and model. Use this when one coherent state carries many
|
|
121
|
+
* independent questions; use `evaluate` for one request.
|
|
112
122
|
*/
|
|
113
123
|
export async function evaluateAll(client, request, options = {}) {
|
|
114
|
-
const
|
|
124
|
+
const limit = chunkSize(options.maxQuestions, (client.limits ?? DEFAULT_BACKEND_LIMITS).maxQuestions);
|
|
125
|
+
const chunks = splitQuestions(request, limit);
|
|
115
126
|
return evaluateMany(client, chunks, options);
|
|
116
127
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Fetch, Questions, SystemOneRequest, SystemOneResult } from "@typesafe-ai/sdk";
|
|
2
2
|
import type { BackendSpec } from "./backends.js";
|
|
3
3
|
import type { BatchEvaluation, BatchOptions } from "./batch.js";
|
|
4
|
+
import type { BackendLimits } from "./schema.js";
|
|
4
5
|
import type { BlockedCap, SpendCaps, UsageLedger, UsageReport } from "./usage.js";
|
|
5
6
|
export { backendHost, backendPrice, resolveBackend, DECISIONS_BACKENDS, DEFAULT_BACKEND } from "./backends.js";
|
|
6
7
|
export type { BackendConfig, BackendEndpoint, BackendSpec, RegistryBackendConfig, ResolvedBackend, TypeSafeBackend } from "./backends.js";
|
|
@@ -55,10 +56,12 @@ export interface SpendReport {
|
|
|
55
56
|
readonly blocked?: BlockedCap;
|
|
56
57
|
}
|
|
57
58
|
export interface TypeSafe {
|
|
59
|
+
/** What one request may ask on this client's backend; known without a request. Absent only on a hand-built TypeSafe, which gets the schema's bounds. */
|
|
60
|
+
readonly limits?: BackendLimits;
|
|
58
61
|
evaluate<Q extends Questions>(request: SystemOneRequest<Q>, options?: EvaluationOptions): Promise<Evaluation<Q>>;
|
|
59
62
|
/** Several requests with bounded concurrency; answers, usage, and model merged. Never throws. */
|
|
60
63
|
evaluateMany<Q extends Questions>(requests: readonly SystemOneRequest<Q>[], options?: BatchOptions): Promise<BatchEvaluation<Q>>;
|
|
61
|
-
/** One state, any number of questions: chunk to the
|
|
64
|
+
/** One state, any number of questions: chunk to the backend's question limit, then fan out. Never throws. */
|
|
62
65
|
evaluateAll<Q extends Questions>(request: SystemOneRequest<Q>, options?: BatchOptions & {
|
|
63
66
|
maxQuestions?: number;
|
|
64
67
|
}): Promise<BatchEvaluation<Q>>;
|
|
@@ -18,7 +18,7 @@ function backendFetch(backend, inner = fetch) {
|
|
|
18
18
|
const { path, modelsPath, modelsField } = backend;
|
|
19
19
|
return async (input, init) => {
|
|
20
20
|
const url = String(input);
|
|
21
|
-
const models = modelsPath !== undefined && url.includes(SDK_MODELS_PATH);
|
|
21
|
+
const models = (modelsPath !== undefined || modelsField !== undefined) && url.includes(SDK_MODELS_PATH);
|
|
22
22
|
const rewrite = models ? modelsPath : path;
|
|
23
23
|
const response = await inner(rewrite === undefined ? url : url.replace(models ? SDK_MODELS_PATH : SDK_PATH, rewrite), init);
|
|
24
24
|
return models && modelsField !== undefined ? translateModels(response, backend) : response;
|
|
@@ -151,8 +151,8 @@ export function createTypeSafe(options = {}) {
|
|
|
151
151
|
...(options.maxInputTokensPerDay === undefined ? {} : { maxInputTokensPerDay: positiveInteger(options.maxInputTokensPerDay, "maxInputTokensPerDay") }),
|
|
152
152
|
...(options.maxUsdPerDay === undefined ? {} : { maxUsdPerDay: positiveNumber(options.maxUsdPerDay, "maxUsdPerDay") }),
|
|
153
153
|
}, capsFromEnvironment());
|
|
154
|
-
// A backend
|
|
155
|
-
const transport = backend.path !== undefined || backend.modelsPath !== undefined ? backendFetch(backend, options.fetch) : options.fetch;
|
|
154
|
+
// A backend with its own paths or model list fields gets a transport that rewrites them; the default backend keeps the caller's.
|
|
155
|
+
const transport = backend.path !== undefined || backend.modelsPath !== undefined || backend.modelsField !== undefined ? backendFetch(backend, options.fetch) : options.fetch;
|
|
156
156
|
// The caller's input is validated as written, then mapped to the backend's id form; omitting it sends the backend's
|
|
157
157
|
// own default, which the mapping leaves unchanged.
|
|
158
158
|
const requested = options.model ?? backend.defaultModel;
|
|
@@ -184,6 +184,7 @@ export function createTypeSafe(options = {}) {
|
|
|
184
184
|
const snapshot = () => ({ ...usage, estimatedUsd: Math.round(sessionUsd * 1e6) / 1e6 });
|
|
185
185
|
const blocked = () => (usage.requestsStarted >= maxRequests ? undefined : ledger.blocked(caps));
|
|
186
186
|
const typesafe = {
|
|
187
|
+
limits: backend.limits,
|
|
187
188
|
getUsage: snapshot,
|
|
188
189
|
getSpend: () => {
|
|
189
190
|
const reached = blocked();
|
|
@@ -212,7 +213,7 @@ export function createTypeSafe(options = {}) {
|
|
|
212
213
|
}
|
|
213
214
|
},
|
|
214
215
|
async evaluate(input, callOptions = {}) {
|
|
215
|
-
const validated = prepareEvaluationRequest(input, { maxInputBytes });
|
|
216
|
+
const validated = prepareEvaluationRequest(input, { maxInputBytes, limits: backend.limits });
|
|
216
217
|
// A per-request model meets the same mapping as the client default; the schema already limited the caller's own id.
|
|
217
218
|
const sentModel = validated.model === undefined ? model : mapModel(validated.model);
|
|
218
219
|
const body = JSON.stringify({ ...validated, model: sentModel });
|
|
@@ -12,7 +12,7 @@ export { capsFromEnvironment, DEFAULT_USD_PER_MTOK, emptyTotals, estimateUsd, lo
|
|
|
12
12
|
export type { BlockedCap, SpendCaps, UsageLedger, UsageLedgerOptions, UsageReport, UsageTotals } from "./usage.js";
|
|
13
13
|
export { TypeSafeIntegrationError } from "./errors.js";
|
|
14
14
|
export type { IntegrationErrorCode } from "./errors.js";
|
|
15
|
-
export { DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_QUESTIONS, evaluationSchema, normalizeEvaluationRequest, parseEvaluationRequest, prepareEvaluationRequest, } from "./schema.js";
|
|
16
|
-
export type { PrepareEvaluationOptions } from "./schema.js";
|
|
15
|
+
export { DEFAULT_BACKEND_LIMITS, DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_QUESTIONS, evaluationSchema, normalizeEvaluationRequest, parseEvaluationRequest, prepareEvaluationRequest, } from "./schema.js";
|
|
16
|
+
export type { BackendLimits, PrepareEvaluationOptions } from "./schema.js";
|
|
17
17
|
export { choice, noul, score } from "@typesafe-ai/sdk";
|
|
18
18
|
export type { Questions, Question, SystemOneRequest, SystemOneResult, EntryType, JsonValue, ChoiceQuestion, ChoiceResponse, NoulQuestion, NoulResponse, ScoreQuestion, ScoreResponse, Usage, } from "@typesafe-ai/sdk";
|
|
@@ -5,5 +5,5 @@ export { authState, authStatePath, clearAuthState, describeAuth, recordAuthFailu
|
|
|
5
5
|
export { clearStoredApiKey, credentialsPath, keySituation, keySourceLabel, normalizeApiKey, piTypesafeDir, resolveApiKey, storeApiKey, } from "./credentials.js";
|
|
6
6
|
export { capsFromEnvironment, DEFAULT_USD_PER_MTOK, emptyTotals, estimateUsd, localDay, mergeCaps, openUsageLedger, usagePath, } from "./usage.js";
|
|
7
7
|
export { TypeSafeIntegrationError } from "./errors.js";
|
|
8
|
-
export { DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_QUESTIONS, evaluationSchema, normalizeEvaluationRequest, parseEvaluationRequest, prepareEvaluationRequest, } from "./schema.js";
|
|
8
|
+
export { DEFAULT_BACKEND_LIMITS, DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_QUESTIONS, evaluationSchema, normalizeEvaluationRequest, parseEvaluationRequest, prepareEvaluationRequest, } from "./schema.js";
|
|
9
9
|
export { choice, noul, score } from "@typesafe-ai/sdk";
|
|
@@ -4,6 +4,19 @@ import { Type } from "typebox";
|
|
|
4
4
|
export declare const DEFAULT_MAX_INPUT_BYTES = 65536;
|
|
5
5
|
/** Questions one request may ask. More than this needs `chunkEvaluationRequest`, which splits and fans out. */
|
|
6
6
|
export declare const DEFAULT_MAX_QUESTIONS = 32;
|
|
7
|
+
/** What one request may ask on a backend. A backend can only narrow the schema's own bounds, never widen them. */
|
|
8
|
+
export interface BackendLimits {
|
|
9
|
+
/** Questions in one request. */
|
|
10
|
+
readonly maxQuestions: number;
|
|
11
|
+
/** Options in one Choice question, at least. */
|
|
12
|
+
readonly minChoiceOptions: number;
|
|
13
|
+
/** Options in one Choice question, at most. */
|
|
14
|
+
readonly maxChoiceOptions: number;
|
|
15
|
+
/** Levels in one Score rubric, at most. */
|
|
16
|
+
readonly maxScoreLevels: number;
|
|
17
|
+
}
|
|
18
|
+
/** The schema's own bounds: the limits of a backend that declares none. */
|
|
19
|
+
export declare const DEFAULT_BACKEND_LIMITS: BackendLimits;
|
|
7
20
|
/** The JSON schema used by both the Pi tool and the programmatic interface. */
|
|
8
21
|
export declare const evaluationSchema: Type.TObject<{
|
|
9
22
|
state: Type.TUnion<[Type.TString, Type.TNull, Type.TArray<Type.TUnknown>, Type.TRecord<"^.*$", Type.TUnknown>]>;
|
|
@@ -32,12 +45,14 @@ export declare function normalizeEvaluationRequest(value: unknown): unknown;
|
|
|
32
45
|
export interface PrepareEvaluationOptions {
|
|
33
46
|
/** UTF-8 JSON bytes of the serialized request. Default: DEFAULT_MAX_INPUT_BYTES. */
|
|
34
47
|
maxInputBytes?: number;
|
|
48
|
+
/** The backend's limits, checked after the schema. Default: DEFAULT_BACKEND_LIMITS, which the schema already enforces. */
|
|
49
|
+
limits?: BackendLimits;
|
|
35
50
|
}
|
|
36
51
|
/** One byte rule for every limit check: measure the serialized request and name the configured limit. */
|
|
37
52
|
export declare function assertWithinByteLimit(text: string, maxInputBytes: number): void;
|
|
38
53
|
/**
|
|
39
|
-
* The one admission rule: normalize known near-miss aliases, validate the schema and JSON-safety,
|
|
40
|
-
* budget — always in that order. The Pi tool, the playground, and client.evaluate() all
|
|
41
|
-
* accepts the others accept.
|
|
54
|
+
* The one admission rule: normalize known near-miss aliases, validate the schema and JSON-safety, check the backend's
|
|
55
|
+
* limits, then enforce the byte budget — always in that order. The Pi tool, the playground, and client.evaluate() all
|
|
56
|
+
* pass through here, so what one accepts the others accept.
|
|
42
57
|
*/
|
|
43
58
|
export declare function prepareEvaluationRequest(value: unknown, options?: PrepareEvaluationOptions): SystemOneRequest;
|
|
@@ -5,6 +5,8 @@ import { TypeSafeIntegrationError } from "./errors.js";
|
|
|
5
5
|
export const DEFAULT_MAX_INPUT_BYTES = 65_536;
|
|
6
6
|
/** Questions one request may ask. More than this needs `chunkEvaluationRequest`, which splits and fans out. */
|
|
7
7
|
export const DEFAULT_MAX_QUESTIONS = 32;
|
|
8
|
+
/** The schema's own bounds: the limits of a backend that declares none. */
|
|
9
|
+
export const DEFAULT_BACKEND_LIMITS = Object.freeze({ maxQuestions: DEFAULT_MAX_QUESTIONS, minChoiceOptions: 1, maxChoiceOptions: 64, maxScoreLevels: 32 });
|
|
8
10
|
// The API accepts structured descriptions, not only strings. The schema is the only shape guidance the model gets
|
|
9
11
|
// before its first call, so every field the agent authors says what it means.
|
|
10
12
|
const entry = (description) => Type.Union([
|
|
@@ -140,6 +142,28 @@ export function normalizeEvaluationRequest(value) {
|
|
|
140
142
|
}
|
|
141
143
|
return { ...request, questions: normalized };
|
|
142
144
|
}
|
|
145
|
+
/** Counts only, never the submitted values: a request the schema accepts but the backend would refuse. */
|
|
146
|
+
function assertWithinBackendLimits(request, limits) {
|
|
147
|
+
const refuse = (detail) => {
|
|
148
|
+
throw new TypeSafeIntegrationError("validation", `Evaluation exceeds the backend's limits: ${detail}`);
|
|
149
|
+
};
|
|
150
|
+
const questions = Object.entries(request.questions);
|
|
151
|
+
if (questions.length > limits.maxQuestions) {
|
|
152
|
+
refuse(`${questions.length} questions, at most ${limits.maxQuestions} per request. evaluateAll splits a request to this limit.`);
|
|
153
|
+
}
|
|
154
|
+
for (const [id, question] of questions) {
|
|
155
|
+
const where = `questions.${id.slice(0, 100)}`;
|
|
156
|
+
if (question.type === "choice") {
|
|
157
|
+
const options = Object.keys(question.criteria).length;
|
|
158
|
+
if (options < limits.minChoiceOptions || options > limits.maxChoiceOptions) {
|
|
159
|
+
refuse(`${where} has ${options} choice options; ${limits.minChoiceOptions}–${limits.maxChoiceOptions} allowed.`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else if (question.type === "score" && question.criteria.length > limits.maxScoreLevels) {
|
|
163
|
+
refuse(`${where} has ${question.criteria.length} score levels; 2–${limits.maxScoreLevels} allowed.`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
143
167
|
/** One byte rule for every limit check: measure the serialized request and name the configured limit. */
|
|
144
168
|
export function assertWithinByteLimit(text, maxInputBytes) {
|
|
145
169
|
if (Buffer.byteLength(text, "utf8") > maxInputBytes) {
|
|
@@ -147,12 +171,14 @@ export function assertWithinByteLimit(text, maxInputBytes) {
|
|
|
147
171
|
}
|
|
148
172
|
}
|
|
149
173
|
/**
|
|
150
|
-
* The one admission rule: normalize known near-miss aliases, validate the schema and JSON-safety,
|
|
151
|
-
* budget — always in that order. The Pi tool, the playground, and client.evaluate() all
|
|
152
|
-
* accepts the others accept.
|
|
174
|
+
* The one admission rule: normalize known near-miss aliases, validate the schema and JSON-safety, check the backend's
|
|
175
|
+
* limits, then enforce the byte budget — always in that order. The Pi tool, the playground, and client.evaluate() all
|
|
176
|
+
* pass through here, so what one accepts the others accept.
|
|
153
177
|
*/
|
|
154
178
|
export function prepareEvaluationRequest(value, options = {}) {
|
|
155
179
|
const validated = parseEvaluationRequest(normalizeEvaluationRequest(value));
|
|
180
|
+
if (options.limits !== undefined)
|
|
181
|
+
assertWithinBackendLimits(validated, options.limits);
|
|
156
182
|
assertWithinByteLimit(JSON.stringify(validated), options.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES);
|
|
157
183
|
return validated;
|
|
158
184
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-typesafe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "TypeSafe AI (Jev) decisions for Pi: batched Choice/Score/Noul evaluation tool, terminal playground, and a typed API other extensions build on.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -4,6 +4,22 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.41.0] - 2026-10-14
|
|
8
|
+
|
|
9
|
+
### Highlights
|
|
10
|
+
|
|
11
|
+
- Sites that turn away AI fetchers can now be read directly: set your own User-Agent for page fetches.
|
|
12
|
+
- A SearXNG instance on your own machine works without opening every local service to page fetches.
|
|
13
|
+
- A bad User-Agent setting fails with a clear config error and never sends the page to another provider.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- Set `fetchContent.userAgent` in `web-search.json` to choose the `User-Agent` sent on page fetches. Use it for sites that reject the default `OpenAI File Downloader, XaiImageApiFetch/1.0`, such as some Australian government sites. Leaving it unset keeps the default. A value that is empty or not printable ASCII fails with a config error before anything is fetched. Thanks to [@r1ckyIn](https://github.com/r1ckyIn) for [issue #568](https://github.com/nicobailon/pi-web-access/issues/568).
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- A SearXNG instance on the same machine (`searxngBaseUrl` on `localhost`, `127.0.0.0/8`, or `::1`) now works without adding loopback to `ssrf.allowRanges`. That workaround also let `fetch_content` reach every local service. Only the configured SearXNG address is allowed, so a redirect to another local service is still blocked. Thanks to [@mikeydiamonds](https://github.com/mikeydiamonds) for [PR #569](https://github.com/nicobailon/pi-web-access/pull/569).
|
|
22
|
+
|
|
7
23
|
## [0.40.0] - 2026-10-12
|
|
8
24
|
|
|
9
25
|
### Highlights
|
|
@@ -598,7 +598,8 @@ Config defaults to `~/.pi/agent/web-search.json` when neither `PI_CODING_AGENT_D
|
|
|
598
598
|
"allow": ["example.com"],
|
|
599
599
|
"deny": ["blocked.example.com"]
|
|
600
600
|
},
|
|
601
|
-
"redirects": "same-origin"
|
|
601
|
+
"redirects": "same-origin",
|
|
602
|
+
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
|
|
602
603
|
},
|
|
603
604
|
"shortcuts": {
|
|
604
605
|
"curate": "ctrl+shift+s",
|
|
@@ -646,13 +647,15 @@ Set `braveBaseUrl`, `exaBaseUrl`, or `tavilyBaseUrl` to route those providers th
|
|
|
646
647
|
|
|
647
648
|
`fetchContent.redirects: "same-origin"` turns on a same-origin redirect policy for every page fetch, including `web_search` `includeContent` and `source_check`. The `fetch_content` parameter `redirects: "same-origin"` turns it on for one call; omitting it never turns a configured policy off. Under the policy every redirect target, including in `auth` profile and `mode: "raw"` fetches, must match the requested URL's scheme, hostname and effective port. The check runs before the target is resolved or requested, so in an A → B → A chain B is never contacted. A refused redirect returns an error with no page content, and no other extraction provider or retry runs after it. Only this extension's own HTTP fetch is used: Jina Reader, Firecrawl, Crawl4AI, the hosted providers and Gemini are disabled, and GitHub issue/PR, GitHub repository and YouTube URLs are refused by name, even when those integrations are turned off. In `mode: "raw"` and `auth` fetches those URLs skip the GitHub and YouTube integrations and go through the same checked HTTP fetch instead. A trusted Pi extension can enforce the policy per call by setting `event.input.redirects = "same-origin"` in a `tool_call` handler for `fetch_content`. Local files and videos are not subject to the policy.
|
|
648
649
|
|
|
650
|
+
`fetchContent.userAgent` sets the `User-Agent` header of this extension's own direct HTTP page fetch, which `fetch_content`, `web_search` `includeContent`, and `source_check` use, including `auth` profile and `mode: "raw"` fetches. It defaults to `OpenAI File Downloader, XaiImageApiFetch/1.0`; set it when a site rejects that default, for example to a regular browser User-Agent. Extraction providers such as Jina Reader or Firecrawl are not affected. The value must be a non-empty string of printable ASCII characters; any other value fails the page fetch with a config error.
|
|
651
|
+
|
|
649
652
|
`fetch.timeout` is an optional positive finite number of seconds for direct HTTP fetches and the Jina Reader fallback. When omitted, both use a 30-second budget. Fractional values are supported and rounded up to at least 1 millisecond; values that cannot be converted to a finite safe integer delay from 1 through Node's 2,147,483,647 ms timer maximum are rejected. An invalid declared value fails closed with an error naming `web-search.json`. An internal/per-call `timeoutMs` override takes precedence over this setting. Other remote extraction fallbacks keep their own documented budgets.
|
|
650
653
|
|
|
651
654
|
`fetch.defaultMode` sets the mode used when `fetch_content` omits `mode`, and `fetch.allowedModes` controls which modes the tool exposes and accepts. Valid modes are `readable`, `raw`, and `answer`. By default, the default mode is `readable` and all three modes are allowed. The default must be included in the non-empty, duplicate-free allowed list. An explicitly requested disabled mode fails before fetching or invoking a model and is never replaced with another mode. Raw mode remains direct HTTP-only and never runs readability, specialized source handling, or hosted extraction fallbacks.
|
|
652
655
|
|
|
653
656
|
`fetch.answerProvider` and `fetch.answerModel` are an optional pair that selects the model used by `fetch_content` answer mode when no per-call `answerModel` is supplied. Both values must be non-empty strings and must identify an enabled text-capable model available in Pi's model registry; invalid or partial configuration fails closed. This is opt-in: answering with the configured provider/model can send fetched page text outside the current session and may incur that provider's costs. A per-call `answerModel` override is resolved first and remains usable even when these configured defaults are malformed.
|
|
654
657
|
|
|
655
|
-
Set `searxngBaseUrl` or `SEARXNG_BASE_URL` to use a self-hosted SearXNG JSON API. A configured endpoint is preferred first in `auto` mode for local/private search.
|
|
658
|
+
Set `searxngBaseUrl` or `SEARXNG_BASE_URL` to use a self-hosted SearXNG JSON API. A configured endpoint is preferred first in `auto` mode for local/private search. A configured SearXNG base URL may use `localhost`, `127.0.0.0/8`, or `::1` without adding those ranges to global `ssrf.allowRanges`; a base URL on another private or synthetic range needs a narrow `ssrf.allowRanges` entry. The base URL and its redirects are otherwise validated like other remote requests, and configured headers are stripped from cross-origin redirects. Optional `searxngHeaders` merges extra HTTP headers into each SearXNG request (string values only; invalid header names are ignored), which is useful for reverse-proxy or Zero Trust auth such as Cloudflare Access service tokens (`CF-Access-Client-Id` / `CF-Access-Client-Secret`). Configured headers override the default `Accept: application/json` when the same name is supplied. Thanks to Marcos A. Núñez (@marnunez) for PR #107 and Avinash Kanaujiya (@avinashkanaujiya) for issue #105.
|
|
656
659
|
|
|
657
660
|
**degoog.** Set `degoogBaseUrl` or `DEGOOG_URL` to use a self-hosted [degoog](https://degoog.org) metasearch instance, or omit both to use the public `https://degoog.org` instance. degoog is keyless and explicit-only: select it with `provider: "degoog"` or place it in `searchRouting`; it is never chosen by `auto` and never participates in `provider: "all"`, so queries do not leave for a third-party metasearch instance unless you ask. When the instance protects its search routes, set `degoogApiKey` or `DEGOOG_API_KEY` and the key is sent as `Authorization: Bearer <key>`; the API key and any `degoogHeaders` are stripped from cross-origin redirects. `degoogEngines` restricts the request to specific engine ids from the instance's engine list (an array of strings), which is sent as the `engines` field on `POST /api/search`; omitting it uses the instance defaults. `recencyFilter` maps to degoog's `time` parameter, and domain filters become `site:`/`-site:` query clauses plus a local result filter; multiple allowed domains are grouped as `(site:a OR site:b)` so the query terms apply to every branch. Only absolute HTTP(S) result URLs are returned as sources, and duplicate URLs are collapsed. A 200 response without a results array is reported as an invalid response, so a configured route can continue when `fallbackOn` includes `"invalid-response"`, while a genuine empty `results` array remains a successful empty search. The configured base URL and redirects remain subject to the SSRF guard; add only the narrowest self-hosted range to `ssrf.allowRanges` when it resolves to a private or synthetic range. Optional `degoogHeaders` merges extra HTTP headers (string values only; invalid header names are ignored) for reverse-proxy or Zero Trust auth. Values from `degoogApiKey` and the configured `degoogHeaders` are redacted from reported upstream error text, and a request that exceeds the 30-second deadline fails as a timeout instead of being recorded as a completed request.
|
|
658
661
|
|
|
@@ -4903,6 +4903,14 @@ function loadFetchContentRedirectPolicy() {
|
|
|
4903
4903
|
}
|
|
4904
4904
|
return redirects;
|
|
4905
4905
|
}
|
|
4906
|
+
function loadFetchContentUserAgent() {
|
|
4907
|
+
const userAgent = loadFetchContentConfig()?.userAgent;
|
|
4908
|
+
if (userAgent === void 0 || userAgent === null) return DEFAULT_FETCH_CONTENT_USER_AGENT;
|
|
4909
|
+
if (typeof userAgent !== "string" || userAgent.trim().length === 0 || !/^[\t\x20-\x7e]+$/.test(userAgent)) {
|
|
4910
|
+
throw new Error(`fetchContent.userAgent in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty string of printable ASCII characters`);
|
|
4911
|
+
}
|
|
4912
|
+
return userAgent.trim();
|
|
4913
|
+
}
|
|
4906
4914
|
function loadFetchContentDomainPolicy() {
|
|
4907
4915
|
const policy = loadFetchContentConfig()?.domainPolicy;
|
|
4908
4916
|
if (policy === void 0 || policy === null) return { ...DEFAULT_DOMAIN_POLICY };
|
|
@@ -5244,7 +5252,7 @@ function bytesMatchPrefix(addr, network, prefix) {
|
|
|
5244
5252
|
}
|
|
5245
5253
|
return true;
|
|
5246
5254
|
}
|
|
5247
|
-
var DEFAULT_MAX_REDIRECTS, REDIRECT_STATUSES, LOOPBACK_ALLOW_RANGES, REMOTE_DNS_PROXY_PROTOCOLS, WEB_SEARCH_CONFIG_PATH, cachedConfigRoot, DEFAULT_DOMAIN_POLICY;
|
|
5255
|
+
var DEFAULT_MAX_REDIRECTS, REDIRECT_STATUSES, LOOPBACK_ALLOW_RANGES, REMOTE_DNS_PROXY_PROTOCOLS, WEB_SEARCH_CONFIG_PATH, cachedConfigRoot, DEFAULT_DOMAIN_POLICY, DEFAULT_FETCH_CONTENT_USER_AGENT;
|
|
5248
5256
|
var init_ssrf_protection = __esm({
|
|
5249
5257
|
"ssrf-protection.ts"() {
|
|
5250
5258
|
init_utils();
|
|
@@ -5255,6 +5263,7 @@ var init_ssrf_protection = __esm({
|
|
|
5255
5263
|
WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
5256
5264
|
cachedConfigRoot = null;
|
|
5257
5265
|
DEFAULT_DOMAIN_POLICY = { allow: [], deny: [] };
|
|
5266
|
+
DEFAULT_FETCH_CONTENT_USER_AGENT = "OpenAI File Downloader, XaiImageApiFetch/1.0";
|
|
5258
5267
|
}
|
|
5259
5268
|
});
|
|
5260
5269
|
|
|
@@ -9972,6 +9981,7 @@ async function extractContent(url, signal, options) {
|
|
|
9972
9981
|
try {
|
|
9973
9982
|
const ssrf = loadSsrfConfig();
|
|
9974
9983
|
const domainPolicy = loadFetchContentDomainPolicy();
|
|
9984
|
+
loadFetchContentUserAgent();
|
|
9975
9985
|
await validateRemoteUrl(remoteUrl, {
|
|
9976
9986
|
allowRanges: ssrf.allowRanges,
|
|
9977
9987
|
trustEnvProxy: ssrf.trustEnvProxy,
|
|
@@ -10542,7 +10552,7 @@ async function extractViaHttp(url, timeoutMs, signal, options, preferMarkdown =
|
|
|
10542
10552
|
signal: controller.signal,
|
|
10543
10553
|
__proxy: options?.proxy,
|
|
10544
10554
|
headers: {
|
|
10545
|
-
"User-Agent":
|
|
10555
|
+
"User-Agent": loadFetchContentUserAgent(),
|
|
10546
10556
|
"Accept": preferMarkdown ? MARKDOWN_FIRST_ACCEPT : BROWSER_ACCEPT,
|
|
10547
10557
|
"Accept-Language": "en-US,en;q=0.9",
|
|
10548
10558
|
"Cache-Control": "no-cache",
|
|
@@ -13863,6 +13873,7 @@ async function searchWithSearXNG(query, options = {}) {
|
|
|
13863
13873
|
signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS17), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS17)
|
|
13864
13874
|
}, {
|
|
13865
13875
|
...loadSsrfConfig(),
|
|
13876
|
+
allowLoopback: isLoopbackHostname(url.hostname),
|
|
13866
13877
|
onRedirect: ({ from, to, init }) => from.origin === to.origin ? init : { ...init, headers: { Accept: "application/json" } }
|
|
13867
13878
|
});
|
|
13868
13879
|
if (!response.ok) {
|
|
@@ -3680,6 +3680,14 @@ function loadFetchContentRedirectPolicy() {
|
|
|
3680
3680
|
}
|
|
3681
3681
|
return redirects;
|
|
3682
3682
|
}
|
|
3683
|
+
function loadFetchContentUserAgent() {
|
|
3684
|
+
const userAgent = loadFetchContentConfig()?.userAgent;
|
|
3685
|
+
if (userAgent === void 0 || userAgent === null) return DEFAULT_FETCH_CONTENT_USER_AGENT;
|
|
3686
|
+
if (typeof userAgent !== "string" || userAgent.trim().length === 0 || !/^[\t\x20-\x7e]+$/.test(userAgent)) {
|
|
3687
|
+
throw new Error(`fetchContent.userAgent in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty string of printable ASCII characters`);
|
|
3688
|
+
}
|
|
3689
|
+
return userAgent.trim();
|
|
3690
|
+
}
|
|
3683
3691
|
function loadFetchContentDomainPolicy() {
|
|
3684
3692
|
const policy = loadFetchContentConfig()?.domainPolicy;
|
|
3685
3693
|
if (policy === void 0 || policy === null) return { ...DEFAULT_DOMAIN_POLICY };
|
|
@@ -4021,7 +4029,7 @@ function bytesMatchPrefix(addr, network, prefix) {
|
|
|
4021
4029
|
}
|
|
4022
4030
|
return true;
|
|
4023
4031
|
}
|
|
4024
|
-
var DEFAULT_MAX_REDIRECTS, REDIRECT_STATUSES, LOOPBACK_ALLOW_RANGES, REMOTE_DNS_PROXY_PROTOCOLS, WEB_SEARCH_CONFIG_PATH, cachedConfigRoot, DEFAULT_DOMAIN_POLICY;
|
|
4032
|
+
var DEFAULT_MAX_REDIRECTS, REDIRECT_STATUSES, LOOPBACK_ALLOW_RANGES, REMOTE_DNS_PROXY_PROTOCOLS, WEB_SEARCH_CONFIG_PATH, cachedConfigRoot, DEFAULT_DOMAIN_POLICY, DEFAULT_FETCH_CONTENT_USER_AGENT;
|
|
4025
4033
|
var init_ssrf_protection = __esm({
|
|
4026
4034
|
"ssrf-protection.ts"() {
|
|
4027
4035
|
init_utils();
|
|
@@ -4032,6 +4040,7 @@ var init_ssrf_protection = __esm({
|
|
|
4032
4040
|
WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
4033
4041
|
cachedConfigRoot = null;
|
|
4034
4042
|
DEFAULT_DOMAIN_POLICY = { allow: [], deny: [] };
|
|
4043
|
+
DEFAULT_FETCH_CONTENT_USER_AGENT = "OpenAI File Downloader, XaiImageApiFetch/1.0";
|
|
4035
4044
|
}
|
|
4036
4045
|
});
|
|
4037
4046
|
|
|
@@ -9827,6 +9836,7 @@ async function extractContent(url, signal, options) {
|
|
|
9827
9836
|
try {
|
|
9828
9837
|
const ssrf = loadSsrfConfig();
|
|
9829
9838
|
const domainPolicy = loadFetchContentDomainPolicy();
|
|
9839
|
+
loadFetchContentUserAgent();
|
|
9830
9840
|
await validateRemoteUrl(remoteUrl, {
|
|
9831
9841
|
allowRanges: ssrf.allowRanges,
|
|
9832
9842
|
trustEnvProxy: ssrf.trustEnvProxy,
|
|
@@ -10397,7 +10407,7 @@ async function extractViaHttp(url, timeoutMs, signal, options, preferMarkdown =
|
|
|
10397
10407
|
signal: controller.signal,
|
|
10398
10408
|
__proxy: options?.proxy,
|
|
10399
10409
|
headers: {
|
|
10400
|
-
"User-Agent":
|
|
10410
|
+
"User-Agent": loadFetchContentUserAgent(),
|
|
10401
10411
|
"Accept": preferMarkdown ? MARKDOWN_FIRST_ACCEPT : BROWSER_ACCEPT,
|
|
10402
10412
|
"Accept-Language": "en-US,en;q=0.9",
|
|
10403
10413
|
"Cache-Control": "no-cache",
|
|
@@ -10735,7 +10745,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
10735
10745
|
// package.json
|
|
10736
10746
|
var package_default = {
|
|
10737
10747
|
name: "pi-web-access",
|
|
10738
|
-
version: "0.
|
|
10748
|
+
version: "0.41.0",
|
|
10739
10749
|
description: "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, and Mistral.",
|
|
10740
10750
|
type: "module",
|
|
10741
10751
|
bin: {
|
|
@@ -22007,6 +22017,7 @@ async function searchWithSearXNG(query, options = {}) {
|
|
|
22007
22017
|
signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS17), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS17)
|
|
22008
22018
|
}, {
|
|
22009
22019
|
...loadSsrfConfig(),
|
|
22020
|
+
allowLoopback: isLoopbackHostname(url.hostname),
|
|
22010
22021
|
onRedirect: ({ from, to, init }) => from.origin === to.origin ? init : { ...init, headers: { Accept: "application/json" } }
|
|
22011
22022
|
});
|
|
22012
22023
|
if (!response.ok) {
|