@sagmans/dsh-provider-extra 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -0
- package/dist/catalog-runtime.js +9 -1
- package/dist/client.js +230 -0
- package/dist/headless-startup.js +92 -0
- package/dist/index.js +13 -1
- package/dist/service-tiers.js +125 -0
- package/dist/tier-client.js +220 -0
- package/dist/tier-invocation.js +66 -0
- package/dist/tier-remote.js +57 -0
- package/dist/tier-store.js +146 -0
- package/dist/tui-actions.js +69 -0
- package/headless.patch.yml +7 -0
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -162,6 +162,89 @@ Routes without models or codexModels continue to read extraModels or codexExtraM
|
|
|
162
162
|
|
|
163
163
|
`codexTransport` pins the transport pi-ai uses for this route: `sse`, `websocket`, `websocket-cached`, or `auto`. Leave it out and pi-ai chooses, which on a network that never lets the subscription's websocket continue past the first answer leaves the reply printed and the process waiting; pin `sse` there.
|
|
164
164
|
|
|
165
|
+
## Service tiers
|
|
166
|
+
|
|
167
|
+
Plugin-owned OpenAI and Codex routes expose service tier selection through the `providerServiceTiers` service.
|
|
168
|
+
Choices are `auto`, `default`, and `priority` (Fast).
|
|
169
|
+
For Codex, Auto omits `service_tier` and lets the provider choose; it has the same wire behavior as Provider default but remains a distinct saved choice.
|
|
170
|
+
Native OpenAI routes continue to send `service_tier: "auto"` for Auto.
|
|
171
|
+
Priority processing can increase usage cost and requires account access.
|
|
172
|
+
The plugin does not offer `ultrafast` or `flex` for Codex.
|
|
173
|
+
|
|
174
|
+
Interactive choices apply to one provider and model pair across profiles.
|
|
175
|
+
The plugin atomically stores each choice under `$DSH_HOME/provider-extra-service-tiers/`, without editing configuration or duplicating the catalog.
|
|
176
|
+
Menus and requests read the latest saved choice.
|
|
177
|
+
Configured `serviceTierSelections` remain defaults until an interactive choice overrides them:
|
|
178
|
+
|
|
179
|
+
```yaml
|
|
180
|
+
- id: dsh-provider-extra
|
|
181
|
+
config:
|
|
182
|
+
serviceTierSelections:
|
|
183
|
+
- provider: example-codex-route
|
|
184
|
+
model: example-codex-model
|
|
185
|
+
tier: priority
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The selection reaches both stream entry points without changing authentication or transport.
|
|
189
|
+
Managed catalog aliases support tiers when their source is `openai` or `openai-codex` and their protocol supports tier selection.
|
|
190
|
+
An OpenAI-compatible protocol alone does not enable tiers.
|
|
191
|
+
Other sources and routes owned by another adapter do not advertise tiers.
|
|
192
|
+
The provider still controls model support and account access.
|
|
193
|
+
|
|
194
|
+
### Web and Desktop
|
|
195
|
+
|
|
196
|
+
Type `/service-tier` in the editor and select the command.
|
|
197
|
+
Its popup offers Provider default, Auto, Standard, and Fast.
|
|
198
|
+
The stock Model/Effort popup stays unchanged.
|
|
199
|
+
Unsupported routes show an unavailable message and no selectable tiers.
|
|
200
|
+
The command uses public npm DSH `0.2.0-rc.2` client services, without upstream patches or a custom React control.
|
|
201
|
+
|
|
202
|
+
### Headless
|
|
203
|
+
|
|
204
|
+
The packaged [headless overlay](headless.patch.yml) requires the public npm DSH `0.2.0-rc.2` startup and request-scoping contracts.
|
|
205
|
+
It replaces only startup parsing; the stock runner still owns execution and resume.
|
|
206
|
+
Enable this provider plugin in the headless profile first.
|
|
207
|
+
Pass the installed overlay path before headless options:
|
|
208
|
+
|
|
209
|
+
```sh
|
|
210
|
+
dsh --profile headless --patch /path/to/dsh-provider-extra/headless.patch.yml --service-tier=fast "Reply with exactly pong"
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Alternatively, compose the overlay entries into your headless profile once, then omit `--patch`.
|
|
214
|
+
Do not apply that overlay to Web, Desktop, or TUI profiles.
|
|
215
|
+
Stock headless startup alone does not recognize `--service-tier`.
|
|
216
|
+
|
|
217
|
+
Accepted values are `auto`, `standard` (`default`), `fast` (`priority`), and `provider-default`.
|
|
218
|
+
Without the flag, requests use the saved choice.
|
|
219
|
+
`provider-default` suppresses it for this invocation without changing storage.
|
|
220
|
+
Only the invoking root agent receives the override, including resumed requests.
|
|
221
|
+
Child agents, titles, and compaction retain their own defaults.
|
|
222
|
+
Invalid values and unsupported routes fail without sending a generation request.
|
|
223
|
+
Invocation overrides never enter settings or durable request headers.
|
|
224
|
+
|
|
225
|
+
### TUI
|
|
226
|
+
|
|
227
|
+
In dsh-tui, confirm an effort to open the tier picker.
|
|
228
|
+
The plugin registers `prefix+t` through the optional `tuiKeymaps` registry.
|
|
229
|
+
The TUI owns generic key dispatch, not this binding or its behavior.
|
|
230
|
+
Use `prefix+t` to open the tier picker independently.
|
|
231
|
+
Rebind `keys.plugin.provider-extra.serviceTier` on the owning TUI row.
|
|
232
|
+
On Config-backed profiles, put `keys` directly under that row's `config`, not under `settings`.
|
|
233
|
+
Keep `sessionId` and the other launch fields when editing the row.
|
|
234
|
+
Removing this provider plugin removes its shortcut and effort follow-up.
|
|
235
|
+
Choose **provider default** to suppress both the saved tier and its configured fallback.
|
|
236
|
+
Cancelling the tier picker does not change the confirmed effort.
|
|
237
|
+
Writes that fail before atomic replacement preserve the previous tier.
|
|
238
|
+
A connection or durability failure after replacement can leave the new tier visible; reopen the picker before retrying.
|
|
239
|
+
Cancelling an already-submitted save does not undo it.
|
|
240
|
+
Shared saves require a DSH profile with a resolved shared home and a filesystem that supports private POSIX permissions and directory synchronization.
|
|
241
|
+
Windows interactive persistence is unsupported; configured defaults and headless flags remain usable when no shared store exists.
|
|
242
|
+
Unreadable or malformed records block tier reads rather than silently restoring paid defaults; repair or remove the affected record.
|
|
243
|
+
With footer-hint support, explicit Auto and Fast appear beside effort, for example `(high · Fast)`.
|
|
244
|
+
Standard and provider-default selections stay hidden.
|
|
245
|
+
Provider default adds no `service_tier` field to normal requests.
|
|
246
|
+
Existing caller options and payload hooks remain unchanged.
|
|
247
|
+
|
|
165
248
|
## Provider sign-in
|
|
166
249
|
|
|
167
250
|
Sign in from the profile you are already using. The plugin registers a command in the harness command palette.
|
|
@@ -244,3 +327,12 @@ The workflow stores no npm token: the registry trusts `release.yml` on the `npm-
|
|
|
244
327
|
## License
|
|
245
328
|
|
|
246
329
|
MIT
|
|
330
|
+
|
|
331
|
+
## Git hooks
|
|
332
|
+
|
|
333
|
+
Checks run in tracked local Git hooks instead of push/PR CI. Run `scripts/setup-hooks` once after cloning; it points this clone's `core.hooksPath` at `.githooks`. Each hook runs the generic checks first (sign-off and commit message format, a gitleaks secret scan, and signed, signed-off commits on push), then this repository's checks in `.githooks/<hook>.d/` in name order. Install [gitleaks](https://github.com/gitleaks/gitleaks) first. Every check must pass before you push; never use `--no-verify`. Pre-push checks test exactly each pushed commit: in place only when it is the clean, unmodified checkout, otherwise in a temporary worktree of that commit.
|
|
334
|
+
|
|
335
|
+
This repository's checks:
|
|
336
|
+
|
|
337
|
+
- `pre-commit`: staged whitespace and conflict-marker check.
|
|
338
|
+
- `pre-push`: `npm audit signatures`, `pnpm run check`, `pnpm audit --audit-level high`.
|
package/dist/catalog-runtime.js
CHANGED
|
@@ -3,6 +3,7 @@ import { LlmError, assertUsableApiKey, resolveImageAttachmentAccess } from '@dee
|
|
|
3
3
|
import { codexAuth } from "./codex.js";
|
|
4
4
|
import { catalogDefault } from "./catalog-default.js";
|
|
5
5
|
import { mountLoginCommand } from "./login-host.js";
|
|
6
|
+
import { mountServiceTiers, withServiceTiers } from "./service-tiers.js";
|
|
6
7
|
const PLUGIN_NAME = 'dsh-provider-extra';
|
|
7
8
|
const OWNER_COLLISION = 'CATALOG_OWNER_COLLISION';
|
|
8
9
|
/** Preflight prevents even an unrelated competing row from expanding managed membership. */
|
|
@@ -27,8 +28,10 @@ export function mountCatalog(ctx, snapshot, config) {
|
|
|
27
28
|
const configured = snapshot.providers.get(route)?.auth;
|
|
28
29
|
return configured !== undefined && 'credentialProvider' in configured ? configured.credentialProvider : route;
|
|
29
30
|
};
|
|
31
|
+
const sourceFor = (route) => snapshot.providers.get(route)?.source;
|
|
32
|
+
const tiers = mountServiceTiers(ctx, config, () => { requireOwnership(); return snapshot.profiles; }, sourceFor);
|
|
30
33
|
const adapter = new PiAiAdapter({
|
|
31
|
-
profiles: () => { requireOwnership(); return snapshot.profiles; },
|
|
34
|
+
profiles: () => { requireOwnership(); return withServiceTiers(snapshot.profiles, tiers.current, sourceFor); },
|
|
32
35
|
auth: {
|
|
33
36
|
...auth,
|
|
34
37
|
// Route aliases must share the source provider's existing OAuth grant.
|
|
@@ -121,7 +124,12 @@ export function mountCatalog(ctx, snapshot, config) {
|
|
|
121
124
|
refreshOwnership();
|
|
122
125
|
// A public update veto runs before disposal, so a competing late-mounted
|
|
123
126
|
// adapter cannot turn a refused reload into loss of the last valid catalog.
|
|
127
|
+
let activeGeneration = true;
|
|
128
|
+
ctx.effect(() => () => { activeGeneration = false; });
|
|
124
129
|
ctx.on('internal/update', (next, _noSave, proceed) => {
|
|
130
|
+
// A retired snapshot must not veto replacement of the current catalog owner.
|
|
131
|
+
if (!activeGeneration)
|
|
132
|
+
return proceed();
|
|
125
133
|
if (next.catalog !== undefined)
|
|
126
134
|
assertCatalogOwnership(ctx, routes, defaults);
|
|
127
135
|
return proceed();
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({id:"@sagmans/dsh-provider-extra",factory(require){const exports={};
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.TIER_CONTRIBUTION = exports.TIER_SAVE_ERROR = exports.TIER_DEFAULT = exports.TIER_NAMESPACE = exports.TIER_PACKAGE = void 0;
|
|
5
|
+
exports.parseTierIdentity = parseTierIdentity;
|
|
6
|
+
exports.parseTier = parseTier;
|
|
7
|
+
exports.parseTierView = parseTierView;
|
|
8
|
+
exports.apply = apply;
|
|
9
|
+
exports.TIER_PACKAGE = '@sagmans/dsh-provider-extra';
|
|
10
|
+
exports.TIER_NAMESPACE = 'providerExtraTiers';
|
|
11
|
+
exports.TIER_DEFAULT = '';
|
|
12
|
+
const COMMAND_NAME = 'service-tier';
|
|
13
|
+
exports.TIER_SAVE_ERROR = 'Could not confirm service tier; check writable shared storage, then reopen /service-tier before retrying';
|
|
14
|
+
const READ_ERROR = 'Could not load service tiers; reopen /service-tier to retry';
|
|
15
|
+
const INVALID_WIRE = 'Invalid service tier data';
|
|
16
|
+
const INVALID_CHOICE = 'Invalid service tier selection';
|
|
17
|
+
const ROW_LABEL = 'Service tier';
|
|
18
|
+
const DEFAULT_LABEL = 'Provider default';
|
|
19
|
+
const COMMAND_SERVICE = 'commandUi';
|
|
20
|
+
const MODEL_SERVICE = 'modelDirectories';
|
|
21
|
+
const SESSION_SERVICE = 'sessions';
|
|
22
|
+
const REMOTE_SERVICE = 'remote';
|
|
23
|
+
const TIER_REMOTE_SERVICE = REMOTE_SERVICE + '.' + exports.TIER_NAMESPACE;
|
|
24
|
+
const UNAVAILABLE = 'Service tiers are unavailable for this model or session';
|
|
25
|
+
const STALE_ROUTE = 'Model changed; reopen /service-tier before saving';
|
|
26
|
+
const COMMAND_DESCRIPTION = 'Choose the current model’s shared service tier';
|
|
27
|
+
const SEARCH_PLACEHOLDER = 'Search service tiers';
|
|
28
|
+
const NO_RESULTS = 'No matching service tiers';
|
|
29
|
+
const TIER_IDS = ['auto', 'default', 'priority'];
|
|
30
|
+
/** Reject extra fields instead of forwarding accidental provider state. */
|
|
31
|
+
function record(value, keys) {
|
|
32
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)
|
|
33
|
+
|| Reflect.ownKeys(value).some(key => typeof key !== 'string' || !keys.includes(key)))
|
|
34
|
+
throw new TypeError(INVALID_WIRE);
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
/** Empty route identities cannot name a provider-owned capability. */
|
|
38
|
+
function parseTierIdentity(value) {
|
|
39
|
+
if (typeof value !== 'string' || value.trim().length === 0)
|
|
40
|
+
throw new TypeError(INVALID_WIRE);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/** Only explicitly supported billing policies may cross this boundary. */
|
|
44
|
+
function parseTier(value) {
|
|
45
|
+
if (value === undefined)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (typeof value !== 'string' || !TIER_IDS.some(id => id === value))
|
|
48
|
+
throw new TypeError(INVALID_WIRE);
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
/** Both gateway output and browser input require a complete, consistent view. */
|
|
52
|
+
function parseTierView(value) {
|
|
53
|
+
const input = record(value, ['choices', 'current']);
|
|
54
|
+
if (!Array.isArray(input.choices))
|
|
55
|
+
throw new TypeError(INVALID_WIRE);
|
|
56
|
+
const choices = input.choices.map(value => {
|
|
57
|
+
const choice = record(value, ['id', 'name', 'description']);
|
|
58
|
+
const id = parseTier(choice.id);
|
|
59
|
+
if (id === undefined)
|
|
60
|
+
throw new TypeError(INVALID_WIRE);
|
|
61
|
+
return { id, name: parseTierIdentity(choice.name), description: parseTierIdentity(choice.description) };
|
|
62
|
+
});
|
|
63
|
+
const ids = new Set(choices.map(choice => choice.id));
|
|
64
|
+
if (ids.size !== choices.length)
|
|
65
|
+
throw new TypeError(INVALID_WIRE);
|
|
66
|
+
const current = parseTier(input.current);
|
|
67
|
+
if (current !== undefined && !ids.has(current))
|
|
68
|
+
throw new TypeError(INVALID_WIRE);
|
|
69
|
+
return { choices, ...(current === undefined ? {} : { current }) };
|
|
70
|
+
}
|
|
71
|
+
/** A successful write returns no unvalidated provider details. */
|
|
72
|
+
function parseVoid(value) {
|
|
73
|
+
if (value !== undefined)
|
|
74
|
+
throw new TypeError(INVALID_WIRE);
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
/** Typert needs only parse; importing a schema library would add browser dependencies. */
|
|
78
|
+
function strict(typeSymbol, parse) {
|
|
79
|
+
return { mode: 'strict', typeSymbol, create: () => ({ parse }), decode: parse };
|
|
80
|
+
}
|
|
81
|
+
const IDENTITY_CODEC = strict(exports.TIER_PACKAGE + '.TierIdentity', parseTierIdentity);
|
|
82
|
+
const TIER_CODEC = strict(exports.TIER_PACKAGE + '.TierSelection', parseTier);
|
|
83
|
+
const VIEW_CODEC = strict(exports.TIER_PACKAGE + '.TierView', parseTierView);
|
|
84
|
+
const VOID_CODEC = strict('void', parseVoid);
|
|
85
|
+
const ROUTE_PARAMETERS = [
|
|
86
|
+
{ name: 'provider', wire: 'provider', source: 'json', codec: IDENTITY_CODEC },
|
|
87
|
+
{ name: 'model', wire: 'model', source: 'json', codec: IDENTITY_CODEC },
|
|
88
|
+
];
|
|
89
|
+
/** Explicit descriptors avoid a generator or a multi-module browser bundler. */
|
|
90
|
+
exports.TIER_CONTRIBUTION = {
|
|
91
|
+
package: exports.TIER_PACKAGE,
|
|
92
|
+
descriptors: [
|
|
93
|
+
{ id: exports.TIER_NAMESPACE + '/describe', service: exports.TIER_NAMESPACE, namespace: exports.TIER_NAMESPACE, method: 'describe',
|
|
94
|
+
invocation: { kind: 'direct' }, parameters: ROUTE_PARAMETERS, cancellation: { parameter: 'signal' }, result: VIEW_CODEC },
|
|
95
|
+
{ id: exports.TIER_NAMESPACE + '/select', service: exports.TIER_NAMESPACE, namespace: exports.TIER_NAMESPACE, method: 'select',
|
|
96
|
+
invocation: { kind: 'direct' }, parameters: [...ROUTE_PARAMETERS,
|
|
97
|
+
{ name: 'tier', wire: 'tier', source: 'json', acceptsUndefined: true, codec: TIER_CODEC }],
|
|
98
|
+
cancellation: { parameter: 'signal' }, result: VOID_CODEC },
|
|
99
|
+
],
|
|
100
|
+
};
|
|
101
|
+
/** Remote failures contain transport detail that must not become UI error text. */
|
|
102
|
+
function resultValue(result, message) {
|
|
103
|
+
if (result === null || typeof result !== 'object' || !('ok' in result) || result.ok !== true)
|
|
104
|
+
throw new Error(message);
|
|
105
|
+
const envelope = record(result, ['ok', 'value']);
|
|
106
|
+
return envelope.value;
|
|
107
|
+
}
|
|
108
|
+
/** Optional injection keeps older hosts inert and scopes command ownership to HMR lifetime. */
|
|
109
|
+
function apply(ctx) {
|
|
110
|
+
ctx.inject([COMMAND_SERVICE, MODEL_SERVICE, SESSION_SERVICE, REMOTE_SERVICE], owner => {
|
|
111
|
+
const command = owner.get(COMMAND_SERVICE);
|
|
112
|
+
const models = owner.get(MODEL_SERVICE);
|
|
113
|
+
const sessions = owner.get(SESSION_SERVICE);
|
|
114
|
+
const remote = owner.get(REMOTE_SERVICE);
|
|
115
|
+
const lifetime = new AbortController();
|
|
116
|
+
const selections = new WeakMap();
|
|
117
|
+
const available = (session) => {
|
|
118
|
+
if (sessions.subagentAddress(session.sessionId) !== undefined)
|
|
119
|
+
return false;
|
|
120
|
+
const state = models.directoryFor(session.sessionId).store.getSnapshot();
|
|
121
|
+
return state.current !== null && state.routable !== false;
|
|
122
|
+
};
|
|
123
|
+
owner.effect(() => () => { lifetime.abort(); });
|
|
124
|
+
owner.effect(async () => {
|
|
125
|
+
const unmount = await remote.$mount(exports.TIER_CONTRIBUTION);
|
|
126
|
+
if (lifetime.signal.aborted)
|
|
127
|
+
return unmount;
|
|
128
|
+
try {
|
|
129
|
+
// The dynamically mounted namespace needs its own declared Cordis dependency.
|
|
130
|
+
const registration = owner.inject([TIER_REMOTE_SERVICE], scope => {
|
|
131
|
+
const tiers = scope.get(TIER_REMOTE_SERVICE);
|
|
132
|
+
const registered = new AbortController();
|
|
133
|
+
scope.effect(() => () => { registered.abort(); });
|
|
134
|
+
scope.effect(() => {
|
|
135
|
+
const unregister = command.register({
|
|
136
|
+
name: COMMAND_NAME,
|
|
137
|
+
label: () => ROW_LABEL,
|
|
138
|
+
description: () => COMMAND_DESCRIPTION,
|
|
139
|
+
available,
|
|
140
|
+
ui: {
|
|
141
|
+
kind: 'popupSelect',
|
|
142
|
+
searchLabels: () => ({ placeholder: SEARCH_PLACEHOLDER, empty: UNAVAILABLE, noResults: NO_RESULTS }),
|
|
143
|
+
async options(session, requestSignal) {
|
|
144
|
+
const opening = new AbortController();
|
|
145
|
+
const signal = AbortSignal.any([requestSignal, lifetime.signal, registered.signal, opening.signal]);
|
|
146
|
+
signal.throwIfAborted();
|
|
147
|
+
if (!available(session))
|
|
148
|
+
return [];
|
|
149
|
+
const directory = models.directoryFor(session.sessionId);
|
|
150
|
+
const current = directory.store.getSnapshot().current;
|
|
151
|
+
const provider = parseTierIdentity(current.provider);
|
|
152
|
+
const model = parseTierIdentity(current.model);
|
|
153
|
+
const invalidate = () => {
|
|
154
|
+
const latest = directory.store.getSnapshot().current;
|
|
155
|
+
try {
|
|
156
|
+
if (available(session) && models.directoryFor(session.sessionId) === directory
|
|
157
|
+
&& latest?.provider === provider && latest.model === model)
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
catch { /* A removed session scope must not retain permission to write. */ }
|
|
161
|
+
opening.abort(new Error(STALE_ROUTE));
|
|
162
|
+
};
|
|
163
|
+
const checkRoute = () => { invalidate(); signal.throwIfAborted(); };
|
|
164
|
+
// A route that changes away and back still invalidates the original billing decision.
|
|
165
|
+
const unsubscribe = directory.store.subscribe(invalidate);
|
|
166
|
+
signal.addEventListener('abort', unsubscribe, { once: true });
|
|
167
|
+
let view;
|
|
168
|
+
try {
|
|
169
|
+
await directory.load();
|
|
170
|
+
checkRoute();
|
|
171
|
+
view = parseTierView(resultValue(await tiers.describe(provider, model, signal), READ_ERROR));
|
|
172
|
+
checkRoute();
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
const error = signal.aborted ? signal.reason : new Error(READ_ERROR);
|
|
176
|
+
opening.abort();
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
if (view.choices.length === 0) {
|
|
180
|
+
opening.abort();
|
|
181
|
+
return [];
|
|
182
|
+
}
|
|
183
|
+
const options = [
|
|
184
|
+
{ id: exports.TIER_DEFAULT, label: DEFAULT_LABEL, active: view.current === undefined },
|
|
185
|
+
...view.choices.map(choice => ({ id: choice.id, label: choice.name, detail: choice.description, active: view.current === choice.id })),
|
|
186
|
+
];
|
|
187
|
+
for (const option of options) {
|
|
188
|
+
const tier = option.id === exports.TIER_DEFAULT ? undefined : option.id;
|
|
189
|
+
selections.set(option, {
|
|
190
|
+
sessionId: session.sessionId,
|
|
191
|
+
async select() {
|
|
192
|
+
checkRoute();
|
|
193
|
+
try {
|
|
194
|
+
parseVoid(resultValue(await tiers.select(provider, model, tier, signal), exports.TIER_SAVE_ERROR));
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
signal.throwIfAborted();
|
|
198
|
+
throw new Error(exports.TIER_SAVE_ERROR);
|
|
199
|
+
}
|
|
200
|
+
checkRoute();
|
|
201
|
+
// The stock shell does not abort its signal on successful selection.
|
|
202
|
+
opening.abort();
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return options;
|
|
207
|
+
},
|
|
208
|
+
async onSelect(option, session) {
|
|
209
|
+
const selection = selections.get(option);
|
|
210
|
+
if (selection === undefined || selection.sessionId !== session.sessionId)
|
|
211
|
+
throw new Error(INVALID_CHOICE);
|
|
212
|
+
await selection.select();
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
return () => { command.dismiss(COMMAND_NAME); unregister(); };
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
await registration;
|
|
220
|
+
return async () => { await registration.dispose(); await unmount(); };
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
await unmount();
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return exports;}});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** Headless-only argument ownership leaves the stock runner and its durable session protocol unchanged. */
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { isServiceTierOverride } from "./service-tiers.js";
|
|
4
|
+
export const name = 'provider-extra-headless-startup';
|
|
5
|
+
export const inject = ['cmdlineArgs', 'appExit', 'agents', 'providerTierInvocation'];
|
|
6
|
+
const STARTUP_SERVICE = 'headlessStartup';
|
|
7
|
+
const SUCCESS = 0;
|
|
8
|
+
const USAGE_ERROR = 1;
|
|
9
|
+
const SEPARATOR = '--';
|
|
10
|
+
const STDIN_TASK = '-';
|
|
11
|
+
const JSON_FLAG = '--json';
|
|
12
|
+
const VALUE_FLAGS = new Set(['--session-id', '--service-tier']);
|
|
13
|
+
const TASK_REQUIRED = 'a task is required, for example: dsh --profile headless "run the tests"';
|
|
14
|
+
const HELP = "Usage: dsh --profile headless [options] [task...]\n\nAnswer one task and exit; the answer goes to stdout and diagnostics to stderr.\n\nOptions:\n --json write newline-delimited run events to stdout instead of the final message\n --session-id <id> adopt the persisted Session with this id; an unknown id is an error\n --service-tier <tier> invocation only: auto, default, priority, fast, standard, provider-default\n -h, --help show this help\n\nThe task text joins multiple words with spaces; - reads stdin.\n\nExamples:\n dsh --profile headless \"run the tests\"\n echo \"run the tests\" | dsh --profile headless\n dsh --profile headless --json \"run the tests\"\n dsh --profile headless --session-id session-… \"continue\"\n";
|
|
15
|
+
/** Only a real flag before the separator can opt parse failures into machine-readable output. */
|
|
16
|
+
function jsonRequested(args) {
|
|
17
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
18
|
+
if (args[index] === SEPARATOR)
|
|
19
|
+
return false;
|
|
20
|
+
if (args[index] === JSON_FLAG)
|
|
21
|
+
return true;
|
|
22
|
+
if (VALUE_FLAGS.has(args[index]))
|
|
23
|
+
index += 1;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
/** Stock required options accept dash-prefixed values; native strict parsing needs their explicit equals form. */
|
|
28
|
+
function nativeArgs(args) {
|
|
29
|
+
const normalized = [];
|
|
30
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
31
|
+
const argument = args[index];
|
|
32
|
+
if (argument === SEPARATOR) {
|
|
33
|
+
normalized.push(...args.slice(index));
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
normalized.push(VALUE_FLAGS.has(argument) && index + 1 < args.length
|
|
37
|
+
? argument + '=' + args[++index] : argument);
|
|
38
|
+
}
|
|
39
|
+
return normalized;
|
|
40
|
+
}
|
|
41
|
+
/** Publishing this public service starts the stock runner, so all syntax validation precedes publication. */
|
|
42
|
+
export function apply(ctx) {
|
|
43
|
+
const cmdline = ctx.get('cmdlineArgs');
|
|
44
|
+
const exit = ctx.get('appExit');
|
|
45
|
+
if (!cmdline || !exit)
|
|
46
|
+
throw new Error('dsh --profile headless: the launcher must provide ctx.cmdlineArgs and ctx.appExit before the tree mounts');
|
|
47
|
+
const args = cmdline.get();
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
parsed = parseArgs({ args: nativeArgs(args), allowPositionals: true, strict: true, options: {
|
|
51
|
+
json: { type: 'boolean' },
|
|
52
|
+
'session-id': { type: 'string' },
|
|
53
|
+
'service-tier': { type: 'string' },
|
|
54
|
+
help: { type: 'boolean', short: 'h' },
|
|
55
|
+
} });
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
reject(error instanceof Error ? error.message : String(error));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const { values, positionals } = parsed;
|
|
62
|
+
if (values.help) {
|
|
63
|
+
process.stdout.write(HELP);
|
|
64
|
+
exit(SUCCESS);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const task = positionals.length === 0 ? undefined : positionals.join(' ');
|
|
68
|
+
const sessionId = values['session-id'];
|
|
69
|
+
const override = values['service-tier'];
|
|
70
|
+
if (positionals.length > 1 && positionals.includes(STDIN_TASK))
|
|
71
|
+
return reject('`-` must be the only task argument');
|
|
72
|
+
if ((task !== undefined && task.trim() === '') || (task === undefined && process.stdin.isTTY))
|
|
73
|
+
return reject(TASK_REQUIRED);
|
|
74
|
+
if (sessionId !== undefined && sessionId.trim() === '')
|
|
75
|
+
return reject('--session-id requires a non-empty session id');
|
|
76
|
+
if (override !== undefined && !isServiceTierOverride(override))
|
|
77
|
+
return reject('unsupported --service-tier: ' + override);
|
|
78
|
+
const agents = ctx.get('agents');
|
|
79
|
+
const controller = ctx.get('providerTierInvocation');
|
|
80
|
+
if (!agents || !controller)
|
|
81
|
+
throw new Error('headless service tiers require agents and providerTierInvocation');
|
|
82
|
+
ctx.effect(() => controller.activate(override, sessionId, agents));
|
|
83
|
+
ctx.provide(STARTUP_SERVICE, { task, sessionId, json: values.json === true });
|
|
84
|
+
/** Usage failures remain launcher-owned exits instead of failing plugin mounts or starting requests. */
|
|
85
|
+
function reject(message) {
|
|
86
|
+
if (jsonRequested(args))
|
|
87
|
+
process.stdout.write(JSON.stringify({ type: 'error', message }) + '\n');
|
|
88
|
+
else
|
|
89
|
+
process.stderr.write('error: ' + message + '\n');
|
|
90
|
+
exit(USAGE_ERROR);
|
|
91
|
+
}
|
|
92
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -38,6 +38,7 @@ import { DEFAULT_LOGIN_COMMAND_NAME } from "./login-command.js";
|
|
|
38
38
|
import { mountLoginCommand } from "./login-host.js";
|
|
39
39
|
import { compileCatalog } from "./catalog.js";
|
|
40
40
|
import { mountCatalog } from "./catalog-runtime.js";
|
|
41
|
+
import { mountServiceTiers, withServiceTiers, SERVICE_TIER_CHOICES } from "./service-tiers.js";
|
|
41
42
|
export { compileCatalog } from "./catalog.js";
|
|
42
43
|
export { buildCatalogProfile } from "./catalog-routes.js";
|
|
43
44
|
/** Settings namespace configuration surfaces address this plugin's section by. */
|
|
@@ -67,6 +68,12 @@ const codexExtraModelSchema = Schema.object({
|
|
|
67
68
|
export const Config = Schema.transform(Schema.object({
|
|
68
69
|
// Keep raw catalog presence: schemastery otherwise materializes absent arrays.
|
|
69
70
|
catalog: Schema.any(),
|
|
71
|
+
// The validated Config transform owns this array; profile edits reconcile it atomically.
|
|
72
|
+
serviceTierSelections: Schema.array(Schema.object({
|
|
73
|
+
provider: Schema.string().required(),
|
|
74
|
+
model: Schema.string().required(),
|
|
75
|
+
tier: Schema.union(SERVICE_TIER_CHOICES.map(choice => choice.id)).required(),
|
|
76
|
+
})).default([]),
|
|
70
77
|
apiKeyEnv: Schema.string().role('credential-ref').default(DEFAULT_OPENCODE_API_KEY_ENV),
|
|
71
78
|
routeId: Schema.string().default(OPENCODE_GO_PROVIDER_ID),
|
|
72
79
|
displayName: Schema.string().default('OpenCode Go'),
|
|
@@ -183,8 +190,11 @@ export function apply(ctx, config) {
|
|
|
183
190
|
}
|
|
184
191
|
return new Map(entries);
|
|
185
192
|
};
|
|
193
|
+
const servedProviders = new Set();
|
|
194
|
+
const sourceFor = (provider) => provider === codex.provider && codexServable ? DEFAULT_CODEX_ROUTE_ID : undefined;
|
|
195
|
+
const tiers = mountServiceTiers(ctx, config, () => new Map([...profiles()].filter(([provider]) => servedProviders.has(provider))), sourceFor);
|
|
186
196
|
const adapter = new PiAiAdapter({
|
|
187
|
-
profiles,
|
|
197
|
+
profiles: () => withServiceTiers(profiles(), tiers.current, sourceFor),
|
|
188
198
|
resolveApiKey: async (provider) => {
|
|
189
199
|
// The Codex route authenticates from the stored OAuth grant, never
|
|
190
200
|
// from a key: absent here is what lets the collection store serve it.
|
|
@@ -225,6 +235,7 @@ export function apply(ctx, config) {
|
|
|
225
235
|
// remediation and every other plugin keeps working.
|
|
226
236
|
try {
|
|
227
237
|
ctx.llm.registerAdapter([route.provider], adapter);
|
|
238
|
+
servedProviders.add(route.provider);
|
|
228
239
|
}
|
|
229
240
|
catch (error) {
|
|
230
241
|
ctx.logger.error('dsh-provider-extra: route "' + route.provider + '" was refused;'
|
|
@@ -239,6 +250,7 @@ export function apply(ctx, config) {
|
|
|
239
250
|
if (codexServable) {
|
|
240
251
|
try {
|
|
241
252
|
ctx.llm.registerAdapter([codex.provider], adapter);
|
|
253
|
+
servedProviders.add(codex.provider);
|
|
242
254
|
}
|
|
243
255
|
catch (error) {
|
|
244
256
|
ctx.logger.warn('dsh-provider-extra: codex route "' + codex.provider + '" stays with its existing owner;'
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { mountTierActions } from "./tui-actions.js";
|
|
2
|
+
import { mountTierRemote } from "./tier-remote.js";
|
|
3
|
+
import { createTierStore } from "./tier-store.js";
|
|
4
|
+
import { currentInvocationTier, mountTierInvocation } from "./tier-invocation.js";
|
|
5
|
+
/** Source and protocol must agree before a route can request paid processing. */
|
|
6
|
+
export const CODEX_TIER_API = 'openai-codex-responses';
|
|
7
|
+
const CODEX_SOURCE = 'openai-codex';
|
|
8
|
+
const OPENAI_SOURCE = 'openai';
|
|
9
|
+
const AUTO_TIER = 'auto';
|
|
10
|
+
const OPENAI_TIER_APIS = ['openai-responses', 'openai-completions'];
|
|
11
|
+
/** Keep saved choices stable while each native protocol resolves its own wire policy. */
|
|
12
|
+
export const SERVICE_TIER_CHOICES = [
|
|
13
|
+
{ id: AUTO_TIER, name: 'Auto', description: 'Use the account service tier' },
|
|
14
|
+
{ id: 'default', name: 'Standard', description: 'Standard processing' },
|
|
15
|
+
{ id: 'priority', name: 'Fast', description: 'Priority processing; higher usage cost, subject to account access' },
|
|
16
|
+
];
|
|
17
|
+
const SERVICE_NAME = 'providerServiceTiers';
|
|
18
|
+
const PROFILE_SERVICE = 'profileContext';
|
|
19
|
+
const INVOCATION_TIERS = new Map([
|
|
20
|
+
['fast', 'priority'],
|
|
21
|
+
['standard', 'default'],
|
|
22
|
+
['provider-default', null],
|
|
23
|
+
]);
|
|
24
|
+
const INVALID_TIER = 'unsupported service tier for this model route';
|
|
25
|
+
const INVALID_PAYLOAD = 'OpenAI service tier requires an object request payload';
|
|
26
|
+
/** Standalone helpers may use native route ids; mounted owners must supply authoritative sources. */
|
|
27
|
+
const routeIdentity = provider => provider;
|
|
28
|
+
/** OpenAI-compatible gateways must not inherit native account billing policy. */
|
|
29
|
+
function supportsTiers(source, api) {
|
|
30
|
+
return source === CODEX_SOURCE ? api === CODEX_TIER_API
|
|
31
|
+
: source === OPENAI_SOURCE && OPENAI_TIER_APIS.includes(api);
|
|
32
|
+
}
|
|
33
|
+
/** Reject stale or hand-edited values before they become request parameters. */
|
|
34
|
+
function validTier(tier) {
|
|
35
|
+
return SERVICE_TIER_CHOICES.some(choice => choice.id === tier);
|
|
36
|
+
}
|
|
37
|
+
/** Startup validation shares the same canonical values and aliases as model-scoped resolution. */
|
|
38
|
+
export function isServiceTierOverride(value) {
|
|
39
|
+
return validTier(value) || INVOCATION_TIERS.has(value);
|
|
40
|
+
}
|
|
41
|
+
/** Durable writes complete before the selected row can truthfully report success. */
|
|
42
|
+
export function createTierSelection(read, write, profiles, sourceFor = routeIdentity) {
|
|
43
|
+
const choices = (provider, model) => profiles().get(provider)?.piProvider?.getModels().some(entry => entry.id === model && supportsTiers(sourceFor(provider), entry.api))
|
|
44
|
+
? SERVICE_TIER_CHOICES : [];
|
|
45
|
+
return {
|
|
46
|
+
choices,
|
|
47
|
+
resolve: (provider, model, override) => {
|
|
48
|
+
const available = choices(provider, model);
|
|
49
|
+
const tier = INVOCATION_TIERS.has(override) ? INVOCATION_TIERS.get(override) : override;
|
|
50
|
+
if (available.length === 0 || (tier !== null && !available.some(choice => choice.id === tier)))
|
|
51
|
+
throw new Error(INVALID_TIER);
|
|
52
|
+
return tier;
|
|
53
|
+
},
|
|
54
|
+
current: (provider, model) => {
|
|
55
|
+
const tier = read(provider, model);
|
|
56
|
+
return typeof tier === 'string' && validTier(tier) ? tier : undefined;
|
|
57
|
+
},
|
|
58
|
+
select: async (provider, model, tier) => {
|
|
59
|
+
if (choices(provider, model).length === 0 || (tier !== undefined && !validTier(tier)))
|
|
60
|
+
throw new Error(INVALID_TIER);
|
|
61
|
+
await write(provider, model, tier ?? null);
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Decorate native streams so existing auth, routing, transport, and replay survive. */
|
|
66
|
+
export function withServiceTiers(profiles, current, sourceFor = routeIdentity) {
|
|
67
|
+
return new Map([...profiles].map(([id, profile]) => {
|
|
68
|
+
const source = profile.piProvider;
|
|
69
|
+
const eligible = (model) => supportsTiers(sourceFor(id), model.api);
|
|
70
|
+
if (source === undefined || !source.getModels().some(eligible))
|
|
71
|
+
return [id, profile];
|
|
72
|
+
const optionsFor = (model, options) => {
|
|
73
|
+
// Plugin-local request scope carries CLI policy without changing host request or session schemas.
|
|
74
|
+
const invocation = currentInvocationTier();
|
|
75
|
+
const override = invocation === undefined
|
|
76
|
+
? options?.serviceTier : invocation;
|
|
77
|
+
if (override === null) {
|
|
78
|
+
if (options === undefined)
|
|
79
|
+
return undefined;
|
|
80
|
+
const forwarded = Object.assign({}, options);
|
|
81
|
+
delete forwarded.serviceTier;
|
|
82
|
+
return forwarded;
|
|
83
|
+
}
|
|
84
|
+
const tier = override ?? current(id, model.id);
|
|
85
|
+
if (!eligible(model) || tier === undefined || !validTier(tier))
|
|
86
|
+
return options;
|
|
87
|
+
// Codex rejects literal auto; omission delegates to the account without changing the saved choice.
|
|
88
|
+
const wireTier = model.api === CODEX_TIER_API && tier === AUTO_TIER ? undefined : tier;
|
|
89
|
+
return Object.assign({}, options, { serviceTier: wireTier, onPayload: async (payload, wireModel) => {
|
|
90
|
+
// pi-ai's simple stream drops serviceTier, but retains this final serialization hook.
|
|
91
|
+
const replacement = await options?.onPayload?.(payload, wireModel);
|
|
92
|
+
const body = replacement === undefined ? payload : replacement;
|
|
93
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body))
|
|
94
|
+
throw new Error(INVALID_PAYLOAD);
|
|
95
|
+
const forwarded = { ...body };
|
|
96
|
+
if (wireTier === undefined)
|
|
97
|
+
delete forwarded.service_tier;
|
|
98
|
+
else
|
|
99
|
+
forwarded.service_tier = wireTier;
|
|
100
|
+
return forwarded;
|
|
101
|
+
} });
|
|
102
|
+
};
|
|
103
|
+
return [id, { ...profile, piProvider: {
|
|
104
|
+
...source,
|
|
105
|
+
stream: (model, context, options) => source.stream(model, context, optionsFor(model, options)),
|
|
106
|
+
streamSimple: (model, context, options) => source.streamSimple(model, context, optionsFor(model, options)),
|
|
107
|
+
} }];
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
/** Plugin-owned records share selections without editing or reconciling profile configuration. */
|
|
111
|
+
export function mountServiceTiers(ctx, config, profiles, sourceFor = routeIdentity) {
|
|
112
|
+
const profile = ctx.get(PROFILE_SERVICE);
|
|
113
|
+
const store = createTierStore(profile?.home, validTier);
|
|
114
|
+
const service = createTierSelection((provider, model) => {
|
|
115
|
+
const tier = store.read(provider, model);
|
|
116
|
+
return tier === undefined
|
|
117
|
+
? config.serviceTierSelections?.find(entry => entry.provider === provider && entry.model === model)?.tier
|
|
118
|
+
: tier;
|
|
119
|
+
}, store.write, profiles, sourceFor);
|
|
120
|
+
ctx.provide(SERVICE_NAME, service);
|
|
121
|
+
mountTierInvocation(ctx, service);
|
|
122
|
+
mountTierRemote(ctx);
|
|
123
|
+
mountTierActions(ctx, service);
|
|
124
|
+
return service;
|
|
125
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
export const TIER_PACKAGE = '@sagmans/dsh-provider-extra';
|
|
2
|
+
export const TIER_NAMESPACE = 'providerExtraTiers';
|
|
3
|
+
export const TIER_DEFAULT = '';
|
|
4
|
+
const COMMAND_NAME = 'service-tier';
|
|
5
|
+
export const TIER_SAVE_ERROR = 'Could not confirm service tier; check writable shared storage, then reopen /service-tier before retrying';
|
|
6
|
+
const READ_ERROR = 'Could not load service tiers; reopen /service-tier to retry';
|
|
7
|
+
const INVALID_WIRE = 'Invalid service tier data';
|
|
8
|
+
const INVALID_CHOICE = 'Invalid service tier selection';
|
|
9
|
+
const ROW_LABEL = 'Service tier';
|
|
10
|
+
const DEFAULT_LABEL = 'Provider default';
|
|
11
|
+
const COMMAND_SERVICE = 'commandUi';
|
|
12
|
+
const MODEL_SERVICE = 'modelDirectories';
|
|
13
|
+
const SESSION_SERVICE = 'sessions';
|
|
14
|
+
const REMOTE_SERVICE = 'remote';
|
|
15
|
+
const TIER_REMOTE_SERVICE = REMOTE_SERVICE + '.' + TIER_NAMESPACE;
|
|
16
|
+
const UNAVAILABLE = 'Service tiers are unavailable for this model or session';
|
|
17
|
+
const STALE_ROUTE = 'Model changed; reopen /service-tier before saving';
|
|
18
|
+
const COMMAND_DESCRIPTION = 'Choose the current model’s shared service tier';
|
|
19
|
+
const SEARCH_PLACEHOLDER = 'Search service tiers';
|
|
20
|
+
const NO_RESULTS = 'No matching service tiers';
|
|
21
|
+
const TIER_IDS = ['auto', 'default', 'priority'];
|
|
22
|
+
/** Reject extra fields instead of forwarding accidental provider state. */
|
|
23
|
+
function record(value, keys) {
|
|
24
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)
|
|
25
|
+
|| Reflect.ownKeys(value).some(key => typeof key !== 'string' || !keys.includes(key)))
|
|
26
|
+
throw new TypeError(INVALID_WIRE);
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/** Empty route identities cannot name a provider-owned capability. */
|
|
30
|
+
export function parseTierIdentity(value) {
|
|
31
|
+
if (typeof value !== 'string' || value.trim().length === 0)
|
|
32
|
+
throw new TypeError(INVALID_WIRE);
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
/** Only explicitly supported billing policies may cross this boundary. */
|
|
36
|
+
export function parseTier(value) {
|
|
37
|
+
if (value === undefined)
|
|
38
|
+
return undefined;
|
|
39
|
+
if (typeof value !== 'string' || !TIER_IDS.some(id => id === value))
|
|
40
|
+
throw new TypeError(INVALID_WIRE);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/** Both gateway output and browser input require a complete, consistent view. */
|
|
44
|
+
export function parseTierView(value) {
|
|
45
|
+
const input = record(value, ['choices', 'current']);
|
|
46
|
+
if (!Array.isArray(input.choices))
|
|
47
|
+
throw new TypeError(INVALID_WIRE);
|
|
48
|
+
const choices = input.choices.map(value => {
|
|
49
|
+
const choice = record(value, ['id', 'name', 'description']);
|
|
50
|
+
const id = parseTier(choice.id);
|
|
51
|
+
if (id === undefined)
|
|
52
|
+
throw new TypeError(INVALID_WIRE);
|
|
53
|
+
return { id, name: parseTierIdentity(choice.name), description: parseTierIdentity(choice.description) };
|
|
54
|
+
});
|
|
55
|
+
const ids = new Set(choices.map(choice => choice.id));
|
|
56
|
+
if (ids.size !== choices.length)
|
|
57
|
+
throw new TypeError(INVALID_WIRE);
|
|
58
|
+
const current = parseTier(input.current);
|
|
59
|
+
if (current !== undefined && !ids.has(current))
|
|
60
|
+
throw new TypeError(INVALID_WIRE);
|
|
61
|
+
return { choices, ...(current === undefined ? {} : { current }) };
|
|
62
|
+
}
|
|
63
|
+
/** A successful write returns no unvalidated provider details. */
|
|
64
|
+
function parseVoid(value) {
|
|
65
|
+
if (value !== undefined)
|
|
66
|
+
throw new TypeError(INVALID_WIRE);
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/** Typert needs only parse; importing a schema library would add browser dependencies. */
|
|
70
|
+
function strict(typeSymbol, parse) {
|
|
71
|
+
return { mode: 'strict', typeSymbol, create: () => ({ parse }), decode: parse };
|
|
72
|
+
}
|
|
73
|
+
const IDENTITY_CODEC = strict(TIER_PACKAGE + '.TierIdentity', parseTierIdentity);
|
|
74
|
+
const TIER_CODEC = strict(TIER_PACKAGE + '.TierSelection', parseTier);
|
|
75
|
+
const VIEW_CODEC = strict(TIER_PACKAGE + '.TierView', parseTierView);
|
|
76
|
+
const VOID_CODEC = strict('void', parseVoid);
|
|
77
|
+
const ROUTE_PARAMETERS = [
|
|
78
|
+
{ name: 'provider', wire: 'provider', source: 'json', codec: IDENTITY_CODEC },
|
|
79
|
+
{ name: 'model', wire: 'model', source: 'json', codec: IDENTITY_CODEC },
|
|
80
|
+
];
|
|
81
|
+
/** Explicit descriptors avoid a generator or a multi-module browser bundler. */
|
|
82
|
+
export const TIER_CONTRIBUTION = {
|
|
83
|
+
package: TIER_PACKAGE,
|
|
84
|
+
descriptors: [
|
|
85
|
+
{ id: TIER_NAMESPACE + '/describe', service: TIER_NAMESPACE, namespace: TIER_NAMESPACE, method: 'describe',
|
|
86
|
+
invocation: { kind: 'direct' }, parameters: ROUTE_PARAMETERS, cancellation: { parameter: 'signal' }, result: VIEW_CODEC },
|
|
87
|
+
{ id: TIER_NAMESPACE + '/select', service: TIER_NAMESPACE, namespace: TIER_NAMESPACE, method: 'select',
|
|
88
|
+
invocation: { kind: 'direct' }, parameters: [...ROUTE_PARAMETERS,
|
|
89
|
+
{ name: 'tier', wire: 'tier', source: 'json', acceptsUndefined: true, codec: TIER_CODEC }],
|
|
90
|
+
cancellation: { parameter: 'signal' }, result: VOID_CODEC },
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
/** Remote failures contain transport detail that must not become UI error text. */
|
|
94
|
+
function resultValue(result, message) {
|
|
95
|
+
if (result === null || typeof result !== 'object' || !('ok' in result) || result.ok !== true)
|
|
96
|
+
throw new Error(message);
|
|
97
|
+
const envelope = record(result, ['ok', 'value']);
|
|
98
|
+
return envelope.value;
|
|
99
|
+
}
|
|
100
|
+
/** Optional injection keeps older hosts inert and scopes command ownership to HMR lifetime. */
|
|
101
|
+
export function apply(ctx) {
|
|
102
|
+
ctx.inject([COMMAND_SERVICE, MODEL_SERVICE, SESSION_SERVICE, REMOTE_SERVICE], owner => {
|
|
103
|
+
const command = owner.get(COMMAND_SERVICE);
|
|
104
|
+
const models = owner.get(MODEL_SERVICE);
|
|
105
|
+
const sessions = owner.get(SESSION_SERVICE);
|
|
106
|
+
const remote = owner.get(REMOTE_SERVICE);
|
|
107
|
+
const lifetime = new AbortController();
|
|
108
|
+
const selections = new WeakMap();
|
|
109
|
+
const available = (session) => {
|
|
110
|
+
if (sessions.subagentAddress(session.sessionId) !== undefined)
|
|
111
|
+
return false;
|
|
112
|
+
const state = models.directoryFor(session.sessionId).store.getSnapshot();
|
|
113
|
+
return state.current !== null && state.routable !== false;
|
|
114
|
+
};
|
|
115
|
+
owner.effect(() => () => { lifetime.abort(); });
|
|
116
|
+
owner.effect(async () => {
|
|
117
|
+
const unmount = await remote.$mount(TIER_CONTRIBUTION);
|
|
118
|
+
if (lifetime.signal.aborted)
|
|
119
|
+
return unmount;
|
|
120
|
+
try {
|
|
121
|
+
// The dynamically mounted namespace needs its own declared Cordis dependency.
|
|
122
|
+
const registration = owner.inject([TIER_REMOTE_SERVICE], scope => {
|
|
123
|
+
const tiers = scope.get(TIER_REMOTE_SERVICE);
|
|
124
|
+
const registered = new AbortController();
|
|
125
|
+
scope.effect(() => () => { registered.abort(); });
|
|
126
|
+
scope.effect(() => {
|
|
127
|
+
const unregister = command.register({
|
|
128
|
+
name: COMMAND_NAME,
|
|
129
|
+
label: () => ROW_LABEL,
|
|
130
|
+
description: () => COMMAND_DESCRIPTION,
|
|
131
|
+
available,
|
|
132
|
+
ui: {
|
|
133
|
+
kind: 'popupSelect',
|
|
134
|
+
searchLabels: () => ({ placeholder: SEARCH_PLACEHOLDER, empty: UNAVAILABLE, noResults: NO_RESULTS }),
|
|
135
|
+
async options(session, requestSignal) {
|
|
136
|
+
const opening = new AbortController();
|
|
137
|
+
const signal = AbortSignal.any([requestSignal, lifetime.signal, registered.signal, opening.signal]);
|
|
138
|
+
signal.throwIfAborted();
|
|
139
|
+
if (!available(session))
|
|
140
|
+
return [];
|
|
141
|
+
const directory = models.directoryFor(session.sessionId);
|
|
142
|
+
const current = directory.store.getSnapshot().current;
|
|
143
|
+
const provider = parseTierIdentity(current.provider);
|
|
144
|
+
const model = parseTierIdentity(current.model);
|
|
145
|
+
const invalidate = () => {
|
|
146
|
+
const latest = directory.store.getSnapshot().current;
|
|
147
|
+
try {
|
|
148
|
+
if (available(session) && models.directoryFor(session.sessionId) === directory
|
|
149
|
+
&& latest?.provider === provider && latest.model === model)
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
catch { /* A removed session scope must not retain permission to write. */ }
|
|
153
|
+
opening.abort(new Error(STALE_ROUTE));
|
|
154
|
+
};
|
|
155
|
+
const checkRoute = () => { invalidate(); signal.throwIfAborted(); };
|
|
156
|
+
// A route that changes away and back still invalidates the original billing decision.
|
|
157
|
+
const unsubscribe = directory.store.subscribe(invalidate);
|
|
158
|
+
signal.addEventListener('abort', unsubscribe, { once: true });
|
|
159
|
+
let view;
|
|
160
|
+
try {
|
|
161
|
+
await directory.load();
|
|
162
|
+
checkRoute();
|
|
163
|
+
view = parseTierView(resultValue(await tiers.describe(provider, model, signal), READ_ERROR));
|
|
164
|
+
checkRoute();
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
const error = signal.aborted ? signal.reason : new Error(READ_ERROR);
|
|
168
|
+
opening.abort();
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
if (view.choices.length === 0) {
|
|
172
|
+
opening.abort();
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
175
|
+
const options = [
|
|
176
|
+
{ id: TIER_DEFAULT, label: DEFAULT_LABEL, active: view.current === undefined },
|
|
177
|
+
...view.choices.map(choice => ({ id: choice.id, label: choice.name, detail: choice.description, active: view.current === choice.id })),
|
|
178
|
+
];
|
|
179
|
+
for (const option of options) {
|
|
180
|
+
const tier = option.id === TIER_DEFAULT ? undefined : option.id;
|
|
181
|
+
selections.set(option, {
|
|
182
|
+
sessionId: session.sessionId,
|
|
183
|
+
async select() {
|
|
184
|
+
checkRoute();
|
|
185
|
+
try {
|
|
186
|
+
parseVoid(resultValue(await tiers.select(provider, model, tier, signal), TIER_SAVE_ERROR));
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
signal.throwIfAborted();
|
|
190
|
+
throw new Error(TIER_SAVE_ERROR);
|
|
191
|
+
}
|
|
192
|
+
checkRoute();
|
|
193
|
+
// The stock shell does not abort its signal on successful selection.
|
|
194
|
+
opening.abort();
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return options;
|
|
199
|
+
},
|
|
200
|
+
async onSelect(option, session) {
|
|
201
|
+
const selection = selections.get(option);
|
|
202
|
+
if (selection === undefined || selection.sessionId !== session.sessionId)
|
|
203
|
+
throw new Error(INVALID_CHOICE);
|
|
204
|
+
await selection.select();
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
return () => { command.dismiss(COMMAND_NAME); unregister(); };
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
await registration;
|
|
212
|
+
return async () => { await registration.dispose(); await unmount(); };
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
await unmount();
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Process-local request scope keeps paid headless policy out of durable session state. */
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import * as llm from '@deepseek-ai/dsh-llm';
|
|
4
|
+
const SERVICE_NAME = 'providerTierInvocation';
|
|
5
|
+
const SINGLE_ROOT = 1;
|
|
6
|
+
const AMBIGUOUS_ROOT = 'headless service tier override cannot identify a unique invoking root';
|
|
7
|
+
const UNSUPPORTED_RUNTIME = 'headless service tiers require the npm DSH 0.2.0-rc.2 loop marker and agents root registry';
|
|
8
|
+
const scope = new AsyncLocalStorage();
|
|
9
|
+
/** Null suppresses saved policy; undefined leaves normal configured/shared defaults intact. */
|
|
10
|
+
export function currentInvocationTier() {
|
|
11
|
+
return scope.getStore();
|
|
12
|
+
}
|
|
13
|
+
/** Mount once beside the tier owner; startup injects this service and supplies the public agents registry. */
|
|
14
|
+
export function mountTierInvocation(ctx, tiers) {
|
|
15
|
+
let active;
|
|
16
|
+
ctx.provide(SERVICE_NAME, {
|
|
17
|
+
activate(override, sessionId, agents) {
|
|
18
|
+
if (override !== undefined && (typeof llm.isAgentLoopRequest !== 'function' || typeof agents.roots !== 'function')) {
|
|
19
|
+
throw new Error(UNSUPPORTED_RUNTIME);
|
|
20
|
+
}
|
|
21
|
+
active = override === undefined ? undefined : {
|
|
22
|
+
override, sessionId, agents, previousRoots: new Set(agents.roots()),
|
|
23
|
+
};
|
|
24
|
+
const activation = active;
|
|
25
|
+
return () => { if (active === activation)
|
|
26
|
+
active = undefined; };
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
ctx.effect(() => () => { active = undefined; });
|
|
30
|
+
ctx.on('llm/stream', (request, next) => {
|
|
31
|
+
const tier = resolve(request);
|
|
32
|
+
// Even excluded nested calls need an explicit empty scope rather than inheriting their caller's tier.
|
|
33
|
+
return {
|
|
34
|
+
[Symbol.asyncIterator]() {
|
|
35
|
+
const iterator = scope.run(tier, () => next()[Symbol.asyncIterator]());
|
|
36
|
+
return {
|
|
37
|
+
next: (...args) => scope.run(tier, () => iterator.next(...args)),
|
|
38
|
+
return: (value) => scope.run(tier, () => iterator.return
|
|
39
|
+
? iterator.return(value) : Promise.resolve({ done: true, value })),
|
|
40
|
+
throw: (error) => scope.run(tier, () => iterator.throw
|
|
41
|
+
? iterator.throw(error) : Promise.reject(error)),
|
|
42
|
+
};
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
/** Bind one newly registered root, or the exact resumed root, before accepting request metadata. */
|
|
47
|
+
function resolve(request) {
|
|
48
|
+
if (!active || !llm.isAgentLoopRequest(request) || !request.sessionId || request.purpose !== undefined)
|
|
49
|
+
return undefined;
|
|
50
|
+
const roots = active.agents.roots();
|
|
51
|
+
if (!active.root) {
|
|
52
|
+
const candidates = roots.filter(root => !active.previousRoots.has(root)
|
|
53
|
+
&& (active.sessionId === undefined || root.id === active.sessionId));
|
|
54
|
+
if (candidates.length !== SINGLE_ROOT) {
|
|
55
|
+
// Falling back here could restore saved paid processing against an explicit provider-default request.
|
|
56
|
+
if (candidates.some(root => root.id === request.sessionId))
|
|
57
|
+
throw new Error(AMBIGUOUS_ROOT);
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
active.root = candidates[0];
|
|
61
|
+
}
|
|
62
|
+
if (!roots.includes(active.root) || active.root.id !== request.sessionId)
|
|
63
|
+
return undefined;
|
|
64
|
+
return tiers.resolve(request.provider, request.model, active.override);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { TIER_CONTRIBUTION, TIER_NAMESPACE, TIER_SAVE_ERROR, parseTier, parseTierIdentity, parseTierView } from "./tier-client.js";
|
|
2
|
+
const TYPERT_SERVICE = 'typert';
|
|
3
|
+
const TIER_SERVICE = 'providerServiceTiers';
|
|
4
|
+
const UNSUPPORTED = 'Service tier is unsupported for this model route';
|
|
5
|
+
const HOST_CONTRIBUTION = {
|
|
6
|
+
package: TIER_CONTRIBUTION.package,
|
|
7
|
+
face: 'host',
|
|
8
|
+
schemas: [],
|
|
9
|
+
model: { services: [], events: [], objects: [] },
|
|
10
|
+
invocations: TIER_CONTRIBUTION.descriptors,
|
|
11
|
+
};
|
|
12
|
+
/** Fresh Context lookups preserve provider replacement and HMR semantics. */
|
|
13
|
+
class TierRemote {
|
|
14
|
+
ctx;
|
|
15
|
+
typertRemote = { service: this, serviceKey: TIER_NAMESPACE, namespace: TIER_NAMESPACE };
|
|
16
|
+
constructor(ctx) {
|
|
17
|
+
this.ctx = ctx;
|
|
18
|
+
}
|
|
19
|
+
/** Do not expose provider internals alongside the public capability view. */
|
|
20
|
+
async describe(provider, model, signal) {
|
|
21
|
+
signal?.throwIfAborted();
|
|
22
|
+
const providerId = parseTierIdentity(provider);
|
|
23
|
+
const modelId = parseTierIdentity(model);
|
|
24
|
+
const tiers = this.ctx.get(TIER_SERVICE);
|
|
25
|
+
const choices = tiers.choices(providerId, modelId).map(({ id, name, description }) => ({ id, name, description }));
|
|
26
|
+
const current = choices.length === 0 ? undefined : tiers.current(providerId, modelId);
|
|
27
|
+
return parseTierView({ choices, ...(current === undefined ? {} : { current }) });
|
|
28
|
+
}
|
|
29
|
+
/** Capability validation precedes mutation; persistence failures reveal no paths or secrets. */
|
|
30
|
+
async select(provider, model, tier, signal) {
|
|
31
|
+
signal?.throwIfAborted();
|
|
32
|
+
const providerId = parseTierIdentity(provider);
|
|
33
|
+
const modelId = parseTierIdentity(model);
|
|
34
|
+
const selected = parseTier(tier);
|
|
35
|
+
const tiers = this.ctx.get(TIER_SERVICE);
|
|
36
|
+
const choices = tiers.choices(providerId, modelId);
|
|
37
|
+
if (choices.length === 0 || (selected !== undefined && !choices.some(choice => choice.id === selected)))
|
|
38
|
+
throw new Error(UNSUPPORTED);
|
|
39
|
+
try {
|
|
40
|
+
await tiers.select(providerId, modelId, selected);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
signal?.throwIfAborted();
|
|
44
|
+
throw new Error(TIER_SAVE_ERROR);
|
|
45
|
+
}
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Older or terminal-only hosts do not need Typert to use provider tier policy. */
|
|
50
|
+
export function mountTierRemote(ctx) {
|
|
51
|
+
ctx.inject([TYPERT_SERVICE, TIER_SERVICE], owner => {
|
|
52
|
+
owner.provide(TIER_NAMESPACE, new TierRemote(owner));
|
|
53
|
+
const typert = owner.get(TYPERT_SERVICE);
|
|
54
|
+
// Host dispatch reads local invocations; remotes.register owns only consumer descriptors.
|
|
55
|
+
owner.effect(() => typert.register(HOST_CONTRIBUTION));
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** Pair-sized records avoid cross-profile lost updates without a shared database or lock. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
|
|
4
|
+
import { mkdir, open, rename, unlink } from 'node:fs/promises';
|
|
5
|
+
import { isAbsolute, join } from 'node:path';
|
|
6
|
+
const DIRECTORY = 'provider-extra-service-tiers';
|
|
7
|
+
const RECORD_VERSION = 1;
|
|
8
|
+
const MAX_RECORD_BYTES = 16 * 1024;
|
|
9
|
+
const MAX_IDENTIFIER_BYTES = 1024;
|
|
10
|
+
const DIRECTORY_MODE = 0o700;
|
|
11
|
+
const RECORD_MODE = 0o600;
|
|
12
|
+
const PUBLIC_PERMISSIONS = 0o077;
|
|
13
|
+
const RECORD_KEYS = ['version', 'provider', 'model', 'tier'];
|
|
14
|
+
const INVALID_INPUT = 'invalid service tier storage selection';
|
|
15
|
+
const READ_FAILURE = 'service tier storage record is unreadable or invalid';
|
|
16
|
+
const MISSING_HOME = 'service tier could not be saved; resolved profileContext.home is required';
|
|
17
|
+
const UNSAFE_DIRECTORY = 'service tier storage directory must be private and not a symlink';
|
|
18
|
+
const UNCERTAIN_WRITE = 'service tier was written, but durability could not be confirmed; reload the selection before retrying';
|
|
19
|
+
const WINDOWS_PLATFORM = 'win32';
|
|
20
|
+
const WINDOWS_UNSUPPORTED = 'service tier persistence is unsupported on Windows';
|
|
21
|
+
/** Identity validation bounds hashing and rejects control characters in hand-edited records. */
|
|
22
|
+
function validIdentifier(value) {
|
|
23
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
24
|
+
&& Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES && !/[\u0000-\u001f\u007f]/u.test(value);
|
|
25
|
+
}
|
|
26
|
+
/** Missing files alone permit configuration fallback; malformed state never enables paid tiers. */
|
|
27
|
+
function missing(error) {
|
|
28
|
+
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
|
29
|
+
}
|
|
30
|
+
/** Reject redirected or public plugin directories without changing home permissions. */
|
|
31
|
+
function privateDirectory(directory) {
|
|
32
|
+
const info = lstatSync(directory);
|
|
33
|
+
if (!info.isDirectory() || (info.mode & PUBLIC_PERMISSIONS) !== 0)
|
|
34
|
+
throw new Error(UNSAFE_DIRECTORY);
|
|
35
|
+
}
|
|
36
|
+
/** File sync alone cannot make a created directory entry or renamed record crash-durable. */
|
|
37
|
+
async function syncDirectory(directory) {
|
|
38
|
+
const file = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY);
|
|
39
|
+
try {
|
|
40
|
+
await file.sync();
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
await file.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** The route owner supplies canonical tiers; storage owns only durability and record validation. */
|
|
47
|
+
export function createTierStore(home, validTier) {
|
|
48
|
+
const directory = typeof home === 'string' && isAbsolute(home) ? join(home, DIRECTORY) : undefined;
|
|
49
|
+
const recordPath = (provider, model) => {
|
|
50
|
+
if (!validIdentifier(provider) || !validIdentifier(model))
|
|
51
|
+
throw new Error(INVALID_INPUT);
|
|
52
|
+
if (directory === undefined)
|
|
53
|
+
throw new Error(MISSING_HOME);
|
|
54
|
+
const digest = createHash('sha256').update(JSON.stringify([provider, model])).digest('hex');
|
|
55
|
+
return join(directory, digest + '.json');
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
read(provider, model) {
|
|
59
|
+
if (directory === undefined)
|
|
60
|
+
return undefined;
|
|
61
|
+
let descriptor;
|
|
62
|
+
try {
|
|
63
|
+
const path = recordPath(provider, model);
|
|
64
|
+
privateDirectory(directory);
|
|
65
|
+
// Nonblocking/no-follow also reject FIFOs and symlinks without hanging a menu or request.
|
|
66
|
+
descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
67
|
+
const info = fstatSync(descriptor);
|
|
68
|
+
if (!info.isFile() || info.size > MAX_RECORD_BYTES || (info.mode & PUBLIC_PERMISSIONS) !== 0)
|
|
69
|
+
throw new Error(READ_FAILURE);
|
|
70
|
+
const bytes = Buffer.alloc(MAX_RECORD_BYTES + 1);
|
|
71
|
+
let length = 0;
|
|
72
|
+
let count;
|
|
73
|
+
do {
|
|
74
|
+
count = readSync(descriptor, bytes, length, bytes.length - length, null);
|
|
75
|
+
length += count;
|
|
76
|
+
} while (count > 0 && length < bytes.length);
|
|
77
|
+
if (length > MAX_RECORD_BYTES)
|
|
78
|
+
throw new Error(READ_FAILURE);
|
|
79
|
+
const record = JSON.parse(bytes.subarray(0, length).toString('utf8'));
|
|
80
|
+
if (record === null || typeof record !== 'object' || Array.isArray(record))
|
|
81
|
+
throw new Error(READ_FAILURE);
|
|
82
|
+
const data = record;
|
|
83
|
+
if (Object.keys(data).length !== RECORD_KEYS.length || !RECORD_KEYS.every(key => Object.hasOwn(data, key))
|
|
84
|
+
|| data.version !== RECORD_VERSION || data.provider !== provider || data.model !== model
|
|
85
|
+
|| (data.tier !== null && (typeof data.tier !== 'string' || !validTier(data.tier))))
|
|
86
|
+
throw new Error(READ_FAILURE);
|
|
87
|
+
return data.tier;
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (missing(error))
|
|
91
|
+
return undefined;
|
|
92
|
+
throw new Error(READ_FAILURE);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
if (descriptor !== undefined)
|
|
96
|
+
closeSync(descriptor);
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
async write(provider, model, tier) {
|
|
100
|
+
const path = recordPath(provider, model);
|
|
101
|
+
if (tier !== null && (typeof tier !== 'string' || !validTier(tier)))
|
|
102
|
+
throw new Error(INVALID_INPUT);
|
|
103
|
+
// Windows cannot guarantee these POSIX privacy and directory-sync contracts; leave fallback state untouched.
|
|
104
|
+
if (process.platform === WINDOWS_PLATFORM)
|
|
105
|
+
throw new Error(WINDOWS_UNSUPPORTED);
|
|
106
|
+
try {
|
|
107
|
+
await mkdir(directory, { mode: DIRECTORY_MODE });
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST'))
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
privateDirectory(directory);
|
|
114
|
+
// Every writer covers a directory another process may have just created but not yet synced.
|
|
115
|
+
await syncDirectory(home);
|
|
116
|
+
const temporary = join(directory, '.' + randomUUID() + '.tmp');
|
|
117
|
+
let created = false;
|
|
118
|
+
try {
|
|
119
|
+
const file = await open(temporary, 'wx', RECORD_MODE);
|
|
120
|
+
created = true;
|
|
121
|
+
try {
|
|
122
|
+
await file.writeFile(JSON.stringify({ version: RECORD_VERSION, provider, model, tier }));
|
|
123
|
+
await file.sync();
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
await file.close();
|
|
127
|
+
}
|
|
128
|
+
await rename(temporary, path);
|
|
129
|
+
created = false;
|
|
130
|
+
try {
|
|
131
|
+
await syncDirectory(directory);
|
|
132
|
+
}
|
|
133
|
+
catch (cause) {
|
|
134
|
+
// Rollback could overwrite a concurrent writer after this record became visible.
|
|
135
|
+
throw new Error(UNCERTAIN_WRITE, { cause });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
// Only uncommitted temporaries belong to this writer after a failed operation.
|
|
140
|
+
if (created)
|
|
141
|
+
await unlink(temporary).catch(error => { if (!missing(error))
|
|
142
|
+
throw error; });
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const REGISTRY = 'tuiKeymaps';
|
|
2
|
+
export const TIER_ACTION_ID = 'plugin.provider-extra.serviceTier';
|
|
3
|
+
const TIER_KEY = 't';
|
|
4
|
+
const TIER_LABEL = 'service tier';
|
|
5
|
+
const PROVIDER_DEFAULT = '';
|
|
6
|
+
/** Ordinary processing stays quiet; only account-auto and expedited choices qualify the route. */
|
|
7
|
+
const FOOTER_TIERS = new Set(['auto', 'priority']);
|
|
8
|
+
const SAVE_FAILURE = 'could not confirm service tier; check writable shared storage, then reopen the picker before retrying';
|
|
9
|
+
const DISCOVERY_FAILURE = 'could not read service tiers; check provider configuration and retry';
|
|
10
|
+
const NO_ROUTE = 'no model route is in use; choose a model first';
|
|
11
|
+
const UNSUPPORTED = 'this model route advertises no service tiers';
|
|
12
|
+
/** The captured owner lasts exactly as long as its scoped registration, including Config reconciliation. */
|
|
13
|
+
export function createTierPicker(tiers) {
|
|
14
|
+
let opening = false;
|
|
15
|
+
return async (ports, quiet = false) => {
|
|
16
|
+
if (opening)
|
|
17
|
+
return;
|
|
18
|
+
opening = true;
|
|
19
|
+
let saving = false;
|
|
20
|
+
try {
|
|
21
|
+
const route = ports.route;
|
|
22
|
+
if (route === undefined) {
|
|
23
|
+
if (!quiet)
|
|
24
|
+
ports.notice(NO_ROUTE);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const choices = tiers.choices(route.provider, route.model);
|
|
28
|
+
if (choices.length === 0) {
|
|
29
|
+
if (!quiet)
|
|
30
|
+
ports.notice(UNSUPPORTED);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const current = tiers.current(route.provider, route.model);
|
|
34
|
+
const rows = [
|
|
35
|
+
{ id: PROVIDER_DEFAULT, name: 'provider default', description: 'clear the explicit service tier', current: current === undefined },
|
|
36
|
+
...choices.map(choice => ({ ...choice, current: choice.id === current })),
|
|
37
|
+
];
|
|
38
|
+
const picked = await ports.pick({ title: TIER_LABEL + ' · ' + route.provider + '/' + route.model, rows });
|
|
39
|
+
if (picked === undefined)
|
|
40
|
+
return;
|
|
41
|
+
if (!rows.some(row => row.id === picked))
|
|
42
|
+
throw new Error(DISCOVERY_FAILURE);
|
|
43
|
+
saving = true;
|
|
44
|
+
await tiers.select(route.provider, route.model, picked === PROVIDER_DEFAULT ? undefined : picked);
|
|
45
|
+
ports.notice(TIER_LABEL + ' set to ' + (picked === PROVIDER_DEFAULT ? 'provider default' : picked) + ' for the next request');
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
ports.notice(saving ? SAVE_FAILURE : DISCOVERY_FAILURE);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
opening = false;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Optional injection leaves console and web profiles independent of the terminal bundle. */
|
|
56
|
+
export function mountTierActions(ctx, tiers) {
|
|
57
|
+
ctx.inject([REGISTRY], owner => {
|
|
58
|
+
const registry = owner.get(REGISTRY);
|
|
59
|
+
const choose = createTierPicker(tiers);
|
|
60
|
+
registry.register(owner, { id: TIER_ACTION_ID, layer: 'chord', defaultKeys: [TIER_KEY], label: TIER_LABEL,
|
|
61
|
+
handler: ports => choose(ports),
|
|
62
|
+
routeHint: route => {
|
|
63
|
+
const tier = tiers.current(route.provider, route.model);
|
|
64
|
+
return FOOTER_TIERS.has(tier ?? PROVIDER_DEFAULT)
|
|
65
|
+
? tiers.choices(route.provider, route.model).find(choice => choice.id === tier)?.name : undefined;
|
|
66
|
+
} });
|
|
67
|
+
registry.afterEffort(owner, ports => choose(ports, true));
|
|
68
|
+
});
|
|
69
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sagmans/dsh-provider-extra",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Extra LLM provider routes for DeepSeek Harness: OpenCode Go with per-session x-opencode-session routing, and OpenAI Codex over ChatGPT-subscription OAuth.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek-harness",
|
|
@@ -18,6 +18,9 @@
|
|
|
18
18
|
"main": "./dist/index.js",
|
|
19
19
|
"exports": {
|
|
20
20
|
".": "./dist/index.js",
|
|
21
|
+
"./client": "./dist/client.js",
|
|
22
|
+
"./headless-startup": "./dist/headless-startup.js",
|
|
23
|
+
"./headless.patch.yml": "./headless.patch.yml",
|
|
21
24
|
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
22
25
|
"./package.json": "./package.json"
|
|
23
26
|
},
|
|
@@ -28,6 +31,7 @@
|
|
|
28
31
|
"dist",
|
|
29
32
|
"docs",
|
|
30
33
|
"cordis.patch.yml",
|
|
34
|
+
"headless.patch.yml",
|
|
31
35
|
"README.md"
|
|
32
36
|
],
|
|
33
37
|
"engines": {
|
|
@@ -45,6 +49,9 @@
|
|
|
45
49
|
"homepage": "https://github.com/sagmans/dsh-provider-extra#readme",
|
|
46
50
|
"bugs": "https://github.com/sagmans/dsh-provider-extra/issues",
|
|
47
51
|
"dsh": {
|
|
52
|
+
"client": {
|
|
53
|
+
"platform": "web"
|
|
54
|
+
},
|
|
48
55
|
"bundle": {
|
|
49
56
|
"patch": "./cordis.patch.yml"
|
|
50
57
|
},
|
|
@@ -63,7 +70,8 @@
|
|
|
63
70
|
"codex:login": "node --import tsx/esm src/login-cli.ts",
|
|
64
71
|
"test": "node --import tsx/esm --test \"tests/*.spec.ts\"",
|
|
65
72
|
"typecheck": "tsc --noEmit",
|
|
66
|
-
"build": "tsc -p tsconfig.build.json",
|
|
73
|
+
"build": "tsc -p tsconfig.build.json && node tools/build-client.mjs",
|
|
74
|
+
"build:client": "node tools/build-client.mjs",
|
|
67
75
|
"test:build": "node --test \"tests/*.test.mjs\"",
|
|
68
76
|
"test:release": "python3 -m unittest discover -s tests/release -p 'test_*.py'",
|
|
69
77
|
"pack-smoke": "node tools/pack-smoke.mjs",
|