pi-refuseless-tether 0.0.0-stage → 0.1.1
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 +13 -0
- package/DETAILS.md +95 -0
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/package.json +52 -4
- package/src/api.ts +52 -0
- package/src/catalog.ts +151 -0
- package/src/credits.ts +91 -0
- package/src/index.ts +124 -0
- package/src/provider.ts +127 -0
- package/src/retry.ts +64 -0
- package/src/thinking.ts +70 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
- Resolve models at startup in restricted Pi children even when the catalog store cannot be written.
|
|
6
|
+
|
|
7
|
+
## 0.1.0 - 2026-11-10
|
|
8
|
+
|
|
9
|
+
- Native Refuseless API-key login validated through the free credits endpoint, with environment fallback and native logout.
|
|
10
|
+
- Live authenticated catalog, Pi-owned offline snapshot, readable flag-based names, vision, current pricing and long-context cost tiers.
|
|
11
|
+
- Offered-only effort cycle, explicit wire off, and catalog defaults for unset CLI sessions.
|
|
12
|
+
- `/refuseless` credit/pricing command, available-credit footer and non-blocking preflight advice.
|
|
13
|
+
- Native streaming, tools, images, usage and retry handling; documented output-limit fallback and test coverage.
|
package/DETAILS.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# pi-refuseless-tether — provider details
|
|
2
|
+
|
|
3
|
+
The reference behind the [README](README.md): exact login, catalog, effort, pricing, credit and retry semantics, and what was and wasn't verified.
|
|
4
|
+
|
|
5
|
+
A native [Refuseless](https://refuseless.com) provider for [Pi](https://pi.dev): validated API-key login, an authenticated live model catalog, reasoning controls, token pricing and credit visibility.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pi install npm:pi-refuseless-tether
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires the native provider API in Pi 1.5.2 (the tested version) or a compatible newer version, and Node.js 22+. No runtime dependencies beyond Pi's host packages.
|
|
14
|
+
|
|
15
|
+
To try a local checkout without installing it:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pi -e /absolute/path/to/pi-refuseless
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Get a key
|
|
22
|
+
|
|
23
|
+
Sign up at [refuseless.com](https://refuseless.com), then create an API key in your account.
|
|
24
|
+
|
|
25
|
+
## Login and select a model
|
|
26
|
+
|
|
27
|
+
Run `/login`, select **Refuseless API key**, and paste your key into the secret prompt. Leading/trailing whitespace is removed. Empty keys are refused; a free `GET /v1/credits` must succeed before Pi saves the credential. A 401 gives an invalid/expired/revoked-key error. A gateway/WAF can instead return 403; that also refuses login.
|
|
28
|
+
|
|
29
|
+
Pi owns credential storage in its selected agent directory and implements `/logout`. The package never writes keys itself. Alternatively, supply `REFUSELESS_API_KEY` through your existing secret manager/environment. A stored key takes precedence. Logging out removes the stored key, not an environment variable; unset that variable to stop using its fallback.
|
|
30
|
+
|
|
31
|
+
Use `/model` to select Refuseless, or:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pi --model refuseless/deepseek-v4.1-flash-fast --thinking off
|
|
35
|
+
pi --list-models refuseless
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The catalog is fetched with your key from `/v1/models`. It reflects account-specific access and current rates. Pi persists the snapshot in its own model store, so `--offline --list-models refuseless` and `--offline -p` can select cached models. Offline mode disables catalog network activity, **not inference**. A first-ever offline start without a snapshot has no Refuseless models. A failed refresh retains the previous snapshot; a successful empty list clears it. Opening Pi's model picker refreshes through Pi's native catalog path.
|
|
39
|
+
|
|
40
|
+
On Pi 1.5.2, newly registered providers are restored cache-only before initial model selection. The awaited extension factory therefore primes the catalog once when online, using the selected agent directory's stored API-key credential or environment fallback, and publishes the result through Pi's generation-checked model store. There is no separate catalog cache or periodic timer. Prices can change after a snapshot; refresh the catalog for current rates.
|
|
41
|
+
|
|
42
|
+
### Names, images and output limits
|
|
43
|
+
|
|
44
|
+
Names are deterministic readable versions of IDs. **“(refusal-removed weights)” comes only from `abliterated: true`**, never from an ID suffix. Image input is enabled only when `vision: true`. Context windows come from `context_length`; entries missing a usable ID/context, malformed rates/efforts, or non-USD pricing are skipped individually instead of hiding valid models or inventing metadata.
|
|
45
|
+
|
|
46
|
+
The catalog does **not** expose maximum output lengths. The package uses **131,072 tokens**, capped by context length, as a documented fallback from [Refuseless's official Pi example](https://docs.refuseless.com/sdks.md), not a measured checkpoint capability. Every model retains a `maxTokensSource` annotation. Requests may end sooner because of checkpoint limits, available credits or model behavior.
|
|
47
|
+
|
|
48
|
+
### Reasoning effort
|
|
49
|
+
|
|
50
|
+
Effort levels are read per model from the authenticated catalog. To generate a table from a saved catalog response, run `node scripts/effort-table.mjs <catalog.json>` from a source checkout. Shift+Tab cycles only offered levels: unsupported levels map to `null`, so there are no duplicate-behaving `minimal`, `medium` or `xhigh` entries. Pi's native upward-then-downward clamp resolves requests for those levels to the next offered level (currently minimal→low, medium→high, xhigh→max). Unsupported `off` clamps to low. Supported `off` sends **`reasoning_effort: "off"`**, rather than omitting the field and accidentally invoking the server default.
|
|
51
|
+
|
|
52
|
+
A new CLI session with no explicit thinking selection starts at `reasoning_default`. CLI `--thinking` / model suffixes, scoped levels, per-model/global settings, and existing conversations win. Reloads/restores do not reset effort. Switching from a non-reasoning model uses the new model's default only when no setting chose a level; reasoning-model switches retain Pi's usual carried level. Embedded SDK callers should set an explicit level after startup if their selection's provenance is not visible to extensions; Pi does not expose that provenance in `session_start`.
|
|
53
|
+
|
|
54
|
+
## Pricing and usage
|
|
55
|
+
|
|
56
|
+
Prices are USD per million tokens, directly from the authenticated catalog:
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
cost = uncached_prompt_tokens × input_per_m / 1e6
|
|
60
|
+
+ cached_prompt_tokens × cached_input_per_m / 1e6
|
|
61
|
+
+ completion_tokens × output_per_m / 1e6
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Completion tokens include reasoning tokens. Cache write cost is zero. Missing pricing yields zeros (unknown cost, **not a promise of free inference**). Discounts are already included in returned rates. Above a `long_context.threshold`, the tier applies to the **whole request, including output**; Pi's `calculateCost` uses the same strict-greater-than threshold and includes cached input when choosing the tier. Zero/missing-price entries and long-context behavior are tested.
|
|
65
|
+
|
|
66
|
+
## Credits
|
|
67
|
+
|
|
68
|
+
In interactive Pi or RPC, `/refuseless` shows `available`, `balance`, `reserved`, `key_limit`, `key_spent`, and the active Refuseless model's pricing. The footer shows **Refuseless $X.XX** using _available_ credit, not total balance, while a Refuseless model is selected. It refreshes at session start, model selection, agent start and after each turn. Failed reads mark retained values stale. Pi 1.5.2 has no auth-change event: an idle footer catches up on the next turn or `/refuseless` after login/logout.
|
|
69
|
+
|
|
70
|
+
Reads are coalesced and spaced at least one second apart to respect the API's 60 credits reads/minute/key limit within this extension instance. Very fast turns reuse the last value. Other Pi processes or clients sharing the key also consume that server limit; there is no cross-process limiter. A 429 never triggers a package polling loop. UI notifications/footer are unavailable in `-p` and JSON modes; RPC UI notifications were tested.
|
|
71
|
+
|
|
72
|
+
Before a request, known available credit is compared with an estimated worst-case hold: conservative UTF-8-byte text prompt estimate (including tool definitions, excluding image data), plus the requested output ceiling at current uncached rates. A low balance produces a **warning, never a block**, at most once per agent run. This is not an exact tokenizer or an image-token estimator, and the server can estimate differently. Plan/promotional allowances can allow calls even with zero paid credit. Top up or reduce the requested output if a reply is cut short.
|
|
73
|
+
|
|
74
|
+
## Errors and compatibility
|
|
75
|
+
|
|
76
|
+
Refuseless HTTP statuses and error codes are surfaced by Pi's OpenAI Chat Completions adapter. `402 insufficient_credits` adds top-up and `/refuseless` guidance; mid-stream credit errors remain errors, not successful partial answers. Free metadata requests give sanitized status/code errors rather than reflecting arbitrary server bodies.
|
|
77
|
+
|
|
78
|
+
`429 model_busy` / `model_warming` and 5xx errors use Pi's ordinary retry policy. Pi 1.5.2 defaults SDK/provider retries to zero; its outer agent retry does not itself read `retry-after`. A small transport wrapper therefore remembers the server's not-before time after a 429 and waits before the **next host-authorized request** for that model, with cancellation support. It adds no attempts, retry loop, retry count or invented delay; the delay comes only from the actual header. If Pi's SDK retries are enabled, they already wait and the wrapper adds no second wait. Both default-path gating and native SDK retry-after are tested with synthetic 429s; real saturation and credit depletion were not induced.
|
|
79
|
+
|
|
80
|
+
Requests use the system role for instructions, OpenAI-style reasoning effort, `max_tokens`, and stream usage. The provider disables OpenAI `store` and uses Pi's existing adapter to preserve reasoning content.
|
|
81
|
+
|
|
82
|
+
## Migrate from models.json
|
|
83
|
+
|
|
84
|
+
A `refuseless` provider/model entry in `models.json` overrides package models with the same IDs, including stale prices, input capabilities and effort maps. Back up your configuration, remove the old `refuseless` entry (leave unrelated providers alone), install this package, then `/login` or use the environment fallback and reload Pi. Do not copy a literal key into package files or diagnostics.
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
npm install
|
|
90
|
+
npm test
|
|
91
|
+
npm run typecheck
|
|
92
|
+
npm run scan:public
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Development dependencies are pinned to the versions used for qualification; Pi host packages remain wildcard peer dependencies. Tests cover catalog conversion/persistence, native cost tiers, reasoning clamping/wire payloads, validated login/logout, key-change races, credits, UI hooks, streamed errors, server-directed cancellation and retry-after under both host retry paths.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mario Hawat
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-refuseless-tether
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use [Refuseless](https://refuseless.com) models in [Pi](https://pi.dev) with a validated API-key login, a live model catalog, and credit and cost information in Pi.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Requires Node.js 22 or newer, Pi 1.5.2 or newer, and a Refuseless API key. Requests use your Refuseless account.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pi install npm:pi-refuseless-tether
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
In Pi, open `/login`, pick **Refuseless API key**, and paste your key. The provider checks the key before Pi saves it. To supply the key through your environment instead, set `REFUSELESS_API_KEY`.
|
|
14
|
+
|
|
15
|
+
Choose **Refuseless** in `/model`, or use `pi --list-models refuseless` to see the model IDs available to your account. The provider ID is `refuseless`, not the npm package name.
|
|
16
|
+
|
|
17
|
+
## Models, effort, and credits
|
|
18
|
+
|
|
19
|
+
- **Models come from your account.** Context, image support, pricing, and available reasoning efforts come from the vendor catalog. An existing cached catalog can be used at an offline start; inference still needs network access.
|
|
20
|
+
- **Effort follows the selected model.** Shift+Tab cycles the levels the model accepts. Where the model supports `off`, the provider sends it explicitly.
|
|
21
|
+
- **Costs use the catalog's rates.** Pi accounts for cached input and any reported long-context tier. Missing pricing means the cost is unknown, not that inference is free.
|
|
22
|
+
- **Credits are visible in Pi.** The footer shows available credit while you're on a Refuseless model. Run `/refuseless` for the balance and current model's prices. A low-credit estimate warns without blocking the request.
|
|
23
|
+
|
|
24
|
+
Pi keeps your session and runs its tools. Refuseless serves the model over its API.
|
|
25
|
+
|
|
26
|
+
## Moving from `models.json`
|
|
27
|
+
|
|
28
|
+
If your Pi configuration already contains a `refuseless` entry in `models.json`, back up the file and remove that entry before reloading Pi. Otherwise its static model definitions can override this package's catalog entries. Leave other providers as they are.
|
|
29
|
+
|
|
30
|
+
[Provider details](DETAILS.md) · [Issues](https://github.com/kyraneth/pi-refuseless/issues) · [MIT License](LICENSE). Not affiliated with Refuseless.
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-refuseless-tether",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Native Refuseless provider, live model catalog and credits for Pi",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "kyraneth",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi-package",
|
|
10
|
+
"pi",
|
|
11
|
+
"refuseless",
|
|
12
|
+
"provider"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/kyraneth/pi-refuseless.git"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22"
|
|
20
|
+
},
|
|
21
|
+
"main": "src/index.ts",
|
|
22
|
+
"pi": {
|
|
23
|
+
"extensions": [
|
|
24
|
+
"src/index.ts"
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"src/",
|
|
29
|
+
"README.md",
|
|
30
|
+
"DETAILS.md",
|
|
31
|
+
"CHANGELOG.md",
|
|
32
|
+
"LICENSE"
|
|
33
|
+
],
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@earendil-works/pi-ai": "*",
|
|
36
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
40
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
41
|
+
"@types/node": "26.6.2",
|
|
42
|
+
"typescript": "5.9.3",
|
|
43
|
+
"vitest": "3.2.7"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"typecheck": "tsc --noEmit",
|
|
48
|
+
"scan:public": "node scripts/check-public-tree.mjs"
|
|
49
|
+
},
|
|
50
|
+
"homepage": "https://github.com/kyraneth/pi-refuseless#readme",
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/kyraneth/pi-refuseless/issues"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export const BASE_URL = "https://api.refuseless.com/v1";
|
|
2
|
+
export const USER_AGENT = "pi-refuseless/0.1.1";
|
|
3
|
+
|
|
4
|
+
export function errorText(
|
|
5
|
+
status: number,
|
|
6
|
+
code: string,
|
|
7
|
+
message: string,
|
|
8
|
+
): string {
|
|
9
|
+
const help =
|
|
10
|
+
status === 401
|
|
11
|
+
? " Check your key with /login → Refuseless API key."
|
|
12
|
+
: status === 402 || code === "insufficient_credits"
|
|
13
|
+
? " Top up at https://refuseless.com and check /refuseless."
|
|
14
|
+
: status === 429
|
|
15
|
+
? " Rate-limited; allow the server's retry-after interval before trying again."
|
|
16
|
+
: status === 403
|
|
17
|
+
? " Gateway/WAF denied the request; check API access and User-Agent."
|
|
18
|
+
: status >= 500
|
|
19
|
+
? " Refuseless is temporarily unavailable; retry after service recovery."
|
|
20
|
+
: "";
|
|
21
|
+
return `Refuseless HTTP ${status} ${code}: ${message}${help}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function getJson(
|
|
25
|
+
path: string,
|
|
26
|
+
key: string,
|
|
27
|
+
signal?: AbortSignal,
|
|
28
|
+
baseUrl = BASE_URL,
|
|
29
|
+
): Promise<unknown> {
|
|
30
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
31
|
+
headers: { authorization: `Bearer ${key}`, "User-Agent": USER_AGENT },
|
|
32
|
+
signal,
|
|
33
|
+
});
|
|
34
|
+
const body = await response.json().catch(() => undefined);
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
// Do not echo arbitrary server messages: an auth gateway could echo credentials.
|
|
37
|
+
const code =
|
|
38
|
+
typeof body?.error?.code === "string"
|
|
39
|
+
? body.error.code.replace(/[^a-z0-9_-]/gi, "")
|
|
40
|
+
: "request_failed";
|
|
41
|
+
throw new Error(
|
|
42
|
+
errorText(
|
|
43
|
+
response.status,
|
|
44
|
+
code,
|
|
45
|
+
response.status === 401
|
|
46
|
+
? "Invalid, expired or revoked API key."
|
|
47
|
+
: "API request failed.",
|
|
48
|
+
),
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return body;
|
|
52
|
+
}
|
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Model,
|
|
3
|
+
ModelThinkingLevel,
|
|
4
|
+
ThinkingLevelMap,
|
|
5
|
+
ModelCost,
|
|
6
|
+
} from "@earendil-works/pi-ai";
|
|
7
|
+
|
|
8
|
+
export type Entry = {
|
|
9
|
+
id: string;
|
|
10
|
+
abliterated: boolean;
|
|
11
|
+
vision?: boolean;
|
|
12
|
+
context_length?: number;
|
|
13
|
+
reasoning_efforts?: string[];
|
|
14
|
+
reasoning_default?: string;
|
|
15
|
+
pricing?: Rates & {
|
|
16
|
+
currency?: string;
|
|
17
|
+
long_context?: Rates & { threshold: number };
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
type Rates = {
|
|
21
|
+
input_per_m: number;
|
|
22
|
+
cached_input_per_m: number;
|
|
23
|
+
output_per_m: number;
|
|
24
|
+
};
|
|
25
|
+
export type RefuselessModel = Model<"openai-completions"> & {
|
|
26
|
+
reasoningDefault?: ModelThinkingLevel;
|
|
27
|
+
abliterated: boolean;
|
|
28
|
+
maxTokensSource: string;
|
|
29
|
+
};
|
|
30
|
+
export const LEVELS = [
|
|
31
|
+
"off",
|
|
32
|
+
"minimal",
|
|
33
|
+
"low",
|
|
34
|
+
"medium",
|
|
35
|
+
"high",
|
|
36
|
+
"xhigh",
|
|
37
|
+
"max",
|
|
38
|
+
] as const;
|
|
39
|
+
export function costRates(r?: Rates): ModelCost {
|
|
40
|
+
return {
|
|
41
|
+
input: r?.input_per_m ?? 0,
|
|
42
|
+
cacheRead: r?.cached_input_per_m ?? 0,
|
|
43
|
+
output: r?.output_per_m ?? 0,
|
|
44
|
+
cacheWrite: 0,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function displayName(id: string, abliterated: boolean): string {
|
|
48
|
+
const words = id.replace(/-abliterated(?=-|$)/g, "").split("-");
|
|
49
|
+
const names: Record<string, string> = {
|
|
50
|
+
glm: "GLM",
|
|
51
|
+
deepseek: "DeepSeek",
|
|
52
|
+
minimax: "MiniMax",
|
|
53
|
+
kimi: "Kimi",
|
|
54
|
+
};
|
|
55
|
+
return (
|
|
56
|
+
words
|
|
57
|
+
.map(
|
|
58
|
+
(w) =>
|
|
59
|
+
names[w] ??
|
|
60
|
+
(/^v?\d/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1)),
|
|
61
|
+
)
|
|
62
|
+
.join(" ") + (abliterated ? " (refusal-removed weights)" : "")
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
function validEntry(e: Entry): boolean {
|
|
66
|
+
if (
|
|
67
|
+
!e ||
|
|
68
|
+
typeof e.id !== "string" ||
|
|
69
|
+
!e.id ||
|
|
70
|
+
!Number.isInteger(e.context_length) ||
|
|
71
|
+
e.context_length! <= 0 ||
|
|
72
|
+
typeof e.abliterated !== "boolean"
|
|
73
|
+
)
|
|
74
|
+
return false;
|
|
75
|
+
if (
|
|
76
|
+
e.reasoning_efforts !== undefined &&
|
|
77
|
+
(!Array.isArray(e.reasoning_efforts) ||
|
|
78
|
+
!e.reasoning_efforts.every((v) =>
|
|
79
|
+
["off", "low", "high", "max"].includes(v),
|
|
80
|
+
))
|
|
81
|
+
)
|
|
82
|
+
return false;
|
|
83
|
+
const rates = (r: Rates) =>
|
|
84
|
+
r &&
|
|
85
|
+
[r.input_per_m, r.cached_input_per_m, r.output_per_m].every(
|
|
86
|
+
(n) => typeof n === "number" && Number.isFinite(n) && n >= 0,
|
|
87
|
+
);
|
|
88
|
+
if (
|
|
89
|
+
e.pricing &&
|
|
90
|
+
((e.pricing.currency && e.pricing.currency !== "USD") || !rates(e.pricing))
|
|
91
|
+
)
|
|
92
|
+
return false;
|
|
93
|
+
const t = e.pricing?.long_context;
|
|
94
|
+
return !t || (rates(t) && Number.isInteger(t.threshold) && t.threshold >= 0);
|
|
95
|
+
}
|
|
96
|
+
export function catalogModels(entries: Entry[]): RefuselessModel[] {
|
|
97
|
+
if (!Array.isArray(entries))
|
|
98
|
+
throw new Error("Refuseless catalog response has no data array.");
|
|
99
|
+
// An incomplete/new model must not hide the rest of an account's valid catalog.
|
|
100
|
+
return entries.filter(validEntry).map((e) => {
|
|
101
|
+
const offered = new Set(e.reasoning_efforts ?? []);
|
|
102
|
+
const thinkingLevelMap = Object.fromEntries(
|
|
103
|
+
LEVELS.map((level) => [
|
|
104
|
+
level,
|
|
105
|
+
offered.has(level) && ["off", "low", "high", "max"].includes(level)
|
|
106
|
+
? level
|
|
107
|
+
: null,
|
|
108
|
+
]),
|
|
109
|
+
) as ThinkingLevelMap;
|
|
110
|
+
const cost = costRates(e.pricing);
|
|
111
|
+
if (e.pricing?.long_context)
|
|
112
|
+
cost.tiers = [
|
|
113
|
+
{
|
|
114
|
+
...costRates(e.pricing.long_context),
|
|
115
|
+
inputTokensAbove: e.pricing.long_context.threshold,
|
|
116
|
+
},
|
|
117
|
+
];
|
|
118
|
+
return {
|
|
119
|
+
type: "chat",
|
|
120
|
+
provider: "refuseless",
|
|
121
|
+
api: "openai-completions",
|
|
122
|
+
baseUrl: "https://api.refuseless.com/v1",
|
|
123
|
+
id: e.id,
|
|
124
|
+
name: displayName(e.id, e.abliterated),
|
|
125
|
+
abliterated: e.abliterated,
|
|
126
|
+
input: e.vision ? ["text", "image"] : ["text"],
|
|
127
|
+
contextWindow: e.context_length!,
|
|
128
|
+
cost,
|
|
129
|
+
// Refuseless's official Pi example: https://docs.refuseless.com/sdks.md.
|
|
130
|
+
// Catalog omits output limits. Live probes only found a gateway validation ceiling of 1,000,000,
|
|
131
|
+
// NOT a checkpoint output limit; do not advertise that as model capacity.
|
|
132
|
+
maxTokens: Math.min(131_072, e.context_length!),
|
|
133
|
+
maxTokensSource:
|
|
134
|
+
"Documented fallback: docs.refuseless.com/sdks.md Pi example (131072), not a measured checkpoint limit",
|
|
135
|
+
reasoning: [...offered].some((x) => ["low", "high", "max"].includes(x)),
|
|
136
|
+
thinkingLevelMap,
|
|
137
|
+
...(offered.has(e.reasoning_default ?? "")
|
|
138
|
+
? { reasoningDefault: e.reasoning_default as ModelThinkingLevel }
|
|
139
|
+
: {}),
|
|
140
|
+
// System role is the portable baseline; live system-role, usage, off/high and tool-history checks in evidence.
|
|
141
|
+
compat: {
|
|
142
|
+
supportsDeveloperRole: false,
|
|
143
|
+
supportsStore: false,
|
|
144
|
+
supportsUsageInStreaming: true,
|
|
145
|
+
supportsReasoningEffort: true,
|
|
146
|
+
thinkingFormat: "openai",
|
|
147
|
+
maxTokensField: "max_tokens",
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
});
|
|
151
|
+
}
|
package/src/credits.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import { getJson } from "./api.ts";
|
|
3
|
+
export interface Credits {
|
|
4
|
+
available: number;
|
|
5
|
+
balance: number;
|
|
6
|
+
reserved: number;
|
|
7
|
+
key_limit: number | null;
|
|
8
|
+
key_spent: number;
|
|
9
|
+
}
|
|
10
|
+
export function validateCredits(value: unknown): Credits {
|
|
11
|
+
const c = value as Credits | undefined;
|
|
12
|
+
if (
|
|
13
|
+
!c ||
|
|
14
|
+
![c.available, c.balance, c.reserved, c.key_spent].every(Number.isFinite) ||
|
|
15
|
+
!(c.key_limit === null || Number.isFinite(c.key_limit))
|
|
16
|
+
)
|
|
17
|
+
throw new Error(
|
|
18
|
+
"Invalid Refuseless credits response; expected credit balances, not a gateway page.",
|
|
19
|
+
);
|
|
20
|
+
return c;
|
|
21
|
+
}
|
|
22
|
+
// API limit: 60 credits reads/minute/key (docs.refuseless.com/api/credits).
|
|
23
|
+
// One in-flight read and >=1 second spacing. Failed reads also consume a slot.
|
|
24
|
+
export class CreditsReader {
|
|
25
|
+
value?: Credits;
|
|
26
|
+
private lastRead = -Infinity;
|
|
27
|
+
private inFlight?: Promise<Credits | undefined>;
|
|
28
|
+
private generation = 0;
|
|
29
|
+
async read(key: string, signal?: AbortSignal): Promise<Credits | undefined> {
|
|
30
|
+
if (this.inFlight) return this.inFlight;
|
|
31
|
+
if (Date.now() - this.lastRead <= 60_000 / 60) return this.value;
|
|
32
|
+
this.lastRead = Date.now();
|
|
33
|
+
const generation = this.generation;
|
|
34
|
+
this.inFlight = (async () => {
|
|
35
|
+
const value = validateCredits(await getJson("/credits", key, signal));
|
|
36
|
+
if (generation !== this.generation) return undefined;
|
|
37
|
+
this.value = value;
|
|
38
|
+
return value;
|
|
39
|
+
})();
|
|
40
|
+
try {
|
|
41
|
+
return await this.inFlight;
|
|
42
|
+
} finally {
|
|
43
|
+
if (generation === this.generation) this.inFlight = undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
clear() {
|
|
47
|
+
this.generation++;
|
|
48
|
+
this.value = undefined;
|
|
49
|
+
this.lastRead = -Infinity;
|
|
50
|
+
this.inFlight = undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function pricingText(model?: Model<any>): string {
|
|
54
|
+
if (model?.provider !== "refuseless")
|
|
55
|
+
return "Current model is not Refuseless.";
|
|
56
|
+
const c = model.cost;
|
|
57
|
+
return (
|
|
58
|
+
`${model.name}\nUSD / 1M tokens: input ${c.input}, cached input ${c.cacheRead}, output ${c.output}; cache write ${c.cacheWrite}` +
|
|
59
|
+
(c.tiers
|
|
60
|
+
?.map(
|
|
61
|
+
(t) =>
|
|
62
|
+
`\nAbove ${t.inputTokensAbove} prompt tokens (whole request): input ${t.input}, cached ${t.cacheRead}, output ${t.output}`,
|
|
63
|
+
)
|
|
64
|
+
.join("") ?? "")
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
export function creditsText(c: Credits, model?: Model<any>): string {
|
|
68
|
+
return `Refuseless credits (USD)\navailable: ${c.available}\nbalance: ${c.balance}\nreserved: ${c.reserved}\nkey_limit: ${c.key_limit ?? "unlimited"}\nkey_spent: ${c.key_spent}\n\n${pricingText(model)}`;
|
|
69
|
+
}
|
|
70
|
+
export function estimateHold(
|
|
71
|
+
payload: Record<string, unknown>,
|
|
72
|
+
model: Model<any>,
|
|
73
|
+
): number {
|
|
74
|
+
// Deliberately conservative text estimate: UTF-8 bytes, one token per byte, includes tool schemas.
|
|
75
|
+
// Not a tokenizer/guarantee; image token counts are unknown. The server estimates independently.
|
|
76
|
+
const prompt = new TextEncoder().encode(
|
|
77
|
+
JSON.stringify(
|
|
78
|
+
{ messages: payload.messages, tools: payload.tools },
|
|
79
|
+
(key, value) => (key === "image_url" ? "[image tokens unknown]" : value),
|
|
80
|
+
),
|
|
81
|
+
).length;
|
|
82
|
+
const output = Number(
|
|
83
|
+
payload.max_tokens ?? payload.max_completion_tokens ?? model.maxTokens,
|
|
84
|
+
);
|
|
85
|
+
let rates = model.cost;
|
|
86
|
+
for (const tier of [...(model.cost.tiers ?? [])].sort(
|
|
87
|
+
(a, b) => a.inputTokensAbove - b.inputTokensAbove,
|
|
88
|
+
))
|
|
89
|
+
if (prompt > tier.inputTokensAbove) rates = tier;
|
|
90
|
+
return (prompt * rates.input + output * rates.output) / 1e6;
|
|
91
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { refuselessProvider } from "./provider.ts";
|
|
6
|
+
import { CreditsReader, creditsText, estimateHold } from "./credits.ts";
|
|
7
|
+
import { registerThinking } from "./thinking.ts";
|
|
8
|
+
|
|
9
|
+
export default async function refuseless(pi: ExtensionAPI) {
|
|
10
|
+
pi.registerProvider(await refuselessProvider());
|
|
11
|
+
registerThinking(pi);
|
|
12
|
+
const credits = new CreditsReader();
|
|
13
|
+
let currentKey: string | undefined;
|
|
14
|
+
async function refresh(ctx: ExtensionContext) {
|
|
15
|
+
if (ctx.model?.provider !== "refuseless") {
|
|
16
|
+
ctx.ui.setStatus("refuseless", undefined);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const key = await ctx.modelRegistry.getApiKeyForProvider("refuseless");
|
|
20
|
+
if (key !== currentKey) {
|
|
21
|
+
credits.clear();
|
|
22
|
+
currentKey = key;
|
|
23
|
+
}
|
|
24
|
+
if (!key) {
|
|
25
|
+
ctx.ui.setStatus("refuseless", undefined);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
const c = await credits.read(key, ctx.signal);
|
|
30
|
+
if (key !== currentKey) return;
|
|
31
|
+
ctx.ui.setStatus(
|
|
32
|
+
"refuseless",
|
|
33
|
+
c
|
|
34
|
+
? `Refuseless $${c.available.toFixed(2)}`
|
|
35
|
+
: "Refuseless credits unavailable",
|
|
36
|
+
);
|
|
37
|
+
} catch {
|
|
38
|
+
ctx.ui.setStatus(
|
|
39
|
+
"refuseless",
|
|
40
|
+
credits.value
|
|
41
|
+
? `Refuseless $${credits.value.available.toFixed(2)} (stale)`
|
|
42
|
+
: "Refuseless credits unavailable",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
pi.on("session_start", async (_e, ctx) => {
|
|
47
|
+
await refresh(ctx);
|
|
48
|
+
});
|
|
49
|
+
pi.on("model_select", async (_e, ctx) => {
|
|
50
|
+
await refresh(ctx);
|
|
51
|
+
});
|
|
52
|
+
pi.on("turn_end", async (_e, ctx) => {
|
|
53
|
+
await refresh(ctx);
|
|
54
|
+
});
|
|
55
|
+
pi.on("agent_start", async (_e, ctx) => {
|
|
56
|
+
warned = false;
|
|
57
|
+
await refresh(ctx);
|
|
58
|
+
});
|
|
59
|
+
let warned = false;
|
|
60
|
+
pi.registerCommand("refuseless", {
|
|
61
|
+
description: "Show Refuseless credits and current model pricing",
|
|
62
|
+
async handler(_args, ctx) {
|
|
63
|
+
const key = await ctx.modelRegistry.getApiKeyForProvider("refuseless");
|
|
64
|
+
if (!key) {
|
|
65
|
+
credits.clear();
|
|
66
|
+
currentKey = undefined;
|
|
67
|
+
ctx.ui.setStatus("refuseless", undefined);
|
|
68
|
+
ctx.ui.notify(
|
|
69
|
+
"Refuseless: /login → Refuseless API key first.",
|
|
70
|
+
"warning",
|
|
71
|
+
);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (key !== currentKey) {
|
|
75
|
+
credits.clear();
|
|
76
|
+
currentKey = key;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const c = await credits.read(key, ctx.signal);
|
|
80
|
+
if (key !== currentKey) return;
|
|
81
|
+
if (c) {
|
|
82
|
+
ctx.ui.notify(creditsText(c, ctx.model), "info");
|
|
83
|
+
await refresh(ctx);
|
|
84
|
+
} else
|
|
85
|
+
ctx.ui.notify(
|
|
86
|
+
"Refuseless credits read is rate-limited; try again shortly.",
|
|
87
|
+
"warning",
|
|
88
|
+
);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
ctx.ui.notify((error as Error).message, "error");
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
pi.on("before_provider_request", (event, ctx) => {
|
|
95
|
+
if (ctx.model?.provider !== "refuseless" || !credits.value || warned)
|
|
96
|
+
return;
|
|
97
|
+
const hold = estimateHold(
|
|
98
|
+
event.payload as Record<string, unknown>,
|
|
99
|
+
ctx.model,
|
|
100
|
+
);
|
|
101
|
+
if (credits.value.available < hold) {
|
|
102
|
+
warned = true;
|
|
103
|
+
ctx.ui.notify(
|
|
104
|
+
`Refuseless: available $${credits.value.available.toFixed(2)} is below the estimated worst-case hold $${hold.toFixed(2)}. Reply may be cut short; check /refuseless or top up. This is an estimate, not a tokenizer (image tokens are unknown).`,
|
|
105
|
+
"warning",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
pi.on("message_end", (event, ctx) => {
|
|
110
|
+
const m = event.message;
|
|
111
|
+
if (
|
|
112
|
+
m.role === "assistant" &&
|
|
113
|
+
m.provider === "refuseless" &&
|
|
114
|
+
m.stopReason === "error" &&
|
|
115
|
+
/insufficient_credits|\b402\b/.test(m.errorMessage ?? "")
|
|
116
|
+
) {
|
|
117
|
+
// The adapter already exposes HTTP status/code and SSE errors. Add actionable guidance only.
|
|
118
|
+
ctx.ui.notify(
|
|
119
|
+
"Refuseless insufficient_credits: top up at https://refuseless.com and check /refuseless.",
|
|
120
|
+
"error",
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createProvider, type ApiKeyAuth } from "@earendil-works/pi-ai";
|
|
2
|
+
import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
|
|
3
|
+
import { BASE_URL, USER_AGENT, getJson } from "./api.ts";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { catalogModels, type Entry } from "./catalog.ts";
|
|
8
|
+
import { validateCredits } from "./credits.ts";
|
|
9
|
+
import { withRetryAfter } from "./retry.ts";
|
|
10
|
+
|
|
11
|
+
export const apiKeyAuth: ApiKeyAuth = {
|
|
12
|
+
name: "Refuseless API key",
|
|
13
|
+
async login(interaction) {
|
|
14
|
+
const key = (
|
|
15
|
+
await interaction.prompt({
|
|
16
|
+
type: "secret",
|
|
17
|
+
message: "Refuseless API key",
|
|
18
|
+
signal: interaction.signal,
|
|
19
|
+
})
|
|
20
|
+
).trim();
|
|
21
|
+
if (!key) throw new Error("Refuseless API key cannot be empty.");
|
|
22
|
+
validateCredits(await getJson("/credits", key, interaction.signal));
|
|
23
|
+
return { type: "api_key", key };
|
|
24
|
+
},
|
|
25
|
+
async resolve({ ctx, credential }) {
|
|
26
|
+
const key = (
|
|
27
|
+
credential?.key ?? (await ctx.env("REFUSELESS_API_KEY"))
|
|
28
|
+
)?.trim();
|
|
29
|
+
return key
|
|
30
|
+
? {
|
|
31
|
+
auth: { apiKey: key },
|
|
32
|
+
source: credential?.key ? "API key" : "REFUSELESS_API_KEY",
|
|
33
|
+
}
|
|
34
|
+
: undefined;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
export async function refuselessProvider() {
|
|
38
|
+
// Pi 1.5.2 restores registered providers cache-only before initial model selection.
|
|
39
|
+
// Prime the native provider during its awaited factory, then publish through Pi's store.
|
|
40
|
+
// Read credentials only from the selected agent dir; never write/copy them ourselves.
|
|
41
|
+
let key = process.env.REFUSELESS_API_KEY?.trim();
|
|
42
|
+
try {
|
|
43
|
+
const stored = JSON.parse(
|
|
44
|
+
await readFile(join(getAgentDir(), "auth.json"), "utf8"),
|
|
45
|
+
).refuseless;
|
|
46
|
+
if (stored?.type === "api_key" && typeof stored.key === "string")
|
|
47
|
+
key = stored.key.trim() || key;
|
|
48
|
+
} catch {
|
|
49
|
+
/* Pi reports credential-store errors; an explicit env fallback still works. */
|
|
50
|
+
}
|
|
51
|
+
let primed: ReturnType<typeof catalogModels> | undefined;
|
|
52
|
+
if (
|
|
53
|
+
key &&
|
|
54
|
+
!["1", "true", "yes"].includes(
|
|
55
|
+
(process.env.PI_OFFLINE ?? "").toLowerCase(),
|
|
56
|
+
) &&
|
|
57
|
+
!process.argv.includes("--offline")
|
|
58
|
+
) {
|
|
59
|
+
try {
|
|
60
|
+
const body = (await getJson("/models", key)) as { data: Entry[] };
|
|
61
|
+
primed = catalogModels(body.data);
|
|
62
|
+
} catch {
|
|
63
|
+
/* Native stored catalog remains usable when the service is unreachable. */
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const provider = createProvider({
|
|
67
|
+
id: "refuseless",
|
|
68
|
+
name: "Refuseless",
|
|
69
|
+
baseUrl: BASE_URL,
|
|
70
|
+
headers: { "User-Agent": USER_AGENT },
|
|
71
|
+
auth: { apiKey: apiKeyAuth },
|
|
72
|
+
models: [],
|
|
73
|
+
api: withRetryAfter(openAICompletionsApi()),
|
|
74
|
+
async fetchModels(context) {
|
|
75
|
+
const key =
|
|
76
|
+
context.credential?.type === "api_key"
|
|
77
|
+
? context.credential.key
|
|
78
|
+
: undefined;
|
|
79
|
+
if (!key) return context.stored?.models ?? [];
|
|
80
|
+
const body = (await getJson(
|
|
81
|
+
"/models",
|
|
82
|
+
key,
|
|
83
|
+
context.signal,
|
|
84
|
+
context.baseUrl ?? BASE_URL,
|
|
85
|
+
)) as { data?: Entry[] };
|
|
86
|
+
if (!Array.isArray(body?.data))
|
|
87
|
+
throw new Error("Refuseless catalog response has no data array.");
|
|
88
|
+
return catalogModels(body.data);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
const primedAt = Date.now();
|
|
92
|
+
const refresh = provider.refreshModels!;
|
|
93
|
+
provider.refreshModels = async (context) => {
|
|
94
|
+
// Reuse createProvider's transactional restore/persist behavior with the already fetched data.
|
|
95
|
+
if (
|
|
96
|
+
primed !== undefined &&
|
|
97
|
+
!context.allowNetwork &&
|
|
98
|
+
(context.stored?.checkedAt ?? 0) <= primedAt
|
|
99
|
+
) {
|
|
100
|
+
const snapshot = primed;
|
|
101
|
+
await refresh({
|
|
102
|
+
...context,
|
|
103
|
+
stored: { models: snapshot, checkedAt: primedAt },
|
|
104
|
+
allowNetwork: false,
|
|
105
|
+
publish: async (publication) => {
|
|
106
|
+
let accepted: boolean;
|
|
107
|
+
try {
|
|
108
|
+
accepted = await context.publish({
|
|
109
|
+
...publication,
|
|
110
|
+
persist: { models: snapshot, checkedAt: primedAt },
|
|
111
|
+
});
|
|
112
|
+
} catch (error) {
|
|
113
|
+
// Pi persists before applying the update. A read-only store must
|
|
114
|
+
// not prevent a child from using the catalog it just fetched.
|
|
115
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
116
|
+
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
|
|
117
|
+
throw error;
|
|
118
|
+
accepted = await context.publish(publication);
|
|
119
|
+
}
|
|
120
|
+
if (accepted) primed = undefined;
|
|
121
|
+
return accepted;
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
} else await refresh(context);
|
|
125
|
+
};
|
|
126
|
+
return provider;
|
|
127
|
+
}
|
package/src/retry.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
FetchFunction,
|
|
3
|
+
ProviderStreams,
|
|
4
|
+
StreamOptions,
|
|
5
|
+
SimpleStreamOptions,
|
|
6
|
+
} from "@earendil-works/pi-ai";
|
|
7
|
+
|
|
8
|
+
/** Keep the server's not-before time across Pi agent-level attempts as well as SDK retries.
|
|
9
|
+
* Pi 1.5.2 defaults provider retries to zero and agent retries ignore retry-after.
|
|
10
|
+
* This adds NO attempts or retry policy; the next host-authorized request simply waits.
|
|
11
|
+
*/
|
|
12
|
+
export function withRetryAfter(api: ProviderStreams): ProviderStreams {
|
|
13
|
+
const deadlines = new Map<string, number>();
|
|
14
|
+
function transport(
|
|
15
|
+
modelId: string,
|
|
16
|
+
fetch: FetchFunction = globalThis.fetch,
|
|
17
|
+
signal?: AbortSignal,
|
|
18
|
+
): FetchFunction {
|
|
19
|
+
return async (input, init) => {
|
|
20
|
+
const requestSignal = init?.signal ?? signal;
|
|
21
|
+
const delay = (deadlines.get(modelId) ?? 0) - Date.now();
|
|
22
|
+
if (delay > 0)
|
|
23
|
+
await new Promise<void>((resolve, reject) => {
|
|
24
|
+
const abort = () => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
reject(new DOMException("Request aborted", "AbortError"));
|
|
27
|
+
};
|
|
28
|
+
const timer = setTimeout(() => {
|
|
29
|
+
requestSignal?.removeEventListener("abort", abort);
|
|
30
|
+
resolve();
|
|
31
|
+
}, delay);
|
|
32
|
+
if (requestSignal?.aborted) abort();
|
|
33
|
+
else requestSignal?.addEventListener("abort", abort, { once: true });
|
|
34
|
+
});
|
|
35
|
+
if ((deadlines.get(modelId) ?? 0) <= Date.now())
|
|
36
|
+
deadlines.delete(modelId);
|
|
37
|
+
const response = await fetch(input, init);
|
|
38
|
+
if (response.status === 429) {
|
|
39
|
+
const header = response.headers.get("retry-after");
|
|
40
|
+
if (header) {
|
|
41
|
+
const seconds = Number(header);
|
|
42
|
+
const deadline = Number.isFinite(seconds)
|
|
43
|
+
? Date.now() + seconds * 1000
|
|
44
|
+
: Date.parse(header);
|
|
45
|
+
if (Number.isFinite(deadline) && deadline > Date.now())
|
|
46
|
+
deadlines.set(modelId, deadline);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return response;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
stream: (m, c, o) =>
|
|
54
|
+
api.stream(m, c, {
|
|
55
|
+
...o,
|
|
56
|
+
fetch: transport(m.id, o?.fetch, o?.signal),
|
|
57
|
+
} as StreamOptions),
|
|
58
|
+
streamSimple: (m, c, o) =>
|
|
59
|
+
api.streamSimple(m, c, {
|
|
60
|
+
...o,
|
|
61
|
+
fetch: transport(m.id, o?.fetch, o?.signal),
|
|
62
|
+
} as SimpleStreamOptions),
|
|
63
|
+
};
|
|
64
|
+
}
|
package/src/thinking.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import {
|
|
2
|
+
clampThinkingLevel,
|
|
3
|
+
getSupportedThinkingLevels,
|
|
4
|
+
} from "@earendil-works/pi-ai";
|
|
5
|
+
import type {
|
|
6
|
+
ExtensionAPI,
|
|
7
|
+
ExtensionContext,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import type { RefuselessModel } from "./catalog.ts";
|
|
10
|
+
|
|
11
|
+
function hasConfiguredLevel(pi: ExtensionAPI, ctx: ExtensionContext): boolean {
|
|
12
|
+
const s = pi.getSettings();
|
|
13
|
+
if (
|
|
14
|
+
s.defaultThinkingLevel !== undefined ||
|
|
15
|
+
s.modelThinkingLevels?.[`${ctx.model?.provider}/${ctx.model?.id}`] !==
|
|
16
|
+
undefined
|
|
17
|
+
)
|
|
18
|
+
return true;
|
|
19
|
+
return ctx.scopedModels.some(
|
|
20
|
+
(s) =>
|
|
21
|
+
s.model.id === ctx.model?.id &&
|
|
22
|
+
s.model.provider === ctx.model?.provider &&
|
|
23
|
+
s.thinkingLevel !== undefined,
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
function cliLevelWasSet(): boolean {
|
|
27
|
+
return process.argv.some(
|
|
28
|
+
(a) =>
|
|
29
|
+
a === "--thinking" ||
|
|
30
|
+
a.startsWith("--thinking=") ||
|
|
31
|
+
/:(off|minimal|low|medium|high|xhigh|max)(,|$)/.test(a),
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
export function registerThinking(pi: ExtensionAPI) {
|
|
35
|
+
pi.on("session_start", (event, ctx) => {
|
|
36
|
+
if (event.reason !== "startup" && event.reason !== "new") return;
|
|
37
|
+
const m = ctx.model as RefuselessModel | undefined;
|
|
38
|
+
if (m?.provider !== "refuseless" || !m.reasoningDefault) return;
|
|
39
|
+
const branch = ctx.sessionManager.getBranch();
|
|
40
|
+
// Pi appends one implicit thinking entry even for a fresh session. Additional entries
|
|
41
|
+
// represent a later selection, including branches that have not sent a message yet.
|
|
42
|
+
if (
|
|
43
|
+
branch.some((e) => e.type === "message" || e.type === "custom") ||
|
|
44
|
+
branch.filter((e) => e.type === "thinking_level_change").length > 1
|
|
45
|
+
)
|
|
46
|
+
return;
|
|
47
|
+
if (cliLevelWasSet() || hasConfiguredLevel(pi, ctx)) return;
|
|
48
|
+
pi.setThinkingLevel(m.reasoningDefault);
|
|
49
|
+
});
|
|
50
|
+
pi.on("model_select", (event, ctx) => {
|
|
51
|
+
const m = event.model as RefuselessModel;
|
|
52
|
+
if (
|
|
53
|
+
event.source === "restore" ||
|
|
54
|
+
m.provider !== "refuseless" ||
|
|
55
|
+
!m.reasoningDefault
|
|
56
|
+
)
|
|
57
|
+
return;
|
|
58
|
+
if (
|
|
59
|
+
event.previousModel &&
|
|
60
|
+
getSupportedThinkingLevels(event.previousModel).some((l) => l !== "off")
|
|
61
|
+
)
|
|
62
|
+
return;
|
|
63
|
+
if (cliLevelWasSet() || hasConfiguredLevel(pi, ctx)) return;
|
|
64
|
+
if (
|
|
65
|
+
!event.previousModel ||
|
|
66
|
+
pi.getThinkingLevel() === clampThinkingLevel(m, "off")
|
|
67
|
+
)
|
|
68
|
+
pi.setThinkingLevel(m.reasoningDefault);
|
|
69
|
+
});
|
|
70
|
+
}
|