@herbertgao/pi-extensions 2026.11.1 → 2026.11.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 +19 -0
- package/README.md +14 -14
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
- package/node_modules/@herbertgao/pi-subagents/README.md +54 -42
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +2 -0
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +9 -8
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +70 -9
- package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +183 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +156 -13
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +52 -8
- package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +3 -4
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +158 -56
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/status-note.ts +3 -1
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
- package/node_modules/@herbertgao/pi-subagents/src/workflow/host.ts +88 -6
- package/node_modules/@herbertgao/pi-subagents/src/workflow/progress.ts +3 -2
- package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
- package/node_modules/@narumitw/pi-btw/package.json +6 -5
- package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
- package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +21 -0
- package/node_modules/pi-commandcode-provider/README.md +18 -6
- package/node_modules/pi-commandcode-provider/index.ts +11 -5
- package/node_modules/pi-commandcode-provider/package.json +1 -1
- package/node_modules/pi-commandcode-provider/src/api-key.ts +26 -10
- package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +2 -2
- package/node_modules/pi-commandcode-provider/src/converters.ts +3 -61
- package/node_modules/pi-commandcode-provider/src/core.ts +29 -4
- package/node_modules/pi-commandcode-provider/src/cost.ts +32 -12
- package/node_modules/pi-commandcode-provider/src/oauth.ts +40 -6
- package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
- package/node_modules/pi-commandcode-provider/src/runtime.ts +14 -7
- package/node_modules/pi-commandcode-provider/src/transport.ts +6 -3
- package/node_modules/pi-provider-qoder/README.md +40 -0
- package/node_modules/pi-provider-qoder/dist/index.js +64 -0
- package/node_modules/pi-provider-qoder/package.json +4 -3
- package/node_modules/pi-typesafe/README.md +3 -3
- package/node_modules/pi-typesafe/dist/auth.d.ts +21 -4
- package/node_modules/pi-typesafe/dist/auth.js +32 -7
- package/node_modules/pi-typesafe/dist/backends.d.ts +2 -2
- package/node_modules/pi-typesafe/dist/backends.js +9 -0
- package/node_modules/pi-typesafe/dist/client.js +7 -12
- package/node_modules/pi-typesafe/dist/errors.d.ts +3 -2
- package/node_modules/pi-typesafe/dist/errors.js +12 -10
- package/node_modules/pi-typesafe/dist/extension.js +14 -10
- package/node_modules/pi-typesafe/package.json +1 -1
- package/node_modules/pi-web-access/CHANGELOG.md +22 -0
- package/node_modules/pi-web-access/README.md +31 -12
- package/node_modules/pi-web-access/curator-page.ts +5 -1
- package/node_modules/pi-web-access/curator-server.ts +2 -0
- package/node_modules/pi-web-access/dist/index.js +673 -308
- package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
- package/node_modules/pi-web-access/gemini-search.ts +12 -4
- package/node_modules/pi-web-access/github-api.ts +1 -1
- package/node_modules/pi-web-access/github-extract.ts +3 -2
- package/node_modules/pi-web-access/index.ts +7 -3
- package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
- package/node_modules/pi-web-access/outcrawl.ts +204 -0
- package/node_modules/pi-web-access/package.json +2 -2
- package/node_modules/pi-web-access/sofya.ts +201 -0
- package/node_modules/pi-web-access/utils.ts +16 -6
- package/node_modules/pi-web-access/web-tool-core.ts +4 -0
- package/package.json +11 -11
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CommandCodeModel, LoadCommandCodeModelsResult } from "./models.ts"
|
|
2
|
+
import { redactCommandCodeErrorText } from "./overflow.ts"
|
|
2
3
|
|
|
3
4
|
export interface CommandCodeUi {
|
|
4
5
|
notify(message: string, type?: "info" | "warning" | "error"): void
|
|
@@ -31,6 +32,13 @@ export interface CommandCodeRuntimeOptions<TProviderConfig> {
|
|
|
31
32
|
loadCachedModels: () => Promise<readonly CommandCodeModel[]>
|
|
32
33
|
createProviderConfig: (models: readonly CommandCodeModel[]) => TProviderConfig
|
|
33
34
|
getTransport?: () => "unknown" | "provider" | "generate"
|
|
35
|
+
/**
|
|
36
|
+
* Forget the probed transport so the next request re-tries the Provider API.
|
|
37
|
+
* Called by `/commandcode-refresh`, the user's explicit "re-check my
|
|
38
|
+
* account" action, since an account upgraded from Go stays on the generate
|
|
39
|
+
* fallback until the key changes or the host restarts.
|
|
40
|
+
*/
|
|
41
|
+
resetTransport?: () => void
|
|
34
42
|
getStreamWarning?: () => string | undefined
|
|
35
43
|
now?: () => number
|
|
36
44
|
logWarning?: (message: string) => void
|
|
@@ -71,15 +79,13 @@ function redactUrl(value: string): string {
|
|
|
71
79
|
}
|
|
72
80
|
}
|
|
73
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Diagnostics drop URL query strings and fragments entirely, then apply the
|
|
84
|
+
* same credential redaction as error messages so both surfaces agree.
|
|
85
|
+
*/
|
|
74
86
|
export function redactDiagnosticText(value: string): string {
|
|
75
87
|
const redactedUrls = value.replace(/https?:\/\/[^\s)]+/gi, (match) => redactUrl(match))
|
|
76
|
-
return redactedUrls
|
|
77
|
-
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, `Bearer ${REDACTED}`)
|
|
78
|
-
.replace(/\b(?:user|cc)_[A-Za-z0-9_-]{8,}\b/gi, REDACTED)
|
|
79
|
-
.replace(/\b(?:api[-_ ]?key|token|secret|password)\s*[=:]\s*[^\s,;)]+/gi, (match) => {
|
|
80
|
-
const separator = match.match(/\s*[=:]\s*/)?.[0] ?? "="
|
|
81
|
-
return `${match.slice(0, match.indexOf(separator))}${separator}${REDACTED}`
|
|
82
|
-
})
|
|
88
|
+
return redactCommandCodeErrorText(redactedUrls)
|
|
83
89
|
}
|
|
84
90
|
|
|
85
91
|
export function redactEndpoint(value: string): string {
|
|
@@ -291,6 +297,7 @@ export class CommandCodeRuntime<TProviderConfig, TContext extends CommandCodeCom
|
|
|
291
297
|
description: "Refresh the Command Code model catalog",
|
|
292
298
|
handler: async (_args, ctx) => {
|
|
293
299
|
await ctx.waitForIdle?.()
|
|
300
|
+
this.options.resetTransport?.()
|
|
294
301
|
const result = await this.refresh()
|
|
295
302
|
if (result.refreshed) {
|
|
296
303
|
ctx.ui.notify(
|
|
@@ -41,6 +41,7 @@ async function isUpgradeRequired(response: Response): Promise<boolean> {
|
|
|
41
41
|
|
|
42
42
|
export function createCommandCodeTransportRouter(deps: TransportDependencies) {
|
|
43
43
|
let transport: CommandCodeTransport = "unknown"
|
|
44
|
+
let generation = 0
|
|
44
45
|
let apiKey: string | undefined
|
|
45
46
|
|
|
46
47
|
function pipe(
|
|
@@ -58,6 +59,7 @@ export function createCommandCodeTransportRouter(deps: TransportDependencies) {
|
|
|
58
59
|
},
|
|
59
60
|
|
|
60
61
|
reset(): void {
|
|
62
|
+
generation += 1
|
|
61
63
|
transport = "unknown"
|
|
62
64
|
apiKey = undefined
|
|
63
65
|
},
|
|
@@ -68,10 +70,11 @@ export function createCommandCodeTransportRouter(deps: TransportDependencies) {
|
|
|
68
70
|
options?: StreamOptions,
|
|
69
71
|
): AssistantMessageEventStreamLike {
|
|
70
72
|
if (options?.apiKey !== apiKey) {
|
|
73
|
+
generation += 1
|
|
71
74
|
apiKey = options?.apiKey
|
|
72
75
|
transport = "unknown"
|
|
73
76
|
}
|
|
74
|
-
const
|
|
77
|
+
const requestGeneration = generation
|
|
75
78
|
if (transport === "generate") return deps.streamGenerate(model, context, options)
|
|
76
79
|
|
|
77
80
|
const output = deps.createStream()
|
|
@@ -96,7 +99,7 @@ export function createCommandCodeTransportRouter(deps: TransportDependencies) {
|
|
|
96
99
|
try {
|
|
97
100
|
for await (const event of providerStream) {
|
|
98
101
|
if (!upgradeRequired) {
|
|
99
|
-
if (
|
|
102
|
+
if (generation === requestGeneration) transport = "provider"
|
|
100
103
|
output.push(event)
|
|
101
104
|
}
|
|
102
105
|
}
|
|
@@ -108,7 +111,7 @@ export function createCommandCodeTransportRouter(deps: TransportDependencies) {
|
|
|
108
111
|
}
|
|
109
112
|
|
|
110
113
|
if (upgradeRequired) {
|
|
111
|
-
if (
|
|
114
|
+
if (generation === requestGeneration) transport = "generate"
|
|
112
115
|
await pipe(deps.streamGenerate(model, context, options), output)
|
|
113
116
|
}
|
|
114
117
|
output.end()
|
|
@@ -157,6 +157,46 @@ Sanitized billing samples in `src/__fixtures__/billing/usage.json` cover free Gl
|
|
|
157
157
|
calls, paid Global/CN calls, and two Kimi-K3 calls totaling 1.03185159 Credits.
|
|
158
158
|
Session accounting regression tests use these samples without making live requests.
|
|
159
159
|
|
|
160
|
+
## Version notices
|
|
161
|
+
|
|
162
|
+
npm-installed extensions get no update check from the host, so the extension asks the
|
|
163
|
+
npm registry once at startup and logs a single line when a newer release exists:
|
|
164
|
+
|
|
165
|
+
```text
|
|
166
|
+
[pi-provider-qoder] 0.6.9 is available (running 0.6.1). Upgrade: omp plugin upgrade pi-provider-qoder
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Nothing is installed automatically. The request has a 2s timeout, failures are silent,
|
|
170
|
+
and `PI_PROVIDER_QODER_SKIP_UPDATE_CHECK=1` turns the check off.
|
|
171
|
+
|
|
172
|
+
## Marketplace install (automatic updates)
|
|
173
|
+
|
|
174
|
+
An npm install never self-updates. To let omp keep this extension current, add this
|
|
175
|
+
repository as a marketplace and install from it:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
omp plugin marketplace add simonsmh/pi-provider-qoder
|
|
179
|
+
omp plugin install pi-provider-qoder@pi-provider-qoder
|
|
180
|
+
omp config set marketplace.autoUpdate auto
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Marketplace installs clone a repository and symlink it — they never run a build — and
|
|
184
|
+
`dist/` is gitignored on `main`, so releases publish the built extension to a `dist`
|
|
185
|
+
branch (`.github/workflows/dist-branch.yml`). The catalog at `.omp-plugin/marketplace.json`
|
|
186
|
+
must declare the released version: `npm run release:sync-marketplace` keeps it in step,
|
|
187
|
+
and `prepublishOnly` fails when the two drift.
|
|
188
|
+
## Version notices
|
|
189
|
+
|
|
190
|
+
npm-installed extensions get no update check from the host, so the extension asks the
|
|
191
|
+
npm registry once at startup and logs a single line when a newer release exists:
|
|
192
|
+
|
|
193
|
+
```text
|
|
194
|
+
[pi-provider-qoder] 0.6.9 is available (running 0.6.1). Upgrade: omp plugin upgrade pi-provider-qoder
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Nothing is installed automatically. The request has a 2s timeout, failures are silent,
|
|
198
|
+
and `PI_PROVIDER_QODER_SKIP_UPDATE_CHECK=1` turns the check off.
|
|
199
|
+
|
|
160
200
|
## License
|
|
161
201
|
|
|
162
202
|
MIT
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
3
|
+
|
|
1
4
|
// src/auth/oauth.ts
|
|
2
5
|
import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
3
6
|
import { homedir as homedir4 } from "node:os";
|
|
@@ -10893,6 +10896,58 @@ function streamQoder(model, context, options) {
|
|
|
10893
10896
|
return stream;
|
|
10894
10897
|
}
|
|
10895
10898
|
|
|
10899
|
+
// src/update-check.ts
|
|
10900
|
+
var PACKAGE_NAME = "pi-provider-qoder";
|
|
10901
|
+
var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
|
|
10902
|
+
var DEFAULT_TIMEOUT_MS2 = 2e3;
|
|
10903
|
+
function parseSemver(version) {
|
|
10904
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
|
|
10905
|
+
if (!match) return null;
|
|
10906
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
10907
|
+
}
|
|
10908
|
+
function compareVersions(a, b2) {
|
|
10909
|
+
const left = parseSemver(a);
|
|
10910
|
+
const right = parseSemver(b2);
|
|
10911
|
+
if (!left || !right) return 0;
|
|
10912
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
10913
|
+
if (left[index] !== right[index]) return left[index] - right[index];
|
|
10914
|
+
}
|
|
10915
|
+
return 0;
|
|
10916
|
+
}
|
|
10917
|
+
function upgradeCommand(hostExecutable) {
|
|
10918
|
+
const binary = (hostExecutable ?? "").split(/[\\/]/).pop() ?? "";
|
|
10919
|
+
if (/omp/i.test(binary)) return `omp plugin upgrade ${PACKAGE_NAME}`;
|
|
10920
|
+
if (/^pi/i.test(binary)) return `pi install npm:${PACKAGE_NAME}`;
|
|
10921
|
+
return `omp plugin upgrade ${PACKAGE_NAME} (pi: pi install npm:${PACKAGE_NAME})`;
|
|
10922
|
+
}
|
|
10923
|
+
function formatUpdateNotice(current, latest, hostExecutable) {
|
|
10924
|
+
if (compareVersions(latest, current) <= 0) return null;
|
|
10925
|
+
return `[${PACKAGE_NAME}] ${latest} is available (running ${current}). Upgrade: ${upgradeCommand(hostExecutable)}`;
|
|
10926
|
+
}
|
|
10927
|
+
async function fetchLatestVersion(fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS2) {
|
|
10928
|
+
const controller = new AbortController();
|
|
10929
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
10930
|
+
try {
|
|
10931
|
+
const response = await fetchImpl(REGISTRY_URL, {
|
|
10932
|
+
signal: controller.signal,
|
|
10933
|
+
headers: { accept: "application/json" }
|
|
10934
|
+
});
|
|
10935
|
+
if (!response.ok) return null;
|
|
10936
|
+
const body = await response.json();
|
|
10937
|
+
return typeof body.version === "string" ? body.version : null;
|
|
10938
|
+
} catch {
|
|
10939
|
+
return null;
|
|
10940
|
+
} finally {
|
|
10941
|
+
clearTimeout(timer);
|
|
10942
|
+
}
|
|
10943
|
+
}
|
|
10944
|
+
async function checkForUpdate(options) {
|
|
10945
|
+
if (options.disabled) return null;
|
|
10946
|
+
const latest = await fetchLatestVersion(options.fetchImpl ?? fetch, options.timeoutMs);
|
|
10947
|
+
if (!latest) return null;
|
|
10948
|
+
return formatUpdateNotice(options.currentVersion, latest, options.hostExecutable);
|
|
10949
|
+
}
|
|
10950
|
+
|
|
10896
10951
|
// src/usage-provider.ts
|
|
10897
10952
|
var KNOWN_UNITS = {
|
|
10898
10953
|
percent: true,
|
|
@@ -10979,6 +11034,8 @@ function createQoderUsageProvider(mode, providerID) {
|
|
|
10979
11034
|
|
|
10980
11035
|
// src/index.ts
|
|
10981
11036
|
var QODER_API = "qoder-api";
|
|
11037
|
+
var requirePackageJson = createRequire3(import.meta.url);
|
|
11038
|
+
var CURRENT_VERSION = requirePackageJson("../package.json").version ?? "0.0.0";
|
|
10982
11039
|
async function registerQoderApi() {
|
|
10983
11040
|
try {
|
|
10984
11041
|
const compat = await import("@earendil-works/pi-ai/compat");
|
|
@@ -11046,6 +11103,13 @@ async function refreshModelsAtStartup(mode) {
|
|
|
11046
11103
|
}
|
|
11047
11104
|
async function index_default(pi) {
|
|
11048
11105
|
await registerQoderApi();
|
|
11106
|
+
void checkForUpdate({
|
|
11107
|
+
currentVersion: CURRENT_VERSION,
|
|
11108
|
+
hostExecutable: process.argv[1],
|
|
11109
|
+
disabled: process.env.PI_PROVIDER_QODER_SKIP_UPDATE_CHECK === "1"
|
|
11110
|
+
}).then((notice) => {
|
|
11111
|
+
if (notice) console.error(notice);
|
|
11112
|
+
});
|
|
11049
11113
|
for (const mode of QODER_MODES) {
|
|
11050
11114
|
const providerID = getQoderRegionConfig(mode).providerID;
|
|
11051
11115
|
applyCachedChatEndpoint(mode);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-provider-qoder",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.10",
|
|
4
4
|
"description": "Pi extension for Qoder AI — with OAuth authentication, COSY signatures and WAF bypass",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,8 +28,9 @@
|
|
|
28
28
|
"test:live": "tsx scripts/record-live-fixtures.ts",
|
|
29
29
|
"test:watch": "vitest",
|
|
30
30
|
"prepare": "npm run build",
|
|
31
|
-
"prepublishOnly": "npm run check && npm run build",
|
|
32
|
-
"demo:credits": "tsx scripts/demo-credit-footer.ts"
|
|
31
|
+
"prepublishOnly": "npm run check && node scripts/sync-marketplace-version.mjs --check && npm run build",
|
|
32
|
+
"demo:credits": "tsx scripts/demo-credit-footer.ts",
|
|
33
|
+
"release:sync-marketplace": "node scripts/sync-marketplace-version.mjs"
|
|
33
34
|
},
|
|
34
35
|
"pi": {
|
|
35
36
|
"extensions": [
|
|
@@ -20,7 +20,7 @@ pi install npm:pi-typesafe
|
|
|
20
20
|
|
|
21
21
|
Then, inside Pi:
|
|
22
22
|
|
|
23
|
-
1. `/typesafe login` and paste a key from [console.typesafe.ai](https://console.typesafe.ai). Input is hidden; the key is verified against the API and saved to `~/.pi/agent/pi-typesafe/auth.json` with owner-only permissions. `/typesafe login <backend>` does the same for OpenRouter, Command Code, Liquid AI, SubQ, or an endpoint you name, keeping each key under its own name in the same store.
|
|
23
|
+
1. `/typesafe login` and paste a key from [console.typesafe.ai](https://console.typesafe.ai). Input is hidden; the key is verified against the API and saved to `~/.pi/agent/pi-typesafe/auth.json` with owner-only permissions. `/typesafe login <backend>` does the same for OpenRouter, Command Code, Liquid AI, SubQ, Nace.AI, or an endpoint you name, keeping each key under its own name in the same store.
|
|
24
24
|
2. `/typesafe test` sends one built-in sample request and shows the answers.
|
|
25
25
|
3. `/typesafe enable` lets the agent call the tool for this session, after you confirm the data notice.
|
|
26
26
|
|
|
@@ -73,7 +73,7 @@ The [TypeSafe docs](https://docs.typesafe.ai/primitives) cover each primitive in
|
|
|
73
73
|
|
|
74
74
|
An enabled extension with no usable key looks exactly like a working one — one evaluation ran keyless for hours before anyone noticed. Three answers exist now, and `/typesafe status` prints all of them:
|
|
75
75
|
|
|
76
|
-
- **Is Jev reachable?** `authState()` reports the key source, whether it has been accepted, and the last failure that degraded it; `describeAuth()` turns that into a level and one safe line. The extension calls both at session start
|
|
76
|
+
- **Is Jev reachable?** `authState()` reports the key source, whether it has been accepted, and the last failure that degraded it; `describeAuth()` turns that into a level and one safe line. The extension calls both at session start, so a headless run says judgments will fail instead of quietly falling back to its offline path. Only an HTTP 401 rejects the key, and even that stops vetoing it after fifteen minutes; a 403 refuses one request — permissions, a guardrail block, moderation, or a provider cap — and is shown without ever making the key unusable. Every message names the backend that answered.
|
|
77
77
|
- **What has this run cost?** `getSpend()` returns session counters, today's persisted counters, and the cap currently reached. Cost is estimated from input tokens only, because output is free; a count the API did not report counts as nothing.
|
|
78
78
|
- **When does it stop?** `maxRequests` bounds a client instance. Three caps bound a local day, survive restarts, and stop a request before it is submitted:
|
|
79
79
|
|
|
@@ -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"`. 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. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one judge request, and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. 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 follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, 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. Nace.AI serves Drex the same way: `createTypeSafe({ backend: "nace" })` sends judgments to `console.nace.ai` with the key from `NACE_API_KEY` and the model `drex-v2.0`, priced at $0.060 per million input tokens; `drex-v1.5` is $0.050, and `drex-max` and `drex-max-v1.1` are $0.030. Nace accepted every request shape the schema allows, so it declares no narrower limits. Drex holds a request for up to 55 seconds upstream, so raise `timeoutMs` above its 15-second default for a heavy 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. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one judge request, and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. 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 follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, 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
|
|
|
@@ -2,6 +2,17 @@ import type { BackendSpec } from "./backends.js";
|
|
|
2
2
|
import type { KeySource } from "./credentials.js";
|
|
3
3
|
import { TypeSafeIntegrationError } from "./errors.js";
|
|
4
4
|
import type { IntegrationErrorCode } from "./errors.js";
|
|
5
|
+
/**
|
|
6
|
+
* How long a stored 401 vetoes the key. The next request proves the key again once the window passes, so one refusal
|
|
7
|
+
* cannot disable judgments for good. Fifteen minutes is a policy choice, not a measured provider constant.
|
|
8
|
+
*/
|
|
9
|
+
export declare const AUTH_REJECTION_TTL_MS: number;
|
|
10
|
+
/**
|
|
11
|
+
* Only HTTP 401 refuses the key itself. A 403 refuses one request — insufficient permissions, a guardrail block, a
|
|
12
|
+
* moderation flag, or a provider cap — so it never vetoes the key. OpenRouter's error page, checked 2026-11-03, gives
|
|
13
|
+
* 401 invalid credentials, 402 insufficient credits, and 403 forbidden.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isKeyRejection(status: number | undefined): boolean;
|
|
5
16
|
/** The last request that degraded TypeSafe, with no upstream body, header, key, or submitted state. */
|
|
6
17
|
export interface AuthFailure {
|
|
7
18
|
readonly code: IntegrationErrorCode;
|
|
@@ -28,14 +39,17 @@ export interface AuthState {
|
|
|
28
39
|
readonly keyName: string;
|
|
29
40
|
/**
|
|
30
41
|
* True when the key in effect was accepted by the backend (a login proves the backend it was asked for; a successful
|
|
31
|
-
* request proves any key).
|
|
32
|
-
* next request.
|
|
42
|
+
* request proves any key). A 401 rejection younger than `AUTH_REJECTION_TTL_MS` clears it; a 403 never does. The
|
|
43
|
+
* record is shared across backends: switching backends keeps the last outcome until the next request.
|
|
33
44
|
*/
|
|
34
45
|
readonly verified: boolean;
|
|
35
46
|
readonly verifiedAt?: string;
|
|
36
47
|
/** The last failure, cleared by the next successful request. */
|
|
37
48
|
readonly lastFailure?: AuthFailure;
|
|
38
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* A key is present and no 401 rejection younger than `AUTH_REJECTION_TTL_MS` stands against it. A 403 never makes it
|
|
51
|
+
* false, because it refuses one request, not the key. False means judgments will fail.
|
|
52
|
+
*/
|
|
39
53
|
readonly usable: boolean;
|
|
40
54
|
}
|
|
41
55
|
/** The auth-state file: one small, owner-only record that outlives the process that wrote it. */
|
|
@@ -56,7 +70,10 @@ export declare function recordAuthFailure(error: TypeSafeIntegrationError, at?:
|
|
|
56
70
|
/** Forget verification and degradation: used when the key itself changes (login or logout). */
|
|
57
71
|
export declare function clearAuthState(): void;
|
|
58
72
|
export interface AuthReport {
|
|
59
|
-
/**
|
|
73
|
+
/**
|
|
74
|
+
* `error` when judgments will fail or the key was rejected, `warning` when the key is unverified or its rejection has
|
|
75
|
+
* expired, otherwise `ok`.
|
|
76
|
+
*/
|
|
60
77
|
readonly level: "ok" | "warning" | "error";
|
|
61
78
|
/** One line naming the key source and, when degraded, the reason. Safe to display. */
|
|
62
79
|
readonly text: string;
|
|
@@ -7,8 +7,29 @@ const AUTH_VERSION = 1;
|
|
|
7
7
|
const CODES = new Set([
|
|
8
8
|
"configuration", "validation", "budget", "aborted", "timeout", "http", "connection", "response",
|
|
9
9
|
]);
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* How long a stored 401 vetoes the key. The next request proves the key again once the window passes, so one refusal
|
|
12
|
+
* cannot disable judgments for good. Fifteen minutes is a policy choice, not a measured provider constant.
|
|
13
|
+
*/
|
|
14
|
+
export const AUTH_REJECTION_TTL_MS = 15 * 60 * 1000;
|
|
15
|
+
/**
|
|
16
|
+
* Only HTTP 401 refuses the key itself. A 403 refuses one request — insufficient permissions, a guardrail block, a
|
|
17
|
+
* moderation flag, or a provider cap — so it never vetoes the key. OpenRouter's error page, checked 2026-11-03, gives
|
|
18
|
+
* 401 invalid credentials, 402 insufficient credits, and 403 forbidden.
|
|
19
|
+
*/
|
|
20
|
+
export function isKeyRejection(status) {
|
|
21
|
+
return status === 401;
|
|
22
|
+
}
|
|
23
|
+
/** `fresh` still vetoes the key, `expired` is only a record of what was refused when: no schema change, no manual reset. */
|
|
24
|
+
function rejectionOf(failure) {
|
|
25
|
+
if (failure === undefined || failure.code !== "http" || !isKeyRejection(failure.status))
|
|
26
|
+
return "none";
|
|
27
|
+
const at = Date.parse(failure.at);
|
|
28
|
+
// A timestamp this code cannot read cannot prove the rejection is current, so it counts as spent.
|
|
29
|
+
if (!Number.isFinite(at))
|
|
30
|
+
return "expired";
|
|
31
|
+
return Date.now() - at < AUTH_REJECTION_TTL_MS ? "fresh" : "expired";
|
|
32
|
+
}
|
|
12
33
|
/** The auth-state file: one small, owner-only record that outlives the process that wrote it. */
|
|
13
34
|
export function authStatePath() {
|
|
14
35
|
return join(piTypesafeDir(), "auth-state.json");
|
|
@@ -61,7 +82,7 @@ export function authState(options = {}) {
|
|
|
61
82
|
const situation = keySituation(backend);
|
|
62
83
|
const stored = readState(path);
|
|
63
84
|
const source = situation.kind === "environment" ? "environment" : situation.kind === "stored" ? "stored" : undefined;
|
|
64
|
-
const rejected = stored.lastFailure
|
|
85
|
+
const rejected = rejectionOf(stored.lastFailure) === "fresh";
|
|
65
86
|
const usable = source !== undefined && !rejected;
|
|
66
87
|
return {
|
|
67
88
|
backend,
|
|
@@ -108,15 +129,19 @@ export function describeAuth(state = authState()) {
|
|
|
108
129
|
const since = state.lastFailure ? ` Last failure: ${state.lastFailure.message}${state.lastFailure.at ? ` (${state.lastFailure.at})` : ""}` : "";
|
|
109
130
|
if (state.kind === "missing") {
|
|
110
131
|
const how = `a key is configured (/typesafe login${config.name && config.name !== DEFAULT_BACKEND ? ` ${config.name}` : ""} or ${config.keyEnv})`;
|
|
111
|
-
return { level: "error", text: `${label}: missing — every Jev judgment
|
|
132
|
+
return { level: "error", text: `${label}: missing — every Jev judgment will fail until ${how}.${since}` };
|
|
112
133
|
}
|
|
113
134
|
if (state.kind === "unusable") {
|
|
114
|
-
return { level: "error", text: `${label}: unusable (${state.reason ?? "unknown reason"}) — judgments
|
|
135
|
+
return { level: "error", text: `${label}: unusable (${state.reason ?? "unknown reason"}) — judgments will fail until the key is fixed.${since}` };
|
|
115
136
|
}
|
|
116
|
-
const
|
|
117
|
-
if (
|
|
137
|
+
const rejection = rejectionOf(state.lastFailure);
|
|
138
|
+
if (rejection === "fresh") {
|
|
118
139
|
return { level: "error", text: `${label}: ${state.keyName} was rejected.${since}` };
|
|
119
140
|
}
|
|
141
|
+
if (rejection === "expired") {
|
|
142
|
+
const at = state.lastFailure?.at;
|
|
143
|
+
return { level: "warning", text: `${label}: ${state.keyName} was rejected${at === undefined ? "" : ` at ${at}`}; that rejection expired, so the next request proves the key.` };
|
|
144
|
+
}
|
|
120
145
|
if (!state.verified) {
|
|
121
146
|
return { level: "warning", text: `${label}: ${state.keyName} (not verified yet — the first request proves it).${since}` };
|
|
122
147
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { BackendLimits } from "./schema.js";
|
|
2
|
-
export type TypeSafeBackend = "typesafe" | "openrouter" | "commandcode" | "liquid" | "subq";
|
|
2
|
+
export type TypeSafeBackend = "typesafe" | "openrouter" | "commandcode" | "liquid" | "subq" | "nace";
|
|
3
3
|
export interface BackendConfig {
|
|
4
|
-
/** Human name for status lines: "TypeSafe", "OpenRouter", "Command Code", "Liquid AI", "SubQ". */
|
|
4
|
+
/** Human name for status lines: "TypeSafe", "OpenRouter", "Command Code", "Liquid AI", "SubQ", "Nace.AI". */
|
|
5
5
|
label: string;
|
|
6
6
|
host: string;
|
|
7
7
|
/** The environment variable that carries this backend's key. Absent means the TypeSafe key resolution applies. */
|
|
@@ -47,6 +47,14 @@ export const DECISIONS_BACKENDS = {
|
|
|
47
47
|
limits: { maxQuestions: 16, minChoiceOptions: 2, maxScoreLevels: 10 },
|
|
48
48
|
prices: { "subq-snap-preview": 0.05 },
|
|
49
49
|
},
|
|
50
|
+
nace: {
|
|
51
|
+
label: "Nace.AI",
|
|
52
|
+
host: "https://console.nace.ai",
|
|
53
|
+
keyEnv: "NACE_API_KEY",
|
|
54
|
+
// No limits: measured on 2026-11-04, Nace accepted 1 option, 2 and 33 score levels, 64 options, and 64 questions.
|
|
55
|
+
// An alias or retired id is billed at the version that answers it; `drex-max-finance` has no published price, so it falls back to the default estimate.
|
|
56
|
+
prices: { "drex-v2.0": 0.06, "drex-v1.5": 0.05, "drex-max": 0.03, "drex-max-v1.1": 0.03, "drex-latest": 0.06, "nacedm-latest": 0.06, "drex-v1.0": 0.03, "drex-v1.1": 0.05 },
|
|
57
|
+
},
|
|
50
58
|
};
|
|
51
59
|
/** The registry entry for a backend name; a `configuration` error for a name the registry does not know. */
|
|
52
60
|
export function backendConfig(name) {
|
|
@@ -86,6 +94,7 @@ const DEFAULT_MODEL = {
|
|
|
86
94
|
commandcode: "typesafe/jev",
|
|
87
95
|
liquid: "d1:free",
|
|
88
96
|
subq: "subq-snap-preview",
|
|
97
|
+
nace: "drex-v2.0",
|
|
89
98
|
};
|
|
90
99
|
/**
|
|
91
100
|
* The model id to send for a caller's `model` on this backend. OpenRouter routes a bare Jev id under the `typesafe`
|
|
@@ -229,9 +229,8 @@ export function createTypeSafe(options = {}) {
|
|
|
229
229
|
const ledger = options.ledger ?? openUsageLedger(callerRate === undefined ? {} : { usdPerMTok: callerRate });
|
|
230
230
|
let sessionUsd = 0;
|
|
231
231
|
const usage = { requestsStarted: 0, requestsSucceeded: 0, requestsFailed: 0, inputTokens: 0, outputTokens: 0 };
|
|
232
|
-
//
|
|
232
|
+
// One verification record per process; every failure is written, because its time is the rejection window's anchor.
|
|
233
233
|
let verificationRecorded = false;
|
|
234
|
-
let lastFailureRecorded;
|
|
235
234
|
const snapshot = () => ({ ...usage, estimatedUsd: Math.round(sessionUsd * 1e6) / 1e6 });
|
|
236
235
|
const blocked = () => (usage.requestsStarted >= maxRequests ? undefined : ledger.blocked(caps));
|
|
237
236
|
const typesafe = {
|
|
@@ -251,7 +250,7 @@ export function createTypeSafe(options = {}) {
|
|
|
251
250
|
try {
|
|
252
251
|
const models = await client.models.list(callOptions);
|
|
253
252
|
if (!Array.isArray(models))
|
|
254
|
-
throw new TypeSafeIntegrationError("response",
|
|
253
|
+
throw new TypeSafeIntegrationError("response", `${backend.label} returned an unexpected model list.`);
|
|
255
254
|
// A backend that serves its list publicly accepts any key, so a success there proves nothing about one.
|
|
256
255
|
if (backend.modelsVerifyKey && !verificationRecorded) {
|
|
257
256
|
verificationRecorded = true;
|
|
@@ -270,14 +269,14 @@ export function createTypeSafe(options = {}) {
|
|
|
270
269
|
const body = JSON.stringify({ ...validated, model: sentModel });
|
|
271
270
|
assertWithinByteLimit(body, maxInputBytes);
|
|
272
271
|
if (callOptions.signal?.aborted)
|
|
273
|
-
throw new TypeSafeIntegrationError("aborted",
|
|
272
|
+
throw new TypeSafeIntegrationError("aborted", `${backend.label} request cancelled before submission.`);
|
|
274
273
|
if (usage.requestsStarted >= maxRequests) {
|
|
275
|
-
throw new TypeSafeIntegrationError("budget",
|
|
274
|
+
throw new TypeSafeIntegrationError("budget", `${backend.label} request limit reached (${maxRequests} attempts per client instance). ${capsDescription(caps)}`);
|
|
276
275
|
}
|
|
277
276
|
const reached = ledger.blocked(caps);
|
|
278
277
|
if (reached) {
|
|
279
278
|
// Name the cap, the used amount, and the day, so a long run stops loudly instead of burning tokens unnoticed.
|
|
280
|
-
throw new TypeSafeIntegrationError("budget",
|
|
279
|
+
throw new TypeSafeIntegrationError("budget", `${backend.label} ${CAP_LABELS[reached.cap]} reached (${reached.used} of ${reached.limit} on ${reached.day}); no request was submitted. Requests resume after the local day rolls over, or raise the cap deliberately.`);
|
|
281
280
|
}
|
|
282
281
|
// Snapshot before awaiting so later mutations cannot change the request or validation.
|
|
283
282
|
const request = JSON.parse(body);
|
|
@@ -287,7 +286,7 @@ export function createTypeSafe(options = {}) {
|
|
|
287
286
|
try {
|
|
288
287
|
const result = await client.systemOne(request, callOptions);
|
|
289
288
|
if (!validResult(result, request.questions))
|
|
290
|
-
throw new TypeSafeIntegrationError("response",
|
|
289
|
+
throw new TypeSafeIntegrationError("response", `${backend.label} returned an unexpected answer or usage format.`);
|
|
291
290
|
usage.requestsSucceeded += 1;
|
|
292
291
|
// An unreported count is not a count this package can add, price, or charge against a token cap.
|
|
293
292
|
const inputTokens = result.usage.input_tokens ?? 0;
|
|
@@ -309,11 +308,7 @@ export function createTypeSafe(options = {}) {
|
|
|
309
308
|
// The request was submitted, so it counts even when it fails; the reason stays visible in `authState()`.
|
|
310
309
|
usage.requestsFailed += 1;
|
|
311
310
|
ledger.recordFailure();
|
|
312
|
-
|
|
313
|
-
if (lastFailureRecorded !== fingerprint) {
|
|
314
|
-
lastFailureRecorded = fingerprint;
|
|
315
|
-
recordAuthFailure(safe);
|
|
316
|
-
}
|
|
311
|
+
recordAuthFailure(safe);
|
|
317
312
|
throw safe;
|
|
318
313
|
}
|
|
319
314
|
},
|
|
@@ -11,7 +11,8 @@ export declare class TypeSafeIntegrationError extends Error {
|
|
|
11
11
|
constructor(code: IntegrationErrorCode, message: string, status?: number | undefined);
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Classify an error into a message safe to display.
|
|
15
|
-
*
|
|
14
|
+
* Classify an error into a message safe to display. The subject of every message is the backend that answered — its
|
|
15
|
+
* `label`, or the caller's endpoint label — falling back to TypeSafe when no backend is passed. `backend` also names
|
|
16
|
+
* the key variable the 401 advice tells the user to check and selects the 402 wording.
|
|
16
17
|
*/
|
|
17
18
|
export declare function safeError(error: unknown, backend?: BackendSpec | BackendConfig): TypeSafeIntegrationError;
|
|
@@ -23,20 +23,22 @@ function retryAfterSeconds(error) {
|
|
|
23
23
|
return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : undefined;
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
|
-
* Classify an error into a message safe to display.
|
|
27
|
-
*
|
|
26
|
+
* Classify an error into a message safe to display. The subject of every message is the backend that answered — its
|
|
27
|
+
* `label`, or the caller's endpoint label — falling back to TypeSafe when no backend is passed. `backend` also names
|
|
28
|
+
* the key variable the 401 advice tells the user to check and selects the 402 wording.
|
|
28
29
|
*/
|
|
29
30
|
export function safeError(error, backend) {
|
|
30
31
|
if (error instanceof TypeSafeIntegrationError)
|
|
31
32
|
return error;
|
|
33
|
+
const config = backend === undefined ? undefined : typeof backend === "string" ? backendConfig(backend) : backend;
|
|
34
|
+
const subject = config?.label ?? "TypeSafe";
|
|
35
|
+
const keyEnv = config?.keyEnv ?? TYPESAFE_KEY_ENV;
|
|
36
|
+
const openrouter = config !== undefined && config.host === DECISIONS_BACKENDS.openrouter.host;
|
|
32
37
|
if (error instanceof APIUserAbortError)
|
|
33
|
-
return new TypeSafeIntegrationError("aborted",
|
|
38
|
+
return new TypeSafeIntegrationError("aborted", `${subject} request cancelled; an already submitted request may still be billed.`);
|
|
34
39
|
if (error instanceof APITimeoutError)
|
|
35
|
-
return new TypeSafeIntegrationError("timeout",
|
|
40
|
+
return new TypeSafeIntegrationError("timeout", `${subject} request timed out; it was not retried and may still be billed.`);
|
|
36
41
|
if (error instanceof APIError) {
|
|
37
|
-
const config = backend === undefined ? undefined : typeof backend === "string" ? backendConfig(backend) : backend;
|
|
38
|
-
const keyEnv = config?.keyEnv ?? TYPESAFE_KEY_ENV;
|
|
39
|
-
const openrouter = config !== undefined && config.host === DECISIONS_BACKENDS.openrouter.host;
|
|
40
42
|
const retry = error.status === 429 ? retryAfterSeconds(error) : undefined;
|
|
41
43
|
const advice = error.status === 401 ? `Check ${keyEnv}.`
|
|
42
44
|
: error.status === 402 ? (openrouter ? "Insufficient credits. Add credits at https://openrouter.ai/credits." : "Check your account balance.")
|
|
@@ -44,9 +46,9 @@ export function safeError(error, backend) {
|
|
|
44
46
|
: error.status === 429 ? `Check your account quota and try again later.${retry === undefined ? "" : ` Retry after ${retry} seconds.`}`
|
|
45
47
|
: error.status === 400 || error.status === 422 ? "Check the question format and model limits."
|
|
46
48
|
: "Try again later or check the service status.";
|
|
47
|
-
return new TypeSafeIntegrationError("http",
|
|
49
|
+
return new TypeSafeIntegrationError("http", `${subject} returned HTTP ${error.status}. ${advice} No automatic retry was made.`, error.status);
|
|
48
50
|
}
|
|
49
51
|
if (error instanceof APIConnectionError)
|
|
50
|
-
return new TypeSafeIntegrationError("connection",
|
|
51
|
-
return new TypeSafeIntegrationError("response",
|
|
52
|
+
return new TypeSafeIntegrationError("connection", `Could not complete the ${subject} connection. No automatic retry was made.`);
|
|
53
|
+
return new TypeSafeIntegrationError("response", `${subject} returned an unreadable or unexpected response.`);
|
|
52
54
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Text } from "@earendil-works/pi-tui";
|
|
2
2
|
import { BACKEND_ENV, DEFAULT_BACKEND, DECISIONS_BACKENDS, MODEL_ENV, backendFromEnvironment, backendHost, modelFromEnvironment, resolveBackend, sentModelId } from "./backends.js";
|
|
3
3
|
import { createTypeSafe, DEFAULT_MAX_REQUESTS } from "./client.js";
|
|
4
|
-
import { authState, clearAuthState, describeAuth } from "./auth.js";
|
|
4
|
+
import { authState, clearAuthState, describeAuth, isKeyRejection } from "./auth.js";
|
|
5
5
|
import { clearStoredApiKey, credentialsPath, keySituation, keySourceLabel } from "./credentials.js";
|
|
6
6
|
import { TypeSafeIntegrationError, safeError } from "./errors.js";
|
|
7
7
|
import { loginWithPrompt } from "./login.js";
|
|
@@ -100,9 +100,9 @@ export default function typesafeExtension(pi) {
|
|
|
100
100
|
const auth = describeAuth(authState({ backend }));
|
|
101
101
|
// A backend name the registry does not know means no judgment can be sent at all, whether or not it is enabled.
|
|
102
102
|
if (backendError !== undefined)
|
|
103
|
-
callOut(ctx, `start:backend`, `${backendError} Judgments
|
|
103
|
+
callOut(ctx, `start:backend`, `${backendError} Judgments will fail until ${BACKEND_ENV} names a valid backend or is unset.`);
|
|
104
104
|
else if (enabled && auth.level === "error")
|
|
105
|
-
callOut(ctx, `start:${auth.level}`, `TypeSafe is enabled but judgments
|
|
105
|
+
callOut(ctx, `start:${auth.level}`, `TypeSafe is enabled but judgments will fail. ${auth.text}`);
|
|
106
106
|
});
|
|
107
107
|
pi.registerEntryRenderer("typesafe-result", (entry, { expanded }) => new Text(entry.data ? format(entry.data, expanded) : "TypeSafe · no result", 0, 0));
|
|
108
108
|
pi.registerTool({
|
|
@@ -134,11 +134,15 @@ export default function typesafeExtension(pi) {
|
|
|
134
134
|
return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
|
|
135
135
|
}
|
|
136
136
|
catch (error) {
|
|
137
|
-
const safe = safeError(error);
|
|
138
|
-
//
|
|
139
|
-
|
|
140
|
-
if (
|
|
141
|
-
|
|
137
|
+
const safe = safeError(error, backend);
|
|
138
|
+
// A 401 is about the key, so it outlives this call and is called out once; a 403 refuses one request and is
|
|
139
|
+
// only thrown. The client recorded the failure before throwing, so describeAuth describes that failure.
|
|
140
|
+
if (isKeyRejection(safe.status)) {
|
|
141
|
+
const auth = describeAuth(authState({ backend }));
|
|
142
|
+
callOut(ctx, `run:${safe.code}:${safe.status ?? ""}`, `${auth.text} Judgments will fail until the key is fixed.`);
|
|
143
|
+
}
|
|
144
|
+
else if (safe.code === "configuration") {
|
|
145
|
+
callOut(ctx, `run:configuration`, `${safe.message} Judgments will fail until that is fixed.`);
|
|
142
146
|
}
|
|
143
147
|
throw safe;
|
|
144
148
|
}
|
|
@@ -205,7 +209,7 @@ export default function typesafeExtension(pi) {
|
|
|
205
209
|
// one that names none, otherwise by the consent sentence itself. An unusable name sends nothing, so that
|
|
206
210
|
// status names no model and quotes no consent.
|
|
207
211
|
const route = backendError !== undefined
|
|
208
|
-
? `Backend: ${BACKEND_ENV} is invalid — ${backendError} Judgments
|
|
212
|
+
? `Backend: ${BACKEND_ENV} is invalid — ${backendError} Judgments will fail.`
|
|
209
213
|
: backendLine(backend);
|
|
210
214
|
const version = backendError === undefined && !consent.namesModel ? `Model: ${sentModelId(backend, model)}.` : "";
|
|
211
215
|
report([
|
|
@@ -311,7 +315,7 @@ export default function typesafeExtension(pi) {
|
|
|
311
315
|
pi.appendEntry("typesafe-result", result);
|
|
312
316
|
}
|
|
313
317
|
catch (error) {
|
|
314
|
-
report(safeError(error).message, "error");
|
|
318
|
+
report(safeError(error, backend).message, "error");
|
|
315
319
|
}
|
|
316
320
|
},
|
|
317
321
|
});
|