dsh-taskbridge 0.0.0-stage → 1.3.2
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 +763 -0
- package/LICENSE +21 -0
- package/README.md +622 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-taskbridge.toml +247 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +34 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +937 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +304 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +223 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +138 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3299 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +456 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3614 -0
- package/src/jobs/history.js +1467 -0
- package/src/jobs/title.js +17 -0
- package/src/mcp/server.js +1821 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1740 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1121 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
// Native OpenAI-compatible (Chat Completions) provider adapter.
|
|
2
|
+
//
|
|
3
|
+
// This module is the plugin-owned bridge between the validated settings shape
|
|
4
|
+
// (`provider { id, name, protocol:'openai-chat', baseUrl, credentialRef,
|
|
5
|
+
// models:[{ id, name, efforts }] }`) and the installed DSH pi-ai adapter
|
|
6
|
+
// (`@deepseek-ai/dsh-llm-pi-ai`), which owns request conversion and SSE parsing.
|
|
7
|
+
// Nothing here parses HTTP or SSE: the proven pi-ai streaming APIs do that, and
|
|
8
|
+
// this file only decides *which* route, model, effort and credential one request
|
|
9
|
+
// may use.
|
|
10
|
+
//
|
|
11
|
+
// Three invariants shape the code:
|
|
12
|
+
//
|
|
13
|
+
// 1. **One immutable snapshot per operation.** `replaceProfiles()` builds a
|
|
14
|
+
// brand-new provider collection and swaps it in whole. The adapter reads the
|
|
15
|
+
// current snapshot once per operation, so a settings change reaches the next
|
|
16
|
+
// request and never the one already in flight.
|
|
17
|
+
// 2. **The snapshot exists before the harness reads it.** Native route
|
|
18
|
+
// registration is not lazy: `LlmRuntime.prepareRoutes()` calls
|
|
19
|
+
// `adapter.providerInfo()` / `adapter.providerRetryPolicy()` *synchronously*
|
|
20
|
+
// while validating a candidate route set, and `PiAiAdapter.providerInfo()`
|
|
21
|
+
// answers from the snapshot it currently serves (`this.current().profiles`).
|
|
22
|
+
// A route that is not already in the served snapshot therefore either throws
|
|
23
|
+
// inside registration or resolves to the placeholder display name. The
|
|
24
|
+
// registration order in the entry point is derived from that fact: prime the
|
|
25
|
+
// snapshot, validate the routes against the real adapter, then register — all
|
|
26
|
+
// of it synchronously, through `prepareRoutes()` and the registry's
|
|
27
|
+
// `commitRoutes()`, so no caller can observe the two sides apart.
|
|
28
|
+
// 3. **No ambient auth, ever.** A route's configured `credentialRef` is resolved
|
|
29
|
+
// through the injected DSH credential service, once per request, and rides to
|
|
30
|
+
// pi-ai as the request-level `apiKey` override. A reference that resolves to
|
|
31
|
+
// nothing fails with `MISSING_CREDENTIAL` before any network I/O; the pi-ai
|
|
32
|
+
// auth context this adapter injects can answer neither `env()` nor
|
|
33
|
+
// `fileExists()`, so pi-ai can never fall back to the process environment or
|
|
34
|
+
// a credential file on its own. The value is never logged, stored on a
|
|
35
|
+
// profile, or copied into an error.
|
|
36
|
+
|
|
37
|
+
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
|
|
38
|
+
import { LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
39
|
+
import { createProvider } from '@earendil-works/pi-ai';
|
|
40
|
+
import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';
|
|
41
|
+
|
|
42
|
+
import { KNOWN_EFFORTS } from '../config/defaults.js';
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* DSH settings protocol id -> pi-ai API id.
|
|
46
|
+
*
|
|
47
|
+
* Only `openai-chat` is served by this slice; it is the one protocol the settings
|
|
48
|
+
* validator accepts (`SUPPORTED_PROTOCOLS` in `src/config/defaults.js`) and the
|
|
49
|
+
* one pi-ai implements as `openai-completions`.
|
|
50
|
+
*/
|
|
51
|
+
const PROTOCOL_API = Object.freeze({ 'openai-chat': 'openai-completions' });
|
|
52
|
+
|
|
53
|
+
/** Protocols this adapter can serve, in declaration order. */
|
|
54
|
+
export const SUPPORTED_PROTOCOLS = Object.freeze(Object.keys(PROTOCOL_API));
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Reasoning ids pi-ai maps through `Model.thinkingLevelMap`.
|
|
58
|
+
*
|
|
59
|
+
* `off` is handled separately in `buildModel`: pi-ai's absence default already
|
|
60
|
+
* means "no reasoning level sent", and writing `off: null` would instead mark it
|
|
61
|
+
* unsupported and make a declared `off` unselectable.
|
|
62
|
+
*/
|
|
63
|
+
const MAPPED_EFFORTS = Object.freeze(KNOWN_EFFORTS.filter((id) => id !== 'off'));
|
|
64
|
+
|
|
65
|
+
/** Stable failure codes. `MISSING_CREDENTIAL` matches the native seam's code. */
|
|
66
|
+
export const ERROR_CODES = Object.freeze({
|
|
67
|
+
missingCredential: 'MISSING_CREDENTIAL',
|
|
68
|
+
credentialUnavailable: 'CREDENTIAL_UNAVAILABLE',
|
|
69
|
+
credentialServiceUnavailable: 'CREDENTIAL_SERVICE_UNAVAILABLE',
|
|
70
|
+
protocolUnsupported: 'PROTOCOL_UNSUPPORTED',
|
|
71
|
+
invalidSnapshot: 'INVALID_SNAPSHOT',
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* pi-ai defaults for a model the settings document does not size.
|
|
76
|
+
* Mirrors `DEFAULT_CONTEXT_WINDOW` / `DEFAULT_MAX_TOKENS` in
|
|
77
|
+
* `@deepseek-ai/dsh-llm-pi-ai`'s configuration module, which is not a root export.
|
|
78
|
+
*/
|
|
79
|
+
const DEFAULT_CONTEXT_WINDOW = 262144;
|
|
80
|
+
const DEFAULT_MAX_TOKENS = 32768;
|
|
81
|
+
|
|
82
|
+
/** Request-level image bounds from the same module's defaults. Inert while `input` is text-only. */
|
|
83
|
+
const IMAGE_DEFAULTS = Object.freeze({
|
|
84
|
+
maxRequestImageBytes: 20971520,
|
|
85
|
+
requestImagePixelBudget: 4194304,
|
|
86
|
+
requestImageMaxBytes: 1048576,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
/** Default provider-idle bound while one stream read is outstanding (pi-ai adapter default). */
|
|
90
|
+
const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300000;
|
|
91
|
+
|
|
92
|
+
/** An empty snapshot: the dormant posture before any profile is supplied. */
|
|
93
|
+
const EMPTY_SNAPSHOT = Object.freeze({
|
|
94
|
+
profiles: new Map(),
|
|
95
|
+
routes: new Map(),
|
|
96
|
+
providerIds: Object.freeze([]),
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Build one adapter failure.
|
|
101
|
+
* @param {string} code - stable machine code.
|
|
102
|
+
* @param {string} message - operator-facing explanation; never carries a secret.
|
|
103
|
+
* @param {object} [details] - bounded, non-secret context.
|
|
104
|
+
* @returns {Error & { code: string, details: object }} the failure.
|
|
105
|
+
*/
|
|
106
|
+
function adapterError(code, message, details = {}) {
|
|
107
|
+
const error = new Error(message);
|
|
108
|
+
error.name = 'OpenAiAdapterError';
|
|
109
|
+
error.code = code;
|
|
110
|
+
error.details = details;
|
|
111
|
+
return error;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Read one required, non-empty string.
|
|
116
|
+
* @param {unknown} value - candidate.
|
|
117
|
+
* @param {string} field - field name for the diagnostic.
|
|
118
|
+
* @param {object} details - context for the failure.
|
|
119
|
+
* @returns {string} the value.
|
|
120
|
+
*/
|
|
121
|
+
function requireName(value, field, details) {
|
|
122
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
123
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `${field} must be a non-empty string`, details);
|
|
124
|
+
}
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Build one pi-ai model declaration from one settings model entry.
|
|
130
|
+
*
|
|
131
|
+
* The model id is preserved verbatim — it is the exact string the endpoint
|
|
132
|
+
* receives — and the effort axis is exactly the declared one: every undeclared
|
|
133
|
+
* level is mapped to `null` (pi-ai's "unsupported"), so nothing the operator did
|
|
134
|
+
* not declare is ever offered or sent.
|
|
135
|
+
* @param {string} route - native route id that owns the model.
|
|
136
|
+
* @param {string} baseUrl - endpoint of the route.
|
|
137
|
+
* @param {object} declaration - validated settings model entry.
|
|
138
|
+
* @returns {object} pi-ai `Model` declaration.
|
|
139
|
+
*/
|
|
140
|
+
function buildModel(route, baseUrl, declaration) {
|
|
141
|
+
const id = requireName(declaration?.id, 'model.id', { route });
|
|
142
|
+
const name = typeof declaration.name === 'string' && declaration.name !== '' ? declaration.name : id;
|
|
143
|
+
const rawEfforts = declaration.efforts ?? [];
|
|
144
|
+
if (!Array.isArray(rawEfforts)) {
|
|
145
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `model ${id} declares efforts that are not a list`, { route, model: id });
|
|
146
|
+
}
|
|
147
|
+
const declared = new Set();
|
|
148
|
+
for (const effort of rawEfforts) {
|
|
149
|
+
if (!KNOWN_EFFORTS.includes(effort)) {
|
|
150
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `model ${id} declares unsupported reasoning effort ${JSON.stringify(effort)}`, {
|
|
151
|
+
route,
|
|
152
|
+
model: id,
|
|
153
|
+
supported: [...KNOWN_EFFORTS],
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
declared.add(effort);
|
|
157
|
+
}
|
|
158
|
+
const thinkingLevelMap = {};
|
|
159
|
+
let selectable = 0;
|
|
160
|
+
for (const effort of MAPPED_EFFORTS) {
|
|
161
|
+
// Identity mapping: the settings id IS the wire spelling, because the
|
|
162
|
+
// validated settings shape carries no per-effort wire alias. `null` marks a
|
|
163
|
+
// level pi-ai must refuse, which is exactly "not declared by this model".
|
|
164
|
+
const offered = declared.has(effort);
|
|
165
|
+
thinkingLevelMap[effort] = offered ? effort : null;
|
|
166
|
+
if (offered) selectable += 1;
|
|
167
|
+
}
|
|
168
|
+
if (declared.has('off')) {
|
|
169
|
+
// Declared `off` keeps pi-ai's default absence semantics: the level is
|
|
170
|
+
// selectable and sends no reasoning parameter. Assigning `off` a mapping
|
|
171
|
+
// here would either send a literal effort string or mark it unsupported.
|
|
172
|
+
selectable += 1;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const contextWindow = Number.isInteger(declaration.contextWindow) ? declaration.contextWindow : DEFAULT_CONTEXT_WINDOW;
|
|
176
|
+
const model = {
|
|
177
|
+
id,
|
|
178
|
+
name,
|
|
179
|
+
api: PROTOCOL_API['openai-chat'],
|
|
180
|
+
provider: route,
|
|
181
|
+
baseUrl,
|
|
182
|
+
input: ['text'],
|
|
183
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
184
|
+
contextWindow,
|
|
185
|
+
maxTokens: DEFAULT_MAX_TOKENS,
|
|
186
|
+
reasoning: selectable > 0,
|
|
187
|
+
};
|
|
188
|
+
if (selectable > 0) model.thinkingLevelMap = thinkingLevelMap;
|
|
189
|
+
return model;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Build the pi-ai provider for one route.
|
|
194
|
+
*
|
|
195
|
+
* The provider's own `apiKey.resolve` reports "configured, no ambient key": the
|
|
196
|
+
* only credential this provider ever sees is the request-level `apiKey` the
|
|
197
|
+
* adapter resolves from the injected DSH service. It deliberately never reads
|
|
198
|
+
* `ctx.env` or `ctx.fileExists`.
|
|
199
|
+
* @param {object} spec - `{ route, name, baseUrl, models }`.
|
|
200
|
+
* @returns {object} pi-ai `Provider`.
|
|
201
|
+
*/
|
|
202
|
+
function buildProvider(spec) {
|
|
203
|
+
return createProvider({
|
|
204
|
+
id: spec.route,
|
|
205
|
+
name: spec.name,
|
|
206
|
+
baseUrl: spec.baseUrl,
|
|
207
|
+
models: spec.models,
|
|
208
|
+
api: openAICompletionsApi(),
|
|
209
|
+
auth: {
|
|
210
|
+
apiKey: {
|
|
211
|
+
name: `${spec.name} credential`,
|
|
212
|
+
resolve: () => Promise.resolve({ auth: {}, source: 'dsh-delegate' }),
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Normalize the route map that accompanies one snapshot.
|
|
220
|
+
* @param {unknown} routes - `Map` (or pairs) of public provider id -> native route id.
|
|
221
|
+
* @returns {Map<string, string>} a private copy.
|
|
222
|
+
*/
|
|
223
|
+
function readRoutes(routes) {
|
|
224
|
+
if (routes instanceof Map) return new Map(routes);
|
|
225
|
+
if (Array.isArray(routes)) return new Map(routes);
|
|
226
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'the snapshot must carry a map from public provider id to native route id');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Build one immutable snapshot from a validated provider list plus its route map.
|
|
231
|
+
*
|
|
232
|
+
* Every check runs before anything is published, so a refused snapshot leaves the
|
|
233
|
+
* serving snapshot untouched.
|
|
234
|
+
* @param {object} input - `{ providers, routes }`.
|
|
235
|
+
* @returns {{ profiles: Map<string, object>, routes: Map<string, string>, providerIds: readonly string[] }} snapshot.
|
|
236
|
+
*/
|
|
237
|
+
function buildSnapshot(input) {
|
|
238
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
|
239
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'a provider snapshot must be an object');
|
|
240
|
+
}
|
|
241
|
+
if (!Array.isArray(input.providers)) {
|
|
242
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'a provider snapshot must carry a provider list');
|
|
243
|
+
}
|
|
244
|
+
const routeMap = readRoutes(input.routes);
|
|
245
|
+
const profiles = new Map();
|
|
246
|
+
const providerIds = [];
|
|
247
|
+
const claimedRoutes = new Map();
|
|
248
|
+
|
|
249
|
+
for (const provider of input.providers) {
|
|
250
|
+
const publicId = requireName(provider?.id, 'provider.id', {});
|
|
251
|
+
if (providerIds.includes(publicId)) {
|
|
252
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} is listed more than once`, { provider: publicId });
|
|
253
|
+
}
|
|
254
|
+
const protocol = provider.protocol ?? 'openai-chat';
|
|
255
|
+
if (!SUPPORTED_PROTOCOLS.includes(protocol)) {
|
|
256
|
+
throw adapterError(ERROR_CODES.protocolUnsupported, `provider ${publicId} speaks unsupported protocol ${JSON.stringify(protocol)}`, {
|
|
257
|
+
provider: publicId,
|
|
258
|
+
supported: [...SUPPORTED_PROTOCOLS],
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
const route = routeMap.get(publicId);
|
|
262
|
+
if (typeof route !== 'string' || route === '') {
|
|
263
|
+
// Guessing the route would be exactly the hidden substitution this plugin
|
|
264
|
+
// refuses; a provider the registry did not map is not served.
|
|
265
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} has no native route in this snapshot`, {
|
|
266
|
+
provider: publicId,
|
|
267
|
+
routes: [...routeMap.keys()].slice(0, 32),
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
const owner = claimedRoutes.get(route);
|
|
271
|
+
if (owner !== undefined) {
|
|
272
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `native route ${route} is claimed by both ${owner} and ${publicId}`, {
|
|
273
|
+
route,
|
|
274
|
+
providers: [owner, publicId],
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
claimedRoutes.set(route, publicId);
|
|
278
|
+
|
|
279
|
+
const name = typeof provider.name === 'string' && provider.name !== '' ? provider.name : publicId;
|
|
280
|
+
const baseUrl = requireName(provider.baseUrl, `provider ${publicId}.baseUrl`, { provider: publicId });
|
|
281
|
+
const credentialRef = provider.credentialRef === undefined ? null : provider.credentialRef;
|
|
282
|
+
if (credentialRef !== null && (typeof credentialRef !== 'string' || credentialRef === '')) {
|
|
283
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} carries an unusable credential reference`, { provider: publicId });
|
|
284
|
+
}
|
|
285
|
+
const declarations = provider.models ?? [];
|
|
286
|
+
if (!Array.isArray(declarations)) {
|
|
287
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} carries a model list that is not a list`, { provider: publicId });
|
|
288
|
+
}
|
|
289
|
+
const models = [];
|
|
290
|
+
const seenModels = new Set();
|
|
291
|
+
for (const declaration of declarations) {
|
|
292
|
+
const model = buildModel(route, baseUrl, declaration);
|
|
293
|
+
if (seenModels.has(model.id)) {
|
|
294
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} lists model ${model.id} more than once`, {
|
|
295
|
+
provider: publicId,
|
|
296
|
+
model: model.id,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
seenModels.add(model.id);
|
|
300
|
+
models.push(model);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
profiles.set(route, Object.freeze({
|
|
304
|
+
// Fields `ResolvedPiAiProviderProfile` requires, resolved the way the
|
|
305
|
+
// installed adapter expects to read them.
|
|
306
|
+
provider: route,
|
|
307
|
+
displayName: name,
|
|
308
|
+
api: PROTOCOL_API['openai-chat'],
|
|
309
|
+
baseURL: baseUrl,
|
|
310
|
+
// Only the *reference* travels on the profile. A value never does.
|
|
311
|
+
credentialRef,
|
|
312
|
+
apiKeyEnv: credentialRef ?? undefined,
|
|
313
|
+
piProvider: buildProvider({ route, name, baseUrl, models }),
|
|
314
|
+
streamIdleTimeoutMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
|
|
315
|
+
...IMAGE_DEFAULTS,
|
|
316
|
+
// This slice owns no retry policy and materializes no per-request cap; the
|
|
317
|
+
// entry-point task supplies those at registration time.
|
|
318
|
+
modelErrors: new Map(),
|
|
319
|
+
configuredMaxTokens: new Map(),
|
|
320
|
+
}));
|
|
321
|
+
providerIds.push(publicId);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return Object.freeze({
|
|
325
|
+
profiles,
|
|
326
|
+
routes: new Map(routeMap),
|
|
327
|
+
providerIds: Object.freeze(providerIds),
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The snapshot a route set would need in order for the *native* adapter to
|
|
333
|
+
* answer for it.
|
|
334
|
+
*
|
|
335
|
+
* Registration reads the adapter, not a plan: `LlmRuntime.prepareRoutes()` asks
|
|
336
|
+
* `providerInfo(route)` for the display name it will store and rejects the whole
|
|
337
|
+
* candidate set unless `info.id === route` and `info.name` is non-empty.
|
|
338
|
+
* `PiAiAdapter` answers from the snapshot it currently serves, falling back to
|
|
339
|
+
* the route id as the display name. So a route that is absent from the served
|
|
340
|
+
* snapshot would register under a placeholder name — or, with any adapter that
|
|
341
|
+
* refuses an unknown route, not register at all — while the plugin believed the
|
|
342
|
+
* operator's configured name had been published. Passing the candidate profiles
|
|
343
|
+
* here is what makes the name the operator sees the name the harness stores.
|
|
344
|
+
* @param {object[]} providers - validated provider list from one settings snapshot.
|
|
345
|
+
* @returns {Map<string, { id: string, name: string }>} display metadata per public id.
|
|
346
|
+
*/
|
|
347
|
+
export function expectedProviderInfo(providers) {
|
|
348
|
+
if (!Array.isArray(providers)) {
|
|
349
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'the provider list must be an array');
|
|
350
|
+
}
|
|
351
|
+
const expected = new Map();
|
|
352
|
+
for (const provider of providers) {
|
|
353
|
+
const publicId = typeof provider?.id === 'string' && provider.id !== ''
|
|
354
|
+
? provider.id
|
|
355
|
+
: null;
|
|
356
|
+
if (publicId === null || expected.has(publicId)) {
|
|
357
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'every provider entry must carry one non-empty id');
|
|
358
|
+
}
|
|
359
|
+
expected.set(publicId, {
|
|
360
|
+
id: publicId,
|
|
361
|
+
name: typeof provider.name === 'string' && provider.name !== '' ? provider.name : publicId,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return expected;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Check that one native registration agrees with the snapshot it was built from.
|
|
369
|
+
*
|
|
370
|
+
* Two reads of the same truth are compared here: the adapter's own answer for
|
|
371
|
+
* each route, and the route the plugin believes it registered. A mismatch is a
|
|
372
|
+
* refusal, never a repair, because both possible repairs are substitutions — a
|
|
373
|
+
* display name the operator did not choose, or a route the adapter does not
|
|
374
|
+
* serve. The retry policy is checked too: the harness captures exactly one
|
|
375
|
+
* policy per route, and a route handing it something unvalidated would land
|
|
376
|
+
* outside the native retry vocabulary the rest of the harness assumes.
|
|
377
|
+
* @param {object} reader - `{ providerInfo(route) -> object, providerRetryPolicy(route) -> unknown }`.
|
|
378
|
+
* @param {Map<string, string>} routes - public provider id -> native route id.
|
|
379
|
+
* @param {Map<string, { id: string, name: string }>} expected - from {@link expectedProviderInfo}.
|
|
380
|
+
* @returns {{ route: string, name: string }[]} the verified display metadata, in input order.
|
|
381
|
+
*/
|
|
382
|
+
export function verifyNativeRoutes(reader, routes, expected) {
|
|
383
|
+
if (reader === null || typeof reader !== 'object'
|
|
384
|
+
|| typeof reader.providerInfo !== 'function'
|
|
385
|
+
|| typeof reader.providerRetryPolicy !== 'function') {
|
|
386
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'the native adapter cannot describe the routes it was given');
|
|
387
|
+
}
|
|
388
|
+
if (!(routes instanceof Map) || !(expected instanceof Map)) {
|
|
389
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'routes and expected metadata must both be maps');
|
|
390
|
+
}
|
|
391
|
+
const verified = [];
|
|
392
|
+
for (const [publicId, route] of routes) {
|
|
393
|
+
if (typeof route !== 'string' || route === '') {
|
|
394
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} has no native route`);
|
|
395
|
+
}
|
|
396
|
+
const wanted = expected.get(publicId);
|
|
397
|
+
if (wanted === undefined) {
|
|
398
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `provider ${publicId} has no expected metadata`);
|
|
399
|
+
}
|
|
400
|
+
const info = reader.providerInfo(route);
|
|
401
|
+
if (info === null || typeof info !== 'object' || info.id !== route
|
|
402
|
+
|| typeof info.name !== 'string' || info.name === '') {
|
|
403
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, 'the native adapter does not describe every registered route', {
|
|
404
|
+
provider: publicId,
|
|
405
|
+
route,
|
|
406
|
+
described: info === null || typeof info !== 'object' ? null : { id: info.id ?? null, name: info.name ?? null },
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
if (info.name !== wanted.name) {
|
|
410
|
+
// The adapter reads its snapshot, not the candidate: a differing name means
|
|
411
|
+
// the snapshot serving this route is not the one the caller just built, so
|
|
412
|
+
// the registration that follows would publish a name nobody chose.
|
|
413
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `route ${route} is served from a snapshot that does not match this one`, {
|
|
414
|
+
provider: publicId,
|
|
415
|
+
route,
|
|
416
|
+
expectedName: wanted.name,
|
|
417
|
+
servedName: info.name,
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
try {
|
|
421
|
+
// The harness calls this synchronously too, and captures the result; doing
|
|
422
|
+
// it here proves the capture succeeds before any route is published.
|
|
423
|
+
reader.providerRetryPolicy(route);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
throw adapterError(ERROR_CODES.invalidSnapshot, `route ${route} cannot supply a retry policy`, {
|
|
426
|
+
provider: publicId,
|
|
427
|
+
route,
|
|
428
|
+
cause: typeof error?.code === 'string' ? error.code : null,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
verified.push({ route, name: info.name });
|
|
432
|
+
}
|
|
433
|
+
return verified;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* The credential store pi-ai is allowed to consult.
|
|
438
|
+
*
|
|
439
|
+
* This plugin stores no pi-ai-native credential: every route authenticates from
|
|
440
|
+
* the operator's `credentialRef`, resolved per request through the DSH seam and
|
|
441
|
+
* passed as the request-level override. Reading therefore reports "nothing
|
|
442
|
+
* stored" and writing is refused rather than silently mislaid — a write here
|
|
443
|
+
* could only mean the adapter was asked to log in, which this slice does not do.
|
|
444
|
+
* @returns {object} pi-ai `CredentialStore`.
|
|
445
|
+
*/
|
|
446
|
+
function createInertCredentialStore() {
|
|
447
|
+
return Object.freeze({
|
|
448
|
+
read: () => Promise.resolve(undefined),
|
|
449
|
+
list: () => Promise.resolve([]),
|
|
450
|
+
modify: () => Promise.reject(adapterError(ERROR_CODES.credentialUnavailable,
|
|
451
|
+
'this adapter keeps no pi-ai credential records; configure a credential reference instead')),
|
|
452
|
+
delete: () => Promise.reject(adapterError(ERROR_CODES.credentialUnavailable,
|
|
453
|
+
'this adapter keeps no pi-ai credential records; configure a credential reference instead')),
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* The auth context pi-ai is allowed to consult: neither the process environment
|
|
459
|
+
* nor the filesystem, so no ambient fallback can supply a credential.
|
|
460
|
+
* @returns {object} pi-ai `AuthContext`.
|
|
461
|
+
*/
|
|
462
|
+
function createStrictAuthContext() {
|
|
463
|
+
return Object.freeze({
|
|
464
|
+
env: () => Promise.resolve(undefined),
|
|
465
|
+
fileExists: () => Promise.resolve(false),
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Create the OpenAI-compatible native adapter slice.
|
|
471
|
+
*
|
|
472
|
+
* The returned API is a *management facade* around one stable `PiAiAdapter`
|
|
473
|
+
* instance, and the two halves exist for different consumers:
|
|
474
|
+
*
|
|
475
|
+
* * `prepareRoutes()` and `replace()` are what the plugin's route registry
|
|
476
|
+
* calls — building a snapshot and publishing it, with the prepared candidate
|
|
477
|
+
* handed back so the caller commits or rolls back inside its own synchronous
|
|
478
|
+
* section;
|
|
479
|
+
* * the object handed to `LlmRuntime.registerAdapter()` must be the
|
|
480
|
+
* `PiAiAdapter` itself, never this facade. The harness calls
|
|
481
|
+
* `providerInfo`/`providerRetryPolicy`/`prepareCall`/`stream` directly on
|
|
482
|
+
* whatever it was given, so passing the facade registers nothing that can
|
|
483
|
+
* be streamed from. `nativeAdapter()` is the only sanctioned way to obtain it.
|
|
484
|
+
* @param {object} options - `{ credentials }`, the injected DSH credential service
|
|
485
|
+
* (`resolve(ref) -> Promise<{ value, source } | undefined>`).
|
|
486
|
+
* @returns {{ prepareRoutes: Function, describes: Function, replace: Function, nativeAdapter: () => object, getAdapter: () => object, snapshot: () => object, expectedProviderInfo: Function }} API.
|
|
487
|
+
*/
|
|
488
|
+
export function createOpenAiAdapter(options) {
|
|
489
|
+
const credentials = options?.credentials;
|
|
490
|
+
if (credentials === null || typeof credentials !== 'object' || typeof credentials.resolve !== 'function') {
|
|
491
|
+
throw adapterError(ERROR_CODES.credentialServiceUnavailable,
|
|
492
|
+
'the DSH credential service is required to resolve provider credential references');
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
let current = EMPTY_SNAPSHOT;
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Resolve one route's configured credential reference.
|
|
499
|
+
*
|
|
500
|
+
* Called by the pi-ai adapter once per stream call, before any network I/O, and
|
|
501
|
+
* frozen for that call. A route with no reference is refused rather than served
|
|
502
|
+
* keyless: pi-ai's `openai-completions` implementation demands a key or an
|
|
503
|
+
* explicit Authorization header, and inventing either would be a hidden
|
|
504
|
+
* substitution. The resolved value is returned to pi-ai and nowhere else.
|
|
505
|
+
* @param {string} route - native route id.
|
|
506
|
+
* @param {object} profile - the snapshot profile for that route.
|
|
507
|
+
* @returns {Promise<string>} the credential value.
|
|
508
|
+
*/
|
|
509
|
+
async function resolveApiKey(route, profile) {
|
|
510
|
+
const ref = profile?.credentialRef ?? null;
|
|
511
|
+
if (ref === null) {
|
|
512
|
+
throw adapterError(ERROR_CODES.missingCredential,
|
|
513
|
+
`provider route ${route} names no credential reference; configure one before requesting`,
|
|
514
|
+
{ provider: route });
|
|
515
|
+
}
|
|
516
|
+
let resolved;
|
|
517
|
+
try {
|
|
518
|
+
resolved = await credentials.resolve(ref);
|
|
519
|
+
} catch (error) {
|
|
520
|
+
// The cause is bounded to its code: a provider may put anything, including
|
|
521
|
+
// the value, in a message.
|
|
522
|
+
throw adapterError(ERROR_CODES.credentialUnavailable,
|
|
523
|
+
`credential ${ref} for provider route ${route} could not be resolved`,
|
|
524
|
+
{ provider: route, reference: ref, cause: typeof error?.code === 'string' ? error.code : null });
|
|
525
|
+
}
|
|
526
|
+
const value = typeof resolved?.value === 'string' ? resolved.value : '';
|
|
527
|
+
if (value === '') {
|
|
528
|
+
throw adapterError(ERROR_CODES.missingCredential,
|
|
529
|
+
`credential ${ref} for provider route ${route} is not configured`,
|
|
530
|
+
{ provider: route, reference: ref });
|
|
531
|
+
}
|
|
532
|
+
return value;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const adapter = new PiAiAdapter({
|
|
536
|
+
// One read per operation: the whole snapshot the operation captured stays
|
|
537
|
+
// fixed for as long as that operation holds it.
|
|
538
|
+
profiles: () => current.profiles,
|
|
539
|
+
resolveApiKey,
|
|
540
|
+
auth: {
|
|
541
|
+
credentials: createInertCredentialStore(),
|
|
542
|
+
authContext: createStrictAuthContext(),
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Build the snapshot one candidate route set would serve, without publishing it.
|
|
548
|
+
*
|
|
549
|
+
* Every validation runs here, so a caller can prepare the served state and find
|
|
550
|
+
* out it is unusable before anything native observes either side.
|
|
551
|
+
* @param {object} input - `{ providers, routes }` for one validated settings snapshot.
|
|
552
|
+
* @returns {object} frozen snapshot.
|
|
553
|
+
*/
|
|
554
|
+
function prepare(input) {
|
|
555
|
+
return buildSnapshot(input);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Replace the served snapshot atomically.
|
|
560
|
+
* @param {object} input - `{ providers, routes }` for one validated settings snapshot.
|
|
561
|
+
* @returns {{ routes: Map<string, string>, providerIds: readonly string[] }} the served route set.
|
|
562
|
+
*/
|
|
563
|
+
function replace(input) {
|
|
564
|
+
const next = prepare(input);
|
|
565
|
+
current = next;
|
|
566
|
+
return { routes: new Map(next.routes), providerIds: [...next.providerIds] };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Prepare the snapshot for one route set, publish it, and hand the caller the
|
|
571
|
+
* *only* two operations that may follow: `commit()` and `rollback()`.
|
|
572
|
+
*
|
|
573
|
+
* The order is dictated by the native core, not by preference:
|
|
574
|
+
*
|
|
575
|
+
* 1. `buildSnapshot` validates the candidate provider list (fails: nothing
|
|
576
|
+
* changed anywhere).
|
|
577
|
+
* 2. The snapshot is published, because `registerAdapter()` — and its
|
|
578
|
+
* `replace()` — ask `providerInfo(route)` *synchronously* while validating
|
|
579
|
+
* the routes. Publishing after registration cannot work: the adapter would
|
|
580
|
+
* still be serving the previous generation when the harness reads it.
|
|
581
|
+
* 3. `verifyNativeRoutes` compares the adapter's answers against the snapshot
|
|
582
|
+
* that was just published. A disagreement is a refusal that restores the
|
|
583
|
+
* previous snapshot, so the adapter never keeps serving a generation the
|
|
584
|
+
* harness did not accept.
|
|
585
|
+
*
|
|
586
|
+
* The native commit is deliberately **not** run here. The caller performs it
|
|
587
|
+
* inside the same synchronous section (`createProviderRegistry`'s
|
|
588
|
+
* `commitRoutes()`), because only the caller knows what `registerAdapter()` or
|
|
589
|
+
* `replace()` threw, and because a yield between publishing and committing is
|
|
590
|
+
* exactly the window in which a second ensure could interleave: the adapter
|
|
591
|
+
* would be serving generation B while the core still held A. `commit()` simply
|
|
592
|
+
* adopts the candidate; `rollback()` is idempotent and restores the generation
|
|
593
|
+
* the candidate displaced, including after `commit()` has run (the core may
|
|
594
|
+
* have refused before publishing anything).
|
|
595
|
+
* @param {object} input - `{ providers, routes }` from one settings snapshot.
|
|
596
|
+
* @returns {{ routes: Map<string, string>, providers: { route: string, name: string }[], commit: () => void, rollback: () => void }} the prepared candidate.
|
|
597
|
+
*/
|
|
598
|
+
function prepareRoutes(input) {
|
|
599
|
+
const next = buildSnapshot(input);
|
|
600
|
+
const expected = expectedProviderInfo(input.providers);
|
|
601
|
+
const previous = current;
|
|
602
|
+
current = next;
|
|
603
|
+
let listed;
|
|
604
|
+
try {
|
|
605
|
+
listed = verifyNativeRoutes(adapter, next.routes, expected);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
current = previous;
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
return {
|
|
611
|
+
routes: new Map(next.routes),
|
|
612
|
+
providers: listed,
|
|
613
|
+
/** Adopt this generation. */
|
|
614
|
+
commit() {},
|
|
615
|
+
/**
|
|
616
|
+
* Restore the generation this candidate displaced. Safe to call once, twice,
|
|
617
|
+
* or after `commit()`: it only ever reinstates `previous`.
|
|
618
|
+
*/
|
|
619
|
+
rollback() {
|
|
620
|
+
current = previous;
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Count one shared verification between two generations.
|
|
627
|
+
*
|
|
628
|
+
* `prepareRoutes()` already refused a candidate whose adapter answers disagree
|
|
629
|
+
* with the published snapshot, so this is the caller's cheap assertion that the
|
|
630
|
+
* route set it is about to register is the one that was published — a
|
|
631
|
+
* comparison of sizes and bindings, never a second validation.
|
|
632
|
+
* @param {{ routes: Map<string, string> }} prepared - from {@link prepareRoutes}.
|
|
633
|
+
* @param {Map<string, string>} routes - the set the caller is registering.
|
|
634
|
+
* @returns {boolean} whether both describe the same mapping.
|
|
635
|
+
*/
|
|
636
|
+
function describes(prepared, routes) {
|
|
637
|
+
if (!(routes instanceof Map) || prepared.routes.size !== routes.size) return false;
|
|
638
|
+
for (const [publicId, route] of prepared.routes) {
|
|
639
|
+
if (routes.get(publicId) !== route) return false;
|
|
640
|
+
}
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
return {
|
|
645
|
+
prepareRoutes,
|
|
646
|
+
describes,
|
|
647
|
+
replace,
|
|
648
|
+
/**
|
|
649
|
+
* The `PiAiAdapter` itself — the only object that may be handed to
|
|
650
|
+
* `LlmRuntime.registerAdapter()`. Named twice on purpose: `nativeAdapter` is
|
|
651
|
+
* the correct call for new code, and `getAdapter` is kept because existing
|
|
652
|
+
* callers and tests use it.
|
|
653
|
+
* @returns {object} the native adapter instance.
|
|
654
|
+
*/
|
|
655
|
+
nativeAdapter: () => adapter,
|
|
656
|
+
getAdapter: () => adapter,
|
|
657
|
+
expectedProviderInfo,
|
|
658
|
+
/**
|
|
659
|
+
* Describe the currently served snapshot without exposing the mutable
|
|
660
|
+
* collections the adapter reads.
|
|
661
|
+
* @returns {{ routes: Map<string, string>, providerIds: readonly string[], models: ReadonlyMap<string, readonly string[]> }} copy.
|
|
662
|
+
*/
|
|
663
|
+
snapshot: () => {
|
|
664
|
+
const models = new Map();
|
|
665
|
+
for (const [route, profile] of current.profiles) {
|
|
666
|
+
models.set(route, profile.piProvider.getModels().map((model) => model.id));
|
|
667
|
+
}
|
|
668
|
+
return { routes: new Map(current.routes), providerIds: [...current.providerIds], models };
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
}
|