dsh-taskbridge 1.7.0 → 1.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/CHANGELOG.md +18 -0
- package/LICENSE +21 -21
- package/README.md +150 -289
- package/THIRD_PARTY_NOTICES.txt +23 -23
- package/antigravity/agents/dsh-taskbridge.md +31 -0
- package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
- package/codex/dsh-taskbridge.toml +170 -627
- package/cordis.patch.yml +6 -6
- package/docs/INTRODUCTION.md +119 -295
- package/docs/INTRODUCTION.zh.md +134 -279
- package/docs/antigravity-integration.md +42 -0
- package/docs/auth-contract.md +138 -138
- package/docs/claude-code.md +6 -11
- package/docs/codex-integration.md +13 -2
- package/docs/contracts-stage-b.md +443 -443
- package/docs/plugin-market.md +30 -30
- package/docs/redaction-contract.md +170 -170
- package/docs/releases/1.7.0.zh.md +11 -11
- package/docs/releases/1.8.0.zh.md +16 -0
- package/docs/runtime-compatibility.md +1 -1
- package/docs/taskbridge-upgrade.md +28 -28
- package/docs/taskdispatch-upgrade.md +25 -25
- package/docs/workspace-contract.md +538 -538
- package/docs/workspace-grouping.md +126 -126
- package/icon.svg +1 -1
- package/lib/client.d.ts +733 -699
- package/lib/client.js +7 -7
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +149 -144
- package/src/antigravity/installer.js +1046 -0
- package/src/antigravity/seam.js +142 -0
- package/src/auth/fence.js +361 -361
- package/src/auth/grants.js +789 -789
- package/src/client/api.js +143 -0
- package/src/client/index.jsx +113 -3
- package/src/client/sidebar.jsx +862 -862
- package/src/client/styles.js +624 -624
- package/src/client/task-cleanup.js +304 -304
- package/src/client/task-records-table.jsx +217 -217
- package/src/client/task-view.js +307 -307
- package/src/client/workspace-groups.js +482 -482
- package/src/client/workspaces-browser.jsx +770 -770
- package/src/codex/agent-ownership.js +270 -270
- package/src/codex/installer.js +6 -0
- package/src/codex/toml.js +784 -784
- package/src/config/redact.js +245 -245
- package/src/config/store.js +186 -186
- package/src/credentials/seam.js +202 -202
- package/src/http/respond.js +6 -5
- package/src/http/user-plane.js +72 -0
- package/src/index.js +25 -0
- package/src/jobs/diagnostics.js +15 -15
- package/src/jobs/plan-store.js +1020 -1020
- package/src/jobs/review-note.js +63 -63
- package/src/jobs/task-descriptions.js +82 -82
- package/src/jobs/task-display.js +73 -73
- package/src/jobs/task-tree.js +786 -786
- package/src/jobs/title.js +134 -134
- package/src/mcp/continuation.js +317 -317
- package/src/mcp/server.js +12 -5
- package/src/model/connectivity.js +371 -371
- package/src/model/discovery.js +582 -582
- package/src/model/native-catalog.js +68 -68
- package/src/model/openai-adapter.js +671 -671
- package/src/model/probe.js +264 -264
- package/src/model/providers.js +756 -756
- package/src/model/routing.js +321 -321
- package/src/runtime/permissions.js +1619 -1619
- package/src/runtime/question-call.js +162 -162
- package/src/runtime/questions.js +909 -909
- package/src/runtime/worker-prompt.js +60 -53
- package/src/workspace/audit.js +775 -775
- package/src/workspace/preflight.js +424 -424
- package/src/workspace/worktrees.js +679 -679
package/src/model/providers.js
CHANGED
|
@@ -1,756 +1,756 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Native provider route registration.
|
|
3
|
-
*
|
|
4
|
-
* Maps the operator-facing provider profile ids from one settings snapshot to
|
|
5
|
-
* namespaced native route ids owned by a single adapter registration on the
|
|
6
|
-
* installed `@deepseek-ai/dsh-llm` runtime.
|
|
7
|
-
*
|
|
8
|
-
* Contract used by `JobEngine.ensureRoutes()` (`src/jobs/engine.js`):
|
|
9
|
-
* `await registry.ensure(providers)` resolves to `{ routes: Map<publicId, nativeRouteId> }`.
|
|
10
|
-
* The returned Map is a fresh snapshot per call, so a job that keeps one cannot
|
|
11
|
-
* observe or corrupt a later ensure.
|
|
12
|
-
*
|
|
13
|
-
* Lifecycle, per the real `LlmRuntime.registerAdapter(providers, adapter)` API:
|
|
14
|
-
* - the first non-empty provider list registers the adapter once;
|
|
15
|
-
* - later ensures swap the whole route set through the disposer's
|
|
16
|
-
* `replace(providers)` (atomic in the core, and legal with an empty list);
|
|
17
|
-
* - `dispose()` releases the registration and is idempotent.
|
|
18
|
-
*
|
|
19
|
-
* Two constraints of that API are load-bearing here and are enforced rather than
|
|
20
|
-
* assumed:
|
|
21
|
-
*
|
|
22
|
-
* 1. The registered object must be the adapter itself. `registerAdapter(ids,
|
|
23
|
-
* facade)` would store a management object whose `providerInfo` may exist
|
|
24
|
-
* but whose `stream`/`prepareCall` never do, so every call on those routes
|
|
25
|
-
* would fail with "no adapter registered" even though registration
|
|
26
|
-
* "succeeded". {@link nativeAdapterOf} unwraps a facade when one is passed,
|
|
27
|
-
* and refuses anything that has no call path at all.
|
|
28
|
-
* 2. `prepareRoutes()` reads `adapter.providerInfo(id)` synchronously before it
|
|
29
|
-
* commits, so whatever snapshot the adapter serves at registration time is
|
|
30
|
-
* the one that names those routes. {@link createProviderRegistry} therefore
|
|
31
|
-
* exposes `register()` as a callback: the caller publishes the candidate
|
|
32
|
-
* snapshot, then registers, and only that order lets `prepareRoutes` see the
|
|
33
|
-
* configured display names instead of the route id placeholder.
|
|
34
|
-
*
|
|
35
|
-
* Both halves of the native side are synchronous — `LlmRuntime.registerAdapter()`
|
|
36
|
-
* and its `replace()` run `prepareRoutes()` + `commitRoutes()` inside one call,
|
|
37
|
-
* and `PiAiAdapter.providerInfo()` answers from a plain field on the current
|
|
38
|
-
* snapshot — so the whole transaction can be synchronous. That is load bearing,
|
|
39
|
-
* not incidental:
|
|
40
|
-
*
|
|
41
|
-
* * the candidate snapshot is published, the native registration runs, and a
|
|
42
|
-
* refusal rolls the snapshot back **all inside one non-awaiting section**, so
|
|
43
|
-
* no second ensure, and no native observer, can ever look between the two
|
|
44
|
-
* sides and find the adapter serving a generation the core did not accept;
|
|
45
|
-
* * the caller's callback never yields. {@link commitCandidate} calls it and
|
|
46
|
-
* rejects its result if it is thenable. An `async` callback would open exactly
|
|
47
|
-
* that window: the native registration would run in a later microtask, after
|
|
48
|
-
* `register()` had already resolved to a mapping nobody registered.
|
|
49
|
-
*
|
|
50
|
-
* Adapter construction stays outside this module: this file only owns the
|
|
51
|
-
* native registration lifecycle. Every candidate set is validated before the
|
|
52
|
-
* core is touched, so a refused ensure leaves the live registration untouched.
|
|
53
|
-
*
|
|
54
|
-
* **One configuration per process, while a task pins it.** The adapter serves the
|
|
55
|
-
* *latest* generation the registry committed (`profiles: () => current.profiles`
|
|
56
|
-
* on every native model operation), and a later `register`/`ensure` with a
|
|
57
|
-
* different provider list swaps that generation in place. A running task keeps
|
|
58
|
-
* using its frozen route id, so without a lease its *next* native model
|
|
59
|
-
* operation would silently reach a different endpoint or model than the one its
|
|
60
|
-
* immutable effective configuration names. {@link createProviderRegistry}
|
|
61
|
-
* therefore keeps a process-local *lease* of the provider-definition set:
|
|
62
|
-
*
|
|
63
|
-
* - a lease is one canonical fingerprint of every *plugin-managed* definition
|
|
64
|
-
* that can affect a later model operation (provider id, display name, protocol,
|
|
65
|
-
* endpoint, credential *reference*, and each model's id, declared efforts and
|
|
66
|
-
* context window) — never a value, never a secret. Native DSH references are
|
|
67
|
-
* excluded on both sides ({@link managedProvidersOf}), because this plugin
|
|
68
|
-
* registers no route for them and the core's copy of such a route is not part
|
|
69
|
-
* of the generation the lease protects;
|
|
70
|
-
* - {@link registry.ensure} and {@link registry.register} take the lease for
|
|
71
|
-
* their own set, and refuse a *different* set while another lease is held, with
|
|
72
|
-
* the stable code `PROVIDER_SET_BUSY`, before the adapter is asked to publish
|
|
73
|
-
* anything and before the core is touched;
|
|
74
|
-
* - an identical set is always allowed: `leases` counts holders, so concurrent
|
|
75
|
-
* jobs on one configuration and concurrent ensures of one snapshot proceed;
|
|
76
|
-
* - the engine takes its lease synchronously *before* it awaits the route ensure
|
|
77
|
-
* and releases it only from its own finalize, after the native executor is
|
|
78
|
-
* confirmed stopped — so a settings change saved during a run is stored
|
|
79
|
-
* normally (the settings service is a different authority), and becomes usable
|
|
80
|
-
* as soon as the running tasks drain. There is no queue, no retry and no
|
|
81
|
-
* substitution: the refused candidate simply did not apply.
|
|
82
|
-
*/
|
|
83
|
-
|
|
84
|
-
/** Namespace prefix that keeps native route ids separate from public profile ids. */
|
|
85
|
-
const ROUTE_NAMESPACE = 'dsh-delegate';
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* The provider `source` that marks a profile DSH already routes itself.
|
|
89
|
-
*
|
|
90
|
-
* A native profile is a *reference* to a route the harness owns: this plugin must
|
|
91
|
-
* never register one (`src/index.js` only maps it onto the DSH route id of the
|
|
92
|
-
* same name), and it must not fingerprint one either — which is why the lease and
|
|
93
|
-
* the route registration share {@link managedProvidersOf} instead of each
|
|
94
|
-
* filtering `source` on its own.
|
|
95
|
-
*/
|
|
96
|
-
const NATIVE_PROVIDER_SOURCE = 'native';
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* The provider profiles this plugin owns a route for, i.e. everything that is not
|
|
100
|
-
* a native DSH reference.
|
|
101
|
-
*
|
|
102
|
-
* One function for both halves of the provider contract, on purpose. The engine
|
|
103
|
-
* takes its long-lived lease over the *plugin-managed* set and `ensureRoutes()`
|
|
104
|
-
* registers exactly that same set, so the lease fingerprint and the registered
|
|
105
|
-
* (adapter-visible) candidate are two readings of one list. Filtering them
|
|
106
|
-
* differently is what made a native-only configuration lease `[workbuddy]` while
|
|
107
|
-
* its own route ensure registered `[]`: same task, one holder, two fingerprints,
|
|
108
|
-
* and the second call refused its own lease with `PROVIDER_SET_BUSY` (0 routes)
|
|
109
|
-
* before any second task existed.
|
|
110
|
-
*
|
|
111
|
-
* Order is preserved: the adapter publishes the list in the order it is given, so
|
|
112
|
-
* a reordering must stay visible to the fingerprint. The entries are returned as
|
|
113
|
-
* they are — this is a projection, not a copy or a validation step.
|
|
114
|
-
* @param {unknown} providers - candidate provider list, typically `settings.providers`.
|
|
115
|
-
* @returns {object[]} the plugin-managed subset, in declared order.
|
|
116
|
-
*/
|
|
117
|
-
export function managedProvidersOf(providers) {
|
|
118
|
-
const list = Array.isArray(providers) ? providers : [];
|
|
119
|
-
return list.filter((provider) => provider?.source !== NATIVE_PROVIDER_SOURCE);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* The provider profiles DSH routes natively, i.e. the complement of
|
|
124
|
-
* {@link managedProvidersOf} over the same list.
|
|
125
|
-
*
|
|
126
|
-
* Offered so the entry point and any diagnostic count both halves with the same
|
|
127
|
-
* rule; nothing here registers these routes.
|
|
128
|
-
* @param {unknown} providers - candidate provider list.
|
|
129
|
-
* @returns {object[]} the native subset, in declared order.
|
|
130
|
-
*/
|
|
131
|
-
export function nativeProvidersOf(providers) {
|
|
132
|
-
const list = Array.isArray(providers) ? providers : [];
|
|
133
|
-
return list.filter((provider) => provider?.source === NATIVE_PROVIDER_SOURCE);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Error code surfaced to the engine's routing diagnostics. */
|
|
137
|
-
const ERROR_CODE = 'provider_registry';
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Stable code of a refusal caused by a lease another party holds.
|
|
141
|
-
*
|
|
142
|
-
* Distinct from {@link ERROR_CODE} on purpose: "another task is running on a
|
|
143
|
-
* different provider configuration" is an operator-visible state that resolves by
|
|
144
|
-
* itself, not a registry failure, and callers must be able to tell the two apart
|
|
145
|
-
* without matching a message.
|
|
146
|
-
*/
|
|
147
|
-
export const PROVIDER_SET_CODES = Object.freeze({ busy: 'PROVIDER_SET_BUSY' });
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Build one registry error.
|
|
151
|
-
* @param {string} message - operator-facing diagnostic.
|
|
152
|
-
* @returns {Error} error carrying this module's code.
|
|
153
|
-
*/
|
|
154
|
-
function registryError(message) {
|
|
155
|
-
const error = new Error(message);
|
|
156
|
-
error.code = ERROR_CODE;
|
|
157
|
-
return error;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Read the public provider id from one settings entry.
|
|
162
|
-
*
|
|
163
|
-
* A settings snapshot may carry either bare ids or provider records; both are
|
|
164
|
-
* accepted so the registry does not depend on the settings module's shape.
|
|
165
|
-
* @param {unknown} entry - one element of the provider list.
|
|
166
|
-
* @returns {string} public provider id.
|
|
167
|
-
*/
|
|
168
|
-
function publicProviderId(entry) {
|
|
169
|
-
const id = typeof entry === 'string' ? entry : entry?.id;
|
|
170
|
-
if (typeof id !== 'string' || id === '') {
|
|
171
|
-
throw registryError('every provider entry must be a non-empty id');
|
|
172
|
-
}
|
|
173
|
-
return id;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Default native route id for one public provider id.
|
|
178
|
-
* @param {string} publicId - validated public provider id.
|
|
179
|
-
* @returns {string} namespaced native route id, distinct from the public id.
|
|
180
|
-
*/
|
|
181
|
-
function defaultRouteId(publicId) {
|
|
182
|
-
return `${ROUTE_NAMESPACE}:${publicId}`;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/**
|
|
186
|
-
* The object that may be handed to `LlmRuntime.registerAdapter()`.
|
|
187
|
-
*
|
|
188
|
-
* A plugin that builds its adapter behind a management facade has two objects
|
|
189
|
-
* per adapter: the facade (`replace`, `snapshot`, …) and the native instance it
|
|
190
|
-
* serves. Only the second one is registrable — the core asks it for
|
|
191
|
-
* `providerInfo`/`providerRetryPolicy` and later for `prepareCall`/`stream`.
|
|
192
|
-
* Accepting either shape here, while refusing an object with no call path,
|
|
193
|
-
* turns that mix-up from a runtime "no adapter registered" on every request
|
|
194
|
-
* into an error at the moment the registry is built.
|
|
195
|
-
* @param {unknown} adapter - native adapter, or a facade exposing `nativeAdapter()`/`getAdapter()`.
|
|
196
|
-
* @returns {object} the native adapter instance.
|
|
197
|
-
*/
|
|
198
|
-
export function nativeAdapterOf(adapter) {
|
|
199
|
-
if (adapter !== null && typeof adapter === 'object' && typeof adapter.stream === 'function') {
|
|
200
|
-
return adapter;
|
|
201
|
-
}
|
|
202
|
-
const unwrap = adapter !== null && typeof adapter === 'object'
|
|
203
|
-
? (typeof adapter.nativeAdapter === 'function' ? adapter.nativeAdapter : adapter.getAdapter)
|
|
204
|
-
: undefined;
|
|
205
|
-
if (typeof unwrap !== 'function') {
|
|
206
|
-
throw registryError('a native provider adapter is required');
|
|
207
|
-
}
|
|
208
|
-
// Called on the facade as receiver so an unwrapper implemented as a method
|
|
209
|
-
// that reads `this` still works; the facade's own getters are plain closures.
|
|
210
|
-
const native = unwrap.call(adapter);
|
|
211
|
-
if (native === null || typeof native !== 'object' || typeof native.stream !== 'function') {
|
|
212
|
-
throw registryError('the adapter facade does not expose a native adapter that can stream');
|
|
213
|
-
}
|
|
214
|
-
if (typeof native.providerInfo !== 'function') {
|
|
215
|
-
throw registryError('the native adapter cannot describe its provider routes');
|
|
216
|
-
}
|
|
217
|
-
return native;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* Canonical JSON: object keys sorted, `undefined` members dropped.
|
|
222
|
-
*
|
|
223
|
-
* The fingerprint below must be *deterministic* across two readings of one
|
|
224
|
-
* configuration, so it cannot depend on key insertion order, and it must not
|
|
225
|
-
* change because a field is absent rather than empty. Arrays keep their order:
|
|
226
|
-
* a reordered model list is a different served generation, and the adapter
|
|
227
|
-
* publishes it as one.
|
|
228
|
-
* @param {unknown} value - JSON-compatible value.
|
|
229
|
-
* @returns {string} canonical JSON text.
|
|
230
|
-
*/
|
|
231
|
-
function canonicalJson(value) {
|
|
232
|
-
if (value === undefined) return 'null';
|
|
233
|
-
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
|
|
234
|
-
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
|
235
|
-
const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
|
|
236
|
-
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Read one scalar as a string, or `null` when it is absent.
|
|
241
|
-
* @param {unknown} value - candidate.
|
|
242
|
-
* @returns {string | null} the value or null.
|
|
243
|
-
*/
|
|
244
|
-
function scalarOrNull(value) {
|
|
245
|
-
if (typeof value === 'string') return value;
|
|
246
|
-
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
247
|
-
return null;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* The canonical form of one provider definition, as far as a later model call
|
|
252
|
-
* can observe it.
|
|
253
|
-
*
|
|
254
|
-
* Everything the adapter copies into the served generation is here: the route
|
|
255
|
-
* (derived from the id), the endpoint, the credential *reference* (a name, never
|
|
256
|
-
* a value), the protocol, and per model the id, the display name, the declared
|
|
257
|
-
* effort axis and the context window — which is what a request's budget and
|
|
258
|
-
* effort selectability are computed from. It is deliberately *not* a hash: a
|
|
259
|
-
* collision has to be impossible, and the assembled text is retained in memory
|
|
260
|
-
* only, never written, logged or returned.
|
|
261
|
-
*
|
|
262
|
-
* A provider that is not a record is fingerprinted by its id alone, so a caller
|
|
263
|
-
* that passes bare ids still gets a lease.
|
|
264
|
-
* @param {unknown} entry - one provider of a settings snapshot.
|
|
265
|
-
* @param {(publicId: string) => string} deriveRouteId - native route id derivation.
|
|
266
|
-
* @returns {object} canonical definition.
|
|
267
|
-
*/
|
|
268
|
-
function providerDefinition(entry, deriveRouteId) {
|
|
269
|
-
const publicId = publicProviderId(entry);
|
|
270
|
-
const route = deriveRouteId(publicId);
|
|
271
|
-
if (entry === null || typeof entry !== 'object') {
|
|
272
|
-
return { id: publicId, route };
|
|
273
|
-
}
|
|
274
|
-
const models = Array.isArray(entry.models) ? entry.models : [];
|
|
275
|
-
return {
|
|
276
|
-
id: publicId,
|
|
277
|
-
route,
|
|
278
|
-
name: scalarOrNull(entry.name),
|
|
279
|
-
protocol: scalarOrNull(entry.protocol),
|
|
280
|
-
baseUrl: scalarOrNull(entry.baseUrl),
|
|
281
|
-
credentialRef: scalarOrNull(entry.credentialRef),
|
|
282
|
-
models: models.map((model) => ({
|
|
283
|
-
id: scalarOrNull(model?.id),
|
|
284
|
-
name: scalarOrNull(model?.name),
|
|
285
|
-
efforts: Array.isArray(model?.efforts) ? model.efforts.map((effort) => scalarOrNull(effort)) : null,
|
|
286
|
-
contextWindow: typeof model?.contextWindow === 'number' && Number.isFinite(model.contextWindow)
|
|
287
|
-
? model.contextWindow
|
|
288
|
-
: null,
|
|
289
|
-
})),
|
|
290
|
-
};
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Canonical fingerprint of a whole provider-definition set.
|
|
295
|
-
*
|
|
296
|
-
* Two readings of one configuration produce the same text, and any change a later
|
|
297
|
-
* model operation could observe produces a different one. The set is sorted by
|
|
298
|
-
* public provider id for the digest, while the *lease* itself keeps the declared
|
|
299
|
-
* order, because order is what the adapter publishes.
|
|
300
|
-
* @param {object[]} definitions - from {@link providerDefinition}, in declared order.
|
|
301
|
-
* @returns {string} fingerprint.
|
|
302
|
-
*/
|
|
303
|
-
function fingerprintOf(definitions) {
|
|
304
|
-
const sorted = [...definitions].sort((a, b) => (a.id < b.id ? -1 : (a.id > b.id ? 1 : 0)));
|
|
305
|
-
return canonicalJson(sorted);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
* Create the native route registry for one adapter instance.
|
|
310
|
-
* @param {object} options - registry dependencies.
|
|
311
|
-
* @param {object} options.llm - native llm runtime exposing `registerAdapter`.
|
|
312
|
-
* @param {object} options.adapter - already-constructed native adapter, or the
|
|
313
|
-
* management facade that wraps one ({@link nativeAdapterOf} unwraps it).
|
|
314
|
-
* @param {(publicId: string) => string} [options.routeIdFor] - native route id derivation.
|
|
315
|
-
* @returns {{
|
|
316
|
-
* ensure: (providers: unknown) => Promise<{ routes: Map<string, string> }>,
|
|
317
|
-
* register: (providers: unknown, commit: (routes: Map<string, string>) => unknown) => Promise<{ routes: Map<string, string> }>,
|
|
318
|
-
* lease: (providers: unknown, holder?: string) => object,
|
|
319
|
-
* release: (lease: object) => boolean,
|
|
320
|
-
* heldLease: () => { count: number, holders: string[], fingerprint: string } | null,
|
|
321
|
-
* commitRoutes: (routes: Map<string, string>) => void,
|
|
322
|
-
* nativeAdapter: () => object,
|
|
323
|
-
* dispose: () => void,
|
|
324
|
-
* }} registry.
|
|
325
|
-
*/
|
|
326
|
-
export function createProviderRegistry(options) {
|
|
327
|
-
const { llm, routeIdFor } = options ?? {};
|
|
328
|
-
if (llm === null || typeof llm !== 'object' || typeof llm.registerAdapter !== 'function') {
|
|
329
|
-
throw registryError('the native llm runtime cannot register provider adapters');
|
|
330
|
-
}
|
|
331
|
-
const adapter = nativeAdapterOf(options?.adapter);
|
|
332
|
-
if (routeIdFor !== undefined && typeof routeIdFor !== 'function') {
|
|
333
|
-
throw registryError('routeIdFor must be a function');
|
|
334
|
-
}
|
|
335
|
-
const deriveRouteId = routeIdFor ?? defaultRouteId;
|
|
336
|
-
let handle = null;
|
|
337
|
-
let disposed = false;
|
|
338
|
-
/**
|
|
339
|
-
* The process-local provider-definition lease, or `null` when no set is pinned.
|
|
340
|
-
*
|
|
341
|
-
* One fingerprint, a holder count and the holder labels. Counting (rather than
|
|
342
|
-
* storing one owner) is what lets several tasks share one configuration while a
|
|
343
|
-
* *different* one is refused; see the module comment.
|
|
344
|
-
* @type {{ fingerprint: string, count: number, holders: string[] } | null}
|
|
345
|
-
*/
|
|
346
|
-
let held = null;
|
|
347
|
-
/**
|
|
348
|
-
* Holders of the lease this registry handed out, so every release is exact and
|
|
349
|
-
* a second release of one lease is a no-op rather than somebody else's.
|
|
350
|
-
* @type {WeakSet<object>}
|
|
351
|
-
*/
|
|
352
|
-
const issued = new WeakSet();
|
|
353
|
-
/**
|
|
354
|
-
* Native routes owned by *other* registrations, captured before this registry
|
|
355
|
-
* registered anything.
|
|
356
|
-
*
|
|
357
|
-
* `LlmRuntime.listProviders()` lists every route in the runtime, not this
|
|
358
|
-
* adapter's. Ownership therefore has to be read relative to this baseline: a
|
|
359
|
-
* route present here belongs to somebody else (refuse it), and a route absent
|
|
360
|
-
* here that this registration has not adopted belongs to nobody (the core will
|
|
361
|
-
* refuse it — the adapter must not publish it first).
|
|
362
|
-
* @type {Set<string> | null}
|
|
363
|
-
*/
|
|
364
|
-
let foreignRoutes = null;
|
|
365
|
-
|
|
366
|
-
/**
|
|
367
|
-
* Freeze the foreign-route baseline, once, before this registry registers.
|
|
368
|
-
* @returns {Error | null} a refusal when the runtime cannot report its routes.
|
|
369
|
-
*/
|
|
370
|
-
function captureForeignRoutes() {
|
|
371
|
-
if (foreignRoutes !== null) return null;
|
|
372
|
-
try {
|
|
373
|
-
foreignRoutes = new Set(llm.listProviders().map((entry) => entry.id));
|
|
374
|
-
} catch {
|
|
375
|
-
// Silence is unsafe here: without a second opinion this module cannot prove
|
|
376
|
-
// the candidate does not claim a route another owner registered.
|
|
377
|
-
return registryError('the native llm runtime cannot list its registered provider routes');
|
|
378
|
-
}
|
|
379
|
-
return null;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* Why one candidate may not be committed to the native core.
|
|
384
|
-
*
|
|
385
|
-
* On a first registration this is the `DUPLICATE_ADAPTER` the core would raise;
|
|
386
|
-
* on a replace it is the `DUPLICATE_ADAPTER` or `INVALID_ADAPTER` the core would
|
|
387
|
-
* raise. Either way the point is the same: refuse *before* the adapter publishes
|
|
388
|
-
* a route set the core is going to reject.
|
|
389
|
-
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
390
|
-
* @returns {Error | null} the refusal, or `null` when the candidate is legal.
|
|
391
|
-
*/
|
|
392
|
-
function ownershipRefusal(routes) {
|
|
393
|
-
const refusal = captureForeignRoutes();
|
|
394
|
-
if (refusal !== null) return refusal;
|
|
395
|
-
for (const [publicId, nativeId] of routes) {
|
|
396
|
-
// A route another registration owns makes `registerAdapter()`/`replace()`
|
|
397
|
-
// throw `DUPLICATE_ADAPTER` — after the caller had already published a
|
|
398
|
-
// snapshot serving it. One this registration has not adopted and nobody owns
|
|
399
|
-
// is not registered at all, so `replace()` would throw `INVALID_ADAPTER` with
|
|
400
|
-
// the adapter already republished. Both are refused here, before the adapter
|
|
401
|
-
// sees the candidate.
|
|
402
|
-
if (foreignRoutes.has(nativeId)) {
|
|
403
|
-
return registryError(`provider ${publicId} maps to native route ${nativeId}, which another adapter registration already owns`);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
return null;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* Validate one candidate provider list and derive its route mapping.
|
|
411
|
-
* Pure: nothing is registered here, so a refusal cannot mutate the core.
|
|
412
|
-
* @param {unknown} providers - candidate provider list.
|
|
413
|
-
* @returns {Map<string, string>} public id -> native route id, in input order.
|
|
414
|
-
*/
|
|
415
|
-
function plan(providers) {
|
|
416
|
-
if (!Array.isArray(providers)) throw registryError('the provider list must be an array');
|
|
417
|
-
const routes = new Map();
|
|
418
|
-
const nativeIds = new Set();
|
|
419
|
-
for (const entry of providers) {
|
|
420
|
-
const publicId = publicProviderId(entry);
|
|
421
|
-
if (routes.has(publicId)) {
|
|
422
|
-
throw registryError(`provider ${publicId} is listed more than once`);
|
|
423
|
-
}
|
|
424
|
-
const nativeId = deriveRouteId(publicId);
|
|
425
|
-
if (typeof nativeId !== 'string' || nativeId === '') {
|
|
426
|
-
throw registryError(`provider ${publicId} has no usable native route id`);
|
|
427
|
-
}
|
|
428
|
-
if (nativeIds.has(nativeId)) {
|
|
429
|
-
throw registryError(`provider ${publicId} collides on native route id ${nativeId}`);
|
|
430
|
-
}
|
|
431
|
-
nativeIds.add(nativeId);
|
|
432
|
-
routes.set(publicId, nativeId);
|
|
433
|
-
}
|
|
434
|
-
return routes;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
/**
|
|
438
|
-
* Commit one validated route set to the native core.
|
|
439
|
-
*
|
|
440
|
-
* The first call registers; later calls replace the whole set. The registration
|
|
441
|
-
* handle is only kept once the core returned one, so a thrown registration
|
|
442
|
-
* leaves this module in the state it was in before the attempt. Synchronous:
|
|
443
|
-
* the core validates and commits inside the call.
|
|
444
|
-
* @param {Map<string, string>} routes - validated public -> native mapping.
|
|
445
|
-
* @returns {void}
|
|
446
|
-
*/
|
|
447
|
-
function commitRoutes(routes) {
|
|
448
|
-
const nativeIds = [...routes.values()];
|
|
449
|
-
if (handle === null) {
|
|
450
|
-
// The baseline is taken before this registration exists, so it holds only
|
|
451
|
-
// other owners' routes. If the caller already refused a candidate, this is a
|
|
452
|
-
// no-op; if it did not run, this is the first and only chance to take it.
|
|
453
|
-
const refusal = captureForeignRoutes();
|
|
454
|
-
if (refusal !== null) throw refusal;
|
|
455
|
-
/**
|
|
456
|
-
* The native handle is the disposer plus `replace()`; a runtime that
|
|
457
|
-
* returns anything else cannot be kept consistent by this module.
|
|
458
|
-
*/
|
|
459
|
-
const registered = llm.registerAdapter(nativeIds, adapter);
|
|
460
|
-
if (typeof registered !== 'function') {
|
|
461
|
-
throw registryError('the native llm runtime returned no adapter disposer');
|
|
462
|
-
}
|
|
463
|
-
handle = registered;
|
|
464
|
-
return;
|
|
465
|
-
}
|
|
466
|
-
// Atomic in the core: a rejected candidate throws and keeps the live routes.
|
|
467
|
-
handle.replace(nativeIds);
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
/**
|
|
471
|
-
* Decide what one candidate needs: a native commit, or nothing at all.
|
|
472
|
-
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
473
|
-
* @returns {boolean} whether the native core has to be touched.
|
|
474
|
-
*/
|
|
475
|
-
function changesNativeState(routes) {
|
|
476
|
-
// An empty first list establishes nothing; the core refuses an empty initial
|
|
477
|
-
// registration, and a later non-empty list registers lazily.
|
|
478
|
-
return handle !== null || routes.size > 0;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
/**
|
|
482
|
-
* Validate one candidate provider list into its canonical definition set.
|
|
483
|
-
* @param {unknown} providers - candidate provider list.
|
|
484
|
-
* @returns {{ routes: Map<string, string>, fingerprint: string }} plan plus its fingerprint.
|
|
485
|
-
*/
|
|
486
|
-
function describe(providers) {
|
|
487
|
-
const routes = plan(providers);
|
|
488
|
-
const fingerprint = fingerprintOf([...providers].map((entry) => providerDefinition(entry, deriveRouteId)));
|
|
489
|
-
return { routes, fingerprint };
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
/**
|
|
493
|
-
* The refusal a different provider set would receive right now, or `null`.
|
|
494
|
-
*
|
|
495
|
-
* This is the whole admission rule: an equal set always shares the lease, and a
|
|
496
|
-
* different one is refused while anybody holds it. It deliberately names no
|
|
497
|
-
* endpoint and no credential reference — only that a configuration is pinned and
|
|
498
|
-
* by whom — because it is reported to a caller who may not be the holder.
|
|
499
|
-
* @param {string} fingerprint - candidate set.
|
|
500
|
-
* @param {number} routeCount - size of the candidate mapping, for the message.
|
|
501
|
-
* @returns {Error | null} refusal carrying {@link PROVIDER_SET_CODES.busy}.
|
|
502
|
-
*/
|
|
503
|
-
function leaseRefusal(fingerprint, routeCount) {
|
|
504
|
-
if (held === null || held.fingerprint === fingerprint) return null;
|
|
505
|
-
const error = registryError(
|
|
506
|
-
`another task is running on a different provider configuration (${held.count} lease holder(s)); `
|
|
507
|
-
+ `this ${routeCount} provider set may not be applied until it finishes`,
|
|
508
|
-
);
|
|
509
|
-
error.code = PROVIDER_SET_CODES.busy;
|
|
510
|
-
error.details = {
|
|
511
|
-
code: PROVIDER_SET_CODES.busy,
|
|
512
|
-
heldBy: held.count,
|
|
513
|
-
// Labels are generated by this module or by the caller and never contain a
|
|
514
|
-
// provider id, an endpoint or a credential reference.
|
|
515
|
-
holders: held.holders.slice(0, 8),
|
|
516
|
-
};
|
|
517
|
-
return error;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
/**
|
|
521
|
-
* Take the provider-definition lease for one already-described set.
|
|
522
|
-
*
|
|
523
|
-
* Synchronous on purpose: the engine calls this in the same step that freezes
|
|
524
|
-
* its task's route set, before it awaits anything, so there is no window in
|
|
525
|
-
* which the set it is about to use could have been swapped by somebody else.
|
|
526
|
-
* @param {string} fingerprint - candidate set.
|
|
527
|
-
* @param {number} routeCount - size of the candidate mapping.
|
|
528
|
-
* @param {string} holder - bounded label for diagnostics.
|
|
529
|
-
* @returns {void}
|
|
530
|
-
* @throws {Error} the busy refusal when another set is pinned.
|
|
531
|
-
*/
|
|
532
|
-
function acquire(fingerprint, routeCount, holder) {
|
|
533
|
-
const refusal = leaseRefusal(fingerprint, routeCount);
|
|
534
|
-
if (refusal !== null) throw refusal;
|
|
535
|
-
if (held === null) held = { fingerprint, count: 0, holders: [] };
|
|
536
|
-
held.count += 1;
|
|
537
|
-
if (holder !== '') held.holders.push(holder);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
/**
|
|
541
|
-
* Give one holder's lease back.
|
|
542
|
-
*
|
|
543
|
-
* `register`/`ensure` take their lease for the duration of their own call and
|
|
544
|
-
* hand it back the same way; a lease object taken through `lease()` is released
|
|
545
|
-
* once and never again, so it cannot drain another holder's share. A release that
|
|
546
|
-
* leaves nobody holding frees the set, i.e. a different configuration may apply
|
|
547
|
-
* from the next call on.
|
|
548
|
-
* @param {string} fingerprint - the set being released.
|
|
549
|
-
* @param {string} holder - the label to remove.
|
|
550
|
-
* @returns {void}
|
|
551
|
-
*/
|
|
552
|
-
function giveBack(fingerprint, holder) {
|
|
553
|
-
if (held === null || held.fingerprint !== fingerprint) return;
|
|
554
|
-
held.count -= 1;
|
|
555
|
-
const index = held.holders.lastIndexOf(holder);
|
|
556
|
-
if (index >= 0) held.holders.splice(index, 1);
|
|
557
|
-
if (held.count <= 0) held = null;
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
/**
|
|
561
|
-
* Take the lease for one provider set and hand back a releasable lease object.
|
|
562
|
-
*
|
|
563
|
-
* The object is the only thing a caller may release; releasing it twice is a
|
|
564
|
-
* no-op, and releasing a lease the registry never issued is refused, so one
|
|
565
|
-
* task cannot drain another's hold.
|
|
566
|
-
* @param {unknown} providers - provider list from one settings snapshot.
|
|
567
|
-
* @param {string} [holder] - bounded diagnostic label (a task id, an operation).
|
|
568
|
-
* @returns {{ kind: string, fingerprint: string, holder: string, released: boolean }} lease.
|
|
569
|
-
*/
|
|
570
|
-
function lease(providers, holder) {
|
|
571
|
-
if (disposed) throw registryError('the provider registry has been disposed');
|
|
572
|
-
const described = describe(providers);
|
|
573
|
-
const label = typeof holder === 'string' && holder !== '' ? holder.slice(0, 120) : '';
|
|
574
|
-
acquire(described.fingerprint, described.routes.size, label);
|
|
575
|
-
const record = { kind: 'provider-definition-lease', fingerprint: described.fingerprint, holder: label, released: false };
|
|
576
|
-
issued.add(record);
|
|
577
|
-
return record;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Release one lease handed out by {@link lease}.
|
|
582
|
-
* @param {unknown} record - lease object.
|
|
583
|
-
* @returns {boolean} true when this call released it.
|
|
584
|
-
*/
|
|
585
|
-
function release(record) {
|
|
586
|
-
if (record === null || typeof record !== 'object' || !issued.has(record)) return false;
|
|
587
|
-
if (record.released === true) return false;
|
|
588
|
-
record.released = true;
|
|
589
|
-
giveBack(record.fingerprint, record.holder);
|
|
590
|
-
return true;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
/**
|
|
594
|
-
* Describe the lease currently held, for diagnostics and tests.
|
|
595
|
-
* @returns {{ count: number, holders: string[], fingerprint: string } | null} copy, or null when free.
|
|
596
|
-
*/
|
|
597
|
-
function heldLease() {
|
|
598
|
-
if (held === null) return null;
|
|
599
|
-
return { count: held.count, holders: [...held.holders], fingerprint: held.fingerprint };
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
/**
|
|
603
|
-
* Ensure the native routes for one provider list.
|
|
604
|
-
*
|
|
605
|
-
* The lease is taken for the duration of this call, which is synchronous apart
|
|
606
|
-
* from its own `async` wrapper, so an ensure of a different set cannot interleave
|
|
607
|
-
* with one already in progress.
|
|
608
|
-
* @param {unknown} providers - provider list from one settings snapshot.
|
|
609
|
-
* @returns {Promise<{ routes: Map<string, string> }>} fresh public -> native mapping.
|
|
610
|
-
*/
|
|
611
|
-
async function ensure(providers) {
|
|
612
|
-
if (disposed) throw registryError('the provider registry has been disposed');
|
|
613
|
-
const { routes, fingerprint } = describe(providers);
|
|
614
|
-
acquire(fingerprint, routes.size, 'ensure');
|
|
615
|
-
try {
|
|
616
|
-
if (changesNativeState(routes)) commitRoutes(routes);
|
|
617
|
-
} finally {
|
|
618
|
-
giveBack(fingerprint, 'ensure');
|
|
619
|
-
}
|
|
620
|
-
return { routes: new Map(routes) };
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
/**
|
|
624
|
-
* Ensure the native routes for one provider list, letting the caller act
|
|
625
|
-
* between validation and registration.
|
|
626
|
-
*
|
|
627
|
-
* The callback exists because the adapter's serving state has to be in place
|
|
628
|
-
* *before* the core validates the routes: `prepareRoutes()` reads
|
|
629
|
-
* `providerInfo(id)` synchronously and refuses (or mislabels) a route the
|
|
630
|
-
* adapter is not already serving. A caller that must publish a snapshot first
|
|
631
|
-
* uses this. The callback runs after the candidate set is fully validated, its
|
|
632
|
-
* native commit runs from inside it, and nothing in between yields, so an
|
|
633
|
-
* exception from the callback — or from the registration — leaves the native
|
|
634
|
-
* registration exactly as it was, and the callback's own restoration is the last
|
|
635
|
-
* word on the snapshot.
|
|
636
|
-
*
|
|
637
|
-
* The callback receives the routes and performs the *publication* only: it
|
|
638
|
-
* calls the second argument, `commit()`, at the point where the native
|
|
639
|
-
* registration must happen. Anything after that call runs with the candidate
|
|
640
|
-
* already committed, so a callback that yields after it is the one thing this
|
|
641
|
-
* contract cannot take back — which is why the return value is checked and why
|
|
642
|
-
* the handed `commit()` refuses to fire once the callback has yielded.
|
|
643
|
-
*
|
|
644
|
-
* The provider-definition lease is checked here too, *before* the callback runs,
|
|
645
|
-
* so a task pinned to another configuration cannot have this one published
|
|
646
|
-
* underneath it — and the adapter is never asked for a snapshot that the core
|
|
647
|
-
* will then refuse.
|
|
648
|
-
* @param {unknown} providers - provider list from one settings snapshot.
|
|
649
|
-
* @param {(routes: Map<string, string>, commit: () => void) => unknown} commit - runs after validation; must not yield.
|
|
650
|
-
* @returns {Promise<{ routes: Map<string, string> }>} fresh public -> native mapping.
|
|
651
|
-
*/
|
|
652
|
-
async function register(providers, commit) {
|
|
653
|
-
if (typeof commit !== 'function') throw registryError('a registration callback is required');
|
|
654
|
-
if (disposed) throw registryError('the provider registry has been disposed');
|
|
655
|
-
const { routes, fingerprint } = describe(providers);
|
|
656
|
-
acquire(fingerprint, routes.size, 'register');
|
|
657
|
-
try {
|
|
658
|
-
if (changesNativeState(routes)) commitCandidate(routes, commit);
|
|
659
|
-
else commit(new Map(), () => {});
|
|
660
|
-
} finally {
|
|
661
|
-
giveBack(fingerprint, 'register');
|
|
662
|
-
}
|
|
663
|
-
return { routes: new Map(routes) };
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
/**
|
|
667
|
-
* The transaction: publication, native commit, and nothing awaited.
|
|
668
|
-
*
|
|
669
|
-
* The callback is handed a `commit()` it must call itself, so the native
|
|
670
|
-
* registration runs from inside the callback's own synchronous stack — never
|
|
671
|
-
* before publication, never after a yield. `commit()` and the callback share
|
|
672
|
-
* one guard: once the callback has yielded it cannot commit, and once it has
|
|
673
|
-
* committed the native state is real, so it cannot pull the snapshot out from
|
|
674
|
-
* under a committed registration either.
|
|
675
|
-
*
|
|
676
|
-
* `adapt` is the only party that can restore the snapshot the candidate
|
|
677
|
-
* displaced, so this function never restores anything on its own. Its contract:
|
|
678
|
-
*
|
|
679
|
-
* 1. the candidate set is refused *before* `adapt` runs if it claims a route
|
|
680
|
-
* another registration owns, so the adapter never publishes a route the
|
|
681
|
-
* core would reject;
|
|
682
|
-
* 2. `adapt()` must not return a thenable — a promise means the callback
|
|
683
|
-
* yielded, and the native registration would then land in a microtask this
|
|
684
|
-
* function has already answered past;
|
|
685
|
-
* 3. whatever `adapt()` throws propagates unchanged, after it has restored the
|
|
686
|
-
* snapshot state it was given.
|
|
687
|
-
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
688
|
-
* @param {(routes: Map<string, string>, commit: () => void) => unknown} adapt - publish, then commit, synchronously.
|
|
689
|
-
* @returns {void}
|
|
690
|
-
* @throws {Error} the ownership refusal, the contract violation, or the native refusal.
|
|
691
|
-
*/
|
|
692
|
-
function commitCandidate(routes, adapt) {
|
|
693
|
-
const refusal = ownershipRefusal(routes);
|
|
694
|
-
if (refusal !== null) throw refusal;
|
|
695
|
-
let open = true;
|
|
696
|
-
let committed = false;
|
|
697
|
-
/**
|
|
698
|
-
* Perform the native commit for this candidate, exactly once.
|
|
699
|
-
* @returns {void}
|
|
700
|
-
* @throws {Error} when called after a yield or a throw.
|
|
701
|
-
*/
|
|
702
|
-
const commit = () => {
|
|
703
|
-
if (!open) {
|
|
704
|
-
throw registryError('the registration callback committed outside its own synchronous section');
|
|
705
|
-
}
|
|
706
|
-
if (committed) throw registryError('the registration callback committed the same candidate twice');
|
|
707
|
-
commitRoutes(routes);
|
|
708
|
-
committed = true;
|
|
709
|
-
};
|
|
710
|
-
let outcome;
|
|
711
|
-
try {
|
|
712
|
-
outcome = adapt(new Map(routes), commit);
|
|
713
|
-
} finally {
|
|
714
|
-
// Closed as soon as the callback's synchronous stack unwinds, whichever way
|
|
715
|
-
// it left: a queued continuation can no longer mutate the native registry.
|
|
716
|
-
open = false;
|
|
717
|
-
}
|
|
718
|
-
if (outcome !== null && (typeof outcome === 'object' || typeof outcome === 'function')
|
|
719
|
-
&& typeof outcome.then === 'function') {
|
|
720
|
-
// Swallow the loser's rejection: the refusal below is the error that reaches
|
|
721
|
-
// the caller, and an unhandled rejection must not surface from a candidate
|
|
722
|
-
// this module already refused.
|
|
723
|
-
Promise.resolve(outcome).catch(() => {});
|
|
724
|
-
throw registryError('the registration callback must not be asynchronous');
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
/**
|
|
729
|
-
* Release the native registration. Idempotent; later ensures are refused.
|
|
730
|
-
*
|
|
731
|
-
* The lease goes with it: a disposed registry can never apply another
|
|
732
|
-
* configuration, so keeping a set pinned would refuse work for no reason. A
|
|
733
|
-
* task that still holds a lease record releases it into a free registry, which
|
|
734
|
-
* is a no-op, so a late finalize after unload cannot resurrect a hold.
|
|
735
|
-
* @returns {void}
|
|
736
|
-
*/
|
|
737
|
-
function dispose() {
|
|
738
|
-
if (disposed) return;
|
|
739
|
-
disposed = true;
|
|
740
|
-
held = null;
|
|
741
|
-
const registered = handle;
|
|
742
|
-
handle = null;
|
|
743
|
-
if (registered !== null) registered();
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
return {
|
|
747
|
-
ensure,
|
|
748
|
-
register,
|
|
749
|
-
lease,
|
|
750
|
-
release,
|
|
751
|
-
heldLease,
|
|
752
|
-
commitRoutes,
|
|
753
|
-
nativeAdapter: () => adapter,
|
|
754
|
-
dispose,
|
|
755
|
-
};
|
|
756
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Native provider route registration.
|
|
3
|
+
*
|
|
4
|
+
* Maps the operator-facing provider profile ids from one settings snapshot to
|
|
5
|
+
* namespaced native route ids owned by a single adapter registration on the
|
|
6
|
+
* installed `@deepseek-ai/dsh-llm` runtime.
|
|
7
|
+
*
|
|
8
|
+
* Contract used by `JobEngine.ensureRoutes()` (`src/jobs/engine.js`):
|
|
9
|
+
* `await registry.ensure(providers)` resolves to `{ routes: Map<publicId, nativeRouteId> }`.
|
|
10
|
+
* The returned Map is a fresh snapshot per call, so a job that keeps one cannot
|
|
11
|
+
* observe or corrupt a later ensure.
|
|
12
|
+
*
|
|
13
|
+
* Lifecycle, per the real `LlmRuntime.registerAdapter(providers, adapter)` API:
|
|
14
|
+
* - the first non-empty provider list registers the adapter once;
|
|
15
|
+
* - later ensures swap the whole route set through the disposer's
|
|
16
|
+
* `replace(providers)` (atomic in the core, and legal with an empty list);
|
|
17
|
+
* - `dispose()` releases the registration and is idempotent.
|
|
18
|
+
*
|
|
19
|
+
* Two constraints of that API are load-bearing here and are enforced rather than
|
|
20
|
+
* assumed:
|
|
21
|
+
*
|
|
22
|
+
* 1. The registered object must be the adapter itself. `registerAdapter(ids,
|
|
23
|
+
* facade)` would store a management object whose `providerInfo` may exist
|
|
24
|
+
* but whose `stream`/`prepareCall` never do, so every call on those routes
|
|
25
|
+
* would fail with "no adapter registered" even though registration
|
|
26
|
+
* "succeeded". {@link nativeAdapterOf} unwraps a facade when one is passed,
|
|
27
|
+
* and refuses anything that has no call path at all.
|
|
28
|
+
* 2. `prepareRoutes()` reads `adapter.providerInfo(id)` synchronously before it
|
|
29
|
+
* commits, so whatever snapshot the adapter serves at registration time is
|
|
30
|
+
* the one that names those routes. {@link createProviderRegistry} therefore
|
|
31
|
+
* exposes `register()` as a callback: the caller publishes the candidate
|
|
32
|
+
* snapshot, then registers, and only that order lets `prepareRoutes` see the
|
|
33
|
+
* configured display names instead of the route id placeholder.
|
|
34
|
+
*
|
|
35
|
+
* Both halves of the native side are synchronous — `LlmRuntime.registerAdapter()`
|
|
36
|
+
* and its `replace()` run `prepareRoutes()` + `commitRoutes()` inside one call,
|
|
37
|
+
* and `PiAiAdapter.providerInfo()` answers from a plain field on the current
|
|
38
|
+
* snapshot — so the whole transaction can be synchronous. That is load bearing,
|
|
39
|
+
* not incidental:
|
|
40
|
+
*
|
|
41
|
+
* * the candidate snapshot is published, the native registration runs, and a
|
|
42
|
+
* refusal rolls the snapshot back **all inside one non-awaiting section**, so
|
|
43
|
+
* no second ensure, and no native observer, can ever look between the two
|
|
44
|
+
* sides and find the adapter serving a generation the core did not accept;
|
|
45
|
+
* * the caller's callback never yields. {@link commitCandidate} calls it and
|
|
46
|
+
* rejects its result if it is thenable. An `async` callback would open exactly
|
|
47
|
+
* that window: the native registration would run in a later microtask, after
|
|
48
|
+
* `register()` had already resolved to a mapping nobody registered.
|
|
49
|
+
*
|
|
50
|
+
* Adapter construction stays outside this module: this file only owns the
|
|
51
|
+
* native registration lifecycle. Every candidate set is validated before the
|
|
52
|
+
* core is touched, so a refused ensure leaves the live registration untouched.
|
|
53
|
+
*
|
|
54
|
+
* **One configuration per process, while a task pins it.** The adapter serves the
|
|
55
|
+
* *latest* generation the registry committed (`profiles: () => current.profiles`
|
|
56
|
+
* on every native model operation), and a later `register`/`ensure` with a
|
|
57
|
+
* different provider list swaps that generation in place. A running task keeps
|
|
58
|
+
* using its frozen route id, so without a lease its *next* native model
|
|
59
|
+
* operation would silently reach a different endpoint or model than the one its
|
|
60
|
+
* immutable effective configuration names. {@link createProviderRegistry}
|
|
61
|
+
* therefore keeps a process-local *lease* of the provider-definition set:
|
|
62
|
+
*
|
|
63
|
+
* - a lease is one canonical fingerprint of every *plugin-managed* definition
|
|
64
|
+
* that can affect a later model operation (provider id, display name, protocol,
|
|
65
|
+
* endpoint, credential *reference*, and each model's id, declared efforts and
|
|
66
|
+
* context window) — never a value, never a secret. Native DSH references are
|
|
67
|
+
* excluded on both sides ({@link managedProvidersOf}), because this plugin
|
|
68
|
+
* registers no route for them and the core's copy of such a route is not part
|
|
69
|
+
* of the generation the lease protects;
|
|
70
|
+
* - {@link registry.ensure} and {@link registry.register} take the lease for
|
|
71
|
+
* their own set, and refuse a *different* set while another lease is held, with
|
|
72
|
+
* the stable code `PROVIDER_SET_BUSY`, before the adapter is asked to publish
|
|
73
|
+
* anything and before the core is touched;
|
|
74
|
+
* - an identical set is always allowed: `leases` counts holders, so concurrent
|
|
75
|
+
* jobs on one configuration and concurrent ensures of one snapshot proceed;
|
|
76
|
+
* - the engine takes its lease synchronously *before* it awaits the route ensure
|
|
77
|
+
* and releases it only from its own finalize, after the native executor is
|
|
78
|
+
* confirmed stopped — so a settings change saved during a run is stored
|
|
79
|
+
* normally (the settings service is a different authority), and becomes usable
|
|
80
|
+
* as soon as the running tasks drain. There is no queue, no retry and no
|
|
81
|
+
* substitution: the refused candidate simply did not apply.
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
/** Namespace prefix that keeps native route ids separate from public profile ids. */
|
|
85
|
+
const ROUTE_NAMESPACE = 'dsh-delegate';
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The provider `source` that marks a profile DSH already routes itself.
|
|
89
|
+
*
|
|
90
|
+
* A native profile is a *reference* to a route the harness owns: this plugin must
|
|
91
|
+
* never register one (`src/index.js` only maps it onto the DSH route id of the
|
|
92
|
+
* same name), and it must not fingerprint one either — which is why the lease and
|
|
93
|
+
* the route registration share {@link managedProvidersOf} instead of each
|
|
94
|
+
* filtering `source` on its own.
|
|
95
|
+
*/
|
|
96
|
+
const NATIVE_PROVIDER_SOURCE = 'native';
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The provider profiles this plugin owns a route for, i.e. everything that is not
|
|
100
|
+
* a native DSH reference.
|
|
101
|
+
*
|
|
102
|
+
* One function for both halves of the provider contract, on purpose. The engine
|
|
103
|
+
* takes its long-lived lease over the *plugin-managed* set and `ensureRoutes()`
|
|
104
|
+
* registers exactly that same set, so the lease fingerprint and the registered
|
|
105
|
+
* (adapter-visible) candidate are two readings of one list. Filtering them
|
|
106
|
+
* differently is what made a native-only configuration lease `[workbuddy]` while
|
|
107
|
+
* its own route ensure registered `[]`: same task, one holder, two fingerprints,
|
|
108
|
+
* and the second call refused its own lease with `PROVIDER_SET_BUSY` (0 routes)
|
|
109
|
+
* before any second task existed.
|
|
110
|
+
*
|
|
111
|
+
* Order is preserved: the adapter publishes the list in the order it is given, so
|
|
112
|
+
* a reordering must stay visible to the fingerprint. The entries are returned as
|
|
113
|
+
* they are — this is a projection, not a copy or a validation step.
|
|
114
|
+
* @param {unknown} providers - candidate provider list, typically `settings.providers`.
|
|
115
|
+
* @returns {object[]} the plugin-managed subset, in declared order.
|
|
116
|
+
*/
|
|
117
|
+
export function managedProvidersOf(providers) {
|
|
118
|
+
const list = Array.isArray(providers) ? providers : [];
|
|
119
|
+
return list.filter((provider) => provider?.source !== NATIVE_PROVIDER_SOURCE);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The provider profiles DSH routes natively, i.e. the complement of
|
|
124
|
+
* {@link managedProvidersOf} over the same list.
|
|
125
|
+
*
|
|
126
|
+
* Offered so the entry point and any diagnostic count both halves with the same
|
|
127
|
+
* rule; nothing here registers these routes.
|
|
128
|
+
* @param {unknown} providers - candidate provider list.
|
|
129
|
+
* @returns {object[]} the native subset, in declared order.
|
|
130
|
+
*/
|
|
131
|
+
export function nativeProvidersOf(providers) {
|
|
132
|
+
const list = Array.isArray(providers) ? providers : [];
|
|
133
|
+
return list.filter((provider) => provider?.source === NATIVE_PROVIDER_SOURCE);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Error code surfaced to the engine's routing diagnostics. */
|
|
137
|
+
const ERROR_CODE = 'provider_registry';
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Stable code of a refusal caused by a lease another party holds.
|
|
141
|
+
*
|
|
142
|
+
* Distinct from {@link ERROR_CODE} on purpose: "another task is running on a
|
|
143
|
+
* different provider configuration" is an operator-visible state that resolves by
|
|
144
|
+
* itself, not a registry failure, and callers must be able to tell the two apart
|
|
145
|
+
* without matching a message.
|
|
146
|
+
*/
|
|
147
|
+
export const PROVIDER_SET_CODES = Object.freeze({ busy: 'PROVIDER_SET_BUSY' });
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Build one registry error.
|
|
151
|
+
* @param {string} message - operator-facing diagnostic.
|
|
152
|
+
* @returns {Error} error carrying this module's code.
|
|
153
|
+
*/
|
|
154
|
+
function registryError(message) {
|
|
155
|
+
const error = new Error(message);
|
|
156
|
+
error.code = ERROR_CODE;
|
|
157
|
+
return error;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Read the public provider id from one settings entry.
|
|
162
|
+
*
|
|
163
|
+
* A settings snapshot may carry either bare ids or provider records; both are
|
|
164
|
+
* accepted so the registry does not depend on the settings module's shape.
|
|
165
|
+
* @param {unknown} entry - one element of the provider list.
|
|
166
|
+
* @returns {string} public provider id.
|
|
167
|
+
*/
|
|
168
|
+
function publicProviderId(entry) {
|
|
169
|
+
const id = typeof entry === 'string' ? entry : entry?.id;
|
|
170
|
+
if (typeof id !== 'string' || id === '') {
|
|
171
|
+
throw registryError('every provider entry must be a non-empty id');
|
|
172
|
+
}
|
|
173
|
+
return id;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Default native route id for one public provider id.
|
|
178
|
+
* @param {string} publicId - validated public provider id.
|
|
179
|
+
* @returns {string} namespaced native route id, distinct from the public id.
|
|
180
|
+
*/
|
|
181
|
+
function defaultRouteId(publicId) {
|
|
182
|
+
return `${ROUTE_NAMESPACE}:${publicId}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The object that may be handed to `LlmRuntime.registerAdapter()`.
|
|
187
|
+
*
|
|
188
|
+
* A plugin that builds its adapter behind a management facade has two objects
|
|
189
|
+
* per adapter: the facade (`replace`, `snapshot`, …) and the native instance it
|
|
190
|
+
* serves. Only the second one is registrable — the core asks it for
|
|
191
|
+
* `providerInfo`/`providerRetryPolicy` and later for `prepareCall`/`stream`.
|
|
192
|
+
* Accepting either shape here, while refusing an object with no call path,
|
|
193
|
+
* turns that mix-up from a runtime "no adapter registered" on every request
|
|
194
|
+
* into an error at the moment the registry is built.
|
|
195
|
+
* @param {unknown} adapter - native adapter, or a facade exposing `nativeAdapter()`/`getAdapter()`.
|
|
196
|
+
* @returns {object} the native adapter instance.
|
|
197
|
+
*/
|
|
198
|
+
export function nativeAdapterOf(adapter) {
|
|
199
|
+
if (adapter !== null && typeof adapter === 'object' && typeof adapter.stream === 'function') {
|
|
200
|
+
return adapter;
|
|
201
|
+
}
|
|
202
|
+
const unwrap = adapter !== null && typeof adapter === 'object'
|
|
203
|
+
? (typeof adapter.nativeAdapter === 'function' ? adapter.nativeAdapter : adapter.getAdapter)
|
|
204
|
+
: undefined;
|
|
205
|
+
if (typeof unwrap !== 'function') {
|
|
206
|
+
throw registryError('a native provider adapter is required');
|
|
207
|
+
}
|
|
208
|
+
// Called on the facade as receiver so an unwrapper implemented as a method
|
|
209
|
+
// that reads `this` still works; the facade's own getters are plain closures.
|
|
210
|
+
const native = unwrap.call(adapter);
|
|
211
|
+
if (native === null || typeof native !== 'object' || typeof native.stream !== 'function') {
|
|
212
|
+
throw registryError('the adapter facade does not expose a native adapter that can stream');
|
|
213
|
+
}
|
|
214
|
+
if (typeof native.providerInfo !== 'function') {
|
|
215
|
+
throw registryError('the native adapter cannot describe its provider routes');
|
|
216
|
+
}
|
|
217
|
+
return native;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Canonical JSON: object keys sorted, `undefined` members dropped.
|
|
222
|
+
*
|
|
223
|
+
* The fingerprint below must be *deterministic* across two readings of one
|
|
224
|
+
* configuration, so it cannot depend on key insertion order, and it must not
|
|
225
|
+
* change because a field is absent rather than empty. Arrays keep their order:
|
|
226
|
+
* a reordered model list is a different served generation, and the adapter
|
|
227
|
+
* publishes it as one.
|
|
228
|
+
* @param {unknown} value - JSON-compatible value.
|
|
229
|
+
* @returns {string} canonical JSON text.
|
|
230
|
+
*/
|
|
231
|
+
function canonicalJson(value) {
|
|
232
|
+
if (value === undefined) return 'null';
|
|
233
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
|
|
234
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
|
235
|
+
const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
|
|
236
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Read one scalar as a string, or `null` when it is absent.
|
|
241
|
+
* @param {unknown} value - candidate.
|
|
242
|
+
* @returns {string | null} the value or null.
|
|
243
|
+
*/
|
|
244
|
+
function scalarOrNull(value) {
|
|
245
|
+
if (typeof value === 'string') return value;
|
|
246
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* The canonical form of one provider definition, as far as a later model call
|
|
252
|
+
* can observe it.
|
|
253
|
+
*
|
|
254
|
+
* Everything the adapter copies into the served generation is here: the route
|
|
255
|
+
* (derived from the id), the endpoint, the credential *reference* (a name, never
|
|
256
|
+
* a value), the protocol, and per model the id, the display name, the declared
|
|
257
|
+
* effort axis and the context window — which is what a request's budget and
|
|
258
|
+
* effort selectability are computed from. It is deliberately *not* a hash: a
|
|
259
|
+
* collision has to be impossible, and the assembled text is retained in memory
|
|
260
|
+
* only, never written, logged or returned.
|
|
261
|
+
*
|
|
262
|
+
* A provider that is not a record is fingerprinted by its id alone, so a caller
|
|
263
|
+
* that passes bare ids still gets a lease.
|
|
264
|
+
* @param {unknown} entry - one provider of a settings snapshot.
|
|
265
|
+
* @param {(publicId: string) => string} deriveRouteId - native route id derivation.
|
|
266
|
+
* @returns {object} canonical definition.
|
|
267
|
+
*/
|
|
268
|
+
function providerDefinition(entry, deriveRouteId) {
|
|
269
|
+
const publicId = publicProviderId(entry);
|
|
270
|
+
const route = deriveRouteId(publicId);
|
|
271
|
+
if (entry === null || typeof entry !== 'object') {
|
|
272
|
+
return { id: publicId, route };
|
|
273
|
+
}
|
|
274
|
+
const models = Array.isArray(entry.models) ? entry.models : [];
|
|
275
|
+
return {
|
|
276
|
+
id: publicId,
|
|
277
|
+
route,
|
|
278
|
+
name: scalarOrNull(entry.name),
|
|
279
|
+
protocol: scalarOrNull(entry.protocol),
|
|
280
|
+
baseUrl: scalarOrNull(entry.baseUrl),
|
|
281
|
+
credentialRef: scalarOrNull(entry.credentialRef),
|
|
282
|
+
models: models.map((model) => ({
|
|
283
|
+
id: scalarOrNull(model?.id),
|
|
284
|
+
name: scalarOrNull(model?.name),
|
|
285
|
+
efforts: Array.isArray(model?.efforts) ? model.efforts.map((effort) => scalarOrNull(effort)) : null,
|
|
286
|
+
contextWindow: typeof model?.contextWindow === 'number' && Number.isFinite(model.contextWindow)
|
|
287
|
+
? model.contextWindow
|
|
288
|
+
: null,
|
|
289
|
+
})),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Canonical fingerprint of a whole provider-definition set.
|
|
295
|
+
*
|
|
296
|
+
* Two readings of one configuration produce the same text, and any change a later
|
|
297
|
+
* model operation could observe produces a different one. The set is sorted by
|
|
298
|
+
* public provider id for the digest, while the *lease* itself keeps the declared
|
|
299
|
+
* order, because order is what the adapter publishes.
|
|
300
|
+
* @param {object[]} definitions - from {@link providerDefinition}, in declared order.
|
|
301
|
+
* @returns {string} fingerprint.
|
|
302
|
+
*/
|
|
303
|
+
function fingerprintOf(definitions) {
|
|
304
|
+
const sorted = [...definitions].sort((a, b) => (a.id < b.id ? -1 : (a.id > b.id ? 1 : 0)));
|
|
305
|
+
return canonicalJson(sorted);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Create the native route registry for one adapter instance.
|
|
310
|
+
* @param {object} options - registry dependencies.
|
|
311
|
+
* @param {object} options.llm - native llm runtime exposing `registerAdapter`.
|
|
312
|
+
* @param {object} options.adapter - already-constructed native adapter, or the
|
|
313
|
+
* management facade that wraps one ({@link nativeAdapterOf} unwraps it).
|
|
314
|
+
* @param {(publicId: string) => string} [options.routeIdFor] - native route id derivation.
|
|
315
|
+
* @returns {{
|
|
316
|
+
* ensure: (providers: unknown) => Promise<{ routes: Map<string, string> }>,
|
|
317
|
+
* register: (providers: unknown, commit: (routes: Map<string, string>) => unknown) => Promise<{ routes: Map<string, string> }>,
|
|
318
|
+
* lease: (providers: unknown, holder?: string) => object,
|
|
319
|
+
* release: (lease: object) => boolean,
|
|
320
|
+
* heldLease: () => { count: number, holders: string[], fingerprint: string } | null,
|
|
321
|
+
* commitRoutes: (routes: Map<string, string>) => void,
|
|
322
|
+
* nativeAdapter: () => object,
|
|
323
|
+
* dispose: () => void,
|
|
324
|
+
* }} registry.
|
|
325
|
+
*/
|
|
326
|
+
export function createProviderRegistry(options) {
|
|
327
|
+
const { llm, routeIdFor } = options ?? {};
|
|
328
|
+
if (llm === null || typeof llm !== 'object' || typeof llm.registerAdapter !== 'function') {
|
|
329
|
+
throw registryError('the native llm runtime cannot register provider adapters');
|
|
330
|
+
}
|
|
331
|
+
const adapter = nativeAdapterOf(options?.adapter);
|
|
332
|
+
if (routeIdFor !== undefined && typeof routeIdFor !== 'function') {
|
|
333
|
+
throw registryError('routeIdFor must be a function');
|
|
334
|
+
}
|
|
335
|
+
const deriveRouteId = routeIdFor ?? defaultRouteId;
|
|
336
|
+
let handle = null;
|
|
337
|
+
let disposed = false;
|
|
338
|
+
/**
|
|
339
|
+
* The process-local provider-definition lease, or `null` when no set is pinned.
|
|
340
|
+
*
|
|
341
|
+
* One fingerprint, a holder count and the holder labels. Counting (rather than
|
|
342
|
+
* storing one owner) is what lets several tasks share one configuration while a
|
|
343
|
+
* *different* one is refused; see the module comment.
|
|
344
|
+
* @type {{ fingerprint: string, count: number, holders: string[] } | null}
|
|
345
|
+
*/
|
|
346
|
+
let held = null;
|
|
347
|
+
/**
|
|
348
|
+
* Holders of the lease this registry handed out, so every release is exact and
|
|
349
|
+
* a second release of one lease is a no-op rather than somebody else's.
|
|
350
|
+
* @type {WeakSet<object>}
|
|
351
|
+
*/
|
|
352
|
+
const issued = new WeakSet();
|
|
353
|
+
/**
|
|
354
|
+
* Native routes owned by *other* registrations, captured before this registry
|
|
355
|
+
* registered anything.
|
|
356
|
+
*
|
|
357
|
+
* `LlmRuntime.listProviders()` lists every route in the runtime, not this
|
|
358
|
+
* adapter's. Ownership therefore has to be read relative to this baseline: a
|
|
359
|
+
* route present here belongs to somebody else (refuse it), and a route absent
|
|
360
|
+
* here that this registration has not adopted belongs to nobody (the core will
|
|
361
|
+
* refuse it — the adapter must not publish it first).
|
|
362
|
+
* @type {Set<string> | null}
|
|
363
|
+
*/
|
|
364
|
+
let foreignRoutes = null;
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Freeze the foreign-route baseline, once, before this registry registers.
|
|
368
|
+
* @returns {Error | null} a refusal when the runtime cannot report its routes.
|
|
369
|
+
*/
|
|
370
|
+
function captureForeignRoutes() {
|
|
371
|
+
if (foreignRoutes !== null) return null;
|
|
372
|
+
try {
|
|
373
|
+
foreignRoutes = new Set(llm.listProviders().map((entry) => entry.id));
|
|
374
|
+
} catch {
|
|
375
|
+
// Silence is unsafe here: without a second opinion this module cannot prove
|
|
376
|
+
// the candidate does not claim a route another owner registered.
|
|
377
|
+
return registryError('the native llm runtime cannot list its registered provider routes');
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Why one candidate may not be committed to the native core.
|
|
384
|
+
*
|
|
385
|
+
* On a first registration this is the `DUPLICATE_ADAPTER` the core would raise;
|
|
386
|
+
* on a replace it is the `DUPLICATE_ADAPTER` or `INVALID_ADAPTER` the core would
|
|
387
|
+
* raise. Either way the point is the same: refuse *before* the adapter publishes
|
|
388
|
+
* a route set the core is going to reject.
|
|
389
|
+
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
390
|
+
* @returns {Error | null} the refusal, or `null` when the candidate is legal.
|
|
391
|
+
*/
|
|
392
|
+
function ownershipRefusal(routes) {
|
|
393
|
+
const refusal = captureForeignRoutes();
|
|
394
|
+
if (refusal !== null) return refusal;
|
|
395
|
+
for (const [publicId, nativeId] of routes) {
|
|
396
|
+
// A route another registration owns makes `registerAdapter()`/`replace()`
|
|
397
|
+
// throw `DUPLICATE_ADAPTER` — after the caller had already published a
|
|
398
|
+
// snapshot serving it. One this registration has not adopted and nobody owns
|
|
399
|
+
// is not registered at all, so `replace()` would throw `INVALID_ADAPTER` with
|
|
400
|
+
// the adapter already republished. Both are refused here, before the adapter
|
|
401
|
+
// sees the candidate.
|
|
402
|
+
if (foreignRoutes.has(nativeId)) {
|
|
403
|
+
return registryError(`provider ${publicId} maps to native route ${nativeId}, which another adapter registration already owns`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Validate one candidate provider list and derive its route mapping.
|
|
411
|
+
* Pure: nothing is registered here, so a refusal cannot mutate the core.
|
|
412
|
+
* @param {unknown} providers - candidate provider list.
|
|
413
|
+
* @returns {Map<string, string>} public id -> native route id, in input order.
|
|
414
|
+
*/
|
|
415
|
+
function plan(providers) {
|
|
416
|
+
if (!Array.isArray(providers)) throw registryError('the provider list must be an array');
|
|
417
|
+
const routes = new Map();
|
|
418
|
+
const nativeIds = new Set();
|
|
419
|
+
for (const entry of providers) {
|
|
420
|
+
const publicId = publicProviderId(entry);
|
|
421
|
+
if (routes.has(publicId)) {
|
|
422
|
+
throw registryError(`provider ${publicId} is listed more than once`);
|
|
423
|
+
}
|
|
424
|
+
const nativeId = deriveRouteId(publicId);
|
|
425
|
+
if (typeof nativeId !== 'string' || nativeId === '') {
|
|
426
|
+
throw registryError(`provider ${publicId} has no usable native route id`);
|
|
427
|
+
}
|
|
428
|
+
if (nativeIds.has(nativeId)) {
|
|
429
|
+
throw registryError(`provider ${publicId} collides on native route id ${nativeId}`);
|
|
430
|
+
}
|
|
431
|
+
nativeIds.add(nativeId);
|
|
432
|
+
routes.set(publicId, nativeId);
|
|
433
|
+
}
|
|
434
|
+
return routes;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Commit one validated route set to the native core.
|
|
439
|
+
*
|
|
440
|
+
* The first call registers; later calls replace the whole set. The registration
|
|
441
|
+
* handle is only kept once the core returned one, so a thrown registration
|
|
442
|
+
* leaves this module in the state it was in before the attempt. Synchronous:
|
|
443
|
+
* the core validates and commits inside the call.
|
|
444
|
+
* @param {Map<string, string>} routes - validated public -> native mapping.
|
|
445
|
+
* @returns {void}
|
|
446
|
+
*/
|
|
447
|
+
function commitRoutes(routes) {
|
|
448
|
+
const nativeIds = [...routes.values()];
|
|
449
|
+
if (handle === null) {
|
|
450
|
+
// The baseline is taken before this registration exists, so it holds only
|
|
451
|
+
// other owners' routes. If the caller already refused a candidate, this is a
|
|
452
|
+
// no-op; if it did not run, this is the first and only chance to take it.
|
|
453
|
+
const refusal = captureForeignRoutes();
|
|
454
|
+
if (refusal !== null) throw refusal;
|
|
455
|
+
/**
|
|
456
|
+
* The native handle is the disposer plus `replace()`; a runtime that
|
|
457
|
+
* returns anything else cannot be kept consistent by this module.
|
|
458
|
+
*/
|
|
459
|
+
const registered = llm.registerAdapter(nativeIds, adapter);
|
|
460
|
+
if (typeof registered !== 'function') {
|
|
461
|
+
throw registryError('the native llm runtime returned no adapter disposer');
|
|
462
|
+
}
|
|
463
|
+
handle = registered;
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
// Atomic in the core: a rejected candidate throws and keeps the live routes.
|
|
467
|
+
handle.replace(nativeIds);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Decide what one candidate needs: a native commit, or nothing at all.
|
|
472
|
+
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
473
|
+
* @returns {boolean} whether the native core has to be touched.
|
|
474
|
+
*/
|
|
475
|
+
function changesNativeState(routes) {
|
|
476
|
+
// An empty first list establishes nothing; the core refuses an empty initial
|
|
477
|
+
// registration, and a later non-empty list registers lazily.
|
|
478
|
+
return handle !== null || routes.size > 0;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Validate one candidate provider list into its canonical definition set.
|
|
483
|
+
* @param {unknown} providers - candidate provider list.
|
|
484
|
+
* @returns {{ routes: Map<string, string>, fingerprint: string }} plan plus its fingerprint.
|
|
485
|
+
*/
|
|
486
|
+
function describe(providers) {
|
|
487
|
+
const routes = plan(providers);
|
|
488
|
+
const fingerprint = fingerprintOf([...providers].map((entry) => providerDefinition(entry, deriveRouteId)));
|
|
489
|
+
return { routes, fingerprint };
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* The refusal a different provider set would receive right now, or `null`.
|
|
494
|
+
*
|
|
495
|
+
* This is the whole admission rule: an equal set always shares the lease, and a
|
|
496
|
+
* different one is refused while anybody holds it. It deliberately names no
|
|
497
|
+
* endpoint and no credential reference — only that a configuration is pinned and
|
|
498
|
+
* by whom — because it is reported to a caller who may not be the holder.
|
|
499
|
+
* @param {string} fingerprint - candidate set.
|
|
500
|
+
* @param {number} routeCount - size of the candidate mapping, for the message.
|
|
501
|
+
* @returns {Error | null} refusal carrying {@link PROVIDER_SET_CODES.busy}.
|
|
502
|
+
*/
|
|
503
|
+
function leaseRefusal(fingerprint, routeCount) {
|
|
504
|
+
if (held === null || held.fingerprint === fingerprint) return null;
|
|
505
|
+
const error = registryError(
|
|
506
|
+
`another task is running on a different provider configuration (${held.count} lease holder(s)); `
|
|
507
|
+
+ `this ${routeCount} provider set may not be applied until it finishes`,
|
|
508
|
+
);
|
|
509
|
+
error.code = PROVIDER_SET_CODES.busy;
|
|
510
|
+
error.details = {
|
|
511
|
+
code: PROVIDER_SET_CODES.busy,
|
|
512
|
+
heldBy: held.count,
|
|
513
|
+
// Labels are generated by this module or by the caller and never contain a
|
|
514
|
+
// provider id, an endpoint or a credential reference.
|
|
515
|
+
holders: held.holders.slice(0, 8),
|
|
516
|
+
};
|
|
517
|
+
return error;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Take the provider-definition lease for one already-described set.
|
|
522
|
+
*
|
|
523
|
+
* Synchronous on purpose: the engine calls this in the same step that freezes
|
|
524
|
+
* its task's route set, before it awaits anything, so there is no window in
|
|
525
|
+
* which the set it is about to use could have been swapped by somebody else.
|
|
526
|
+
* @param {string} fingerprint - candidate set.
|
|
527
|
+
* @param {number} routeCount - size of the candidate mapping.
|
|
528
|
+
* @param {string} holder - bounded label for diagnostics.
|
|
529
|
+
* @returns {void}
|
|
530
|
+
* @throws {Error} the busy refusal when another set is pinned.
|
|
531
|
+
*/
|
|
532
|
+
function acquire(fingerprint, routeCount, holder) {
|
|
533
|
+
const refusal = leaseRefusal(fingerprint, routeCount);
|
|
534
|
+
if (refusal !== null) throw refusal;
|
|
535
|
+
if (held === null) held = { fingerprint, count: 0, holders: [] };
|
|
536
|
+
held.count += 1;
|
|
537
|
+
if (holder !== '') held.holders.push(holder);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Give one holder's lease back.
|
|
542
|
+
*
|
|
543
|
+
* `register`/`ensure` take their lease for the duration of their own call and
|
|
544
|
+
* hand it back the same way; a lease object taken through `lease()` is released
|
|
545
|
+
* once and never again, so it cannot drain another holder's share. A release that
|
|
546
|
+
* leaves nobody holding frees the set, i.e. a different configuration may apply
|
|
547
|
+
* from the next call on.
|
|
548
|
+
* @param {string} fingerprint - the set being released.
|
|
549
|
+
* @param {string} holder - the label to remove.
|
|
550
|
+
* @returns {void}
|
|
551
|
+
*/
|
|
552
|
+
function giveBack(fingerprint, holder) {
|
|
553
|
+
if (held === null || held.fingerprint !== fingerprint) return;
|
|
554
|
+
held.count -= 1;
|
|
555
|
+
const index = held.holders.lastIndexOf(holder);
|
|
556
|
+
if (index >= 0) held.holders.splice(index, 1);
|
|
557
|
+
if (held.count <= 0) held = null;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Take the lease for one provider set and hand back a releasable lease object.
|
|
562
|
+
*
|
|
563
|
+
* The object is the only thing a caller may release; releasing it twice is a
|
|
564
|
+
* no-op, and releasing a lease the registry never issued is refused, so one
|
|
565
|
+
* task cannot drain another's hold.
|
|
566
|
+
* @param {unknown} providers - provider list from one settings snapshot.
|
|
567
|
+
* @param {string} [holder] - bounded diagnostic label (a task id, an operation).
|
|
568
|
+
* @returns {{ kind: string, fingerprint: string, holder: string, released: boolean }} lease.
|
|
569
|
+
*/
|
|
570
|
+
function lease(providers, holder) {
|
|
571
|
+
if (disposed) throw registryError('the provider registry has been disposed');
|
|
572
|
+
const described = describe(providers);
|
|
573
|
+
const label = typeof holder === 'string' && holder !== '' ? holder.slice(0, 120) : '';
|
|
574
|
+
acquire(described.fingerprint, described.routes.size, label);
|
|
575
|
+
const record = { kind: 'provider-definition-lease', fingerprint: described.fingerprint, holder: label, released: false };
|
|
576
|
+
issued.add(record);
|
|
577
|
+
return record;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Release one lease handed out by {@link lease}.
|
|
582
|
+
* @param {unknown} record - lease object.
|
|
583
|
+
* @returns {boolean} true when this call released it.
|
|
584
|
+
*/
|
|
585
|
+
function release(record) {
|
|
586
|
+
if (record === null || typeof record !== 'object' || !issued.has(record)) return false;
|
|
587
|
+
if (record.released === true) return false;
|
|
588
|
+
record.released = true;
|
|
589
|
+
giveBack(record.fingerprint, record.holder);
|
|
590
|
+
return true;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Describe the lease currently held, for diagnostics and tests.
|
|
595
|
+
* @returns {{ count: number, holders: string[], fingerprint: string } | null} copy, or null when free.
|
|
596
|
+
*/
|
|
597
|
+
function heldLease() {
|
|
598
|
+
if (held === null) return null;
|
|
599
|
+
return { count: held.count, holders: [...held.holders], fingerprint: held.fingerprint };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Ensure the native routes for one provider list.
|
|
604
|
+
*
|
|
605
|
+
* The lease is taken for the duration of this call, which is synchronous apart
|
|
606
|
+
* from its own `async` wrapper, so an ensure of a different set cannot interleave
|
|
607
|
+
* with one already in progress.
|
|
608
|
+
* @param {unknown} providers - provider list from one settings snapshot.
|
|
609
|
+
* @returns {Promise<{ routes: Map<string, string> }>} fresh public -> native mapping.
|
|
610
|
+
*/
|
|
611
|
+
async function ensure(providers) {
|
|
612
|
+
if (disposed) throw registryError('the provider registry has been disposed');
|
|
613
|
+
const { routes, fingerprint } = describe(providers);
|
|
614
|
+
acquire(fingerprint, routes.size, 'ensure');
|
|
615
|
+
try {
|
|
616
|
+
if (changesNativeState(routes)) commitRoutes(routes);
|
|
617
|
+
} finally {
|
|
618
|
+
giveBack(fingerprint, 'ensure');
|
|
619
|
+
}
|
|
620
|
+
return { routes: new Map(routes) };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Ensure the native routes for one provider list, letting the caller act
|
|
625
|
+
* between validation and registration.
|
|
626
|
+
*
|
|
627
|
+
* The callback exists because the adapter's serving state has to be in place
|
|
628
|
+
* *before* the core validates the routes: `prepareRoutes()` reads
|
|
629
|
+
* `providerInfo(id)` synchronously and refuses (or mislabels) a route the
|
|
630
|
+
* adapter is not already serving. A caller that must publish a snapshot first
|
|
631
|
+
* uses this. The callback runs after the candidate set is fully validated, its
|
|
632
|
+
* native commit runs from inside it, and nothing in between yields, so an
|
|
633
|
+
* exception from the callback — or from the registration — leaves the native
|
|
634
|
+
* registration exactly as it was, and the callback's own restoration is the last
|
|
635
|
+
* word on the snapshot.
|
|
636
|
+
*
|
|
637
|
+
* The callback receives the routes and performs the *publication* only: it
|
|
638
|
+
* calls the second argument, `commit()`, at the point where the native
|
|
639
|
+
* registration must happen. Anything after that call runs with the candidate
|
|
640
|
+
* already committed, so a callback that yields after it is the one thing this
|
|
641
|
+
* contract cannot take back — which is why the return value is checked and why
|
|
642
|
+
* the handed `commit()` refuses to fire once the callback has yielded.
|
|
643
|
+
*
|
|
644
|
+
* The provider-definition lease is checked here too, *before* the callback runs,
|
|
645
|
+
* so a task pinned to another configuration cannot have this one published
|
|
646
|
+
* underneath it — and the adapter is never asked for a snapshot that the core
|
|
647
|
+
* will then refuse.
|
|
648
|
+
* @param {unknown} providers - provider list from one settings snapshot.
|
|
649
|
+
* @param {(routes: Map<string, string>, commit: () => void) => unknown} commit - runs after validation; must not yield.
|
|
650
|
+
* @returns {Promise<{ routes: Map<string, string> }>} fresh public -> native mapping.
|
|
651
|
+
*/
|
|
652
|
+
async function register(providers, commit) {
|
|
653
|
+
if (typeof commit !== 'function') throw registryError('a registration callback is required');
|
|
654
|
+
if (disposed) throw registryError('the provider registry has been disposed');
|
|
655
|
+
const { routes, fingerprint } = describe(providers);
|
|
656
|
+
acquire(fingerprint, routes.size, 'register');
|
|
657
|
+
try {
|
|
658
|
+
if (changesNativeState(routes)) commitCandidate(routes, commit);
|
|
659
|
+
else commit(new Map(), () => {});
|
|
660
|
+
} finally {
|
|
661
|
+
giveBack(fingerprint, 'register');
|
|
662
|
+
}
|
|
663
|
+
return { routes: new Map(routes) };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* The transaction: publication, native commit, and nothing awaited.
|
|
668
|
+
*
|
|
669
|
+
* The callback is handed a `commit()` it must call itself, so the native
|
|
670
|
+
* registration runs from inside the callback's own synchronous stack — never
|
|
671
|
+
* before publication, never after a yield. `commit()` and the callback share
|
|
672
|
+
* one guard: once the callback has yielded it cannot commit, and once it has
|
|
673
|
+
* committed the native state is real, so it cannot pull the snapshot out from
|
|
674
|
+
* under a committed registration either.
|
|
675
|
+
*
|
|
676
|
+
* `adapt` is the only party that can restore the snapshot the candidate
|
|
677
|
+
* displaced, so this function never restores anything on its own. Its contract:
|
|
678
|
+
*
|
|
679
|
+
* 1. the candidate set is refused *before* `adapt` runs if it claims a route
|
|
680
|
+
* another registration owns, so the adapter never publishes a route the
|
|
681
|
+
* core would reject;
|
|
682
|
+
* 2. `adapt()` must not return a thenable — a promise means the callback
|
|
683
|
+
* yielded, and the native registration would then land in a microtask this
|
|
684
|
+
* function has already answered past;
|
|
685
|
+
* 3. whatever `adapt()` throws propagates unchanged, after it has restored the
|
|
686
|
+
* snapshot state it was given.
|
|
687
|
+
* @param {Map<string, string>} routes - validated candidate mapping.
|
|
688
|
+
* @param {(routes: Map<string, string>, commit: () => void) => unknown} adapt - publish, then commit, synchronously.
|
|
689
|
+
* @returns {void}
|
|
690
|
+
* @throws {Error} the ownership refusal, the contract violation, or the native refusal.
|
|
691
|
+
*/
|
|
692
|
+
function commitCandidate(routes, adapt) {
|
|
693
|
+
const refusal = ownershipRefusal(routes);
|
|
694
|
+
if (refusal !== null) throw refusal;
|
|
695
|
+
let open = true;
|
|
696
|
+
let committed = false;
|
|
697
|
+
/**
|
|
698
|
+
* Perform the native commit for this candidate, exactly once.
|
|
699
|
+
* @returns {void}
|
|
700
|
+
* @throws {Error} when called after a yield or a throw.
|
|
701
|
+
*/
|
|
702
|
+
const commit = () => {
|
|
703
|
+
if (!open) {
|
|
704
|
+
throw registryError('the registration callback committed outside its own synchronous section');
|
|
705
|
+
}
|
|
706
|
+
if (committed) throw registryError('the registration callback committed the same candidate twice');
|
|
707
|
+
commitRoutes(routes);
|
|
708
|
+
committed = true;
|
|
709
|
+
};
|
|
710
|
+
let outcome;
|
|
711
|
+
try {
|
|
712
|
+
outcome = adapt(new Map(routes), commit);
|
|
713
|
+
} finally {
|
|
714
|
+
// Closed as soon as the callback's synchronous stack unwinds, whichever way
|
|
715
|
+
// it left: a queued continuation can no longer mutate the native registry.
|
|
716
|
+
open = false;
|
|
717
|
+
}
|
|
718
|
+
if (outcome !== null && (typeof outcome === 'object' || typeof outcome === 'function')
|
|
719
|
+
&& typeof outcome.then === 'function') {
|
|
720
|
+
// Swallow the loser's rejection: the refusal below is the error that reaches
|
|
721
|
+
// the caller, and an unhandled rejection must not surface from a candidate
|
|
722
|
+
// this module already refused.
|
|
723
|
+
Promise.resolve(outcome).catch(() => {});
|
|
724
|
+
throw registryError('the registration callback must not be asynchronous');
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Release the native registration. Idempotent; later ensures are refused.
|
|
730
|
+
*
|
|
731
|
+
* The lease goes with it: a disposed registry can never apply another
|
|
732
|
+
* configuration, so keeping a set pinned would refuse work for no reason. A
|
|
733
|
+
* task that still holds a lease record releases it into a free registry, which
|
|
734
|
+
* is a no-op, so a late finalize after unload cannot resurrect a hold.
|
|
735
|
+
* @returns {void}
|
|
736
|
+
*/
|
|
737
|
+
function dispose() {
|
|
738
|
+
if (disposed) return;
|
|
739
|
+
disposed = true;
|
|
740
|
+
held = null;
|
|
741
|
+
const registered = handle;
|
|
742
|
+
handle = null;
|
|
743
|
+
if (registered !== null) registered();
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
return {
|
|
747
|
+
ensure,
|
|
748
|
+
register,
|
|
749
|
+
lease,
|
|
750
|
+
release,
|
|
751
|
+
heldLease,
|
|
752
|
+
commitRoutes,
|
|
753
|
+
nativeAdapter: () => adapter,
|
|
754
|
+
dispose,
|
|
755
|
+
};
|
|
756
|
+
}
|