@tokensize/agent-router 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,717 @@
1
+ // src/contracts.ts
2
+ import { z } from "zod";
3
+ var AGENT_ROUTER_SCHEMA_VERSION = 2;
4
+ var AGENT_ROUTER_VERSION = "2026-07-20-allowance-aware-v2";
5
+ var harnessIdSchema = z.enum(["codex", "claude", "copilot", "cursor", "opencode", "custom"]);
6
+ var readinessSchema = z.enum([
7
+ "installed",
8
+ "auth-ready",
9
+ "model-listed",
10
+ "invocation-compatible",
11
+ "live-confirmed"
12
+ ]);
13
+ var permissionProfileSchema = z.enum(["inspect", "edit", "test", "network"]);
14
+ var taskRoleSchema = z.enum(["inspect", "plan", "implement", "review", "test"]);
15
+ var taskTypeSchema = z.enum([
16
+ "bug",
17
+ "feature",
18
+ "refactor",
19
+ "migration",
20
+ "review",
21
+ "research",
22
+ "docs",
23
+ "test",
24
+ "unknown"
25
+ ]);
26
+ var routingObjectiveSchema = z.enum(["quality", "balanced", "tokens", "latency"]);
27
+ var clientSurfaceSchema = z.enum(["cli", "skill", "codex-plugin", "opencode-plugin"]);
28
+ var allowanceSchema = z.object({
29
+ status: z.enum(["available", "low", "exhausted", "unmetered", "unknown"]),
30
+ remainingFraction: z.number().min(0).max(1).optional(),
31
+ resetsAt: z.iso.datetime().optional(),
32
+ observedAt: z.iso.datetime(),
33
+ source: z.enum(["runtime-reported", "credential-free", "unavailable"])
34
+ });
35
+ var agentModelSchema = z.object({
36
+ id: z.string().min(1).max(256),
37
+ harness: harnessIdSchema,
38
+ nativeModelId: z.string().min(1).max(200),
39
+ displayName: z.string().min(1).max(200),
40
+ readiness: readinessSchema,
41
+ authMode: z.enum(["subscription", "api-key", "cloud-provider", "local", "unknown"]),
42
+ productUseApproved: z.boolean(),
43
+ capabilities: z.object({
44
+ tools: z.boolean(),
45
+ vision: z.boolean(),
46
+ structuredOutput: z.enum(["none", "json", "jsonl", "schema"]),
47
+ sessions: z.enum(["none", "resume", "continue"]),
48
+ permissions: z.array(permissionProfileSchema).min(1)
49
+ }),
50
+ identityProof: z.enum(["requested", "runtime-reported", "unavailable"]),
51
+ qualityPrior: z.number().min(0).max(1),
52
+ tokenEfficiencyPrior: z.number().min(0).max(1),
53
+ latencyPrior: z.number().min(0).max(1),
54
+ allowance: allowanceSchema.optional(),
55
+ localHistory: z.object({
56
+ verifiedRuns: z.number().int().nonnegative(),
57
+ successRate: z.number().min(0).max(1),
58
+ medianTokens: z.number().nonnegative().optional()
59
+ }).optional()
60
+ });
61
+ var agentTaskFeaturesSchema = z.object({
62
+ role: taskRoleSchema,
63
+ type: taskTypeSchema,
64
+ complexity: z.number().min(0).max(1),
65
+ scopeBreadth: z.number().min(0).max(1),
66
+ contextTokens: z.number().int().nonnegative(),
67
+ oracleStrength: z.number().min(0).max(1),
68
+ codeDensity: z.number().min(0).max(1),
69
+ risk: z.enum(["low", "medium", "high", "critical"]),
70
+ languages: z.array(z.string().min(1).max(50)).max(20),
71
+ requiredTools: z.array(z.string().min(1).max(80)).max(30),
72
+ requiresVision: z.boolean(),
73
+ requiresNetwork: z.boolean(),
74
+ cacheHit: z.boolean()
75
+ });
76
+ var agentRouteRequestSchema = z.object({
77
+ schemaVersion: z.literal(AGENT_ROUTER_SCHEMA_VERSION),
78
+ client: z.object({
79
+ surface: clientSurfaceSchema,
80
+ version: z.string().min(1).max(100)
81
+ }),
82
+ requestId: z.uuid(),
83
+ installationId: z.string().min(8).max(128),
84
+ routerMode: z.enum(["metadata-only", "prompt-assisted"]),
85
+ task: agentTaskFeaturesSchema,
86
+ prompt: z.string().min(1).max(12e3).optional(),
87
+ candidates: z.array(agentModelSchema).max(100),
88
+ root: z.object({
89
+ harness: harnessIdSchema,
90
+ active: z.boolean(),
91
+ modelId: z.string().min(1).max(200).optional(),
92
+ qualityPrior: z.number().min(0).max(1).default(0.9),
93
+ allowance: allowanceSchema.optional()
94
+ }),
95
+ policy: z.object({
96
+ objective: routingObjectiveSchema,
97
+ maxDelegationDepth: z.number().int().min(0).max(3),
98
+ delegationDepth: z.number().int().min(0).max(10),
99
+ allowedHarnesses: z.array(harnessIdSchema).max(10).optional(),
100
+ permissionCeiling: permissionProfileSchema,
101
+ tokenBudget: z.number().int().positive().max(1e7).optional(),
102
+ wallTimeBudgetMs: z.number().int().positive().max(864e5).optional()
103
+ })
104
+ });
105
+ var workflowSchema = z.enum([
106
+ "root-only",
107
+ "single-inspector",
108
+ "single-implementer",
109
+ "implementer-deterministic-verify",
110
+ "implementer-independent-review"
111
+ ]);
112
+ var executionPlanSchema = z.object({
113
+ workflow: workflowSchema,
114
+ targetId: z.string().min(1).max(256).nullable(),
115
+ permissionProfile: permissionProfileSchema,
116
+ maxWallMs: z.number().int().positive(),
117
+ maxTurns: z.number().int().positive().max(100),
118
+ requiresWorktree: z.boolean()
119
+ });
120
+ var agentRouteResponseSchema = z.object({
121
+ schemaVersion: z.literal(AGENT_ROUTER_SCHEMA_VERSION),
122
+ requestId: z.uuid(),
123
+ routeId: z.uuid(),
124
+ routerVersion: z.string().min(1),
125
+ expiresAt: z.iso.datetime(),
126
+ plan: executionPlanSchema,
127
+ fallback: executionPlanSchema,
128
+ confidence: z.number().min(0).max(1),
129
+ reasonCodes: z.array(z.string().min(1)).max(20),
130
+ expected: z.object({
131
+ verifiedSuccess: z.number().min(0).max(1),
132
+ contextTokens: z.number().int().nonnegative(),
133
+ wallTimeMs: z.number().int().nonnegative()
134
+ }),
135
+ feedbackToken: z.string().min(16).max(200)
136
+ });
137
+ var agentFeedbackSchema = z.object({
138
+ schemaVersion: z.literal(AGENT_ROUTER_SCHEMA_VERSION),
139
+ routeId: z.uuid(),
140
+ feedbackToken: z.string().min(16).max(200),
141
+ idempotencyKey: z.string().min(1).max(200),
142
+ status: z.enum(["completed", "verified", "failed", "blocked", "cancelled"]),
143
+ confirmedTargetId: z.string().min(1).max(256).nullable(),
144
+ identityConfirmed: z.boolean(),
145
+ checksPassed: z.number().int().nonnegative(),
146
+ checksFailed: z.number().int().nonnegative(),
147
+ retries: z.number().int().nonnegative().max(100),
148
+ usage: z.object({
149
+ inputTokens: z.number().int().nonnegative().optional(),
150
+ outputTokens: z.number().int().nonnegative().optional(),
151
+ contextTokensEstimated: z.number().int().nonnegative(),
152
+ source: z.enum(["reported", "estimated", "unknown"])
153
+ }),
154
+ timings: z.object({
155
+ totalMs: z.number().int().nonnegative(),
156
+ routingMs: z.number().int().nonnegative(),
157
+ executionMs: z.number().int().nonnegative(),
158
+ verificationMs: z.number().int().nonnegative()
159
+ }),
160
+ failureCode: z.string().min(1).max(100).optional()
161
+ });
162
+
163
+ // src/featurize.ts
164
+ function has(text, pattern) {
165
+ return pattern.test(text);
166
+ }
167
+ function clamp(value) {
168
+ return Math.max(0, Math.min(1, value));
169
+ }
170
+ function featurizeAgentTask(input) {
171
+ const text = input.task.trim();
172
+ const lower = text.toLowerCase();
173
+ const role = input.role ?? (input.permissionProfile === "inspect" ? "inspect" : "implement");
174
+ let type = "unknown";
175
+ if (has(lower, /\b(bug|fix|broken|regression|error|crash)\b/)) type = "bug";
176
+ else if (has(lower, /\b(refactor|cleanup|restructure|simplif)\w*\b/)) type = "refactor";
177
+ else if (has(lower, /\b(migrat|upgrade|port)\w*\b/)) type = "migration";
178
+ else if (has(lower, /\b(review|audit|analyse|analyze|inspect)\b/)) type = "review";
179
+ else if (has(lower, /\b(test|coverage|spec)\b/)) type = "test";
180
+ else if (has(lower, /\b(document|readme|docs|guide)\b/)) type = "docs";
181
+ else if (has(lower, /\b(research|investigate|compare)\b/)) type = "research";
182
+ else if (has(lower, /\b(add|build|create|implement|ship)\b/)) type = "feature";
183
+ const codeMatches = text.match(/```|\b(function|class|interface|const|let|SELECT|CREATE TABLE|npm|git)\b/g) ?? [];
184
+ const codeDensity = clamp(codeMatches.length / Math.max(4, text.split(/\s+/).length / 8));
185
+ const scopeBreadth = clamp(((input.scopePaths?.length ?? 1) - 1) / 12 + (has(lower, /\b(repo|workspace|all|across)\b/) ? 0.25 : 0));
186
+ const acceptanceCount = input.acceptance?.length ?? 0;
187
+ const complexity = clamp(
188
+ 0.16 + Math.min(text.length / 3e3, 0.3) + scopeBreadth * 0.25 + Math.min(acceptanceCount * 0.04, 0.16) + (has(lower, /\b(security|migration|concurrency|distributed|architecture|production)\b/) ? 0.2 : 0)
189
+ );
190
+ const risk = has(lower, /\b(secret|credential|payment|production deploy|delete data)\b/) ? "critical" : has(lower, /\b(auth|security|migration|database|deploy|billing)\b/) ? "high" : complexity > 0.65 ? "medium" : "low";
191
+ const oracleStrength = clamp(
192
+ (type === "test" || has(lower, /\b(test|typecheck|lint|build|benchmark|acceptance)\b/) ? 0.65 : 0.2) + Math.min(acceptanceCount * 0.05, 0.25)
193
+ );
194
+ return {
195
+ role,
196
+ type,
197
+ complexity,
198
+ scopeBreadth,
199
+ contextTokens: Math.max(0, Math.round(input.contextTokens ?? text.length / 4)),
200
+ oracleStrength,
201
+ codeDensity,
202
+ risk,
203
+ languages: [...new Set(input.languages ?? [])].slice(0, 20),
204
+ requiredTools: [...new Set(input.requiredTools ?? [])].slice(0, 30),
205
+ requiresVision: has(lower, /\b(image|screenshot|visual|design|browser)\b/),
206
+ requiresNetwork: input.permissionProfile === "network" || has(lower, /\b(web|internet|latest|browse|api docs)\b/),
207
+ cacheHit: false
208
+ };
209
+ }
210
+
211
+ // src/route.ts
212
+ var QUALITY_EQUIVALENCE_MARGIN = 5e-3;
213
+ var LOW_ALLOWANCE_THRESHOLD = 0.15;
214
+ var permissionRank = {
215
+ inspect: 0,
216
+ edit: 1,
217
+ test: 2,
218
+ network: 3
219
+ };
220
+ function rootPlan() {
221
+ return {
222
+ workflow: "root-only",
223
+ targetId: null,
224
+ permissionProfile: "inspect",
225
+ maxWallMs: 3e5,
226
+ maxTurns: 1,
227
+ requiresWorktree: false
228
+ };
229
+ }
230
+ function requiredPermission(request) {
231
+ if (request.task.requiresNetwork) return "network";
232
+ if (request.task.role === "test") return "test";
233
+ if (request.task.role === "implement") return "edit";
234
+ return "inspect";
235
+ }
236
+ function readinessScore(model) {
237
+ return {
238
+ installed: 0,
239
+ "auth-ready": 0.25,
240
+ "model-listed": 0.6,
241
+ "invocation-compatible": 0.85,
242
+ "live-confirmed": 1
243
+ }[model.readiness];
244
+ }
245
+ function candidateQuality(request, model) {
246
+ const history = model.localHistory;
247
+ const historyQuality = history && history.verifiedRuns >= 3 ? history.successRate : model.qualityPrior;
248
+ let quality = model.qualityPrior * 0.7 + historyQuality * 0.3;
249
+ if (request.task.codeDensity > 0.2 && model.capabilities.tools) quality += 0.03;
250
+ if (request.task.requiresVision && model.capabilities.vision) quality += 0.04;
251
+ return quality * (0.8 + readinessScore(model) * 0.2);
252
+ }
253
+ function candidateScore(request, model) {
254
+ const quality = candidateQuality(request, model);
255
+ switch (request.policy.objective) {
256
+ case "quality":
257
+ return quality;
258
+ case "tokens":
259
+ return quality * 0.65 + model.tokenEfficiencyPrior * 0.35;
260
+ case "latency":
261
+ return quality * 0.65 + model.latencyPrior * 0.35;
262
+ case "balanced":
263
+ return quality * 0.7 + model.tokenEfficiencyPrior * 0.2 + model.latencyPrior * 0.1;
264
+ }
265
+ }
266
+ function allowanceScore(allowance) {
267
+ if (!allowance || allowance.status === "unknown") return 2;
268
+ if (allowance.status === "unmetered") return 4;
269
+ if (allowance.status === "exhausted") return -1;
270
+ if (allowance.status === "available") return 3 + (allowance.remainingFraction ?? 0);
271
+ return 1 + (allowance.remainingFraction ?? 0);
272
+ }
273
+ function allowanceConstrained(allowance) {
274
+ return allowance?.status === "exhausted" || allowance?.status === "low" || allowance?.remainingFraction !== void 0 && allowance.remainingFraction <= LOW_ALLOWANCE_THRESHOLD;
275
+ }
276
+ function workflowFor(request) {
277
+ if (request.task.role === "inspect" || request.task.role === "plan" || request.task.role === "review") {
278
+ return "single-inspector";
279
+ }
280
+ if (request.task.role === "implement" && request.task.oracleStrength >= 0.4) {
281
+ return "implementer-deterministic-verify";
282
+ }
283
+ if (request.task.role === "implement" && (request.task.risk === "high" || request.task.risk === "critical")) {
284
+ return "implementer-independent-review";
285
+ }
286
+ return "single-implementer";
287
+ }
288
+ function selectAgentRoute(request) {
289
+ const fallback = rootPlan();
290
+ const permission = requiredPermission(request);
291
+ const reasons = [];
292
+ if (permissionRank[permission] > permissionRank[request.policy.permissionCeiling]) {
293
+ return {
294
+ plan: fallback,
295
+ fallback,
296
+ confidence: 1,
297
+ reasonCodes: ["PERMISSION_CEILING_EXCEEDED"],
298
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
299
+ };
300
+ }
301
+ if (request.policy.delegationDepth >= request.policy.maxDelegationDepth) {
302
+ return {
303
+ plan: fallback,
304
+ fallback,
305
+ confidence: 1,
306
+ reasonCodes: ["DELEGATION_DEPTH_LIMIT"],
307
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
308
+ };
309
+ }
310
+ const capabilityEligible = request.candidates.filter((candidate) => {
311
+ if (!candidate.productUseApproved) return false;
312
+ if (readinessScore(candidate) < 0.6) return false;
313
+ if (!candidate.capabilities.permissions.includes(permission)) return false;
314
+ if (request.policy.allowedHarnesses && !request.policy.allowedHarnesses.includes(candidate.harness)) return false;
315
+ if (request.root.active && candidate.harness === request.root.harness) return false;
316
+ if (request.task.requiresVision && !candidate.capabilities.vision) return false;
317
+ return true;
318
+ });
319
+ if (capabilityEligible.length === 0) {
320
+ return {
321
+ plan: fallback,
322
+ fallback,
323
+ confidence: 1,
324
+ reasonCodes: ["NO_ELIGIBLE_LOCAL_TARGET"],
325
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
326
+ };
327
+ }
328
+ const eligible = capabilityEligible.filter((candidate) => candidate.allowance?.status !== "exhausted");
329
+ if (eligible.length === 0) {
330
+ return {
331
+ plan: fallback,
332
+ fallback,
333
+ confidence: 1,
334
+ reasonCodes: ["LOCAL_ALLOWANCE_EXHAUSTED"],
335
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
336
+ };
337
+ }
338
+ const ranked = eligible.map((candidate) => ({
339
+ candidate,
340
+ quality: candidateQuality(request, candidate),
341
+ score: candidateScore(request, candidate),
342
+ allowance: allowanceScore(candidate.allowance)
343
+ }));
344
+ const qualityCeiling = Math.max(...ranked.map((item) => item.quality));
345
+ const qualityPeers = ranked.filter((item) => item.quality >= qualityCeiling - QUALITY_EQUIVALENCE_MARGIN);
346
+ const allowancePeers = [...qualityPeers].sort((a, b) => b.allowance - a.allowance || b.score - a.score || a.candidate.id.localeCompare(b.candidate.id));
347
+ const rankedByUtility = [...qualityPeers].sort((a, b) => b.score - a.score || a.candidate.id.localeCompare(b.candidate.id));
348
+ const best = allowancePeers[0];
349
+ const second = [...allowancePeers, ...ranked.filter((item) => !allowancePeers.includes(item))].filter((item) => item !== best).sort((a, b) => b.score - a.score)[0];
350
+ const rootIsConstrained = allowanceConstrained(request.root.allowance);
351
+ const targetHasHealthierAllowance = best.allowance > allowanceScore(request.root.allowance);
352
+ const quotaReliefIsQualitySafe = rootIsConstrained && targetHasHealthierAllowance && best.quality >= request.root.qualityPrior - QUALITY_EQUIVALENCE_MARGIN;
353
+ if (request.task.complexity < 0.24 && request.task.scopeBreadth < 0.2 && !quotaReliefIsQualitySafe) {
354
+ return {
355
+ plan: fallback,
356
+ fallback,
357
+ confidence: 0.9,
358
+ reasonCodes: ["ROOT_MORE_EFFICIENT_FOR_SMALL_TASK"],
359
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
360
+ };
361
+ }
362
+ const delegationMargin = best.score - request.root.qualityPrior;
363
+ if (delegationMargin < -0.08 && request.task.complexity < 0.7 && !quotaReliefIsQualitySafe) {
364
+ return {
365
+ plan: fallback,
366
+ fallback,
367
+ confidence: Math.min(1, Math.abs(delegationMargin) + 0.75),
368
+ reasonCodes: ["ROOT_EXPECTED_UTILITY_HIGHER"],
369
+ expected: { verifiedSuccess: request.root.qualityPrior, contextTokens: request.task.contextTokens, wallTimeMs: 0 }
370
+ };
371
+ }
372
+ reasons.push("QUALITY_SAFE_LOCAL_TARGET");
373
+ if (rootIsConstrained) reasons.push("ROOT_ALLOWANCE_LOW");
374
+ if (targetHasHealthierAllowance) reasons.push("TARGET_ALLOWANCE_HEALTHIER");
375
+ if (best.candidate.id !== rankedByUtility[0]?.candidate.id) reasons.push("ALLOWANCE_BALANCED_WITHIN_QUALITY_TIER");
376
+ if (request.policy.objective === "tokens") reasons.push("TOKEN_EFFICIENCY_OBJECTIVE");
377
+ if (request.task.oracleStrength >= 0.4) reasons.push("DETERMINISTIC_VERIFICATION_AVAILABLE");
378
+ const workflow = workflowFor(request);
379
+ const maxWallMs = Math.min(request.policy.wallTimeBudgetMs ?? 9e5, 36e5);
380
+ const plan = {
381
+ workflow,
382
+ targetId: best.candidate.id,
383
+ permissionProfile: permission,
384
+ maxWallMs,
385
+ maxTurns: Math.max(3, Math.min(30, Math.round(5 + request.task.complexity * 15))),
386
+ requiresWorktree: permissionRank[permission] >= permissionRank.edit
387
+ };
388
+ const estimatedContext = Math.round(
389
+ request.task.contextTokens * (request.task.cacheHit ? 0.18 : 0.32) + 600 + request.task.scopeBreadth * 1200
390
+ );
391
+ return {
392
+ plan,
393
+ fallback,
394
+ confidence: Math.max(0.5, Math.min(0.99, 0.72 + (best.score - (second?.score ?? request.root.qualityPrior)) * 0.8)),
395
+ reasonCodes: reasons,
396
+ expected: {
397
+ verifiedSuccess: Math.max(0, Math.min(1, best.score)),
398
+ contextTokens: estimatedContext,
399
+ wallTimeMs: Math.round(6e4 + request.task.complexity * 42e4)
400
+ }
401
+ };
402
+ }
403
+
404
+ // src/run.ts
405
+ import { z as z2 } from "zod";
406
+ var RUN_SCHEMA_VERSION = 3;
407
+ var runStatusSchema = z2.enum([
408
+ "planned",
409
+ "awaiting-approval",
410
+ "executing",
411
+ "verifying",
412
+ "completed",
413
+ "failed",
414
+ "cancelled",
415
+ "expired"
416
+ ]);
417
+ var runActorSchema = z2.enum(["router", "root-agent", "delegate", "human", "system"]);
418
+ var approvalKindSchema = z2.enum(["subscription-use", "execute", "share-prompt"]);
419
+ var approvalSurfaceSchema = z2.enum(["local-cli", "web"]);
420
+ var usageSchema = z2.strictObject({
421
+ inputTokens: z2.number().int().nonnegative().optional(),
422
+ outputTokens: z2.number().int().nonnegative().optional(),
423
+ contextTokensEstimated: z2.number().int().nonnegative(),
424
+ source: z2.enum(["reported", "estimated", "unknown"])
425
+ });
426
+ var failureCode = z2.string().min(1).max(100);
427
+ var reasonCode = z2.string().min(1).max(100);
428
+ var eventBase = {
429
+ seq: z2.number().int().nonnegative(),
430
+ at: z2.iso.datetime(),
431
+ actor: runActorSchema
432
+ };
433
+ var runEventSchema = z2.discriminatedUnion("type", [
434
+ z2.strictObject({
435
+ ...eventBase,
436
+ type: z2.literal("created"),
437
+ data: z2.strictObject({
438
+ surface: clientSurfaceSchema,
439
+ routerMode: z2.enum(["metadata-only", "prompt-assisted"])
440
+ })
441
+ }),
442
+ z2.strictObject({
443
+ ...eventBase,
444
+ type: z2.literal("routed"),
445
+ data: z2.strictObject({
446
+ targetId: z2.string().min(1).max(256).nullable(),
447
+ workflow: executionPlanSchema.shape.workflow,
448
+ confidence: z2.number().min(0).max(1),
449
+ reasonCodes: z2.array(reasonCode).max(20)
450
+ })
451
+ }),
452
+ z2.strictObject({
453
+ ...eventBase,
454
+ type: z2.literal("approval-requested"),
455
+ data: z2.strictObject({
456
+ kind: approvalKindSchema,
457
+ harness: harnessIdSchema.optional()
458
+ })
459
+ }),
460
+ z2.strictObject({
461
+ ...eventBase,
462
+ type: z2.literal("approval-granted"),
463
+ data: z2.strictObject({
464
+ kind: approvalKindSchema,
465
+ grantedBy: approvalSurfaceSchema
466
+ })
467
+ }),
468
+ z2.strictObject({
469
+ ...eventBase,
470
+ type: z2.literal("approval-denied"),
471
+ data: z2.strictObject({
472
+ kind: approvalKindSchema,
473
+ deniedBy: approvalSurfaceSchema
474
+ })
475
+ }),
476
+ z2.strictObject({
477
+ ...eventBase,
478
+ type: z2.literal("execution-started"),
479
+ data: z2.strictObject({
480
+ targetId: z2.string().min(1).max(256),
481
+ permissionProfile: permissionProfileSchema,
482
+ worktree: z2.boolean()
483
+ })
484
+ }),
485
+ z2.strictObject({
486
+ ...eventBase,
487
+ type: z2.literal("execution-progress"),
488
+ data: z2.strictObject({
489
+ turn: z2.number().int().nonnegative(),
490
+ elapsedMs: z2.number().int().nonnegative()
491
+ })
492
+ }),
493
+ z2.strictObject({
494
+ ...eventBase,
495
+ type: z2.literal("execution-finished"),
496
+ data: z2.strictObject({
497
+ outcome: z2.enum(["success", "failure", "timeout"]),
498
+ failureCode: failureCode.optional(),
499
+ elapsedMs: z2.number().int().nonnegative(),
500
+ usage: usageSchema.optional()
501
+ })
502
+ }),
503
+ z2.strictObject({
504
+ ...eventBase,
505
+ type: z2.literal("verification-started"),
506
+ data: z2.strictObject({})
507
+ }),
508
+ z2.strictObject({
509
+ ...eventBase,
510
+ type: z2.literal("verification-finished"),
511
+ data: z2.strictObject({
512
+ passed: z2.boolean(),
513
+ checksPassed: z2.number().int().nonnegative(),
514
+ checksFailed: z2.number().int().nonnegative()
515
+ })
516
+ }),
517
+ z2.strictObject({
518
+ ...eventBase,
519
+ type: z2.literal("feedback"),
520
+ data: z2.strictObject({
521
+ status: z2.enum(["completed", "verified", "failed", "blocked", "cancelled"]),
522
+ rating: z2.number().int().min(1).max(5).optional(),
523
+ modelChoice: z2.enum(["right", "acceptable", "wrong"]).optional(),
524
+ wouldUseAgain: z2.boolean().optional()
525
+ })
526
+ }),
527
+ z2.strictObject({
528
+ ...eventBase,
529
+ type: z2.literal("cancelled"),
530
+ data: z2.strictObject({
531
+ by: runActorSchema
532
+ })
533
+ }),
534
+ z2.strictObject({
535
+ ...eventBase,
536
+ type: z2.literal("expired"),
537
+ data: z2.strictObject({})
538
+ })
539
+ ]);
540
+ var runCandidateSchema = z2.strictObject({
541
+ id: z2.string().min(1).max(256),
542
+ harness: harnessIdSchema,
543
+ nativeModelId: z2.string().min(1).max(200),
544
+ readiness: z2.enum(["installed", "auth-ready", "model-listed", "invocation-compatible", "live-confirmed"]),
545
+ authMode: z2.enum(["subscription", "api-key", "cloud-provider", "local", "unknown"]),
546
+ productUseApproved: z2.boolean(),
547
+ capabilities: z2.object({
548
+ tools: z2.boolean(),
549
+ vision: z2.boolean(),
550
+ structuredOutput: z2.enum(["none", "json", "jsonl", "schema"]),
551
+ sessions: z2.enum(["none", "resume", "continue"]),
552
+ permissions: z2.array(permissionProfileSchema).min(1)
553
+ }),
554
+ identityProof: z2.enum(["requested", "runtime-reported", "unavailable"]),
555
+ qualityPrior: z2.number().min(0).max(1),
556
+ tokenEfficiencyPrior: z2.number().min(0).max(1),
557
+ latencyPrior: z2.number().min(0).max(1)
558
+ });
559
+ var effectivePolicySchema = z2.strictObject({
560
+ objective: routingObjectiveSchema,
561
+ maxDelegationDepth: z2.number().int().min(0).max(3),
562
+ permissionCeiling: permissionProfileSchema,
563
+ allowedHarnesses: z2.array(harnessIdSchema).max(10).optional(),
564
+ tokenBudget: z2.number().int().positive().max(1e7).optional(),
565
+ wallTimeBudgetMs: z2.number().int().positive().max(864e5).optional()
566
+ });
567
+ var runApprovalSchema = z2.strictObject({
568
+ kind: approvalKindSchema,
569
+ state: z2.enum(["pending", "granted", "denied"]),
570
+ surface: approvalSurfaceSchema.optional(),
571
+ at: z2.iso.datetime()
572
+ });
573
+ var runDocumentSchema = z2.strictObject({
574
+ schemaVersion: z2.literal(RUN_SCHEMA_VERSION),
575
+ runId: z2.uuid(),
576
+ createdAt: z2.iso.datetime(),
577
+ expiresAt: z2.iso.datetime(),
578
+ origin: z2.strictObject({
579
+ surface: clientSurfaceSchema,
580
+ clientVersion: z2.string().min(1).max(100)
581
+ }),
582
+ task: agentTaskFeaturesSchema,
583
+ candidatesSnapshot: z2.array(runCandidateSchema).max(100),
584
+ decision: z2.strictObject({
585
+ plan: executionPlanSchema,
586
+ fallback: executionPlanSchema,
587
+ confidence: z2.number().min(0).max(1),
588
+ reasonCodes: z2.array(reasonCode).max(20),
589
+ expected: z2.strictObject({
590
+ verifiedSuccess: z2.number().min(0).max(1),
591
+ contextTokens: z2.number().int().nonnegative(),
592
+ wallTimeMs: z2.number().int().nonnegative()
593
+ }),
594
+ routerVersion: z2.string().min(1).max(100)
595
+ }),
596
+ policy: effectivePolicySchema,
597
+ approvals: z2.array(runApprovalSchema).max(20),
598
+ events: z2.array(runEventSchema).max(500),
599
+ status: runStatusSchema,
600
+ usage: usageSchema.optional()
601
+ });
602
+ var TERMINAL = /* @__PURE__ */ new Set(["cancelled", "expired"]);
603
+ var ALLOWED = {
604
+ none: ["created"],
605
+ planned: ["routed", "approval-requested", "execution-started", "cancelled", "expired"],
606
+ "awaiting-approval": ["approval-granted", "approval-denied", "cancelled", "expired"],
607
+ executing: ["execution-progress", "execution-finished", "cancelled", "expired"],
608
+ verifying: ["verification-finished", "cancelled", "expired"],
609
+ completed: ["verification-started", "feedback", "expired"],
610
+ failed: ["verification-started", "feedback", "expired"],
611
+ cancelled: ["feedback"],
612
+ expired: []
613
+ };
614
+ function apply(status, event) {
615
+ switch (event.type) {
616
+ case "created":
617
+ return "planned";
618
+ case "routed":
619
+ return "planned";
620
+ case "approval-requested":
621
+ return "awaiting-approval";
622
+ case "approval-granted":
623
+ return "planned";
624
+ case "approval-denied":
625
+ return "cancelled";
626
+ case "execution-started":
627
+ case "execution-progress":
628
+ return "executing";
629
+ case "execution-finished":
630
+ return event.data.outcome === "success" ? "completed" : "failed";
631
+ case "verification-started":
632
+ return "verifying";
633
+ case "verification-finished":
634
+ return event.data.passed ? "completed" : "failed";
635
+ case "feedback":
636
+ return status === "none" ? "planned" : status;
637
+ case "cancelled":
638
+ return "cancelled";
639
+ case "expired":
640
+ return "expired";
641
+ }
642
+ }
643
+ function validateTransition(status, event) {
644
+ return ALLOWED[status].includes(event.type);
645
+ }
646
+ function deriveRunStatus(events) {
647
+ let status = "none";
648
+ for (const event of events) status = apply(status, event);
649
+ return status;
650
+ }
651
+ function appendRunEvent(events, candidate) {
652
+ const parsed = runEventSchema.parse(candidate);
653
+ const expectedSeq = events.length === 0 ? 0 : events[events.length - 1].seq + 1;
654
+ if (parsed.seq !== expectedSeq) throw new Error(`RUN_EVENT_SEQ: expected seq ${expectedSeq}, received ${parsed.seq}`);
655
+ const status = deriveRunStatus(events);
656
+ if (!validateTransition(status, parsed)) {
657
+ throw new Error(`RUN_EVENT_TRANSITION: ${parsed.type} is not valid from ${status}`);
658
+ }
659
+ return [...events, parsed];
660
+ }
661
+ function isTerminalRunStatus(status) {
662
+ return TERMINAL.has(status) || status === "completed" || status === "failed";
663
+ }
664
+ var permissionRank2 = { inspect: 0, edit: 1, test: 2, network: 3 };
665
+ function lowerPermission(a, b) {
666
+ return permissionRank2[a] <= permissionRank2[b] ? a : b;
667
+ }
668
+ function mergePolicy(local, hosted = {}) {
669
+ const allowedHarnesses = local.allowedHarnesses && hosted.allowedHarnesses ? local.allowedHarnesses.filter((harness) => hosted.allowedHarnesses?.includes(harness)) : local.allowedHarnesses ?? hosted.allowedHarnesses;
670
+ const tokenBudget = local.tokenBudget !== void 0 && hosted.tokenBudget !== void 0 ? Math.min(local.tokenBudget, hosted.tokenBudget) : local.tokenBudget ?? hosted.tokenBudget;
671
+ const wallTimeBudgetMs = local.wallTimeBudgetMs !== void 0 && hosted.wallTimeBudgetMs !== void 0 ? Math.min(local.wallTimeBudgetMs, hosted.wallTimeBudgetMs) : local.wallTimeBudgetMs ?? hosted.wallTimeBudgetMs;
672
+ return effectivePolicySchema.parse({
673
+ objective: local.objective ?? hosted.objective ?? "balanced",
674
+ maxDelegationDepth: Math.min(local.maxDelegationDepth ?? 1, hosted.maxDelegationDepth ?? 3),
675
+ permissionCeiling: lowerPermission(local.permissionCeiling ?? "inspect", hosted.permissionCeiling ?? "network"),
676
+ ...allowedHarnesses === void 0 ? {} : { allowedHarnesses },
677
+ ...tokenBudget === void 0 ? {} : { tokenBudget },
678
+ ...wallTimeBudgetMs === void 0 ? {} : { wallTimeBudgetMs }
679
+ });
680
+ }
681
+ export {
682
+ AGENT_ROUTER_SCHEMA_VERSION,
683
+ AGENT_ROUTER_VERSION,
684
+ RUN_SCHEMA_VERSION,
685
+ agentFeedbackSchema,
686
+ agentModelSchema,
687
+ agentRouteRequestSchema,
688
+ agentRouteResponseSchema,
689
+ agentTaskFeaturesSchema,
690
+ allowanceSchema,
691
+ appendRunEvent,
692
+ approvalKindSchema,
693
+ approvalSurfaceSchema,
694
+ clientSurfaceSchema,
695
+ deriveRunStatus,
696
+ effectivePolicySchema,
697
+ executionPlanSchema,
698
+ featurizeAgentTask,
699
+ harnessIdSchema,
700
+ isTerminalRunStatus,
701
+ mergePolicy,
702
+ permissionProfileSchema,
703
+ readinessSchema,
704
+ routingObjectiveSchema,
705
+ runActorSchema,
706
+ runApprovalSchema,
707
+ runCandidateSchema,
708
+ runDocumentSchema,
709
+ runEventSchema,
710
+ runStatusSchema,
711
+ selectAgentRoute,
712
+ taskRoleSchema,
713
+ taskTypeSchema,
714
+ validateTransition,
715
+ workflowSchema
716
+ };
717
+ //# sourceMappingURL=index.js.map