dsh-taskbridge 0.0.0-stage → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1122 @@
1
+ // User plane: the authenticated DSH surface an operator drives from the GUI.
2
+ //
3
+ // This half of the API is registered on the native authenticated channel
4
+ // (`ctx.connection.fetch`), so the harness applies its own Host/Origin fence and
5
+ // browser-cookie authentication *before* any handler here runs. That ordering is
6
+ // the reason this plane may issue authorization: a request that reaches it has
7
+ // already been proven to come from the operator's own browser session. This
8
+ // module therefore adds no authentication of its own — a duplicate header check
9
+ // here would be a second, weaker copy of a guarantee the carrier already made.
10
+ //
11
+ // Nothing in this plane can be reached over a bare HTTP route, and no route here
12
+ // accepts a caller-supplied identity.
13
+ //
14
+ // Registration constraints of `ctx.connection.fetch.register` (native
15
+ // `@deepseek-ai/dsh-client-connection`, 0.2.0-rc.2):
16
+ //
17
+ // * `path` is an absolute path that must resolve below `/api`; a path without
18
+ // that prefix is rejected by the harness.
19
+ // * `methods` may only contain `GET`, `HEAD` and `POST`.
20
+ // * `requestBody` is only `buffered` or `streaming` — there is no `none` mode,
21
+ // and the bridge always hands the handler a `Request` object.
22
+ // * routes are keyed by exact path, so the same path may be registered once.
23
+ // A second registration of one path throws.
24
+ //
25
+ // Consequences encoded below: every exact path appears exactly once, and a path
26
+ // that needs both a read and a write carries both methods and dispatches on
27
+ // `request.method` itself. All routes declare `buffered`: the bodies here are
28
+ // small JSON control documents, and streaming would buy nothing but an
29
+ // unbounded read.
30
+
31
+ import { publicSettings, resolveEffectiveConfig } from '../config/settings.js';
32
+ import { redactDeep } from '../config/redact.js';
33
+ import { describeCatalog } from '../model/routing.js';
34
+ import { listNativeProviderCatalog } from '../model/native-catalog.js';
35
+ import { discoverProviderModels } from '../model/discovery.js';
36
+ import { checkProviderConnectivity } from '../model/connectivity.js';
37
+ import { MAX_CREDENTIAL_VALUE_CHARS } from '../credentials/seam.js';
38
+ import { CODEX_ACTIONS, publicCodexStatus, runCodexAction } from '../codex/installer.js';
39
+ import { classifyError, HttpError, jsonResponse, readJsonRequest } from '../http/respond.js';
40
+
41
+ /**
42
+ * Route prefix, already below `/api` because the native exact-route registry
43
+ * validates that prefix itself. A full URL is therefore `/api/dsh-delegate/...`.
44
+ */
45
+ export const USER_PLANE_PREFIX = '/api/dsh-delegate';
46
+
47
+ /** Body mode every user-plane route declares. Only `buffered`/`streaming` exist. */
48
+ const BODY_MODE = 'buffered';
49
+
50
+ const GRANT_CONTROL_PATHS = new Set([
51
+ `${USER_PLANE_PREFIX}/connections`,
52
+ `${USER_PLANE_PREFIX}/connections/revoke`,
53
+ `${USER_PLANE_PREFIX}/grants`,
54
+ `${USER_PLANE_PREFIX}/grants/revoke`,
55
+ `${USER_PLANE_PREFIX}/authorization/revoke-all`,
56
+ ]);
57
+
58
+ /** Methods the native registry accepts on an exact fetch route. */
59
+ export const ALLOWED_METHODS = Object.freeze(['GET', 'HEAD', 'POST']);
60
+
61
+ /**
62
+ * Build the authenticated user-plane fetch routes.
63
+ * @param {object} deps - `settings`, `auth`, `engine`, `llm`, `logger`, `describeRuntime`.
64
+ * @returns {Array<{ path: string, methods: string[], requestBody: string, fetch: Function }>} routes.
65
+ */
66
+ export function userPlaneRoutes(deps) {
67
+ return [
68
+ {
69
+ path: `${USER_PLANE_PREFIX}/status`,
70
+ methods: ['GET'],
71
+ requestBody: BODY_MODE,
72
+ fetch: async () => {
73
+ return jsonResponse(200, {
74
+ ok: true,
75
+ delegation: deps.engine.posture(),
76
+ runtime: deps.describeRuntime?.(),
77
+ });
78
+ },
79
+ },
80
+ {
81
+ path: `${USER_PLANE_PREFIX}/native-providers`,
82
+ methods: ['GET'],
83
+ requestBody: BODY_MODE,
84
+ fetch: async () => {
85
+ const result = await listNativeProviderCatalog(deps.llm);
86
+ return jsonResponse(200, { ok: true, ...result });
87
+ },
88
+ },
89
+ {
90
+ path: `${USER_PLANE_PREFIX}/delegation`,
91
+ methods: ['POST'],
92
+ requestBody: BODY_MODE,
93
+ fetch: async (request) => {
94
+ const body = await readJsonRequest(request);
95
+ if (typeof body.enabled !== 'boolean') {
96
+ throw new HttpError(400, 'DELEGATION_SWITCH_INVALID', 'enabled must be a boolean');
97
+ }
98
+ // Closing the gate takes effect before disk I/O so no new task can slip
99
+ // through while the setting is being persisted; active tasks are aborted.
100
+ if (body.enabled === false) deps.engine.setDelegationEnabled(false);
101
+ const settings = await deps.settings.setDelegationEnabled(body.enabled);
102
+ if (body.enabled === true) deps.engine.setDelegationEnabled(settings.delegationEnabled);
103
+ return jsonResponse(200, { ok: true, delegation: deps.engine.posture() });
104
+ },
105
+ },
106
+ // One narrow route for the two silence thresholds.
107
+ //
108
+ // It is on the AUTHENTICATED operator plane, like every other settings write, and
109
+ // it is the only place a monitoring edit can enter. The MCP surface never gains a
110
+ // settings write: this route is reachable only from the operator's own page, and
111
+ // it cannot widen an authorization, a grant, a switch, a provider or an isolation
112
+ // mode — `setMonitoring` validates its own block and rewrites nothing else.
113
+ {
114
+ path: `${USER_PLANE_PREFIX}/monitoring`,
115
+ methods: ['POST'],
116
+ requestBody: BODY_MODE,
117
+ fetch: async (request) => {
118
+ const body = await readJsonRequest(request);
119
+ if (body.monitoring === undefined) {
120
+ throw new HttpError(400, 'MONITORING_MISSING', 'a monitoring block is required');
121
+ }
122
+ // `setMonitoring` refuses an invalid block with a `MONITORING_*` code. That
123
+ // code is the validator's, and the shared error translator would render an
124
+ // unlisted code as a 500; a refused TIMER is the caller's mistake, so it is
125
+ // re-thrown here as a 400 that keeps the original code and its field details.
126
+ // Nothing is written when this throws.
127
+ let committed;
128
+ try {
129
+ committed = await deps.settings.setMonitoring(body.monitoring);
130
+ } catch (error) {
131
+ const code = typeof error?.code === 'string' ? error.code : '';
132
+ if (!code.startsWith('MONITORING_')) throw error;
133
+ throw new HttpError(400, code, String(error?.message ?? 'the monitoring block is invalid'), error?.details ?? {});
134
+ }
135
+ return jsonResponse(200, {
136
+ ok: true,
137
+ monitoring: { ...committed.monitoring },
138
+ // The whole document is returned too, because the page adopts it after a
139
+ // narrow save and must not have to issue a second read to stay truthful.
140
+ settings: publicSettings(committed),
141
+ });
142
+ },
143
+ },
144
+ // One path, two methods. `GET` reads the stored document, `POST` replaces it.
145
+ // There is deliberately no `PUT`: the native registry cannot express it.
146
+ {
147
+ path: `${USER_PLANE_PREFIX}/settings`,
148
+ methods: ['GET', 'POST'],
149
+ requestBody: BODY_MODE,
150
+ fetch: async (request) => {
151
+ const method = String(request.method ?? 'GET').toUpperCase();
152
+ if (method === 'GET') {
153
+ const settings = await deps.settings.read();
154
+ return jsonResponse(200, {
155
+ ok: true,
156
+ settings: publicSettings(settings),
157
+ // Stated in the payload so a client cannot infer it wrongly.
158
+ secrets: { stored: 'credential-seam-only', values_returned: false },
159
+ });
160
+ }
161
+ if (method !== 'POST') return methodRefusal(request, ['GET', 'POST']);
162
+ const body = await readJsonRequest(request);
163
+ if (body.settings === undefined) {
164
+ throw new HttpError(400, 'SETTINGS_MISSING', 'a settings document is required');
165
+ }
166
+ const committed = await deps.settings.replaceConfiguration(body.settings);
167
+ return jsonResponse(200, { ok: true, settings: publicSettings(committed) });
168
+ },
169
+ },
170
+ {
171
+ path: `${USER_PLANE_PREFIX}/catalog`,
172
+ methods: ['POST'],
173
+ requestBody: BODY_MODE,
174
+ fetch: async (request) => {
175
+ const body = await readJsonRequest(request);
176
+ const settings = await deps.settings.read();
177
+ // Every row must name the route the harness actually serves. A catalog
178
+ // built from public profile ids alone would describe routes that were
179
+ // never registered — and would silently agree with an *ambient* route of
180
+ // the same name (`relay`, `workbuddy`) that this plugin does not own.
181
+ const resolved = await resolveRoutesForCatalog(deps, settings);
182
+ const catalog = await describeCatalog(deps, settings.providers, {
183
+ signal: body.signal,
184
+ routes: resolved.routes,
185
+ });
186
+ const effective = settings.providers.length === 0
187
+ ? null
188
+ : resolveEffectiveConfig(settings, { projectPath: body.projectPath ?? null });
189
+ return jsonResponse(200, {
190
+ ok: true,
191
+ catalog,
192
+ effective,
193
+ // `null` when every configured provider was mapped. A non-null value
194
+ // means no row can be trusted as routable, and says why.
195
+ registration: resolved.error,
196
+ secrets: { values_returned: false },
197
+ });
198
+ },
199
+ },
200
+ // One path, two methods: list connections, or issue a new one.
201
+ {
202
+ path: `${USER_PLANE_PREFIX}/connections`,
203
+ methods: ['GET', 'POST'],
204
+ requestBody: BODY_MODE,
205
+ fetch: async (request) => {
206
+ const method = String(request.method ?? 'GET').toUpperCase();
207
+ if (method === 'GET') {
208
+ return jsonResponse(200, { ok: true, connections: deps.auth.listConnections() });
209
+ }
210
+ if (method !== 'POST') return methodRefusal(request, ['GET', 'POST']);
211
+ const body = await readJsonRequest(request);
212
+ const issued = deps.auth.issueConnection({
213
+ label: body.label,
214
+ peer: { address: 'operator-session' },
215
+ });
216
+ // The token is returned exactly once. It is never stored in the clear and
217
+ // never appears in a later listing.
218
+ return jsonResponse(201, {
219
+ ok: true,
220
+ connection: { connectionId: issued.connectionId, label: issued.label, createdAt: issued.createdAt },
221
+ token: issued.token,
222
+ tokenReturnedOnce: true,
223
+ });
224
+ },
225
+ },
226
+ {
227
+ path: `${USER_PLANE_PREFIX}/connections/revoke`,
228
+ methods: ['POST'],
229
+ requestBody: BODY_MODE,
230
+ fetch: async (request) => {
231
+ const body = await readJsonRequest(request);
232
+ if (typeof body.connectionId !== 'string') {
233
+ throw new HttpError(400, 'CONNECTION_ID_REQUIRED', 'connectionId is required');
234
+ }
235
+ const revoked = deps.auth.revokeConnection(body.connectionId);
236
+ return jsonResponse(200, { ok: true, grantsRevoked: revoked });
237
+ },
238
+ },
239
+ // One path, two methods: list grants for a connection, or issue a grant.
240
+ {
241
+ path: `${USER_PLANE_PREFIX}/grants`,
242
+ methods: ['GET', 'POST'],
243
+ requestBody: BODY_MODE,
244
+ fetch: async (request) => {
245
+ const method = String(request.method ?? 'GET').toUpperCase();
246
+ if (method === 'GET') {
247
+ const url = new URL(request.url, 'http://localhost');
248
+ const connectionId = url.searchParams.get('connectionId');
249
+ if (connectionId === null) {
250
+ throw new HttpError(400, 'CONNECTION_ID_REQUIRED', 'connectionId query parameter is required');
251
+ }
252
+ return jsonResponse(200, { ok: true, grants: deps.auth.listGrants(connectionId) });
253
+ }
254
+ if (method !== 'POST') return methodRefusal(request, ['GET', 'POST']);
255
+ const body = await readJsonRequest(request);
256
+ const settings = await deps.settings.read();
257
+ const ttl = body.kind === 'session'
258
+ ? settings.authorization.sessionGrantTtlSeconds
259
+ : settings.authorization.taskGrantTtlSeconds;
260
+ const grant = deps.auth.issueGrant(body.connectionId, {
261
+ kind: body.kind,
262
+ workspacePath: body.workspacePath,
263
+ ttlSeconds: body.ttlSeconds ?? ttl,
264
+ overrides: body.overrides ?? null,
265
+ });
266
+ return jsonResponse(201, { ok: true, grant });
267
+ },
268
+ },
269
+ {
270
+ path: `${USER_PLANE_PREFIX}/grants/revoke`,
271
+ methods: ['POST'],
272
+ requestBody: BODY_MODE,
273
+ fetch: async (request) => {
274
+ const body = await readJsonRequest(request);
275
+ if (typeof body.grantId !== 'string') {
276
+ throw new HttpError(400, 'GRANT_ID_REQUIRED', 'grantId is required');
277
+ }
278
+ const grant = deps.auth.revokeGrant({ grantId: body.grantId, allowOperator: true });
279
+ return jsonResponse(200, { ok: true, grant });
280
+ },
281
+ },
282
+ {
283
+ path: `${USER_PLANE_PREFIX}/authorization/revoke-all`,
284
+ methods: ['POST'],
285
+ requestBody: BODY_MODE,
286
+ fetch: async () => {
287
+ const revoked = deps.auth.revokeAll();
288
+ return jsonResponse(200, { ok: true, grantsRevoked: revoked });
289
+ },
290
+ },
291
+ // ---- task records ------------------------------------------------------
292
+ // The operator's task list is the *live engine plus the durable archive*.
293
+ //
294
+ // A restart begins with an empty engine (that is the whole point of the
295
+ // execution plane's restart story), so a user-plane list built from
296
+ // `engine.list()` alone would report "no tasks" while the history document on
297
+ // disk still holds every finished job. These two read routes therefore
298
+ // project `HistoryStore.load()` alongside the engine, with three rules:
299
+ //
300
+ // * live wins on collision. A record the engine still holds under the same
301
+ // `taskId` is returned unchanged, so an in-process task can never be
302
+ // replaced by its own stored copy (which lags the engine: history is
303
+ // written at terminal time, while the engine view carries prompt,
304
+ // acceptance and later bookkeeping). Archived records are shallow copies
305
+ // of detached loaded views, so nothing here writes through to the store.
306
+ // * archived is a marker, not a state. A persisted-only record is returned
307
+ // with `archived: true` and keeps the state the store normalized it to —
308
+ // `pending`/`running` already became `interrupted`
309
+ // (`error.code = JOB_INTERRUPTED_RESTART`) at load time, and that
310
+ // normalization is consumed as-is, never re-derived or "upgraded" here.
311
+ // * archived records are sealed. Nothing in this plane may create a
312
+ // controller, an agent, a workspace lease, an authorization or a token
313
+ // from them, so `/tasks/cancel` refuses an archived id outright rather
314
+ // than letting the engine's own `JOB_NOT_OK` path decide, and the
315
+ // projection is read-only in both directions: it neither dispatches work
316
+ // nor rewrites the document.
317
+ //
318
+ // A history document that cannot be read is a *visible refusal*, never an
319
+ // empty success: answering `tasks: []` for an unreadable archive would tell
320
+ // an operator that nothing ever ran.
321
+ //
322
+ // This is the authenticated user plane only. The execution plane's
323
+ // `/tasks`, `/tasks/get` and `/tasks/cancel` are untouched: an external
324
+ // connection still sees exactly its own in-memory tasks, and a new
325
+ // connection never sees another connection's or a previous process's work.
326
+ {
327
+ path: `${USER_PLANE_PREFIX}/tasks`,
328
+ methods: ['GET'],
329
+ requestBody: BODY_MODE,
330
+ fetch: async (request) => {
331
+ const url = new URL(request.url, 'http://localhost');
332
+ const connectionId = url.searchParams.get('connectionId') ?? undefined;
333
+ const { tasks, history } = await readTaskRecords(deps, { connectionId });
334
+ return jsonResponse(200, {
335
+ ok: true,
336
+ tasks,
337
+ // Stated, not implied: a client must be able to tell a complete list
338
+ // from one whose archive section could not be read.
339
+ history,
340
+ });
341
+ },
342
+ },
343
+ {
344
+ path: `${USER_PLANE_PREFIX}/tasks/get`,
345
+ methods: ['POST'],
346
+ requestBody: BODY_MODE,
347
+ fetch: async (request) => {
348
+ const body = await readJsonRequest(request);
349
+ const taskId = typeof body.taskId === 'string' ? body.taskId.trim() : '';
350
+ if (taskId === '') {
351
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
352
+ }
353
+ const live = engineRecord(deps, taskId);
354
+ if (live !== null) {
355
+ return jsonResponse(200, {
356
+ ok: true,
357
+ task: { ...live, archived: false, live: true },
358
+ history: historyStatus(null),
359
+ });
360
+ }
361
+ // Only the engine's own "no such task" may fall through to the archive.
362
+ // Any other engine failure (disposed, internal) is a real failure and is
363
+ // propagated unchanged: reporting it as "archived task not found" would
364
+ // hide a broken engine behind a 404.
365
+ const { jobs } = await loadArchive(deps);
366
+ const archived = jobs.find((job) => job.taskId === taskId) ?? null;
367
+ if (archived === null) {
368
+ throw new HttpError(404, 'JOB_TASK_NOT_FOUND', 'no such task', { taskId });
369
+ }
370
+ // The prompt is not in the archive by design (`HistoryStore` never stores
371
+ // it), so the response says so rather than leaving a silent gap.
372
+ return jsonResponse(200, {
373
+ ok: true,
374
+ task: { ...archivedRecord(archived), prompt: null, promptArchived: false },
375
+ history: historyStatus({ available: true, archived: jobs.length }),
376
+ });
377
+ },
378
+ },
379
+ {
380
+ path: `${USER_PLANE_PREFIX}/tasks/cancel`,
381
+ methods: ['POST'],
382
+ requestBody: BODY_MODE,
383
+ fetch: async (request) => {
384
+ const body = await readJsonRequest(request);
385
+ const taskId = typeof body.taskId === 'string' ? body.taskId.trim() : '';
386
+ if (taskId === '') {
387
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
388
+ }
389
+ // An archived task has no run behind it: no controller, no leases and no
390
+ // authorization survive a restart, so "cancel" could only mark a record.
391
+ // The live engine is consulted first (it throws its own not-found), and
392
+ // an id that exists only in the archive is refused explicitly.
393
+ const live = engineRecord(deps, taskId);
394
+ if (live === null) {
395
+ const { jobs } = await loadArchive(deps);
396
+ if (jobs.some((job) => job.taskId === taskId)) {
397
+ throw new HttpError(
398
+ 409,
399
+ 'JOB_ARCHIVED_TASK',
400
+ 'the task exists only in durable history; it has no live run to cancel and was not resubmitted',
401
+ { taskId, archived: true },
402
+ );
403
+ }
404
+ }
405
+ const task = await deps.engine.cancel(taskId, 'operator');
406
+ return jsonResponse(200, { ok: true, task });
407
+ },
408
+ },
409
+
410
+ // ---- provider model list -----------------------------------------------
411
+ // Remote discovery: one authenticated `GET <provider baseUrl>/models` against
412
+ // the provider the operator selected, using only *that profile's* credential
413
+ // reference, resolved through the DSH gateway for this request alone.
414
+ //
415
+ // This is not a native catalog read. An empty configured provider has no
416
+ // models to enumerate, and no native route is needed to ask its API what it
417
+ // serves — so discovery works whether or not the native routes registered,
418
+ // and a failure here is reported as a discovery failure, never as a fake
419
+ // native-list success. `/catalog` remains the surface that reports what the
420
+ // harness can actually resolve for the configured models.
421
+ //
422
+ // `POST` rather than `GET ?providerId=`: the request carries an operator action
423
+ // (spend one upstream call with their key), it must never be prefetched or
424
+ // cached by an intermediary, and the native registry cannot express `PUT`.
425
+ {
426
+ path: `${USER_PLANE_PREFIX}/models`,
427
+ methods: ['POST'],
428
+ requestBody: BODY_MODE,
429
+ fetch: async (request) => {
430
+ const body = await readJsonRequest(request);
431
+ const { provider } = await requireProvider(deps, body.providerId, 'models');
432
+ // The route-shaped facts, reported without touching the native registry:
433
+ // `route` is a *configured* resolution hint (the mapped native route, or
434
+ // null when there is none), never the bare profile id, so no caller can
435
+ // read it as "this list is routable".
436
+ const route = await configuredRoute(deps, provider.id);
437
+ const outcome = await discoverProviderModels({
438
+ provider,
439
+ credentials: deps.credentials,
440
+ ...(deps.fetchImpl === undefined ? {} : { fetchImpl: deps.fetchImpl }),
441
+ ...(body.signal === undefined || body.signal === null ? {} : { signal: body.signal }),
442
+ });
443
+ if (outcome.ok !== true) {
444
+ // A 200 with an explicit diagnosis: the operator keeps their manual
445
+ // configuration, and the empty list is explained rather than implied.
446
+ return jsonResponse(200, {
447
+ ok: true,
448
+ providerId: provider.id,
449
+ route,
450
+ models: [],
451
+ source: 'remote',
452
+ discovery: {
453
+ attempted: true,
454
+ failed: true,
455
+ code: outcome.diagnosis?.code ?? 'DISCOVERY_UNKNOWN',
456
+ message: outcome.diagnosis?.message ?? 'the model list could not be retrieved',
457
+ details: outcome.diagnosis?.details ?? {},
458
+ },
459
+ error: outcome.diagnosis ?? null,
460
+ registration: null,
461
+ secrets: { values_returned: false },
462
+ });
463
+ }
464
+ return jsonResponse(200, {
465
+ ok: true,
466
+ providerId: provider.id,
467
+ route,
468
+ models: outcome.models,
469
+ // Named so a caller never has to infer where ids came from.
470
+ source: 'remote',
471
+ discovery: {
472
+ attempted: true,
473
+ failed: false,
474
+ code: null,
475
+ message: null,
476
+ details: outcome.facts,
477
+ // The one thing a list cannot prove, stated instead of implied.
478
+ note: 'a model listing does not establish reasoning-effort support',
479
+ },
480
+ error: null,
481
+ registration: null,
482
+ secrets: { values_returned: false },
483
+ });
484
+ },
485
+ },
486
+
487
+ // ---- credential seam ---------------------------------------------------
488
+ // Three exact paths, because each is a distinct operator action with a
489
+ // distinct refusal. None of them can read a value back: the seam's
490
+ // `CredentialInfo` has no slot for one, and no handler below adds one.
491
+ {
492
+ path: `${USER_PLANE_PREFIX}/credentials/status`,
493
+ methods: ['POST'],
494
+ requestBody: BODY_MODE,
495
+ fetch: async (request) => {
496
+ const body = await readJsonRequest(request);
497
+ const { provider } = await requireProvider(deps, body.providerId, 'credential status');
498
+ const reference = requireCredentialRef(provider);
499
+ const credential = await requireSeam(deps).describe(reference);
500
+ return jsonResponse(200, {
501
+ ok: true,
502
+ providerId: provider.id,
503
+ reference,
504
+ credential,
505
+ secrets: { values_returned: false },
506
+ });
507
+ },
508
+ },
509
+ {
510
+ path: `${USER_PLANE_PREFIX}/credentials/set`,
511
+ methods: ['POST'],
512
+ requestBody: BODY_MODE,
513
+ fetch: async (request) => {
514
+ const body = await readJsonRequest(request);
515
+ const { provider } = await requireProvider(deps, body.providerId, 'credential write');
516
+ const reference = requireCredentialRef(provider);
517
+ const seam = requireSeam(deps);
518
+ // Bounds are checked here as well as inside the gateway. A route that
519
+ // delegated every check to an injected object would be trusting whatever
520
+ // was injected; the boundary that accepts the secret is the boundary that
521
+ // must refuse a bad one.
522
+ const value = requireCredentialValue(body.value, reference);
523
+ // The literal is forwarded and dropped here. It is never normalized
524
+ // (trimming would silently store a different secret), never echoed, never
525
+ // logged, and never placed in a refusal detail.
526
+ await seam.set(reference, value);
527
+ const credential = await seam.describe(reference);
528
+ // The value itself is not read back even to confirm the write: `describe`
529
+ // is the seam's own answer to "is it configured now".
530
+ return jsonResponse(200, {
531
+ ok: true,
532
+ providerId: provider.id,
533
+ reference,
534
+ credential,
535
+ secrets: { values_returned: false },
536
+ });
537
+ },
538
+ },
539
+ {
540
+ path: `${USER_PLANE_PREFIX}/credentials/unset`,
541
+ methods: ['POST'],
542
+ requestBody: BODY_MODE,
543
+ fetch: async (request) => {
544
+ const body = await readJsonRequest(request);
545
+ const { provider } = await requireProvider(deps, body.providerId, 'credential removal');
546
+ const reference = requireCredentialRef(provider);
547
+ const seam = requireSeam(deps);
548
+ await seam.unset(reference);
549
+ const credential = await seam.describe(reference);
550
+ return jsonResponse(200, {
551
+ ok: true,
552
+ providerId: provider.id,
553
+ reference,
554
+ credential,
555
+ secrets: { values_returned: false },
556
+ });
557
+ },
558
+ },
559
+
560
+ // ---- Codex integration -------------------------------------------------
561
+ // Two routes, both on the authenticated operator plane because both are
562
+ // operator actions about a *host-side* file (Codex's own config), not about
563
+ // this plugin's document.
564
+ //
565
+ // GET /codex — read-only diagnosis. It never writes, and it is the only
566
+ // way the page learns what is installed.
567
+ // POST /codex — one explicit action: `install`, `repair` or `remove`.
568
+ //
569
+ // Nothing here runs on plugin load, and no action enables the delegation
570
+ // switch: installing a Codex agent is a separate decision from authorizing
571
+ // local dispatch, and the response reports the switch state without changing it.
572
+ {
573
+ path: `${USER_PLANE_PREFIX}/codex`,
574
+ methods: ['GET', 'POST'],
575
+ requestBody: BODY_MODE,
576
+ fetch: async (request) => {
577
+ const method = String(request.method ?? 'GET').toUpperCase();
578
+ if (method === 'GET') {
579
+ const outcome = await runCodexIntegration(deps, 'status');
580
+ return jsonResponse(200, { ok: true, ...outcome });
581
+ }
582
+ if (method !== 'POST') return methodRefusal(request, ['GET', 'POST']);
583
+ const body = await readJsonRequest(request);
584
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
585
+ if (!CODEX_ACTIONS.includes(action) || action === 'status') {
586
+ throw new HttpError(
587
+ 400,
588
+ 'CODEX_ACTION_INVALID',
589
+ `action must be one of ${CODEX_ACTIONS.filter((entry) => entry !== 'status').join(', ')}`,
590
+ { allowed: CODEX_ACTIONS.filter((entry) => entry !== 'status') },
591
+ );
592
+ }
593
+ const outcome = await runCodexIntegration(deps, action);
594
+ deps.logger?.info?.('dsh-delegate: Codex integration action applied', {
595
+ action,
596
+ changed: outcome.changed,
597
+ refused: outcome.refused.map((entry) => entry.code),
598
+ });
599
+ return jsonResponse(200, { ok: true, ...outcome });
600
+ },
601
+ },
602
+
603
+ // ---- layered connectivity ---------------------------------------------
604
+ // One provider per request. The report is the four-layer structure documented
605
+ // in `docs/native-integration-audit.md`; a layer that was not attempted is
606
+ // `ok: null`, never `ok: true`.
607
+ {
608
+ path: `${USER_PLANE_PREFIX}/connectivity`,
609
+ methods: ['POST'],
610
+ requestBody: BODY_MODE,
611
+ fetch: async (request) => {
612
+ const body = await readJsonRequest(request);
613
+ // An unknown provider is a 404 here, not a report: a report would need a
614
+ // profile to describe and would otherwise be a manufactured green row.
615
+ const { provider } = await requireProvider(deps, body.providerId, 'the connectivity check');
616
+ const report = await checkProviderConnectivity(deps, {
617
+ providerId: provider.id,
618
+ model: body.model,
619
+ reasoningEffort: body.reasoningEffort,
620
+ });
621
+ return jsonResponse(200, {
622
+ ok: true,
623
+ providerId: report.providerId,
624
+ // Redacted even though every producer here is already careful: this is
625
+ // the one response an operator pastes into a bug report.
626
+ report: redactDeep(report),
627
+ secrets: { values_returned: false },
628
+ });
629
+ },
630
+ },
631
+ ];
632
+ }
633
+
634
+ // ---- Codex integration ------------------------------------------------------
635
+
636
+ /**
637
+ * Run one Codex integration action and shape the answer for the settings page.
638
+ *
639
+ * The three facts an operator needs are kept apart on purpose, because they fail
640
+ * independently and mean different things:
641
+ *
642
+ * * `agent` — the custom agent file exists (and is ours);
643
+ * * `mcp` — Codex is configured to launch this package's stdio MCP server;
644
+ * * `switch` — the DSH local-call switch, which this route never changes.
645
+ *
646
+ * A `status` read is refused for a bad `CODEX_HOME` rather than silently falling
647
+ * back to the default: reporting on the wrong directory would be worse than
648
+ * saying that the configured one is unusable.
649
+ * @param {object} deps - dependency object with an optional `codex` seam.
650
+ * @param {string} action - `status`, `install`, `repair` or `remove`.
651
+ * @returns {Promise<object>} outcome with `changed`, `refused`, `codex` and `switch`.
652
+ * @throws {HttpError} `CODEX_INTEGRATION_UNAVAILABLE` when no seam is wired.
653
+ */
654
+ async function runCodexIntegration(deps, action) {
655
+ const seam = deps.codex;
656
+ if (seam === null || seam === undefined || typeof seam.run !== 'function' || typeof seam.status !== 'function') {
657
+ throw new HttpError(
658
+ 503,
659
+ 'CODEX_INTEGRATION_UNAVAILABLE',
660
+ 'this host does not expose the Codex integration, so nothing can be installed or reported',
661
+ );
662
+ }
663
+ let outcome;
664
+ try {
665
+ outcome = action === 'status' ? await seam.status() : await seam.run(action);
666
+ } catch (error) {
667
+ const code = typeof error?.code === 'string' ? error.code : 'CODEX_INTEGRATION_FAILED';
668
+ // The installer's own refusals carry a bounded details object; a filesystem
669
+ // error does not, and its message may contain a path but never a secret.
670
+ throw new HttpError(
671
+ code === 'CODEX_HOME_INVALID' ? 400 : code === 'CODEX_CONFIG_UNSUPPORTED' ? 409 : 500,
672
+ code,
673
+ typeof error?.message === 'string' ? error.message : 'the Codex integration action failed',
674
+ error?.details !== undefined && error.details !== null ? error.details : {},
675
+ );
676
+ }
677
+ const switchPosture = typeof deps.engine?.posture === 'function' ? deps.engine.posture() : null;
678
+ return {
679
+ action,
680
+ changed: Array.isArray(outcome?.changed) ? outcome.changed : [],
681
+ refused: Array.isArray(outcome?.refused) ? outcome.refused : [],
682
+ // `publicCodexStatus` drops the internal `agent.expect` bytes, which exist only
683
+ // for the installer's own compare-before-write step.
684
+ codex: redactDeep(publicCodexStatus(outcome?.status ?? {})),
685
+ // Reported, never written: installing the agent must not authorize dispatch.
686
+ switch: {
687
+ authorized: switchPosture?.authorized === true,
688
+ mode: switchPosture?.mode ?? 'switch',
689
+ reason: switchPosture?.reason ?? null,
690
+ changedByThisAction: false,
691
+ },
692
+ };
693
+ }
694
+
695
+ // ---- task-record projection (live engine + durable archive) ----------------
696
+
697
+ /**
698
+ * Read the durable archive, or throw an `HttpError` that says so.
699
+ *
700
+ * Three postures, deliberately distinct:
701
+ *
702
+ * * no store injected — the archive is simply absent, and the response says
703
+ * so instead of implying that nothing was ever persisted;
704
+ * * an empty document — a real, successful empty archive;
705
+ * * a refused document — a 503 carrying the store's own code
706
+ * (`HISTORY_MALFORMED`, `HISTORY_UNREADABLE`, …). Never an empty success:
707
+ * `load()` rejects for exactly this case, and swallowing it would report
708
+ * "your tasks are gone" for "this file cannot be read".
709
+ * @param {object} deps - dependency object with an optional `history` store.
710
+ * @returns {Promise<{ available: boolean, jobs: object[], code: string | null }>} archive state.
711
+ * @throws {HttpError} `JOB_HISTORY_UNREADABLE` when the document is refused.
712
+ */
713
+ async function loadArchive(deps) {
714
+ const store = deps.history;
715
+ if (store === null || store === undefined || typeof store.load !== 'function') {
716
+ return { available: false, jobs: [], code: 'HISTORY_UNAVAILABLE' };
717
+ }
718
+ try {
719
+ const jobs = await store.load();
720
+ return { available: true, jobs: Array.isArray(jobs) ? jobs : [], code: null };
721
+ } catch (error) {
722
+ deps.logger?.warn?.('dsh-delegate: durable task history could not be read', error?.code ?? 'HISTORY_UNREADABLE');
723
+ throw new HttpError(
724
+ 503,
725
+ 'JOB_HISTORY_UNREADABLE',
726
+ 'the durable task history could not be read, so archived tasks are not shown',
727
+ {
728
+ // A history refusal is a code, not a secret; the document text is not.
729
+ cause: typeof error?.code === 'string' ? error.code : 'HISTORY_UNREADABLE',
730
+ },
731
+ );
732
+ }
733
+ }
734
+
735
+ /**
736
+ * Describe the archive section of a task response.
737
+ * @param {{ available: boolean, archived: number, reason?: string } | null} status - archive state, or null when it was not read.
738
+ * @returns {{ available: boolean, archived: number, unreadable: boolean, reason?: string }} bounded status.
739
+ */
740
+ function historyStatus(status) {
741
+ if (status === null || status === undefined) return { available: false, archived: 0, unreadable: false };
742
+ return status.available
743
+ ? { available: true, archived: status.archived, unreadable: false }
744
+ : { available: false, archived: 0, unreadable: false, reason: status.reason ?? 'HISTORY_UNAVAILABLE' };
745
+ }
746
+
747
+ /**
748
+ * The engine's own view of one task, or `null` when the engine does not know it.
749
+ *
750
+ * Only the engine's not-found code means "not live". Everything else — a disposed
751
+ * engine, an internal failure — is re-thrown, because a broken engine must not be
752
+ * mistaken for an empty one and then papered over by the archive.
753
+ * @param {object} deps - dependency object with `engine`.
754
+ * @param {string} taskId - task id.
755
+ * @returns {object | null} live view, including the prompt for the operator.
756
+ */
757
+ function engineRecord(deps, taskId) {
758
+ try {
759
+ return deps.engine.get(taskId, { includePrompt: true });
760
+ } catch (error) {
761
+ if (error?.code === 'JOB_TASK_NOT_FOUND') return null;
762
+ throw error;
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Mark a stored record as archive-only without touching the stored object.
768
+ * @param {object} job - detached view returned by `HistoryStore.load()`.
769
+ * @returns {object} a new object; nested blocks are the store's already-redacted ones.
770
+ */
771
+ function archivedRecord(job) {
772
+ return {
773
+ ...job,
774
+ // No live run exists, so there is nothing further to withhold or replay.
775
+ archived: true,
776
+ live: false,
777
+ };
778
+ }
779
+
780
+ /**
781
+ * Merge live engine views with the durable archive into one newest-first list.
782
+ *
783
+ * Ordering is by creation time only; the task id breaks ties so the list is a
784
+ * stable total order rather than dependent on merge order. `connectionId`
785
+ * filtering is applied to both halves with the same equality rule the engine's
786
+ * own `list()` uses, so the user plane cannot disagree with the execution plane
787
+ * about which records belong to a connection.
788
+ * @param {object} deps - dependency object with `engine` and optional `history`.
789
+ * @param {object} [options] - `connectionId` to filter on.
790
+ * @returns {Promise<{ tasks: object[], history: object }>} merged list and archive status.
791
+ */
792
+ async function readTaskRecords(deps, options = {}) {
793
+ const filtered = options.connectionId !== undefined && options.connectionId !== null;
794
+ const live = deps.engine.list(filtered ? { connectionId: options.connectionId } : {});
795
+ const archive = await loadArchive(deps);
796
+ const liveIds = new Set(live.map((task) => task.taskId));
797
+
798
+ const merged = [];
799
+ for (const task of live) {
800
+ // Live wins: an in-process record is the newer truth for its own id.
801
+ merged.push({ ...task, archived: false, live: true });
802
+ }
803
+ for (const job of archive.jobs) {
804
+ if (liveIds.has(job.taskId)) continue;
805
+ if (filtered && job.connectionId !== options.connectionId) continue;
806
+ merged.push(archivedRecord(job));
807
+ }
808
+ merged.sort(compareNewestFirst);
809
+
810
+ return {
811
+ tasks: merged,
812
+ history: {
813
+ available: archive.available,
814
+ archived: archive.available ? archive.jobs.length : 0,
815
+ unreadable: false,
816
+ ...(archive.available ? {} : { reason: archive.code }),
817
+ },
818
+ };
819
+ }
820
+
821
+ /**
822
+ * Newest first by creation time, then by id.
823
+ * @param {object} a - first record.
824
+ * @param {object} b - second record.
825
+ * @returns {number} sort order.
826
+ */
827
+ function compareNewestFirst(a, b) {
828
+ const left = Number.isFinite(a?.createdAt) ? a.createdAt : -Infinity;
829
+ const right = Number.isFinite(b?.createdAt) ? b.createdAt : -Infinity;
830
+ if (left !== right) return right < left ? -1 : 1;
831
+ const leftId = typeof a?.taskId === 'string' ? a.taskId : '';
832
+ const rightId = typeof b?.taskId === 'string' ? b.taskId : '';
833
+ if (leftId === rightId) return 0;
834
+ return leftId < rightId ? -1 : 1;
835
+ }
836
+
837
+ /**
838
+ * Resolve one provider profile from the current settings document.
839
+ *
840
+ * Every route that names a provider starts here, so "a provider id that is not
841
+ * configured" is one refusal with one code everywhere instead of three subtly
842
+ * different behaviours.
843
+ * @param {object} deps - dependency object with `settings`.
844
+ * @param {unknown} providerId - caller-supplied profile id.
845
+ * @param {string} operation - what was being attempted, for the message.
846
+ * @returns {Promise<{ settings: object, provider: object }>} the profile and the snapshot it came from.
847
+ */
848
+ async function requireProvider(deps, providerId, operation) {
849
+ const id = typeof providerId === 'string' ? providerId.trim() : '';
850
+ if (id === '') {
851
+ throw new HttpError(400, 'PROVIDER_ID_REQUIRED', `providerId is required for ${operation}`);
852
+ }
853
+ const settings = await deps.settings.read();
854
+ const provider = settings.providers.find((entry) => entry.id === id);
855
+ if (provider === undefined) {
856
+ throw new HttpError(404, 'PROVIDER_UNKNOWN', `no provider profile named ${id}`, { providerId: id });
857
+ }
858
+ return { settings, provider };
859
+ }
860
+
861
+ /**
862
+ * A credential operation needs a reference to name. A profile without one cannot
863
+ * have a credential, and reporting that as "unconfigured" would hide the real fix.
864
+ * @param {object} provider - validated provider profile.
865
+ * @returns {string} the credential reference name.
866
+ */
867
+ function requireCredentialRef(provider) {
868
+ const reference = provider?.credentialRef;
869
+ if (typeof reference !== 'string' || reference === '') {
870
+ throw new HttpError(
871
+ 400,
872
+ 'PROVIDER_CREDENTIAL_REF_MISSING',
873
+ `provider ${provider?.id ?? ''} names no credential reference; set one before storing a secret`,
874
+ { providerId: provider?.id ?? null },
875
+ );
876
+ }
877
+ return reference;
878
+ }
879
+
880
+ /**
881
+ * Validate a pasted secret at the route boundary.
882
+ *
883
+ * The refusal detail carries the bound, never the value or its length: a length
884
+ * is a fingerprint of the secret and a provider key may be short.
885
+ * @param {unknown} value - caller-supplied literal.
886
+ * @param {string} reference - credential reference the value is for.
887
+ * @returns {string} the literal, unchanged.
888
+ */
889
+ function requireCredentialValue(value, reference) {
890
+ if (typeof value !== 'string' || value.trim() === '') {
891
+ throw new HttpError(
892
+ 400,
893
+ 'CREDENTIAL_VALUE_REQUIRED',
894
+ 'a credential value is required; use the clear action to remove one',
895
+ { reference },
896
+ );
897
+ }
898
+ if (value.length > MAX_CREDENTIAL_VALUE_CHARS) {
899
+ throw new HttpError(
900
+ 400,
901
+ 'CREDENTIAL_VALUE_TOO_LARGE',
902
+ 'the credential value exceeds the accepted bound',
903
+ { reference, limit: MAX_CREDENTIAL_VALUE_CHARS },
904
+ );
905
+ }
906
+ return value;
907
+ }
908
+
909
+ /**
910
+ * The credential gateway, or a refusal.
911
+ * @param {object} deps - dependency object with an optional `credentials` gateway.
912
+ * @returns {object} the gateway.
913
+ */
914
+ function requireSeam(deps) {
915
+ const seam = deps.credentials;
916
+ if (seam === null || seam === undefined || typeof seam.describe !== 'function') {
917
+ // The plugin loads without a credential service on purpose. That must read as
918
+ // an honest "this host cannot store secrets", not as a failed write.
919
+ throw new HttpError(
920
+ 503,
921
+ 'CREDENTIAL_SEAM_UNAVAILABLE',
922
+ 'this harness exposes no credential service, so a secret cannot be stored or described',
923
+ );
924
+ }
925
+ return seam;
926
+ }
927
+
928
+ /**
929
+ * Resolve the native route mapping for one snapshot, keeping the failure.
930
+ *
931
+ * Read paths (`/models`, `/catalog`) answer with a body rather than a thrown
932
+ * refusal, so they need the *reason* a mapping does not exist. Returning `null`
933
+ * routes — which is what an unguarded `ensureRoutes()` wrapper used to do — is
934
+ * worse than failing: `describeCatalog` treats a missing map as "no mapping was
935
+ * supplied" and falls back to the public profile id, so a provider whose
936
+ * registration was refused would be reported under an ambient native route
937
+ * (`relay`, `workbuddy`) that this plugin does not own. Here a failure is
938
+ * carried explicitly and no route is ever invented.
939
+ * @param {object} deps - dependency object with an optional `ensureRoutes`.
940
+ * @param {object} settings - validated settings snapshot.
941
+ * @param {string} operation - what was being attempted, for the message.
942
+ * @returns {Promise<{ routes: Map<string, string> | null, error: { code: string, message: string } | null }>} outcome.
943
+ */
944
+ async function resolveRoutes(deps, settings, operation) {
945
+ if (typeof deps.resolveRoutes === 'function') {
946
+ // Injected by the entry point, which decides how a failure is logged.
947
+ return await deps.resolveRoutes(settings, operation);
948
+ }
949
+ if (typeof deps.ensureRoutes !== 'function') {
950
+ return {
951
+ routes: null,
952
+ error: { code: 'PROVIDER_ROUTES_UNAVAILABLE', message: 'native provider routes cannot be registered in this host' },
953
+ };
954
+ }
955
+ try {
956
+ return { routes: await deps.ensureRoutes(settings), error: null };
957
+ } catch (error) {
958
+ deps.logger?.warn?.('dsh-delegate: provider route registration failed during', operation, error?.code ?? 'UNKNOWN');
959
+ return {
960
+ routes: null,
961
+ error: {
962
+ code: typeof error?.code === 'string' ? error.code : 'PROVIDER_ROUTES_UNAVAILABLE',
963
+ message: 'the native provider routes could not be registered',
964
+ },
965
+ };
966
+ }
967
+ }
968
+
969
+ /**
970
+ * Route mapping for the whole-document catalog.
971
+ *
972
+ * A catalog of an empty provider list needs no registration at all, and
973
+ * registering one would create native state as a side effect of a read. With
974
+ * providers configured, so is the registration.
975
+ * @param {object} deps - dependency object.
976
+ * @param {object} settings - validated settings snapshot.
977
+ * @returns {Promise<{ routes: Map<string, string> | null, error: object | null }>} outcome.
978
+ */
979
+ async function resolveRoutesForCatalog(deps, settings) {
980
+ if (settings.providers.length === 0) return { routes: new Map(), error: null };
981
+ return await resolveRoutes(deps, settings, 'a catalog read');
982
+ }
983
+
984
+ /**
985
+ * The native route this provider *would* be served under, for disclosure only.
986
+ *
987
+ * Discovery does not need a route and does not create one: it asks the provider's
988
+ * own API. The route is still reported because an operator uses this row to reason
989
+ * about the whole configuration, and the rule for reporting it is the same one
990
+ * `/catalog` follows — the registered mapping wins, and its absence is `null`,
991
+ * never the bare profile id (which may name an ambient route this plugin does not
992
+ * own).
993
+ * @param {object} deps - dependency object with an optional `resolveRoutes`.
994
+ * @param {string} providerId - configured provider id.
995
+ * @returns {Promise<string | null>} native route id, or null.
996
+ */
997
+ async function configuredRoute(deps, providerId) {
998
+ if (typeof deps.resolveRoutes !== 'function' && typeof deps.ensureRoutes !== 'function') return null;
999
+ try {
1000
+ const settings = await deps.settings.read();
1001
+ const resolved = await resolveRoutes(deps, settings, 'a model list');
1002
+ const mapped = resolved.routes instanceof Map ? resolved.routes.get(providerId) : undefined;
1003
+ return typeof mapped === 'string' && mapped !== '' ? mapped : null;
1004
+ } catch {
1005
+ // Registration failed: no route is reported, and model discovery is
1006
+ // unaffected — it never depends on the native registry.
1007
+ return null;
1008
+ }
1009
+ }
1010
+
1011
+ /**
1012
+ * Refuse a method a multi-method path does not accept.
1013
+ *
1014
+ * The native carrier only forwards methods the route declared, but a handler can
1015
+ * also be invoked directly (tests, in-process callers, a future carrier that
1016
+ * relaxes method filtering), so each dispatcher states its own accepted set
1017
+ * rather than assuming the router filtered for it.
1018
+ * @param {Request} request - incoming request.
1019
+ * @param {string[]} allowed - methods this branch handles.
1020
+ * @returns {Response} 405 with an `Allow` header.
1021
+ */
1022
+ function methodRefusal(request, allowed) {
1023
+ const method = String(request?.method ?? 'GET').toUpperCase();
1024
+ return jsonResponse(
1025
+ 405,
1026
+ {
1027
+ ok: false,
1028
+ error: {
1029
+ code: 'USER_PLANE_METHOD_NOT_ALLOWED',
1030
+ message: `${method} is not allowed on ${new URL(request.url, 'http://localhost').pathname}`,
1031
+ details: { method, allowed },
1032
+ },
1033
+ },
1034
+ { allow: allowed.join(', ') },
1035
+ );
1036
+ }
1037
+
1038
+ /**
1039
+ * Assert a route set is registrable on the native exact-route channel.
1040
+ *
1041
+ * This mirrors the constraints the harness enforces and adds the one it does not
1042
+ * check for us in a useful place: exact paths are unique. Running it before
1043
+ * registration turns a mid-registration throw (which would leave earlier routes
1044
+ * mounted and later ones missing) into a single clear refusal.
1045
+ * @param {Array<object>} routes - candidate routes.
1046
+ * @returns {Array<object>} the same routes when valid.
1047
+ * @throws {Error} when a route could not be registered.
1048
+ */
1049
+ export function assertUserPlaneRoutes(routes) {
1050
+ if (!Array.isArray(routes) || routes.length === 0) {
1051
+ throw new Error('dsh-delegate: the user plane declares no routes');
1052
+ }
1053
+ const seen = new Map();
1054
+ for (const route of routes) {
1055
+ const path = route?.path;
1056
+ if (typeof path !== 'string' || !path.startsWith('/api/')) {
1057
+ // The native registry resolves routes below `/api`; anything else is
1058
+ // silently unreachable or rejected outright.
1059
+ throw new Error(`dsh-delegate: user-plane route path ${JSON.stringify(path)} must start with "/api/"`);
1060
+ }
1061
+ if (seen.has(path)) {
1062
+ // Exact paths are keyed, so a duplicate is not "the same route twice" but a
1063
+ // guaranteed throw on the second registration.
1064
+ throw new Error(`dsh-delegate: user-plane route ${JSON.stringify(path)} is registered twice`);
1065
+ }
1066
+ seen.set(path, route);
1067
+ if (!Array.isArray(route.methods) || route.methods.length === 0) {
1068
+ throw new Error(`dsh-delegate: user-plane route ${JSON.stringify(path)} declares no methods`);
1069
+ }
1070
+ if (new Set(route.methods).size !== route.methods.length) {
1071
+ throw new Error(`dsh-delegate: user-plane route ${JSON.stringify(path)} repeats a method`);
1072
+ }
1073
+ for (const method of route.methods) {
1074
+ if (!ALLOWED_METHODS.includes(method)) {
1075
+ throw new Error(
1076
+ `dsh-delegate: user-plane route ${JSON.stringify(path)} declares ${JSON.stringify(method)}; only ${ALLOWED_METHODS.join('/')} are supported`,
1077
+ );
1078
+ }
1079
+ }
1080
+ if (route.requestBody !== 'buffered' && route.requestBody !== 'streaming') {
1081
+ throw new Error(
1082
+ `dsh-delegate: user-plane route ${JSON.stringify(path)} declares requestBody ${JSON.stringify(route.requestBody)}; only "buffered" or "streaming" are supported`,
1083
+ );
1084
+ }
1085
+ if (typeof route.fetch !== 'function') {
1086
+ throw new Error(`dsh-delegate: user-plane route ${JSON.stringify(path)} has no fetch handler`);
1087
+ }
1088
+ }
1089
+ return routes;
1090
+ }
1091
+
1092
+ /**
1093
+ * Wrap a user-plane route set into a validated, error-handling dispatcher.
1094
+ *
1095
+ * Registration is per exact path on the native channel, so each route already
1096
+ * carries its own guard. This wrapper validates the set once and standardizes
1097
+ * failure rendering: an operator surface must answer with a JSON refusal, never
1098
+ * with a stack trace or a bare 500 page.
1099
+ * @param {object} deps - dependency object passed to {@link userPlaneRoutes}.
1100
+ * @returns {Array<object>} validated, wrapped routes.
1101
+ */
1102
+ export function wrapUserPlaneRoutes(deps) {
1103
+ const routes = userPlaneRoutes(deps);
1104
+ const activeRoutes = deps.engine?.authorizationMode === 'switch'
1105
+ ? routes.filter((route) => !GRANT_CONTROL_PATHS.has(route.path))
1106
+ : routes;
1107
+ return assertUserPlaneRoutes(activeRoutes).map((route) => ({
1108
+ ...route,
1109
+ fetch: async (request) => {
1110
+ try {
1111
+ return await route.fetch(request);
1112
+ } catch (error) {
1113
+ const mapped = classifyError(error);
1114
+ deps.logger?.warn?.('dsh-delegate: user plane refusal', mapped.code);
1115
+ return jsonResponse(mapped.status, {
1116
+ ok: false,
1117
+ error: { code: mapped.code, message: mapped.message, details: redactDeep(mapped.details) },
1118
+ });
1119
+ }
1120
+ },
1121
+ }));
1122
+ }