@narumitw/pi-subagents 0.49.2 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +313 -53
  2. package/package.json +11 -8
  3. package/src/adaptive-scheduler.ts +196 -0
  4. package/src/admission-benchmark.ts +95 -0
  5. package/src/admission-policy.ts +78 -0
  6. package/src/agent-projection.ts +53 -0
  7. package/src/agents.ts +58 -1
  8. package/src/auto-transport.ts +114 -0
  9. package/src/blocking-status.ts +63 -0
  10. package/src/capabilities.ts +145 -0
  11. package/src/capability-grant.ts +115 -0
  12. package/src/capability-router.ts +107 -0
  13. package/src/completion-delivery.ts +257 -0
  14. package/src/config-status.ts +221 -0
  15. package/src/config-ui.ts +215 -236
  16. package/src/consult-resources.ts +4 -27
  17. package/src/consult.ts +9 -1
  18. package/src/create-stateful-transport.ts +55 -0
  19. package/src/delegation-contract.ts +417 -0
  20. package/src/execution-plan.ts +322 -0
  21. package/src/execution-profiles.ts +95 -0
  22. package/src/execution-ui.ts +320 -0
  23. package/src/execution.ts +848 -158
  24. package/src/in-process-transport.ts +269 -25
  25. package/src/inspect-render.ts +101 -1
  26. package/src/inspect.ts +296 -3
  27. package/src/integration-controller.ts +98 -0
  28. package/src/limits.ts +3 -0
  29. package/src/orchestration-metrics.ts +78 -0
  30. package/src/outcome.ts +61 -0
  31. package/src/panel-child-group.ts +35 -0
  32. package/src/panel-contract.ts +343 -0
  33. package/src/panel-evidence.ts +59 -0
  34. package/src/panel-execution.ts +772 -0
  35. package/src/panel-failure.ts +56 -0
  36. package/src/panel-planning.ts +175 -0
  37. package/src/panel-prompts.ts +132 -0
  38. package/src/panel-reconciliation.ts +57 -0
  39. package/src/panel-render.ts +103 -0
  40. package/src/parallel-limit-ui.ts +112 -0
  41. package/src/params.ts +172 -3
  42. package/src/persistence.ts +182 -32
  43. package/src/prompt-resources.ts +38 -0
  44. package/src/registry-types.ts +175 -0
  45. package/src/registry.ts +466 -143
  46. package/src/render.ts +72 -6
  47. package/src/result-contract.ts +416 -0
  48. package/src/retained-semantic-state.ts +100 -0
  49. package/src/rpc-timeout-finalization.ts +207 -0
  50. package/src/rpc-transport-metadata.ts +65 -0
  51. package/src/rpc-transport.ts +990 -0
  52. package/src/rpc-turn-capture.ts +142 -0
  53. package/src/runner-result.ts +55 -0
  54. package/src/runner-usage.ts +48 -0
  55. package/src/runner.ts +325 -73
  56. package/src/semantic-snapshot.ts +214 -0
  57. package/src/settings.ts +254 -35
  58. package/src/spawn-idempotency.ts +61 -0
  59. package/src/stateful-config.ts +13 -0
  60. package/src/stateful-guidance.ts +1 -0
  61. package/src/stateful-lifecycle.ts +45 -2
  62. package/src/stateful-limit-ui.ts +246 -0
  63. package/src/stateful-limits.ts +96 -0
  64. package/src/stateful-prompt.ts +11 -2
  65. package/src/stateful-render.ts +48 -3
  66. package/src/stateful.ts +467 -357
  67. package/src/subagents.ts +114 -46
  68. package/src/subprocess-transport.ts +64 -5
  69. package/src/supervision.ts +103 -0
  70. package/src/timeout-checkpoint.ts +305 -0
  71. package/src/timeout-finalization.ts +75 -0
  72. package/src/transport-types.ts +68 -0
  73. package/src/transport-ui.ts +169 -0
  74. package/src/transport.ts +16 -4
  75. package/src/turn-budget.ts +109 -0
  76. package/src/verification-policy.ts +17 -0
  77. package/src/work-item-ledger.ts +682 -0
  78. package/src/work-item-persistence.ts +218 -0
  79. package/src/workflow-planning.ts +150 -0
  80. package/src/workflow-ui.ts +61 -0
  81. package/src/workspace.ts +69 -12
