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.
Files changed (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -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-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -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 +138 -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 +3299 -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 +456 -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 +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,763 @@
1
+ // Settings validation.
2
+ //
3
+ // Every accepted document is normalized into a closed shape: unknown keys are
4
+ // dropped rather than stored, and every persisted field passed exactly one
5
+ // documented check. Validation is the only place that decides whether a
6
+ // provider/model/effort combination is legal, so an unsupported combination has
7
+ // one refusal point instead of being silently ignored later.
8
+
9
+ import { posix, win32 } from 'node:path';
10
+
11
+ import {
12
+ DEFAULT_ISOLATION,
13
+ EFFORT_ORDER,
14
+ ISOLATION_MODES,
15
+ KNOWN_EFFORTS,
16
+ LEGACY_CONVERSATION_MODES,
17
+ LIMITS,
18
+ MONITORING_DEFAULTS,
19
+ SCHEMA_VERSION,
20
+ SUPPORTED_PROTOCOLS,
21
+ defaultSettings,
22
+ } from './defaults.js';
23
+
24
+ /** A validation refusal with a stable machine code. */
25
+ export class ConfigError extends Error {
26
+ /**
27
+ * @param {string} code - stable machine code.
28
+ * @param {string} message - human-readable explanation.
29
+ * @param {object} [details] - bounded, non-secret details.
30
+ */
31
+ constructor(code, message, details = {}) {
32
+ super(message);
33
+ this.name = 'ConfigError';
34
+ this.code = code;
35
+ this.details = details;
36
+ }
37
+ }
38
+
39
+ const ID_PATTERN = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
40
+ const PROVIDER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,159}$/;
41
+ const CREDENTIAL_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
42
+
43
+ /**
44
+ * Provider-profile keys that may only ever carry a credential *reference*.
45
+ * A profile carrying one of these is refused instead of having it dropped, so an
46
+ * operator who pasted a key learns immediately that it was not stored.
47
+ */
48
+ const PROVIDER_SECRET_KEYS = Object.freeze([
49
+ 'apiKey',
50
+ 'api_key',
51
+ 'apikey',
52
+ 'key',
53
+ 'token',
54
+ 'secret',
55
+ 'password',
56
+ 'passwd',
57
+ 'authorization',
58
+ 'bearer',
59
+ 'headers',
60
+ ]);
61
+
62
+ function requireString(value, code, field, { max = 200, pattern = null, allowEmpty = false } = {}) {
63
+ if (typeof value !== 'string') throw new ConfigError(code, `${field} must be a string`, { field });
64
+ const trimmed = value.trim();
65
+ if (!allowEmpty && trimmed === '') throw new ConfigError(code, `${field} must not be empty`, { field });
66
+ if (trimmed.length > max) throw new ConfigError(code, `${field} exceeds ${max} characters`, { field });
67
+ if (pattern !== null && !pattern.test(trimmed)) throw new ConfigError(code, `${field} has an unsupported format`, { field });
68
+ return trimmed;
69
+ }
70
+
71
+ function requireInt(value, code, field, min, max) {
72
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
73
+ throw new ConfigError(code, `${field} must be an integer`, { field });
74
+ }
75
+ if (value < min || value > max) {
76
+ throw new ConfigError(code, `${field} must be between ${min} and ${max}`, { field, min, max });
77
+ }
78
+ return value;
79
+ }
80
+
81
+ function requireBool(value, code, field) {
82
+ if (typeof value !== 'boolean') throw new ConfigError(code, `${field} must be a boolean`, { field });
83
+ return value;
84
+ }
85
+
86
+ function optionalString(value, code, field, options) {
87
+ if (value === null || value === undefined) return null;
88
+ return requireString(value, code, field, options);
89
+ }
90
+
91
+ /** Whether a raw path string is a Windows-style absolute path (drive or UNC). */
92
+ const WINDOWS_STYLE = /^(?:[A-Za-z]:[\\/]|\\\\)/;
93
+
94
+ function stripTrailingSeparators(candidate, pathImpl) {
95
+ let out = candidate;
96
+ const { root } = pathImpl.parse(candidate);
97
+ while (out.length > root.length && /[\\/]$/.test(out)) out = out.slice(0, -1);
98
+ return out;
99
+ }
100
+
101
+ /**
102
+ * Canonicalize one absolute project path.
103
+ *
104
+ * One canonical form is used by validation, by every settings mutation and by
105
+ * lookup when a job composes its effective configuration, so `C:/Work/Proj/`,
106
+ * `c:\work\proj` and `C:\Work\Proj` are the same project key instead of three
107
+ * overrides that only one of which ever applies.
108
+ *
109
+ * Rules:
110
+ * - the input must be absolute (a relative key is refused, never resolved
111
+ * against the plugin's own cwd, which would silently pick a different project);
112
+ * - separators are normalized to the path style's native separator and `.`/`..`
113
+ * are collapsed, with a trailing separator removed except at a filesystem root;
114
+ * - Windows-style paths (and any path on Windows) are case-folded for the key,
115
+ * because NTFS compares case-insensitively while a JSON object key does not.
116
+ * @param {string} projectPath - absolute project path.
117
+ * @param {string} [field] - field name for refusals.
118
+ * @returns {{ key: string, display: string }} canonical lookup key and normalized display form.
119
+ */
120
+ export function canonicalProjectKey(projectPath, field = 'projectPath') {
121
+ const raw = requireString(projectPath, 'PROJECT_OVERRIDE_INVALID', field, { max: 1024 });
122
+ const windowsStyle = WINDOWS_STYLE.test(raw);
123
+ const pathImpl = windowsStyle ? win32 : posix;
124
+ if (!pathImpl.isAbsolute(raw)) {
125
+ throw new ConfigError('PROJECT_OVERRIDE_INVALID', `${field} must be an absolute path`, { field });
126
+ }
127
+ const display = stripTrailingSeparators(pathImpl.normalize(raw), pathImpl);
128
+ const foldCase = windowsStyle || process.platform === 'win32';
129
+ return { key: foldCase ? display.toLowerCase() : display, display };
130
+ }
131
+
132
+ /**
133
+ * Validate one `http(s)` base URL.
134
+ *
135
+ * A base URL is persisted in the settings document and can be exported, so it is
136
+ * an endpoint *without* anything that could carry a secret: no `user:password@`
137
+ * authority (the classic way a key ends up inside a URL) and no query or fragment
138
+ * at all, including a bare `?` or `#` — those are exactly where an SDK would
139
+ * append an `api_key=…` parameter. Plaintext loopback is allowed because the
140
+ * shipped relay runs there; anything else must be `https`.
141
+ * @param {unknown} value - candidate base URL.
142
+ * @param {string} field - field name for the refusal.
143
+ * @returns {string} normalized base URL without a trailing slash, query or fragment.
144
+ */
145
+ export function validateBaseUrl(value, field = 'baseUrl') {
146
+ const raw = requireString(value, 'PROVIDER_BASE_URL_INVALID', field, { max: 2048 });
147
+ if (raw.includes('?') || raw.includes('#')) {
148
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} must not contain a query or fragment`, { field });
149
+ }
150
+ let parsed;
151
+ try {
152
+ parsed = new URL(raw);
153
+ } catch {
154
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} is not a valid URL`, { field });
155
+ }
156
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
157
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} must use http or https`, { field });
158
+ }
159
+ if (parsed.username !== '' || parsed.password !== '') {
160
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} must not embed credentials`, { field });
161
+ }
162
+ if (parsed.search !== '' || parsed.hash !== '') {
163
+ // Defence in depth: a URL implementation that keeps a query would persist it.
164
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} must not contain a query or fragment`, { field });
165
+ }
166
+ if (parsed.hostname === '') {
167
+ throw new ConfigError('PROVIDER_BASE_URL_INVALID', `${field} must name a host`, { field });
168
+ }
169
+ const path = parsed.pathname.replace(/\/+$/, '');
170
+ return `${parsed.protocol}//${parsed.host}${path}`;
171
+ }
172
+
173
+ /**
174
+ * Validate a credential reference. A reference is an environment-variable-style
175
+ * name resolved through the native credential seam; a value is never accepted
176
+ * here because this module is not allowed to hold secrets.
177
+ * @param {unknown} value - candidate reference.
178
+ * @returns {string} the reference name.
179
+ */
180
+ export function validateCredentialRef(value) {
181
+ return requireString(value, 'PROVIDER_CREDENTIAL_REF_INVALID', 'credentialRef', {
182
+ max: 128,
183
+ pattern: CREDENTIAL_REF_PATTERN,
184
+ });
185
+ }
186
+
187
+ /**
188
+ * Normalize a model's declared reasoning-effort list.
189
+ *
190
+ * The declaration is the *only* authority on what a model supports: an id that
191
+ * this build does not know is refused outright (it would be sent to a provider
192
+ * that may ignore or reject it), and the accepted ids are sorted into the
193
+ * canonical weakest-to-strongest order so a UI renders a stable list.
194
+ * @param {unknown} value - candidate `efforts` array.
195
+ * @param {string} modelId - model id for refusals.
196
+ * @returns {string[]} canonical effort ids.
197
+ */
198
+ function normalizeDeclaredEfforts(value, modelId, { native = false } = {}) {
199
+ const raw = value ?? [];
200
+ if (!Array.isArray(raw)) throw new ConfigError('MODEL_EFFORTS_INVALID', 'model.efforts must be a list', { model: modelId });
201
+ if (raw.length > (native ? 64 : KNOWN_EFFORTS.length)) {
202
+ throw new ConfigError('MODEL_EFFORTS_INVALID', 'model.efforts declares more efforts than exist', { model: modelId });
203
+ }
204
+ const efforts = [];
205
+ for (const effort of raw) {
206
+ if (typeof effort !== 'string' || effort.length > 80 || effort.trim() !== effort || effort === ''
207
+ || (!native && !KNOWN_EFFORTS.includes(effort))) {
208
+ throw new ConfigError('MODEL_EFFORTS_INVALID', `unsupported reasoning effort ${JSON.stringify(effort)}`, {
209
+ model: modelId,
210
+ supported: [...KNOWN_EFFORTS],
211
+ });
212
+ }
213
+ if (!efforts.includes(effort)) efforts.push(effort);
214
+ }
215
+ return native
216
+ ? efforts
217
+ : efforts.sort((a, b) => EFFORT_ORDER.get(a) - EFFORT_ORDER.get(b));
218
+ }
219
+
220
+ /**
221
+ * Validate one declared model entry, including its effort capability list.
222
+ * @param {unknown} value - candidate model declaration.
223
+ * @returns {{ id: string, efforts: string[], contextWindow: number | null }} normalized entry.
224
+ */
225
+ export function validateModelDeclaration(value, options = {}) {
226
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
227
+ throw new ConfigError('MODEL_INVALID', 'model declaration must be an object', {});
228
+ }
229
+ const id = requireString(value.id, 'MODEL_INVALID', 'model.id', { max: 160 });
230
+ const efforts = normalizeDeclaredEfforts(value.efforts, id, options);
231
+ const contextWindow = value.contextWindow === undefined || value.contextWindow === null
232
+ ? null
233
+ : requireInt(value.contextWindow, 'MODEL_INVALID', 'model.contextWindow', 1024, 10_000_000);
234
+ return { id, efforts, contextWindow };
235
+ }
236
+
237
+ /**
238
+ * Validate one provider profile.
239
+ * @param {unknown} value - candidate profile.
240
+ * @returns {object} normalized provider profile (never containing a secret value).
241
+ */
242
+ export function validateProviderProfile(value) {
243
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
244
+ throw new ConfigError('PROVIDER_INVALID', 'provider profile must be an object', {});
245
+ }
246
+ const id = requireString(value.id, 'PROVIDER_ID_INVALID', 'provider.id', { max: 160, pattern: PROVIDER_ID_PATTERN });
247
+ const name = requireString(value.name, 'PROVIDER_NAME_INVALID', 'provider.name', { max: 80 });
248
+ const source = value.source ?? 'custom';
249
+ if (source !== 'native' && source !== 'custom') {
250
+ throw new ConfigError('PROVIDER_SOURCE_UNSUPPORTED', 'provider.source is unsupported', { id });
251
+ }
252
+ for (const key of PROVIDER_SECRET_KEYS) {
253
+ const candidate = value[key];
254
+ if (candidate === undefined || candidate === null || candidate === '') continue;
255
+ // A secret value must enter through the credential seam, never through a
256
+ // settings document that is exported, logged and packaged.
257
+ throw new ConfigError('PROVIDER_SECRET_IN_SETTINGS', `provider ${key} is a secret; use credentialRef`, { id });
258
+ }
259
+ const rawModels = value.models ?? [];
260
+ if (!Array.isArray(rawModels)) throw new ConfigError('MODEL_INVALID', 'provider.models must be a list', { id });
261
+ if (rawModels.length > LIMITS.manualModelsPerProvider) {
262
+ throw new ConfigError('MODEL_INVALID', `provider.models exceeds ${LIMITS.manualModelsPerProvider} entries`, { id });
263
+ }
264
+ const models = rawModels.map((entry) => validateModelDeclaration(entry, { native: source === 'native' }));
265
+ const seen = new Set();
266
+ for (const model of models) {
267
+ if (seen.has(model.id)) throw new ConfigError('MODEL_DUPLICATE', `duplicate model id ${model.id}`, { id });
268
+ seen.add(model.id);
269
+ }
270
+ if (source === 'native') {
271
+ return { id, name, source, protocol: null, baseUrl: null, credentialRef: null, models };
272
+ }
273
+ const protocol = requireString(value.protocol ?? 'openai-chat', 'PROVIDER_PROTOCOL_UNSUPPORTED', 'provider.protocol', { max: 40 });
274
+ if (!SUPPORTED_PROTOCOLS.includes(protocol)) {
275
+ throw new ConfigError('PROVIDER_PROTOCOL_UNSUPPORTED', `protocol ${protocol} is not supported by this stage`, {
276
+ protocol,
277
+ supported: [...SUPPORTED_PROTOCOLS],
278
+ });
279
+ }
280
+ const baseUrl = validateBaseUrl(value.baseUrl, 'provider.baseUrl');
281
+ const credentialRef = value.credentialRef === null || value.credentialRef === undefined
282
+ ? null
283
+ : validateCredentialRef(value.credentialRef);
284
+ return { id, name, source, protocol, baseUrl, credentialRef, models };
285
+ }
286
+
287
+ /**
288
+ * Validate a provider list and enforce unique ids.
289
+ * @param {unknown} value - candidate list.
290
+ * @returns {object[]} normalized providers.
291
+ */
292
+ export function validateProviders(value) {
293
+ if (!Array.isArray(value)) throw new ConfigError('PROVIDER_INVALID', 'providers must be a list', {});
294
+ if (value.length > LIMITS.providers) {
295
+ throw new ConfigError('PROVIDER_INVALID', `providers exceeds ${LIMITS.providers} entries`, {});
296
+ }
297
+ const providers = value.map(validateProviderProfile);
298
+ const seen = new Set();
299
+ for (const provider of providers) {
300
+ if (seen.has(provider.id)) throw new ConfigError('PROVIDER_DUPLICATE', `duplicate provider id ${provider.id}`, { id: provider.id });
301
+ seen.add(provider.id);
302
+ }
303
+ return providers;
304
+ }
305
+
306
+ /**
307
+ * Validate an execution-selection triple against a provider list.
308
+ *
309
+ * This is the single decision point for "is this provider/model/effort
310
+ * combination real". It never substitutes another model or effort for the one
311
+ * requested: an unknown provider, an undeclared model, an effort id this build
312
+ * does not know, or an effort the model does not declare is a refusal.
313
+ * @param {{ providerId: unknown, model: unknown, reasoningEffort: unknown }} selection - requested triple.
314
+ * @param {object[]} providers - validated provider list.
315
+ * @param {string} field - field prefix for refusals.
316
+ * @returns {{ providerId: string, model: string, reasoningEffort: string | null, provider: object, modelEntry: object }} resolved triple.
317
+ */
318
+ export function validateSelection(selection, providers, field = 'selection') {
319
+ const providerId = requireString(selection?.providerId, 'SELECTION_PROVIDER_REQUIRED', `${field}.providerId`, { max: 160, pattern: PROVIDER_ID_PATTERN });
320
+ const provider = providers.find((entry) => entry.id === providerId);
321
+ if (provider === undefined) {
322
+ throw new ConfigError('SELECTION_PROVIDER_UNKNOWN', `provider ${providerId} is not configured`, { providerId });
323
+ }
324
+ const model = requireString(selection?.model, 'SELECTION_MODEL_REQUIRED', `${field}.model`, { max: 160 });
325
+ const modelEntry = provider.models.find((entry) => entry.id === model);
326
+ if (modelEntry === undefined) {
327
+ throw new ConfigError('SELECTION_MODEL_UNKNOWN', `model ${model} is not declared for provider ${providerId}`, { providerId, model });
328
+ }
329
+ const requested = selection?.reasoningEffort ?? null;
330
+ if (requested === null) {
331
+ return { providerId, model, reasoningEffort: null, provider, modelEntry };
332
+ }
333
+ if (typeof requested !== 'string' || requested === '' || requested.length > 80 || requested.trim() !== requested) {
334
+ throw new ConfigError('SELECTION_EFFORT_UNKNOWN', `reasoning effort ${JSON.stringify(requested)} does not exist`, {
335
+ providerId,
336
+ model,
337
+ supported: [...modelEntry.efforts],
338
+ });
339
+ }
340
+ if (!modelEntry.efforts.includes(requested)) {
341
+ throw new ConfigError('SELECTION_EFFORT_UNSUPPORTED', `model ${model} does not support reasoning effort ${requested}`, {
342
+ providerId,
343
+ model,
344
+ requested,
345
+ supported: [...modelEntry.efforts],
346
+ });
347
+ }
348
+ return { providerId, model, reasoningEffort: requested, provider, modelEntry };
349
+ }
350
+
351
+ function validateIsolation(value, code, field) {
352
+ const isolation = requireString(value ?? DEFAULT_ISOLATION, code, field, { max: 16 });
353
+ if (!ISOLATION_MODES.includes(isolation)) {
354
+ throw new ConfigError(code, `isolation ${isolation} is not supported`, { field, isolation, supported: [...ISOLATION_MODES] });
355
+ }
356
+ return isolation;
357
+ }
358
+
359
+ /**
360
+ * Validate the worker execution settings block.
361
+ * @param {unknown} value - candidate worker block.
362
+ * @param {object[]} providers - validated providers.
363
+ * @returns {object} normalized worker block.
364
+ */
365
+ export function validateWorkerSettings(value, providers) {
366
+ const source = value ?? {};
367
+ if (typeof source !== 'object' || Array.isArray(source)) {
368
+ throw new ConfigError('WORKER_INVALID', 'worker settings must be an object', {});
369
+ }
370
+ const selection = validateSelection(source, providers, 'worker');
371
+ const timeoutSeconds = requireInt(
372
+ source.timeoutSeconds ?? 1800,
373
+ 'WORKER_TIMEOUT_INVALID',
374
+ 'worker.timeoutSeconds',
375
+ LIMITS.timeoutSecondsMin,
376
+ LIMITS.timeoutSecondsMax,
377
+ );
378
+ const maxParallelism = requireInt(
379
+ source.maxParallelism ?? 1,
380
+ 'WORKER_PARALLELISM_INVALID',
381
+ 'worker.maxParallelism',
382
+ LIMITS.maxParallelismMin,
383
+ LIMITS.maxParallelismMax,
384
+ );
385
+ // Isolation is a decision, not a fallback: an absent value is the documented
386
+ // default (worktree) and `shared` must be stated by the operator.
387
+ const isolation = validateIsolation(source.isolation, 'WORKER_ISOLATION_INVALID', 'worker.isolation');
388
+ return {
389
+ providerId: selection.providerId,
390
+ model: selection.model,
391
+ reasoningEffort: selection.reasoningEffort,
392
+ timeoutSeconds,
393
+ maxParallelism,
394
+ isolation,
395
+ };
396
+ }
397
+
398
+ /**
399
+ * Validate the additional-review block. Review is off unless explicitly enabled
400
+ * and it owns a fully separate provider/model/effort triple.
401
+ * @param {unknown} value - candidate review block.
402
+ * @param {object[]} providers - validated providers.
403
+ * @returns {object} normalized review block.
404
+ */
405
+ export function validateReviewSettings(value, providers) {
406
+ const source = value ?? {};
407
+ if (typeof source !== 'object' || Array.isArray(source)) {
408
+ throw new ConfigError('REVIEW_INVALID', 'review settings must be an object', {});
409
+ }
410
+ const enabled = requireBool(source.enabled ?? false, 'REVIEW_INVALID', 'review.enabled');
411
+ if (!enabled) {
412
+ return { enabled: false, providerId: null, model: null, reasoningEffort: null };
413
+ }
414
+ const selection = validateSelection(source, providers, 'review');
415
+ return {
416
+ enabled: true,
417
+ providerId: selection.providerId,
418
+ model: selection.model,
419
+ reasoningEffort: selection.reasoningEffort,
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Validate the activity-monitoring block.
425
+ *
426
+ * Two silence thresholds, both in whole seconds, both bounded:
427
+ *
428
+ * * `selfCheckSeconds` is when the engine performs ONE read-only local
429
+ * inspection of the executor it already holds (alive, phase, pending request,
430
+ * current tool) and reports it on an internal re-wait. It never starts an LLM
431
+ * call and never touches the task's state, budget or deadline.
432
+ * * `attentionSeconds` is when a wait stops keeping quiet and reports
433
+ * `attention` to the commander instead of `heartbeat`.
434
+ *
435
+ * A missing block is the documented default (backwards compatible: documents
436
+ * written before this field existed keep loading). Everything else is refused
437
+ * rather than repaired — an unknown key (a typo such as `atentionSeconds` would
438
+ * otherwise silently keep the default), a wrong type, a non-integer, an
439
+ * out-of-range value, and any pair where the attention threshold is not strictly
440
+ * greater than the self-check one. A repaired value would make the two timers
441
+ * disagree with what the operator stored, which is exactly the class of silent
442
+ * mismatch this plugin refuses everywhere else.
443
+ * @param {unknown} value - candidate monitoring block.
444
+ * @returns {{ selfCheckSeconds: number, attentionSeconds: number }} normalized block.
445
+ */
446
+ export function validateMonitoringSettings(value) {
447
+ if (value === undefined || value === null) {
448
+ return {
449
+ selfCheckSeconds: MONITORING_DEFAULTS.selfCheckSeconds,
450
+ attentionSeconds: MONITORING_DEFAULTS.attentionSeconds,
451
+ };
452
+ }
453
+ if (typeof value !== 'object' || Array.isArray(value)) {
454
+ throw new ConfigError('MONITORING_INVALID', 'monitoring settings must be an object', { field: 'monitoring' });
455
+ }
456
+ for (const key of Object.keys(value)) {
457
+ if (key !== 'selfCheckSeconds' && key !== 'attentionSeconds') {
458
+ throw new ConfigError('MONITORING_INVALID', `monitoring setting ${key} is not supported`, {
459
+ field: `monitoring.${key}`,
460
+ supported: ['selfCheckSeconds', 'attentionSeconds'],
461
+ });
462
+ }
463
+ }
464
+ const selfCheckSeconds = requireInt(
465
+ value.selfCheckSeconds === undefined ? MONITORING_DEFAULTS.selfCheckSeconds : value.selfCheckSeconds,
466
+ 'MONITORING_INVALID',
467
+ 'monitoring.selfCheckSeconds',
468
+ LIMITS.selfCheckSecondsMin,
469
+ LIMITS.selfCheckSecondsMax,
470
+ );
471
+ const attentionSeconds = requireInt(
472
+ value.attentionSeconds === undefined ? MONITORING_DEFAULTS.attentionSeconds : value.attentionSeconds,
473
+ 'MONITORING_INVALID',
474
+ 'monitoring.attentionSeconds',
475
+ LIMITS.attentionSecondsMin,
476
+ LIMITS.attentionSecondsMax,
477
+ );
478
+ if (attentionSeconds <= selfCheckSeconds) {
479
+ throw new ConfigError(
480
+ 'MONITORING_TIMING_INVALID',
481
+ 'monitoring.attentionSeconds must be greater than monitoring.selfCheckSeconds',
482
+ { field: 'monitoring.attentionSeconds', selfCheckSeconds, attentionSeconds },
483
+ );
484
+ }
485
+ return { selfCheckSeconds, attentionSeconds };
486
+ }
487
+
488
+ /** Validate legacy grant TTLs kept for backwards-compatible imports. */
489
+ export function validateAuthorizationSettings(value) {
490
+ const source = value ?? {};
491
+ if (typeof source !== 'object' || Array.isArray(source)) {
492
+ throw new ConfigError('AUTHORIZATION_INVALID', 'authorization settings must be an object', {});
493
+ }
494
+ return {
495
+ taskGrantTtlSeconds: requireInt(source.taskGrantTtlSeconds ?? 900, 'AUTHORIZATION_INVALID', 'authorization.taskGrantTtlSeconds', LIMITS.taskGrantTtlSecondsMin, LIMITS.taskGrantTtlSecondsMax),
496
+ sessionGrantTtlSeconds: requireInt(source.sessionGrantTtlSeconds ?? 4 * 60 * 60, 'AUTHORIZATION_INVALID', 'authorization.sessionGrantTtlSeconds', LIMITS.sessionGrantTtlSecondsMin, LIMITS.sessionGrantTtlSecondsMax),
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Validate bounded per-job overrides.
502
+ *
503
+ * An override is a *patch*, not a complete selection: naming only
504
+ * `reasoningEffort` is legitimate because the provider and model come from the
505
+ * layer beneath. Each present field is therefore validated on its own, and the
506
+ * composed triple is validated again after merging (in `resolveEffectiveConfig`),
507
+ * which is where an incomplete or inconsistent combination is actually caught.
508
+ * @param {unknown} value - candidate override block.
509
+ * @param {object[]} providers - validated providers.
510
+ * @returns {object} normalized override block (only present keys).
511
+ */
512
+ export function validateJobOverrides(value, providers) {
513
+ if (value === null || value === undefined) return {};
514
+ if (typeof value !== 'object' || Array.isArray(value)) {
515
+ throw new ConfigError('OVERRIDE_INVALID', 'job overrides must be an object', {});
516
+ }
517
+ const allowed = new Set(['providerId', 'model', 'reasoningEffort', 'timeoutSeconds', 'isolation']);
518
+ for (const key of Object.keys(value)) {
519
+ if (!allowed.has(key)) {
520
+ throw new ConfigError('OVERRIDE_INVALID', `job override ${key} is not allowed`, { field: key });
521
+ }
522
+ }
523
+ const out = {};
524
+ if (value.providerId !== undefined) {
525
+ const providerId = requireString(value.providerId, 'SELECTION_PROVIDER_REQUIRED', 'override.providerId', {
526
+ max: 160,
527
+ pattern: PROVIDER_ID_PATTERN,
528
+ });
529
+ if (!providers.some((entry) => entry.id === providerId)) {
530
+ throw new ConfigError('SELECTION_PROVIDER_UNKNOWN', `provider ${providerId} is not configured`, { providerId });
531
+ }
532
+ out.providerId = providerId;
533
+ }
534
+ if (value.model !== undefined) {
535
+ out.model = requireString(value.model, 'SELECTION_MODEL_REQUIRED', 'override.model', { max: 160 });
536
+ }
537
+ if (value.reasoningEffort !== undefined && value.reasoningEffort !== null) {
538
+ const effort = value.reasoningEffort;
539
+ if (typeof effort !== 'string' || effort === '' || effort.length > 80 || effort.trim() !== effort) {
540
+ throw new ConfigError('SELECTION_EFFORT_UNKNOWN', `reasoning effort ${JSON.stringify(effort)} does not exist`, {
541
+ supported: [...KNOWN_EFFORTS],
542
+ });
543
+ }
544
+ out.reasoningEffort = effort;
545
+ } else if (value.reasoningEffort === null) {
546
+ // An explicit null clears an inherited effort; it is not the same as omitting
547
+ // the key, which leaves the lower layer's effort in place.
548
+ out.reasoningEffort = null;
549
+ }
550
+ if (value.timeoutSeconds !== undefined) {
551
+ out.timeoutSeconds = requireInt(
552
+ value.timeoutSeconds,
553
+ 'WORKER_TIMEOUT_INVALID',
554
+ 'override.timeoutSeconds',
555
+ LIMITS.timeoutSecondsMin,
556
+ LIMITS.timeoutSecondsMax,
557
+ );
558
+ }
559
+ if (value.isolation !== undefined) {
560
+ out.isolation = validateIsolation(value.isolation, 'WORKER_ISOLATION_INVALID', 'override.isolation');
561
+ }
562
+ return out;
563
+ }
564
+
565
+ /**
566
+ * Validate one project override entry keyed by an absolute project path.
567
+ * @param {unknown} value - candidate project block.
568
+ * @param {object[]} providers - validated providers.
569
+ * @returns {object} normalized project block.
570
+ */
571
+ export function validateProjectOverride(value, providers) {
572
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
573
+ throw new ConfigError('PROJECT_OVERRIDE_INVALID', 'project override must be an object', {});
574
+ }
575
+ const out = {};
576
+ if (value.worker !== undefined) out.worker = validateWorkerSettings(value.worker, providers);
577
+ if (value.review !== undefined) out.review = validateReviewSettings(value.review, providers);
578
+ return out;
579
+ }
580
+
581
+ /**
582
+ * Validate the retired conversation block.
583
+ *
584
+ * The directory-level mode is gone: what a run does with its DSH conversation is
585
+ * now decided per submission (`continueFromTaskId`), not by a saved setting. A
586
+ * document that still carries `conversation.mode` is accepted so an upgraded
587
+ * installation keeps loading, and the stored value is preserved verbatim so this
588
+ * build never rewrites an operator's file on read.
589
+ *
590
+ * The value is INERT. Nothing consults it, which is what makes a legacy
591
+ * `reuse` incapable of causing an implicit reuse. A value that is not one of the
592
+ * documented legacy ids is still refused rather than quietly normalized, because a
593
+ * hand-edited document should be reported, not silently reinterpreted.
594
+ * @param {unknown} value - candidate conversation block.
595
+ * @returns {{ mode: string }} normalized block.
596
+ */
597
+ export function validateConversationSettings(value) {
598
+ const source = value ?? {};
599
+ if (typeof source !== 'object' || Array.isArray(source)) {
600
+ throw new ConfigError('CONVERSATION_INVALID', 'conversation settings must be an object', {});
601
+ }
602
+ // An empty string is not "absent": a document that explicitly stores a blank mode
603
+ // is malformed, not a request for the default. Only a missing field takes the
604
+ // default, so a hand-edited file is reported instead of silently reinterpreted.
605
+ const requested = source.mode === undefined ? LEGACY_CONVERSATION_MODES[0] : source.mode;
606
+ const mode = requireString(
607
+ requested,
608
+ 'CONVERSATION_MODE_UNSUPPORTED',
609
+ 'conversation.mode',
610
+ { max: 16 },
611
+ );
612
+ if (!LEGACY_CONVERSATION_MODES.includes(mode)) {
613
+ throw new ConfigError('CONVERSATION_MODE_UNSUPPORTED', `conversation mode ${mode} is not supported`, {
614
+ field: 'conversation.mode',
615
+ mode,
616
+ supported: [...LEGACY_CONVERSATION_MODES],
617
+ deprecated: true,
618
+ reason: 'the directory-level conversation mode has been removed; use continueFromTaskId for a follow-up',
619
+ });
620
+ }
621
+ return { mode };
622
+ }
623
+
624
+ /**
625
+ * Validate the project-override map, canonicalizing every key.
626
+ *
627
+ * Two spellings of one project (`C:/work/p` and `c:\WORK\p`) would otherwise be
628
+ * two independent overrides of which only the lookup spelling ever applies, so a
629
+ * duplicate canonical key is refused rather than silently merged.
630
+ * @param {unknown} value - candidate `projectOverrides` map.
631
+ * @param {object[]} providers - validated providers.
632
+ * @returns {Record<string, object>} map keyed by canonical display path.
633
+ */
634
+ export function validateProjectOverrides(value, providers) {
635
+ const raw = value ?? {};
636
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
637
+ throw new ConfigError('PROJECT_OVERRIDE_INVALID', 'projectOverrides must be an object', {});
638
+ }
639
+ const out = {};
640
+ const seen = new Map();
641
+ for (const [projectPath, block] of Object.entries(raw)) {
642
+ const { key, display } = canonicalProjectKey(projectPath, 'projectOverrides key');
643
+ const existing = seen.get(key);
644
+ if (existing !== undefined) {
645
+ throw new ConfigError('PROJECT_OVERRIDE_DUPLICATE', 'two project overrides name the same project', {
646
+ key,
647
+ paths: [existing, display],
648
+ });
649
+ }
650
+ seen.set(key, display);
651
+ out[display] = validateProjectOverride(block, providers);
652
+ }
653
+ return out;
654
+ }
655
+
656
+ /**
657
+ * Validate one named preset: a reusable, entirely non-secret worker/review
658
+ * combination. Both blocks are validated against the same provider list as live
659
+ * settings, so a preset can never store a combination that settings would refuse.
660
+ * @param {unknown} value - candidate preset.
661
+ * @param {object[]} providers - validated providers.
662
+ * @returns {{ id: string, name: string, worker: object | null, review: object | null }} normalized preset.
663
+ */
664
+ export function validatePreset(value, providers) {
665
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
666
+ throw new ConfigError('PRESET_INVALID', 'preset must be an object', {});
667
+ }
668
+ const id = requireString(value.id, 'PRESET_INVALID', 'preset.id', { max: 40, pattern: ID_PATTERN });
669
+ const name = requireString(value.name ?? id, 'PRESET_INVALID', 'preset.name', { max: 80 });
670
+ if (value.worker === undefined && value.review === undefined) {
671
+ throw new ConfigError('PRESET_INVALID', 'preset must contain worker or review settings', { id });
672
+ }
673
+ return {
674
+ id,
675
+ name,
676
+ worker: value.worker === undefined ? null : validateWorkerSettings(value.worker, providers),
677
+ review: value.review === undefined ? null : validateReviewSettings(value.review, providers),
678
+ };
679
+ }
680
+
681
+ /**
682
+ * Validate the preset list (backward compatible: a document without presets has
683
+ * none). A preset only refers to providers by id, so it holds no endpoint,
684
+ * credential reference or secret.
685
+ * @param {unknown} value - candidate `presets` array.
686
+ * @param {object[]} providers - validated providers.
687
+ * @returns {object[]} normalized presets.
688
+ */
689
+ export function validatePresets(value, providers) {
690
+ const raw = value ?? [];
691
+ if (!Array.isArray(raw)) throw new ConfigError('PRESET_INVALID', 'presets must be a list', {});
692
+ if (raw.length > LIMITS.presets) {
693
+ throw new ConfigError('PRESET_INVALID', `presets exceeds ${LIMITS.presets} entries`, {});
694
+ }
695
+ const presets = raw.map((entry) => validatePreset(entry, providers));
696
+ const seen = new Set();
697
+ for (const preset of presets) {
698
+ if (seen.has(preset.id)) throw new ConfigError('PRESET_DUPLICATE', `duplicate preset id ${preset.id}`, { id: preset.id });
699
+ seen.add(preset.id);
700
+ }
701
+ return presets;
702
+ }
703
+
704
+ /**
705
+ * Whether a settings block simply has no provider chosen yet.
706
+ * @param {unknown} value - candidate block.
707
+ * @returns {boolean} true when the block stores "not configured".
708
+ */
709
+ function isUnconfiguredSelection(value) {
710
+ if (value === null || value === undefined) return true;
711
+ if (typeof value !== 'object' || Array.isArray(value)) return false;
712
+ const enabled = value.enabled;
713
+ if (enabled === true) return false;
714
+ return (value.providerId ?? null) === null;
715
+ }
716
+
717
+ /**
718
+ * Validate and normalize a complete settings document.
719
+ * @param {unknown} value - parsed document.
720
+ * @param {object} [options] - `options.requireProviders` refuses an empty list.
721
+ * @returns {object} normalized settings.
722
+ */
723
+ export function validateSettings(value, options = {}) {
724
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
725
+ throw new ConfigError('SETTINGS_INVALID', 'settings document must be an object', {});
726
+ }
727
+ const schemaVersion = value.schemaVersion ?? SCHEMA_VERSION;
728
+ if (schemaVersion !== SCHEMA_VERSION) {
729
+ throw new ConfigError('SETTINGS_SCHEMA_UNSUPPORTED', `unsupported settings schemaVersion ${String(schemaVersion)}`, {
730
+ expected: SCHEMA_VERSION,
731
+ found: schemaVersion,
732
+ });
733
+ }
734
+ const providers = validateProviders(value.providers ?? []);
735
+
736
+ // An unconfigured selection (no provider chosen yet) is legal to STORE, so a
737
+ // fresh install can add its first provider before choosing a worker. It is
738
+ // never legal to RUN: resolveEffectiveConfig refuses it, which keeps the
739
+ // refusal at the job boundary instead of at every settings edit.
740
+ const worker = isUnconfiguredSelection(value.worker)
741
+ ? defaultSettings().worker
742
+ : validateWorkerSettings(value.worker ?? {}, providers);
743
+ const review = isUnconfiguredSelection(value.review)
744
+ ? defaultSettings().review
745
+ : validateReviewSettings(value.review ?? {}, providers);
746
+
747
+ if (options.requireProviders === true && providers.length === 0) {
748
+ throw new ConfigError('SETTINGS_NO_PROVIDERS', 'no provider profile is configured', {});
749
+ }
750
+
751
+ return {
752
+ schemaVersion: SCHEMA_VERSION,
753
+ delegationEnabled: requireBool(value.delegationEnabled ?? false, 'SETTINGS_INVALID', 'delegationEnabled'),
754
+ providers,
755
+ worker,
756
+ review,
757
+ authorization: validateAuthorizationSettings(value.authorization),
758
+ monitoring: validateMonitoringSettings(value.monitoring),
759
+ projectOverrides: validateProjectOverrides(value.projectOverrides, providers),
760
+ presets: validatePresets(value.presets, providers),
761
+ conversation: validateConversationSettings(value.conversation),
762
+ };
763
+ }