@@ -0,0 +1,55 @@
1
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
+ import { discoverAgents, type SubagentSettings, type SubagentTransportKind } from "./agents.js";
3
+ import { AutoTransport } from "./auto-transport.js";
4
+ import {
5
+ type ChildSessionFactory,
6
+ InProcessTransport,
7
+ type ParentRuntimeSnapshot,
8
+ } from "./in-process-transport.js";
9
+ import { RpcTransport } from "./rpc-transport.js";
10
+ import { SubprocessTransport } from "./subprocess-transport.js";
11
+ import type { SubagentTransport } from "./transport.js";
12
+
13
+ export interface CreateStatefulTransportOptions {
14
+ kind: SubagentTransportKind;
15
+ modelRegistry: ModelRegistry;
16
+ getParentRuntime(): ParentRuntimeSnapshot;
17
+ getSettings(): SubagentSettings | undefined;
18
+ createInProcessSession?: ChildSessionFactory;
19
+ }
20
+
21
+ export function createStatefulTransport(
22
+ options: CreateStatefulTransportOptions,
23
+ ): SubagentTransport {
24
+ const subprocess = () => new SubprocessTransport({ getSettings: options.getSettings });
25
+ const inProcess = () =>
26
+ new InProcessTransport({
27
+ modelRegistry: options.modelRegistry,
28
+ getParentRuntime: options.getParentRuntime,
29
+ createSession: options.createInProcessSession,
30
+ discoverAgent: (agent) =>
31
+ discoverAgents(agent.cwd, agent.agentScope ?? "user", options.getSettings()).agents.find(
32
+ (candidate) => candidate.name === agent.agent,
33
+ ),
34
+ });
35
+ const rpc = () =>
36
+ new RpcTransport({
37
+ getSettings: options.getSettings,
38
+ getParentRuntime: options.getParentRuntime,
39
+ });
40
+ switch (options.kind) {
41
+ case "subprocess":
42
+ return subprocess();
43
+ case "in-process":
44
+ return inProcess();
45
+ case "rpc":
46
+ return rpc();
47
+ case "auto":
48
+ return new AutoTransport({
49
+ subprocess: subprocess(),
50
+ inProcess: inProcess(),
51
+ rpc: rpc(),
52
+ getSettings: options.getSettings,
53
+ });
54
+ }
55
+ }
@@ -0,0 +1,417 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { Type } from "typebox";
3
+ import { redactPrivateText } from "./context.js";
4
+ import { DEFAULT_MAX_CONTEXT_BYTES, MAX_SUBAGENT_TIMEOUT_MS, truncateUtf8 } from "./limits.js";
5
+
6
+ export const DELEGATION_CONTRACT_VERSION = "pi-subagents:delegation:v2" as const;
7
+ export const DELEGATION_CONTRACT_LEVELS = ["minimal", "full"] as const;
8
+ export const DELEGATION_ENFORCEMENT_MODES = ["audit", "enforce"] as const;
9
+ export const AUTHORITY_REQUIREMENTS = ["unspecified", "denied", "required"] as const;
10
+ export const DELEGATION_SIDE_EFFECT_POLICIES = ["read-only", "idempotent", "mutating"] as const;
11
+
12
+ const MAX_IDENTIFIER_BYTES = 256;
13
+ const MAX_TEXT_BYTES = 16 * 1024;
14
+ const MAX_ITEM_BYTES = 4 * 1024;
15
+ const MAX_ITEMS = 50;
16
+ const MAX_TURNS_OR_TOOLS = 1_000_000;
17
+
18
+ const BoundedString = Type.String({ maxLength: MAX_TEXT_BYTES });
19
+ const BoundedItem = Type.String({ maxLength: MAX_ITEM_BYTES });
20
+ const BoundedItems = Type.Array(BoundedItem, { maxItems: MAX_ITEMS });
21
+ const DependencySchema = Type.Object(
22
+ {
23
+ taskId: Type.String({ minLength: 1, maxLength: MAX_IDENTIFIER_BYTES }),
24
+ artifactId: Type.Optional(Type.String({ minLength: 1, maxLength: MAX_IDENTIFIER_BYTES })),
25
+ version: Type.Optional(Type.String({ minLength: 1, maxLength: MAX_IDENTIFIER_BYTES })),
26
+ },
27
+ { additionalProperties: false },
28
+ );
29
+
30
+ export const DelegationContractSchema = Type.Object(
31
+ {
32
+ version: Type.Literal(DELEGATION_CONTRACT_VERSION),
33
+ level: StringEnum(DELEGATION_CONTRACT_LEVELS),
34
+ taskId: Type.String({ minLength: 1, maxLength: MAX_IDENTIFIER_BYTES }),
35
+ objective: BoundedString,
36
+ nonGoals: Type.Optional(BoundedItems),
37
+ dependencies: Type.Optional(Type.Array(DependencySchema, { maxItems: MAX_ITEMS })),
38
+ requiredInputs: Type.Optional(BoundedItems),
39
+ requestedAuthority: Type.Optional(
40
+ Type.Object(
41
+ {
42
+ capabilities: Type.Optional(BoundedItems),
43
+ tools: Type.Optional(BoundedItems),
44
+ readPaths: Type.Optional(BoundedItems),
45
+ writePaths: Type.Optional(BoundedItems),
46
+ network: Type.Optional(StringEnum(AUTHORITY_REQUIREMENTS)),
47
+ secrets: Type.Optional(StringEnum(AUTHORITY_REQUIREMENTS)),
48
+ },
49
+ { additionalProperties: false },
50
+ ),
51
+ ),
52
+ acceptanceCriteria: Type.Optional(BoundedItems),
53
+ requiredEvidence: Type.Optional(BoundedItems),
54
+ budget: Type.Optional(
55
+ Type.Object(
56
+ {
57
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_SUBAGENT_TIMEOUT_MS })),
58
+ maxTurns: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_TURNS_OR_TOOLS })),
59
+ maxToolCalls: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_TURNS_OR_TOOLS })),
60
+ },
61
+ { additionalProperties: false },
62
+ ),
63
+ ),
64
+ admission: Type.Optional(
65
+ Type.Object(
66
+ {
67
+ contextPressure: StringEnum(["low", "medium", "high"] as const),
68
+ independentWorkItems: Type.Integer({ minimum: 1, maximum: 2 }),
69
+ coupling: StringEnum(["dense", "sparse"] as const),
70
+ verificationRequired: Type.Boolean(),
71
+ verificationAvailable: Type.Boolean(),
72
+ budgetAllowsChildren: Type.Boolean(),
73
+ requirementsComplete: Type.Boolean(),
74
+ },
75
+ { additionalProperties: false },
76
+ ),
77
+ ),
78
+ sideEffectPolicy: Type.Optional(StringEnum(DELEGATION_SIDE_EFFECT_POLICIES)),
79
+ enforcement: Type.Optional(StringEnum(DELEGATION_ENFORCEMENT_MODES)),
80
+ },
81
+ { additionalProperties: false },
82
+ );
83
+
84
+ export interface DelegationDependency {
85
+ taskId: string;
86
+ artifactId?: string;
87
+ version?: string;
88
+ }
89
+
90
+ export interface DelegationAuthorityRequest {
91
+ capabilities?: string[];
92
+ tools?: string[];
93
+ readPaths?: string[];
94
+ writePaths?: string[];
95
+ network?: (typeof AUTHORITY_REQUIREMENTS)[number];
96
+ secrets?: (typeof AUTHORITY_REQUIREMENTS)[number];
97
+ }
98
+
99
+ export interface DelegationBudgetRequest {
100
+ timeoutMs?: number;
101
+ maxTurns?: number;
102
+ maxToolCalls?: number;
103
+ }
104
+
105
+ export interface DelegationAdmissionRequest {
106
+ contextPressure: "low" | "medium" | "high";
107
+ independentWorkItems: number;
108
+ coupling: "dense" | "sparse";
109
+ verificationRequired: boolean;
110
+ verificationAvailable: boolean;
111
+ budgetAllowsChildren: boolean;
112
+ requirementsComplete: boolean;
113
+ }
114
+
115
+ export interface DelegationContract {
116
+ version: typeof DELEGATION_CONTRACT_VERSION;
117
+ level: (typeof DELEGATION_CONTRACT_LEVELS)[number];
118
+ taskId: string;
119
+ objective: string;
120
+ nonGoals: string[];
121
+ dependencies: DelegationDependency[];
122
+ requiredInputs: string[];
123
+ requestedAuthority?: DelegationAuthorityRequest;
124
+ acceptanceCriteria: string[];
125
+ requiredEvidence: string[];
126
+ budget?: DelegationBudgetRequest;
127
+ admission?: DelegationAdmissionRequest;
128
+ sideEffectPolicy: (typeof DELEGATION_SIDE_EFFECT_POLICIES)[number];
129
+ enforcement: (typeof DELEGATION_ENFORCEMENT_MODES)[number];
130
+ }
131
+
132
+ export interface AppendedDelegationContract {
133
+ text: string;
134
+ contract?: DelegationContract;
135
+ truncated: boolean;
136
+ }
137
+
138
+ export function normalizeDelegationContract(value: unknown): DelegationContract | undefined {
139
+ if (!isPlainObject(value)) return undefined;
140
+ if (
141
+ !hasOnlyKeys(value, [
142
+ "version",
143
+ "level",
144
+ "taskId",
145
+ "objective",
146
+ "nonGoals",
147
+ "dependencies",
148
+ "requiredInputs",
149
+ "requestedAuthority",
150
+ "acceptanceCriteria",
151
+ "requiredEvidence",
152
+ "budget",
153
+ "admission",
154
+ "sideEffectPolicy",
155
+ "enforcement",
156
+ ])
157
+ ) {
158
+ return undefined;
159
+ }
160
+ if (
161
+ value.version !== DELEGATION_CONTRACT_VERSION ||
162
+ typeof value.level !== "string" ||
163
+ !DELEGATION_CONTRACT_LEVELS.includes(
164
+ value.level as (typeof DELEGATION_CONTRACT_LEVELS)[number],
165
+ ) ||
166
+ typeof value.taskId !== "string" ||
167
+ !value.taskId.trim() ||
168
+ typeof value.objective !== "string"
169
+ ) {
170
+ return undefined;
171
+ }
172
+ const taskId = bounded(value.taskId, MAX_IDENTIFIER_BYTES);
173
+ const objective = bounded(value.objective, MAX_TEXT_BYTES);
174
+ if (!taskId || !objective) return undefined;
175
+ const nonGoals = normalizeStrings(value.nonGoals);
176
+ const requiredInputs = normalizeStrings(value.requiredInputs);
177
+ const acceptanceCriteria = normalizeStrings(value.acceptanceCriteria);
178
+ const requiredEvidence = normalizeStrings(value.requiredEvidence);
179
+ if (!nonGoals || !requiredInputs || !acceptanceCriteria || !requiredEvidence) return undefined;
180
+ const dependencies = normalizeDependencies(value.dependencies);
181
+ if (!dependencies) return undefined;
182
+ const authority = normalizeAuthority(value.requestedAuthority);
183
+ if (authority === false) return undefined;
184
+ const budget = normalizeBudget(value.budget);
185
+ if (budget === false) return undefined;
186
+ const admission = normalizeAdmission(value.admission);
187
+ if (admission === false) return undefined;
188
+ const sideEffectPolicy = value.sideEffectPolicy ?? "mutating";
189
+ if (
190
+ typeof sideEffectPolicy !== "string" ||
191
+ !DELEGATION_SIDE_EFFECT_POLICIES.includes(
192
+ sideEffectPolicy as (typeof DELEGATION_SIDE_EFFECT_POLICIES)[number],
193
+ )
194
+ ) {
195
+ return undefined;
196
+ }
197
+ const enforcement = value.enforcement ?? "audit";
198
+ if (
199
+ typeof enforcement !== "string" ||
200
+ !DELEGATION_ENFORCEMENT_MODES.includes(
201
+ enforcement as (typeof DELEGATION_ENFORCEMENT_MODES)[number],
202
+ )
203
+ ) {
204
+ return undefined;
205
+ }
206
+ return {
207
+ version: DELEGATION_CONTRACT_VERSION,
208
+ level: value.level as DelegationContract["level"],
209
+ taskId,
210
+ objective,
211
+ nonGoals,
212
+ dependencies,
213
+ requiredInputs,
214
+ ...(authority === undefined ? {} : { requestedAuthority: authority }),
215
+ acceptanceCriteria,
216
+ requiredEvidence,
217
+ ...(budget === undefined ? {} : { budget }),
218
+ ...(admission === undefined ? {} : { admission }),
219
+ sideEffectPolicy: sideEffectPolicy as DelegationContract["sideEffectPolicy"],
220
+ enforcement: enforcement as DelegationContract["enforcement"],
221
+ };
222
+ }
223
+
224
+ export function appendDelegationContract(
225
+ prompt: string,
226
+ value: unknown,
227
+ maxBytes = DEFAULT_MAX_CONTEXT_BYTES,
228
+ ): AppendedDelegationContract {
229
+ const contract = normalizeDelegationContract(value);
230
+ if (!contract) return { text: prompt, truncated: false };
231
+ const suffix = [
232
+ "",
233
+ "Delegation contract:",
234
+ JSON.stringify(contract),
235
+ "The requested authority is advisory until an executor-owned ExecutionPlan confirms which controls are enforceable and effective.",
236
+ "Acknowledge missing inputs, authority, capabilities, or verification instead of guessing.",
237
+ ].join("\n");
238
+ const suffixBytes = Buffer.byteLength(suffix, "utf8");
239
+ const boundedPrompt = truncateUtf8(
240
+ redactPrivateText(prompt),
241
+ Math.max(0, maxBytes - suffixBytes),
242
+ );
243
+ const text = truncateUtf8(`${boundedPrompt.text}${suffix}`, maxBytes);
244
+ return {
245
+ text: text.text,
246
+ contract,
247
+ truncated: boundedPrompt.truncated || text.truncated,
248
+ };
249
+ }
250
+
251
+ function normalizeAdmission(value: unknown): DelegationAdmissionRequest | undefined | false {
252
+ if (value === undefined) return undefined;
253
+ if (!isPlainObject(value)) return false;
254
+ if (
255
+ !hasOnlyKeys(value, [
256
+ "contextPressure",
257
+ "independentWorkItems",
258
+ "coupling",
259
+ "verificationRequired",
260
+ "verificationAvailable",
261
+ "budgetAllowsChildren",
262
+ "requirementsComplete",
263
+ ]) ||
264
+ !["low", "medium", "high"].includes(String(value.contextPressure)) ||
265
+ !Number.isSafeInteger(value.independentWorkItems) ||
266
+ Number(value.independentWorkItems) < 1 ||
267
+ Number(value.independentWorkItems) > 2 ||
268
+ !["dense", "sparse"].includes(String(value.coupling)) ||
269
+ typeof value.verificationRequired !== "boolean" ||
270
+ typeof value.verificationAvailable !== "boolean" ||
271
+ typeof value.budgetAllowsChildren !== "boolean" ||
272
+ typeof value.requirementsComplete !== "boolean"
273
+ ) {
274
+ return false;
275
+ }
276
+ return {
277
+ contextPressure: value.contextPressure as DelegationAdmissionRequest["contextPressure"],
278
+ independentWorkItems: Number(value.independentWorkItems),
279
+ coupling: value.coupling as DelegationAdmissionRequest["coupling"],
280
+ verificationRequired: value.verificationRequired,
281
+ verificationAvailable: value.verificationAvailable,
282
+ budgetAllowsChildren: value.budgetAllowsChildren,
283
+ requirementsComplete: value.requirementsComplete,
284
+ };
285
+ }
286
+
287
+ function normalizeDependencies(value: unknown): DelegationDependency[] | undefined {
288
+ if (value === undefined) return [];
289
+ if (!Array.isArray(value) || value.length > MAX_ITEMS) return undefined;
290
+ const result: DelegationDependency[] = [];
291
+ const seen = new Set<string>();
292
+ for (const item of value) {
293
+ if (
294
+ !isPlainObject(item) ||
295
+ !hasOnlyKeys(item, ["taskId", "artifactId", "version"]) ||
296
+ typeof item.taskId !== "string"
297
+ ) {
298
+ return undefined;
299
+ }
300
+ const taskId = bounded(item.taskId, MAX_IDENTIFIER_BYTES);
301
+ if (!taskId || seen.has(taskId)) return undefined;
302
+ seen.add(taskId);
303
+ const artifactId = optionalString(item.artifactId, MAX_IDENTIFIER_BYTES);
304
+ const version = optionalString(item.version, MAX_IDENTIFIER_BYTES);
305
+ if (artifactId === false || version === false) return undefined;
306
+ result.push({
307
+ taskId,
308
+ ...(artifactId === undefined ? {} : { artifactId }),
309
+ ...(version === undefined ? {} : { version }),
310
+ });
311
+ }
312
+ return result;
313
+ }
314
+
315
+ function normalizeAuthority(value: unknown): DelegationAuthorityRequest | undefined | false {
316
+ if (value === undefined) return undefined;
317
+ if (!isPlainObject(value)) return false;
318
+ if (
319
+ !hasOnlyKeys(value, ["capabilities", "tools", "readPaths", "writePaths", "network", "secrets"])
320
+ ) {
321
+ return false;
322
+ }
323
+ const capabilities = normalizeOptionalStrings(value.capabilities);
324
+ const tools = normalizeOptionalStrings(value.tools);
325
+ const readPaths = normalizeOptionalStrings(value.readPaths);
326
+ const writePaths = normalizeOptionalStrings(value.writePaths);
327
+ if (capabilities === false || tools === false || readPaths === false || writePaths === false) {
328
+ return false;
329
+ }
330
+ const network = normalizeAuthorityRequirement(value.network);
331
+ const secrets = normalizeAuthorityRequirement(value.secrets);
332
+ if (network === false || secrets === false) return false;
333
+ return {
334
+ ...(capabilities === undefined ? {} : { capabilities }),
335
+ ...(tools === undefined ? {} : { tools }),
336
+ ...(readPaths === undefined ? {} : { readPaths }),
337
+ ...(writePaths === undefined ? {} : { writePaths }),
338
+ ...(network === undefined ? {} : { network }),
339
+ ...(secrets === undefined ? {} : { secrets }),
340
+ };
341
+ }
342
+
343
+ function normalizeBudget(value: unknown): DelegationBudgetRequest | undefined | false {
344
+ if (value === undefined) return undefined;
345
+ if (!isPlainObject(value) || !hasOnlyKeys(value, ["timeoutMs", "maxTurns", "maxToolCalls"])) {
346
+ return false;
347
+ }
348
+ const timeoutMs = optionalInteger(value.timeoutMs, MAX_SUBAGENT_TIMEOUT_MS);
349
+ const maxTurns = optionalInteger(value.maxTurns, MAX_TURNS_OR_TOOLS);
350
+ const maxToolCalls = optionalInteger(value.maxToolCalls, MAX_TURNS_OR_TOOLS);
351
+ if (timeoutMs === false || maxTurns === false || maxToolCalls === false) return false;
352
+ return {
353
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
354
+ ...(maxTurns === undefined ? {} : { maxTurns }),
355
+ ...(maxToolCalls === undefined ? {} : { maxToolCalls }),
356
+ };
357
+ }
358
+
359
+ function normalizeStrings(value: unknown): string[] | undefined {
360
+ if (value === undefined) return [];
361
+ const normalized = normalizeOptionalStrings(value);
362
+ return normalized === false ? undefined : normalized;
363
+ }
364
+
365
+ function normalizeOptionalStrings(value: unknown): string[] | undefined | false {
366
+ if (value === undefined) return undefined;
367
+ if (!Array.isArray(value) || value.length > MAX_ITEMS) return false;
368
+ const result: string[] = [];
369
+ const seen = new Set<string>();
370
+ for (const item of value) {
371
+ if (typeof item !== "string") return false;
372
+ const normalized = bounded(item, MAX_ITEM_BYTES);
373
+ if (!normalized || seen.has(normalized)) continue;
374
+ seen.add(normalized);
375
+ result.push(normalized);
376
+ }
377
+ return result;
378
+ }
379
+
380
+ function normalizeAuthorityRequirement(
381
+ value: unknown,
382
+ ): (typeof AUTHORITY_REQUIREMENTS)[number] | undefined | false {
383
+ if (value === undefined) return undefined;
384
+ if (
385
+ typeof value !== "string" ||
386
+ !AUTHORITY_REQUIREMENTS.includes(value as (typeof AUTHORITY_REQUIREMENTS)[number])
387
+ ) {
388
+ return false;
389
+ }
390
+ return value as (typeof AUTHORITY_REQUIREMENTS)[number];
391
+ }
392
+
393
+ function optionalString(value: unknown, maxBytes: number): string | undefined | false {
394
+ if (value === undefined) return undefined;
395
+ if (typeof value !== "string") return false;
396
+ const normalized = bounded(value, maxBytes);
397
+ return normalized || false;
398
+ }
399
+
400
+ function optionalInteger(value: unknown, max: number): number | undefined | false {
401
+ if (value === undefined) return undefined;
402
+ if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > max)
403
+ return false;
404
+ return value as number;
405
+ }
406
+
407
+ function bounded(value: string, maxBytes: number): string {
408
+ return truncateUtf8(redactPrivateText(value), maxBytes).text.trim();
409
+ }
410
+
411
+ function hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {
412
+ return Object.keys(value).every((key) => allowed.includes(key));
413
+ }
414
+
415
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
416
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
417
+ }